_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
2c8d91eb84582c460d4da7f26b757cbe9b3da2dbf763fd54ff24db49dfd559e4
TaylanUB/scheme-srfis
derived.body.scm
Copyright ( C ) ( 2007 ) . All Rights Reserved . Made an R7RS library by , Copyright ( C ) 2014 . ;;; 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. Eval these in Emacs : ( put ' stream - lambda ' scheme - indent - function 1 ) ( put ' stream - let ' scheme - indent - function 2 ) (define-syntax define-stream (syntax-rules () ((define-stream (name . formal) body0 body1 ...) (define name (stream-lambda formal body0 body1 ...))))) (define (list->stream objs) (define list->stream (stream-lambda (objs) (if (null? objs) stream-null (stream-cons (car objs) (list->stream (cdr objs)))))) (if (not (list? objs)) (error "non-list argument" objs) (list->stream objs))) (define (port->stream . port) (define port->stream (stream-lambda (p) (let ((c (read-char p))) (if (eof-object? c) stream-null (stream-cons c (port->stream p)))))) (let ((p (if (null? port) (current-input-port) (car port)))) (if (not (input-port? p)) (error "non-input-port argument" p) (port->stream p)))) (define-syntax stream (syntax-rules () ((stream) stream-null) ((stream x y ...) (stream-cons x (stream y ...))))) (define (stream->list . args) (let ((n (if (= 1 (length args)) #f (car args))) (strm (if (= 1 (length args)) (car args) (cadr args)))) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((and n (not (integer? n))) (error "non-integer count" n)) ((and n (negative? n)) (error "negative count" n)) (else (let loop ((n (if n n -1)) (strm strm)) (if (or (zero? n) (stream-null? strm)) '() (cons (stream-car strm) (loop (- n 1) (stream-cdr strm))))))))) (define (stream-append . strms) (define stream-append (stream-lambda (strms) (cond ((null? (cdr strms)) (car strms)) ((stream-null? (car strms)) (stream-append (cdr strms))) (else (stream-cons (stream-car (car strms)) (stream-append (cons (stream-cdr (car strms)) (cdr strms)))))))) (cond ((null? strms) stream-null) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-append strms)))) (define (stream-concat strms) (define stream-concat (stream-lambda (strms) (cond ((stream-null? strms) stream-null) ((not (stream? (stream-car strms))) (error "non-stream object in input stream" strms)) ((stream-null? (stream-car strms)) (stream-concat (stream-cdr strms))) (else (stream-cons (stream-car (stream-car strms)) (stream-concat (stream-cons (stream-cdr (stream-car strms)) (stream-cdr strms)))))))) (if (not (stream? strms)) (error "non-stream argument" strms) (stream-concat strms))) (define stream-constant (stream-lambda objs (cond ((null? objs) stream-null) ((null? (cdr objs)) (stream-cons (car objs) (stream-constant (car objs)))) (else (stream-cons (car objs) (apply stream-constant (append (cdr objs) (list (car objs))))))))) (define (stream-drop n strm) (define stream-drop (stream-lambda (n strm) (if (or (zero? n) (stream-null? strm)) strm (stream-drop (- n 1) (stream-cdr strm))))) (cond ((not (integer? n)) (error "non-integer argument" n)) ((negative? n) (error "negative argument" n)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-drop n strm)))) (define (stream-drop-while pred? strm) (define stream-drop-while (stream-lambda (strm) (if (and (stream-pair? strm) (pred? (stream-car strm))) (stream-drop-while (stream-cdr strm)) strm))) (cond ((not (procedure? pred?)) (error "non-procedural argument" pred?)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-drop-while strm)))) (define (stream-filter pred? strm) (define stream-filter (stream-lambda (strm) (cond ((stream-null? strm) stream-null) ((pred? (stream-car strm)) (stream-cons (stream-car strm) (stream-filter (stream-cdr strm)))) (else (stream-filter (stream-cdr strm)))))) (cond ((not (procedure? pred?)) (error "non-procedural argument" pred?)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-filter strm)))) (define (stream-fold proc base strm) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (let loop ((base base) (strm strm)) (if (stream-null? strm) base (loop (proc base (stream-car strm)) (stream-cdr strm))))))) (define (stream-for-each proc . strms) (define (stream-for-each strms) (if (not (find stream-null? strms)) (begin (apply proc (map stream-car strms)) (stream-for-each (map stream-cdr strms))))) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((null? strms) (error "no stream arguments")) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-for-each strms)))) (define (stream-from first . step) (define stream-from (stream-lambda (first delta) (stream-cons first (stream-from (+ first delta) delta)))) (let ((delta (if (null? step) 1 (car step)))) (cond ((not (number? first)) (error "non-numeric starting number" first)) ((not (number? delta)) (error "non-numeric step size" delta)) (else (stream-from first delta))))) (define (stream-iterate proc base) (define stream-iterate (stream-lambda (base) (stream-cons base (stream-iterate (proc base))))) (if (not (procedure? proc)) (error "non-procedural argument" proc) (stream-iterate base))) (define (stream-length strm) (if (not (stream? strm)) (error "non-stream argument" strm) (let loop ((len 0) (strm strm)) (if (stream-null? strm) len (loop (+ len 1) (stream-cdr strm)))))) (define-syntax stream-let (syntax-rules () ((stream-let tag ((name val) ...) body1 body2 ...) ((letrec ((tag (stream-lambda (name ...) body1 body2 ...))) tag) val ...)))) (define (stream-map proc . strms) (define stream-map (stream-lambda (strms) (if (find stream-null? strms) stream-null (stream-cons (apply proc (map stream-car strms)) (stream-map (map stream-cdr strms)))))) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((null? strms) (error "no stream arguments")) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-map strms)))) (define-syntax stream-match (syntax-rules () ((stream-match strm-expr clause ...) (let ((strm strm-expr)) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((stream-match-test strm clause) => car) ... (else (error "pattern failure"))))))) (define-syntax stream-match-test (syntax-rules () ((stream-match-test strm (pattern fender expr)) (stream-match-pattern strm pattern () (and fender (list expr)))) ((stream-match-test strm (pattern expr)) (stream-match-pattern strm pattern () (list expr))))) (define-syntax stream-match-pattern (syntax-rules (_) ((stream-match-pattern strm () (binding ...) body) (and (stream-null? strm) (let (binding ...) body))) ((stream-match-pattern strm (_ . rest) (binding ...) body) (and (stream-pair? strm) (let ((strm (stream-cdr strm))) (stream-match-pattern strm rest (binding ...) body)))) ((stream-match-pattern strm (var . rest) (binding ...) body) (and (stream-pair? strm) (let ((temp (stream-car strm)) (strm (stream-cdr strm))) (stream-match-pattern strm rest ((var temp) binding ...) body)))) ((stream-match-pattern strm _ (binding ...) body) (let (binding ...) body)) ((stream-match-pattern strm var (binding ...) body) (let ((var strm) binding ...) body)))) (define-syntax stream-of (syntax-rules () ((_ expr rest ...) (stream-of-aux expr stream-null rest ...)))) (define-syntax stream-of-aux (syntax-rules (in is) ((stream-of-aux expr base) (stream-cons expr base)) ((stream-of-aux expr base (var in stream) rest ...) (stream-let loop ((strm stream)) (if (stream-null? strm) base (let ((var (stream-car strm))) (stream-of-aux expr (loop (stream-cdr strm)) rest ...))))) ((stream-of-aux expr base (var is exp) rest ...) (let ((var exp)) (stream-of-aux expr base rest ...))) ((stream-of-aux expr base pred? rest ...) (if pred? (stream-of-aux expr base rest ...) base)))) (define (stream-range first past . step) (define stream-range (stream-lambda (first past delta lt?) (if (lt? first past) (stream-cons first (stream-range (+ first delta) past delta lt?)) stream-null))) (cond ((not (number? first)) (error "non-numeric starting number" first)) ((not (number? past)) (error "non-numeric ending number" past)) (else (let ((delta (cond ((pair? step) (car step)) ((< first past) 1) (else -1)))) (if (not (number? delta)) (error "non-numeric step size" delta) (let ((lt? (if (< 0 delta) < >))) (stream-range first past delta lt?))))))) (define (stream-ref strm n) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((not (integer? n)) (error "non-integer argument" n)) ((negative? n) (error "negative argument" n)) (else (let loop ((strm strm) (n n)) (cond ((stream-null? strm) (error "beyond end of stream" strm)) ((zero? n) (stream-car strm)) (else (loop (stream-cdr strm) (- n 1)))))))) (define (stream-reverse strm) (define stream-reverse (stream-lambda (strm rev) (if (stream-null? strm) rev (stream-reverse (stream-cdr strm) (stream-cons (stream-car strm) rev))))) (if (not (stream? strm)) (error "non-stream argument" strm) (stream-reverse strm stream-null))) (define (stream-scan proc base strm) (define stream-scan (stream-lambda (base strm) (if (stream-null? strm) (stream base) (stream-cons base (stream-scan (proc base (stream-car strm)) (stream-cdr strm)))))) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-scan base strm)))) (define (stream-take n strm) (define stream-take (stream-lambda (n strm) (if (or (stream-null? strm) (zero? n)) stream-null (stream-cons (stream-car strm) (stream-take (- n 1) (stream-cdr strm)))))) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((not (integer? n)) (error "non-integer argument" n)) ((negative? n) (error "negative argument" n)) (else (stream-take n strm)))) (define (stream-take-while pred? strm) (define stream-take-while (stream-lambda (strm) (cond ((stream-null? strm) stream-null) ((pred? (stream-car strm)) (stream-cons (stream-car strm) (stream-take-while (stream-cdr strm)))) (else stream-null)))) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((not (procedure? pred?)) (error "non-procedural argument" pred?)) (else (stream-take-while strm)))) (define (stream-unfold mapper pred? generator base) (define stream-unfold (stream-lambda (base) (if (pred? base) (stream-cons (mapper base) (stream-unfold (generator base))) stream-null))) (cond ((not (procedure? mapper)) (error "non-procedural mapper" mapper)) ((not (procedure? pred?)) (error "non-procedural pred?" pred?)) ((not (procedure? generator)) (error "non-procedural generator" generator)) (else (stream-unfold base)))) (define (stream-unfolds gen seed) (define (len-values gen seed) (call-with-values (lambda () (gen seed)) (lambda vs (- (length vs) 1)))) (define unfold-result-stream (stream-lambda (gen seed) (call-with-values (lambda () (gen seed)) (lambda (next . results) (stream-cons results (unfold-result-stream gen next)))))) (define result-stream->output-stream (stream-lambda (result-stream i) (let ((result (list-ref (stream-car result-stream) (- i 1)))) (cond ((pair? result) (stream-cons (car result) (result-stream->output-stream (stream-cdr result-stream) i))) ((not result) (result-stream->output-stream (stream-cdr result-stream) i)) ((null? result) stream-null) (else (error "can't happen")))))) (define (result-stream->output-streams result-stream) (let loop ((i (len-values gen seed)) (outputs '())) (if (zero? i) (apply values outputs) (loop (- i 1) (cons (result-stream->output-stream result-stream i) outputs))))) (if (not (procedure? gen)) (error "non-procedural argument" gen) (result-stream->output-streams (unfold-result-stream gen seed)))) (define (stream-zip . strms) (define stream-zip (stream-lambda (strms) (if (find stream-null? strms) stream-null (stream-cons (map stream-car strms) (stream-zip (map stream-cdr strms)))))) (cond ((null? strms) (error "no stream arguments")) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-zip strms))))
null
https://raw.githubusercontent.com/TaylanUB/scheme-srfis/2d2b306e7a20a7155f639001a02b0870d5a3d3f7/srfi/41/derived.body.scm
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 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 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright ( C ) ( 2007 ) . All Rights Reserved . Made an R7RS library by , Copyright ( C ) 2014 . deal in the Software without restriction , including without limitation the sell 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 Eval these in Emacs : ( put ' stream - lambda ' scheme - indent - function 1 ) ( put ' stream - let ' scheme - indent - function 2 ) (define-syntax define-stream (syntax-rules () ((define-stream (name . formal) body0 body1 ...) (define name (stream-lambda formal body0 body1 ...))))) (define (list->stream objs) (define list->stream (stream-lambda (objs) (if (null? objs) stream-null (stream-cons (car objs) (list->stream (cdr objs)))))) (if (not (list? objs)) (error "non-list argument" objs) (list->stream objs))) (define (port->stream . port) (define port->stream (stream-lambda (p) (let ((c (read-char p))) (if (eof-object? c) stream-null (stream-cons c (port->stream p)))))) (let ((p (if (null? port) (current-input-port) (car port)))) (if (not (input-port? p)) (error "non-input-port argument" p) (port->stream p)))) (define-syntax stream (syntax-rules () ((stream) stream-null) ((stream x y ...) (stream-cons x (stream y ...))))) (define (stream->list . args) (let ((n (if (= 1 (length args)) #f (car args))) (strm (if (= 1 (length args)) (car args) (cadr args)))) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((and n (not (integer? n))) (error "non-integer count" n)) ((and n (negative? n)) (error "negative count" n)) (else (let loop ((n (if n n -1)) (strm strm)) (if (or (zero? n) (stream-null? strm)) '() (cons (stream-car strm) (loop (- n 1) (stream-cdr strm))))))))) (define (stream-append . strms) (define stream-append (stream-lambda (strms) (cond ((null? (cdr strms)) (car strms)) ((stream-null? (car strms)) (stream-append (cdr strms))) (else (stream-cons (stream-car (car strms)) (stream-append (cons (stream-cdr (car strms)) (cdr strms)))))))) (cond ((null? strms) stream-null) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-append strms)))) (define (stream-concat strms) (define stream-concat (stream-lambda (strms) (cond ((stream-null? strms) stream-null) ((not (stream? (stream-car strms))) (error "non-stream object in input stream" strms)) ((stream-null? (stream-car strms)) (stream-concat (stream-cdr strms))) (else (stream-cons (stream-car (stream-car strms)) (stream-concat (stream-cons (stream-cdr (stream-car strms)) (stream-cdr strms)))))))) (if (not (stream? strms)) (error "non-stream argument" strms) (stream-concat strms))) (define stream-constant (stream-lambda objs (cond ((null? objs) stream-null) ((null? (cdr objs)) (stream-cons (car objs) (stream-constant (car objs)))) (else (stream-cons (car objs) (apply stream-constant (append (cdr objs) (list (car objs))))))))) (define (stream-drop n strm) (define stream-drop (stream-lambda (n strm) (if (or (zero? n) (stream-null? strm)) strm (stream-drop (- n 1) (stream-cdr strm))))) (cond ((not (integer? n)) (error "non-integer argument" n)) ((negative? n) (error "negative argument" n)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-drop n strm)))) (define (stream-drop-while pred? strm) (define stream-drop-while (stream-lambda (strm) (if (and (stream-pair? strm) (pred? (stream-car strm))) (stream-drop-while (stream-cdr strm)) strm))) (cond ((not (procedure? pred?)) (error "non-procedural argument" pred?)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-drop-while strm)))) (define (stream-filter pred? strm) (define stream-filter (stream-lambda (strm) (cond ((stream-null? strm) stream-null) ((pred? (stream-car strm)) (stream-cons (stream-car strm) (stream-filter (stream-cdr strm)))) (else (stream-filter (stream-cdr strm)))))) (cond ((not (procedure? pred?)) (error "non-procedural argument" pred?)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-filter strm)))) (define (stream-fold proc base strm) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (let loop ((base base) (strm strm)) (if (stream-null? strm) base (loop (proc base (stream-car strm)) (stream-cdr strm))))))) (define (stream-for-each proc . strms) (define (stream-for-each strms) (if (not (find stream-null? strms)) (begin (apply proc (map stream-car strms)) (stream-for-each (map stream-cdr strms))))) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((null? strms) (error "no stream arguments")) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-for-each strms)))) (define (stream-from first . step) (define stream-from (stream-lambda (first delta) (stream-cons first (stream-from (+ first delta) delta)))) (let ((delta (if (null? step) 1 (car step)))) (cond ((not (number? first)) (error "non-numeric starting number" first)) ((not (number? delta)) (error "non-numeric step size" delta)) (else (stream-from first delta))))) (define (stream-iterate proc base) (define stream-iterate (stream-lambda (base) (stream-cons base (stream-iterate (proc base))))) (if (not (procedure? proc)) (error "non-procedural argument" proc) (stream-iterate base))) (define (stream-length strm) (if (not (stream? strm)) (error "non-stream argument" strm) (let loop ((len 0) (strm strm)) (if (stream-null? strm) len (loop (+ len 1) (stream-cdr strm)))))) (define-syntax stream-let (syntax-rules () ((stream-let tag ((name val) ...) body1 body2 ...) ((letrec ((tag (stream-lambda (name ...) body1 body2 ...))) tag) val ...)))) (define (stream-map proc . strms) (define stream-map (stream-lambda (strms) (if (find stream-null? strms) stream-null (stream-cons (apply proc (map stream-car strms)) (stream-map (map stream-cdr strms)))))) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((null? strms) (error "no stream arguments")) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-map strms)))) (define-syntax stream-match (syntax-rules () ((stream-match strm-expr clause ...) (let ((strm strm-expr)) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((stream-match-test strm clause) => car) ... (else (error "pattern failure"))))))) (define-syntax stream-match-test (syntax-rules () ((stream-match-test strm (pattern fender expr)) (stream-match-pattern strm pattern () (and fender (list expr)))) ((stream-match-test strm (pattern expr)) (stream-match-pattern strm pattern () (list expr))))) (define-syntax stream-match-pattern (syntax-rules (_) ((stream-match-pattern strm () (binding ...) body) (and (stream-null? strm) (let (binding ...) body))) ((stream-match-pattern strm (_ . rest) (binding ...) body) (and (stream-pair? strm) (let ((strm (stream-cdr strm))) (stream-match-pattern strm rest (binding ...) body)))) ((stream-match-pattern strm (var . rest) (binding ...) body) (and (stream-pair? strm) (let ((temp (stream-car strm)) (strm (stream-cdr strm))) (stream-match-pattern strm rest ((var temp) binding ...) body)))) ((stream-match-pattern strm _ (binding ...) body) (let (binding ...) body)) ((stream-match-pattern strm var (binding ...) body) (let ((var strm) binding ...) body)))) (define-syntax stream-of (syntax-rules () ((_ expr rest ...) (stream-of-aux expr stream-null rest ...)))) (define-syntax stream-of-aux (syntax-rules (in is) ((stream-of-aux expr base) (stream-cons expr base)) ((stream-of-aux expr base (var in stream) rest ...) (stream-let loop ((strm stream)) (if (stream-null? strm) base (let ((var (stream-car strm))) (stream-of-aux expr (loop (stream-cdr strm)) rest ...))))) ((stream-of-aux expr base (var is exp) rest ...) (let ((var exp)) (stream-of-aux expr base rest ...))) ((stream-of-aux expr base pred? rest ...) (if pred? (stream-of-aux expr base rest ...) base)))) (define (stream-range first past . step) (define stream-range (stream-lambda (first past delta lt?) (if (lt? first past) (stream-cons first (stream-range (+ first delta) past delta lt?)) stream-null))) (cond ((not (number? first)) (error "non-numeric starting number" first)) ((not (number? past)) (error "non-numeric ending number" past)) (else (let ((delta (cond ((pair? step) (car step)) ((< first past) 1) (else -1)))) (if (not (number? delta)) (error "non-numeric step size" delta) (let ((lt? (if (< 0 delta) < >))) (stream-range first past delta lt?))))))) (define (stream-ref strm n) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((not (integer? n)) (error "non-integer argument" n)) ((negative? n) (error "negative argument" n)) (else (let loop ((strm strm) (n n)) (cond ((stream-null? strm) (error "beyond end of stream" strm)) ((zero? n) (stream-car strm)) (else (loop (stream-cdr strm) (- n 1)))))))) (define (stream-reverse strm) (define stream-reverse (stream-lambda (strm rev) (if (stream-null? strm) rev (stream-reverse (stream-cdr strm) (stream-cons (stream-car strm) rev))))) (if (not (stream? strm)) (error "non-stream argument" strm) (stream-reverse strm stream-null))) (define (stream-scan proc base strm) (define stream-scan (stream-lambda (base strm) (if (stream-null? strm) (stream base) (stream-cons base (stream-scan (proc base (stream-car strm)) (stream-cdr strm)))))) (cond ((not (procedure? proc)) (error "non-procedural argument" proc)) ((not (stream? strm)) (error "non-stream argument" strm)) (else (stream-scan base strm)))) (define (stream-take n strm) (define stream-take (stream-lambda (n strm) (if (or (stream-null? strm) (zero? n)) stream-null (stream-cons (stream-car strm) (stream-take (- n 1) (stream-cdr strm)))))) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((not (integer? n)) (error "non-integer argument" n)) ((negative? n) (error "negative argument" n)) (else (stream-take n strm)))) (define (stream-take-while pred? strm) (define stream-take-while (stream-lambda (strm) (cond ((stream-null? strm) stream-null) ((pred? (stream-car strm)) (stream-cons (stream-car strm) (stream-take-while (stream-cdr strm)))) (else stream-null)))) (cond ((not (stream? strm)) (error "non-stream argument" strm)) ((not (procedure? pred?)) (error "non-procedural argument" pred?)) (else (stream-take-while strm)))) (define (stream-unfold mapper pred? generator base) (define stream-unfold (stream-lambda (base) (if (pred? base) (stream-cons (mapper base) (stream-unfold (generator base))) stream-null))) (cond ((not (procedure? mapper)) (error "non-procedural mapper" mapper)) ((not (procedure? pred?)) (error "non-procedural pred?" pred?)) ((not (procedure? generator)) (error "non-procedural generator" generator)) (else (stream-unfold base)))) (define (stream-unfolds gen seed) (define (len-values gen seed) (call-with-values (lambda () (gen seed)) (lambda vs (- (length vs) 1)))) (define unfold-result-stream (stream-lambda (gen seed) (call-with-values (lambda () (gen seed)) (lambda (next . results) (stream-cons results (unfold-result-stream gen next)))))) (define result-stream->output-stream (stream-lambda (result-stream i) (let ((result (list-ref (stream-car result-stream) (- i 1)))) (cond ((pair? result) (stream-cons (car result) (result-stream->output-stream (stream-cdr result-stream) i))) ((not result) (result-stream->output-stream (stream-cdr result-stream) i)) ((null? result) stream-null) (else (error "can't happen")))))) (define (result-stream->output-streams result-stream) (let loop ((i (len-values gen seed)) (outputs '())) (if (zero? i) (apply values outputs) (loop (- i 1) (cons (result-stream->output-stream result-stream i) outputs))))) (if (not (procedure? gen)) (error "non-procedural argument" gen) (result-stream->output-streams (unfold-result-stream gen seed)))) (define (stream-zip . strms) (define stream-zip (stream-lambda (strms) (if (find stream-null? strms) stream-null (stream-cons (map stream-car strms) (stream-zip (map stream-cdr strms)))))) (cond ((null? strms) (error "no stream arguments")) ((find (lambda (x) (not (stream? x))) strms) => (lambda (strm) (error "non-stream argument" strm))) (else (stream-zip strms))))
75414318e723e17f4ae2e90a8dcf25789a05539dcb67ff165802c069032b61f8
Chream/mockingbird
all.lisp
;;;; mockingbird/t/all.lisp (in-package :cl-user) (uiop:define-package :mockingbird/t/all (:nicknames :mb.test) (:use :closer-common-lisp) (:use-reexport :mockingbird/t/functions :mockingbird/t/methods) (:documentation "")) (in-package :mb.test)
null
https://raw.githubusercontent.com/Chream/mockingbird/bf56e15faf8684fb96bd8094bd76c2d1b966c0ae/t/all.lisp
lisp
mockingbird/t/all.lisp
(in-package :cl-user) (uiop:define-package :mockingbird/t/all (:nicknames :mb.test) (:use :closer-common-lisp) (:use-reexport :mockingbird/t/functions :mockingbird/t/methods) (:documentation "")) (in-package :mb.test)
4669bde92599c277e8a6f622035134b2021fe8f1538ec22c7dbdf4778b95aa3f
dtgoitia/civil-autolisp
DeleteObjectFromBlock.lsp
Credit to ; ; For ; ; for the Recursive Routine ; ; ;; Me for tweaking it for you ;; (defun c:fxb (/ blockName doc FLST) (vl-load-com) (setq doc (vla-get-activedocument (vlax-get-acad-object)) ) (setq blockName (cdr (assoc 2 (entget (car (entsel "\nSelect block: "))))) FLST nil ) (fix1 blockName) (vl-cmdf "regen") (prin1) ) (defun fix1 (blockName / blockEntityName) If the blockName is not in FLST , carry on (if (not (member blockName FLST)) (progn (setq Add blockName to FLST FLST (cons blockName FLST) ; Get entity name of blockName blockEntityName (tblobjname "block" blockName) ) ; Get next object within the drawing object table (while (setq blockEntityName (entnext blockEntityName)) ;(print (entget blockEntityName)) ; If the next object is an INSERT object (if (= (cdr (assoc 0 (entget blockEntityName))) "INSERT") ; If true, get the name block and pass it as argument to "fix1" (recursive) (fix1 (cdr (assoc 2 (entget blockEntityName)))) ; If false, check if next object is a dimension, if it is DIMENSION object, delete it (if (= (cdr (assoc 0 (entget blockEntityName))) "DIMENSION") (progn (setq dimToDelete (vlax-ename->vla-object blockEntityName) blk (vla-ObjectIdToObject doc (vla-get-ownerID dimToDelete) ) );END setq ;(vla-delete dimToDelete) (vla-get-count blk) );END progn );END if );END if );END while );END progn );END if (princ) )
null
https://raw.githubusercontent.com/dtgoitia/civil-autolisp/72d68139d372c84014d160f8e4918f062356349f/Dump%20folder/DeleteObjectFromBlock.lsp
lisp
; ; ; Me for tweaking it for you ;; Get entity name of blockName Get next object within the drawing object table (print (entget blockEntityName)) If the next object is an INSERT object If true, get the name block and pass it as argument to "fix1" (recursive) If false, check if next object is a dimension, if it is DIMENSION object, delete it END setq (vla-delete dimToDelete) END progn END if END if END while END progn END if
(defun c:fxb (/ blockName doc FLST) (vl-load-com) (setq doc (vla-get-activedocument (vlax-get-acad-object)) ) (setq blockName (cdr (assoc 2 (entget (car (entsel "\nSelect block: "))))) FLST nil ) (fix1 blockName) (vl-cmdf "regen") (prin1) ) (defun fix1 (blockName / blockEntityName) If the blockName is not in FLST , carry on (if (not (member blockName FLST)) (progn (setq Add blockName to FLST FLST (cons blockName FLST) blockEntityName (tblobjname "block" blockName) ) (while (setq blockEntityName (entnext blockEntityName)) (if (= (cdr (assoc 0 (entget blockEntityName))) "INSERT") (fix1 (cdr (assoc 2 (entget blockEntityName)))) (if (= (cdr (assoc 0 (entget blockEntityName))) "DIMENSION") (progn (setq dimToDelete (vlax-ename->vla-object blockEntityName) blk (vla-ObjectIdToObject doc (vla-get-ownerID dimToDelete) ) (vla-get-count blk) (princ) )
52b97d4c3fab21e384a4a7024ffe9da3245fb61a20f0e442a593e628ac4f96f5
FrankC01/clasew
examples7.clj
(ns ^{:author "Frank V. Castellucci" :doc "Identities Examples (Multi-Application)"} clasew.examples7 (:require [clojure.pprint :refer :all] [clasew.outlook :as outlook] [clasew.contacts :as contacts] [clasew.identities :as ident] [clasew.ast-utils :as astu])) (def p pprint) ;; ;; Sample ease of use forms ;; (def ident-apps {:contacts #(contacts/script %) :outlook #(outlook/script %)}) (def ident-app-quit {:contacts (astu/quit :contacts) :outlook (astu/quit :outlook)}) (defn- map-requests "Performs substitution or passthrough of script function" [app coll] (map #(condp = % :quit (app ident-app-quit) ((app ident-apps) %)) coll)) (defn run-sample "Calls the target application script generator to create script as defined by request and then executes the results: app - Defines target app. Can be :mail or :outlook & rqs - script requests (supports substitution)" [app & rqs] (apply ident/run-script! (map-requests app rqs))) (defn print-sample "Calls the target application script generator to create script as defined by request and then prints the results: app - Defines target app. Can be :mail or :outlook & rqs - script requests (supports substitution)" [app & rqs] (apply println (map-requests app rqs))) ;; ;; Setup a number of fictional contacts for demonstration ;; (def oxnard {:first_name "Oxnard" :last_name "Gimbel" :emails (list {:email_type "work" :email_address ""} {:email_type "home" :email_address ""}) :addresses (list {:address_type "work" :city_name "West Somewhere"} {:address_type "home" :city_name "New York"}) :phones (list {:number_type "home phone" :number_value "999 999-0000"} {:number_type "mobile" :number_value "999 999 0001"} {:number_type "work" :number_value "000 000 0000"}) }) (def sally {:first_name "Sally" :last_name "Abercrombe" :emails (list {:email_type "work" :email_address ""} {:email_type "home" :email_address ""}) :addresses (list {:address_type "work" :city_name "East Somewhere"} {:address_type "home" :city_name "Maine"}) :phones (list {:number_type "home" :number_value "999 999-0002"} {:number_type "mobile" :number_value "999 999 0003"}) }) ;; Create new individuals ;; Uncomment to run ;(print-sample :contacts (ident/add-individuals oxnard sally)) ;(print-sample :outlook (ident/add-individuals oxnard sally)) ;(p (run-sample :contacts (ident/add-individuals oxnard sally))) ;(p (run-sample :outlook (ident/add-individuals oxnard sally))) ;; ;; Fetch ALL individuals from outlook contacts ;; ;; Uncomment to run ;(p (run-sample :contacts (ident/individuals))) ;(p (run-sample :outlook (ident/individuals))) ;; Fetch all individuals and email addresses where individual 's first name contains " Oxnard " ;; This uses the simple filter option (def s-get-individuals-with-name-filter (ident/individuals (astu/filter :first_name astu/CT "Oxnard") (ident/email-addresses))) ;; Uncomment to run ;(p (run-sample :contacts s-get-individuals-with-name-filter)) ;(p (run-sample :outlook s-get-individuals-with-name-filter)) ;; Fetch all individuals and phone numbers where individual 's first name contains " " ;; This uses a simple filter option (def s-get-individuals-and-phones-with-name-filter (ident/individuals (astu/filter :first_name astu/EQ "Sally") (ident/phones))) ;; Uncomment to run ;(p (run-sample :contacts s-get-individuals-and-phones-with-name-filter)) ;(p (run-sample :outlook s-get-individuals-and-phones-with-name-filter)) ;; Fetch all individuals (full name only) their streeet address, phones and emails where individuals first name contains Oxnard ;; This uses a simple filter option (def s-get-fullname-and-info-with-name-filter (ident/individuals :full_name (ident/addresses) (ident/email-addresses) (ident/phones) (astu/filter :first_name astu/EQ "Oxnard"))) ;; Uncomment to run ;(p (run-sample :contacts s-get-fullname-and-info-with-name-filter)) ;(p (run-sample :outlook s-get-fullname-and-info-with-name-filter)) ;; Fetch all individuals their email addresses,street addresses and ;; phone numbers. This is equivalent to call (individuals-all...) as ;; shown below (def s-get-all-individuals-ala-carte (ident/individuals (ident/addresses) (ident/email-addresses) (ident/phones))) ;; Uncomment to run ;(p (run-sample :contacts s-get-all-individuals-ala-carte)) ;(p (run-sample :outlook s-get-all-individuals-ala-carte)) ;; Short version to do the same (def s-get-all-individuals-fixed-price (ident/individuals-all)) ;; Uncomment to run ;(p (run-sample :contacts s-get-all-individuals-fixed-price)) ;(p (run-sample :outlook s-get-all-individuals-fixed-price)) ;; Updates with filters (def s-update-individuals-meeting-criteria (ident/update-individual (astu/filter :first_name astu/EQ "Oxnard" :last_name astu/EQ "Gimbel") :first_name "Oxnardio" (ident/update-addresses (astu/filter :address_type astu/EQ "work" :city_name astu/EQ "West Somewhere") :city_name "West Palm Beach") (ident/update-addresses (astu/filter :address_type astu/EQ "home" :city_name astu/EQ "New York") :city_name "NJ") (ident/update-email-addresses (astu/filter :email_type astu/EQ "home" :email_address astu/EQ "") :email_address "oxnard@my_new_home.com") (ident/update-email-addresses (astu/filter :email_type astu/EQ "work" :email_address astu/EQ "") :email_address "oxnard@my_old_business.com" (ident/adds {:email_type "work" :email_address ""})) (ident/update-phones (astu/filter :number_type astu/EQ "work" :number_value astu/EQ "000 000 0000") :number_value "991 991 9991"))) ;; Uncomment to run ;(p (run-sample :contacts s-update-individuals-meeting-criteria)) ;(p (run-sample :outlook s-update-individuals-meeting-criteria)) ;; Construct a complex filter ;; (def s-reusable-nested-filter (astu/filter :first_name astu/CT "Oxnard" :last_name astu/EQ "Gimbel" (astu/or :first_name astu/EQ "Sally" :last_name astu/EQ "Abercrombe"))) ;; Fetch individuals based on complex filter ;; Uncomment to run ;(p (run-sample :contacts (ident/individuals s-reusable-nested-filter))) ;(p (run-sample :outlook (ident/individuals s-reusable-nested-filter))) ;; Delete individuals based on complex filter ;; Uncomment to run ;(p (run-sample :contacts (ident/delete-individual s-reusable-nested-filter) :quit)) ;(p (run-sample :outlook (ident/delete-individual s-reusable-nested-filter) :quit))
null
https://raw.githubusercontent.com/FrankC01/clasew/1e5a444bccd4f34c68a1e5d1ec2121a36fd8c959/dev/src/clasew/examples7.clj
clojure
Sample ease of use forms Setup a number of fictional contacts for demonstration Create new individuals Uncomment to run (print-sample :contacts (ident/add-individuals oxnard sally)) (print-sample :outlook (ident/add-individuals oxnard sally)) (p (run-sample :contacts (ident/add-individuals oxnard sally))) (p (run-sample :outlook (ident/add-individuals oxnard sally))) Fetch ALL individuals from outlook contacts Uncomment to run (p (run-sample :contacts (ident/individuals))) (p (run-sample :outlook (ident/individuals))) Fetch all individuals and email addresses where This uses the simple filter option Uncomment to run (p (run-sample :contacts s-get-individuals-with-name-filter)) (p (run-sample :outlook s-get-individuals-with-name-filter)) Fetch all individuals and phone numbers where This uses a simple filter option Uncomment to run (p (run-sample :contacts s-get-individuals-and-phones-with-name-filter)) (p (run-sample :outlook s-get-individuals-and-phones-with-name-filter)) Fetch all individuals (full name only) their streeet address, This uses a simple filter option Uncomment to run (p (run-sample :contacts s-get-fullname-and-info-with-name-filter)) (p (run-sample :outlook s-get-fullname-and-info-with-name-filter)) Fetch all individuals their email addresses,street addresses and phone numbers. This is equivalent to call (individuals-all...) as shown below Uncomment to run (p (run-sample :contacts s-get-all-individuals-ala-carte)) (p (run-sample :outlook s-get-all-individuals-ala-carte)) Short version to do the same Uncomment to run (p (run-sample :contacts s-get-all-individuals-fixed-price)) (p (run-sample :outlook s-get-all-individuals-fixed-price)) Updates with filters Uncomment to run (p (run-sample :contacts s-update-individuals-meeting-criteria)) (p (run-sample :outlook s-update-individuals-meeting-criteria)) Fetch individuals based on complex filter Uncomment to run (p (run-sample :contacts (ident/individuals s-reusable-nested-filter))) (p (run-sample :outlook (ident/individuals s-reusable-nested-filter))) Delete individuals based on complex filter Uncomment to run (p (run-sample :contacts (ident/delete-individual s-reusable-nested-filter) :quit)) (p (run-sample :outlook (ident/delete-individual s-reusable-nested-filter) :quit))
(ns ^{:author "Frank V. Castellucci" :doc "Identities Examples (Multi-Application)"} clasew.examples7 (:require [clojure.pprint :refer :all] [clasew.outlook :as outlook] [clasew.contacts :as contacts] [clasew.identities :as ident] [clasew.ast-utils :as astu])) (def p pprint) (def ident-apps {:contacts #(contacts/script %) :outlook #(outlook/script %)}) (def ident-app-quit {:contacts (astu/quit :contacts) :outlook (astu/quit :outlook)}) (defn- map-requests "Performs substitution or passthrough of script function" [app coll] (map #(condp = % :quit (app ident-app-quit) ((app ident-apps) %)) coll)) (defn run-sample "Calls the target application script generator to create script as defined by request and then executes the results: app - Defines target app. Can be :mail or :outlook & rqs - script requests (supports substitution)" [app & rqs] (apply ident/run-script! (map-requests app rqs))) (defn print-sample "Calls the target application script generator to create script as defined by request and then prints the results: app - Defines target app. Can be :mail or :outlook & rqs - script requests (supports substitution)" [app & rqs] (apply println (map-requests app rqs))) (def oxnard {:first_name "Oxnard" :last_name "Gimbel" :emails (list {:email_type "work" :email_address ""} {:email_type "home" :email_address ""}) :addresses (list {:address_type "work" :city_name "West Somewhere"} {:address_type "home" :city_name "New York"}) :phones (list {:number_type "home phone" :number_value "999 999-0000"} {:number_type "mobile" :number_value "999 999 0001"} {:number_type "work" :number_value "000 000 0000"}) }) (def sally {:first_name "Sally" :last_name "Abercrombe" :emails (list {:email_type "work" :email_address ""} {:email_type "home" :email_address ""}) :addresses (list {:address_type "work" :city_name "East Somewhere"} {:address_type "home" :city_name "Maine"}) :phones (list {:number_type "home" :number_value "999 999-0002"} {:number_type "mobile" :number_value "999 999 0003"}) }) individual 's first name contains " Oxnard " (def s-get-individuals-with-name-filter (ident/individuals (astu/filter :first_name astu/CT "Oxnard") (ident/email-addresses))) individual 's first name contains " " (def s-get-individuals-and-phones-with-name-filter (ident/individuals (astu/filter :first_name astu/EQ "Sally") (ident/phones))) phones and emails where individuals first name contains Oxnard (def s-get-fullname-and-info-with-name-filter (ident/individuals :full_name (ident/addresses) (ident/email-addresses) (ident/phones) (astu/filter :first_name astu/EQ "Oxnard"))) (def s-get-all-individuals-ala-carte (ident/individuals (ident/addresses) (ident/email-addresses) (ident/phones))) (def s-get-all-individuals-fixed-price (ident/individuals-all)) (def s-update-individuals-meeting-criteria (ident/update-individual (astu/filter :first_name astu/EQ "Oxnard" :last_name astu/EQ "Gimbel") :first_name "Oxnardio" (ident/update-addresses (astu/filter :address_type astu/EQ "work" :city_name astu/EQ "West Somewhere") :city_name "West Palm Beach") (ident/update-addresses (astu/filter :address_type astu/EQ "home" :city_name astu/EQ "New York") :city_name "NJ") (ident/update-email-addresses (astu/filter :email_type astu/EQ "home" :email_address astu/EQ "") :email_address "oxnard@my_new_home.com") (ident/update-email-addresses (astu/filter :email_type astu/EQ "work" :email_address astu/EQ "") :email_address "oxnard@my_old_business.com" (ident/adds {:email_type "work" :email_address ""})) (ident/update-phones (astu/filter :number_type astu/EQ "work" :number_value astu/EQ "000 000 0000") :number_value "991 991 9991"))) Construct a complex filter (def s-reusable-nested-filter (astu/filter :first_name astu/CT "Oxnard" :last_name astu/EQ "Gimbel" (astu/or :first_name astu/EQ "Sally" :last_name astu/EQ "Abercrombe")))
5735877d9bf226232057ee4476bc1265dd2f06e7325da4f24424bee8ca1ab2f4
CatalaLang/catala
print.mli
This file is part of the Catala compiler , a specification language for tax and social benefits computation rules . Copyright ( C ) 2020 , contributor : < > 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 . and social benefits computation rules. Copyright (C) 2020 Inria, contributor: Denis Merigoux <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) val scope : ?debug:bool (** [true] for debug printing *) -> Shared_ast.decl_ctx -> Format.formatter -> Shared_ast.ScopeName.t * 'm Ast.scope_decl -> unit val program : ?debug:bool (** [true] for debug printing *) -> Format.formatter -> 'm Ast.program -> unit
null
https://raw.githubusercontent.com/CatalaLang/catala/d371df85a9c1de441674a8e2c73b5db10f1b96a9/compiler/scopelang/print.mli
ocaml
* [true] for debug printing * [true] for debug printing
This file is part of the Catala compiler , a specification language for tax and social benefits computation rules . Copyright ( C ) 2020 , contributor : < > 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 . and social benefits computation rules. Copyright (C) 2020 Inria, contributor: Denis Merigoux <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) val scope : Shared_ast.decl_ctx -> Format.formatter -> Shared_ast.ScopeName.t * 'm Ast.scope_decl -> unit val program : Format.formatter -> 'm Ast.program -> unit
1a4b6dec1dec8635df88a792e78327c0ca776b4e8aa28f85914b277332095e16
ChrisPenner/eve
Listeners.hs
{-# LANGUAGE GADTs #-} # LANGUAGE ExistentialQuantification # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE RankNTypes #-} module Eve.Internal.Listeners ( HasEvents , dispatchEvent , dispatchEvent_ , dispatchLocalEvent , dispatchLocalEvent_ , dispatchEventAsync , addListener , addListener_ , addLocalListener , addLocalListener_ , removeListener , removeLocalListener , asyncEventProvider , afterInit , beforeEvent , beforeEvent_ , afterEvent , afterEvent_ , onExit , Listener , ListenerId , EventDispatcher ) where import Eve.Internal.States import Eve.Internal.Async import Eve.Internal.Actions import Eve.Internal.Events import Control.Monad.State import Control.Lens import Data.Default import Data.Typeable import Data.Maybe import qualified Data.Map as M -- | Registers an action to be performed directly following the Initialization phase. -- At this point any listeners in the initialization block have run , so you may ' dispatchEvent 's here . afterInit :: forall base m a. (Monad m, HasEvents base, Typeable m) => AppT base m a -> AppT base m () afterInit action = addListener_ (const (void action) :: AfterInit -> AppT base m ()) -- | Registers an action to be performed BEFORE each async event is processed phase. beforeEvent :: forall base zoomed m a. (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m ListenerId beforeEvent action = addListener (const (void action) :: BeforeEvent -> AppT base m ()) beforeEvent_ :: (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m () beforeEvent_ = void . beforeEvent -- | Registers an action to be performed AFTER each event phase. afterEvent :: forall base zoomed m a. (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m ListenerId afterEvent action = addListener (const (void action) :: AfterEvent -> AppT base m ()) afterEvent_ :: (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m () afterEvent_ = void . afterEvent -- | Registers an action to be run before shutdown. Any asynchronous combinators used in this block will NOT be run. onExit :: forall base zoomed m a. (HasEvents base, Typeable m, Monad m) => AppT base m a -> ActionT base zoomed m () onExit action = addListener_ (const (void action) :: Exit -> AppT base m ()) -- | A local version of 'dispatchEvent'. -- The local version dispatches the event in the context of the current 'Action', -- If you don't know what this means, you probably want 'dispatchEvent' instead dispatchLocalEvent :: forall result eventType m s. (MonadState s m ,HasEvents s ,Monoid result ,Typeable m ,Typeable eventType ,Typeable result) => eventType -> m result dispatchLocalEvent evt = do LocalListeners _ listeners <- use localListeners results <- traverse ($ evt) (matchingListeners listeners :: [eventType -> m result]) return (mconcat results :: result) dispatchLocalEvent_ :: forall eventType m s. (MonadState s m ,HasEvents s ,Typeable m ,Typeable eventType) => eventType -> m () dispatchLocalEvent_ = dispatchLocalEvent -- | Runs any listeners registered for the provided event with the provided event; -- -- You can also 'query' listeners and receive a ('Monoid'al) result. -- -- > data RequestNames = GetFirstName | GetLastName -- > provideName1, provideName2 :: RequestNames -> App [String] > provideName1 GetFirstNames = return [ " " ] > provideName1 GetLastNames = return [ " " ] > provideName2 GetFirstNames = return [ " " ] > provideName2 GetLastNames = return [ " " ] -- > -- > -- Note that if we registered an action of type 'GetFirstName -> ()' it would NOT -- > -- be run in response to the following 'dispatchEvent', since it's type doesn't match. -- > -- > greetNames :: App [String] > greetNames = do > addListener _ provideName1 -- > addListener_ provideName2 -- > firstNames <- dispatchEvent GetFirstName -- > lastNames <- dispatchEvent GetLastName -- > liftIO $ print firstNames > -- [ " " , " " ] -- > liftIO $ print lastNames > -- [ " " , " " ] dispatchEvent :: forall result eventType m base zoomed. (HasEvents base ,Monoid result ,Monad m ,Typeable m ,Typeable eventType ,Typeable result) => eventType -> ActionT base zoomed m result dispatchEvent evt = runApp $ dispatchLocalEvent evt dispatchEvent_ :: forall eventType m base zoomed. (HasEvents base ,Monad m ,Typeable m ,Typeable eventType) => eventType -> ActionT base zoomed m () dispatchEvent_ = dispatchEvent | The local version of ' addListener ' . It will register a listener within an ' Action 's local event context . If you do n't know what this means you probably want ' addListener ' instead . addLocalListener :: forall result eventType m s. (MonadState s m ,HasEvents s ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> m result) -> m ListenerId addLocalListener lFunc = do LocalListeners nextListenerId listeners <- use localListeners let (listener, listenerId, eventType) = mkListener nextListenerId lFunc newListeners = M.insertWith mappend eventType [listener] listeners localListeners .= LocalListeners (nextListenerId + 1) newListeners return listenerId where mkListener :: forall event r. (Typeable event, Typeable r, Monoid r) => Int -> (event -> m r) -> (Listener, ListenerId, TypeRep) mkListener n listenerFunc = let list = Listener (typeOf listenerFunc) listId listenerFunc listId = ListenerId n (typeRep (Proxy :: Proxy event)) prox = typeRep (Proxy :: Proxy event) in (list, listId, prox) addLocalListener_ :: forall result eventType m s. (MonadState s m ,HasEvents s ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> m result) -> m () addLocalListener_ = void . addLocalListener -- | Registers an 'Action' or 'App' to respond to an event. -- -- For a given use: @addListener myListener@, @myListener@ might have the type @MyEvent -> App a@ it will register the function @myListener@ to be run in response to a @dispatchEvent ( MyEvent eventInfo)@ and will be provided @(MyEvent eventInfo)@ as an argument . -- This returns a ' ' which corresponds to the registered listener for use with ' removeListener ' addListener :: forall result eventType m base zoomed. (HasEvents base ,Monad m ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> AppT base m result) -> ActionT base zoomed m ListenerId addListener = runApp . addLocalListener addListener_ :: forall result eventType m base zoomed. (HasEvents base ,Monad m ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> AppT base m result) -> ActionT base zoomed m () addListener_ = void . addListener -- | The local version of 'removeListener'. -- This removes a listener from an 'Action's event context. If you don't -- know what this means you probably want 'removeListener' instead. removeLocalListener :: (MonadState s m, HasEvents s) => ListenerId -> m () removeLocalListener listenerId@(ListenerId _ eventType) = localListeners %= remover where remover (LocalListeners nextListenerId listeners) = let newListeners = listeners & at eventType . _Just %~ filter (notMatch listenerId) in LocalListeners nextListenerId newListeners notMatch idA (Listener _ idB _) = idA /= idB | Unregisters a listener referred to by the provided ' ' removeListener :: (HasEvents base ,Monad m) => ListenerId -> ActionT base zoomed m () removeListener = runApp . removeLocalListener -- | This function takes an IO which results in some event, it runs the IO -- asynchronously, THEN dispatches the event. Note that only the -- code which generates the event is asynchronous, not any responses to the event -- itself. dispatchEventAsync :: (Typeable event ,MonadIO m ,Typeable m ,HasEvents base ) => IO event -> ActionT base zoomed m () dispatchEventAsync ioEvent = dispatchActionAsync $ dispatchEvent <$> ioEvent -- | A wrapper around event listeners so they can be stored in 'Listeners'. data Listener where Listener :: (MonadState s m, Typeable m, Typeable eventType, Typeable result, Monoid result, HasStates s) => TypeRep -> ListenerId -> (eventType -> m result) -> Listener -- | An opaque reverence to a specific registered event-listener. A is used only to remove listeners later with ' removeListener ' . data ListenerId = ListenerId Int TypeRep instance Eq ListenerId where ListenerId a _ == ListenerId b _ = a == b -- | A map of event types to a list of listeners for that event type Listeners = M.Map TypeRep [Listener] -- | Store the listeners in the state-map data LocalListeners = LocalListeners Int Listeners instance Default LocalListeners where def = LocalListeners 0 M.empty localListeners :: HasStates s => Lens' s LocalListeners localListeners = stateLens -- | This extracts all event listeners from a map of listeners which match the type of the provided event. matchingListeners :: forall m eventType result. (Typeable m ,Typeable eventType ,Typeable result) => Listeners -> [eventType -> m result] matchingListeners listeners = catMaybes $ (getListener :: Listener -> Maybe (eventType -> m result)) <$> (listeners ^. at (typeRep (Proxy :: Proxy eventType)) . _Just) | Extract the listener function from eventType listener getListener :: Typeable expected => Listener -> Maybe expected getListener (Listener _ _ x) = cast x -- | This is a type alias to make defining your functions for use with 'asyncEventProvider' easier; -- It represents the function your event provider function will be passed to allow dispatching -- events. Using this type requires the @RankNTypes@ language pragma. type EventDispatcher = forall event. Typeable event => event -> IO () | This allows long - running IO processes to provide Events to the application asyncronously . -- -- Don't let the type signature confuse you; it's much simpler than it seems. -- -- Let's break it down: -- Using the ' EventDispatcher ' type with asyncEventProvider requires the @RankNTypes@ language pragma . -- This type as a whole represents a function which accepts an ' EventDispatcher ' and returns an ' IO ' ; the dispatcher itself accepts data of ANY ' ' type and emits it as an event . -- -- When you call 'asyncEventProvider' you pass it a function which accepts a @dispatch@ function as an argument -- and then calls it with various events within the resulting 'IO'. -- -- Note that this function calls forkIO internally, so there's no need to do that yourself. -- -- Here's an example which fires a @Timer@ event every second. -- > { - # language RankNTypes # - } -- > data Timer = Timer -- > myTimer :: EventDispatcher -> IO () > myTimer dispatch = forever $ dispatch Timer > > threadDelay 1000000 -- > -- > myInit :: App () -- > myInit = asyncEventProvider myTimer asyncEventProvider :: (HasEvents base, MonadIO m, Typeable m) => (EventDispatcher -> IO ()) -> ActionT base zoomed m () asyncEventProvider asyncEventProv = asyncActionProvider $ eventsToActions asyncEventProv where eventsToActions :: (Monad m, HasEvents base, Typeable m) => (EventDispatcher -> IO ()) -> (AppT base m () -> IO ()) -> IO () eventsToActions aEventProv dispatcher = aEventProv (dispatcher . dispatchEvent)
null
https://raw.githubusercontent.com/ChrisPenner/eve/6081b1ff13229b93e5e5a4505fd23aa0a25c96b1/src/Eve/Internal/Listeners.hs
haskell
# LANGUAGE GADTs # # LANGUAGE RankNTypes # | Registers an action to be performed directly following the Initialization phase. | Registers an action to be performed BEFORE each async event is processed phase. | Registers an action to be performed AFTER each event phase. | Registers an action to be run before shutdown. Any asynchronous combinators used in this block will NOT be run. | A local version of 'dispatchEvent'. The local version dispatches the event in the context of the current 'Action', If you don't know what this means, you probably want 'dispatchEvent' instead | Runs any listeners registered for the provided event with the provided event; You can also 'query' listeners and receive a ('Monoid'al) result. > data RequestNames = GetFirstName | GetLastName > provideName1, provideName2 :: RequestNames -> App [String] > > -- Note that if we registered an action of type 'GetFirstName -> ()' it would NOT > -- be run in response to the following 'dispatchEvent', since it's type doesn't match. > > greetNames :: App [String] > addListener_ provideName2 > firstNames <- dispatchEvent GetFirstName > lastNames <- dispatchEvent GetLastName > liftIO $ print firstNames [ " " , " " ] > liftIO $ print lastNames [ " " , " " ] | Registers an 'Action' or 'App' to respond to an event. For a given use: @addListener myListener@, @myListener@ might have the type @MyEvent -> App a@ | The local version of 'removeListener'. This removes a listener from an 'Action's event context. If you don't know what this means you probably want 'removeListener' instead. | This function takes an IO which results in some event, it runs the IO asynchronously, THEN dispatches the event. Note that only the code which generates the event is asynchronous, not any responses to the event itself. | A wrapper around event listeners so they can be stored in 'Listeners'. | An opaque reverence to a specific registered event-listener. | A map of event types to a list of listeners for that event | Store the listeners in the state-map | This extracts all event listeners from a map of listeners which match the type of the provided event. | This is a type alias to make defining your functions for use with 'asyncEventProvider' easier; It represents the function your event provider function will be passed to allow dispatching events. Using this type requires the @RankNTypes@ language pragma. Don't let the type signature confuse you; it's much simpler than it seems. Let's break it down: When you call 'asyncEventProvider' you pass it a function which accepts a @dispatch@ function as an argument and then calls it with various events within the resulting 'IO'. Note that this function calls forkIO internally, so there's no need to do that yourself. Here's an example which fires a @Timer@ event every second. > data Timer = Timer > myTimer :: EventDispatcher -> IO () > > myInit :: App () > myInit = asyncEventProvider myTimer
# LANGUAGE ExistentialQuantification # # LANGUAGE ScopedTypeVariables # module Eve.Internal.Listeners ( HasEvents , dispatchEvent , dispatchEvent_ , dispatchLocalEvent , dispatchLocalEvent_ , dispatchEventAsync , addListener , addListener_ , addLocalListener , addLocalListener_ , removeListener , removeLocalListener , asyncEventProvider , afterInit , beforeEvent , beforeEvent_ , afterEvent , afterEvent_ , onExit , Listener , ListenerId , EventDispatcher ) where import Eve.Internal.States import Eve.Internal.Async import Eve.Internal.Actions import Eve.Internal.Events import Control.Monad.State import Control.Lens import Data.Default import Data.Typeable import Data.Maybe import qualified Data.Map as M At this point any listeners in the initialization block have run , so you may ' dispatchEvent 's here . afterInit :: forall base m a. (Monad m, HasEvents base, Typeable m) => AppT base m a -> AppT base m () afterInit action = addListener_ (const (void action) :: AfterInit -> AppT base m ()) beforeEvent :: forall base zoomed m a. (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m ListenerId beforeEvent action = addListener (const (void action) :: BeforeEvent -> AppT base m ()) beforeEvent_ :: (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m () beforeEvent_ = void . beforeEvent afterEvent :: forall base zoomed m a. (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m ListenerId afterEvent action = addListener (const (void action) :: AfterEvent -> AppT base m ()) afterEvent_ :: (Monad m, HasEvents base, Typeable m) => AppT base m a -> ActionT base zoomed m () afterEvent_ = void . afterEvent onExit :: forall base zoomed m a. (HasEvents base, Typeable m, Monad m) => AppT base m a -> ActionT base zoomed m () onExit action = addListener_ (const (void action) :: Exit -> AppT base m ()) dispatchLocalEvent :: forall result eventType m s. (MonadState s m ,HasEvents s ,Monoid result ,Typeable m ,Typeable eventType ,Typeable result) => eventType -> m result dispatchLocalEvent evt = do LocalListeners _ listeners <- use localListeners results <- traverse ($ evt) (matchingListeners listeners :: [eventType -> m result]) return (mconcat results :: result) dispatchLocalEvent_ :: forall eventType m s. (MonadState s m ,HasEvents s ,Typeable m ,Typeable eventType) => eventType -> m () dispatchLocalEvent_ = dispatchLocalEvent > provideName1 GetFirstNames = return [ " " ] > provideName1 GetLastNames = return [ " " ] > provideName2 GetFirstNames = return [ " " ] > provideName2 GetLastNames = return [ " " ] > greetNames = do > addListener _ provideName1 dispatchEvent :: forall result eventType m base zoomed. (HasEvents base ,Monoid result ,Monad m ,Typeable m ,Typeable eventType ,Typeable result) => eventType -> ActionT base zoomed m result dispatchEvent evt = runApp $ dispatchLocalEvent evt dispatchEvent_ :: forall eventType m base zoomed. (HasEvents base ,Monad m ,Typeable m ,Typeable eventType) => eventType -> ActionT base zoomed m () dispatchEvent_ = dispatchEvent | The local version of ' addListener ' . It will register a listener within an ' Action 's local event context . If you do n't know what this means you probably want ' addListener ' instead . addLocalListener :: forall result eventType m s. (MonadState s m ,HasEvents s ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> m result) -> m ListenerId addLocalListener lFunc = do LocalListeners nextListenerId listeners <- use localListeners let (listener, listenerId, eventType) = mkListener nextListenerId lFunc newListeners = M.insertWith mappend eventType [listener] listeners localListeners .= LocalListeners (nextListenerId + 1) newListeners return listenerId where mkListener :: forall event r. (Typeable event, Typeable r, Monoid r) => Int -> (event -> m r) -> (Listener, ListenerId, TypeRep) mkListener n listenerFunc = let list = Listener (typeOf listenerFunc) listId listenerFunc listId = ListenerId n (typeRep (Proxy :: Proxy event)) prox = typeRep (Proxy :: Proxy event) in (list, listId, prox) addLocalListener_ :: forall result eventType m s. (MonadState s m ,HasEvents s ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> m result) -> m () addLocalListener_ = void . addLocalListener it will register the function @myListener@ to be run in response to a @dispatchEvent ( MyEvent eventInfo)@ and will be provided @(MyEvent eventInfo)@ as an argument . This returns a ' ' which corresponds to the registered listener for use with ' removeListener ' addListener :: forall result eventType m base zoomed. (HasEvents base ,Monad m ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> AppT base m result) -> ActionT base zoomed m ListenerId addListener = runApp . addLocalListener addListener_ :: forall result eventType m base zoomed. (HasEvents base ,Monad m ,Typeable m ,Typeable eventType ,Typeable result ,Monoid result) => (eventType -> AppT base m result) -> ActionT base zoomed m () addListener_ = void . addListener removeLocalListener :: (MonadState s m, HasEvents s) => ListenerId -> m () removeLocalListener listenerId@(ListenerId _ eventType) = localListeners %= remover where remover (LocalListeners nextListenerId listeners) = let newListeners = listeners & at eventType . _Just %~ filter (notMatch listenerId) in LocalListeners nextListenerId newListeners notMatch idA (Listener _ idB _) = idA /= idB | Unregisters a listener referred to by the provided ' ' removeListener :: (HasEvents base ,Monad m) => ListenerId -> ActionT base zoomed m () removeListener = runApp . removeLocalListener dispatchEventAsync :: (Typeable event ,MonadIO m ,Typeable m ,HasEvents base ) => IO event -> ActionT base zoomed m () dispatchEventAsync ioEvent = dispatchActionAsync $ dispatchEvent <$> ioEvent data Listener where Listener :: (MonadState s m, Typeable m, Typeable eventType, Typeable result, Monoid result, HasStates s) => TypeRep -> ListenerId -> (eventType -> m result) -> Listener A is used only to remove listeners later with ' removeListener ' . data ListenerId = ListenerId Int TypeRep instance Eq ListenerId where ListenerId a _ == ListenerId b _ = a == b type Listeners = M.Map TypeRep [Listener] data LocalListeners = LocalListeners Int Listeners instance Default LocalListeners where def = LocalListeners 0 M.empty localListeners :: HasStates s => Lens' s LocalListeners localListeners = stateLens matchingListeners :: forall m eventType result. (Typeable m ,Typeable eventType ,Typeable result) => Listeners -> [eventType -> m result] matchingListeners listeners = catMaybes $ (getListener :: Listener -> Maybe (eventType -> m result)) <$> (listeners ^. at (typeRep (Proxy :: Proxy eventType)) . _Just) | Extract the listener function from eventType listener getListener :: Typeable expected => Listener -> Maybe expected getListener (Listener _ _ x) = cast x type EventDispatcher = forall event. Typeable event => event -> IO () | This allows long - running IO processes to provide Events to the application asyncronously . Using the ' EventDispatcher ' type with asyncEventProvider requires the @RankNTypes@ language pragma . This type as a whole represents a function which accepts an ' EventDispatcher ' and returns an ' IO ' ; the dispatcher itself accepts data of ANY ' ' type and emits it as an event . > { - # language RankNTypes # - } > myTimer dispatch = forever $ dispatch Timer > > threadDelay 1000000 asyncEventProvider :: (HasEvents base, MonadIO m, Typeable m) => (EventDispatcher -> IO ()) -> ActionT base zoomed m () asyncEventProvider asyncEventProv = asyncActionProvider $ eventsToActions asyncEventProv where eventsToActions :: (Monad m, HasEvents base, Typeable m) => (EventDispatcher -> IO ()) -> (AppT base m () -> IO ()) -> IO () eventsToActions aEventProv dispatcher = aEventProv (dispatcher . dispatchEvent)
5c4c57c36aeaaf5d54e3b7f5673c8156f6179754dec81c5a3df5e609ad6dfda0
haskell/cabal
Assignment.hs
module Distribution.Solver.Modular.Assignment ( Assignment(..) , PAssignment , FAssignment , SAssignment , toCPs ) where import Prelude () import Distribution.Solver.Compat.Prelude hiding (pi) import qualified Data.Array as A import qualified Data.List as L import qualified Data.Map as M import Data.Maybe (fromJust) from Cabal import Distribution.Solver.Types.ComponentDeps (ComponentDeps, Component) import qualified Distribution.Solver.Types.ComponentDeps as CD import Distribution.Solver.Types.OptionalStanza import Distribution.Solver.Types.PackagePath import Distribution.Solver.Modular.Configured import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.LabeledGraph import Distribution.Solver.Modular.Package -- | A (partial) package assignment. Qualified package names -- are associated with instances. type PAssignment = Map QPN I type FAssignment = Map QFN Bool type SAssignment = Map QSN Bool -- | A (partial) assignment of variables. data Assignment = A PAssignment FAssignment SAssignment deriving (Show, Eq) -- | Delivers an ordered list of fully configured packages. -- -- TODO: This function is (sort of) ok. However, there's an open bug -- w.r.t. unqualification. There might be several different instances of one package version chosen by the solver , which will lead to -- clashes. toCPs :: Assignment -> RevDepMap -> [CP QPN] toCPs (A pa fa sa) rdm = let -- get hold of the graph g :: Graph Component vm :: Vertex -> ((), QPN, [(Component, QPN)]) cvm :: QPN -> Maybe Vertex -- Note that the RevDepMap contains duplicate dependencies. Therefore the nub. (g, vm, cvm) = graphFromEdges (L.map (\ (x, xs) -> ((), x, nub xs)) (M.toList rdm)) tg :: Graph Component tg = transposeG g -- Topsort the dependency graph, yielding a list of pkgs in the right order. -- The graph will still contain all the installed packages, and it might -- contain duplicates, because several variables might actually resolve to -- the same package in the presence of qualified package names. ps :: [PI QPN] ps = L.map ((\ (_, x, _) -> PI x (pa M.! x)) . vm) $ topSort g -- Determine the flags per package, by walking over and regrouping the -- complete flag assignment by package. fapp :: Map QPN FlagAssignment fapp = M.fromListWith mappend $ L.map (\ ((FN qpn fn), b) -> (qpn, mkFlagAssignment [(fn, b)])) $ M.toList $ fa -- Stanzas per package. sapp :: Map QPN OptionalStanzaSet sapp = M.fromListWith mappend $ L.map (\ ((SN qpn sn), b) -> (qpn, if b then optStanzaSetSingleton sn else mempty)) $ M.toList sa -- Dependencies per package. depp :: QPN -> [(Component, PI QPN)] depp qpn = let v :: Vertex v = fromJust (cvm qpn) -- TODO: why this is safe? dvs :: [(Component, Vertex)] dvs = tg A.! v in L.map (\ (comp, dv) -> case vm dv of (_, x, _) -> (comp, PI x (pa M.! x))) dvs -- Translated to PackageDeps depp' :: QPN -> ComponentDeps [PI QPN] depp' = CD.fromList . L.map (\(comp, d) -> (comp, [d])) . depp in L.map (\ pi@(PI qpn _) -> CP pi (M.findWithDefault mempty qpn fapp) (M.findWithDefault mempty qpn sapp) (depp' qpn)) ps
null
https://raw.githubusercontent.com/haskell/cabal/6896c6aa0e4804913aaba0bbbe00649e18f17bb8/cabal-install-solver/src/Distribution/Solver/Modular/Assignment.hs
haskell
| A (partial) package assignment. Qualified package names are associated with instances. | A (partial) assignment of variables. | Delivers an ordered list of fully configured packages. TODO: This function is (sort of) ok. However, there's an open bug w.r.t. unqualification. There might be several different instances clashes. get hold of the graph Note that the RevDepMap contains duplicate dependencies. Therefore the nub. Topsort the dependency graph, yielding a list of pkgs in the right order. The graph will still contain all the installed packages, and it might contain duplicates, because several variables might actually resolve to the same package in the presence of qualified package names. Determine the flags per package, by walking over and regrouping the complete flag assignment by package. Stanzas per package. Dependencies per package. TODO: why this is safe? Translated to PackageDeps
module Distribution.Solver.Modular.Assignment ( Assignment(..) , PAssignment , FAssignment , SAssignment , toCPs ) where import Prelude () import Distribution.Solver.Compat.Prelude hiding (pi) import qualified Data.Array as A import qualified Data.List as L import qualified Data.Map as M import Data.Maybe (fromJust) from Cabal import Distribution.Solver.Types.ComponentDeps (ComponentDeps, Component) import qualified Distribution.Solver.Types.ComponentDeps as CD import Distribution.Solver.Types.OptionalStanza import Distribution.Solver.Types.PackagePath import Distribution.Solver.Modular.Configured import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.LabeledGraph import Distribution.Solver.Modular.Package type PAssignment = Map QPN I type FAssignment = Map QFN Bool type SAssignment = Map QSN Bool data Assignment = A PAssignment FAssignment SAssignment deriving (Show, Eq) of one package version chosen by the solver , which will lead to toCPs :: Assignment -> RevDepMap -> [CP QPN] toCPs (A pa fa sa) rdm = let g :: Graph Component vm :: Vertex -> ((), QPN, [(Component, QPN)]) cvm :: QPN -> Maybe Vertex (g, vm, cvm) = graphFromEdges (L.map (\ (x, xs) -> ((), x, nub xs)) (M.toList rdm)) tg :: Graph Component tg = transposeG g ps :: [PI QPN] ps = L.map ((\ (_, x, _) -> PI x (pa M.! x)) . vm) $ topSort g fapp :: Map QPN FlagAssignment fapp = M.fromListWith mappend $ L.map (\ ((FN qpn fn), b) -> (qpn, mkFlagAssignment [(fn, b)])) $ M.toList $ fa sapp :: Map QPN OptionalStanzaSet sapp = M.fromListWith mappend $ L.map (\ ((SN qpn sn), b) -> (qpn, if b then optStanzaSetSingleton sn else mempty)) $ M.toList sa depp :: QPN -> [(Component, PI QPN)] depp qpn = let v :: Vertex dvs :: [(Component, Vertex)] dvs = tg A.! v in L.map (\ (comp, dv) -> case vm dv of (_, x, _) -> (comp, PI x (pa M.! x))) dvs depp' :: QPN -> ComponentDeps [PI QPN] depp' = CD.fromList . L.map (\(comp, d) -> (comp, [d])) . depp in L.map (\ pi@(PI qpn _) -> CP pi (M.findWithDefault mempty qpn fapp) (M.findWithDefault mempty qpn sapp) (depp' qpn)) ps
2049ea68d4d1ff3d3aaea6bc4a65f2b84a887707817b57522c618f12659148b5
penpot/penpot
main.clj
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.srepl.main "A collection of adhoc fixes scripts." #_:clj-kondo/ignore (:require [app.common.logging :as l] [app.common.pprint :as p] [app.common.spec :as us] [app.db :as db] [app.rpc.commands.auth :as auth] [app.rpc.commands.profile :as profile] [app.srepl.fixes :as f] [app.srepl.helpers :as h] [app.util.blob :as blob] [app.util.objects-map :as omap] [app.util.pointer-map :as pmap] [app.util.time :as dt] [app.worker :as wrk] [clojure.pprint :refer [pprint]] [cuerdas.core :as str])) (defn print-available-tasks [system] (let [tasks (:app.worker/registry system)] (p/pprint (keys tasks) :level 200))) (defn run-task! ([system name] (run-task! system name {})) ([system name params] (let [tasks (:app.worker/registry system)] (if-let [task-fn (get tasks name)] (task-fn params) (println (format "no task '%s' found" name)))))) (defn schedule-task! ([system name] (schedule-task! system name {})) ([system name props] (let [pool (:app.db/pool system)] (wrk/submit! ::wrk/conn pool ::wrk/task name ::wrk/props props)))) (defn send-test-email! [system destination] (us/verify! :expr (some? system) :hint "system should be provided") (us/verify! :expr (string? destination) :hint "destination should be provided") (let [handler (:app.email/sendmail system)] (handler {:body "test email" :subject "test email" :to [destination]}))) (defn resend-email-verification-email! [system email] (us/verify! :expr (some? system) :hint "system should be provided") (let [sprops (:app.setup/props system) pool (:app.db/pool system) profile (profile/get-profile-by-email pool email)] (auth/send-email-verification! pool sprops profile) :email-sent)) (defn mark-profile-as-active! "Mark the profile blocked and removes all the http sessiones associated with the profile-id." [system email] (db/with-atomic [conn (:app.db/pool system)] (when-let [profile (db/get* conn :profile {:email (str/lower email)} {:columns [:id :email]})] (when-not (:is-blocked profile) (db/update! conn :profile {:is-active true} {:id (:id profile)}) :activated)))) (defn mark-profile-as-blocked! "Mark the profile blocked and removes all the http sessiones associated with the profile-id." [system email] (db/with-atomic [conn (:app.db/pool system)] (when-let [profile (db/get* conn :profile {:email (str/lower email)} {:columns [:id :email]})] (when-not (:is-blocked profile) (db/update! conn :profile {:is-blocked true} {:id (:id profile)}) (db/delete! conn :http-session {:profile-id (:id profile)}) :blocked)))) (defn enable-objects-map-feature-on-file! [system & {:keys [save? id]}] (letfn [(update-file [{:keys [features] :as file}] (if (contains? features "storage/objects-map") file (-> file (update :data migrate) (update :features conj "storage/objects-map")))) (migrate [data] (-> data (update :pages-index update-vals #(update % :objects omap/wrap)) (update :components update-vals #(update % :objects omap/wrap))))] (h/update-file! system :id id :update-fn update-file :save? save?))) (defn enable-pointer-map-feature-on-file! [system & {:keys [save? id]}] (letfn [(update-file [{:keys [features] :as file}] (if (contains? features "storage/pointer-map") file (-> file (update :data migrate) (update :features conj "storage/pointer-map")))) (migrate [data] (-> data (update :pages-index update-vals pmap/wrap) (update :components pmap/wrap)))] (h/update-file! system :id id :update-fn update-file :save? save?))) (defn enable-storage-features-on-file! [system & {:as params}] (enable-objects-map-feature-on-file! system params) (enable-pointer-map-feature-on-file! system params)) (defn instrument-var [var] (alter-var-root var (fn [f] (let [mf (meta f)] (if (::original mf) f (with-meta (fn [& params] (tap> params) (let [result (apply f params)] (tap> result) result)) {::original f})))))) (defn uninstrument-var [var] (alter-var-root var (fn [f] (or (::original (meta f)) f))))
null
https://raw.githubusercontent.com/penpot/penpot/b2b224e5a73cfd5a5642e050e731bb401732f6f1/backend/src/app/srepl/main.clj
clojure
Copyright (c) KALEIDOS INC
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.srepl.main "A collection of adhoc fixes scripts." #_:clj-kondo/ignore (:require [app.common.logging :as l] [app.common.pprint :as p] [app.common.spec :as us] [app.db :as db] [app.rpc.commands.auth :as auth] [app.rpc.commands.profile :as profile] [app.srepl.fixes :as f] [app.srepl.helpers :as h] [app.util.blob :as blob] [app.util.objects-map :as omap] [app.util.pointer-map :as pmap] [app.util.time :as dt] [app.worker :as wrk] [clojure.pprint :refer [pprint]] [cuerdas.core :as str])) (defn print-available-tasks [system] (let [tasks (:app.worker/registry system)] (p/pprint (keys tasks) :level 200))) (defn run-task! ([system name] (run-task! system name {})) ([system name params] (let [tasks (:app.worker/registry system)] (if-let [task-fn (get tasks name)] (task-fn params) (println (format "no task '%s' found" name)))))) (defn schedule-task! ([system name] (schedule-task! system name {})) ([system name props] (let [pool (:app.db/pool system)] (wrk/submit! ::wrk/conn pool ::wrk/task name ::wrk/props props)))) (defn send-test-email! [system destination] (us/verify! :expr (some? system) :hint "system should be provided") (us/verify! :expr (string? destination) :hint "destination should be provided") (let [handler (:app.email/sendmail system)] (handler {:body "test email" :subject "test email" :to [destination]}))) (defn resend-email-verification-email! [system email] (us/verify! :expr (some? system) :hint "system should be provided") (let [sprops (:app.setup/props system) pool (:app.db/pool system) profile (profile/get-profile-by-email pool email)] (auth/send-email-verification! pool sprops profile) :email-sent)) (defn mark-profile-as-active! "Mark the profile blocked and removes all the http sessiones associated with the profile-id." [system email] (db/with-atomic [conn (:app.db/pool system)] (when-let [profile (db/get* conn :profile {:email (str/lower email)} {:columns [:id :email]})] (when-not (:is-blocked profile) (db/update! conn :profile {:is-active true} {:id (:id profile)}) :activated)))) (defn mark-profile-as-blocked! "Mark the profile blocked and removes all the http sessiones associated with the profile-id." [system email] (db/with-atomic [conn (:app.db/pool system)] (when-let [profile (db/get* conn :profile {:email (str/lower email)} {:columns [:id :email]})] (when-not (:is-blocked profile) (db/update! conn :profile {:is-blocked true} {:id (:id profile)}) (db/delete! conn :http-session {:profile-id (:id profile)}) :blocked)))) (defn enable-objects-map-feature-on-file! [system & {:keys [save? id]}] (letfn [(update-file [{:keys [features] :as file}] (if (contains? features "storage/objects-map") file (-> file (update :data migrate) (update :features conj "storage/objects-map")))) (migrate [data] (-> data (update :pages-index update-vals #(update % :objects omap/wrap)) (update :components update-vals #(update % :objects omap/wrap))))] (h/update-file! system :id id :update-fn update-file :save? save?))) (defn enable-pointer-map-feature-on-file! [system & {:keys [save? id]}] (letfn [(update-file [{:keys [features] :as file}] (if (contains? features "storage/pointer-map") file (-> file (update :data migrate) (update :features conj "storage/pointer-map")))) (migrate [data] (-> data (update :pages-index update-vals pmap/wrap) (update :components pmap/wrap)))] (h/update-file! system :id id :update-fn update-file :save? save?))) (defn enable-storage-features-on-file! [system & {:as params}] (enable-objects-map-feature-on-file! system params) (enable-pointer-map-feature-on-file! system params)) (defn instrument-var [var] (alter-var-root var (fn [f] (let [mf (meta f)] (if (::original mf) f (with-meta (fn [& params] (tap> params) (let [result (apply f params)] (tap> result) result)) {::original f})))))) (defn uninstrument-var [var] (alter-var-root var (fn [f] (or (::original (meta f)) f))))
ef7d0af2c1c46dc1aa2e69c32c2de2399fc082c43336c8bf9a3856343c44208d
wilkerlucio/multi-timer
timer.cljs
(ns com.wsscode.multi-timer.components.timer (:require [fulcro.client.primitives :as fp] [com.wsscode.multi-timer.ui :as ui] [clojure.spec.alpha :as s] [fulcro.client.mutations :as mutations])) (s/def ::id uuid?) (s/def ::sections (s/coll-of (s/keys))) (s/def ::record-start pos-int?) (defn time-now [] (js/Math.floor (/ (.getTime (js/Date.)) 1000))) (mutations/defmutation add-section [_] (action [{:keys [state ref]}] (let [time (- (time-now) (get-in @state (conj ref ::record-start)))] (swap! state update-in ref update ::sections conj {::section-id (random-uuid) ::time time})))) (fp/defsc Timer [this props] {:ident [::id ::id] :query [::id]} (ui/view (clj->js {}) )) (def timer (fp/factory Timer {:keyfn ::id})) (fp/defsc RecorderTimeSection [this {::keys [time]}] {:initial-state {} :ident [::section-id ::section-id] :query [::section-id ::time ::action]} (ui/view nil (ui/text #js {:style #js {:color "#000"}} (str time)))) (def recorder-time-section (fp/factory RecorderTimeSection {:keyfn ::section-id})) (fp/defsc Recorder [this {::keys [current-time record-start sections]}] {:initial-state {::id (random-uuid) ::sections [] ::record-start nil} :ident [::id ::id] :query [::id ::sections ::record-start [::current-time '_]]} (ui/view nil (mapv recorder-time-section sections) (if record-start (ui/view nil (ui/text #js {:style #js {:color "#000"}} (str "Running clock!! " (js/Math.max 0 (- current-time record-start)))) (ui/button #js {:onPress #(fp/transact! this [`(add-section {})]) :title "Add time point"})) (ui/touchable-highlight #js {:onPress #(mutations/set-value! this ::record-start (time-now))} (ui/text #js {:style #js {:color "#000"}} "Start"))))) (def recorder (fp/factory Recorder {:keyfn ::id})) [{::time 3.5 ::action "Colocar no fogo"} {::time 6.3 ::action "Trocar X"} {::time 9 ::action "Bla"}]
null
https://raw.githubusercontent.com/wilkerlucio/multi-timer/efd2c04dc7f25249368bdabadc2a76d54a9bb5f8/src/com/wsscode/multi_timer/components/timer.cljs
clojure
(ns com.wsscode.multi-timer.components.timer (:require [fulcro.client.primitives :as fp] [com.wsscode.multi-timer.ui :as ui] [clojure.spec.alpha :as s] [fulcro.client.mutations :as mutations])) (s/def ::id uuid?) (s/def ::sections (s/coll-of (s/keys))) (s/def ::record-start pos-int?) (defn time-now [] (js/Math.floor (/ (.getTime (js/Date.)) 1000))) (mutations/defmutation add-section [_] (action [{:keys [state ref]}] (let [time (- (time-now) (get-in @state (conj ref ::record-start)))] (swap! state update-in ref update ::sections conj {::section-id (random-uuid) ::time time})))) (fp/defsc Timer [this props] {:ident [::id ::id] :query [::id]} (ui/view (clj->js {}) )) (def timer (fp/factory Timer {:keyfn ::id})) (fp/defsc RecorderTimeSection [this {::keys [time]}] {:initial-state {} :ident [::section-id ::section-id] :query [::section-id ::time ::action]} (ui/view nil (ui/text #js {:style #js {:color "#000"}} (str time)))) (def recorder-time-section (fp/factory RecorderTimeSection {:keyfn ::section-id})) (fp/defsc Recorder [this {::keys [current-time record-start sections]}] {:initial-state {::id (random-uuid) ::sections [] ::record-start nil} :ident [::id ::id] :query [::id ::sections ::record-start [::current-time '_]]} (ui/view nil (mapv recorder-time-section sections) (if record-start (ui/view nil (ui/text #js {:style #js {:color "#000"}} (str "Running clock!! " (js/Math.max 0 (- current-time record-start)))) (ui/button #js {:onPress #(fp/transact! this [`(add-section {})]) :title "Add time point"})) (ui/touchable-highlight #js {:onPress #(mutations/set-value! this ::record-start (time-now))} (ui/text #js {:style #js {:color "#000"}} "Start"))))) (def recorder (fp/factory Recorder {:keyfn ::id})) [{::time 3.5 ::action "Colocar no fogo"} {::time 6.3 ::action "Trocar X"} {::time 9 ::action "Bla"}]
1d87fe60d9870a2f8ca1c65206c0e983b12b1495dfeedafc51b2045a5601e689
steshaw/PLAR
skolems.ml
(* ========================================================================= *) (* Illustration of Skolemizing a set of formulas *) (* *) Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . ) (* ========================================================================= *) let rec rename_term tm = match tm with Fn(f,args) -> Fn("old_"^f,map rename_term args) | _ -> tm;; let rename_form = onformula rename_term;; let rec skolems fms corr = match fms with [] -> [],corr | (p::ofms) -> let p',corr' = skolem (rename_form p) corr in let ps',corr'' = skolems ofms corr' in p'::ps',corr'';; let skolemizes fms = fst(skolems fms []);; START_INTERACTIVE;; skolemizes [<<exists x y. x + y = 2>>; <<forall x. exists y. x + 1 = y>>];; END_INTERACTIVE;;
null
https://raw.githubusercontent.com/steshaw/PLAR/c143b097d1028963f4c1d24f45a1a56c8b65b838/skolems.ml
ocaml
========================================================================= Illustration of Skolemizing a set of formulas =========================================================================
Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . ) let rec rename_term tm = match tm with Fn(f,args) -> Fn("old_"^f,map rename_term args) | _ -> tm;; let rename_form = onformula rename_term;; let rec skolems fms corr = match fms with [] -> [],corr | (p::ofms) -> let p',corr' = skolem (rename_form p) corr in let ps',corr'' = skolems ofms corr' in p'::ps',corr'';; let skolemizes fms = fst(skolems fms []);; START_INTERACTIVE;; skolemizes [<<exists x y. x + y = 2>>; <<forall x. exists y. x + 1 = y>>];; END_INTERACTIVE;;
39c3063c49912597f7311c00957e126e57aa3a1880f6f158533f4d5cec219976
OCamlPro/OCamlPro-OCaml-Branch
poly.ml
$ I d : poly.ml 9396 2009 - 10 - 26 07:11:36Z garrigue $ (* Polymorphic methods are now available in the main branch. Enjoy. *) (* Tests for explicit polymorphism *) open StdLabels;; type 'a t = { t : 'a };; type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b };; let f l = { fold = List.fold_left l };; (f [1;2;3]).fold ~f:(+) ~init:0;; class ['b] ilist l = object val l = l method add x = {< l = x :: l >} method fold : 'a. f:('a -> 'b -> 'a) -> init:'a -> 'a = List.fold_left l end ;; class virtual ['a] vlist = object (_ : 'self) method virtual add : 'a -> 'self method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b end ;; class ilist2 l = object inherit [int] vlist val l = l method add x = {< l = x :: l >} method fold = List.fold_left l end ;; let ilist2 l = object inherit [_] vlist val l = l method add x = {< l = x :: l >} method fold = List.fold_left l end ;; class ['a] ilist3 l = object inherit ['a] vlist val l = l method add x = {< l = x :: l >} method fold = List.fold_left l end ;; class ['a] ilist4 (l : 'a list) = object val l = l method virtual add : _ method add x = {< l = x :: l >} method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method fold = List.fold_left l end ;; class ['a] ilist5 (l : 'a list) = object (self) val l = l method add x = {< l = x :: l >} method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init) method fold = List.fold_left l end ;; class ['a] ilist6 l = object (self) inherit ['a] vlist val l = l method add x = {< l = x :: l >} method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init) method fold = List.fold_left l end ;; class virtual ['a] olist = object method virtual fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c end ;; class ['a] onil = object inherit ['a] olist method fold ~f ~init = init end ;; class ['a] ocons ~hd ~tl = object (_ : 'b) inherit ['a] olist val hd : 'a = hd val tl : 'a olist = tl method fold ~f ~init = f hd (tl#fold ~f ~init) end ;; class ['a] ostream ~hd ~tl = object (_ : 'b) inherit ['a] olist val hd : 'a = hd val tl : _ #olist = (tl : 'a ostream) method fold ~f ~init = f hd (tl#fold ~f ~init) method empty = false end ;; class ['a] ostream1 ~hd ~tl = object (self : 'b) inherit ['a] olist val hd = hd val tl : 'b = tl method hd = hd method tl = tl method fold ~f ~init = self#tl#fold ~f ~init:(f self#hd init) end ;; class vari = object method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int method m = function `A -> 1 | `B|`C -> 0 end ;; class vari = object method m : 'a. ([< `A|`B|`C] as 'a) -> int = function `A -> 1 | `B|`C -> 0 end ;; module V = struct type v = [`A | `B | `C] let m : [< v] -> int = function `A -> 1 | #v -> 0 end ;; class varj = object method virtual m : 'a. ([< V.v] as 'a) -> int method m = V.m end ;; module type T = sig class vari : object method m : 'a. ([< `A | `B | `C] as 'a) -> int end end ;; module M0 = struct class vari = object method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int method m = function `A -> 1 | `B|`C -> 0 end end ;; module M : T = M0 ;; let v = new M.vari;; v#m `A;; class point ~x ~y = object val x : int = x val y : int = y method x = x method y = y end ;; class color_point ~x ~y ~color = object inherit point ~x ~y val color : string = color method color = color end ;; class circle (p : #point) ~r = object val p = (p :> point) val r = r method virtual distance : 'a. (#point as 'a) -> float method distance p' = let dx = p#x - p'#x and dy = p#y - p'#y in let d = sqrt (float (dx * dx + dy * dy)) -. float r in if d < 0. then 0. else d end ;; let p0 = new point ~x:3 ~y:5 let p1 = new point ~x:10 ~y:13 let cp = new color_point ~x:12 ~y:(-5) ~color:"green" let c = new circle p0 ~r:2 let d = c#distance cp ;; let f (x : < m : 'a. 'a -> 'a >) = (x : < m : 'b. 'b -> 'b >) ;; let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >) ;; class id = object method virtual id : 'a. 'a -> 'a method id x = x end ;; class type id_spec = object method id : 'a -> 'a end ;; class id_impl = object (_ : #id_spec) method id x = x end ;; class a = object method m = (new b : id_spec)#id true end and b = object (_ : #id_spec) method id x = x end ;; class ['a] id1 = object method virtual id : 'b. 'b -> 'a method id x = x end ;; class id2 (x : 'a) = object method virtual id : 'b. 'b -> 'a method id x = x end ;; class id3 x = object val x = x method virtual id : 'a. 'a -> 'a method id _ = x end ;; class id4 () = object val mutable r = None method virtual id : 'a. 'a -> 'a method id x = match r with None -> r <- Some x; x | Some y -> y end ;; class c = object method virtual m : 'a 'b. 'a -> 'b -> 'a method m x y = x end ;; let f1 (f : id) = f#id 1, f#id true ;; let f2 f = (f : id)#id 1, (f : id)#id true ;; let f3 f = f#id 1, f#id true ;; let f4 f = ignore(f : id); f#id 1, f#id true ;; class c = object method virtual m : 'a. (#id as 'a) -> int * bool method m (f : #id) = f#id 1, f#id true end ;; class id2 = object (_ : 'b) method virtual id : 'a. 'a -> 'a method id x = x method mono (x : int) = x end ;; let app = new c #m (new id2) ;; type 'a foo = 'a foo list ;; class ['a] bar (x : 'a) = object end ;; type 'a foo = 'a foo bar ;; fun x -> (x : < m : 'a. 'a * 'b > as 'b)#m;; fun x -> (x : < m : 'a. 'b * 'a list> as 'b)#m;; let f x = (x : < m : 'a. 'b * (< n : 'a; .. > as 'a) > as 'b)#m;; fun (x : < p : 'a. < m : 'a ; n : 'b ; .. > as 'a > as 'b) -> x#p;; fun (x : <m:'a. 'a * <p:'b. 'b * 'c * 'd> as 'c> as 'd) -> x#m;; (* printer is wrong on the next (no official syntax) *) fun (x : <m:'a.<p:'a;..> >) -> x#m;; type sum = T of < id: 'a. 'a -> 'a > ;; fun (T x) -> x#id;; type record = { r: < id: 'a. 'a -> 'a > } ;; fun x -> x.r#id;; fun {r=x} -> x#id;; class myself = object (self) method self : 'a. 'a -> 'b = fun _ -> self end;; class number = object (self : 'self) val num = 0 method num = num method succ = {< num = num + 1 >} method prev = self#switch ~zero:(fun () -> failwith "zero") ~prev:(fun x -> x) method switch : 'a. zero:(unit -> 'a) -> prev:('self -> 'a) -> 'a = fun ~zero ~prev -> if num = 0 then zero () else prev {< num = num - 1 >} end ;; let id x = x ;; class c = object method id : 'a. 'a -> 'a = id end ;; class c' = object inherit c method id = id end ;; class d = object inherit c as c val mutable count = 0 method id x = count <- count+1; x method count = count method old : 'a. 'a -> 'a = c#id end ;; class ['a] olist l = object val l = l method fold : 'b. f:('a -> 'b -> 'b) -> init:'b -> 'b = List.fold_right l method cons a = {< l = a :: l >} end ;; let sum (l : 'a #olist) = l#fold ~f:(fun x acc -> x+acc) ~init:0 ;; let count (l : 'a #olist) = l#fold ~f:(fun _ acc -> acc+1) ~init:0 ;; let append (l : 'a #olist) (l' : 'b #olist) = l#fold ~init:l' ~f:(fun x acc -> acc#cons x) ;; type 'a t = unit ;; class o = object method x : 'a. ([> `A] as 'a) t -> unit = fun _ -> () end ;; class c = object method m = new d () end and d ?(x=0) () = object end;; class d ?(x=0) () = object end and c = object method m = new d () end;; class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end class zero = object (_ : #numeral) method fold f x = x end class next (n : #numeral) = object (_ : #numeral) method fold f x = n#fold f (f x) end ;; class type node_type = object method as_variant : [> `Node of node_type] end;; class node : node_type = object (self) method as_variant : 'a. [> `Node of node_type] as 'a = `Node (self :> node_type) end;; class node = object (self : #node_type) method as_variant = `Node (self :> node_type) end;; type bad = {bad : 'a. 'a option ref};; let bad = {bad = ref None};; type bad2 = {mutable bad2 : 'a. 'a option ref option};; let bad2 = {bad2 = None};; bad2.bad2 <- Some (ref None);; (* Type variable scope *) let f (x: <m:'a.<p: 'a * 'b> as 'b>) (y : 'b) = ();; let f (x: <m:'a. 'a * (<p:int*'b> as 'b)>) (y : 'b) = ();; (* PR#1374 *) type 'a t= [`A of 'a];; class c = object (self) method m : 'a. ([> 'a t] as 'a) -> unit = fun x -> self#m x end;; class c = object (self) method m : 'a. ([> 'a t] as 'a) -> unit = function | `A x' -> self#m x' | _ -> failwith "c#m" end;; class c = object (self) method m : 'a. ([> 'a t] as 'a) -> 'a = fun x -> self#m x end;; (* usage avant instance *) class c = object method m : 'a. 'a option -> ([> `A] as 'a) = fun x -> `A end;; (* various old bugs *) class virtual ['a] visitor = object method virtual caseNil : 'a end and virtual int_list = object method virtual visit : 'a.('a visitor -> 'a) end;; type ('a,'b) list_visitor = < caseNil : 'a; caseCons : 'b -> 'b list -> 'a > type 'b alist = < visit : 'a. ('a,'b) list_visitor -> 'a > (* PR#1607 *) class type ct = object ('s) method fold : ('b -> 's -> 'b) -> 'b -> 'b end type t = {f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b};; PR#1663 type t = u and u = t;; (* PR#1731 *) class ['t] a = object constraint 't = [> `A of 't a] end type t = [ `A of t a ];; Wrong in 3.06 type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;; (* Full polymorphism if we do not expand *) type 'a t = 'a and u = int t;; (* Loose polymorphism if we expand *) type 'a t constraint 'a = int;; type 'a u = 'a and 'a v = 'a u t;; type 'a u = 'a and 'a v = 'a u t constraint 'a = int;; (* Behaviour is unstable *) type g = int;; type 'a t = unit constraint 'a = g;; type 'a u = 'a and 'a v = 'a u t;; type 'a u = 'a and 'a v = 'a u t constraint 'a = int;; (* Example of wrong expansion *) type 'a u = < m : 'a v > and 'a v = 'a list u;; (* PR#1744: Ctype.matches *) type 'a t = 'a type 'a u = A of 'a t;; (* Unification of cyclic terms *) type 'a t = < a : 'a >;; fun (x : 'a t as 'a) -> (x : 'b t);; type u = 'a t as 'a;; (* Variant tests *) type t = A | B;; function `A,_ -> 1 | _,A -> 2 | _,B -> 3;; function `A,_ -> 1 | _,(A|B) -> 2;; function Some `A, _ -> 1 | Some _, A -> 2 | None, A -> 3 | _, B -> 4;; function Some `A, A -> 1 | Some `A, B -> 1 | Some _, A -> 2 | None, A -> 3 | _, B -> 4;; function A, `A -> 1 | A, `B -> 2 | B, _ -> 3;; function `A, A -> 1 | `B, A -> 2 | _, B -> 3;; function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;; function `B,1 -> 1 | _,1 -> 2;; function 1,`B -> 1 | 1,_ -> 2;; (* pass typetexp, but fails during Typedecl.check_recursion *) type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b] and ('a, 'b) b = 'b -> unit constraint 'b = [> `A of ('a, 'b) a as 'a];; (* PR#1917: expanding may change original in Ctype.unify2 *) Note : since 3.11 , the abbreviations are not used when printing a type where they occur recursively inside . a type where they occur recursively inside. *) class type ['a, 'b] a = object method b: ('a, 'b) #b as 'b method as_a: ('a, 'b) a end and ['a, 'b] b = object method a: ('a, 'b) #a as 'a method as_b: ('a, 'b) b end class type ['b] ca = object ('s) inherit ['s, 'b] a end class type ['a] cb = object ('s) inherit ['a, 's] b end type bt = 'b ca cb as 'b ;; (* final classes, etc... *) class c = object method m = 1 end;; let f () = object (self:c) method m = 1 end;; let f () = object (self:c) method private n = 1 method m = self#n end;; let f () = object method private n = 1 method m = {<>}#n end;; let f () = object (self:c) method n = 1 method m = 2 end;; let f () = object (_:'s) constraint 's = < n : int > method m = 1 end;; class c = object (_ : 's) method x = 1 method private m = object (self: 's) method x = 3 method private m = self end end;; let o = object (_ : 's) method x = 1 method private m = object (self: 's) method x = 3 method private m = self end end;; (* Unsound! *) fun (x : <m : 'a. 'a * <m: 'b. 'a * 'foo> > as 'foo) -> (x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);; type 'a foo = <m: 'b. 'a * 'a foo> type foo' = <m: 'a. 'a * 'a foo> type 'a bar = <m: 'b. 'a * <m: 'c. 'c * 'a bar> > type bar' = <m: 'a. 'a * 'a bar > let f (x : foo') = (x : bar');; fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) -> (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);; fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) -> (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('b * 'bar)>)> as 'bar);; fun (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) -> (x : <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>);; let f x = (x : <m : 'a. 'a -> ('a * <m:'c. 'c -> 'bar> as 'bar)> :> <m : 'a. 'a -> ('a * 'foo)> as 'foo);; module M : sig val f : (<m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>) -> unit end = struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;; module M : sig type t = <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)> end = struct type t = <m : 'a. 'a * ('a * 'foo)> as 'foo end;; module M : sig type 'a t type u = <m: 'a. 'a t> end = struct type 'a t = int type u = <m: int> end;; module M : sig type 'a t val f : <m: 'a. 'a t> -> int end = struct type 'a t = int let f (x : <m:int>) = x#m end;; (* The following should be accepted too! *) module M : sig type 'a t val f : <m: 'a. 'a t> -> int end = struct type 'a t = int let f x = x#m end;; let f x y = ignore (x :> <m:'a.'a -> 'c * < > > as 'c); ignore (y :> <m:'b.'b -> 'd * < > > as 'd); x = y;; (* Subtyping *) type t = [`A|`B];; type v = private [> t];; fun x -> (x : t :> v);; type u = private [< t];; fun x -> (x : u :> v);; fun x -> (x : v :> u);; type v = private [< t];; fun x -> (x : u :> v);; type p = <x:p>;; type q = private <x:p; ..>;; fun x -> (x : q :> p);; fun x -> (x : p :> q);; let f1 x = (x : <m:'a. (<p:int;..> as 'a) -> int> :> <m:'b. (<p:int;q:int;..> as 'b) -> int>);; let f2 x = (x : <m:'a. (<p:<a:int>;..> as 'a) -> int> :> <m:'b. (<p:<a:int;b:int>;..> as 'b) -> int>);; let f3 x = (x : <m:'a. (<p:<a:int;b:int>;..> as 'a) -> int> :> <m:'b. (<p:<a:int>;..> as 'b) -> int>);; let f4 x = (x : <p:<a:int;b:int>;..> :> <p:<a:int>;..>);; let f5 x = (x : <m:'a. [< `A of <p:int> ] as 'a> :> <m:'a. [< `A of < > ] as 'a>);; let f6 x = (x : <m:'a. [< `A of < > ] as 'a> :> <m:'a. [< `A of <p:int> ] as 'a>);; (* Not really principal? *) class c = object method id : 'a. 'a -> 'a = fun x -> x end;; type u = c option;; let just = function None -> failwith "just" | Some x -> x;; let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;; let g x = let none = match None with y -> ignore [y;(None:u)]; y in let x = List.hd [Some x; none] in (just x)#id;; let h x = let none = let y = None in ignore [y;(None:u)]; y in let x = List.hd [Some x; none] in (just x)#id;; (* polymorphic recursion *) let rec f : 'a. 'a -> _ = fun x -> 1 and g x = f x;; type 'a t = Leaf of 'a | Node of ('a * 'a) t;; let rec depth : 'a. 'a t -> _ = function Leaf _ -> 1 | Node x -> 1 + depth x;; let rec depth : 'a. 'a t -> _ = function Leaf _ -> 1 | Node x -> 1 + d x and d x = depth x;; (* fails *) let rec depth : 'a. 'a t -> _ = function Leaf x -> x | Node x -> 1 + depth x;; (* fails *) let rec depth : 'a. 'a t -> _ = function Leaf x -> x | Node x -> depth x;; (* fails *) let rec depth : 'a 'b. 'a t -> 'b = function Leaf x -> x | Node x -> depth x;; (* fails *) let rec r : 'a. 'a list * 'b list ref = [], ref [] and q () = r;; let f : 'a. _ -> _ = fun x -> x;; let zero : 'a. [> `Int of int | `B of 'a] as 'a = `Int 0;; (* ok *) let zero : 'a. [< `Int of int] as 'a = `Int 0;; (* fails *) (* compare with records (should be the same) *) type t = {f: 'a. [> `Int of int | `B of 'a] as 'a} let zero = {f = `Int 0} ;; type t = {f: 'a. [< `Int of int] as 'a} let zero = {f = `Int 0} ;; (* fails *) (* Yet another example *) let rec id : 'a. 'a -> 'a = fun x -> x and neg i b = (id (-i), id (not b));; type t = A of int | B of (int*t) list | C of (string*t) list let rec transf f = function | A x -> f x | B l -> B (transf_alist f l) | C l -> C (transf_alist f l) and transf_alist : 'a. _ -> ('a*t) list -> ('a*t) list = fun f -> function | [] -> [] | (k,v)::tl -> (k, transf f v) :: transf_alist f tl ;; (* PR#4862 *) type t = {f: 'a. ('a list -> int) Lazy.t} let l : t = { f = lazy (raise Not_found)};; (* variant *) type t = {f: 'a. 'a -> unit};; {f=fun ?x y -> ()};; {f=fun ?x y -> y};; (* fail *)
null
https://raw.githubusercontent.com/OCamlPro/OCamlPro-OCaml-Branch/3a522985649389f89dac73e655d562c54f0456a5/inline-more/testsuite/tests/typing-poly/poly.ml
ocaml
Polymorphic methods are now available in the main branch. Enjoy. Tests for explicit polymorphism printer is wrong on the next (no official syntax) Type variable scope PR#1374 usage avant instance various old bugs PR#1607 PR#1731 Full polymorphism if we do not expand Loose polymorphism if we expand Behaviour is unstable Example of wrong expansion PR#1744: Ctype.matches Unification of cyclic terms Variant tests pass typetexp, but fails during Typedecl.check_recursion PR#1917: expanding may change original in Ctype.unify2 final classes, etc... Unsound! The following should be accepted too! Subtyping Not really principal? polymorphic recursion fails fails fails fails ok fails compare with records (should be the same) fails Yet another example PR#4862 variant fail
$ I d : poly.ml 9396 2009 - 10 - 26 07:11:36Z garrigue $ open StdLabels;; type 'a t = { t : 'a };; type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b };; let f l = { fold = List.fold_left l };; (f [1;2;3]).fold ~f:(+) ~init:0;; class ['b] ilist l = object val l = l method add x = {< l = x :: l >} method fold : 'a. f:('a -> 'b -> 'a) -> init:'a -> 'a = List.fold_left l end ;; class virtual ['a] vlist = object (_ : 'self) method virtual add : 'a -> 'self method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b end ;; class ilist2 l = object inherit [int] vlist val l = l method add x = {< l = x :: l >} method fold = List.fold_left l end ;; let ilist2 l = object inherit [_] vlist val l = l method add x = {< l = x :: l >} method fold = List.fold_left l end ;; class ['a] ilist3 l = object inherit ['a] vlist val l = l method add x = {< l = x :: l >} method fold = List.fold_left l end ;; class ['a] ilist4 (l : 'a list) = object val l = l method virtual add : _ method add x = {< l = x :: l >} method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method fold = List.fold_left l end ;; class ['a] ilist5 (l : 'a list) = object (self) val l = l method add x = {< l = x :: l >} method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init) method fold = List.fold_left l end ;; class ['a] ilist6 l = object (self) inherit ['a] vlist val l = l method add x = {< l = x :: l >} method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init) method fold = List.fold_left l end ;; class virtual ['a] olist = object method virtual fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c end ;; class ['a] onil = object inherit ['a] olist method fold ~f ~init = init end ;; class ['a] ocons ~hd ~tl = object (_ : 'b) inherit ['a] olist val hd : 'a = hd val tl : 'a olist = tl method fold ~f ~init = f hd (tl#fold ~f ~init) end ;; class ['a] ostream ~hd ~tl = object (_ : 'b) inherit ['a] olist val hd : 'a = hd val tl : _ #olist = (tl : 'a ostream) method fold ~f ~init = f hd (tl#fold ~f ~init) method empty = false end ;; class ['a] ostream1 ~hd ~tl = object (self : 'b) inherit ['a] olist val hd = hd val tl : 'b = tl method hd = hd method tl = tl method fold ~f ~init = self#tl#fold ~f ~init:(f self#hd init) end ;; class vari = object method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int method m = function `A -> 1 | `B|`C -> 0 end ;; class vari = object method m : 'a. ([< `A|`B|`C] as 'a) -> int = function `A -> 1 | `B|`C -> 0 end ;; module V = struct type v = [`A | `B | `C] let m : [< v] -> int = function `A -> 1 | #v -> 0 end ;; class varj = object method virtual m : 'a. ([< V.v] as 'a) -> int method m = V.m end ;; module type T = sig class vari : object method m : 'a. ([< `A | `B | `C] as 'a) -> int end end ;; module M0 = struct class vari = object method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int method m = function `A -> 1 | `B|`C -> 0 end end ;; module M : T = M0 ;; let v = new M.vari;; v#m `A;; class point ~x ~y = object val x : int = x val y : int = y method x = x method y = y end ;; class color_point ~x ~y ~color = object inherit point ~x ~y val color : string = color method color = color end ;; class circle (p : #point) ~r = object val p = (p :> point) val r = r method virtual distance : 'a. (#point as 'a) -> float method distance p' = let dx = p#x - p'#x and dy = p#y - p'#y in let d = sqrt (float (dx * dx + dy * dy)) -. float r in if d < 0. then 0. else d end ;; let p0 = new point ~x:3 ~y:5 let p1 = new point ~x:10 ~y:13 let cp = new color_point ~x:12 ~y:(-5) ~color:"green" let c = new circle p0 ~r:2 let d = c#distance cp ;; let f (x : < m : 'a. 'a -> 'a >) = (x : < m : 'b. 'b -> 'b >) ;; let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >) ;; class id = object method virtual id : 'a. 'a -> 'a method id x = x end ;; class type id_spec = object method id : 'a -> 'a end ;; class id_impl = object (_ : #id_spec) method id x = x end ;; class a = object method m = (new b : id_spec)#id true end and b = object (_ : #id_spec) method id x = x end ;; class ['a] id1 = object method virtual id : 'b. 'b -> 'a method id x = x end ;; class id2 (x : 'a) = object method virtual id : 'b. 'b -> 'a method id x = x end ;; class id3 x = object val x = x method virtual id : 'a. 'a -> 'a method id _ = x end ;; class id4 () = object val mutable r = None method virtual id : 'a. 'a -> 'a method id x = match r with None -> r <- Some x; x | Some y -> y end ;; class c = object method virtual m : 'a 'b. 'a -> 'b -> 'a method m x y = x end ;; let f1 (f : id) = f#id 1, f#id true ;; let f2 f = (f : id)#id 1, (f : id)#id true ;; let f3 f = f#id 1, f#id true ;; let f4 f = ignore(f : id); f#id 1, f#id true ;; class c = object method virtual m : 'a. (#id as 'a) -> int * bool method m (f : #id) = f#id 1, f#id true end ;; class id2 = object (_ : 'b) method virtual id : 'a. 'a -> 'a method id x = x method mono (x : int) = x end ;; let app = new c #m (new id2) ;; type 'a foo = 'a foo list ;; class ['a] bar (x : 'a) = object end ;; type 'a foo = 'a foo bar ;; fun x -> (x : < m : 'a. 'a * 'b > as 'b)#m;; fun x -> (x : < m : 'a. 'b * 'a list> as 'b)#m;; let f x = (x : < m : 'a. 'b * (< n : 'a; .. > as 'a) > as 'b)#m;; fun (x : < p : 'a. < m : 'a ; n : 'b ; .. > as 'a > as 'b) -> x#p;; fun (x : <m:'a. 'a * <p:'b. 'b * 'c * 'd> as 'c> as 'd) -> x#m;; fun (x : <m:'a.<p:'a;..> >) -> x#m;; type sum = T of < id: 'a. 'a -> 'a > ;; fun (T x) -> x#id;; type record = { r: < id: 'a. 'a -> 'a > } ;; fun x -> x.r#id;; fun {r=x} -> x#id;; class myself = object (self) method self : 'a. 'a -> 'b = fun _ -> self end;; class number = object (self : 'self) val num = 0 method num = num method succ = {< num = num + 1 >} method prev = self#switch ~zero:(fun () -> failwith "zero") ~prev:(fun x -> x) method switch : 'a. zero:(unit -> 'a) -> prev:('self -> 'a) -> 'a = fun ~zero ~prev -> if num = 0 then zero () else prev {< num = num - 1 >} end ;; let id x = x ;; class c = object method id : 'a. 'a -> 'a = id end ;; class c' = object inherit c method id = id end ;; class d = object inherit c as c val mutable count = 0 method id x = count <- count+1; x method count = count method old : 'a. 'a -> 'a = c#id end ;; class ['a] olist l = object val l = l method fold : 'b. f:('a -> 'b -> 'b) -> init:'b -> 'b = List.fold_right l method cons a = {< l = a :: l >} end ;; let sum (l : 'a #olist) = l#fold ~f:(fun x acc -> x+acc) ~init:0 ;; let count (l : 'a #olist) = l#fold ~f:(fun _ acc -> acc+1) ~init:0 ;; let append (l : 'a #olist) (l' : 'b #olist) = l#fold ~init:l' ~f:(fun x acc -> acc#cons x) ;; type 'a t = unit ;; class o = object method x : 'a. ([> `A] as 'a) t -> unit = fun _ -> () end ;; class c = object method m = new d () end and d ?(x=0) () = object end;; class d ?(x=0) () = object end and c = object method m = new d () end;; class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end class zero = object (_ : #numeral) method fold f x = x end class next (n : #numeral) = object (_ : #numeral) method fold f x = n#fold f (f x) end ;; class type node_type = object method as_variant : [> `Node of node_type] end;; class node : node_type = object (self) method as_variant : 'a. [> `Node of node_type] as 'a = `Node (self :> node_type) end;; class node = object (self : #node_type) method as_variant = `Node (self :> node_type) end;; type bad = {bad : 'a. 'a option ref};; let bad = {bad = ref None};; type bad2 = {mutable bad2 : 'a. 'a option ref option};; let bad2 = {bad2 = None};; bad2.bad2 <- Some (ref None);; let f (x: <m:'a.<p: 'a * 'b> as 'b>) (y : 'b) = ();; let f (x: <m:'a. 'a * (<p:int*'b> as 'b)>) (y : 'b) = ();; type 'a t= [`A of 'a];; class c = object (self) method m : 'a. ([> 'a t] as 'a) -> unit = fun x -> self#m x end;; class c = object (self) method m : 'a. ([> 'a t] as 'a) -> unit = function | `A x' -> self#m x' | _ -> failwith "c#m" end;; class c = object (self) method m : 'a. ([> 'a t] as 'a) -> 'a = fun x -> self#m x end;; class c = object method m : 'a. 'a option -> ([> `A] as 'a) = fun x -> `A end;; class virtual ['a] visitor = object method virtual caseNil : 'a end and virtual int_list = object method virtual visit : 'a.('a visitor -> 'a) end;; type ('a,'b) list_visitor = < caseNil : 'a; caseCons : 'b -> 'b list -> 'a > type 'b alist = < visit : 'a. ('a,'b) list_visitor -> 'a > class type ct = object ('s) method fold : ('b -> 's -> 'b) -> 'b -> 'b end type t = {f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b};; PR#1663 type t = u and u = t;; class ['t] a = object constraint 't = [> `A of 't a] end type t = [ `A of t a ];; Wrong in 3.06 type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;; type 'a t = 'a and u = int t;; type 'a t constraint 'a = int;; type 'a u = 'a and 'a v = 'a u t;; type 'a u = 'a and 'a v = 'a u t constraint 'a = int;; type g = int;; type 'a t = unit constraint 'a = g;; type 'a u = 'a and 'a v = 'a u t;; type 'a u = 'a and 'a v = 'a u t constraint 'a = int;; type 'a u = < m : 'a v > and 'a v = 'a list u;; type 'a t = 'a type 'a u = A of 'a t;; type 'a t = < a : 'a >;; fun (x : 'a t as 'a) -> (x : 'b t);; type u = 'a t as 'a;; type t = A | B;; function `A,_ -> 1 | _,A -> 2 | _,B -> 3;; function `A,_ -> 1 | _,(A|B) -> 2;; function Some `A, _ -> 1 | Some _, A -> 2 | None, A -> 3 | _, B -> 4;; function Some `A, A -> 1 | Some `A, B -> 1 | Some _, A -> 2 | None, A -> 3 | _, B -> 4;; function A, `A -> 1 | A, `B -> 2 | B, _ -> 3;; function `A, A -> 1 | `B, A -> 2 | _, B -> 3;; function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;; function `B,1 -> 1 | _,1 -> 2;; function 1,`B -> 1 | 1,_ -> 2;; type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b] and ('a, 'b) b = 'b -> unit constraint 'b = [> `A of ('a, 'b) a as 'a];; Note : since 3.11 , the abbreviations are not used when printing a type where they occur recursively inside . a type where they occur recursively inside. *) class type ['a, 'b] a = object method b: ('a, 'b) #b as 'b method as_a: ('a, 'b) a end and ['a, 'b] b = object method a: ('a, 'b) #a as 'a method as_b: ('a, 'b) b end class type ['b] ca = object ('s) inherit ['s, 'b] a end class type ['a] cb = object ('s) inherit ['a, 's] b end type bt = 'b ca cb as 'b ;; class c = object method m = 1 end;; let f () = object (self:c) method m = 1 end;; let f () = object (self:c) method private n = 1 method m = self#n end;; let f () = object method private n = 1 method m = {<>}#n end;; let f () = object (self:c) method n = 1 method m = 2 end;; let f () = object (_:'s) constraint 's = < n : int > method m = 1 end;; class c = object (_ : 's) method x = 1 method private m = object (self: 's) method x = 3 method private m = self end end;; let o = object (_ : 's) method x = 1 method private m = object (self: 's) method x = 3 method private m = self end end;; fun (x : <m : 'a. 'a * <m: 'b. 'a * 'foo> > as 'foo) -> (x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);; type 'a foo = <m: 'b. 'a * 'a foo> type foo' = <m: 'a. 'a * 'a foo> type 'a bar = <m: 'b. 'a * <m: 'c. 'c * 'a bar> > type bar' = <m: 'a. 'a * 'a bar > let f (x : foo') = (x : bar');; fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) -> (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);; fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) -> (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('b * 'bar)>)> as 'bar);; fun (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) -> (x : <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>);; let f x = (x : <m : 'a. 'a -> ('a * <m:'c. 'c -> 'bar> as 'bar)> :> <m : 'a. 'a -> ('a * 'foo)> as 'foo);; module M : sig val f : (<m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>) -> unit end = struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;; module M : sig type t = <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)> end = struct type t = <m : 'a. 'a * ('a * 'foo)> as 'foo end;; module M : sig type 'a t type u = <m: 'a. 'a t> end = struct type 'a t = int type u = <m: int> end;; module M : sig type 'a t val f : <m: 'a. 'a t> -> int end = struct type 'a t = int let f (x : <m:int>) = x#m end;; module M : sig type 'a t val f : <m: 'a. 'a t> -> int end = struct type 'a t = int let f x = x#m end;; let f x y = ignore (x :> <m:'a.'a -> 'c * < > > as 'c); ignore (y :> <m:'b.'b -> 'd * < > > as 'd); x = y;; type t = [`A|`B];; type v = private [> t];; fun x -> (x : t :> v);; type u = private [< t];; fun x -> (x : u :> v);; fun x -> (x : v :> u);; type v = private [< t];; fun x -> (x : u :> v);; type p = <x:p>;; type q = private <x:p; ..>;; fun x -> (x : q :> p);; fun x -> (x : p :> q);; let f1 x = (x : <m:'a. (<p:int;..> as 'a) -> int> :> <m:'b. (<p:int;q:int;..> as 'b) -> int>);; let f2 x = (x : <m:'a. (<p:<a:int>;..> as 'a) -> int> :> <m:'b. (<p:<a:int;b:int>;..> as 'b) -> int>);; let f3 x = (x : <m:'a. (<p:<a:int;b:int>;..> as 'a) -> int> :> <m:'b. (<p:<a:int>;..> as 'b) -> int>);; let f4 x = (x : <p:<a:int;b:int>;..> :> <p:<a:int>;..>);; let f5 x = (x : <m:'a. [< `A of <p:int> ] as 'a> :> <m:'a. [< `A of < > ] as 'a>);; let f6 x = (x : <m:'a. [< `A of < > ] as 'a> :> <m:'a. [< `A of <p:int> ] as 'a>);; class c = object method id : 'a. 'a -> 'a = fun x -> x end;; type u = c option;; let just = function None -> failwith "just" | Some x -> x;; let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;; let g x = let none = match None with y -> ignore [y;(None:u)]; y in let x = List.hd [Some x; none] in (just x)#id;; let h x = let none = let y = None in ignore [y;(None:u)]; y in let x = List.hd [Some x; none] in (just x)#id;; let rec f : 'a. 'a -> _ = fun x -> 1 and g x = f x;; type 'a t = Leaf of 'a | Node of ('a * 'a) t;; let rec depth : 'a. 'a t -> _ = function Leaf _ -> 1 | Node x -> 1 + depth x;; let rec depth : 'a. 'a t -> _ = function Leaf _ -> 1 | Node x -> 1 + d x let rec depth : 'a. 'a t -> _ = let rec depth : 'a. 'a t -> _ = let rec depth : 'a 'b. 'a t -> 'b = let rec r : 'a. 'a list * 'b list ref = [], ref [] and q () = r;; let f : 'a. _ -> _ = fun x -> x;; type t = {f: 'a. [> `Int of int | `B of 'a] as 'a} let zero = {f = `Int 0} ;; type t = {f: 'a. [< `Int of int] as 'a} let rec id : 'a. 'a -> 'a = fun x -> x and neg i b = (id (-i), id (not b));; type t = A of int | B of (int*t) list | C of (string*t) list let rec transf f = function | A x -> f x | B l -> B (transf_alist f l) | C l -> C (transf_alist f l) and transf_alist : 'a. _ -> ('a*t) list -> ('a*t) list = fun f -> function | [] -> [] | (k,v)::tl -> (k, transf f v) :: transf_alist f tl ;; type t = {f: 'a. ('a list -> int) Lazy.t} let l : t = { f = lazy (raise Not_found)};; type t = {f: 'a. 'a -> unit};; {f=fun ?x y -> ()};;
eb5def9610f2b8be3c11e97b5d7a5a13e383742c69b4c2317f67ebf805e4292b
softwarelanguageslab/maf
R5RS_WeiChenRompf2019_the-little-schemer_ch6-2.scm
; Changes: * removed : 0 * added : 1 * swaps : 0 * negated predicates : 1 ; * swapped branches: 0 ; * calls to id fun: 0 (letrec ((atom? (lambda (x) (if (not (pair? x)) (not (null? x)) #f))) (numbered? (lambda (aexp) (<change> () aexp) (if (atom? aexp) (number? aexp) (if (numbered? (car aexp)) (numbered? (car (cdr (cdr aexp)))) #f)))) (^ (lambda (n m) (if (<change> (zero? m) (not (zero? m))) 1 (* n (^ n (- m 1)))))) (value (lambda (nexp) (if (atom? nexp) nexp (if (eq? (car (cdr nexp)) '+) (+ (value (car nexp)) (value (car (cdr (cdr nexp))))) (if (eq? (car (cdr nexp)) '*) (* (value (car nexp)) (value (car (cdr (cdr nexp))))) (^ (value (car nexp)) (value (car (cdr (cdr nexp))))))))))) (value (__toplevel_cons (__toplevel_cons 5 (__toplevel_cons '^ (__toplevel_cons 1 ()))) (__toplevel_cons '* (__toplevel_cons (__toplevel_cons 3 (__toplevel_cons '+ (__toplevel_cons 3 ()))) ())))))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_WeiChenRompf2019_the-little-schemer_ch6-2.scm
scheme
Changes: * swapped branches: 0 * calls to id fun: 0
* removed : 0 * added : 1 * swaps : 0 * negated predicates : 1 (letrec ((atom? (lambda (x) (if (not (pair? x)) (not (null? x)) #f))) (numbered? (lambda (aexp) (<change> () aexp) (if (atom? aexp) (number? aexp) (if (numbered? (car aexp)) (numbered? (car (cdr (cdr aexp)))) #f)))) (^ (lambda (n m) (if (<change> (zero? m) (not (zero? m))) 1 (* n (^ n (- m 1)))))) (value (lambda (nexp) (if (atom? nexp) nexp (if (eq? (car (cdr nexp)) '+) (+ (value (car nexp)) (value (car (cdr (cdr nexp))))) (if (eq? (car (cdr nexp)) '*) (* (value (car nexp)) (value (car (cdr (cdr nexp))))) (^ (value (car nexp)) (value (car (cdr (cdr nexp))))))))))) (value (__toplevel_cons (__toplevel_cons 5 (__toplevel_cons '^ (__toplevel_cons 1 ()))) (__toplevel_cons '* (__toplevel_cons (__toplevel_cons 3 (__toplevel_cons '+ (__toplevel_cons 3 ()))) ())))))
26b7247fbfa14c39b242b5546623cad7b0516f61b23a8a02db821e872fc6f2fc
biocaml/phylogenetics
test_felsenstein.ml
* Tests of the felsenstein implementation . The results are compared to bppml to check correctness . A variety of models and problem sizes are used to generate trees and alignments which are submitted to our felsenstein implementation and bppml . to check correctness. A variety of models and problem sizes are used to generate trees and alignments which are submitted to our felsenstein implementation and bppml.*) open Phylogenetics open Core type 'a model = (module Site_evolution_model.Nucleotide_S_with_reduction with type param = 'a) type test_case = Test_case : { model : 'a model ; param : 'a ; bpp_spec : Bppsuite.model ; } -> test_case * { 6 Preliminary functions } * Generates a random tree , a random sequence ( using the provided model ) , runs both and , and checks that the results are identical runs both biocaml felsenstein and bppml, and checks that the results are identical*) let test_felsenstein ?(treesize=5) ?(seqsize=5) (Test_case c) () = let module M = (val c.model) in let module Align = Alignment.Make(Seq.DNA) in let module F = Felsenstein.Make(Nucleotide)(Align)(M) in let module SG = Sequence_generation.Make(Nucleotide)(Seq.DNA)(Align)(M) in let tree = Phylogenetic_tree.make_random treesize in let align = SG.seqgen_string_list c.param tree seqsize |> Align.of_string_list in let my_result = F.felsenstein c.param tree align in let bpp_result = begin TODO unique file name Align.to_file align "tmp.seq" ; try Test_utils.felsenstein_bpp ~model:c.bpp_spec ~tree:("tmp.tree") "tmp.seq" with | Failure s -> Printf.printf "\027[0;31mERROR\027[0;0m(felsenstein_bpp): %s\n" s; 0.0 end in Test_utils.check_likelihood my_result bpp_result * { 6 Test list } let models = Site_evolution_model.[ Test_case { model = (module JC69) ; param = () ; bpp_spec = JC69 } ; Test_case { model = (module K80) ; param = 2. ; bpp_spec = K80 { kappa = Some 2. } } ; Test_case { model = (module K80) ; param = 0.5 ; bpp_spec = K80 { kappa = Some 0.5 } } ; Test_case { model = (module JC69_numerical) ; param = () ; bpp_spec = JC69 } ; Test_case { model = (module K80_numerical) ; param = 4. ; bpp_spec = K80 { kappa = Some 4. } } ; ] let tree_sizes = [10 ; 250] let seq_sizes = [1 ; 100 ] let tests = List.cartesian_product tree_sizes seq_sizes |> List.cartesian_product models |> List.map ~f:(fun ((Test_case tc as test_case), (treesize, seqsize)) -> (Printf.sprintf "test against bppml\t%s\ttreesize=%d\tseqsize=%d" (Bppsuite.string_of_model tc.bpp_spec) treesize seqsize, `Slow, test_felsenstein ~treesize ~seqsize test_case) )
null
https://raw.githubusercontent.com/biocaml/phylogenetics/e225616a700b03c429c16f760dbe8c363fb4c79d/tests/test_felsenstein.ml
ocaml
* Tests of the felsenstein implementation . The results are compared to bppml to check correctness . A variety of models and problem sizes are used to generate trees and alignments which are submitted to our felsenstein implementation and bppml . to check correctness. A variety of models and problem sizes are used to generate trees and alignments which are submitted to our felsenstein implementation and bppml.*) open Phylogenetics open Core type 'a model = (module Site_evolution_model.Nucleotide_S_with_reduction with type param = 'a) type test_case = Test_case : { model : 'a model ; param : 'a ; bpp_spec : Bppsuite.model ; } -> test_case * { 6 Preliminary functions } * Generates a random tree , a random sequence ( using the provided model ) , runs both and , and checks that the results are identical runs both biocaml felsenstein and bppml, and checks that the results are identical*) let test_felsenstein ?(treesize=5) ?(seqsize=5) (Test_case c) () = let module M = (val c.model) in let module Align = Alignment.Make(Seq.DNA) in let module F = Felsenstein.Make(Nucleotide)(Align)(M) in let module SG = Sequence_generation.Make(Nucleotide)(Seq.DNA)(Align)(M) in let tree = Phylogenetic_tree.make_random treesize in let align = SG.seqgen_string_list c.param tree seqsize |> Align.of_string_list in let my_result = F.felsenstein c.param tree align in let bpp_result = begin TODO unique file name Align.to_file align "tmp.seq" ; try Test_utils.felsenstein_bpp ~model:c.bpp_spec ~tree:("tmp.tree") "tmp.seq" with | Failure s -> Printf.printf "\027[0;31mERROR\027[0;0m(felsenstein_bpp): %s\n" s; 0.0 end in Test_utils.check_likelihood my_result bpp_result * { 6 Test list } let models = Site_evolution_model.[ Test_case { model = (module JC69) ; param = () ; bpp_spec = JC69 } ; Test_case { model = (module K80) ; param = 2. ; bpp_spec = K80 { kappa = Some 2. } } ; Test_case { model = (module K80) ; param = 0.5 ; bpp_spec = K80 { kappa = Some 0.5 } } ; Test_case { model = (module JC69_numerical) ; param = () ; bpp_spec = JC69 } ; Test_case { model = (module K80_numerical) ; param = 4. ; bpp_spec = K80 { kappa = Some 4. } } ; ] let tree_sizes = [10 ; 250] let seq_sizes = [1 ; 100 ] let tests = List.cartesian_product tree_sizes seq_sizes |> List.cartesian_product models |> List.map ~f:(fun ((Test_case tc as test_case), (treesize, seqsize)) -> (Printf.sprintf "test against bppml\t%s\ttreesize=%d\tseqsize=%d" (Bppsuite.string_of_model tc.bpp_spec) treesize seqsize, `Slow, test_felsenstein ~treesize ~seqsize test_case) )
efa6351845cd5ffb6ada31598e109b20b714a9356a8864313999c7c82e24d982
VERIMAG-Polyhedra/VPL
FMapAVL.ml
open Datatypes open FMapList open Nat0 type __ = Obj.t let __ = let rec f _ = Obj.repr f in Obj.repr f module Raw = functor (I:Int.Int) -> functor (X:OrderedType.OrderedType) -> struct type key = X.t type 'elt tree = | Leaf | Node of 'elt tree * key * 'elt * 'elt tree * I.t (** val tree_rect : 'a2 -> ('a1 tree -> 'a2 -> key -> 'a1 -> 'a1 tree -> 'a2 -> I.t -> 'a2) -> 'a1 tree -> 'a2 **) let rec tree_rect f f0 = function | Leaf -> f | Node (t1, k, e, t2, t3) -> f0 t1 (tree_rect f f0 t1) k e t2 (tree_rect f f0 t2) t3 * tree_rec : ' a2 - > ( ' a1 tree - > ' a2 - > key - > ' a1 - > ' a1 tree - > ' a2 - > I.t - > ' a2 ) - > ' a1 tree - > ' a2 * 'a2 -> ('a1 tree -> 'a2 -> key -> 'a1 -> 'a1 tree -> 'a2 -> I.t -> 'a2) -> 'a1 tree -> 'a2 **) let rec tree_rec f f0 = function | Leaf -> f | Node (t1, k, e, t2, t3) -> f0 t1 (tree_rec f f0 t1) k e t2 (tree_rec f f0 t2) t3 (** val height : 'a1 tree -> I.t **) let height = function | Leaf -> I._0 | Node (_, _, _, _, h) -> h * cardinal : ' a1 tree - > nat * let rec cardinal = function | Leaf -> O | Node (l, _, _, r, _) -> S (add (cardinal l) (cardinal r)) (** val empty : 'a1 tree **) let empty = Leaf (** val is_empty : 'a1 tree -> bool **) let is_empty = function | Leaf -> true | Node (_, _, _, _, _) -> false * : X.t - > ' a1 tree - > bool * let rec mem x = function | Leaf -> false | Node (l, y, _, r, _) -> (match X.compare x y with | OrderedType.LT -> mem x l | OrderedType.EQ -> true | OrderedType.GT -> mem x r) * find : X.t - > ' a1 tree - > ' a1 option * let rec find x = function | Leaf -> None | Node (l, y, d, r, _) -> (match X.compare x y with | OrderedType.LT -> find x l | OrderedType.EQ -> Some d | OrderedType.GT -> find x r) (** val create : 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree **) let create l x e r = Node (l, x, e, r, (I.add (I.max (height l) (height r)) I._1)) (** val assert_false : 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree **) let assert_false = create * : ' a1 tree - > key - > ' a1 - > ' a1 tree - > ' a1 tree * let bal l x d r = let hl = height l in let hr = height r in if I.gt_le_dec hl (I.add hr I._2) then (match l with | Leaf -> assert_false l x d r | Node (ll, lx, ld, lr, _) -> if I.ge_lt_dec (height ll) (height lr) then create ll lx ld (create lr x d r) else (match lr with | Leaf -> assert_false l x d r | Node (lrl, lrx, lrd, lrr, _) -> create (create ll lx ld lrl) lrx lrd (create lrr x d r))) else if I.gt_le_dec hr (I.add hl I._2) then (match r with | Leaf -> assert_false l x d r | Node (rl, rx, rd, rr, _) -> if I.ge_lt_dec (height rr) (height rl) then create (create l x d rl) rx rd rr else (match rl with | Leaf -> assert_false l x d r | Node (rll, rlx, rld, rlr, _) -> create (create l x d rll) rlx rld (create rlr rx rd rr))) else create l x d r * add : key - > ' a1 - > ' a1 tree - > ' a1 tree * let rec add x d = function | Leaf -> Node (Leaf, x, d, Leaf, I._1) | Node (l, y, d', r, h) -> (match X.compare x y with | OrderedType.LT -> bal (add x d l) y d' r | OrderedType.EQ -> Node (l, y, d, r, h) | OrderedType.GT -> bal l y d' (add x d r)) * remove_min : ' a1 tree - > key - > ' a1 - > ' a1 tree - > ' a1 tree*(key*'a1 ) * 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree*(key*'a1) **) let rec remove_min l x d r = match l with | Leaf -> r,(x,d) | Node (ll, lx, ld, lr, _) -> let l',m = remove_min ll lx ld lr in (bal l' x d r),m * merge : ' a1 tree - > ' a1 tree - > ' a1 tree * let merge s1 s2 = match s1 with | Leaf -> s2 | Node (_, _, _, _, _) -> (match s2 with | Leaf -> s1 | Node (l2, x2, d2, r2, _) -> let s2',p = remove_min l2 x2 d2 r2 in let x,d = p in bal s1 x d s2') * remove : X.t - > ' a1 tree - > ' a1 tree * let rec remove x = function | Leaf -> Leaf | Node (l, y, d, r, _) -> (match X.compare x y with | OrderedType.LT -> bal (remove x l) y d r | OrderedType.EQ -> merge l r | OrderedType.GT -> bal l y d (remove x r)) * join : ' a1 tree - > key - > ' a1 - > ' a1 tree - > ' a1 tree * let rec join l = match l with | Leaf -> add | Node (ll, lx, ld, lr, lh) -> (fun x d -> let rec join_aux r = match r with | Leaf -> add x d l | Node (rl, rx, rd, rr, rh) -> if I.gt_le_dec lh (I.add rh I._2) then bal ll lx ld (join lr x d r) else if I.gt_le_dec rh (I.add lh I._2) then bal (join_aux rl) rx rd rr else create l x d r in join_aux) type 'elt triple = { t_left : 'elt tree; t_opt : 'elt option; t_right : 'elt tree } (** val t_left : 'a1 triple -> 'a1 tree **) let t_left t0 = t0.t_left * : ' a1 triple - > ' a1 option * let t_opt t0 = t0.t_opt * val : ' a1 triple - > ' a1 tree * let t_right t0 = t0.t_right (** val split : X.t -> 'a1 tree -> 'a1 triple **) let rec split x = function | Leaf -> { t_left = Leaf; t_opt = None; t_right = Leaf } | Node (l, y, d, r, _) -> (match X.compare x y with | OrderedType.LT -> let { t_left = ll; t_opt = o; t_right = rl } = split x l in { t_left = ll; t_opt = o; t_right = (join rl y d r) } | OrderedType.EQ -> { t_left = l; t_opt = (Some d); t_right = r } | OrderedType.GT -> let { t_left = rl; t_opt = o; t_right = rr } = split x r in { t_left = (join l y d rl); t_opt = o; t_right = rr }) (** val concat : 'a1 tree -> 'a1 tree -> 'a1 tree **) let concat m1 m2 = match m1 with | Leaf -> m2 | Node (_, _, _, _, _) -> (match m2 with | Leaf -> m1 | Node (l2, x2, d2, r2, _) -> let m2',xd = remove_min l2 x2 d2 r2 in join m1 (fst xd) (snd xd) m2') (** val elements_aux : (key*'a1) list -> 'a1 tree -> (key*'a1) list **) let rec elements_aux acc = function | Leaf -> acc | Node (l, x, d, r, _) -> elements_aux ((x,d)::(elements_aux acc r)) l (** val elements : 'a1 tree -> (key*'a1) list **) let elements m = elements_aux [] m (** val fold : (key -> 'a1 -> 'a2 -> 'a2) -> 'a1 tree -> 'a2 -> 'a2 **) let rec fold f m a = match m with | Leaf -> a | Node (l, x, d, r, _) -> fold f r (f x d (fold f l a)) type 'elt enumeration = | End | More of key * 'elt * 'elt tree * 'elt enumeration (** val enumeration_rect : 'a2 -> (key -> 'a1 -> 'a1 tree -> 'a1 enumeration -> 'a2 -> 'a2) -> 'a1 enumeration -> 'a2 **) let rec enumeration_rect f f0 = function | End -> f | More (k, e0, t0, e1) -> f0 k e0 t0 e1 (enumeration_rect f f0 e1) * : ' a2 - > ( key - > ' a1 - > ' a1 tree - > ' a1 enumeration - > ' a2 - > ' a2 ) - > ' a1 enumeration - > ' a2 * 'a2 -> (key -> 'a1 -> 'a1 tree -> 'a1 enumeration -> 'a2 -> 'a2) -> 'a1 enumeration -> 'a2 **) let rec enumeration_rec f f0 = function | End -> f | More (k, e0, t0, e1) -> f0 k e0 t0 e1 (enumeration_rec f f0 e1) (** val cons : 'a1 tree -> 'a1 enumeration -> 'a1 enumeration **) let rec cons m e = match m with | Leaf -> e | Node (l, x, d, r, _) -> cons l (More (x, d, r, e)) (** val equal_more : ('a1 -> 'a1 -> bool) -> X.t -> 'a1 -> ('a1 enumeration -> bool) -> 'a1 enumeration -> bool **) let equal_more cmp x1 d1 cont = function | End -> false | More (x2, d2, r2, e3) -> (match X.compare x1 x2 with | OrderedType.EQ -> if cmp d1 d2 then cont (cons r2 e3) else false | _ -> false) (** val equal_cont : ('a1 -> 'a1 -> bool) -> 'a1 tree -> ('a1 enumeration -> bool) -> 'a1 enumeration -> bool **) let rec equal_cont cmp m1 cont e2 = match m1 with | Leaf -> cont e2 | Node (l1, x1, d1, r1, _) -> equal_cont cmp l1 (equal_more cmp x1 d1 (equal_cont cmp r1 cont)) e2 * equal_end : ' a1 enumeration - > bool * let equal_end = function | End -> true | More (_, _, _, _) -> false (** val equal : ('a1 -> 'a1 -> bool) -> 'a1 tree -> 'a1 tree -> bool **) let equal cmp m1 m2 = equal_cont cmp m1 equal_end (cons m2 End) (** val map : ('a1 -> 'a2) -> 'a1 tree -> 'a2 tree **) let rec map f = function | Leaf -> Leaf | Node (l, x, d, r, h) -> Node ((map f l), x, (f d), (map f r), h) * : ( key - > ' a1 - > ' a2 ) - > ' a1 tree - > ' a2 tree * let rec mapi f = function | Leaf -> Leaf | Node (l, x, d, r, h) -> Node ((mapi f l), x, (f x d), (mapi f r), h) (** val map_option : (key -> 'a1 -> 'a2 option) -> 'a1 tree -> 'a2 tree **) let rec map_option f = function | Leaf -> Leaf | Node (l, x, d, r, _) -> (match f x d with | Some d' -> join (map_option f l) x d' (map_option f r) | None -> concat (map_option f l) (map_option f r)) * : ( key - > ' a1 - > ' a2 option - > ' a3 option ) - > ( ' a1 tree - > ' a3 tree ) - > ( ' a2 tree - > ' a3 tree ) - > ' a1 tree - > ' a2 tree - > ' a3 tree * (key -> 'a1 -> 'a2 option -> 'a3 option) -> ('a1 tree -> 'a3 tree) -> ('a2 tree -> 'a3 tree) -> 'a1 tree -> 'a2 tree -> 'a3 tree **) let rec map2_opt f mapl mapr m1 m2 = match m1 with | Leaf -> mapr m2 | Node (l1, x1, d1, r1, _) -> (match m2 with | Leaf -> mapl m1 | Node (_, _, _, _, _) -> let { t_left = l2'; t_opt = o2; t_right = r2' } = split x1 m2 in (match f x1 d1 o2 with | Some e -> join (map2_opt f mapl mapr l1 l2') x1 e (map2_opt f mapl mapr r1 r2') | None -> concat (map2_opt f mapl mapr l1 l2') (map2_opt f mapl mapr r1 r2'))) * val map2 : ( ' a1 option - > ' a2 option - > ' a3 option ) - > ' a1 tree - > ' a2 tree - > ' a3 tree * ('a1 option -> 'a2 option -> 'a3 option) -> 'a1 tree -> 'a2 tree -> 'a3 tree **) let map2 f = map2_opt (fun _ d o -> f (Some d) o) (map_option (fun _ d -> f (Some d) None)) (map_option (fun _ d' -> f None (Some d'))) module Proofs = struct module MX = OrderedType.OrderedTypeFacts(X) module PX = OrderedType.KeyOrderedType(X) module L = Raw(X) type 'elt coq_R_mem = | R_mem_0 of 'elt tree | R_mem_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * bool * 'elt coq_R_mem | R_mem_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_mem_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * bool * 'elt coq_R_mem * : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ' a1 tree - > bool - > ' a1 coq_R_mem - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> 'a1 tree -> bool -> 'a1 coq_R_mem -> 'a2 **) let rec coq_R_mem_rect x f f0 f1 f2 _ _ = function | R_mem_0 m -> f m __ | R_mem_1 (m, l, y, _x, r0, _x0, _res, r1) -> f0 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rect x f f0 f1 f2 l _res r1) | R_mem_2 (m, l, y, _x, r0, _x0) -> f1 m l y _x r0 _x0 __ __ __ | R_mem_3 (m, l, y, _x, r0, _x0, _res, r1) -> f2 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rect x f f0 f1 f2 r0 _res r1) * coq_R_mem_rec : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ' a1 tree - > bool - > ' a1 coq_R_mem - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> 'a1 tree -> bool -> 'a1 coq_R_mem -> 'a2 **) let rec coq_R_mem_rec x f f0 f1 f2 _ _ = function | R_mem_0 m -> f m __ | R_mem_1 (m, l, y, _x, r0, _x0, _res, r1) -> f0 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rec x f f0 f1 f2 l _res r1) | R_mem_2 (m, l, y, _x, r0, _x0) -> f1 m l y _x r0 _x0 __ __ __ | R_mem_3 (m, l, y, _x, r0, _x0, _res, r1) -> f2 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rec x f f0 f1 f2 r0 _res r1) type 'elt coq_R_find = | R_find_0 of 'elt tree | R_find_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt option * 'elt coq_R_find | R_find_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_find_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt option * 'elt coq_R_find (** val coq_R_find_rect : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 option -> 'a1 coq_R_find -> 'a2 **) let rec coq_R_find_rect x f f0 f1 f2 _ _ = function | R_find_0 m -> f m __ | R_find_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rect x f f0 f1 f2 l _res r1) | R_find_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_find_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rect x f f0 f1 f2 r0 _res r1) * coq_R_find_rec : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 option - > ' a1 coq_R_find - > ' a2 - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 option - > ' a1 coq_R_find - > ' a2 - > ' a2 ) - > ' a1 tree - > ' a1 option - > ' a1 coq_R_find - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 option -> 'a1 coq_R_find -> 'a2 **) let rec coq_R_find_rec x f f0 f1 f2 _ _ = function | R_find_0 m -> f m __ | R_find_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rec x f f0 f1 f2 l _res r1) | R_find_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_find_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rec x f f0 f1 f2 r0 _res r1) type 'elt coq_R_bal = | R_bal_0 of 'elt tree * key * 'elt * 'elt tree | R_bal_1 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_2 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_3 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_4 of 'elt tree * key * 'elt * 'elt tree | R_bal_5 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_6 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_7 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_8 of 'elt tree * key * 'elt * 'elt tree (** val coq_R_bal_rect : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_bal -> 'a2 **) let coq_R_bal_rect f f0 f1 f2 f3 f4 f5 f6 f7 _ _ _ _ _ = function | R_bal_0 (x, x0, x1, x2) -> f x x0 x1 x2 __ __ __ | R_bal_1 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f0 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_2 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f1 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_3 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f2 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_4 (x, x0, x1, x2) -> f3 x x0 x1 x2 __ __ __ __ __ | R_bal_5 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f4 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_6 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f5 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_7 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f6 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_8 (x, x0, x1, x2) -> f7 x x0 x1 x2 __ __ __ __ (** val coq_R_bal_rec : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_bal -> 'a2 **) let coq_R_bal_rec f f0 f1 f2 f3 f4 f5 f6 f7 _ _ _ _ _ = function | R_bal_0 (x, x0, x1, x2) -> f x x0 x1 x2 __ __ __ | R_bal_1 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f0 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_2 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f1 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_3 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f2 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_4 (x, x0, x1, x2) -> f3 x x0 x1 x2 __ __ __ __ __ | R_bal_5 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f4 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_6 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f5 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_7 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f6 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_8 (x, x0, x1, x2) -> f7 x x0 x1 x2 __ __ __ __ type 'elt coq_R_add = | R_add_0 of 'elt tree | R_add_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_add | R_add_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_add_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_add (** val coq_R_add_rect : key -> 'a1 -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_add -> 'a2 **) let rec coq_R_add_rect x d f f0 f1 f2 _ _ = function | R_add_0 m -> f m __ | R_add_1 (m, l, y, d', r0, h, _res, r1) -> f0 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rect x d f f0 f1 f2 l _res r1) | R_add_2 (m, l, y, d', r0, h) -> f1 m l y d' r0 h __ __ __ | R_add_3 (m, l, y, d', r0, h, _res, r1) -> f2 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rect x d f f0 f1 f2 r0 _res r1) (** val coq_R_add_rec : key -> 'a1 -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_add -> 'a2 **) let rec coq_R_add_rec x d f f0 f1 f2 _ _ = function | R_add_0 m -> f m __ | R_add_1 (m, l, y, d', r0, h, _res, r1) -> f0 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rec x d f f0 f1 f2 l _res r1) | R_add_2 (m, l, y, d', r0, h) -> f1 m l y d' r0 h __ __ __ | R_add_3 (m, l, y, d', r0, h, _res, r1) -> f2 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rec x d f f0 f1 f2 r0 _res r1) type 'elt coq_R_remove_min = | R_remove_min_0 of 'elt tree * key * 'elt * 'elt tree | R_remove_min_1 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * ('elt tree*(key*'elt)) * 'elt coq_R_remove_min * 'elt tree * (key*'elt) (** val coq_R_remove_min_rect : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 **) let rec coq_R_remove_min_rect f f0 _ _ _ _ _ = function | R_remove_min_0 (l, x, d, r0) -> f l x d r0 __ | R_remove_min_1 (l, x, d, r0, ll, lx, ld, lr, _x, _res, r1, l', m) -> f0 l x d r0 ll lx ld lr _x __ _res r1 (coq_R_remove_min_rect f f0 ll lx ld lr _res r1) l' m __ (** val coq_R_remove_min_rec : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 **) let rec coq_R_remove_min_rec f f0 _ _ _ _ _ = function | R_remove_min_0 (l, x, d, r0) -> f l x d r0 __ | R_remove_min_1 (l, x, d, r0, ll, lx, ld, lr, _x, _res, r1, l', m) -> f0 l x d r0 ll lx ld lr _x __ _res r1 (coq_R_remove_min_rec f f0 ll lx ld lr _res r1) l' m __ type 'elt coq_R_merge = | R_merge_0 of 'elt tree * 'elt tree | R_merge_1 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_merge_2 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * (key*'elt) * key * 'elt * val coq_R_merge_rect : ( ' a1 tree - > ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > ( key*'a1 ) - > _ _ - > key - > ' a1 - > _ _ - > ' a2 ) - > ' a1 tree - > ' a1 tree - > ' a1 tree - > ' a2 * ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> key -> 'a1 -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_merge -> 'a2 **) let coq_R_merge_rect f f0 f1 _ _ _ = function | R_merge_0 (x, x0) -> f x x0 __ | R_merge_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_merge_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ x13 x14 __ * val coq_R_merge_rec : ( ' a1 tree - > ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > ( key*'a1 ) - > _ _ - > key - > ' a1 - > _ _ - > ' a2 ) - > ' a1 tree - > ' a1 tree - > ' a1 tree - > ' a2 * ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> key -> 'a1 -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_merge -> 'a2 **) let coq_R_merge_rec f f0 f1 _ _ _ = function | R_merge_0 (x, x0) -> f x x0 __ | R_merge_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_merge_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ x13 x14 __ type 'elt coq_R_remove = | R_remove_0 of 'elt tree | R_remove_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_remove | R_remove_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_remove_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_remove (** val coq_R_remove_rect : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 **) let rec coq_R_remove_rect x f f0 f1 f2 _ _ = function | R_remove_0 m -> f m __ | R_remove_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rect x f f0 f1 f2 l _res r1) | R_remove_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_remove_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rect x f f0 f1 f2 r0 _res r1) (** val coq_R_remove_rec : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 **) let rec coq_R_remove_rec x f f0 f1 f2 _ _ = function | R_remove_0 m -> f m __ | R_remove_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rec x f f0 f1 f2 l _res r1) | R_remove_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_remove_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rec x f f0 f1 f2 r0 _res r1) type 'elt coq_R_concat = | R_concat_0 of 'elt tree * 'elt tree | R_concat_1 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_concat_2 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * (key*'elt) (** val coq_R_concat_rect : ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_concat -> 'a2 **) let coq_R_concat_rect f f0 f1 _ _ _ = function | R_concat_0 (x, x0) -> f x x0 __ | R_concat_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_concat_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ (** val coq_R_concat_rec : ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_concat -> 'a2 **) let coq_R_concat_rec f f0 f1 _ _ _ = function | R_concat_0 (x, x0) -> f x x0 __ | R_concat_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_concat_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ type 'elt coq_R_split = | R_split_0 of 'elt tree | R_split_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt triple * 'elt coq_R_split * 'elt tree * 'elt option * 'elt tree | R_split_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_split_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt triple * 'elt coq_R_split * 'elt tree * 'elt option * 'elt tree (** val coq_R_split_rect : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> 'a1 tree -> 'a1 triple -> 'a1 coq_R_split -> 'a2 **) let rec coq_R_split_rect x f f0 f1 f2 _ _ = function | R_split_0 m -> f m __ | R_split_1 (m, l, y, d, r0, _x, _res, r1, ll, o, rl) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rect x f f0 f1 f2 l _res r1) ll o rl __ | R_split_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_split_3 (m, l, y, d, r0, _x, _res, r1, rl, o, rr) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rect x f f0 f1 f2 r0 _res r1) rl o rr __ * : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 triple - > ' a1 coq_R_split - > ' a2 - > ' a1 tree - > ' a1 option - > ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 triple - > ' a1 coq_R_split - > ' a2 - > ' a1 tree - > ' a1 option - > ' a1 tree - > _ _ - > ' a2 ) - > ' a1 tree - > ' a1 triple - > ' a1 coq_R_split - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> 'a1 tree -> 'a1 triple -> 'a1 coq_R_split -> 'a2 **) let rec coq_R_split_rec x f f0 f1 f2 _ _ = function | R_split_0 m -> f m __ | R_split_1 (m, l, y, d, r0, _x, _res, r1, ll, o, rl) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rec x f f0 f1 f2 l _res r1) ll o rl __ | R_split_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_split_3 (m, l, y, d, r0, _x, _res, r1, rl, o, rr) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rec x f f0 f1 f2 r0 _res r1) rl o rr __ type ('elt, 'x) coq_R_map_option = | R_map_option_0 of 'elt tree | R_map_option_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x * 'x tree * ('elt, 'x) coq_R_map_option * 'x tree * ('elt, 'x) coq_R_map_option | R_map_option_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x tree * ('elt, 'x) coq_R_map_option * 'x tree * ('elt, 'x) coq_R_map_option (** val coq_R_map_option_rect : (key -> 'a1 -> 'a2 option) -> ('a1 tree -> __ -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> 'a1 tree -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 **) let rec coq_R_map_option_rect f f0 f1 f2 _ _ = function | R_map_option_0 m -> f0 m __ | R_map_option_1 (m, l, x, d, r0, _x, d', _res0, r1, _res, r2) -> f1 m l x d r0 _x __ d' __ _res0 r1 (coq_R_map_option_rect f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rect f f0 f1 f2 r0 _res r2) | R_map_option_2 (m, l, x, d, r0, _x, _res0, r1, _res, r2) -> f2 m l x d r0 _x __ __ _res0 r1 (coq_R_map_option_rect f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rect f f0 f1 f2 r0 _res r2) * : ( key - > ' a1 - > ' a2 option ) - > ( ' a1 tree - > _ _ - > ' a3 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a2 - > _ _ - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a3 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a3 ) - > ' a1 tree - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 * (key -> 'a1 -> 'a2 option) -> ('a1 tree -> __ -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> 'a1 tree -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 **) let rec coq_R_map_option_rec f f0 f1 f2 _ _ = function | R_map_option_0 m -> f0 m __ | R_map_option_1 (m, l, x, d, r0, _x, d', _res0, r1, _res, r2) -> f1 m l x d r0 _x __ d' __ _res0 r1 (coq_R_map_option_rec f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rec f f0 f1 f2 r0 _res r2) | R_map_option_2 (m, l, x, d, r0, _x, _res0, r1, _res, r2) -> f2 m l x d r0 _x __ __ _res0 r1 (coq_R_map_option_rec f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rec f f0 f1 f2 r0 _res r2) type ('elt, 'x0, 'x) coq_R_map2_opt = | R_map2_opt_0 of 'elt tree * 'x0 tree | R_map2_opt_1 of 'elt tree * 'x0 tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_map2_opt_2 of 'elt tree * 'x0 tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x0 tree * key * 'x0 * 'x0 tree * I.t * 'x0 tree * 'x0 option * 'x0 tree * 'x * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt | R_map2_opt_3 of 'elt tree * 'x0 tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x0 tree * key * 'x0 * 'x0 tree * I.t * 'x0 tree * 'x0 option * 'x0 tree * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt (** val coq_R_map2_opt_rect : (key -> 'a1 -> 'a2 option -> 'a3 option) -> ('a1 tree -> 'a3 tree) -> ('a2 tree -> 'a3 tree) -> ('a1 tree -> 'a2 tree -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> 'a3 -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> 'a1 tree -> 'a2 tree -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 **) let rec coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 _ _ _ = function | R_map2_opt_0 (m1, m2) -> f0 m1 m2 __ | R_map2_opt_1 (m1, m2, l1, x1, d1, r1, _x) -> f1 m1 m2 l1 x1 d1 r1 _x __ __ | R_map2_opt_2 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', e, _res0, r0, _res, r2) -> f2 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ e __ _res0 r0 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) | R_map2_opt_3 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', _res0, r0, _res, r2) -> f3 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ __ _res0 r0 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) (** val coq_R_map2_opt_rec : (key -> 'a1 -> 'a2 option -> 'a3 option) -> ('a1 tree -> 'a3 tree) -> ('a2 tree -> 'a3 tree) -> ('a1 tree -> 'a2 tree -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> 'a3 -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> 'a1 tree -> 'a2 tree -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 **) let rec coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 _ _ _ = function | R_map2_opt_0 (m1, m2) -> f0 m1 m2 __ | R_map2_opt_1 (m1, m2, l1, x1, d1, r1, _x) -> f1 m1 m2 l1 x1 d1 r1 _x __ __ | R_map2_opt_2 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', e, _res0, r0, _res, r2) -> f2 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ e __ _res0 r0 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) | R_map2_opt_3 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', _res0, r0, _res, r2) -> f3 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ __ _res0 r0 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) (** val fold' : (key -> 'a1 -> 'a2 -> 'a2) -> 'a1 tree -> 'a2 -> 'a2 **) let fold' f s = L.fold f (elements s) (** val flatten_e : 'a1 enumeration -> (key*'a1) list **) let rec flatten_e = function | End -> [] | More (x, e0, t0, r) -> (x,e0)::(app (elements t0) (flatten_e r)) end end module IntMake = functor (I:Int.Int) -> functor (X:OrderedType.OrderedType) -> struct module E = X module Raw = Raw(I)(X) type 'elt bst = 'elt Raw.tree (* singleton inductive, whose constructor was Bst *) * this : ' a1 Raw.tree * let this b = b type 'elt t = 'elt bst type key = E.t (** val empty : 'a1 t **) let empty = Raw.empty (** val is_empty : 'a1 t -> bool **) let is_empty m = Raw.is_empty (this m) * add : key - > ' a1 - > ' a1 t - > ' a1 t * let add x e m = Raw.add x e (this m) * remove : key - > ' a1 t - > ' a1 t * let remove x m = Raw.remove x (this m) * : key - > ' a1 t - > bool * let mem x m = Raw.mem x (this m) * find : key - > ' a1 t - > ' a1 option * let find x m = Raw.find x (this m) (** val map : ('a1 -> 'a2) -> 'a1 t -> 'a2 t **) let map f m = Raw.map f (this m) * : ( key - > ' a1 - > ' a2 ) - > ' a1 t - > ' a2 t * let mapi f m = Raw.mapi f (this m) * val map2 : ( ' a1 option - > ' a2 option - > ' a3 option ) - > ' a1 t - > ' a2 t - > ' a3 t * ('a1 option -> 'a2 option -> 'a3 option) -> 'a1 t -> 'a2 t -> 'a3 t **) let map2 f m m' = Raw.map2 f (this m) (this m') (** val elements : 'a1 t -> (key*'a1) list **) let elements m = Raw.elements (this m) * cardinal : ' a1 t - > nat * let cardinal m = Raw.cardinal (this m) (** val fold : (key -> 'a1 -> 'a2 -> 'a2) -> 'a1 t -> 'a2 -> 'a2 **) let fold f m i = Raw.fold f (this m) i (** val equal : ('a1 -> 'a1 -> bool) -> 'a1 t -> 'a1 t -> bool **) let equal cmp m m' = Raw.equal cmp (this m) (this m') end module Make = functor (X:OrderedType.OrderedType) -> IntMake(Int.Z_as_Int)(X)
null
https://raw.githubusercontent.com/VERIMAG-Polyhedra/VPL/cd78d6e7d120508fd5a694bdb01300477e5646f8/ocaml/extracted/FMapAVL.ml
ocaml
* val tree_rect : 'a2 -> ('a1 tree -> 'a2 -> key -> 'a1 -> 'a1 tree -> 'a2 -> I.t -> 'a2) -> 'a1 tree -> 'a2 * * val height : 'a1 tree -> I.t * * val empty : 'a1 tree * * val is_empty : 'a1 tree -> bool * * val create : 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree * * val assert_false : 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree * * val t_left : 'a1 triple -> 'a1 tree * * val split : X.t -> 'a1 tree -> 'a1 triple * * val concat : 'a1 tree -> 'a1 tree -> 'a1 tree * * val elements_aux : (key*'a1) list -> 'a1 tree -> (key*'a1) list * * val elements : 'a1 tree -> (key*'a1) list * * val fold : (key -> 'a1 -> 'a2 -> 'a2) -> 'a1 tree -> 'a2 -> 'a2 * * val enumeration_rect : 'a2 -> (key -> 'a1 -> 'a1 tree -> 'a1 enumeration -> 'a2 -> 'a2) -> 'a1 enumeration -> 'a2 * * val cons : 'a1 tree -> 'a1 enumeration -> 'a1 enumeration * * val equal_more : ('a1 -> 'a1 -> bool) -> X.t -> 'a1 -> ('a1 enumeration -> bool) -> 'a1 enumeration -> bool * * val equal_cont : ('a1 -> 'a1 -> bool) -> 'a1 tree -> ('a1 enumeration -> bool) -> 'a1 enumeration -> bool * * val equal : ('a1 -> 'a1 -> bool) -> 'a1 tree -> 'a1 tree -> bool * * val map : ('a1 -> 'a2) -> 'a1 tree -> 'a2 tree * * val map_option : (key -> 'a1 -> 'a2 option) -> 'a1 tree -> 'a2 tree * * val coq_R_find_rect : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 option -> 'a1 coq_R_find -> 'a2 * * val coq_R_bal_rect : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_bal -> 'a2 * * val coq_R_bal_rec : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> __ -> __ -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_bal -> 'a2 * * val coq_R_add_rect : key -> 'a1 -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_add -> 'a2 * * val coq_R_add_rec : key -> 'a1 -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_add -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_add -> 'a2 * * val coq_R_remove_min_rect : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 * * val coq_R_remove_min_rec : ('a1 tree -> key -> 'a1 -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> ('a1 tree*(key*'a1)) -> 'a1 coq_R_remove_min -> 'a2 * * val coq_R_remove_rect : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 * * val coq_R_remove_rec : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_remove -> 'a2 * * val coq_R_concat_rect : ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_concat -> 'a2 * * val coq_R_concat_rec : ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_concat -> 'a2 * * val coq_R_split_rect : X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> 'a1 tree -> 'a1 triple -> 'a1 coq_R_split -> 'a2 * * val coq_R_map_option_rect : (key -> 'a1 -> 'a2 option) -> ('a1 tree -> __ -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> 'a1 tree -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 * * val coq_R_map2_opt_rect : (key -> 'a1 -> 'a2 option -> 'a3 option) -> ('a1 tree -> 'a3 tree) -> ('a2 tree -> 'a3 tree) -> ('a1 tree -> 'a2 tree -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> 'a3 -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> 'a1 tree -> 'a2 tree -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 * * val coq_R_map2_opt_rec : (key -> 'a1 -> 'a2 option -> 'a3 option) -> ('a1 tree -> 'a3 tree) -> ('a2 tree -> 'a3 tree) -> ('a1 tree -> 'a2 tree -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> 'a3 -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> ('a1 tree -> 'a2 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 tree -> key -> 'a2 -> 'a2 tree -> I.t -> __ -> 'a2 tree -> 'a2 option -> 'a2 tree -> __ -> __ -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 -> 'a4) -> 'a1 tree -> 'a2 tree -> 'a3 tree -> ('a1, 'a2, 'a3) coq_R_map2_opt -> 'a4 * * val fold' : (key -> 'a1 -> 'a2 -> 'a2) -> 'a1 tree -> 'a2 -> 'a2 * * val flatten_e : 'a1 enumeration -> (key*'a1) list * singleton inductive, whose constructor was Bst * val empty : 'a1 t * * val is_empty : 'a1 t -> bool * * val map : ('a1 -> 'a2) -> 'a1 t -> 'a2 t * * val elements : 'a1 t -> (key*'a1) list * * val fold : (key -> 'a1 -> 'a2 -> 'a2) -> 'a1 t -> 'a2 -> 'a2 * * val equal : ('a1 -> 'a1 -> bool) -> 'a1 t -> 'a1 t -> bool *
open Datatypes open FMapList open Nat0 type __ = Obj.t let __ = let rec f _ = Obj.repr f in Obj.repr f module Raw = functor (I:Int.Int) -> functor (X:OrderedType.OrderedType) -> struct type key = X.t type 'elt tree = | Leaf | Node of 'elt tree * key * 'elt * 'elt tree * I.t let rec tree_rect f f0 = function | Leaf -> f | Node (t1, k, e, t2, t3) -> f0 t1 (tree_rect f f0 t1) k e t2 (tree_rect f f0 t2) t3 * tree_rec : ' a2 - > ( ' a1 tree - > ' a2 - > key - > ' a1 - > ' a1 tree - > ' a2 - > I.t - > ' a2 ) - > ' a1 tree - > ' a2 * 'a2 -> ('a1 tree -> 'a2 -> key -> 'a1 -> 'a1 tree -> 'a2 -> I.t -> 'a2) -> 'a1 tree -> 'a2 **) let rec tree_rec f f0 = function | Leaf -> f | Node (t1, k, e, t2, t3) -> f0 t1 (tree_rec f f0 t1) k e t2 (tree_rec f f0 t2) t3 let height = function | Leaf -> I._0 | Node (_, _, _, _, h) -> h * cardinal : ' a1 tree - > nat * let rec cardinal = function | Leaf -> O | Node (l, _, _, r, _) -> S (add (cardinal l) (cardinal r)) let empty = Leaf let is_empty = function | Leaf -> true | Node (_, _, _, _, _) -> false * : X.t - > ' a1 tree - > bool * let rec mem x = function | Leaf -> false | Node (l, y, _, r, _) -> (match X.compare x y with | OrderedType.LT -> mem x l | OrderedType.EQ -> true | OrderedType.GT -> mem x r) * find : X.t - > ' a1 tree - > ' a1 option * let rec find x = function | Leaf -> None | Node (l, y, d, r, _) -> (match X.compare x y with | OrderedType.LT -> find x l | OrderedType.EQ -> Some d | OrderedType.GT -> find x r) let create l x e r = Node (l, x, e, r, (I.add (I.max (height l) (height r)) I._1)) let assert_false = create * : ' a1 tree - > key - > ' a1 - > ' a1 tree - > ' a1 tree * let bal l x d r = let hl = height l in let hr = height r in if I.gt_le_dec hl (I.add hr I._2) then (match l with | Leaf -> assert_false l x d r | Node (ll, lx, ld, lr, _) -> if I.ge_lt_dec (height ll) (height lr) then create ll lx ld (create lr x d r) else (match lr with | Leaf -> assert_false l x d r | Node (lrl, lrx, lrd, lrr, _) -> create (create ll lx ld lrl) lrx lrd (create lrr x d r))) else if I.gt_le_dec hr (I.add hl I._2) then (match r with | Leaf -> assert_false l x d r | Node (rl, rx, rd, rr, _) -> if I.ge_lt_dec (height rr) (height rl) then create (create l x d rl) rx rd rr else (match rl with | Leaf -> assert_false l x d r | Node (rll, rlx, rld, rlr, _) -> create (create l x d rll) rlx rld (create rlr rx rd rr))) else create l x d r * add : key - > ' a1 - > ' a1 tree - > ' a1 tree * let rec add x d = function | Leaf -> Node (Leaf, x, d, Leaf, I._1) | Node (l, y, d', r, h) -> (match X.compare x y with | OrderedType.LT -> bal (add x d l) y d' r | OrderedType.EQ -> Node (l, y, d, r, h) | OrderedType.GT -> bal l y d' (add x d r)) * remove_min : ' a1 tree - > key - > ' a1 - > ' a1 tree - > ' a1 tree*(key*'a1 ) * 'a1 tree -> key -> 'a1 -> 'a1 tree -> 'a1 tree*(key*'a1) **) let rec remove_min l x d r = match l with | Leaf -> r,(x,d) | Node (ll, lx, ld, lr, _) -> let l',m = remove_min ll lx ld lr in (bal l' x d r),m * merge : ' a1 tree - > ' a1 tree - > ' a1 tree * let merge s1 s2 = match s1 with | Leaf -> s2 | Node (_, _, _, _, _) -> (match s2 with | Leaf -> s1 | Node (l2, x2, d2, r2, _) -> let s2',p = remove_min l2 x2 d2 r2 in let x,d = p in bal s1 x d s2') * remove : X.t - > ' a1 tree - > ' a1 tree * let rec remove x = function | Leaf -> Leaf | Node (l, y, d, r, _) -> (match X.compare x y with | OrderedType.LT -> bal (remove x l) y d r | OrderedType.EQ -> merge l r | OrderedType.GT -> bal l y d (remove x r)) * join : ' a1 tree - > key - > ' a1 - > ' a1 tree - > ' a1 tree * let rec join l = match l with | Leaf -> add | Node (ll, lx, ld, lr, lh) -> (fun x d -> let rec join_aux r = match r with | Leaf -> add x d l | Node (rl, rx, rd, rr, rh) -> if I.gt_le_dec lh (I.add rh I._2) then bal ll lx ld (join lr x d r) else if I.gt_le_dec rh (I.add lh I._2) then bal (join_aux rl) rx rd rr else create l x d r in join_aux) type 'elt triple = { t_left : 'elt tree; t_opt : 'elt option; t_right : 'elt tree } let t_left t0 = t0.t_left * : ' a1 triple - > ' a1 option * let t_opt t0 = t0.t_opt * val : ' a1 triple - > ' a1 tree * let t_right t0 = t0.t_right let rec split x = function | Leaf -> { t_left = Leaf; t_opt = None; t_right = Leaf } | Node (l, y, d, r, _) -> (match X.compare x y with | OrderedType.LT -> let { t_left = ll; t_opt = o; t_right = rl } = split x l in { t_left = ll; t_opt = o; t_right = (join rl y d r) } | OrderedType.EQ -> { t_left = l; t_opt = (Some d); t_right = r } | OrderedType.GT -> let { t_left = rl; t_opt = o; t_right = rr } = split x r in { t_left = (join l y d rl); t_opt = o; t_right = rr }) let concat m1 m2 = match m1 with | Leaf -> m2 | Node (_, _, _, _, _) -> (match m2 with | Leaf -> m1 | Node (l2, x2, d2, r2, _) -> let m2',xd = remove_min l2 x2 d2 r2 in join m1 (fst xd) (snd xd) m2') let rec elements_aux acc = function | Leaf -> acc | Node (l, x, d, r, _) -> elements_aux ((x,d)::(elements_aux acc r)) l let elements m = elements_aux [] m let rec fold f m a = match m with | Leaf -> a | Node (l, x, d, r, _) -> fold f r (f x d (fold f l a)) type 'elt enumeration = | End | More of key * 'elt * 'elt tree * 'elt enumeration let rec enumeration_rect f f0 = function | End -> f | More (k, e0, t0, e1) -> f0 k e0 t0 e1 (enumeration_rect f f0 e1) * : ' a2 - > ( key - > ' a1 - > ' a1 tree - > ' a1 enumeration - > ' a2 - > ' a2 ) - > ' a1 enumeration - > ' a2 * 'a2 -> (key -> 'a1 -> 'a1 tree -> 'a1 enumeration -> 'a2 -> 'a2) -> 'a1 enumeration -> 'a2 **) let rec enumeration_rec f f0 = function | End -> f | More (k, e0, t0, e1) -> f0 k e0 t0 e1 (enumeration_rec f f0 e1) let rec cons m e = match m with | Leaf -> e | Node (l, x, d, r, _) -> cons l (More (x, d, r, e)) let equal_more cmp x1 d1 cont = function | End -> false | More (x2, d2, r2, e3) -> (match X.compare x1 x2 with | OrderedType.EQ -> if cmp d1 d2 then cont (cons r2 e3) else false | _ -> false) let rec equal_cont cmp m1 cont e2 = match m1 with | Leaf -> cont e2 | Node (l1, x1, d1, r1, _) -> equal_cont cmp l1 (equal_more cmp x1 d1 (equal_cont cmp r1 cont)) e2 * equal_end : ' a1 enumeration - > bool * let equal_end = function | End -> true | More (_, _, _, _) -> false let equal cmp m1 m2 = equal_cont cmp m1 equal_end (cons m2 End) let rec map f = function | Leaf -> Leaf | Node (l, x, d, r, h) -> Node ((map f l), x, (f d), (map f r), h) * : ( key - > ' a1 - > ' a2 ) - > ' a1 tree - > ' a2 tree * let rec mapi f = function | Leaf -> Leaf | Node (l, x, d, r, h) -> Node ((mapi f l), x, (f x d), (mapi f r), h) let rec map_option f = function | Leaf -> Leaf | Node (l, x, d, r, _) -> (match f x d with | Some d' -> join (map_option f l) x d' (map_option f r) | None -> concat (map_option f l) (map_option f r)) * : ( key - > ' a1 - > ' a2 option - > ' a3 option ) - > ( ' a1 tree - > ' a3 tree ) - > ( ' a2 tree - > ' a3 tree ) - > ' a1 tree - > ' a2 tree - > ' a3 tree * (key -> 'a1 -> 'a2 option -> 'a3 option) -> ('a1 tree -> 'a3 tree) -> ('a2 tree -> 'a3 tree) -> 'a1 tree -> 'a2 tree -> 'a3 tree **) let rec map2_opt f mapl mapr m1 m2 = match m1 with | Leaf -> mapr m2 | Node (l1, x1, d1, r1, _) -> (match m2 with | Leaf -> mapl m1 | Node (_, _, _, _, _) -> let { t_left = l2'; t_opt = o2; t_right = r2' } = split x1 m2 in (match f x1 d1 o2 with | Some e -> join (map2_opt f mapl mapr l1 l2') x1 e (map2_opt f mapl mapr r1 r2') | None -> concat (map2_opt f mapl mapr l1 l2') (map2_opt f mapl mapr r1 r2'))) * val map2 : ( ' a1 option - > ' a2 option - > ' a3 option ) - > ' a1 tree - > ' a2 tree - > ' a3 tree * ('a1 option -> 'a2 option -> 'a3 option) -> 'a1 tree -> 'a2 tree -> 'a3 tree **) let map2 f = map2_opt (fun _ d o -> f (Some d) o) (map_option (fun _ d -> f (Some d) None)) (map_option (fun _ d' -> f None (Some d'))) module Proofs = struct module MX = OrderedType.OrderedTypeFacts(X) module PX = OrderedType.KeyOrderedType(X) module L = Raw(X) type 'elt coq_R_mem = | R_mem_0 of 'elt tree | R_mem_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * bool * 'elt coq_R_mem | R_mem_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_mem_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * bool * 'elt coq_R_mem * : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ' a1 tree - > bool - > ' a1 coq_R_mem - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> 'a1 tree -> bool -> 'a1 coq_R_mem -> 'a2 **) let rec coq_R_mem_rect x f f0 f1 f2 _ _ = function | R_mem_0 m -> f m __ | R_mem_1 (m, l, y, _x, r0, _x0, _res, r1) -> f0 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rect x f f0 f1 f2 l _res r1) | R_mem_2 (m, l, y, _x, r0, _x0) -> f1 m l y _x r0 _x0 __ __ __ | R_mem_3 (m, l, y, _x, r0, _x0, _res, r1) -> f2 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rect x f f0 f1 f2 r0 _res r1) * coq_R_mem_rec : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > bool - > ' a1 coq_R_mem - > ' a2 - > ' a2 ) - > ' a1 tree - > bool - > ' a1 coq_R_mem - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> bool -> 'a1 coq_R_mem -> 'a2 -> 'a2) -> 'a1 tree -> bool -> 'a1 coq_R_mem -> 'a2 **) let rec coq_R_mem_rec x f f0 f1 f2 _ _ = function | R_mem_0 m -> f m __ | R_mem_1 (m, l, y, _x, r0, _x0, _res, r1) -> f0 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rec x f f0 f1 f2 l _res r1) | R_mem_2 (m, l, y, _x, r0, _x0) -> f1 m l y _x r0 _x0 __ __ __ | R_mem_3 (m, l, y, _x, r0, _x0, _res, r1) -> f2 m l y _x r0 _x0 __ __ __ _res r1 (coq_R_mem_rec x f f0 f1 f2 r0 _res r1) type 'elt coq_R_find = | R_find_0 of 'elt tree | R_find_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt option * 'elt coq_R_find | R_find_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_find_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt option * 'elt coq_R_find let rec coq_R_find_rect x f f0 f1 f2 _ _ = function | R_find_0 m -> f m __ | R_find_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rect x f f0 f1 f2 l _res r1) | R_find_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_find_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rect x f f0 f1 f2 r0 _res r1) * coq_R_find_rec : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 option - > ' a1 coq_R_find - > ' a2 - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 option - > ' a1 coq_R_find - > ' a2 - > ' a2 ) - > ' a1 tree - > ' a1 option - > ' a1 coq_R_find - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 option -> 'a1 coq_R_find -> 'a2 -> 'a2) -> 'a1 tree -> 'a1 option -> 'a1 coq_R_find -> 'a2 **) let rec coq_R_find_rec x f f0 f1 f2 _ _ = function | R_find_0 m -> f m __ | R_find_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rec x f f0 f1 f2 l _res r1) | R_find_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_find_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_find_rec x f f0 f1 f2 r0 _res r1) type 'elt coq_R_bal = | R_bal_0 of 'elt tree * key * 'elt * 'elt tree | R_bal_1 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_2 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_3 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_4 of 'elt tree * key * 'elt * 'elt tree | R_bal_5 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_6 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_7 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t | R_bal_8 of 'elt tree * key * 'elt * 'elt tree let coq_R_bal_rect f f0 f1 f2 f3 f4 f5 f6 f7 _ _ _ _ _ = function | R_bal_0 (x, x0, x1, x2) -> f x x0 x1 x2 __ __ __ | R_bal_1 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f0 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_2 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f1 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_3 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f2 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_4 (x, x0, x1, x2) -> f3 x x0 x1 x2 __ __ __ __ __ | R_bal_5 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f4 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_6 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f5 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_7 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f6 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_8 (x, x0, x1, x2) -> f7 x x0 x1 x2 __ __ __ __ let coq_R_bal_rec f f0 f1 f2 f3 f4 f5 f6 f7 _ _ _ _ _ = function | R_bal_0 (x, x0, x1, x2) -> f x x0 x1 x2 __ __ __ | R_bal_1 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f0 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_2 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f1 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_3 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f2 x x0 x1 x2 __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_4 (x, x0, x1, x2) -> f3 x x0 x1 x2 __ __ __ __ __ | R_bal_5 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f4 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ | R_bal_6 (x, x0, x1, x2, x3, x4, x5, x6, x7) -> f5 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ __ | R_bal_7 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f6 x x0 x1 x2 __ __ __ __ x3 x4 x5 x6 x7 __ __ __ x8 x9 x10 x11 x12 __ | R_bal_8 (x, x0, x1, x2) -> f7 x x0 x1 x2 __ __ __ __ type 'elt coq_R_add = | R_add_0 of 'elt tree | R_add_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_add | R_add_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_add_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_add let rec coq_R_add_rect x d f f0 f1 f2 _ _ = function | R_add_0 m -> f m __ | R_add_1 (m, l, y, d', r0, h, _res, r1) -> f0 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rect x d f f0 f1 f2 l _res r1) | R_add_2 (m, l, y, d', r0, h) -> f1 m l y d' r0 h __ __ __ | R_add_3 (m, l, y, d', r0, h, _res, r1) -> f2 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rect x d f f0 f1 f2 r0 _res r1) let rec coq_R_add_rec x d f f0 f1 f2 _ _ = function | R_add_0 m -> f m __ | R_add_1 (m, l, y, d', r0, h, _res, r1) -> f0 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rec x d f f0 f1 f2 l _res r1) | R_add_2 (m, l, y, d', r0, h) -> f1 m l y d' r0 h __ __ __ | R_add_3 (m, l, y, d', r0, h, _res, r1) -> f2 m l y d' r0 h __ __ __ _res r1 (coq_R_add_rec x d f f0 f1 f2 r0 _res r1) type 'elt coq_R_remove_min = | R_remove_min_0 of 'elt tree * key * 'elt * 'elt tree | R_remove_min_1 of 'elt tree * key * 'elt * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * ('elt tree*(key*'elt)) * 'elt coq_R_remove_min * 'elt tree * (key*'elt) let rec coq_R_remove_min_rect f f0 _ _ _ _ _ = function | R_remove_min_0 (l, x, d, r0) -> f l x d r0 __ | R_remove_min_1 (l, x, d, r0, ll, lx, ld, lr, _x, _res, r1, l', m) -> f0 l x d r0 ll lx ld lr _x __ _res r1 (coq_R_remove_min_rect f f0 ll lx ld lr _res r1) l' m __ let rec coq_R_remove_min_rec f f0 _ _ _ _ _ = function | R_remove_min_0 (l, x, d, r0) -> f l x d r0 __ | R_remove_min_1 (l, x, d, r0, ll, lx, ld, lr, _x, _res, r1, l', m) -> f0 l x d r0 ll lx ld lr _x __ _res r1 (coq_R_remove_min_rec f f0 ll lx ld lr _res r1) l' m __ type 'elt coq_R_merge = | R_merge_0 of 'elt tree * 'elt tree | R_merge_1 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_merge_2 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * (key*'elt) * key * 'elt * val coq_R_merge_rect : ( ' a1 tree - > ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > ( key*'a1 ) - > _ _ - > key - > ' a1 - > _ _ - > ' a2 ) - > ' a1 tree - > ' a1 tree - > ' a1 tree - > ' a2 * ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> key -> 'a1 -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_merge -> 'a2 **) let coq_R_merge_rect f f0 f1 _ _ _ = function | R_merge_0 (x, x0) -> f x x0 __ | R_merge_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_merge_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ x13 x14 __ * val coq_R_merge_rec : ( ' a1 tree - > ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a1 tree - > ( key*'a1 ) - > _ _ - > key - > ' a1 - > _ _ - > ' a2 ) - > ' a1 tree - > ' a1 tree - > ' a1 tree - > ' a2 * ('a1 tree -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a1 tree -> (key*'a1) -> __ -> key -> 'a1 -> __ -> 'a2) -> 'a1 tree -> 'a1 tree -> 'a1 tree -> 'a1 coq_R_merge -> 'a2 **) let coq_R_merge_rec f f0 f1 _ _ _ = function | R_merge_0 (x, x0) -> f x x0 __ | R_merge_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_merge_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ x13 x14 __ type 'elt coq_R_remove = | R_remove_0 of 'elt tree | R_remove_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_remove | R_remove_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_remove_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * 'elt coq_R_remove let rec coq_R_remove_rect x f f0 f1 f2 _ _ = function | R_remove_0 m -> f m __ | R_remove_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rect x f f0 f1 f2 l _res r1) | R_remove_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_remove_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rect x f f0 f1 f2 r0 _res r1) let rec coq_R_remove_rec x f f0 f1 f2 _ _ = function | R_remove_0 m -> f m __ | R_remove_1 (m, l, y, d, r0, _x, _res, r1) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rec x f f0 f1 f2 l _res r1) | R_remove_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_remove_3 (m, l, y, d, r0, _x, _res, r1) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_remove_rec x f f0 f1 f2 r0 _res r1) type 'elt coq_R_concat = | R_concat_0 of 'elt tree * 'elt tree | R_concat_1 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_concat_2 of 'elt tree * 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt tree * (key*'elt) let coq_R_concat_rect f f0 f1 _ _ _ = function | R_concat_0 (x, x0) -> f x x0 __ | R_concat_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_concat_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ let coq_R_concat_rec f f0 f1 _ _ _ = function | R_concat_0 (x, x0) -> f x x0 __ | R_concat_1 (x, x0, x1, x2, x3, x4, x5) -> f0 x x0 x1 x2 x3 x4 x5 __ __ | R_concat_2 (x, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) -> f1 x x0 x1 x2 x3 x4 x5 __ x6 x7 x8 x9 x10 __ x11 x12 __ type 'elt coq_R_split = | R_split_0 of 'elt tree | R_split_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt triple * 'elt coq_R_split * 'elt tree * 'elt option * 'elt tree | R_split_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_split_3 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'elt triple * 'elt coq_R_split * 'elt tree * 'elt option * 'elt tree let rec coq_R_split_rect x f f0 f1 f2 _ _ = function | R_split_0 m -> f m __ | R_split_1 (m, l, y, d, r0, _x, _res, r1, ll, o, rl) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rect x f f0 f1 f2 l _res r1) ll o rl __ | R_split_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_split_3 (m, l, y, d, r0, _x, _res, r1, rl, o, rr) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rect x f f0 f1 f2 r0 _res r1) rl o rr __ * : X.t - > ( ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 triple - > ' a1 coq_R_split - > ' a2 - > ' a1 tree - > ' a1 option - > ' a1 tree - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a2 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > _ _ - > ' a1 triple - > ' a1 coq_R_split - > ' a2 - > ' a1 tree - > ' a1 option - > ' a1 tree - > _ _ - > ' a2 ) - > ' a1 tree - > ' a1 triple - > ' a1 coq_R_split - > ' a2 * X.t -> ('a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a2) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> __ -> 'a1 triple -> 'a1 coq_R_split -> 'a2 -> 'a1 tree -> 'a1 option -> 'a1 tree -> __ -> 'a2) -> 'a1 tree -> 'a1 triple -> 'a1 coq_R_split -> 'a2 **) let rec coq_R_split_rec x f f0 f1 f2 _ _ = function | R_split_0 m -> f m __ | R_split_1 (m, l, y, d, r0, _x, _res, r1, ll, o, rl) -> f0 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rec x f f0 f1 f2 l _res r1) ll o rl __ | R_split_2 (m, l, y, d, r0, _x) -> f1 m l y d r0 _x __ __ __ | R_split_3 (m, l, y, d, r0, _x, _res, r1, rl, o, rr) -> f2 m l y d r0 _x __ __ __ _res r1 (coq_R_split_rec x f f0 f1 f2 r0 _res r1) rl o rr __ type ('elt, 'x) coq_R_map_option = | R_map_option_0 of 'elt tree | R_map_option_1 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x * 'x tree * ('elt, 'x) coq_R_map_option * 'x tree * ('elt, 'x) coq_R_map_option | R_map_option_2 of 'elt tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x tree * ('elt, 'x) coq_R_map_option * 'x tree * ('elt, 'x) coq_R_map_option let rec coq_R_map_option_rect f f0 f1 f2 _ _ = function | R_map_option_0 m -> f0 m __ | R_map_option_1 (m, l, x, d, r0, _x, d', _res0, r1, _res, r2) -> f1 m l x d r0 _x __ d' __ _res0 r1 (coq_R_map_option_rect f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rect f f0 f1 f2 r0 _res r2) | R_map_option_2 (m, l, x, d, r0, _x, _res0, r1, _res, r2) -> f2 m l x d r0 _x __ __ _res0 r1 (coq_R_map_option_rect f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rect f f0 f1 f2 r0 _res r2) * : ( key - > ' a1 - > ' a2 option ) - > ( ' a1 tree - > _ _ - > ' a3 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > ' a2 - > _ _ - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a3 ) - > ( ' a1 tree - > ' a1 tree - > key - > ' a1 - > ' a1 tree - > I.t - > _ _ - > _ _ - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 - > ' a3 ) - > ' a1 tree - > ' a2 tree - > ( ' a1 , ' a2 ) coq_R_map_option - > ' a3 * (key -> 'a1 -> 'a2 option) -> ('a1 tree -> __ -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> 'a2 -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> ('a1 tree -> 'a1 tree -> key -> 'a1 -> 'a1 tree -> I.t -> __ -> __ -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 -> 'a3) -> 'a1 tree -> 'a2 tree -> ('a1, 'a2) coq_R_map_option -> 'a3 **) let rec coq_R_map_option_rec f f0 f1 f2 _ _ = function | R_map_option_0 m -> f0 m __ | R_map_option_1 (m, l, x, d, r0, _x, d', _res0, r1, _res, r2) -> f1 m l x d r0 _x __ d' __ _res0 r1 (coq_R_map_option_rec f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rec f f0 f1 f2 r0 _res r2) | R_map_option_2 (m, l, x, d, r0, _x, _res0, r1, _res, r2) -> f2 m l x d r0 _x __ __ _res0 r1 (coq_R_map_option_rec f f0 f1 f2 l _res0 r1) _res r2 (coq_R_map_option_rec f f0 f1 f2 r0 _res r2) type ('elt, 'x0, 'x) coq_R_map2_opt = | R_map2_opt_0 of 'elt tree * 'x0 tree | R_map2_opt_1 of 'elt tree * 'x0 tree * 'elt tree * key * 'elt * 'elt tree * I.t | R_map2_opt_2 of 'elt tree * 'x0 tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x0 tree * key * 'x0 * 'x0 tree * I.t * 'x0 tree * 'x0 option * 'x0 tree * 'x * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt | R_map2_opt_3 of 'elt tree * 'x0 tree * 'elt tree * key * 'elt * 'elt tree * I.t * 'x0 tree * key * 'x0 * 'x0 tree * I.t * 'x0 tree * 'x0 option * 'x0 tree * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt * 'x tree * ('elt, 'x0, 'x) coq_R_map2_opt let rec coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 _ _ _ = function | R_map2_opt_0 (m1, m2) -> f0 m1 m2 __ | R_map2_opt_1 (m1, m2, l1, x1, d1, r1, _x) -> f1 m1 m2 l1 x1 d1 r1 _x __ __ | R_map2_opt_2 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', e, _res0, r0, _res, r2) -> f2 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ e __ _res0 r0 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) | R_map2_opt_3 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', _res0, r0, _res, r2) -> f3 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ __ _res0 r0 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rect f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) let rec coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 _ _ _ = function | R_map2_opt_0 (m1, m2) -> f0 m1 m2 __ | R_map2_opt_1 (m1, m2, l1, x1, d1, r1, _x) -> f1 m1 m2 l1 x1 d1 r1 _x __ __ | R_map2_opt_2 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', e, _res0, r0, _res, r2) -> f2 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ e __ _res0 r0 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) | R_map2_opt_3 (m1, m2, l1, x1, d1, r1, _x, _x0, _x1, _x2, _x3, _x4, l2', o2, r2', _res0, r0, _res, r2) -> f3 m1 m2 l1 x1 d1 r1 _x __ _x0 _x1 _x2 _x3 _x4 __ l2' o2 r2' __ __ _res0 r0 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 l1 l2' _res0 r0) _res r2 (coq_R_map2_opt_rec f mapl mapr f0 f1 f2 f3 r1 r2' _res r2) let fold' f s = L.fold f (elements s) let rec flatten_e = function | End -> [] | More (x, e0, t0, r) -> (x,e0)::(app (elements t0) (flatten_e r)) end end module IntMake = functor (I:Int.Int) -> functor (X:OrderedType.OrderedType) -> struct module E = X module Raw = Raw(I)(X) type 'elt bst = 'elt Raw.tree * this : ' a1 Raw.tree * let this b = b type 'elt t = 'elt bst type key = E.t let empty = Raw.empty let is_empty m = Raw.is_empty (this m) * add : key - > ' a1 - > ' a1 t - > ' a1 t * let add x e m = Raw.add x e (this m) * remove : key - > ' a1 t - > ' a1 t * let remove x m = Raw.remove x (this m) * : key - > ' a1 t - > bool * let mem x m = Raw.mem x (this m) * find : key - > ' a1 t - > ' a1 option * let find x m = Raw.find x (this m) let map f m = Raw.map f (this m) * : ( key - > ' a1 - > ' a2 ) - > ' a1 t - > ' a2 t * let mapi f m = Raw.mapi f (this m) * val map2 : ( ' a1 option - > ' a2 option - > ' a3 option ) - > ' a1 t - > ' a2 t - > ' a3 t * ('a1 option -> 'a2 option -> 'a3 option) -> 'a1 t -> 'a2 t -> 'a3 t **) let map2 f m m' = Raw.map2 f (this m) (this m') let elements m = Raw.elements (this m) * cardinal : ' a1 t - > nat * let cardinal m = Raw.cardinal (this m) let fold f m i = Raw.fold f (this m) i let equal cmp m m' = Raw.equal cmp (this m) (this m') end module Make = functor (X:OrderedType.OrderedType) -> IntMake(Int.Z_as_Int)(X)
248a932694e20f07b2e0e2dcc39b029c27b9e222b08a665ff0bcdb0250c2ab46
exercism/babashka
project.clj
(defproject interest-is-interesting "0.1.0-SNAPSHOT" :description "interest-is-interesting exercise." :url "-is-interesting" :dependencies [[org.clojure/clojure "1.10.0"]])
null
https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/concept/interest-is-interesting/project.clj
clojure
(defproject interest-is-interesting "0.1.0-SNAPSHOT" :description "interest-is-interesting exercise." :url "-is-interesting" :dependencies [[org.clojure/clojure "1.10.0"]])
bbca70312dbd25ba6c1d09d32891a006a2c7407c5c5dfb884663f0333f0ce977
HunterYIboHu/htdp2-solution
ex219-going-on.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-abbr-reader.ss" "lang")((modname ex219-going-on) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/universe) (require 2htdp/image) ;; graphic constants (define RADIUS 10) (define HEIGHT (* 50 RADIUS)) (define WIDTH (* HEIGHT 2)) (define MID-HEIGHT (/ HEIGHT 2)) (define MID-WIDTH (/ WIDTH 2)) (define SCENE (empty-scene WIDTH HEIGHT)) (define SEGMENT (circle RADIUS "solid" "red")) (define FOOD (circle RADIUS "solid" "black")) (define HIT-WALL (text "hit the wall!" 24 "green")) (define RAN-INTO-IT-SELF (text "run into worm itself!" 24 "green")) ;; physical constants (define MOVE (* RADIUS 2)) (define UP (list 0 (- 0 MOVE))) (define DOWN (list 0 MOVE)) (define LEFT (list (- 0 MOVE) 0)) (define RIGHT (list MOVE 0)) ;; data difinitions ; a Segment is a Posn represent the segment's current position (define SEG-1 (make-posn 170 25)) (define SEG-2 (make-posn 190 25)) (define SEG-3 (make-posn 130 25)) (define SEG-4 (make-posn 110 25)) (define SEG-A (make-posn 170 45)) (define SEG-B (make-posn 150 45)) (define SEG-C (make-posn 130 45)) (define-struct worm [head tail direction food]) a Worm is ( make - worm Posn List - of - segments Direction Posn ) ; (make-worm p los d f) p is the current position of the head of worm, ; los is a list of "connected" segments, the d is the direction of the ; moving worm, and the f is the current position of food. ; Direction is (list Number Number) ; (list h v) h represent the moving speed in horizenal, negative means left, ; positive means right, 0 means no moving on horizenal; ; v represent the moving speed in vertical, negative means up, positive ; means down, ; 0 means no moving on vertical. LOS ( list of segments ) is one of : ; - '() ; - (cons Segment LOS) ; interpretation: represent the posn of the tail. (define TAIL-1 (list SEG-1 SEG-2)) (define TAIL-2 (list SEG-3 SEG-4)) (define TAIL-W (list SEG-1 SEG-A SEG-B SEG-C)) ;; struct constants (define WRONG-FOOD (make-posn 970 470)) (define INITIAL (make-worm (make-posn MID-WIDTH MID-HEIGHT) '() RIGHT WRONG-FOOD)) (define NORMAL (make-worm (make-posn 150 25) '() UP WRONG-FOOD)) (define OUTSIDE (make-worm (make-posn 100 490) '() DOWN WRONG-FOOD)) (define MULTI-1 (make-worm (make-posn 150 25) TAIL-1 DOWN WRONG-FOOD)) (define MULTI-2 (make-worm (make-posn 150 25) TAIL-2 UP WRONG-FOOD)) (define MULTI-W (make-worm (make-posn 150 25) TAIL-W DOWN WRONG-FOOD)) (define MULTI-R (make-worm (make-posn 150 25) TAIL-W UP WRONG-FOOD)) (define INITIAL-2 (make-worm (make-posn 150 25) TAIL-W LEFT WRONG-FOOD)) ;; main functions ; Worm -> Worm (define (worm-main w) (big-bang w [on-tick worm-move 0.2] [on-key keyh] [to-draw render] [stop-when stop? render-final])) ;; important functions ; Worm -> Worm ; determine the current position of the given worm's head and tail according ; to the direction of it. (check-expect (worm-move INITIAL) (make-worm (head-move INITIAL) '() RIGHT WRONG-FOOD)) (check-expect (worm-move MULTI-2) (make-worm (head-move MULTI-2) (list (make-posn 150 25) SEG-3) UP WRONG-FOOD)) (define (worm-move w) (make-worm (head-move w) (if (equal? (head-move w) (worm-food w)) (cons (worm-head w) (worm-tail w)) (cut-the-last (cons (worm-head w) (worm-tail w)))) (worm-direction w) (if (equal? (head-move w) (worm-food w)) (create-food w) (worm-food w)))) Worm KeyEvent - > Worm ; determine the direction of worm according to the ke. if is " up " , then the direction is set to UP ; if is " down " , then the direction is set to DOWN ; if is " left " , then the direction is set to LEFT ; if is " right " , then the direction is set to RIGHT ; ; otherwise the direction won't change. (check-expect (keyh INITIAL "right") INITIAL) (check-expect (keyh INITIAL "up") (make-worm (worm-head INITIAL) (worm-tail INITIAL) UP WRONG-FOOD)) (check-expect (keyh INITIAL "p") INITIAL) (check-expect (keyh NORMAL "left") (make-worm (worm-head NORMAL) (worm-tail NORMAL) LEFT WRONG-FOOD)) (check-expect (keyh NORMAL "up") NORMAL) (check-expect (keyh NORMAL "p") NORMAL) (check-expect (keyh MULTI-1 "down") MULTI-1) (check-expect (keyh MULTI-1 "up") MULTI-1) (check-expect (keyh MULTI-1 "left") (make-worm (worm-head MULTI-1) (worm-tail MULTI-1) LEFT WRONG-FOOD)) (define (keyh w ke) (make-worm (worm-head w) (worm-tail w) (cond [(and (key=? "up" ke) (change? (worm-direction w) ke)) UP] [(and (key=? "down" ke) (change? (worm-direction w) ke)) DOWN] [(and (key=? "left" ke) (change? (worm-direction w) ke)) LEFT] [(and (key=? "right" ke) (change? (worm-direction w) ke)) RIGHT] [else (worm-direction w)]) (worm-food w))) ; Worm -> Image ; add a worm on the scene. (check-expect (render INITIAL) (place-images (list FOOD SEGMENT) (list WRONG-FOOD (make-posn MID-WIDTH MID-HEIGHT)) SCENE)) (check-expect (render MULTI-1) (place-images (cons FOOD(make-list 3 SEGMENT)) (list WRONG-FOOD (make-posn 150 25) SEG-1 SEG-2) SCENE)) (define (render w) (place-images (cons FOOD (make-list (add1 (length (worm-tail w))) SEGMENT)) (cons (worm-food w) (cons (worm-head w) (worm-tail w))) SCENE)) ; Worm -> Boolean determine whether to end the game . Game will end under one of these ; conditions is satisfied: ; - the worm's head run into the wall ; - the worm's head run into itself (check-expect (stop? INITIAL) #false) (check-expect (stop? MULTI-1) #false) (check-expect (stop? (worm-move MULTI-W)) #true) (define (stop? w) (or (hit-the-wall? (worm-head w)) (member? (worm-head w) (worm-tail w)))) ; Worm -> Image ; render the end scene for different reason. (check-expect (render-final (worm-move MULTI-W)) (overlay/align "left" "bottom" RAN-INTO-IT-SELF (render (worm-move MULTI-W)))) (check-expect (render-final OUTSIDE) (overlay/align "left" "bottom" HIT-WALL (render OUTSIDE))) (define (render-final w) (overlay/align "left" "bottom" (cond [(hit-the-wall? (worm-head w)) HIT-WALL] [else RAN-INTO-IT-SELF]) (render w))) ;; auxiliary functions ; Worm -> Posn ; produces a new Posn which different from the head, tail and old food. Here different means far away from them at least one MOVE , no matter ; x-coordinate or y-coordinate. ;;;; there won't check the food will be different or not... (define (create-food w) (make-posn (- (* (add1 (random 50)) MOVE) RADIUS) (- (* (add1 (random 25)) MOVE) RADIUS))) ; Segment -> Boolean if the given head 's posn is close to wall in one MOVE , ; return #true; else reutrn #false. (check-expect (hit-the-wall? (make-posn MID-WIDTH MID-HEIGHT)) #false) (check-expect (hit-the-wall? (make-posn 10000 100)) #true) (check-expect (hit-the-wall? (make-posn 100 490)) #true) (define (hit-the-wall? head) (not (and (< MOVE (posn-x head) (- WIDTH MOVE)) (< MOVE (posn-y head) (- HEIGHT MOVE))))) ; Worm -> Worm ; determine the current position of worm (without tail) according to the direction. (check-expect (head-move INITIAL) (make-posn (+ MID-WIDTH 20) MID-HEIGHT)) (check-expect (head-move NORMAL) (make-posn 150 (+ 25 -20))) (define (head-move w) (make-posn (+ (posn-x (worm-head w)) (first (worm-direction w))) (+ (posn-y (worm-head w)) (second (worm-direction w))))) ; Worm -> Worm ; cut the last segment of the given w's tail (check-expect (cut-the-last (worm-tail MULTI-1)) (list SEG-1)) (check-expect (cut-the-last (worm-tail MULTI-2)) (list SEG-3)) (define (cut-the-last w) (cond [(empty? (rest w)) '()] [else (cons (first w) (cut-the-last (rest w)))])) ; Direction -> Boolean ; determine whether the direction can be changed. (check-expect (change? UP "up") #true) (check-expect (change? DOWN "up") #false) (check-expect (change? LEFT "down") #true) (check-expect (change? RIGHT "left") #false) (define (change? d ke) (not (equal? (cond [(key=? "up" ke) DOWN] [(key=? "down" ke) UP] [(key=? "left" ke) RIGHT] [(key=? "right" ke) LEFT]) d))) ;; launch program (worm-main (make-worm (make-posn 30 30) '() RIGHT (create-food NORMAL)))
null
https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter2/Section13-project-list/ex219-going-on.rkt
racket
about the language level of this file in a form that our tools can easily process. graphic constants physical constants data difinitions a Segment is a Posn represent the segment's current position (make-worm p los d f) p is the current position of the head of worm, los is a list of "connected" segments, the d is the direction of the moving worm, and the f is the current position of food. Direction is (list Number Number) (list h v) h represent the moving speed in horizenal, negative means left, positive means right, 0 means no moving on horizenal; v represent the moving speed in vertical, negative means up, positive means down, 0 means no moving on vertical. - '() - (cons Segment LOS) interpretation: represent the posn of the tail. struct constants main functions Worm -> Worm important functions Worm -> Worm determine the current position of the given worm's head and tail according to the direction of it. determine the direction of worm according to the ke. otherwise the direction won't change. Worm -> Image add a worm on the scene. Worm -> Boolean conditions is satisfied: - the worm's head run into the wall - the worm's head run into itself Worm -> Image render the end scene for different reason. auxiliary functions Worm -> Posn produces a new Posn which different from the head, tail and old food. x-coordinate or y-coordinate. there won't check the food will be different or not... Segment -> Boolean return #true; else reutrn #false. Worm -> Worm determine the current position of worm (without tail) according to the direction. Worm -> Worm cut the last segment of the given w's tail Direction -> Boolean determine whether the direction can be changed. launch program
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex219-going-on) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/universe) (require 2htdp/image) (define RADIUS 10) (define HEIGHT (* 50 RADIUS)) (define WIDTH (* HEIGHT 2)) (define MID-HEIGHT (/ HEIGHT 2)) (define MID-WIDTH (/ WIDTH 2)) (define SCENE (empty-scene WIDTH HEIGHT)) (define SEGMENT (circle RADIUS "solid" "red")) (define FOOD (circle RADIUS "solid" "black")) (define HIT-WALL (text "hit the wall!" 24 "green")) (define RAN-INTO-IT-SELF (text "run into worm itself!" 24 "green")) (define MOVE (* RADIUS 2)) (define UP (list 0 (- 0 MOVE))) (define DOWN (list 0 MOVE)) (define LEFT (list (- 0 MOVE) 0)) (define RIGHT (list MOVE 0)) (define SEG-1 (make-posn 170 25)) (define SEG-2 (make-posn 190 25)) (define SEG-3 (make-posn 130 25)) (define SEG-4 (make-posn 110 25)) (define SEG-A (make-posn 170 45)) (define SEG-B (make-posn 150 45)) (define SEG-C (make-posn 130 45)) (define-struct worm [head tail direction food]) a Worm is ( make - worm Posn List - of - segments Direction Posn ) LOS ( list of segments ) is one of : (define TAIL-1 (list SEG-1 SEG-2)) (define TAIL-2 (list SEG-3 SEG-4)) (define TAIL-W (list SEG-1 SEG-A SEG-B SEG-C)) (define WRONG-FOOD (make-posn 970 470)) (define INITIAL (make-worm (make-posn MID-WIDTH MID-HEIGHT) '() RIGHT WRONG-FOOD)) (define NORMAL (make-worm (make-posn 150 25) '() UP WRONG-FOOD)) (define OUTSIDE (make-worm (make-posn 100 490) '() DOWN WRONG-FOOD)) (define MULTI-1 (make-worm (make-posn 150 25) TAIL-1 DOWN WRONG-FOOD)) (define MULTI-2 (make-worm (make-posn 150 25) TAIL-2 UP WRONG-FOOD)) (define MULTI-W (make-worm (make-posn 150 25) TAIL-W DOWN WRONG-FOOD)) (define MULTI-R (make-worm (make-posn 150 25) TAIL-W UP WRONG-FOOD)) (define INITIAL-2 (make-worm (make-posn 150 25) TAIL-W LEFT WRONG-FOOD)) (define (worm-main w) (big-bang w [on-tick worm-move 0.2] [on-key keyh] [to-draw render] [stop-when stop? render-final])) (check-expect (worm-move INITIAL) (make-worm (head-move INITIAL) '() RIGHT WRONG-FOOD)) (check-expect (worm-move MULTI-2) (make-worm (head-move MULTI-2) (list (make-posn 150 25) SEG-3) UP WRONG-FOOD)) (define (worm-move w) (make-worm (head-move w) (if (equal? (head-move w) (worm-food w)) (cons (worm-head w) (worm-tail w)) (cut-the-last (cons (worm-head w) (worm-tail w)))) (worm-direction w) (if (equal? (head-move w) (worm-food w)) (create-food w) (worm-food w)))) Worm KeyEvent - > Worm (check-expect (keyh INITIAL "right") INITIAL) (check-expect (keyh INITIAL "up") (make-worm (worm-head INITIAL) (worm-tail INITIAL) UP WRONG-FOOD)) (check-expect (keyh INITIAL "p") INITIAL) (check-expect (keyh NORMAL "left") (make-worm (worm-head NORMAL) (worm-tail NORMAL) LEFT WRONG-FOOD)) (check-expect (keyh NORMAL "up") NORMAL) (check-expect (keyh NORMAL "p") NORMAL) (check-expect (keyh MULTI-1 "down") MULTI-1) (check-expect (keyh MULTI-1 "up") MULTI-1) (check-expect (keyh MULTI-1 "left") (make-worm (worm-head MULTI-1) (worm-tail MULTI-1) LEFT WRONG-FOOD)) (define (keyh w ke) (make-worm (worm-head w) (worm-tail w) (cond [(and (key=? "up" ke) (change? (worm-direction w) ke)) UP] [(and (key=? "down" ke) (change? (worm-direction w) ke)) DOWN] [(and (key=? "left" ke) (change? (worm-direction w) ke)) LEFT] [(and (key=? "right" ke) (change? (worm-direction w) ke)) RIGHT] [else (worm-direction w)]) (worm-food w))) (check-expect (render INITIAL) (place-images (list FOOD SEGMENT) (list WRONG-FOOD (make-posn MID-WIDTH MID-HEIGHT)) SCENE)) (check-expect (render MULTI-1) (place-images (cons FOOD(make-list 3 SEGMENT)) (list WRONG-FOOD (make-posn 150 25) SEG-1 SEG-2) SCENE)) (define (render w) (place-images (cons FOOD (make-list (add1 (length (worm-tail w))) SEGMENT)) (cons (worm-food w) (cons (worm-head w) (worm-tail w))) SCENE)) determine whether to end the game . Game will end under one of these (check-expect (stop? INITIAL) #false) (check-expect (stop? MULTI-1) #false) (check-expect (stop? (worm-move MULTI-W)) #true) (define (stop? w) (or (hit-the-wall? (worm-head w)) (member? (worm-head w) (worm-tail w)))) (check-expect (render-final (worm-move MULTI-W)) (overlay/align "left" "bottom" RAN-INTO-IT-SELF (render (worm-move MULTI-W)))) (check-expect (render-final OUTSIDE) (overlay/align "left" "bottom" HIT-WALL (render OUTSIDE))) (define (render-final w) (overlay/align "left" "bottom" (cond [(hit-the-wall? (worm-head w)) HIT-WALL] [else RAN-INTO-IT-SELF]) (render w))) Here different means far away from them at least one MOVE , no matter (define (create-food w) (make-posn (- (* (add1 (random 50)) MOVE) RADIUS) (- (* (add1 (random 25)) MOVE) RADIUS))) if the given head 's posn is close to wall in one MOVE , (check-expect (hit-the-wall? (make-posn MID-WIDTH MID-HEIGHT)) #false) (check-expect (hit-the-wall? (make-posn 10000 100)) #true) (check-expect (hit-the-wall? (make-posn 100 490)) #true) (define (hit-the-wall? head) (not (and (< MOVE (posn-x head) (- WIDTH MOVE)) (< MOVE (posn-y head) (- HEIGHT MOVE))))) (check-expect (head-move INITIAL) (make-posn (+ MID-WIDTH 20) MID-HEIGHT)) (check-expect (head-move NORMAL) (make-posn 150 (+ 25 -20))) (define (head-move w) (make-posn (+ (posn-x (worm-head w)) (first (worm-direction w))) (+ (posn-y (worm-head w)) (second (worm-direction w))))) (check-expect (cut-the-last (worm-tail MULTI-1)) (list SEG-1)) (check-expect (cut-the-last (worm-tail MULTI-2)) (list SEG-3)) (define (cut-the-last w) (cond [(empty? (rest w)) '()] [else (cons (first w) (cut-the-last (rest w)))])) (check-expect (change? UP "up") #true) (check-expect (change? DOWN "up") #false) (check-expect (change? LEFT "down") #true) (check-expect (change? RIGHT "left") #false) (define (change? d ke) (not (equal? (cond [(key=? "up" ke) DOWN] [(key=? "down" ke) UP] [(key=? "left" ke) RIGHT] [(key=? "right" ke) LEFT]) d))) (worm-main (make-worm (make-posn 30 30) '() RIGHT (create-food NORMAL)))
98b391819f5d2b034a876a2fefd96df294ad8272d372c92d0c0d2ce11cb5ddcc
clash-lang/clash-compiler
Signed.hs
| Copyright : ( C ) 2021 - 2022 , QBayLogic B.V. License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > Random generation of Signed numbers . Copyright : (C) 2021-2022, QBayLogic B.V. License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> Random generation of Signed numbers. -} # OPTIONS_GHC -fplugin = GHC.TypeLits . KnownNat . Solver # # LANGUAGE CPP # {-# LANGUAGE GADTs #-} module Clash.Hedgehog.Sized.Signed ( genSigned , SomeSigned(..) , genSomeSigned ) where #if !MIN_VERSION_base(4,16,0) import GHC.Natural (Natural) #endif import GHC.TypeNats import Hedgehog (MonadGen, Range) import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Clash.Promoted.Nat import Clash.Sized.Internal.Signed genSigned :: (MonadGen m, KnownNat n) => Range (Signed n) -> m (Signed n) genSigned range = Gen.frequency [ (60, Gen.integral range) , (20, Gen.constant (Range.lowerBound 99 range)) , (20, Gen.constant (Range.upperBound 99 range)) ] data SomeSigned atLeast where SomeSigned :: SNat n -> Signed (atLeast + n) -> SomeSigned atLeast instance KnownNat atLeast => Show (SomeSigned atLeast) where show (SomeSigned SNat x) = show x genSomeSigned :: (MonadGen m, KnownNat atLeast) => Range Natural -> m (SomeSigned atLeast) genSomeSigned rangeSigned = do numExtra <- Gen.integral rangeSigned case someNatVal numExtra of SomeNat proxy -> SomeSigned (snatProxy proxy) <$> genSigned Range.linearBounded
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/ba4765139ea0728546bf934005d2d9b77e48d8c7/clash-prelude-hedgehog/src/Clash/Hedgehog/Sized/Signed.hs
haskell
# LANGUAGE GADTs #
| Copyright : ( C ) 2021 - 2022 , QBayLogic B.V. License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > Random generation of Signed numbers . Copyright : (C) 2021-2022, QBayLogic B.V. License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> Random generation of Signed numbers. -} # OPTIONS_GHC -fplugin = GHC.TypeLits . KnownNat . Solver # # LANGUAGE CPP # module Clash.Hedgehog.Sized.Signed ( genSigned , SomeSigned(..) , genSomeSigned ) where #if !MIN_VERSION_base(4,16,0) import GHC.Natural (Natural) #endif import GHC.TypeNats import Hedgehog (MonadGen, Range) import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Clash.Promoted.Nat import Clash.Sized.Internal.Signed genSigned :: (MonadGen m, KnownNat n) => Range (Signed n) -> m (Signed n) genSigned range = Gen.frequency [ (60, Gen.integral range) , (20, Gen.constant (Range.lowerBound 99 range)) , (20, Gen.constant (Range.upperBound 99 range)) ] data SomeSigned atLeast where SomeSigned :: SNat n -> Signed (atLeast + n) -> SomeSigned atLeast instance KnownNat atLeast => Show (SomeSigned atLeast) where show (SomeSigned SNat x) = show x genSomeSigned :: (MonadGen m, KnownNat atLeast) => Range Natural -> m (SomeSigned atLeast) genSomeSigned rangeSigned = do numExtra <- Gen.integral rangeSigned case someNatVal numExtra of SomeNat proxy -> SomeSigned (snatProxy proxy) <$> genSigned Range.linearBounded
7ec82064c8e81b81033667d06589d087cad1e2fb9a6f03ebe3b2ce9b7710251b
Ekatereana/CommonLispWorks
where.lisp
(defun get_operation (symbol value) (cond ((string= symbol "=") (cond ((numberp value) #'=) ((stringp value) #'string=))) ((string= symbol ">") (cond ((numberp value) #'>) ((stringp value) #'string>))) ((string= symbol "<") (cond ((numberp value) #'<) ((stringp value) #'string<))) (t #'eq) ) ) (defstruct where-statement first_arg second_arg operation ) (defun is_column (row column) (position column row)) (defun read-where (stat) (let ((statement (coerce stat 'vector))) (make-where-statement :first_arg (aref statement 0) :second_arg (aref statement 2) :operation (aref statement 1) )) ) (defun where_multiply (statement separator) "split big query to list of single conditions" (let ((result '()) (temp '())) (loop for arg in statement do (cond ((string= arg separator) (progn (setq result (append result (list (read-where temp)))) (setq temp '()))) (t (setq temp (append temp (list arg)))) ) ) (setq result (append result (list (read-where temp)))) (return-from where_multiply result) ) ) (defun get_where (statement is_and is_or) "define separator (AND or OR)" (cond (is_and (where_multiply statement "and")) (is_or (where_multiply statement "or")) (t (list (read-where statement))))) (defun init_id (list_where table-names) (let ((id-s '() )) (loop for w in list_where do (setq id-s (append id-s (list (is_column table-names (read-from-string (where-statement-first_arg w))))))) (return-from init_id id-s) ) ) (defun define_operations (list_where) (let ((operations '())) (loop for w in list_where do( if (not (eq (read-from-string (where-statement-second_arg w)) 0)) (setq operations (append operations (list (get_operation (where-statement-operation w) (read-from-string (where-statement-second_arg w)))))) (setq operations (append operations (list (get_operation (where-statement-operation w) (where-statement-second_arg w))))) )) (return-from define_operations operations) ) ) (defun execute_condition ( rows condition id operation) "create table for one condition" (let ((result (simple-table:make-table))) (simple-table:with-rows (rows row) (if (funcall operation (simple-table:get-row-column id row) (read-from-string (where-statement-second_arg condition))) (simple-table:add-to-table row result) ) ) (return-from execute_condition result) ) ) (defun get_tables (list_where id-s operations basic) "get tables that associate with certain condition " (let ((result '()) (iterator 0)) (loop for w in list_where do (progn (setq result (append result (list ( execute_condition basic w (nth iterator id-s) (nth iterator operations)) ))) (setq iterator (+ iterator 1)))) (return-from get_tables result) ) ) (defun intersect (smaller_t static_t) "intersections of tables" (let ((result (simple-table:make-table))) (simple-table:with-rows (smaller_t small_row) (simple-table:with-rows (static_t static_row) (if (equal (coerce small_row 'list) (coerce static_row 'list) ) (simple-table:add-to-table small_row result) ) ) ) (return-from intersect result) ) ) (defun union_cond (base_el tables_list) "union tables with certain conditions" (cond ((null tables_list) base_el) (t (if (< (simple-table:num-rows base_el) (simple-table:num-rows (car tables_list))) (union_cond (intersect base_el (car tables_list)) (cdr tables_list)) (union_cond (intersect (car tables_list) base_el) (cdr tables_list)))) ) ) (defun where (table-rows table-names statement &optional is_and is_or) "implementation of where operation" (let ((result (simple-table:make-table)) (id-s '()) (operations) (list_where) (tables)) ;; get list of conditions (setq list_where (get_where statement is_and is_or)) ;; get id-s of column that would be compare (setq id-s (init_id list_where table-names)) ;; get operations for all conditions (setq operations (define_operations list_where)) get tables that fits to one certain condition (setq tables (get_tables list_where id-s operations table-rows)) ;; get result table by intersection of all tables that we have (setq result (union_cond (car tables) (cdr tables))) (return-from where result) ) )
null
https://raw.githubusercontent.com/Ekatereana/CommonLispWorks/13111f7c45ec4d672dfdf3689ba22554d5c60727/where.lisp
lisp
get list of conditions get id-s of column that would be compare get operations for all conditions get result table by intersection of all tables that we have
(defun get_operation (symbol value) (cond ((string= symbol "=") (cond ((numberp value) #'=) ((stringp value) #'string=))) ((string= symbol ">") (cond ((numberp value) #'>) ((stringp value) #'string>))) ((string= symbol "<") (cond ((numberp value) #'<) ((stringp value) #'string<))) (t #'eq) ) ) (defstruct where-statement first_arg second_arg operation ) (defun is_column (row column) (position column row)) (defun read-where (stat) (let ((statement (coerce stat 'vector))) (make-where-statement :first_arg (aref statement 0) :second_arg (aref statement 2) :operation (aref statement 1) )) ) (defun where_multiply (statement separator) "split big query to list of single conditions" (let ((result '()) (temp '())) (loop for arg in statement do (cond ((string= arg separator) (progn (setq result (append result (list (read-where temp)))) (setq temp '()))) (t (setq temp (append temp (list arg)))) ) ) (setq result (append result (list (read-where temp)))) (return-from where_multiply result) ) ) (defun get_where (statement is_and is_or) "define separator (AND or OR)" (cond (is_and (where_multiply statement "and")) (is_or (where_multiply statement "or")) (t (list (read-where statement))))) (defun init_id (list_where table-names) (let ((id-s '() )) (loop for w in list_where do (setq id-s (append id-s (list (is_column table-names (read-from-string (where-statement-first_arg w))))))) (return-from init_id id-s) ) ) (defun define_operations (list_where) (let ((operations '())) (loop for w in list_where do( if (not (eq (read-from-string (where-statement-second_arg w)) 0)) (setq operations (append operations (list (get_operation (where-statement-operation w) (read-from-string (where-statement-second_arg w)))))) (setq operations (append operations (list (get_operation (where-statement-operation w) (where-statement-second_arg w))))) )) (return-from define_operations operations) ) ) (defun execute_condition ( rows condition id operation) "create table for one condition" (let ((result (simple-table:make-table))) (simple-table:with-rows (rows row) (if (funcall operation (simple-table:get-row-column id row) (read-from-string (where-statement-second_arg condition))) (simple-table:add-to-table row result) ) ) (return-from execute_condition result) ) ) (defun get_tables (list_where id-s operations basic) "get tables that associate with certain condition " (let ((result '()) (iterator 0)) (loop for w in list_where do (progn (setq result (append result (list ( execute_condition basic w (nth iterator id-s) (nth iterator operations)) ))) (setq iterator (+ iterator 1)))) (return-from get_tables result) ) ) (defun intersect (smaller_t static_t) "intersections of tables" (let ((result (simple-table:make-table))) (simple-table:with-rows (smaller_t small_row) (simple-table:with-rows (static_t static_row) (if (equal (coerce small_row 'list) (coerce static_row 'list) ) (simple-table:add-to-table small_row result) ) ) ) (return-from intersect result) ) ) (defun union_cond (base_el tables_list) "union tables with certain conditions" (cond ((null tables_list) base_el) (t (if (< (simple-table:num-rows base_el) (simple-table:num-rows (car tables_list))) (union_cond (intersect base_el (car tables_list)) (cdr tables_list)) (union_cond (intersect (car tables_list) base_el) (cdr tables_list)))) ) ) (defun where (table-rows table-names statement &optional is_and is_or) "implementation of where operation" (let ((result (simple-table:make-table)) (id-s '()) (operations) (list_where) (tables)) (setq list_where (get_where statement is_and is_or)) (setq id-s (init_id list_where table-names)) (setq operations (define_operations list_where)) get tables that fits to one certain condition (setq tables (get_tables list_where id-s operations table-rows)) (setq result (union_cond (car tables) (cdr tables))) (return-from where result) ) )
f9500933cc31090960cc3bb3b4f024f7670f3e7e432fe53554110147baac0937
2600hz/kazoo
knm_inum.erl
%%%----------------------------------------------------------------------------- ( C ) 2011 - 2020 , 2600Hz %%% @doc Carrier for inums @author @author This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(knm_inum). -behaviour(knm_gen_carrier). -export([info/0]). -export([is_local/0]). -export([find_numbers/3]). -export([acquire_number/1]). -export([disconnect_number/1]). -export([is_number_billable/1]). -export([should_lookup_cnam/0]). -export([check_numbers/1]). -export([generate_numbers/3]). -include("knm.hrl"). %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec info() -> map(). info() -> #{?CARRIER_INFO_MAX_PREFIX => 15 }. %%------------------------------------------------------------------------------ %% @doc Is this carrier handling numbers local to the system? %% %% <div class="notice">A non-local (foreign) carrier module makes HTTP requests.</div> %% @end %%------------------------------------------------------------------------------ -spec is_local() -> boolean(). is_local() -> 'true'. %%------------------------------------------------------------------------------ %% @doc Check with carrier if these numbers are registered with it. %% @end %%------------------------------------------------------------------------------ -spec check_numbers(kz_term:ne_binaries()) -> {'ok', kz_json:object()} | {'error', any()}. check_numbers(_Numbers) -> {'error', 'not_implemented'}. %%------------------------------------------------------------------------------ %% @doc Query the local system for a quantity of available numbers %% in a rate center %% @end %%------------------------------------------------------------------------------ -spec find_numbers(kz_term:ne_binary(), pos_integer(), knm_carriers:options()) -> knm_search:mod_response(). find_numbers(<<"+", _/binary>>=Prefix, Quantity, Options) -> AccountId = knm_carriers:account_id(Options), find_numbers_in_account(Prefix, Quantity, AccountId, Options); find_numbers(Prefix, Quantity, Options) -> find_numbers(<<"+",Prefix/binary>>, Quantity, Options). -spec find_numbers_in_account(kz_term:ne_binary(), pos_integer(), kz_term:api_ne_binary(), knm_carriers:options()) -> knm_search:mod_response(). find_numbers_in_account(_Prefix, _Quantity, 'undefined', _Options) -> {'ok', []}; find_numbers_in_account(Prefix, Quantity, AccountId, Options) -> Offset = knm_carriers:offset(Options), QID = knm_search:query_id(Options), case do_find_numbers_in_account(Prefix, Quantity, Offset, AccountId, QID) of {'error', 'not_available'} -> ResellerId = knm_carriers:reseller_id(Options), case AccountId =:= ResellerId of 'true' -> {'ok', []}; 'false' -> NewOptions = [{'offset', 0} | Options], find_numbers_in_account(Prefix, Quantity, ResellerId, NewOptions) end; Result -> Result end. -spec do_find_numbers_in_account(kz_term:ne_binary(), pos_integer(), non_neg_integer(), kz_term:ne_binary(), kz_term:ne_binary()) -> knm_search:mod_response(). do_find_numbers_in_account(Prefix, Quantity, Offset, AccountId, QID) -> ViewOptions = [{'startkey', [AccountId, ?NUMBER_STATE_AVAILABLE, Prefix]} ,{'endkey', [AccountId, ?NUMBER_STATE_AVAILABLE, <<Prefix/binary,"\ufff0">>]} ,{'limit', Quantity} ,{'skip', Offset} ,'include_docs' ], case kz_datamgr:get_results(?KZ_INUM_DB, <<"numbers_inum/status">>, ViewOptions) of {'ok', []} -> lager:debug("found no available inum numbers for account ~s", [AccountId]), {'error', 'not_available'}; {'ok', JObjs} -> lager:debug("found available inum numbers for account ~s", [AccountId]), {'ok', format_numbers_resp(QID, JObjs)}; {'error', _R} -> lager:debug("failed to lookup available local numbers: ~p", [_R]), {'error', 'datastore_fault'} end. -spec format_numbers_resp(kz_term:ne_binary(), kz_json:objects()) -> knm_search:results(). format_numbers_resp(QID, JObjs) -> [{QID, {Num, ?MODULE, ?NUMBER_STATE_AVAILABLE, kz_json:new()}} || JObj <- JObjs, Num <- [kz_doc:id(kz_json:get_value(<<"doc">>, JObj))] ]. %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec is_number_billable(knm_phone_number:record()) -> boolean(). is_number_billable(_PN) -> 'false'. %%------------------------------------------------------------------------------ %% @doc Acquire a given number from the carrier %% @end %%------------------------------------------------------------------------------ -spec acquire_number(knm_phone_number:record()) -> knm_phone_number:record(). acquire_number(PN) -> lager:debug("acquiring number ~s", [knm_phone_number:number(PN)]), update_doc(PN, [{kzd_phone_numbers:pvt_state_path(), knm_phone_number:state(PN)} ,{kzd_phone_numbers:pvt_assigned_to_path(), knm_phone_number:assigned_to(PN)} ]). %%------------------------------------------------------------------------------ %% @doc Release a number from the routing table %% @end %%------------------------------------------------------------------------------ -spec disconnect_number(knm_phone_number:record()) -> knm_phone_number:record(). disconnect_number(PN) -> lager:debug("disconnect number ~s in managed provider" ,[knm_phone_number:number(PN)] ), update_doc(PN, [{kzd_phone_numbers:pvt_state_path(), ?NUMBER_STATE_RELEASED} ,{kzd_phone_numbers:pvt_assigned_to_path(), 'null'} ,{kzd_phone_numbers:pvt_reserve_history_path(), []} ]). -spec generate_numbers(kz_term:ne_binary(), pos_integer(), non_neg_integer()) -> 'ok'. generate_numbers(AccountId, <<"8835100",_/binary>> = Number, Quantity) when byte_size(Number) =:= 15 -> generate_numbers(AccountId, kz_term:to_integer(Number), kz_term:to_integer(Quantity)); generate_numbers(_AccountId, _Number, 0) -> 'ok'; generate_numbers(?MATCH_ACCOUNT_RAW(AccountId), Number, Quantity) when is_integer(Number), is_integer(Quantity), Quantity > 0 -> _R = save_doc(AccountId, <<"+",(kz_term:to_binary(Number))/binary>>), lager:info("number ~p/~p/~p", [Number, Quantity, _R]), generate_numbers(AccountId, Number+1, Quantity-1). -spec save_doc(kz_term:ne_binary(), kz_term:ne_binary()) -> {'ok', kz_json:object()} | {'error', any()}. save_doc(AccountId, Number) -> Setters = [{fun kzd_phone_numbers:set_pvt_module_name/2, kz_term:to_binary(?MODULE)} ,{fun kzd_phone_numbers:set_pvt_state/2, ?NUMBER_STATE_AVAILABLE} ], PvtOptions = [{'account_id', AccountId} ,{'id', knm_converters:normalize(Number)} ,{'type', kzd_phone_numbers:type()} ], kz_datamgr:save_doc(?KZ_INUM_DB, kz_doc:update_pvt_parameters(kz_doc:setters(Setters), 'undefined', PvtOptions)). -spec update_doc(knm_phone_number:record(), kz_term:proplist()) -> knm_phone_number:record(). update_doc(PN, UpdateProps) -> Num = knm_phone_number:number(PN), Updates = [{kzd_phone_numbers:pvt_module_name_path(), kz_term:to_binary(?MODULE)} | UpdateProps ], UpdateOptions = [{'update', Updates}], case kz_datamgr:update_doc(?KZ_INUM_DB, Num, UpdateOptions) of {'ok', _UpdatedDoc} -> PN; {'error', Reason} -> knm_errors:database_error(Reason, PN) end. %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec should_lookup_cnam() -> 'true'. should_lookup_cnam() -> 'true'.
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_numbers/src/carriers/knm_inum.erl
erlang
----------------------------------------------------------------------------- @doc Carrier for inums @end ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Is this carrier handling numbers local to the system? <div class="notice">A non-local (foreign) carrier module makes HTTP requests.</div> @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Check with carrier if these numbers are registered with it. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Query the local system for a quantity of available numbers in a rate center @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Acquire a given number from the carrier @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Release a number from the routing table @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------
( C ) 2011 - 2020 , 2600Hz @author @author This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(knm_inum). -behaviour(knm_gen_carrier). -export([info/0]). -export([is_local/0]). -export([find_numbers/3]). -export([acquire_number/1]). -export([disconnect_number/1]). -export([is_number_billable/1]). -export([should_lookup_cnam/0]). -export([check_numbers/1]). -export([generate_numbers/3]). -include("knm.hrl"). -spec info() -> map(). info() -> #{?CARRIER_INFO_MAX_PREFIX => 15 }. -spec is_local() -> boolean(). is_local() -> 'true'. -spec check_numbers(kz_term:ne_binaries()) -> {'ok', kz_json:object()} | {'error', any()}. check_numbers(_Numbers) -> {'error', 'not_implemented'}. -spec find_numbers(kz_term:ne_binary(), pos_integer(), knm_carriers:options()) -> knm_search:mod_response(). find_numbers(<<"+", _/binary>>=Prefix, Quantity, Options) -> AccountId = knm_carriers:account_id(Options), find_numbers_in_account(Prefix, Quantity, AccountId, Options); find_numbers(Prefix, Quantity, Options) -> find_numbers(<<"+",Prefix/binary>>, Quantity, Options). -spec find_numbers_in_account(kz_term:ne_binary(), pos_integer(), kz_term:api_ne_binary(), knm_carriers:options()) -> knm_search:mod_response(). find_numbers_in_account(_Prefix, _Quantity, 'undefined', _Options) -> {'ok', []}; find_numbers_in_account(Prefix, Quantity, AccountId, Options) -> Offset = knm_carriers:offset(Options), QID = knm_search:query_id(Options), case do_find_numbers_in_account(Prefix, Quantity, Offset, AccountId, QID) of {'error', 'not_available'} -> ResellerId = knm_carriers:reseller_id(Options), case AccountId =:= ResellerId of 'true' -> {'ok', []}; 'false' -> NewOptions = [{'offset', 0} | Options], find_numbers_in_account(Prefix, Quantity, ResellerId, NewOptions) end; Result -> Result end. -spec do_find_numbers_in_account(kz_term:ne_binary(), pos_integer(), non_neg_integer(), kz_term:ne_binary(), kz_term:ne_binary()) -> knm_search:mod_response(). do_find_numbers_in_account(Prefix, Quantity, Offset, AccountId, QID) -> ViewOptions = [{'startkey', [AccountId, ?NUMBER_STATE_AVAILABLE, Prefix]} ,{'endkey', [AccountId, ?NUMBER_STATE_AVAILABLE, <<Prefix/binary,"\ufff0">>]} ,{'limit', Quantity} ,{'skip', Offset} ,'include_docs' ], case kz_datamgr:get_results(?KZ_INUM_DB, <<"numbers_inum/status">>, ViewOptions) of {'ok', []} -> lager:debug("found no available inum numbers for account ~s", [AccountId]), {'error', 'not_available'}; {'ok', JObjs} -> lager:debug("found available inum numbers for account ~s", [AccountId]), {'ok', format_numbers_resp(QID, JObjs)}; {'error', _R} -> lager:debug("failed to lookup available local numbers: ~p", [_R]), {'error', 'datastore_fault'} end. -spec format_numbers_resp(kz_term:ne_binary(), kz_json:objects()) -> knm_search:results(). format_numbers_resp(QID, JObjs) -> [{QID, {Num, ?MODULE, ?NUMBER_STATE_AVAILABLE, kz_json:new()}} || JObj <- JObjs, Num <- [kz_doc:id(kz_json:get_value(<<"doc">>, JObj))] ]. -spec is_number_billable(knm_phone_number:record()) -> boolean(). is_number_billable(_PN) -> 'false'. -spec acquire_number(knm_phone_number:record()) -> knm_phone_number:record(). acquire_number(PN) -> lager:debug("acquiring number ~s", [knm_phone_number:number(PN)]), update_doc(PN, [{kzd_phone_numbers:pvt_state_path(), knm_phone_number:state(PN)} ,{kzd_phone_numbers:pvt_assigned_to_path(), knm_phone_number:assigned_to(PN)} ]). -spec disconnect_number(knm_phone_number:record()) -> knm_phone_number:record(). disconnect_number(PN) -> lager:debug("disconnect number ~s in managed provider" ,[knm_phone_number:number(PN)] ), update_doc(PN, [{kzd_phone_numbers:pvt_state_path(), ?NUMBER_STATE_RELEASED} ,{kzd_phone_numbers:pvt_assigned_to_path(), 'null'} ,{kzd_phone_numbers:pvt_reserve_history_path(), []} ]). -spec generate_numbers(kz_term:ne_binary(), pos_integer(), non_neg_integer()) -> 'ok'. generate_numbers(AccountId, <<"8835100",_/binary>> = Number, Quantity) when byte_size(Number) =:= 15 -> generate_numbers(AccountId, kz_term:to_integer(Number), kz_term:to_integer(Quantity)); generate_numbers(_AccountId, _Number, 0) -> 'ok'; generate_numbers(?MATCH_ACCOUNT_RAW(AccountId), Number, Quantity) when is_integer(Number), is_integer(Quantity), Quantity > 0 -> _R = save_doc(AccountId, <<"+",(kz_term:to_binary(Number))/binary>>), lager:info("number ~p/~p/~p", [Number, Quantity, _R]), generate_numbers(AccountId, Number+1, Quantity-1). -spec save_doc(kz_term:ne_binary(), kz_term:ne_binary()) -> {'ok', kz_json:object()} | {'error', any()}. save_doc(AccountId, Number) -> Setters = [{fun kzd_phone_numbers:set_pvt_module_name/2, kz_term:to_binary(?MODULE)} ,{fun kzd_phone_numbers:set_pvt_state/2, ?NUMBER_STATE_AVAILABLE} ], PvtOptions = [{'account_id', AccountId} ,{'id', knm_converters:normalize(Number)} ,{'type', kzd_phone_numbers:type()} ], kz_datamgr:save_doc(?KZ_INUM_DB, kz_doc:update_pvt_parameters(kz_doc:setters(Setters), 'undefined', PvtOptions)). -spec update_doc(knm_phone_number:record(), kz_term:proplist()) -> knm_phone_number:record(). update_doc(PN, UpdateProps) -> Num = knm_phone_number:number(PN), Updates = [{kzd_phone_numbers:pvt_module_name_path(), kz_term:to_binary(?MODULE)} | UpdateProps ], UpdateOptions = [{'update', Updates}], case kz_datamgr:update_doc(?KZ_INUM_DB, Num, UpdateOptions) of {'ok', _UpdatedDoc} -> PN; {'error', Reason} -> knm_errors:database_error(Reason, PN) end. -spec should_lookup_cnam() -> 'true'. should_lookup_cnam() -> 'true'.
eaea0eb5299d2e873543e481e1cd59fcf4ceb546d2c7d99ed27d5129f2b575dc
lmj/lparallel
defpun.lisp
Copyright ( c ) 2014 , . All rights reserved . ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials provided ;;; with the distribution. ;;; ;;; * Neither the name of the project nor the names of its ;;; contributors may be used to endorse or promote products derived ;;; from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (defpackage #:lparallel.defpun (:documentation "Fine-grained parallelism.") (:use #:cl #:lparallel.util #:lparallel.kernel #:lparallel.thread-util #:lparallel.slet) (:export #:defpun #:defpun* #:defpun/type #:defpun/type* #:declaim-defpun #:plet #:plet-if #:slet) (:import-from #:alexandria #:simple-style-warning) (:import-from #:lparallel.util #:symbolicate/package) (:import-from #:lparallel.slet #:make-binding-data #:parse-bindings) (:import-from #:lparallel.kernel #:*worker* #:*make-limiter-data* #:kernel #:use-caller-p #:unwrap-result #:call-with-task-handler #:limiter-accept-task-p #:limiter-count #:limiter-lock #:submit-raw-task #:make-task #:task-lambda #:wrapped-error #:with-task-context #:steal-work)) (in-package #:lparallel.defpun) ;;;; function registration defpun relies upon the inlined accept - task - p call in order to ;;; achieve speedup, which means that *kernel* must exist before the ;;; call takes place. If *kernel* is nil, the error may be confusing ;;; due to inlining and optimizations. Inserting `check-kernel' into the body of defpun functions negates the speedup for small ;;; functions. ;;; ;;; Thus for user-friendliness we define checked and unchecked ;;; functions for each defpun form. The user calls the checked version ; defpun calls the unchecked one via a macrolet . ;;; ;;; The macrolets also have the happy side-effect of preventing ;;; reference to the checked (slower) function via #'. ;;; ;;; We store references to the checked and unchecked functions in order to detect redefinitions with defun or otherwise . (defconstant +checked-key+ 'checked-key) (defconstant +unchecked-key+ 'unchecked-key) (defvar *registered-names* nil) (defvar *registration-lock* (make-lock)) (defun unchecked-name (name) ;; We could intern this into a private package and maintain an alist ;; of (public . private) package pairs, but that seems ;; over-engineered. Anonymous packages don't exist anyway. (symbolicate/package (symbol-package name) '#:%%%%.defpun. name) ) (defun register-name (name) (pushnew name *registered-names*)) (defun register-fn (name) (setf (get name +checked-key+) (symbol-function name)) (setf (get name +unchecked-key+) (symbol-function (unchecked-name name)))) (defun registered-fn-p (name) (get name +checked-key+)) (defun valid-registered-fn-p (name) (and (fboundp name) (eq (symbol-function name) (get name +checked-key+)) (fboundp (unchecked-name name)) (eq (symbol-function (unchecked-name name)) (get name +unchecked-key+)))) ;;; a name may be registered without having a corresponding function (defun valid-registered-name-p (name) (and (symbol-package name) (or (not (registered-fn-p name)) (valid-registered-fn-p name)))) (defun delete-stale-registrations () (setf *registered-names* (remove-if-not #'valid-registered-name-p *registered-names*))) (defun registered-macrolets (kernel) (loop for name in *registered-names* collect `(,name (&rest args) `(,',(unchecked-name name) ,',kernel ,@args)))) (defmacro declaim-defpun (&rest names) "See `defpun'." This is used outside of the defpun macro . `(eval-when (:compile-toplevel :load-toplevel :execute) (with-lock-held (*registration-lock*) ,@(loop for name in names collect `(register-name ',name))))) (defun delete-registered-names (names) This is used outside of the defpun macro . (with-lock-held (*registration-lock*) (setf *registered-names* (set-difference *registered-names* names)))) ;;;; limiter ;;; New tasks are accepted when limiter-count is positive. Creating a ;;; task decrements limiter-count; finishing a task increments it. (defun initial-limiter-count (thread-count) (+ thread-count 1)) (defun make-limiter-data (thread-count) (list :limiter-accept-task-p t :limiter-count (initial-limiter-count thread-count) :limiter-lock (make-spin-lock))) (setf *make-limiter-data* 'make-limiter-data) (defmacro accept-task-p (kernel) (check-type kernel symbol) `(locally (declare #.*full-optimize*) (limiter-accept-task-p (the kernel ,kernel)))) (defun/type update-limiter-count/no-lock (kernel delta) (kernel fixnum) (values) (declare #.*full-optimize*) (incf (limiter-count kernel) delta) (setf (limiter-accept-task-p kernel) (to-boolean (plusp (the fixnum (limiter-count kernel))))) (values)) (defun/type update-limiter-count (kernel delta) (kernel fixnum) (values) (declare #.*full-optimize*) (with-spin-lock-held ((limiter-lock kernel)) (update-limiter-count/no-lock kernel delta)) (values)) ;;;; plet (defconstant +no-result+ 'no-result) (defmacro msetq (vars form) (if (= 1 (length vars)) `(setq ,(first vars) ,form) `(multiple-value-setq ,vars ,form))) (defun client-vars (binding-data) (reduce #'append binding-data :key #'first)) (defun temp-vars (binding-data) (reduce #'append binding-data :key #'second)) (defun primary-temp-vars (binding-data) (loop for (nil temp-vars nil) in binding-data collect (first temp-vars))) (defmacro with-temp-bindings (here-binding-datum spawn-binding-data &body body) `(let (,@(temp-vars (list here-binding-datum)) ,@(loop for var in (temp-vars spawn-binding-data) collect `(,var +no-result+))) ,@body)) (defmacro with-client-bindings (binding-data null-bindings &body body) `(let (,@null-bindings ,@(mapcar #'list (client-vars binding-data) (temp-vars binding-data))) ,@body)) (defmacro spawn (kernel temp-vars form) (check-type kernel symbol) `(submit-raw-task (make-task (task-lambda ;; task handler already established (unwind-protect (msetq ,temp-vars (with-task-context ,form)) (locally (declare #.*full-optimize*) (update-limiter-count (the kernel ,kernel) 1))) (values))) ,kernel)) (defmacro spawn-tasks (kernel spawn-binding-data) (check-type kernel symbol) `(progn ,@(loop for (nil temp-vars form) in spawn-binding-data collect `(spawn ,kernel ,temp-vars ,form)))) (defmacro exec-task (here-binding-datum) (destructuring-bind (client-vars temp-vars form) here-binding-datum (declare (ignore client-vars)) `(msetq ,temp-vars ,form))) (defmacro sync (kernel spawn-binding-data) (check-type kernel symbol) reverse to check last spawn first (let ((temp-vars (reverse (temp-vars spawn-binding-data)))) `(locally (declare #.*full-optimize*) (loop with worker = *worker* while (or ,@(loop for temp-var in temp-vars collect `(eq ,temp-var +no-result+))) do #+lparallel.with-green-threads (thread-yield) (steal-work (the kernel ,kernel) worker))))) (defmacro scan-for-errors (binding-data) ;; a wrapped error would only appear as the primary return value `(locally (declare #.*full-optimize*) ,@(loop for temp-var in (primary-temp-vars binding-data) collect `(when (typep ,temp-var 'wrapped-error) (unwrap-result ,temp-var))))) (defmacro %%%%plet (kernel bindings body) (multiple-value-bind (binding-data null-bindings) (make-binding-data bindings) (destructuring-bind (here-binding-datum &rest spawn-binding-data) binding-data `(with-temp-bindings ,here-binding-datum ,spawn-binding-data (spawn-tasks ,kernel ,spawn-binding-data) (exec-task ,here-binding-datum) (sync ,kernel ,spawn-binding-data) (scan-for-errors ,spawn-binding-data) (with-client-bindings ,binding-data ,null-bindings ,@body))))) (defmacro with-lock-predicates (&key lock predicate1 predicate2 succeed/lock succeed/no-lock fail) (with-gensyms (top fail-tag) `(block ,top (tagbody (when ,predicate1 (with-spin-lock-held (,lock) (if ,predicate2 ,succeed/lock (go ,fail-tag))) (return-from ,top ,succeed/no-lock)) ,fail-tag (return-from ,top ,fail))))) (defmacro %%%plet (kernel predicate spawn-count bindings body) ;; Putting the body code into a shared dynamic-extent function ;; caused some slowdown, so reluctantly duplicate the body. `(with-lock-predicates :lock (limiter-lock (the kernel ,kernel)) :predicate1 ,predicate :predicate2 (accept-task-p ,kernel) :succeed/lock (update-limiter-count/no-lock ,kernel ,(- spawn-count)) :succeed/no-lock (%%%%plet ,kernel ,bindings ,body) :fail (slet ,bindings ,@body))) (defmacro %%plet (kernel predicate bindings body) (let ((spawn-count (- (length (parse-bindings bindings)) 1))) (if (plusp spawn-count) `(%%%plet ,kernel ,predicate ,spawn-count ,bindings ,body) `(slet ,bindings ,@body)))) (defmacro %plet (kernel bindings &body body) `(%%plet ,kernel (accept-task-p ,kernel) ,bindings ,body)) (defmacro %plet-if (kernel predicate bindings &body body) `(%%plet ,kernel (and (accept-task-p ,kernel) ,predicate) ,bindings ,body)) defpun (defmacro defun/wrapper (wrapper-name impl-name lambda-list &body body) (with-gensyms (args kernel) (multiple-value-bind (wrapper-lambda-list expansion) (if (intersection lambda-list lambda-list-keywords) (values `(&rest ,args) ``(apply (function ,',impl-name) ,,kernel ,',args)) (values lambda-list ``(,',impl-name ,,kernel ,@',lambda-list))) `(defun ,wrapper-name ,wrapper-lambda-list (macrolet ((call-impl (,kernel) ,expansion)) ,@body))))) (defun call-with-toplevel-handler (fn) (declare #.*full-optimize*) (declare (type function fn)) (let* ((results (multiple-value-list (call-with-task-handler fn))) (first (first results))) (when (typep first 'wrapped-error) (unwrap-result first)) (values-list results))) (defun call-inside-worker (kernel fn) (declare #.*full-optimize*) (declare (type function fn)) (let ((channel (let ((*kernel* kernel)) (make-channel)))) (submit-task channel (lambda () (multiple-value-list (funcall fn)))) (values-list (receive-result channel)))) (defun call-impl-fn (kernel impl) (declare #.*full-optimize*) (declare (type function impl)) (if (or *worker* (use-caller-p kernel)) (call-with-toplevel-handler impl) (call-inside-worker kernel impl))) (defmacro define-defpun (defpun doc defun &rest types) `(defmacro ,defpun (name lambda-list ,@types &body body) ,doc (with-parsed-body (body declares docstring) (with-lock-held (*registration-lock*) these two calls may affect the registered macrolets in the ;; return form below (delete-stale-registrations) (register-name name) (with-gensyms (kernel) `(progn (,',defun ,(unchecked-name name) (,kernel ,@lambda-list) ,,@(unsplice (when types ``(kernel ,@,(first types)))) ,,@(unsplice (when types (second types))) ,@declares (declare (ignorable ,kernel)) (macrolet ((plet (bindings &body body) `(%plet ,',kernel ,bindings ,@body)) (plet-if (predicate bindings &body body) `(%plet-if ,',kernel ,predicate ,bindings ,@body)) ,@(registered-macrolets kernel)) ,@body)) (defun/wrapper ,name ,(unchecked-name name) ,lambda-list ,@(unsplice docstring) (let ((,kernel (check-kernel))) (call-impl-fn ,kernel (lambda () (call-impl ,kernel))))) (eval-when (:load-toplevel :execute) (with-lock-held (*registration-lock*) (register-fn ',name))) ',name)))))) (define-defpun defpun "`defpun' defines a function which is specially geared for fine-grained parallelism. If you have many small tasks which bog down the system, `defpun' may help. The syntax of `defpun' matches that of `defun'. The difference is that `plet' and `plet-if' take on new meaning inside `defpun'. The symbols in the binding positions of `plet' and `plet-if' should be viewed as lazily evaluated immutable references. Inside a `defpun' form the name of the function being defined is a macrolet, as are the names of other functions which were defined by `defpun'. Thus using #' on them is an error. Calls to functions defined by `defpun' entail more overhead when the caller lies outside a `defpun' form. A `defpun' function must exist before it is referenced inside another `defpun' function. If this is not possible--for example if func1 and func2 reference each other--then use `declaim-defpun' to specify intent: (declaim-defpun func1 func2) " defun) (define-defpun defpun/type "Typed version of `defpun'. `arg-types' is an unevaluated list of argument types. `return-type' is an unevaluated form of the return type, possibly indicating multiple values as in (values fixnum float). \(As a technical point, if `return-type' contains no lambda list keywords then the return type given to ftype will be additionally constrained to match the number of return values specified.)" defun/type arg-types return-type) (defmacro defpun* (&rest args) "Deprecated. Instead use `defpun' and pass `:use-caller t' to `make-kernel'." (simple-style-warning "`defpun*' is deprecated. Instead use `defpun' and pass ~ `:use-caller t' to `make-kernel'.") `(defpun ,@args)) (defmacro defpun/type* (&rest args) "Deprecated. Instead use `defpun/type' and pass `:use-caller t' to `make-kernel'." (simple-style-warning "`defpun/type*' is deprecated. Instead use `defpun/type' and pass ~ `:use-caller t' to `make-kernel'.") `(defpun/type ,@args))
null
https://raw.githubusercontent.com/lmj/lparallel/9c11f40018155a472c540b63684049acc9b36e15/src/defpun.lisp
lisp
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. function registration achieve speedup, which means that *kernel* must exist before the call takes place. If *kernel* is nil, the error may be confusing due to inlining and optimizations. Inserting `check-kernel' into functions. Thus for user-friendliness we define checked and unchecked functions for each defpun form. The user calls the checked defpun calls the unchecked one via a macrolet . The macrolets also have the happy side-effect of preventing reference to the checked (slower) function via #'. We store references to the checked and unchecked functions in We could intern this into a private package and maintain an alist of (public . private) package pairs, but that seems over-engineered. Anonymous packages don't exist anyway. a name may be registered without having a corresponding function limiter New tasks are accepted when limiter-count is positive. Creating a task decrements limiter-count; finishing a task increments it. plet task handler already established a wrapped error would only appear as the primary return value Putting the body code into a shared dynamic-extent function caused some slowdown, so reluctantly duplicate the body. return form below
Copyright ( c ) 2014 , . All rights reserved . " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (defpackage #:lparallel.defpun (:documentation "Fine-grained parallelism.") (:use #:cl #:lparallel.util #:lparallel.kernel #:lparallel.thread-util #:lparallel.slet) (:export #:defpun #:defpun* #:defpun/type #:defpun/type* #:declaim-defpun #:plet #:plet-if #:slet) (:import-from #:alexandria #:simple-style-warning) (:import-from #:lparallel.util #:symbolicate/package) (:import-from #:lparallel.slet #:make-binding-data #:parse-bindings) (:import-from #:lparallel.kernel #:*worker* #:*make-limiter-data* #:kernel #:use-caller-p #:unwrap-result #:call-with-task-handler #:limiter-accept-task-p #:limiter-count #:limiter-lock #:submit-raw-task #:make-task #:task-lambda #:wrapped-error #:with-task-context #:steal-work)) (in-package #:lparallel.defpun) defpun relies upon the inlined accept - task - p call in order to the body of defpun functions negates the speedup for small order to detect redefinitions with defun or otherwise . (defconstant +checked-key+ 'checked-key) (defconstant +unchecked-key+ 'unchecked-key) (defvar *registered-names* nil) (defvar *registration-lock* (make-lock)) (defun unchecked-name (name) (symbolicate/package (symbol-package name) '#:%%%%.defpun. name) ) (defun register-name (name) (pushnew name *registered-names*)) (defun register-fn (name) (setf (get name +checked-key+) (symbol-function name)) (setf (get name +unchecked-key+) (symbol-function (unchecked-name name)))) (defun registered-fn-p (name) (get name +checked-key+)) (defun valid-registered-fn-p (name) (and (fboundp name) (eq (symbol-function name) (get name +checked-key+)) (fboundp (unchecked-name name)) (eq (symbol-function (unchecked-name name)) (get name +unchecked-key+)))) (defun valid-registered-name-p (name) (and (symbol-package name) (or (not (registered-fn-p name)) (valid-registered-fn-p name)))) (defun delete-stale-registrations () (setf *registered-names* (remove-if-not #'valid-registered-name-p *registered-names*))) (defun registered-macrolets (kernel) (loop for name in *registered-names* collect `(,name (&rest args) `(,',(unchecked-name name) ,',kernel ,@args)))) (defmacro declaim-defpun (&rest names) "See `defpun'." This is used outside of the defpun macro . `(eval-when (:compile-toplevel :load-toplevel :execute) (with-lock-held (*registration-lock*) ,@(loop for name in names collect `(register-name ',name))))) (defun delete-registered-names (names) This is used outside of the defpun macro . (with-lock-held (*registration-lock*) (setf *registered-names* (set-difference *registered-names* names)))) (defun initial-limiter-count (thread-count) (+ thread-count 1)) (defun make-limiter-data (thread-count) (list :limiter-accept-task-p t :limiter-count (initial-limiter-count thread-count) :limiter-lock (make-spin-lock))) (setf *make-limiter-data* 'make-limiter-data) (defmacro accept-task-p (kernel) (check-type kernel symbol) `(locally (declare #.*full-optimize*) (limiter-accept-task-p (the kernel ,kernel)))) (defun/type update-limiter-count/no-lock (kernel delta) (kernel fixnum) (values) (declare #.*full-optimize*) (incf (limiter-count kernel) delta) (setf (limiter-accept-task-p kernel) (to-boolean (plusp (the fixnum (limiter-count kernel))))) (values)) (defun/type update-limiter-count (kernel delta) (kernel fixnum) (values) (declare #.*full-optimize*) (with-spin-lock-held ((limiter-lock kernel)) (update-limiter-count/no-lock kernel delta)) (values)) (defconstant +no-result+ 'no-result) (defmacro msetq (vars form) (if (= 1 (length vars)) `(setq ,(first vars) ,form) `(multiple-value-setq ,vars ,form))) (defun client-vars (binding-data) (reduce #'append binding-data :key #'first)) (defun temp-vars (binding-data) (reduce #'append binding-data :key #'second)) (defun primary-temp-vars (binding-data) (loop for (nil temp-vars nil) in binding-data collect (first temp-vars))) (defmacro with-temp-bindings (here-binding-datum spawn-binding-data &body body) `(let (,@(temp-vars (list here-binding-datum)) ,@(loop for var in (temp-vars spawn-binding-data) collect `(,var +no-result+))) ,@body)) (defmacro with-client-bindings (binding-data null-bindings &body body) `(let (,@null-bindings ,@(mapcar #'list (client-vars binding-data) (temp-vars binding-data))) ,@body)) (defmacro spawn (kernel temp-vars form) (check-type kernel symbol) `(submit-raw-task (make-task (task-lambda (unwind-protect (msetq ,temp-vars (with-task-context ,form)) (locally (declare #.*full-optimize*) (update-limiter-count (the kernel ,kernel) 1))) (values))) ,kernel)) (defmacro spawn-tasks (kernel spawn-binding-data) (check-type kernel symbol) `(progn ,@(loop for (nil temp-vars form) in spawn-binding-data collect `(spawn ,kernel ,temp-vars ,form)))) (defmacro exec-task (here-binding-datum) (destructuring-bind (client-vars temp-vars form) here-binding-datum (declare (ignore client-vars)) `(msetq ,temp-vars ,form))) (defmacro sync (kernel spawn-binding-data) (check-type kernel symbol) reverse to check last spawn first (let ((temp-vars (reverse (temp-vars spawn-binding-data)))) `(locally (declare #.*full-optimize*) (loop with worker = *worker* while (or ,@(loop for temp-var in temp-vars collect `(eq ,temp-var +no-result+))) do #+lparallel.with-green-threads (thread-yield) (steal-work (the kernel ,kernel) worker))))) (defmacro scan-for-errors (binding-data) `(locally (declare #.*full-optimize*) ,@(loop for temp-var in (primary-temp-vars binding-data) collect `(when (typep ,temp-var 'wrapped-error) (unwrap-result ,temp-var))))) (defmacro %%%%plet (kernel bindings body) (multiple-value-bind (binding-data null-bindings) (make-binding-data bindings) (destructuring-bind (here-binding-datum &rest spawn-binding-data) binding-data `(with-temp-bindings ,here-binding-datum ,spawn-binding-data (spawn-tasks ,kernel ,spawn-binding-data) (exec-task ,here-binding-datum) (sync ,kernel ,spawn-binding-data) (scan-for-errors ,spawn-binding-data) (with-client-bindings ,binding-data ,null-bindings ,@body))))) (defmacro with-lock-predicates (&key lock predicate1 predicate2 succeed/lock succeed/no-lock fail) (with-gensyms (top fail-tag) `(block ,top (tagbody (when ,predicate1 (with-spin-lock-held (,lock) (if ,predicate2 ,succeed/lock (go ,fail-tag))) (return-from ,top ,succeed/no-lock)) ,fail-tag (return-from ,top ,fail))))) (defmacro %%%plet (kernel predicate spawn-count bindings body) `(with-lock-predicates :lock (limiter-lock (the kernel ,kernel)) :predicate1 ,predicate :predicate2 (accept-task-p ,kernel) :succeed/lock (update-limiter-count/no-lock ,kernel ,(- spawn-count)) :succeed/no-lock (%%%%plet ,kernel ,bindings ,body) :fail (slet ,bindings ,@body))) (defmacro %%plet (kernel predicate bindings body) (let ((spawn-count (- (length (parse-bindings bindings)) 1))) (if (plusp spawn-count) `(%%%plet ,kernel ,predicate ,spawn-count ,bindings ,body) `(slet ,bindings ,@body)))) (defmacro %plet (kernel bindings &body body) `(%%plet ,kernel (accept-task-p ,kernel) ,bindings ,body)) (defmacro %plet-if (kernel predicate bindings &body body) `(%%plet ,kernel (and (accept-task-p ,kernel) ,predicate) ,bindings ,body)) defpun (defmacro defun/wrapper (wrapper-name impl-name lambda-list &body body) (with-gensyms (args kernel) (multiple-value-bind (wrapper-lambda-list expansion) (if (intersection lambda-list lambda-list-keywords) (values `(&rest ,args) ``(apply (function ,',impl-name) ,,kernel ,',args)) (values lambda-list ``(,',impl-name ,,kernel ,@',lambda-list))) `(defun ,wrapper-name ,wrapper-lambda-list (macrolet ((call-impl (,kernel) ,expansion)) ,@body))))) (defun call-with-toplevel-handler (fn) (declare #.*full-optimize*) (declare (type function fn)) (let* ((results (multiple-value-list (call-with-task-handler fn))) (first (first results))) (when (typep first 'wrapped-error) (unwrap-result first)) (values-list results))) (defun call-inside-worker (kernel fn) (declare #.*full-optimize*) (declare (type function fn)) (let ((channel (let ((*kernel* kernel)) (make-channel)))) (submit-task channel (lambda () (multiple-value-list (funcall fn)))) (values-list (receive-result channel)))) (defun call-impl-fn (kernel impl) (declare #.*full-optimize*) (declare (type function impl)) (if (or *worker* (use-caller-p kernel)) (call-with-toplevel-handler impl) (call-inside-worker kernel impl))) (defmacro define-defpun (defpun doc defun &rest types) `(defmacro ,defpun (name lambda-list ,@types &body body) ,doc (with-parsed-body (body declares docstring) (with-lock-held (*registration-lock*) these two calls may affect the registered macrolets in the (delete-stale-registrations) (register-name name) (with-gensyms (kernel) `(progn (,',defun ,(unchecked-name name) (,kernel ,@lambda-list) ,,@(unsplice (when types ``(kernel ,@,(first types)))) ,,@(unsplice (when types (second types))) ,@declares (declare (ignorable ,kernel)) (macrolet ((plet (bindings &body body) `(%plet ,',kernel ,bindings ,@body)) (plet-if (predicate bindings &body body) `(%plet-if ,',kernel ,predicate ,bindings ,@body)) ,@(registered-macrolets kernel)) ,@body)) (defun/wrapper ,name ,(unchecked-name name) ,lambda-list ,@(unsplice docstring) (let ((,kernel (check-kernel))) (call-impl-fn ,kernel (lambda () (call-impl ,kernel))))) (eval-when (:load-toplevel :execute) (with-lock-held (*registration-lock*) (register-fn ',name))) ',name)))))) (define-defpun defpun "`defpun' defines a function which is specially geared for fine-grained parallelism. If you have many small tasks which bog down the system, `defpun' may help. The syntax of `defpun' matches that of `defun'. The difference is that `plet' and `plet-if' take on new meaning inside `defpun'. The symbols in the binding positions of `plet' and `plet-if' should be viewed as lazily evaluated immutable references. Inside a `defpun' form the name of the function being defined is a macrolet, as are the names of other functions which were defined by `defpun'. Thus using #' on them is an error. Calls to functions defined by `defpun' entail more overhead when the caller lies outside a `defpun' form. A `defpun' function must exist before it is referenced inside another `defpun' function. If this is not possible--for example if func1 and func2 reference each other--then use `declaim-defpun' to specify intent: (declaim-defpun func1 func2) " defun) (define-defpun defpun/type "Typed version of `defpun'. `arg-types' is an unevaluated list of argument types. `return-type' is an unevaluated form of the return type, possibly indicating multiple values as in (values fixnum float). \(As a technical point, if `return-type' contains no lambda list keywords then the return type given to ftype will be additionally constrained to match the number of return values specified.)" defun/type arg-types return-type) (defmacro defpun* (&rest args) "Deprecated. Instead use `defpun' and pass `:use-caller t' to `make-kernel'." (simple-style-warning "`defpun*' is deprecated. Instead use `defpun' and pass ~ `:use-caller t' to `make-kernel'.") `(defpun ,@args)) (defmacro defpun/type* (&rest args) "Deprecated. Instead use `defpun/type' and pass `:use-caller t' to `make-kernel'." (simple-style-warning "`defpun/type*' is deprecated. Instead use `defpun/type' and pass ~ `:use-caller t' to `make-kernel'.") `(defpun/type ,@args))
13ab1008c14b0585ce84e0775507af41ed6f1d67cebb85791431e3bb01d5416a
asdr/easyweb
_view.lisp
(in-package :common-lisp-user) (defpackage :(% TMPL_VAR APPLICATION_NAME %).view (:use #:cl #:easyweb #:easyweb.html #:hunchentoot)) (in-package :(% TMPL_VAR APPLICATION_NAME %).view) (let ((easyweb::*application-name* "(% TMPL_VAR APPLICATION_NAME %)")) (defview index-page/get :url-pattern (:prefix "/") :request-type :GET :defun (((name "mervecigim")) (:doctype () (:html () (:head () (:title () "Welcome to le-jango project!")) (:body (:font-color "green") (:p () (:h2 () "Hello, world! le-jango is working...") (:h4 () "GET: " (format nil "~A" name))) (:p () (:br ()) "For more information, go on and jump into " (:a (:href "-jango/docs.html") "tutorials") " page.")))))) (defview index-page/post :url-pattern (:prefix "/") :request-type :POST :defun (((msg "asdr")) (:doctype () (:html () (:head () (:title () "Welcome to le-jango project!")) (:body (:font-color "green") (:p () (:h2 () "Hello, world! le-jango is working...") (:h4 () "POST: " msg)) (:p () (:br ()) "For more information, go on and jump into " (:a (:href "-jango/docs.html") "tutorials") " page.")))))) (defview form :url-pattern (:absolute "/form") :request-type :BOTH :defun (((url "(% TMPL_VAR APPLICATION_NAME %)")) (:doctype () (:html () (:body () (:form (:action url :method :post) (:input (:type "textfield" :name "msg")) (:input (:type "submit" :value "send")))))))))
null
https://raw.githubusercontent.com/asdr/easyweb/b259358a5f5e146b233b38d5e5df5b85a5a479cd/template-app/_view.lisp
lisp
(in-package :common-lisp-user) (defpackage :(% TMPL_VAR APPLICATION_NAME %).view (:use #:cl #:easyweb #:easyweb.html #:hunchentoot)) (in-package :(% TMPL_VAR APPLICATION_NAME %).view) (let ((easyweb::*application-name* "(% TMPL_VAR APPLICATION_NAME %)")) (defview index-page/get :url-pattern (:prefix "/") :request-type :GET :defun (((name "mervecigim")) (:doctype () (:html () (:head () (:title () "Welcome to le-jango project!")) (:body (:font-color "green") (:p () (:h2 () "Hello, world! le-jango is working...") (:h4 () "GET: " (format nil "~A" name))) (:p () (:br ()) "For more information, go on and jump into " (:a (:href "-jango/docs.html") "tutorials") " page.")))))) (defview index-page/post :url-pattern (:prefix "/") :request-type :POST :defun (((msg "asdr")) (:doctype () (:html () (:head () (:title () "Welcome to le-jango project!")) (:body (:font-color "green") (:p () (:h2 () "Hello, world! le-jango is working...") (:h4 () "POST: " msg)) (:p () (:br ()) "For more information, go on and jump into " (:a (:href "-jango/docs.html") "tutorials") " page.")))))) (defview form :url-pattern (:absolute "/form") :request-type :BOTH :defun (((url "(% TMPL_VAR APPLICATION_NAME %)")) (:doctype () (:html () (:body () (:form (:action url :method :post) (:input (:type "textfield" :name "msg")) (:input (:type "submit" :value "send")))))))))
d973ce076d6ef5ec188aa09fa606dc433a99da905c6203ac714e60d6ea2a0f74
MisakaCenter/RayTracer.ml
Aarect.ml
open Base open Vec open Ray open Hittable open Utils open Core open Float open Aabb class xy_rect _x0 _x1 _y0 _y1 _k (m : hit_record material_meta pointer) = object inherit hittable val mutable x0:float = _x0 val mutable x1:float = _x1 val mutable y0:float = _y0 val mutable y1:float = _y1 val mutable k:float = _k val mutable mat_ptr = m method hit (r : ray) (t_min : float) (t_max : float) (rcd : hit_record pointer) = let t = (k -. r#origin#z) /. (r#direction#z) in if (t <. t_min || t >. t_max) then false else begin let x = r#origin#x +. (t *. r#direction#x) in let y = r#origin#y +. (t *. r#direction#y) in if (x <. x0 || x >. x1 || y <. y0 || y >. y1) then false else begin let outward_normal = new vec3 [|0.0;0.0;1.0|] in let u_ = (x -. x0) /. (x1 -. x0) in let v_ = (y -. y0) /. (y1 -. y0) in rcd ^:= set_face_normal { p = at r t ; t = t; normal = outward_normal; front_face = true; mat_ptr; u = u_; v =v_ } r outward_normal; true end end method bounding_box (_ : float) (_ : float) output_box = output_box ^:= new aabb (new vec3 [|x0;y0;k -. 0.0001|]) (new vec3 [|x1;y1;k +. 0.0001|]); true end class xz_rect _x0 _x1 _z0 _z1 _k (m : hit_record material_meta pointer) = object inherit hittable val mutable x0:float = _x0 val mutable x1:float = _x1 val mutable z0:float = _z0 val mutable z1:float = _z1 val mutable k:float = _k val mutable mat_ptr = m method hit (r : ray) (t_min : float) (t_max : float) (rcd : hit_record pointer) = let t = (k -. r#origin#y) /. (r#direction#y) in if (t <. t_min || t >. t_max) then false else begin let x = r#origin#x +. (t *. r#direction#x) in let z = r#origin#z +. (t *. r#direction#z) in if (x <. x0 || x >. x1 || z <. z0 || z >. z1) then false else begin let outward_normal = new vec3 [|0.0;1.0;0.0|] in let u_ = (x -. x0) /. (x1 -. x0) in let v_ = (z -. z0) /. (z1 -. z0) in rcd ^:= set_face_normal { p = at r t ; t = t; normal = outward_normal; front_face = true; mat_ptr; u = u_; v =v_ } r outward_normal; true end end method bounding_box (_ : float) (_ : float) output_box = output_box ^:= new aabb (new vec3 [|x0;k -. 0.0001;z0|]) (new vec3 [|x1;k +. 0.0001;z1|]); true end class yz_rect _y0 _y1 _z0 _z1 _k (m : hit_record material_meta pointer) = object inherit hittable val mutable y0:float = _y0 val mutable y1:float = _y1 val mutable z0:float = _z0 val mutable z1:float = _z1 val mutable k:float = _k val mutable mat_ptr = m method hit (r : ray) (t_min : float) (t_max : float) (rcd : hit_record pointer) = let t = (k -. r#origin#x) /. (r#direction#x) in if (t <. t_min || t >. t_max) then false else begin let y = r#origin#y +. (t *. r#direction#y) in let z = r#origin#z +. (t *. r#direction#z) in if (y <. y0 || y >. y1 || z <. z0 || z >. z1) then false else begin let outward_normal = new vec3 [|1.0;0.0;0.0|] in let u_ = (y -. y0) /. (y1 -. y0) in let v_ = (z -. z0) /. (z1 -. z0) in rcd ^:= set_face_normal { p = at r t ; t = t; normal = outward_normal; front_face = true; mat_ptr; u = u_; v =v_ } r outward_normal; true end end method bounding_box (_ : float) (_ : float) output_box = output_box ^:= new aabb (new vec3 [|k -. 0.0001;y0;z0|]) (new vec3 [|k +. 0.0001;y1;z1|]); true end
null
https://raw.githubusercontent.com/MisakaCenter/RayTracer.ml/07bacba1ae3f46e1055465a7b79af5cfbf5d2010/lib/Aarect.ml
ocaml
open Base open Vec open Ray open Hittable open Utils open Core open Float open Aabb class xy_rect _x0 _x1 _y0 _y1 _k (m : hit_record material_meta pointer) = object inherit hittable val mutable x0:float = _x0 val mutable x1:float = _x1 val mutable y0:float = _y0 val mutable y1:float = _y1 val mutable k:float = _k val mutable mat_ptr = m method hit (r : ray) (t_min : float) (t_max : float) (rcd : hit_record pointer) = let t = (k -. r#origin#z) /. (r#direction#z) in if (t <. t_min || t >. t_max) then false else begin let x = r#origin#x +. (t *. r#direction#x) in let y = r#origin#y +. (t *. r#direction#y) in if (x <. x0 || x >. x1 || y <. y0 || y >. y1) then false else begin let outward_normal = new vec3 [|0.0;0.0;1.0|] in let u_ = (x -. x0) /. (x1 -. x0) in let v_ = (y -. y0) /. (y1 -. y0) in rcd ^:= set_face_normal { p = at r t ; t = t; normal = outward_normal; front_face = true; mat_ptr; u = u_; v =v_ } r outward_normal; true end end method bounding_box (_ : float) (_ : float) output_box = output_box ^:= new aabb (new vec3 [|x0;y0;k -. 0.0001|]) (new vec3 [|x1;y1;k +. 0.0001|]); true end class xz_rect _x0 _x1 _z0 _z1 _k (m : hit_record material_meta pointer) = object inherit hittable val mutable x0:float = _x0 val mutable x1:float = _x1 val mutable z0:float = _z0 val mutable z1:float = _z1 val mutable k:float = _k val mutable mat_ptr = m method hit (r : ray) (t_min : float) (t_max : float) (rcd : hit_record pointer) = let t = (k -. r#origin#y) /. (r#direction#y) in if (t <. t_min || t >. t_max) then false else begin let x = r#origin#x +. (t *. r#direction#x) in let z = r#origin#z +. (t *. r#direction#z) in if (x <. x0 || x >. x1 || z <. z0 || z >. z1) then false else begin let outward_normal = new vec3 [|0.0;1.0;0.0|] in let u_ = (x -. x0) /. (x1 -. x0) in let v_ = (z -. z0) /. (z1 -. z0) in rcd ^:= set_face_normal { p = at r t ; t = t; normal = outward_normal; front_face = true; mat_ptr; u = u_; v =v_ } r outward_normal; true end end method bounding_box (_ : float) (_ : float) output_box = output_box ^:= new aabb (new vec3 [|x0;k -. 0.0001;z0|]) (new vec3 [|x1;k +. 0.0001;z1|]); true end class yz_rect _y0 _y1 _z0 _z1 _k (m : hit_record material_meta pointer) = object inherit hittable val mutable y0:float = _y0 val mutable y1:float = _y1 val mutable z0:float = _z0 val mutable z1:float = _z1 val mutable k:float = _k val mutable mat_ptr = m method hit (r : ray) (t_min : float) (t_max : float) (rcd : hit_record pointer) = let t = (k -. r#origin#x) /. (r#direction#x) in if (t <. t_min || t >. t_max) then false else begin let y = r#origin#y +. (t *. r#direction#y) in let z = r#origin#z +. (t *. r#direction#z) in if (y <. y0 || y >. y1 || z <. z0 || z >. z1) then false else begin let outward_normal = new vec3 [|1.0;0.0;0.0|] in let u_ = (y -. y0) /. (y1 -. y0) in let v_ = (z -. z0) /. (z1 -. z0) in rcd ^:= set_face_normal { p = at r t ; t = t; normal = outward_normal; front_face = true; mat_ptr; u = u_; v =v_ } r outward_normal; true end end method bounding_box (_ : float) (_ : float) output_box = output_box ^:= new aabb (new vec3 [|k -. 0.0001;y0;z0|]) (new vec3 [|k +. 0.0001;y1;z1|]); true end
7b3dc10c4293759258c588c7dca16903b1f721019410c6711a211d3b390e3409
ept/compsci
tick5.ml
ML ASSESSED EXERCISES . TICK 5 SUBMISSION FROM M.A. KLEPPMANN Estimated time : 1h . Actual time : 40 mins . (* Part 1: A function f(m) that returns another function which adds m onto a given parameter. *) fun plus(m:int) = (fn n => m+n); (* This is equivalent to writing: *) fun plus m n: int = m+n; val succ = plus 1; succ is now a function that returns the successor to its argument passed , i.e. the argument plus 1 . passed, i.e. the argument plus 1. *) fun add(m,n): int = m+n; Add differs from plus in that it is not curried . It takes only one argument , which must be a pair of two ints . It is not possible to make it return another function / to call it with only one parameter . argument, which must be a pair of two ints. It is not possible to make it return another function / to call it with only one parameter. *) Part 3 : The nfold function as defined in the question sheet . fun nfold f x 0 = x | nfold f x n = f(nfold f x (n-1)); Now Part 2 : Computing sums , products and powers in a vastly inefficient way . Computing sums, products and powers in a vastly inefficient way. *) fun sum(a,b) = nfold (fn n => n+1) a b; fun product(a,b) = nfold (fn n => n+a) 0 b; (* or, to be a bit crazier: *) fun product_slow(a,b) = nfold (fn n => sum(n,a)) 0 b; fun power(a,b) = nfold (fn n => n*a) 1 b; (* or, to complete the craziness: *) fun power_slow(a,b) = nfold (fn n => product_slow(n,a)) 1 b;
null
https://raw.githubusercontent.com/ept/compsci/ed666bb4cf52ac2af5c2d13894870bdc23dca237/ml/tick5.ml
ocaml
Part 1: A function f(m) that returns another function which adds m onto a given parameter. This is equivalent to writing: or, to be a bit crazier: or, to complete the craziness:
ML ASSESSED EXERCISES . TICK 5 SUBMISSION FROM M.A. KLEPPMANN Estimated time : 1h . Actual time : 40 mins . fun plus(m:int) = (fn n => m+n); fun plus m n: int = m+n; val succ = plus 1; succ is now a function that returns the successor to its argument passed , i.e. the argument plus 1 . passed, i.e. the argument plus 1. *) fun add(m,n): int = m+n; Add differs from plus in that it is not curried . It takes only one argument , which must be a pair of two ints . It is not possible to make it return another function / to call it with only one parameter . argument, which must be a pair of two ints. It is not possible to make it return another function / to call it with only one parameter. *) Part 3 : The nfold function as defined in the question sheet . fun nfold f x 0 = x | nfold f x n = f(nfold f x (n-1)); Now Part 2 : Computing sums , products and powers in a vastly inefficient way . Computing sums, products and powers in a vastly inefficient way. *) fun sum(a,b) = nfold (fn n => n+1) a b; fun product(a,b) = nfold (fn n => n+a) 0 b; fun product_slow(a,b) = nfold (fn n => sum(n,a)) 0 b; fun power(a,b) = nfold (fn n => n*a) 1 b; fun power_slow(a,b) = nfold (fn n => product_slow(n,a)) 1 b;
43a265baac6f9ee09e97fbee4286e1f785a510dac38b2bf038a219119796ddac
synrc/nitro
element_meter.erl
-module(element_meter). -author('Vladimir Galunshchikov'). -include_lib("nitro/include/nitro.hrl"). -compile(export_all). render_element(Record) when Record#meter.show_if==false -> [<<>>]; render_element(Record) -> List = [ %global {<<"accesskey">>, Record#meter.accesskey}, {<<"class">>, Record#meter.class}, {<<"contenteditable">>, case Record#meter.contenteditable of true -> "true"; false -> "false"; _ -> [] end}, {<<"contextmenu">>, Record#meter.contextmenu}, {<<"dir">>, case Record#meter.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end}, {<<"draggable">>, case Record#meter.draggable of true -> "true"; false -> "false"; _ -> [] end}, {<<"dropzone">>, Record#meter.dropzone}, {<<"hidden">>, case Record#meter.hidden of "hidden" -> "hidden"; _ -> [] end}, {<<"id">>, Record#meter.id}, {<<"lang">>, Record#meter.lang}, {<<"spellcheck">>, case Record#meter.spellcheck of true -> "true"; false -> "false"; _ -> [] end}, {<<"style">>, Record#meter.style}, {<<"tabindex">>, Record#meter.tabindex}, {<<"title">>, Record#meter.title}, {<<"translate">>, case Record#meter.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end}, % spec {<<"high">>,Record#meter.high}, {<<"low">>,Record#meter.low}, {<<"max">>,Record#meter.max}, {<<"min">>,Record#meter.min}, {<<"optimum">>,Record#meter.optimum}, {<<"value">>, Record#meter.value} | Record#meter.data_fields ], wf_tags:emit_tag(<<"meter">>, nitro:render(case Record#meter.body of [] -> []; B -> B end), List).
null
https://raw.githubusercontent.com/synrc/nitro/753b543626add2c014584546ec50870808a2eb90/src/elements/form/element_meter.erl
erlang
global spec
-module(element_meter). -author('Vladimir Galunshchikov'). -include_lib("nitro/include/nitro.hrl"). -compile(export_all). render_element(Record) when Record#meter.show_if==false -> [<<>>]; render_element(Record) -> List = [ {<<"accesskey">>, Record#meter.accesskey}, {<<"class">>, Record#meter.class}, {<<"contenteditable">>, case Record#meter.contenteditable of true -> "true"; false -> "false"; _ -> [] end}, {<<"contextmenu">>, Record#meter.contextmenu}, {<<"dir">>, case Record#meter.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end}, {<<"draggable">>, case Record#meter.draggable of true -> "true"; false -> "false"; _ -> [] end}, {<<"dropzone">>, Record#meter.dropzone}, {<<"hidden">>, case Record#meter.hidden of "hidden" -> "hidden"; _ -> [] end}, {<<"id">>, Record#meter.id}, {<<"lang">>, Record#meter.lang}, {<<"spellcheck">>, case Record#meter.spellcheck of true -> "true"; false -> "false"; _ -> [] end}, {<<"style">>, Record#meter.style}, {<<"tabindex">>, Record#meter.tabindex}, {<<"title">>, Record#meter.title}, {<<"translate">>, case Record#meter.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end}, {<<"high">>,Record#meter.high}, {<<"low">>,Record#meter.low}, {<<"max">>,Record#meter.max}, {<<"min">>,Record#meter.min}, {<<"optimum">>,Record#meter.optimum}, {<<"value">>, Record#meter.value} | Record#meter.data_fields ], wf_tags:emit_tag(<<"meter">>, nitro:render(case Record#meter.body of [] -> []; B -> B end), List).
989ab636406a38afc8c15cc34d6630d40687c72edee1712b3d869941f45f212b
ocaml-batteries-team/batteries-included
odoc_batteries_factored.ml
(*From OCamlDoc*) open Odoc_info;; open Odoc_info.Value open Odoc_info.Module open Odoc_info.Type open Odoc_info.Class open Odoc_info.Exception (*module StringSet = Odoc_html.StringSet*) module StringSet = Set.Make(String);; warning "Loading factored";; (*From the base library*) open List (** {1 Tools}*) * two names into a module path . [ concat a b ] is [ a^" . "^b ] if neither [ a ] nor [ b ] is empty , [ a ] if [ b ] is empty and [ b ] if [ a ] is empty . [concat a b] is [a^"."^b] if neither [a] nor [b] is empty, [a] if [b] is empty and [b] if [a] is empty.*) let concat a b = if String.length b = 0 then a else if String.length a = 0 then b else Name.concat a b (** Return the basename in a path. [end_of_name "A.B.C.D.E.t"] produces ["t"] *) let end_of_name name = Name.get_relative (Name.father (Name.father name)) name (** Print an [info option]*) let string_of_info_opt = function | None -> "No information" | Some i -> info_string_of_info i let bs = Buffer.add_string let bp = Printf.bprintf let opt = Odoc_info.apply_opt let new_buf () = Buffer.create 1024 (** {1 Configuration}*) (** A list of primitive type names for which we should rather link to the corresponding module *) let primitive_types_names = [ "char", "Char.t"; "string", "String.t"; "array", "Array.t" ; "lazy_t", "Lazy.t"; "list", "List.t"; "option", "Option.t"; "int32", "Int32.t"; "int64", "Int64.t"; "nativeint", "Nativeint.t"; "big_int", "Big_int.t"; "int", "Int.t"; "bool", "Bool.t"; "unit", "Unit.t"; "float", "Float.t"; "ref", "Ref.t"; "exn", "Exception.t"; "format4", "Printf.format4" ] let has_parent a ~parent:b = a = b || let len_a = String.length a and len_b = String.length b in let result = len_a > len_b && let prefix = String.sub a 0 len_b in prefix = b && a.[len_b] = '.' in verbose (Printf.sprintf "Checking whether %s has parent %s: %b" a b result); result let merge_info_opt a b = verbose ("Merging information"); if a <> b then begin verbose ("1: "^(string_of_info_opt a)); verbose ("2: "^(string_of_info_opt b)); let result = Odoc_merge.merge_info_opt Odoc_types.all_merge_options a b in verbose (">: "^(string_of_info_opt result)); result end else a (** The list of modules which should appear as roots in the hierarchy. *) let roots = ["Batteries"] * { 1 Actual rewriting } (**[get_documents i] determines if information [i] specifies that this module "documents" another module, not included in the source tree. Specifying that module [Foo] documents module [Bar] means that every hyperlink to some element [e] in module [Bar] should actually point to an with the same name in module [Foo]. To add such a specification, add [@documents Bar] to the module comments of module [Foo]. Typical use of this feature: - the documentation of module [Sna] makes use of elements (types, values, etc.) of module [Bar] - module [Bar] is not included in the project, as it belongs to another project - for some reason, documenting module [Bar] is important, possibly because this module has not been documented by its original author or because it is expected that developers will need to read through the documentation of module [Bar] so often that this documentation should be added to the project - create a module [Foo] in the project by importing or re-creating [bar.mli] - document [foo.mli] - add [@documents Bar] in the module comments of module [Foo] *) let get_documents = function | None -> [] | Some i -> List.fold_left (fun acc x -> match x with | ("documents", [Raw s]) -> verbose ("This module documents "^s); s::acc | ("documents", x ) -> warning ("Weird documents "^(string_of_text x)); (string_of_text x)::acc | _ -> acc) [] i.i_custom (* undocumented for now, possibly useless *) let get_documented = function | None -> [] | Some i -> List.fold_left (fun acc x -> match x with | ("documented", [Raw s]) -> verbose ("This module should take its place as "^s); s::acc | ("documented", x ) -> warning ("Weird documented "^(string_of_text x)); (string_of_text x)::acc | _ -> acc) [] i.i_custom (** [module_dependencies m] lists the dependencies of a module [m] in terms of other modules*) let module_dependencies m = let rec handle_kind acc = function | Module_struct e -> List.fold_left (fun acc x -> handle_element acc x) acc e | Module_alias a -> a.ma_name :: acc | Module_functor (_, a) -> handle_kind acc a | Module_apply (a, b) -> handle_kind (handle_kind acc a) b | Module_with (_, _) -> acc | Module_constraint (a, _) -> handle_kind acc a and handle_element acc = function | Element_module m -> handle_kind acc m.m_kind | Element_included_module a -> a.im_name :: acc | _ -> acc in handle_kind m.m_top_deps m.m_kind * [ rebuild_structure m ] walks through list [ m ] and rebuilds it as a forest of modules and sub - modules . - Resolving aliases : if we have a module [ A ] containing [ module B = C ] , module [ C ] is renamed [ ] and we keep that renaming for reference generation . - Resolving inclusions : if we have a module [ A ] containing [ include C ] , the contents of module [ C ] are copied into [ A ] and we fabricate a renaming from [ C ] to [ A ] for reference generation . @return [ ( m , r ) ] , where [ m ] is the new list of modules and [ r ] is a mapping from old module names to new module names . [rebuild_structure m] walks through list [m] and rebuilds it as a forest of modules and sub-modules. - Resolving aliases: if we have a module [A] containing [module B = C], module [C] is renamed [A.B] and we keep that renaming for reference generation. - Resolving inclusions: if we have a module [A] containing [include C], the contents of module [C] are copied into [A] and we fabricate a renaming from [C] to [A] for reference generation. @return [(m, r)], where [m] is the new list of modules and [r] is a mapping from old module names to new module names. *) let rebuild_structure modules = let all_renamed_modules = Hashtbl.create 256 (**Mapping [old name] -> [new name, latest info]*) and all_renamed_module_types = Hashtbl.create 256 (**Mapping [old name] -> [new name, latest info]*) and all_modules = Hashtbl.create 256 (**Mapping [name] -> [t_module] -- unused*) in let add_renamed_module ~old:(old_name,old_info) ~current:(new_name,new_info) = verbose ("Setting module renaming from "^old_name^" to "^new_name); try let (better, better_info) = Hashtbl.find all_renamed_modules new_name in verbose ("... actually setting renaming from "^old_name^" to "^better); let complete_info = merge_info_opt (merge_info_opt old_info new_info) better_info in Hashtbl.replace all_renamed_modules old_name (better, complete_info); complete_info with Not_found -> let complete_info = merge_info_opt old_info new_info in Hashtbl.add all_renamed_modules old_name (new_name, complete_info); complete_info and add_renamed_module_type old current = verbose ("Setting module type renaming from "^old^" to "^current); try let further_references = Hashtbl.find all_renamed_module_types current in verbose ("... actually setting renaming from "^old^" to "^further_references); Hashtbl.add all_renamed_module_types old further_references with Not_found -> Hashtbl.add all_renamed_module_types old current in First pass : build hierarchy let rec handle_kind path (m:t_module) = function | Module_struct x -> Module_struct (List.flatten (List.map (handle_module_element path m) x)) | Module_alias x -> Module_alias (handle_alias path m x) | Module_functor (p, k) -> Module_functor (p, handle_kind path m k) | Module_apply (x, y) -> Module_apply (handle_kind path m x, handle_kind path m y) | Module_with (k, s) -> Module_with (handle_type_kind path m k, s) | Module_constraint (x, y) -> Module_constraint (handle_kind path m x, handle_type_kind path m y) and handle_module_element path m = function | Element_module x -> [Element_module (handle_module path m x)] | Element_module_type x -> [Element_module_type (handle_module_type path m x)] | Element_module_comment _ as y -> [y] | Element_class x -> [Element_class {(x) with cl_name = concat path (Name.simple x.cl_name)}] | Element_class_type x -> [Element_class_type{(x) with clt_name = concat path (Name.simple x.clt_name)}] | Element_value x -> [Element_value {(x) with val_name = concat path (Name.simple x.val_name)}] | Element_exception x -> [Element_exception {(x) with ex_name = concat path (Name.simple x.ex_name)}] | Element_type x -> [Element_type {(x) with ty_name = concat path (Name.simple x.ty_name)}] | Element_included_module x as y -> (* verbose ("Meeting inclusion "^x.im_name);*) match x.im_module with | Some (Mod a) -> verbose ("This is an included module, we'll treat it as "^path); let a' = handle_module path m {(a) with m_name = ""} in ( match a'.m_kind with | Module_struct l -> (*Copy the contents of [a] into [m]*) (*Copy the information on [a] into [m]*) verbose ("Merging "^m.m_name^" and included "^a'.m_name); m.m_info <- merge_info_opt (add_renamed_module ~old:(a.m_name,a.m_info) ~current:(m.m_name, m.m_info)) (add_renamed_module ~old:(Name.get_relative m.m_name a.m_name, None) ~current:(m.m_name, m.m_info)); l | _ -> verbose ("Structure of the module is complex"); [Element_included_module {(x) with im_module = Some (Mod a')}] (*Otherwise, it's too complicated*) ) | Some (Modtype a) -> (* verbose ("This is an included module type");*) let a' = handle_module_type path m a in [Element_included_module {(x) with im_module = Some (Modtype a')}] | None -> verbose ("Module couldn't be found"); m.m_info <- add_renamed_module ~old:(x.im_name,None) ~current:(m.m_name,m.m_info); [y] and handle_module path m t = let path' = concat path (Name.simple t.m_name) in verbose ("Visiting module "^t.m_name^" from "^m.m_name^", at path "^path'); let result = {(t) with m_kind = handle_kind path' t t.m_kind; m_name = path'} in result.m_info <- add_renamed_module ~old:(t.m_name,t.m_info) ~current:(path',None); (match get_documents t.m_info with | [] -> verbose ("No @documents for module "^t.m_name) | l -> List.iter (fun r -> verbose ("Manual @documents of module "^r^" with "^path'); result.m_info <- add_renamed_module ~old:(r,None) ~current:(path',result.m_info)) l); (match get_documented t.m_info with | [] -> verbose ("No @documented for module "^t.m_name) | l -> List.iter (fun r -> verbose ("Manual @documented of module "^r^" with "^path'); result.m_info <- add_renamed_module ~current:(r,None) ~old:(path',result.m_info)) l); result and handle_module_type path m (t:Odoc_module.t_module_type) = let path' = concat path (Name.simple t.mt_name) in verbose ("Visiting module "^t.mt_name^" from "^m.m_name^", at path "^path'); let result = {(t) with mt_kind = (match t.mt_kind with | None -> None | Some kind -> Some (handle_type_kind path' m kind)); mt_name = path'} in add_renamed_module_type t.mt_name path'; result and handle_alias path m (t:module_alias) : module_alias = (*Module [m] is an alias to [t.ma_module]*) match t.ma_module with | None -> verbose ("I'd like to merge information from "^m.m_name^" and "^t.ma_name^" but I can't find that module"); t let rec aux = function | [ ] - > verbose ( " Ca n't do better " ) ; t | x::xs - > if Name.prefix x t.ma_name then let suffix = Name.get_relative x t.ma_name in let info = add_renamed_module ~old:(suffix , ) ~current:(path , None ) in { ( t ) with ma_name = suffix } else aux xs in aux packs | [] -> verbose ("Can't do better"); t | x::xs -> if Name.prefix x t.ma_name then let suffix = Name.get_relative x t.ma_name in let info = add_renamed_module ~old:(suffix, m.m_info) ~current:(path, None) in {(t) with ma_name = suffix} else aux xs in aux packs*) | Some (Mod a) -> (* add_renamed_module a.m_name path;*) verbose ("Merging information from "^m.m_name^" and aliased "^a.m_name); let info = add_renamed_module ~old:(a.m_name,a.m_info) ~current:(path,m.m_info) in m.m_info <- info; a.m_info <- info; let a' = {(a) with m_kind = handle_kind path m a.m_kind} in {(t) with ma_module = Some (Mod a')} | Some (Modtype a) -> verbose ("Merging information from "^m.m_name^" and aliased type "^a.mt_name); m.m_info <- merge_info_opt m.m_info a.mt_info; a.mt_info <- m.m_info; add_renamed_module_type a.mt_name path; let info = Odoc_merge.merge_info_opt Odoc_types.all_merge_options m.m_info a.mt_info in let a' = match a.mt_kind with | None -> a | Some kind -> {(a) with mt_kind = Some (handle_type_kind path m kind); mt_info = info} in {(t) with ma_module = Some (Modtype a')} and handle_type_kind path m :module_type_kind -> module_type_kind = function | Module_type_struct x -> Module_type_struct (List.flatten (List.map (handle_module_element path m) x)) | Module_type_functor (p, x)-> Module_type_functor (p, handle_type_kind path m x) | Module_type_alias x -> Module_type_alias (handle_type_alias path m x) | Module_type_with (k, s) -> Module_type_with (handle_type_kind path m k, s) and handle_type_alias path m t = match t.mta_module with verbose ( " module type " ^t.mta_name^ " not resolved in cross - reference stage " ) ; | Some a -> (*verbose ("module type "^a.mt_name^" renamed "^(concat m.m_name a.mt_name));*) if a.mt_info < > None then < - a.mt_info ; add_renamed_module_type a.mt_name path; let info = Odoc_merge.merge_info_opt Odoc_types.all_merge_options m.m_info a.mt_info in {(t) with mta_module = Some ({(a) with mt_name = concat m.m_name a.mt_name; mt_info = info})} in 1 . Find root modules , i.e. modules which are neither included nor aliased let all_roots = Hashtbl.create 100 in List.iter ( fun x - > if x.m_name = " " then ( ( * verbose ( " Adding " ^x.m_name^ " to the list of roots " ) ; List.iter (fun x -> if Name.father x.m_name = "" then ( (* verbose ("Adding "^x.m_name^" to the list of roots");*) Hashtbl.add all_roots x.m_name x ) (*else verbose ("Not adding "^x.m_name^" to the list of roots")*) ) modules; List.iter (fun x -> begin List.iter (fun y -> (*verbose(" removing "^y^" which is brought out by "^x.m_name);*) Hashtbl.remove all_roots y ) (*x.m_top_deps*) (module_dependencies x) end) modules; Hashtbl.iter (fun name _ -> verbose ("Root: "^name)) all_roots; let for_rewriting = Hashtbl.fold ( fun k m acc - > if List.mem k roots then begin verbose ( " Rewriting : " ) ; ( k , m)::acc end else begin verbose ( " Not rewriting : " ) ; acc end ) all_roots [ ] in begin verbose ("Rewriting: " ^k); (k,m)::acc end else begin verbose ("Not rewriting: "^k); acc end) all_roots [] in*) (*Actually, we're only interested in modules which appear in [roots]*) (*Note: we could probably do something much more simple, without resorting to this dependency analysis stuff*)*) let for_rewriting = List.fold_left (fun acc x -> Hashtbl.add all_modules x.m_name x; if List.mem x.m_name roots then begin verbose ("We need to visit module "^x.m_name); (x.m_name, x)::acc end else begin verbose ("Discarding module "^x.m_name^" for now"); acc end) [] modules in verbose ("[Starting to rearrange module structure]"); let for_rewriting = Hashtbl.fold ( fun k m acc - > ( k , m)::acc ) all_roots [ ] in 2 . Dive into these (*let rewritten = Hashtbl.fold (fun name contents acc -> {(contents) with m_kind = handle_kind name contents contents.m_kind}::acc ) all_roots [] in*) let rewritten = List.fold_left (fun acc (name, contents) -> {(contents) with m_kind = handle_kind "" contents contents.m_kind}::acc) [] for_rewriting in let result = Search.modules rewritten in TODO : Second pass : walk through references -- handled during html generation for the moment (result, all_renamed_modules) (** Determine into which topics each module/type/value/... goes *) let sort_by_topics modules = let write s = verbose ( "[SORT] "^s ) in let rec string_of_path = function | [] -> "" | (`Level l)::t -> Printf.sprintf "[%d] > %s" l (string_of_path t) | (`Topic top)::t -> Printf.sprintf "%s > %s" top (string_of_path t) in let write s = Printf.eprintf " [ SORT ] % s\n% ! " s in let topics : StringSet.t ref = ref StringSet.empty (**The set of topics*) and modules_by_topic : (string, t_module list ref) Hashtbl.t = Hashtbl.create 16 (**topic -> set of modules*) in let add_module top m = write ("Adding module "^m.m_name); List.iter (function `Topic t -> write ("Adding module "^m.m_name^" to topic "^t); ( try let l = Hashtbl.find modules_by_topic t in l := m :: !l with Not_found -> Hashtbl.add modules_by_topic t (ref [m]) ) | _ -> ()) top in let push_top_topic l t = (*Push the latest topic on the stack of topics/levels*) write ("Adding topic "^t); topics := StringSet.add t !topics; let result = (`Topic t)::l in write ("Added topics from "^(string_of_path l)^" to "^(string_of_path result)); result and push_top_level l t = (*Push the latest level on the stack of topics/levels*) write ("Entering level "^(string_of_int t)); let result = (`Level t)::l in write ("Entered level from "^(string_of_path l)^" to "^(string_of_path result)); result and pop_top_to_level l level = write ("Removing levels higher than "^(string_of_int level)); let rec aux prefix = function | (`Level l')::t when l' >= level -> aux [] t | ((`Topic _ ) as p)::t -> aux (p::prefix) t | _ as t -> List.rev_append prefix t in let result = aux [] l in write("From "^(string_of_path l)^" to "^(string_of_path result)); result in let adjust_to_level top level = write ("Moving to level "^(string_of_int level)); let result = push_top_level (pop_top_to_level top level) level in write("Moved levels from "^(string_of_path top)^" to "^(string_of_path result)); result in let adjust_top_from_comment top c = fold_left (fun acc text -> match text with | Title (level, title, text) -> adjust_to_level acc level | Custom (("topic" | "{topic"), text) -> write ("Custom topic "^(string_of_text text)); push_top_topic acc (string_of_text text) | Custom (other, _) -> write ("Custom other "^other); acc | _ -> acc ) top c in let adjust_top_from_info top = function | None -> top | Some ({i_custom = l} as i) -> write ("Meeting custom in info "^(string_of_info i)); List.fold_left (fun acc -> function (("topic"|"{topic"), t) -> write ("Custom topic in info "^(string_of_text t)); push_top_topic acc (string_of_text t) | (other, content) -> write ("Custom other in info "^other^": "^(string_of_text content)); acc | _ - > acc in let rec handle_kind top = function | Module_struct x -> List.fold_left handle_module_element top x | _ -> top and handle_module_element top = function | Element_module x -> let top' = adjust_top_from_info top x.m_info in add_module top' x; ignore (handle_kind top' x.m_kind); top | Element_module_comment c -> adjust_top_from_comment top c (*Extract level (if any) and topics (if any) If level exists - pop from [top] until we're at a level strictly higher than the level specified - push the level of [c] and, if available, information If no level exists but information exists - push the information at the current level Otherwise - do nothing *) (* let (level, topic) = extract_info_from_comment c in (match (level, topic) with | (None, Some x) -> List.fold push_top_topic top x | (Some l, None) -> push_top_level (pop_top_to_level top l) l | (Some l, Some x)-> List.fold push_top_topic (push_top_level (pop_top_to_level top l) l) x | _ -> top)*) | _ -> top (*!TODO: other tables*) and handle_module top m = handle_kind (adjust_top_from_info top m.m_info) m.m_kind in let _ = List.fold_left handle_module [] modules in (StringSet.elements !topics, modules_by_topic) let find_renaming renamings original = let rec aux s suffix = if String.length s = 0 then ( (* verbose ("Name '"^original^"' remains unchanged");*) suffix ) else let renaming = try Some (fst(Hashtbl.find renamings s)) with Not_found -> None in match renaming with | None -> let father = Name.father s in let son = Name.get_relative father s in aux father (concat son suffix) | Some r -> (*We have found a substitution, it should be over*) let result = concat r suffix in verbose ( " We have a renaming of " ^s^ " to " ^r ) ; verbose ("Name "^original^" replaced with "^result); result in aux original ""
null
https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/f143ef5ec583d87d538b8f06f06d046d64555e90/build/odoc_batteries_factored.ml
ocaml
From OCamlDoc module StringSet = Odoc_html.StringSet From the base library * {1 Tools} * Return the basename in a path. [end_of_name "A.B.C.D.E.t"] produces ["t"] * Print an [info option] * {1 Configuration} * A list of primitive type names for which we should rather link to the corresponding module * The list of modules which should appear as roots in the hierarchy. *[get_documents i] determines if information [i] specifies that this module "documents" another module, not included in the source tree. Specifying that module [Foo] documents module [Bar] means that every hyperlink to some element [e] in module [Bar] should actually point to an with the same name in module [Foo]. To add such a specification, add [@documents Bar] to the module comments of module [Foo]. Typical use of this feature: - the documentation of module [Sna] makes use of elements (types, values, etc.) of module [Bar] - module [Bar] is not included in the project, as it belongs to another project - for some reason, documenting module [Bar] is important, possibly because this module has not been documented by its original author or because it is expected that developers will need to read through the documentation of module [Bar] so often that this documentation should be added to the project - create a module [Foo] in the project by importing or re-creating [bar.mli] - document [foo.mli] - add [@documents Bar] in the module comments of module [Foo] undocumented for now, possibly useless * [module_dependencies m] lists the dependencies of a module [m] in terms of other modules *Mapping [old name] -> [new name, latest info] *Mapping [old name] -> [new name, latest info] *Mapping [name] -> [t_module] -- unused verbose ("Meeting inclusion "^x.im_name); Copy the contents of [a] into [m] Copy the information on [a] into [m] Otherwise, it's too complicated verbose ("This is an included module type"); Module [m] is an alias to [t.ma_module] add_renamed_module a.m_name path; verbose ("module type "^a.mt_name^" renamed "^(concat m.m_name a.mt_name)); verbose ("Adding "^x.m_name^" to the list of roots"); else verbose ("Not adding "^x.m_name^" to the list of roots") verbose(" removing "^y^" which is brought out by "^x.m_name); x.m_top_deps Actually, we're only interested in modules which appear in [roots] Note: we could probably do something much more simple, without resorting to this dependency analysis stuff let rewritten = Hashtbl.fold (fun name contents acc -> {(contents) with m_kind = handle_kind name contents contents.m_kind}::acc ) all_roots [] in * Determine into which topics each module/type/value/... goes *The set of topics *topic -> set of modules Push the latest topic on the stack of topics/levels Push the latest level on the stack of topics/levels Extract level (if any) and topics (if any) If level exists - pop from [top] until we're at a level strictly higher than the level specified - push the level of [c] and, if available, information If no level exists but information exists - push the information at the current level Otherwise - do nothing let (level, topic) = extract_info_from_comment c in (match (level, topic) with | (None, Some x) -> List.fold push_top_topic top x | (Some l, None) -> push_top_level (pop_top_to_level top l) l | (Some l, Some x)-> List.fold push_top_topic (push_top_level (pop_top_to_level top l) l) x | _ -> top) !TODO: other tables verbose ("Name '"^original^"' remains unchanged"); We have found a substitution, it should be over
open Odoc_info;; open Odoc_info.Value open Odoc_info.Module open Odoc_info.Type open Odoc_info.Class open Odoc_info.Exception module StringSet = Set.Make(String);; warning "Loading factored";; open List * two names into a module path . [ concat a b ] is [ a^" . "^b ] if neither [ a ] nor [ b ] is empty , [ a ] if [ b ] is empty and [ b ] if [ a ] is empty . [concat a b] is [a^"."^b] if neither [a] nor [b] is empty, [a] if [b] is empty and [b] if [a] is empty.*) let concat a b = if String.length b = 0 then a else if String.length a = 0 then b else Name.concat a b let end_of_name name = Name.get_relative (Name.father (Name.father name)) name let string_of_info_opt = function | None -> "No information" | Some i -> info_string_of_info i let bs = Buffer.add_string let bp = Printf.bprintf let opt = Odoc_info.apply_opt let new_buf () = Buffer.create 1024 let primitive_types_names = [ "char", "Char.t"; "string", "String.t"; "array", "Array.t" ; "lazy_t", "Lazy.t"; "list", "List.t"; "option", "Option.t"; "int32", "Int32.t"; "int64", "Int64.t"; "nativeint", "Nativeint.t"; "big_int", "Big_int.t"; "int", "Int.t"; "bool", "Bool.t"; "unit", "Unit.t"; "float", "Float.t"; "ref", "Ref.t"; "exn", "Exception.t"; "format4", "Printf.format4" ] let has_parent a ~parent:b = a = b || let len_a = String.length a and len_b = String.length b in let result = len_a > len_b && let prefix = String.sub a 0 len_b in prefix = b && a.[len_b] = '.' in verbose (Printf.sprintf "Checking whether %s has parent %s: %b" a b result); result let merge_info_opt a b = verbose ("Merging information"); if a <> b then begin verbose ("1: "^(string_of_info_opt a)); verbose ("2: "^(string_of_info_opt b)); let result = Odoc_merge.merge_info_opt Odoc_types.all_merge_options a b in verbose (">: "^(string_of_info_opt result)); result end else a let roots = ["Batteries"] * { 1 Actual rewriting } let get_documents = function | None -> [] | Some i -> List.fold_left (fun acc x -> match x with | ("documents", [Raw s]) -> verbose ("This module documents "^s); s::acc | ("documents", x ) -> warning ("Weird documents "^(string_of_text x)); (string_of_text x)::acc | _ -> acc) [] i.i_custom let get_documented = function | None -> [] | Some i -> List.fold_left (fun acc x -> match x with | ("documented", [Raw s]) -> verbose ("This module should take its place as "^s); s::acc | ("documented", x ) -> warning ("Weird documented "^(string_of_text x)); (string_of_text x)::acc | _ -> acc) [] i.i_custom let module_dependencies m = let rec handle_kind acc = function | Module_struct e -> List.fold_left (fun acc x -> handle_element acc x) acc e | Module_alias a -> a.ma_name :: acc | Module_functor (_, a) -> handle_kind acc a | Module_apply (a, b) -> handle_kind (handle_kind acc a) b | Module_with (_, _) -> acc | Module_constraint (a, _) -> handle_kind acc a and handle_element acc = function | Element_module m -> handle_kind acc m.m_kind | Element_included_module a -> a.im_name :: acc | _ -> acc in handle_kind m.m_top_deps m.m_kind * [ rebuild_structure m ] walks through list [ m ] and rebuilds it as a forest of modules and sub - modules . - Resolving aliases : if we have a module [ A ] containing [ module B = C ] , module [ C ] is renamed [ ] and we keep that renaming for reference generation . - Resolving inclusions : if we have a module [ A ] containing [ include C ] , the contents of module [ C ] are copied into [ A ] and we fabricate a renaming from [ C ] to [ A ] for reference generation . @return [ ( m , r ) ] , where [ m ] is the new list of modules and [ r ] is a mapping from old module names to new module names . [rebuild_structure m] walks through list [m] and rebuilds it as a forest of modules and sub-modules. - Resolving aliases: if we have a module [A] containing [module B = C], module [C] is renamed [A.B] and we keep that renaming for reference generation. - Resolving inclusions: if we have a module [A] containing [include C], the contents of module [C] are copied into [A] and we fabricate a renaming from [C] to [A] for reference generation. @return [(m, r)], where [m] is the new list of modules and [r] is a mapping from old module names to new module names. *) let rebuild_structure modules = in let add_renamed_module ~old:(old_name,old_info) ~current:(new_name,new_info) = verbose ("Setting module renaming from "^old_name^" to "^new_name); try let (better, better_info) = Hashtbl.find all_renamed_modules new_name in verbose ("... actually setting renaming from "^old_name^" to "^better); let complete_info = merge_info_opt (merge_info_opt old_info new_info) better_info in Hashtbl.replace all_renamed_modules old_name (better, complete_info); complete_info with Not_found -> let complete_info = merge_info_opt old_info new_info in Hashtbl.add all_renamed_modules old_name (new_name, complete_info); complete_info and add_renamed_module_type old current = verbose ("Setting module type renaming from "^old^" to "^current); try let further_references = Hashtbl.find all_renamed_module_types current in verbose ("... actually setting renaming from "^old^" to "^further_references); Hashtbl.add all_renamed_module_types old further_references with Not_found -> Hashtbl.add all_renamed_module_types old current in First pass : build hierarchy let rec handle_kind path (m:t_module) = function | Module_struct x -> Module_struct (List.flatten (List.map (handle_module_element path m) x)) | Module_alias x -> Module_alias (handle_alias path m x) | Module_functor (p, k) -> Module_functor (p, handle_kind path m k) | Module_apply (x, y) -> Module_apply (handle_kind path m x, handle_kind path m y) | Module_with (k, s) -> Module_with (handle_type_kind path m k, s) | Module_constraint (x, y) -> Module_constraint (handle_kind path m x, handle_type_kind path m y) and handle_module_element path m = function | Element_module x -> [Element_module (handle_module path m x)] | Element_module_type x -> [Element_module_type (handle_module_type path m x)] | Element_module_comment _ as y -> [y] | Element_class x -> [Element_class {(x) with cl_name = concat path (Name.simple x.cl_name)}] | Element_class_type x -> [Element_class_type{(x) with clt_name = concat path (Name.simple x.clt_name)}] | Element_value x -> [Element_value {(x) with val_name = concat path (Name.simple x.val_name)}] | Element_exception x -> [Element_exception {(x) with ex_name = concat path (Name.simple x.ex_name)}] | Element_type x -> [Element_type {(x) with ty_name = concat path (Name.simple x.ty_name)}] | Element_included_module x as y -> match x.im_module with | Some (Mod a) -> verbose ("This is an included module, we'll treat it as "^path); let a' = handle_module path m {(a) with m_name = ""} in ( match a'.m_kind with | Module_struct l -> verbose ("Merging "^m.m_name^" and included "^a'.m_name); m.m_info <- merge_info_opt (add_renamed_module ~old:(a.m_name,a.m_info) ~current:(m.m_name, m.m_info)) (add_renamed_module ~old:(Name.get_relative m.m_name a.m_name, None) ~current:(m.m_name, m.m_info)); l | _ -> verbose ("Structure of the module is complex"); [Element_included_module {(x) with im_module = Some (Mod a')}] ) | Some (Modtype a) -> let a' = handle_module_type path m a in [Element_included_module {(x) with im_module = Some (Modtype a')}] | None -> verbose ("Module couldn't be found"); m.m_info <- add_renamed_module ~old:(x.im_name,None) ~current:(m.m_name,m.m_info); [y] and handle_module path m t = let path' = concat path (Name.simple t.m_name) in verbose ("Visiting module "^t.m_name^" from "^m.m_name^", at path "^path'); let result = {(t) with m_kind = handle_kind path' t t.m_kind; m_name = path'} in result.m_info <- add_renamed_module ~old:(t.m_name,t.m_info) ~current:(path',None); (match get_documents t.m_info with | [] -> verbose ("No @documents for module "^t.m_name) | l -> List.iter (fun r -> verbose ("Manual @documents of module "^r^" with "^path'); result.m_info <- add_renamed_module ~old:(r,None) ~current:(path',result.m_info)) l); (match get_documented t.m_info with | [] -> verbose ("No @documented for module "^t.m_name) | l -> List.iter (fun r -> verbose ("Manual @documented of module "^r^" with "^path'); result.m_info <- add_renamed_module ~current:(r,None) ~old:(path',result.m_info)) l); result and handle_module_type path m (t:Odoc_module.t_module_type) = let path' = concat path (Name.simple t.mt_name) in verbose ("Visiting module "^t.mt_name^" from "^m.m_name^", at path "^path'); let result = {(t) with mt_kind = (match t.mt_kind with | None -> None | Some kind -> Some (handle_type_kind path' m kind)); mt_name = path'} in add_renamed_module_type t.mt_name path'; result match t.ma_module with | None -> verbose ("I'd like to merge information from "^m.m_name^" and "^t.ma_name^" but I can't find that module"); t let rec aux = function | [ ] - > verbose ( " Ca n't do better " ) ; t | x::xs - > if Name.prefix x t.ma_name then let suffix = Name.get_relative x t.ma_name in let info = add_renamed_module ~old:(suffix , ) ~current:(path , None ) in { ( t ) with ma_name = suffix } else aux xs in aux packs | [] -> verbose ("Can't do better"); t | x::xs -> if Name.prefix x t.ma_name then let suffix = Name.get_relative x t.ma_name in let info = add_renamed_module ~old:(suffix, m.m_info) ~current:(path, None) in {(t) with ma_name = suffix} else aux xs in aux packs*) | Some (Mod a) -> verbose ("Merging information from "^m.m_name^" and aliased "^a.m_name); let info = add_renamed_module ~old:(a.m_name,a.m_info) ~current:(path,m.m_info) in m.m_info <- info; a.m_info <- info; let a' = {(a) with m_kind = handle_kind path m a.m_kind} in {(t) with ma_module = Some (Mod a')} | Some (Modtype a) -> verbose ("Merging information from "^m.m_name^" and aliased type "^a.mt_name); m.m_info <- merge_info_opt m.m_info a.mt_info; a.mt_info <- m.m_info; add_renamed_module_type a.mt_name path; let info = Odoc_merge.merge_info_opt Odoc_types.all_merge_options m.m_info a.mt_info in let a' = match a.mt_kind with | None -> a | Some kind -> {(a) with mt_kind = Some (handle_type_kind path m kind); mt_info = info} in {(t) with ma_module = Some (Modtype a')} and handle_type_kind path m :module_type_kind -> module_type_kind = function | Module_type_struct x -> Module_type_struct (List.flatten (List.map (handle_module_element path m) x)) | Module_type_functor (p, x)-> Module_type_functor (p, handle_type_kind path m x) | Module_type_alias x -> Module_type_alias (handle_type_alias path m x) | Module_type_with (k, s) -> Module_type_with (handle_type_kind path m k, s) and handle_type_alias path m t = match t.mta_module with verbose ( " module type " ^t.mta_name^ " not resolved in cross - reference stage " ) ; | Some a -> if a.mt_info < > None then < - a.mt_info ; add_renamed_module_type a.mt_name path; let info = Odoc_merge.merge_info_opt Odoc_types.all_merge_options m.m_info a.mt_info in {(t) with mta_module = Some ({(a) with mt_name = concat m.m_name a.mt_name; mt_info = info})} in 1 . Find root modules , i.e. modules which are neither included nor aliased let all_roots = Hashtbl.create 100 in List.iter ( fun x - > if x.m_name = " " then ( ( * verbose ( " Adding " ^x.m_name^ " to the list of roots " ) ; List.iter (fun x -> if Name.father x.m_name = "" then ( Hashtbl.add all_roots x.m_name x ) modules; List.iter (fun x -> begin Hashtbl.remove all_roots y end) modules; Hashtbl.iter (fun name _ -> verbose ("Root: "^name)) all_roots; let for_rewriting = Hashtbl.fold ( fun k m acc - > if List.mem k roots then begin verbose ( " Rewriting : " ) ; ( k , m)::acc end else begin verbose ( " Not rewriting : " ) ; acc end ) all_roots [ ] in begin verbose ("Rewriting: " ^k); (k,m)::acc end else begin verbose ("Not rewriting: "^k); acc end) all_roots [] in*) let for_rewriting = List.fold_left (fun acc x -> Hashtbl.add all_modules x.m_name x; if List.mem x.m_name roots then begin verbose ("We need to visit module "^x.m_name); (x.m_name, x)::acc end else begin verbose ("Discarding module "^x.m_name^" for now"); acc end) [] modules in verbose ("[Starting to rearrange module structure]"); let for_rewriting = Hashtbl.fold ( fun k m acc - > ( k , m)::acc ) all_roots [ ] in 2 . Dive into these let rewritten = List.fold_left (fun acc (name, contents) -> {(contents) with m_kind = handle_kind "" contents contents.m_kind}::acc) [] for_rewriting in let result = Search.modules rewritten in TODO : Second pass : walk through references -- handled during html generation for the moment (result, all_renamed_modules) let sort_by_topics modules = let write s = verbose ( "[SORT] "^s ) in let rec string_of_path = function | [] -> "" | (`Level l)::t -> Printf.sprintf "[%d] > %s" l (string_of_path t) | (`Topic top)::t -> Printf.sprintf "%s > %s" top (string_of_path t) in let write s = Printf.eprintf " [ SORT ] % s\n% ! " s in in let add_module top m = write ("Adding module "^m.m_name); List.iter (function `Topic t -> write ("Adding module "^m.m_name^" to topic "^t); ( try let l = Hashtbl.find modules_by_topic t in l := m :: !l with Not_found -> Hashtbl.add modules_by_topic t (ref [m]) ) | _ -> ()) top in write ("Adding topic "^t); topics := StringSet.add t !topics; let result = (`Topic t)::l in write ("Added topics from "^(string_of_path l)^" to "^(string_of_path result)); result write ("Entering level "^(string_of_int t)); let result = (`Level t)::l in write ("Entered level from "^(string_of_path l)^" to "^(string_of_path result)); result and pop_top_to_level l level = write ("Removing levels higher than "^(string_of_int level)); let rec aux prefix = function | (`Level l')::t when l' >= level -> aux [] t | ((`Topic _ ) as p)::t -> aux (p::prefix) t | _ as t -> List.rev_append prefix t in let result = aux [] l in write("From "^(string_of_path l)^" to "^(string_of_path result)); result in let adjust_to_level top level = write ("Moving to level "^(string_of_int level)); let result = push_top_level (pop_top_to_level top level) level in write("Moved levels from "^(string_of_path top)^" to "^(string_of_path result)); result in let adjust_top_from_comment top c = fold_left (fun acc text -> match text with | Title (level, title, text) -> adjust_to_level acc level | Custom (("topic" | "{topic"), text) -> write ("Custom topic "^(string_of_text text)); push_top_topic acc (string_of_text text) | Custom (other, _) -> write ("Custom other "^other); acc | _ -> acc ) top c in let adjust_top_from_info top = function | None -> top | Some ({i_custom = l} as i) -> write ("Meeting custom in info "^(string_of_info i)); List.fold_left (fun acc -> function (("topic"|"{topic"), t) -> write ("Custom topic in info "^(string_of_text t)); push_top_topic acc (string_of_text t) | (other, content) -> write ("Custom other in info "^other^": "^(string_of_text content)); acc | _ - > acc in let rec handle_kind top = function | Module_struct x -> List.fold_left handle_module_element top x | _ -> top and handle_module_element top = function | Element_module x -> let top' = adjust_top_from_info top x.m_info in add_module top' x; ignore (handle_kind top' x.m_kind); top | Element_module_comment c -> adjust_top_from_comment top c and handle_module top m = handle_kind (adjust_top_from_info top m.m_info) m.m_kind in let _ = List.fold_left handle_module [] modules in (StringSet.elements !topics, modules_by_topic) let find_renaming renamings original = let rec aux s suffix = if String.length s = 0 then ( suffix ) else let renaming = try Some (fst(Hashtbl.find renamings s)) with Not_found -> None in match renaming with | None -> let father = Name.father s in let son = Name.get_relative father s in aux father (concat son suffix) let result = concat r suffix in verbose ( " We have a renaming of " ^s^ " to " ^r ) ; verbose ("Name "^original^" replaced with "^result); result in aux original ""
4c7ff72d24bd73742f684a8543f8ff07884aca5401cb7542d1ec7bfa4fc0b148
pauleve/pint
an_cli.ml
open PintTypes open AutomataNetwork let parse_local_state an data = let sig_ls = An_input.parse_string An_parser.local_state data in resolve_sig_ls an sig_ls let parse_sls_list = An_input.parse_string An_parser.local_state_list let parse_local_state_list an data = let sls = parse_sls_list data in List.map (resolve_sig_ls an) sls let arg_string_set f ref = Arg.String (fun s -> ref := f s) let arg_set_sls_list = arg_string_set parse_sls_list let opt_json_stdout = ref false let common_cmdopts = [ ("--no-debug", Arg.Clear Debug.dodebug, "Disable debugging"); ("--debug", Arg.Set Debug.dodebug, "Enable debugging"); ("--debug-level", Arg.Set_int Debug.debuglevel, "Maximum debug level"); ("--version", Arg.Unit (fun () -> print_endline ("Pint version "^Pintmeta.version); ignore(exit 0)), "Print Pint version and quit"); ("--json-stdout", Arg.Set opt_json_stdout, "Output in JSON format"); ] (** Input options **) let opt_channel_in = ref stdin let opt_filename_in = ref "<stdin>" let setup_opt_channel_in filename = opt_filename_in := filename; opt_channel_in := open_in filename let opt_override_ctx = ref [] let input_cmdopts = [ ("-i", Arg.String setup_opt_channel_in, "<model.an>\tInput filename"); ("--initial-state", arg_set_sls_list opt_override_ctx, "<local state list>\tInitial state"); ("--initial-context", arg_set_sls_list opt_override_ctx, "<local state list>\tInitial context (equivalent to --initial-state)"); ] (** Main usage **) let parse cmdopts usage_msg = let opt_anonargs = ref ([]:string list) in let anon_fun arg = opt_anonargs := !opt_anonargs @ [arg] in Arg.parse cmdopts anon_fun usage_msg; !opt_anonargs, (fun () -> Arg.usage cmdopts usage_msg; raise Exit) let process_input () = let an, ctx = An_input.parse !opt_channel_in in let user_ctx = ctx_of_siglocalstates an !opt_override_ctx in let ctx = ctx_override_by_ctx ctx user_ctx in an, ctx let prepare_goal (an, ctx) args = let goal_spec = String.concat " " args in let sig_goal = An_input.parse_string An_parser.goals goal_spec in let default_injection () = An_reach.inject_goal_automaton (an, ctx) sig_goal in match sig_goal with [] | [[]] -> failwith "No goal specified." | [[sig_state]] -> if SMap.cardinal sig_state = 1 then let sig_ls = SMap.choose sig_state in (an, ctx), resolve_sig_ls an sig_ls, [] else default_injection () | _ -> default_injection ()
null
https://raw.githubusercontent.com/pauleve/pint/7cf943ec60afcf285c368950925fd45f59f66f4a/anlib/an_cli.ml
ocaml
* Input options * * Main usage *
open PintTypes open AutomataNetwork let parse_local_state an data = let sig_ls = An_input.parse_string An_parser.local_state data in resolve_sig_ls an sig_ls let parse_sls_list = An_input.parse_string An_parser.local_state_list let parse_local_state_list an data = let sls = parse_sls_list data in List.map (resolve_sig_ls an) sls let arg_string_set f ref = Arg.String (fun s -> ref := f s) let arg_set_sls_list = arg_string_set parse_sls_list let opt_json_stdout = ref false let common_cmdopts = [ ("--no-debug", Arg.Clear Debug.dodebug, "Disable debugging"); ("--debug", Arg.Set Debug.dodebug, "Enable debugging"); ("--debug-level", Arg.Set_int Debug.debuglevel, "Maximum debug level"); ("--version", Arg.Unit (fun () -> print_endline ("Pint version "^Pintmeta.version); ignore(exit 0)), "Print Pint version and quit"); ("--json-stdout", Arg.Set opt_json_stdout, "Output in JSON format"); ] let opt_channel_in = ref stdin let opt_filename_in = ref "<stdin>" let setup_opt_channel_in filename = opt_filename_in := filename; opt_channel_in := open_in filename let opt_override_ctx = ref [] let input_cmdopts = [ ("-i", Arg.String setup_opt_channel_in, "<model.an>\tInput filename"); ("--initial-state", arg_set_sls_list opt_override_ctx, "<local state list>\tInitial state"); ("--initial-context", arg_set_sls_list opt_override_ctx, "<local state list>\tInitial context (equivalent to --initial-state)"); ] let parse cmdopts usage_msg = let opt_anonargs = ref ([]:string list) in let anon_fun arg = opt_anonargs := !opt_anonargs @ [arg] in Arg.parse cmdopts anon_fun usage_msg; !opt_anonargs, (fun () -> Arg.usage cmdopts usage_msg; raise Exit) let process_input () = let an, ctx = An_input.parse !opt_channel_in in let user_ctx = ctx_of_siglocalstates an !opt_override_ctx in let ctx = ctx_override_by_ctx ctx user_ctx in an, ctx let prepare_goal (an, ctx) args = let goal_spec = String.concat " " args in let sig_goal = An_input.parse_string An_parser.goals goal_spec in let default_injection () = An_reach.inject_goal_automaton (an, ctx) sig_goal in match sig_goal with [] | [[]] -> failwith "No goal specified." | [[sig_state]] -> if SMap.cardinal sig_state = 1 then let sig_ls = SMap.choose sig_state in (an, ctx), resolve_sig_ls an sig_ls, [] else default_injection () | _ -> default_injection ()
9993815f51fb59f6d46bb768578c555e06bd78a3a14b5eec943b5b16e480d7d0
TyOverby/mono
types.ml
This file defines the mutually recursive types at the heart of Async . The functions associated with the types are defined in the corresponding file(s ) for each module . This file should define only types , not functions , since functions defined inside the recursive modules are not inlined . If you need to add functionality to a module but doing so would create a dependency cycle , split the file into pieces as needed to break the cycle , e.g. scheduler0.ml , scheduler1.ml , scheduler.ml . associated with the types are defined in the corresponding file(s) for each module. This file should define only types, not functions, since functions defined inside the recursive modules are not inlined. If you need to add functionality to a module but doing so would create a dependency cycle, split the file into pieces as needed to break the cycle, e.g. scheduler0.ml, scheduler1.ml, scheduler.ml. *) open! Core open! Import module rec Cell : sig type any = [ `Empty | `Empty_one_handler | `Empty_one_or_more_handlers | `Full | `Indir ] type ('a, 'b) t = | Empty_one_or_more_handlers : { mutable run : 'a -> unit ; execution_context : Execution_context.t ; mutable prev : 'a Handler.t ; mutable next : 'a Handler.t } -> ('a, [> `Empty_one_or_more_handlers ]) t | Empty_one_handler : ('a -> unit) * Execution_context.t -> ('a, [> `Empty_one_handler ]) t | Empty : ('a, [> `Empty ]) t | Full : 'a -> ('a, [> `Full ]) t | Indir : 'a Ivar.t -> ('a, [> `Indir ]) t end = Cell and Handler : sig type 'a t = ('a, [ `Empty_one_or_more_handlers ]) Cell.t end = Handler and Ivar : sig type 'a t = { mutable cell : ('a, Cell.any) Cell.t } module Immutable : sig type 'a t = { cell : ('a, Cell.any) Cell.t } end end = Ivar and Deferred : sig type +'a t end = Deferred and Execution_context : sig type t = { monitor : Monitor.t ; priority : Priority.t ; local_storage : Univ_map.t ; backtrace_history : Backtrace.t list } end = Execution_context and Forwarding : sig type t = | Detached | Parent of Monitor.t | Report_uncaught_exn end = Forwarding and Monitor : sig type t = { name : Info.t ; here : Source_code_position.t option ; id : int ; mutable next_error : exn Ivar.t ; mutable handlers_for_all_errors : (Execution_context.t * (exn -> unit)) Bag.t ; mutable tails_for_all_errors : exn Tail.t list ; mutable has_seen_error : bool ; mutable forwarding : Forwarding.t } end = Monitor and Tail : sig type 'a t = { mutable next : 'a Stream.next Ivar.t } end = Tail and Stream : sig type 'a t = 'a next Deferred.t and 'a next = | Nil | Cons of 'a * 'a t end = Stream We avoid using [ module rec ] to define [ ] , so that [ to_repr ] and [ of_repr ] are inlined . inlined. *) module Bvar : sig type ('a, -'permission) t (** [repr] exists so that we may hide the implementation of a [Bvar.t], and then add a phantom type to it upstream. Without this, the phantom type variable would allow for anything to be coerced in and out, since it is unused. *) type 'a repr = { mutable has_any_waiters : bool ; mutable ivar : 'a Ivar.t } val of_repr : 'a repr -> ('a, 'permission) t val to_repr : ('a, 'permission) t -> 'a repr end = struct type 'a repr = { mutable has_any_waiters : bool ; mutable ivar : 'a Ivar.t } type ('a, 'permission) t = 'a repr let to_repr t = t let of_repr t = t end module rec Event : sig module Status : sig type t = | Fired | Happening | Scheduled | Unscheduled end module Option : sig type t end type t = { mutable alarm : Job_or_event.t Timing_wheel.Alarm.t ; mutable at : Time_ns.t ; callback : unit -> unit ; execution_context : Execution_context.t ; mutable interval : Time_ns.Span.t option ; mutable next_fired : Option.t ; mutable prev_fired : Option.t ; mutable status : Status.t } end = Event and External_job : sig type t = T : Execution_context.t * ('a -> unit) * 'a -> t end = External_job and Job : sig type slots = (Execution_context.t, Obj.t -> unit, Obj.t) Pool.Slots.t3 type t = slots Pool.Pointer.t end = Job and Job_or_event : sig type t end = Job_or_event and Job_pool : sig type t = Job.slots Pool.t end = Job_pool and Job_queue : sig type t = { mutable num_jobs_run : int ; mutable jobs_left_this_cycle : int ; mutable jobs : Obj.t Uniform_array.t ; mutable mask : int ; mutable front : int ; mutable length : int } end = Job_queue and Jobs : sig type t = { scheduler : Scheduler.t ; mutable job_pool : Job_pool.t ; normal : Job_queue.t ; low : Job_queue.t } end = Jobs and Scheduler : sig type t = { mutable check_access : (unit -> unit) option ; mutable job_pool : Job_pool.t ; normal_priority_jobs : Job_queue.t ; low_priority_jobs : Job_queue.t ; very_low_priority_workers : Very_low_priority_worker.t Deque.t ; mutable main_execution_context : Execution_context.t ; mutable current_execution_context : Execution_context.t ; mutable uncaught_exn : (Exn.t * Sexp.t) option ; mutable cycle_count : int ; mutable cycle_start : Time_ns.t ; mutable in_cycle : bool ; mutable run_every_cycle_start : Cycle_hook.t list ; run_every_cycle_start_state : (Cycle_hook_handle.t, Cycle_hook.t) Hashtbl.t ; mutable run_every_cycle_end : Cycle_hook.t list ; run_every_cycle_end_state : (Cycle_hook_handle.t, Cycle_hook.t) Hashtbl.t ; mutable last_cycle_time : Time_ns.Span.t ; mutable last_cycle_num_jobs : int ; mutable total_cycle_time : Time_ns.Span.t ; mutable time_source : read_write Time_source.t1 ; external_jobs : External_job.t Thread_safe_queue.t ; mutable thread_safe_external_job_hook : unit -> unit ; mutable job_queued_hook : (Priority.t -> unit) option ; mutable event_added_hook : (Time_ns.t -> unit) option ; mutable yield : (unit, read_write) Bvar.t ; mutable yield_until_no_jobs_remain : (unit, read_write) Bvar.t ; mutable check_invariants : bool ; mutable max_num_jobs_per_priority_per_cycle : Max_num_jobs_per_priority_per_cycle.t ; mutable record_backtraces : bool } end = Scheduler and Cycle_hook : sig type t = unit -> unit end = Cycle_hook and Cycle_hook_handle : Unique_id.Id = Unique_id.Int63 () and Time_source_id : Unique_id.Id = Unique_id.Int63 () and Time_source : sig type -'rw t1 = { id : Time_source_id.t ; mutable advance_errors : Error.t list ; mutable am_advancing : bool ; events : Job_or_event.t Timing_wheel.t ; mutable fired_events : Event.Option.t ; mutable most_recently_fired : Event.Option.t ; handle_fired : Job_or_event.t Timing_wheel.Alarm.t -> unit ; is_wall_clock : bool ; scheduler : Scheduler.t } end = Time_source and Very_low_priority_worker : sig module Exec_result : sig type t = | Finished | Not_finished end type t = { execution_context : Execution_context.t ; exec : unit -> Exec_result.t } end = Very_low_priority_worker
null
https://raw.githubusercontent.com/TyOverby/mono/5ce4569fc6edf6564d29d37b66d455549df1e497/vendor/janestreet-async_kernel/src/types.ml
ocaml
* [repr] exists so that we may hide the implementation of a [Bvar.t], and then add a phantom type to it upstream. Without this, the phantom type variable would allow for anything to be coerced in and out, since it is unused.
This file defines the mutually recursive types at the heart of Async . The functions associated with the types are defined in the corresponding file(s ) for each module . This file should define only types , not functions , since functions defined inside the recursive modules are not inlined . If you need to add functionality to a module but doing so would create a dependency cycle , split the file into pieces as needed to break the cycle , e.g. scheduler0.ml , scheduler1.ml , scheduler.ml . associated with the types are defined in the corresponding file(s) for each module. This file should define only types, not functions, since functions defined inside the recursive modules are not inlined. If you need to add functionality to a module but doing so would create a dependency cycle, split the file into pieces as needed to break the cycle, e.g. scheduler0.ml, scheduler1.ml, scheduler.ml. *) open! Core open! Import module rec Cell : sig type any = [ `Empty | `Empty_one_handler | `Empty_one_or_more_handlers | `Full | `Indir ] type ('a, 'b) t = | Empty_one_or_more_handlers : { mutable run : 'a -> unit ; execution_context : Execution_context.t ; mutable prev : 'a Handler.t ; mutable next : 'a Handler.t } -> ('a, [> `Empty_one_or_more_handlers ]) t | Empty_one_handler : ('a -> unit) * Execution_context.t -> ('a, [> `Empty_one_handler ]) t | Empty : ('a, [> `Empty ]) t | Full : 'a -> ('a, [> `Full ]) t | Indir : 'a Ivar.t -> ('a, [> `Indir ]) t end = Cell and Handler : sig type 'a t = ('a, [ `Empty_one_or_more_handlers ]) Cell.t end = Handler and Ivar : sig type 'a t = { mutable cell : ('a, Cell.any) Cell.t } module Immutable : sig type 'a t = { cell : ('a, Cell.any) Cell.t } end end = Ivar and Deferred : sig type +'a t end = Deferred and Execution_context : sig type t = { monitor : Monitor.t ; priority : Priority.t ; local_storage : Univ_map.t ; backtrace_history : Backtrace.t list } end = Execution_context and Forwarding : sig type t = | Detached | Parent of Monitor.t | Report_uncaught_exn end = Forwarding and Monitor : sig type t = { name : Info.t ; here : Source_code_position.t option ; id : int ; mutable next_error : exn Ivar.t ; mutable handlers_for_all_errors : (Execution_context.t * (exn -> unit)) Bag.t ; mutable tails_for_all_errors : exn Tail.t list ; mutable has_seen_error : bool ; mutable forwarding : Forwarding.t } end = Monitor and Tail : sig type 'a t = { mutable next : 'a Stream.next Ivar.t } end = Tail and Stream : sig type 'a t = 'a next Deferred.t and 'a next = | Nil | Cons of 'a * 'a t end = Stream We avoid using [ module rec ] to define [ ] , so that [ to_repr ] and [ of_repr ] are inlined . inlined. *) module Bvar : sig type ('a, -'permission) t type 'a repr = { mutable has_any_waiters : bool ; mutable ivar : 'a Ivar.t } val of_repr : 'a repr -> ('a, 'permission) t val to_repr : ('a, 'permission) t -> 'a repr end = struct type 'a repr = { mutable has_any_waiters : bool ; mutable ivar : 'a Ivar.t } type ('a, 'permission) t = 'a repr let to_repr t = t let of_repr t = t end module rec Event : sig module Status : sig type t = | Fired | Happening | Scheduled | Unscheduled end module Option : sig type t end type t = { mutable alarm : Job_or_event.t Timing_wheel.Alarm.t ; mutable at : Time_ns.t ; callback : unit -> unit ; execution_context : Execution_context.t ; mutable interval : Time_ns.Span.t option ; mutable next_fired : Option.t ; mutable prev_fired : Option.t ; mutable status : Status.t } end = Event and External_job : sig type t = T : Execution_context.t * ('a -> unit) * 'a -> t end = External_job and Job : sig type slots = (Execution_context.t, Obj.t -> unit, Obj.t) Pool.Slots.t3 type t = slots Pool.Pointer.t end = Job and Job_or_event : sig type t end = Job_or_event and Job_pool : sig type t = Job.slots Pool.t end = Job_pool and Job_queue : sig type t = { mutable num_jobs_run : int ; mutable jobs_left_this_cycle : int ; mutable jobs : Obj.t Uniform_array.t ; mutable mask : int ; mutable front : int ; mutable length : int } end = Job_queue and Jobs : sig type t = { scheduler : Scheduler.t ; mutable job_pool : Job_pool.t ; normal : Job_queue.t ; low : Job_queue.t } end = Jobs and Scheduler : sig type t = { mutable check_access : (unit -> unit) option ; mutable job_pool : Job_pool.t ; normal_priority_jobs : Job_queue.t ; low_priority_jobs : Job_queue.t ; very_low_priority_workers : Very_low_priority_worker.t Deque.t ; mutable main_execution_context : Execution_context.t ; mutable current_execution_context : Execution_context.t ; mutable uncaught_exn : (Exn.t * Sexp.t) option ; mutable cycle_count : int ; mutable cycle_start : Time_ns.t ; mutable in_cycle : bool ; mutable run_every_cycle_start : Cycle_hook.t list ; run_every_cycle_start_state : (Cycle_hook_handle.t, Cycle_hook.t) Hashtbl.t ; mutable run_every_cycle_end : Cycle_hook.t list ; run_every_cycle_end_state : (Cycle_hook_handle.t, Cycle_hook.t) Hashtbl.t ; mutable last_cycle_time : Time_ns.Span.t ; mutable last_cycle_num_jobs : int ; mutable total_cycle_time : Time_ns.Span.t ; mutable time_source : read_write Time_source.t1 ; external_jobs : External_job.t Thread_safe_queue.t ; mutable thread_safe_external_job_hook : unit -> unit ; mutable job_queued_hook : (Priority.t -> unit) option ; mutable event_added_hook : (Time_ns.t -> unit) option ; mutable yield : (unit, read_write) Bvar.t ; mutable yield_until_no_jobs_remain : (unit, read_write) Bvar.t ; mutable check_invariants : bool ; mutable max_num_jobs_per_priority_per_cycle : Max_num_jobs_per_priority_per_cycle.t ; mutable record_backtraces : bool } end = Scheduler and Cycle_hook : sig type t = unit -> unit end = Cycle_hook and Cycle_hook_handle : Unique_id.Id = Unique_id.Int63 () and Time_source_id : Unique_id.Id = Unique_id.Int63 () and Time_source : sig type -'rw t1 = { id : Time_source_id.t ; mutable advance_errors : Error.t list ; mutable am_advancing : bool ; events : Job_or_event.t Timing_wheel.t ; mutable fired_events : Event.Option.t ; mutable most_recently_fired : Event.Option.t ; handle_fired : Job_or_event.t Timing_wheel.Alarm.t -> unit ; is_wall_clock : bool ; scheduler : Scheduler.t } end = Time_source and Very_low_priority_worker : sig module Exec_result : sig type t = | Finished | Not_finished end type t = { execution_context : Execution_context.t ; exec : unit -> Exec_result.t } end = Very_low_priority_worker
3771a8cee68753d133ae01639fa9ae24eb24dfa5bf8adf8f0f819ba6a836181a
zalando/friboo
http.clj
(ns org.zalando.stups.friboo.system.http (:require [io.sarnowski.swagger1st.executor :as s1stexec] [io.clj.logging :refer [with-logging-context]] [ring.util.response :as r] [org.zalando.stups.friboo.ring :as ring] [org.zalando.stups.friboo.log :as log] [io.sarnowski.swagger1st.util.api :as api] [io.sarnowski.swagger1st.core :as s1st] [io.sarnowski.swagger1st.util.api :as s1stapi] [ring.adapter.jetty :as jetty] [ring.middleware.gzip :as gzip] [com.stuartsierra.component :refer [Lifecycle]]) (:import (com.netflix.hystrix.exception HystrixRuntimeException) (org.zalando.stups.txdemarcator Transactions) (clojure.lang ExceptionInfo))) (defn merged-parameters "According to the swagger spec, parameter names are only unique with their type. This one assumes that parameter names are unique in general and flattens them for easier access." [request] (apply merge (vals (:parameters request)))) (defn make-resolver-fn [controller] "Calls operationId function with controller, flattened request params and raw request map." (fn [request-definition] (when-let [operation-fn (s1stexec/operationId-to-function request-definition)] (fn [request] (operation-fn controller (merged-parameters request) request))))) (defn middleware-chain [context middlewares] (reduce #(%2 %1) context middlewares)) (defn flatten1 "Flattens the collection one level, for example, converts {:a 1 :b 2} to (:a 1 :b 2)." [coll] (apply concat coll)) (defn- with-flattened-options-map "If f is defined like this: `(defn f [first-arg & {:keys [a b] :as opts}] ... )` makes it convenient to pass `opts` as a map: `(-> first-arg (with-flattened-options-map f {:a 1 :b 2}))` will result in `(f first-arg :a 1 :b 2)` Used in `start-component` for clarity. " [first-arg f options] (apply f first-arg (flatten1 options))) (defn allow-all "Returns a swagger1st security handler that allows everything." [] (fn [request definition requirements] request)) ;; Security handler types according to /#securitySchemeObject (def allow-all-handlers {"oauth2" (allow-all) "basic" (allow-all) "apiKey" (allow-all)}) (defn start-component [{:as this :keys [api-resource configuration middlewares security-handlers controller s1st-options]}] (log/info "Starting HTTP daemon for API %s" api-resource) (when (:handler this) (throw (ex-info "Component already started, aborting." {}))) ;; Refer to default-middlewares object below for middleware lists ;; Create context from the YAML definition on the classpath, optionally provide validation flag (let [handler (-> (apply s1st/context :yaml-cp api-resource (flatten1 (:context s1st-options))) ;; Some middleware will need to access the component later (assoc :component this) ;; User can provide additional handlers to be executed before discoverer (middleware-chain (:before-discoverer middlewares)) ;; Enables paths for API discovery, like /ui, /swagger.json and /.well-known/schema-discovery (with-flattened-options-map s1st/discoverer (:discoverer s1st-options)) ;; User can provide additional handlers to be executed before mapper (middleware-chain (:before-mapper middlewares)) ;; Given a path, figures out the spec part describing it (s1st/mapper) ;; User can provide additional handlers to be executed before protector (middleware-chain (:before-protector middlewares)) ;; Enforces security according to the settings, depends on the spec from mapper (s1st/protector (merge allow-all-handlers security-handlers)) ;; User can provide additional handlers to be executed before parser (middleware-chain (:before-parser middlewares)) ;; Extracts parameter values from path, query and body of the request (with-flattened-options-map s1st/parser (:parser s1st-options)) ;; User can provide additional handlers to be executed before executor (middleware-chain (:before-executor middlewares)) ;; Calls the handler function for the request. Customizable through :resolver (with-flattened-options-map s1st/executor (merge {:resolver (make-resolver-fn controller)} (:executor s1st-options))))] (merge this {:handler handler :httpd (jetty/run-jetty handler (merge configuration {:join? false}))}))) (defn stop-component "Stops the Http component." [{:as this :keys [handler httpd]}] (if-not handler (do (log/debug "Skipping stop of Http because it's not running.") this) (do (log/info "Stopping Http.") (when httpd (.stop httpd)) (dissoc this :handler :httpd)))) (defrecord Http [;; parameters (filled in by make-http on creation) api-resource configuration security-handlers middlewares s1st-options ;; dependencies (filled in by the component library before starting) controller metrics audit-log ;; runtime vals (filled in by start-component) httpd handler] Lifecycle (start [this] (start-component this)) (stop [this] (stop-component this))) (defn redirect-to-swagger-ui "Can be used as operationId for GET /" [& _] (ring.util.response/redirect "/ui/")) # # Middleware (defn wrap-default-content-type [next-handler content-type] (fn [request] (let [response (next-handler request)] (if (get-in response [:headers "Content-Type"]) response (assoc-in response [:headers "Content-Type"] content-type))))) (defn compute-request-info "Creates a nice, readable request info text for logline prefixing." [request] (str (.toUpperCase (-> request :request-method name)) " " (:uri request) " <- " (if-let [x-forwarded-for (-> request :headers (get "x-forwarded-for"))] x-forwarded-for (:remote-addr request)) (if-let [tokeninfo (:tokeninfo request)] (str " / " (get tokeninfo "uid") " @ " (get tokeninfo "realm")) ""))) (defn enrich-log-lines "Adds HTTP request context information to the logging facility's MDC in the 'request' key." [next-handler] (fn [request] (let [request-info (compute-request-info request)] (with-logging-context {:request (str " [" request-info "]")} (next-handler request))))) (defn health-endpoint "Adds a /.well-known/health endpoint for load balancer tests." [handler] (fn [request] (if (= (:uri request) "/.well-known/health") (-> (r/response "{\"health\": true}") (ring/content-type-json) (r/status 200)) (handler request)))) (defn add-config-to-request "Adds the HTTP configuration to the request object, so that handlers can access it." [next-handler configuration] (fn [request] (next-handler (assoc request :configuration configuration)))) (defn convert-exceptions [next-handler] (fn [request] (try (next-handler request) Hystrix exceptions as 503 (catch HystrixRuntimeException e (let [reason (-> e .getCause .toString) failure-type (str (.getFailureType e))] (log/warn (str "Hystrix: " (.getMessage e) " %s occurred, because %s") failure-type reason) (api/throw-error 503 (str "A dependency is unavailable: " (.getMessage e))))) ;; ex-info pass-through, will be caught inside parser (catch ExceptionInfo e (throw e)) Other exceptions as 500 (catch Exception e (log/error e "Unhandled exception.") (api/throw-error 500 "Internal server error" (str e)))))) (defn mark-transaction "Trigger the TransactionMarker with the swagger operationId for instrumentalisation." [next-handler] (fn [request] (let [operation-id (get-in request [:swagger :request "operationId"]) tx-parent-id (get-in request [:headers Transactions/APPDYNAMICS_HTTP_HEADER])] (Transactions/runInTransaction operation-id tx-parent-id #(next-handler request))))) (def default-middlewares "Default set of ring middlewares that are groupped by s1st phases" {:before-discoverer [#(s1st/ring % add-config-to-request (-> % :component :configuration)) #(s1st/ring % gzip/wrap-gzip) #(s1st/ring % enrich-log-lines) #(s1st/ring % s1stapi/add-hsts-header) #(s1st/ring % s1stapi/add-cors-headers) #(s1st/ring % s1stapi/surpress-favicon-requests) #(s1st/ring % health-endpoint)] :before-mapper [] :before-protector [] :before-parser [#(s1st/ring % mark-transaction)] Convert exceptions to ex - info so that parser creates nice 5xx responses #(s1st/ring % convert-exceptions) ;; now we also know the user, replace request info #(s1st/ring % enrich-log-lines) #(s1st/ring % wrap-default-content-type "application/json")]}) ;; For documentation (def default-s1st-options {;; It's possible to disable validation of the spec ;; :context {:validate? true} :context {} ;; The following parts are customizable: ;; :discoverer {:discovery-path "/.well-known/schema-discovery" ;; :definition-path "/swagger.json" ;; :ui-path "/ui/" ;; :overwrite-host? true } :discoverer {} ;; No available options for parser, this is here for future :parser {} ;; It's possible customize how exactly handler functions should be called ;; :executor {:resolver io.sarnowski.swagger1st.executor/operationId-to-function} :executor {}}) (defn make-http "Creates Http component using mostly default parameters. No security, no additional middlewares." [api-resource configuration] (map->Http {:api-resource api-resource :configuration configuration :middlewares default-middlewares :security-handlers {} ; No security by default :s1st-options default-s1st-options}))
null
https://raw.githubusercontent.com/zalando/friboo/5e312365a57535b0197fd787bd95ffafe6c3f4aa/src/org/zalando/stups/friboo/system/http.clj
clojure
Security handler types according to /#securitySchemeObject Refer to default-middlewares object below for middleware lists Create context from the YAML definition on the classpath, optionally provide validation flag Some middleware will need to access the component later User can provide additional handlers to be executed before discoverer Enables paths for API discovery, like /ui, /swagger.json and /.well-known/schema-discovery User can provide additional handlers to be executed before mapper Given a path, figures out the spec part describing it User can provide additional handlers to be executed before protector Enforces security according to the settings, depends on the spec from mapper User can provide additional handlers to be executed before parser Extracts parameter values from path, query and body of the request User can provide additional handlers to be executed before executor Calls the handler function for the request. Customizable through :resolver parameters (filled in by make-http on creation) dependencies (filled in by the component library before starting) runtime vals (filled in by start-component) ex-info pass-through, will be caught inside parser now we also know the user, replace request info For documentation It's possible to disable validation of the spec :context {:validate? true} The following parts are customizable: :discoverer {:discovery-path "/.well-known/schema-discovery" :definition-path "/swagger.json" :ui-path "/ui/" :overwrite-host? true } No available options for parser, this is here for future It's possible customize how exactly handler functions should be called :executor {:resolver io.sarnowski.swagger1st.executor/operationId-to-function} No security by default
(ns org.zalando.stups.friboo.system.http (:require [io.sarnowski.swagger1st.executor :as s1stexec] [io.clj.logging :refer [with-logging-context]] [ring.util.response :as r] [org.zalando.stups.friboo.ring :as ring] [org.zalando.stups.friboo.log :as log] [io.sarnowski.swagger1st.util.api :as api] [io.sarnowski.swagger1st.core :as s1st] [io.sarnowski.swagger1st.util.api :as s1stapi] [ring.adapter.jetty :as jetty] [ring.middleware.gzip :as gzip] [com.stuartsierra.component :refer [Lifecycle]]) (:import (com.netflix.hystrix.exception HystrixRuntimeException) (org.zalando.stups.txdemarcator Transactions) (clojure.lang ExceptionInfo))) (defn merged-parameters "According to the swagger spec, parameter names are only unique with their type. This one assumes that parameter names are unique in general and flattens them for easier access." [request] (apply merge (vals (:parameters request)))) (defn make-resolver-fn [controller] "Calls operationId function with controller, flattened request params and raw request map." (fn [request-definition] (when-let [operation-fn (s1stexec/operationId-to-function request-definition)] (fn [request] (operation-fn controller (merged-parameters request) request))))) (defn middleware-chain [context middlewares] (reduce #(%2 %1) context middlewares)) (defn flatten1 "Flattens the collection one level, for example, converts {:a 1 :b 2} to (:a 1 :b 2)." [coll] (apply concat coll)) (defn- with-flattened-options-map "If f is defined like this: `(defn f [first-arg & {:keys [a b] :as opts}] ... )` makes it convenient to pass `opts` as a map: `(-> first-arg (with-flattened-options-map f {:a 1 :b 2}))` will result in `(f first-arg :a 1 :b 2)` Used in `start-component` for clarity. " [first-arg f options] (apply f first-arg (flatten1 options))) (defn allow-all "Returns a swagger1st security handler that allows everything." [] (fn [request definition requirements] request)) (def allow-all-handlers {"oauth2" (allow-all) "basic" (allow-all) "apiKey" (allow-all)}) (defn start-component [{:as this :keys [api-resource configuration middlewares security-handlers controller s1st-options]}] (log/info "Starting HTTP daemon for API %s" api-resource) (when (:handler this) (throw (ex-info "Component already started, aborting." {}))) (let [handler (-> (apply s1st/context :yaml-cp api-resource (flatten1 (:context s1st-options))) (assoc :component this) (middleware-chain (:before-discoverer middlewares)) (with-flattened-options-map s1st/discoverer (:discoverer s1st-options)) (middleware-chain (:before-mapper middlewares)) (s1st/mapper) (middleware-chain (:before-protector middlewares)) (s1st/protector (merge allow-all-handlers security-handlers)) (middleware-chain (:before-parser middlewares)) (with-flattened-options-map s1st/parser (:parser s1st-options)) (middleware-chain (:before-executor middlewares)) (with-flattened-options-map s1st/executor (merge {:resolver (make-resolver-fn controller)} (:executor s1st-options))))] (merge this {:handler handler :httpd (jetty/run-jetty handler (merge configuration {:join? false}))}))) (defn stop-component "Stops the Http component." [{:as this :keys [handler httpd]}] (if-not handler (do (log/debug "Skipping stop of Http because it's not running.") this) (do (log/info "Stopping Http.") (when httpd (.stop httpd)) (dissoc this :handler :httpd)))) api-resource configuration security-handlers middlewares s1st-options controller metrics audit-log httpd handler] Lifecycle (start [this] (start-component this)) (stop [this] (stop-component this))) (defn redirect-to-swagger-ui "Can be used as operationId for GET /" [& _] (ring.util.response/redirect "/ui/")) # # Middleware (defn wrap-default-content-type [next-handler content-type] (fn [request] (let [response (next-handler request)] (if (get-in response [:headers "Content-Type"]) response (assoc-in response [:headers "Content-Type"] content-type))))) (defn compute-request-info "Creates a nice, readable request info text for logline prefixing." [request] (str (.toUpperCase (-> request :request-method name)) " " (:uri request) " <- " (if-let [x-forwarded-for (-> request :headers (get "x-forwarded-for"))] x-forwarded-for (:remote-addr request)) (if-let [tokeninfo (:tokeninfo request)] (str " / " (get tokeninfo "uid") " @ " (get tokeninfo "realm")) ""))) (defn enrich-log-lines "Adds HTTP request context information to the logging facility's MDC in the 'request' key." [next-handler] (fn [request] (let [request-info (compute-request-info request)] (with-logging-context {:request (str " [" request-info "]")} (next-handler request))))) (defn health-endpoint "Adds a /.well-known/health endpoint for load balancer tests." [handler] (fn [request] (if (= (:uri request) "/.well-known/health") (-> (r/response "{\"health\": true}") (ring/content-type-json) (r/status 200)) (handler request)))) (defn add-config-to-request "Adds the HTTP configuration to the request object, so that handlers can access it." [next-handler configuration] (fn [request] (next-handler (assoc request :configuration configuration)))) (defn convert-exceptions [next-handler] (fn [request] (try (next-handler request) Hystrix exceptions as 503 (catch HystrixRuntimeException e (let [reason (-> e .getCause .toString) failure-type (str (.getFailureType e))] (log/warn (str "Hystrix: " (.getMessage e) " %s occurred, because %s") failure-type reason) (api/throw-error 503 (str "A dependency is unavailable: " (.getMessage e))))) (catch ExceptionInfo e (throw e)) Other exceptions as 500 (catch Exception e (log/error e "Unhandled exception.") (api/throw-error 500 "Internal server error" (str e)))))) (defn mark-transaction "Trigger the TransactionMarker with the swagger operationId for instrumentalisation." [next-handler] (fn [request] (let [operation-id (get-in request [:swagger :request "operationId"]) tx-parent-id (get-in request [:headers Transactions/APPDYNAMICS_HTTP_HEADER])] (Transactions/runInTransaction operation-id tx-parent-id #(next-handler request))))) (def default-middlewares "Default set of ring middlewares that are groupped by s1st phases" {:before-discoverer [#(s1st/ring % add-config-to-request (-> % :component :configuration)) #(s1st/ring % gzip/wrap-gzip) #(s1st/ring % enrich-log-lines) #(s1st/ring % s1stapi/add-hsts-header) #(s1st/ring % s1stapi/add-cors-headers) #(s1st/ring % s1stapi/surpress-favicon-requests) #(s1st/ring % health-endpoint)] :before-mapper [] :before-protector [] :before-parser [#(s1st/ring % mark-transaction)] Convert exceptions to ex - info so that parser creates nice 5xx responses #(s1st/ring % convert-exceptions) #(s1st/ring % enrich-log-lines) #(s1st/ring % wrap-default-content-type "application/json")]}) :context {} :discoverer {} :parser {} :executor {}}) (defn make-http "Creates Http component using mostly default parameters. No security, no additional middlewares." [api-resource configuration] (map->Http {:api-resource api-resource :configuration configuration :middlewares default-middlewares :s1st-options default-s1st-options}))
351c38f15c8a76330170830b7babedfc5e9a2dc8608ef762359a3a90bf405202
typeable/compaREST
GitHub.hs
module Control.Monad.Freer.GitHub ( GitHub (..), runGitHub, sendGitHub, ) where import Control.Monad.Freer import Control.Monad.Freer.Error import Control.Monad.IO.Class import Data.Aeson import GitHub hiding (Error) import qualified GitHub as GH data GitHub r where SendGHRequest :: FromJSON x => Request 'RW x -> GitHub x runGitHub :: (Member (Error GH.Error) effs, MonadIO (Eff effs)) => Auth -> Eff (GitHub ': effs) ~> Eff effs runGitHub auth = interpret ( \(SendGHRequest req) -> liftIO (executeRequest auth req) >>= either throwError pure ) sendGitHub :: (FromJSON x, Member GitHub effs) => Request 'RW x -> Eff effs x sendGitHub req = send $ SendGHRequest req
null
https://raw.githubusercontent.com/typeable/compaREST/6d8a67339c0e7b20a6c721eec7a2db093a0311fc/github-action/Control/Monad/Freer/GitHub.hs
haskell
module Control.Monad.Freer.GitHub ( GitHub (..), runGitHub, sendGitHub, ) where import Control.Monad.Freer import Control.Monad.Freer.Error import Control.Monad.IO.Class import Data.Aeson import GitHub hiding (Error) import qualified GitHub as GH data GitHub r where SendGHRequest :: FromJSON x => Request 'RW x -> GitHub x runGitHub :: (Member (Error GH.Error) effs, MonadIO (Eff effs)) => Auth -> Eff (GitHub ': effs) ~> Eff effs runGitHub auth = interpret ( \(SendGHRequest req) -> liftIO (executeRequest auth req) >>= either throwError pure ) sendGitHub :: (FromJSON x, Member GitHub effs) => Request 'RW x -> Eff effs x sendGitHub req = send $ SendGHRequest req
078c0204ef21b5b59b6b492849ae7311fcbb07c7aa0df100ac250dbcae68f9d3
metaocaml/ber-metaocaml
t210-setfield2.ml
TEST include tool - ocaml - lib flags = " -w a " ocaml_script_as_argument = " true " * setup - ocaml - build - env * * include tool-ocaml-lib flags = "-w a" ocaml_script_as_argument = "true" * setup-ocaml-build-env ** ocaml *) open Lib;; type t = { mutable a : int; mutable b : int; mutable c : int; };; let x = {a = 7; b = 6; c = 5} in x.c <- 11; if x.c <> 11 then raise Not_found; x ;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONSTINT 5 11 PUSHCONSTINT 6 13 PUSHCONSTINT 7 15 MAKEBLOCK3 0 17 PUSHCONSTINT 11 19 PUSHACC1 20 SETFIELD2 21 CONSTINT 11 23 PUSHACC1 24 GETFIELD2 25 NEQ 26 BRANCHIFNOT 33 28 GETGLOBAL Not_found 30 MAKEBLOCK1 0 32 RAISE 33 ACC0 34 POP 1 36 ATOM0 37 SETGLOBAL 39 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONSTINT 5 11 PUSHCONSTINT 6 13 PUSHCONSTINT 7 15 MAKEBLOCK3 0 17 PUSHCONSTINT 11 19 PUSHACC1 20 SETFIELD2 21 CONSTINT 11 23 PUSHACC1 24 GETFIELD2 25 NEQ 26 BRANCHIFNOT 33 28 GETGLOBAL Not_found 30 MAKEBLOCK1 0 32 RAISE 33 ACC0 34 POP 1 36 ATOM0 37 SETGLOBAL T210-setfield2 39 STOP **)
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/tool-ocaml/t210-setfield2.ml
ocaml
TEST include tool - ocaml - lib flags = " -w a " ocaml_script_as_argument = " true " * setup - ocaml - build - env * * include tool-ocaml-lib flags = "-w a" ocaml_script_as_argument = "true" * setup-ocaml-build-env ** ocaml *) open Lib;; type t = { mutable a : int; mutable b : int; mutable c : int; };; let x = {a = 7; b = 6; c = 5} in x.c <- 11; if x.c <> 11 then raise Not_found; x ;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONSTINT 5 11 PUSHCONSTINT 6 13 PUSHCONSTINT 7 15 MAKEBLOCK3 0 17 PUSHCONSTINT 11 19 PUSHACC1 20 SETFIELD2 21 CONSTINT 11 23 PUSHACC1 24 GETFIELD2 25 NEQ 26 BRANCHIFNOT 33 28 GETGLOBAL Not_found 30 MAKEBLOCK1 0 32 RAISE 33 ACC0 34 POP 1 36 ATOM0 37 SETGLOBAL 39 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONSTINT 5 11 PUSHCONSTINT 6 13 PUSHCONSTINT 7 15 MAKEBLOCK3 0 17 PUSHCONSTINT 11 19 PUSHACC1 20 SETFIELD2 21 CONSTINT 11 23 PUSHACC1 24 GETFIELD2 25 NEQ 26 BRANCHIFNOT 33 28 GETGLOBAL Not_found 30 MAKEBLOCK1 0 32 RAISE 33 ACC0 34 POP 1 36 ATOM0 37 SETGLOBAL T210-setfield2 39 STOP **)
112b4a1d35dd9541650f9505b4a361c83c70f901ca34e5ce1c2cc8a28833c7e4
smallmelon/sdzmmo
data_skill.erl
%%%--------------------------------------- %%% @Module : data_skill @Author : xyao %%% @Email : @Created : 2010 - 08 - 20 10:46:47 %%% @Description: 自动生成 %%%--------------------------------------- -module(data_skill). -export([get/2, get_ids/1]). -include("record.hrl"). get_ids(1) -> [101101,101102,101201,102101,102301,103101,103301,104301,105101,105301,106101]; get_ids(2) -> [301101,301102,301201,302301,302501,303101,303301,304101,305101,305501,306101]; get_ids(3) -> [201101,201102,201201,202101,202301,203101,203301,204101,205301,205401,206101]. get(101101, Lv) -> #ets_skill{ id=101101, name = <<"基本刀法">>, desc = <<"初入江湖的基本刀法,只能用来教训一下地痞混混">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 800, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,1},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 20} ]; Lv == 2 -> [ {condition, [{lv,3},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 40} ]; Lv == 3 -> [ {condition, [{lv,5},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 60} ]; Lv == 4 -> [ {condition, [{lv,8},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 81} ]; Lv == 5 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 102} ]; Lv == 6 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 123} ]; Lv == 7 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 144} ]; Lv == 8 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 165} ]; Lv == 9 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 186} ]; Lv == 10 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 207} ]; true -> [] end }; get(101102, Lv) -> #ets_skill{ id=101102, name = <<"凌风斩">>, desc = <<"双手挥起宝刀大力劈向对手,造成一定伤害">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 4000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,9},{coin,1000},{skill1,101101,3},{skill2,0,0}]}, {mp_out, 18}, {att, 1.05}, {hurt_add, 60} ]; Lv == 2 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 21}, {att, 1.07}, {hurt_add, 70} ]; Lv == 3 -> [ {condition, [{lv,13},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 24}, {att, 1.09}, {hurt_add, 80} ]; Lv == 4 -> [ {condition, [{lv,16},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 27}, {att, 1.11}, {hurt_add, 90} ]; Lv == 5 -> [ {condition, [{lv,19},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 30}, {att, 1.13}, {hurt_add, 100} ]; Lv == 6 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 33}, {att, 1.15}, {hurt_add, 110} ]; Lv == 7 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 36}, {att, 1.17}, {hurt_add, 120} ]; Lv == 8 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 39}, {att, 1.19}, {hurt_add, 130} ]; Lv == 9 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 42}, {att, 1.21}, {hurt_add, 140} ]; Lv == 10 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {att, 1.25}, {hurt_add, 150} ]; true -> [] end }; get(101201, Lv) -> #ets_skill{ id=101201, name = <<"天罡护体">>, desc = <<"昆仑的健体之术,永久增加人的生命上限">>, career = 1, type = 2, obj = 1, mod = 1, area = 0, cd = 0, lastime = 0, attime = 0, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,5},{coin,1000},{skill1,101101,2},{skill2,0,0}]}, {hp, 101} ]; Lv == 2 -> [ {condition, [{lv,10},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 153} ]; Lv == 3 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 228} ]; Lv == 4 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 331} ]; Lv == 5 -> [ {condition, [{lv,25},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 463} ]; Lv == 6 -> [ {condition, [{lv,30},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 613} ]; Lv == 7 -> [ {condition, [{lv,35},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 784} ]; Lv == 8 -> [ {condition, [{lv,40},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 982} ]; Lv == 9 -> [ {condition, [{lv,45},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 1193} ]; Lv == 10 -> [ {condition, [{lv,50},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 1428} ]; true -> [] end }; get(102101, Lv) -> #ets_skill{ id=102101, name = <<"一夫当关">>, desc = <<"一夫当关,万夫莫开。攻击周围的所有敌人,并且吸引所有注意力">>, career = 1, type = 1, obj = 1, mod = 2, area = 2, cd = 25000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,19},{coin,1000},{skill1,101102,3},{skill2,0,0}]}, {mp_out, 43}, {att, 0.7} ]; Lv == 2 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 46}, {att, 0.75} ]; Lv == 3 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {att, 0.8} ]; Lv == 4 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 52}, {att, 0.85} ]; Lv == 5 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {att, 0.9} ]; Lv == 6 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 58}, {att, 0.95} ]; Lv == 7 -> [ {condition, [{lv,38},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 61}, {att, 1.0} ]; Lv == 8 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 64}, {att, 1.05} ]; Lv == 9 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 67}, {att, 1.1} ]; Lv == 10 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 70}, {att, 1.15} ]; true -> [] end }; get(102301, Lv) -> #ets_skill{ id=102301, name = <<"霸王卸甲">>, desc = <<"舍弃自身的防御,以获得更高的攻击,力求快速打倒敌人">>, career = 1, type = 3, obj = 1, mod = 1, area = 0, cd = 180000, lastime = 30000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,14},{coin,1000},{skill1,101101,3},{skill2,0,0}]}, {mp_out, 81}, {att, 80}, {def_add, 0.85} ]; Lv == 2 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 84}, {att, 153}, {def_add, 0.85} ]; Lv == 3 -> [ {condition, [{lv,18},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 87}, {att, 235}, {def_add, 0.85} ]; Lv == 4 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {att, 325}, {def_add, 0.85} ]; Lv == 5 -> [ {condition, [{lv,24},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {att, 424}, {def_add, 0.85} ]; Lv == 6 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 96}, {att, 532}, {def_add, 0.85} ]; Lv == 7 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {att, 617}, {def_add, 0.85} ]; Lv == 8 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 102}, {att, 702}, {def_add, 0.85} ]; Lv == 9 -> [ {condition, [{lv,46},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 105}, {att, 788}, {def_add, 0.85} ]; Lv == 10 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 108}, {att, 873}, {def_add, 0.85} ]; true -> [] end }; get(103101, Lv) -> #ets_skill{ id=103101, name = <<"我为刀俎">>, desc = <<"我为刀俎,你为鱼肉。攻击敌人,造成伤害,并且降低敌人的防御">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 9000, lastime = 5000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,29},{coin,1000},{skill1,102101,4},{skill2,0,0}]}, {mp_out, 34}, {hurt_add, 1.35} ]; Lv == 2 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 37}, {hurt_add, 1.4} ]; Lv == 3 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 40}, {hurt_add, 1.45} ]; Lv == 4 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {hurt_add, 1.5} ]; Lv == 5 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 46}, {hurt_add, 1.55} ]; Lv == 6 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {hurt_add, 1.6} ]; Lv == 7 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 52}, {hurt_add, 1.65} ]; Lv == 8 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {hurt_add, 1.7} ]; Lv == 9 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 58}, {hurt_add, 1.75} ]; Lv == 10 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 61}, {hurt_add, 1.8} ]; true -> [] end }; get(103301, Lv) -> #ets_skill{ id=103301, name = <<"固若金汤">>, desc = <<"以自我为中心,暂时提升自己及周围队友的防御力">>, career = 1, type = 3, obj = 1, mod = 2, area = 4, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,24},{coin,1000},{skill1,102301,3},{skill2,0,0}]}, {mp_out, 73}, {def_add, 116} ]; Lv == 2 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 76}, {def_add, 156} ]; Lv == 3 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 79}, {def_add, 198} ]; Lv == 4 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 82}, {def_add, 238} ]; Lv == 5 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 85}, {def_add, 277} ]; Lv == 6 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 88}, {def_add, 317} ]; Lv == 7 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 91}, {def_add, 358} ]; Lv == 8 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 94}, {def_add, 397} ]; Lv == 9 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {def_add, 472} ]; Lv == 10 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 100}, {def_add, 591} ]; true -> [] end }; get(104301, Lv) -> #ets_skill{ id=104301, name = <<"不动如山">>, desc = <<"任他支离狂悖,颠倒颇僻,我自八风不动,减少自己所受到得伤害。与人不留行不可同时存在">>, career = 1, type = 3, obj = 1, mod = 1, area = 0, cd = 60000, lastime = 12000, attime = 1, attarea = 0, limit = [105301], data = if Lv == 1 -> [ {condition, [{lv,39},{coin,1000},{skill1,103301,3},{skill2,0,0}]}, {mp_out, 78}, {hurt_del, 0.9} ]; Lv == 2 -> [ {condition, [{lv,43},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 81}, {hurt_del, 0.89} ]; Lv == 3 -> [ {condition, [{lv,47},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 84}, {hurt_del, 0.88} ]; Lv == 4 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 87}, {hurt_del, 0.87} ]; Lv == 5 -> [ {condition, [{lv,55},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {hurt_del, 0.86} ]; Lv == 6 -> [ {condition, [{lv,60},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {hurt_del, 0.85} ]; Lv == 7 -> [ {condition, [{lv,65},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 96}, {hurt_del, 0.84} ]; Lv == 8 -> [ {condition, [{lv,70},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {hurt_del, 0.83} ]; Lv == 9 -> [ {condition, [{lv,75},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 102}, {hurt_del, 0.82} ]; Lv == 10 -> [ {condition, [{lv,80},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 105}, {hurt_del, 0.8} ]; true -> [] end }; get(105101, Lv) -> #ets_skill{ id=105101, name = <<"浮光掠影">>, desc = <<"宝刀像一道流光飞速斩向对手,一触即回,而后敌人才察觉已受重伤">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 12000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,44},{coin,1000},{skill1,103101,4},{skill2,0,0}]}, {mp_out, 50}, {att, 1.15}, {hurt_add, 135}, {hit_add, 0.3} ]; Lv == 2 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {att, 1.17}, {hurt_add, 145}, {hit_add, 0.3} ]; Lv == 3 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 56}, {att, 1.19}, {hurt_add, 155}, {hit_add, 0.3} ]; Lv == 4 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 59}, {att, 1.21}, {hurt_add, 165} ]; Lv == 5 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 62}, {att, 1.24}, {hurt_add, 175}, {hit_add, 0.3} ]; Lv == 6 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {att, 1.27}, {hurt_add, 185}, {hit_add, 0.3} ]; Lv == 7 -> [ {condition, [{lv,74},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 68}, {att, 1.3}, {hurt_add, 195}, {hit_add, 0.3} ]; Lv == 8 -> [ {condition, [{lv,79},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {att, 1.35}, {hurt_add, 205}, {hit_add, 0.3} ]; true -> [] end }; get(105301, Lv) -> #ets_skill{ id=105301, name = <<"人不留行">>, desc = <<"十步杀一人,千里不留行。加快自身的移动速度。与不动如山不可同时存在">>, career = 1, type = 3, obj = 1, mod = 1, area = 0, cd = 60000, lastime = 15000, attime = 1, attarea = 0, limit = [104301], data = if Lv == 1 -> [ {condition, [{lv,49},{coin,1000},{skill1,102301,8},{skill2,0,0}]}, {mp_out, 84}, {add_speed, 0.2} ]; Lv == 2 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 87}, {add_speed, 0.21} ]; Lv == 3 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {add_speed, 0.22} ]; Lv == 4 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {add_speed, 0.23} ]; Lv == 5 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 96}, {add_speed, 0.24} ]; Lv == 6 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {add_speed, 0.26} ]; Lv == 7 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 102}, {add_speed, 0.28} ]; Lv == 8 -> [ {condition, [{lv,84},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 105}, {add_speed, 0.3} ]; true -> [] end }; get(106101, Lv) -> #ets_skill{ id=106101, name = <<"荒火燎原">>, desc = <<"野火烧不尽,春风吹又生。宝刀挥洒而出,攻击周围的敌人。">>, career = 1, type = 1, obj = 1, mod = 2, area = 2, cd = 35000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,59},{coin,1000},{skill1,105301,2},{skill2,105101,3}]}, {mp_out, 133}, {att, 1.4} ]; Lv == 2 -> [ {condition, [{lv,66},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 136}, {att, 1.45} ]; Lv == 3 -> [ {condition, [{lv,73},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 139}, {att, 1.5} ]; Lv == 4 -> [ {condition, [{lv,81},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 142}, {att, 1.55} ]; Lv == 5 -> [ {condition, [{lv,89},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 145}, {att, 1.6} ]; true -> [] end }; get(201101, Lv) -> #ets_skill{ id=201101, name = <<"基本刺法">>, desc = <<"初入江湖的基本刺法,只能用来教训一下地痞混混">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 800, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,1},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 10} ]; Lv == 2 -> [ {condition, [{lv,3},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 30} ]; Lv == 3 -> [ {condition, [{lv,5},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 50} ]; Lv == 4 -> [ {condition, [{lv,8},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 71} ]; Lv == 5 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 92} ]; Lv == 6 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 113} ]; Lv == 7 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 134} ]; Lv == 8 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 155} ]; Lv == 9 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 176} ]; Lv == 10 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 197} ]; true -> [] end }; get(201102, Lv) -> #ets_skill{ id=201102, name = <<"幽影刺">>, desc = <<"挥舞双刺,如蛇一般刺向敌人胸膛">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 3000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,9},{coin,1000},{skill1,201101,3},{skill2,0,0}]}, {mp_out, 13}, {att, 1.1}, {hurt_add, 50} ]; Lv == 2 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 15}, {att, 1.12}, {hurt_add, 60} ]; Lv == 3 -> [ {condition, [{lv,13},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 17}, {att, 1.14}, {hurt_add, 65} ]; Lv == 4 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 19}, {att, 1.16}, {hurt_add, 70} ]; Lv == 5 -> [ {condition, [{lv,19},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 21}, {att, 1.18}, {hurt_add, 75} ]; Lv == 6 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 23}, {att, 1.2}, {hurt_add, 80} ]; Lv == 7 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 25}, {att, 1.22}, {hurt_add, 85} ]; Lv == 8 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 27}, {att, 1.24}, {hurt_add, 90} ]; Lv == 9 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 29}, {att, 1.27}, {hurt_add, 95} ]; Lv == 10 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 31}, {att, 1.3}, {hurt_add, 100} ]; true -> [] end }; get(201201, Lv) -> #ets_skill{ id=201201, name = <<"慧眼明察">>, desc = <<"唐门的秘术,使人拥有杀手一般的嗅觉,轻易找出对手的破绽">>, career = 3, type = 2, obj = 2, mod = 1, area = 0, cd = 0, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,5},{coin,1000},{skill1,201101,2},{skill2,0,0}]}, {crit, 12} ]; Lv == 2 -> [ {condition, [{lv,10},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 18} ]; Lv == 3 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 24} ]; Lv == 4 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 30} ]; Lv == 5 -> [ {condition, [{lv,25},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 36} ]; Lv == 6 -> [ {condition, [{lv,30},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 42} ]; Lv == 7 -> [ {condition, [{lv,35},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 48} ]; Lv == 8 -> [ {condition, [{lv,40},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 54} ]; Lv == 9 -> [ {condition, [{lv,45},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 60} ]; Lv == 10 -> [ {condition, [{lv,50},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 66} ]; true -> [] end }; get(202101, Lv) -> #ets_skill{ id=202101, name = <<"流星赶月">>, desc = <<"双刺上下翩飞,一前一后刺向敌人咽喉,造成2次伤害">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 6000, lastime = 0, attime = 2, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,14},{coin,1000},{skill1,201102,2},{skill2,0,0}]}, {mp_out, 20}, {att, 0.6} ]; Lv == 2 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 23}, {att, 0.61} ]; Lv == 3 -> [ {condition, [{lv,18},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 26}, {att, 0.62} ]; Lv == 4 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 29}, {att, 0.63} ]; Lv == 5 -> [ {condition, [{lv,24},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 32}, {att, 0.64} ]; Lv == 6 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 35}, {att, 0.65} ]; Lv == 7 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 38}, {att, 0.66} ]; Lv == 8 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 41}, {att, 0.67} ]; Lv == 9 -> [ {condition, [{lv,46},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 44}, {att, 0.68} ]; Lv == 10 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {att, 0.7} ]; true -> [] end }; get(202301, Lv) -> #ets_skill{ id=202301, name = <<"捕风捉影">>, desc = <<"唐门奇术,大幅增加自身的命中。与镜花水月不可同时存在">>, career = 3, type = 1, obj = 1, mod = 1, area = 0, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [205301], data = if Lv == 1 -> [ {condition, [{lv,19},{coin,1000},{skill1,201101,5},{skill2,0,0}]}, {mp_out, 27}, {hit_add, 0.08} ]; Lv == 2 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 29}, {hit_add, 0.09} ]; Lv == 3 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 31}, {hit_add, 0.1} ]; Lv == 4 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 33}, {hit_add, 0.11} ]; Lv == 5 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 35}, {hit_add, 0.12} ]; Lv == 6 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 37}, {hit_add, 0.13} ]; Lv == 7 -> [ {condition, [{lv,38},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 39}, {hit_add, 0.14} ]; Lv == 8 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 41}, {hit_add, 0.15} ]; Lv == 9 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {hit_add, 0.17} ]; Lv == 10 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {hit_add, 0.2} ]; true -> [] end }; get(203101, Lv) -> #ets_skill{ id=203101, name = <<"晓风残月">>, desc = <<"醒时何处,奈何桥,晓风残月。唐门技艺,使人陷入中毒状态">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 8000, lastime = 3000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,24},{coin,1000},{skill1,202101,3},{skill2,0,0}]}, {mp_out, 39}, {att, 1.1}, {drug, [3,1,25]} ]; Lv == 2 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 41}, {att, 1.11}, {drug, [3,1,30]} ]; Lv == 3 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {att, 1.12}, {drug, [3,1,35]} ]; Lv == 4 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {att, 1.13}, {drug, [3,1,40]} ]; Lv == 5 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {att, 1.15}, {drug, [3,1,45]} ]; Lv == 6 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {att, 1.17}, {drug, [3,1,50]} ]; Lv == 7 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {att, 1.19}, {drug, [3,1,55]} ]; Lv == 8 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {att, 1.21}, {drug, [3,1,60]} ]; Lv == 9 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {att, 1.23}, {drug, [3,1,65]} ]; Lv == 10 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 57}, {att, 1.25}, {drug, [3,1,70]} ]; true -> [] end }; get(203301, Lv) -> #ets_skill{ id=203301, name = <<"修罗喋血">>, desc = <<"以自我为中心,暂时提升自己及周围队友的暴击几率">>, career = 3, type = 3, obj = 1, mod = 2, area = 4, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,29},{coin,1000},{skill1,202301,4},{skill2,0,0}]}, {mp_out, 53}, {crit, 20} ]; Lv == 2 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 56}, {crit, 22} ]; Lv == 3 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 59}, {crit, 24} ]; Lv == 4 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 62}, {crit, 26} ]; Lv == 5 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {crit, 28} ]; Lv == 6 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 68}, {crit, 30} ]; Lv == 7 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {crit, 32} ]; Lv == 8 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 74}, {crit, 34} ]; Lv == 9 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {crit, 36} ]; Lv == 10 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 80}, {crit, 38} ]; true -> [] end }; get(204101, Lv) -> #ets_skill{ id=204101, name = <<"漫天花雨">>, desc = <<"无边花雨萧萧飘下,轻取性命手到擒来。唐门高级技艺,伤害周围的目标,并且出现暴击">>, career = 3, type = 1, obj = 2, mod = 2, area = 2, cd = 15000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,39},{coin,1000},{skill1,202101,6},{skill2,0,0}]}, {mp_out, 59}, {att, 1.15}, {crit, 100} ]; Lv == 2 -> [ {condition, [{lv,43},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 61}, {att, 1.17}, {crit, 100} ]; Lv == 3 -> [ {condition, [{lv,47},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 63}, {att, 1.19}, {crit, 100} ]; Lv == 4 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {att, 1.21}, {crit, 100} ]; Lv == 5 -> [ {condition, [{lv,55},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 67}, {att, 1.23}, {crit, 100} ]; Lv == 6 -> [ {condition, [{lv,60},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 69}, {att, 1.25}, {crit, 100} ]; Lv == 7 -> [ {condition, [{lv,65},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {att, 1.27}, {crit, 100} ]; Lv == 8 -> [ {condition, [{lv,70},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 73}, {att, 1.29}, {crit, 100} ]; Lv == 9 -> [ {condition, [{lv,75},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 75}, {att, 1.32}, {crit, 100} ]; Lv == 10 -> [ {condition, [{lv,80},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {att, 1.35}, {crit, 100} ]; true -> [] end }; get(205301, Lv) -> #ets_skill{ id=205301, name = <<"镜花水月">>, desc = <<"镜中花,水中月。使用此招,唐门弟子可冲锋陷阵,进退自如。与捕风捉影不可同时存在">>, career = 3, type = 3, obj = 1, mod = 1, area = 0, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [202301], data = if Lv == 1 -> [ {condition, [{lv,44},{coin,1000},{skill1,202301,6},{skill2,0,0}]}, {mp_out, 41}, {dodge, 0.08} ]; Lv == 2 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {dodge, 0.09} ]; Lv == 3 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {dodge, 0.1} ]; Lv == 4 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {dodge, 0.11} ]; Lv == 5 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {dodge, 0.12} ]; Lv == 6 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {dodge, 0.13} ]; Lv == 7 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {dodge, 0.14} ]; Lv == 8 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {dodge, 0.15} ]; true -> [] end }; get(205401, Lv) -> #ets_skill{ id=205401, name = <<"一叶障目">>, desc = <<"一叶障目,不见泰山。中招后,对手会处于失明状态,命中降低">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 45000, lastime = 15000, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,49},{coin,1000},{skill1,201201,7},{skill2,0,0}]}, {mp_out, 41}, {hit_del, 0.16} ]; Lv == 2 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {hit_del, 0.18} ]; Lv == 3 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {hit_del, 0.20} ]; Lv == 4 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {hit_del, 0.22} ]; Lv == 5 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {hit_del, 0.24} ]; Lv == 6 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {hit_del, 0.26} ]; Lv == 7 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {hit_del, 0.28} ]; Lv == 8 -> [ {condition, [{lv,84},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {hit_del, 0.3} ]; true -> [] end }; get(206101, Lv) -> #ets_skill{ id=206101, name = <<"碧落黄泉">>, desc = <<"上穷碧落下黄泉,终究要相见。但是此见非彼见,是要人性命之见">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 30000, lastime = 4000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,59},{coin,1000},{skill1,203101,8},{skill2,205301,3}]}, {mp_out, 73}, {att, 1.3}, {speed, 0.3}, {drug, [2,2,75]} ]; Lv == 2 -> [ {condition, [{lv,66},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 78}, {att, 1.35}, {speed, 0.3}, {drug, [2,2,90]} ]; Lv == 3 -> [ {condition, [{lv,73},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {att, 1.4}, {speed, 0.3}, {drug, [2,2,105]} ]; Lv == 4 -> [ {condition, [{lv,81},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 88}, {att, 1.45}, {speed, 0.3}, {drug, [2,2,120]} ]; Lv == 5 -> [ {condition, [{lv,89},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {att, 1.5}, {speed, 0.3}, {drug, [2,2,135]} ]; true -> [] end }; get(301101, Lv) -> #ets_skill{ id=301101, name = <<"基本剑法">>, desc = <<"初入江湖的基本剑法,只能用来教训一下地痞混混">>, career = 2, type = 1, obj = 2, mod = 1, area = 0, cd = 800, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,1},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 40} ]; Lv == 2 -> [ {condition, [{lv,3},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 60} ]; Lv == 3 -> [ {condition, [{lv,5},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 80} ]; Lv == 4 -> [ {condition, [{lv,8},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 111} ]; Lv == 5 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 122} ]; Lv == 6 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 143} ]; Lv == 7 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 164} ]; Lv == 8 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 185} ]; Lv == 9 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 206} ]; Lv == 10 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 227} ]; true -> [] end }; get(301102, Lv) -> #ets_skill{ id=301102, name = <<"碎影破">>, desc = <<"剑若闪电,向敌人咽喉要害狠狠刺去">>, career = 2, type = 1, obj = 2, mod = 1, area = 0, cd = 3000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,9},{coin,1000},{skill1,301101,3},{skill2,0,0}]}, {mp_out, 24}, {att, 1.22} ]; Lv == 2 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 27}, {att, 1.24} ]; Lv == 3 -> [ {condition, [{lv,13},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 30}, {att, 1.26} ]; Lv == 4 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 33}, {att, 1.28} ]; Lv == 5 -> [ {condition, [{lv,19},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 36}, {att, 1.3} ]; Lv == 6 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 39}, {att, 1.32} ]; Lv == 7 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 42}, {att, 1.34} ]; Lv == 8 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {att, 1.36} ]; Lv == 9 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 48}, {att, 1.38} ]; Lv == 10 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {att, 1.4} ]; true -> [] end }; get(301201, Lv) -> #ets_skill{ id=301201, name = <<"韬光养晦">>, desc = <<"逍遥的心法,永久增加自身的攻击和内力">>, career = 2, type = 2, obj = 2, mod = 1, area = 0, cd = 0, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,5},{coin,1000},{skill1,301101,2},{skill2,0,0}]}, {att, 50}, {mp, 60} ]; Lv == 2 -> [ {condition, [{lv,10},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 70}, {mp, 75} ]; Lv == 3 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 100}, {mp, 95} ]; Lv == 4 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 140}, {mp, 120} ]; Lv == 5 -> [ {condition, [{lv,25},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 190}, {mp, 150} ]; Lv == 6 -> [ {condition, [{lv,30},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 250}, {mp, 185} ]; Lv == 7 -> [ {condition, [{lv,35},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 320}, {mp, 225} ]; Lv == 8 -> [ {condition, [{lv,40},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 400}, {mp, 275} ]; Lv == 9 -> [ {condition, [{lv,45},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 490}, {mp, 330} ]; Lv == 10 -> [ {condition, [{lv,50},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 590}, {mp, 390} ]; true -> [] end }; get(302301, Lv) -> #ets_skill{ id=302301, name = <<"坐忘无我">>, desc = <<"将自己的内力转化成一个护盾,化解所受到伤害">>, career = 2, type = 3, obj = 1, mod = 1, area = 0, cd = 180000, lastime = 60000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,14},{coin,1000},{skill1,301101,3},{skill2,0,0}]}, {mp_out, 60}, {shield, 120} ]; Lv == 2 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 73}, {shield, 146} ]; Lv == 3 -> [ {condition, [{lv,18},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 81}, {shield, 163} ]; Lv == 4 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 98}, {shield, 196} ]; Lv == 5 -> [ {condition, [{lv,24},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 121}, {shield, 243} ]; Lv == 6 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 148}, {shield, 296} ]; Lv == 7 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 166}, {shield, 333} ]; Lv == 8 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 192}, {shield, 386} ]; Lv == 9 -> [ {condition, [{lv,46},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 231}, {shield, 463} ]; Lv == 10 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 293}, {shield, 586} ]; true -> [] end }; get(302501, Lv) -> #ets_skill{ id=302501, name = <<"春泥护花">>, desc = <<"落红本有情,春泥更护花。逍遥弟子怀柔天下,此计可以回复选中目标的生命值">>, career = 2, type = 3, obj = 3, mod = 1, area = 0, cd = 15000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,19},{coin,1000},{skill1,301201,3},{skill2,0,0}]}, {mp_out, 69}, {hp, 200} ]; Lv == 2 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 76}, {hp, 250} ]; Lv == 3 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {hp, 300} ]; Lv == 4 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {hp, 400} ]; Lv == 5 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {hp, 500} ]; Lv == 6 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 104}, {hp, 600} ]; Lv == 7 -> [ {condition, [{lv,38},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 111}, {hp, 750} ]; Lv == 8 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 118}, {hp, 900} ]; Lv == 9 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 125}, {hp, 1050} ]; Lv == 10 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 132}, {hp, 1200} ]; true -> [] end }; get(303101, Lv) -> #ets_skill{ id=303101, name = <<"风卷残云">>, desc = <<"风卷残云,剑气临空惊魂梦。对目标范围内发出半月形的剑气,群体伤害">>, career = 2, type = 1, obj = 2, mod = 2, area = 2, cd = 6000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,24},{coin,1000},{skill1,301102,5},{skill2,0,0}]}, {mp_out, 47}, {att, 1.22} ]; Lv == 2 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {att, 1.24} ]; Lv == 3 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 59}, {att, 1.26} ]; Lv == 4 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {att, 1.28} ]; Lv == 5 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {att, 1.3} ]; Lv == 6 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {att, 1.32} ]; Lv == 7 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {att, 1.34} ]; Lv == 8 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 89}, {att, 1.36} ]; Lv == 9 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 95}, {att, 1.38} ]; Lv == 10 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 101}, {att, 1.4} ]; true -> [] end }; get(303301, Lv) -> #ets_skill{ id=303301, name = <<"剑气纵横">>, desc = <<"剑气惊风雨,纵横泣鬼神。出以气为兵,以剑为辅,群体增加攻击力">>, career = 2, type = 3, obj = 1, mod = 2, area = 4, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,29},{coin,1000},{skill1,302301,4},{skill2,0,0}]}, {mp_out, 69}, {att, 116} ]; Lv == 2 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 76}, {att, 156} ]; Lv == 3 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {att, 223} ]; Lv == 4 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {att, 263} ]; Lv == 5 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {att, 307} ]; Lv == 6 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 104}, {att, 347} ]; Lv == 7 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 111}, {att, 393} ]; Lv == 8 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 118}, {att, 432} ]; Lv == 9 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 125}, {att, 522} ]; Lv == 10 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 132}, {att, 651} ]; true -> [] end }; get(304101, Lv) -> #ets_skill{ id=304101, name = <<"碧海潮生">>, desc = <<"碧海涛起天地惊,潮生潮落尽彷徨。以自身为中心,周围所有单位受到伤害,而且移动速度降低">>, career = 2, type = 1, obj = 1, mod = 2, area = 2, cd = 10000, lastime = 3000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,39},{coin,1000},{skill1,303101,3},{skill2,0,0}]}, {mp_out, 67}, {att, 1.25}, {speed, 0.15} ]; Lv == 2 -> [ {condition, [{lv,43},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 73}, {att, 1.27}, {speed, 0.15} ]; Lv == 3 -> [ {condition, [{lv,47},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 79}, {att, 1.3}, {speed, 0.15} ]; Lv == 4 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 85}, {att, 1.33}, {speed, 0.15} ]; Lv == 5 -> [ {condition, [{lv,55},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 91}, {att, 1.35}, {speed, 0.15} ]; Lv == 6 -> [ {condition, [{lv,60},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {att, 1.38}, {speed, 0.15} ]; Lv == 7 -> [ {condition, [{lv,65},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 103}, {att, 1.4}, {speed, 0.15} ]; Lv == 8 -> [ {condition, [{lv,70},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 109}, {att, 1.43}, {speed, 0.15} ]; Lv == 9 -> [ {condition, [{lv,75},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 115}, {att, 1.46}, {speed, 0.15} ]; Lv == 10 -> [ {condition, [{lv,80},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 121}, {att, 1.5}, {speed, 0.15} ]; true -> [] end }; get(305101, Lv) -> #ets_skill{ id=305101, name = <<"绕指柔">>, desc = <<"相见时难别亦难。发出数道剑气,降低目标的移动速度">>, career = 2, type = 1, obj = 2, mod = 1, area = 0, cd = 15000, lastime = 2000, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,49},{coin,1000},{skill1,304101,3},{skill2,0,0}]}, {mp_out, 59}, {hurt_add, 1.45}, {speed, 0.3} ]; Lv == 2 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {hurt_add, 1.5}, {speed, 0.3} ]; Lv == 3 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {hurt_add, 1.55}, {speed, 0.3} ]; Lv == 4 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {hurt_add, 1.6}, {speed, 0.3} ]; Lv == 5 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {hurt_add, 1.65}, {speed, 0.3} ]; Lv == 6 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 89}, {hurt_add, 1.7}, {speed, 0.3} ]; Lv == 7 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 95}, {hurt_add, 1.75}, {speed, 0.3} ]; Lv == 8 -> [ {condition, [{lv,84},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 101}, {hurt_add, 1.8}, {speed, 0.3} ]; true -> [] end }; get(305501, Lv) -> #ets_skill{ id=305501, name = <<"慈航普渡">>, desc = <<"心怀天下,大爱无边。逍遥济世之术,群体回复生命值">>, career = 2, type = 3, obj = 1, mod = 2, area = 4, cd = 25000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,44},{coin,1000},{skill1,302501,6},{skill2,0,0}]}, {mp_out, 90}, {hp, 220} ]; Lv == 2 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {hp, 298} ]; Lv == 3 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 108}, {hp, 361} ]; Lv == 4 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 117}, {hp, 433} ]; Lv == 5 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 126}, {hp, 534} ]; Lv == 6 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 135}, {hp, 612} ]; Lv == 7 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 144}, {hp, 718} ]; Lv == 8 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 153}, {hp, 862} ]; true -> [] end }; get(306101, Lv) -> #ets_skill{ id=306101, name = <<"六合独尊">>, desc = <<"六合同归,大道逍遥。发出无数剑气,对目标范围内的敌人进行致命打击">>, career = 2, type = 1, obj = 2, mod = 2, area = 2, cd = 30000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,59},{coin,1000},{skill1,305501,3},{skill2,305101,2}]}, {mp_out, 118}, {att, 1.6} ]; Lv == 2 -> [ {condition, [{lv,67},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 130}, {att, 1.65} ]; Lv == 3 -> [ {condition, [{lv,73},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 142}, {att, 1.7} ]; Lv == 4 -> [ {condition, [{lv,81},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 154}, {att, 1.75} ]; Lv == 5 -> [ {condition, [{lv,89},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 166}, {att, 1.8} ]; true -> [] end }; get(_Id, _Lv) -> [].
null
https://raw.githubusercontent.com/smallmelon/sdzmmo/254ff430481de474527c0e96202c63fb0d2c29d2/src/data/data_skill.erl
erlang
--------------------------------------- @Module : data_skill @Email : @Description: 自动生成 ---------------------------------------
@Author : xyao @Created : 2010 - 08 - 20 10:46:47 -module(data_skill). -export([get/2, get_ids/1]). -include("record.hrl"). get_ids(1) -> [101101,101102,101201,102101,102301,103101,103301,104301,105101,105301,106101]; get_ids(2) -> [301101,301102,301201,302301,302501,303101,303301,304101,305101,305501,306101]; get_ids(3) -> [201101,201102,201201,202101,202301,203101,203301,204101,205301,205401,206101]. get(101101, Lv) -> #ets_skill{ id=101101, name = <<"基本刀法">>, desc = <<"初入江湖的基本刀法,只能用来教训一下地痞混混">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 800, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,1},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 20} ]; Lv == 2 -> [ {condition, [{lv,3},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 40} ]; Lv == 3 -> [ {condition, [{lv,5},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 60} ]; Lv == 4 -> [ {condition, [{lv,8},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 81} ]; Lv == 5 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 102} ]; Lv == 6 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 123} ]; Lv == 7 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 144} ]; Lv == 8 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 165} ]; Lv == 9 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 186} ]; Lv == 10 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 207} ]; true -> [] end }; get(101102, Lv) -> #ets_skill{ id=101102, name = <<"凌风斩">>, desc = <<"双手挥起宝刀大力劈向对手,造成一定伤害">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 4000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,9},{coin,1000},{skill1,101101,3},{skill2,0,0}]}, {mp_out, 18}, {att, 1.05}, {hurt_add, 60} ]; Lv == 2 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 21}, {att, 1.07}, {hurt_add, 70} ]; Lv == 3 -> [ {condition, [{lv,13},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 24}, {att, 1.09}, {hurt_add, 80} ]; Lv == 4 -> [ {condition, [{lv,16},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 27}, {att, 1.11}, {hurt_add, 90} ]; Lv == 5 -> [ {condition, [{lv,19},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 30}, {att, 1.13}, {hurt_add, 100} ]; Lv == 6 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 33}, {att, 1.15}, {hurt_add, 110} ]; Lv == 7 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 36}, {att, 1.17}, {hurt_add, 120} ]; Lv == 8 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 39}, {att, 1.19}, {hurt_add, 130} ]; Lv == 9 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 42}, {att, 1.21}, {hurt_add, 140} ]; Lv == 10 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {att, 1.25}, {hurt_add, 150} ]; true -> [] end }; get(101201, Lv) -> #ets_skill{ id=101201, name = <<"天罡护体">>, desc = <<"昆仑的健体之术,永久增加人的生命上限">>, career = 1, type = 2, obj = 1, mod = 1, area = 0, cd = 0, lastime = 0, attime = 0, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,5},{coin,1000},{skill1,101101,2},{skill2,0,0}]}, {hp, 101} ]; Lv == 2 -> [ {condition, [{lv,10},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 153} ]; Lv == 3 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 228} ]; Lv == 4 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 331} ]; Lv == 5 -> [ {condition, [{lv,25},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 463} ]; Lv == 6 -> [ {condition, [{lv,30},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 613} ]; Lv == 7 -> [ {condition, [{lv,35},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 784} ]; Lv == 8 -> [ {condition, [{lv,40},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 982} ]; Lv == 9 -> [ {condition, [{lv,45},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 1193} ]; Lv == 10 -> [ {condition, [{lv,50},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {hp, 1428} ]; true -> [] end }; get(102101, Lv) -> #ets_skill{ id=102101, name = <<"一夫当关">>, desc = <<"一夫当关,万夫莫开。攻击周围的所有敌人,并且吸引所有注意力">>, career = 1, type = 1, obj = 1, mod = 2, area = 2, cd = 25000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,19},{coin,1000},{skill1,101102,3},{skill2,0,0}]}, {mp_out, 43}, {att, 0.7} ]; Lv == 2 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 46}, {att, 0.75} ]; Lv == 3 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {att, 0.8} ]; Lv == 4 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 52}, {att, 0.85} ]; Lv == 5 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {att, 0.9} ]; Lv == 6 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 58}, {att, 0.95} ]; Lv == 7 -> [ {condition, [{lv,38},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 61}, {att, 1.0} ]; Lv == 8 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 64}, {att, 1.05} ]; Lv == 9 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 67}, {att, 1.1} ]; Lv == 10 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 70}, {att, 1.15} ]; true -> [] end }; get(102301, Lv) -> #ets_skill{ id=102301, name = <<"霸王卸甲">>, desc = <<"舍弃自身的防御,以获得更高的攻击,力求快速打倒敌人">>, career = 1, type = 3, obj = 1, mod = 1, area = 0, cd = 180000, lastime = 30000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,14},{coin,1000},{skill1,101101,3},{skill2,0,0}]}, {mp_out, 81}, {att, 80}, {def_add, 0.85} ]; Lv == 2 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 84}, {att, 153}, {def_add, 0.85} ]; Lv == 3 -> [ {condition, [{lv,18},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 87}, {att, 235}, {def_add, 0.85} ]; Lv == 4 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {att, 325}, {def_add, 0.85} ]; Lv == 5 -> [ {condition, [{lv,24},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {att, 424}, {def_add, 0.85} ]; Lv == 6 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 96}, {att, 532}, {def_add, 0.85} ]; Lv == 7 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {att, 617}, {def_add, 0.85} ]; Lv == 8 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 102}, {att, 702}, {def_add, 0.85} ]; Lv == 9 -> [ {condition, [{lv,46},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 105}, {att, 788}, {def_add, 0.85} ]; Lv == 10 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 108}, {att, 873}, {def_add, 0.85} ]; true -> [] end }; get(103101, Lv) -> #ets_skill{ id=103101, name = <<"我为刀俎">>, desc = <<"我为刀俎,你为鱼肉。攻击敌人,造成伤害,并且降低敌人的防御">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 9000, lastime = 5000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,29},{coin,1000},{skill1,102101,4},{skill2,0,0}]}, {mp_out, 34}, {hurt_add, 1.35} ]; Lv == 2 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 37}, {hurt_add, 1.4} ]; Lv == 3 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 40}, {hurt_add, 1.45} ]; Lv == 4 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {hurt_add, 1.5} ]; Lv == 5 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 46}, {hurt_add, 1.55} ]; Lv == 6 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {hurt_add, 1.6} ]; Lv == 7 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 52}, {hurt_add, 1.65} ]; Lv == 8 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {hurt_add, 1.7} ]; Lv == 9 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 58}, {hurt_add, 1.75} ]; Lv == 10 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 61}, {hurt_add, 1.8} ]; true -> [] end }; get(103301, Lv) -> #ets_skill{ id=103301, name = <<"固若金汤">>, desc = <<"以自我为中心,暂时提升自己及周围队友的防御力">>, career = 1, type = 3, obj = 1, mod = 2, area = 4, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,24},{coin,1000},{skill1,102301,3},{skill2,0,0}]}, {mp_out, 73}, {def_add, 116} ]; Lv == 2 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 76}, {def_add, 156} ]; Lv == 3 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 79}, {def_add, 198} ]; Lv == 4 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 82}, {def_add, 238} ]; Lv == 5 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 85}, {def_add, 277} ]; Lv == 6 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 88}, {def_add, 317} ]; Lv == 7 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 91}, {def_add, 358} ]; Lv == 8 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 94}, {def_add, 397} ]; Lv == 9 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {def_add, 472} ]; Lv == 10 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 100}, {def_add, 591} ]; true -> [] end }; get(104301, Lv) -> #ets_skill{ id=104301, name = <<"不动如山">>, desc = <<"任他支离狂悖,颠倒颇僻,我自八风不动,减少自己所受到得伤害。与人不留行不可同时存在">>, career = 1, type = 3, obj = 1, mod = 1, area = 0, cd = 60000, lastime = 12000, attime = 1, attarea = 0, limit = [105301], data = if Lv == 1 -> [ {condition, [{lv,39},{coin,1000},{skill1,103301,3},{skill2,0,0}]}, {mp_out, 78}, {hurt_del, 0.9} ]; Lv == 2 -> [ {condition, [{lv,43},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 81}, {hurt_del, 0.89} ]; Lv == 3 -> [ {condition, [{lv,47},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 84}, {hurt_del, 0.88} ]; Lv == 4 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 87}, {hurt_del, 0.87} ]; Lv == 5 -> [ {condition, [{lv,55},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {hurt_del, 0.86} ]; Lv == 6 -> [ {condition, [{lv,60},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {hurt_del, 0.85} ]; Lv == 7 -> [ {condition, [{lv,65},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 96}, {hurt_del, 0.84} ]; Lv == 8 -> [ {condition, [{lv,70},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {hurt_del, 0.83} ]; Lv == 9 -> [ {condition, [{lv,75},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 102}, {hurt_del, 0.82} ]; Lv == 10 -> [ {condition, [{lv,80},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 105}, {hurt_del, 0.8} ]; true -> [] end }; get(105101, Lv) -> #ets_skill{ id=105101, name = <<"浮光掠影">>, desc = <<"宝刀像一道流光飞速斩向对手,一触即回,而后敌人才察觉已受重伤">>, career = 1, type = 1, obj = 2, mod = 1, area = 0, cd = 12000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,44},{coin,1000},{skill1,103101,4},{skill2,0,0}]}, {mp_out, 50}, {att, 1.15}, {hurt_add, 135}, {hit_add, 0.3} ]; Lv == 2 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {att, 1.17}, {hurt_add, 145}, {hit_add, 0.3} ]; Lv == 3 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 56}, {att, 1.19}, {hurt_add, 155}, {hit_add, 0.3} ]; Lv == 4 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 59}, {att, 1.21}, {hurt_add, 165} ]; Lv == 5 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 62}, {att, 1.24}, {hurt_add, 175}, {hit_add, 0.3} ]; Lv == 6 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {att, 1.27}, {hurt_add, 185}, {hit_add, 0.3} ]; Lv == 7 -> [ {condition, [{lv,74},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 68}, {att, 1.3}, {hurt_add, 195}, {hit_add, 0.3} ]; Lv == 8 -> [ {condition, [{lv,79},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {att, 1.35}, {hurt_add, 205}, {hit_add, 0.3} ]; true -> [] end }; get(105301, Lv) -> #ets_skill{ id=105301, name = <<"人不留行">>, desc = <<"十步杀一人,千里不留行。加快自身的移动速度。与不动如山不可同时存在">>, career = 1, type = 3, obj = 1, mod = 1, area = 0, cd = 60000, lastime = 15000, attime = 1, attarea = 0, limit = [104301], data = if Lv == 1 -> [ {condition, [{lv,49},{coin,1000},{skill1,102301,8},{skill2,0,0}]}, {mp_out, 84}, {add_speed, 0.2} ]; Lv == 2 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 87}, {add_speed, 0.21} ]; Lv == 3 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {add_speed, 0.22} ]; Lv == 4 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {add_speed, 0.23} ]; Lv == 5 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 96}, {add_speed, 0.24} ]; Lv == 6 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {add_speed, 0.26} ]; Lv == 7 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 102}, {add_speed, 0.28} ]; Lv == 8 -> [ {condition, [{lv,84},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 105}, {add_speed, 0.3} ]; true -> [] end }; get(106101, Lv) -> #ets_skill{ id=106101, name = <<"荒火燎原">>, desc = <<"野火烧不尽,春风吹又生。宝刀挥洒而出,攻击周围的敌人。">>, career = 1, type = 1, obj = 1, mod = 2, area = 2, cd = 35000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,59},{coin,1000},{skill1,105301,2},{skill2,105101,3}]}, {mp_out, 133}, {att, 1.4} ]; Lv == 2 -> [ {condition, [{lv,66},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 136}, {att, 1.45} ]; Lv == 3 -> [ {condition, [{lv,73},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 139}, {att, 1.5} ]; Lv == 4 -> [ {condition, [{lv,81},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 142}, {att, 1.55} ]; Lv == 5 -> [ {condition, [{lv,89},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 145}, {att, 1.6} ]; true -> [] end }; get(201101, Lv) -> #ets_skill{ id=201101, name = <<"基本刺法">>, desc = <<"初入江湖的基本刺法,只能用来教训一下地痞混混">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 800, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,1},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 10} ]; Lv == 2 -> [ {condition, [{lv,3},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 30} ]; Lv == 3 -> [ {condition, [{lv,5},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 50} ]; Lv == 4 -> [ {condition, [{lv,8},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 71} ]; Lv == 5 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 92} ]; Lv == 6 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 113} ]; Lv == 7 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 134} ]; Lv == 8 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 155} ]; Lv == 9 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 176} ]; Lv == 10 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 197} ]; true -> [] end }; get(201102, Lv) -> #ets_skill{ id=201102, name = <<"幽影刺">>, desc = <<"挥舞双刺,如蛇一般刺向敌人胸膛">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 3000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,9},{coin,1000},{skill1,201101,3},{skill2,0,0}]}, {mp_out, 13}, {att, 1.1}, {hurt_add, 50} ]; Lv == 2 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 15}, {att, 1.12}, {hurt_add, 60} ]; Lv == 3 -> [ {condition, [{lv,13},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 17}, {att, 1.14}, {hurt_add, 65} ]; Lv == 4 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 19}, {att, 1.16}, {hurt_add, 70} ]; Lv == 5 -> [ {condition, [{lv,19},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 21}, {att, 1.18}, {hurt_add, 75} ]; Lv == 6 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 23}, {att, 1.2}, {hurt_add, 80} ]; Lv == 7 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 25}, {att, 1.22}, {hurt_add, 85} ]; Lv == 8 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 27}, {att, 1.24}, {hurt_add, 90} ]; Lv == 9 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 29}, {att, 1.27}, {hurt_add, 95} ]; Lv == 10 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 31}, {att, 1.3}, {hurt_add, 100} ]; true -> [] end }; get(201201, Lv) -> #ets_skill{ id=201201, name = <<"慧眼明察">>, desc = <<"唐门的秘术,使人拥有杀手一般的嗅觉,轻易找出对手的破绽">>, career = 3, type = 2, obj = 2, mod = 1, area = 0, cd = 0, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,5},{coin,1000},{skill1,201101,2},{skill2,0,0}]}, {crit, 12} ]; Lv == 2 -> [ {condition, [{lv,10},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 18} ]; Lv == 3 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 24} ]; Lv == 4 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 30} ]; Lv == 5 -> [ {condition, [{lv,25},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 36} ]; Lv == 6 -> [ {condition, [{lv,30},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 42} ]; Lv == 7 -> [ {condition, [{lv,35},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 48} ]; Lv == 8 -> [ {condition, [{lv,40},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 54} ]; Lv == 9 -> [ {condition, [{lv,45},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 60} ]; Lv == 10 -> [ {condition, [{lv,50},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {crit, 66} ]; true -> [] end }; get(202101, Lv) -> #ets_skill{ id=202101, name = <<"流星赶月">>, desc = <<"双刺上下翩飞,一前一后刺向敌人咽喉,造成2次伤害">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 6000, lastime = 0, attime = 2, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,14},{coin,1000},{skill1,201102,2},{skill2,0,0}]}, {mp_out, 20}, {att, 0.6} ]; Lv == 2 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 23}, {att, 0.61} ]; Lv == 3 -> [ {condition, [{lv,18},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 26}, {att, 0.62} ]; Lv == 4 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 29}, {att, 0.63} ]; Lv == 5 -> [ {condition, [{lv,24},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 32}, {att, 0.64} ]; Lv == 6 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 35}, {att, 0.65} ]; Lv == 7 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 38}, {att, 0.66} ]; Lv == 8 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 41}, {att, 0.67} ]; Lv == 9 -> [ {condition, [{lv,46},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 44}, {att, 0.68} ]; Lv == 10 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {att, 0.7} ]; true -> [] end }; get(202301, Lv) -> #ets_skill{ id=202301, name = <<"捕风捉影">>, desc = <<"唐门奇术,大幅增加自身的命中。与镜花水月不可同时存在">>, career = 3, type = 1, obj = 1, mod = 1, area = 0, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [205301], data = if Lv == 1 -> [ {condition, [{lv,19},{coin,1000},{skill1,201101,5},{skill2,0,0}]}, {mp_out, 27}, {hit_add, 0.08} ]; Lv == 2 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 29}, {hit_add, 0.09} ]; Lv == 3 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 31}, {hit_add, 0.1} ]; Lv == 4 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 33}, {hit_add, 0.11} ]; Lv == 5 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 35}, {hit_add, 0.12} ]; Lv == 6 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 37}, {hit_add, 0.13} ]; Lv == 7 -> [ {condition, [{lv,38},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 39}, {hit_add, 0.14} ]; Lv == 8 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 41}, {hit_add, 0.15} ]; Lv == 9 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {hit_add, 0.17} ]; Lv == 10 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {hit_add, 0.2} ]; true -> [] end }; get(203101, Lv) -> #ets_skill{ id=203101, name = <<"晓风残月">>, desc = <<"醒时何处,奈何桥,晓风残月。唐门技艺,使人陷入中毒状态">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 8000, lastime = 3000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,24},{coin,1000},{skill1,202101,3},{skill2,0,0}]}, {mp_out, 39}, {att, 1.1}, {drug, [3,1,25]} ]; Lv == 2 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 41}, {att, 1.11}, {drug, [3,1,30]} ]; Lv == 3 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {att, 1.12}, {drug, [3,1,35]} ]; Lv == 4 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {att, 1.13}, {drug, [3,1,40]} ]; Lv == 5 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {att, 1.15}, {drug, [3,1,45]} ]; Lv == 6 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {att, 1.17}, {drug, [3,1,50]} ]; Lv == 7 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {att, 1.19}, {drug, [3,1,55]} ]; Lv == 8 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {att, 1.21}, {drug, [3,1,60]} ]; Lv == 9 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {att, 1.23}, {drug, [3,1,65]} ]; Lv == 10 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 57}, {att, 1.25}, {drug, [3,1,70]} ]; true -> [] end }; get(203301, Lv) -> #ets_skill{ id=203301, name = <<"修罗喋血">>, desc = <<"以自我为中心,暂时提升自己及周围队友的暴击几率">>, career = 3, type = 3, obj = 1, mod = 2, area = 4, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,29},{coin,1000},{skill1,202301,4},{skill2,0,0}]}, {mp_out, 53}, {crit, 20} ]; Lv == 2 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 56}, {crit, 22} ]; Lv == 3 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 59}, {crit, 24} ]; Lv == 4 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 62}, {crit, 26} ]; Lv == 5 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {crit, 28} ]; Lv == 6 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 68}, {crit, 30} ]; Lv == 7 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {crit, 32} ]; Lv == 8 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 74}, {crit, 34} ]; Lv == 9 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {crit, 36} ]; Lv == 10 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 80}, {crit, 38} ]; true -> [] end }; get(204101, Lv) -> #ets_skill{ id=204101, name = <<"漫天花雨">>, desc = <<"无边花雨萧萧飘下,轻取性命手到擒来。唐门高级技艺,伤害周围的目标,并且出现暴击">>, career = 3, type = 1, obj = 2, mod = 2, area = 2, cd = 15000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,39},{coin,1000},{skill1,202101,6},{skill2,0,0}]}, {mp_out, 59}, {att, 1.15}, {crit, 100} ]; Lv == 2 -> [ {condition, [{lv,43},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 61}, {att, 1.17}, {crit, 100} ]; Lv == 3 -> [ {condition, [{lv,47},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 63}, {att, 1.19}, {crit, 100} ]; Lv == 4 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {att, 1.21}, {crit, 100} ]; Lv == 5 -> [ {condition, [{lv,55},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 67}, {att, 1.23}, {crit, 100} ]; Lv == 6 -> [ {condition, [{lv,60},{coin,0},{skill1,0,0},{skill2,0,0}]}, {mp_out, 69}, {att, 1.25}, {crit, 100} ]; Lv == 7 -> [ {condition, [{lv,65},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {att, 1.27}, {crit, 100} ]; Lv == 8 -> [ {condition, [{lv,70},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 73}, {att, 1.29}, {crit, 100} ]; Lv == 9 -> [ {condition, [{lv,75},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 75}, {att, 1.32}, {crit, 100} ]; Lv == 10 -> [ {condition, [{lv,80},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {att, 1.35}, {crit, 100} ]; true -> [] end }; get(205301, Lv) -> #ets_skill{ id=205301, name = <<"镜花水月">>, desc = <<"镜中花,水中月。使用此招,唐门弟子可冲锋陷阵,进退自如。与捕风捉影不可同时存在">>, career = 3, type = 3, obj = 1, mod = 1, area = 0, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [202301], data = if Lv == 1 -> [ {condition, [{lv,44},{coin,1000},{skill1,202301,6},{skill2,0,0}]}, {mp_out, 41}, {dodge, 0.08} ]; Lv == 2 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {dodge, 0.09} ]; Lv == 3 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {dodge, 0.1} ]; Lv == 4 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {dodge, 0.11} ]; Lv == 5 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {dodge, 0.12} ]; Lv == 6 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {dodge, 0.13} ]; Lv == 7 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {dodge, 0.14} ]; Lv == 8 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {dodge, 0.15} ]; true -> [] end }; get(205401, Lv) -> #ets_skill{ id=205401, name = <<"一叶障目">>, desc = <<"一叶障目,不见泰山。中招后,对手会处于失明状态,命中降低">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 45000, lastime = 15000, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,49},{coin,1000},{skill1,201201,7},{skill2,0,0}]}, {mp_out, 41}, {hit_del, 0.16} ]; Lv == 2 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 43}, {hit_del, 0.18} ]; Lv == 3 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {hit_del, 0.20} ]; Lv == 4 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 47}, {hit_del, 0.22} ]; Lv == 5 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 49}, {hit_del, 0.24} ]; Lv == 6 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {hit_del, 0.26} ]; Lv == 7 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {hit_del, 0.28} ]; Lv == 8 -> [ {condition, [{lv,84},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 55}, {hit_del, 0.3} ]; true -> [] end }; get(206101, Lv) -> #ets_skill{ id=206101, name = <<"碧落黄泉">>, desc = <<"上穷碧落下黄泉,终究要相见。但是此见非彼见,是要人性命之见">>, career = 3, type = 1, obj = 2, mod = 1, area = 0, cd = 30000, lastime = 4000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,59},{coin,1000},{skill1,203101,8},{skill2,205301,3}]}, {mp_out, 73}, {att, 1.3}, {speed, 0.3}, {drug, [2,2,75]} ]; Lv == 2 -> [ {condition, [{lv,66},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 78}, {att, 1.35}, {speed, 0.3}, {drug, [2,2,90]} ]; Lv == 3 -> [ {condition, [{lv,73},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {att, 1.4}, {speed, 0.3}, {drug, [2,2,105]} ]; Lv == 4 -> [ {condition, [{lv,81},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 88}, {att, 1.45}, {speed, 0.3}, {drug, [2,2,120]} ]; Lv == 5 -> [ {condition, [{lv,89},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 93}, {att, 1.5}, {speed, 0.3}, {drug, [2,2,135]} ]; true -> [] end }; get(301101, Lv) -> #ets_skill{ id=301101, name = <<"基本剑法">>, desc = <<"初入江湖的基本剑法,只能用来教训一下地痞混混">>, career = 2, type = 1, obj = 2, mod = 1, area = 0, cd = 800, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,1},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 40} ]; Lv == 2 -> [ {condition, [{lv,3},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 60} ]; Lv == 3 -> [ {condition, [{lv,5},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 80} ]; Lv == 4 -> [ {condition, [{lv,8},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 111} ]; Lv == 5 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 122} ]; Lv == 6 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 143} ]; Lv == 7 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 164} ]; Lv == 8 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 185} ]; Lv == 9 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 206} ]; Lv == 10 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 1}, {att, 227} ]; true -> [] end }; get(301102, Lv) -> #ets_skill{ id=301102, name = <<"碎影破">>, desc = <<"剑若闪电,向敌人咽喉要害狠狠刺去">>, career = 2, type = 1, obj = 2, mod = 1, area = 0, cd = 3000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,9},{coin,1000},{skill1,301101,3},{skill2,0,0}]}, {mp_out, 24}, {att, 1.22} ]; Lv == 2 -> [ {condition, [{lv,11},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 27}, {att, 1.24} ]; Lv == 3 -> [ {condition, [{lv,13},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 30}, {att, 1.26} ]; Lv == 4 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 33}, {att, 1.28} ]; Lv == 5 -> [ {condition, [{lv,19},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 36}, {att, 1.3} ]; Lv == 6 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 39}, {att, 1.32} ]; Lv == 7 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 42}, {att, 1.34} ]; Lv == 8 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 45}, {att, 1.36} ]; Lv == 9 -> [ {condition, [{lv,41},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 48}, {att, 1.38} ]; Lv == 10 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 51}, {att, 1.4} ]; true -> [] end }; get(301201, Lv) -> #ets_skill{ id=301201, name = <<"韬光养晦">>, desc = <<"逍遥的心法,永久增加自身的攻击和内力">>, career = 2, type = 2, obj = 2, mod = 1, area = 0, cd = 0, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,5},{coin,1000},{skill1,301101,2},{skill2,0,0}]}, {att, 50}, {mp, 60} ]; Lv == 2 -> [ {condition, [{lv,10},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 70}, {mp, 75} ]; Lv == 3 -> [ {condition, [{lv,15},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 100}, {mp, 95} ]; Lv == 4 -> [ {condition, [{lv,20},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 140}, {mp, 120} ]; Lv == 5 -> [ {condition, [{lv,25},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 190}, {mp, 150} ]; Lv == 6 -> [ {condition, [{lv,30},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 250}, {mp, 185} ]; Lv == 7 -> [ {condition, [{lv,35},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 320}, {mp, 225} ]; Lv == 8 -> [ {condition, [{lv,40},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 400}, {mp, 275} ]; Lv == 9 -> [ {condition, [{lv,45},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 490}, {mp, 330} ]; Lv == 10 -> [ {condition, [{lv,50},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {att, 590}, {mp, 390} ]; true -> [] end }; get(302301, Lv) -> #ets_skill{ id=302301, name = <<"坐忘无我">>, desc = <<"将自己的内力转化成一个护盾,化解所受到伤害">>, career = 2, type = 3, obj = 1, mod = 1, area = 0, cd = 180000, lastime = 60000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,14},{coin,1000},{skill1,301101,3},{skill2,0,0}]}, {mp_out, 60}, {shield, 120} ]; Lv == 2 -> [ {condition, [{lv,16},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 73}, {shield, 146} ]; Lv == 3 -> [ {condition, [{lv,18},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 81}, {shield, 163} ]; Lv == 4 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 98}, {shield, 196} ]; Lv == 5 -> [ {condition, [{lv,24},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 121}, {shield, 243} ]; Lv == 6 -> [ {condition, [{lv,28},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 148}, {shield, 296} ]; Lv == 7 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 166}, {shield, 333} ]; Lv == 8 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 192}, {shield, 386} ]; Lv == 9 -> [ {condition, [{lv,46},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 231}, {shield, 463} ]; Lv == 10 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 293}, {shield, 586} ]; true -> [] end }; get(302501, Lv) -> #ets_skill{ id=302501, name = <<"春泥护花">>, desc = <<"落红本有情,春泥更护花。逍遥弟子怀柔天下,此计可以回复选中目标的生命值">>, career = 2, type = 3, obj = 3, mod = 1, area = 0, cd = 15000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,19},{coin,1000},{skill1,301201,3},{skill2,0,0}]}, {mp_out, 69}, {hp, 200} ]; Lv == 2 -> [ {condition, [{lv,21},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 76}, {hp, 250} ]; Lv == 3 -> [ {condition, [{lv,23},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {hp, 300} ]; Lv == 4 -> [ {condition, [{lv,26},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {hp, 400} ]; Lv == 5 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {hp, 500} ]; Lv == 6 -> [ {condition, [{lv,33},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 104}, {hp, 600} ]; Lv == 7 -> [ {condition, [{lv,38},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 111}, {hp, 750} ]; Lv == 8 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 118}, {hp, 900} ]; Lv == 9 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 125}, {hp, 1050} ]; Lv == 10 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 132}, {hp, 1200} ]; true -> [] end }; get(303101, Lv) -> #ets_skill{ id=303101, name = <<"风卷残云">>, desc = <<"风卷残云,剑气临空惊魂梦。对目标范围内发出半月形的剑气,群体伤害">>, career = 2, type = 1, obj = 2, mod = 2, area = 2, cd = 6000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,24},{coin,1000},{skill1,301102,5},{skill2,0,0}]}, {mp_out, 47}, {att, 1.22} ]; Lv == 2 -> [ {condition, [{lv,29},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 53}, {att, 1.24} ]; Lv == 3 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 59}, {att, 1.26} ]; Lv == 4 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {att, 1.28} ]; Lv == 5 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {att, 1.3} ]; Lv == 6 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {att, 1.32} ]; Lv == 7 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {att, 1.34} ]; Lv == 8 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 89}, {att, 1.36} ]; Lv == 9 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 95}, {att, 1.38} ]; Lv == 10 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 101}, {att, 1.4} ]; true -> [] end }; get(303301, Lv) -> #ets_skill{ id=303301, name = <<"剑气纵横">>, desc = <<"剑气惊风雨,纵横泣鬼神。出以气为兵,以剑为辅,群体增加攻击力">>, career = 2, type = 3, obj = 1, mod = 2, area = 4, cd = 30000, lastime = 900000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,29},{coin,1000},{skill1,302301,4},{skill2,0,0}]}, {mp_out, 69}, {att, 116} ]; Lv == 2 -> [ {condition, [{lv,34},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 76}, {att, 156} ]; Lv == 3 -> [ {condition, [{lv,39},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {att, 223} ]; Lv == 4 -> [ {condition, [{lv,44},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 90}, {att, 263} ]; Lv == 5 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {att, 307} ]; Lv == 6 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 104}, {att, 347} ]; Lv == 7 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 111}, {att, 393} ]; Lv == 8 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 118}, {att, 432} ]; Lv == 9 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 125}, {att, 522} ]; Lv == 10 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 132}, {att, 651} ]; true -> [] end }; get(304101, Lv) -> #ets_skill{ id=304101, name = <<"碧海潮生">>, desc = <<"碧海涛起天地惊,潮生潮落尽彷徨。以自身为中心,周围所有单位受到伤害,而且移动速度降低">>, career = 2, type = 1, obj = 1, mod = 2, area = 2, cd = 10000, lastime = 3000, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,39},{coin,1000},{skill1,303101,3},{skill2,0,0}]}, {mp_out, 67}, {att, 1.25}, {speed, 0.15} ]; Lv == 2 -> [ {condition, [{lv,43},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 73}, {att, 1.27}, {speed, 0.15} ]; Lv == 3 -> [ {condition, [{lv,47},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 79}, {att, 1.3}, {speed, 0.15} ]; Lv == 4 -> [ {condition, [{lv,51},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 85}, {att, 1.33}, {speed, 0.15} ]; Lv == 5 -> [ {condition, [{lv,55},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 91}, {att, 1.35}, {speed, 0.15} ]; Lv == 6 -> [ {condition, [{lv,60},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 97}, {att, 1.38}, {speed, 0.15} ]; Lv == 7 -> [ {condition, [{lv,65},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 103}, {att, 1.4}, {speed, 0.15} ]; Lv == 8 -> [ {condition, [{lv,70},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 109}, {att, 1.43}, {speed, 0.15} ]; Lv == 9 -> [ {condition, [{lv,75},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 115}, {att, 1.46}, {speed, 0.15} ]; Lv == 10 -> [ {condition, [{lv,80},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 121}, {att, 1.5}, {speed, 0.15} ]; true -> [] end }; get(305101, Lv) -> #ets_skill{ id=305101, name = <<"绕指柔">>, desc = <<"相见时难别亦难。发出数道剑气,降低目标的移动速度">>, career = 2, type = 1, obj = 2, mod = 1, area = 0, cd = 15000, lastime = 2000, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,49},{coin,1000},{skill1,304101,3},{skill2,0,0}]}, {mp_out, 59}, {hurt_add, 1.45}, {speed, 0.3} ]; Lv == 2 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 65}, {hurt_add, 1.5}, {speed, 0.3} ]; Lv == 3 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 71}, {hurt_add, 1.55}, {speed, 0.3} ]; Lv == 4 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 77}, {hurt_add, 1.6}, {speed, 0.3} ]; Lv == 5 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 83}, {hurt_add, 1.65}, {speed, 0.3} ]; Lv == 6 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 89}, {hurt_add, 1.7}, {speed, 0.3} ]; Lv == 7 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 95}, {hurt_add, 1.75}, {speed, 0.3} ]; Lv == 8 -> [ {condition, [{lv,84},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 101}, {hurt_add, 1.8}, {speed, 0.3} ]; true -> [] end }; get(305501, Lv) -> #ets_skill{ id=305501, name = <<"慈航普渡">>, desc = <<"心怀天下,大爱无边。逍遥济世之术,群体回复生命值">>, career = 2, type = 3, obj = 1, mod = 2, area = 4, cd = 25000, lastime = 0, attime = 1, attarea = 0, limit = [], data = if Lv == 1 -> [ {condition, [{lv,44},{coin,1000},{skill1,302501,6},{skill2,0,0}]}, {mp_out, 90}, {hp, 220} ]; Lv == 2 -> [ {condition, [{lv,49},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 99}, {hp, 298} ]; Lv == 3 -> [ {condition, [{lv,54},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 108}, {hp, 361} ]; Lv == 4 -> [ {condition, [{lv,59},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 117}, {hp, 433} ]; Lv == 5 -> [ {condition, [{lv,64},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 126}, {hp, 534} ]; Lv == 6 -> [ {condition, [{lv,69},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 135}, {hp, 612} ]; Lv == 7 -> [ {condition, [{lv,74},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 144}, {hp, 718} ]; Lv == 8 -> [ {condition, [{lv,79},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 153}, {hp, 862} ]; true -> [] end }; get(306101, Lv) -> #ets_skill{ id=306101, name = <<"六合独尊">>, desc = <<"六合同归,大道逍遥。发出无数剑气,对目标范围内的敌人进行致命打击">>, career = 2, type = 1, obj = 2, mod = 2, area = 2, cd = 30000, lastime = 0, attime = 1, attarea = 4, limit = [], data = if Lv == 1 -> [ {condition, [{lv,59},{coin,1000},{skill1,305501,3},{skill2,305101,2}]}, {mp_out, 118}, {att, 1.6} ]; Lv == 2 -> [ {condition, [{lv,67},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 130}, {att, 1.65} ]; Lv == 3 -> [ {condition, [{lv,73},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 142}, {att, 1.7} ]; Lv == 4 -> [ {condition, [{lv,81},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 154}, {att, 1.75} ]; Lv == 5 -> [ {condition, [{lv,89},{coin,1000},{skill1,0,0},{skill2,0,0}]}, {mp_out, 166}, {att, 1.8} ]; true -> [] end }; get(_Id, _Lv) -> [].
765e34bd5c8c7307bafb04c6a4a29344aa13de7f161e699982c444e705eb5b0e
tsloughter/kuberl
kuberl_v1_pod_template_list.erl
-module(kuberl_v1_pod_template_list). -export([encode/1]). -export_type([kuberl_v1_pod_template_list/0]). -type kuberl_v1_pod_template_list() :: #{ 'apiVersion' => binary(), 'items' := list(), 'kind' => binary(), 'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta() }. encode(#{ 'apiVersion' := ApiVersion, 'items' := Items, 'kind' := Kind, 'metadata' := Metadata }) -> #{ 'apiVersion' => ApiVersion, 'items' => Items, 'kind' => Kind, 'metadata' => Metadata }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_pod_template_list.erl
erlang
-module(kuberl_v1_pod_template_list). -export([encode/1]). -export_type([kuberl_v1_pod_template_list/0]). -type kuberl_v1_pod_template_list() :: #{ 'apiVersion' => binary(), 'items' := list(), 'kind' => binary(), 'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta() }. encode(#{ 'apiVersion' := ApiVersion, 'items' := Items, 'kind' := Kind, 'metadata' := Metadata }) -> #{ 'apiVersion' => ApiVersion, 'items' => Items, 'kind' => Kind, 'metadata' => Metadata }.
e60f23224fc50220cb2a9d9381090785fa204548aa5f2095e39dbd6b661d66d1
jaredly/reason-language-server
switch.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet , INRIA Rocquencourt (* *) Copyright 2000 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. *) (* *) (**************************************************************************) (* This module transforms generic switches in combinations of if tests and switches. *) (* For detecting action sharing, object style *) (* Store for actions in object style: act_store : store an action, returns index in table In case an action with equal key exists, returns index of the stored action. Otherwise add entry in table. act_store_shared : This stored action will always be shared. act_get : retrieve table act_get_shared : retrieve table, with sharing explicit *) type 'a shared = Shared of 'a | Single of 'a type 'a t_store = {act_get : unit -> 'a array ; act_get_shared : unit -> 'a shared array ; act_store : 'a -> int ; act_store_shared : 'a -> int ; } exception Not_simple module type Stored = sig type t type key val compare_key : key -> key -> int val make_key : t -> key option end module Store(A:Stored) : sig val mk_store : unit -> A.t t_store end (* Arguments to the Make functor *) module type S = sig (* type of basic tests *) type primitive (* basic tests themselves *) val eqint : primitive val neint : primitive val leint : primitive val ltint : primitive val geint : primitive val gtint : primitive (* type of actions *) type act Various constructors , for making a binder , adding one integer , etc . adding one integer, etc. *) val bind : act -> (act -> act) -> act val make_const : int -> act val make_offset : act -> int -> act val make_prim : primitive -> act list -> act val make_isout : act -> act -> act val make_isin : act -> act -> act val make_if : act -> act -> act -> act construct an actual switch : make_switch arg cases acts NB : cases is in the value form make_switch arg cases acts NB: cases is in the value form *) val make_switch : Location.t -> act -> int array -> act array -> act Build last minute sharing of action stuff val make_catch : act -> int * (act -> act) val make_exit : int -> act end Make.zyva arg low high cases actions where - arg is the argument of the switch . - low , high are the interval limits . - cases is a list of sub - interval and action indices - actions is an array of actions . All these arguments specify a switch construct and zyva returns an action that performs the switch . Make.zyva arg low high cases actions where - arg is the argument of the switch. - low, high are the interval limits. - cases is a list of sub-interval and action indices - actions is an array of actions. All these arguments specify a switch construct and zyva returns an action that performs the switch. *) module Make : functor (Arg : S) -> sig (* Standard entry point, sharing is tracked *) val zyva : Location.t -> (int * int) -> Arg.act -> (int * int * int) array -> Arg.act t_store -> Arg.act (* Output test sequence, sharing tracked *) val test_sequence : Arg.act -> (int * int * int) array -> Arg.act t_store -> Arg.act end
null
https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/406/switch.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. ************************************************************************ This module transforms generic switches in combinations of if tests and switches. For detecting action sharing, object style Store for actions in object style: act_store : store an action, returns index in table In case an action with equal key exists, returns index of the stored action. Otherwise add entry in table. act_store_shared : This stored action will always be shared. act_get : retrieve table act_get_shared : retrieve table, with sharing explicit Arguments to the Make functor type of basic tests basic tests themselves type of actions Standard entry point, sharing is tracked Output test sequence, sharing tracked
, projet , INRIA Rocquencourt Copyright 2000 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the type 'a shared = Shared of 'a | Single of 'a type 'a t_store = {act_get : unit -> 'a array ; act_get_shared : unit -> 'a shared array ; act_store : 'a -> int ; act_store_shared : 'a -> int ; } exception Not_simple module type Stored = sig type t type key val compare_key : key -> key -> int val make_key : t -> key option end module Store(A:Stored) : sig val mk_store : unit -> A.t t_store end module type S = sig type primitive val eqint : primitive val neint : primitive val leint : primitive val ltint : primitive val geint : primitive val gtint : primitive type act Various constructors , for making a binder , adding one integer , etc . adding one integer, etc. *) val bind : act -> (act -> act) -> act val make_const : int -> act val make_offset : act -> int -> act val make_prim : primitive -> act list -> act val make_isout : act -> act -> act val make_isin : act -> act -> act val make_if : act -> act -> act -> act construct an actual switch : make_switch arg cases acts NB : cases is in the value form make_switch arg cases acts NB: cases is in the value form *) val make_switch : Location.t -> act -> int array -> act array -> act Build last minute sharing of action stuff val make_catch : act -> int * (act -> act) val make_exit : int -> act end Make.zyva arg low high cases actions where - arg is the argument of the switch . - low , high are the interval limits . - cases is a list of sub - interval and action indices - actions is an array of actions . All these arguments specify a switch construct and zyva returns an action that performs the switch . Make.zyva arg low high cases actions where - arg is the argument of the switch. - low, high are the interval limits. - cases is a list of sub-interval and action indices - actions is an array of actions. All these arguments specify a switch construct and zyva returns an action that performs the switch. *) module Make : functor (Arg : S) -> sig val zyva : Location.t -> (int * int) -> Arg.act -> (int * int * int) array -> Arg.act t_store -> Arg.act val test_sequence : Arg.act -> (int * int * int) array -> Arg.act t_store -> Arg.act end
a51c4e1268d96d50cc680deee38a5c4847d9a8f6557e46f094fe48feab48ad56
vraid/earthgen
flvector3.rkt
#lang typed/racket (provide (all-defined-out)) (require "flvector3-local.rkt" math/flonum) (: flvector3-zero (-> FlVector)) (define (flvector3-zero) (flvector 0.0 0.0 0.0)) (: flvector3-zero? (FlVector -> Boolean)) (define (flvector3-zero? v) (zero? (flvector3-length-squared v))) (: flvector3-negative (FlVector -> FlVector)) (define (flvector3-negative v) (flvector3-scale -1.0 v)) (: flvector3-length-squared (FlVector -> Float)) (define (flvector3-length-squared v) (flvector-sum (flvector-sqr v))) (: flvector3-length (FlVector -> Float)) (define (flvector3-length v) (flsqrt (flvector3-length-squared v))) (: flvector3-distance-squared (FlVector FlVector -> Float)) (define (flvector3-distance-squared u v) (flvector3-length-squared (flvector- v u))) (: flvector3-distance (FlVector FlVector -> Float)) (define (flvector3-distance u v) (flvector3-length (flvector- v u))) (: flvector3-scale (Float FlVector -> FlVector)) (define (flvector3-scale a v) (flvector-scale v a)) (: flvector3-scale-to (Float FlVector -> FlVector)) (define (flvector3-scale-to a v) (flvector3-scale (/ a (flvector3-length v)) v)) (: flvector3-normal (FlVector -> FlVector)) (define (flvector3-normal a) (if (zero? (flvector3-length-squared a)) a (flvector3-scale (/ (flvector3-length a)) a))) (: flvector3-sum (FlVector * -> FlVector)) (define (flvector3-sum . vecs) (foldl flvector+ (flvector3-zero) vecs)) (: flvector3-subtract (FlVector FlVector -> FlVector)) (define (flvector3-subtract a b) (flvector- a b)) (: flvector3-subtract-by (FlVector FlVector -> FlVector)) (define (flvector3-subtract-by a b) (flvector- b a)) (: flvector3-dot-product (FlVector FlVector -> Float)) (define (flvector3-dot-product u v) (flvector-sum (flvector-map * u v))) (: flvector3-cross-product (FlVector FlVector -> FlVector)) (define (flvector3-cross-product u v) (let* ([m (vector 1 2 0)] [n (vector 2 0 1)]) (flvector- (col u m v n) (col u n v m)))) (: flvector3-angle (FlVector FlVector -> Float)) (define (flvector3-angle a b) (flacos (fl/ (flvector3-dot-product a b) (flsqrt (* (flvector3-length-squared a) (flvector3-length-squared b)))))) (: flvector3-projection (FlVector FlVector -> FlVector)) (define (flvector3-projection target v) (let ([n (flvector3-normal target)]) (flvector3-scale (flvector3-dot-product n v) n))) (: flvector3-rejection (FlVector FlVector -> FlVector)) (define (flvector3-rejection rejector v) (flvector- v (flvector3-projection rejector v))) (: flvector3-parallel? (FlVector FlVector -> Boolean)) (define (flvector3-parallel? u v) (zero? (flvector-sum (flvector3-cross-product u v))))
null
https://raw.githubusercontent.com/vraid/earthgen/208ac834c02208ddc16a31aa9e7ff7f91c18e046/package/vraid/math/flvector3.rkt
racket
#lang typed/racket (provide (all-defined-out)) (require "flvector3-local.rkt" math/flonum) (: flvector3-zero (-> FlVector)) (define (flvector3-zero) (flvector 0.0 0.0 0.0)) (: flvector3-zero? (FlVector -> Boolean)) (define (flvector3-zero? v) (zero? (flvector3-length-squared v))) (: flvector3-negative (FlVector -> FlVector)) (define (flvector3-negative v) (flvector3-scale -1.0 v)) (: flvector3-length-squared (FlVector -> Float)) (define (flvector3-length-squared v) (flvector-sum (flvector-sqr v))) (: flvector3-length (FlVector -> Float)) (define (flvector3-length v) (flsqrt (flvector3-length-squared v))) (: flvector3-distance-squared (FlVector FlVector -> Float)) (define (flvector3-distance-squared u v) (flvector3-length-squared (flvector- v u))) (: flvector3-distance (FlVector FlVector -> Float)) (define (flvector3-distance u v) (flvector3-length (flvector- v u))) (: flvector3-scale (Float FlVector -> FlVector)) (define (flvector3-scale a v) (flvector-scale v a)) (: flvector3-scale-to (Float FlVector -> FlVector)) (define (flvector3-scale-to a v) (flvector3-scale (/ a (flvector3-length v)) v)) (: flvector3-normal (FlVector -> FlVector)) (define (flvector3-normal a) (if (zero? (flvector3-length-squared a)) a (flvector3-scale (/ (flvector3-length a)) a))) (: flvector3-sum (FlVector * -> FlVector)) (define (flvector3-sum . vecs) (foldl flvector+ (flvector3-zero) vecs)) (: flvector3-subtract (FlVector FlVector -> FlVector)) (define (flvector3-subtract a b) (flvector- a b)) (: flvector3-subtract-by (FlVector FlVector -> FlVector)) (define (flvector3-subtract-by a b) (flvector- b a)) (: flvector3-dot-product (FlVector FlVector -> Float)) (define (flvector3-dot-product u v) (flvector-sum (flvector-map * u v))) (: flvector3-cross-product (FlVector FlVector -> FlVector)) (define (flvector3-cross-product u v) (let* ([m (vector 1 2 0)] [n (vector 2 0 1)]) (flvector- (col u m v n) (col u n v m)))) (: flvector3-angle (FlVector FlVector -> Float)) (define (flvector3-angle a b) (flacos (fl/ (flvector3-dot-product a b) (flsqrt (* (flvector3-length-squared a) (flvector3-length-squared b)))))) (: flvector3-projection (FlVector FlVector -> FlVector)) (define (flvector3-projection target v) (let ([n (flvector3-normal target)]) (flvector3-scale (flvector3-dot-product n v) n))) (: flvector3-rejection (FlVector FlVector -> FlVector)) (define (flvector3-rejection rejector v) (flvector- v (flvector3-projection rejector v))) (: flvector3-parallel? (FlVector FlVector -> Boolean)) (define (flvector3-parallel? u v) (zero? (flvector-sum (flvector3-cross-product u v))))
2618ee28f69c995eacae7e16a70a9b307bfd538761ecffe6d23c4c3491ee7d69
biocad/servant-openapi3
OpenApi.hs
-- | Module : Servant . OpenApi License : BSD3 Maintainer : < > -- Stability: experimental -- -- This module provides means to generate and manipulate OpenApi specification for servant APIs . -- OpenApi is a project used to describe and document RESTful APIs . -- The OpenApi specification defines a set of files required to describe such an API . These files can then be used by the OpenApi - UI project to display the API and OpenApi - Codegen to generate clients in various languages . -- Additional utilities can also take advantage of the resulting files, such as testing tools. -- For more information see < / OpenApi documentation > . module Servant.OpenApi ( -- * How to use this library -- $howto -- ** Generate @'OpenApi'@ -- $generate -- ** Annotate -- $annotate -- ** Test -- $test -- ** Serve -- $serve -- * @'HasOpenApi'@ class HasOpenApi(..), -- * Manipulation subOperations, -- * Testing validateEveryToJSON, validateEveryToJSONWithPatternChecker, ) where import Servant.OpenApi.Internal import Servant.OpenApi.Test import Servant.OpenApi.Internal.Orphans () -- $setup > > > import Control . Applicative > > > import Control . Lens -- >>> import Data.Aeson > > > import Data . OpenApi > > > import Data . Typeable > > > import -- >>> import Servant.API -- >>> import Test.Hspec -- >>> import Test.QuickCheck > > > import qualified Data . ByteString . Lazy . Char8 as BSL8 > > > import Servant . OpenApi . Internal . Test -- >>> :set -XDataKinds -- >>> :set -XDeriveDataTypeable -- >>> :set -XDeriveGeneric -- >>> :set -XGeneralizedNewtypeDeriving -- >>> :set -XOverloadedStrings -- >>> :set -XTypeOperators > > > data User = User { name : : String , age : : Int } deriving ( Show , Generic , ) > > > newtype UserId = UserId Integer deriving ( Show , Generic , Typeable , ToJSON ) > > > instance ToJSON User > > > instance User > > > instance UserId > > > instance ToParamSchema UserId > > > type = Get ' [ JSON ] [ User ] > > > type Capture " user_id " UserId :> Get ' [ JSON ] User > > > type PostUser = ReqBody ' [ JSON ] User :> Post ' [ JSON ] UserId > > > type UserAPI = GetUsers : < | > GetUser : < | > PostUser -- $howto -- This section explains how to use this library to generate OpenApi specification , -- modify it and run automatic tests for a servant API. -- -- For the purposes of this section we will use this servant API: -- > > > data User = User { name : : String , age : : Int } deriving ( Show , Generic , ) > > > newtype UserId = UserId Integer deriving ( Show , Generic , Typeable , ToJSON ) > > > instance ToJSON User > > > instance User > > > instance UserId > > > instance ToParamSchema UserId > > > type = Get ' [ JSON ] [ User ] > > > type Capture " user_id " UserId :> Get ' [ JSON ] User > > > type PostUser = ReqBody ' [ JSON ] User :> Post ' [ JSON ] UserId > > > type UserAPI = GetUsers : < | > GetUser : < | > PostUser -- Here we define a user API with three endpoints . @GetUsers@ endpoint returns a list of all users . -- @GetUser@ returns a user given his\/her ID. @PostUser@ creates a new user and returns his\/her ID. -- $generate In order to generate @'OpenApi'@ specification for a servant API , just use @'toOpenApi'@ : -- > > > BSL8.putStrLn $ encodePretty $ toOpenApi ( Proxy : : Proxy UserAPI ) -- { -- "components": { -- "schemas": { -- "User": { -- "properties": { -- "age": { " maximum " : 9223372036854775807 , -- "minimum": -9223372036854775808, -- "type": "integer" -- }, -- "name": { -- "type": "string" -- } -- }, -- "required": [ -- "name", -- "age" -- ], -- "type": "object" -- }, -- "UserId": { -- "type": "integer" -- } -- } -- }, -- "info": { -- "title": "", -- "version": "" -- }, -- "openapi": "3.0.0", -- "paths": { -- "/": { -- "get": { -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "items": { -- "$ref": "#/components/schemas/User" -- }, -- "type": "array" -- } -- } -- }, -- "description": "" -- } -- } -- }, -- "post": { -- "requestBody": { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/User" -- } -- } -- } -- }, -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/UserId" -- } -- } -- }, -- "description": "" -- }, " 400 " : { -- "description": "Invalid `body`" -- } -- } -- } -- }, -- "/{user_id}": { -- "get": { -- "parameters": [ -- { -- "in": "path", -- "name": "user_id", -- "required": true, -- "schema": { -- "type": "integer" -- } -- } -- ], -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/User" -- } -- } -- }, -- "description": "" -- }, " 404 " : { -- "description": "`user_id` not found" -- } -- } -- } -- } -- } -- } -- By default @'toOpenApi'@ will generate specification for all API routes , parameters , headers , responses and data schemas . -- For some parameters it will also add 400 and/or 404 responses with a description mentioning parameter name . -- -- Data schemas come from @'ToParamSchema'@ and @'ToSchema'@ classes. -- $annotate -- While initially generated @'OpenApi'@ looks good, it lacks some information it can't get from a servant API. -- -- We can add this information using field lenses from @"Data.OpenApi"@: -- -- >>> :{ BSL8.putStrLn $ encodePretty $ toOpenApi ( Proxy : : Proxy UserAPI ) -- & info.title .~ "User API" & info.version .~ " 1.0 " -- & info.description ?~ "This is an API for the Users service" & info.license ? ~ " MIT " & servers .~ [ " " ] -- :} -- { -- "components": { -- "schemas": { -- "User": { -- "properties": { -- "age": { " maximum " : 9223372036854775807 , -- "minimum": -9223372036854775808, -- "type": "integer" -- }, -- "name": { -- "type": "string" -- } -- }, -- "required": [ -- "name", -- "age" -- ], -- "type": "object" -- }, -- "UserId": { -- "type": "integer" -- } -- } -- }, -- "info": { -- "description": "This is an API for the Users service", -- "license": { " name " : " MIT " -- }, -- "title": "User API", " version " : " 1.0 " -- }, -- "openapi": "3.0.0", -- "paths": { -- "/": { -- "get": { -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "items": { -- "$ref": "#/components/schemas/User" -- }, -- "type": "array" -- } -- } -- }, -- "description": "" -- } -- } -- }, -- "post": { -- "requestBody": { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/User" -- } -- } -- } -- }, -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/UserId" -- } -- } -- }, -- "description": "" -- }, " 400 " : { -- "description": "Invalid `body`" -- } -- } -- } -- }, -- "/{user_id}": { -- "get": { -- "parameters": [ -- { -- "in": "path", -- "name": "user_id", -- "required": true, -- "schema": { -- "type": "integer" -- } -- } -- ], -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/User" -- } -- } -- }, -- "description": "" -- }, " 404 " : { -- "description": "`user_id` not found" -- } -- } -- } -- } -- }, -- "servers": [ -- { -- "url": "" -- } -- ] -- } -- -- It is also useful to annotate or modify certain endpoints. @'subOperations'@ provides a convenient way to zoom into a part of an API . -- -- @'subOperations' sub api@ traverses all operations of the @api@ which are also present in @sub@. Furthermore , @sub@ is required to be an exact sub API of @api . Otherwise it will not . -- @"Data . OpenApi . Operation"@ provides some useful helpers that can be used with @'subOperations'@. One example is applying tags to certain endpoints : -- > > > let subOperations ( Proxy : : Proxy ( GetUsers : < | > GetUser ) ) ( Proxy : : Proxy UserAPI ) > > > let postOps = subOperations ( Proxy : : Proxy PostUser ) ( Proxy : : Proxy UserAPI ) -- >>> :{ BSL8.putStrLn $ encodePretty $ toOpenApi ( Proxy : : Proxy UserAPI ) & applyTagsFor [ " get " & description ? ~ " GET operations " ] -- & applyTagsFor postOps ["post" & description ?~ "POST operations"] -- :} -- { -- "components": { -- "schemas": { -- "User": { -- "properties": { -- "age": { " maximum " : 9223372036854775807 , -- "minimum": -9223372036854775808, -- "type": "integer" -- }, -- "name": { -- "type": "string" -- } -- }, -- "required": [ -- "name", -- "age" -- ], -- "type": "object" -- }, -- "UserId": { -- "type": "integer" -- } -- } -- }, -- "info": { -- "title": "", -- "version": "" -- }, -- "openapi": "3.0.0", -- "paths": { -- "/": { -- "get": { -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "items": { -- "$ref": "#/components/schemas/User" -- }, -- "type": "array" -- } -- } -- }, -- "description": "" -- } -- }, -- "tags": [ -- "get" -- ] -- }, -- "post": { -- "requestBody": { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/User" -- } -- } -- } -- }, -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/UserId" -- } -- } -- }, -- "description": "" -- }, " 400 " : { -- "description": "Invalid `body`" -- } -- }, -- "tags": [ -- "post" -- ] -- } -- }, -- "/{user_id}": { -- "get": { -- "parameters": [ -- { -- "in": "path", -- "name": "user_id", -- "required": true, -- "schema": { -- "type": "integer" -- } -- } -- ], -- "responses": { " 200 " : { -- "content": { -- "application/json;charset=utf-8": { -- "schema": { -- "$ref": "#/components/schemas/User" -- } -- } -- }, -- "description": "" -- }, " 404 " : { -- "description": "`user_id` not found" -- } -- }, -- "tags": [ -- "get" -- ] -- } -- } -- }, -- "tags": [ -- { -- "description": "GET operations", -- "name": "get" -- }, -- { -- "description": "POST operations", -- "name": "post" -- } -- ] -- } -- This applies @\"get\"@ tag to the @GET@ endpoints and @\"post\"@ tag to the @POST@ endpoint of the User API . -- $test -- Automatic generation of data schemas uses @'ToSchema'@ instances for the types -- used in a servant API. But to encode/decode actual data servant uses different classes. For instance in @UserAPI@ @User@ is always encoded / decoded using @'ToJSON'@ and @'FromJSON'@ instances . -- To be sure your server / client handles data properly you need to check that @'ToJSON'@ instance always generates values that satisfy schema produced -- by @'ToSchema'@ instance. -- -- With @'validateEveryToJSON'@ it is possible to test all those instances automatically, -- without having to write down every type: -- -- >>> instance Arbitrary User where arbitrary = User <$> arbitrary <*> arbitrary -- >>> instance Arbitrary UserId where arbitrary = UserId <$> arbitrary > > > validateEveryToJSON ( Proxy : : Proxy UserAPI ) -- <BLANKLINE> -- [User]... -- ... -- User... -- ... -- UserId... -- ... -- Finished in ... seconds ... 3 examples , 0 failures ... -- Although servant is great , chances are that your API clients do n't use . In many cases @swagger.json@ serves as a specification , not a type . -- -- In this cases it is a good idea to store generated and annotated @'OpenApi'@ in a @swagger.json@ file under a version control system ( such as , Subversion , Mercurial , etc . ) . -- -- It is also recommended to version API based on changes to the @swagger.json@ rather than changes to the Haskell API . -- -- See <example/test/TodoSpec.hs TodoSpec.hs> for an example of a complete test suite for a swagger specification. -- $serve -- If you're implementing a server for an API, you might also want to serve its @'OpenApi'@ specification. -- -- See <example/src/Todo.hs Todo.hs> for an example of a server.
null
https://raw.githubusercontent.com/biocad/servant-openapi3/f7d5491cd16f6cd390244a53c18c4c781c75b995/src/Servant/OpenApi.hs
haskell
| Stability: experimental This module provides means to generate and manipulate Additional utilities can also take advantage of the resulting files, such as testing tools. * How to use this library $howto ** Generate @'OpenApi'@ $generate ** Annotate $annotate ** Test $test ** Serve $serve * @'HasOpenApi'@ class * Manipulation * Testing $setup >>> import Data.Aeson >>> import Servant.API >>> import Test.Hspec >>> import Test.QuickCheck >>> :set -XDataKinds >>> :set -XDeriveDataTypeable >>> :set -XDeriveGeneric >>> :set -XGeneralizedNewtypeDeriving >>> :set -XOverloadedStrings >>> :set -XTypeOperators $howto modify it and run automatic tests for a servant API. For the purposes of this section we will use this servant API: @GetUser@ returns a user given his\/her ID. @PostUser@ creates a new user and returns his\/her ID. $generate { "components": { "schemas": { "User": { "properties": { "age": { "minimum": -9223372036854775808, "type": "integer" }, "name": { "type": "string" } }, "required": [ "name", "age" ], "type": "object" }, "UserId": { "type": "integer" } } }, "info": { "title": "", "version": "" }, "openapi": "3.0.0", "paths": { "/": { "get": { "responses": { "content": { "application/json;charset=utf-8": { "schema": { "items": { "$ref": "#/components/schemas/User" }, "type": "array" } } }, "description": "" } } }, "post": { "requestBody": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/User" } } } }, "responses": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/UserId" } } }, "description": "" }, "description": "Invalid `body`" } } } }, "/{user_id}": { "get": { "parameters": [ { "in": "path", "name": "user_id", "required": true, "schema": { "type": "integer" } } ], "responses": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/User" } } }, "description": "" }, "description": "`user_id` not found" } } } } } } Data schemas come from @'ToParamSchema'@ and @'ToSchema'@ classes. $annotate While initially generated @'OpenApi'@ looks good, it lacks some information it can't get from a servant API. We can add this information using field lenses from @"Data.OpenApi"@: >>> :{ & info.title .~ "User API" & info.description ?~ "This is an API for the Users service" :} { "components": { "schemas": { "User": { "properties": { "age": { "minimum": -9223372036854775808, "type": "integer" }, "name": { "type": "string" } }, "required": [ "name", "age" ], "type": "object" }, "UserId": { "type": "integer" } } }, "info": { "description": "This is an API for the Users service", "license": { }, "title": "User API", }, "openapi": "3.0.0", "paths": { "/": { "get": { "responses": { "content": { "application/json;charset=utf-8": { "schema": { "items": { "$ref": "#/components/schemas/User" }, "type": "array" } } }, "description": "" } } }, "post": { "requestBody": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/User" } } } }, "responses": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/UserId" } } }, "description": "" }, "description": "Invalid `body`" } } } }, "/{user_id}": { "get": { "parameters": [ { "in": "path", "name": "user_id", "required": true, "schema": { "type": "integer" } } ], "responses": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/User" } } }, "description": "" }, "description": "`user_id` not found" } } } } }, "servers": [ { "url": "" } ] } It is also useful to annotate or modify certain endpoints. @'subOperations' sub api@ traverses all operations of the @api@ which are also present in @sub@. >>> :{ & applyTagsFor postOps ["post" & description ?~ "POST operations"] :} { "components": { "schemas": { "User": { "properties": { "age": { "minimum": -9223372036854775808, "type": "integer" }, "name": { "type": "string" } }, "required": [ "name", "age" ], "type": "object" }, "UserId": { "type": "integer" } } }, "info": { "title": "", "version": "" }, "openapi": "3.0.0", "paths": { "/": { "get": { "responses": { "content": { "application/json;charset=utf-8": { "schema": { "items": { "$ref": "#/components/schemas/User" }, "type": "array" } } }, "description": "" } }, "tags": [ "get" ] }, "post": { "requestBody": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/User" } } } }, "responses": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/UserId" } } }, "description": "" }, "description": "Invalid `body`" } }, "tags": [ "post" ] } }, "/{user_id}": { "get": { "parameters": [ { "in": "path", "name": "user_id", "required": true, "schema": { "type": "integer" } } ], "responses": { "content": { "application/json;charset=utf-8": { "schema": { "$ref": "#/components/schemas/User" } } }, "description": "" }, "description": "`user_id` not found" } }, "tags": [ "get" ] } } }, "tags": [ { "description": "GET operations", "name": "get" }, { "description": "POST operations", "name": "post" } ] } $test Automatic generation of data schemas uses @'ToSchema'@ instances for the types used in a servant API. But to encode/decode actual data servant uses different classes. by @'ToSchema'@ instance. With @'validateEveryToJSON'@ it is possible to test all those instances automatically, without having to write down every type: >>> instance Arbitrary User where arbitrary = User <$> arbitrary <*> arbitrary >>> instance Arbitrary UserId where arbitrary = UserId <$> arbitrary <BLANKLINE> [User]... ... User... ... UserId... ... Finished in ... seconds In this cases it is a good idea to store generated and annotated @'OpenApi'@ in a @swagger.json@ file It is also recommended to version API based on changes to the @swagger.json@ rather than changes See <example/test/TodoSpec.hs TodoSpec.hs> for an example of a complete test suite for a swagger specification. $serve If you're implementing a server for an API, you might also want to serve its @'OpenApi'@ specification. See <example/src/Todo.hs Todo.hs> for an example of a server.
Module : Servant . OpenApi License : BSD3 Maintainer : < > OpenApi specification for servant APIs . OpenApi is a project used to describe and document RESTful APIs . The OpenApi specification defines a set of files required to describe such an API . These files can then be used by the OpenApi - UI project to display the API and OpenApi - Codegen to generate clients in various languages . For more information see < / OpenApi documentation > . module Servant.OpenApi ( HasOpenApi(..), subOperations, validateEveryToJSON, validateEveryToJSONWithPatternChecker, ) where import Servant.OpenApi.Internal import Servant.OpenApi.Test import Servant.OpenApi.Internal.Orphans () > > > import Control . Applicative > > > import Control . Lens > > > import Data . OpenApi > > > import Data . Typeable > > > import > > > import qualified Data . ByteString . Lazy . Char8 as BSL8 > > > import Servant . OpenApi . Internal . Test > > > data User = User { name : : String , age : : Int } deriving ( Show , Generic , ) > > > newtype UserId = UserId Integer deriving ( Show , Generic , Typeable , ToJSON ) > > > instance ToJSON User > > > instance User > > > instance UserId > > > instance ToParamSchema UserId > > > type = Get ' [ JSON ] [ User ] > > > type Capture " user_id " UserId :> Get ' [ JSON ] User > > > type PostUser = ReqBody ' [ JSON ] User :> Post ' [ JSON ] UserId > > > type UserAPI = GetUsers : < | > GetUser : < | > PostUser This section explains how to use this library to generate OpenApi specification , > > > data User = User { name : : String , age : : Int } deriving ( Show , Generic , ) > > > newtype UserId = UserId Integer deriving ( Show , Generic , Typeable , ToJSON ) > > > instance ToJSON User > > > instance User > > > instance UserId > > > instance ToParamSchema UserId > > > type = Get ' [ JSON ] [ User ] > > > type Capture " user_id " UserId :> Get ' [ JSON ] User > > > type PostUser = ReqBody ' [ JSON ] User :> Post ' [ JSON ] UserId > > > type UserAPI = GetUsers : < | > GetUser : < | > PostUser Here we define a user API with three endpoints . @GetUsers@ endpoint returns a list of all users . In order to generate @'OpenApi'@ specification for a servant API , just use @'toOpenApi'@ : > > > BSL8.putStrLn $ encodePretty $ toOpenApi ( Proxy : : Proxy UserAPI ) " maximum " : 9223372036854775807 , " 200 " : { " 200 " : { " 400 " : { " 200 " : { " 404 " : { By default @'toOpenApi'@ will generate specification for all API routes , parameters , headers , responses and data schemas . For some parameters it will also add 400 and/or 404 responses with a description mentioning parameter name . BSL8.putStrLn $ encodePretty $ toOpenApi ( Proxy : : Proxy UserAPI ) & info.version .~ " 1.0 " & info.license ? ~ " MIT " & servers .~ [ " " ] " maximum " : 9223372036854775807 , " name " : " MIT " " version " : " 1.0 " " 200 " : { " 200 " : { " 400 " : { " 200 " : { " 404 " : { @'subOperations'@ provides a convenient way to zoom into a part of an API . Furthermore , @sub@ is required to be an exact sub API of @api . Otherwise it will not . @"Data . OpenApi . Operation"@ provides some useful helpers that can be used with @'subOperations'@. One example is applying tags to certain endpoints : > > > let subOperations ( Proxy : : Proxy ( GetUsers : < | > GetUser ) ) ( Proxy : : Proxy UserAPI ) > > > let postOps = subOperations ( Proxy : : Proxy PostUser ) ( Proxy : : Proxy UserAPI ) BSL8.putStrLn $ encodePretty $ toOpenApi ( Proxy : : Proxy UserAPI ) & applyTagsFor [ " get " & description ? ~ " GET operations " ] " maximum " : 9223372036854775807 , " 200 " : { " 200 " : { " 400 " : { " 200 " : { " 404 " : { This applies @\"get\"@ tag to the @GET@ endpoints and @\"post\"@ tag to the @POST@ endpoint of the User API . For instance in @UserAPI@ @User@ is always encoded / decoded using @'ToJSON'@ and @'FromJSON'@ instances . To be sure your server / client handles data properly you need to check that @'ToJSON'@ instance always generates values that satisfy schema produced > > > validateEveryToJSON ( Proxy : : Proxy UserAPI ) ... 3 examples , 0 failures ... Although servant is great , chances are that your API clients do n't use . In many cases @swagger.json@ serves as a specification , not a type . under a version control system ( such as , Subversion , Mercurial , etc . ) . to the Haskell API .
c2f2332b3bd780383e731da0c5d92434386dbeeb8a0686bbf7d5b6f52465db8b
tqtezos/minter-sdk
Util.hs
{-# OPTIONS_GHC -Wno-redundant-constraints #-} module Test.Swaps.Util ( originateFA2 , originateWithAdmin , originateSwap , originateAllowlistedSwap , originateAllowlistedBurnSwap , originateAllowlistedFeeSwap , originateChangeBurnAddressSwap , originateOffchainCollections , originateOffchainSwap , originateOffchainSwapBurnFee , originateOffchainCollectionsWithAdmin , originateAllowlistedSwapWithAdmin , originateOffchainSwapWithAdmin , originateAllowlistedBurnSwapWithAdmin , originateChangeBurnAddressSwapWithAdmin , originateOffchainSwapBurnFeeWithAdmin , mkFA2Assets ) where import qualified Lorentz.Contracts.Spec.FA2Interface as FA2 import Lorentz.Value import Morley.Nettest import Lorentz.Contracts.Swaps.Contracts import Lorentz.Contracts.Swaps.Allowlisted import Lorentz.Contracts.Swaps.Basic import Lorentz.Contracts.Swaps.SwapPermit import qualified Lorentz.Contracts.Swaps.AllowlistedFee as AllowlistedFee import Lorentz.Contracts.Swaps.Burn import Lorentz.Contracts.Swaps.Collections import Lorentz.Contracts.Swaps.SwapPermitBurnFee import Test.Util -- | Originate the swaps contract. originateSwap :: MonadNettest caps base m => m (ContractHandler SwapEntrypoints SwapStorage) originateSwap = originateSimple "swaps" initSwapStorage swapsContract -- | Originate the allowlisted swaps contract. originateAllowlistedSwap :: MonadNettest caps base m => Address -> m (ContractHandler AllowlistedSwapEntrypoints AllowlistedSwapStorage) originateAllowlistedSwap admin = originateSimple "swaps" (initAllowlistedSwapStorage admin) allowlistedSwapsContract -- | Originate the allowlisted burn swaps contract. originateAllowlistedBurnSwap :: MonadNettest caps base m => Address -> m (ContractHandler AllowlistedBurnSwapEntrypoints AllowlistedBurnSwapStorage) originateAllowlistedBurnSwap admin = do originateSimple "swaps" (initAllowlistedBurnSwapStorage admin) allowlistedBurnSwapsContract -- | Originate the allowlisted burn swaps contract and admin for it. originateAllowlistedBurnSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler AllowlistedBurnSwapEntrypoints AllowlistedBurnSwapStorage, Address) originateAllowlistedBurnSwapWithAdmin = originateWithAdmin originateAllowlistedBurnSwap -- | Originate the allowlisted burn swaps contract. originateChangeBurnAddressSwap :: MonadNettest caps base m => Address -> m (ContractHandler ChangeBurnAddressSwapEntrypoints AllowlistedBurnSwapStorage) originateChangeBurnAddressSwap admin = do originateSimple "swaps" (initAllowlistedBurnSwapStorage admin) changeBurnAddressSwapsContract -- | Originate the allowlisted burn swaps contract and admin for it. originateChangeBurnAddressSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler ChangeBurnAddressSwapEntrypoints AllowlistedBurnSwapStorage, Address) originateChangeBurnAddressSwapWithAdmin = originateWithAdmin originateChangeBurnAddressSwap -- | Originate the allowlisted burn swaps contract and admin for it. originateOffchainSwapBurnFeeWithAdmin :: MonadNettest caps base m => m (ContractHandler PermitSwapBurnFeeEntrypoints AllowlistedBurnSwapFeeStorage, Address) originateOffchainSwapBurnFeeWithAdmin = originateWithAdmin originateOffchainSwapBurnFee | Originate the allowlisted feeswaps contract with tez fee . originateAllowlistedFeeSwap :: MonadNettest caps base m => Address -> m $ ContractHandler AllowlistedFee.AllowlistedFeeSwapEntrypoints AllowlistedFee.AllowlistedFeeSwapStorage originateAllowlistedFeeSwap admin = do originateSimple "swaps" (AllowlistedFee.initAllowlistedFeeSwapStorage admin) allowlistedFeeSwapsContract -- | Originate the allowlisted swaps contract and admin for it. originateAllowlistedSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler AllowlistedSwapEntrypoints AllowlistedSwapStorage, Address) originateAllowlistedSwapWithAdmin = originateWithAdmin originateAllowlistedSwap -- | Originate the swaps contract with offchain_accept entrypoint. originateOffchainSwap :: MonadNettest caps base m => Address -> m (ContractHandler PermitSwapEntrypoints AllowlistedSwapStorage) originateOffchainSwap admin = do originateSimple "swaps" (initAllowlistedSwapStorage admin) allowlistedSwapsPermitContract -- | Originate the offchain collections contract originateOffchainCollections :: MonadNettest caps base m => Address -> Address -> m (ContractHandler OffchainCollectionsEntrypoints CollectionsStorage) originateOffchainCollections admin fa2 = do originateSimple "swaps" (initCollectionsStorage admin fa2) offchainCollectionsContract -- | Originate the swaps contract with offchain_accept entrypoint. originateOffchainSwapBurnFee :: MonadNettest caps base m => Address -> m (ContractHandler PermitSwapBurnFeeEntrypoints AllowlistedBurnSwapFeeStorage) originateOffchainSwapBurnFee admin = do originateSimple "swaps" (initAllowlistedBurnSwapFeeStorage admin) allowlistedSwapsPermitBurnFeeContract -- | Originate the allowlisted swaps contract and admin for it. originateOffchainSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler PermitSwapEntrypoints AllowlistedSwapStorage, Address) originateOffchainSwapWithAdmin = originateWithAdmin originateOffchainSwap ---- | Originate the offchain collections contract originateOffchainCollectionsWithAdmin : : MonadNettest caps base m = > m ( ContractHandler OffchainCollectionsEntrypoints CollectionsStorage , Address ) originateOffchainCollectionsWithAdmin = -- originateWithAdmin originateOffchainCollections -- | Construct 'FA2Assets' from a simplified representation. mkFA2Assets :: ContractHandler fa2Param fa2Storage -> [(FA2.TokenId, Natural)] -> FA2Assets mkFA2Assets addr tokens = FA2Assets (toAddress addr) (uncurry FA2Token <$> tokens)
null
https://raw.githubusercontent.com/tqtezos/minter-sdk/6239f6ee8435977085c00c194224d4223386841a/packages/minter-contracts/test-hs/Test/Swaps/Util.hs
haskell
# OPTIONS_GHC -Wno-redundant-constraints # | Originate the swaps contract. | Originate the allowlisted swaps contract. | Originate the allowlisted burn swaps contract. | Originate the allowlisted burn swaps contract and admin for it. | Originate the allowlisted burn swaps contract. | Originate the allowlisted burn swaps contract and admin for it. | Originate the allowlisted burn swaps contract and admin for it. | Originate the allowlisted swaps contract and admin for it. | Originate the swaps contract with offchain_accept entrypoint. | Originate the offchain collections contract | Originate the swaps contract with offchain_accept entrypoint. | Originate the allowlisted swaps contract and admin for it. -- | Originate the offchain collections contract originateWithAdmin originateOffchainCollections | Construct 'FA2Assets' from a simplified representation.
module Test.Swaps.Util ( originateFA2 , originateWithAdmin , originateSwap , originateAllowlistedSwap , originateAllowlistedBurnSwap , originateAllowlistedFeeSwap , originateChangeBurnAddressSwap , originateOffchainCollections , originateOffchainSwap , originateOffchainSwapBurnFee , originateOffchainCollectionsWithAdmin , originateAllowlistedSwapWithAdmin , originateOffchainSwapWithAdmin , originateAllowlistedBurnSwapWithAdmin , originateChangeBurnAddressSwapWithAdmin , originateOffchainSwapBurnFeeWithAdmin , mkFA2Assets ) where import qualified Lorentz.Contracts.Spec.FA2Interface as FA2 import Lorentz.Value import Morley.Nettest import Lorentz.Contracts.Swaps.Contracts import Lorentz.Contracts.Swaps.Allowlisted import Lorentz.Contracts.Swaps.Basic import Lorentz.Contracts.Swaps.SwapPermit import qualified Lorentz.Contracts.Swaps.AllowlistedFee as AllowlistedFee import Lorentz.Contracts.Swaps.Burn import Lorentz.Contracts.Swaps.Collections import Lorentz.Contracts.Swaps.SwapPermitBurnFee import Test.Util originateSwap :: MonadNettest caps base m => m (ContractHandler SwapEntrypoints SwapStorage) originateSwap = originateSimple "swaps" initSwapStorage swapsContract originateAllowlistedSwap :: MonadNettest caps base m => Address -> m (ContractHandler AllowlistedSwapEntrypoints AllowlistedSwapStorage) originateAllowlistedSwap admin = originateSimple "swaps" (initAllowlistedSwapStorage admin) allowlistedSwapsContract originateAllowlistedBurnSwap :: MonadNettest caps base m => Address -> m (ContractHandler AllowlistedBurnSwapEntrypoints AllowlistedBurnSwapStorage) originateAllowlistedBurnSwap admin = do originateSimple "swaps" (initAllowlistedBurnSwapStorage admin) allowlistedBurnSwapsContract originateAllowlistedBurnSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler AllowlistedBurnSwapEntrypoints AllowlistedBurnSwapStorage, Address) originateAllowlistedBurnSwapWithAdmin = originateWithAdmin originateAllowlistedBurnSwap originateChangeBurnAddressSwap :: MonadNettest caps base m => Address -> m (ContractHandler ChangeBurnAddressSwapEntrypoints AllowlistedBurnSwapStorage) originateChangeBurnAddressSwap admin = do originateSimple "swaps" (initAllowlistedBurnSwapStorage admin) changeBurnAddressSwapsContract originateChangeBurnAddressSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler ChangeBurnAddressSwapEntrypoints AllowlistedBurnSwapStorage, Address) originateChangeBurnAddressSwapWithAdmin = originateWithAdmin originateChangeBurnAddressSwap originateOffchainSwapBurnFeeWithAdmin :: MonadNettest caps base m => m (ContractHandler PermitSwapBurnFeeEntrypoints AllowlistedBurnSwapFeeStorage, Address) originateOffchainSwapBurnFeeWithAdmin = originateWithAdmin originateOffchainSwapBurnFee | Originate the allowlisted feeswaps contract with tez fee . originateAllowlistedFeeSwap :: MonadNettest caps base m => Address -> m $ ContractHandler AllowlistedFee.AllowlistedFeeSwapEntrypoints AllowlistedFee.AllowlistedFeeSwapStorage originateAllowlistedFeeSwap admin = do originateSimple "swaps" (AllowlistedFee.initAllowlistedFeeSwapStorage admin) allowlistedFeeSwapsContract originateAllowlistedSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler AllowlistedSwapEntrypoints AllowlistedSwapStorage, Address) originateAllowlistedSwapWithAdmin = originateWithAdmin originateAllowlistedSwap originateOffchainSwap :: MonadNettest caps base m => Address -> m (ContractHandler PermitSwapEntrypoints AllowlistedSwapStorage) originateOffchainSwap admin = do originateSimple "swaps" (initAllowlistedSwapStorage admin) allowlistedSwapsPermitContract originateOffchainCollections :: MonadNettest caps base m => Address -> Address -> m (ContractHandler OffchainCollectionsEntrypoints CollectionsStorage) originateOffchainCollections admin fa2 = do originateSimple "swaps" (initCollectionsStorage admin fa2) offchainCollectionsContract originateOffchainSwapBurnFee :: MonadNettest caps base m => Address -> m (ContractHandler PermitSwapBurnFeeEntrypoints AllowlistedBurnSwapFeeStorage) originateOffchainSwapBurnFee admin = do originateSimple "swaps" (initAllowlistedBurnSwapFeeStorage admin) allowlistedSwapsPermitBurnFeeContract originateOffchainSwapWithAdmin :: MonadNettest caps base m => m (ContractHandler PermitSwapEntrypoints AllowlistedSwapStorage, Address) originateOffchainSwapWithAdmin = originateWithAdmin originateOffchainSwap originateOffchainCollectionsWithAdmin : : MonadNettest caps base m = > m ( ContractHandler OffchainCollectionsEntrypoints CollectionsStorage , Address ) originateOffchainCollectionsWithAdmin = mkFA2Assets :: ContractHandler fa2Param fa2Storage -> [(FA2.TokenId, Natural)] -> FA2Assets mkFA2Assets addr tokens = FA2Assets (toAddress addr) (uncurry FA2Token <$> tokens)
d6fa14fc2b02c58d832c76d26710b8acb9a871b43f785817c1758875d6da5aaa
ghcjs/jsaddle-dom
SVGFEDiffuseLightingElement.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGFEDiffuseLightingElement (getIn1, getSurfaceScale, getDiffuseConstant, getKernelUnitLengthX, getKernelUnitLengthY, SVGFEDiffuseLightingElement(..), gTypeSVGFEDiffuseLightingElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGFEDiffuseLightingElement.in1 Mozilla documentation > getIn1 :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedString getIn1 self = liftDOM ((self ^. js "in1") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.surfaceScale Mozilla SVGFEDiffuseLightingElement.surfaceScale documentation > getSurfaceScale :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getSurfaceScale self = liftDOM ((self ^. js "surfaceScale") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.diffuseConstant Mozilla SVGFEDiffuseLightingElement.diffuseConstant documentation > getDiffuseConstant :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getDiffuseConstant self = liftDOM ((self ^. js "diffuseConstant") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.kernelUnitLengthX Mozilla SVGFEDiffuseLightingElement.kernelUnitLengthX documentation > getKernelUnitLengthX :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getKernelUnitLengthX self = liftDOM ((self ^. js "kernelUnitLengthX") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.kernelUnitLengthY Mozilla SVGFEDiffuseLightingElement.kernelUnitLengthY documentation > getKernelUnitLengthY :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getKernelUnitLengthY self = liftDOM ((self ^. js "kernelUnitLengthY") >>= fromJSValUnchecked)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/SVGFEDiffuseLightingElement.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGFEDiffuseLightingElement (getIn1, getSurfaceScale, getDiffuseConstant, getKernelUnitLengthX, getKernelUnitLengthY, SVGFEDiffuseLightingElement(..), gTypeSVGFEDiffuseLightingElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGFEDiffuseLightingElement.in1 Mozilla documentation > getIn1 :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedString getIn1 self = liftDOM ((self ^. js "in1") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.surfaceScale Mozilla SVGFEDiffuseLightingElement.surfaceScale documentation > getSurfaceScale :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getSurfaceScale self = liftDOM ((self ^. js "surfaceScale") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.diffuseConstant Mozilla SVGFEDiffuseLightingElement.diffuseConstant documentation > getDiffuseConstant :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getDiffuseConstant self = liftDOM ((self ^. js "diffuseConstant") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.kernelUnitLengthX Mozilla SVGFEDiffuseLightingElement.kernelUnitLengthX documentation > getKernelUnitLengthX :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getKernelUnitLengthX self = liftDOM ((self ^. js "kernelUnitLengthX") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGFEDiffuseLightingElement.kernelUnitLengthY Mozilla SVGFEDiffuseLightingElement.kernelUnitLengthY documentation > getKernelUnitLengthY :: (MonadDOM m) => SVGFEDiffuseLightingElement -> m SVGAnimatedNumber getKernelUnitLengthY self = liftDOM ((self ^. js "kernelUnitLengthY") >>= fromJSValUnchecked)
3ba06499e9e2ebcf06c45e968ec4444548ce6e0f2743d1dd93eadb14435ed485
containium/containium
mail.clj
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns containium.systems.mail "A mail sending system." (:require [containium.systems :refer (require-system Startable)] [containium.systems.config :as config :refer (Config)] [containium.systems.logging :refer (SystemLogger refer-logging)] [boxure.core :refer (->Boxure) :as boxure] [postal.core :as postal] [clojure.xml :as xml] [clojure.zip :as zip] [clojure.java.io :as io :refer (resource as-file)]) (:import [java.io ByteArrayInputStream FileInputStream BufferedInputStream File] [java.nio.file Files] [java.net URLConnection])) (refer-logging) ;;; The public API (defprotocol Mail (send-message [this from to subject body] [this from to subject body options])) An SMTP implementation using Postal (defrecord Postal [logger box smtp] Mail (send-message [this from to subject body] (send-message this from to subject body nil)) (send-message [this from to subject body opts] (let [from (str from) to (map str (flatten [to]))] (debug logger "Sending email from" from "to" (apply str (interpose ", " to)) "with subject" subject "using options" opts) (boxure/call-in-box box (postal/send-message smtp (merge {:from from, :to to, :subject subject, :body body} opts)))))) (def ^{:doc "This Startable needs a Config system to in the systems. The configuration is read from the :postal key within that config. It should hold the SMTP data as specified by the postal library. The started Postal instance can be used to send e-mail messages. The body can be anything that the postal library supports. The optional `opts` parameter is merged with the send info, such as extra headers."} postal (reify Startable (start [_ systems] (let [config (config/get-config (require-system Config systems) :postal) logger (require-system SystemLogger systems) sysbox (->Boxure "postal" (.getClassLoader clojure.lang.RT) {} (clojure.lang.Var/getThreadBindingFrame))] (info logger "Starting Postal system, using config:" config) (Postal. logger sysbox config))))) (defn- file-content-type [^File file] (with-open [stream (-> file FileInputStream. BufferedInputStream.)] (URLConnection/guessContentTypeFromStream stream))) (defn- make-inline [^String html-str src-root src-map] (let [src-root (str src-root (when-not (= (last src-root) \/) "/"))] (loop [loc (zip/xml-zip (xml/parse (ByteArrayInputStream. (.getBytes (.trim html-str))))) contents []] (if (zip/end? loc) (cons {:type "text/html; charset=utf-8" :content (with-out-str (xml/emit-element (zip/node loc)))} contents) (let [node (zip/node loc)] (if (= :img (:tag node)) (let [cid (str (gensym "img-")) src (-> node :attrs :src) content (as-file (or (get src-map src) (resource (str src-root src)))) content-type (file-content-type content)] (recur (zip/next (zip/edit loc assoc-in [:attrs :src] (str "cid:" cid))) (cond-> contents content (conj {:type :inline, :content content, :content-id cid :content-type content-type, :file-name src})))) (recur (zip/next loc) contents))))))) (defn send-html-message "Use this function to send a HTML mail with the Postal SMTP Mail system. It needs at least the mail system, the from address, the to address, a subject, and the HTML string. The following options are also available: :cc - A single string or a seq of strings with CC addresses. :bcc - A single string or a seq of strings with Blind CC addresses. :text - You can supply a plain text version of the message, which will be included as an alternative. :attachments - You can supply a seq of attachment maps. These maps should at least contain a :content value, and may also contain :content-type and :file-name. :src-root - The root directory/package in which the image resources can be found on the classpath for inlining. Note that due to a limitation in javax.mail/Postal the actual resource must be unpacked, i.e. not in a JAR. :src-map - This is a map holding files for image tags that, taking the 'src' attribute as key, contains resource values for inline use. This map overrides the default lookup when inlining. Note that the values in this map must support being passed to clojure.java.io/file." [mail-system from to subject html & {:keys [cc bcc text attachments src-root src-map]}] (let [html-contents (make-inline html src-root src-map) attachment-contents (doall (map (fn [a] (assoc a :type :attachment)) attachments)) body-contents (if text [:alternative {:type "text/plain" :content text} (cons :related html-contents)] (cons :related html-contents)) contents (if (seq attachment-contents) [:mixed body-contents attachment-contents] body-contents)] (send-message mail-system from to subject contents (merge (when cc {:cc cc}) (when bcc {:bcc bcc})))))
null
https://raw.githubusercontent.com/containium/containium/dede4098de928bed9ce8fccfc0a3891655ee162e/systems/mail/src/containium/systems/mail.clj
clojure
The public API
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns containium.systems.mail "A mail sending system." (:require [containium.systems :refer (require-system Startable)] [containium.systems.config :as config :refer (Config)] [containium.systems.logging :refer (SystemLogger refer-logging)] [boxure.core :refer (->Boxure) :as boxure] [postal.core :as postal] [clojure.xml :as xml] [clojure.zip :as zip] [clojure.java.io :as io :refer (resource as-file)]) (:import [java.io ByteArrayInputStream FileInputStream BufferedInputStream File] [java.nio.file Files] [java.net URLConnection])) (refer-logging) (defprotocol Mail (send-message [this from to subject body] [this from to subject body options])) An SMTP implementation using Postal (defrecord Postal [logger box smtp] Mail (send-message [this from to subject body] (send-message this from to subject body nil)) (send-message [this from to subject body opts] (let [from (str from) to (map str (flatten [to]))] (debug logger "Sending email from" from "to" (apply str (interpose ", " to)) "with subject" subject "using options" opts) (boxure/call-in-box box (postal/send-message smtp (merge {:from from, :to to, :subject subject, :body body} opts)))))) (def ^{:doc "This Startable needs a Config system to in the systems. The configuration is read from the :postal key within that config. It should hold the SMTP data as specified by the postal library. The started Postal instance can be used to send e-mail messages. The body can be anything that the postal library supports. The optional `opts` parameter is merged with the send info, such as extra headers."} postal (reify Startable (start [_ systems] (let [config (config/get-config (require-system Config systems) :postal) logger (require-system SystemLogger systems) sysbox (->Boxure "postal" (.getClassLoader clojure.lang.RT) {} (clojure.lang.Var/getThreadBindingFrame))] (info logger "Starting Postal system, using config:" config) (Postal. logger sysbox config))))) (defn- file-content-type [^File file] (with-open [stream (-> file FileInputStream. BufferedInputStream.)] (URLConnection/guessContentTypeFromStream stream))) (defn- make-inline [^String html-str src-root src-map] (let [src-root (str src-root (when-not (= (last src-root) \/) "/"))] (loop [loc (zip/xml-zip (xml/parse (ByteArrayInputStream. (.getBytes (.trim html-str))))) contents []] (if (zip/end? loc) (cons {:type "text/html; charset=utf-8" :content (with-out-str (xml/emit-element (zip/node loc)))} contents) (let [node (zip/node loc)] (if (= :img (:tag node)) (let [cid (str (gensym "img-")) src (-> node :attrs :src) content (as-file (or (get src-map src) (resource (str src-root src)))) content-type (file-content-type content)] (recur (zip/next (zip/edit loc assoc-in [:attrs :src] (str "cid:" cid))) (cond-> contents content (conj {:type :inline, :content content, :content-id cid :content-type content-type, :file-name src})))) (recur (zip/next loc) contents))))))) (defn send-html-message "Use this function to send a HTML mail with the Postal SMTP Mail system. It needs at least the mail system, the from address, the to address, a subject, and the HTML string. The following options are also available: :cc - A single string or a seq of strings with CC addresses. :bcc - A single string or a seq of strings with Blind CC addresses. :text - You can supply a plain text version of the message, which will be included as an alternative. :attachments - You can supply a seq of attachment maps. These maps should at least contain a :content value, and may also contain :content-type and :file-name. :src-root - The root directory/package in which the image resources can be found on the classpath for inlining. Note that due to a limitation in javax.mail/Postal the actual resource must be unpacked, i.e. not in a JAR. :src-map - This is a map holding files for image tags that, taking the 'src' attribute as key, contains resource values for inline use. This map overrides the default lookup when inlining. Note that the values in this map must support being passed to clojure.java.io/file." [mail-system from to subject html & {:keys [cc bcc text attachments src-root src-map]}] (let [html-contents (make-inline html src-root src-map) attachment-contents (doall (map (fn [a] (assoc a :type :attachment)) attachments)) body-contents (if text [:alternative {:type "text/plain" :content text} (cons :related html-contents)] (cons :related html-contents)) contents (if (seq attachment-contents) [:mixed body-contents attachment-contents] body-contents)] (send-message mail-system from to subject contents (merge (when cc {:cc cc}) (when bcc {:bcc bcc})))))
66dc1d6de88738dc75aa11be781776905b1b975c50e7ddea69b2d8e10f941b16
robert-spurrier/robokit
midi.clj
(ns robokit.midi (:require [overtone.midi.file :as midi]) (:import [javax.sound.midi.spi MidiFileWriter] [javax.sound.midi Sequence Track MidiEvent MidiMessage ShortMessage MetaMessage SysexMessage MidiSystem])) (defn midi-sequences [dir] "Read in a collection of MIDI files and convert into a sequence of Clojure maps representing MIDI objects." (->> (clojure.java.io/resource dir) clojure.java.io/file .listFiles (filter #(.isFile %)) (map (comp midi/midi-file str)))) (defmulti jmidi-message "Turns a Clojure MIDI note event into a Java MIDI Message." :command) (defmethod jmidi-message :note-on [m] (ShortMessage. (ShortMessage/NOTE_ON) (:note m) (:velocity m))) (defmethod jmidi-message :note-off [m] (ShortMessage. (ShortMessage/NOTE_OFF) (:note m) (:velocity m))) (defn jmidi-sequence "Create a Java MIDI Sequence." [resolution tracks] (Sequence. (Sequence/PPQ) resolution tracks)) (defn jmidi-track "Create a Java MIDI Track." [sequence] (.createTrack sequence)) (defn add-track-event [track message tick] (doto track (.add (MidiEvent. message (long tick))))) (defn write-jmidi-file! "Write a Java MIDI Sequence to the filesystem." ([sequence type filename] (let [f (java.io.File. filename)] (MidiSystem/write sequence type f))) ([sequence filename] (write-jmidi-file! sequence 1 filename))) (defn write-midi-sequence! "Convert a Clojure MIDI sequence to Java and save to a MIDI file." [midi-sequence filename] (let [jsequence (jmidi-sequence 96 1) assuming one track for now (doseq [event midi-sequence] (add-track-event jtrack (jmidi-message event) (:timestamp event))) (write-jmidi-file! jsequence filename)))
null
https://raw.githubusercontent.com/robert-spurrier/robokit/ea81cfd37223c0c067e67c405598bc25c594d61d/src/robokit/midi.clj
clojure
(ns robokit.midi (:require [overtone.midi.file :as midi]) (:import [javax.sound.midi.spi MidiFileWriter] [javax.sound.midi Sequence Track MidiEvent MidiMessage ShortMessage MetaMessage SysexMessage MidiSystem])) (defn midi-sequences [dir] "Read in a collection of MIDI files and convert into a sequence of Clojure maps representing MIDI objects." (->> (clojure.java.io/resource dir) clojure.java.io/file .listFiles (filter #(.isFile %)) (map (comp midi/midi-file str)))) (defmulti jmidi-message "Turns a Clojure MIDI note event into a Java MIDI Message." :command) (defmethod jmidi-message :note-on [m] (ShortMessage. (ShortMessage/NOTE_ON) (:note m) (:velocity m))) (defmethod jmidi-message :note-off [m] (ShortMessage. (ShortMessage/NOTE_OFF) (:note m) (:velocity m))) (defn jmidi-sequence "Create a Java MIDI Sequence." [resolution tracks] (Sequence. (Sequence/PPQ) resolution tracks)) (defn jmidi-track "Create a Java MIDI Track." [sequence] (.createTrack sequence)) (defn add-track-event [track message tick] (doto track (.add (MidiEvent. message (long tick))))) (defn write-jmidi-file! "Write a Java MIDI Sequence to the filesystem." ([sequence type filename] (let [f (java.io.File. filename)] (MidiSystem/write sequence type f))) ([sequence filename] (write-jmidi-file! sequence 1 filename))) (defn write-midi-sequence! "Convert a Clojure MIDI sequence to Java and save to a MIDI file." [midi-sequence filename] (let [jsequence (jmidi-sequence 96 1) assuming one track for now (doseq [event midi-sequence] (add-track-event jtrack (jmidi-message event) (:timestamp event))) (write-jmidi-file! jsequence filename)))
49db6be223e747ae3310459ffbe5b022dee7560d24e329a960b6a49f74025a43
stackbuilders/inflections-hs
CamelCase.hs
-- | Module : Text . Inflections . . CamelCase Copyright : © 2016 License : MIT -- Maintainer : < > -- Stability : experimental -- Portability : portable -- Parser for camel case “ symbols ” . # LANGUAGE CPP # # LANGUAGE DataKinds # {-# LANGUAGE OverloadedStrings #-} module Text.Inflections.Parse.CamelCase ( parseCamelCase ) where # if MIN_VERSION_base(4,8,0) import Control.Applicative (empty, many, (<|>)) #else import Control.Applicative (empty, many, (<|>), (<$>), (<*)) #endif import Data.Text (Text) import Data.Void (Void) import Text.Inflections.Types import Text.Megaparsec (Parsec, ParseErrorBundle, choice, eof, parse) import Text.Megaparsec.Char import qualified Data.Text as T #if MIN_VERSION_base(4,8,0) import Prelude hiding (Word) #else import Data.Foldable import Prelude hiding (elem) #endif type Parser = Parsec Void Text | Parse a CamelCase string . -- -- >>> bar <- mkAcronym "bar" -- >>> parseCamelCase [bar] "FooBarBazz" -- Right [Word "Foo",Acronym "Bar",Word "Bazz"] -- -- >>> parseCamelCase [] "foo_bar_bazz" 1:4 : -- unexpected '_' -- expecting end of input, lowercase letter, or uppercase letter parseCamelCase :: (Foldable f, Functor f) => f (Word 'Acronym) -- ^ Collection of acronyms -> Text -- ^ Input -> Either (ParseErrorBundle Text Void) [SomeWord] -- ^ Result of parsing parseCamelCase acronyms = parse (parser acronyms) "" parser :: (Foldable f, Functor f) => f (Word 'Acronym) -- ^ Collection of acronyms ^ CamelCase parser parser acronyms = many (a <|> n) <* eof where n = SomeWord <$> word a = SomeWord <$> acronym acronyms acronym :: (Foldable f, Functor f) => f (Word 'Acronym) -> Parser (Word 'Acronym) acronym acronyms = do x <- choice (string . unWord <$> acronyms) case mkAcronym x of Nothing -> empty -- cannot happen if the system is sound Just acr -> return acr # INLINE acronym # word :: Parser (Word 'Normal) word = do firstChar <- upperChar <|> lowerChar restChars <- many $ lowerChar <|> digitChar case (mkWord . T.pack) (firstChar : restChars) of Nothing -> empty -- cannot happen if the system is sound Just wrd -> return wrd # INLINE word #
null
https://raw.githubusercontent.com/stackbuilders/inflections-hs/5f731cba9bc03cc128f7f4aa8486b09eafe2786d/Text/Inflections/Parse/CamelCase.hs
haskell
| Stability : experimental Portability : portable # LANGUAGE OverloadedStrings # >>> bar <- mkAcronym "bar" >>> parseCamelCase [bar] "FooBarBazz" Right [Word "Foo",Acronym "Bar",Word "Bazz"] >>> parseCamelCase [] "foo_bar_bazz" unexpected '_' expecting end of input, lowercase letter, or uppercase letter ^ Collection of acronyms ^ Input ^ Result of parsing ^ Collection of acronyms cannot happen if the system is sound cannot happen if the system is sound
Module : Text . Inflections . . CamelCase Copyright : © 2016 License : MIT Maintainer : < > Parser for camel case “ symbols ” . # LANGUAGE CPP # # LANGUAGE DataKinds # module Text.Inflections.Parse.CamelCase ( parseCamelCase ) where # if MIN_VERSION_base(4,8,0) import Control.Applicative (empty, many, (<|>)) #else import Control.Applicative (empty, many, (<|>), (<$>), (<*)) #endif import Data.Text (Text) import Data.Void (Void) import Text.Inflections.Types import Text.Megaparsec (Parsec, ParseErrorBundle, choice, eof, parse) import Text.Megaparsec.Char import qualified Data.Text as T #if MIN_VERSION_base(4,8,0) import Prelude hiding (Word) #else import Data.Foldable import Prelude hiding (elem) #endif type Parser = Parsec Void Text | Parse a CamelCase string . 1:4 : parseCamelCase :: (Foldable f, Functor f) parseCamelCase acronyms = parse (parser acronyms) "" parser :: (Foldable f, Functor f) ^ CamelCase parser parser acronyms = many (a <|> n) <* eof where n = SomeWord <$> word a = SomeWord <$> acronym acronyms acronym :: (Foldable f, Functor f) => f (Word 'Acronym) -> Parser (Word 'Acronym) acronym acronyms = do x <- choice (string . unWord <$> acronyms) case mkAcronym x of Just acr -> return acr # INLINE acronym # word :: Parser (Word 'Normal) word = do firstChar <- upperChar <|> lowerChar restChars <- many $ lowerChar <|> digitChar case (mkWord . T.pack) (firstChar : restChars) of Just wrd -> return wrd # INLINE word #
58e3d6d3126a820ca80b806bccf7e8b0fd574a0f52b39981def517d3df778e65
LPCIC/matita
boxPp.ml
Copyright ( C ) 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) $ I d : boxPp.ml 11188 2011 - 01 - 27 14:58:12Z sacerdot $ module Pres = Mpresentation * { 2 Pretty printing from to strings } let utf8_string_length s = Utf8.compute_len s 0 (String.length s) let string_space = " " let string_space_len = utf8_string_length string_space let string_indent = (* string_space *) [],"" let string_indent_len = utf8_string_length (snd string_indent) let string_ink = "---------------------------" let string_ink_len = utf8_string_length string_ink let contains_attrs contained container = List.for_all (fun attr -> List.mem attr container) contained let want_indent = contains_attrs (RenderingAttrs.indent_attributes `BoxML) let want_spacing = contains_attrs (RenderingAttrs.spacing_attributes `BoxML) let shift off = List.map (fun (start,stop,v) -> start+off,stop+off,v);; let (^^) (map1,s1) (map2,s2) = map1 @ (shift (utf8_string_length s1) map2), s1 ^ s2;; CSC : inefficient ( quadratic ) implementation let mapped_string_concat sep = let sep_len = utf8_string_length sep in let rec aux off = function [] -> [],"" | [map,s] -> shift off map,s | (map,s)::tl -> let map = shift off map in let map2,s2 = aux (off + utf8_string_length s + sep_len) tl in map@map2, s ^ sep ^ s2 in aux 0 ;; let indent_string s = string_indent ^^ s let indent_children (size, children) = let children' = List.map indent_string children in size + string_space_len, children' let choose_rendering size (best, other) = let best_size, _ = best in if size >= best_size then best else other merge_columns [ X1 ; X3 ] returns X1 X2 X4 X2 X3 X4 X2 X4 X2 X3 X4 *) let merge_columns sep cols = let sep_len = utf8_string_length sep in let indent = ref 0 in let res_rows = ref [] in let add_row ~continue row = match !res_rows with | last :: prev when continue -> res_rows := (last ^^ ([],sep) ^^ row) :: prev; indent := !indent + utf8_string_length (snd last) + sep_len | _ -> res_rows := (([],String.make !indent ' ') ^^ row) :: !res_rows; in List.iter (fun rows -> match rows with | hd :: tl -> add_row ~continue:true hd; List.iter (add_row ~continue:false) tl | [] -> ()) cols; List.rev !res_rows let max_len = List.fold_left (fun max_size (_,s) -> max (utf8_string_length s) max_size) 0 let render_row available_space spacing children = let spacing_bonus = if spacing then string_space_len else 0 in let rem_space = ref available_space in let renderings = ref [] in List.iter (fun f -> let occupied_space, rendering = f !rem_space in renderings := rendering :: !renderings; rem_space := !rem_space - (occupied_space + spacing_bonus)) children; let sep = if spacing then string_space else "" in let rendering = merge_columns sep (List.rev !renderings) in max_len rendering, rendering let fixed_rendering href s = let s_len = utf8_string_length s in let map = match href with None -> [] | Some href -> [0,s_len-1,href] in (fun _ -> s_len, [map,s]) let render_to_strings ~map_unicode_to_tex choose_action size markup = let max_size = max_int in let rec aux_box = function | Box.Text (_, t) -> fixed_rendering None t | Box.Space _ -> fixed_rendering None string_space | Box.Ink _ -> fixed_rendering None string_ink | Box.Action (_, []) -> assert false | Box.Action (_, l) -> aux_box (choose_action l) | Box.Object (_, o) -> aux_mpres o | Box.H (attrs, children) -> let spacing = want_spacing attrs in let children' = List.map aux_box children in (fun size -> render_row size spacing children') | Box.HV (attrs, children) -> let spacing = want_spacing attrs in let children' = List.map aux_box children in (fun size -> let (size', renderings) as res = render_row max_size spacing children' in if size' <= size then (* children fit in a row *) res else (* break needed, re-render using a Box.V *) aux_box (Box.V (attrs, children)) size) | Box.V (attrs, []) -> assert false | Box.V (attrs, [child]) -> aux_box child | Box.V (attrs, hd :: tl) -> let indent = want_indent attrs in let hd_f = aux_box hd in let tl_fs = List.map aux_box tl in (fun size -> let _, hd_rendering = hd_f size in let children_size = max 0 (if indent then size - string_indent_len else size) in let tl_renderings = List.map (fun f -> (* let indent_header = if indent then string_indent else "" in *) snd (indent_children (f children_size))) tl_fs in let rows = hd_rendering @ List.concat tl_renderings in max_len rows, rows) | Box.HOV (attrs, []) -> assert false | Box.HOV (attrs, [child]) -> aux_box child | Box.HOV (attrs, children) -> let spacing = want_spacing attrs in let indent = want_indent attrs in let spacing_bonus = if spacing then string_space_len else 0 in let indent_bonus = if indent then string_indent_len else 0 in let sep = if spacing then string_space else "" in let fs = List.map aux_box children in (fun size -> let rows = ref [] in let renderings = ref [] in let rem_space = ref size in let first_row = ref true in let use_rendering (space, rendering) = let use_indent = !renderings = [] && not !first_row in let rendering' = if use_indent then List.map indent_string rendering else rendering in renderings := rendering' :: !renderings; let bonus = if use_indent then indent_bonus else spacing_bonus in rem_space := !rem_space - (space + bonus) in let end_cluster () = let new_rows = merge_columns sep (List.rev !renderings) in rows := List.rev_append new_rows !rows; rem_space := size - indent_bonus; renderings := []; first_row := false in List.iter (fun f -> let (best_space, _) as best = f max_size in if best_space <= !rem_space then use_rendering best else begin end_cluster (); if best_space <= !rem_space then use_rendering best else use_rendering (f size) end) fs; if !renderings <> [] then end_cluster (); max_len !rows, List.rev !rows) and aux_mpres = let text s = Pres.Mtext ([], s) in let mrow c = Pres.Mrow ([], c) in let parentesize s = s in function x -> let attrs = Pres.get_attr x in let href = try let _,_,href = List.find (fun (ns,na,value) -> ns = Some "xlink" && na = "href") attrs in Some href with Not_found -> None in match x with | Pres.Mi (_, s) | Pres.Mn (_, s) | Pres.Mtext (_, s) | Pres.Ms (_, s) | Pres.Mgliph (_, s) -> fixed_rendering href s | Pres.Mo (_, s) -> let s = if map_unicode_to_tex then begin if utf8_string_length s = 1 && Char.code s.[0] < 128 then s else match Utf8Macro.tex_of_unicode s with | s::_ -> s ^ " " | [] -> " " ^ s ^ " " end else s in fixed_rendering href s | Pres.Mspace _ -> fixed_rendering href string_space | Pres.Mrow (attrs, children) -> let children' = List.map aux_mpres children in (fun size -> render_row size false children') | Pres.Mfrac (_, m, n) -> aux_mpres (mrow [ text " \\frac "; parentesize m ; text " "; parentesize n; text " " ]) | Pres.Msqrt (_, m) -> aux_mpres (mrow [ text " \\sqrt "; parentesize m; text " "]) | Pres.Mroot (_, r, i) -> aux_mpres (mrow [ text " \\root "; parentesize i; text " \\of "; parentesize r; text " " ]) | Pres.Mstyle (_, m) | Pres.Merror (_, m) | Pres.Mpadded (_, m) | Pres.Mphantom (_, m) | Pres.Menclose (_, m) -> aux_mpres m | Pres.Mfenced (_, children) -> aux_mpres (mrow children) | Pres.Maction (_, []) -> assert false | Pres.Msub (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\sub "; parentesize n; text " " ]) | Pres.Msup (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\sup "; parentesize n; text " " ]) | Pres.Munder (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\below "; parentesize n; text " " ]) | Pres.Mover (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\above "; parentesize n; text " " ]) | Pres.Msubsup _ | Pres.Munderover _ | Pres.Mtable _ -> prerr_endline "MathML presentation element not yet available in concrete syntax"; assert false | Pres.Maction (_, hd :: _) -> aux_mpres hd | Pres.Mobject (_, o) -> aux_box (o: CicNotationPres.boxml_markup) in snd (aux_mpres markup size) let render_to_string ~map_unicode_to_tex choose_action size markup = mapped_string_concat "\n" (render_to_strings ~map_unicode_to_tex choose_action size markup)
null
https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/content_pres/boxPp.ml
ocaml
string_space children fit in a row break needed, re-render using a Box.V let indent_header = if indent then string_indent else "" in
Copyright ( C ) 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) $ I d : boxPp.ml 11188 2011 - 01 - 27 14:58:12Z sacerdot $ module Pres = Mpresentation * { 2 Pretty printing from to strings } let utf8_string_length s = Utf8.compute_len s 0 (String.length s) let string_space = " " let string_space_len = utf8_string_length string_space let string_indent_len = utf8_string_length (snd string_indent) let string_ink = "---------------------------" let string_ink_len = utf8_string_length string_ink let contains_attrs contained container = List.for_all (fun attr -> List.mem attr container) contained let want_indent = contains_attrs (RenderingAttrs.indent_attributes `BoxML) let want_spacing = contains_attrs (RenderingAttrs.spacing_attributes `BoxML) let shift off = List.map (fun (start,stop,v) -> start+off,stop+off,v);; let (^^) (map1,s1) (map2,s2) = map1 @ (shift (utf8_string_length s1) map2), s1 ^ s2;; CSC : inefficient ( quadratic ) implementation let mapped_string_concat sep = let sep_len = utf8_string_length sep in let rec aux off = function [] -> [],"" | [map,s] -> shift off map,s | (map,s)::tl -> let map = shift off map in let map2,s2 = aux (off + utf8_string_length s + sep_len) tl in map@map2, s ^ sep ^ s2 in aux 0 ;; let indent_string s = string_indent ^^ s let indent_children (size, children) = let children' = List.map indent_string children in size + string_space_len, children' let choose_rendering size (best, other) = let best_size, _ = best in if size >= best_size then best else other merge_columns [ X1 ; X3 ] returns X1 X2 X4 X2 X3 X4 X2 X4 X2 X3 X4 *) let merge_columns sep cols = let sep_len = utf8_string_length sep in let indent = ref 0 in let res_rows = ref [] in let add_row ~continue row = match !res_rows with | last :: prev when continue -> res_rows := (last ^^ ([],sep) ^^ row) :: prev; indent := !indent + utf8_string_length (snd last) + sep_len | _ -> res_rows := (([],String.make !indent ' ') ^^ row) :: !res_rows; in List.iter (fun rows -> match rows with | hd :: tl -> add_row ~continue:true hd; List.iter (add_row ~continue:false) tl | [] -> ()) cols; List.rev !res_rows let max_len = List.fold_left (fun max_size (_,s) -> max (utf8_string_length s) max_size) 0 let render_row available_space spacing children = let spacing_bonus = if spacing then string_space_len else 0 in let rem_space = ref available_space in let renderings = ref [] in List.iter (fun f -> let occupied_space, rendering = f !rem_space in renderings := rendering :: !renderings; rem_space := !rem_space - (occupied_space + spacing_bonus)) children; let sep = if spacing then string_space else "" in let rendering = merge_columns sep (List.rev !renderings) in max_len rendering, rendering let fixed_rendering href s = let s_len = utf8_string_length s in let map = match href with None -> [] | Some href -> [0,s_len-1,href] in (fun _ -> s_len, [map,s]) let render_to_strings ~map_unicode_to_tex choose_action size markup = let max_size = max_int in let rec aux_box = function | Box.Text (_, t) -> fixed_rendering None t | Box.Space _ -> fixed_rendering None string_space | Box.Ink _ -> fixed_rendering None string_ink | Box.Action (_, []) -> assert false | Box.Action (_, l) -> aux_box (choose_action l) | Box.Object (_, o) -> aux_mpres o | Box.H (attrs, children) -> let spacing = want_spacing attrs in let children' = List.map aux_box children in (fun size -> render_row size spacing children') | Box.HV (attrs, children) -> let spacing = want_spacing attrs in let children' = List.map aux_box children in (fun size -> let (size', renderings) as res = render_row max_size spacing children' in res aux_box (Box.V (attrs, children)) size) | Box.V (attrs, []) -> assert false | Box.V (attrs, [child]) -> aux_box child | Box.V (attrs, hd :: tl) -> let indent = want_indent attrs in let hd_f = aux_box hd in let tl_fs = List.map aux_box tl in (fun size -> let _, hd_rendering = hd_f size in let children_size = max 0 (if indent then size - string_indent_len else size) in let tl_renderings = List.map (fun f -> snd (indent_children (f children_size))) tl_fs in let rows = hd_rendering @ List.concat tl_renderings in max_len rows, rows) | Box.HOV (attrs, []) -> assert false | Box.HOV (attrs, [child]) -> aux_box child | Box.HOV (attrs, children) -> let spacing = want_spacing attrs in let indent = want_indent attrs in let spacing_bonus = if spacing then string_space_len else 0 in let indent_bonus = if indent then string_indent_len else 0 in let sep = if spacing then string_space else "" in let fs = List.map aux_box children in (fun size -> let rows = ref [] in let renderings = ref [] in let rem_space = ref size in let first_row = ref true in let use_rendering (space, rendering) = let use_indent = !renderings = [] && not !first_row in let rendering' = if use_indent then List.map indent_string rendering else rendering in renderings := rendering' :: !renderings; let bonus = if use_indent then indent_bonus else spacing_bonus in rem_space := !rem_space - (space + bonus) in let end_cluster () = let new_rows = merge_columns sep (List.rev !renderings) in rows := List.rev_append new_rows !rows; rem_space := size - indent_bonus; renderings := []; first_row := false in List.iter (fun f -> let (best_space, _) as best = f max_size in if best_space <= !rem_space then use_rendering best else begin end_cluster (); if best_space <= !rem_space then use_rendering best else use_rendering (f size) end) fs; if !renderings <> [] then end_cluster (); max_len !rows, List.rev !rows) and aux_mpres = let text s = Pres.Mtext ([], s) in let mrow c = Pres.Mrow ([], c) in let parentesize s = s in function x -> let attrs = Pres.get_attr x in let href = try let _,_,href = List.find (fun (ns,na,value) -> ns = Some "xlink" && na = "href") attrs in Some href with Not_found -> None in match x with | Pres.Mi (_, s) | Pres.Mn (_, s) | Pres.Mtext (_, s) | Pres.Ms (_, s) | Pres.Mgliph (_, s) -> fixed_rendering href s | Pres.Mo (_, s) -> let s = if map_unicode_to_tex then begin if utf8_string_length s = 1 && Char.code s.[0] < 128 then s else match Utf8Macro.tex_of_unicode s with | s::_ -> s ^ " " | [] -> " " ^ s ^ " " end else s in fixed_rendering href s | Pres.Mspace _ -> fixed_rendering href string_space | Pres.Mrow (attrs, children) -> let children' = List.map aux_mpres children in (fun size -> render_row size false children') | Pres.Mfrac (_, m, n) -> aux_mpres (mrow [ text " \\frac "; parentesize m ; text " "; parentesize n; text " " ]) | Pres.Msqrt (_, m) -> aux_mpres (mrow [ text " \\sqrt "; parentesize m; text " "]) | Pres.Mroot (_, r, i) -> aux_mpres (mrow [ text " \\root "; parentesize i; text " \\of "; parentesize r; text " " ]) | Pres.Mstyle (_, m) | Pres.Merror (_, m) | Pres.Mpadded (_, m) | Pres.Mphantom (_, m) | Pres.Menclose (_, m) -> aux_mpres m | Pres.Mfenced (_, children) -> aux_mpres (mrow children) | Pres.Maction (_, []) -> assert false | Pres.Msub (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\sub "; parentesize n; text " " ]) | Pres.Msup (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\sup "; parentesize n; text " " ]) | Pres.Munder (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\below "; parentesize n; text " " ]) | Pres.Mover (_, m, n) -> aux_mpres (mrow [ text " "; parentesize m; text " \\above "; parentesize n; text " " ]) | Pres.Msubsup _ | Pres.Munderover _ | Pres.Mtable _ -> prerr_endline "MathML presentation element not yet available in concrete syntax"; assert false | Pres.Maction (_, hd :: _) -> aux_mpres hd | Pres.Mobject (_, o) -> aux_box (o: CicNotationPres.boxml_markup) in snd (aux_mpres markup size) let render_to_string ~map_unicode_to_tex choose_action size markup = mapped_string_concat "\n" (render_to_strings ~map_unicode_to_tex choose_action size markup)
754be4173757a61d81c4d1fd80037518916b2b719aa5aec99968e8a3df6253aa
mitsuchi/mud
TypeEval.hs
-- 型評価 module TypeEval where import Control.Monad (forM_) import Control.Monad.Except import Data.Char import Data.IORef import Data.List (find, intercalate) import Data.Map ((!?)) import qualified Data.Map as Map hiding (foldr, take) import Data.Maybe import Debug.Trace import Env import EvalUtil import Expr import Primitive import RecList import TypeUtil 与えられた環境で、式の型を評価する typeEval :: Expr -> Env -> IOThrowsError (RecList Type) typeEval (IntLit i) env = pure $ Elem "Int" typeEval (StrLit s) env = pure $ Elem "String" typeEval (BoolLit b) env = pure $ Elem "Bool" typeEval (DoubleLit b) env = pure $ Elem "Double" typeEval (Var "True" _) env = pure $ Elem "Bool" typeEval (Var "False" _) env = pure $ Elem "Bool" typeEval (TypeSig sig _) env = pure sig typeEval (TypeLit types) env = pure types typeEval (Fun sig _ _ _) env = pure sig typeEval (ListLit [] _) env = pure $ Elems [Elem "List", Elem "t0"] -- リストの型は、要素すべてと同じ型。ひとつでも違う型があるとエラー。 typeEval (ListLit es c) env = do es' <- mapM (`typeEval` env) es if allTheSame es' then pure $ Elems [Elem "List", head es'] else throwError $ show (lineOfCode c) ++ ":type mismatch. list can't contain different type of elements." typeEval (StructValue s) env = case s !? "type" of Just (StrLit str) -> pure $ Elem str Nothing -> error "type not defined in struct value" typeEval (Seq [e]) env = typeEval e env -- 複式の型は最後の式の型なので、途中が違う型でもいい typeEval (Seq (e:es)) env = do typeEval e env typeEval (Seq es) env typeEval (Neg expr) env = typeEval expr env typeEval (Assign (Var name code) fun@(Fun types params expr outerEnv)) env = do res <- liftIO $ insertFun name types fun env case res of Left message -> throwError $ show (lineOfCode code) ++ ":" ++ message Right env -> pure types typeEval (Assign (Var name code) (TypeLit type')) env = do res <- liftIO $ insertVar name (TypeLit type') env case res of Left message -> throwError $ show (lineOfCode code) ++ ":" ++ message Right env -> pure type' typeEval (Var name c) env = do var <- liftIO $ lookupVarLoose name env env' <- liftIO $ readIORef env case var of Nothing -> throwError (show (lineOfCode c) ++ ":variable '" ++ name ++ "' not found.") Just (TypeLit x) -> pure x Just (Fun types _ _ _) -> pure types otherwise -> throwError $ show var typeEval (BinOp Eq _ v e) env = do t' <- typeEval e env typeEval (Assign v (TypeLit t')) env typeEval (BinOp Dot _ e1 var@(Var name code)) env = typeEval (Apply var [e1]) env typeEval (BinOp Dot _ e1 fun@(Fun types params expr outerEnv)) env = typeEval (Apply fun [e1]) env typeEval (BinOp Dot _ e1 (Apply expr args)) env = typeEval (Apply expr (e1 : args)) env typeEval (BinOp Dot _ e1 e2) env = typeEval (Apply e2 [e1]) env typeEval (BinOp (OpLit lit) code e1 e2) env = typeEval (Apply (Var lit code) [e1, e2]) env typeEval (BinOp op code e1 e2) env = do e1' <- typeEval e1 env e2' <- typeEval e2 env typeEval (BinOp op code (TypeLit e1') (TypeLit e2')) env typeEval (Apply (Var name code) args) env = do args' <- mapM (`typeEval` env) args fun' <- liftIO $ lookupFun name (Elems args') env False types <- case fun' of Just (Fun types _ _ _) -> pure types Just (Call name types) -> pure types Just (TypeLit types) -> pure types _ -> throwError $ show (lineOfCode code) ++ ":type mismatch. function '" ++ name ++ " : " ++ intercalate " -> " (map rArrow args') ++ " -> ?' not found" let ts = generalizeTypesWith "t" types let xs = generalizeTypesWith "x" (Elems args') case unify (rInit ts) xs mempty of Nothing -> throwError $ show (lineOfCode code) ++ "ts:" ++ show ts ++ ",xs:" ++ show xs ++ ":fugafuga type mismatch. function '" ++ name ++ " : " ++ intercalate " -> " (rArrow <$> args') ++ " -> ?' not found." Just typeEnv -> let env1 = (`typeInst` typeEnv) <$> typeEnv in pure $ typeInst (rLast ts) $ Map.mapWithKey (\k e -> cancelXs k e env1) env1 typeEval (Apply (TypeLit types) args) env = do args' <- mapM (`typeEval` env) args let ts = generalizeTypesWith "t" types xs = generalizeTypesWith "x" (Elems args') case unify (rInit ts) xs mempty of Nothing -> throwError $ "type mismatch. function has type : " ++ argSig types ++ ", but actual args are : " ++ intercalate " -> " (map rArrow args') Just typeEnv -> let env1 = (`typeInst` typeEnv) <$> typeEnv in pure $ typeInst (rLast ts) $ Map.mapWithKey (\k e -> cancelXs k e env1) env1 typeEval (Apply expr args) env = do expr' <- typeEval expr env typeEval (Apply (TypeLit expr') args) env typeEval (If condExpr thenExpr elseExpr code) env = do cond' <- typeEval condExpr env then' <- typeEval thenExpr env else' <- typeEval elseExpr env if cond' == Elem "Bool" then if then' == else' then pure then' else throwError $ show (lineOfCode code) ++ ": type mismatch. then-part has a type '" ++ rArrow then' ++ "', else-part has '" ++ rArrow else' ++ "'. they must be the same." else throwError $ show (lineOfCode code) ++ ": type mismatch. condition-part has a type '" ++ rArrow cond' ++ "'. must be 'Bool'." typeEval (FunDef nameExpr@(Var name code) types params body) env = do -- 本体の型が返り値の型と一致する必要がある varMap <- liftIO $ readIORef env env' <- liftIO $ newEnv params (map TypeLit (rArgs (generalizeTypes types))) varMap -- 関数が再帰的に定義される可能性があるので、いま定義しようとしてる関数を先に型環境に登録しちゃう res <- liftIO $ insertFun name types (Fun types params body env) env' body' <- typeEval body env' case unify types (rAppend (rInit types) (Elems [body'])) mempty of Just env0 -> typeEval (Assign nameExpr (Fun types params body env)) env Nothing -> throwError $ show (lineOfCode code) ++ ": type mismatch. function supposed to pure '" ++ rArrow (rLast types) ++ "', but actually pures '" ++ rArrow body' ++ "'" typeEval (FunDefAnon types params body code) env = do -- 本体の型が返り値の型と一致する必要がある varMap <- liftIO $ readIORef env env' <- liftIO $ newEnv params (map TypeLit (rArgs (generalizeTypes types))) varMap varMap' <- liftIO $ readIORef env' body' <- typeEval body env' case unify types (rAppend (rInit types) (Elems [body'])) mempty of Just env0 -> pure $ generalizeTypes types Nothing -> throwError $ show (lineOfCode code) ++ ": type mismatch. function supposed to pure '" ++ rArrow (rLast types) ++ "', but actually pures '" ++ rArrow body' ++ "'" typeEval (Case es [(args, body, guard, code)] (Elems types')) env = do (Elems types) <- pure $ generalizeTypes (Elems types') (bool, typeEnv) <- liftIO $ matchCondType (init types) args guard mempty env bodyType <- typeEvalMatchExprBody body typeEnv env case unify (last types) bodyType typeEnv of Just env0 -> pure $ last types Nothing -> throwError $ show (lineOfCode code) ++ ": type mismatch. function supposed to pure '" ++ rArrow (last types) ++ "', but actually pures '" ++ rArrow bodyType ++ "'" typeEval (Case es (expr:matchExprs) (Elems types')) env = do typeEval (Case es [expr] (Elems types')) env typeEval (Case es matchExprs (Elems types')) env typeEval (TypeDef (Var name code) typeDef) env = do forM_ typeDef $ \(member, Elems [typeList]) -> typeEval (FunDef (Var member code) (Elems [Elem name, typeList]) ["x"] (TypeLit typeList)) env typeEval (FunDef (Var name code) types params (TypeLit (rLast types))) env where types = typeDefToTypes typeDef name params = map fst typeDef typeEval e env = trace ("runtime error: typeEval failed. " ++ show e) $ pure (Elem "") -- プリミティブな環境で、与えられた式の型を評価する typeEvalWithPrimitiveEnv :: Expr -> IOThrowsError Expr typeEvalWithPrimitiveEnv expr = do env <- liftIO $ newIORef mempty liftIO $ insertPrimitives env expr' <- typeEval expr env pure $ TypeLit expr' -- 与えられた環境をコピーして新しい環境をつくり、その下で与えられた式の型を評価する -- もとの環境に影響を与えないように typeEvalWithEnv :: Expr -> Env -> IOThrowsError Expr typeEvalWithEnv expr env = do varMap <- liftIO $ readIORef env env' <- liftIO $ newIORef (fmap (\(types, expr) -> (types, (TypeLit . typeOf') expr)) <$> varMap) liftIO $ insertPrimitives env' expr' <- typeEval expr env' pure $ TypeLit expr' -- 型環境 typeEnv と env のもとで body を評価する typeEvalMatchExprBody :: Expr -> Map.Map String (RecList Type) -> Env -> IOThrowsError (RecList Type) typeEvalMatchExprBody body typeEnv env = do varMap' <- liftIO $ readIORef env env' <- liftIO $ newIORef varMap' res <- liftIO $ mapM_ (\(name, types) -> insertAny (name, TypeLit types) env') (Map.toList typeEnv) typeEval body env' リストの要素がすべて同一か ? allTheSame :: (Eq a) => [a] -> Bool allTheSame [] = True allTheSame [e] = True allTheSame (e:es) = e == head es && allTheSame es -- マッチ式の引数の列が、与えられた型の列(マッチ式を含む関数の型)とマッチするか? matchCondType :: [RecList Type] -> [Expr] -> Maybe Expr -> Map.Map String (RecList Type) -> Env -> IO (Bool, Map.Map String (RecList Type)) matchCondType (e1:e1s) (Var v _:e2s) guard varMap env = -- マッチ式に変数がくる場合:変数に対する型の既存の割り当てと矛盾しなければマッチ case varMap !? v of Nothing -> matchCondType e1s e2s guard (Map.insert v e1 varMap) env Just types -> if types == e1 then matchCondType e1s e2s guard varMap env else pure (False, mempty) matchCondType (listType@(Elems [Elem "List", Elem a]):e1s) (ListLit [Var e _, Var es _] _:e2s) guard varMap env = do -- マッチ式にリスト([e;es])がくる場合 -- 対応する引数の型もリストであることが必要 それを [ a ] とすると、e : a , es:[a ] を型環境に割り当てる let vmap1 = Map.insert e (Elem a) varMap vmap2 = Map.insert es listType vmap1 matchCondType e1s e2s guard vmap2 env matchCondType (e1:e1s) (e2:e2s) guard varMap env = -- 一般の場合:型としてマッチすればOK (Int vs Int, a vs String など) case unify e1 (typeOf' e2) varMap of Just varMap' -> matchCondType e1s e2s guard varMap' env Nothing -> pure (False, mempty) matchCondType [] [] guard varMap env = case guard of Nothing -> pure (True, varMap) Just guard' -> do -- もしガード節があれば、現状の型環境の下でガード節の型がBoolになることが必要 varMap' <- liftIO $ readIORef env env' <- newIORef varMap' mapM_ (\(name, types) -> insertAny (name, TypeLit types) env') (Map.toList varMap) guardBodyType <- runExceptT (typeEval guard' env') case guardBodyType of Right val -> if val == Elem "Bool" then pure (True, varMap) else pure (False, mempty) Left error -> trace error $ pure (False, mempty) matchCondType e1 e2 _ varMap env = trace ("matchCondType: " ++ show (e1,e2)) $ pure (False, mempty) -- 型もしくは型変数を、型環境を元にインスタンス化する typeInst :: RecList Type -> Map.Map String (RecList Type) -> RecList Type typeInst (Elem a) env | isUpper (head a) = Elem a | isLower (head a) = fromMaybe (Elem a) $ env !? a typeInst (Elems es) env = Elems ((`typeInst` env) <$> es) -- 型環境において、キーとなる型変数の値が型変数だった場合、値をキー自身で上書きする cancelXs :: String -> RecList Type -> Map.Map String (RecList Type) -> RecList Type cancelXs key value env | isConcrete value = value --cancelXs key value env | hasVariable value = Elem key cancelXs key value env | hasVariable value = renameType value [ x0 ] - > x1 を [ t0 ] - > t1 に変更する renameType :: RecList Type -> RecList Type renameType (Elem ('x':xs)) = Elem ('t':xs) renameType (Elem xs) = Elem xs renameType (Elems es) = Elems (map renameType es)
null
https://raw.githubusercontent.com/mitsuchi/mud/48c08a2847b6f3efcef598806682da7efca2449d/src/TypeEval.hs
haskell
型評価 リストの型は、要素すべてと同じ型。ひとつでも違う型があるとエラー。 複式の型は最後の式の型なので、途中が違う型でもいい 本体の型が返り値の型と一致する必要がある 関数が再帰的に定義される可能性があるので、いま定義しようとしてる関数を先に型環境に登録しちゃう 本体の型が返り値の型と一致する必要がある プリミティブな環境で、与えられた式の型を評価する 与えられた環境をコピーして新しい環境をつくり、その下で与えられた式の型を評価する もとの環境に影響を与えないように 型環境 typeEnv と env のもとで body を評価する マッチ式の引数の列が、与えられた型の列(マッチ式を含む関数の型)とマッチするか? マッチ式に変数がくる場合:変数に対する型の既存の割り当てと矛盾しなければマッチ マッチ式にリスト([e;es])がくる場合 対応する引数の型もリストであることが必要 一般の場合:型としてマッチすればOK (Int vs Int, a vs String など) もしガード節があれば、現状の型環境の下でガード節の型がBoolになることが必要 型もしくは型変数を、型環境を元にインスタンス化する 型環境において、キーとなる型変数の値が型変数だった場合、値をキー自身で上書きする cancelXs key value env | hasVariable value = Elem key
module TypeEval where import Control.Monad (forM_) import Control.Monad.Except import Data.Char import Data.IORef import Data.List (find, intercalate) import Data.Map ((!?)) import qualified Data.Map as Map hiding (foldr, take) import Data.Maybe import Debug.Trace import Env import EvalUtil import Expr import Primitive import RecList import TypeUtil 与えられた環境で、式の型を評価する typeEval :: Expr -> Env -> IOThrowsError (RecList Type) typeEval (IntLit i) env = pure $ Elem "Int" typeEval (StrLit s) env = pure $ Elem "String" typeEval (BoolLit b) env = pure $ Elem "Bool" typeEval (DoubleLit b) env = pure $ Elem "Double" typeEval (Var "True" _) env = pure $ Elem "Bool" typeEval (Var "False" _) env = pure $ Elem "Bool" typeEval (TypeSig sig _) env = pure sig typeEval (TypeLit types) env = pure types typeEval (Fun sig _ _ _) env = pure sig typeEval (ListLit [] _) env = pure $ Elems [Elem "List", Elem "t0"] typeEval (ListLit es c) env = do es' <- mapM (`typeEval` env) es if allTheSame es' then pure $ Elems [Elem "List", head es'] else throwError $ show (lineOfCode c) ++ ":type mismatch. list can't contain different type of elements." typeEval (StructValue s) env = case s !? "type" of Just (StrLit str) -> pure $ Elem str Nothing -> error "type not defined in struct value" typeEval (Seq [e]) env = typeEval e env typeEval (Seq (e:es)) env = do typeEval e env typeEval (Seq es) env typeEval (Neg expr) env = typeEval expr env typeEval (Assign (Var name code) fun@(Fun types params expr outerEnv)) env = do res <- liftIO $ insertFun name types fun env case res of Left message -> throwError $ show (lineOfCode code) ++ ":" ++ message Right env -> pure types typeEval (Assign (Var name code) (TypeLit type')) env = do res <- liftIO $ insertVar name (TypeLit type') env case res of Left message -> throwError $ show (lineOfCode code) ++ ":" ++ message Right env -> pure type' typeEval (Var name c) env = do var <- liftIO $ lookupVarLoose name env env' <- liftIO $ readIORef env case var of Nothing -> throwError (show (lineOfCode c) ++ ":variable '" ++ name ++ "' not found.") Just (TypeLit x) -> pure x Just (Fun types _ _ _) -> pure types otherwise -> throwError $ show var typeEval (BinOp Eq _ v e) env = do t' <- typeEval e env typeEval (Assign v (TypeLit t')) env typeEval (BinOp Dot _ e1 var@(Var name code)) env = typeEval (Apply var [e1]) env typeEval (BinOp Dot _ e1 fun@(Fun types params expr outerEnv)) env = typeEval (Apply fun [e1]) env typeEval (BinOp Dot _ e1 (Apply expr args)) env = typeEval (Apply expr (e1 : args)) env typeEval (BinOp Dot _ e1 e2) env = typeEval (Apply e2 [e1]) env typeEval (BinOp (OpLit lit) code e1 e2) env = typeEval (Apply (Var lit code) [e1, e2]) env typeEval (BinOp op code e1 e2) env = do e1' <- typeEval e1 env e2' <- typeEval e2 env typeEval (BinOp op code (TypeLit e1') (TypeLit e2')) env typeEval (Apply (Var name code) args) env = do args' <- mapM (`typeEval` env) args fun' <- liftIO $ lookupFun name (Elems args') env False types <- case fun' of Just (Fun types _ _ _) -> pure types Just (Call name types) -> pure types Just (TypeLit types) -> pure types _ -> throwError $ show (lineOfCode code) ++ ":type mismatch. function '" ++ name ++ " : " ++ intercalate " -> " (map rArrow args') ++ " -> ?' not found" let ts = generalizeTypesWith "t" types let xs = generalizeTypesWith "x" (Elems args') case unify (rInit ts) xs mempty of Nothing -> throwError $ show (lineOfCode code) ++ "ts:" ++ show ts ++ ",xs:" ++ show xs ++ ":fugafuga type mismatch. function '" ++ name ++ " : " ++ intercalate " -> " (rArrow <$> args') ++ " -> ?' not found." Just typeEnv -> let env1 = (`typeInst` typeEnv) <$> typeEnv in pure $ typeInst (rLast ts) $ Map.mapWithKey (\k e -> cancelXs k e env1) env1 typeEval (Apply (TypeLit types) args) env = do args' <- mapM (`typeEval` env) args let ts = generalizeTypesWith "t" types xs = generalizeTypesWith "x" (Elems args') case unify (rInit ts) xs mempty of Nothing -> throwError $ "type mismatch. function has type : " ++ argSig types ++ ", but actual args are : " ++ intercalate " -> " (map rArrow args') Just typeEnv -> let env1 = (`typeInst` typeEnv) <$> typeEnv in pure $ typeInst (rLast ts) $ Map.mapWithKey (\k e -> cancelXs k e env1) env1 typeEval (Apply expr args) env = do expr' <- typeEval expr env typeEval (Apply (TypeLit expr') args) env typeEval (If condExpr thenExpr elseExpr code) env = do cond' <- typeEval condExpr env then' <- typeEval thenExpr env else' <- typeEval elseExpr env if cond' == Elem "Bool" then if then' == else' then pure then' else throwError $ show (lineOfCode code) ++ ": type mismatch. then-part has a type '" ++ rArrow then' ++ "', else-part has '" ++ rArrow else' ++ "'. they must be the same." else throwError $ show (lineOfCode code) ++ ": type mismatch. condition-part has a type '" ++ rArrow cond' ++ "'. must be 'Bool'." typeEval (FunDef nameExpr@(Var name code) types params body) env = do varMap <- liftIO $ readIORef env env' <- liftIO $ newEnv params (map TypeLit (rArgs (generalizeTypes types))) varMap res <- liftIO $ insertFun name types (Fun types params body env) env' body' <- typeEval body env' case unify types (rAppend (rInit types) (Elems [body'])) mempty of Just env0 -> typeEval (Assign nameExpr (Fun types params body env)) env Nothing -> throwError $ show (lineOfCode code) ++ ": type mismatch. function supposed to pure '" ++ rArrow (rLast types) ++ "', but actually pures '" ++ rArrow body' ++ "'" typeEval (FunDefAnon types params body code) env = do varMap <- liftIO $ readIORef env env' <- liftIO $ newEnv params (map TypeLit (rArgs (generalizeTypes types))) varMap varMap' <- liftIO $ readIORef env' body' <- typeEval body env' case unify types (rAppend (rInit types) (Elems [body'])) mempty of Just env0 -> pure $ generalizeTypes types Nothing -> throwError $ show (lineOfCode code) ++ ": type mismatch. function supposed to pure '" ++ rArrow (rLast types) ++ "', but actually pures '" ++ rArrow body' ++ "'" typeEval (Case es [(args, body, guard, code)] (Elems types')) env = do (Elems types) <- pure $ generalizeTypes (Elems types') (bool, typeEnv) <- liftIO $ matchCondType (init types) args guard mempty env bodyType <- typeEvalMatchExprBody body typeEnv env case unify (last types) bodyType typeEnv of Just env0 -> pure $ last types Nothing -> throwError $ show (lineOfCode code) ++ ": type mismatch. function supposed to pure '" ++ rArrow (last types) ++ "', but actually pures '" ++ rArrow bodyType ++ "'" typeEval (Case es (expr:matchExprs) (Elems types')) env = do typeEval (Case es [expr] (Elems types')) env typeEval (Case es matchExprs (Elems types')) env typeEval (TypeDef (Var name code) typeDef) env = do forM_ typeDef $ \(member, Elems [typeList]) -> typeEval (FunDef (Var member code) (Elems [Elem name, typeList]) ["x"] (TypeLit typeList)) env typeEval (FunDef (Var name code) types params (TypeLit (rLast types))) env where types = typeDefToTypes typeDef name params = map fst typeDef typeEval e env = trace ("runtime error: typeEval failed. " ++ show e) $ pure (Elem "") typeEvalWithPrimitiveEnv :: Expr -> IOThrowsError Expr typeEvalWithPrimitiveEnv expr = do env <- liftIO $ newIORef mempty liftIO $ insertPrimitives env expr' <- typeEval expr env pure $ TypeLit expr' typeEvalWithEnv :: Expr -> Env -> IOThrowsError Expr typeEvalWithEnv expr env = do varMap <- liftIO $ readIORef env env' <- liftIO $ newIORef (fmap (\(types, expr) -> (types, (TypeLit . typeOf') expr)) <$> varMap) liftIO $ insertPrimitives env' expr' <- typeEval expr env' pure $ TypeLit expr' typeEvalMatchExprBody :: Expr -> Map.Map String (RecList Type) -> Env -> IOThrowsError (RecList Type) typeEvalMatchExprBody body typeEnv env = do varMap' <- liftIO $ readIORef env env' <- liftIO $ newIORef varMap' res <- liftIO $ mapM_ (\(name, types) -> insertAny (name, TypeLit types) env') (Map.toList typeEnv) typeEval body env' リストの要素がすべて同一か ? allTheSame :: (Eq a) => [a] -> Bool allTheSame [] = True allTheSame [e] = True allTheSame (e:es) = e == head es && allTheSame es matchCondType :: [RecList Type] -> [Expr] -> Maybe Expr -> Map.Map String (RecList Type) -> Env -> IO (Bool, Map.Map String (RecList Type)) matchCondType (e1:e1s) (Var v _:e2s) guard varMap env = case varMap !? v of Nothing -> matchCondType e1s e2s guard (Map.insert v e1 varMap) env Just types -> if types == e1 then matchCondType e1s e2s guard varMap env else pure (False, mempty) matchCondType (listType@(Elems [Elem "List", Elem a]):e1s) (ListLit [Var e _, Var es _] _:e2s) guard varMap env = do それを [ a ] とすると、e : a , es:[a ] を型環境に割り当てる let vmap1 = Map.insert e (Elem a) varMap vmap2 = Map.insert es listType vmap1 matchCondType e1s e2s guard vmap2 env matchCondType (e1:e1s) (e2:e2s) guard varMap env = case unify e1 (typeOf' e2) varMap of Just varMap' -> matchCondType e1s e2s guard varMap' env Nothing -> pure (False, mempty) matchCondType [] [] guard varMap env = case guard of Nothing -> pure (True, varMap) Just guard' -> do varMap' <- liftIO $ readIORef env env' <- newIORef varMap' mapM_ (\(name, types) -> insertAny (name, TypeLit types) env') (Map.toList varMap) guardBodyType <- runExceptT (typeEval guard' env') case guardBodyType of Right val -> if val == Elem "Bool" then pure (True, varMap) else pure (False, mempty) Left error -> trace error $ pure (False, mempty) matchCondType e1 e2 _ varMap env = trace ("matchCondType: " ++ show (e1,e2)) $ pure (False, mempty) typeInst :: RecList Type -> Map.Map String (RecList Type) -> RecList Type typeInst (Elem a) env | isUpper (head a) = Elem a | isLower (head a) = fromMaybe (Elem a) $ env !? a typeInst (Elems es) env = Elems ((`typeInst` env) <$> es) cancelXs :: String -> RecList Type -> Map.Map String (RecList Type) -> RecList Type cancelXs key value env | isConcrete value = value cancelXs key value env | hasVariable value = renameType value [ x0 ] - > x1 を [ t0 ] - > t1 に変更する renameType :: RecList Type -> RecList Type renameType (Elem ('x':xs)) = Elem ('t':xs) renameType (Elem xs) = Elem xs renameType (Elems es) = Elems (map renameType es)
b4f661d45115d6516c75a0b8571fe79e6ec921419fb2e64d5bce1ca03ca4f711
RefactoringTools/HaRe
D2a.hs
module Demote.D2a where --demote 'sumSquares' should fail as it used by module 'A2'. sumSquares (x:xs) = sq x + sumSquares xs sumSquares [] = 0 sq x = x ^pow pow = 2 main = sumSquares [1..4]
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/Demote/D2a.hs
haskell
demote 'sumSquares' should fail as it used by module 'A2'.
module Demote.D2a where sumSquares (x:xs) = sq x + sumSquares xs sumSquares [] = 0 sq x = x ^pow pow = 2 main = sumSquares [1..4]
4561b60969f07d680c6b11faa36718f4aa0cfb0e511b6f55fe99d0c7c30ac412
haskell-webgear/webgear
Body.hs
# OPTIONS_GHC -Wno - deprecations # module Properties.Trait.Body ( tests, ) where import Control.Monad.IO.Class (MonadIO, liftIO) import Data.IORef (newIORef, readIORef, writeIORef) import Data.String (fromString) import Network.Wai (defaultRequest, requestBody) import Test.QuickCheck (Property, allProperties, counterexample, property) import Test.QuickCheck.Instances () import Test.QuickCheck.Monadic (assert, monadicIO, monitor) import Test.Tasty (TestTree) import Test.Tasty.QuickCheck (testProperties) import WebGear.Core.Request (Request (..)) import WebGear.Core.Trait (Linked, getTrait, linkzero) import WebGear.Core.Trait.Body (JSONBody (..)) import WebGear.Server.Handler (runServerHandler) import WebGear.Server.Trait.Body () jsonBody :: JSONBody t jsonBody = JSONBody (Just "application/json") bodyToRequest :: (MonadIO m, Show a) => a -> m (Linked '[] Request) bodyToRequest x = do body <- liftIO $ newIORef $ Just $ fromString $ show x let f = readIORef body >>= maybe (pure "") (\s -> writeIORef body Nothing >> pure s) return $ linkzero $ Request $ defaultRequest{requestBody = f} prop_emptyRequestBodyFails :: Property prop_emptyRequestBodyFails = monadicIO $ do req <- bodyToRequest ("" :: String) runServerHandler (getTrait (jsonBody :: JSONBody Int)) [""] req >>= \case Right (Left _) -> assert True e -> monitor (counterexample $ "Unexpected " <> show e) >> assert False prop_validBodyParses :: Property prop_validBodyParses = property $ \n -> monadicIO $ do req <- bodyToRequest (n :: Integer) runServerHandler (getTrait jsonBody) [""] req >>= \case Right (Right n') -> assert (n == n') _ -> assert False prop_invalidBodyTypeFails :: Property prop_invalidBodyTypeFails = property $ \n -> monadicIO $ do req <- bodyToRequest (n :: Integer) runServerHandler (getTrait (jsonBody :: JSONBody String)) [""] req >>= \case Right (Left _) -> assert True _ -> assert False Hack for TH splicing return [] tests :: TestTree tests = testProperties "Trait.Body" $allProperties
null
https://raw.githubusercontent.com/haskell-webgear/webgear/60e5547f9450aac36727e8d9980e0a8cbdb69660/webgear-server/test/Properties/Trait/Body.hs
haskell
# OPTIONS_GHC -Wno - deprecations # module Properties.Trait.Body ( tests, ) where import Control.Monad.IO.Class (MonadIO, liftIO) import Data.IORef (newIORef, readIORef, writeIORef) import Data.String (fromString) import Network.Wai (defaultRequest, requestBody) import Test.QuickCheck (Property, allProperties, counterexample, property) import Test.QuickCheck.Instances () import Test.QuickCheck.Monadic (assert, monadicIO, monitor) import Test.Tasty (TestTree) import Test.Tasty.QuickCheck (testProperties) import WebGear.Core.Request (Request (..)) import WebGear.Core.Trait (Linked, getTrait, linkzero) import WebGear.Core.Trait.Body (JSONBody (..)) import WebGear.Server.Handler (runServerHandler) import WebGear.Server.Trait.Body () jsonBody :: JSONBody t jsonBody = JSONBody (Just "application/json") bodyToRequest :: (MonadIO m, Show a) => a -> m (Linked '[] Request) bodyToRequest x = do body <- liftIO $ newIORef $ Just $ fromString $ show x let f = readIORef body >>= maybe (pure "") (\s -> writeIORef body Nothing >> pure s) return $ linkzero $ Request $ defaultRequest{requestBody = f} prop_emptyRequestBodyFails :: Property prop_emptyRequestBodyFails = monadicIO $ do req <- bodyToRequest ("" :: String) runServerHandler (getTrait (jsonBody :: JSONBody Int)) [""] req >>= \case Right (Left _) -> assert True e -> monitor (counterexample $ "Unexpected " <> show e) >> assert False prop_validBodyParses :: Property prop_validBodyParses = property $ \n -> monadicIO $ do req <- bodyToRequest (n :: Integer) runServerHandler (getTrait jsonBody) [""] req >>= \case Right (Right n') -> assert (n == n') _ -> assert False prop_invalidBodyTypeFails :: Property prop_invalidBodyTypeFails = property $ \n -> monadicIO $ do req <- bodyToRequest (n :: Integer) runServerHandler (getTrait (jsonBody :: JSONBody String)) [""] req >>= \case Right (Left _) -> assert True _ -> assert False Hack for TH splicing return [] tests :: TestTree tests = testProperties "Trait.Body" $allProperties
284aa92dfb382fc5dc819485509497e48b6140b23d485af9ad3c3c78af9db38c
onyx-platform/onyx-benchmark
bench_plugin_test.clj
(ns onyx.plugin.bench-plugin-test (:require [clojure.core.async :refer [chan dropping-buffer put! >! <! <!! go >!!]] [taoensso.timbre :refer [info warn trace fatal] :as timbre] [onyx.peer.pipeline-extensions :as p-ext] [onyx.plugin.bench-plugin] [onyx.static.logging-configuration :as log-config] [onyx.plugin.core-async] [onyx.lifecycle.metrics.timbre] [onyx.lifecycle.metrics.metrics] [onyx.monitoring.events :as monitoring] [onyx.test-helper :refer [load-config]] [interval-metrics.core :as im] [onyx.api]) #_(:import [onyx.plugin RandomInputPlugin])) (def id (java.util.UUID/randomUUID)) (def scheduler :onyx.job-scheduler/balanced) (def id (java.util.UUID/randomUUID)) (def config (load-config)) (def env-config (assoc (:env-config config) :onyx/tenancy-id id)) (def peer-config (assoc (:peer-config config) :onyx/tenancy-id id)) (def env (onyx.api/start-env env-config)) (def peer-group (onyx.api/start-peer-group peer-config)) (def batch-size 20) (def batch-timeout 10) (defn my-inc [{:keys [n] :as segment}] (assoc segment :n (inc n))) (def catalog [{:onyx/name :in :onyx/plugin :onyx.plugin.bench-plugin/generator :onyx/type :input :onyx/medium :generator :benchmark/segment-generator :hundred-bytes :onyx/max-pending 10000 :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc1 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc2 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc3 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc4 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :no-op :onyx/plugin :onyx.plugin.core-async/output :onyx/type :output :onyx/max-peers 1 :onyx/medium :core.async :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size :onyx/doc "Drops messages on the floor"}]) (def workflow [[:in :inc1] [:inc1 :inc2] [:inc2 :inc3] [:inc3 :inc4] [:inc4 :no-op]]) (println "Starting Vpeers") (let [host-id (str "thishost") m-cfg (monitoring/monitoring-config host-id 10000) monitoring-thread (onyx.lifecycle.metrics.timbre/timbre-sender {} (:monitoring/ch m-cfg)) v-peers (onyx.api/start-peers 6 peer-group m-cfg)] (println "Started vpeers") (def bench-length 120000) (Thread/sleep 10000) (def in-calls {:lifecycle/before-task-start (fn inject-no-op-ch [event lifecycle] {:core.async/chan (chan (dropping-buffer 1))})}) (def lifecycles [{:lifecycle/task :no-op :lifecycle/calls :onyx.plugin.bench-plugin-test/in-calls} {:lifecycle/task :no-op :lifecycle/calls :onyx.plugin.core-async/writer-calls} {:lifecycle/task :in ; or :task-name for an individual task :lifecycle/calls :onyx.lifecycle.metrics.metrics/calls :metrics/buffer-capacity 10000 :metrics/workflow-name "your-workflow-name" :metrics/sender-fn :onyx.lifecycle.metrics.timbre/timbre-sender :lifecycle/doc "Instruments a task's metrics to timbre"}]) (onyx.api/submit-job peer-config {:catalog catalog :workflow workflow :lifecycles lifecycles :task-scheduler :onyx.task-scheduler/balanced}) (Thread/sleep bench-length) (doseq [v-peer v-peers] (onyx.api/shutdown-peer v-peer)) (onyx.api/shutdown-peer-group peer-group) (onyx.api/shutdown-env env))
null
https://raw.githubusercontent.com/onyx-platform/onyx-benchmark/bad93b27b9d7139330697616b04c31f4f040034b/test/onyx/plugin/bench_plugin_test.clj
clojure
or :task-name for an individual task
(ns onyx.plugin.bench-plugin-test (:require [clojure.core.async :refer [chan dropping-buffer put! >! <! <!! go >!!]] [taoensso.timbre :refer [info warn trace fatal] :as timbre] [onyx.peer.pipeline-extensions :as p-ext] [onyx.plugin.bench-plugin] [onyx.static.logging-configuration :as log-config] [onyx.plugin.core-async] [onyx.lifecycle.metrics.timbre] [onyx.lifecycle.metrics.metrics] [onyx.monitoring.events :as monitoring] [onyx.test-helper :refer [load-config]] [interval-metrics.core :as im] [onyx.api]) #_(:import [onyx.plugin RandomInputPlugin])) (def id (java.util.UUID/randomUUID)) (def scheduler :onyx.job-scheduler/balanced) (def id (java.util.UUID/randomUUID)) (def config (load-config)) (def env-config (assoc (:env-config config) :onyx/tenancy-id id)) (def peer-config (assoc (:peer-config config) :onyx/tenancy-id id)) (def env (onyx.api/start-env env-config)) (def peer-group (onyx.api/start-peer-group peer-config)) (def batch-size 20) (def batch-timeout 10) (defn my-inc [{:keys [n] :as segment}] (assoc segment :n (inc n))) (def catalog [{:onyx/name :in :onyx/plugin :onyx.plugin.bench-plugin/generator :onyx/type :input :onyx/medium :generator :benchmark/segment-generator :hundred-bytes :onyx/max-pending 10000 :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc1 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc2 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc3 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :inc4 :onyx/fn :onyx.plugin.bench-plugin-test/my-inc :onyx/type :function :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size} {:onyx/name :no-op :onyx/plugin :onyx.plugin.core-async/output :onyx/type :output :onyx/max-peers 1 :onyx/medium :core.async :onyx/batch-timeout batch-timeout :onyx/batch-size batch-size :onyx/doc "Drops messages on the floor"}]) (def workflow [[:in :inc1] [:inc1 :inc2] [:inc2 :inc3] [:inc3 :inc4] [:inc4 :no-op]]) (println "Starting Vpeers") (let [host-id (str "thishost") m-cfg (monitoring/monitoring-config host-id 10000) monitoring-thread (onyx.lifecycle.metrics.timbre/timbre-sender {} (:monitoring/ch m-cfg)) v-peers (onyx.api/start-peers 6 peer-group m-cfg)] (println "Started vpeers") (def bench-length 120000) (Thread/sleep 10000) (def in-calls {:lifecycle/before-task-start (fn inject-no-op-ch [event lifecycle] {:core.async/chan (chan (dropping-buffer 1))})}) (def lifecycles [{:lifecycle/task :no-op :lifecycle/calls :onyx.plugin.bench-plugin-test/in-calls} {:lifecycle/task :no-op :lifecycle/calls :onyx.plugin.core-async/writer-calls} :lifecycle/calls :onyx.lifecycle.metrics.metrics/calls :metrics/buffer-capacity 10000 :metrics/workflow-name "your-workflow-name" :metrics/sender-fn :onyx.lifecycle.metrics.timbre/timbre-sender :lifecycle/doc "Instruments a task's metrics to timbre"}]) (onyx.api/submit-job peer-config {:catalog catalog :workflow workflow :lifecycles lifecycles :task-scheduler :onyx.task-scheduler/balanced}) (Thread/sleep bench-length) (doseq [v-peer v-peers] (onyx.api/shutdown-peer v-peer)) (onyx.api/shutdown-peer-group peer-group) (onyx.api/shutdown-env env))
a476874bbcc3f4edfb271cde6956d199b3478de8a4a928a355db7b0e3c8cc7bb
RichiH/git-annex
MatchExpression.hs
git - annex command - - Copyright 2016 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2016 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Command.MatchExpression where import Command import Annex.FileMatcher import Types.FileMatcher import Utility.DataUnits import Utility.Matcher import Annex.UUID import Logs.Group import qualified Data.Map as M import qualified Data.Set as S cmd :: Command cmd = noCommit $ command "matchexpression" SectionPlumbing "checks if a preferred content expression matches" paramExpression (seek <$$> optParser) data MatchExpressionOptions = MatchExpressionOptions { matchexpr :: String , largeFilesExpression :: Bool , matchinfo :: MatchInfo } optParser :: CmdParamsDesc -> Parser MatchExpressionOptions optParser desc = MatchExpressionOptions <$> argument str (metavar desc) <*> switch ( long "largefiles" <> help "parse as annex.largefiles expression" ) <*> (addkeysize <$> dataparser) where dataparser = MatchingInfo <$> optinfo "file" (strOption ( long "file" <> metavar paramFile <> help "specify filename to match against" )) <*> optinfo "key" (option (str >>= parseKey) ( long "key" <> metavar paramKey <> help "specify key to match against" )) <*> optinfo "size" (option (str >>= maybe (fail "parse error") return . readSize dataUnits) ( long "size" <> metavar paramSize <> help "specify size to match against" )) <*> optinfo "mimetype" (strOption ( long "mimetype" <> metavar paramValue <> help "specify mime type to match against" )) optinfo datadesc mk = (Right <$> mk) <|> (pure $ Left $ missingdata datadesc) missingdata datadesc = bail $ "cannot match this expression without " ++ datadesc ++ " data" -- When a key is provided, use its size. addkeysize i@(MatchingInfo f (Right k) _ m) = case keySize k of Just sz -> MatchingInfo f (Right k) (Right sz) m Nothing -> i addkeysize i = i seek :: MatchExpressionOptions -> CommandSeek seek o = do parser <- if largeFilesExpression o then mkLargeFilesParser else preferredContentParser matchAll matchAll groupMap M.empty . Just <$> getUUID case parsedToMatcher $ parser ((matchexpr o)) of Left e -> liftIO $ bail $ "bad expression: " ++ e Right matcher -> ifM (checkmatcher matcher) ( liftIO exitSuccess , liftIO exitFailure ) where checkmatcher matcher = matchMrun matcher $ \a -> a S.empty (matchinfo o) bail :: String -> IO a bail s = do hPutStrLn stderr s exitWith $ ExitFailure 42
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Command/MatchExpression.hs
haskell
When a key is provided, use its size.
git - annex command - - Copyright 2016 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2016 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Command.MatchExpression where import Command import Annex.FileMatcher import Types.FileMatcher import Utility.DataUnits import Utility.Matcher import Annex.UUID import Logs.Group import qualified Data.Map as M import qualified Data.Set as S cmd :: Command cmd = noCommit $ command "matchexpression" SectionPlumbing "checks if a preferred content expression matches" paramExpression (seek <$$> optParser) data MatchExpressionOptions = MatchExpressionOptions { matchexpr :: String , largeFilesExpression :: Bool , matchinfo :: MatchInfo } optParser :: CmdParamsDesc -> Parser MatchExpressionOptions optParser desc = MatchExpressionOptions <$> argument str (metavar desc) <*> switch ( long "largefiles" <> help "parse as annex.largefiles expression" ) <*> (addkeysize <$> dataparser) where dataparser = MatchingInfo <$> optinfo "file" (strOption ( long "file" <> metavar paramFile <> help "specify filename to match against" )) <*> optinfo "key" (option (str >>= parseKey) ( long "key" <> metavar paramKey <> help "specify key to match against" )) <*> optinfo "size" (option (str >>= maybe (fail "parse error") return . readSize dataUnits) ( long "size" <> metavar paramSize <> help "specify size to match against" )) <*> optinfo "mimetype" (strOption ( long "mimetype" <> metavar paramValue <> help "specify mime type to match against" )) optinfo datadesc mk = (Right <$> mk) <|> (pure $ Left $ missingdata datadesc) missingdata datadesc = bail $ "cannot match this expression without " ++ datadesc ++ " data" addkeysize i@(MatchingInfo f (Right k) _ m) = case keySize k of Just sz -> MatchingInfo f (Right k) (Right sz) m Nothing -> i addkeysize i = i seek :: MatchExpressionOptions -> CommandSeek seek o = do parser <- if largeFilesExpression o then mkLargeFilesParser else preferredContentParser matchAll matchAll groupMap M.empty . Just <$> getUUID case parsedToMatcher $ parser ((matchexpr o)) of Left e -> liftIO $ bail $ "bad expression: " ++ e Right matcher -> ifM (checkmatcher matcher) ( liftIO exitSuccess , liftIO exitFailure ) where checkmatcher matcher = matchMrun matcher $ \a -> a S.empty (matchinfo o) bail :: String -> IO a bail s = do hPutStrLn stderr s exitWith $ ExitFailure 42
937e0eef56a544d2ae4c83d1970d62962a0ee59621fc7cc12b8cf27958e7c451
azimut/shiny
molecular.lisp
(in-package :shiny) ;; -------------------------------------------------------------------- ;; The rules for the algorithm are as follows : ;; two different note lengths need to be defined , e.g. " 4 " and " 3 " ;; a scale needs to be defined, e.g. C major (the white keys on a piano), let's say we start on the E note, the list of notes will then contain : E, F, G, A, B, C a pattern length needs to be defined , e.g. 4 bars ;; ;; The algorithm will then function like so (keeping the above definitions in mind) : ;; the first note of the scale ( E ) is played at the length of the first defined note length ( 4 ) each time the duration of the played note has ended , the NEXT note in the scale ( F ) is played once the first pattern length has been reached ( 4 bars ) , a new pattern will start ;; the previously "recorded" pattern will loop its contents indefinitely while the new patterns are created / played if a newly played note sounds simultaneously with another note from a PREVIOUS pattern , the note length will change ( in above example from 4 to 3 ) . this will be the new note length to use for ALL SUBSEQUENT added notes , until another simultaneously played note is found , leading it to switch back to the previous note length ( in above example , back to 4 ) . ;; as the pattern is now played over an existing one, it is likely that notes will be played in unison, leading to the switching of note length ;; as more patterns are accumulated, a perfectly mathematical pattern of notes are weaving in and out of the notes of the other patterns ;; ;; -music-generator ;; -------------------------------------------------------------------- (defvar *mtempos* '()) (defvar *p* '()) (defvar *n* nil) (defun mbox-show () (loop :for i :in (reverse *p*) :for ii :below 100 :do (destructuring-bind (n d c b) i (print (format nil "~5A~10A~10A~10A~A" ii n d c b))))) ;; (defun spattern ()) ;; (defun ppattern ()) (defun spattern (time notes pattern lengths r) "Repeats the given pattern infinitly. You might want to comment the push to *mtempos* once the pattern are all done. Also you can play around by adding a probabily to NOT play the pattern. Instead of just fade away. TIME the (now) time in samples where the sample will begin. NOTES a list midi notes to play PATTERN a list with 0's and 1's that indicate when to play the beat LENGTHS a list of duration in beats a note should play R is the midi channel used." (let ((pbeat (loop :for beat :in pattern :and nbeat :upto 64 :when (= 1 beat) :collect nbeat))) ;; Take the list of beats where a note is played ;; pbeat = '(0 4 8 32) and schedule it (loop :for cbeat :in pbeat :do (push cbeat *mtempos*)) (push (list (next notes 't) (next lengths 't) r pattern) *p*))) ;; I need to use (mod) to get the next beat where there is a note (defun ppattern (time lpattern notes length1 length2 &key (cbeat 0) (ibeat 0) (chan 2) (pchan 0) accumbeats accumnotes accumlengths play pbeat) (if (not (null notes)) (let ((nbeat (+ .5 cbeat)) (nibeat (+ 1 ibeat)) (nchan (if (= 9 (+ 1 chan)) (+ 2 chan) (+ 1 chan))) (npchan (mod (+ pchan 1) 2)) (t-nbeat (+ time .5)) (note (first notes))) ;; play now (if (or (eq play 'yes) (= pbeat ibeat)) (progn (setf notes (cdr notes) pbeat (mod (+ ibeat (* length1 2)) lpattern)) (push note accumnotes) (push 1 accumbeats) (push length1 accumlengths)) (push 0 accumbeats)) reset when the next .5 beat is the last beat of the pattern ;; if not is business as usual and we stick with this pattern (if (= lpattern nibeat) (progn ;; (print "endpattern") (spattern time (new cycle :of (reverse accumnotes) :repeat 1) (reverse accumbeats) (new cycle :of (reverse accumlengths) :repeat 1) chan) ;; This works to match agains the prev NOT the global (if (and (= 1 (first accumbeats)) (= pbeat 0)) (progn (print "endswap") (ppattern time lpattern notes length2 length1 :pbeat pbeat :chan nchan :pchan npchan)) (ppattern time lpattern notes length1 length2 :pbeat pbeat :chan nchan :pchan npchan))) (if (and (= pbeat (mod nibeat lpattern)) (find pbeat *mtempos*)) (progn ;; (print "middle swap") (ppattern time lpattern notes length2 length1 :accumnotes accumnotes :accumbeats accumbeats :accumlengths accumlengths :cbeat nbeat :chan chan :ibeat nibeat :pbeat pbeat)) (progn (ppattern time lpattern notes length1 length2 :accumnotes accumnotes :accumbeats accumbeats :accumlengths accumlengths :cbeat nbeat :chan chan :ibeat nibeat :pbeat pbeat))))))) (defun mbox (time lpattern note length1 length2 bottom up pc &optional startchan) (setf *mtempos* nil) (setf *p* nil) (setf *n* nil) (let* ((midinote (cm:keynum note)) (notes (loop :for x :from bottom :to up :collect (pc-relative midinote x pc))) (notes (rest notes))) (setf *n* notes) (ppattern time lpattern notes length1 length2 :play 'yes) (setf *p* (reverse *p*)))) Macro for common play (defmacro mbox-play (index volume beat-duration note-duration-mul channel) (let ((fname (intern (format nil "~A-~A" 'mplay index))) (fname-loop (intern (format nil "%~A-~A" 'mplay index)))) `(let ((p-volume ,volume) (p-note-duration-mul ,note-duration-mul) (p-beat-duration ,beat-duration) (index ,index) (p-channel ,channel) (p-durations nil)) (defun ,fname-loop (time notes beats durations raw-durations) (let ((beat (next beats))) (when (= 1 beat) (let ((note (next notes)) (duration (next durations))) (p time note p-volume (* duration p-note-duration-mul) p-channel)))) (aat (+ time p-beat-duration) #',fname-loop it notes beats durations raw-durations)) (defun ,fname () (destructuring-bind (notes durations channel beats) (nth index (reverse *p*)) (declare (ignore channel)) (setf p-durations durations) (,fname-loop (quant (* (length (cadddr (first *p*))) ;; length pattern p-beat-duration)) (make-cycle notes) (make-cycle beats) (make-cycle durations) durations)))))) ;; macro for custom play (defmacro mbox-custom (index ;;volume beat-duration note - duration - mul channel &body body) (let ((fname (intern (format nil "~A-~A" 'mplay index))) (fname-loop (intern (format nil "%~A-~A" 'mplay index)))) `(let (;;(p-volume ,volume) ;;(p-note-duration-mul ,note-duration-mul) (p-beat-duration ,beat-duration) (index ,index) ;;(p-channel ,channel) (p-durations nil)) (defun ,fname-loop (time notes beats durations raw-durations) (let ((beat (next beats))) (when (= 1 beat) (let ((note (next notes)) (duration (next durations))) ,@body))) (aat (+ time p-beat-duration) #',fname-loop it notes beats durations raw-durations)) (defun ,fname () (destructuring-bind (notes durations channel beats) (nth index (reverse *p*)) (declare (ignore channel)) (setf p-durations durations) (,fname-loop (quant (* (length (cadddr (first *p*))) ;; length pattern p-beat-duration)) (make-cycle notes) (make-cycle beats) (make-cycle durations) durations)))))) (defun merge-beats (beats &optional merged) "SLIME> (merge-beats '((0 0 0 1) (1 0 0 0))) (1 0 0 1)" (let ((a (car beats)) (b (if merged merged (cadr beats)))) (if (and a b) (merge-beats (cddr beats) (loop :for x :in a :for y :in b :collect (if (or (= x 1) (= y 1)) 1 0))) merged))) (defun get-mbeats (start end) (declare (integer start end)) (merge-beats (mapcar #'cadddr (subseq *p* start end)))) (defun get-mnotes (start end) (declare (integer start end)) (mapcar #'caar (subseq *p* start end)))
null
https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/lib/molecular.lisp
lisp
-------------------------------------------------------------------- The rules for the algorithm are as follows : a scale needs to be defined, e.g. C major (the white keys on a piano), let's say we start on the E note, the list of notes will then contain : E, F, G, A, B, C The algorithm will then function like so (keeping the above definitions in mind) : the previously "recorded" pattern will loop its contents indefinitely while the new patterns are created / played as the pattern is now played over an existing one, it is likely that notes will be played in unison, leading to the switching of note length as more patterns are accumulated, a perfectly mathematical pattern of notes are weaving in and out of the notes of the other patterns -music-generator -------------------------------------------------------------------- (defun spattern ()) (defun ppattern ()) Take the list of beats where a note is played pbeat = '(0 4 8 32) and schedule it I need to use (mod) to get the next beat where there is a note play now if not is business as usual and we stick with this pattern (print "endpattern") This works to match agains the prev NOT the global (print "middle swap") length pattern macro for custom play volume (p-volume ,volume) (p-note-duration-mul ,note-duration-mul) (p-channel ,channel) length pattern
(in-package :shiny) two different note lengths need to be defined , e.g. " 4 " and " 3 " a pattern length needs to be defined , e.g. 4 bars the first note of the scale ( E ) is played at the length of the first defined note length ( 4 ) each time the duration of the played note has ended , the NEXT note in the scale ( F ) is played once the first pattern length has been reached ( 4 bars ) , a new pattern will start if a newly played note sounds simultaneously with another note from a PREVIOUS pattern , the note length will change ( in above example from 4 to 3 ) . this will be the new note length to use for ALL SUBSEQUENT added notes , until another simultaneously played note is found , leading it to switch back to the previous note length ( in above example , back to 4 ) . (defvar *mtempos* '()) (defvar *p* '()) (defvar *n* nil) (defun mbox-show () (loop :for i :in (reverse *p*) :for ii :below 100 :do (destructuring-bind (n d c b) i (print (format nil "~5A~10A~10A~10A~A" ii n d c b))))) (defun spattern (time notes pattern lengths r) "Repeats the given pattern infinitly. You might want to comment the push to *mtempos* once the pattern are all done. Also you can play around by adding a probabily to NOT play the pattern. Instead of just fade away. TIME the (now) time in samples where the sample will begin. NOTES a list midi notes to play PATTERN a list with 0's and 1's that indicate when to play the beat LENGTHS a list of duration in beats a note should play R is the midi channel used." (let ((pbeat (loop :for beat :in pattern :and nbeat :upto 64 :when (= 1 beat) :collect nbeat))) (loop :for cbeat :in pbeat :do (push cbeat *mtempos*)) (push (list (next notes 't) (next lengths 't) r pattern) *p*))) (defun ppattern (time lpattern notes length1 length2 &key (cbeat 0) (ibeat 0) (chan 2) (pchan 0) accumbeats accumnotes accumlengths play pbeat) (if (not (null notes)) (let ((nbeat (+ .5 cbeat)) (nibeat (+ 1 ibeat)) (nchan (if (= 9 (+ 1 chan)) (+ 2 chan) (+ 1 chan))) (npchan (mod (+ pchan 1) 2)) (t-nbeat (+ time .5)) (note (first notes))) (if (or (eq play 'yes) (= pbeat ibeat)) (progn (setf notes (cdr notes) pbeat (mod (+ ibeat (* length1 2)) lpattern)) (push note accumnotes) (push 1 accumbeats) (push length1 accumlengths)) (push 0 accumbeats)) reset when the next .5 beat is the last beat of the pattern (if (= lpattern nibeat) (progn (spattern time (new cycle :of (reverse accumnotes) :repeat 1) (reverse accumbeats) (new cycle :of (reverse accumlengths) :repeat 1) chan) (if (and (= 1 (first accumbeats)) (= pbeat 0)) (progn (print "endswap") (ppattern time lpattern notes length2 length1 :pbeat pbeat :chan nchan :pchan npchan)) (ppattern time lpattern notes length1 length2 :pbeat pbeat :chan nchan :pchan npchan))) (if (and (= pbeat (mod nibeat lpattern)) (find pbeat *mtempos*)) (progn (ppattern time lpattern notes length2 length1 :accumnotes accumnotes :accumbeats accumbeats :accumlengths accumlengths :cbeat nbeat :chan chan :ibeat nibeat :pbeat pbeat)) (progn (ppattern time lpattern notes length1 length2 :accumnotes accumnotes :accumbeats accumbeats :accumlengths accumlengths :cbeat nbeat :chan chan :ibeat nibeat :pbeat pbeat))))))) (defun mbox (time lpattern note length1 length2 bottom up pc &optional startchan) (setf *mtempos* nil) (setf *p* nil) (setf *n* nil) (let* ((midinote (cm:keynum note)) (notes (loop :for x :from bottom :to up :collect (pc-relative midinote x pc))) (notes (rest notes))) (setf *n* notes) (ppattern time lpattern notes length1 length2 :play 'yes) (setf *p* (reverse *p*)))) Macro for common play (defmacro mbox-play (index volume beat-duration note-duration-mul channel) (let ((fname (intern (format nil "~A-~A" 'mplay index))) (fname-loop (intern (format nil "%~A-~A" 'mplay index)))) `(let ((p-volume ,volume) (p-note-duration-mul ,note-duration-mul) (p-beat-duration ,beat-duration) (index ,index) (p-channel ,channel) (p-durations nil)) (defun ,fname-loop (time notes beats durations raw-durations) (let ((beat (next beats))) (when (= 1 beat) (let ((note (next notes)) (duration (next durations))) (p time note p-volume (* duration p-note-duration-mul) p-channel)))) (aat (+ time p-beat-duration) #',fname-loop it notes beats durations raw-durations)) (defun ,fname () (destructuring-bind (notes durations channel beats) (nth index (reverse *p*)) (declare (ignore channel)) (setf p-durations durations) p-beat-duration)) (make-cycle notes) (make-cycle beats) (make-cycle durations) durations)))))) (defmacro mbox-custom (index beat-duration note - duration - mul channel &body body) (let ((fname (intern (format nil "~A-~A" 'mplay index))) (fname-loop (intern (format nil "%~A-~A" 'mplay index)))) (p-beat-duration ,beat-duration) (index ,index) (p-durations nil)) (defun ,fname-loop (time notes beats durations raw-durations) (let ((beat (next beats))) (when (= 1 beat) (let ((note (next notes)) (duration (next durations))) ,@body))) (aat (+ time p-beat-duration) #',fname-loop it notes beats durations raw-durations)) (defun ,fname () (destructuring-bind (notes durations channel beats) (nth index (reverse *p*)) (declare (ignore channel)) (setf p-durations durations) p-beat-duration)) (make-cycle notes) (make-cycle beats) (make-cycle durations) durations)))))) (defun merge-beats (beats &optional merged) "SLIME> (merge-beats '((0 0 0 1) (1 0 0 0))) (1 0 0 1)" (let ((a (car beats)) (b (if merged merged (cadr beats)))) (if (and a b) (merge-beats (cddr beats) (loop :for x :in a :for y :in b :collect (if (or (= x 1) (= y 1)) 1 0))) merged))) (defun get-mbeats (start end) (declare (integer start end)) (merge-beats (mapcar #'cadddr (subseq *p* start end)))) (defun get-mnotes (start end) (declare (integer start end)) (mapcar #'caar (subseq *p* start end)))
f28b4cc627d4753f456e9026346b6a058cfc2ff3f651f05412f655096e6b5b84
HealthSamurai/stresty
storage.cljc
(ns zframes.storage (:require [zframes.re-frame :as zrf])) #?(:clj (def local-storage (atom {}))) (zrf/reg-cofx :storage/get (fn [coeffects k] (assoc-in coeffects [:storage k] #?(:clj (get @local-storage k) :cljs (try (some-> (js/window.localStorage.getItem (str k)) (js/decodeURIComponent) (js/JSON.parse) (js->clj :keywordize-keys true)) (catch :default _ nil)))))) (zrf/defe :storage/set [items] (doseq [[k v] items] #?(:clj (swap! local-storage assoc k v) :cljs (js/window.localStorage.setItem (str k) (-> (clj->js v) (js/JSON.stringify) (js/encodeURIComponent)))))) (zrf/defe :storage/remove [keys] (doseq [k keys] #?(:clj (swap! local-storage dissoc k) :cljs (js/window.localStorage.removeItem (str key)))))
null
https://raw.githubusercontent.com/HealthSamurai/stresty/130cedde6bf53e07fe25a6b0b13b8bf70846f15a/src-ui/zframes/storage.cljc
clojure
(ns zframes.storage (:require [zframes.re-frame :as zrf])) #?(:clj (def local-storage (atom {}))) (zrf/reg-cofx :storage/get (fn [coeffects k] (assoc-in coeffects [:storage k] #?(:clj (get @local-storage k) :cljs (try (some-> (js/window.localStorage.getItem (str k)) (js/decodeURIComponent) (js/JSON.parse) (js->clj :keywordize-keys true)) (catch :default _ nil)))))) (zrf/defe :storage/set [items] (doseq [[k v] items] #?(:clj (swap! local-storage assoc k v) :cljs (js/window.localStorage.setItem (str k) (-> (clj->js v) (js/JSON.stringify) (js/encodeURIComponent)))))) (zrf/defe :storage/remove [keys] (doseq [k keys] #?(:clj (swap! local-storage dissoc k) :cljs (js/window.localStorage.removeItem (str key)))))
0287c6454ccbd691cde7252d8d8db07190f5ecc637ab3010d0c5602e7d3286e0
janestreet/krb
principal.mli
open! Core open Async open Import * A principal is a unique identity to which can assign tickets . Generally , principals are a name ( containing an arbitrary number of components separated by ' / ' ) followed by " > " . The [ Krb ] library allows for two kinds of principals : User : < username>@<REALM > Service : < service>/<hostname>.<domain>@<REALM > See [ Config ] for information on how to configure < REALM > and < domain > . For a more complete explanation , see the MIT krb5 documentation : -1.5/krb5-1.5.4/doc/krb5-user/What-is-a-Kerberos-Principal_003f.html principals are a name (containing an arbitrary number of components separated by '/') followed by "@<REALM>". The [Krb] library allows for two kinds of principals: User: <username>@<REALM> Service: <service>/<hostname>.<domain>@<REALM> See [Config] for information on how to configure <REALM> and <domain>. For a more complete explanation, see the MIT krb5 documentation: -1.5/krb5-1.5.4/doc/krb5-user/What-is-a-Kerberos-Principal_003f.html *) type t = Internal.Principal.t module Name : sig * A [ Name.t ] represents the conventional names that may appear in a Kerberos principal ( i.e. the bit before " @REALM " ) . By default , when constructing a principal from this type , we assume that the principal is within the default realm configured in [ krb.conf ] . If realm information should be preserved ( eg . within cross - realm environments ) , use [ Cross_realm_principal_name.t ] instead . principal (i.e. the bit before "@REALM"). By default, when constructing a principal from this type, we assume that the principal is within the default realm configured in [krb.conf]. If realm information should be preserved (eg. within cross-realm environments), use [Cross_realm_principal_name.t] instead. *) type t = | User of string | Service of { service : string ; hostname : string } [@@deriving compare, hash, sexp_of] (** [to_string] returns either <username> or <service>/<hostname>. [of_string] is lenient to inclusion of the realm (for all principals) and full qualification of the domain name (for service principals). We drop the provided realm and drop a provided domain name if it matches the default domain. *) include Stringable.S with type t := t include Comparable.S_plain with type t := t include Hashable.S_plain with type t := t (** accepts <username> or <service>/<hostname> *) val arg : t Command.Arg_type.t (** Returns [None] if [t] is a [Service] *) val to_username : t -> Username.t option (** Raises if [t] is a [Service] *) val to_username_exn : t -> Username.t val service_on_this_host : service:string -> t (** Cross-realm *) val of_cross_realm : Cross_realm_principal_name.t -> t val with_realm : realm:Realm.t -> t -> Cross_realm_principal_name.t val with_default_realm : t -> Cross_realm_principal_name.t Deferred.Or_error.t end val create : Name.t -> t Deferred.Or_error.t val name : t -> Name.t (** Constructs a principal [<service_name>/<canonicalized_hostname>], where the canonicalized hostname is derived from [hostname] with the rules defined by the Kerberos config (as described at -devel/doc/admin/princ_dns.html). *) val service_with_canonicalized_hostname : service:string -> hostname:string -> t Deferred.Or_error.t module Cross_realm : sig val create : Cross_realm_principal_name.t -> t Deferred.Or_error.t val name : t -> Cross_realm_principal_name.t end val to_string : t -> string val check_password : t -> password:string -> unit Deferred.Or_error.t * [ kvno ] returns the key version number known by the KDC . Consequently this is an online test and must be called by a user with a valid TGT . an online test and must be called by a user with a valid TGT. *) val kvno : ?cred_cache:Internal.Cred_cache.t -> t -> int Deferred.Or_error.t module Stable : sig module Name : sig module V1 : sig type t = Name.t [@@deriving bin_io, compare, sexp] include Comparable.Stable.V1.S with type comparable := Name.t with type comparator_witness = Name.comparator_witness end end end
null
https://raw.githubusercontent.com/janestreet/krb/c9dbe0ec0ca646753873283dae509d07757ba546/src/principal.mli
ocaml
* [to_string] returns either <username> or <service>/<hostname>. [of_string] is lenient to inclusion of the realm (for all principals) and full qualification of the domain name (for service principals). We drop the provided realm and drop a provided domain name if it matches the default domain. * accepts <username> or <service>/<hostname> * Returns [None] if [t] is a [Service] * Raises if [t] is a [Service] * Cross-realm * Constructs a principal [<service_name>/<canonicalized_hostname>], where the canonicalized hostname is derived from [hostname] with the rules defined by the Kerberos config (as described at -devel/doc/admin/princ_dns.html).
open! Core open Async open Import * A principal is a unique identity to which can assign tickets . Generally , principals are a name ( containing an arbitrary number of components separated by ' / ' ) followed by " > " . The [ Krb ] library allows for two kinds of principals : User : < username>@<REALM > Service : < service>/<hostname>.<domain>@<REALM > See [ Config ] for information on how to configure < REALM > and < domain > . For a more complete explanation , see the MIT krb5 documentation : -1.5/krb5-1.5.4/doc/krb5-user/What-is-a-Kerberos-Principal_003f.html principals are a name (containing an arbitrary number of components separated by '/') followed by "@<REALM>". The [Krb] library allows for two kinds of principals: User: <username>@<REALM> Service: <service>/<hostname>.<domain>@<REALM> See [Config] for information on how to configure <REALM> and <domain>. For a more complete explanation, see the MIT krb5 documentation: -1.5/krb5-1.5.4/doc/krb5-user/What-is-a-Kerberos-Principal_003f.html *) type t = Internal.Principal.t module Name : sig * A [ Name.t ] represents the conventional names that may appear in a Kerberos principal ( i.e. the bit before " @REALM " ) . By default , when constructing a principal from this type , we assume that the principal is within the default realm configured in [ krb.conf ] . If realm information should be preserved ( eg . within cross - realm environments ) , use [ Cross_realm_principal_name.t ] instead . principal (i.e. the bit before "@REALM"). By default, when constructing a principal from this type, we assume that the principal is within the default realm configured in [krb.conf]. If realm information should be preserved (eg. within cross-realm environments), use [Cross_realm_principal_name.t] instead. *) type t = | User of string | Service of { service : string ; hostname : string } [@@deriving compare, hash, sexp_of] include Stringable.S with type t := t include Comparable.S_plain with type t := t include Hashable.S_plain with type t := t val arg : t Command.Arg_type.t val to_username : t -> Username.t option val to_username_exn : t -> Username.t val service_on_this_host : service:string -> t val of_cross_realm : Cross_realm_principal_name.t -> t val with_realm : realm:Realm.t -> t -> Cross_realm_principal_name.t val with_default_realm : t -> Cross_realm_principal_name.t Deferred.Or_error.t end val create : Name.t -> t Deferred.Or_error.t val name : t -> Name.t val service_with_canonicalized_hostname : service:string -> hostname:string -> t Deferred.Or_error.t module Cross_realm : sig val create : Cross_realm_principal_name.t -> t Deferred.Or_error.t val name : t -> Cross_realm_principal_name.t end val to_string : t -> string val check_password : t -> password:string -> unit Deferred.Or_error.t * [ kvno ] returns the key version number known by the KDC . Consequently this is an online test and must be called by a user with a valid TGT . an online test and must be called by a user with a valid TGT. *) val kvno : ?cred_cache:Internal.Cred_cache.t -> t -> int Deferred.Or_error.t module Stable : sig module Name : sig module V1 : sig type t = Name.t [@@deriving bin_io, compare, sexp] include Comparable.Stable.V1.S with type comparable := Name.t with type comparator_witness = Name.comparator_witness end end end
02ffd9a564a6d5ab6f472a0c48721b2271a2389ec4445017057d566c6cfd1ad3
CompSciCabal/SMRTYPRTY
sequences.rkt
#lang racket (define (filter predicate sequence) (cond ((null? sequence) null) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))) (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (enumerate-interval low high) (if (> low high) null (cons low (enumerate-interval (+ low 1) high)))) 2.33 ;; Later we need to use the more general system map function. ;; Uncomment if you want to test below. #| (define (map p sequence) |# #| (accumulate (lambda (x y) |# #| (cons (p x) y)) |# #| null sequence)) |# ;; Later we need to use a different append. #| (define (append seq1 seq2) |# ( accumulate cons seq2 seq1 ) ) (define (length sequence) (accumulate (lambda (el counter) (+ counter 1)) 0 sequence)) ( map ( lambda ( x ) ( * x x ) ) ( list 1 2 3 4 5 ) ) ( append ( list 1 2 3 4 5 ) ( list 6 7 8 9 10 ) ) ( length ( list 1 2 3 4 ) ) 2.34 (define (horner-eval x coeff-seq) (accumulate (lambda (coeff higher-terms) (+ coeff (* higher-terms x))) 0 coeff-seq)) ( horner - eval 2 ( list 1 3 0 5 0 1 ) ) ; should be 79 2.35 from 2.2 (define (join lst1 lst2) (cond [(null? lst1) lst2] [else (cons (car lst1) (append (cdr lst1) lst2))])) (define (fringe tree) (cond [(empty? tree) empty] [(pair? tree) (join (fringe (car tree)) (fringe (cadr tree)))] [else (list tree)])) #| (define (count-leaves t) |# #| (accumulate (lambda (x y) (+ 1 y)) ; the increment function |# 0 #| (fringe t))) |# ;; hmm, or... (define (count-leaves t) (accumulate + 0 (map (lambda (x) 1) (fringe t)))) (define simple-tree (list (list 2 5) (list 1 3))) (define my-tree (list (list (list 4 (list 2 9)) 2) (list 6 (list (list 5 (list 2 4)) 2)))) #| (count-leaves simple-tree) |# #| (count-leaves my-tree) |# 2.36 (define (accumulate-n op init seqs) (if (empty? (car seqs)) empty (cons (accumulate op init (map car seqs)) (accumulate-n op init (map cdr seqs))))) ( define s ' ( ( 1 2 3 ) ( 4 5 6 ) ( 7 8 9 ) ( 10 11 12 ) ) ) #| (accumulate-n + 0 s) |# 2.37 (define (dot-product v w) (accumulate + 0 (map * v w))) (define (matrix-*-vector m v) (map (lambda (row) (dot-product row v)) m)) (define (transpose mat) (accumulate-n cons empty mat)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (row) (map (lambda (col) (dot-product row col)) cols)) m))) ( define m ' ( ( 1 2 3 4 ) ( 4 5 6 6 ) ( 6 7 8 9 ) ) ) ( define i ' ( ( 1 0 0 0 ) ( 0 1 0 0 ) ( 0 0 1 0 ) ( 0 0 0 1 ) ) ) ( define v ' ( 2 1 10 20 ) ) ( define r1 ' ( 1 2 3 4 ) ) ( define r2 ' ( 4 5 6 6 ) ) ( define r3 ' ( 6 7 8 9 ) ) ( dot - product v r1 ) ; ; should be 2 + 2 + 30 + 80 = 114 ( dot - product v r2 ) ; ; should be 193 ( dot - product v r3 ) ; ; should be 279 ( matrix-*-vector m v ) ; ; should be ' ( 114 193 279 ) ( transpose m ) ; ; should be ' ( ( 1 4 6 ) ( 2 5 7 ) ( 3 6 8) ( 4 6 9 ) ) #| (matrix-*-matrix m i) ;; should be m |# 2.38 (define (fold-right op initial sequence) (if (null? sequence) initial (op (car sequence) (fold-right op initial (cdr sequence))))) (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) ;; the operation needs to be associative (grouping does not matter) ;; Note that I did not say commutative; matrix multiplication for example will work ;; fine with either fold-right or fold-left. ( fold - right / 1 ( list 1 2 3 ) ) ; should give 1/(2/3 ) = 3/2 ( fold - left / 1 ( list 1 2 3 ) ) ; should give ( 1/2)/3 = 1/6 ( fold - right list empty ( list 1 2 3 ) ) ; should be ( list 1 ( list 2 ( list 3 ( list empty ) ) ) ) ; or ' ( 1 ( 2 ( 3 ( ) ) ) ) ( fold - left list empty ( list 1 2 3 ) ) ; ( list ( list ( list ( list empty ) 1 ) 2 ) 3 ) ; or ' ( ( ( ( ) 1 ) 2 ) ( 3 ) ) 2.39 redefine append as before so second arg is an element (define (append lst el) (cond [(empty? lst) (cons el empty)] [else (cons (car lst) (append (cdr lst) el))])) (define (reverse sequence) (fold-right (lambda (x y) (append y x)) null sequence)) #| (define (reverse sequence) |# #| (fold-left |# #| (lambda (x y) (cons y x)) null sequence)) |# (reverse (list 1 2 3 4))
null
https://raw.githubusercontent.com/CompSciCabal/SMRTYPRTY/4a5550789c997c20fb7256b81469de1f1fce3514/sicp/v4/2.3/sequences.rkt
racket
Later we need to use the more general system map function. Uncomment if you want to test below. (define (map p sequence) (accumulate (lambda (x y) (cons (p x) y)) null sequence)) Later we need to use a different append. (define (append seq1 seq2) should be 79 (define (count-leaves t) (accumulate (lambda (x y) (+ 1 y)) ; the increment function (fringe t))) hmm, or... (count-leaves simple-tree) (count-leaves my-tree) (accumulate-n + 0 s) ; should be 2 + 2 + 30 + 80 = 114 ; should be 193 ; should be 279 ; should be ' ( 114 193 279 ) ; should be ' ( ( 1 4 6 ) ( 2 5 7 ) ( 3 6 8) ( 4 6 9 ) ) (matrix-*-matrix m i) ;; should be m the operation needs to be associative (grouping does not matter) Note that I did not say commutative; matrix multiplication for example will work fine with either fold-right or fold-left. should give 1/(2/3 ) = 3/2 should give ( 1/2)/3 = 1/6 should be ( list 1 ( list 2 ( list 3 ( list empty ) ) ) ) or ' ( 1 ( 2 ( 3 ( ) ) ) ) ( list ( list ( list ( list empty ) 1 ) 2 ) 3 ) or ' ( ( ( ( ) 1 ) 2 ) ( 3 ) ) (define (reverse sequence) (fold-left (lambda (x y) (cons y x)) null sequence))
#lang racket (define (filter predicate sequence) (cond ((null? sequence) null) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))) (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (enumerate-interval low high) (if (> low high) null (cons low (enumerate-interval (+ low 1) high)))) 2.33 ( accumulate cons seq2 seq1 ) ) (define (length sequence) (accumulate (lambda (el counter) (+ counter 1)) 0 sequence)) ( map ( lambda ( x ) ( * x x ) ) ( list 1 2 3 4 5 ) ) ( append ( list 1 2 3 4 5 ) ( list 6 7 8 9 10 ) ) ( length ( list 1 2 3 4 ) ) 2.34 (define (horner-eval x coeff-seq) (accumulate (lambda (coeff higher-terms) (+ coeff (* higher-terms x))) 0 coeff-seq)) 2.35 from 2.2 (define (join lst1 lst2) (cond [(null? lst1) lst2] [else (cons (car lst1) (append (cdr lst1) lst2))])) (define (fringe tree) (cond [(empty? tree) empty] [(pair? tree) (join (fringe (car tree)) (fringe (cadr tree)))] [else (list tree)])) 0 (define (count-leaves t) (accumulate + 0 (map (lambda (x) 1) (fringe t)))) (define simple-tree (list (list 2 5) (list 1 3))) (define my-tree (list (list (list 4 (list 2 9)) 2) (list 6 (list (list 5 (list 2 4)) 2)))) 2.36 (define (accumulate-n op init seqs) (if (empty? (car seqs)) empty (cons (accumulate op init (map car seqs)) (accumulate-n op init (map cdr seqs))))) ( define s ' ( ( 1 2 3 ) ( 4 5 6 ) ( 7 8 9 ) ( 10 11 12 ) ) ) 2.37 (define (dot-product v w) (accumulate + 0 (map * v w))) (define (matrix-*-vector m v) (map (lambda (row) (dot-product row v)) m)) (define (transpose mat) (accumulate-n cons empty mat)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (row) (map (lambda (col) (dot-product row col)) cols)) m))) ( define m ' ( ( 1 2 3 4 ) ( 4 5 6 6 ) ( 6 7 8 9 ) ) ) ( define i ' ( ( 1 0 0 0 ) ( 0 1 0 0 ) ( 0 0 1 0 ) ( 0 0 0 1 ) ) ) ( define v ' ( 2 1 10 20 ) ) ( define r1 ' ( 1 2 3 4 ) ) ( define r2 ' ( 4 5 6 6 ) ) ( define r3 ' ( 6 7 8 9 ) ) 2.38 (define (fold-right op initial sequence) (if (null? sequence) initial (op (car sequence) (fold-right op initial (cdr sequence))))) (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) 2.39 redefine append as before so second arg is an element (define (append lst el) (cond [(empty? lst) (cons el empty)] [else (cons (car lst) (append (cdr lst) el))])) (define (reverse sequence) (fold-right (lambda (x y) (append y x)) null sequence)) (reverse (list 1 2 3 4))
1f93052626a6ddd4bb47d3ef4d7d77d5145c2042f35e0f85bceae3bed22c2583
jgm/pandoc-citeproc
Pandoc.hs
# LANGUAGE CPP , ScopedTypeVariables , NoImplicitPrelude # -- | Compatibility module to work around differences in the -- types of functions between pandoc < 2.0 and pandoc >= 2.0. module Text.CSL.Compat.Pandoc ( writeMarkdown, writePlain, writeNative, writeHtmlString, readNative, readHtml, readMarkdown, readLaTeX, fetchItem, pipeProcess ) where import Prelude import qualified Control.Exception as E import System.Exit (ExitCode) import Data.ByteString.Lazy as BL import Data.ByteString as B import Data.Text (Text) import Text.Pandoc (Extension (..), Pandoc, ReaderOptions(..), WrapOption(..), WriterOptions(..), def, pandocExtensions) import qualified Text.Pandoc as Pandoc import qualified Text.Pandoc.Process import qualified Data.Text as T import Text.Pandoc.MIME (MimeType) import Text.Pandoc.Error (PandocError) import Text.Pandoc.Class (runPure, runIO) import qualified Text.Pandoc.Class (fetchItem) import Control.Monad.Except (runExceptT, lift) import Text.Pandoc.Extensions (extensionsFromList, disableExtension) readHtml :: Text -> Pandoc readHtml = either mempty id . runPure . Pandoc.readHtml def{ readerExtensions = extensionsFromList [Ext_native_divs, Ext_native_spans, Ext_raw_html, Ext_smart] } readMarkdown :: Text -> Pandoc readMarkdown = either mempty id . runPure . Pandoc.readMarkdown def{ readerExtensions = pandocExtensions, readerStandalone = True } readLaTeX :: Text -> Pandoc readLaTeX = either mempty id . runPure . Pandoc.readLaTeX def{ readerExtensions = extensionsFromList [Ext_raw_tex, Ext_smart] } readNative :: Text -> Pandoc readNative = either mempty id . runPure . Pandoc.readNative def writeMarkdown, writePlain, writeNative, writeHtmlString :: Pandoc -> Text writeMarkdown = either mempty id . runPure . Pandoc.writeMarkdown def{ writerExtensions = disableExtension Ext_smart $ disableExtension Ext_bracketed_spans $ disableExtension Ext_raw_attribute $ pandocExtensions, writerWrapText = WrapNone } writePlain = either mempty id . runPure . Pandoc.writePlain def writeNative = either mempty id . runPure . Pandoc.writeNative def{ writerTemplate = Just mempty } writeHtmlString = either mempty id . runPure . Pandoc.writeHtml4String def{ writerExtensions = extensionsFromList [Ext_native_divs, Ext_native_spans, Ext_raw_html], writerWrapText = WrapPreserve } pipeProcess :: Maybe [(String, String)] -> FilePath -> [String] -> BL.ByteString -> IO (ExitCode,BL.ByteString) pipeProcess = Text.Pandoc.Process.pipeProcess fetchItem :: String -> IO (Either E.SomeException (B.ByteString, Maybe MimeType)) fetchItem s = do res <- runIO $ runExceptT $ lift $ Text.Pandoc.Class.fetchItem $ T.pack s return $ case res of Left e -> Left (E.toException e) Right (Left (e :: PandocError)) -> Left (E.toException e) Right (Right r) -> Right r
null
https://raw.githubusercontent.com/jgm/pandoc-citeproc/473378e588c40a6c3cb3b24330431b89cf4f81b4/compat/Text/CSL/Compat/Pandoc.hs
haskell
| Compatibility module to work around differences in the types of functions between pandoc < 2.0 and pandoc >= 2.0.
# LANGUAGE CPP , ScopedTypeVariables , NoImplicitPrelude # module Text.CSL.Compat.Pandoc ( writeMarkdown, writePlain, writeNative, writeHtmlString, readNative, readHtml, readMarkdown, readLaTeX, fetchItem, pipeProcess ) where import Prelude import qualified Control.Exception as E import System.Exit (ExitCode) import Data.ByteString.Lazy as BL import Data.ByteString as B import Data.Text (Text) import Text.Pandoc (Extension (..), Pandoc, ReaderOptions(..), WrapOption(..), WriterOptions(..), def, pandocExtensions) import qualified Text.Pandoc as Pandoc import qualified Text.Pandoc.Process import qualified Data.Text as T import Text.Pandoc.MIME (MimeType) import Text.Pandoc.Error (PandocError) import Text.Pandoc.Class (runPure, runIO) import qualified Text.Pandoc.Class (fetchItem) import Control.Monad.Except (runExceptT, lift) import Text.Pandoc.Extensions (extensionsFromList, disableExtension) readHtml :: Text -> Pandoc readHtml = either mempty id . runPure . Pandoc.readHtml def{ readerExtensions = extensionsFromList [Ext_native_divs, Ext_native_spans, Ext_raw_html, Ext_smart] } readMarkdown :: Text -> Pandoc readMarkdown = either mempty id . runPure . Pandoc.readMarkdown def{ readerExtensions = pandocExtensions, readerStandalone = True } readLaTeX :: Text -> Pandoc readLaTeX = either mempty id . runPure . Pandoc.readLaTeX def{ readerExtensions = extensionsFromList [Ext_raw_tex, Ext_smart] } readNative :: Text -> Pandoc readNative = either mempty id . runPure . Pandoc.readNative def writeMarkdown, writePlain, writeNative, writeHtmlString :: Pandoc -> Text writeMarkdown = either mempty id . runPure . Pandoc.writeMarkdown def{ writerExtensions = disableExtension Ext_smart $ disableExtension Ext_bracketed_spans $ disableExtension Ext_raw_attribute $ pandocExtensions, writerWrapText = WrapNone } writePlain = either mempty id . runPure . Pandoc.writePlain def writeNative = either mempty id . runPure . Pandoc.writeNative def{ writerTemplate = Just mempty } writeHtmlString = either mempty id . runPure . Pandoc.writeHtml4String def{ writerExtensions = extensionsFromList [Ext_native_divs, Ext_native_spans, Ext_raw_html], writerWrapText = WrapPreserve } pipeProcess :: Maybe [(String, String)] -> FilePath -> [String] -> BL.ByteString -> IO (ExitCode,BL.ByteString) pipeProcess = Text.Pandoc.Process.pipeProcess fetchItem :: String -> IO (Either E.SomeException (B.ByteString, Maybe MimeType)) fetchItem s = do res <- runIO $ runExceptT $ lift $ Text.Pandoc.Class.fetchItem $ T.pack s return $ case res of Left e -> Left (E.toException e) Right (Left (e :: PandocError)) -> Left (E.toException e) Right (Right r) -> Right r
5fcaf2ce4b4dd123f371311cd1b193eddcc68e481dbb282e33a4a41c24c62294
c4-project/c4f
path_kind.mli
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) (** Kinds of path. *) (** Enumeration of kinds of path. Most of the path producer code is uniform across all path kinds, and so we use a single generator with a kind enumeration rather than separate producers. *) type t = | Insert (** Paths that insert a statement into a block. *) | Transform (** Paths that transform a statement. *) | Transform_list (** Paths that transform a list of statements in a block. *) include C4f_utils.Enum_types.Extension_table with type t := t * { 1 With actions } Kinds with actions are used in path consumers . Kinds with actions are used in path consumers. *) module With_action : sig (** Type of transformation functions. *) type 'a transformer = 'a -> 'a Base.Or_error.t type kind := t type t = | Insert of Subject.Statement.t list | Transform of Subject.Statement.t transformer | Transform_list of Subject.Statement.t list transformer (** Enumeration of kinds of path, complete with actions. *) val to_kind : t -> kind (** [to_kind ka] erases [ka]'s action, turning it into a kind which can be stringified, sexpified, and so on. *) end
null
https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/fuzz/src/path_kind.mli
ocaml
* Kinds of path. * Enumeration of kinds of path. Most of the path producer code is uniform across all path kinds, and so we use a single generator with a kind enumeration rather than separate producers. * Paths that insert a statement into a block. * Paths that transform a statement. * Paths that transform a list of statements in a block. * Type of transformation functions. * Enumeration of kinds of path, complete with actions. * [to_kind ka] erases [ka]'s action, turning it into a kind which can be stringified, sexpified, and so on.
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) type t = | Transform_list include C4f_utils.Enum_types.Extension_table with type t := t * { 1 With actions } Kinds with actions are used in path consumers . Kinds with actions are used in path consumers. *) module With_action : sig type 'a transformer = 'a -> 'a Base.Or_error.t type kind := t type t = | Insert of Subject.Statement.t list | Transform of Subject.Statement.t transformer | Transform_list of Subject.Statement.t list transformer val to_kind : t -> kind end
5518a01898e61e591dbce72b3e38f4e3e85c9705163246931e085bbf540089c1
drapanjanas/pneumatic-tubes
subs.cljs
(ns group-chat-app.subs (:require [re-frame.core :refer [reg-sub]])) (reg-sub :name (fn [db] (:name db))) (reg-sub :active-tab (fn [db] (:active-tab db))) (reg-sub :backend-connected (fn [db] (:backend-connected db))) (reg-sub :chat-room/name (fn [db] (get-in db [:chat-room :name]))) (reg-sub :chat-room/users (fn [db] (get-in db [:chat-room :users]))) (reg-sub :chat-room/messages (fn [db] (sort-by :chat-message/at (vals (get-in db [:chat-room :messages])))))
null
https://raw.githubusercontent.com/drapanjanas/pneumatic-tubes/ea3834ea04e06cd2d4a03da333461a474c0475f5/examples/group-chat-app/src/group_chat_app/subs.cljs
clojure
(ns group-chat-app.subs (:require [re-frame.core :refer [reg-sub]])) (reg-sub :name (fn [db] (:name db))) (reg-sub :active-tab (fn [db] (:active-tab db))) (reg-sub :backend-connected (fn [db] (:backend-connected db))) (reg-sub :chat-room/name (fn [db] (get-in db [:chat-room :name]))) (reg-sub :chat-room/users (fn [db] (get-in db [:chat-room :users]))) (reg-sub :chat-room/messages (fn [db] (sort-by :chat-message/at (vals (get-in db [:chat-room :messages])))))
6740aca65cafeffe5fa8c049a0f02bd80aa6ed4e48c67f286f83b4ed7d8163a1
auser/beehive
git_controller.erl
%%%------------------------------------------------------------------- %%% File : git_controller.erl Author : %%% Description : %%% Created : Sun Nov 29 23:18:32 PST 2009 %%%------------------------------------------------------------------- -module (git_controller). -export ([get/2, post/2, put/2, delete/2]). get(_, _Data) -> {struct, [{"beehive", <<"app, node, bees, stats">>}]}. post([Name, "post-receive"], Data) -> io:format("Git post commit hook fired for ~p: ~p~n", [Name, Data]), misc_utils:to_bin("Success!"); post(_Path, _Data) -> "unhandled". put(_Path, _Data) -> "unhandled". delete(_Path, _Data) -> "unhandled".
null
https://raw.githubusercontent.com/auser/beehive/dfe257701b21c56a50af73c8203ecac60ed21991/lib/erlang/apps/beehive/src/bh_rest/app_controllers/git_controller.erl
erlang
------------------------------------------------------------------- File : git_controller.erl Description : -------------------------------------------------------------------
Author : Created : Sun Nov 29 23:18:32 PST 2009 -module (git_controller). -export ([get/2, post/2, put/2, delete/2]). get(_, _Data) -> {struct, [{"beehive", <<"app, node, bees, stats">>}]}. post([Name, "post-receive"], Data) -> io:format("Git post commit hook fired for ~p: ~p~n", [Name, Data]), misc_utils:to_bin("Success!"); post(_Path, _Data) -> "unhandled". put(_Path, _Data) -> "unhandled". delete(_Path, _Data) -> "unhandled".
9f0de320518b90c6b38c7f4381168c43eb30345dd56aa3cbaae31f4cd96f5973
mirage/mirage-lambda
lambda_rpc.ml
module Int64 = struct let ( lsl ) a n = Int64.shift_left (Int64.of_int a) n let ( lsr ) a n = Int64.(to_int (shift_right a n)) let ( lor ) = Int64.logor let ( land ) = Int64.logand let of_int = Int64.of_int let to_int = Int64.to_int let ( + ) = Int64.add let ( - ) = Int64.sub let succ = Int64.succ end type request = Request type reply = Reply module Decoder = struct type error let pp_error : error Fmt.t = fun _ _ -> assert false type 'kind t = { i_off : int ; i_pos : int ; i_len : int ; proto_size : int64 ; block_size : int64 ; block_n : int64 ; i_tmp : Cstruct.t ; kind : 'kind ; state : 'kind state } and 'kind state = | Header of 'kind k | Raw of { kind : kind; consumed : int64 } | Stp of { kind : kind; consumed : int64; buf : Cstruct.t } | Exception of error | End and 'kind k = Cstruct.t -> 'kind t -> 'kind res and 'kind res = | Wait of 'kind t | Error of 'kind t * error | Flush of 'kind t * kind * Cstruct.t | Cont of 'kind t | Ok of 'kind t and kind = [ `Protobuf | `Block of int64 ] let pp_kind ppf = function | `Protobuf -> Fmt.string ppf "`Protobuf" | `Block n -> Fmt.pf ppf "(`Block %Ld)" n let pp_state ppf = function | Header _ -> Fmt.pf ppf "(Header #fun)" | Raw { kind; consumed; } -> Fmt.pf ppf "(Raw { @[<hov>kind = %a;@ consumed = %Ld;@] })" pp_kind kind consumed | Stp { kind; consumed; _ } -> Fmt.pf ppf "(Stp { @[<hov>kind = %a;@ consumed = %Ld;@] })" pp_kind kind consumed | Exception err -> Fmt.pf ppf "(Exception %a)" pp_error err | End -> Fmt.string ppf "End" let pp ppf t = Fmt.pf ppf "{ @[<hov>i_off = %d;@ \ i_pos = %d;@ \ i_len = %d;@ \ proto_size = %Ld;@ \ block_size = %Ld;@ \ block_n = %Ld;@ \ i_tmp = #buf;@ \ state = %a;@] }" t.i_off t.i_pos t.i_len t.proto_size t.block_size t.block_n pp_state t.state let await t = Wait t let error t err = Error ({ t with state = Exception err }, err) let ok t = Ok { t with state = End } let flush t kind consumed buf = Flush ({ t with state = Stp { kind; consumed; buf; }}, kind, buf) let rec get_byte ~ctor k src t = if (t.i_len - t.i_pos) > 0 then let byte = Cstruct.get_uint8 src (t.i_off + t.i_pos) in k byte src { t with i_pos = t.i_pos + 1 } else await { t with state = ctor (fun src t -> (get_byte[@tailcall]) ~ctor k src t) } let rec get_int64 ~ctor k src t = let get_byte k src t = get_byte ~ctor k src t in if (t.i_len - t.i_pos) > 7 then let n = Cstruct.LE.get_uint64 src (t.i_off + t.i_pos) in k n src { t with i_pos = t.i_pos + 8 } else if (t.i_len - t.i_pos) > 0 then (get_byte @@ fun byte7 -> get_byte @@ fun byte6 -> get_byte @@ fun byte5 -> get_byte @@ fun byte4 -> get_byte @@ fun byte3 -> get_byte @@ fun byte2 -> get_byte @@ fun byte1 -> get_byte @@ fun byte0 -> let n = Int64.((byte7 lsl 56) lor (byte6 lsl 48) lor (byte5 lsl 40) lor (byte4 lsl 32) lor (byte3 lsl 24) lor (byte2 lsl 16) lor (byte1 lsl 8) lor (of_int byte0)) in k n) src t else await { t with state = ctor (fun src t -> (get_int64[@tailcall]) ~ctor k src t) } module KHeader = struct let ctor k = Header k let get_byte k src t = get_byte ~ctor k src t let get_int64 k src t = get_int64 ~ctor k src t end let block src t n consumed = if consumed = t.block_size then flush t (`Block n) consumed (Cstruct.sub t.i_tmp 0 0) else if (t.i_len - t.i_pos) = 0 then await t else let len = min (Cstruct.len t.i_tmp) (t.i_len - t.i_pos) in let len = min len Int64.(to_int (t.block_size - consumed)) in Cstruct.blit src (t.i_off + t.i_pos) t.i_tmp 0 len; flush { t with i_pos = t.i_pos + len } (`Block n) Int64.(consumed + (of_int len)) (Cstruct.sub t.i_tmp 0 len) let proto src t consumed = if consumed = t.proto_size then flush t `Protobuf consumed (Cstruct.sub t.i_tmp 0 0) else if (t.i_len - t.i_pos) = 0 then await t else let len = min (Cstruct.len t.i_tmp) (t.i_len - t.i_pos) in let len = min len Int64.(to_int (t.proto_size - consumed)) in Cstruct.blit src (t.i_off + t.i_pos) t.i_tmp 0 len; flush { t with i_pos = t.i_pos + len } `Protobuf Int64.(consumed + (of_int len)) (Cstruct.sub t.i_tmp 0 len) let header src t = (KHeader.get_int64 @@ fun proto_size -> KHeader.get_int64 @@ fun block_size -> KHeader.get_int64 @@ fun block_n _src t -> Cont { t with proto_size ; block_size ; block_n ; state = Raw { kind = `Protobuf ; consumed = 0L } }) src t let default ?(len = 0x8000) kind = { i_off = 0 ; i_pos = 0 ; i_len = 0 ; proto_size = 0L ; block_size = 0L ; block_n = 0L ; i_tmp = Cstruct.create len ; kind ; state = Header header } let reset t = { t with proto_size = 0L ; block_size = 0L ; block_n = 0L ; state = Header header } let eval0 src t = match t.state with | Header k -> k src t | Raw { kind = `Protobuf; consumed; } -> proto src t consumed | Raw { kind = (`Block n); consumed; } -> block src t n consumed | Stp { kind; consumed; buf; } -> flush t kind consumed buf | Exception err -> error t err | End -> ok t let eval src t = let rec loop t = match eval0 src t with | Flush (t, kind, buf) -> `Flush (t, kind, buf) | Wait t -> `Await t | Error (t, err) -> `Error (t, err) | Cont t -> loop t | Ok t -> `End t in loop t let flush t = match t.state with | Stp { kind = `Protobuf; consumed; _ } -> if consumed = t.proto_size then { t with state = if t.block_n = 0L then End else Raw { kind = `Block 0L; consumed = 0L } } else { t with state = Raw { kind = `Protobuf; consumed; } } | Stp { kind = `Block n; consumed; _ } -> if consumed = t.block_size then { t with state = if Int64.succ n = t.block_n then End else Raw { kind = `Block (Int64.succ n); consumed = 0L } } else { t with state = Raw { kind = `Block n; consumed; } } | _ -> invalid_arg "Rpc.Decoder.flush: invalid state" let refill off len t = { t with i_off = off ; i_len = len ; i_pos = 0 } let block_size t = t.block_size let proto_size t = t.proto_size let block_n t = t.block_n end module Encoder = struct type error let pp_error : error Fmt.t = fun _ _ -> assert false type 'kind t = { o_off : int ; o_pos : int ; o_len : int ; i_off : int ; i_pos : int ; i_len : int ; proto_size : int64 ; block_size : int64 ; block_n : int64 ; p_tmp : string ; o_tmp : Cstruct.t ; kind : 'kind ; state : 'kind state } and 'kind state = | Header of 'kind k | Protobuf of { consumed : int } | Block of { n : int64; consumed : int } | Exception of error | End and 'kind k = Cstruct.t -> Cstruct.t -> 'kind t -> 'kind res and 'kind res = | Cont of 'kind t | Flush of 'kind t | Wait of 'kind t | Ok of 'kind t | Error of 'kind t * error let pp_state ppf = function | Header _ -> Fmt.pf ppf "(Header #k)" | Protobuf { consumed; } -> Fmt.pf ppf "(Protobuf { @[<hov>consumed = %d;@] })" consumed | Block { n; consumed; } -> Fmt.pf ppf "(Block { @[<hov>n = %Ld;@ consumed = %d;@] })" n consumed | Exception err -> Fmt.pf ppf "(Exception %a)" pp_error err | End -> Fmt.string ppf "End" let pp ppf t = Fmt.pf ppf "{ @[<hov>o_off = %d;@ \ o_pos = %d;@ \ o_len = %d;@ \ i_off = %d;@ \ i_pos = %d;@ \ i_len = %d;@ \ proto_size = %Ld;@ \ block_size = %Ld;@ \ block_n = %Ld;@ \ p_tmp = #buffer;@ \ o_tmp = #buffer;@ \ state = %a;@] }" t.o_off t.o_pos t.o_len t.i_off t.i_pos t.i_len t.proto_size t.block_size t.block_n pp_state t.state let ok t = Ok { t with state = End } let await t = Wait t let flush t = Flush t let error t err = Error ({ t with state = Exception err }, err) let rec put_byte ~ctor byte k src dst t = if (t.o_len - t.o_pos) > 0 then begin Cstruct.set_uint8 dst (t.o_off + t.o_pos) byte; k src dst { t with o_pos = t.o_pos + 1 } end else flush { t with state = ctor (fun dst t -> (put_byte[@tailcall]) ~ctor byte k dst t) } let rec put_int64 ~ctor n k src dst t = let put_byte byte k dst t = put_byte ~ctor byte k dst t in if (t.o_len - t.o_pos) > 8 then begin Cstruct.LE.set_uint64 dst (t.o_off + t.o_pos) n; k src dst { t with o_pos = t.o_pos + 8 } end else if (t.o_len - t.o_pos) > 0 then begin let byte7 = Int64.((n land 0xFF00000000000000L) lsr 56) in let byte6 = Int64.((n land 0x00FF000000000000L) lsr 48) in let byte5 = Int64.((n land 0x0000FF0000000000L) lsr 40) in let byte4 = Int64.((n land 0x000000FF00000000L) lsr 32) in let byte3 = Int64.((n land 0x00000000FF000000L) lsr 24) in let byte2 = Int64.((n land 0x0000000000FF0000L) lsr 16) in let byte1 = Int64.((n land 0x000000000000FF00L) lsr 8) in let byte0 = Int64.(to_int (n land 0x00000000000000FFL)) in (put_byte byte0 @@ put_byte byte1 @@ put_byte byte2 @@ put_byte byte3 @@ put_byte byte4 @@ put_byte byte5 @@ put_byte byte6 @@ put_byte byte7 k) src dst t end else flush { t with state = ctor (fun dst t -> (put_int64[@tailcall]) ~ctor n k dst t) } module KHeader = struct let ctor k = Header k let put_byte byte k src dst t = put_byte ~ctor byte k src dst t let put_int64 n k src dst t = put_int64 ~ctor n k src dst t end let block src dst t n consumed = if consumed = (Int64.to_int t.block_size) then flush { t with state = if Int64.succ n = t.block_n then End else Block { n = Int64.succ n; consumed = 0 } } else begin let len = min (t.o_len - t.o_pos) (t.i_len - t.i_pos) in let len = min len (Int64.to_int t.block_size - consumed) in Cstruct.blit src (t.i_off + t.i_pos) dst (t.o_off + t.o_pos) len; match (t.i_len - (t.i_pos + len)) > 0, (t.o_len - (t.o_pos + len)) > 0 with | true, true | false, false | true, false -> flush { t with i_pos = t.i_pos + len ; o_pos = t.o_pos + len ; state = Block { n; consumed = consumed + len; } } | false, true -> await { t with i_pos = t.i_pos + len ; o_pos = t.o_pos + len ; state = Block { n; consumed = consumed + len; } } end let proto _src dst t consumed = if consumed = String.length t.p_tmp then Cont { t with state = if t.block_n = 0L then End else Block { n = 0L; consumed = 0 } } else begin let len = min (t.o_len - t.o_pos) (String.length t.p_tmp - consumed) in let len = min len (Int64.to_int t.proto_size - consumed) in Cstruct.blit_from_string t.p_tmp consumed dst (t.o_off + t.o_pos) len; flush { t with o_pos = t.o_pos + len ; state = Protobuf { consumed = consumed + len } } end let header src dst t = (KHeader.put_int64 t.proto_size @@ KHeader.put_int64 t.block_size @@ KHeader.put_int64 t.block_n @@ fun _src _dst t -> Cont { t with state = Protobuf { consumed = 0 } }) src dst t type ('k, 'v) protobuf = | Request : (Lambda_types.request, request) protobuf | Reply : (Lambda_types.reply, reply) protobuf let default : type p k. (p, k) protobuf -> ?len:int -> p -> int64 -> int64 -> k t = fun kind ?(len = 0x8000) protobuf block_size block_n -> let encoder = Pbrt.Encoder.create () in let () = match kind with | Request -> Lambda_pb.encode_request protobuf encoder | Reply -> Lambda_pb.encode_reply protobuf encoder in let p_tmp = Pbrt.Encoder.to_bytes encoder |> Bytes.unsafe_to_string in { i_off = 0 ; i_pos = 0 ; i_len = 0 ; o_off = 0 ; o_pos = 0 ; o_len = 0 ; proto_size = Int64.of_int (String.length p_tmp) ; block_size ; block_n ; p_tmp ; o_tmp = Cstruct.create len GADT LOLILOL ; state = Header header } let eval0 src dst t = match t.state with | Header k -> k src dst t | Protobuf { consumed } -> proto src dst t consumed | Block { n; consumed; } -> block src dst t n consumed | Exception err -> error t err | End -> ok t let eval src dst t = let rec loop t = match eval0 src dst t with | Wait t -> `Await t | Flush t -> `Flush t | Cont t -> loop t | Error (t, err) -> `Error (t, err) | Ok t -> `End t in loop t let refill off len t = { t with i_off = off ; i_len = len ; i_pos = 0 } let flush off len t = { t with o_off = off ; o_len = len ; o_pos = 0 } let used_out t = t.o_pos let used_in t = t.i_pos let block t = match t.state with | Block { n; consumed; } -> n, consumed | _ -> invalid_arg "block: invalid state" end
null
https://raw.githubusercontent.com/mirage/mirage-lambda/a89b265b552f8b63ff725fc942f41a276fabb4f5/proto/lambda_rpc.ml
ocaml
module Int64 = struct let ( lsl ) a n = Int64.shift_left (Int64.of_int a) n let ( lsr ) a n = Int64.(to_int (shift_right a n)) let ( lor ) = Int64.logor let ( land ) = Int64.logand let of_int = Int64.of_int let to_int = Int64.to_int let ( + ) = Int64.add let ( - ) = Int64.sub let succ = Int64.succ end type request = Request type reply = Reply module Decoder = struct type error let pp_error : error Fmt.t = fun _ _ -> assert false type 'kind t = { i_off : int ; i_pos : int ; i_len : int ; proto_size : int64 ; block_size : int64 ; block_n : int64 ; i_tmp : Cstruct.t ; kind : 'kind ; state : 'kind state } and 'kind state = | Header of 'kind k | Raw of { kind : kind; consumed : int64 } | Stp of { kind : kind; consumed : int64; buf : Cstruct.t } | Exception of error | End and 'kind k = Cstruct.t -> 'kind t -> 'kind res and 'kind res = | Wait of 'kind t | Error of 'kind t * error | Flush of 'kind t * kind * Cstruct.t | Cont of 'kind t | Ok of 'kind t and kind = [ `Protobuf | `Block of int64 ] let pp_kind ppf = function | `Protobuf -> Fmt.string ppf "`Protobuf" | `Block n -> Fmt.pf ppf "(`Block %Ld)" n let pp_state ppf = function | Header _ -> Fmt.pf ppf "(Header #fun)" | Raw { kind; consumed; } -> Fmt.pf ppf "(Raw { @[<hov>kind = %a;@ consumed = %Ld;@] })" pp_kind kind consumed | Stp { kind; consumed; _ } -> Fmt.pf ppf "(Stp { @[<hov>kind = %a;@ consumed = %Ld;@] })" pp_kind kind consumed | Exception err -> Fmt.pf ppf "(Exception %a)" pp_error err | End -> Fmt.string ppf "End" let pp ppf t = Fmt.pf ppf "{ @[<hov>i_off = %d;@ \ i_pos = %d;@ \ i_len = %d;@ \ proto_size = %Ld;@ \ block_size = %Ld;@ \ block_n = %Ld;@ \ i_tmp = #buf;@ \ state = %a;@] }" t.i_off t.i_pos t.i_len t.proto_size t.block_size t.block_n pp_state t.state let await t = Wait t let error t err = Error ({ t with state = Exception err }, err) let ok t = Ok { t with state = End } let flush t kind consumed buf = Flush ({ t with state = Stp { kind; consumed; buf; }}, kind, buf) let rec get_byte ~ctor k src t = if (t.i_len - t.i_pos) > 0 then let byte = Cstruct.get_uint8 src (t.i_off + t.i_pos) in k byte src { t with i_pos = t.i_pos + 1 } else await { t with state = ctor (fun src t -> (get_byte[@tailcall]) ~ctor k src t) } let rec get_int64 ~ctor k src t = let get_byte k src t = get_byte ~ctor k src t in if (t.i_len - t.i_pos) > 7 then let n = Cstruct.LE.get_uint64 src (t.i_off + t.i_pos) in k n src { t with i_pos = t.i_pos + 8 } else if (t.i_len - t.i_pos) > 0 then (get_byte @@ fun byte7 -> get_byte @@ fun byte6 -> get_byte @@ fun byte5 -> get_byte @@ fun byte4 -> get_byte @@ fun byte3 -> get_byte @@ fun byte2 -> get_byte @@ fun byte1 -> get_byte @@ fun byte0 -> let n = Int64.((byte7 lsl 56) lor (byte6 lsl 48) lor (byte5 lsl 40) lor (byte4 lsl 32) lor (byte3 lsl 24) lor (byte2 lsl 16) lor (byte1 lsl 8) lor (of_int byte0)) in k n) src t else await { t with state = ctor (fun src t -> (get_int64[@tailcall]) ~ctor k src t) } module KHeader = struct let ctor k = Header k let get_byte k src t = get_byte ~ctor k src t let get_int64 k src t = get_int64 ~ctor k src t end let block src t n consumed = if consumed = t.block_size then flush t (`Block n) consumed (Cstruct.sub t.i_tmp 0 0) else if (t.i_len - t.i_pos) = 0 then await t else let len = min (Cstruct.len t.i_tmp) (t.i_len - t.i_pos) in let len = min len Int64.(to_int (t.block_size - consumed)) in Cstruct.blit src (t.i_off + t.i_pos) t.i_tmp 0 len; flush { t with i_pos = t.i_pos + len } (`Block n) Int64.(consumed + (of_int len)) (Cstruct.sub t.i_tmp 0 len) let proto src t consumed = if consumed = t.proto_size then flush t `Protobuf consumed (Cstruct.sub t.i_tmp 0 0) else if (t.i_len - t.i_pos) = 0 then await t else let len = min (Cstruct.len t.i_tmp) (t.i_len - t.i_pos) in let len = min len Int64.(to_int (t.proto_size - consumed)) in Cstruct.blit src (t.i_off + t.i_pos) t.i_tmp 0 len; flush { t with i_pos = t.i_pos + len } `Protobuf Int64.(consumed + (of_int len)) (Cstruct.sub t.i_tmp 0 len) let header src t = (KHeader.get_int64 @@ fun proto_size -> KHeader.get_int64 @@ fun block_size -> KHeader.get_int64 @@ fun block_n _src t -> Cont { t with proto_size ; block_size ; block_n ; state = Raw { kind = `Protobuf ; consumed = 0L } }) src t let default ?(len = 0x8000) kind = { i_off = 0 ; i_pos = 0 ; i_len = 0 ; proto_size = 0L ; block_size = 0L ; block_n = 0L ; i_tmp = Cstruct.create len ; kind ; state = Header header } let reset t = { t with proto_size = 0L ; block_size = 0L ; block_n = 0L ; state = Header header } let eval0 src t = match t.state with | Header k -> k src t | Raw { kind = `Protobuf; consumed; } -> proto src t consumed | Raw { kind = (`Block n); consumed; } -> block src t n consumed | Stp { kind; consumed; buf; } -> flush t kind consumed buf | Exception err -> error t err | End -> ok t let eval src t = let rec loop t = match eval0 src t with | Flush (t, kind, buf) -> `Flush (t, kind, buf) | Wait t -> `Await t | Error (t, err) -> `Error (t, err) | Cont t -> loop t | Ok t -> `End t in loop t let flush t = match t.state with | Stp { kind = `Protobuf; consumed; _ } -> if consumed = t.proto_size then { t with state = if t.block_n = 0L then End else Raw { kind = `Block 0L; consumed = 0L } } else { t with state = Raw { kind = `Protobuf; consumed; } } | Stp { kind = `Block n; consumed; _ } -> if consumed = t.block_size then { t with state = if Int64.succ n = t.block_n then End else Raw { kind = `Block (Int64.succ n); consumed = 0L } } else { t with state = Raw { kind = `Block n; consumed; } } | _ -> invalid_arg "Rpc.Decoder.flush: invalid state" let refill off len t = { t with i_off = off ; i_len = len ; i_pos = 0 } let block_size t = t.block_size let proto_size t = t.proto_size let block_n t = t.block_n end module Encoder = struct type error let pp_error : error Fmt.t = fun _ _ -> assert false type 'kind t = { o_off : int ; o_pos : int ; o_len : int ; i_off : int ; i_pos : int ; i_len : int ; proto_size : int64 ; block_size : int64 ; block_n : int64 ; p_tmp : string ; o_tmp : Cstruct.t ; kind : 'kind ; state : 'kind state } and 'kind state = | Header of 'kind k | Protobuf of { consumed : int } | Block of { n : int64; consumed : int } | Exception of error | End and 'kind k = Cstruct.t -> Cstruct.t -> 'kind t -> 'kind res and 'kind res = | Cont of 'kind t | Flush of 'kind t | Wait of 'kind t | Ok of 'kind t | Error of 'kind t * error let pp_state ppf = function | Header _ -> Fmt.pf ppf "(Header #k)" | Protobuf { consumed; } -> Fmt.pf ppf "(Protobuf { @[<hov>consumed = %d;@] })" consumed | Block { n; consumed; } -> Fmt.pf ppf "(Block { @[<hov>n = %Ld;@ consumed = %d;@] })" n consumed | Exception err -> Fmt.pf ppf "(Exception %a)" pp_error err | End -> Fmt.string ppf "End" let pp ppf t = Fmt.pf ppf "{ @[<hov>o_off = %d;@ \ o_pos = %d;@ \ o_len = %d;@ \ i_off = %d;@ \ i_pos = %d;@ \ i_len = %d;@ \ proto_size = %Ld;@ \ block_size = %Ld;@ \ block_n = %Ld;@ \ p_tmp = #buffer;@ \ o_tmp = #buffer;@ \ state = %a;@] }" t.o_off t.o_pos t.o_len t.i_off t.i_pos t.i_len t.proto_size t.block_size t.block_n pp_state t.state let ok t = Ok { t with state = End } let await t = Wait t let flush t = Flush t let error t err = Error ({ t with state = Exception err }, err) let rec put_byte ~ctor byte k src dst t = if (t.o_len - t.o_pos) > 0 then begin Cstruct.set_uint8 dst (t.o_off + t.o_pos) byte; k src dst { t with o_pos = t.o_pos + 1 } end else flush { t with state = ctor (fun dst t -> (put_byte[@tailcall]) ~ctor byte k dst t) } let rec put_int64 ~ctor n k src dst t = let put_byte byte k dst t = put_byte ~ctor byte k dst t in if (t.o_len - t.o_pos) > 8 then begin Cstruct.LE.set_uint64 dst (t.o_off + t.o_pos) n; k src dst { t with o_pos = t.o_pos + 8 } end else if (t.o_len - t.o_pos) > 0 then begin let byte7 = Int64.((n land 0xFF00000000000000L) lsr 56) in let byte6 = Int64.((n land 0x00FF000000000000L) lsr 48) in let byte5 = Int64.((n land 0x0000FF0000000000L) lsr 40) in let byte4 = Int64.((n land 0x000000FF00000000L) lsr 32) in let byte3 = Int64.((n land 0x00000000FF000000L) lsr 24) in let byte2 = Int64.((n land 0x0000000000FF0000L) lsr 16) in let byte1 = Int64.((n land 0x000000000000FF00L) lsr 8) in let byte0 = Int64.(to_int (n land 0x00000000000000FFL)) in (put_byte byte0 @@ put_byte byte1 @@ put_byte byte2 @@ put_byte byte3 @@ put_byte byte4 @@ put_byte byte5 @@ put_byte byte6 @@ put_byte byte7 k) src dst t end else flush { t with state = ctor (fun dst t -> (put_int64[@tailcall]) ~ctor n k dst t) } module KHeader = struct let ctor k = Header k let put_byte byte k src dst t = put_byte ~ctor byte k src dst t let put_int64 n k src dst t = put_int64 ~ctor n k src dst t end let block src dst t n consumed = if consumed = (Int64.to_int t.block_size) then flush { t with state = if Int64.succ n = t.block_n then End else Block { n = Int64.succ n; consumed = 0 } } else begin let len = min (t.o_len - t.o_pos) (t.i_len - t.i_pos) in let len = min len (Int64.to_int t.block_size - consumed) in Cstruct.blit src (t.i_off + t.i_pos) dst (t.o_off + t.o_pos) len; match (t.i_len - (t.i_pos + len)) > 0, (t.o_len - (t.o_pos + len)) > 0 with | true, true | false, false | true, false -> flush { t with i_pos = t.i_pos + len ; o_pos = t.o_pos + len ; state = Block { n; consumed = consumed + len; } } | false, true -> await { t with i_pos = t.i_pos + len ; o_pos = t.o_pos + len ; state = Block { n; consumed = consumed + len; } } end let proto _src dst t consumed = if consumed = String.length t.p_tmp then Cont { t with state = if t.block_n = 0L then End else Block { n = 0L; consumed = 0 } } else begin let len = min (t.o_len - t.o_pos) (String.length t.p_tmp - consumed) in let len = min len (Int64.to_int t.proto_size - consumed) in Cstruct.blit_from_string t.p_tmp consumed dst (t.o_off + t.o_pos) len; flush { t with o_pos = t.o_pos + len ; state = Protobuf { consumed = consumed + len } } end let header src dst t = (KHeader.put_int64 t.proto_size @@ KHeader.put_int64 t.block_size @@ KHeader.put_int64 t.block_n @@ fun _src _dst t -> Cont { t with state = Protobuf { consumed = 0 } }) src dst t type ('k, 'v) protobuf = | Request : (Lambda_types.request, request) protobuf | Reply : (Lambda_types.reply, reply) protobuf let default : type p k. (p, k) protobuf -> ?len:int -> p -> int64 -> int64 -> k t = fun kind ?(len = 0x8000) protobuf block_size block_n -> let encoder = Pbrt.Encoder.create () in let () = match kind with | Request -> Lambda_pb.encode_request protobuf encoder | Reply -> Lambda_pb.encode_reply protobuf encoder in let p_tmp = Pbrt.Encoder.to_bytes encoder |> Bytes.unsafe_to_string in { i_off = 0 ; i_pos = 0 ; i_len = 0 ; o_off = 0 ; o_pos = 0 ; o_len = 0 ; proto_size = Int64.of_int (String.length p_tmp) ; block_size ; block_n ; p_tmp ; o_tmp = Cstruct.create len GADT LOLILOL ; state = Header header } let eval0 src dst t = match t.state with | Header k -> k src dst t | Protobuf { consumed } -> proto src dst t consumed | Block { n; consumed; } -> block src dst t n consumed | Exception err -> error t err | End -> ok t let eval src dst t = let rec loop t = match eval0 src dst t with | Wait t -> `Await t | Flush t -> `Flush t | Cont t -> loop t | Error (t, err) -> `Error (t, err) | Ok t -> `End t in loop t let refill off len t = { t with i_off = off ; i_len = len ; i_pos = 0 } let flush off len t = { t with o_off = off ; o_len = len ; o_pos = 0 } let used_out t = t.o_pos let used_in t = t.i_pos let block t = match t.state with | Block { n; consumed; } -> n, consumed | _ -> invalid_arg "block: invalid state" end
bf98e5192829751133826959afdec1f2c8a9817daf37deffef019e426a6a1694
cerner/clara-rules
test_node_sharing.cljc
#?(:clj (ns clara.test-node-sharing (:require [clara.tools.testing-utils :refer [def-rules-test] :as tu] [clara.rules :refer [fire-rules insert insert-all insert-unconditional! insert! retract query]] [clara.rules.testfacts :refer [->Temperature ->Cold ->WindSpeed ->ColdAndWindy]] [clojure.test :refer [is deftest run-tests testing use-fixtures]] [clara.rules.accumulators] [schema.test :as st]) (:import [clara.rules.testfacts Temperature Cold WindSpeed ColdAndWindy WindSpeed])) :cljs (ns clara.test-node-sharing (:require [clara.rules :refer [fire-rules insert insert! insert-all insert-unconditional! retract query]] [clara.rules.testfacts :refer [->Temperature Temperature ->Cold Cold ->WindSpeed WindSpeed ->ColdAndWindy ColdAndWindy]] [clara.rules.accumulators] [cljs.test] [schema.test :as st] [clara.tools.testing-utils :as tu]) (:require-macros [clara.tools.testing-utils :refer [def-rules-test]] [cljs.test :refer [is deftest run-tests testing use-fixtures]]))) (use-fixtures :once st/validate-schemas #?(:clj tu/opts-fixture) tu/side-effect-holder-fixture) See issue 433 for more information (def-rules-test test-or-sharing-same-condition {:rules [or-rule [[[:or [::a] [::b]] [::d]] (insert! {:fact-type ::c})] other-rule [[[::a] [::d]] (insert! {:fact-type ::e})]] :queries [c-query [[] [[?c <- ::c]]] e-query [[] [[?e <- ::e]]]] :sessions [empty-session [or-rule other-rule c-query e-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::b}) (insert {:fact-type ::d}) fire-rules)] (is (= (set (query session c-query)) #{{:?c {:fact-type ::c}}})) (is (= (set (query session e-query)) #{})))) ;; Replicate the same logical scenario as above in test-or-sharing-same-condition ;; in a single rule with a boolean :or condition. (def-rules-test test-or-sharing-same-condition-in-same-production {:rules [single-rule [[[:or [:and [:or [::a] [::b]] [::d]] [:and [::a] [::d]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::b}) (insert {:fact-type ::d}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}}])))) ;; FIXME: Log an issue for this bug and uncomment when it is resolved. Since an :or condition is essentially creating two rules I 'd expect this to insert twice . (comment (def-rules-test test-or-sharing-same-condition-in-same-production-duplicate-path {:rules [single-rule [[[:or [:and [:or [::a] [::b]] [::d] ] [:and [::a] [::d]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::a}) (insert {:fact-type ::d}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}} {:?c {:fact-type ::c}}]))))) (def-rules-test test-or-sharing-same-condition-in-same-production-beginning-duplicate-path {:rules [single-rule [[[:or [:and [:or [::a] [::b]] [::d] [::e]] [:and [::a] [::d] [::f]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::a}) (insert {:fact-type ::d}) (insert {:fact-type ::e}) (insert {:fact-type ::f}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}} {:?c {:fact-type ::c}}])))) (def-rules-test test-or-sharing-same-condition-in-same-production-ending-duplicate-path {:rules [single-rule [[[:or [:and [::e] [:or [::a] [::b]] [::d]] [:and [::f] [::a] [::d]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::a}) (insert {:fact-type ::d}) (insert {:fact-type ::e}) (insert {:fact-type ::f}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}} {:?c {:fact-type ::c}}])))) (def-rules-test test-or-sharing-same-condition-with-different-intervening-conditions {:rules [or-rule [[[:or [::a] [::b]] [::f] [::d]] (insert! {:fact-type ::c})] other-rule [[[::a] [::g] [::d]] (insert! {:fact-type ::e})]] :queries [c-query [[] [[?c <- ::c]]] e-query [[] [[?e <- ::e]]]] :sessions [empty-session [or-rule other-rule c-query e-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::b}) (insert {:fact-type ::d}) (insert {:fact-type ::f}) fire-rules)] (is (= (set (query session c-query)) #{{:?c {:fact-type ::c}}})) (is (= (set (query session e-query)) #{})))) (def-rules-test test-sharing-simple-condition-followed-by-or {:rules [cold-and-windy-rule [[[WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [:or [Cold] [Temperature (< temperature 0)]]] (insert! (->ColdAndWindy nil nil))]] :queries [cold-windy-query [[] [[?cw <- ColdAndWindy]]]] :sessions [empty-session [cold-and-windy-rule cold-windy-query] {}]} (reset! tu/side-effect-holder 0) (is (= (-> empty-session (insert (->WindSpeed 30 "LCY") (->Cold -20)) fire-rules (query cold-windy-query)) [{:?cw (->ColdAndWindy nil nil)}])) (is (= @tu/side-effect-holder 1) "The constraints on WindSpeed should only be evaluated once")) (def-rules-test test-shared-first-condition-multiple-rules-met {:rules [cold-fact-rule [[[WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Cold]] (insert! (->ColdAndWindy nil nil))] temp-fact-rule [[[WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Temperature (< temperature 0)]] (insert! (->ColdAndWindy nil nil))]] :queries [cold-windy-query [[] [[?cw <- ColdAndWindy]]]] :sessions [empty-session [cold-fact-rule temp-fact-rule cold-windy-query] {}]} (reset! tu/side-effect-holder 0) (is (= (-> empty-session (insert (->WindSpeed 30 "LCY") (->Cold -20)) fire-rules (query cold-windy-query)) [{:?cw (->ColdAndWindy nil nil)}])) (is (= @tu/side-effect-holder 1) "The constraints on WindSpeed should only be evaluated once")) (def-rules-test test-shared-second-condition-multiple-rules-unmet {:rules [cold-fact-rule [[[::absent-type-1] [WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Cold]] (insert! (->ColdAndWindy nil nil))] temp-fact-rule [[[::absent-type-2] [WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Temperature (< temperature 0)]] (insert! (->ColdAndWindy nil nil))]] :queries [cold-windy-query [[] [[?cw <- ColdAndWindy]]]] :sessions [empty-session [cold-fact-rule temp-fact-rule cold-windy-query] {}]} (reset! tu/side-effect-holder 0) (is (empty? (-> empty-session (insert (->WindSpeed 30 "LCY") (->Cold -20)) fire-rules (query cold-windy-query)))) Note that even though the parent condition is n't met , the WindSpeed will still be evaluated ;; to determine if it meets the constraints since it isn't dependent on the parent condition. ;; It is possible that this would be change in the future if we decided to use lazy evaluation, but in any case it should not be more than 1 . (is (= @tu/side-effect-holder 1) "The constraints on WindSpeed should be evaluated exactly once"))
null
https://raw.githubusercontent.com/cerner/clara-rules/8107a5ab7fdb475e323c0bcb39084a83454deb1c/src/test/common/clara/test_node_sharing.cljc
clojure
Replicate the same logical scenario as above in test-or-sharing-same-condition in a single rule with a boolean :or condition. FIXME: Log an issue for this bug and uncomment when it is resolved. Since an :or to determine if it meets the constraints since it isn't dependent on the parent condition. It is possible that this would be change in the future if we decided to use lazy evaluation,
#?(:clj (ns clara.test-node-sharing (:require [clara.tools.testing-utils :refer [def-rules-test] :as tu] [clara.rules :refer [fire-rules insert insert-all insert-unconditional! insert! retract query]] [clara.rules.testfacts :refer [->Temperature ->Cold ->WindSpeed ->ColdAndWindy]] [clojure.test :refer [is deftest run-tests testing use-fixtures]] [clara.rules.accumulators] [schema.test :as st]) (:import [clara.rules.testfacts Temperature Cold WindSpeed ColdAndWindy WindSpeed])) :cljs (ns clara.test-node-sharing (:require [clara.rules :refer [fire-rules insert insert! insert-all insert-unconditional! retract query]] [clara.rules.testfacts :refer [->Temperature Temperature ->Cold Cold ->WindSpeed WindSpeed ->ColdAndWindy ColdAndWindy]] [clara.rules.accumulators] [cljs.test] [schema.test :as st] [clara.tools.testing-utils :as tu]) (:require-macros [clara.tools.testing-utils :refer [def-rules-test]] [cljs.test :refer [is deftest run-tests testing use-fixtures]]))) (use-fixtures :once st/validate-schemas #?(:clj tu/opts-fixture) tu/side-effect-holder-fixture) See issue 433 for more information (def-rules-test test-or-sharing-same-condition {:rules [or-rule [[[:or [::a] [::b]] [::d]] (insert! {:fact-type ::c})] other-rule [[[::a] [::d]] (insert! {:fact-type ::e})]] :queries [c-query [[] [[?c <- ::c]]] e-query [[] [[?e <- ::e]]]] :sessions [empty-session [or-rule other-rule c-query e-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::b}) (insert {:fact-type ::d}) fire-rules)] (is (= (set (query session c-query)) #{{:?c {:fact-type ::c}}})) (is (= (set (query session e-query)) #{})))) (def-rules-test test-or-sharing-same-condition-in-same-production {:rules [single-rule [[[:or [:and [:or [::a] [::b]] [::d]] [:and [::a] [::d]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::b}) (insert {:fact-type ::d}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}}])))) condition is essentially creating two rules I 'd expect this to insert twice . (comment (def-rules-test test-or-sharing-same-condition-in-same-production-duplicate-path {:rules [single-rule [[[:or [:and [:or [::a] [::b]] [::d] ] [:and [::a] [::d]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::a}) (insert {:fact-type ::d}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}} {:?c {:fact-type ::c}}]))))) (def-rules-test test-or-sharing-same-condition-in-same-production-beginning-duplicate-path {:rules [single-rule [[[:or [:and [:or [::a] [::b]] [::d] [::e]] [:and [::a] [::d] [::f]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::a}) (insert {:fact-type ::d}) (insert {:fact-type ::e}) (insert {:fact-type ::f}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}} {:?c {:fact-type ::c}}])))) (def-rules-test test-or-sharing-same-condition-in-same-production-ending-duplicate-path {:rules [single-rule [[[:or [:and [::e] [:or [::a] [::b]] [::d]] [:and [::f] [::a] [::d]]]] (insert! {:fact-type ::c})]] :queries [c-query [[] [[?c <- ::c]]]] :sessions [empty-session [single-rule c-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::a}) (insert {:fact-type ::d}) (insert {:fact-type ::e}) (insert {:fact-type ::f}) fire-rules)] (is (= (query session c-query) [{:?c {:fact-type ::c}} {:?c {:fact-type ::c}}])))) (def-rules-test test-or-sharing-same-condition-with-different-intervening-conditions {:rules [or-rule [[[:or [::a] [::b]] [::f] [::d]] (insert! {:fact-type ::c})] other-rule [[[::a] [::g] [::d]] (insert! {:fact-type ::e})]] :queries [c-query [[] [[?c <- ::c]]] e-query [[] [[?e <- ::e]]]] :sessions [empty-session [or-rule other-rule c-query e-query] {:fact-type-fn :fact-type}]} (let [session (-> empty-session (insert {:fact-type ::b}) (insert {:fact-type ::d}) (insert {:fact-type ::f}) fire-rules)] (is (= (set (query session c-query)) #{{:?c {:fact-type ::c}}})) (is (= (set (query session e-query)) #{})))) (def-rules-test test-sharing-simple-condition-followed-by-or {:rules [cold-and-windy-rule [[[WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [:or [Cold] [Temperature (< temperature 0)]]] (insert! (->ColdAndWindy nil nil))]] :queries [cold-windy-query [[] [[?cw <- ColdAndWindy]]]] :sessions [empty-session [cold-and-windy-rule cold-windy-query] {}]} (reset! tu/side-effect-holder 0) (is (= (-> empty-session (insert (->WindSpeed 30 "LCY") (->Cold -20)) fire-rules (query cold-windy-query)) [{:?cw (->ColdAndWindy nil nil)}])) (is (= @tu/side-effect-holder 1) "The constraints on WindSpeed should only be evaluated once")) (def-rules-test test-shared-first-condition-multiple-rules-met {:rules [cold-fact-rule [[[WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Cold]] (insert! (->ColdAndWindy nil nil))] temp-fact-rule [[[WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Temperature (< temperature 0)]] (insert! (->ColdAndWindy nil nil))]] :queries [cold-windy-query [[] [[?cw <- ColdAndWindy]]]] :sessions [empty-session [cold-fact-rule temp-fact-rule cold-windy-query] {}]} (reset! tu/side-effect-holder 0) (is (= (-> empty-session (insert (->WindSpeed 30 "LCY") (->Cold -20)) fire-rules (query cold-windy-query)) [{:?cw (->ColdAndWindy nil nil)}])) (is (= @tu/side-effect-holder 1) "The constraints on WindSpeed should only be evaluated once")) (def-rules-test test-shared-second-condition-multiple-rules-unmet {:rules [cold-fact-rule [[[::absent-type-1] [WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Cold]] (insert! (->ColdAndWindy nil nil))] temp-fact-rule [[[::absent-type-2] [WindSpeed (> windspeed 20) (do (swap! tu/side-effect-holder inc) true)] [Temperature (< temperature 0)]] (insert! (->ColdAndWindy nil nil))]] :queries [cold-windy-query [[] [[?cw <- ColdAndWindy]]]] :sessions [empty-session [cold-fact-rule temp-fact-rule cold-windy-query] {}]} (reset! tu/side-effect-holder 0) (is (empty? (-> empty-session (insert (->WindSpeed 30 "LCY") (->Cold -20)) fire-rules (query cold-windy-query)))) Note that even though the parent condition is n't met , the WindSpeed will still be evaluated but in any case it should not be more than 1 . (is (= @tu/side-effect-holder 1) "The constraints on WindSpeed should be evaluated exactly once"))
6112322d0e0c5a424c160b59b69d08dda37007c06db13dc97e0cff07eaf21730
BillHallahan/G2
Translation.hs
-- | Translation -- Export module for G2.Translation. module G2.Translation ( module G2.Translation.Haskell , module G2.Translation.HaskellCheck , module G2.Translation.Interface , module G2.Translation.PrimInject , module G2.Translation.TransTypes ) where import G2.Translation.Haskell import G2.Translation.HaskellCheck import G2.Translation.PrimInject import G2.Translation.Interface import G2.Translation.TransTypes
null
https://raw.githubusercontent.com/BillHallahan/G2/dfd377793dcccdc7126a9f4a65b58249673e8a70/src/G2/Translation.hs
haskell
| Translation Export module for G2.Translation.
module G2.Translation ( module G2.Translation.Haskell , module G2.Translation.HaskellCheck , module G2.Translation.Interface , module G2.Translation.PrimInject , module G2.Translation.TransTypes ) where import G2.Translation.Haskell import G2.Translation.HaskellCheck import G2.Translation.PrimInject import G2.Translation.Interface import G2.Translation.TransTypes
06deefd3e65f7da91ee74d4fd832bfc7c1df2de03c94403cfe24d0a804d9327d
aws-beam/aws-erlang
aws_synthetics.erl
%% WARNING: DO NOT EDIT, AUTO-GENERATED CODE! See -beam/aws-codegen for more details . @doc Amazon CloudWatch Synthetics %% You can use Amazon CloudWatch Synthetics to continually monitor your %% services. %% %% You can create and manage canaries, which are modular, lightweight scripts %% that monitor your endpoints and APIs from the outside-in. You can set up your canaries to run 24 hours a day , once per minute . The canaries help %% you check the availability and latency of your web services and %% troubleshoot anomalies by investigating load time data, screenshots of the UI , logs , and metrics . The canaries seamlessly integrate with CloudWatch ServiceLens to help you trace the causes of impacted nodes in your %% applications. For more information, see Using ServiceLens to Monitor the Health of Your Applications in the Amazon CloudWatch User Guide . %% %% Before you create and manage canaries, be aware of the security %% considerations. For more information, see Security Considerations for %% Synthetics Canaries. -module(aws_synthetics). -export([associate_resource/3, associate_resource/4, create_canary/2, create_canary/3, create_group/2, create_group/3, delete_canary/3, delete_canary/4, delete_group/3, delete_group/4, describe_canaries/2, describe_canaries/3, describe_canaries_last_run/2, describe_canaries_last_run/3, describe_runtime_versions/2, describe_runtime_versions/3, disassociate_resource/3, disassociate_resource/4, get_canary/2, get_canary/4, get_canary/5, get_canary_runs/3, get_canary_runs/4, get_group/2, get_group/4, get_group/5, list_associated_groups/3, list_associated_groups/4, list_group_resources/3, list_group_resources/4, list_groups/2, list_groups/3, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, start_canary/3, start_canary/4, stop_canary/3, stop_canary/4, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4, update_canary/3, update_canary/4]). -include_lib("hackney/include/hackney_lib.hrl"). %%==================================================================== %% API %%==================================================================== %% @doc Associates a canary with a group. %% %% Using groups can help you with managing and automating your canaries, and %% you can also view aggregated run results and statistics for all canaries %% in a group. %% You must run this operation in the Region where the canary exists . associate_resource(Client, GroupIdentifier, Input) -> associate_resource(Client, GroupIdentifier, Input, []). associate_resource(Client, GroupIdentifier, Input0, Options0) -> Method = patch, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), "/associate"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Creates a canary. %% %% Canaries are scripts that monitor your endpoints and APIs from the outside - in . Canaries help you check the availability and latency of your %% web services and troubleshoot anomalies by investigating load time data, %% screenshots of the UI, logs, and metrics. You can set up a canary to run %% continuously or just once. %% Do not use ` CreateCanary ' to modify an existing canary . Use UpdateCanary instead . %% To create canaries , you must have the ` ' policy . If you are creating a new IAM role for the canary , you also need the ` iam : CreateRole ' , ` iam : CreatePolicy ' and ` iam : ' permissions . For more information , see %% Necessary Roles and Permissions. %% %% Do not include secrets or proprietary information in your canary names. The canary name makes up part of the Amazon Resource Name ( ARN ) for the canary , and the ARN is included in outbound calls over the internet . For %% more information, see Security Considerations for Synthetics Canaries. create_canary(Client, Input) -> create_canary(Client, Input, []). create_canary(Client, Input0, Options0) -> Method = post, Path = ["/canary"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Creates a group which you can use to associate canaries with each %% other, including cross-Region canaries. %% %% Using groups can help you with managing and automating your canaries, and %% you can also view aggregated run results and statistics for all canaries %% in a group. %% Groups are global resources . When you create a group , it is replicated across Amazon Web Services Regions , and you can view it and add canaries to it from any Region . Although the group ARN format reflects the Region %% name where it was created, a group is not constrained to any Region. This means that you can put canaries from multiple Regions into the same group , %% and then use that group to view and manage all of those canaries in a %% single view. %% Groups are supported in all Regions except the Regions that are disabled by default . For more information about these Regions , see Enabling a %% Region. %% Each group can contain as many as 10 canaries . You can have as many as 20 groups in your account . Any single canary can be a member of up to 10 %% groups. create_group(Client, Input) -> create_group(Client, Input, []). create_group(Client, Input0, Options0) -> Method = post, Path = ["/group"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Permanently deletes the specified canary. %% If you specify ` DeleteLambda ' to ` true ' , CloudWatch Synthetics %% also deletes the Lambda functions and layers that are used by the canary. %% %% Other resources used and created by the canary are not automatically %% deleted. After you delete a canary that you do not intend to use again, %% you should also delete the following: %% < ul > < li > The CloudWatch alarms created for this canary . These alarms have %% a name of `Synthetics-SharpDrop-Alarm-MyCanaryName '. %% %% </li> <li> Amazon S3 objects and buckets, such as the canary's %% artifact location. %% < /li > < li > IAM roles created for the canary . If they were created in the %% console, these roles have the name ` %% role/service-role/CloudWatchSyntheticsRole-MyCanaryName '. %% %% </li> <li> CloudWatch Logs log groups created for the canary. These logs groups have the name ` /aws / lambda / cwsyn - MyCanaryName ' . %% %% </li> </ul> Before you delete a canary, you might want to use ` GetCanary ' to display the information about this canary . Make note of %% the information returned by this operation so that you can delete these %% resources after you delete the canary. delete_canary(Client, Name, Input) -> delete_canary(Client, Name, Input, []). delete_canary(Client, Name, Input0, Options0) -> Method = delete, Path = ["/canary/", aws_util:encode_uri(Name), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"deleteLambda">>, <<"DeleteLambda">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Deletes a group. %% %% The group doesn't need to be empty to be deleted. If there are %% canaries in the group, they are not deleted when you delete the group. %% Groups are a global resource that appear in all Regions , but the request %% to delete a group must be made from its home Region. You can find the home Region of a group within its ARN . delete_group(Client, GroupIdentifier, Input) -> delete_group(Client, GroupIdentifier, Input, []). delete_group(Client, GroupIdentifier, Input0, Options0) -> Method = delete, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc This operation returns a list of the canaries in your account, along %% with full details about each canary. %% This operation supports resource - level authorization using an IAM policy %% and the `Names' parameter. If you specify the `Names' parameter, %% the operation is successful only if you have authorization to view all the %% canaries that you specify in your request. If you do not have permission to view any of the canaries , the request fails with a 403 response . %% %% You are required to use the `Names' parameter if you are logged on to a user or role that has an IAM policy that restricts which canaries that %% you are allowed to view. For more information, see Limiting a user to %% viewing specific canaries. describe_canaries(Client, Input) -> describe_canaries(Client, Input, []). describe_canaries(Client, Input0, Options0) -> Method = post, Path = ["/canaries"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Use this operation to see information from the most recent run of %% each canary that you have created. %% This operation supports resource - level authorization using an IAM policy %% and the `Names' parameter. If you specify the `Names' parameter, %% the operation is successful only if you have authorization to view all the %% canaries that you specify in your request. If you do not have permission to view any of the canaries , the request fails with a 403 response . %% %% You are required to use the `Names' parameter if you are logged on to a user or role that has an IAM policy that restricts which canaries that %% you are allowed to view. For more information, see Limiting a user to %% viewing specific canaries. describe_canaries_last_run(Client, Input) -> describe_canaries_last_run(Client, Input, []). describe_canaries_last_run(Client, Input0, Options0) -> Method = post, Path = ["/canaries/last-run"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Returns a list of Synthetics canary runtime versions. %% For more information , see Canary Runtime Versions . describe_runtime_versions(Client, Input) -> describe_runtime_versions(Client, Input, []). describe_runtime_versions(Client, Input0, Options0) -> Method = post, Path = ["/runtime-versions"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Removes a canary from a group. %% You must run this operation in the Region where the canary exists . disassociate_resource(Client, GroupIdentifier, Input) -> disassociate_resource(Client, GroupIdentifier, Input, []). disassociate_resource(Client, GroupIdentifier, Input0, Options0) -> Method = patch, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), "/disassociate"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Retrieves complete information about one canary . %% %% You must specify the name of the canary that you want. To get a list of canaries and their names , use DescribeCanaries . get_canary(Client, Name) when is_map(Client) -> get_canary(Client, Name, #{}, #{}). get_canary(Client, Name, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_canary(Client, Name, QueryMap, HeadersMap, []). get_canary(Client, Name, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/canary/", aws_util:encode_uri(Name), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Retrieves a list of runs for a specified canary. get_canary_runs(Client, Name, Input) -> get_canary_runs(Client, Name, Input, []). get_canary_runs(Client, Name, Input0, Options0) -> Method = post, Path = ["/canary/", aws_util:encode_uri(Name), "/runs"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Returns information about one group . %% Groups are a global resource , so you can use this operation from any %% Region. get_group(Client, GroupIdentifier) when is_map(Client) -> get_group(Client, GroupIdentifier, #{}, #{}). get_group(Client, GroupIdentifier, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_group(Client, GroupIdentifier, QueryMap, HeadersMap, []). get_group(Client, GroupIdentifier, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/group/", aws_util:encode_uri(GroupIdentifier), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of the groups that the specified canary is associated %% with. %% %% The canary that you specify must be in the current Region. list_associated_groups(Client, ResourceArn, Input) -> list_associated_groups(Client, ResourceArn, Input, []). list_associated_groups(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/resource/", aws_util:encode_uri(ResourceArn), "/groups"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc This operation returns a list of the ARNs of the canaries that are %% associated with the specified group. list_group_resources(Client, GroupIdentifier, Input) -> list_group_resources(Client, GroupIdentifier, Input, []). list_group_resources(Client, GroupIdentifier, Input0, Options0) -> Method = post, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), "/resources"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Returns a list of all groups in the account, displaying their names, %% unique IDs, and ARNs. %% The groups from all Regions are returned . list_groups(Client, Input) -> list_groups(Client, Input, []). list_groups(Client, Input0, Options0) -> Method = post, Path = ["/groups"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Displays the tags associated with a canary or group. list_tags_for_resource(Client, ResourceArn) when is_map(Client) -> list_tags_for_resource(Client, ResourceArn, #{}, #{}). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Use this operation to run a canary that has already been created. %% %% The frequency of the canary runs is determined by the value of the %% canary's `Schedule'. To see a canary's schedule, use GetCanary . start_canary(Client, Name, Input) -> start_canary(Client, Name, Input, []). start_canary(Client, Name, Input0, Options0) -> Method = post, Path = ["/canary/", aws_util:encode_uri(Name), "/start"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Stops the canary to prevent all future runs. %% %% If the canary is currently running,the run that is in progress completes %% on its own, publishes metrics, and uploads artifacts, but it is not recorded in Synthetics as a completed run . %% You can use ` StartCanary ' to start it running again with the canary ’s %% current schedule at any point in the future. stop_canary(Client, Name, Input) -> stop_canary(Client, Name, Input, []). stop_canary(Client, Name, Input0, Options0) -> Method = post, Path = ["/canary/", aws_util:encode_uri(Name), "/stop"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Assigns one or more tags ( key - value pairs ) to the specified canary or %% group. %% %% Tags can help you organize and categorize your resources. You can also use %% them to scope user permissions, by granting a user permission to access or %% change only resources with certain tag values. %% Tags do n't have any semantic meaning to Amazon Web Services and are %% interpreted strictly as strings of characters. %% You can use the ` TagResource ' action with a resource that already has %% tags. If you specify a new tag key for the resource, this tag is appended %% to the list of tags associated with the resource. If you specify a tag key %% that is already associated with the resource, the new tag value that you %% specify replaces the previous value for that tag. %% You can associate as many as 50 tags with a canary or group . tag_resource(Client, ResourceArn, Input) -> tag_resource(Client, ResourceArn, Input, []). tag_resource(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Removes one or more tags from the specified resource . untag_resource(Client, ResourceArn, Input) -> untag_resource(Client, ResourceArn, Input, []). untag_resource(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates the configuration of a canary that has already been created. %% %% You can't use this operation to update the tags of an existing canary. To change the tags of an existing canary , use TagResource . update_canary(Client, Name, Input) -> update_canary(Client, Name, Input, []). update_canary(Client, Name, Input0, Options0) -> Method = patch, Path = ["/canary/", aws_util:encode_uri(Name), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %%==================================================================== Internal functions %%==================================================================== -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"synthetics">>}, Host = build_host(<<"synthetics">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
null
https://raw.githubusercontent.com/aws-beam/aws-erlang/699287cee7dfc9dc8c08ced5f090dcc192c9cba8/src/aws_synthetics.erl
erlang
WARNING: DO NOT EDIT, AUTO-GENERATED CODE! services. You can create and manage canaries, which are modular, lightweight scripts that monitor your endpoints and APIs from the outside-in. You can set up you check the availability and latency of your web services and troubleshoot anomalies by investigating load time data, screenshots of the applications. For more information, see Using ServiceLens to Monitor the Before you create and manage canaries, be aware of the security considerations. For more information, see Security Considerations for Synthetics Canaries. ==================================================================== API ==================================================================== @doc Associates a canary with a group. Using groups can help you with managing and automating your canaries, and you can also view aggregated run results and statistics for all canaries in a group. @doc Creates a canary. Canaries are scripts that monitor your endpoints and APIs from the web services and troubleshoot anomalies by investigating load time data, screenshots of the UI, logs, and metrics. You can set up a canary to run continuously or just once. Necessary Roles and Permissions. Do not include secrets or proprietary information in your canary names. more information, see Security Considerations for Synthetics Canaries. @doc Creates a group which you can use to associate canaries with each other, including cross-Region canaries. Using groups can help you with managing and automating your canaries, and you can also view aggregated run results and statistics for all canaries in a group. name where it was created, a group is not constrained to any Region. This and then use that group to view and manage all of those canaries in a single view. Region. groups. @doc Permanently deletes the specified canary. also deletes the Lambda functions and layers that are used by the canary. Other resources used and created by the canary are not automatically deleted. After you delete a canary that you do not intend to use again, you should also delete the following: a name of `Synthetics-SharpDrop-Alarm-MyCanaryName '. </li> <li> Amazon S3 objects and buckets, such as the canary's artifact location. console, these roles have the name ` role/service-role/CloudWatchSyntheticsRole-MyCanaryName '. </li> <li> CloudWatch Logs log groups created for the canary. These logs </li> </ul> Before you delete a canary, you might want to use the information returned by this operation so that you can delete these resources after you delete the canary. @doc Deletes a group. The group doesn't need to be empty to be deleted. If there are canaries in the group, they are not deleted when you delete the group. to delete a group must be made from its home Region. You can find the home @doc This operation returns a list of the canaries in your account, along with full details about each canary. and the `Names' parameter. If you specify the `Names' parameter, the operation is successful only if you have authorization to view all the canaries that you specify in your request. If you do not have permission You are required to use the `Names' parameter if you are logged on to you are allowed to view. For more information, see Limiting a user to viewing specific canaries. @doc Use this operation to see information from the most recent run of each canary that you have created. and the `Names' parameter. If you specify the `Names' parameter, the operation is successful only if you have authorization to view all the canaries that you specify in your request. If you do not have permission You are required to use the `Names' parameter if you are logged on to you are allowed to view. For more information, see Limiting a user to viewing specific canaries. @doc Returns a list of Synthetics canary runtime versions. @doc Removes a canary from a group. You must specify the name of the canary that you want. To get a list of @doc Retrieves a list of runs for a specified canary. Region. @doc Returns a list of the groups that the specified canary is associated with. The canary that you specify must be in the current Region. @doc This operation returns a list of the ARNs of the canaries that are associated with the specified group. @doc Returns a list of all groups in the account, displaying their names, unique IDs, and ARNs. @doc Displays the tags associated with a canary or group. @doc Use this operation to run a canary that has already been created. The frequency of the canary runs is determined by the value of the canary's `Schedule'. To see a canary's schedule, use @doc Stops the canary to prevent all future runs. If the canary is currently running,the run that is in progress completes on its own, publishes metrics, and uploads artifacts, but it is not current schedule at any point in the future. group. Tags can help you organize and categorize your resources. You can also use them to scope user permissions, by granting a user permission to access or change only resources with certain tag values. interpreted strictly as strings of characters. tags. If you specify a new tag key for the resource, this tag is appended to the list of tags associated with the resource. If you specify a tag key that is already associated with the resource, the new tag value that you specify replaces the previous value for that tag. @doc Updates the configuration of a canary that has already been created. You can't use this operation to update the tags of an existing canary. ==================================================================== ====================================================================
See -beam/aws-codegen for more details . @doc Amazon CloudWatch Synthetics You can use Amazon CloudWatch Synthetics to continually monitor your your canaries to run 24 hours a day , once per minute . The canaries help UI , logs , and metrics . The canaries seamlessly integrate with CloudWatch ServiceLens to help you trace the causes of impacted nodes in your Health of Your Applications in the Amazon CloudWatch User Guide . -module(aws_synthetics). -export([associate_resource/3, associate_resource/4, create_canary/2, create_canary/3, create_group/2, create_group/3, delete_canary/3, delete_canary/4, delete_group/3, delete_group/4, describe_canaries/2, describe_canaries/3, describe_canaries_last_run/2, describe_canaries_last_run/3, describe_runtime_versions/2, describe_runtime_versions/3, disassociate_resource/3, disassociate_resource/4, get_canary/2, get_canary/4, get_canary/5, get_canary_runs/3, get_canary_runs/4, get_group/2, get_group/4, get_group/5, list_associated_groups/3, list_associated_groups/4, list_group_resources/3, list_group_resources/4, list_groups/2, list_groups/3, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, start_canary/3, start_canary/4, stop_canary/3, stop_canary/4, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4, update_canary/3, update_canary/4]). -include_lib("hackney/include/hackney_lib.hrl"). You must run this operation in the Region where the canary exists . associate_resource(Client, GroupIdentifier, Input) -> associate_resource(Client, GroupIdentifier, Input, []). associate_resource(Client, GroupIdentifier, Input0, Options0) -> Method = patch, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), "/associate"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). outside - in . Canaries help you check the availability and latency of your Do not use ` CreateCanary ' to modify an existing canary . Use UpdateCanary instead . To create canaries , you must have the ` ' policy . If you are creating a new IAM role for the canary , you also need the ` iam : CreateRole ' , ` iam : CreatePolicy ' and ` iam : ' permissions . For more information , see The canary name makes up part of the Amazon Resource Name ( ARN ) for the canary , and the ARN is included in outbound calls over the internet . For create_canary(Client, Input) -> create_canary(Client, Input, []). create_canary(Client, Input0, Options0) -> Method = post, Path = ["/canary"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Groups are global resources . When you create a group , it is replicated across Amazon Web Services Regions , and you can view it and add canaries to it from any Region . Although the group ARN format reflects the Region means that you can put canaries from multiple Regions into the same group , Groups are supported in all Regions except the Regions that are disabled by default . For more information about these Regions , see Enabling a Each group can contain as many as 10 canaries . You can have as many as 20 groups in your account . Any single canary can be a member of up to 10 create_group(Client, Input) -> create_group(Client, Input, []). create_group(Client, Input0, Options0) -> Method = post, Path = ["/group"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). If you specify ` DeleteLambda ' to ` true ' , CloudWatch Synthetics < ul > < li > The CloudWatch alarms created for this canary . These alarms have < /li > < li > IAM roles created for the canary . If they were created in the groups have the name ` /aws / lambda / cwsyn - MyCanaryName ' . ` GetCanary ' to display the information about this canary . Make note of delete_canary(Client, Name, Input) -> delete_canary(Client, Name, Input, []). delete_canary(Client, Name, Input0, Options0) -> Method = delete, Path = ["/canary/", aws_util:encode_uri(Name), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"deleteLambda">>, <<"DeleteLambda">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Groups are a global resource that appear in all Regions , but the request Region of a group within its ARN . delete_group(Client, GroupIdentifier, Input) -> delete_group(Client, GroupIdentifier, Input, []). delete_group(Client, GroupIdentifier, Input0, Options0) -> Method = delete, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). This operation supports resource - level authorization using an IAM policy to view any of the canaries , the request fails with a 403 response . a user or role that has an IAM policy that restricts which canaries that describe_canaries(Client, Input) -> describe_canaries(Client, Input, []). describe_canaries(Client, Input0, Options0) -> Method = post, Path = ["/canaries"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). This operation supports resource - level authorization using an IAM policy to view any of the canaries , the request fails with a 403 response . a user or role that has an IAM policy that restricts which canaries that describe_canaries_last_run(Client, Input) -> describe_canaries_last_run(Client, Input, []). describe_canaries_last_run(Client, Input0, Options0) -> Method = post, Path = ["/canaries/last-run"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). For more information , see Canary Runtime Versions . describe_runtime_versions(Client, Input) -> describe_runtime_versions(Client, Input, []). describe_runtime_versions(Client, Input0, Options0) -> Method = post, Path = ["/runtime-versions"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). You must run this operation in the Region where the canary exists . disassociate_resource(Client, GroupIdentifier, Input) -> disassociate_resource(Client, GroupIdentifier, Input, []). disassociate_resource(Client, GroupIdentifier, Input0, Options0) -> Method = patch, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), "/disassociate"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Retrieves complete information about one canary . canaries and their names , use DescribeCanaries . get_canary(Client, Name) when is_map(Client) -> get_canary(Client, Name, #{}, #{}). get_canary(Client, Name, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_canary(Client, Name, QueryMap, HeadersMap, []). get_canary(Client, Name, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/canary/", aws_util:encode_uri(Name), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). get_canary_runs(Client, Name, Input) -> get_canary_runs(Client, Name, Input, []). get_canary_runs(Client, Name, Input0, Options0) -> Method = post, Path = ["/canary/", aws_util:encode_uri(Name), "/runs"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Returns information about one group . Groups are a global resource , so you can use this operation from any get_group(Client, GroupIdentifier) when is_map(Client) -> get_group(Client, GroupIdentifier, #{}, #{}). get_group(Client, GroupIdentifier, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_group(Client, GroupIdentifier, QueryMap, HeadersMap, []). get_group(Client, GroupIdentifier, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/group/", aws_util:encode_uri(GroupIdentifier), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_associated_groups(Client, ResourceArn, Input) -> list_associated_groups(Client, ResourceArn, Input, []). list_associated_groups(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/resource/", aws_util:encode_uri(ResourceArn), "/groups"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). list_group_resources(Client, GroupIdentifier, Input) -> list_group_resources(Client, GroupIdentifier, Input, []). list_group_resources(Client, GroupIdentifier, Input0, Options0) -> Method = post, Path = ["/group/", aws_util:encode_uri(GroupIdentifier), "/resources"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). The groups from all Regions are returned . list_groups(Client, Input) -> list_groups(Client, Input, []). list_groups(Client, Input0, Options0) -> Method = post, Path = ["/groups"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). list_tags_for_resource(Client, ResourceArn) when is_map(Client) -> list_tags_for_resource(Client, ResourceArn, #{}, #{}). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). GetCanary . start_canary(Client, Name, Input) -> start_canary(Client, Name, Input, []). start_canary(Client, Name, Input0, Options0) -> Method = post, Path = ["/canary/", aws_util:encode_uri(Name), "/start"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). recorded in Synthetics as a completed run . You can use ` StartCanary ' to start it running again with the canary ’s stop_canary(Client, Name, Input) -> stop_canary(Client, Name, Input, []). stop_canary(Client, Name, Input0, Options0) -> Method = post, Path = ["/canary/", aws_util:encode_uri(Name), "/stop"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Assigns one or more tags ( key - value pairs ) to the specified canary or Tags do n't have any semantic meaning to Amazon Web Services and are You can use the ` TagResource ' action with a resource that already has You can associate as many as 50 tags with a canary or group . tag_resource(Client, ResourceArn, Input) -> tag_resource(Client, ResourceArn, Input, []). tag_resource(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Removes one or more tags from the specified resource . untag_resource(Client, ResourceArn, Input) -> untag_resource(Client, ResourceArn, Input, []). untag_resource(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). To change the tags of an existing canary , use TagResource . update_canary(Client, Name, Input) -> update_canary(Client, Name, Input, []). update_canary(Client, Name, Input0, Options0) -> Method = patch, Path = ["/canary/", aws_util:encode_uri(Name), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Internal functions -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"synthetics">>}, Host = build_host(<<"synthetics">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
ed4d1eafc57a406c7d93e332be3a34bdd1146437983e7965405822c5053d368b
Shen-Language/shen-cl
overwrite.lsp
Copyright ( c ) 2010 - 2015 , ; 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. 3 . The name of may not be used to endorse or promote products ; derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY 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 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 :shen) (defvar |shen-cl.kernel-sysfunc?| (fdefinition '|shen.sysfunc?|)) (defun |shen.sysfunc?| (symbol) (if (not (symbolp symbol)) '|false| (|or| (|shen-cl.lisp-prefixed?| symbol) (apply |shen-cl.kernel-sysfunc?| (list symbol))))) (defun shen.pvar? (x) (if (and (arrayp x) (not (stringp x)) (eq (svref x 0) '|shen.pvar|)) '|true| '|false|)) (defvar specials (coerce "=*/+-_?$!@~><&%{}:;`#'." 'list)) (defun symbol-characterp (c) (or (alphanumericp c) (not (null (member c specials))))) (defun |shen.analyse-symbol?| (s) (if (and (> (length s) 0) (not (digit-char-p (char s 0))) (symbol-characterp (char s 0)) (every #'symbol-characterp s)) '|true| '|false|)) (defun |symbol?| (val) (if (and (symbolp val) (not (null val)) (not (eq t val)) (not (eq val '|true|)) (not (eq val '|false|))) (|shen.analyse-symbol?| (|str| val)) '|false|)) (defun |variable?| (val) (if (and (symbolp val) (not (null val)) (not (eq t val)) (not (eq val '|true|)) (not (eq val '|false|)) (upper-case-p (char (symbol-name val) 0)) (every #'symbol-characterp (symbol-name val))) '|true| '|false|)) (defun |shen.lazyderef| (x process-n) (if (and (arrayp x) (not (stringp x)) (eq (svref x 0) '|shen.pvar|)) (let ((value (|shen.valvector| x process-n))) (if (eq value '|shen.-null-|) x (|shen.lazyderef| value process-n))) x)) (defun |shen.valvector| (var process-n) (svref (svref |shen.*prologvectors*| process-n) (svref var 1))) (defun |shen.unbindv| (var n) (let ((vector (svref |shen.*prologvectors*| n))) (setf (svref vector (svref var 1)) '|shen.-null-|))) (defun |shen.bindv| (var val n) (let ((vector (svref |shen.*prologvectors*| n))) (setf (svref vector (svref var 1)) val))) (defun |shen.copy-vector-stage-1| (count vector big-vector max) (if (= max count) big-vector (|shen.copy-vector-stage-1| (1+ count) vector (|address->| big-vector count (|<-address| vector count)) max))) (defun |shen.copy-vector-stage-2| (count max fill big-vector) (if (= max count) big-vector (|shen.copy-vector-stage-2| (1+ count) max fill (|address->| big-vector count fill)))) (defun |shen.newpv| (n) (let ((count+1 (1+ (the integer (svref |shen.*varcounter*| n)))) (vector (svref |shen.*prologvectors*| n))) (setf (svref |shen.*varcounter*| n) count+1) (if (= (the integer count+1) (the integer (|limit| vector))) (|shen.resizeprocessvector| n count+1) '|skip|) (|shen.mk-pvar| count+1))) (defun |vector->| (vector n x) (if (zerop n) (error "cannot access 0th element of a vector~%") (|address->| vector n x))) (defun |<-vector| (vector n) (if (zerop n) (error "cannot access 0th element of a vector~%") (let ((vector-element (svref vector n))) (if (eq vector-element (|fail|)) (error "vector element not found~%") vector-element)))) (defun |variable?| (x) (if (and (symbolp x) (not (null x)) (upper-case-p (char (symbol-name x) 0))) '|true| '|false|)) (defun |shen.+string?| (x) (if (and (stringp x) (not (string-equal x ""))) '|true| '|false|)) (defun |thaw| (f) (funcall f)) (defun |hash| (val bound) (mod (sxhash val) bound)) (defun |shen.dict| (size) (make-hash-table :size size)) (defun |shen.dict?| (dict) (if (hash-table-p dict) '|true| '|false|)) (defun |shen.dict-count| (dict) (hash-table-count dict)) (defun |shen.dict->| (dict key value) (setf (gethash key dict) value)) (defun |shen.<-dict| (dict key) (multiple-value-bind (result found) (gethash key dict) (if found result (error "value ~A not found in dict~%" key)))) (defun |shen.dict-rm| (dict key) (progn (remhash key dict) key)) (defun |shen.dict-fold| (f dict init) (let ((acc init)) (maphash #'(lambda (k v) (setf acc (funcall (funcall (funcall f k) v) acc))) dict) acc)) #+clisp (defun |cl.exit| (code) (ext:exit code)) #+(and ccl (not windows)) (defun |cl.exit| (code) (ccl:quit code)) #+(and ccl windows) (ccl::eval (ccl::read-from-string "(defun |cl.exit| (code) (#__exit code))")) #+ecl (defun |cl.exit| (code) (si:quit code)) #+sbcl (defun |cl.exit| (code) (alien-funcall (extern-alien "exit" (function void int)) code)) (defun |shen-cl.exit| (code) (|cl.exit| code)) (defun |shen-cl.initialise| () (progn (|shen-cl.initialise-compiler|) (|put| '|cl.exit| '|arity| 1 |*property-vector*|) (|put| '|shen-cl.exit| '|arity| 1 |*property-vector*|) (|declare| '|cl.exit| (list '|number| '--> '|unit|)) (|declare| '|shen-cl.exit| (list '|number| '--> '|unit|)) (|shen-cl.read-eval| "(defmacro cl.exit-macro [cl.exit] -> [cl.exit 0])") (|shen-cl.read-eval| "(defmacro shen-cl.exit-macro [shen-cl.exit] -> [cl.exit 0])"))) #+(or ccl sbcl) (defun |shen.read-char-code| (s) (let ((c (read-char s nil -1))) (if (eq c -1) -1 (char-int c)))) #+(or ccl sbcl) (defun |pr| (x s) (write-string x s) (when (or (eq s |*stoutput*|) (eq s |*stinput*|)) (force-output s)) x) ;; file reading (defun |read-file-as-bytelist| (path) (with-open-file (stream (format nil "~A~A" |*home-directory*| path) :direction :input :element-type 'unsigned-byte) (let ((data (make-array (file-length stream) :element-type 'unsigned-byte :initial-element 0))) (read-sequence data stream) (coerce data 'list)))) (defun |shen.read-file-as-charlist| (path) (|read-file-as-bytelist| path)) (defun |shen.read-file-as-string| (path) (with-open-file (stream (format nil "~A~A" |*home-directory*| path) :direction :input) (let ((data (make-string (file-length stream)))) (read-sequence data stream) data))) ;; tuples (defun |@p| (x y) (vector '|shen.tuple| x y)) ;; vectors (defun |vector| (n) (let ((vec (make-array (1+ n) :initial-element (|fail|)))) (setf (svref vec 0) n) vec)) ; Amend the REPL credits message to explain exit command (setf (symbol-function '|shen-cl.original-credits|) #'|shen.credits|) (defun |shen.credits| () (|shen-cl.original-credits|) (format t "exit REPL with (cl.exit)")) Compiler functions (defun |shen-cl.cl| (symbol) (let* ((str (symbol-name symbol)) (lispname (string-upcase str))) (|intern| lispname))) (defun |shen-cl.lisp-prefixed?| (symbol) (|shen-cl.lisp-true?| (and (not (null symbol)) (symbolp symbol) (|shen-cl.prefix?| (symbol-name symbol) "lisp.")))) (defun |shen-cl.remove-lisp-prefix| (symbol) (|intern| (subseq (symbol-name symbol) 5)))
null
https://raw.githubusercontent.com/Shen-Language/shen-cl/c26776641fe4b63aacfbc6013fad9c1c16974a5e/src/overwrite.lsp
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: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. derived from this software without specific prior written permission. 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. file reading tuples vectors Amend the REPL credits message to explain exit command
Copyright ( c ) 2010 - 2015 , 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright 3 . The name of may not be used to endorse or promote products THIS SOFTWARE IS PROVIDED BY AS IS '' AND ANY DISCLAIMED . IN NO EVENT SHALL FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (in-package :shen) (defvar |shen-cl.kernel-sysfunc?| (fdefinition '|shen.sysfunc?|)) (defun |shen.sysfunc?| (symbol) (if (not (symbolp symbol)) '|false| (|or| (|shen-cl.lisp-prefixed?| symbol) (apply |shen-cl.kernel-sysfunc?| (list symbol))))) (defun shen.pvar? (x) (if (and (arrayp x) (not (stringp x)) (eq (svref x 0) '|shen.pvar|)) '|true| '|false|)) (defvar specials (coerce "=*/+-_?$!@~><&%{}:;`#'." 'list)) (defun symbol-characterp (c) (or (alphanumericp c) (not (null (member c specials))))) (defun |shen.analyse-symbol?| (s) (if (and (> (length s) 0) (not (digit-char-p (char s 0))) (symbol-characterp (char s 0)) (every #'symbol-characterp s)) '|true| '|false|)) (defun |symbol?| (val) (if (and (symbolp val) (not (null val)) (not (eq t val)) (not (eq val '|true|)) (not (eq val '|false|))) (|shen.analyse-symbol?| (|str| val)) '|false|)) (defun |variable?| (val) (if (and (symbolp val) (not (null val)) (not (eq t val)) (not (eq val '|true|)) (not (eq val '|false|)) (upper-case-p (char (symbol-name val) 0)) (every #'symbol-characterp (symbol-name val))) '|true| '|false|)) (defun |shen.lazyderef| (x process-n) (if (and (arrayp x) (not (stringp x)) (eq (svref x 0) '|shen.pvar|)) (let ((value (|shen.valvector| x process-n))) (if (eq value '|shen.-null-|) x (|shen.lazyderef| value process-n))) x)) (defun |shen.valvector| (var process-n) (svref (svref |shen.*prologvectors*| process-n) (svref var 1))) (defun |shen.unbindv| (var n) (let ((vector (svref |shen.*prologvectors*| n))) (setf (svref vector (svref var 1)) '|shen.-null-|))) (defun |shen.bindv| (var val n) (let ((vector (svref |shen.*prologvectors*| n))) (setf (svref vector (svref var 1)) val))) (defun |shen.copy-vector-stage-1| (count vector big-vector max) (if (= max count) big-vector (|shen.copy-vector-stage-1| (1+ count) vector (|address->| big-vector count (|<-address| vector count)) max))) (defun |shen.copy-vector-stage-2| (count max fill big-vector) (if (= max count) big-vector (|shen.copy-vector-stage-2| (1+ count) max fill (|address->| big-vector count fill)))) (defun |shen.newpv| (n) (let ((count+1 (1+ (the integer (svref |shen.*varcounter*| n)))) (vector (svref |shen.*prologvectors*| n))) (setf (svref |shen.*varcounter*| n) count+1) (if (= (the integer count+1) (the integer (|limit| vector))) (|shen.resizeprocessvector| n count+1) '|skip|) (|shen.mk-pvar| count+1))) (defun |vector->| (vector n x) (if (zerop n) (error "cannot access 0th element of a vector~%") (|address->| vector n x))) (defun |<-vector| (vector n) (if (zerop n) (error "cannot access 0th element of a vector~%") (let ((vector-element (svref vector n))) (if (eq vector-element (|fail|)) (error "vector element not found~%") vector-element)))) (defun |variable?| (x) (if (and (symbolp x) (not (null x)) (upper-case-p (char (symbol-name x) 0))) '|true| '|false|)) (defun |shen.+string?| (x) (if (and (stringp x) (not (string-equal x ""))) '|true| '|false|)) (defun |thaw| (f) (funcall f)) (defun |hash| (val bound) (mod (sxhash val) bound)) (defun |shen.dict| (size) (make-hash-table :size size)) (defun |shen.dict?| (dict) (if (hash-table-p dict) '|true| '|false|)) (defun |shen.dict-count| (dict) (hash-table-count dict)) (defun |shen.dict->| (dict key value) (setf (gethash key dict) value)) (defun |shen.<-dict| (dict key) (multiple-value-bind (result found) (gethash key dict) (if found result (error "value ~A not found in dict~%" key)))) (defun |shen.dict-rm| (dict key) (progn (remhash key dict) key)) (defun |shen.dict-fold| (f dict init) (let ((acc init)) (maphash #'(lambda (k v) (setf acc (funcall (funcall (funcall f k) v) acc))) dict) acc)) #+clisp (defun |cl.exit| (code) (ext:exit code)) #+(and ccl (not windows)) (defun |cl.exit| (code) (ccl:quit code)) #+(and ccl windows) (ccl::eval (ccl::read-from-string "(defun |cl.exit| (code) (#__exit code))")) #+ecl (defun |cl.exit| (code) (si:quit code)) #+sbcl (defun |cl.exit| (code) (alien-funcall (extern-alien "exit" (function void int)) code)) (defun |shen-cl.exit| (code) (|cl.exit| code)) (defun |shen-cl.initialise| () (progn (|shen-cl.initialise-compiler|) (|put| '|cl.exit| '|arity| 1 |*property-vector*|) (|put| '|shen-cl.exit| '|arity| 1 |*property-vector*|) (|declare| '|cl.exit| (list '|number| '--> '|unit|)) (|declare| '|shen-cl.exit| (list '|number| '--> '|unit|)) (|shen-cl.read-eval| "(defmacro cl.exit-macro [cl.exit] -> [cl.exit 0])") (|shen-cl.read-eval| "(defmacro shen-cl.exit-macro [shen-cl.exit] -> [cl.exit 0])"))) #+(or ccl sbcl) (defun |shen.read-char-code| (s) (let ((c (read-char s nil -1))) (if (eq c -1) -1 (char-int c)))) #+(or ccl sbcl) (defun |pr| (x s) (write-string x s) (when (or (eq s |*stoutput*|) (eq s |*stinput*|)) (force-output s)) x) (defun |read-file-as-bytelist| (path) (with-open-file (stream (format nil "~A~A" |*home-directory*| path) :direction :input :element-type 'unsigned-byte) (let ((data (make-array (file-length stream) :element-type 'unsigned-byte :initial-element 0))) (read-sequence data stream) (coerce data 'list)))) (defun |shen.read-file-as-charlist| (path) (|read-file-as-bytelist| path)) (defun |shen.read-file-as-string| (path) (with-open-file (stream (format nil "~A~A" |*home-directory*| path) :direction :input) (let ((data (make-string (file-length stream)))) (read-sequence data stream) data))) (defun |@p| (x y) (vector '|shen.tuple| x y)) (defun |vector| (n) (let ((vec (make-array (1+ n) :initial-element (|fail|)))) (setf (svref vec 0) n) vec)) (setf (symbol-function '|shen-cl.original-credits|) #'|shen.credits|) (defun |shen.credits| () (|shen-cl.original-credits|) (format t "exit REPL with (cl.exit)")) Compiler functions (defun |shen-cl.cl| (symbol) (let* ((str (symbol-name symbol)) (lispname (string-upcase str))) (|intern| lispname))) (defun |shen-cl.lisp-prefixed?| (symbol) (|shen-cl.lisp-true?| (and (not (null symbol)) (symbolp symbol) (|shen-cl.prefix?| (symbol-name symbol) "lisp.")))) (defun |shen-cl.remove-lisp-prefix| (symbol) (|intern| (subseq (symbol-name symbol) 5)))
d429a9c40247377f796dac80ebd393ea380b05577ca3d83a4a1a8a205d08b73a
eponai/sulolive
query.cljc
(ns eponai.common.database.query (:require [taoensso.timbre :refer [error debug trace info warn]] [eponai.common.database :as db] [datascript.db] [eponai.common.parser.util :as parser])) (defn project [] {:where '[[?e :project/uuid]]}) (defn project-with-uuid [project-uuid] ;; Harder to check if it's actually a uuid. {:pre [(not (string? project-uuid))]} {:where '[[?e :project/uuid ?project-uuid]] :symbols {'?project-uuid project-uuid}}) (defn with-auth [query user-uuid] (db/merge-query query {:where '[[?u :user/uuid ?user-uuid]] :symbols {'?user-uuid user-uuid}})) (defn project-with-auth [user-uuid] (with-auth {:where '[[?e :project/users ?u]]} user-uuid)) (defn verifications [db user-db-id status] {:pre [(db/database? db) (number? user-db-id) (keyword? status)]} (db/q '[:find [?v ...] :in $ ?u ?s :where [?v :verification/entity ?u] [?u :user/email ?e] [?v :verification/value ?e] [?v :verification/status ?s]] db user-db-id status)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Transactions # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (defn transaction-entity-query [{:keys [project-eid user-uuid]}] (assert (some? user-uuid) "User UUID must be supplied to read transactions.") (assert (number? project-eid) (str "Project eid must be a number to read transactions. Was: " project-eid)) {:where '[[?u :user/uuid ?user-uuid] [?p :project/users ?u] [?e :transaction/project ?p]] :symbols {'?user-uuid user-uuid '?p project-eid}}) (defn transaction-with-conversion-fn [db transaction-convs user-convs] {:pre [(delay? transaction-convs) (delay? user-convs)]} (let [approx-tx-conv (memoize (fn [curr] (or (some->> curr (get @transaction-convs) (first) (val)) (when curr (db/one-with db {:where [['?e :conversion/currency curr]]}))))) approx-user-curr (memoize (fn [] (some-> @user-convs (first) (val))))] (fn [transaction] (let [tx-date (get-in transaction [:transaction/date :db/id]) curr->conv (fn [curr] (or (get-in @transaction-convs [curr tx-date]) (approx-tx-conv curr))) tx-curr (get-in transaction [:transaction/currency :db/id]) tx-conv (curr->conv tx-curr) user-conv (get @user-convs tx-date) user-conv (or user-conv (approx-user-curr))] (if (and (some? tx-conv) (some? user-conv)) (let [;; All rates are relative USD so we need to pull what rates the user currency has, ;; so we can convert the rate appropriately for the user's selected currency conv->rate (fn [conv] (let [transaction-conversion (db/entity* db conv) user-currency-conversion (db/entity* db user-conv) #?@(:cljs [rate (/ (:conversion/rate transaction-conversion) (:conversion/rate user-currency-conversion))] :clj [rate (with-precision 10 (bigdec (/ (:conversion/rate transaction-conversion) (:conversion/rate user-currency-conversion))))])] rate)) curr->conversion-map (fn [curr] (when curr (let [conv (curr->conv curr) rate (conv->rate conv)] {:conversion/currency {:db/id curr} :conversion/rate rate :conversion/date (:conversion/date (db/entity* db conv))})))] ;; Convert the rate from USD to whatever currency the user has set ( e.g. user is using SEK , so the new rate will be ;; conversion-of-transaction-currency / conversion-of-user-currency [(:db/id transaction) (merge (curr->conversion-map tx-curr) {:user-conversion-id user-conv :transaction-conversion-id tx-conv ::currency-to-conversion-map-fn curr->conversion-map})]) (debug "No tx-conv or user-conv. Tx-conv: " tx-conv " user-conv: " user-conv " for transaction: " (into {} transaction))))))) (defn absolute-fee? [fee] #(= :transaction.fee.type/absolute (:transaction.fee/type fee))) (defn same-conversions? [db user-curr] (let [user-conv->user-curr (memoize (fn [user-conv] (get-in (db/entity* db user-conv) [:conversion/currency :db/id])))] (fn [tx] (letfn [(same-conversion? [currency conversion] (and (= user-curr (user-conv->user-curr (:user-conversion-id conversion))) (= (get-in currency [:db/id]) (get-in conversion [:conversion/currency :db/id]))))] (every? (fn [[curr conv]] (same-conversion? curr conv)) (cons [(:transaction/currency tx) (:transaction/conversion tx)] (->> (:transaction/fees tx) (filter absolute-fee?) (map (juxt :transaction.fee/currency :transaction.fee/conversion))))))))) (defn transaction-conversions [db user-uuid transaction-entities] ;; user currency is always the same ;; transaction/dates and currencies are shared across multiple transactions. ;; Must be possible to pre-compute some table between date<->conversion<->currency. (let [currency-date-pairs (delay (transduce (comp (mapcat #(map vector (cons (get-in % [:transaction/currency :db/id]) (->> (:transaction/fees %) (map (fn [fee] (get-in fee [:transaction.fee/currency :db/id]))) (filter some?))) (repeat (get-in % [:transaction/date :db/id])))) (distinct)) (completing (fn [m [k v]] {:pre [(number? k) (number? v)]} (assoc m k (conj (get m k []) v)))) {} transaction-entities)) transaction-convs (delay (->> (db/find-with db {:find '[?currency ?date ?conv] :symbols {'[[?currency [?date ...]] ...] @currency-date-pairs} :where '[[?conv :conversion/currency ?currency] [?conv :conversion/date ?date]]}) (reduce (fn [m [curr date conv]] (assoc-in m [curr date] conv)) {}))) user-curr (db/one-with db {:where '[[?u :user/uuid ?user-uuid] [?u :user/currency ?e]] :symbols {'?user-uuid user-uuid}}) user-convs (delay (when user-curr (let [convs (into {} (db/find-with db {:find '[?date ?conv] :symbols {'[?date ...] (reduce into #{} (vals @currency-date-pairs)) '?user-curr user-curr} :where '[[?conv :conversion/currency ?user-curr] [?conv :conversion/date ?date]]}))] (if (seq convs) convs ;; When there are no conversions for any of the transaction's dates, just pick any one. (let [one-conv (db/entity* db (db/one-with db {:where '[[?e :conversion/currency ?user-curr]] :symbols {'?user-curr user-curr}}))] {(get-in one-conv [:conversion/date :db/id]) (:db/id one-conv)})))))] (into {} ;; Skip transactions that has a conversion with the same currency. (comp (remove (same-conversions? db user-curr)) (map (transaction-with-conversion-fn db transaction-convs user-convs)) (filter some?)) transaction-entities))) (defn assoc-conversion-xf [conversions] (map (fn [tx] {:pre [(:db/id tx)]} (let [tx-conversion (get conversions (:db/id tx)) fee-with-conv (fn [fee] (if-not (absolute-fee? fee) fee (let [curr->conv (::currency-to-conversion-map-fn tx-conversion) _ (assert (fn? curr->conv)) fee-conv (curr->conv (get-in fee [:transaction.fee/currency :db/id]))] (cond-> fee (some? fee-conv) (assoc :transaction.fee/conversion fee-conv)))))] (cond-> tx (some? tx-conversion) (-> (assoc :transaction/conversion (dissoc tx-conversion ::currency-to-conversion-map-fn)) (update :transaction/fees #(into #{} (map fee-with-conv) %)))))))) (defn transactions-with-conversions [db user-uuid tx-entities] (let [conversions (transaction-conversions db user-uuid tx-entities)] (into [] (assoc-conversion-xf conversions) tx-entities))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Widgets # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (defn transaction-query [] (parser/put-db-id-in-query '[:transaction/uuid :transaction/amount :transaction/conversion {:transaction/type [:db/ident]} {:transaction/currency [:currency/code]} {:transaction/tags [:tag/name]} {:transaction/date [*]}]))
null
https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/src/eponai/common/database/query.cljc
clojure
Harder to check if it's actually a uuid. All rates are relative USD so we need to pull what rates the user currency has, so we can convert the rate appropriately for the user's selected currency Convert the rate from USD to whatever currency the user has set conversion-of-transaction-currency / conversion-of-user-currency user currency is always the same transaction/dates and currencies are shared across multiple transactions. Must be possible to pre-compute some table between date<->conversion<->currency. When there are no conversions for any of the transaction's dates, just pick any one. Skip transactions that has a conversion with the same currency.
(ns eponai.common.database.query (:require [taoensso.timbre :refer [error debug trace info warn]] [eponai.common.database :as db] [datascript.db] [eponai.common.parser.util :as parser])) (defn project [] {:where '[[?e :project/uuid]]}) (defn project-with-uuid [project-uuid] {:pre [(not (string? project-uuid))]} {:where '[[?e :project/uuid ?project-uuid]] :symbols {'?project-uuid project-uuid}}) (defn with-auth [query user-uuid] (db/merge-query query {:where '[[?u :user/uuid ?user-uuid]] :symbols {'?user-uuid user-uuid}})) (defn project-with-auth [user-uuid] (with-auth {:where '[[?e :project/users ?u]]} user-uuid)) (defn verifications [db user-db-id status] {:pre [(db/database? db) (number? user-db-id) (keyword? status)]} (db/q '[:find [?v ...] :in $ ?u ?s :where [?v :verification/entity ?u] [?u :user/email ?e] [?v :verification/value ?e] [?v :verification/status ?s]] db user-db-id status)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Transactions # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (defn transaction-entity-query [{:keys [project-eid user-uuid]}] (assert (some? user-uuid) "User UUID must be supplied to read transactions.") (assert (number? project-eid) (str "Project eid must be a number to read transactions. Was: " project-eid)) {:where '[[?u :user/uuid ?user-uuid] [?p :project/users ?u] [?e :transaction/project ?p]] :symbols {'?user-uuid user-uuid '?p project-eid}}) (defn transaction-with-conversion-fn [db transaction-convs user-convs] {:pre [(delay? transaction-convs) (delay? user-convs)]} (let [approx-tx-conv (memoize (fn [curr] (or (some->> curr (get @transaction-convs) (first) (val)) (when curr (db/one-with db {:where [['?e :conversion/currency curr]]}))))) approx-user-curr (memoize (fn [] (some-> @user-convs (first) (val))))] (fn [transaction] (let [tx-date (get-in transaction [:transaction/date :db/id]) curr->conv (fn [curr] (or (get-in @transaction-convs [curr tx-date]) (approx-tx-conv curr))) tx-curr (get-in transaction [:transaction/currency :db/id]) tx-conv (curr->conv tx-curr) user-conv (get @user-convs tx-date) user-conv (or user-conv (approx-user-curr))] (if (and (some? tx-conv) (some? user-conv)) conv->rate (fn [conv] (let [transaction-conversion (db/entity* db conv) user-currency-conversion (db/entity* db user-conv) #?@(:cljs [rate (/ (:conversion/rate transaction-conversion) (:conversion/rate user-currency-conversion))] :clj [rate (with-precision 10 (bigdec (/ (:conversion/rate transaction-conversion) (:conversion/rate user-currency-conversion))))])] rate)) curr->conversion-map (fn [curr] (when curr (let [conv (curr->conv curr) rate (conv->rate conv)] {:conversion/currency {:db/id curr} :conversion/rate rate :conversion/date (:conversion/date (db/entity* db conv))})))] ( e.g. user is using SEK , so the new rate will be [(:db/id transaction) (merge (curr->conversion-map tx-curr) {:user-conversion-id user-conv :transaction-conversion-id tx-conv ::currency-to-conversion-map-fn curr->conversion-map})]) (debug "No tx-conv or user-conv. Tx-conv: " tx-conv " user-conv: " user-conv " for transaction: " (into {} transaction))))))) (defn absolute-fee? [fee] #(= :transaction.fee.type/absolute (:transaction.fee/type fee))) (defn same-conversions? [db user-curr] (let [user-conv->user-curr (memoize (fn [user-conv] (get-in (db/entity* db user-conv) [:conversion/currency :db/id])))] (fn [tx] (letfn [(same-conversion? [currency conversion] (and (= user-curr (user-conv->user-curr (:user-conversion-id conversion))) (= (get-in currency [:db/id]) (get-in conversion [:conversion/currency :db/id]))))] (every? (fn [[curr conv]] (same-conversion? curr conv)) (cons [(:transaction/currency tx) (:transaction/conversion tx)] (->> (:transaction/fees tx) (filter absolute-fee?) (map (juxt :transaction.fee/currency :transaction.fee/conversion))))))))) (defn transaction-conversions [db user-uuid transaction-entities] (let [currency-date-pairs (delay (transduce (comp (mapcat #(map vector (cons (get-in % [:transaction/currency :db/id]) (->> (:transaction/fees %) (map (fn [fee] (get-in fee [:transaction.fee/currency :db/id]))) (filter some?))) (repeat (get-in % [:transaction/date :db/id])))) (distinct)) (completing (fn [m [k v]] {:pre [(number? k) (number? v)]} (assoc m k (conj (get m k []) v)))) {} transaction-entities)) transaction-convs (delay (->> (db/find-with db {:find '[?currency ?date ?conv] :symbols {'[[?currency [?date ...]] ...] @currency-date-pairs} :where '[[?conv :conversion/currency ?currency] [?conv :conversion/date ?date]]}) (reduce (fn [m [curr date conv]] (assoc-in m [curr date] conv)) {}))) user-curr (db/one-with db {:where '[[?u :user/uuid ?user-uuid] [?u :user/currency ?e]] :symbols {'?user-uuid user-uuid}}) user-convs (delay (when user-curr (let [convs (into {} (db/find-with db {:find '[?date ?conv] :symbols {'[?date ...] (reduce into #{} (vals @currency-date-pairs)) '?user-curr user-curr} :where '[[?conv :conversion/currency ?user-curr] [?conv :conversion/date ?date]]}))] (if (seq convs) convs (let [one-conv (db/entity* db (db/one-with db {:where '[[?e :conversion/currency ?user-curr]] :symbols {'?user-curr user-curr}}))] {(get-in one-conv [:conversion/date :db/id]) (:db/id one-conv)})))))] (into {} (comp (remove (same-conversions? db user-curr)) (map (transaction-with-conversion-fn db transaction-convs user-convs)) (filter some?)) transaction-entities))) (defn assoc-conversion-xf [conversions] (map (fn [tx] {:pre [(:db/id tx)]} (let [tx-conversion (get conversions (:db/id tx)) fee-with-conv (fn [fee] (if-not (absolute-fee? fee) fee (let [curr->conv (::currency-to-conversion-map-fn tx-conversion) _ (assert (fn? curr->conv)) fee-conv (curr->conv (get-in fee [:transaction.fee/currency :db/id]))] (cond-> fee (some? fee-conv) (assoc :transaction.fee/conversion fee-conv)))))] (cond-> tx (some? tx-conversion) (-> (assoc :transaction/conversion (dissoc tx-conversion ::currency-to-conversion-map-fn)) (update :transaction/fees #(into #{} (map fee-with-conv) %)))))))) (defn transactions-with-conversions [db user-uuid tx-entities] (let [conversions (transaction-conversions db user-uuid tx-entities)] (into [] (assoc-conversion-xf conversions) tx-entities))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Widgets # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (defn transaction-query [] (parser/put-db-id-in-query '[:transaction/uuid :transaction/amount :transaction/conversion {:transaction/type [:db/ident]} {:transaction/currency [:currency/code]} {:transaction/tags [:tag/name]} {:transaction/date [*]}]))
1d6998f1e4754258ee8fad8048b6c25e91f7b770b67beb0e2f9efffb550e33ef
ocurrent/ocluster
utils.ml
open Lwt.Infix open Capnp_rpc_lwt module Api = Cluster_api let speed_multiplier = 60.0 let sleep d = Lwt_unix.sleep (Duration.to_f d /. speed_multiplier) let submit cap ~name ~i ~pool ~urgent ~cache_hint = let job_id = Printf.sprintf "%s-%d" name !i in incr i; let descr = Api.Submission.obuilder_build job_id in Capability.with_ref (Api.Submission.submit cap ~action:descr ~pool ~urgent ~cache_hint) @@ fun ticket -> Capability.with_ref (Api.Ticket.job ticket) @@ fun job -> Capability.await_settled_exn job >>= fun () -> Logs.info (fun f -> f "%s: job %S running" name job_id); Api.Job.result job >|= function | Ok _ -> Logs.info (fun f -> f "%s : job %S finished" name job_id); | Error (`Capnp ex) -> Logs.info (fun f -> f "%s: job %S failed: %a" name job_id Capnp_rpc.Error.pp ex) let opam_repo_head = ref 0 let opam_repository_updated : unit Lwt_condition.t = Lwt_condition.create () let update_opam_repository () = incr opam_repo_head; Lwt_condition.broadcast opam_repository_updated ()
null
https://raw.githubusercontent.com/ocurrent/ocluster/26939dced7239c4283cbae028cd237f8037bdf64/stress/utils.ml
ocaml
open Lwt.Infix open Capnp_rpc_lwt module Api = Cluster_api let speed_multiplier = 60.0 let sleep d = Lwt_unix.sleep (Duration.to_f d /. speed_multiplier) let submit cap ~name ~i ~pool ~urgent ~cache_hint = let job_id = Printf.sprintf "%s-%d" name !i in incr i; let descr = Api.Submission.obuilder_build job_id in Capability.with_ref (Api.Submission.submit cap ~action:descr ~pool ~urgent ~cache_hint) @@ fun ticket -> Capability.with_ref (Api.Ticket.job ticket) @@ fun job -> Capability.await_settled_exn job >>= fun () -> Logs.info (fun f -> f "%s: job %S running" name job_id); Api.Job.result job >|= function | Ok _ -> Logs.info (fun f -> f "%s : job %S finished" name job_id); | Error (`Capnp ex) -> Logs.info (fun f -> f "%s: job %S failed: %a" name job_id Capnp_rpc.Error.pp ex) let opam_repo_head = ref 0 let opam_repository_updated : unit Lwt_condition.t = Lwt_condition.create () let update_opam_repository () = incr opam_repo_head; Lwt_condition.broadcast opam_repository_updated ()
b5f91b17764c4f466d266d8f66ac59dd94a9ea763c509d549276fcaf50bd3862
andrewthad/impure-containers
Maybe.hs
# LANGUAGE MagicHash # -- | This uses some unsafe hackery. module Data.Primitive.Array.Maybe ( MutableMaybeArray , newMaybeArray , readMaybeArray , writeMaybeArray ) where import Control.Monad.Primitive import Data.Primitive.Array import GHC.Exts (Any) import GHC.Prim (reallyUnsafePtrEquality#) import Unsafe.Coerce (unsafeCoerce) newtype MutableMaybeArray s a = MutableMaybeArray (MutableArray s Any) unsafeToMaybe :: Any -> Maybe a unsafeToMaybe a = case reallyUnsafePtrEquality# a nothingSurrogate of 0# -> Just (unsafeCoerce a) _ -> Nothing {-# INLINE unsafeToMaybe #-} nothingSurrogate :: Any nothingSurrogate = error "nothingSurrogate: This value should not be forced!" # NOINLINE nothingSurrogate # newMaybeArray :: PrimMonad m => Int -> Maybe a -> m (MutableMaybeArray (PrimState m) a) newMaybeArray i ma = case ma of Just a -> do x <- newArray i (unsafeCoerce a) return (MutableMaybeArray x) Nothing -> do x <- newArray i nothingSurrogate return (MutableMaybeArray x) readMaybeArray :: PrimMonad m => MutableMaybeArray (PrimState m) a -> Int -> m (Maybe a) readMaybeArray (MutableMaybeArray m) ix = do a <- readArray m ix return (unsafeToMaybe a) writeMaybeArray :: PrimMonad m => MutableMaybeArray (PrimState m) a -> Int -> Maybe a -> m () writeMaybeArray (MutableMaybeArray marr) ix ma = case ma of Just a -> writeArray marr ix (unsafeCoerce a) Nothing -> writeArray marr ix nothingSurrogate
null
https://raw.githubusercontent.com/andrewthad/impure-containers/20f14e3c671543cbb5af142767188e5111bebc65/src/Data/Primitive/Array/Maybe.hs
haskell
| This uses some unsafe hackery. # INLINE unsafeToMaybe #
# LANGUAGE MagicHash # module Data.Primitive.Array.Maybe ( MutableMaybeArray , newMaybeArray , readMaybeArray , writeMaybeArray ) where import Control.Monad.Primitive import Data.Primitive.Array import GHC.Exts (Any) import GHC.Prim (reallyUnsafePtrEquality#) import Unsafe.Coerce (unsafeCoerce) newtype MutableMaybeArray s a = MutableMaybeArray (MutableArray s Any) unsafeToMaybe :: Any -> Maybe a unsafeToMaybe a = case reallyUnsafePtrEquality# a nothingSurrogate of 0# -> Just (unsafeCoerce a) _ -> Nothing nothingSurrogate :: Any nothingSurrogate = error "nothingSurrogate: This value should not be forced!" # NOINLINE nothingSurrogate # newMaybeArray :: PrimMonad m => Int -> Maybe a -> m (MutableMaybeArray (PrimState m) a) newMaybeArray i ma = case ma of Just a -> do x <- newArray i (unsafeCoerce a) return (MutableMaybeArray x) Nothing -> do x <- newArray i nothingSurrogate return (MutableMaybeArray x) readMaybeArray :: PrimMonad m => MutableMaybeArray (PrimState m) a -> Int -> m (Maybe a) readMaybeArray (MutableMaybeArray m) ix = do a <- readArray m ix return (unsafeToMaybe a) writeMaybeArray :: PrimMonad m => MutableMaybeArray (PrimState m) a -> Int -> Maybe a -> m () writeMaybeArray (MutableMaybeArray marr) ix ma = case ma of Just a -> writeArray marr ix (unsafeCoerce a) Nothing -> writeArray marr ix nothingSurrogate
2f267e71222c9c7734a71ae9607b4c293959baee24e82f0a0be6cc93d043c4cb
serokell/tztime
FromLocalTime.hs
SPDX - FileCopyrightText : 2022 > -- SPDX - License - Identifier : MPL-2.0 module Test.Data.Time.TZTime.FromLocalTime where import Data.Time (LocalTime(..), TimeOfDay(..), TimeZone(..)) import Data.Time.Calendar.Compat (pattern YearMonthDay) import Data.Time.TZInfo as TZI import Data.Time.TZTime as TZT import Data.Time.TZTime.Internal (TZTime(UnsafeTZTime)) import Test.Tasty (TestTree) import Test.Tasty.HUnit import Test.Utils unit_fromLocalTimeStrict_at_gaps :: Assertion unit_fromLocalTimeStrict_at_gaps = do At 01:59:59 on 2022 - 03 - 13 , the America / Winnipeg time zone switches from CST ( ) to ( UTC-5 ) . In other words , the clocks “ skip ” 1 hour , straight to 03:00:00 . -- -- See: -- -- Therefore, the local time "2:15" is invalid. -- `fromLocalTimeStrict` should return the local time shifted backwards / forwards by the duration of the gap ( + /- 1 hour ) . let local = LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 2 15 0) let tz = TZI.fromLabel TZI.America__Winnipeg TZT.fromLocalTimeStrict tz local @?= Left (TZGap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 1 15 0)) tz cst ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 3 15 0)) tz cdt ) ) test_fromLocalTimeStrict_at_odd_gaps :: [TestTree] test_fromLocalTimeStrict_at_odd_gaps = [ testCase "Australia/Lord_Howe" do Australia / Lord_Howe turns the clocks forward 30 mins . -- -- See: -howe-island?year=2022 let local = LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 2 7 0) let tz = TZI.fromLabel TZI.Australia__Lord_Howe TZT.fromLocalTimeStrict tz local @?= Left (TZGap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 1 37 0)) tz (TimeZone (10 * 60 + 30) False "+1030") ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 2 37 0)) tz (TimeZone (11 * 60) True "+11") ) ) , testCase "Pacific/Apia" do On 2011 - 12 - 29 , at 23:59:59 , the island of Samoa switched from UTC-10 to . In other words , the clocks were turned forward 24 hours , effectively skipping a whole calendar day ( from 29 Dec to 31 Dec ) . -- -- See: let local = LocalTime (YearMonthDay 2011 12 30) (TimeOfDay 10 7 0) let tz = TZI.fromLabel TZI.Pacific__Apia TZT.fromLocalTimeStrict tz local @?= Left (TZGap local (UnsafeTZTime (LocalTime (YearMonthDay 2011 12 29) (TimeOfDay 10 7 0)) tz (TimeZone (-10 * 60) True "-10") ) (UnsafeTZTime (LocalTime (YearMonthDay 2011 12 31) (TimeOfDay 10 7 0)) tz (TimeZone (14 * 60) True "+14") ) ) ] unit_fromLocalTimeStrict_at_overlaps :: Assertion unit_fromLocalTimeStrict_at_overlaps = do At 01:59:59 on 2022 - 11 - 06 , the America / Winnipeg time zone switches from ( UTC-5 ) to CST ( ) . In other words , the clocks are turned back 1 hour , back to 01:00:00 . -- -- See: -- -- Therefore, the local time "01:15" happens twice: once at the -5 offset -- and again at the -6 offset. -- `fromLocalTimeStrict` should return both instants. let local = LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0) let tz = TZI.fromLabel TZI.America__Winnipeg TZT.fromLocalTimeStrict tz local @?= Left (TZOverlap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0)) tz cdt ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0)) tz cst ) ) unit_fromLocalTimeStrict_at_odd_overlaps :: Assertion unit_fromLocalTimeStrict_at_odd_overlaps = do Australia / Lord_Howe turns the clocks backwards 30 mins . -- -- See: -howe-island?year=2022 let local = LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0) let tz = TZI.fromLabel TZI.Australia__Lord_Howe TZT.fromLocalTimeStrict tz local @?= Left (TZOverlap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0)) tz (TimeZone (11 * 60) True "+11") ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0)) tz (TimeZone (10 * 60 + 30) False "+1030") ) )
null
https://raw.githubusercontent.com/serokell/tztime/a7bab0eb311b691c11844b8ddab39764687cd79e/test/Test/Data/Time/TZTime/FromLocalTime.hs
haskell
See: Therefore, the local time "2:15" is invalid. `fromLocalTimeStrict` should return the local time shifted backwards / forwards See: -howe-island?year=2022 See: See: Therefore, the local time "01:15" happens twice: once at the -5 offset and again at the -6 offset. `fromLocalTimeStrict` should return both instants. See: -howe-island?year=2022
SPDX - FileCopyrightText : 2022 > SPDX - License - Identifier : MPL-2.0 module Test.Data.Time.TZTime.FromLocalTime where import Data.Time (LocalTime(..), TimeOfDay(..), TimeZone(..)) import Data.Time.Calendar.Compat (pattern YearMonthDay) import Data.Time.TZInfo as TZI import Data.Time.TZTime as TZT import Data.Time.TZTime.Internal (TZTime(UnsafeTZTime)) import Test.Tasty (TestTree) import Test.Tasty.HUnit import Test.Utils unit_fromLocalTimeStrict_at_gaps :: Assertion unit_fromLocalTimeStrict_at_gaps = do At 01:59:59 on 2022 - 03 - 13 , the America / Winnipeg time zone switches from CST ( ) to ( UTC-5 ) . In other words , the clocks “ skip ” 1 hour , straight to 03:00:00 . by the duration of the gap ( + /- 1 hour ) . let local = LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 2 15 0) let tz = TZI.fromLabel TZI.America__Winnipeg TZT.fromLocalTimeStrict tz local @?= Left (TZGap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 1 15 0)) tz cst ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 3 15 0)) tz cdt ) ) test_fromLocalTimeStrict_at_odd_gaps :: [TestTree] test_fromLocalTimeStrict_at_odd_gaps = [ testCase "Australia/Lord_Howe" do Australia / Lord_Howe turns the clocks forward 30 mins . let local = LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 2 7 0) let tz = TZI.fromLabel TZI.Australia__Lord_Howe TZT.fromLocalTimeStrict tz local @?= Left (TZGap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 1 37 0)) tz (TimeZone (10 * 60 + 30) False "+1030") ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 2 37 0)) tz (TimeZone (11 * 60) True "+11") ) ) , testCase "Pacific/Apia" do On 2011 - 12 - 29 , at 23:59:59 , the island of Samoa switched from UTC-10 to . In other words , the clocks were turned forward 24 hours , effectively skipping a whole calendar day ( from 29 Dec to 31 Dec ) . let local = LocalTime (YearMonthDay 2011 12 30) (TimeOfDay 10 7 0) let tz = TZI.fromLabel TZI.Pacific__Apia TZT.fromLocalTimeStrict tz local @?= Left (TZGap local (UnsafeTZTime (LocalTime (YearMonthDay 2011 12 29) (TimeOfDay 10 7 0)) tz (TimeZone (-10 * 60) True "-10") ) (UnsafeTZTime (LocalTime (YearMonthDay 2011 12 31) (TimeOfDay 10 7 0)) tz (TimeZone (14 * 60) True "+14") ) ) ] unit_fromLocalTimeStrict_at_overlaps :: Assertion unit_fromLocalTimeStrict_at_overlaps = do At 01:59:59 on 2022 - 11 - 06 , the America / Winnipeg time zone switches from ( UTC-5 ) to CST ( ) . In other words , the clocks are turned back 1 hour , back to 01:00:00 . let local = LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0) let tz = TZI.fromLabel TZI.America__Winnipeg TZT.fromLocalTimeStrict tz local @?= Left (TZOverlap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0)) tz cdt ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0)) tz cst ) ) unit_fromLocalTimeStrict_at_odd_overlaps :: Assertion unit_fromLocalTimeStrict_at_odd_overlaps = do Australia / Lord_Howe turns the clocks backwards 30 mins . let local = LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0) let tz = TZI.fromLabel TZI.Australia__Lord_Howe TZT.fromLocalTimeStrict tz local @?= Left (TZOverlap local (UnsafeTZTime (LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0)) tz (TimeZone (11 * 60) True "+11") ) (UnsafeTZTime (LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0)) tz (TimeZone (10 * 60 + 30) False "+1030") ) )
0a41053478e02a69ddb2aebbc3a12283eac2e77e9f4bad24ae2ecf991ca538e7
baryluk/ex11
swTopLevel.erl
-module(swTopLevel). Copyright ( C ) 2004 by ( ) %% All rights reserved. %% The copyright holder hereby grants the rights of usage, distribution %% and modification of this software to everyone and for any purpose, as %% long as this license and the copyright notice above are preserved and %% not modified. There is no warranty for this software. 2004 - 01- ? ? Original version by 2004 - 02 - 15 Added support for multiple screens < > -include("sw.hrl"). -import(ex11_lib, [reply/2, reply/2, rpc/2, get_display/2, get_root_of_screen/2, xClearArea/1, xColor/2, xCreateGC/3, xDo/2, xFlush/1]). -import(lists, [foreach/2]). -export([make/4, make/5]). make(Parent, Width, Ht, Color) -> make(Parent, get_display(Parent, default_screen), Width, Ht, Color). make(Parent, Screen, Width, Ht, Color) -> S = self(), spawn_link(fun() -> init(S, Parent, Screen, Width, Ht, Color) end). init(Pid, Display, Screen, Width, Ht, Color) -> Wargs = #win{parent=get_root_of_screen(Display, Screen), width=Width,ht=Ht,color=Color,type=top, mask=?EVENT_BUTTON_PRESS bor ?EVENT_EXPOSURE bor ?EVENT_STRUCTURE_NOTIFY, screen=Screen}, Wargs1 = sw:mkWindow(Display, Pid, Wargs), Win = Wargs1#win.win, process_flag(trap_exit, true), %Display1 = rpc(Display, display), io:format("Display=~p~n",[Display]), loop(Display, Wargs1, dict:new(), {[],1}, fun(_) -> void end, fun(_) -> void end). loop(Display, Wargs, Pens, L, Fun, CFun) -> receive {onClick, Fun1} -> loop(Display, Wargs, Pens, L, Fun1, CFun); {onReconfigure, Fun1} -> loop(Display, Wargs, Pens, L, Fun, Fun1); {event,_,expose,_} -> refresh(Display, Wargs#win.win,L), loop(Display, Wargs, Pens, L, Fun, CFun); {event,_,buttonPress, X} -> Fun(X), loop(Display, Wargs, Pens, L, Fun, CFun); {event,_,configureNotify, X} -> CFun(X), loop(Display, Wargs, Pens, L, Fun, CFun); {event,_,buttonPress, X} -> Fun(X), loop(Display, Wargs, Pens, L, Fun, CFun); {newPen, Name, Color, Width} -> Win = Wargs#win.win, GC = xCreateGC(Display, Win, [{function,copy}, {line_width,Width}, {line_style,solid}, {foreground, xColor(Display, Color)}]), Pens1 = dict:store(Name, GC, Pens), loop(Display,Wargs,Pens1, L, Fun, CFun); {From, {draw, Pen, Obj}} -> case dict:find(Pen, Pens) of {ok, GC} -> case swCanvas:cdraw(Wargs#win.win, GC, Obj) of {error, What} -> exit({badArg, What}); Bin -> {L1, Free} = L, L2 = L1 ++ [{Free, Bin}], L3 = {L2, Free+1}, refresh(Display,Wargs#win.win,L3), reply(From, Free), loop(Display, Wargs, Pens, L3, Fun, CFun) end; error -> io:format("Invalid pen:~p~n",[Pen]), exit({eBadPen, Pen}) end; {From, {delete, Id}} -> {L1, Free} = L, L2 = swCanvas:delete_obj(Id, L1), L3 = {L2, Free}, refresh(Display,Wargs#win.win,L3), reply(From, Free), loop(Display, Wargs, Pens, L3, Fun, CFun); {From, id} -> reply(From, {Display, Wargs#win.win}), loop(Display, Wargs, Pens, L, Fun, CFun); {'EXIT', Who,Why} -> io:format("swToplevel got Exit from:~p reason:~p~n", [Who,Why]), exit(killed); Any -> Wargs1 = sw:generic(Any, Display, Wargs), loop(Display, Wargs1, Pens, L, Fun, CFun) end. refresh(Display, Win, {L,_}) -> xDo(Display, xClearArea(Win)), foreach(fun({_,Bin}) -> xDo(Display, Bin) end, L), xFlush(Display).
null
https://raw.githubusercontent.com/baryluk/ex11/be8abc64ab9fb50611f93d6631fc33ffdee08fdb/widgets/swTopLevel.erl
erlang
All rights reserved. The copyright holder hereby grants the rights of usage, distribution and modification of this software to everyone and for any purpose, as long as this license and the copyright notice above are preserved and not modified. There is no warranty for this software. Display1 = rpc(Display, display),
-module(swTopLevel). Copyright ( C ) 2004 by ( ) 2004 - 01- ? ? Original version by 2004 - 02 - 15 Added support for multiple screens < > -include("sw.hrl"). -import(ex11_lib, [reply/2, reply/2, rpc/2, get_display/2, get_root_of_screen/2, xClearArea/1, xColor/2, xCreateGC/3, xDo/2, xFlush/1]). -import(lists, [foreach/2]). -export([make/4, make/5]). make(Parent, Width, Ht, Color) -> make(Parent, get_display(Parent, default_screen), Width, Ht, Color). make(Parent, Screen, Width, Ht, Color) -> S = self(), spawn_link(fun() -> init(S, Parent, Screen, Width, Ht, Color) end). init(Pid, Display, Screen, Width, Ht, Color) -> Wargs = #win{parent=get_root_of_screen(Display, Screen), width=Width,ht=Ht,color=Color,type=top, mask=?EVENT_BUTTON_PRESS bor ?EVENT_EXPOSURE bor ?EVENT_STRUCTURE_NOTIFY, screen=Screen}, Wargs1 = sw:mkWindow(Display, Pid, Wargs), Win = Wargs1#win.win, process_flag(trap_exit, true), io:format("Display=~p~n",[Display]), loop(Display, Wargs1, dict:new(), {[],1}, fun(_) -> void end, fun(_) -> void end). loop(Display, Wargs, Pens, L, Fun, CFun) -> receive {onClick, Fun1} -> loop(Display, Wargs, Pens, L, Fun1, CFun); {onReconfigure, Fun1} -> loop(Display, Wargs, Pens, L, Fun, Fun1); {event,_,expose,_} -> refresh(Display, Wargs#win.win,L), loop(Display, Wargs, Pens, L, Fun, CFun); {event,_,buttonPress, X} -> Fun(X), loop(Display, Wargs, Pens, L, Fun, CFun); {event,_,configureNotify, X} -> CFun(X), loop(Display, Wargs, Pens, L, Fun, CFun); {event,_,buttonPress, X} -> Fun(X), loop(Display, Wargs, Pens, L, Fun, CFun); {newPen, Name, Color, Width} -> Win = Wargs#win.win, GC = xCreateGC(Display, Win, [{function,copy}, {line_width,Width}, {line_style,solid}, {foreground, xColor(Display, Color)}]), Pens1 = dict:store(Name, GC, Pens), loop(Display,Wargs,Pens1, L, Fun, CFun); {From, {draw, Pen, Obj}} -> case dict:find(Pen, Pens) of {ok, GC} -> case swCanvas:cdraw(Wargs#win.win, GC, Obj) of {error, What} -> exit({badArg, What}); Bin -> {L1, Free} = L, L2 = L1 ++ [{Free, Bin}], L3 = {L2, Free+1}, refresh(Display,Wargs#win.win,L3), reply(From, Free), loop(Display, Wargs, Pens, L3, Fun, CFun) end; error -> io:format("Invalid pen:~p~n",[Pen]), exit({eBadPen, Pen}) end; {From, {delete, Id}} -> {L1, Free} = L, L2 = swCanvas:delete_obj(Id, L1), L3 = {L2, Free}, refresh(Display,Wargs#win.win,L3), reply(From, Free), loop(Display, Wargs, Pens, L3, Fun, CFun); {From, id} -> reply(From, {Display, Wargs#win.win}), loop(Display, Wargs, Pens, L, Fun, CFun); {'EXIT', Who,Why} -> io:format("swToplevel got Exit from:~p reason:~p~n", [Who,Why]), exit(killed); Any -> Wargs1 = sw:generic(Any, Display, Wargs), loop(Display, Wargs1, Pens, L, Fun, CFun) end. refresh(Display, Win, {L,_}) -> xDo(Display, xClearArea(Win)), foreach(fun({_,Bin}) -> xDo(Display, Bin) end, L), xFlush(Display).
b4029724205d7ef19d37ef346be10ae4c72b3350944ca5def1a6a6b6460b0e42
replikativ/datahike
index_test.cljc
(ns datahike.test.index-test (:require #?(:cljs [cljs.test :as t :refer-macros [is deftest testing]] :clj [clojure.test :as t :refer [is deftest testing]]) [datahike.api :as d] [datahike.constants :refer [e0 tx0 emax txmax]] [datahike.datom :as dd] [datahike.db :as db] [datahike.index :as di])) (deftest test-datoms (let [dvec #(vector (:e %) (:a %) (:v %)) db (-> (db/empty-db {:age {:db/index true}}) (d/db-with [[:db/add 1 :name "Petr"] [:db/add 1 :age 44] [:db/add 2 :name "Ivan"] [:db/add 2 :age 25] [:db/add 3 :name "Sergey"] [:db/add 3 :age 11]]))] (testing "Main indexes, sort order" (is (= [[1 :age 44] [2 :age 25] [3 :age 11] [1 :name "Petr"] [2 :name "Ivan"] [3 :name "Sergey"]] (map dvec (d/datoms db :aevt)))) (is (= [[1 :age 44] [1 :name "Petr"] [2 :age 25] [2 :name "Ivan"] [3 :age 11] [3 :name "Sergey"]] (map dvec (d/datoms db :eavt)))) (is (= [[3 :age 11] [2 :age 25] [1 :age 44]] (map dvec (d/datoms db :avet))))) ;; name non-indexed, excluded from avet (testing "Components filtration" (is (= [[1 :age 44] [1 :name "Petr"]] (map dvec (d/datoms db :eavt 1)))) (is (= [[1 :age 44]] (map dvec (d/datoms db :eavt 1 :age)))) (is (= [[3 :age 11] [2 :age 25] [1 :age 44]] (map dvec (d/datoms db :avet :age))))))) (deftest test-seek-datoms (let [dvec #(vector (:e %) (:a %) (:v %)) db (-> (db/empty-db {:name {:db/index true} :age {:db/index true}}) (d/db-with [[:db/add 1 :name "Petr"] [:db/add 1 :age 44] [:db/add 2 :name "Ivan"] [:db/add 2 :age 25] [:db/add 3 :name "Sergey"] [:db/add 3 :age 11]]))] (testing "Non-termination" (is (= (map dvec (d/seek-datoms db :avet :age 10)) [[3 :age 11] [2 :age 25] [1 :age 44] [2 :name "Ivan"] [1 :name "Petr"] [3 :name "Sergey"]]))) (testing "Closest value lookup" (is (= (map dvec (d/seek-datoms db :avet :name "P")) [[1 :name "Petr"] [3 :name "Sergey"]]))) (testing "Exact value lookup" (is (= (map dvec (d/seek-datoms db :avet :name "Petr")) [[1 :name "Petr"] [3 :name "Sergey"]]))))) #_(deftest test-rseek-datoms ;; TODO: implement rseek within hitchhiker tree (let [dvec #(vector (:e %) (:a %) (:v %)) db (-> (db/empty-db {:name {:db/index true} :age {:db/index true}}) (d/db-with [[:db/add 1 :name "Petr"] [:db/add 1 :age 44] [:db/add 2 :name "Ivan"] [:db/add 2 :age 25] [:db/add 3 :name "Sergey"] [:db/add 3 :age 11]]))] (testing "Non-termination" (is (= (map dvec (d/rseek-datoms db :avet :name "Petr")) [[1 :name "Petr"] [2 :name "Ivan"] [1 :age 44] [2 :age 25] [3 :age 11]]))) (testing "Closest value lookup" (is (= (map dvec (d/rseek-datoms db :avet :age 26)) [[2 :age 25] [3 :age 11]]))) (testing "Exact value lookup" (is (= (map dvec (d/rseek-datoms db :avet :age 25)) [[2 :age 25] [3 :age 11]]))))) (deftest test-index-range (let [dvec #(vector (:e %) (:a %) (:v %)) db (d/db-with (db/empty-db {:name {:db/index true} :age {:db/index true}}) [{:db/id 1 :name "Ivan" :age 15} {:db/id 2 :name "Oleg" :age 20} {:db/id 3 :name "Sergey" :age 7} {:db/id 4 :name "Pavel" :age 45} {:db/id 5 :name "Petr" :age 20}])] (is (= (map dvec (d/index-range db {:attrid :name :start "Pe" :end "S"})) [[5 :name "Petr"]])) (is (= (map dvec (d/index-range db {:attrid :name :start "O" :end "Sergey"})) [[2 :name "Oleg"] [4 :name "Pavel"] [5 :name "Petr"] [3 :name "Sergey"]])) (is (= (map dvec (d/index-range db {:attrid :name :start nil :end "P"})) [[1 :name "Ivan"] [2 :name "Oleg"]])) (is (= (map dvec (d/index-range db {:attrid :name :start "R" :end nil})) [[3 :name "Sergey"]])) (is (= (map dvec (d/index-range db {:attrid :name :start nil :end nil})) [[1 :name "Ivan"] [2 :name "Oleg"] [4 :name "Pavel"] [5 :name "Petr"] [3 :name "Sergey"]])) (is (= (map dvec (d/index-range db {:attrid :age :start 15 :end 20})) [[1 :age 15] [2 :age 20] [5 :age 20]])) (is (= (map dvec (d/index-range db {:attrid :age :start 7 :end 45})) [[3 :age 7] [1 :age 15] [2 :age 20] [5 :age 20] [4 :age 45]])) (is (= (map dvec (d/index-range db {:attrid :age :start 0 :end 100})) [[3 :age 7] [1 :age 15] [2 :age 20] [5 :age 20] [4 :age 45]])))) (deftest test-slice [] (testing "Test index -slice" (let [dvec #(vector (:e %) (:a %) (:v %)) db (d/db-with (db/empty-db {:name {:db/index true} :age {:db/index true}}) [{:db/id 1 :name "Ivan" :age 15} {:db/id 2 :name "Oleg" :age 20} {:db/id 3 :name "Sergey" :age 7} {:db/id 4 :name "Pavel" :age 45} {:db/id 5 :name "Petr" :age 20}]) eavt (:eavt db) aevt (:aevt db) avet (:avet db)] (is (= (di/-slice eavt (dd/datom e0 nil nil tx0) (dd/datom emax nil nil txmax) :eavt) (d/datoms db :eavt))) (is (= (map dvec (di/-slice eavt (dd/datom e0 nil nil tx0) (dd/datom 2 nil nil txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 nil nil tx0) (dd/datom 3 :age 7 txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 :age nil tx0) (dd/datom 3 :name "Timofey" txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7] [3 :name "Sergey"]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 :age nil tx0) (dd/datom 3 :name "Timofey" tx0) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7] [3 :name "Sergey"]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 :age nil tx0) (dd/datom 5 :age nil txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7] [3 :name "Sergey"] [4 :age 45] [4 :name "Pavel"] [5 :age 20]])) (is (= (map dvec (di/-slice aevt (dd/datom e0 nil nil tx0) (dd/datom 3 :name "Pavel" txmax) :aevt)) [[1 :age 15] [2 :age 20] [3 :age 7] [4 :age 45] [5 :age 20] [1 :name "Ivan"] [2 :name "Oleg"]])) (is (= (map dvec (di/-slice aevt (dd/datom e0 nil nil tx0) (dd/datom 5 :age 18 txmax) :aevt)) [[1 :age 15] [2 :age 20] [3 :age 7] [4 :age 45]])) (is (= (map dvec (di/-slice aevt (dd/datom e0 nil nil tx0) (dd/datom 3 :name nil txmax) :aevt)) [[1 :age 15] [2 :age 20] [3 :age 7] [4 :age 45] [5 :age 20] [1 :name "Ivan"] [2 :name "Oleg"] [3 :name "Sergey"]])) (is (= (map dvec (di/-slice avet (dd/datom e0 nil nil tx0) (dd/datom 3 :age 50 txmax) :avet)) [[3 :age 7] [1 :age 15] [2 :age 20] [5 :age 20] [4 :age 45]])))))
null
https://raw.githubusercontent.com/replikativ/datahike/6c1468fd833ed8079b482fe934ae08f1ca2dda3c/test/datahike/test/index_test.cljc
clojure
name non-indexed, excluded from avet TODO: implement rseek within hitchhiker tree
(ns datahike.test.index-test (:require #?(:cljs [cljs.test :as t :refer-macros [is deftest testing]] :clj [clojure.test :as t :refer [is deftest testing]]) [datahike.api :as d] [datahike.constants :refer [e0 tx0 emax txmax]] [datahike.datom :as dd] [datahike.db :as db] [datahike.index :as di])) (deftest test-datoms (let [dvec #(vector (:e %) (:a %) (:v %)) db (-> (db/empty-db {:age {:db/index true}}) (d/db-with [[:db/add 1 :name "Petr"] [:db/add 1 :age 44] [:db/add 2 :name "Ivan"] [:db/add 2 :age 25] [:db/add 3 :name "Sergey"] [:db/add 3 :age 11]]))] (testing "Main indexes, sort order" (is (= [[1 :age 44] [2 :age 25] [3 :age 11] [1 :name "Petr"] [2 :name "Ivan"] [3 :name "Sergey"]] (map dvec (d/datoms db :aevt)))) (is (= [[1 :age 44] [1 :name "Petr"] [2 :age 25] [2 :name "Ivan"] [3 :age 11] [3 :name "Sergey"]] (map dvec (d/datoms db :eavt)))) (is (= [[3 :age 11] [2 :age 25] [1 :age 44]] (testing "Components filtration" (is (= [[1 :age 44] [1 :name "Petr"]] (map dvec (d/datoms db :eavt 1)))) (is (= [[1 :age 44]] (map dvec (d/datoms db :eavt 1 :age)))) (is (= [[3 :age 11] [2 :age 25] [1 :age 44]] (map dvec (d/datoms db :avet :age))))))) (deftest test-seek-datoms (let [dvec #(vector (:e %) (:a %) (:v %)) db (-> (db/empty-db {:name {:db/index true} :age {:db/index true}}) (d/db-with [[:db/add 1 :name "Petr"] [:db/add 1 :age 44] [:db/add 2 :name "Ivan"] [:db/add 2 :age 25] [:db/add 3 :name "Sergey"] [:db/add 3 :age 11]]))] (testing "Non-termination" (is (= (map dvec (d/seek-datoms db :avet :age 10)) [[3 :age 11] [2 :age 25] [1 :age 44] [2 :name "Ivan"] [1 :name "Petr"] [3 :name "Sergey"]]))) (testing "Closest value lookup" (is (= (map dvec (d/seek-datoms db :avet :name "P")) [[1 :name "Petr"] [3 :name "Sergey"]]))) (testing "Exact value lookup" (is (= (map dvec (d/seek-datoms db :avet :name "Petr")) [[1 :name "Petr"] [3 :name "Sergey"]]))))) (let [dvec #(vector (:e %) (:a %) (:v %)) db (-> (db/empty-db {:name {:db/index true} :age {:db/index true}}) (d/db-with [[:db/add 1 :name "Petr"] [:db/add 1 :age 44] [:db/add 2 :name "Ivan"] [:db/add 2 :age 25] [:db/add 3 :name "Sergey"] [:db/add 3 :age 11]]))] (testing "Non-termination" (is (= (map dvec (d/rseek-datoms db :avet :name "Petr")) [[1 :name "Petr"] [2 :name "Ivan"] [1 :age 44] [2 :age 25] [3 :age 11]]))) (testing "Closest value lookup" (is (= (map dvec (d/rseek-datoms db :avet :age 26)) [[2 :age 25] [3 :age 11]]))) (testing "Exact value lookup" (is (= (map dvec (d/rseek-datoms db :avet :age 25)) [[2 :age 25] [3 :age 11]]))))) (deftest test-index-range (let [dvec #(vector (:e %) (:a %) (:v %)) db (d/db-with (db/empty-db {:name {:db/index true} :age {:db/index true}}) [{:db/id 1 :name "Ivan" :age 15} {:db/id 2 :name "Oleg" :age 20} {:db/id 3 :name "Sergey" :age 7} {:db/id 4 :name "Pavel" :age 45} {:db/id 5 :name "Petr" :age 20}])] (is (= (map dvec (d/index-range db {:attrid :name :start "Pe" :end "S"})) [[5 :name "Petr"]])) (is (= (map dvec (d/index-range db {:attrid :name :start "O" :end "Sergey"})) [[2 :name "Oleg"] [4 :name "Pavel"] [5 :name "Petr"] [3 :name "Sergey"]])) (is (= (map dvec (d/index-range db {:attrid :name :start nil :end "P"})) [[1 :name "Ivan"] [2 :name "Oleg"]])) (is (= (map dvec (d/index-range db {:attrid :name :start "R" :end nil})) [[3 :name "Sergey"]])) (is (= (map dvec (d/index-range db {:attrid :name :start nil :end nil})) [[1 :name "Ivan"] [2 :name "Oleg"] [4 :name "Pavel"] [5 :name "Petr"] [3 :name "Sergey"]])) (is (= (map dvec (d/index-range db {:attrid :age :start 15 :end 20})) [[1 :age 15] [2 :age 20] [5 :age 20]])) (is (= (map dvec (d/index-range db {:attrid :age :start 7 :end 45})) [[3 :age 7] [1 :age 15] [2 :age 20] [5 :age 20] [4 :age 45]])) (is (= (map dvec (d/index-range db {:attrid :age :start 0 :end 100})) [[3 :age 7] [1 :age 15] [2 :age 20] [5 :age 20] [4 :age 45]])))) (deftest test-slice [] (testing "Test index -slice" (let [dvec #(vector (:e %) (:a %) (:v %)) db (d/db-with (db/empty-db {:name {:db/index true} :age {:db/index true}}) [{:db/id 1 :name "Ivan" :age 15} {:db/id 2 :name "Oleg" :age 20} {:db/id 3 :name "Sergey" :age 7} {:db/id 4 :name "Pavel" :age 45} {:db/id 5 :name "Petr" :age 20}]) eavt (:eavt db) aevt (:aevt db) avet (:avet db)] (is (= (di/-slice eavt (dd/datom e0 nil nil tx0) (dd/datom emax nil nil txmax) :eavt) (d/datoms db :eavt))) (is (= (map dvec (di/-slice eavt (dd/datom e0 nil nil tx0) (dd/datom 2 nil nil txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 nil nil tx0) (dd/datom 3 :age 7 txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 :age nil tx0) (dd/datom 3 :name "Timofey" txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7] [3 :name "Sergey"]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 :age nil tx0) (dd/datom 3 :name "Timofey" tx0) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7] [3 :name "Sergey"]])) (is (= (map dvec (di/-slice eavt (dd/datom e0 :age nil tx0) (dd/datom 5 :age nil txmax) :eavt)) [[1 :age 15] [1 :name "Ivan"] [2 :age 20] [2 :name "Oleg"] [3 :age 7] [3 :name "Sergey"] [4 :age 45] [4 :name "Pavel"] [5 :age 20]])) (is (= (map dvec (di/-slice aevt (dd/datom e0 nil nil tx0) (dd/datom 3 :name "Pavel" txmax) :aevt)) [[1 :age 15] [2 :age 20] [3 :age 7] [4 :age 45] [5 :age 20] [1 :name "Ivan"] [2 :name "Oleg"]])) (is (= (map dvec (di/-slice aevt (dd/datom e0 nil nil tx0) (dd/datom 5 :age 18 txmax) :aevt)) [[1 :age 15] [2 :age 20] [3 :age 7] [4 :age 45]])) (is (= (map dvec (di/-slice aevt (dd/datom e0 nil nil tx0) (dd/datom 3 :name nil txmax) :aevt)) [[1 :age 15] [2 :age 20] [3 :age 7] [4 :age 45] [5 :age 20] [1 :name "Ivan"] [2 :name "Oleg"] [3 :name "Sergey"]])) (is (= (map dvec (di/-slice avet (dd/datom e0 nil nil tx0) (dd/datom 3 :age 50 txmax) :avet)) [[3 :age 7] [1 :age 15] [2 :age 20] [5 :age 20] [4 :age 45]])))))
d701735b08d1556b6a4dc2b2d035282dd1d9eb96eea3e4e91dfc9518137cb71a
bluejay77/MRS-NOVEL9
timer.lisp
;;; -*- Mode: Common-LISP -*- ;;; 0.2 18 - Mar-83 0156 000 1 ML E 18 - Mar-83 ;;; timing function ;;; perm filename TIMER.LSP[MRS , LSP ] blob sn#702139 filedate 1983 - 03 - 18 ;;; generic text, type T, neo UTF8 ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Please do not modify this file . See MRG . ; ; ; ( c ) Copyright 1981 ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; ------------------------------------------------------------ ;;; Dr 2015 - 05 - 10 ;;; ;;; ------------------------------------------------------------ ;;; (defun runtime () (let ((ticks (get-internal-run-time))) (/ (coerce ticks 'float) (coerce internal-time-units-per-second 'float)))) (defmacro timer (&rest x) `(time ,x))
null
https://raw.githubusercontent.com/bluejay77/MRS-NOVEL9/3a2d7a9c52b711125521444bb3eb6df7fb727017/timer.lisp
lisp
-*- Mode: Common-LISP -*- timing function generic text, type T, neo UTF8 ; ; ; ; ------------------------------------------------------------ ------------------------------------------------------------
0.2 18 - Mar-83 0156 000 1 ML E 18 - Mar-83 perm filename TIMER.LSP[MRS , LSP ] blob sn#702139 filedate 1983 - 03 - 18 Dr 2015 - 05 - 10 (defun runtime () (let ((ticks (get-internal-run-time))) (/ (coerce ticks 'float) (coerce internal-time-units-per-second 'float)))) (defmacro timer (&rest x) `(time ,x))
f174fc85e617cae528da26b9566519ee58e8c94a30e9ca3d5b13ab352d03e867
tonyg/kali-scheme
interfaces.scm
Copyright ( c ) 1994 . See file COPYING . (define-interface ps-primop-interface (export get-prescheme-primop (define-scheme-primop :syntax) (define-polymorphic-scheme-primop :syntax) (define-nonsimple-scheme-primop :syntax) (define-scheme-cond-primop :syntax) prescheme-integer-size lshr)) (define-interface ps-c-primop-interface (export simple-c-primop? primop-generate-c (define-c-generator :syntax))) (define-interface ps-type-interface (export ;type/int7u ;type/int8 ;type/int8u type/integer type/float type/char type/address type/null type/unit type/boolean type/undetermined type/input-port type/output-port type/unknown type/string other-type? other-type-kind other-type-subtypes make-other-type base-type? base-type-name base-type-uid make-atomic-type make-arrow-type arrow-type? arrow-type-result arrow-type-args make-pointer-type pointer-type? pointer-type-to make-tuple-type tuple-type? tuple-type-types record-type? lookup-type type-scheme? schemify-type instantiate-type-scheme copy-type type-scheme-type make-nonpolymorphic! type-scheme-free-uvars ; for error messages ; type-scheme-lattice-uvars ; type-scheme-type type-eq? ; type> ; type>= ; lattice-type? expand-type-spec finalize-type display-type make-base-type-table )) (define-interface type-variable-interface (export make-uvar make-tuple-uvar uvar? maybe-follow-uvar uvar-source set-uvar-source! reset-type-vars! uvar-binding set-uvar-binding! uvar-prefix uvar-id uvar-temp set-uvar-temp! bind-uvar! unique-id )) (define-interface record-type-interface (export reset-record-data! all-record-types get-record-type record-type-name record-type-fields get-record-type-field record-field-record-type record-field-name record-field-type)) (define-interface inference-interface (export infer-definition-type get-package-variable-type get-variable-type ;add-type-coercions node-type lambda-node-return-type)) (define-interface inference-internal-interface (export unify! infer-type infer-types check-arg-type literal-value-type )) (define-interface form-interface (export make-form form? form-value set-form-value! form-value-type set-form-value-type! node-form set-form-node! set-form-integrate! set-form-exported?! form-node form-var form-exported? form-type set-form-type! form-free set-form-free! suspend-form-use! use-this-form! also-use-this-form! set-form-lambdas! form-lambdas form-name form-merge set-form-merge! form-providers set-form-providers! form-clients set-form-clients! form-shadowed set-form-shadowed! variable-set!? note-variable-set!! make-form-unused! variable->form maybe-variable->form ; high level stuff sort-forms expand-and-simplify-form remove-unreferenced-forms integrate-stob-form resimplify-form )) (define-interface linking-interface (export package-specs->packages+exports package-source define-prescheme! prescheme-compiler-env )) (define-interface c-internal-interface (export c-assignment indent-to c-argument-var form-tail-called? *doing-tail-called-procedure?* merged-procedure-reference goto-protocol? c-ify c-value form-value form-name form-c-name form-type c-assign-to-variable write-c-identifier write-value-list write-value-list-with-extras write-value+result-var-list form-return-count set-form-return-count! simple-c-primop c-variable *current-merged-procedure* *extra-tail-call-args* write-c-block write-c-coercion no-value-node? display-c-type add-c-type-declaration! note-jump-generated! ))
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/ps-compiler/prescheme/interfaces.scm
scheme
type/int7u type/int8 type/int8u for error messages type-scheme-lattice-uvars type-scheme-type type> type>= lattice-type? add-type-coercions high level stuff
Copyright ( c ) 1994 . See file COPYING . (define-interface ps-primop-interface (export get-prescheme-primop (define-scheme-primop :syntax) (define-polymorphic-scheme-primop :syntax) (define-nonsimple-scheme-primop :syntax) (define-scheme-cond-primop :syntax) prescheme-integer-size lshr)) (define-interface ps-c-primop-interface (export simple-c-primop? primop-generate-c (define-c-generator :syntax))) (define-interface ps-type-interface type/integer type/float type/char type/address type/null type/unit type/boolean type/undetermined type/input-port type/output-port type/unknown type/string other-type? other-type-kind other-type-subtypes make-other-type base-type? base-type-name base-type-uid make-atomic-type make-arrow-type arrow-type? arrow-type-result arrow-type-args make-pointer-type pointer-type? pointer-type-to make-tuple-type tuple-type? tuple-type-types record-type? lookup-type type-scheme? schemify-type instantiate-type-scheme copy-type type-scheme-type make-nonpolymorphic! type-eq? expand-type-spec finalize-type display-type make-base-type-table )) (define-interface type-variable-interface (export make-uvar make-tuple-uvar uvar? maybe-follow-uvar uvar-source set-uvar-source! reset-type-vars! uvar-binding set-uvar-binding! uvar-prefix uvar-id uvar-temp set-uvar-temp! bind-uvar! unique-id )) (define-interface record-type-interface (export reset-record-data! all-record-types get-record-type record-type-name record-type-fields get-record-type-field record-field-record-type record-field-name record-field-type)) (define-interface inference-interface (export infer-definition-type get-package-variable-type get-variable-type node-type lambda-node-return-type)) (define-interface inference-internal-interface (export unify! infer-type infer-types check-arg-type literal-value-type )) (define-interface form-interface (export make-form form? form-value set-form-value! form-value-type set-form-value-type! node-form set-form-node! set-form-integrate! set-form-exported?! form-node form-var form-exported? form-type set-form-type! form-free set-form-free! suspend-form-use! use-this-form! also-use-this-form! set-form-lambdas! form-lambdas form-name form-merge set-form-merge! form-providers set-form-providers! form-clients set-form-clients! form-shadowed set-form-shadowed! variable-set!? note-variable-set!! make-form-unused! variable->form maybe-variable->form sort-forms expand-and-simplify-form remove-unreferenced-forms integrate-stob-form resimplify-form )) (define-interface linking-interface (export package-specs->packages+exports package-source define-prescheme! prescheme-compiler-env )) (define-interface c-internal-interface (export c-assignment indent-to c-argument-var form-tail-called? *doing-tail-called-procedure?* merged-procedure-reference goto-protocol? c-ify c-value form-value form-name form-c-name form-type c-assign-to-variable write-c-identifier write-value-list write-value-list-with-extras write-value+result-var-list form-return-count set-form-return-count! simple-c-primop c-variable *current-merged-procedure* *extra-tail-call-args* write-c-block write-c-coercion no-value-node? display-c-type add-c-type-declaration! note-jump-generated! ))
97a9f0af30b48c2c72ad7ea4f70968d6d30308a39bd79b67684285fdf1ac8f9b
haskell/cabal
Setup.hs
module Main (main) where import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PreProcess import Distribution.Simple.Program import Distribution.Types.BuildInfo import Distribution.Verbosity import System.Directory ppHGen :: BuildInfo -> LocalBuildInfo -> ComponentLocalBuildInfo -> PreProcessor ppHGen _bi lbi _clbi = PreProcessor { platformIndependent = True , ppOrdering = unsorted , runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity -> copyFile inFile outFile } main :: IO () main = defaultMainWithHooks simpleUserHooks { hookedPreProcessors = ("hgen", ppHGen) : hookedPreProcessors simpleUserHooks }
null
https://raw.githubusercontent.com/haskell/cabal/664e17db2458b67378d0d0e3bd7de8096d5e55d0/cabal-testsuite/PackageTests/AutogenModulesToggling/Setup.hs
haskell
module Main (main) where import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PreProcess import Distribution.Simple.Program import Distribution.Types.BuildInfo import Distribution.Verbosity import System.Directory ppHGen :: BuildInfo -> LocalBuildInfo -> ComponentLocalBuildInfo -> PreProcessor ppHGen _bi lbi _clbi = PreProcessor { platformIndependent = True , ppOrdering = unsorted , runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity -> copyFile inFile outFile } main :: IO () main = defaultMainWithHooks simpleUserHooks { hookedPreProcessors = ("hgen", ppHGen) : hookedPreProcessors simpleUserHooks }
301ecc887fc3ba266a49160e3f8e0e91e89fea1ea9b1d47cbe7bfec39d471cf5
kwanghoon/polyrpc
Token.hs
module Token where import Prelude hiding(EQ) import TokenInterface data Token = END_OF_TOKEN | OPEN_PAREN_TOKEN | CLOSE_PAREN_TOKEN | OPEN_BRACE_TOKEN | CLOSE_BRACE_TOKEN | OPEN_BRACKET_TOKEN | CLOSE_BRACKET_TOKEN | IDENTIFIER_TOKEN | LOCFUN_TOKEN | FUN_TOKEN | FORALL_TOKEN | EXISTS_TOKEN | DOT_TOKEN | COMMA_TOKEN | SEMICOLON_TOKEN | COLON_TOKEN | DEF_TOKEN -- = | BAR_TOKEN | BACKSLASH_TOKEN | KEYWORD_DATA_TOKEN | KEYWORD_LET_TOKEN | KEYWORD_END_TOKEN | KEYWORD_IF_TOKEN | KEYWORD_THEN_TOKEN | KEYWORD_ELSE_TOKEN | KEYWORD_CASE_TOKEN | KEYWORD_OR_TOKEN | KEYWORD_AND_TOKEN | AT_TOKEN | ALT_ARROW_TOKEN | NOT_TOKEN | NOTEQUAL_TOKEN | EQUAL_TOKEN -- == | LESSTHAN_TOKEN | LESSEQUAL_TOKEN | GREATERTHAN_TOKEN | GREATEREQUAL_TOKEN | ADD_TOKEN | SUB_TOKEN | MUL_TOKEN | DIV_TOKEN | ASSIGN_TOKEN | INTEGER_TOKEN | BOOLEAN_TOKEN | STRING_TOKEN | UNIT_TYPE_TOKEN | INTEGER_TYPE_TOKEN | BOOLEAN_TYPE_TOKEN | STRING_TYPE_TOKEN deriving (Eq, Show) tokenStrList :: [(Token,String)] tokenStrList = [ (END_OF_TOKEN, "$"), (OPEN_PAREN_TOKEN, "("), (CLOSE_PAREN_TOKEN, ")"), (OPEN_BRACE_TOKEN, "{"), (CLOSE_BRACE_TOKEN, "}"), (OPEN_BRACKET_TOKEN, "["), (CLOSE_BRACKET_TOKEN, "]"), (IDENTIFIER_TOKEN, "identifier"), (LOCFUN_TOKEN, "locFun"), (FUN_TOKEN, "->"), (FORALL_TOKEN, "forall"), (EXISTS_TOKEN, "exists"), (DOT_TOKEN, "."), (COMMA_TOKEN, ","), (SEMICOLON_TOKEN, ";"), (COLON_TOKEN, ":"), (DEF_TOKEN, "="), (BAR_TOKEN, "|"), (BACKSLASH_TOKEN, "\\"), (KEYWORD_DATA_TOKEN, "data"), (KEYWORD_LET_TOKEN, "let"), (KEYWORD_END_TOKEN, "end"), (KEYWORD_IF_TOKEN, "if"), (KEYWORD_THEN_TOKEN, "then"), (KEYWORD_ELSE_TOKEN, "else"), (KEYWORD_CASE_TOKEN, "case"), (KEYWORD_OR_TOKEN, "or"), (KEYWORD_AND_TOKEN, "and"), (AT_TOKEN, "@"), (ALT_ARROW_TOKEN, "=>"), (NOT_TOKEN, "!"), (NOTEQUAL_TOKEN, "!="), (EQUAL_TOKEN, "=="), (LESSTHAN_TOKEN, "<"), (LESSEQUAL_TOKEN, "<="), (GREATERTHAN_TOKEN, ">"), (GREATEREQUAL_TOKEN, ">="), (ADD_TOKEN, "+"), (SUB_TOKEN, "-"), (MUL_TOKEN, "*"), (DIV_TOKEN, "/"), (ASSIGN_TOKEN, ":="), (INTEGER_TOKEN, "integer"), (BOOLEAN_TOKEN, "boolean"), (STRING_TOKEN, "string") ( UNIT_TYPE_TOKEN , " Unit " ) , ( INTEGER_TYPE_TOKEN , " Int " ) , ( BOOLEAN_TYPE_TOKEN , " " ) , ( STRING_TYPE_TOKEN , " String " ) ] findTok tok [] = Nothing findTok tok ((tok_,str):list) | tok == tok_ = Just str | otherwise = findTok tok list findStr str [] = Nothing findStr str ((tok,str_):list) | str == str_ = Just tok | otherwise = findStr str list instance TokenInterface Token where fromToken tok = case findTok tok tokenStrList of Nothing -> error ("fromToken: " ++ show tok) Just str -> str isEOT END_OF_TOKEN = True isEOT _ = False
null
https://raw.githubusercontent.com/kwanghoon/polyrpc/50bca2be26004ffd36ea059ccda7be077a0f6706/app/Token.hs
haskell
= ==
module Token where import Prelude hiding(EQ) import TokenInterface data Token = END_OF_TOKEN | OPEN_PAREN_TOKEN | CLOSE_PAREN_TOKEN | OPEN_BRACE_TOKEN | CLOSE_BRACE_TOKEN | OPEN_BRACKET_TOKEN | CLOSE_BRACKET_TOKEN | IDENTIFIER_TOKEN | LOCFUN_TOKEN | FUN_TOKEN | FORALL_TOKEN | EXISTS_TOKEN | DOT_TOKEN | COMMA_TOKEN | SEMICOLON_TOKEN | COLON_TOKEN | BAR_TOKEN | BACKSLASH_TOKEN | KEYWORD_DATA_TOKEN | KEYWORD_LET_TOKEN | KEYWORD_END_TOKEN | KEYWORD_IF_TOKEN | KEYWORD_THEN_TOKEN | KEYWORD_ELSE_TOKEN | KEYWORD_CASE_TOKEN | KEYWORD_OR_TOKEN | KEYWORD_AND_TOKEN | AT_TOKEN | ALT_ARROW_TOKEN | NOT_TOKEN | NOTEQUAL_TOKEN | LESSTHAN_TOKEN | LESSEQUAL_TOKEN | GREATERTHAN_TOKEN | GREATEREQUAL_TOKEN | ADD_TOKEN | SUB_TOKEN | MUL_TOKEN | DIV_TOKEN | ASSIGN_TOKEN | INTEGER_TOKEN | BOOLEAN_TOKEN | STRING_TOKEN | UNIT_TYPE_TOKEN | INTEGER_TYPE_TOKEN | BOOLEAN_TYPE_TOKEN | STRING_TYPE_TOKEN deriving (Eq, Show) tokenStrList :: [(Token,String)] tokenStrList = [ (END_OF_TOKEN, "$"), (OPEN_PAREN_TOKEN, "("), (CLOSE_PAREN_TOKEN, ")"), (OPEN_BRACE_TOKEN, "{"), (CLOSE_BRACE_TOKEN, "}"), (OPEN_BRACKET_TOKEN, "["), (CLOSE_BRACKET_TOKEN, "]"), (IDENTIFIER_TOKEN, "identifier"), (LOCFUN_TOKEN, "locFun"), (FUN_TOKEN, "->"), (FORALL_TOKEN, "forall"), (EXISTS_TOKEN, "exists"), (DOT_TOKEN, "."), (COMMA_TOKEN, ","), (SEMICOLON_TOKEN, ";"), (COLON_TOKEN, ":"), (DEF_TOKEN, "="), (BAR_TOKEN, "|"), (BACKSLASH_TOKEN, "\\"), (KEYWORD_DATA_TOKEN, "data"), (KEYWORD_LET_TOKEN, "let"), (KEYWORD_END_TOKEN, "end"), (KEYWORD_IF_TOKEN, "if"), (KEYWORD_THEN_TOKEN, "then"), (KEYWORD_ELSE_TOKEN, "else"), (KEYWORD_CASE_TOKEN, "case"), (KEYWORD_OR_TOKEN, "or"), (KEYWORD_AND_TOKEN, "and"), (AT_TOKEN, "@"), (ALT_ARROW_TOKEN, "=>"), (NOT_TOKEN, "!"), (NOTEQUAL_TOKEN, "!="), (EQUAL_TOKEN, "=="), (LESSTHAN_TOKEN, "<"), (LESSEQUAL_TOKEN, "<="), (GREATERTHAN_TOKEN, ">"), (GREATEREQUAL_TOKEN, ">="), (ADD_TOKEN, "+"), (SUB_TOKEN, "-"), (MUL_TOKEN, "*"), (DIV_TOKEN, "/"), (ASSIGN_TOKEN, ":="), (INTEGER_TOKEN, "integer"), (BOOLEAN_TOKEN, "boolean"), (STRING_TOKEN, "string") ( UNIT_TYPE_TOKEN , " Unit " ) , ( INTEGER_TYPE_TOKEN , " Int " ) , ( BOOLEAN_TYPE_TOKEN , " " ) , ( STRING_TYPE_TOKEN , " String " ) ] findTok tok [] = Nothing findTok tok ((tok_,str):list) | tok == tok_ = Just str | otherwise = findTok tok list findStr str [] = Nothing findStr str ((tok,str_):list) | str == str_ = Just tok | otherwise = findStr str list instance TokenInterface Token where fromToken tok = case findTok tok tokenStrList of Nothing -> error ("fromToken: " ++ show tok) Just str -> str isEOT END_OF_TOKEN = True isEOT _ = False
b5aa567ecaa0001be664e415784abf4339892d759710e0cab954c096573f0769
LexiFi/menhir
keyword.mli
(******************************************************************************) (* *) (* *) , Paris , PPS , Université Paris Diderot (* *) . All rights reserved . This file is distributed under the terms of the GNU General Public License version 2 , as described in the (* file LICENSE. *) (* *) (******************************************************************************) (* This module provides some type and function definitions that help deal with the keywords that we recognize within semantic actions. *) (* The user can request position information either at several types: - a simple offset of type [int], e.g., via $startofs; - a position of type [Lexing.position], e.g., via $startpos; - a location, e.g., via $loc. A location is currently represented as a pair of positions, but this might change in the future; we may allow the user to choose a custom type of locations. *) type flavor = | FlavorOffset | FlavorPosition | FlavorLocation The user can request position information about the $ start or $ end of a symbol . Also , $ symbolstart requests the computation of the start position of the first nonempty element in a production . of a symbol. Also, $symbolstart requests the computation of the start position of the first nonempty element in a production. *) type where = | WhereSymbolStart | WhereStart | WhereEnd The user can request position information about a production 's left - hand side or about one of the symbols in its right - hand side , which he must refer to by name . ( Referring to its symbol by its position , using [ $ i ] , is permitted in the concrete syntax , but the lexer eliminates this form . ) We add a new subject , [ Before ] , which corresponds to [ $ endpos($0 ) ] in concrete syntax . We adopt the ( slightly awkward ) convention that when the subject is [ Before ] , the [ where ] component must be [ WhereEnd ] . If [ flavor ] is [ FlavorLocation ] , then [ where ] must be [ WhereSymbolStart ] or [ WhereStart ] . In the former case , [ subject ] must be [ Left ] ; this corresponds to $ sloc in concrete syntax . In the latter case , [ subject ] must be [ Left ] or [ RightNamed _ ] ; this corresponds to $ loc and $ loc(x ) in concrete syntax . left-hand side or about one of the symbols in its right-hand side, which he must refer to by name. (Referring to its symbol by its position, using [$i], is permitted in the concrete syntax, but the lexer eliminates this form.) We add a new subject, [Before], which corresponds to [$endpos($0)] in concrete syntax. We adopt the (slightly awkward) convention that when the subject is [Before], the [where] component must be [WhereEnd]. If [flavor] is [FlavorLocation], then [where] must be [WhereSymbolStart] or [WhereStart]. In the former case, [subject] must be [Left]; this corresponds to $sloc in concrete syntax. In the latter case, [subject] must be [Left] or [RightNamed _]; this corresponds to $loc and $loc(x) in concrete syntax. *) type subject = | Before | Left | RightNamed of string (* Keywords inside semantic actions. They allow access to semantic values or to position information. *) type keyword = | Position of subject * where * flavor | SyntaxError (* This maps a [Position] keyword to the name of the variable that the keyword is replaced with. *) val posvar: subject -> where -> flavor -> string (* Sets of keywords. *) module KeywordSet : sig include Set.S with type elt = keyword val map: (keyword -> keyword) -> t -> t end
null
https://raw.githubusercontent.com/LexiFi/menhir/794e64e7997d4d3f91d36dd49aaecc942ea858b7/sdk/keyword.mli
ocaml
**************************************************************************** file LICENSE. **************************************************************************** This module provides some type and function definitions that help deal with the keywords that we recognize within semantic actions. The user can request position information either at several types: - a simple offset of type [int], e.g., via $startofs; - a position of type [Lexing.position], e.g., via $startpos; - a location, e.g., via $loc. A location is currently represented as a pair of positions, but this might change in the future; we may allow the user to choose a custom type of locations. Keywords inside semantic actions. They allow access to semantic values or to position information. This maps a [Position] keyword to the name of the variable that the keyword is replaced with. Sets of keywords.
, Paris , PPS , Université Paris Diderot . All rights reserved . This file is distributed under the terms of the GNU General Public License version 2 , as described in the type flavor = | FlavorOffset | FlavorPosition | FlavorLocation The user can request position information about the $ start or $ end of a symbol . Also , $ symbolstart requests the computation of the start position of the first nonempty element in a production . of a symbol. Also, $symbolstart requests the computation of the start position of the first nonempty element in a production. *) type where = | WhereSymbolStart | WhereStart | WhereEnd The user can request position information about a production 's left - hand side or about one of the symbols in its right - hand side , which he must refer to by name . ( Referring to its symbol by its position , using [ $ i ] , is permitted in the concrete syntax , but the lexer eliminates this form . ) We add a new subject , [ Before ] , which corresponds to [ $ endpos($0 ) ] in concrete syntax . We adopt the ( slightly awkward ) convention that when the subject is [ Before ] , the [ where ] component must be [ WhereEnd ] . If [ flavor ] is [ FlavorLocation ] , then [ where ] must be [ WhereSymbolStart ] or [ WhereStart ] . In the former case , [ subject ] must be [ Left ] ; this corresponds to $ sloc in concrete syntax . In the latter case , [ subject ] must be [ Left ] or [ RightNamed _ ] ; this corresponds to $ loc and $ loc(x ) in concrete syntax . left-hand side or about one of the symbols in its right-hand side, which he must refer to by name. (Referring to its symbol by its position, using [$i], is permitted in the concrete syntax, but the lexer eliminates this form.) We add a new subject, [Before], which corresponds to [$endpos($0)] in concrete syntax. We adopt the (slightly awkward) convention that when the subject is [Before], the [where] component must be [WhereEnd]. If [flavor] is [FlavorLocation], then [where] must be [WhereSymbolStart] or [WhereStart]. In the former case, [subject] must be [Left]; this corresponds to $sloc in concrete syntax. In the latter case, [subject] must be [Left] or [RightNamed _]; this corresponds to $loc and $loc(x) in concrete syntax. *) type subject = | Before | Left | RightNamed of string type keyword = | Position of subject * where * flavor | SyntaxError val posvar: subject -> where -> flavor -> string module KeywordSet : sig include Set.S with type elt = keyword val map: (keyword -> keyword) -> t -> t end
b0e021908fe225efb3613954b73a018c968ae0519eae6c8d266e4aff835937fd
brianhempel/maniposynth
primitives.ml
open Data open open Runtime_lib open Runtime_base open Runtime_stdlib open Runtime_compiler let exp_of_desc loc desc = Parsetree.{ pexp_desc = desc; pexp_loc = loc; pexp_attributes = [] } let seq_or loc = function | [ (_, arg1); (_, arg2) ] -> let open Parsetree in let expr_true = Pexp_construct ({ txt = Longident.Lident "true"; loc }, None) in Some (exp_of_desc loc (Pexp_ifthenelse (arg1, exp_of_desc loc expr_true, Some arg2))) | _ -> None let seq_and loc = function | [ (_, arg1); (_, arg2) ] -> let open Parsetree in let expr_false = Pexp_construct ({ txt = Longident.Lident "false"; loc }, None) in Some (exp_of_desc loc (Pexp_ifthenelse (arg1, arg2, Some (exp_of_desc loc expr_false)))) | _ -> None let apply loc = function | [ (_, f); (_, x) ] -> let open Parsetree in Some (exp_of_desc loc (Pexp_apply (f, [ (Nolabel, x) ]))) | _ -> None let rev_apply loc = function | [ (_, x); (_, f) ] -> let open Parsetree in Some (exp_of_desc loc (Pexp_apply (f, [ (Asttypes.Nolabel, x) ]))) | _ -> None external reraise : exn -> 'a = "%reraise" external raise_notrace : exn -> 'a = "%raise_notrace" let prims = let prim1 f = prim1 f Runtime_base.wrap_exn in let prim2 f = prim2 f Runtime_base.wrap_exn in let prim3 f = prim3 f Runtime_base.wrap_exn in let prim4 f = prim4 f Runtime_base.wrap_exn in let prim5 f = prim5 f Runtime_base.wrap_exn in [ ("%apply", ptr @@ Fexpr apply); ("%revapply", ptr @@ Fexpr rev_apply); ("%raise", ptr @@ Prim (fun v -> raise (InternalException v))); ("%reraise", ptr @@ Prim (fun v -> reraise (InternalException v))); ("%raise_notrace", ptr @@ Prim (fun v -> raise_notrace (InternalException v))); ("%sequand", ptr @@ Fexpr seq_and); ("%sequor", ptr @@ Fexpr seq_or); ("%boolnot", prim1 not unwrap_bool wrap_bool); ("%negint", prim1 ( ~- ) unwrap_int wrap_int); ("%succint", prim1 succ unwrap_int wrap_int); ("%predint", prim1 pred unwrap_int wrap_int); ("%addint", prim2 ( + ) unwrap_int unwrap_int wrap_int); ("%subint", prim2 ( - ) unwrap_int unwrap_int wrap_int); ("%mulint", prim2 ( * ) unwrap_int unwrap_int wrap_int); ("%divint", prim2 ( / ) unwrap_int unwrap_int wrap_int); ("%modint", prim2 ( mod ) unwrap_int unwrap_int wrap_int); ("%andint", prim2 ( land ) unwrap_int unwrap_int wrap_int); ("%orint", prim2 ( lor ) unwrap_int unwrap_int wrap_int); ("%xorint", prim2 ( lxor ) unwrap_int unwrap_int wrap_int); ("%lslint", prim2 ( lsl ) unwrap_int unwrap_int wrap_int); ("%lsrint", prim2 ( lsr ) unwrap_int unwrap_int wrap_int); ("%asrint", prim2 ( asr ) unwrap_int unwrap_int wrap_int); ("%addfloat", prim2 ( +. ) unwrap_float unwrap_float wrap_float); ("%subfloat", prim2 ( -. ) unwrap_float unwrap_float wrap_float); ("%mulfloat", prim2 ( *. ) unwrap_float unwrap_float wrap_float); ("%divfloat", prim2 ( /. ) unwrap_float unwrap_float wrap_float); ("%floatofint", prim1 float_of_int unwrap_int wrap_float); ("%intoffloat", prim1 int_of_float unwrap_float wrap_int); ("%lessthan", prim2 value_lt id id wrap_bool); ("%lessequal", prim2 value_le id id wrap_bool); ("%greaterthan", prim2 value_gt id id wrap_bool); ("%greaterequal", prim2 value_ge id id wrap_bool); ("%compare", prim2 value_compare id id wrap_int); ("%equal", prim2 value_equal id id wrap_bool); ("%notequal", prim2 value_equal id id (fun x -> wrap_bool (not x))); ("%eq", prim2 ( == ) id id wrap_bool); ("%noteq", prim2 ( != ) id id wrap_bool); ("%identity", ptr @@ Prim (fun x -> x)); ("caml_register_named_value", ptr @@ Prim (fun _ -> ptr @@ Prim (fun _ -> unit))); ( "caml_int64_float_of_bits", prim1 Int64.float_of_bits unwrap_int64 wrap_float ); ( "caml_ml_open_descriptor_out", prim1 open_descriptor_out unwrap_int wrap_out_channel ); ( "caml_ml_open_descriptor_in", prim1 open_descriptor_in unwrap_int wrap_in_channel ); ( "caml_sys_open", prim3 open_desc unwrap_string (unwrap_list unwrap_open_flag) unwrap_int wrap_int ); ( "caml_sys_close", prim1 close_desc unwrap_int wrap_unit ); ( "caml_sys_system_command", prim1 caml_sys_system_command unwrap_string wrap_int ); ( "caml_ml_set_channel_name", prim2 (fun v s -> match Ptr.get v with | InChannel ic -> set_in_channel_name ic s | OutChannel oc -> set_out_channel_name oc s | _ -> assert false) id unwrap_string wrap_unit ); ( "caml_ml_close_channel", prim1 (onptr @@ function | InChannel ic -> close_in ic | OutChannel oc -> close_out oc | _ -> assert false) id wrap_unit ); ( "caml_ml_out_channels_list", prim1 out_channels_list unwrap_unit (wrap_list wrap_out_channel) ); ( "caml_ml_output_bytes", prim4 unsafe_output unwrap_out_channel unwrap_bytes unwrap_int unwrap_int wrap_unit ); ( "caml_ml_output", prim4 unsafe_output_string unwrap_out_channel unwrap_string unwrap_int unwrap_int wrap_unit ); ( "caml_ml_output_int", prim2 output_binary_int unwrap_out_channel unwrap_int wrap_unit ); ( "caml_ml_output_char", prim2 output_char unwrap_out_channel unwrap_char wrap_unit ); ("caml_ml_flush", prim1 flush unwrap_out_channel wrap_unit); ("caml_ml_input_char", prim1 input_char unwrap_in_channel wrap_char); ("caml_ml_input_int", prim1 input_binary_int unwrap_in_channel wrap_int); ( "caml_ml_input_scan_line", prim1 input_scan_line unwrap_in_channel wrap_int ); ( "caml_ml_input", prim4 unsafe_input unwrap_in_channel unwrap_bytes unwrap_int unwrap_int wrap_int ); ("caml_ml_seek_in", prim2 seek_in unwrap_in_channel unwrap_int wrap_unit); ("caml_ml_pos_out", prim1 pos_out unwrap_out_channel wrap_int); ("caml_ml_pos_in", prim1 pos_in unwrap_in_channel wrap_int); ("caml_ml_seek_out", prim2 seek_out unwrap_out_channel unwrap_int wrap_unit); ("%makemutable", ptr @@ Prim (fun v -> ptr @@ Record (SMap.singleton "contents" (ref v)))); ( "%field0", ptr @@ Prim (onptr @@ function | Record r -> !(SMap.find "contents" r) | Tuple l -> List.hd l | _ -> assert false) ); ( "%field1", ptr @@ Prim (onptr @@ function | Tuple l -> List.hd (List.tl l) | _ -> assert false) ); ( "%setfield0", ptr @@ Prim (onptr @@ function | Record r -> ptr @@ Prim (fun v -> SMap.find "contents" r := v; unit) | _ -> assert false) ); ( "%incr", ptr @@ Prim (onptr @@ function | Record r -> let z = SMap.find "contents" r in z := wrap_int (unwrap_int !z + 1); unit | _ -> assert false) ); ( "%decr", ptr @@ Prim (onptr @@ function | Record r -> let z = SMap.find "contents" r in z := wrap_int (unwrap_int !z - 1); unit | _ -> assert false) ); ("%ignore", ptr @@ Prim (fun _ -> unit)); ("caml_format_int", prim2 format_int unwrap_string unwrap_int wrap_string); ( "caml_format_float", prim2 format_float unwrap_string unwrap_float wrap_string ); ("caml_int32_format", prim2 caml_int32_format unwrap_string unwrap_int32 wrap_string); ("caml_int64_format", prim2 caml_int64_format unwrap_string unwrap_int64 wrap_string); ("caml_nativeint_format", prim2 caml_nativeint_format unwrap_string unwrap_nativeint wrap_string); ("caml_int_of_string", prim1 int_of_string unwrap_string wrap_int); ("caml_float_of_string", prim1 float_of_string unwrap_string wrap_float); ( "caml_output_value", prim3 marshal_to_channel unwrap_out_channel id (unwrap_list unwrap_unit) wrap_unit ); ( "caml_output_value_to_buffer", prim5 Marshal.to_buffer unwrap_bytes unwrap_int unwrap_int id (unwrap_list unwrap_marshal_flag) wrap_int ); ( "caml_output_value_to_string", prim2 caml_output_value_to_string id (unwrap_list unwrap_marshal_flag) wrap_string ); ("caml_input_value", prim1 input_value unwrap_in_channel id); ("caml_sys_exit", prim1 exit unwrap_int wrap_unit); ("caml_parse_engine", parse_engine_prim); ("caml_lex_engine", lex_engine_prim); ("caml_new_lex_engine", new_lex_engine_prim); Sys ( "caml_sys_get_argv", ptr @@ Prim (fun _ -> ptr @@ Tuple [ wrap_string ""; ptr @@ Array (Array.map wrap_string Sys.argv) ]) ); ( "caml_sys_get_config", ptr @@ Prim (fun _ -> ptr @@ Tuple [ wrap_string "Unix"; wrap_int 0; wrap_bool true ]) ); ("%big_endian", ptr @@ Prim (fun _ -> wrap_bool Sys.big_endian)); ("%word_size", ptr @@ Prim (fun _ -> ptr @@ Int 64)); ("%int_size", ptr @@ Prim (fun _ -> ptr @@ Int 64)); ("%max_wosize", ptr @@ Prim (fun _ -> ptr @@ Int 1000000)); ("%ostype_unix", ptr @@ Prim (fun _ -> wrap_bool false)); ("%ostype_win32", ptr @@ Prim (fun _ -> wrap_bool false)); ("%ostype_cygwin", ptr @@ Prim (fun _ -> wrap_bool false)); ( "%backend_type", ptr @@ Prim (fun _ -> ptr @@ Constructor ("Other", 0, Some (wrap_string "Interpreter"))) ); ("caml_sys_getenv", prim1 Sys.getenv unwrap_string wrap_string); ("caml_sys_file_exists", prim1 Sys.file_exists unwrap_string wrap_bool); ("caml_sys_getcwd", prim1 Sys.getcwd unwrap_unit wrap_string); ("caml_sys_rename", prim2 Sys.rename unwrap_string unwrap_string wrap_unit); ("caml_sys_remove", prim1 Sys.remove unwrap_string wrap_unit); Bytes ("caml_create_bytes", prim1 Bytes.create unwrap_int wrap_bytes); ( "caml_fill_bytes", prim4 Bytes.unsafe_fill unwrap_bytes unwrap_int unwrap_int unwrap_char wrap_unit ); ("%bytes_to_string", ptr @@ Prim (fun v -> v)); ("%bytes_of_string", ptr @@ Prim (fun v -> v)); ("%string_length", prim1 Bytes.length unwrap_bytes wrap_int); ("%bytes_length", prim1 Bytes.length unwrap_bytes wrap_int); ("%string_safe_get", prim2 Bytes.get unwrap_bytes unwrap_int wrap_char); ( "%string_unsafe_get", prim2 Bytes.unsafe_get unwrap_bytes unwrap_int wrap_char ); ("%bytes_safe_get", prim2 Bytes.get unwrap_bytes unwrap_int wrap_char); ( "%bytes_unsafe_get", prim2 Bytes.unsafe_get unwrap_bytes unwrap_int wrap_char ); ( "%bytes_safe_set", prim3 Bytes.set unwrap_bytes unwrap_int unwrap_char wrap_unit ); ( "%bytes_unsafe_set", prim3 Bytes.unsafe_set unwrap_bytes unwrap_int unwrap_char wrap_unit ); ( "caml_blit_string", prim5 String.blit unwrap_string unwrap_int unwrap_bytes unwrap_int unwrap_int wrap_unit ); ( "caml_blit_bytes", prim5 Bytes.blit unwrap_bytes unwrap_int unwrap_bytes unwrap_int unwrap_int wrap_unit ); (* Lazy *) ( "%lazy_force", ptr @@ Prim (onptr @@ function | Lz f -> let v = !f () in (f := fun () -> v); v | _ -> assert false) ); Int64 ("%int64_neg", prim1 Int64.neg unwrap_int64 wrap_int64); ("%int64_add", prim2 Int64.add unwrap_int64 unwrap_int64 wrap_int64); ("%int64_sub", prim2 Int64.sub unwrap_int64 unwrap_int64 wrap_int64); ("%int64_mul", prim2 Int64.mul unwrap_int64 unwrap_int64 wrap_int64); ("%int64_div", prim2 Int64.div unwrap_int64 unwrap_int64 wrap_int64); ("%int64_mod", prim2 Int64.rem unwrap_int64 unwrap_int64 wrap_int64); ("%int64_and", prim2 Int64.logand unwrap_int64 unwrap_int64 wrap_int64); ("%int64_or", prim2 Int64.logor unwrap_int64 unwrap_int64 wrap_int64); ("%int64_xor", prim2 Int64.logxor unwrap_int64 unwrap_int64 wrap_int64); ("%int64_lsl", prim2 Int64.shift_left unwrap_int64 unwrap_int wrap_int64); ( "%int64_lsr", prim2 Int64.shift_right_logical unwrap_int64 unwrap_int wrap_int64 ); ("%int64_asr", prim2 Int64.shift_right unwrap_int64 unwrap_int wrap_int64); ("%int64_of_int", prim1 Int64.of_int unwrap_int wrap_int64); ("%int64_to_int", prim1 Int64.to_int unwrap_int64 wrap_int); ("%int64_to_int32", prim1 Int64.to_int32 unwrap_int64 wrap_int32); ("%int64_of_int32", prim1 Int64.of_int32 unwrap_int32 wrap_int64); ("%int64_of_nativeint", prim1 Int64.of_nativeint unwrap_nativeint wrap_int64); ("%int64_to_nativeint", prim1 Int64.to_nativeint unwrap_int64 wrap_nativeint); ("caml_int64_of_string", prim1 Int64.of_string unwrap_string wrap_int64); Int32 ("caml_int32_of_string", prim1 int_of_string unwrap_string wrap_int); ("%int32_neg", prim1 ( ~- ) unwrap_int wrap_int); Nativeint ("%nativeint_neg", prim1 Nativeint.neg unwrap_nativeint wrap_nativeint); ("%nativeint_add", prim2 Nativeint.add unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_sub", prim2 Nativeint.sub unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_mul", prim2 Nativeint.mul unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_div", prim2 Nativeint.div unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_mod", prim2 Nativeint.rem unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_and", prim2 Nativeint.logand unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_or", prim2 Nativeint.logor unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_xor", prim2 Nativeint.logxor unwrap_nativeint unwrap_nativeint wrap_nativeint); ( "%nativeint_lsl", prim2 Nativeint.shift_left unwrap_nativeint unwrap_int wrap_nativeint ); ( "%nativeint_lsr", prim2 Nativeint.shift_right_logical unwrap_nativeint unwrap_int wrap_nativeint ); ( "%nativeint_asr", prim2 Nativeint.shift_right unwrap_nativeint unwrap_int wrap_nativeint ); ("%nativeint_of_int", prim1 Nativeint.of_int unwrap_int wrap_nativeint); ("%nativeint_to_int", prim1 Nativeint.to_int unwrap_nativeint wrap_int); ("caml_nativeint_of_string", prim1 Nativeint.of_string unwrap_string wrap_nativeint); (* Array *) ("caml_make_vect", prim2 Array.make unwrap_int id wrap_array_id); ("%array_length", prim1 Array.length unwrap_array_id wrap_int); ( "caml_array_sub", prim3 Array.sub unwrap_array_id unwrap_int unwrap_int wrap_array_id ); ( "caml_array_concat", prim1 Array.concat (unwrap_list unwrap_array_id) wrap_array_id ); ("%array_safe_get", prim2 Array.get unwrap_array_id unwrap_int id); ("%array_unsafe_get", prim2 Array.unsafe_get unwrap_array_id unwrap_int id); ("%array_safe_set", prim3 Array.set unwrap_array_id unwrap_int id wrap_unit); ( "%array_unsafe_set", prim3 Array.unsafe_set unwrap_array_id unwrap_int id wrap_unit ); ( "caml_array_blit", prim5 Array.blit unwrap_array_id unwrap_int unwrap_array_id unwrap_int unwrap_int wrap_unit ); ( "caml_array_append", prim2 append_prim unwrap_array_id unwrap_array_id wrap_array_id ); ( "caml_hash", prim4 seeded_hash_param unwrap_int unwrap_int unwrap_int id wrap_int ); (* TODO: records defined in different order... *) (* Weak *) ( "caml_weak_create", prim1 (fun n -> Array.make n (ptr @@ Constructor ("None", 0, None))) unwrap_int wrap_array_id ); ("caml_weak_get", prim2 (fun a n -> a.(n)) unwrap_array_id unwrap_int id); ( "caml_weak_get_copy", prim2 (fun a n -> a.(n)) unwrap_array_id unwrap_int id ); ( "caml_weak_set", prim3 (fun a n v -> a.(n) <- v) unwrap_array_id unwrap_int id wrap_unit ); ( "caml_weak_check", prim2 (fun a n -> Ptr.get a.(n) <> Constructor ("None", 0, None)) unwrap_array_id unwrap_int wrap_bool ); ( "caml_weak_blit", prim5 Array.blit unwrap_array_id unwrap_int unwrap_array_id unwrap_int unwrap_int wrap_unit ); (* Random *) ( "caml_sys_random_seed", prim1 random_seed unwrap_unit (wrap_array wrap_int) ); Spacetime ( "caml_spacetime_enabled", let module Prim = struct external spacetime_enabled : unit -> bool = "caml_spacetime_enabled" [@@noalloc] end in prim1 Prim.spacetime_enabled unwrap_unit wrap_bool ); Gc ("caml_gc_quick_stat", prim1 Gc.quick_stat unwrap_unit wrap_gc_stat); (* utils/profile.ml *) ( "caml_sys_time_include_children", let module Prim = struct external time_include_children : bool -> float = "caml_sys_time_include_children" end in prim1 Prim.time_include_children unwrap_bool wrap_float ); (* utils/misc.ml *) ( "caml_sys_isatty", let module Prim = struct external isatty : out_channel -> bool = "caml_sys_isatty" end in prim1 Prim.isatty unwrap_out_channel wrap_bool ); Digest ( "caml_md5_string", prim3 digest_unsafe_string unwrap_string unwrap_int unwrap_int wrap_string ); ( "caml_md5_chan", prim2 Digest.channel unwrap_in_channel unwrap_int wrap_string ); (* Ugly *) ( "%obj_size", prim1 (onptr @@ function | Array a -> Array.length a + 2 | _ -> 4) id wrap_int ); ( "caml_obj_block", prim2 (fun tag size -> let block = ptr @@ Array (Array.init size (fun _ -> ptr @@ Int 0)) in ptr @@ Constructor ("", tag, Some block)) unwrap_int unwrap_int id ); ( "%obj_set_field", prim3 (fun data idx v -> let err () = Format.eprintf "obj_set_field (%a).(%d) <- (%a)@." pp_print_value data idx pp_print_value v in match Ptr.get data with | Array arr -> arr.(idx) <- v | Constructor(_, _, Some arg) -> begin match Ptr.get arg with | Array arr -> arr.(idx) <- v | _ -> err (); assert false end | _ -> err (); assert false ) id unwrap_int id wrap_unit ); ] let prims = List.fold_left (fun env (name, v) -> SMap.add name v env) SMap.empty prims (* let () = Runtime_compiler.apply_ref := Eval.apply prims *)
null
https://raw.githubusercontent.com/brianhempel/maniposynth/9092013ddcb0964348ba8902a6f48cd9763b576e/synth_stats_model/camlboot_interpreter_for_stats/primitives.ml
ocaml
Lazy Array TODO: records defined in different order... Weak Random utils/profile.ml utils/misc.ml Ugly let () = Runtime_compiler.apply_ref := Eval.apply prims
open Data open open Runtime_lib open Runtime_base open Runtime_stdlib open Runtime_compiler let exp_of_desc loc desc = Parsetree.{ pexp_desc = desc; pexp_loc = loc; pexp_attributes = [] } let seq_or loc = function | [ (_, arg1); (_, arg2) ] -> let open Parsetree in let expr_true = Pexp_construct ({ txt = Longident.Lident "true"; loc }, None) in Some (exp_of_desc loc (Pexp_ifthenelse (arg1, exp_of_desc loc expr_true, Some arg2))) | _ -> None let seq_and loc = function | [ (_, arg1); (_, arg2) ] -> let open Parsetree in let expr_false = Pexp_construct ({ txt = Longident.Lident "false"; loc }, None) in Some (exp_of_desc loc (Pexp_ifthenelse (arg1, arg2, Some (exp_of_desc loc expr_false)))) | _ -> None let apply loc = function | [ (_, f); (_, x) ] -> let open Parsetree in Some (exp_of_desc loc (Pexp_apply (f, [ (Nolabel, x) ]))) | _ -> None let rev_apply loc = function | [ (_, x); (_, f) ] -> let open Parsetree in Some (exp_of_desc loc (Pexp_apply (f, [ (Asttypes.Nolabel, x) ]))) | _ -> None external reraise : exn -> 'a = "%reraise" external raise_notrace : exn -> 'a = "%raise_notrace" let prims = let prim1 f = prim1 f Runtime_base.wrap_exn in let prim2 f = prim2 f Runtime_base.wrap_exn in let prim3 f = prim3 f Runtime_base.wrap_exn in let prim4 f = prim4 f Runtime_base.wrap_exn in let prim5 f = prim5 f Runtime_base.wrap_exn in [ ("%apply", ptr @@ Fexpr apply); ("%revapply", ptr @@ Fexpr rev_apply); ("%raise", ptr @@ Prim (fun v -> raise (InternalException v))); ("%reraise", ptr @@ Prim (fun v -> reraise (InternalException v))); ("%raise_notrace", ptr @@ Prim (fun v -> raise_notrace (InternalException v))); ("%sequand", ptr @@ Fexpr seq_and); ("%sequor", ptr @@ Fexpr seq_or); ("%boolnot", prim1 not unwrap_bool wrap_bool); ("%negint", prim1 ( ~- ) unwrap_int wrap_int); ("%succint", prim1 succ unwrap_int wrap_int); ("%predint", prim1 pred unwrap_int wrap_int); ("%addint", prim2 ( + ) unwrap_int unwrap_int wrap_int); ("%subint", prim2 ( - ) unwrap_int unwrap_int wrap_int); ("%mulint", prim2 ( * ) unwrap_int unwrap_int wrap_int); ("%divint", prim2 ( / ) unwrap_int unwrap_int wrap_int); ("%modint", prim2 ( mod ) unwrap_int unwrap_int wrap_int); ("%andint", prim2 ( land ) unwrap_int unwrap_int wrap_int); ("%orint", prim2 ( lor ) unwrap_int unwrap_int wrap_int); ("%xorint", prim2 ( lxor ) unwrap_int unwrap_int wrap_int); ("%lslint", prim2 ( lsl ) unwrap_int unwrap_int wrap_int); ("%lsrint", prim2 ( lsr ) unwrap_int unwrap_int wrap_int); ("%asrint", prim2 ( asr ) unwrap_int unwrap_int wrap_int); ("%addfloat", prim2 ( +. ) unwrap_float unwrap_float wrap_float); ("%subfloat", prim2 ( -. ) unwrap_float unwrap_float wrap_float); ("%mulfloat", prim2 ( *. ) unwrap_float unwrap_float wrap_float); ("%divfloat", prim2 ( /. ) unwrap_float unwrap_float wrap_float); ("%floatofint", prim1 float_of_int unwrap_int wrap_float); ("%intoffloat", prim1 int_of_float unwrap_float wrap_int); ("%lessthan", prim2 value_lt id id wrap_bool); ("%lessequal", prim2 value_le id id wrap_bool); ("%greaterthan", prim2 value_gt id id wrap_bool); ("%greaterequal", prim2 value_ge id id wrap_bool); ("%compare", prim2 value_compare id id wrap_int); ("%equal", prim2 value_equal id id wrap_bool); ("%notequal", prim2 value_equal id id (fun x -> wrap_bool (not x))); ("%eq", prim2 ( == ) id id wrap_bool); ("%noteq", prim2 ( != ) id id wrap_bool); ("%identity", ptr @@ Prim (fun x -> x)); ("caml_register_named_value", ptr @@ Prim (fun _ -> ptr @@ Prim (fun _ -> unit))); ( "caml_int64_float_of_bits", prim1 Int64.float_of_bits unwrap_int64 wrap_float ); ( "caml_ml_open_descriptor_out", prim1 open_descriptor_out unwrap_int wrap_out_channel ); ( "caml_ml_open_descriptor_in", prim1 open_descriptor_in unwrap_int wrap_in_channel ); ( "caml_sys_open", prim3 open_desc unwrap_string (unwrap_list unwrap_open_flag) unwrap_int wrap_int ); ( "caml_sys_close", prim1 close_desc unwrap_int wrap_unit ); ( "caml_sys_system_command", prim1 caml_sys_system_command unwrap_string wrap_int ); ( "caml_ml_set_channel_name", prim2 (fun v s -> match Ptr.get v with | InChannel ic -> set_in_channel_name ic s | OutChannel oc -> set_out_channel_name oc s | _ -> assert false) id unwrap_string wrap_unit ); ( "caml_ml_close_channel", prim1 (onptr @@ function | InChannel ic -> close_in ic | OutChannel oc -> close_out oc | _ -> assert false) id wrap_unit ); ( "caml_ml_out_channels_list", prim1 out_channels_list unwrap_unit (wrap_list wrap_out_channel) ); ( "caml_ml_output_bytes", prim4 unsafe_output unwrap_out_channel unwrap_bytes unwrap_int unwrap_int wrap_unit ); ( "caml_ml_output", prim4 unsafe_output_string unwrap_out_channel unwrap_string unwrap_int unwrap_int wrap_unit ); ( "caml_ml_output_int", prim2 output_binary_int unwrap_out_channel unwrap_int wrap_unit ); ( "caml_ml_output_char", prim2 output_char unwrap_out_channel unwrap_char wrap_unit ); ("caml_ml_flush", prim1 flush unwrap_out_channel wrap_unit); ("caml_ml_input_char", prim1 input_char unwrap_in_channel wrap_char); ("caml_ml_input_int", prim1 input_binary_int unwrap_in_channel wrap_int); ( "caml_ml_input_scan_line", prim1 input_scan_line unwrap_in_channel wrap_int ); ( "caml_ml_input", prim4 unsafe_input unwrap_in_channel unwrap_bytes unwrap_int unwrap_int wrap_int ); ("caml_ml_seek_in", prim2 seek_in unwrap_in_channel unwrap_int wrap_unit); ("caml_ml_pos_out", prim1 pos_out unwrap_out_channel wrap_int); ("caml_ml_pos_in", prim1 pos_in unwrap_in_channel wrap_int); ("caml_ml_seek_out", prim2 seek_out unwrap_out_channel unwrap_int wrap_unit); ("%makemutable", ptr @@ Prim (fun v -> ptr @@ Record (SMap.singleton "contents" (ref v)))); ( "%field0", ptr @@ Prim (onptr @@ function | Record r -> !(SMap.find "contents" r) | Tuple l -> List.hd l | _ -> assert false) ); ( "%field1", ptr @@ Prim (onptr @@ function | Tuple l -> List.hd (List.tl l) | _ -> assert false) ); ( "%setfield0", ptr @@ Prim (onptr @@ function | Record r -> ptr @@ Prim (fun v -> SMap.find "contents" r := v; unit) | _ -> assert false) ); ( "%incr", ptr @@ Prim (onptr @@ function | Record r -> let z = SMap.find "contents" r in z := wrap_int (unwrap_int !z + 1); unit | _ -> assert false) ); ( "%decr", ptr @@ Prim (onptr @@ function | Record r -> let z = SMap.find "contents" r in z := wrap_int (unwrap_int !z - 1); unit | _ -> assert false) ); ("%ignore", ptr @@ Prim (fun _ -> unit)); ("caml_format_int", prim2 format_int unwrap_string unwrap_int wrap_string); ( "caml_format_float", prim2 format_float unwrap_string unwrap_float wrap_string ); ("caml_int32_format", prim2 caml_int32_format unwrap_string unwrap_int32 wrap_string); ("caml_int64_format", prim2 caml_int64_format unwrap_string unwrap_int64 wrap_string); ("caml_nativeint_format", prim2 caml_nativeint_format unwrap_string unwrap_nativeint wrap_string); ("caml_int_of_string", prim1 int_of_string unwrap_string wrap_int); ("caml_float_of_string", prim1 float_of_string unwrap_string wrap_float); ( "caml_output_value", prim3 marshal_to_channel unwrap_out_channel id (unwrap_list unwrap_unit) wrap_unit ); ( "caml_output_value_to_buffer", prim5 Marshal.to_buffer unwrap_bytes unwrap_int unwrap_int id (unwrap_list unwrap_marshal_flag) wrap_int ); ( "caml_output_value_to_string", prim2 caml_output_value_to_string id (unwrap_list unwrap_marshal_flag) wrap_string ); ("caml_input_value", prim1 input_value unwrap_in_channel id); ("caml_sys_exit", prim1 exit unwrap_int wrap_unit); ("caml_parse_engine", parse_engine_prim); ("caml_lex_engine", lex_engine_prim); ("caml_new_lex_engine", new_lex_engine_prim); Sys ( "caml_sys_get_argv", ptr @@ Prim (fun _ -> ptr @@ Tuple [ wrap_string ""; ptr @@ Array (Array.map wrap_string Sys.argv) ]) ); ( "caml_sys_get_config", ptr @@ Prim (fun _ -> ptr @@ Tuple [ wrap_string "Unix"; wrap_int 0; wrap_bool true ]) ); ("%big_endian", ptr @@ Prim (fun _ -> wrap_bool Sys.big_endian)); ("%word_size", ptr @@ Prim (fun _ -> ptr @@ Int 64)); ("%int_size", ptr @@ Prim (fun _ -> ptr @@ Int 64)); ("%max_wosize", ptr @@ Prim (fun _ -> ptr @@ Int 1000000)); ("%ostype_unix", ptr @@ Prim (fun _ -> wrap_bool false)); ("%ostype_win32", ptr @@ Prim (fun _ -> wrap_bool false)); ("%ostype_cygwin", ptr @@ Prim (fun _ -> wrap_bool false)); ( "%backend_type", ptr @@ Prim (fun _ -> ptr @@ Constructor ("Other", 0, Some (wrap_string "Interpreter"))) ); ("caml_sys_getenv", prim1 Sys.getenv unwrap_string wrap_string); ("caml_sys_file_exists", prim1 Sys.file_exists unwrap_string wrap_bool); ("caml_sys_getcwd", prim1 Sys.getcwd unwrap_unit wrap_string); ("caml_sys_rename", prim2 Sys.rename unwrap_string unwrap_string wrap_unit); ("caml_sys_remove", prim1 Sys.remove unwrap_string wrap_unit); Bytes ("caml_create_bytes", prim1 Bytes.create unwrap_int wrap_bytes); ( "caml_fill_bytes", prim4 Bytes.unsafe_fill unwrap_bytes unwrap_int unwrap_int unwrap_char wrap_unit ); ("%bytes_to_string", ptr @@ Prim (fun v -> v)); ("%bytes_of_string", ptr @@ Prim (fun v -> v)); ("%string_length", prim1 Bytes.length unwrap_bytes wrap_int); ("%bytes_length", prim1 Bytes.length unwrap_bytes wrap_int); ("%string_safe_get", prim2 Bytes.get unwrap_bytes unwrap_int wrap_char); ( "%string_unsafe_get", prim2 Bytes.unsafe_get unwrap_bytes unwrap_int wrap_char ); ("%bytes_safe_get", prim2 Bytes.get unwrap_bytes unwrap_int wrap_char); ( "%bytes_unsafe_get", prim2 Bytes.unsafe_get unwrap_bytes unwrap_int wrap_char ); ( "%bytes_safe_set", prim3 Bytes.set unwrap_bytes unwrap_int unwrap_char wrap_unit ); ( "%bytes_unsafe_set", prim3 Bytes.unsafe_set unwrap_bytes unwrap_int unwrap_char wrap_unit ); ( "caml_blit_string", prim5 String.blit unwrap_string unwrap_int unwrap_bytes unwrap_int unwrap_int wrap_unit ); ( "caml_blit_bytes", prim5 Bytes.blit unwrap_bytes unwrap_int unwrap_bytes unwrap_int unwrap_int wrap_unit ); ( "%lazy_force", ptr @@ Prim (onptr @@ function | Lz f -> let v = !f () in (f := fun () -> v); v | _ -> assert false) ); Int64 ("%int64_neg", prim1 Int64.neg unwrap_int64 wrap_int64); ("%int64_add", prim2 Int64.add unwrap_int64 unwrap_int64 wrap_int64); ("%int64_sub", prim2 Int64.sub unwrap_int64 unwrap_int64 wrap_int64); ("%int64_mul", prim2 Int64.mul unwrap_int64 unwrap_int64 wrap_int64); ("%int64_div", prim2 Int64.div unwrap_int64 unwrap_int64 wrap_int64); ("%int64_mod", prim2 Int64.rem unwrap_int64 unwrap_int64 wrap_int64); ("%int64_and", prim2 Int64.logand unwrap_int64 unwrap_int64 wrap_int64); ("%int64_or", prim2 Int64.logor unwrap_int64 unwrap_int64 wrap_int64); ("%int64_xor", prim2 Int64.logxor unwrap_int64 unwrap_int64 wrap_int64); ("%int64_lsl", prim2 Int64.shift_left unwrap_int64 unwrap_int wrap_int64); ( "%int64_lsr", prim2 Int64.shift_right_logical unwrap_int64 unwrap_int wrap_int64 ); ("%int64_asr", prim2 Int64.shift_right unwrap_int64 unwrap_int wrap_int64); ("%int64_of_int", prim1 Int64.of_int unwrap_int wrap_int64); ("%int64_to_int", prim1 Int64.to_int unwrap_int64 wrap_int); ("%int64_to_int32", prim1 Int64.to_int32 unwrap_int64 wrap_int32); ("%int64_of_int32", prim1 Int64.of_int32 unwrap_int32 wrap_int64); ("%int64_of_nativeint", prim1 Int64.of_nativeint unwrap_nativeint wrap_int64); ("%int64_to_nativeint", prim1 Int64.to_nativeint unwrap_int64 wrap_nativeint); ("caml_int64_of_string", prim1 Int64.of_string unwrap_string wrap_int64); Int32 ("caml_int32_of_string", prim1 int_of_string unwrap_string wrap_int); ("%int32_neg", prim1 ( ~- ) unwrap_int wrap_int); Nativeint ("%nativeint_neg", prim1 Nativeint.neg unwrap_nativeint wrap_nativeint); ("%nativeint_add", prim2 Nativeint.add unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_sub", prim2 Nativeint.sub unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_mul", prim2 Nativeint.mul unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_div", prim2 Nativeint.div unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_mod", prim2 Nativeint.rem unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_and", prim2 Nativeint.logand unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_or", prim2 Nativeint.logor unwrap_nativeint unwrap_nativeint wrap_nativeint); ("%nativeint_xor", prim2 Nativeint.logxor unwrap_nativeint unwrap_nativeint wrap_nativeint); ( "%nativeint_lsl", prim2 Nativeint.shift_left unwrap_nativeint unwrap_int wrap_nativeint ); ( "%nativeint_lsr", prim2 Nativeint.shift_right_logical unwrap_nativeint unwrap_int wrap_nativeint ); ( "%nativeint_asr", prim2 Nativeint.shift_right unwrap_nativeint unwrap_int wrap_nativeint ); ("%nativeint_of_int", prim1 Nativeint.of_int unwrap_int wrap_nativeint); ("%nativeint_to_int", prim1 Nativeint.to_int unwrap_nativeint wrap_int); ("caml_nativeint_of_string", prim1 Nativeint.of_string unwrap_string wrap_nativeint); ("caml_make_vect", prim2 Array.make unwrap_int id wrap_array_id); ("%array_length", prim1 Array.length unwrap_array_id wrap_int); ( "caml_array_sub", prim3 Array.sub unwrap_array_id unwrap_int unwrap_int wrap_array_id ); ( "caml_array_concat", prim1 Array.concat (unwrap_list unwrap_array_id) wrap_array_id ); ("%array_safe_get", prim2 Array.get unwrap_array_id unwrap_int id); ("%array_unsafe_get", prim2 Array.unsafe_get unwrap_array_id unwrap_int id); ("%array_safe_set", prim3 Array.set unwrap_array_id unwrap_int id wrap_unit); ( "%array_unsafe_set", prim3 Array.unsafe_set unwrap_array_id unwrap_int id wrap_unit ); ( "caml_array_blit", prim5 Array.blit unwrap_array_id unwrap_int unwrap_array_id unwrap_int unwrap_int wrap_unit ); ( "caml_array_append", prim2 append_prim unwrap_array_id unwrap_array_id wrap_array_id ); ( "caml_hash", prim4 seeded_hash_param unwrap_int unwrap_int unwrap_int id wrap_int ); ( "caml_weak_create", prim1 (fun n -> Array.make n (ptr @@ Constructor ("None", 0, None))) unwrap_int wrap_array_id ); ("caml_weak_get", prim2 (fun a n -> a.(n)) unwrap_array_id unwrap_int id); ( "caml_weak_get_copy", prim2 (fun a n -> a.(n)) unwrap_array_id unwrap_int id ); ( "caml_weak_set", prim3 (fun a n v -> a.(n) <- v) unwrap_array_id unwrap_int id wrap_unit ); ( "caml_weak_check", prim2 (fun a n -> Ptr.get a.(n) <> Constructor ("None", 0, None)) unwrap_array_id unwrap_int wrap_bool ); ( "caml_weak_blit", prim5 Array.blit unwrap_array_id unwrap_int unwrap_array_id unwrap_int unwrap_int wrap_unit ); ( "caml_sys_random_seed", prim1 random_seed unwrap_unit (wrap_array wrap_int) ); Spacetime ( "caml_spacetime_enabled", let module Prim = struct external spacetime_enabled : unit -> bool = "caml_spacetime_enabled" [@@noalloc] end in prim1 Prim.spacetime_enabled unwrap_unit wrap_bool ); Gc ("caml_gc_quick_stat", prim1 Gc.quick_stat unwrap_unit wrap_gc_stat); ( "caml_sys_time_include_children", let module Prim = struct external time_include_children : bool -> float = "caml_sys_time_include_children" end in prim1 Prim.time_include_children unwrap_bool wrap_float ); ( "caml_sys_isatty", let module Prim = struct external isatty : out_channel -> bool = "caml_sys_isatty" end in prim1 Prim.isatty unwrap_out_channel wrap_bool ); Digest ( "caml_md5_string", prim3 digest_unsafe_string unwrap_string unwrap_int unwrap_int wrap_string ); ( "caml_md5_chan", prim2 Digest.channel unwrap_in_channel unwrap_int wrap_string ); ( "%obj_size", prim1 (onptr @@ function | Array a -> Array.length a + 2 | _ -> 4) id wrap_int ); ( "caml_obj_block", prim2 (fun tag size -> let block = ptr @@ Array (Array.init size (fun _ -> ptr @@ Int 0)) in ptr @@ Constructor ("", tag, Some block)) unwrap_int unwrap_int id ); ( "%obj_set_field", prim3 (fun data idx v -> let err () = Format.eprintf "obj_set_field (%a).(%d) <- (%a)@." pp_print_value data idx pp_print_value v in match Ptr.get data with | Array arr -> arr.(idx) <- v | Constructor(_, _, Some arg) -> begin match Ptr.get arg with | Array arr -> arr.(idx) <- v | _ -> err (); assert false end | _ -> err (); assert false ) id unwrap_int id wrap_unit ); ] let prims = List.fold_left (fun env (name, v) -> SMap.add name v env) SMap.empty prims
c0e94e4c8daaf09b408bf0ed19593cacbfc6534d67498f1945d43f666a1b4604
TerrorJack/ghc-alter
quotOverflow.hs
import Control.Exception as E import Data.Int main :: IO () main = do putStrLn "Int8" mapM_ p =<< (f :: IO [Either Int8 String]) putStrLn "Int16" mapM_ p =<< (f :: IO [Either Int16 String]) putStrLn "Int32" mapM_ p =<< (f :: IO [Either Int32 String]) putStrLn "Int64" mapM_ p =<< (f :: IO [Either Int64 String]) putStrLn "Int" mapM_ p =<< (f :: IO [Either Int String]) where p (Left x) = print x p (Right e) = putStrLn e f :: (Integral a, Bounded a) => IO [Either a String] f = sequence [ g (minBound `div` (-1)), g (minBound `mod` (-1)), g (case minBound `divMod` (-1) of (x, _) -> x), g (case minBound `divMod` (-1) of (_, x) -> x), g (minBound `quot` (-1)), g (minBound `rem` (-1)), g (case minBound `quotRem` (-1) of (x, _) -> x), g (case minBound `quotRem` (-1) of (_, x) -> x) ] where g x = do x' <- evaluate x return (Left x') `E.catch` \e -> return (Right (show (e :: SomeException)))
null
https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/quotOverflow.hs
haskell
import Control.Exception as E import Data.Int main :: IO () main = do putStrLn "Int8" mapM_ p =<< (f :: IO [Either Int8 String]) putStrLn "Int16" mapM_ p =<< (f :: IO [Either Int16 String]) putStrLn "Int32" mapM_ p =<< (f :: IO [Either Int32 String]) putStrLn "Int64" mapM_ p =<< (f :: IO [Either Int64 String]) putStrLn "Int" mapM_ p =<< (f :: IO [Either Int String]) where p (Left x) = print x p (Right e) = putStrLn e f :: (Integral a, Bounded a) => IO [Either a String] f = sequence [ g (minBound `div` (-1)), g (minBound `mod` (-1)), g (case minBound `divMod` (-1) of (x, _) -> x), g (case minBound `divMod` (-1) of (_, x) -> x), g (minBound `quot` (-1)), g (minBound `rem` (-1)), g (case minBound `quotRem` (-1) of (x, _) -> x), g (case minBound `quotRem` (-1) of (_, x) -> x) ] where g x = do x' <- evaluate x return (Left x') `E.catch` \e -> return (Right (show (e :: SomeException)))
1563ff8598b473e0eca9917dfc50cfb063a19824d6bf1f6e85352c0bac799339
ppedrot/ocaml-melt
configure.ml
(**************************************************************************) Copyright ( c ) 2009 , (* All rights reserved. *) (* *) (* Redistribution and use in source and binary forms, with or without *) (* modification, are permitted provided that the following conditions are *) (* met: *) (* *) (* * Redistributions of source code must retain the above copyright *) (* notice, this list of conditions and the following disclaimer. *) (* * Redistributions in binary form must reproduce the above copyright *) (* notice, this list of conditions and the following disclaimer in the *) (* documentation and/or other materials provided with the distribution. *) (* * Neither the name of Melt 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 , 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. *) (**************************************************************************) open Format #use "totoconf.ml" let () = init ~file: "Config" ~spec: [ force "OCAMLC" "<path> OCaml bytecode compiler"; force "MLPOST" "<path> Mlpost library directory"; force "INSTALLBIN" "<path> Install directory (tool binaries)"; force "INSTALLLIB" "<path> Install directory (OCaml libraries)"; force "INSTALLMAN" "<path> Install directory (man pages)"; ] (); let ocamlc = SVar.make ~query: "OCaml bytecode compiler" ~guess: (guess_bins ["ocamlc.opt"; "ocamlc"]) "OCAMLC" in let ocaml_dir = Filename.dirname !!ocamlc in let ocaml_version = exec_line !!ocamlc ["-version"] in echo "OCaml version: %s" ocaml_version; let ocaml_where = exec_line !!ocamlc ["-where"] in let ocaml_var name = SVar.umake ~guess: (guess_bins [ Filename.concat ocaml_dir (name ^ ".opt"); Filename.concat ocaml_dir name; name ^ ".opt"; name ]) ~check: (fun s -> let v = Str.last_word (exec_line s ["-version"]) in if name <> "ocamlbuild" || Version.ge ocaml_version "3.11" then if not (Version.eq ocaml_version v) then warning "Version of %s (%s) do not match \ compiler version (%s)" s v ocaml_version; true) (String.uppercase name) in if (try Sys.getenv "HAS_OCAMLOPT" with Not_found -> "no") = "yes" then ocaml_var "ocamlopt"; ocaml_var "ocamlbuild"; ocaml_var "ocaml"; ocaml_var "ocamllex"; ocaml_var "ocamlyacc"; ocaml_var "ocamldoc"; let cm_dir pkg cm = SVar.make ~guess: (fun s -> let l = [ Filename.concat ocaml_where pkg; ocaml_where; Filename.concat ocaml_dir pkg; ocaml_dir; ] in try exec_line "ocamlfind" ["query"; pkg; "2> /dev/null"] :: l with Exec_error _ -> l) ~check: (fun s -> Sys.file_exists (Filename.concat s cm)) in let mlpost_cm_dir = cm_dir "mlpost" "mlpost.cma" ~query: "Mlpost library directory" ~fail: (fun () -> warning "Mlpost not found"; "") "MLPOSTLIBDIR" in let check_mlpost_version () = try let v = exec_line (which "mlpost") ["-version"; "2> /dev/null"] in if Version.ge v "0.6" || v = "current" then begin echo "Mlpost version: %s" v; true end else begin echo "Mlpost version too old (%s)" v; false end with | Not_found -> warning "Mlpost tool not found."; false | Exec_error 2 -> warning "Mlpost version too old (<0.6)."; false in let mlpost = !!mlpost_cm_dir <> "" && check_mlpost_version () in BVar.usimple "MLPOST" mlpost; SVar.usimple "MLPOSTSPECIFIC" (if mlpost then "melt/mlpost_on.ml" else "melt/mlpost_off.ml"); let mlpost_with_cairo = mlpost && try ignore (exec_line "mlpost" ["-cairo"]); true with Exec_error _ -> false in BVar.usimple "MLPOSTCAIRO" mlpost_with_cairo; let cm_dir_if_mlpost_with_cairo pkg cm name var = if mlpost_with_cairo then cm_dir pkg cm ~query: (name^" library directory") ~fail: (fun () -> warning "%s not found" name; "") var else cm_dir pkg cm ~fail: (fun () -> "") var in let bitstring_cm_dir = cm_dir_if_mlpost_with_cairo "bitstring" "bitstring.cma" "Bitstring" "BITSTRINGLIBDIR" in let cairo_cm_dir = cm_dir_if_mlpost_with_cairo "cairo" "cairo.cma" "Cairo" "CAIROLIBDIR" in SVar.umake ~query: "Install directory (tool binaries)" ~guess: (fun () -> ["/usr/local/bin"]) "INSTALLBIN"; SVar.umake ~query: "Install directory (OCaml libraries)" ~guess: (fun () -> let l = [Filename.concat ocaml_where "melt"] in try let dir = exec_line "ocamlfind" ["printconf"; "destdir"; "2> /dev/null"] in (Filename.concat dir "melt"):: l with Exec_error _ -> l ) "INSTALLLIB"; SVar.umake ~query: "Install directory (man pages)" ~guess: (fun () -> ["/usr/local/share/man/man1"]) "INSTALLMAN"; let ocaml_includes l = let l = List.filter (fun s -> s <> "" && s <> ocaml_where) l in let l = List.map (sprintf "-I %s") l in String.concat " " l in let ocaml_includes = let includes = if mlpost then [ !!mlpost_cm_dir; !!bitstring_cm_dir; !!cairo_cm_dir ] else [] in SVar.simple "OCAMLINCLUDES" (ocaml_includes includes) in let ocamlbuild_flags l = let l = String.concat " " l in let l = Str.replace_char l ' ' ',' in if l <> "" then sprintf "-cflags %s -lflags %s" l l else "" in SVar.usimple "OCAMLBUILDFLAGS" (ocamlbuild_flags [!!ocaml_includes]); finish ()
null
https://raw.githubusercontent.com/ppedrot/ocaml-melt/0e58bb97e2afe2b7cadbaac906481f28cea1932e/configure.ml
ocaml
************************************************************************ 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 Melt 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 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, (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 ) 2009 , " AS IS " AND ANY EXPRESS OR , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR OWNER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT open Format #use "totoconf.ml" let () = init ~file: "Config" ~spec: [ force "OCAMLC" "<path> OCaml bytecode compiler"; force "MLPOST" "<path> Mlpost library directory"; force "INSTALLBIN" "<path> Install directory (tool binaries)"; force "INSTALLLIB" "<path> Install directory (OCaml libraries)"; force "INSTALLMAN" "<path> Install directory (man pages)"; ] (); let ocamlc = SVar.make ~query: "OCaml bytecode compiler" ~guess: (guess_bins ["ocamlc.opt"; "ocamlc"]) "OCAMLC" in let ocaml_dir = Filename.dirname !!ocamlc in let ocaml_version = exec_line !!ocamlc ["-version"] in echo "OCaml version: %s" ocaml_version; let ocaml_where = exec_line !!ocamlc ["-where"] in let ocaml_var name = SVar.umake ~guess: (guess_bins [ Filename.concat ocaml_dir (name ^ ".opt"); Filename.concat ocaml_dir name; name ^ ".opt"; name ]) ~check: (fun s -> let v = Str.last_word (exec_line s ["-version"]) in if name <> "ocamlbuild" || Version.ge ocaml_version "3.11" then if not (Version.eq ocaml_version v) then warning "Version of %s (%s) do not match \ compiler version (%s)" s v ocaml_version; true) (String.uppercase name) in if (try Sys.getenv "HAS_OCAMLOPT" with Not_found -> "no") = "yes" then ocaml_var "ocamlopt"; ocaml_var "ocamlbuild"; ocaml_var "ocaml"; ocaml_var "ocamllex"; ocaml_var "ocamlyacc"; ocaml_var "ocamldoc"; let cm_dir pkg cm = SVar.make ~guess: (fun s -> let l = [ Filename.concat ocaml_where pkg; ocaml_where; Filename.concat ocaml_dir pkg; ocaml_dir; ] in try exec_line "ocamlfind" ["query"; pkg; "2> /dev/null"] :: l with Exec_error _ -> l) ~check: (fun s -> Sys.file_exists (Filename.concat s cm)) in let mlpost_cm_dir = cm_dir "mlpost" "mlpost.cma" ~query: "Mlpost library directory" ~fail: (fun () -> warning "Mlpost not found"; "") "MLPOSTLIBDIR" in let check_mlpost_version () = try let v = exec_line (which "mlpost") ["-version"; "2> /dev/null"] in if Version.ge v "0.6" || v = "current" then begin echo "Mlpost version: %s" v; true end else begin echo "Mlpost version too old (%s)" v; false end with | Not_found -> warning "Mlpost tool not found."; false | Exec_error 2 -> warning "Mlpost version too old (<0.6)."; false in let mlpost = !!mlpost_cm_dir <> "" && check_mlpost_version () in BVar.usimple "MLPOST" mlpost; SVar.usimple "MLPOSTSPECIFIC" (if mlpost then "melt/mlpost_on.ml" else "melt/mlpost_off.ml"); let mlpost_with_cairo = mlpost && try ignore (exec_line "mlpost" ["-cairo"]); true with Exec_error _ -> false in BVar.usimple "MLPOSTCAIRO" mlpost_with_cairo; let cm_dir_if_mlpost_with_cairo pkg cm name var = if mlpost_with_cairo then cm_dir pkg cm ~query: (name^" library directory") ~fail: (fun () -> warning "%s not found" name; "") var else cm_dir pkg cm ~fail: (fun () -> "") var in let bitstring_cm_dir = cm_dir_if_mlpost_with_cairo "bitstring" "bitstring.cma" "Bitstring" "BITSTRINGLIBDIR" in let cairo_cm_dir = cm_dir_if_mlpost_with_cairo "cairo" "cairo.cma" "Cairo" "CAIROLIBDIR" in SVar.umake ~query: "Install directory (tool binaries)" ~guess: (fun () -> ["/usr/local/bin"]) "INSTALLBIN"; SVar.umake ~query: "Install directory (OCaml libraries)" ~guess: (fun () -> let l = [Filename.concat ocaml_where "melt"] in try let dir = exec_line "ocamlfind" ["printconf"; "destdir"; "2> /dev/null"] in (Filename.concat dir "melt"):: l with Exec_error _ -> l ) "INSTALLLIB"; SVar.umake ~query: "Install directory (man pages)" ~guess: (fun () -> ["/usr/local/share/man/man1"]) "INSTALLMAN"; let ocaml_includes l = let l = List.filter (fun s -> s <> "" && s <> ocaml_where) l in let l = List.map (sprintf "-I %s") l in String.concat " " l in let ocaml_includes = let includes = if mlpost then [ !!mlpost_cm_dir; !!bitstring_cm_dir; !!cairo_cm_dir ] else [] in SVar.simple "OCAMLINCLUDES" (ocaml_includes includes) in let ocamlbuild_flags l = let l = String.concat " " l in let l = Str.replace_char l ' ' ',' in if l <> "" then sprintf "-cflags %s -lflags %s" l l else "" in SVar.usimple "OCAMLBUILDFLAGS" (ocamlbuild_flags [!!ocaml_includes]); finish ()
c74392a1e0b6b3ce9196a2bd5257bb2f3cc835492342f4437c17a714a85f6e5b
psilord/option-9
increase-power.lisp
(in-package #:option-9) ;; TODO: increase-power needs keywords, or a &rest or something to provide ;; more context of the power increase. ;; By default, something cannot increase its own power. (defmethod increase-power (thing) nil) (defmethod increase-power ((mine-muzzle mine-muzzle)) (setf (mine-count mine-muzzle) 5)) ;; We don't waste an increase of power if possible. (defmethod increase-power ((tf tesla-field)) (if (zerop (random 2)) (if (power-density-maxp tf) (increase-range tf) (increase-density tf)) (if (power-range-maxp tf) (increase-density tf) (increase-range tf)))) ;; Recharge the shield back to full (meaning it hasn't absorbed any shots). ;; This is ok behavior for now, we'll see if I do something more complex later. (defmethod increase-power ((sh shield)) (setf (shots-absorbed sh) 0))
null
https://raw.githubusercontent.com/psilord/option-9/44d96cbc5543ee2acbdcf45d300207ef175462bc/increase-power.lisp
lisp
TODO: increase-power needs keywords, or a &rest or something to provide more context of the power increase. By default, something cannot increase its own power. We don't waste an increase of power if possible. Recharge the shield back to full (meaning it hasn't absorbed any shots). This is ok behavior for now, we'll see if I do something more complex later.
(in-package #:option-9) (defmethod increase-power (thing) nil) (defmethod increase-power ((mine-muzzle mine-muzzle)) (setf (mine-count mine-muzzle) 5)) (defmethod increase-power ((tf tesla-field)) (if (zerop (random 2)) (if (power-density-maxp tf) (increase-range tf) (increase-density tf)) (if (power-range-maxp tf) (increase-density tf) (increase-range tf)))) (defmethod increase-power ((sh shield)) (setf (shots-absorbed sh) 0))
00a48c9f02cb897045c01d7f99166239bd5f4809260b49c5e1184b3beffe71a5
RyanMcG/manners
bellman_test.clj
(ns manners.bellman-test (:require [manners.bellman :refer :all] [clojure.test :refer :all])) (def ^:private messages ["b" "c"]) (deftest test-prefix (is (= ((prefix "a ") messages) ["a b" "a c"])) (is (= ((prefix {}) messages) ["{}b" "{}c"]))) (deftest test-suffix (is (= ((suffix " a") messages) ["b a" "c a"])) (is (= ((suffix {}) messages) ["b{}" "c{}"]))) (deftest test-at (let [v {:a {:b {:c 4}}} three-coach (constantly ["must be 3"]) four-coach (constantly [])] (is (= ((at three-coach :a :b :c) v) ["a b c must be 3"])) (is (= ((at four-coach :a :b :c) v) [])))) (deftest test-specifiying (testing "a very simple specifying function" (let [derp (constantly "derp") a-coach (constantly ["yep" "anything, this will get overridden"]) derp-coach (specifiying derp a-coach)] (is (= (derp-coach 1) ["derp" "derp"])))) (testing "speciying function using message and value" (let [a-coach (constantly [10 3828]) spec-coach (specifiying / a-coach)] (is (= (spec-coach 10) [1 3828/10]))))) (deftest test-formatting (is (= ((formatting (constantly ["I got a %s"])) "thing") ["I got a thing"])) (is (= ((formatting (constantly ["I got a %8.2f"])) 1234.0) ["I got a 1234.00"]))) (deftest test-invoking (let [i-coach (invoking (constantly [identity inc]))] (is (= (i-coach 1) [1 2])) (is (= (i-coach 388) [388 389])))) #_(run-tests)
null
https://raw.githubusercontent.com/RyanMcG/manners/f7872c8c68a087c5e3e55062800c5ce9658d7c78/test/manners/bellman_test.clj
clojure
(ns manners.bellman-test (:require [manners.bellman :refer :all] [clojure.test :refer :all])) (def ^:private messages ["b" "c"]) (deftest test-prefix (is (= ((prefix "a ") messages) ["a b" "a c"])) (is (= ((prefix {}) messages) ["{}b" "{}c"]))) (deftest test-suffix (is (= ((suffix " a") messages) ["b a" "c a"])) (is (= ((suffix {}) messages) ["b{}" "c{}"]))) (deftest test-at (let [v {:a {:b {:c 4}}} three-coach (constantly ["must be 3"]) four-coach (constantly [])] (is (= ((at three-coach :a :b :c) v) ["a b c must be 3"])) (is (= ((at four-coach :a :b :c) v) [])))) (deftest test-specifiying (testing "a very simple specifying function" (let [derp (constantly "derp") a-coach (constantly ["yep" "anything, this will get overridden"]) derp-coach (specifiying derp a-coach)] (is (= (derp-coach 1) ["derp" "derp"])))) (testing "speciying function using message and value" (let [a-coach (constantly [10 3828]) spec-coach (specifiying / a-coach)] (is (= (spec-coach 10) [1 3828/10]))))) (deftest test-formatting (is (= ((formatting (constantly ["I got a %s"])) "thing") ["I got a thing"])) (is (= ((formatting (constantly ["I got a %8.2f"])) 1234.0) ["I got a 1234.00"]))) (deftest test-invoking (let [i-coach (invoking (constantly [identity inc]))] (is (= (i-coach 1) [1 2])) (is (= (i-coach 388) [388 389])))) #_(run-tests)
e133dbc99b8ff9327cd304cddbd13ed90ae2f48d7d0b484d322e697d8925bead
EasyCrypt/easycrypt
ecField.ml
(* -------------------------------------------------------------------- *) open EcRing open EcBigInt.Notations module BI = EcBigInt (* -------------------------------------------------------------------- *) type fexpr = | FEc of c | FEX of int | FEadd of fexpr * fexpr | FEsub of fexpr * fexpr | FEmul of fexpr * fexpr | FEopp of fexpr | FEinv of fexpr | FEdiv of fexpr * fexpr | FEpow of fexpr * BI.zint (* -------------------------------------------------------------------- *) type rsplit = pexpr * pexpr * pexpr let left ((t,_,_) : rsplit) : pexpr = t let right ((_,_,t) : rsplit) : pexpr = t let common ((_,t,_) : rsplit) : pexpr = t (* -------------------------------------------------------------------- *) let npepow x n = if BI.equal n BI.zero then PEc c1 else if BI.equal n BI.one then x else match x with | PEc c -> begin if ceq c c1 then PEc c1 else if ceq c c0 then PEc c0 else try PEc (BI.pow c (BI.to_int n)) with BI.Overflow -> PEpow (x, n) end | _ -> PEpow (x, n) (* -------------------------------------------------------------------- *) let rec npemul (x : pexpr) (y : pexpr) : pexpr = match x,y with | PEc c, PEc c' -> PEc (cmul c c') | PEc c, _ -> if ceq c c1 then y else if ceq c c0 then PEc c0 else PEmul (x,y) | _, PEc c -> if ceq c c1 then x else if ceq c c0 then PEc c0 else PEmul (x,y) | PEpow (e1,n1), PEpow (e2,n2) -> if BI.equal n1 n2 then npepow (npemul e1 e2) n1 else PEmul (x,y) | _,_ -> PEmul (x,y) (* -------------------------------------------------------------------- *) let rec isin (e1 : pexpr) (p1 : BI.zint) (e2 : pexpr) (p2 : BI.zint) = match e2 with | PEmul (e3, e4) -> begin match isin e1 p1 e3 p2 with | Some (p, e5) when BI.sign p = 0 -> Some (p, npemul e5 (npepow e4 p2)) | Some (p, e5) -> begin match isin e1 p e4 p2 with | Some (n, e6) -> Some (n, npemul e5 e6) | None -> Some (p, npemul e5 (npepow e4 p2)) end | None -> match isin e1 p1 e4 p2 with | Some (n,e5) -> Some (n,npemul (npepow e3 p2) e5) | None -> None end | PEpow (e3, p3) -> if BI.sign p3 = 0 then None else isin e1 p1 e3 (p3 *^ p2) | _ -> if pexpr_eq e1 e2 then match BI.compare p1 p2 with | c when c > 0 -> Some (p1-^p2, PEc c1) | c when c < 0 -> Some (BI.zero, npepow e2 (p2-^p1)) | _ -> Some (BI.zero, PEc c1) else None (* -------------------------------------------------------------------- *) let rec split_aux (e1 : pexpr) (p : BI.zint) (e2 : pexpr) : rsplit = match e1 with | PEmul (e3, e4) -> let r1 = split_aux e3 p e2 in let r2 = split_aux e4 p (right r1) in (npemul (left r1) (left r2), npemul (common r1) (common r2), right r2) | PEpow (e3, p3) -> if BI.sign p3 = 0 then (PEc c1, PEc c1, e2) else split_aux e3 (p3 *^ p) e2 | _ -> match isin e1 p e2 BI.one with | Some (q, e3) -> if BI.sign q = 0 then (PEc c1, npepow e1 p, e3) else (npepow e1 q, npepow e1 (p -^ q), e3) | None -> (npepow e1 p, PEc c1, e2) let split e1 e2 = split_aux e1 BI.one e2 (* -------------------------------------------------------------------- *) type linear = (pexpr * pexpr * (pexpr list)) let num (t,_,_) = t let denum (_,t,_) = t let condition (_,_,t) = t (* -------------------------------------------------------------------- *) let npeadd (e1 : pexpr) (e2 : pexpr) = match (e1, e2) with | (PEc c, PEc c') -> PEc (cadd c c') | (PEc c, _) -> if (ceq c c0) then e2 else PEadd (e1, e2) | (_, PEc c) -> if (ceq c c0) then e1 else PEadd (e1, e2) | _ -> PEadd (e1, e2) (* -------------------------------------------------------------------- *) let npesub e1 e2 = match (e1,e2) with | (PEc c, PEc c') -> PEc (csub c c') | (PEc c, _ ) -> if (ceq c c0) then PEopp e2 else PEsub (e1, e2) | ( _, PEc c) -> if (ceq c c0) then e1 else PEsub (e1, e2) | _ -> PEsub (e1, e2) (* -------------------------------------------------------------------- *) let npeopp e1 = match e1 with PEc c -> PEc (copp c) | _ -> PEopp e1 (* -------------------------------------------------------------------- *) let rec fnorm (e : fexpr) : linear = match e with | FEc c -> (PEc c, PEc c1, []) | FEX x -> (PEX x, PEc c1, []) | FEadd (e1, e2) -> let x = fnorm e1 in let y = fnorm e2 in let s = split (denum x) (denum y) in (npeadd (npemul (num x) (right s)) (npemul (num y) (left s)), npemul (left s) (npemul (right s) (common s)), condition x @ condition y) | FEsub (e1,e2) -> let x = fnorm e1 in let y = fnorm e2 in let s = split (denum x) (denum y) in (npesub (npemul (num x) (right s)) (npemul (num y) (left s)), npemul (left s) (npemul (right s) (common s)), condition x @ condition y) | FEmul (e1,e2) -> let x = fnorm e1 in let y = fnorm e2 in let s1 = split (num x) (denum y) in let s2 = split (num y) (denum x) in (npemul (left s1) (left s2), npemul (right s2) (right s1), condition x @ condition y) | FEopp e1 -> let x = fnorm e1 in (npeopp (num x), denum x, condition x) | FEinv e -> let x = fnorm e in (denum x, num x, (num x) :: (condition x)) | FEdiv (e1,e2) -> let x = fnorm e1 in let y = fnorm e2 in let s1 = split (num x) (num y) in let s2 = split (denum x) (denum y) in (npemul (left s1) (right s2), npemul (left s2) (right s1), (num y) :: ((condition x) @ (condition y))) | FEpow (e1,n) -> let x = fnorm e1 in (npepow (num x) n, npepow (denum x) n, condition x)
null
https://raw.githubusercontent.com/EasyCrypt/easycrypt/f87695472e70c313ef2966e20979b1afcc2e543e/src/ecField.ml
ocaml
-------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
open EcRing open EcBigInt.Notations module BI = EcBigInt type fexpr = | FEc of c | FEX of int | FEadd of fexpr * fexpr | FEsub of fexpr * fexpr | FEmul of fexpr * fexpr | FEopp of fexpr | FEinv of fexpr | FEdiv of fexpr * fexpr | FEpow of fexpr * BI.zint type rsplit = pexpr * pexpr * pexpr let left ((t,_,_) : rsplit) : pexpr = t let right ((_,_,t) : rsplit) : pexpr = t let common ((_,t,_) : rsplit) : pexpr = t let npepow x n = if BI.equal n BI.zero then PEc c1 else if BI.equal n BI.one then x else match x with | PEc c -> begin if ceq c c1 then PEc c1 else if ceq c c0 then PEc c0 else try PEc (BI.pow c (BI.to_int n)) with BI.Overflow -> PEpow (x, n) end | _ -> PEpow (x, n) let rec npemul (x : pexpr) (y : pexpr) : pexpr = match x,y with | PEc c, PEc c' -> PEc (cmul c c') | PEc c, _ -> if ceq c c1 then y else if ceq c c0 then PEc c0 else PEmul (x,y) | _, PEc c -> if ceq c c1 then x else if ceq c c0 then PEc c0 else PEmul (x,y) | PEpow (e1,n1), PEpow (e2,n2) -> if BI.equal n1 n2 then npepow (npemul e1 e2) n1 else PEmul (x,y) | _,_ -> PEmul (x,y) let rec isin (e1 : pexpr) (p1 : BI.zint) (e2 : pexpr) (p2 : BI.zint) = match e2 with | PEmul (e3, e4) -> begin match isin e1 p1 e3 p2 with | Some (p, e5) when BI.sign p = 0 -> Some (p, npemul e5 (npepow e4 p2)) | Some (p, e5) -> begin match isin e1 p e4 p2 with | Some (n, e6) -> Some (n, npemul e5 e6) | None -> Some (p, npemul e5 (npepow e4 p2)) end | None -> match isin e1 p1 e4 p2 with | Some (n,e5) -> Some (n,npemul (npepow e3 p2) e5) | None -> None end | PEpow (e3, p3) -> if BI.sign p3 = 0 then None else isin e1 p1 e3 (p3 *^ p2) | _ -> if pexpr_eq e1 e2 then match BI.compare p1 p2 with | c when c > 0 -> Some (p1-^p2, PEc c1) | c when c < 0 -> Some (BI.zero, npepow e2 (p2-^p1)) | _ -> Some (BI.zero, PEc c1) else None let rec split_aux (e1 : pexpr) (p : BI.zint) (e2 : pexpr) : rsplit = match e1 with | PEmul (e3, e4) -> let r1 = split_aux e3 p e2 in let r2 = split_aux e4 p (right r1) in (npemul (left r1) (left r2), npemul (common r1) (common r2), right r2) | PEpow (e3, p3) -> if BI.sign p3 = 0 then (PEc c1, PEc c1, e2) else split_aux e3 (p3 *^ p) e2 | _ -> match isin e1 p e2 BI.one with | Some (q, e3) -> if BI.sign q = 0 then (PEc c1, npepow e1 p, e3) else (npepow e1 q, npepow e1 (p -^ q), e3) | None -> (npepow e1 p, PEc c1, e2) let split e1 e2 = split_aux e1 BI.one e2 type linear = (pexpr * pexpr * (pexpr list)) let num (t,_,_) = t let denum (_,t,_) = t let condition (_,_,t) = t let npeadd (e1 : pexpr) (e2 : pexpr) = match (e1, e2) with | (PEc c, PEc c') -> PEc (cadd c c') | (PEc c, _) -> if (ceq c c0) then e2 else PEadd (e1, e2) | (_, PEc c) -> if (ceq c c0) then e1 else PEadd (e1, e2) | _ -> PEadd (e1, e2) let npesub e1 e2 = match (e1,e2) with | (PEc c, PEc c') -> PEc (csub c c') | (PEc c, _ ) -> if (ceq c c0) then PEopp e2 else PEsub (e1, e2) | ( _, PEc c) -> if (ceq c c0) then e1 else PEsub (e1, e2) | _ -> PEsub (e1, e2) let npeopp e1 = match e1 with PEc c -> PEc (copp c) | _ -> PEopp e1 let rec fnorm (e : fexpr) : linear = match e with | FEc c -> (PEc c, PEc c1, []) | FEX x -> (PEX x, PEc c1, []) | FEadd (e1, e2) -> let x = fnorm e1 in let y = fnorm e2 in let s = split (denum x) (denum y) in (npeadd (npemul (num x) (right s)) (npemul (num y) (left s)), npemul (left s) (npemul (right s) (common s)), condition x @ condition y) | FEsub (e1,e2) -> let x = fnorm e1 in let y = fnorm e2 in let s = split (denum x) (denum y) in (npesub (npemul (num x) (right s)) (npemul (num y) (left s)), npemul (left s) (npemul (right s) (common s)), condition x @ condition y) | FEmul (e1,e2) -> let x = fnorm e1 in let y = fnorm e2 in let s1 = split (num x) (denum y) in let s2 = split (num y) (denum x) in (npemul (left s1) (left s2), npemul (right s2) (right s1), condition x @ condition y) | FEopp e1 -> let x = fnorm e1 in (npeopp (num x), denum x, condition x) | FEinv e -> let x = fnorm e in (denum x, num x, (num x) :: (condition x)) | FEdiv (e1,e2) -> let x = fnorm e1 in let y = fnorm e2 in let s1 = split (num x) (num y) in let s2 = split (denum x) (denum y) in (npemul (left s1) (right s2), npemul (left s2) (right s1), (num y) :: ((condition x) @ (condition y))) | FEpow (e1,n) -> let x = fnorm e1 in (npepow (num x) n, npepow (denum x) n, condition x)
9e131157772d28b2ff551af3520a47043e895fd2d334ab7f0049fb7b1581216c
janestreet/ppx_css
make_css.mli
(* bin *)
null
https://raw.githubusercontent.com/janestreet/ppx_css/5848e1dc76b0ecf504e3b01d07d05741759cee72/inline_css/example/bin/make_css.mli
ocaml
bin
af9d51c4957b945456459452f7f46ef515c68235885ba74eb66fedd050bdd9b2
angavrilov/cl-linux-debug
ptrace-grovel.lisp
;;; -*- mode: Lisp; indent-tabs-mode: nil; -*- (in-package :cl-linux-debug) (include "signal.h") (include "unistd.h") (include "sys/ptrace.h") (include "sys/syscall.h") (include "sys/types.h") (include "sys/user.h") (include "sys/mman.h") (include "sys/wait.h") ;; Signals (cstruct siginfo_t "siginfo_t" (si_pid "si_pid" :type :int) (si_status "si_status" :type :int) (si_code "si_code" :type :int)) (constant (CLD_EXITED "CLD_EXITED")) (constant (CLD_KILLED "CLD_KILLED")) (constant (CLD_DUMPED "CLD_DUMPED")) (constant (CLD_TRAPPED "CLD_TRAPPED")) (constant (CLD_STOPPED "CLD_STOPPED")) (constant (CLD_CONTINUED "CLD_CONTINUED")) (constant (WNOHANG "WNOHANG")) (constant (WEXITED "WEXITED")) (constant (WSTOPPED "WSTOPPED")) (constant (__WALL "__WALL")) (constant (SIGTRAP "SIGTRAP")) (constant (SIGSTOP "SIGSTOP")) (constant (SIGCONT "SIGCONT")) (constant (SYS_tgkill "SYS_tgkill")) (constant (PROT_READ "PROT_READ")) (constant (PROT_WRITE "PROT_WRITE")) (constant (PROT_EXEC "PROT_EXEC")) (constant (MAP_PRIVATE "MAP_PRIVATE")) (constant (MAP_ANONYMOUS "MAP_ANONYMOUS")) (ctype pid_t "pid_t") (cenum ptrace-request ((:PTRACE_TRACEME "PTRACE_TRACEME")) ((:PTRACE_ATTACH "PTRACE_ATTACH")) ((:PTRACE_DETACH "PTRACE_DETACH")) ((:PTRACE_CONT "PTRACE_CONT")) ((:PTRACE_KILL "PTRACE_KILL")) ((:PTRACE_GETREGS "PTRACE_GETREGS")) ((:PTRACE_SETREGS "PTRACE_SETREGS")) ((:PTRACE_GETSIGINFO "PTRACE_GETSIGINFO")) ((:PTRACE_PEEKTEXT "PTRACE_PEEKTEXT")) ((:PTRACE_PEEKDATA "PTRACE_PEEKDATA")) ((:PTRACE_POKETEXT "PTRACE_POKETEXT")) ((:PTRACE_POKEDATA "PTRACE_POKEDATA")) ((:PTRACE_SETOPTIONS "PTRACE_SETOPTIONS")) ((:PTRACE_GETEVENTMSG "PTRACE_GETEVENTMSG"))) (cenum ptrace-options ((:PTRACE_O_TRACEFORK "PTRACE_O_TRACEFORK")) ((:PTRACE_O_TRACEVFORK "PTRACE_O_TRACEVFORK")) ((:PTRACE_O_TRACECLONE "PTRACE_O_TRACECLONE")) ((:PTRACE_O_TRACEEXEC "PTRACE_O_TRACEEXEC"))) (cenum ptrace-event ((:PTRACE_EVENT_FORK "PTRACE_EVENT_FORK")) ((:PTRACE_EVENT_VFORK "PTRACE_EVENT_VFORK")) ((:PTRACE_EVENT_CLONE "PTRACE_EVENT_CLONE")) ((:PTRACE_EVENT_EXEC "PTRACE_EVENT_EXEC"))) (constantenum errno-vals ((:EBUSY "EBUSY")) ((:EFAULT "EFAULT")) ((:EINVAL "EINVAL")) ((:EIO "EIO")) ((:EPERM "EPERM")) ((:ESRCH "ESRCH"))) #-x86-64 (cstruct user_regs_struct "struct user_regs_struct" (eax "eax" :type :long) (ebx "ebx" :type :long) (ecx "ecx" :type :long) (edx "edx" :type :long) (esi "esi" :type :long) (edi "edi" :type :long) (esp "esp" :type :long) (ebp "ebp" :type :long) (eip "eip" :type :long) (orig-eax "orig_eax" :type :long) (eflags "eflags" :type :long) (cs "xcs" :type :long) (ds "xds" :type :long) (ss "xss" :type :long) (es "xes" :type :long) (fs "xfs" :type :long) (gs "xgs" :type :long)) #+x86-64 (cstruct user_regs_struct "struct user_regs_struct" (r15 "r15" :type :long) (r14 "r14" :type :long) (r13 "r13" :type :long) (r12 "r12" :type :long) (rbp "rbp" :type :long) (rbx "rbx" :type :long) (r11 "r11" :type :long) (r10 "r10" :type :long) (r9 "r9" :type :long) (r8 "r8" :type :long) (rax "rax" :type :long) (rcx "rcx" :type :long) (rdx "rdx" :type :long) (rsi "rsi" :type :long) (rdi "rdi" :type :long) (orig-rax "orig_rax" :type :long) (rip "rip" :type :long) (cs "cs" :type :long) (eflags "eflags" :type :long) (rsp "rsp" :type :long) (ss "ss" :type :long) (fs_base "fs_base" :type :long) (gs_base "gs_base" :type :long) (ds "ds" :type :long) (es "es" :type :long) (fs "fs" :type :long) (gs "gs" :type :long))
null
https://raw.githubusercontent.com/angavrilov/cl-linux-debug/879da2dcd14918bb8ffab003e934f4b01fba12ff/debugger/ptrace-grovel.lisp
lisp
-*- mode: Lisp; indent-tabs-mode: nil; -*- Signals
(in-package :cl-linux-debug) (include "signal.h") (include "unistd.h") (include "sys/ptrace.h") (include "sys/syscall.h") (include "sys/types.h") (include "sys/user.h") (include "sys/mman.h") (include "sys/wait.h") (cstruct siginfo_t "siginfo_t" (si_pid "si_pid" :type :int) (si_status "si_status" :type :int) (si_code "si_code" :type :int)) (constant (CLD_EXITED "CLD_EXITED")) (constant (CLD_KILLED "CLD_KILLED")) (constant (CLD_DUMPED "CLD_DUMPED")) (constant (CLD_TRAPPED "CLD_TRAPPED")) (constant (CLD_STOPPED "CLD_STOPPED")) (constant (CLD_CONTINUED "CLD_CONTINUED")) (constant (WNOHANG "WNOHANG")) (constant (WEXITED "WEXITED")) (constant (WSTOPPED "WSTOPPED")) (constant (__WALL "__WALL")) (constant (SIGTRAP "SIGTRAP")) (constant (SIGSTOP "SIGSTOP")) (constant (SIGCONT "SIGCONT")) (constant (SYS_tgkill "SYS_tgkill")) (constant (PROT_READ "PROT_READ")) (constant (PROT_WRITE "PROT_WRITE")) (constant (PROT_EXEC "PROT_EXEC")) (constant (MAP_PRIVATE "MAP_PRIVATE")) (constant (MAP_ANONYMOUS "MAP_ANONYMOUS")) (ctype pid_t "pid_t") (cenum ptrace-request ((:PTRACE_TRACEME "PTRACE_TRACEME")) ((:PTRACE_ATTACH "PTRACE_ATTACH")) ((:PTRACE_DETACH "PTRACE_DETACH")) ((:PTRACE_CONT "PTRACE_CONT")) ((:PTRACE_KILL "PTRACE_KILL")) ((:PTRACE_GETREGS "PTRACE_GETREGS")) ((:PTRACE_SETREGS "PTRACE_SETREGS")) ((:PTRACE_GETSIGINFO "PTRACE_GETSIGINFO")) ((:PTRACE_PEEKTEXT "PTRACE_PEEKTEXT")) ((:PTRACE_PEEKDATA "PTRACE_PEEKDATA")) ((:PTRACE_POKETEXT "PTRACE_POKETEXT")) ((:PTRACE_POKEDATA "PTRACE_POKEDATA")) ((:PTRACE_SETOPTIONS "PTRACE_SETOPTIONS")) ((:PTRACE_GETEVENTMSG "PTRACE_GETEVENTMSG"))) (cenum ptrace-options ((:PTRACE_O_TRACEFORK "PTRACE_O_TRACEFORK")) ((:PTRACE_O_TRACEVFORK "PTRACE_O_TRACEVFORK")) ((:PTRACE_O_TRACECLONE "PTRACE_O_TRACECLONE")) ((:PTRACE_O_TRACEEXEC "PTRACE_O_TRACEEXEC"))) (cenum ptrace-event ((:PTRACE_EVENT_FORK "PTRACE_EVENT_FORK")) ((:PTRACE_EVENT_VFORK "PTRACE_EVENT_VFORK")) ((:PTRACE_EVENT_CLONE "PTRACE_EVENT_CLONE")) ((:PTRACE_EVENT_EXEC "PTRACE_EVENT_EXEC"))) (constantenum errno-vals ((:EBUSY "EBUSY")) ((:EFAULT "EFAULT")) ((:EINVAL "EINVAL")) ((:EIO "EIO")) ((:EPERM "EPERM")) ((:ESRCH "ESRCH"))) #-x86-64 (cstruct user_regs_struct "struct user_regs_struct" (eax "eax" :type :long) (ebx "ebx" :type :long) (ecx "ecx" :type :long) (edx "edx" :type :long) (esi "esi" :type :long) (edi "edi" :type :long) (esp "esp" :type :long) (ebp "ebp" :type :long) (eip "eip" :type :long) (orig-eax "orig_eax" :type :long) (eflags "eflags" :type :long) (cs "xcs" :type :long) (ds "xds" :type :long) (ss "xss" :type :long) (es "xes" :type :long) (fs "xfs" :type :long) (gs "xgs" :type :long)) #+x86-64 (cstruct user_regs_struct "struct user_regs_struct" (r15 "r15" :type :long) (r14 "r14" :type :long) (r13 "r13" :type :long) (r12 "r12" :type :long) (rbp "rbp" :type :long) (rbx "rbx" :type :long) (r11 "r11" :type :long) (r10 "r10" :type :long) (r9 "r9" :type :long) (r8 "r8" :type :long) (rax "rax" :type :long) (rcx "rcx" :type :long) (rdx "rdx" :type :long) (rsi "rsi" :type :long) (rdi "rdi" :type :long) (orig-rax "orig_rax" :type :long) (rip "rip" :type :long) (cs "cs" :type :long) (eflags "eflags" :type :long) (rsp "rsp" :type :long) (ss "ss" :type :long) (fs_base "fs_base" :type :long) (gs_base "gs_base" :type :long) (ds "ds" :type :long) (es "es" :type :long) (fs "fs" :type :long) (gs "gs" :type :long))
0724f15fbe441bf4d9703cbe8534a727fb388abdb6f540c5caa7c9dbdd56b4c1
discus-lang/ddc
CreateMainHS.hs
module DDC.War.Create.CreateMainHS (create) where import DDC.War.Create.Way import DDC.War.Driver import System.FilePath import DDC.War.Job () import Data.Set (Set) import qualified DDC.War.Job.CompileHS as CompileHS import qualified DDC.War.Job.RunExe as RunExe -- | Compile and run Main.hs files. When we run the exectuable , pass it out build dir as the first argument . create :: Way -> Set FilePath -> FilePath -> Maybe Chain create way _allFiles filePath | takeFileName filePath == "Main.hs" = let sourceDir = takeDirectory filePath buildDir = sourceDir </> "war-" ++ wayName way testName = filePath mainBin = buildDir </> "Main.bin" mainCompStdout = buildDir </> "Main.compile.stdout" mainCompStderr = buildDir </> "Main.compile.stderr" mainRunStdout = buildDir </> "Main.run.stdout" mainRunStderr = buildDir </> "Main.run.stderr" compile = jobOfSpec (JobId testName (wayName way)) $ CompileHS.Spec filePath [] buildDir mainCompStdout mainCompStderr mainBin run = jobOfSpec (JobId testName (wayName way)) $ RunExe.Spec filePath mainBin [buildDir] mainRunStdout mainRunStderr True in Just $ Chain [compile, run] | otherwise = Nothing
null
https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-tools/src/ddc-war/DDC/War/Create/CreateMainHS.hs
haskell
| Compile and run Main.hs files.
module DDC.War.Create.CreateMainHS (create) where import DDC.War.Create.Way import DDC.War.Driver import System.FilePath import DDC.War.Job () import Data.Set (Set) import qualified DDC.War.Job.CompileHS as CompileHS import qualified DDC.War.Job.RunExe as RunExe When we run the exectuable , pass it out build dir as the first argument . create :: Way -> Set FilePath -> FilePath -> Maybe Chain create way _allFiles filePath | takeFileName filePath == "Main.hs" = let sourceDir = takeDirectory filePath buildDir = sourceDir </> "war-" ++ wayName way testName = filePath mainBin = buildDir </> "Main.bin" mainCompStdout = buildDir </> "Main.compile.stdout" mainCompStderr = buildDir </> "Main.compile.stderr" mainRunStdout = buildDir </> "Main.run.stdout" mainRunStderr = buildDir </> "Main.run.stderr" compile = jobOfSpec (JobId testName (wayName way)) $ CompileHS.Spec filePath [] buildDir mainCompStdout mainCompStderr mainBin run = jobOfSpec (JobId testName (wayName way)) $ RunExe.Spec filePath mainBin [buildDir] mainRunStdout mainRunStderr True in Just $ Chain [compile, run] | otherwise = Nothing
12ae3e86822e47b085bb0e8f29bbda8011e8a8352b47981f6f7eef0f7b72cdac
coccinelle/coccinelle
ephemeron.mli
module type S = sig type key type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module type SeededS = sig type key type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module K1 : sig type ('k, 'd) t val create : unit -> ('k, 'd) t val get_key : ('k, 'd) t -> 'k option val get_key_copy : ('k, 'd) t -> 'k option val set_key : ('k, 'd) t -> 'k -> unit val unset_key : ('k, 'd) t -> unit val check_key : ('k, 'd) t -> bool val blit_key : ('k, 'a) t -> ('k, 'b) t -> unit val get_data : ('k, 'd) t -> 'd option val get_data_copy : ('k, 'd) t -> 'd option val set_data : ('k, 'd) t -> 'd -> unit val unset_data : ('k, 'd) t -> unit val check_data : ('k, 'd) t -> bool val blit_data : ('a, 'd) t -> ('b, 'd) t -> unit val make : 'k -> 'd -> ('k, 'd) t val query : ('k, 'd) t -> 'k -> 'd option module Make : functor (H : Hashtbl.HashedType) -> sig type key = H.t type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module MakeSeeded : functor (H : Hashtbl.SeededHashedType) -> sig type key = H.t type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module Bucket : sig type ('k, 'd) t val make : unit -> ('k, 'd) t val add : ('k, 'd) t -> 'k -> 'd -> unit val remove : ('k, 'd) t -> 'k -> unit val find : ('k, 'd) t -> 'k -> 'd option val length : ('k, 'd) t -> int val clear : ('k, 'd) t -> unit end end module K2 : sig type ('k1, 'k2, 'd) t val create : unit -> ('k1, 'k2, 'd) t val get_key1 : ('k1, 'k2, 'd) t -> 'k1 option val get_key1_copy : ('k1, 'k2, 'd) t -> 'k1 option val set_key1 : ('k1, 'k2, 'd) t -> 'k1 -> unit val unset_key1 : ('k1, 'k2, 'd) t -> unit val check_key1 : ('k1, 'k2, 'd) t -> bool val get_key2 : ('k1, 'k2, 'd) t -> 'k2 option val get_key2_copy : ('k1, 'k2, 'd) t -> 'k2 option val set_key2 : ('k1, 'k2, 'd) t -> 'k2 -> unit val unset_key2 : ('k1, 'k2, 'd) t -> unit val check_key2 : ('k1, 'k2, 'd) t -> bool val blit_key1 : ('k1, 'a, 'b) t -> ('k1, 'c, 'd) t -> unit val blit_key2 : ('a, 'k2, 'b) t -> ('c, 'k2, 'd) t -> unit val blit_key12 : ('k1, 'k2, 'a) t -> ('k1, 'k2, 'b) t -> unit val get_data : ('k1, 'k2, 'd) t -> 'd option val get_data_copy : ('k1, 'k2, 'd) t -> 'd option val set_data : ('k1, 'k2, 'd) t -> 'd -> unit val unset_data : ('k1, 'k2, 'd) t -> unit val check_data : ('k1, 'k2, 'd) t -> bool val blit_data : ('k1, 'k2, 'd) t -> ('k1, 'k2, 'd) t -> unit val make : 'k1 -> 'k2 -> 'd -> ('k1, 'k2, 'd) t val query : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd option module Make : functor (H1 : Hashtbl.HashedType) -> functor (H2 : Hashtbl.HashedType) -> sig type key = (H1.t * H2.t) type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module MakeSeeded : functor (H1 : Hashtbl.SeededHashedType) -> functor (H2 : Hashtbl.SeededHashedType) -> sig type key = (H1.t * H2.t) type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module Bucket : sig type ('k1, 'k2, 'd) t val make : unit -> ('k1, 'k2, 'd) t val add : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd -> unit val remove : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> unit val find : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd option val length : ('k1, 'k2, 'd) t -> int val clear : ('k1, 'k2, 'd) t -> unit end end module Kn : sig type ('k, 'd) t val create : int -> ('k, 'd) t val get_key : ('k, 'd) t -> int -> 'k option val get_key_copy : ('k, 'd) t -> int -> 'k option val set_key : ('k, 'd) t -> int -> 'k -> unit val unset_key : ('k, 'd) t -> int -> unit val check_key : ('k, 'd) t -> int -> bool val blit_key : ('k, 'a) t -> int -> ('k, 'b) t -> int -> int -> unit val get_data : ('k, 'd) t -> 'd option val get_data_copy : ('k, 'd) t -> 'd option val set_data : ('k, 'd) t -> 'd -> unit val unset_data : ('k, 'd) t -> unit val check_data : ('k, 'd) t -> bool val blit_data : ('k, 'd) t -> ('k, 'd) t -> unit val make : 'k array -> 'd -> ('k, 'd) t val query : ('k, 'd) t -> 'k array -> 'd option module Make : functor (H : Hashtbl.HashedType) -> sig type key = H.t array type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module MakeSeeded : functor (H : Hashtbl.SeededHashedType) -> sig type key = H.t array type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module Bucket : sig type ('k, 'd) t val make : unit -> ('k, 'd) t val add : ('k, 'd) t -> 'k array -> 'd -> unit val remove : ('k, 'd) t -> 'k array -> unit val find : ('k, 'd) t -> 'k array -> 'd option val length : ('k, 'd) t -> int val clear : ('k, 'd) t -> unit end end module GenHashTable : sig type equal = | ETrue | EFalse | EDead module MakeSeeded : functor (H : sig type t type 'a container val hash : int -> t -> int val equal : 'a container -> t -> equal val create : t -> 'a -> 'a container val get_key : 'a container -> t option val get_data : 'a container -> 'a option val set_key_data : 'a container -> t -> 'a -> unit val check_key : 'a container -> bool end) -> sig type key = H.t type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end end
null
https://raw.githubusercontent.com/coccinelle/coccinelle/5448bb2bd03491ffec356bf7bd6ddcdbf4d36bc9/bundles/stdcompat/stdcompat-current/interfaces/4.14/ephemeron.mli
ocaml
module type S = sig type key type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module type SeededS = sig type key type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module K1 : sig type ('k, 'd) t val create : unit -> ('k, 'd) t val get_key : ('k, 'd) t -> 'k option val get_key_copy : ('k, 'd) t -> 'k option val set_key : ('k, 'd) t -> 'k -> unit val unset_key : ('k, 'd) t -> unit val check_key : ('k, 'd) t -> bool val blit_key : ('k, 'a) t -> ('k, 'b) t -> unit val get_data : ('k, 'd) t -> 'd option val get_data_copy : ('k, 'd) t -> 'd option val set_data : ('k, 'd) t -> 'd -> unit val unset_data : ('k, 'd) t -> unit val check_data : ('k, 'd) t -> bool val blit_data : ('a, 'd) t -> ('b, 'd) t -> unit val make : 'k -> 'd -> ('k, 'd) t val query : ('k, 'd) t -> 'k -> 'd option module Make : functor (H : Hashtbl.HashedType) -> sig type key = H.t type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module MakeSeeded : functor (H : Hashtbl.SeededHashedType) -> sig type key = H.t type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module Bucket : sig type ('k, 'd) t val make : unit -> ('k, 'd) t val add : ('k, 'd) t -> 'k -> 'd -> unit val remove : ('k, 'd) t -> 'k -> unit val find : ('k, 'd) t -> 'k -> 'd option val length : ('k, 'd) t -> int val clear : ('k, 'd) t -> unit end end module K2 : sig type ('k1, 'k2, 'd) t val create : unit -> ('k1, 'k2, 'd) t val get_key1 : ('k1, 'k2, 'd) t -> 'k1 option val get_key1_copy : ('k1, 'k2, 'd) t -> 'k1 option val set_key1 : ('k1, 'k2, 'd) t -> 'k1 -> unit val unset_key1 : ('k1, 'k2, 'd) t -> unit val check_key1 : ('k1, 'k2, 'd) t -> bool val get_key2 : ('k1, 'k2, 'd) t -> 'k2 option val get_key2_copy : ('k1, 'k2, 'd) t -> 'k2 option val set_key2 : ('k1, 'k2, 'd) t -> 'k2 -> unit val unset_key2 : ('k1, 'k2, 'd) t -> unit val check_key2 : ('k1, 'k2, 'd) t -> bool val blit_key1 : ('k1, 'a, 'b) t -> ('k1, 'c, 'd) t -> unit val blit_key2 : ('a, 'k2, 'b) t -> ('c, 'k2, 'd) t -> unit val blit_key12 : ('k1, 'k2, 'a) t -> ('k1, 'k2, 'b) t -> unit val get_data : ('k1, 'k2, 'd) t -> 'd option val get_data_copy : ('k1, 'k2, 'd) t -> 'd option val set_data : ('k1, 'k2, 'd) t -> 'd -> unit val unset_data : ('k1, 'k2, 'd) t -> unit val check_data : ('k1, 'k2, 'd) t -> bool val blit_data : ('k1, 'k2, 'd) t -> ('k1, 'k2, 'd) t -> unit val make : 'k1 -> 'k2 -> 'd -> ('k1, 'k2, 'd) t val query : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd option module Make : functor (H1 : Hashtbl.HashedType) -> functor (H2 : Hashtbl.HashedType) -> sig type key = (H1.t * H2.t) type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module MakeSeeded : functor (H1 : Hashtbl.SeededHashedType) -> functor (H2 : Hashtbl.SeededHashedType) -> sig type key = (H1.t * H2.t) type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module Bucket : sig type ('k1, 'k2, 'd) t val make : unit -> ('k1, 'k2, 'd) t val add : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd -> unit val remove : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> unit val find : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd option val length : ('k1, 'k2, 'd) t -> int val clear : ('k1, 'k2, 'd) t -> unit end end module Kn : sig type ('k, 'd) t val create : int -> ('k, 'd) t val get_key : ('k, 'd) t -> int -> 'k option val get_key_copy : ('k, 'd) t -> int -> 'k option val set_key : ('k, 'd) t -> int -> 'k -> unit val unset_key : ('k, 'd) t -> int -> unit val check_key : ('k, 'd) t -> int -> bool val blit_key : ('k, 'a) t -> int -> ('k, 'b) t -> int -> int -> unit val get_data : ('k, 'd) t -> 'd option val get_data_copy : ('k, 'd) t -> 'd option val set_data : ('k, 'd) t -> 'd -> unit val unset_data : ('k, 'd) t -> unit val check_data : ('k, 'd) t -> bool val blit_data : ('k, 'd) t -> ('k, 'd) t -> unit val make : 'k array -> 'd -> ('k, 'd) t val query : ('k, 'd) t -> 'k array -> 'd option module Make : functor (H : Hashtbl.HashedType) -> sig type key = H.t array type !'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module MakeSeeded : functor (H : Hashtbl.SeededHashedType) -> sig type key = H.t array type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end module Bucket : sig type ('k, 'd) t val make : unit -> ('k, 'd) t val add : ('k, 'd) t -> 'k array -> 'd -> unit val remove : ('k, 'd) t -> 'k array -> unit val find : ('k, 'd) t -> 'k array -> 'd option val length : ('k, 'd) t -> int val clear : ('k, 'd) t -> unit end end module GenHashTable : sig type equal = | ETrue | EFalse | EDead module MakeSeeded : functor (H : sig type t type 'a container val hash : int -> t -> int val equal : 'a container -> t -> equal val create : t -> 'a -> 'a container val get_key : 'a container -> t option val get_data : 'a container -> 'a option val set_key_data : 'a container -> t -> 'a -> unit val check_key : 'a container -> bool end) -> sig type key = H.t type !'a t val create : ?random:bool -> int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit val stats_alive : 'a t -> Hashtbl.statistics end end
38c8962027c5ff8feec35ec253aef2a1268c7f64bd517f3ff7b7883358d7ac8b
Javran/advent-of-code
Day21.hs
module Javran.AdventOfCode.Y2019.Day21 ( ) where TODO : below are some initial ideas without further looking into detail . Notice that the machine can only have a very limited space of state : we have 6 registers , all of which are booleans , 2 ^ 6 = 64 states . So I suspect this is sort of like day 15 ( in which we detect details about a 2d map ) but here we are detecting a truth table instead . One limitation is that we have at most 15 instructions to use , so probably some optimization needed to encode this truth table . This might be of interest ( putting the link here just so that I do n't forget what it 's called again ): Update : forget about map , it does not scale to variables > = 6 . However we have some constraints that might be interesting : Notice that while the truth table of AND and OR depends on the values of both of the input registers , NOT completely ignores what value is in Y , meaning it could destroy information so if we want to get some negated read from a register , NOT must be the first instruction to read from it . In addition , although this is not explicitly specified that * when * does register J and T reset to false , but I suspect it means every turn , meaning we ca n't take advange of " hidden states " - say we have two different situations where all read - only registers are the same but T is different - this assumption actually limits the solution space quite a lot . TODO: below are some initial ideas without further looking into detail. Notice that the machine can only have a very limited space of state: we have 6 registers, all of which are booleans, meanihg 2^6 = 64 states. So I suspect this is sort of like day 15 (in which we detect details about a 2d map) but here we are detecting a truth table instead. One limitation is that we have at most 15 instructions to use, so probably some optimization needed to encode this truth table. This might be of interest (putting the link here just so that I don't forget what it's called again): Update: forget about Karnaugh map, it does not scale to variables >= 6. However we have some constraints that might be interesting: Notice that while the truth table of AND and OR depends on the values of both of the input registers, NOT completely ignores what value is in Y, meaning it could destroy information so if we want to get some negated read from a register, NOT must be the first instruction to read from it. In addition, although this is not explicitly specified that *when* does register J and T reset to false, but I suspect it means every turn, meaning we can't take advange of "hidden states" - say we have two different situations where all read-only registers are the same but T is different - this assumption actually limits the solution space quite a lot. -} import Control.Monad import Data.Char import Javran.AdventOfCode.Prelude import Javran.AdventOfCode.Y2019.IntCode data Day21 deriving (Generic) TODO : I do n't have a good idea of how to solve this in a general way for now , but I think the best we can do is to have some tools to help the process of getting one solution and gradually automate what we can . TODO: I don't have a good idea of how to solve this in a general way for now, but I think the best we can do is to have some tools to help the process of getting one solution and gradually automate what we can. -} if we do nothing , we fall at this scenario : > # # # # # @ # # # # # # # # # # # So we issue ` NOT A J ` , which should allow us to jump here : > @ > # # # # > ABCD Next failure : > # # # # # .. # @ # # # # # # # # Meaning we should not jump here : > @ > # .. # . > ABCD or , recognizing jumping a bit earlier will allow us to landing on a safe block , we should jump here : > @ > # # .. # > ABCD So ` OR D J ` , but we now have two branches . making room by using T : - NOT A J - OR D T - OR T J Next failure : > # # # # # .. # @ # # # # # # # # We jumped too eagerly here : > @ > # # # # # > ABCD Probably putting in a condition that C should be missing : - NOT A J - NOT C T - AND D T - OR T J notice how NOT must be the first one of each " AND - section " if we do nothing, we fall at this scenario: > #####@########### So we issue `NOT A J`, which should allow us to jump here: > @ > # ### > ABCD Next failure: > #####..#@######## Meaning we should not jump here: > @ > #..#. > ABCD or, recognizing jumping a bit earlier will allow us to landing on a safe block, we should jump here: > @ > ##..# > ABCD So `OR D J`, but we now have two branches. making room by using T: - NOT A J - OR D T - OR T J Next failure: > #####..#@######## We jumped too eagerly here: > @ > ##### > ABCD Probably putting in a condition that C should be missing: - NOT A J - NOT C T - AND D T - OR T J notice how NOT must be the first one of each "AND-section" -} p1Input :: [String] p1Input = [ "NOT A J" , "NOT C T" , "AND D T" , "OR T J" , "WALK" ] Starting from scratch , but ` NOT A J ` looks good to keep . Failure : > # # # # # .. # @ # # # # # # # # let 's make it jump when D is present > @ > # # .. # . # # # # > ABCDEFGHI - NOT A J - OR D T - OR T J ... I get the feeling that this is exactly p1 , let 's just use the stuff there ... also let 's change notation . say in p1 we have : > ! A + ! C*D should not jump : > @ .............. > # # # . # . # .. # # # # # # > ABCDEFGHI > ! A + ! should not jump : > @ ............ > # . # # . # . # # # # # # > ABCDEFGHI > @ > # # . # # . # . # # > ABCDEFGHI > ! A + ! C*D*H + ! B*F should not jump : > @ ......... > # # ... # # # # # > ABCDEFGHI > ! A + ! C*D*H + ! B*D*F should jump : > @ ............ > # . # # ... # # . # # # > ABCDEFGHI > @ ... ? ... ? > # # . # # ... # # . # # # > ABCDEFGHI > ! A + ! C*D*H + ! B*D*F + ! B*D*H Starting from scratch, but `NOT A J` looks good to keep. Failure: > #####..#@######## let's make it jump when D is present > @ > ##..#.#### > ABCDEFGHI - NOT A J - OR D T - OR T J ... I get the feeling that this is exactly p1, let's just use the stuff there... also let's change notation. say in p1 we have: > !A + !C*D should not jump: > @.............. > ###.#.#..###### > ABCDEFGHI > !A + !C*D*H should not jump: > @............ > #.##.#.###### > ABCDEFGHI > @ > ##.##.#.## > ABCDEFGHI > !A + !C*D*H + !B*F should not jump: > @......... > ##...##### > ABCDEFGHI > !A + !C*D*H + !B*D*F should jump: > @............ > #.##...##.### > ABCDEFGHI > @...?...? > ##.##...##.### > ABCDEFGHI > !A + !C*D*H + !B*D*F + !B*D*H -} p2Input :: [String] p2Input = [ "NOT A J" , "NOT C T" , "AND D T" , "AND H T" , "OR T J" , "NOT B T" , "AND D T" , "AND F T" , "OR T J" , "NOT B T" , "AND D T" , "AND H T" , "OR T J" , "RUN" ] TODO : find something not that manual ... TODO: find something not that manual... -} instance Solution Day21 where solutionRun _ SolutionContext {getInputS, answerShow} = do code <- parseCodeOrDie <$> getInputS let runPart1 = True runPart2 = True when runPart1 do (_, out) <- runProgram code (fmap ord $ unlines p1Input) let isSolved = last out > 0x7f if isSolved then answerShow (last out) else putStrLn (fmap chr out) when runPart2 do (_, out) <- runProgram code (fmap ord $ unlines p2Input) let isSolved = last out > 0x7f if isSolved then answerShow (last out) else putStrLn (fmap chr out)
null
https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/Y2019/Day21.hs
haskell
module Javran.AdventOfCode.Y2019.Day21 ( ) where TODO : below are some initial ideas without further looking into detail . Notice that the machine can only have a very limited space of state : we have 6 registers , all of which are booleans , 2 ^ 6 = 64 states . So I suspect this is sort of like day 15 ( in which we detect details about a 2d map ) but here we are detecting a truth table instead . One limitation is that we have at most 15 instructions to use , so probably some optimization needed to encode this truth table . This might be of interest ( putting the link here just so that I do n't forget what it 's called again ): Update : forget about map , it does not scale to variables > = 6 . However we have some constraints that might be interesting : Notice that while the truth table of AND and OR depends on the values of both of the input registers , NOT completely ignores what value is in Y , meaning it could destroy information so if we want to get some negated read from a register , NOT must be the first instruction to read from it . In addition , although this is not explicitly specified that * when * does register J and T reset to false , but I suspect it means every turn , meaning we ca n't take advange of " hidden states " - say we have two different situations where all read - only registers are the same but T is different - this assumption actually limits the solution space quite a lot . TODO: below are some initial ideas without further looking into detail. Notice that the machine can only have a very limited space of state: we have 6 registers, all of which are booleans, meanihg 2^6 = 64 states. So I suspect this is sort of like day 15 (in which we detect details about a 2d map) but here we are detecting a truth table instead. One limitation is that we have at most 15 instructions to use, so probably some optimization needed to encode this truth table. This might be of interest (putting the link here just so that I don't forget what it's called again): Update: forget about Karnaugh map, it does not scale to variables >= 6. However we have some constraints that might be interesting: Notice that while the truth table of AND and OR depends on the values of both of the input registers, NOT completely ignores what value is in Y, meaning it could destroy information so if we want to get some negated read from a register, NOT must be the first instruction to read from it. In addition, although this is not explicitly specified that *when* does register J and T reset to false, but I suspect it means every turn, meaning we can't take advange of "hidden states" - say we have two different situations where all read-only registers are the same but T is different - this assumption actually limits the solution space quite a lot. -} import Control.Monad import Data.Char import Javran.AdventOfCode.Prelude import Javran.AdventOfCode.Y2019.IntCode data Day21 deriving (Generic) TODO : I do n't have a good idea of how to solve this in a general way for now , but I think the best we can do is to have some tools to help the process of getting one solution and gradually automate what we can . TODO: I don't have a good idea of how to solve this in a general way for now, but I think the best we can do is to have some tools to help the process of getting one solution and gradually automate what we can. -} if we do nothing , we fall at this scenario : > # # # # # @ # # # # # # # # # # # So we issue ` NOT A J ` , which should allow us to jump here : > @ > # # # # > ABCD Next failure : > # # # # # .. # @ # # # # # # # # Meaning we should not jump here : > @ > # .. # . > ABCD or , recognizing jumping a bit earlier will allow us to landing on a safe block , we should jump here : > @ > # # .. # > ABCD So ` OR D J ` , but we now have two branches . making room by using T : - NOT A J - OR D T - OR T J Next failure : > # # # # # .. # @ # # # # # # # # We jumped too eagerly here : > @ > # # # # # > ABCD Probably putting in a condition that C should be missing : - NOT A J - NOT C T - AND D T - OR T J notice how NOT must be the first one of each " AND - section " if we do nothing, we fall at this scenario: > #####@########### So we issue `NOT A J`, which should allow us to jump here: > @ > # ### > ABCD Next failure: > #####..#@######## Meaning we should not jump here: > @ > #..#. > ABCD or, recognizing jumping a bit earlier will allow us to landing on a safe block, we should jump here: > @ > ##..# > ABCD So `OR D J`, but we now have two branches. making room by using T: - NOT A J - OR D T - OR T J Next failure: > #####..#@######## We jumped too eagerly here: > @ > ##### > ABCD Probably putting in a condition that C should be missing: - NOT A J - NOT C T - AND D T - OR T J notice how NOT must be the first one of each "AND-section" -} p1Input :: [String] p1Input = [ "NOT A J" , "NOT C T" , "AND D T" , "OR T J" , "WALK" ] Starting from scratch , but ` NOT A J ` looks good to keep . Failure : > # # # # # .. # @ # # # # # # # # let 's make it jump when D is present > @ > # # .. # . # # # # > ABCDEFGHI - NOT A J - OR D T - OR T J ... I get the feeling that this is exactly p1 , let 's just use the stuff there ... also let 's change notation . say in p1 we have : > ! A + ! C*D should not jump : > @ .............. > # # # . # . # .. # # # # # # > ABCDEFGHI > ! A + ! should not jump : > @ ............ > # . # # . # . # # # # # # > ABCDEFGHI > @ > # # . # # . # . # # > ABCDEFGHI > ! A + ! C*D*H + ! B*F should not jump : > @ ......... > # # ... # # # # # > ABCDEFGHI > ! A + ! C*D*H + ! B*D*F should jump : > @ ............ > # . # # ... # # . # # # > ABCDEFGHI > @ ... ? ... ? > # # . # # ... # # . # # # > ABCDEFGHI > ! A + ! C*D*H + ! B*D*F + ! B*D*H Starting from scratch, but `NOT A J` looks good to keep. Failure: > #####..#@######## let's make it jump when D is present > @ > ##..#.#### > ABCDEFGHI - NOT A J - OR D T - OR T J ... I get the feeling that this is exactly p1, let's just use the stuff there... also let's change notation. say in p1 we have: > !A + !C*D should not jump: > @.............. > ###.#.#..###### > ABCDEFGHI > !A + !C*D*H should not jump: > @............ > #.##.#.###### > ABCDEFGHI > @ > ##.##.#.## > ABCDEFGHI > !A + !C*D*H + !B*F should not jump: > @......... > ##...##### > ABCDEFGHI > !A + !C*D*H + !B*D*F should jump: > @............ > #.##...##.### > ABCDEFGHI > @...?...? > ##.##...##.### > ABCDEFGHI > !A + !C*D*H + !B*D*F + !B*D*H -} p2Input :: [String] p2Input = [ "NOT A J" , "NOT C T" , "AND D T" , "AND H T" , "OR T J" , "NOT B T" , "AND D T" , "AND F T" , "OR T J" , "NOT B T" , "AND D T" , "AND H T" , "OR T J" , "RUN" ] TODO : find something not that manual ... TODO: find something not that manual... -} instance Solution Day21 where solutionRun _ SolutionContext {getInputS, answerShow} = do code <- parseCodeOrDie <$> getInputS let runPart1 = True runPart2 = True when runPart1 do (_, out) <- runProgram code (fmap ord $ unlines p1Input) let isSolved = last out > 0x7f if isSolved then answerShow (last out) else putStrLn (fmap chr out) when runPart2 do (_, out) <- runProgram code (fmap ord $ unlines p2Input) let isSolved = last out > 0x7f if isSolved then answerShow (last out) else putStrLn (fmap chr out)
b8965e4245cda2faf256f90cf95c4cded728f5c9916bdfe64e6dd3463c1c6601
nuprl/gradual-typing-performance
make-cards.rkt
(module make-cards racket (require racket/class (prefix-in mred: racket/draw) (prefix-in card-class: "card-class.rkt")) (provide back deck-of-cards (contract-out [make-card (->i ([front-bm (back-bm) (and/c (is-a?/c mred:bitmap%) (same-size back-bm))] [back-bm (or/c #f (is-a?/c mred:bitmap%))] [suit-id any/c] [value any/c]) [result (is-a?/c card-class:card%)])])) (define (same-size given-bitmap) (cond [given-bitmap (define w (send given-bitmap get-width)) (define h (send given-bitmap get-height)) (define (check bmp) (and (= w (send bmp get-width)) (= h (send bmp get-height)))) (procedure-rename check (string->symbol (format "~ax~a-bitmap?" w h)))] [else any/c])) (define (get-bitmap file) (mred:read-bitmap file bg ; ( ( mred : get - display - backing - scale ) . > . 1 ) ) ) (define (make-dim bm-in) (let ([w (send bm-in get-width)] [h (send bm-in get-height)] [s (inexact->exact (round (send bm-in get-backing-scale)))]) (let* ([bm (mred:make-bitmap w h #:backing-scale s)] [mdc (make-object mred:bitmap-dc% bm)]) (send mdc draw-bitmap bm-in 0 0) (let* ([len (* w h 4 s s)] [b (make-bytes len)]) (send bm get-argb-pixels 0 0 (* w s) (* h s) b #:unscaled? #t) (let loop ([i 0]) (unless (= i len) (when (positive? (modulo i 4)) (bytes-set! b i (quotient (* 3 (bytes-ref b i)) 4))) (loop (add1 i)))) (send bm set-argb-pixels 0 0 (* w s) (* h s) b #:unscaled? #t)) (send mdc set-bitmap #f) bm))) (define here (let ([cp (collection-path "games" "cards")]) (lambda (file) (build-path cp (if #t ;;bg;((mred:get-display-depth) . <= . 8) "locolor" "hicolor") file)))) (define back (get-bitmap (here "card-back.png"))) (define dim-back (make-dim back)) (define deck-of-cards (let* ([w (send back get-width)] [h (send back get-height)]) (let sloop ([suit 4]) (if (zero? suit) null (let vloop ([value 13]) (sleep) (if (zero? value) (sloop (sub1 suit)) (let ([front (get-bitmap (here (format "card-~a-~a.png" (sub1 value) (sub1 suit))))]) (cons (make-object card-class:card% suit value w h front back (lambda () (make-dim front)) (lambda () dim-back) (make-hash)) (vloop (sub1 value)))))))))) (define (make-card front-bm back-bm suit-id value) (let ([w (send back get-width)] [h (send back get-height)]) (make-object card-class:card% suit-id value w h front-bm (or back-bm back) (lambda () (make-dim front-bm)) (lambda () (if back-bm (make-dim back) dim-back)) (make-hash)))))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/gofish/base/cards/make-cards.rkt
racket
( ( mred : get - display - backing - scale ) . > . 1 ) ) ) bg;((mred:get-display-depth) . <= . 8)
(module make-cards racket (require racket/class (prefix-in mred: racket/draw) (prefix-in card-class: "card-class.rkt")) (provide back deck-of-cards (contract-out [make-card (->i ([front-bm (back-bm) (and/c (is-a?/c mred:bitmap%) (same-size back-bm))] [back-bm (or/c #f (is-a?/c mred:bitmap%))] [suit-id any/c] [value any/c]) [result (is-a?/c card-class:card%)])])) (define (same-size given-bitmap) (cond [given-bitmap (define w (send given-bitmap get-width)) (define h (send given-bitmap get-height)) (define (check bmp) (and (= w (send bmp get-width)) (= h (send bmp get-height)))) (procedure-rename check (string->symbol (format "~ax~a-bitmap?" w h)))] [else any/c])) (define (get-bitmap file) (mred:read-bitmap file (define (make-dim bm-in) (let ([w (send bm-in get-width)] [h (send bm-in get-height)] [s (inexact->exact (round (send bm-in get-backing-scale)))]) (let* ([bm (mred:make-bitmap w h #:backing-scale s)] [mdc (make-object mred:bitmap-dc% bm)]) (send mdc draw-bitmap bm-in 0 0) (let* ([len (* w h 4 s s)] [b (make-bytes len)]) (send bm get-argb-pixels 0 0 (* w s) (* h s) b #:unscaled? #t) (let loop ([i 0]) (unless (= i len) (when (positive? (modulo i 4)) (bytes-set! b i (quotient (* 3 (bytes-ref b i)) 4))) (loop (add1 i)))) (send bm set-argb-pixels 0 0 (* w s) (* h s) b #:unscaled? #t)) (send mdc set-bitmap #f) bm))) (define here (let ([cp (collection-path "games" "cards")]) (lambda (file) (build-path cp "locolor" "hicolor") file)))) (define back (get-bitmap (here "card-back.png"))) (define dim-back (make-dim back)) (define deck-of-cards (let* ([w (send back get-width)] [h (send back get-height)]) (let sloop ([suit 4]) (if (zero? suit) null (let vloop ([value 13]) (sleep) (if (zero? value) (sloop (sub1 suit)) (let ([front (get-bitmap (here (format "card-~a-~a.png" (sub1 value) (sub1 suit))))]) (cons (make-object card-class:card% suit value w h front back (lambda () (make-dim front)) (lambda () dim-back) (make-hash)) (vloop (sub1 value)))))))))) (define (make-card front-bm back-bm suit-id value) (let ([w (send back get-width)] [h (send back get-height)]) (make-object card-class:card% suit-id value w h front-bm (or back-bm back) (lambda () (make-dim front-bm)) (lambda () (if back-bm (make-dim back) dim-back)) (make-hash)))))
5a9f108daa1ddef95663371f4c194acad6f63e2451cfc5a9dada6986006aa3af
fourier/lw-config
darkula-theme.lisp
(in-package "CL-USER") (defun make-rgb (red green blue &optional alpha) (color:make-rgb (/ red 255s0) (/ green 255s0) (/ blue 255s0) (and alpha (/ alpha 255s0)))) (defvar *darkula-color-table* '(:darkula-background (43 43 43) :darkula-foreground (169 183 198) :darkula-selection-background (33 66 131) :darkula-function-name (255 198 109) :darkula-comment (128 128 128) :darkula-type (170 73 38) :darkula-variable-name (152 118 170) :darkula-string (106 135 89) :darkula-keyword (204 120 50) :darkula-builtin (152 118 170) :darkula-caret (187 187 187) :darkula-unknown-symbol (188 63 60) :darkula-warning-background (82 80 58) :darkula-warning-foreground (190 145 23) :darkula-matched-brace-foreground (255 239 40) :darkula-matched-brace-background (59 81 77) :darkula-incremental-search-background (50 81 61) :darkula-incremental-search-other-matches-background (21 82 33) :darkula-buffers-list-selected-foreground (255 255 255) :darkula-buffers-list-unselected-foreground (187 187 187) )) (loop for list on *darkula-color-table* by #'cddr for name = (first list) for rgb = (second list) do (color:define-color-alias name (apply #'make-rgb rgb))) (editor-color-theme:define-color-theme "darkula" () :foreground :darkula-foreground :background :darkula-background ;; if not specified uses the :background and :foreground :listener-background :darkula-background :listener-foreground :darkula-foreground :output-background :black :output-foreground :green :buffers-foreground :darkula-buffers-list-unselected-foreground :buffers-selected-foreground :darkula-buffers-list-selected-foreground :buffers-background :darkula-background :region '(:background :darkula-selection-background) :highlight '(:background :darkula-background) :font-lock-function-name-face '(:foreground :darkula-function-name) :font-lock-comment-face '(:foreground :darkula-comment :italic-p t) :font-lock-type-face '(:foreground :darkula-type) :font-lock-variable-name-face '(:foreground :darkula-variable-name :italic-p t) :font-lock-string-face '(:foreground :darkula-string) :font-lock-keyword-face '(:foreground :darkula-keyword) :font-lock-builtin-face '(:foreground :darkula-builtin :italic-p t) :compiler-note-highlight '(:foreground :magenta :bold-p t) :compiler-warning-highlight '(:foreground :darkula-warning-foreground :background :darkula-warning-background :bold-p t) :compiler-error-highlight '(:foreground :darkula-unknown-symbol :inverse-p t) :show-point-face '(:foreground :darkula-matched-brace-foreground :background :darkula-matched-brace-background :bold-p t) :interactive-input-face '(:foreground :cyan) :non-focus-complete-face '(:background :darkula-background) :incremental-search-face '(:background :darkula-incremental-search-background :underline-p t) :incremental-search-other-matches-face '(:background :darkula-incremental-search-other-matches-background))
null
https://raw.githubusercontent.com/fourier/lw-config/a77c92af0e9641325235055257490200a3e89714/darkula-theme.lisp
lisp
if not specified uses the :background and :foreground
(in-package "CL-USER") (defun make-rgb (red green blue &optional alpha) (color:make-rgb (/ red 255s0) (/ green 255s0) (/ blue 255s0) (and alpha (/ alpha 255s0)))) (defvar *darkula-color-table* '(:darkula-background (43 43 43) :darkula-foreground (169 183 198) :darkula-selection-background (33 66 131) :darkula-function-name (255 198 109) :darkula-comment (128 128 128) :darkula-type (170 73 38) :darkula-variable-name (152 118 170) :darkula-string (106 135 89) :darkula-keyword (204 120 50) :darkula-builtin (152 118 170) :darkula-caret (187 187 187) :darkula-unknown-symbol (188 63 60) :darkula-warning-background (82 80 58) :darkula-warning-foreground (190 145 23) :darkula-matched-brace-foreground (255 239 40) :darkula-matched-brace-background (59 81 77) :darkula-incremental-search-background (50 81 61) :darkula-incremental-search-other-matches-background (21 82 33) :darkula-buffers-list-selected-foreground (255 255 255) :darkula-buffers-list-unselected-foreground (187 187 187) )) (loop for list on *darkula-color-table* by #'cddr for name = (first list) for rgb = (second list) do (color:define-color-alias name (apply #'make-rgb rgb))) (editor-color-theme:define-color-theme "darkula" () :foreground :darkula-foreground :background :darkula-background :listener-background :darkula-background :listener-foreground :darkula-foreground :output-background :black :output-foreground :green :buffers-foreground :darkula-buffers-list-unselected-foreground :buffers-selected-foreground :darkula-buffers-list-selected-foreground :buffers-background :darkula-background :region '(:background :darkula-selection-background) :highlight '(:background :darkula-background) :font-lock-function-name-face '(:foreground :darkula-function-name) :font-lock-comment-face '(:foreground :darkula-comment :italic-p t) :font-lock-type-face '(:foreground :darkula-type) :font-lock-variable-name-face '(:foreground :darkula-variable-name :italic-p t) :font-lock-string-face '(:foreground :darkula-string) :font-lock-keyword-face '(:foreground :darkula-keyword) :font-lock-builtin-face '(:foreground :darkula-builtin :italic-p t) :compiler-note-highlight '(:foreground :magenta :bold-p t) :compiler-warning-highlight '(:foreground :darkula-warning-foreground :background :darkula-warning-background :bold-p t) :compiler-error-highlight '(:foreground :darkula-unknown-symbol :inverse-p t) :show-point-face '(:foreground :darkula-matched-brace-foreground :background :darkula-matched-brace-background :bold-p t) :interactive-input-face '(:foreground :cyan) :non-focus-complete-face '(:background :darkula-background) :incremental-search-face '(:background :darkula-incremental-search-background :underline-p t) :incremental-search-other-matches-face '(:background :darkula-incremental-search-other-matches-background))
e9b145c7373e3f355c6133804c45f4af34d191a4a2837d33d6184f9a30ff807a
christiaanb/clash
Alu.hs
{-# LANGUAGE Arrows #-} module Alu where import CLasH.HardwareTypes dontcare = Low program = [ -- (addr, we , op ) z = r1 and t ( 0 ) ; t = r1 ( 1 ) z = r0 or t ( 1 ) ; t = r0 ( 0 ) r0 = z ( 1 ) z = r1 and t ( 0 ) ; t = r1 ( 1 ) (High, High, dontcare) -- r1 = z (0) ] -- --initial_state = (Regs Low High, Low, Low) initial_state = State ( State ( 0 , 1 ) , 0 , 0 ) type Word = Unsigned D4 Register bank type RegAddr = Bit type RegisterBankState = State (Word, Word) register_bank :: RegisterBankState -> -- ^ State (RegAddr, Bit, Word) -> -- ^ (Address, Write Enable, Data) ^ ( State ' , Output ) register_bank (State s) (addr, we, d) = (State s', o) where s' = case we of Low -> s -- Read High -> -- Write let (r0, r1) = s r0' = case addr of Low -> d; High -> r0 r1' = case addr of High -> d; Low -> r1 in (r0', r1') o = case we of -- Read Low -> case addr of Low -> fst s; High -> snd s -- Write High -> 0 -- Don't output anything useful -- ALU type AluOp = Bit alu :: AluOp -> Word -> Word -> Word alu High a b = a + b alu Low a b = a - b delayN (State s) inp = (State (inp +>> s), vlast s) # ANN exec TopEntity # exec = proc (addr,we,op) -> do rec (t,z) <- delayN ^^^ (singleton (0,0)) -< (t',z') t' <- register_bank ^^^ (0,1) -< (addr,we,z) z' <- arr (\(a,b,c) -> alu a b c) -< (op, t', t) returnA -< z'
null
https://raw.githubusercontent.com/christiaanb/clash/18247975e8bbd3f903abc667285e11228a640457/examples/Alu.hs
haskell
# LANGUAGE Arrows # (addr, we , op ) r1 = z (0) --initial_state = (Regs Low High, Low, Low) ^ State ^ (Address, Write Enable, Data) Read Write Read Write Don't output anything useful ALU
module Alu where import CLasH.HardwareTypes dontcare = Low program = [ z = r1 and t ( 0 ) ; t = r1 ( 1 ) z = r0 or t ( 1 ) ; t = r0 ( 0 ) r0 = z ( 1 ) z = r1 and t ( 0 ) ; t = r1 ( 1 ) ] initial_state = State ( State ( 0 , 1 ) , 0 , 0 ) type Word = Unsigned D4 Register bank type RegAddr = Bit type RegisterBankState = State (Word, Word) register_bank :: ^ ( State ' , Output ) register_bank (State s) (addr, we, d) = (State s', o) where s' = case we of let (r0, r1) = s r0' = case addr of Low -> d; High -> r0 r1' = case addr of High -> d; Low -> r1 in (r0', r1') o = case we of Low -> case addr of Low -> fst s; High -> snd s type AluOp = Bit alu :: AluOp -> Word -> Word -> Word alu High a b = a + b alu Low a b = a - b delayN (State s) inp = (State (inp +>> s), vlast s) # ANN exec TopEntity # exec = proc (addr,we,op) -> do rec (t,z) <- delayN ^^^ (singleton (0,0)) -< (t',z') t' <- register_bank ^^^ (0,1) -< (addr,we,z) z' <- arr (\(a,b,c) -> alu a b c) -< (op, t', t) returnA -< z'
6c9ea35d8dde17a1c8b21082c1ab0ae6170c0cfcbe1a9fcdab576f7bc4495d07
sKabYY/palestra
p41.scm
(load "lib.scm") (define (unique-3-tuple n) (flatmap (lambda (k) (map (lambda (p) (list (car p) (cadr p) k)) (unique-pairs (- k 1)))) (enumerate-interval 1 n))) (define (sum-s n s) (define (sum-equal-s? tuple) (= s (+ (car tuple) (cadr tuple) (caddr tuple)))) (filter sum-equal-s? (unique-3-tuple n))) (display (sum-s 6 10)) (newline)
null
https://raw.githubusercontent.com/sKabYY/palestra/0906cc3a1fb786093a388d5ae7d59120f5aae16c/old1/sicp/2/p41.scm
scheme
(load "lib.scm") (define (unique-3-tuple n) (flatmap (lambda (k) (map (lambda (p) (list (car p) (cadr p) k)) (unique-pairs (- k 1)))) (enumerate-interval 1 n))) (define (sum-s n s) (define (sum-equal-s? tuple) (= s (+ (car tuple) (cadr tuple) (caddr tuple)))) (filter sum-equal-s? (unique-3-tuple n))) (display (sum-s 6 10)) (newline)
1037b8939958828ef5377d8bffce68c6a49bbdaf1fe4f4230adc23f4fe81d08e
larcenists/larceny
unicode0.body.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Help procedures (not part of R6RS) ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Given an exact integer key and a vector of exact integers ; in strictly increasing order, returns the largest i such ; that element i of the vector is less than or equal to key, ; or -1 if key is less than every element of the vector. (define (binary-search-of-vector key vec) ; Loop invariants: ; 0 <= i < j <= (vector-length vec) ; vec[i] <= key ; if j < (vector-length vec), then key < vec[j] (define (loop i j) (let ((mid (div (+ i j) 2))) (cond ((= i mid) mid) ((<= (vector-ref vec mid) key) (loop mid j)) (else (loop i mid))))) (let ((hi (vector-length vec))) (if (or (= hi 0) (< key (vector-ref vec 0))) -1 (loop 0 hi)))) ; Given an exact integer key and a vector of exact integers ; in strictly increasing order, returns the index of key, ; or returns #f if the key is not within the vector. (define (binary-search key vec) ; Loop invariants: ; 0 <= i < j <= (vector-length vec) ; vec[i] <= key ; if j < (vector-length vec), then key < vec[j] (define (loop i j) (let ((mid (div (+ i j) 2))) (cond ((= i mid) (if (= key (vector-ref vec mid)) mid #f)) ((<= (vector-ref vec mid) key) (loop mid j)) (else (loop i mid))))) (let ((hi (vector-length vec))) (if (or (= hi 0) (< key (vector-ref vec 0))) #f (loop 0 hi)))) Given an exact integer key and a bytevector of 16 - bit unsigned ; big-endian integers in strictly increasing order, returns i such that elements ( * 2 i ) and ( + ( * 2 i ) 1 ) ; are equal to the key, or returns #f if the key is not found. (define (binary-search-16bit key bvec) (define (bytevector-ref16 bvec i) (let ((i2 (+ i i))) (+ (* 256 (bytevector-u8-ref bvec i2)) (bytevector-u8-ref bvec (+ i2 1))))) (define (loop i j) (let ((mid (div (+ i j) 2))) (cond ((= i mid) (if (= (bytevector-ref16 bvec mid) key) mid #f)) ((<= (bytevector-ref16 bvec mid) key) (loop mid j)) (else (loop i mid))))) (let ((hi (div (bytevector-length bvec) 2))) (if (or (= hi 0) (< key (bytevector-ref16 bvec 0))) #f (loop 0 hi)))) ; Given a binary comparison predicate, returns a predicate that accepts two or more arguments . (define (make-comparison-predicate binop) (letrec ((loop (lambda (first rest) (cond ((null? rest) #t) ((binop first (car rest)) (loop (car rest) (cdr rest))) (else #f))))) (lambda (a b . rest) (if (null? rest) (binop a b) (and (binop a b) (loop b rest))))))
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/tools/R6RS/r6rs/unicode-reference/unicode0.body.scm
scheme
Help procedures (not part of R6RS) Given an exact integer key and a vector of exact integers in strictly increasing order, returns the largest i such that element i of the vector is less than or equal to key, or -1 if key is less than every element of the vector. Loop invariants: 0 <= i < j <= (vector-length vec) vec[i] <= key if j < (vector-length vec), then key < vec[j] Given an exact integer key and a vector of exact integers in strictly increasing order, returns the index of key, or returns #f if the key is not within the vector. Loop invariants: 0 <= i < j <= (vector-length vec) vec[i] <= key if j < (vector-length vec), then key < vec[j] big-endian integers in strictly increasing order, are equal to the key, or returns #f if the key is not found. Given a binary comparison predicate, returns a predicate
(define (binary-search-of-vector key vec) (define (loop i j) (let ((mid (div (+ i j) 2))) (cond ((= i mid) mid) ((<= (vector-ref vec mid) key) (loop mid j)) (else (loop i mid))))) (let ((hi (vector-length vec))) (if (or (= hi 0) (< key (vector-ref vec 0))) -1 (loop 0 hi)))) (define (binary-search key vec) (define (loop i j) (let ((mid (div (+ i j) 2))) (cond ((= i mid) (if (= key (vector-ref vec mid)) mid #f)) ((<= (vector-ref vec mid) key) (loop mid j)) (else (loop i mid))))) (let ((hi (vector-length vec))) (if (or (= hi 0) (< key (vector-ref vec 0))) #f (loop 0 hi)))) Given an exact integer key and a bytevector of 16 - bit unsigned returns i such that elements ( * 2 i ) and ( + ( * 2 i ) 1 ) (define (binary-search-16bit key bvec) (define (bytevector-ref16 bvec i) (let ((i2 (+ i i))) (+ (* 256 (bytevector-u8-ref bvec i2)) (bytevector-u8-ref bvec (+ i2 1))))) (define (loop i j) (let ((mid (div (+ i j) 2))) (cond ((= i mid) (if (= (bytevector-ref16 bvec mid) key) mid #f)) ((<= (bytevector-ref16 bvec mid) key) (loop mid j)) (else (loop i mid))))) (let ((hi (div (bytevector-length bvec) 2))) (if (or (= hi 0) (< key (bytevector-ref16 bvec 0))) #f (loop 0 hi)))) that accepts two or more arguments . (define (make-comparison-predicate binop) (letrec ((loop (lambda (first rest) (cond ((null? rest) #t) ((binop first (car rest)) (loop (car rest) (cdr rest))) (else #f))))) (lambda (a b . rest) (if (null? rest) (binop a b) (and (binop a b) (loop b rest))))))
f341845b63404ade5b4c3093f8a579c8791ef1ade93d4f304ef87d385983d3fa
puppetlabs/puppetserver
master_core.clj
(ns puppetlabs.services.master.master-core (:require [bidi.bidi :as bidi] [bidi.schema :as bidi-schema] [cheshire.core :as json] [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [me.raynes.fs :as fs] [puppetlabs.comidi :as comidi] [puppetlabs.http.client.common :as http-client-common] [puppetlabs.http.client.metrics :as http-client-metrics] [puppetlabs.i18n.core :as i18n] [puppetlabs.kitchensink.core :as ks] [puppetlabs.metrics :as metrics] [puppetlabs.metrics.http :as http-metrics] [puppetlabs.puppetserver.common :as ps-common] [puppetlabs.puppetserver.jruby-request :as jruby-request] [puppetlabs.puppetserver.ringutils :as ringutils] [puppetlabs.ring-middleware.core :as middleware] [puppetlabs.ring-middleware.utils :as middleware-utils] [puppetlabs.services.master.file-serving :as file-serving] [puppetlabs.services.protocols.jruby-puppet :as jruby-protocol] [puppetlabs.trapperkeeper.services.status.status-core :as status-core] [ring.middleware.params :as ring] [ring.util.response :as rr] [schema.core :as schema] [slingshot.slingshot :refer [throw+ try+]]) (:import (clojure.lang IFn) (com.codahale.metrics Gauge MetricRegistry) (com.fasterxml.jackson.core JsonParseException) (java.io FileInputStream) (java.lang.management ManagementFactory) (java.util List Map Map$Entry) (org.jruby.exceptions RaiseException) (org.jruby RubySymbol))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Constants (def puppet-API-version "v3") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Private (def EnvironmentClassesFileClassParameter "Schema for an individual parameter found in a class defined within an environment_classes file. Includes the name of the parameter. Optionally, if available in the parameter definition, includes the type, source text for the parameter's default value, and a literal (primitive data type) representation of the parameter's default value. For example, if a class parameter were defined like this in a Puppet manifest ... Integer $someint = 3 ... then the map representation of that parameter would be: {:name \"someint\", :type \"Integer\", :default_source \"3\", :default_literal 3 } For a parameter default value which contains an expression - something that cannot be coerced into a primitive data type - the map representation omits the default_literal. For example, this parameter definition in a Puppet manifest ... String $osfam = \"$::osfamily\" ... would produce a map representation which looks like this ... {:name \"osfam\", :type \"String\", :default_source \"\"$::osfamily\"\", } The data types that could be used in the value for a :default_literal may vary over time, as the Puppet language continues to evolve. For this reason, the more permissive schema/Any is used here. General data types that we could see based on current types that the Puppet language allows today are in the table below: Puppet | :default_literal value ================================================ String | java.lang.String Boolean | java.lang.Boolean Float/Numeric | java.lang.Double Integer/Numeric | java.lang.Long Array | clojure.lang.LazySeq Hash | clojure.lang.PersistentTreeMap For the Regexp, Undef, Default, any Hash objects (top-level or nested within another Array or Hash) whose keys are not of type String, and any Array or Hash objects (top-level or nested within another Array or Hash) which contain a Regexp, Undef, or Default typed value, the :default_literal value will not be populated. These are not populated because they cannot be represented in JSON transfer without some loss of fidelity as compared to what the original data type from the manifest was." {:name schema/Str (schema/optional-key :type) schema/Str (schema/optional-key :default_source) schema/Str (schema/optional-key :default_literal) schema/Any}) (def EnvironmentClassesFileClass "Schema for an individual class found within an environment_classes file entry. Includes the name of the class and a vector of information about each parameter found in the class definition." {:name schema/Str :params [EnvironmentClassesFileClassParameter]}) (def EnvironmentClassesFileWithError "Schema for an environment_classes file that could not be parsed. Includes the path to the file and an error string containing details about the problem encountered during parsing." {:path schema/Str :error schema/Str}) (def EnvironmentClassesFileWithClasses "Schema for an environment_classes file that was successfully parsed. Includes the path to the file and a vector of information about each class found in the file." {:path schema/Str :classes [EnvironmentClassesFileClass]}) (def EnvironmentClassesFileEntry "Schema for an individual file entry which is part of the return payload for an environment_classes request." (schema/conditional #(contains? % :error) EnvironmentClassesFileWithError #(contains? % :classes) EnvironmentClassesFileWithClasses)) (def EnvironmentClassesInfo "Schema for the return payload an environment_classes request." {:name schema/Str :files [EnvironmentClassesFileEntry]}) (def EnvironmentModuleInfo "Schema for a given module that can be returned within the :modules key in EnvironmentModulesInfo." {:name schema/Str :version (schema/maybe schema/Str)}) (def EnvironmentModulesInfo "Schema for the return payload for an environment_classes request." {:name schema/Str :modules [EnvironmentModuleInfo]}) (def TaskData "Response from puppet's TaskInformationService for data on a single task, *after* it has been converted to a Clojure map." {:metadata (schema/maybe {schema/Keyword schema/Any}) :files [{:name schema/Str :path schema/Str}] (schema/optional-key :error) {:msg schema/Str :kind schema/Str :details {schema/Keyword schema/Any}}}) (def TaskDetails "A filled-in map of information about a task." {:metadata {schema/Keyword schema/Any} :name schema/Str :files [{:filename schema/Str :sha256 schema/Str :size_bytes schema/Int :uri {:path schema/Str :params {:environment schema/Str (schema/optional-key :code_id) schema/Str}}}]}) (def PlanData "Response from puppet's PlanInformationService for data on a single plan, *after* it has been converted to a Clojure map." {:metadata (schema/maybe {schema/Keyword schema/Any}) :files [{:name schema/Str :path schema/Str}] (schema/optional-key :error) {:msg schema/Str :kind schema/Str :details {schema/Keyword schema/Any}}}) (def PlanDetails "A filled-in map of information about a plan." {:metadata {schema/Keyword schema/Any} :name schema/Str}) (defn obj-or-ruby-symbol-as-string "If the supplied object is of type RubySymbol, returns a string representation of the RubySymbol. Otherwise, just returns the original object." [obj] (if (instance? RubySymbol obj) (.asJavaString obj) obj)) (defn obj->keyword "Attempt to convert the supplied object to a Clojure keyword. On failure to do so, throws an IllegalArgumentException." [obj] (if-let [obj-as-keyword (-> obj obj-or-ruby-symbol-as-string keyword)] obj-as-keyword (throw (IllegalArgumentException. (i18n/trs "Object cannot be coerced to a keyword: {0}" obj))))) (defn sort-nested-info-maps "For a data structure, recursively sort any nested maps and sets descending into map values, lists, vectors and set members as well. The result should be that all maps in the data structure become explicitly sorted with natural ordering. This can be used before serialization to ensure predictable serialization. The returned data structure is not a transient so it is still able to be modified, therefore caution should be taken to avoid modification else the data will lose its sorted status. This function was copypasta'd from clj-kitchensink's core/sort-nested-maps. sort-nested-maps can only deep sort a structure that contains native Clojure types, whereas this function includes a couple of changes which handle the sorting of the data structure returned from JRuby: 1) This function sorts keys within any `java.util.Map`, as opposed to just an object for which `map?` returns true. 2) This function attempts to coerces any keys found within a map to a Clojure keyword before using `sorted-map` to sort the keys. `sorted-map` would otherwise throw an error upon encountering a non-keyword type key." [data] (cond (instance? Map data) (into (sorted-map) (for [[k v] data] [(obj->keyword k) (sort-nested-info-maps v)])) (instance? Iterable data) (map sort-nested-info-maps data) :else data)) (schema/defn ^:always-validate if-none-match-from-request :- (schema/maybe String) "Retrieve the value of an 'If-None-Match' HTTP header from the supplied Ring request. If the header is not found, returns nil." [request :- {schema/Keyword schema/Any}] ;; SERVER-1153 - For a non-nil value, the characters '--gzip' will be ;; stripped from the end of the value which is returned. The '--gzip' characters are added by the Jetty web server to an HTTP Etag response ;; header for cases in which the corresponding response payload has been gzipped . Newer versions of Jetty , 9.3.x series , have logic in the GzipHandler to strip these characters back off of the If - None - Match header value before the Ring request would see it . The version of being ;; used at the time this code was written (9.2.10), however, did not have this ;; logic to strip the "--gzip" characters from the incoming header. This ;; function compensates for that by stripping the characters here - before ;; other Puppet Server code would use it. When/if Puppet Server is upgraded to a version of trapperkeeper - webserver - jetty9 which is based on Jetty 9.3.x ;; or newer, it may be safe to take out the line that removes the '--gzip' ;; characters. (some-> (rr/get-header request "If-None-Match") (str/replace #"--gzip$" ""))) (schema/defn ^:always-validate add-path-to-file-entry :- Map "Convert the value for a manifest file entry into an appropriate map for use in serializing an environment_classes response to JSON." [file-detail :- Map file-name :- schema/Str] (.put file-detail "path" file-name) file-detail) (schema/defn ^:always-validate manifest-info-from-jruby->manifest-info-for-json :- EnvironmentClassesFileEntry "Convert the per-manifest file information received from the jruby service into an appropriate map for use in serializing an environment_classes response to JSON." [file-info :- Map$Entry] (-> file-info val (add-path-to-file-entry (key file-info)) sort-nested-info-maps)) (schema/defn ^:always-validate class-info-from-jruby->class-info-for-json :- EnvironmentClassesInfo "Convert a class info map received from the jruby service into an appropriate map for use in serializing an environment_classes response to JSON. The map that this function returns should be 'sorted' by key - both at the top-level and within any nested map - so that it will consistently serialize to the exact same content. For this reason, this function and the functions that this function calls use the `sorted-map` and `sort-nested-java-maps` helper functions when constructing / translating maps." [info-from-jruby :- Map environment :- schema/Str] (->> info-from-jruby (map manifest-info-from-jruby->manifest-info-for-json) (sort-by :path) (vec) (sorted-map :name environment :files))) (schema/defn ^:always-validate response-with-etag :- ringutils/RingResponse "Create a Ring response, including the supplied 'body' and an HTTP 'Etag' header set to the supplied 'etag' parameter." [body :- schema/Str etag :- schema/Str] (-> body (rr/response) (rr/header "Etag" etag))) (schema/defn ^:always-validate not-modified-response :- ringutils/RingResponse "Create an HTTP 304 (Not Modified) response, including an HTTP 'Etag' header set to the supplied 'etag' parameter." [etag] (-> "" (response-with-etag etag) (rr/status 304))) (schema/defn ^:always-validate all-tasks-response! :- ringutils/RingResponse "Process the info, returning a Ring response to be propagated back up to the caller of the endpoint. Returns environment as a list of objects for an eventual future in which tasks for all environments can be requested, and a given task will list all the environments it is found in." [info-from-jruby :- [{schema/Any schema/Any}] environment :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (let [format-task (fn [task-object] {:name (:name task-object) :private (get-in task-object [:metadata :private] false) :description (get-in task-object [:metadata :description] "") :environment [{:name environment :code_id nil}]})] (->> (map format-task info-from-jruby) (middleware-utils/json-response 200)))) (defn task-file-uri-components "The 'id' portion for a task implementation is a single component like 'foo.sh' and can never be nested in subdirectories. In that case we know the 'file' must be structured <environment>/<module root>/<module>/tasks/<filename>. Other task files are the path relative to the module root, in the form <module>/<mount>/<path> where <path> may have subdirectories. For those, we just slice that off the end of the file path and take the last component that remains as the module root." [file-id file] (if (str/includes? file-id "/") (let [[module mount subpath] (str/split file-id #"/" 3) module-root (fs/base-name (subs file 0 (str/last-index-of file file-id)))] [module-root module mount subpath]) (take-last 4 (str/split file #"/")))) (defn describe-task-file [get-code-content env-name code-id file-data] (let [file (:path file-data) file-id (:name file-data) size (fs/size file) sha256 (ks/file->sha256 (io/file file)) ;; we trust the file path from Puppet, so extract the relative path info from the file [module-root module-name mount relative-path] (task-file-uri-components file-id file) static-path (str/join "/" [module-root module-name mount relative-path]) uri (try ;; if code content can be retrieved, then use static_file_content (when (not= sha256 (ks/stream->sha256 (get-code-content env-name code-id static-path))) (throw (Exception. (i18n/trs "file did not match versioned file contents")))) {:path (str "/puppet/v3/static_file_content/" static-path) :params {:environment env-name :code_id code-id}} (catch Exception e (log/debug (i18n/trs "Static file unavailable for {0}: {1}" file e)) {:path (case mount "files" (format "/puppet/v3/file_content/modules/%s/%s" module-name relative-path) "lib" (format "/puppet/v3/file_content/plugins/%s" relative-path) "scripts" (format "/puppet/v3/file_content/scripts/%s/%s" module-name relative-path) "tasks" (format "/puppet/v3/file_content/tasks/%s/%s" module-name relative-path)) :params {:environment env-name}}))] {:filename file-id :sha256 sha256 :size_bytes size :uri uri})) (defn full-task-name "Construct a full task name from the two components. If the task's short name is 'init', then the second component is omitted so the task name is just the module's name." [module-name task-shortname] (if (= task-shortname "init") module-name (str module-name "::" task-shortname))) (schema/defn ^:always-validate task-data->task-details :- TaskDetails "Fills in a bare TaskData map by examining the files it refers to, returning TaskDetails." [task-data :- TaskData get-code-content :- IFn env-name :- schema/Str code-id :- (schema/maybe schema/Str) module-name :- schema/Str task-name :- schema/Str] (if (:error task-data) (throw+ (:error task-data)) {:metadata (or (:metadata task-data) {}) :name (full-task-name module-name task-name) :files (mapv (partial describe-task-file get-code-content env-name code-id) (:files task-data))})) (schema/defn environment-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when an environment is not found." [environment :- schema/Str] (rr/not-found (i18n/tru "Could not find environment ''{0}''" environment))) (schema/defn module-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when a module is not found." [module :- schema/Str] (rr/not-found (i18n/tru "Could not find module ''{0}''" module))) (schema/defn task-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when a task is not found." [task :- schema/Str] (rr/not-found (i18n/tru "Could not find task ''{0}''" task))) (schema/defn plan-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when a plan is not found." [plan :- schema/Str] (rr/not-found (i18n/tru "Could not find plan ''{0}''" plan))) (schema/defn ^:always-validate module-info-from-jruby->module-info-for-json :- EnvironmentModulesInfo "Creates a new map with a top level key `name` that corresponds to the requested environment and a top level key `modules` which contains the module information obtained from JRuby." [info-from-jruby :- List environment :- schema/Str] (->> info-from-jruby sort-nested-info-maps vec (sorted-map :name environment :modules))) (schema/defn ^:always-validate environment-module-response! :- ringutils/RingResponse "Process the environment module information, returning a ring response to be propagated back up to the caller of the environment_modules endpoint." ([info-from-jruby :- Map] (let [all-info-as-json (map #(module-info-from-jruby->module-info-for-json (val %) (name (key %))) (sort-nested-info-maps info-from-jruby))] (middleware-utils/json-response 200 all-info-as-json))) ([info-from-jruby :- List environment :- schema/Str] (let [info-as-json (module-info-from-jruby->module-info-for-json info-from-jruby environment)] (middleware-utils/json-response 200 info-as-json)))) (schema/defn ^:always-validate environment-module-info-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for environment_modules information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (if-let [environment (jruby-request/get-environment-from-request request)] (if-let [module-info (jruby-protocol/get-environment-module-info jruby-service (:jruby-instance request) environment)] (environment-module-response! module-info environment) (rr/not-found (i18n/tru "Could not find environment ''{0}''" environment))) (let [module-info (jruby-protocol/get-all-environment-module-info jruby-service (:jruby-instance request))] (environment-module-response! module-info))))) (schema/defn ^:always-validate all-tasks-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for tasks information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request)] (if-let [task-info-for-env (sort-nested-info-maps (jruby-protocol/get-tasks jruby-service (:jruby-instance request) environment))] (all-tasks-response! task-info-for-env environment jruby-service) (environment-not-found environment))))) (schema/defn ^:always-validate task-details :- TaskDetails "Returns a TaskDetails map for the task matching the given environment, module, and name. Will throw a JRuby RaiseException with (EnvironmentNotFound), (MissingModule), or (TaskNotFound) if any of those conditions occur." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) jruby-instance code-content-fn :- IFn environment-name :- schema/Str code-id :- (schema/maybe schema/Str) module-name :- schema/Str task-name :- schema/Str] (-> (jruby-protocol/get-task-data jruby-service jruby-instance environment-name module-name task-name) sort-nested-info-maps (task-data->task-details code-content-fn environment-name code-id module-name task-name))) (schema/defn exception-matches? :- schema/Bool [^Exception e :- Exception pattern :- schema/Regex] (->> e .getMessage (re-find pattern) boolean)) (defn handle-task-details-jruby-exception "Given a JRuby RaiseException arising from a call to task-details, constructs a 4xx error response if appropriate, otherwise re-throws." [jruby-exception environment module task] (cond (exception-matches? jruby-exception #"^\(EnvironmentNotFound\)") (environment-not-found environment) (exception-matches? jruby-exception #"^\(MissingModule\)") (module-not-found module) (exception-matches? jruby-exception #"^\(TaskNotFound\)") (task-not-found task) :else (throw jruby-exception))) (defn is-task-error? [err] (and (map? err) (:kind err) (str/starts-with? (:kind err) "puppet.task"))) (defn handle-plan-details-jruby-exception "Given a JRuby RaiseException arising from a call to plan-details, constructs a 4xx error response if appropriate, otherwise re-throws." [jruby-exception environment module plan] (cond (exception-matches? jruby-exception #"^\(EnvironmentNotFound\)") (environment-not-found environment) (exception-matches? jruby-exception #"^\(MissingModule\)") (module-not-found module) (exception-matches? jruby-exception #"^\(PlanNotFound\)") (plan-not-found plan) :else (throw jruby-exception))) (defn is-plan-error? [err] (and (map? err) (:kind err) (str/starts-with? (:kind err) "puppet.plan"))) (schema/defn ^:always-validate task-details-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for detailed task information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn] (fn [request] (let [environment (jruby-request/get-environment-from-request request) module (get-in request [:route-params :module-name]) task (get-in request [:route-params :task-name])] (try+ (->> (task-details jruby-service (:jruby-instance request) get-code-content-fn environment (current-code-id-fn environment) module task) (middleware-utils/json-response 200)) (catch is-task-error? {:keys [kind msg details]} (middleware-utils/json-response 500 {:kind kind :msg msg :details details})) (catch RaiseException e (handle-task-details-jruby-exception e environment module task)))))) (schema/defn ^:always-validate all-plans-response! :- ringutils/RingResponse "Process the info, returning a Ring response to be propagated back up to the caller of the endpoint. Returns environment as a list of objects for an eventual future in which tasks for all environments can be requested, and a given task will list all the environments it is found in." [info-from-jruby :- [{schema/Any schema/Any}] environment :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (let [format-plan (fn [plan-object] {:name (:name plan-object) :environment [{:name environment :code_id nil}]})] (->> (map format-plan info-from-jruby) (middleware-utils/json-response 200)))) (schema/defn ^:always-validate all-plans-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for plans information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request)] (if-let [plan-info-for-env (sort-nested-info-maps (jruby-protocol/get-plans jruby-service (:jruby-instance request) environment))] (all-plans-response! plan-info-for-env environment jruby-service) (environment-not-found environment))))) (schema/defn ^:always-validate plan-data->plan-details :- PlanDetails "Fills in a bare PlanData map by examining the files it refers to, returning PlanDetails." [plan-data :- PlanData env-name :- schema/Str module-name :- schema/Str plan-name :- schema/Str] (if (:error plan-data) (throw+ (:error plan-data)) {:metadata (or (:metadata plan-data) {}) :name (full-task-name module-name plan-name)})) (schema/defn ^:always-validate plan-details :- PlanDetails "Returns a PlanDetails map for the plan matching the given environment, module, and name. Will throw a JRuby RaiseException with (EnvironmentNotFound), (MissingModule), or (PlanNotFound) if any of those conditions occur." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) jruby-instance environment-name :- schema/Str module-name :- schema/Str plan-name :- schema/Str] (-> (jruby-protocol/get-plan-data jruby-service jruby-instance environment-name module-name plan-name) sort-nested-info-maps (plan-data->plan-details environment-name module-name plan-name))) (schema/defn ^:always-validate plan-details-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for detailed plan information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request) module (get-in request [:route-params :module-name]) plan (get-in request [:route-params :plan-name])] (try+ (->> (plan-details jruby-service (:jruby-instance request) environment module plan) (middleware-utils/json-response 200)) (catch is-plan-error? {:keys [kind msg details]} (middleware-utils/json-response 500 {:kind kind :msg msg :details details})) (catch RaiseException e (handle-plan-details-jruby-exception e environment module plan)))))) (defn info-service [request] (let [path-components (-> request :route-info :path) ;; path-components will be something like ;; ["/puppet" "/v3" "/environment_classes" ["*" :rest]] ;; and we want to map "/environment_classes" to a ;; cacheable info service resource-component (-> path-components butlast last)] (when resource-component (get {"environment_classes" :classes "environment_transports" :transports} (str/replace resource-component "/" ""))))) (schema/defn ^:always-validate wrap-with-cache-check :- IFn "Middleware function which validates whether or not the If-None-Match header on an incoming cacheable request matches the last Etag computed for the environment whose info is being requested. If the two match, the middleware function returns an HTTP 304 (Not Modified) Ring response. If the two do not match, the request is threaded through to the supplied handler function." [handler :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request) svc-key (info-service request) request-tag (if-none-match-from-request request)] (if (and request-tag (= request-tag (jruby-protocol/get-cached-info-tag jruby-service environment svc-key))) (not-modified-response request-tag) (handler request))))) (schema/defn ^:always-validate raw-transports->response-map [data :- List env :- schema/Str] (sort-nested-info-maps {:name env :transports data})) (schema/defn ^:always-validate maybe-update-cache! :- ringutils/RingResponse "Updates cached etag for a given info service if the etag is different than the etag requested. Note, the content version at the time of etag computation must be supplied, the jruby service will only update the cache if the current content version of the cache has not changed while the etag was being computed." [info :- {schema/Any schema/Any} env :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) svc-key :- (schema/maybe schema/Keyword) request-tag :- (schema/maybe String) content-version :- (schema/maybe schema/Int)] (let [body (json/encode info) tag (ks/utf8-string->sha256 body)] (jruby-protocol/set-cache-info-tag! jruby-service env svc-key tag content-version) (if (= tag request-tag) (not-modified-response tag) (-> (response-with-etag body tag) (rr/content-type "application/json"))))) (schema/defn ^:always-validate make-cacheable-handler :- IFn "Given a function to retrieve information from the jruby protocol (referred to as an info service), builds a handler that honors the environment cache." [info-fn :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) cache-enabled? :- schema/Bool] (fn [request] (let [env (jruby-request/get-environment-from-request request) service-id (info-service request) content-version (jruby-protocol/get-cached-content-version jruby-service env service-id)] (if-let [info (info-fn (:jruby-instance request) env)] (let [known-tag (if-none-match-from-request request)] (if cache-enabled? (maybe-update-cache! info env jruby-service service-id known-tag content-version) (middleware-utils/json-response 200 info))) (environment-not-found env))))) (schema/defn ^:always-validate create-cacheable-info-handler-with-middleware :- IFn "Creates a cacheable info handler and wraps it in appropriate middleware." [info-fn :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) cache-enabled :- schema/Bool] (-> (make-cacheable-handler info-fn jruby-service cache-enabled) (jruby-request/wrap-with-jruby-instance jruby-service) (wrap-with-cache-check jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate environment-module-handler :- IFn "Handler for processing an incoming environment_modules Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (environment-module-info-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) (jruby-request/wrap-with-environment-validation true) jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate all-tasks-handler :- IFn "Handler for processing an incoming all_tasks Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (all-tasks-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate task-details-handler :- IFn "Handler for processing an incoming /tasks/:module/:task-name Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn] (-> (task-details-fn jruby-service get-code-content-fn current-code-id-fn) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate all-plans-handler :- IFn "Handler for processing an incoming all_plans Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (all-plans-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate plan-details-handler :- IFn "Handler for processing an incoming /plans/:module/:plan-name Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (plan-details-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate valid-static-file-path? "Helper function to decide if a static_file_content path is valid. The access here is designed to mimic Puppet's file_content endpoint." [path :- schema/Str] ;; Here, keywords represent a single element in the path. Anything between two '/' counts. The second vector takes anything else that might be on the end of the path . ;; Below, this corresponds to '*/*/files/**' or '*/*/tasks/**' or '*/*/scripts/**' in a filesystem glob. (bidi/match-route [[#"[^/]+/" :module-name #"/(files|tasks|scripts|lib)/" [#".+" :rest]] :_] path)) (defn static-file-content-request-handler "Returns a function which is the main request handler for the /static_file_content endpoint, utilizing the provided implementation of `get-code-content`" [get-code-content] (fn [req] (let [environment (get-in req [:params "environment"]) code-id (get-in req [:params "code_id"]) file-path (get-in req [:params :rest])] (cond (some empty? [environment code-id file-path]) {:status 400 :headers {"Content-Type" "text/plain"} :body (i18n/tru "Error: A /static_file_content request requires an environment, a code-id, and a file-path")} (not (nil? (schema/check ps-common/Environment environment))) {:status 400 :headers {"Content-Type" "text/plain"} :body (ps-common/environment-validation-error-msg environment)} (not (nil? (schema/check ps-common/CodeId code-id))) {:status 400 :headers {"Content-Type" "text/plain"} :body (ps-common/code-id-validation-error-msg code-id)} (not (valid-static-file-path? file-path)) {:status 403 :headers {"Content-Type" "text/plain"} :body (i18n/tru "Request Denied: A /static_file_content request must be a file within the files, lib, scripts, or tasks directory of a module.")} :else {:status 200 :headers {"Content-Type" "application/octet-stream"} :body (get-code-content environment code-id file-path)})))) (defn valid-env-name? [string] (re-matches #"\w+" string)) (def CatalogRequestV4 {(schema/required-key "certname") schema/Str (schema/required-key "persistence") {(schema/required-key "facts") schema/Bool (schema/required-key "catalog") schema/Bool} (schema/required-key "environment") (schema/constrained schema/Str valid-env-name?) (schema/optional-key "trusted_facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/optional-key "facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/optional-key "job_id") schema/Str (schema/optional-key "transaction_uuid") schema/Str (schema/optional-key "options") {(schema/optional-key "capture_logs") schema/Bool (schema/optional-key "log_level") (schema/enum "debug" "info" "warning" "err") (schema/optional-key "prefer_requested_environment") schema/Bool}}) (def CompileRequest {(schema/required-key "certname") schema/Str (schema/required-key "code_ast") schema/Str (schema/required-key "trusted_facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/required-key "facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/required-key "variables") {(schema/required-key "values") (schema/either [{schema/Str schema/Any}] {schema/Str schema/Any})} ;; Both environment and versioned project are technically listed in the schema as ;; "optional" but we will check later that exactly one of them is set. (schema/optional-key "environment") schema/Str (schema/optional-key "versioned_project") schema/Str (schema/optional-key "target_variables") {(schema/required-key "values") {schema/Str schema/Any}} (schema/optional-key "job_id") schema/Str (schema/optional-key "transaction_uuid") schema/Str (schema/optional-key "options") {(schema/optional-key "capture_logs") schema/Bool (schema/optional-key "log_level") (schema/enum "debug" "info" "warning" "error") (schema/optional-key "compile_for_plan") schema/Bool}}) (defn validated-body [body schema] (let [parameters (try+ (json/decode body false) (catch JsonParseException e (throw+ {:kind :bad-request :msg (format "Error parsing JSON: %s" e)})))] (try+ (schema/validate schema parameters) (catch [:type :schema.core/error] {:keys [error]} (throw+ {:kind :bad-request :msg (format "Invalid input: %s" error)}))) parameters)) (schema/defn ^:always-validate v4-catalog-fn :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) current-code-id-fn :- IFn] (fn [request] (let [request-options (-> request :body slurp (validated-body CatalogRequestV4))] {:status 200 :headers {"Content-Type" "application/json"} :body (json/encode (jruby-protocol/compile-catalog jruby-service (:jruby-instance request) (assoc request-options "code_id" (current-code-id-fn (get request-options "environment")))))}))) (defn parse-project-compile-data "Parse data required to compile a catalog inside a project. Data required includes * Root path to project * modulepath * hiera config * project_name" [request-options versioned-project bolt-projects-dir] (let [project-root (file-serving/get-project-root bolt-projects-dir versioned-project) project-config (file-serving/read-bolt-project-config project-root)] (assoc request-options "project_root" project-root "modulepath" (map #(str project-root "/" %) (file-serving/get-project-modulepath project-config)) "hiera_config" (str project-root "/" (get project-config :hiera-config "hiera.yaml")) "project_name" (:name project-config)))) (schema/defn ^:always-validate compile-fn :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) current-code-id-fn :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (fn [request] (let [request-options (-> request :body slurp (validated-body CompileRequest)) versioned-project (get request-options "versioned_project") environment (get request-options "environment")] ;; Check to ensure environment/versioned_project are mutually exlusive and at least one of them is set . (cond (and versioned-project environment) {:status 400 :headers {"Content-Type" "text/plain"} :body (i18n/tru "A compile request cannot specify both `environment` and `versioned_project` parameters.")} (and (nil? versioned-project) (nil? environment)) {:status 400 :headers {"Content-Type" "text/plain"} :body (i18n/tru "A compile request must include an `environment` or `versioned_project` parameter.")} :else (let [compile-options (if versioned-project ;; we need to parse some data from the project config for project compiles (parse-project-compile-data request-options versioned-project bolt-projects-dir) ;; environment compiles only need to set the code ID (assoc request-options "code_id" (current-code-id-fn environment)))] {:status 200 :headers {"Content-Type" "application/json"} :body (json/encode (jruby-protocol/compile-ast jruby-service (:jruby-instance request) compile-options boltlib-path))}))))) (schema/defn ^:always-validate v4-catalog-handler :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn current-code-id-fn :- IFn] (-> (v4-catalog-fn jruby-service current-code-id-fn) (jruby-request/wrap-with-jruby-instance jruby-service) wrap-with-jruby-queue-limit jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate compile-handler :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn current-code-id-fn :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (-> (compile-fn jruby-service current-code-id-fn boltlib-path bolt-projects-dir) (jruby-request/wrap-with-jruby-instance jruby-service) wrap-with-jruby-queue-limit jruby-request/wrap-with-error-handling)) (def MetricIdsForStatus (schema/atom [[schema/Str]])) (schema/defn http-client-metrics-summary :- {:metrics-data [http-client-common/MetricIdMetricData] :sorted-metrics-data [http-client-common/MetricIdMetricData]} [metric-registry :- MetricRegistry metric-ids-to-select :- MetricIdsForStatus] (let [metrics-data (map #(http-client-metrics/get-client-metrics-data-by-metric-id metric-registry %) @metric-ids-to-select) flattened-data (flatten metrics-data)] {:metrics-data flattened-data :sorted-metrics-data (sort-by :aggregate > flattened-data)})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Routing (schema/defn ^:always-validate v3-ruby-routes :- bidi-schema/RoutePair "v3 route tree for the ruby side of the master service." [request-handler :- IFn bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (comidi/routes (comidi/GET ["/node/" [#".*" :rest]] request (request-handler request)) (comidi/GET ["/file_content/" [#".*" :rest]] request ;; Not strictly ruby routes anymore because of this (file-serving/file-content-handler bolt-builtin-content-dir bolt-projects-dir request-handler (ring/params-request request))) (comidi/GET ["/file_metadatas/" [#".*" :rest]] request (file-serving/file-metadatas-handler bolt-builtin-content-dir bolt-projects-dir request-handler (ring/params-request request))) (comidi/GET ["/file_metadata/" [#".*" :rest]] request (request-handler request)) (comidi/GET ["/file_bucket_file/" [#".*" :rest]] request (request-handler request)) (comidi/PUT ["/file_bucket_file/" [#".*" :rest]] request (request-handler request)) (comidi/HEAD ["/file_bucket_file/" [#".*" :rest]] request (request-handler request)) (comidi/GET ["/catalog/" [#".*" :rest]] request (request-handler (assoc request :include-code-id? true))) (comidi/POST ["/catalog/" [#".*" :rest]] request (request-handler (assoc request :include-code-id? true))) (comidi/PUT ["/facts/" [#".*" :rest]] request (request-handler request)) (comidi/PUT ["/report/" [#".*" :rest]] request (request-handler request)) (comidi/GET "/environments" request (request-handler request)))) (schema/defn ^:always-validate v3-clojure-routes :- bidi-schema/RoutePair "v3 route tree for the clojure side of the master service." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn cache-enabled :- schema/Bool wrap-with-jruby-queue-limit :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (let [class-handler (create-cacheable-info-handler-with-middleware (fn [jruby env] (some-> jruby-service (jruby-protocol/get-environment-class-info jruby env) (class-info-from-jruby->class-info-for-json env))) jruby-service cache-enabled) module-handler (environment-module-handler jruby-service) tasks-handler (all-tasks-handler jruby-service) plans-handler (all-plans-handler jruby-service) transport-handler (create-cacheable-info-handler-with-middleware (fn [jruby env] (some-> jruby-service (jruby-protocol/get-environment-transport-info jruby env) (raw-transports->response-map env))) jruby-service cache-enabled) task-handler (task-details-handler jruby-service get-code-content-fn current-code-id-fn) plan-handler (plan-details-handler jruby-service) static-content-handler (static-file-content-request-handler get-code-content-fn) compile-handler' (compile-handler jruby-service wrap-with-jruby-queue-limit current-code-id-fn boltlib-path bolt-projects-dir)] (comidi/routes (comidi/POST "/compile" request (compile-handler' request)) (comidi/GET ["/environment_classes" [#".*" :rest]] request (class-handler request)) (comidi/GET ["/environment_modules" [#".*" :rest]] request (module-handler request)) (comidi/GET ["/environment_transports" [#".*" :rest]] request (transport-handler request)) (comidi/GET ["/tasks/" :module-name "/" :task-name] request (task-handler request)) (comidi/GET ["/tasks"] request (tasks-handler request)) (comidi/GET ["/plans/" :module-name "/" :plan-name] request (plan-handler request)) (comidi/GET ["/plans"] request (plans-handler request)) (comidi/GET ["/static_file_content/" [#".*" :rest]] request (static-content-handler request))))) (schema/defn ^:always-validate v4-routes :- bidi-schema/RoutePair [clojure-request-wrapper :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn current-code-id-fn :- IFn] (let [v4-catalog-handler (v4-catalog-handler jruby-service wrap-with-jruby-queue-limit current-code-id-fn)] (comidi/context "/v4" (comidi/wrap-routes (comidi/routes (comidi/POST "/catalog" request (v4-catalog-handler request))) clojure-request-wrapper)))) (schema/defn ^:always-validate v3-routes :- bidi-schema/RoutePair "Creates the routes to handle the master's '/v3' routes, which includes '/environments' and the non-CA indirected routes. The CA-related endpoints are handled separately by the CA service." [ruby-request-handler :- IFn clojure-request-wrapper :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn environment-class-cache-enabled :- schema/Bool wrap-with-jruby-queue-limit :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (comidi/context "/v3" (v3-ruby-routes ruby-request-handler bolt-builtin-content-dir bolt-projects-dir) (comidi/wrap-routes (v3-clojure-routes jruby-service get-code-content-fn current-code-id-fn environment-class-cache-enabled wrap-with-jruby-queue-limit boltlib-path bolt-projects-dir) clojure-request-wrapper))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Lifecycle Helper Functions (defn meminfo-content "Read and return the contents of /proc/meminfo, if it exists. Otherwise return nil." [] (when (fs/exists? "/proc/meminfo") Due to OpenJDK Issue JDK-7132461 ; (-7132461), ; we have to open and slurp a FileInputStream object rather than ; slurping the file directly, since directly slurping the file causes a call to be made to ( ) . (with-open [mem-info-file (FileInputStream. "/proc/meminfo")] (slurp mem-info-file)))) the current max java heap size ( -Xmx ) in kB defined for with - redefs in tests (def max-heap-size (/ (.maxMemory (Runtime/getRuntime)) 1024)) (defn validate-memory-requirements! "On Linux Distributions, parses the /proc/meminfo file to determine the total amount of System RAM, and throws an exception if that is less than 1.1 times the maximum heap size of the JVM. This is done so that the JVM doesn't fail later due to an Out of Memory error." [] (when-let [meminfo-file-content (meminfo-content)] (let [heap-size max-heap-size mem-size (Integer. (second (re-find #"MemTotal:\s+(\d+)\s+\S+" meminfo-file-content))) required-mem-size (* heap-size 1.1)] (when (< mem-size required-mem-size) (throw (Error. (format "%s %s %s" (i18n/trs "Not enough available RAM ({0}MB) to safely accommodate the configured JVM heap size of {1}MB." (int (/ mem-size 1024.0)) (int (/ heap-size 1024.0))) (i18n/trs "Puppet Server requires at least {0}MB of available RAM given this heap size, computed as 1.1 * max heap (-Xmx)." (int (/ required-mem-size 1024.0))) (i18n/trs "Either increase available memory or decrease the configured heap size by reducing the -Xms and -Xmx values in JAVA_ARGS in /etc/sysconfig/puppetserver on EL systems or /etc/default/puppetserver on Debian systems.")))))))) (defn register-gauge! [registry hostname metric-name metric-fn] (.register registry (metrics/host-metric-name hostname metric-name) (proxy [Gauge] [] (getValue [] (metric-fn))))) (schema/defn register-jvm-metrics! [registry :- MetricRegistry hostname :- schema/Str] (register-gauge! registry hostname "uptime" (fn [] (.getUptime (ManagementFactory/getRuntimeMXBean)))) (let [memory-mbean (ManagementFactory/getMemoryMXBean) get-heap-memory (fn [] (.getHeapMemoryUsage memory-mbean)) get-non-heap-memory (fn [] (.getNonHeapMemoryUsage memory-mbean))] (register-gauge! registry hostname "memory.heap.committed" (fn [] (.getCommitted (get-heap-memory)))) (register-gauge! registry hostname "memory.heap.init" (fn [] (.getInit (get-heap-memory)))) (register-gauge! registry hostname "memory.heap.max" (fn [] (.getMax (get-heap-memory)))) (register-gauge! registry hostname "memory.heap.used" (fn [] (.getUsed (get-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.committed" (fn [] (.getCommitted (get-non-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.init" (fn [] (.getInit (get-non-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.max" (fn [] (.getMax (get-non-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.used" (fn [] (.getUsed (get-non-heap-memory)))) Unfortunately there is n't an mbean for " total " memory . Dropwizard metrics ' MetricUsageGaugeSet has " total " metrics that are computed by adding together Heap Memory and ;; Non Heap Memory. (register-gauge! registry hostname "memory.total.committed" (fn [] (+ (.getCommitted (get-heap-memory)) (.getCommitted (get-non-heap-memory))))) (register-gauge! registry hostname "memory.total.init" (fn [] (+ (.getInit (get-heap-memory)) (.getInit (get-non-heap-memory))))) (register-gauge! registry hostname "memory.total.max" (fn [] (+ (.getMax (get-heap-memory)) (.getMax (get-non-heap-memory))))) (register-gauge! registry hostname "memory.total.used" (fn [] (+ (.getUsed (get-heap-memory)) (.getUsed (get-non-heap-memory))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Public (schema/defn ^:always-validate root-routes :- bidi-schema/RoutePair "Creates all of the web routes for the master." [ruby-request-handler :- IFn clojure-request-wrapper :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn get-code-content-fn :- IFn current-code-id-fn :- IFn environment-class-cache-enabled :- schema/Bool boltlib-path :- (schema/maybe [schema/Str]) bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (comidi/routes (v3-routes ruby-request-handler clojure-request-wrapper jruby-service get-code-content-fn current-code-id-fn environment-class-cache-enabled wrap-with-jruby-queue-limit boltlib-path bolt-builtin-content-dir bolt-projects-dir) (v4-routes clojure-request-wrapper jruby-service wrap-with-jruby-queue-limit current-code-id-fn))) (schema/defn ^:always-validate wrap-middleware :- IFn [handler :- IFn authorization-fn :- IFn puppet-version :- schema/Str] (-> handler authorization-fn (middleware/wrap-uncaught-errors :plain) middleware/wrap-request-logging i18n/locale-negotiator middleware/wrap-response-logging (ringutils/wrap-with-puppet-version-header puppet-version))) (schema/defn ^:always-validate get-master-route-config "Get the webserver route configuration for the master service" [master-ns :- schema/Keyword config :- {schema/Keyword schema/Any}] (get-in config [:web-router-service master-ns])) (schema/defn ^:always-validate get-master-mount :- schema/Str "Get the webserver mount point that the master service is rooted under" [master-ns :- schema/Keyword config-route] (cond ;; if the route config is a map, we need to determine whether it's the ;; new-style multi-server config (where there will be a `:route` key and a ;; `:server`, key), or the old style where there is a single key that is ;; assumed to be our hard-coded route id (`:master-routes`). ;; It should be possible to delete this hack (perhaps this entire function) ;; when we remove support for legacy routes. (and (map? config-route) (or (contains? config-route :route) (contains? config-route :master-routes))) (or (:route config-route) (:master-routes config-route)) (string? config-route) config-route :else (throw (IllegalArgumentException. (i18n/trs "Route not found for service {0}" master-ns))))) (schema/defn ^:always-validate construct-root-routes :- bidi-schema/RoutePair "Creates a wrapped ruby request handler and a clojure request handler, then uses those to create all of the web routes for the master." [puppet-version :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content :- IFn current-code-id :- IFn handle-request :- IFn wrap-with-authorization-check :- IFn wrap-with-jruby-queue-limit :- IFn environment-class-cache-enabled :- schema/Bool boltlib-path :- (schema/maybe [schema/Str]) bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (let [ruby-request-handler (wrap-middleware handle-request wrap-with-authorization-check puppet-version) clojure-request-wrapper (fn [handler] (wrap-middleware (ring/wrap-params handler) wrap-with-authorization-check puppet-version))] (root-routes ruby-request-handler clojure-request-wrapper jruby-service wrap-with-jruby-queue-limit get-code-content current-code-id environment-class-cache-enabled boltlib-path bolt-builtin-content-dir bolt-projects-dir))) (def MasterStatusV1 {(schema/optional-key :experimental) {:http-metrics [http-metrics/RouteSummary] :http-client-metrics [http-client-common/MetricIdMetricData]}}) (def puppet-server-http-client-metrics-for-status [["puppet" "report" "http"] ["puppetdb" "command" "replace_catalog"] ["puppetdb" "command" "replace_facts"] ["puppetdb" "command" "store_report"] ["puppetdb" "facts" "find"] ["puppetdb" "facts" "search"] ["puppetdb" "query"] ["puppetdb" "resource" "search"]]) (schema/defn ^:always-validate add-metric-ids-to-http-client-metrics-list! [metric-id-atom :- MetricIdsForStatus metric-ids-to-add :- [[schema/Str]]] (swap! metric-id-atom concat metric-ids-to-add)) (schema/defn ^:always-validate v1-status :- status-core/StatusCallbackResponse [http-metrics :- http-metrics/HttpMetrics http-client-metric-ids-for-status :- MetricIdsForStatus metric-registry :- MetricRegistry level :- status-core/ServiceStatusDetailLevel] (let [level>= (partial status-core/compare-levels >= level)] {:state :running :status (cond-> ;; no status info at ':critical' level {} ;; no extra status at ':info' level yet (level>= :info) identity (level>= :debug) (-> (assoc-in [:experimental :http-metrics] (:sorted-routes (http-metrics/request-summary http-metrics))) (assoc-in [:experimental :http-client-metrics] (:sorted-metrics-data (http-client-metrics-summary metric-registry http-client-metric-ids-for-status)))))}))
null
https://raw.githubusercontent.com/puppetlabs/puppetserver/2d6ca01b4b72716ca543b606f752261b969e401b/src/clj/puppetlabs/services/master/master_core.clj
clojure
Constants Private SERVER-1153 - For a non-nil value, the characters '--gzip' will be stripped from the end of the value which is returned. The '--gzip' header for cases in which the corresponding response payload has been used at the time this code was written (9.2.10), however, did not have this logic to strip the "--gzip" characters from the incoming header. This function compensates for that by stripping the characters here - before other Puppet Server code would use it. When/if Puppet Server is upgraded to or newer, it may be safe to take out the line that removes the '--gzip' characters. we trust the file path from Puppet, so extract the relative path info from the file if code content can be retrieved, then use static_file_content path-components will be something like ["/puppet" "/v3" "/environment_classes" ["*" :rest]] and we want to map "/environment_classes" to a cacheable info service Here, keywords represent a single element in the path. Anything between two '/' counts. Below, this corresponds to '*/*/files/**' or '*/*/tasks/**' or '*/*/scripts/**' in a filesystem glob. Both environment and versioned project are technically listed in the schema as "optional" but we will check later that exactly one of them is set. Check to ensure environment/versioned_project are mutually exlusive and we need to parse some data from the project config for project compiles environment compiles only need to set the code ID Routing Not strictly ruby routes anymore because of this Lifecycle Helper Functions (-7132461), we have to open and slurp a FileInputStream object rather than slurping the file directly, since directly slurping the file Non Heap Memory. Public if the route config is a map, we need to determine whether it's the new-style multi-server config (where there will be a `:route` key and a `:server`, key), or the old style where there is a single key that is assumed to be our hard-coded route id (`:master-routes`). It should be possible to delete this hack (perhaps this entire function) when we remove support for legacy routes. no status info at ':critical' level no extra status at ':info' level yet
(ns puppetlabs.services.master.master-core (:require [bidi.bidi :as bidi] [bidi.schema :as bidi-schema] [cheshire.core :as json] [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [me.raynes.fs :as fs] [puppetlabs.comidi :as comidi] [puppetlabs.http.client.common :as http-client-common] [puppetlabs.http.client.metrics :as http-client-metrics] [puppetlabs.i18n.core :as i18n] [puppetlabs.kitchensink.core :as ks] [puppetlabs.metrics :as metrics] [puppetlabs.metrics.http :as http-metrics] [puppetlabs.puppetserver.common :as ps-common] [puppetlabs.puppetserver.jruby-request :as jruby-request] [puppetlabs.puppetserver.ringutils :as ringutils] [puppetlabs.ring-middleware.core :as middleware] [puppetlabs.ring-middleware.utils :as middleware-utils] [puppetlabs.services.master.file-serving :as file-serving] [puppetlabs.services.protocols.jruby-puppet :as jruby-protocol] [puppetlabs.trapperkeeper.services.status.status-core :as status-core] [ring.middleware.params :as ring] [ring.util.response :as rr] [schema.core :as schema] [slingshot.slingshot :refer [throw+ try+]]) (:import (clojure.lang IFn) (com.codahale.metrics Gauge MetricRegistry) (com.fasterxml.jackson.core JsonParseException) (java.io FileInputStream) (java.lang.management ManagementFactory) (java.util List Map Map$Entry) (org.jruby.exceptions RaiseException) (org.jruby RubySymbol))) (def puppet-API-version "v3") (def EnvironmentClassesFileClassParameter "Schema for an individual parameter found in a class defined within an environment_classes file. Includes the name of the parameter. Optionally, if available in the parameter definition, includes the type, source text for the parameter's default value, and a literal (primitive data type) representation of the parameter's default value. For example, if a class parameter were defined like this in a Puppet manifest ... Integer $someint = 3 ... then the map representation of that parameter would be: {:name \"someint\", :type \"Integer\", :default_source \"3\", :default_literal 3 } For a parameter default value which contains an expression - something that cannot be coerced into a primitive data type - the map representation omits the default_literal. For example, this parameter definition in a Puppet manifest ... String $osfam = \"$::osfamily\" ... would produce a map representation which looks like this ... {:name \"osfam\", :type \"String\", :default_source \"\"$::osfamily\"\", } The data types that could be used in the value for a :default_literal may vary over time, as the Puppet language continues to evolve. For this reason, the more permissive schema/Any is used here. General data types that we could see based on current types that the Puppet language allows today are in the table below: Puppet | :default_literal value ================================================ String | java.lang.String Boolean | java.lang.Boolean Float/Numeric | java.lang.Double Integer/Numeric | java.lang.Long Array | clojure.lang.LazySeq Hash | clojure.lang.PersistentTreeMap For the Regexp, Undef, Default, any Hash objects (top-level or nested within another Array or Hash) whose keys are not of type String, and any Array or Hash objects (top-level or nested within another Array or Hash) which contain a Regexp, Undef, or Default typed value, the :default_literal value will not be populated. These are not populated because they cannot be represented in JSON transfer without some loss of fidelity as compared to what the original data type from the manifest was." {:name schema/Str (schema/optional-key :type) schema/Str (schema/optional-key :default_source) schema/Str (schema/optional-key :default_literal) schema/Any}) (def EnvironmentClassesFileClass "Schema for an individual class found within an environment_classes file entry. Includes the name of the class and a vector of information about each parameter found in the class definition." {:name schema/Str :params [EnvironmentClassesFileClassParameter]}) (def EnvironmentClassesFileWithError "Schema for an environment_classes file that could not be parsed. Includes the path to the file and an error string containing details about the problem encountered during parsing." {:path schema/Str :error schema/Str}) (def EnvironmentClassesFileWithClasses "Schema for an environment_classes file that was successfully parsed. Includes the path to the file and a vector of information about each class found in the file." {:path schema/Str :classes [EnvironmentClassesFileClass]}) (def EnvironmentClassesFileEntry "Schema for an individual file entry which is part of the return payload for an environment_classes request." (schema/conditional #(contains? % :error) EnvironmentClassesFileWithError #(contains? % :classes) EnvironmentClassesFileWithClasses)) (def EnvironmentClassesInfo "Schema for the return payload an environment_classes request." {:name schema/Str :files [EnvironmentClassesFileEntry]}) (def EnvironmentModuleInfo "Schema for a given module that can be returned within the :modules key in EnvironmentModulesInfo." {:name schema/Str :version (schema/maybe schema/Str)}) (def EnvironmentModulesInfo "Schema for the return payload for an environment_classes request." {:name schema/Str :modules [EnvironmentModuleInfo]}) (def TaskData "Response from puppet's TaskInformationService for data on a single task, *after* it has been converted to a Clojure map." {:metadata (schema/maybe {schema/Keyword schema/Any}) :files [{:name schema/Str :path schema/Str}] (schema/optional-key :error) {:msg schema/Str :kind schema/Str :details {schema/Keyword schema/Any}}}) (def TaskDetails "A filled-in map of information about a task." {:metadata {schema/Keyword schema/Any} :name schema/Str :files [{:filename schema/Str :sha256 schema/Str :size_bytes schema/Int :uri {:path schema/Str :params {:environment schema/Str (schema/optional-key :code_id) schema/Str}}}]}) (def PlanData "Response from puppet's PlanInformationService for data on a single plan, *after* it has been converted to a Clojure map." {:metadata (schema/maybe {schema/Keyword schema/Any}) :files [{:name schema/Str :path schema/Str}] (schema/optional-key :error) {:msg schema/Str :kind schema/Str :details {schema/Keyword schema/Any}}}) (def PlanDetails "A filled-in map of information about a plan." {:metadata {schema/Keyword schema/Any} :name schema/Str}) (defn obj-or-ruby-symbol-as-string "If the supplied object is of type RubySymbol, returns a string representation of the RubySymbol. Otherwise, just returns the original object." [obj] (if (instance? RubySymbol obj) (.asJavaString obj) obj)) (defn obj->keyword "Attempt to convert the supplied object to a Clojure keyword. On failure to do so, throws an IllegalArgumentException." [obj] (if-let [obj-as-keyword (-> obj obj-or-ruby-symbol-as-string keyword)] obj-as-keyword (throw (IllegalArgumentException. (i18n/trs "Object cannot be coerced to a keyword: {0}" obj))))) (defn sort-nested-info-maps "For a data structure, recursively sort any nested maps and sets descending into map values, lists, vectors and set members as well. The result should be that all maps in the data structure become explicitly sorted with natural ordering. This can be used before serialization to ensure predictable serialization. The returned data structure is not a transient so it is still able to be modified, therefore caution should be taken to avoid modification else the data will lose its sorted status. This function was copypasta'd from clj-kitchensink's core/sort-nested-maps. sort-nested-maps can only deep sort a structure that contains native Clojure types, whereas this function includes a couple of changes which handle the sorting of the data structure returned from JRuby: 1) This function sorts keys within any `java.util.Map`, as opposed to just an object for which `map?` returns true. 2) This function attempts to coerces any keys found within a map to a Clojure keyword before using `sorted-map` to sort the keys. `sorted-map` would otherwise throw an error upon encountering a non-keyword type key." [data] (cond (instance? Map data) (into (sorted-map) (for [[k v] data] [(obj->keyword k) (sort-nested-info-maps v)])) (instance? Iterable data) (map sort-nested-info-maps data) :else data)) (schema/defn ^:always-validate if-none-match-from-request :- (schema/maybe String) "Retrieve the value of an 'If-None-Match' HTTP header from the supplied Ring request. If the header is not found, returns nil." [request :- {schema/Keyword schema/Any}] characters are added by the Jetty web server to an HTTP Etag response gzipped . Newer versions of Jetty , 9.3.x series , have logic in the GzipHandler to strip these characters back off of the If - None - Match header value before the Ring request would see it . The version of being a version of trapperkeeper - webserver - jetty9 which is based on Jetty 9.3.x (some-> (rr/get-header request "If-None-Match") (str/replace #"--gzip$" ""))) (schema/defn ^:always-validate add-path-to-file-entry :- Map "Convert the value for a manifest file entry into an appropriate map for use in serializing an environment_classes response to JSON." [file-detail :- Map file-name :- schema/Str] (.put file-detail "path" file-name) file-detail) (schema/defn ^:always-validate manifest-info-from-jruby->manifest-info-for-json :- EnvironmentClassesFileEntry "Convert the per-manifest file information received from the jruby service into an appropriate map for use in serializing an environment_classes response to JSON." [file-info :- Map$Entry] (-> file-info val (add-path-to-file-entry (key file-info)) sort-nested-info-maps)) (schema/defn ^:always-validate class-info-from-jruby->class-info-for-json :- EnvironmentClassesInfo "Convert a class info map received from the jruby service into an appropriate map for use in serializing an environment_classes response to JSON. The map that this function returns should be 'sorted' by key - both at the top-level and within any nested map - so that it will consistently serialize to the exact same content. For this reason, this function and the functions that this function calls use the `sorted-map` and `sort-nested-java-maps` helper functions when constructing / translating maps." [info-from-jruby :- Map environment :- schema/Str] (->> info-from-jruby (map manifest-info-from-jruby->manifest-info-for-json) (sort-by :path) (vec) (sorted-map :name environment :files))) (schema/defn ^:always-validate response-with-etag :- ringutils/RingResponse "Create a Ring response, including the supplied 'body' and an HTTP 'Etag' header set to the supplied 'etag' parameter." [body :- schema/Str etag :- schema/Str] (-> body (rr/response) (rr/header "Etag" etag))) (schema/defn ^:always-validate not-modified-response :- ringutils/RingResponse "Create an HTTP 304 (Not Modified) response, including an HTTP 'Etag' header set to the supplied 'etag' parameter." [etag] (-> "" (response-with-etag etag) (rr/status 304))) (schema/defn ^:always-validate all-tasks-response! :- ringutils/RingResponse "Process the info, returning a Ring response to be propagated back up to the caller of the endpoint. Returns environment as a list of objects for an eventual future in which tasks for all environments can be requested, and a given task will list all the environments it is found in." [info-from-jruby :- [{schema/Any schema/Any}] environment :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (let [format-task (fn [task-object] {:name (:name task-object) :private (get-in task-object [:metadata :private] false) :description (get-in task-object [:metadata :description] "") :environment [{:name environment :code_id nil}]})] (->> (map format-task info-from-jruby) (middleware-utils/json-response 200)))) (defn task-file-uri-components "The 'id' portion for a task implementation is a single component like 'foo.sh' and can never be nested in subdirectories. In that case we know the 'file' must be structured <environment>/<module root>/<module>/tasks/<filename>. Other task files are the path relative to the module root, in the form <module>/<mount>/<path> where <path> may have subdirectories. For those, we just slice that off the end of the file path and take the last component that remains as the module root." [file-id file] (if (str/includes? file-id "/") (let [[module mount subpath] (str/split file-id #"/" 3) module-root (fs/base-name (subs file 0 (str/last-index-of file file-id)))] [module-root module mount subpath]) (take-last 4 (str/split file #"/")))) (defn describe-task-file [get-code-content env-name code-id file-data] (let [file (:path file-data) file-id (:name file-data) size (fs/size file) sha256 (ks/file->sha256 (io/file file)) [module-root module-name mount relative-path] (task-file-uri-components file-id file) static-path (str/join "/" [module-root module-name mount relative-path]) uri (try (when (not= sha256 (ks/stream->sha256 (get-code-content env-name code-id static-path))) (throw (Exception. (i18n/trs "file did not match versioned file contents")))) {:path (str "/puppet/v3/static_file_content/" static-path) :params {:environment env-name :code_id code-id}} (catch Exception e (log/debug (i18n/trs "Static file unavailable for {0}: {1}" file e)) {:path (case mount "files" (format "/puppet/v3/file_content/modules/%s/%s" module-name relative-path) "lib" (format "/puppet/v3/file_content/plugins/%s" relative-path) "scripts" (format "/puppet/v3/file_content/scripts/%s/%s" module-name relative-path) "tasks" (format "/puppet/v3/file_content/tasks/%s/%s" module-name relative-path)) :params {:environment env-name}}))] {:filename file-id :sha256 sha256 :size_bytes size :uri uri})) (defn full-task-name "Construct a full task name from the two components. If the task's short name is 'init', then the second component is omitted so the task name is just the module's name." [module-name task-shortname] (if (= task-shortname "init") module-name (str module-name "::" task-shortname))) (schema/defn ^:always-validate task-data->task-details :- TaskDetails "Fills in a bare TaskData map by examining the files it refers to, returning TaskDetails." [task-data :- TaskData get-code-content :- IFn env-name :- schema/Str code-id :- (schema/maybe schema/Str) module-name :- schema/Str task-name :- schema/Str] (if (:error task-data) (throw+ (:error task-data)) {:metadata (or (:metadata task-data) {}) :name (full-task-name module-name task-name) :files (mapv (partial describe-task-file get-code-content env-name code-id) (:files task-data))})) (schema/defn environment-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when an environment is not found." [environment :- schema/Str] (rr/not-found (i18n/tru "Could not find environment ''{0}''" environment))) (schema/defn module-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when a module is not found." [module :- schema/Str] (rr/not-found (i18n/tru "Could not find module ''{0}''" module))) (schema/defn task-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when a task is not found." [task :- schema/Str] (rr/not-found (i18n/tru "Could not find task ''{0}''" task))) (schema/defn plan-not-found :- ringutils/RingResponse "Ring handler to provide a standard error when a plan is not found." [plan :- schema/Str] (rr/not-found (i18n/tru "Could not find plan ''{0}''" plan))) (schema/defn ^:always-validate module-info-from-jruby->module-info-for-json :- EnvironmentModulesInfo "Creates a new map with a top level key `name` that corresponds to the requested environment and a top level key `modules` which contains the module information obtained from JRuby." [info-from-jruby :- List environment :- schema/Str] (->> info-from-jruby sort-nested-info-maps vec (sorted-map :name environment :modules))) (schema/defn ^:always-validate environment-module-response! :- ringutils/RingResponse "Process the environment module information, returning a ring response to be propagated back up to the caller of the environment_modules endpoint." ([info-from-jruby :- Map] (let [all-info-as-json (map #(module-info-from-jruby->module-info-for-json (val %) (name (key %))) (sort-nested-info-maps info-from-jruby))] (middleware-utils/json-response 200 all-info-as-json))) ([info-from-jruby :- List environment :- schema/Str] (let [info-as-json (module-info-from-jruby->module-info-for-json info-from-jruby environment)] (middleware-utils/json-response 200 info-as-json)))) (schema/defn ^:always-validate environment-module-info-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for environment_modules information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (if-let [environment (jruby-request/get-environment-from-request request)] (if-let [module-info (jruby-protocol/get-environment-module-info jruby-service (:jruby-instance request) environment)] (environment-module-response! module-info environment) (rr/not-found (i18n/tru "Could not find environment ''{0}''" environment))) (let [module-info (jruby-protocol/get-all-environment-module-info jruby-service (:jruby-instance request))] (environment-module-response! module-info))))) (schema/defn ^:always-validate all-tasks-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for tasks information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request)] (if-let [task-info-for-env (sort-nested-info-maps (jruby-protocol/get-tasks jruby-service (:jruby-instance request) environment))] (all-tasks-response! task-info-for-env environment jruby-service) (environment-not-found environment))))) (schema/defn ^:always-validate task-details :- TaskDetails "Returns a TaskDetails map for the task matching the given environment, module, and name. Will throw a JRuby RaiseException with (EnvironmentNotFound), (MissingModule), or (TaskNotFound) if any of those conditions occur." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) jruby-instance code-content-fn :- IFn environment-name :- schema/Str code-id :- (schema/maybe schema/Str) module-name :- schema/Str task-name :- schema/Str] (-> (jruby-protocol/get-task-data jruby-service jruby-instance environment-name module-name task-name) sort-nested-info-maps (task-data->task-details code-content-fn environment-name code-id module-name task-name))) (schema/defn exception-matches? :- schema/Bool [^Exception e :- Exception pattern :- schema/Regex] (->> e .getMessage (re-find pattern) boolean)) (defn handle-task-details-jruby-exception "Given a JRuby RaiseException arising from a call to task-details, constructs a 4xx error response if appropriate, otherwise re-throws." [jruby-exception environment module task] (cond (exception-matches? jruby-exception #"^\(EnvironmentNotFound\)") (environment-not-found environment) (exception-matches? jruby-exception #"^\(MissingModule\)") (module-not-found module) (exception-matches? jruby-exception #"^\(TaskNotFound\)") (task-not-found task) :else (throw jruby-exception))) (defn is-task-error? [err] (and (map? err) (:kind err) (str/starts-with? (:kind err) "puppet.task"))) (defn handle-plan-details-jruby-exception "Given a JRuby RaiseException arising from a call to plan-details, constructs a 4xx error response if appropriate, otherwise re-throws." [jruby-exception environment module plan] (cond (exception-matches? jruby-exception #"^\(EnvironmentNotFound\)") (environment-not-found environment) (exception-matches? jruby-exception #"^\(MissingModule\)") (module-not-found module) (exception-matches? jruby-exception #"^\(PlanNotFound\)") (plan-not-found plan) :else (throw jruby-exception))) (defn is-plan-error? [err] (and (map? err) (:kind err) (str/starts-with? (:kind err) "puppet.plan"))) (schema/defn ^:always-validate task-details-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for detailed task information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn] (fn [request] (let [environment (jruby-request/get-environment-from-request request) module (get-in request [:route-params :module-name]) task (get-in request [:route-params :task-name])] (try+ (->> (task-details jruby-service (:jruby-instance request) get-code-content-fn environment (current-code-id-fn environment) module task) (middleware-utils/json-response 200)) (catch is-task-error? {:keys [kind msg details]} (middleware-utils/json-response 500 {:kind kind :msg msg :details details})) (catch RaiseException e (handle-task-details-jruby-exception e environment module task)))))) (schema/defn ^:always-validate all-plans-response! :- ringutils/RingResponse "Process the info, returning a Ring response to be propagated back up to the caller of the endpoint. Returns environment as a list of objects for an eventual future in which tasks for all environments can be requested, and a given task will list all the environments it is found in." [info-from-jruby :- [{schema/Any schema/Any}] environment :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (let [format-plan (fn [plan-object] {:name (:name plan-object) :environment [{:name environment :code_id nil}]})] (->> (map format-plan info-from-jruby) (middleware-utils/json-response 200)))) (schema/defn ^:always-validate all-plans-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for plans information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request)] (if-let [plan-info-for-env (sort-nested-info-maps (jruby-protocol/get-plans jruby-service (:jruby-instance request) environment))] (all-plans-response! plan-info-for-env environment jruby-service) (environment-not-found environment))))) (schema/defn ^:always-validate plan-data->plan-details :- PlanDetails "Fills in a bare PlanData map by examining the files it refers to, returning PlanDetails." [plan-data :- PlanData env-name :- schema/Str module-name :- schema/Str plan-name :- schema/Str] (if (:error plan-data) (throw+ (:error plan-data)) {:metadata (or (:metadata plan-data) {}) :name (full-task-name module-name plan-name)})) (schema/defn ^:always-validate plan-details :- PlanDetails "Returns a PlanDetails map for the plan matching the given environment, module, and name. Will throw a JRuby RaiseException with (EnvironmentNotFound), (MissingModule), or (PlanNotFound) if any of those conditions occur." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) jruby-instance environment-name :- schema/Str module-name :- schema/Str plan-name :- schema/Str] (-> (jruby-protocol/get-plan-data jruby-service jruby-instance environment-name module-name plan-name) sort-nested-info-maps (plan-data->plan-details environment-name module-name plan-name))) (schema/defn ^:always-validate plan-details-fn :- IFn "Middleware function for constructing a Ring response from an incoming request for detailed plan information." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request) module (get-in request [:route-params :module-name]) plan (get-in request [:route-params :plan-name])] (try+ (->> (plan-details jruby-service (:jruby-instance request) environment module plan) (middleware-utils/json-response 200)) (catch is-plan-error? {:keys [kind msg details]} (middleware-utils/json-response 500 {:kind kind :msg msg :details details})) (catch RaiseException e (handle-plan-details-jruby-exception e environment module plan)))))) (defn info-service [request] (let [path-components (-> request :route-info :path) resource-component (-> path-components butlast last)] (when resource-component (get {"environment_classes" :classes "environment_transports" :transports} (str/replace resource-component "/" ""))))) (schema/defn ^:always-validate wrap-with-cache-check :- IFn "Middleware function which validates whether or not the If-None-Match header on an incoming cacheable request matches the last Etag computed for the environment whose info is being requested. If the two match, the middleware function returns an HTTP 304 (Not Modified) Ring response. If the two do not match, the request is threaded through to the supplied handler function." [handler :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (fn [request] (let [environment (jruby-request/get-environment-from-request request) svc-key (info-service request) request-tag (if-none-match-from-request request)] (if (and request-tag (= request-tag (jruby-protocol/get-cached-info-tag jruby-service environment svc-key))) (not-modified-response request-tag) (handler request))))) (schema/defn ^:always-validate raw-transports->response-map [data :- List env :- schema/Str] (sort-nested-info-maps {:name env :transports data})) (schema/defn ^:always-validate maybe-update-cache! :- ringutils/RingResponse "Updates cached etag for a given info service if the etag is different than the etag requested. Note, the content version at the time of etag computation must be supplied, the jruby service will only update the cache if the current content version of the cache has not changed while the etag was being computed." [info :- {schema/Any schema/Any} env :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) svc-key :- (schema/maybe schema/Keyword) request-tag :- (schema/maybe String) content-version :- (schema/maybe schema/Int)] (let [body (json/encode info) tag (ks/utf8-string->sha256 body)] (jruby-protocol/set-cache-info-tag! jruby-service env svc-key tag content-version) (if (= tag request-tag) (not-modified-response tag) (-> (response-with-etag body tag) (rr/content-type "application/json"))))) (schema/defn ^:always-validate make-cacheable-handler :- IFn "Given a function to retrieve information from the jruby protocol (referred to as an info service), builds a handler that honors the environment cache." [info-fn :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) cache-enabled? :- schema/Bool] (fn [request] (let [env (jruby-request/get-environment-from-request request) service-id (info-service request) content-version (jruby-protocol/get-cached-content-version jruby-service env service-id)] (if-let [info (info-fn (:jruby-instance request) env)] (let [known-tag (if-none-match-from-request request)] (if cache-enabled? (maybe-update-cache! info env jruby-service service-id known-tag content-version) (middleware-utils/json-response 200 info))) (environment-not-found env))))) (schema/defn ^:always-validate create-cacheable-info-handler-with-middleware :- IFn "Creates a cacheable info handler and wraps it in appropriate middleware." [info-fn :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) cache-enabled :- schema/Bool] (-> (make-cacheable-handler info-fn jruby-service cache-enabled) (jruby-request/wrap-with-jruby-instance jruby-service) (wrap-with-cache-check jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate environment-module-handler :- IFn "Handler for processing an incoming environment_modules Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (environment-module-info-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) (jruby-request/wrap-with-environment-validation true) jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate all-tasks-handler :- IFn "Handler for processing an incoming all_tasks Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (all-tasks-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate task-details-handler :- IFn "Handler for processing an incoming /tasks/:module/:task-name Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn] (-> (task-details-fn jruby-service get-code-content-fn current-code-id-fn) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate all-plans-handler :- IFn "Handler for processing an incoming all_plans Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (all-plans-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate plan-details-handler :- IFn "Handler for processing an incoming /plans/:module/:plan-name Ring request" [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService)] (-> (plan-details-fn jruby-service) (jruby-request/wrap-with-jruby-instance jruby-service) jruby-request/wrap-with-environment-validation jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate valid-static-file-path? "Helper function to decide if a static_file_content path is valid. The access here is designed to mimic Puppet's file_content endpoint." [path :- schema/Str] The second vector takes anything else that might be on the end of the path . (bidi/match-route [[#"[^/]+/" :module-name #"/(files|tasks|scripts|lib)/" [#".+" :rest]] :_] path)) (defn static-file-content-request-handler "Returns a function which is the main request handler for the /static_file_content endpoint, utilizing the provided implementation of `get-code-content`" [get-code-content] (fn [req] (let [environment (get-in req [:params "environment"]) code-id (get-in req [:params "code_id"]) file-path (get-in req [:params :rest])] (cond (some empty? [environment code-id file-path]) {:status 400 :headers {"Content-Type" "text/plain"} :body (i18n/tru "Error: A /static_file_content request requires an environment, a code-id, and a file-path")} (not (nil? (schema/check ps-common/Environment environment))) {:status 400 :headers {"Content-Type" "text/plain"} :body (ps-common/environment-validation-error-msg environment)} (not (nil? (schema/check ps-common/CodeId code-id))) {:status 400 :headers {"Content-Type" "text/plain"} :body (ps-common/code-id-validation-error-msg code-id)} (not (valid-static-file-path? file-path)) {:status 403 :headers {"Content-Type" "text/plain"} :body (i18n/tru "Request Denied: A /static_file_content request must be a file within the files, lib, scripts, or tasks directory of a module.")} :else {:status 200 :headers {"Content-Type" "application/octet-stream"} :body (get-code-content environment code-id file-path)})))) (defn valid-env-name? [string] (re-matches #"\w+" string)) (def CatalogRequestV4 {(schema/required-key "certname") schema/Str (schema/required-key "persistence") {(schema/required-key "facts") schema/Bool (schema/required-key "catalog") schema/Bool} (schema/required-key "environment") (schema/constrained schema/Str valid-env-name?) (schema/optional-key "trusted_facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/optional-key "facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/optional-key "job_id") schema/Str (schema/optional-key "transaction_uuid") schema/Str (schema/optional-key "options") {(schema/optional-key "capture_logs") schema/Bool (schema/optional-key "log_level") (schema/enum "debug" "info" "warning" "err") (schema/optional-key "prefer_requested_environment") schema/Bool}}) (def CompileRequest {(schema/required-key "certname") schema/Str (schema/required-key "code_ast") schema/Str (schema/required-key "trusted_facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/required-key "facts") {(schema/required-key "values") {schema/Str schema/Any}} (schema/required-key "variables") {(schema/required-key "values") (schema/either [{schema/Str schema/Any}] {schema/Str schema/Any})} (schema/optional-key "environment") schema/Str (schema/optional-key "versioned_project") schema/Str (schema/optional-key "target_variables") {(schema/required-key "values") {schema/Str schema/Any}} (schema/optional-key "job_id") schema/Str (schema/optional-key "transaction_uuid") schema/Str (schema/optional-key "options") {(schema/optional-key "capture_logs") schema/Bool (schema/optional-key "log_level") (schema/enum "debug" "info" "warning" "error") (schema/optional-key "compile_for_plan") schema/Bool}}) (defn validated-body [body schema] (let [parameters (try+ (json/decode body false) (catch JsonParseException e (throw+ {:kind :bad-request :msg (format "Error parsing JSON: %s" e)})))] (try+ (schema/validate schema parameters) (catch [:type :schema.core/error] {:keys [error]} (throw+ {:kind :bad-request :msg (format "Invalid input: %s" error)}))) parameters)) (schema/defn ^:always-validate v4-catalog-fn :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) current-code-id-fn :- IFn] (fn [request] (let [request-options (-> request :body slurp (validated-body CatalogRequestV4))] {:status 200 :headers {"Content-Type" "application/json"} :body (json/encode (jruby-protocol/compile-catalog jruby-service (:jruby-instance request) (assoc request-options "code_id" (current-code-id-fn (get request-options "environment")))))}))) (defn parse-project-compile-data "Parse data required to compile a catalog inside a project. Data required includes * Root path to project * modulepath * hiera config * project_name" [request-options versioned-project bolt-projects-dir] (let [project-root (file-serving/get-project-root bolt-projects-dir versioned-project) project-config (file-serving/read-bolt-project-config project-root)] (assoc request-options "project_root" project-root "modulepath" (map #(str project-root "/" %) (file-serving/get-project-modulepath project-config)) "hiera_config" (str project-root "/" (get project-config :hiera-config "hiera.yaml")) "project_name" (:name project-config)))) (schema/defn ^:always-validate compile-fn :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) current-code-id-fn :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (fn [request] (let [request-options (-> request :body slurp (validated-body CompileRequest)) versioned-project (get request-options "versioned_project") environment (get request-options "environment")] at least one of them is set . (cond (and versioned-project environment) {:status 400 :headers {"Content-Type" "text/plain"} :body (i18n/tru "A compile request cannot specify both `environment` and `versioned_project` parameters.")} (and (nil? versioned-project) (nil? environment)) {:status 400 :headers {"Content-Type" "text/plain"} :body (i18n/tru "A compile request must include an `environment` or `versioned_project` parameter.")} :else (let [compile-options (if versioned-project (parse-project-compile-data request-options versioned-project bolt-projects-dir) (assoc request-options "code_id" (current-code-id-fn environment)))] {:status 200 :headers {"Content-Type" "application/json"} :body (json/encode (jruby-protocol/compile-ast jruby-service (:jruby-instance request) compile-options boltlib-path))}))))) (schema/defn ^:always-validate v4-catalog-handler :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn current-code-id-fn :- IFn] (-> (v4-catalog-fn jruby-service current-code-id-fn) (jruby-request/wrap-with-jruby-instance jruby-service) wrap-with-jruby-queue-limit jruby-request/wrap-with-error-handling)) (schema/defn ^:always-validate compile-handler :- IFn [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn current-code-id-fn :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (-> (compile-fn jruby-service current-code-id-fn boltlib-path bolt-projects-dir) (jruby-request/wrap-with-jruby-instance jruby-service) wrap-with-jruby-queue-limit jruby-request/wrap-with-error-handling)) (def MetricIdsForStatus (schema/atom [[schema/Str]])) (schema/defn http-client-metrics-summary :- {:metrics-data [http-client-common/MetricIdMetricData] :sorted-metrics-data [http-client-common/MetricIdMetricData]} [metric-registry :- MetricRegistry metric-ids-to-select :- MetricIdsForStatus] (let [metrics-data (map #(http-client-metrics/get-client-metrics-data-by-metric-id metric-registry %) @metric-ids-to-select) flattened-data (flatten metrics-data)] {:metrics-data flattened-data :sorted-metrics-data (sort-by :aggregate > flattened-data)})) (schema/defn ^:always-validate v3-ruby-routes :- bidi-schema/RoutePair "v3 route tree for the ruby side of the master service." [request-handler :- IFn bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (comidi/routes (comidi/GET ["/node/" [#".*" :rest]] request (request-handler request)) (comidi/GET ["/file_content/" [#".*" :rest]] request (file-serving/file-content-handler bolt-builtin-content-dir bolt-projects-dir request-handler (ring/params-request request))) (comidi/GET ["/file_metadatas/" [#".*" :rest]] request (file-serving/file-metadatas-handler bolt-builtin-content-dir bolt-projects-dir request-handler (ring/params-request request))) (comidi/GET ["/file_metadata/" [#".*" :rest]] request (request-handler request)) (comidi/GET ["/file_bucket_file/" [#".*" :rest]] request (request-handler request)) (comidi/PUT ["/file_bucket_file/" [#".*" :rest]] request (request-handler request)) (comidi/HEAD ["/file_bucket_file/" [#".*" :rest]] request (request-handler request)) (comidi/GET ["/catalog/" [#".*" :rest]] request (request-handler (assoc request :include-code-id? true))) (comidi/POST ["/catalog/" [#".*" :rest]] request (request-handler (assoc request :include-code-id? true))) (comidi/PUT ["/facts/" [#".*" :rest]] request (request-handler request)) (comidi/PUT ["/report/" [#".*" :rest]] request (request-handler request)) (comidi/GET "/environments" request (request-handler request)))) (schema/defn ^:always-validate v3-clojure-routes :- bidi-schema/RoutePair "v3 route tree for the clojure side of the master service." [jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn cache-enabled :- schema/Bool wrap-with-jruby-queue-limit :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (let [class-handler (create-cacheable-info-handler-with-middleware (fn [jruby env] (some-> jruby-service (jruby-protocol/get-environment-class-info jruby env) (class-info-from-jruby->class-info-for-json env))) jruby-service cache-enabled) module-handler (environment-module-handler jruby-service) tasks-handler (all-tasks-handler jruby-service) plans-handler (all-plans-handler jruby-service) transport-handler (create-cacheable-info-handler-with-middleware (fn [jruby env] (some-> jruby-service (jruby-protocol/get-environment-transport-info jruby env) (raw-transports->response-map env))) jruby-service cache-enabled) task-handler (task-details-handler jruby-service get-code-content-fn current-code-id-fn) plan-handler (plan-details-handler jruby-service) static-content-handler (static-file-content-request-handler get-code-content-fn) compile-handler' (compile-handler jruby-service wrap-with-jruby-queue-limit current-code-id-fn boltlib-path bolt-projects-dir)] (comidi/routes (comidi/POST "/compile" request (compile-handler' request)) (comidi/GET ["/environment_classes" [#".*" :rest]] request (class-handler request)) (comidi/GET ["/environment_modules" [#".*" :rest]] request (module-handler request)) (comidi/GET ["/environment_transports" [#".*" :rest]] request (transport-handler request)) (comidi/GET ["/tasks/" :module-name "/" :task-name] request (task-handler request)) (comidi/GET ["/tasks"] request (tasks-handler request)) (comidi/GET ["/plans/" :module-name "/" :plan-name] request (plan-handler request)) (comidi/GET ["/plans"] request (plans-handler request)) (comidi/GET ["/static_file_content/" [#".*" :rest]] request (static-content-handler request))))) (schema/defn ^:always-validate v4-routes :- bidi-schema/RoutePair [clojure-request-wrapper :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn current-code-id-fn :- IFn] (let [v4-catalog-handler (v4-catalog-handler jruby-service wrap-with-jruby-queue-limit current-code-id-fn)] (comidi/context "/v4" (comidi/wrap-routes (comidi/routes (comidi/POST "/catalog" request (v4-catalog-handler request))) clojure-request-wrapper)))) (schema/defn ^:always-validate v3-routes :- bidi-schema/RoutePair "Creates the routes to handle the master's '/v3' routes, which includes '/environments' and the non-CA indirected routes. The CA-related endpoints are handled separately by the CA service." [ruby-request-handler :- IFn clojure-request-wrapper :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content-fn :- IFn current-code-id-fn :- IFn environment-class-cache-enabled :- schema/Bool wrap-with-jruby-queue-limit :- IFn boltlib-path :- (schema/maybe [schema/Str]) bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (comidi/context "/v3" (v3-ruby-routes ruby-request-handler bolt-builtin-content-dir bolt-projects-dir) (comidi/wrap-routes (v3-clojure-routes jruby-service get-code-content-fn current-code-id-fn environment-class-cache-enabled wrap-with-jruby-queue-limit boltlib-path bolt-projects-dir) clojure-request-wrapper))) (defn meminfo-content "Read and return the contents of /proc/meminfo, if it exists. Otherwise return nil." [] (when (fs/exists? "/proc/meminfo") Due to OpenJDK Issue JDK-7132461 causes a call to be made to ( ) . (with-open [mem-info-file (FileInputStream. "/proc/meminfo")] (slurp mem-info-file)))) the current max java heap size ( -Xmx ) in kB defined for with - redefs in tests (def max-heap-size (/ (.maxMemory (Runtime/getRuntime)) 1024)) (defn validate-memory-requirements! "On Linux Distributions, parses the /proc/meminfo file to determine the total amount of System RAM, and throws an exception if that is less than 1.1 times the maximum heap size of the JVM. This is done so that the JVM doesn't fail later due to an Out of Memory error." [] (when-let [meminfo-file-content (meminfo-content)] (let [heap-size max-heap-size mem-size (Integer. (second (re-find #"MemTotal:\s+(\d+)\s+\S+" meminfo-file-content))) required-mem-size (* heap-size 1.1)] (when (< mem-size required-mem-size) (throw (Error. (format "%s %s %s" (i18n/trs "Not enough available RAM ({0}MB) to safely accommodate the configured JVM heap size of {1}MB." (int (/ mem-size 1024.0)) (int (/ heap-size 1024.0))) (i18n/trs "Puppet Server requires at least {0}MB of available RAM given this heap size, computed as 1.1 * max heap (-Xmx)." (int (/ required-mem-size 1024.0))) (i18n/trs "Either increase available memory or decrease the configured heap size by reducing the -Xms and -Xmx values in JAVA_ARGS in /etc/sysconfig/puppetserver on EL systems or /etc/default/puppetserver on Debian systems.")))))))) (defn register-gauge! [registry hostname metric-name metric-fn] (.register registry (metrics/host-metric-name hostname metric-name) (proxy [Gauge] [] (getValue [] (metric-fn))))) (schema/defn register-jvm-metrics! [registry :- MetricRegistry hostname :- schema/Str] (register-gauge! registry hostname "uptime" (fn [] (.getUptime (ManagementFactory/getRuntimeMXBean)))) (let [memory-mbean (ManagementFactory/getMemoryMXBean) get-heap-memory (fn [] (.getHeapMemoryUsage memory-mbean)) get-non-heap-memory (fn [] (.getNonHeapMemoryUsage memory-mbean))] (register-gauge! registry hostname "memory.heap.committed" (fn [] (.getCommitted (get-heap-memory)))) (register-gauge! registry hostname "memory.heap.init" (fn [] (.getInit (get-heap-memory)))) (register-gauge! registry hostname "memory.heap.max" (fn [] (.getMax (get-heap-memory)))) (register-gauge! registry hostname "memory.heap.used" (fn [] (.getUsed (get-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.committed" (fn [] (.getCommitted (get-non-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.init" (fn [] (.getInit (get-non-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.max" (fn [] (.getMax (get-non-heap-memory)))) (register-gauge! registry hostname "memory.non-heap.used" (fn [] (.getUsed (get-non-heap-memory)))) Unfortunately there is n't an mbean for " total " memory . Dropwizard metrics ' MetricUsageGaugeSet has " total " metrics that are computed by adding together Heap Memory and (register-gauge! registry hostname "memory.total.committed" (fn [] (+ (.getCommitted (get-heap-memory)) (.getCommitted (get-non-heap-memory))))) (register-gauge! registry hostname "memory.total.init" (fn [] (+ (.getInit (get-heap-memory)) (.getInit (get-non-heap-memory))))) (register-gauge! registry hostname "memory.total.max" (fn [] (+ (.getMax (get-heap-memory)) (.getMax (get-non-heap-memory))))) (register-gauge! registry hostname "memory.total.used" (fn [] (+ (.getUsed (get-heap-memory)) (.getUsed (get-non-heap-memory))))))) (schema/defn ^:always-validate root-routes :- bidi-schema/RoutePair "Creates all of the web routes for the master." [ruby-request-handler :- IFn clojure-request-wrapper :- IFn jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) wrap-with-jruby-queue-limit :- IFn get-code-content-fn :- IFn current-code-id-fn :- IFn environment-class-cache-enabled :- schema/Bool boltlib-path :- (schema/maybe [schema/Str]) bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (comidi/routes (v3-routes ruby-request-handler clojure-request-wrapper jruby-service get-code-content-fn current-code-id-fn environment-class-cache-enabled wrap-with-jruby-queue-limit boltlib-path bolt-builtin-content-dir bolt-projects-dir) (v4-routes clojure-request-wrapper jruby-service wrap-with-jruby-queue-limit current-code-id-fn))) (schema/defn ^:always-validate wrap-middleware :- IFn [handler :- IFn authorization-fn :- IFn puppet-version :- schema/Str] (-> handler authorization-fn (middleware/wrap-uncaught-errors :plain) middleware/wrap-request-logging i18n/locale-negotiator middleware/wrap-response-logging (ringutils/wrap-with-puppet-version-header puppet-version))) (schema/defn ^:always-validate get-master-route-config "Get the webserver route configuration for the master service" [master-ns :- schema/Keyword config :- {schema/Keyword schema/Any}] (get-in config [:web-router-service master-ns])) (schema/defn ^:always-validate get-master-mount :- schema/Str "Get the webserver mount point that the master service is rooted under" [master-ns :- schema/Keyword config-route] (cond (and (map? config-route) (or (contains? config-route :route) (contains? config-route :master-routes))) (or (:route config-route) (:master-routes config-route)) (string? config-route) config-route :else (throw (IllegalArgumentException. (i18n/trs "Route not found for service {0}" master-ns))))) (schema/defn ^:always-validate construct-root-routes :- bidi-schema/RoutePair "Creates a wrapped ruby request handler and a clojure request handler, then uses those to create all of the web routes for the master." [puppet-version :- schema/Str jruby-service :- (schema/protocol jruby-protocol/JRubyPuppetService) get-code-content :- IFn current-code-id :- IFn handle-request :- IFn wrap-with-authorization-check :- IFn wrap-with-jruby-queue-limit :- IFn environment-class-cache-enabled :- schema/Bool boltlib-path :- (schema/maybe [schema/Str]) bolt-builtin-content-dir :- (schema/maybe [schema/Str]) bolt-projects-dir :- (schema/maybe schema/Str)] (let [ruby-request-handler (wrap-middleware handle-request wrap-with-authorization-check puppet-version) clojure-request-wrapper (fn [handler] (wrap-middleware (ring/wrap-params handler) wrap-with-authorization-check puppet-version))] (root-routes ruby-request-handler clojure-request-wrapper jruby-service wrap-with-jruby-queue-limit get-code-content current-code-id environment-class-cache-enabled boltlib-path bolt-builtin-content-dir bolt-projects-dir))) (def MasterStatusV1 {(schema/optional-key :experimental) {:http-metrics [http-metrics/RouteSummary] :http-client-metrics [http-client-common/MetricIdMetricData]}}) (def puppet-server-http-client-metrics-for-status [["puppet" "report" "http"] ["puppetdb" "command" "replace_catalog"] ["puppetdb" "command" "replace_facts"] ["puppetdb" "command" "store_report"] ["puppetdb" "facts" "find"] ["puppetdb" "facts" "search"] ["puppetdb" "query"] ["puppetdb" "resource" "search"]]) (schema/defn ^:always-validate add-metric-ids-to-http-client-metrics-list! [metric-id-atom :- MetricIdsForStatus metric-ids-to-add :- [[schema/Str]]] (swap! metric-id-atom concat metric-ids-to-add)) (schema/defn ^:always-validate v1-status :- status-core/StatusCallbackResponse [http-metrics :- http-metrics/HttpMetrics http-client-metric-ids-for-status :- MetricIdsForStatus metric-registry :- MetricRegistry level :- status-core/ServiceStatusDetailLevel] (let [level>= (partial status-core/compare-levels >= level)] {:state :running :status (cond-> {} (level>= :info) identity (level>= :debug) (-> (assoc-in [:experimental :http-metrics] (:sorted-routes (http-metrics/request-summary http-metrics))) (assoc-in [:experimental :http-client-metrics] (:sorted-metrics-data (http-client-metrics-summary metric-registry http-client-metric-ids-for-status)))))}))
38ce2af9891d92fce6d7715fb76c166d4addcbebc1fa649f2c898e4dafbd0b69
patricoferris/ocaml-multicore-monorepo
test_entropy_collection.ml
open Lwt.Infix module Printing_rng = struct type g = unit let block = 16 let create ?time:_ () = () let generate ~g:_ _n = assert false let reseed ~g:_ data = Format.printf "reseeding: %a@.%!" Cstruct.hexdump_pp data let accumulate ~g:_ source = let print data = Format.printf "accumulate: (src: %a) %a@.%!" Mirage_crypto_rng.Entropy.pp_source source Cstruct.hexdump_pp data in `Acc print let seeded ~g:_ = true let pools = 1 end module E = Mirage_crypto_rng_mirage.Make(Time)(Mclock) let with_entropy act = E.initialize (module Printing_rng) >>= fun () -> Format.printf "entropy sources: %a@,%!" (fun ppf -> List.iter (fun x -> Mirage_crypto_rng.Entropy.pp_source ppf x; Format.pp_print_space ppf ())) (Mirage_crypto_rng.Entropy.sources ()); act () let () = OS.(Main.run (with_entropy (fun () -> Time.sleep_ns (Duration.of_sec 3))))
null
https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/mirage-crypto/tests/test_entropy_collection.ml
ocaml
open Lwt.Infix module Printing_rng = struct type g = unit let block = 16 let create ?time:_ () = () let generate ~g:_ _n = assert false let reseed ~g:_ data = Format.printf "reseeding: %a@.%!" Cstruct.hexdump_pp data let accumulate ~g:_ source = let print data = Format.printf "accumulate: (src: %a) %a@.%!" Mirage_crypto_rng.Entropy.pp_source source Cstruct.hexdump_pp data in `Acc print let seeded ~g:_ = true let pools = 1 end module E = Mirage_crypto_rng_mirage.Make(Time)(Mclock) let with_entropy act = E.initialize (module Printing_rng) >>= fun () -> Format.printf "entropy sources: %a@,%!" (fun ppf -> List.iter (fun x -> Mirage_crypto_rng.Entropy.pp_source ppf x; Format.pp_print_space ppf ())) (Mirage_crypto_rng.Entropy.sources ()); act () let () = OS.(Main.run (with_entropy (fun () -> Time.sleep_ns (Duration.of_sec 3))))
0b25988a6ee91b29f76703709b27f2802dee6fde6bcf8e6e30a9ad2c4a76421b
coq/coq
pretype_errors.ml
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) open Names open Environ open EConstr open Type_errors type unification_error = | OccurCheck of Evar.t * constr Constr is a variable not in scope | NotSameArgSize | NotSameHead | NoCanonicalStructure | ConversionFailed of env * constr * constr (* Non convertible closed terms *) | IncompatibleInstances of env * existential * constr * constr | MetaOccurInBody of Evar.t | InstanceNotSameType of Evar.t * env * types * types | InstanceNotFunctionalType of Evar.t * env * constr * types | UnifUnivInconsistency of UGraph.univ_inconsistency | CannotSolveConstraint of Evd.evar_constraint * unification_error | ProblemBeyondCapabilities type position = (Id.t * Locus.hyp_location_flag) option type position_reporting = (position * int) * constr type subterm_unification_error = bool * position_reporting * position_reporting * (constr * constr * unification_error) option type type_error = (constr, types) ptype_error type pretype_error = (* Old Case *) | CantFindCaseType of constr (* Type inference unification *) | ActualTypeNotCoercible of unsafe_judgment * types * unification_error (* Tactic unification *) | UnifOccurCheck of Evar.t * constr | UnsolvableImplicit of Evar.t * Evd.unsolvability_explanation option | CannotUnify of constr * constr * unification_error option | CannotUnifyLocal of constr * constr * constr | CannotUnifyBindingType of constr * constr | CannotGeneralize of constr | NoOccurrenceFound of constr * Id.t option | CannotFindWellTypedAbstraction of constr * constr list * (env * pretype_error) option | WrongAbstractionType of Name.t * constr * types * types | AbstractionOverMeta of Name.t * Name.t | NonLinearUnification of Name.t * constr (* Pretyping *) | VarNotFound of Id.t | EvarNotFound of Id.t | UnexpectedType of constr * constr * unification_error | NotProduct of constr | TypingError of type_error | CannotUnifyOccurrences of subterm_unification_error | UnsatisfiableConstraints of (Evar.t * Evar_kinds.t) option * Evar.Set.t | DisallowedSProp exception PretypeError of env * Evd.evar_map * pretype_error let precatchable_exception = function | CErrors.UserError _ | TypeError _ | PretypeError _ | Nametab.GlobalizationError _ -> true | _ -> false let raise_pretype_error ?loc ?info (env,sigma,te) = let info = Option.default Exninfo.null info in let info = Option.cata (Loc.add_loc info) info loc in Exninfo.iraise (PretypeError(env,sigma,te),info) let raise_type_error ?loc (env,sigma,te) = Loc.raise ?loc (PretypeError(env,sigma,TypingError te)) let error_actual_type ?loc ?info env sigma {uj_val=c;uj_type=actty} expty reason = let j = {uj_val=c;uj_type=actty} in raise_pretype_error ?loc ?info (env, sigma, ActualTypeNotCoercible (j, expty, reason)) let error_actual_type_core ?loc env sigma {uj_val=c;uj_type=actty} expty = let j = {uj_val=c;uj_type=actty} in raise_type_error ?loc (env, sigma, ActualType (j, expty)) let error_cant_apply_not_functional ?loc env sigma rator randl = raise_type_error ?loc (env, sigma, CantApplyNonFunctional (rator, randl)) let error_cant_apply_bad_type ?loc env sigma (n,c,t) rator randl = raise_type_error ?loc (env, sigma, CantApplyBadType ((n,c,t), rator, randl)) let error_ill_formed_branch ?loc env sigma c i actty expty = raise_type_error ?loc (env, sigma, IllFormedBranch (c, i, actty, expty)) let error_number_branches ?loc env sigma cj expn = raise_type_error ?loc (env, sigma, NumberBranches (cj, expn)) let error_case_not_inductive ?loc env sigma cj = raise_type_error ?loc (env, sigma, CaseNotInductive cj) let error_ill_typed_rec_body ?loc env sigma i na jl tys = raise_type_error ?loc (env, sigma, IllTypedRecBody (i, na, jl, tys)) let error_elim_arity ?loc env sigma pi c a = raise_type_error ?loc (env, sigma, ElimArity (pi, c, a)) let error_not_a_type ?loc env sigma j = raise_type_error ?loc (env, sigma, NotAType j) let error_assumption ?loc env sigma j = raise_type_error ?loc (env, sigma, BadAssumption j) (*s Implicit arguments synthesis errors. It is hard to find a precise location. *) let error_occur_check env sigma ev c = raise (PretypeError (env, sigma, UnifOccurCheck (ev,c))) let error_unsolvable_implicit ?loc env sigma evk explain = Loc.raise ?loc (PretypeError (env, sigma, UnsolvableImplicit (evk, explain))) let error_cannot_unify ?loc env sigma ?reason (m,n) = Loc.raise ?loc (PretypeError (env, sigma,CannotUnify (m,n,reason))) let error_cannot_unify_local env sigma (m,n,sn) = raise (PretypeError (env, sigma,CannotUnifyLocal (m,n,sn))) let error_cannot_coerce env sigma (m,n) = raise (PretypeError (env, sigma,CannotUnify (m,n,None))) let error_cannot_find_well_typed_abstraction env sigma p l e = raise (PretypeError (env, sigma,CannotFindWellTypedAbstraction (p,l,e))) let error_wrong_abstraction_type env sigma na a p l = raise (PretypeError (env, sigma,WrongAbstractionType (na,a,p,l))) let error_abstraction_over_meta env sigma hdmeta metaarg = let m = Evd.meta_name sigma hdmeta and n = Evd.meta_name sigma metaarg in raise (PretypeError (env, sigma,AbstractionOverMeta (m,n))) let error_non_linear_unification env sigma hdmeta t = let m = Evd.meta_name sigma hdmeta in raise (PretypeError (env, sigma,NonLinearUnification (m,t))) (*s Ml Case errors *) let error_cant_find_case_type ?loc env sigma expr = raise_pretype_error ?loc (env, sigma, CantFindCaseType expr) (*s Pretyping errors *) let error_unexpected_type ?loc env sigma actty expty e = raise_pretype_error ?loc (env, sigma, UnexpectedType (actty, expty, e)) let error_not_product ?loc env sigma c = raise_pretype_error ?loc (env, sigma, NotProduct c) s Error in conversion from AST to glob_constr let error_var_not_found ?loc env sigma s = raise_pretype_error ?loc (env, sigma, VarNotFound s) let error_evar_not_found ?loc env sigma id = raise_pretype_error ?loc (env, sigma, EvarNotFound id) let error_disallowed_sprop env sigma = raise (PretypeError (env, sigma, DisallowedSProp)) s errors let unsatisfiable_constraints env evd ev comp = match ev with | None -> let err = UnsatisfiableConstraints (None, comp) in raise (PretypeError (env,evd,err)) | Some ev -> let loc, kind = Evd.evar_source (Evd.find_undefined evd ev) in let err = UnsatisfiableConstraints (Some (ev, kind), comp) in Loc.raise ?loc (PretypeError (env,evd,err)) let unsatisfiable_exception exn = match exn with | PretypeError (_, _, UnsatisfiableConstraints _) -> true | _ -> false
null
https://raw.githubusercontent.com/coq/coq/cc78d97f52f85dc6321acc27daa09fb1b62c80fa/pretyping/pretype_errors.ml
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** Non convertible closed terms Old Case Type inference unification Tactic unification Pretyping s Implicit arguments synthesis errors. It is hard to find a precise location. s Ml Case errors s Pretyping errors
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Names open Environ open EConstr open Type_errors type unification_error = | OccurCheck of Evar.t * constr Constr is a variable not in scope | NotSameArgSize | NotSameHead | NoCanonicalStructure | IncompatibleInstances of env * existential * constr * constr | MetaOccurInBody of Evar.t | InstanceNotSameType of Evar.t * env * types * types | InstanceNotFunctionalType of Evar.t * env * constr * types | UnifUnivInconsistency of UGraph.univ_inconsistency | CannotSolveConstraint of Evd.evar_constraint * unification_error | ProblemBeyondCapabilities type position = (Id.t * Locus.hyp_location_flag) option type position_reporting = (position * int) * constr type subterm_unification_error = bool * position_reporting * position_reporting * (constr * constr * unification_error) option type type_error = (constr, types) ptype_error type pretype_error = | CantFindCaseType of constr | ActualTypeNotCoercible of unsafe_judgment * types * unification_error | UnifOccurCheck of Evar.t * constr | UnsolvableImplicit of Evar.t * Evd.unsolvability_explanation option | CannotUnify of constr * constr * unification_error option | CannotUnifyLocal of constr * constr * constr | CannotUnifyBindingType of constr * constr | CannotGeneralize of constr | NoOccurrenceFound of constr * Id.t option | CannotFindWellTypedAbstraction of constr * constr list * (env * pretype_error) option | WrongAbstractionType of Name.t * constr * types * types | AbstractionOverMeta of Name.t * Name.t | NonLinearUnification of Name.t * constr | VarNotFound of Id.t | EvarNotFound of Id.t | UnexpectedType of constr * constr * unification_error | NotProduct of constr | TypingError of type_error | CannotUnifyOccurrences of subterm_unification_error | UnsatisfiableConstraints of (Evar.t * Evar_kinds.t) option * Evar.Set.t | DisallowedSProp exception PretypeError of env * Evd.evar_map * pretype_error let precatchable_exception = function | CErrors.UserError _ | TypeError _ | PretypeError _ | Nametab.GlobalizationError _ -> true | _ -> false let raise_pretype_error ?loc ?info (env,sigma,te) = let info = Option.default Exninfo.null info in let info = Option.cata (Loc.add_loc info) info loc in Exninfo.iraise (PretypeError(env,sigma,te),info) let raise_type_error ?loc (env,sigma,te) = Loc.raise ?loc (PretypeError(env,sigma,TypingError te)) let error_actual_type ?loc ?info env sigma {uj_val=c;uj_type=actty} expty reason = let j = {uj_val=c;uj_type=actty} in raise_pretype_error ?loc ?info (env, sigma, ActualTypeNotCoercible (j, expty, reason)) let error_actual_type_core ?loc env sigma {uj_val=c;uj_type=actty} expty = let j = {uj_val=c;uj_type=actty} in raise_type_error ?loc (env, sigma, ActualType (j, expty)) let error_cant_apply_not_functional ?loc env sigma rator randl = raise_type_error ?loc (env, sigma, CantApplyNonFunctional (rator, randl)) let error_cant_apply_bad_type ?loc env sigma (n,c,t) rator randl = raise_type_error ?loc (env, sigma, CantApplyBadType ((n,c,t), rator, randl)) let error_ill_formed_branch ?loc env sigma c i actty expty = raise_type_error ?loc (env, sigma, IllFormedBranch (c, i, actty, expty)) let error_number_branches ?loc env sigma cj expn = raise_type_error ?loc (env, sigma, NumberBranches (cj, expn)) let error_case_not_inductive ?loc env sigma cj = raise_type_error ?loc (env, sigma, CaseNotInductive cj) let error_ill_typed_rec_body ?loc env sigma i na jl tys = raise_type_error ?loc (env, sigma, IllTypedRecBody (i, na, jl, tys)) let error_elim_arity ?loc env sigma pi c a = raise_type_error ?loc (env, sigma, ElimArity (pi, c, a)) let error_not_a_type ?loc env sigma j = raise_type_error ?loc (env, sigma, NotAType j) let error_assumption ?loc env sigma j = raise_type_error ?loc (env, sigma, BadAssumption j) let error_occur_check env sigma ev c = raise (PretypeError (env, sigma, UnifOccurCheck (ev,c))) let error_unsolvable_implicit ?loc env sigma evk explain = Loc.raise ?loc (PretypeError (env, sigma, UnsolvableImplicit (evk, explain))) let error_cannot_unify ?loc env sigma ?reason (m,n) = Loc.raise ?loc (PretypeError (env, sigma,CannotUnify (m,n,reason))) let error_cannot_unify_local env sigma (m,n,sn) = raise (PretypeError (env, sigma,CannotUnifyLocal (m,n,sn))) let error_cannot_coerce env sigma (m,n) = raise (PretypeError (env, sigma,CannotUnify (m,n,None))) let error_cannot_find_well_typed_abstraction env sigma p l e = raise (PretypeError (env, sigma,CannotFindWellTypedAbstraction (p,l,e))) let error_wrong_abstraction_type env sigma na a p l = raise (PretypeError (env, sigma,WrongAbstractionType (na,a,p,l))) let error_abstraction_over_meta env sigma hdmeta metaarg = let m = Evd.meta_name sigma hdmeta and n = Evd.meta_name sigma metaarg in raise (PretypeError (env, sigma,AbstractionOverMeta (m,n))) let error_non_linear_unification env sigma hdmeta t = let m = Evd.meta_name sigma hdmeta in raise (PretypeError (env, sigma,NonLinearUnification (m,t))) let error_cant_find_case_type ?loc env sigma expr = raise_pretype_error ?loc (env, sigma, CantFindCaseType expr) let error_unexpected_type ?loc env sigma actty expty e = raise_pretype_error ?loc (env, sigma, UnexpectedType (actty, expty, e)) let error_not_product ?loc env sigma c = raise_pretype_error ?loc (env, sigma, NotProduct c) s Error in conversion from AST to glob_constr let error_var_not_found ?loc env sigma s = raise_pretype_error ?loc (env, sigma, VarNotFound s) let error_evar_not_found ?loc env sigma id = raise_pretype_error ?loc (env, sigma, EvarNotFound id) let error_disallowed_sprop env sigma = raise (PretypeError (env, sigma, DisallowedSProp)) s errors let unsatisfiable_constraints env evd ev comp = match ev with | None -> let err = UnsatisfiableConstraints (None, comp) in raise (PretypeError (env,evd,err)) | Some ev -> let loc, kind = Evd.evar_source (Evd.find_undefined evd ev) in let err = UnsatisfiableConstraints (Some (ev, kind), comp) in Loc.raise ?loc (PretypeError (env,evd,err)) let unsatisfiable_exception exn = match exn with | PretypeError (_, _, UnsatisfiableConstraints _) -> true | _ -> false
60dbbd762e4c21ee200b5984ae64d25868d8751bdd2f08de7a7af9c9918ab95a
cyga/real-world-haskell
CountEntries.hs
file : ch18 / CountEntries.hs module CountEntries (listDirectory, countEntriesTrad) where import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath ((</>)) import Control.Monad (forM, liftM) listDirectory :: FilePath -> IO [String] listDirectory = liftM (filter notDots) . getDirectoryContents where notDots p = p /= "." && p /= ".." countEntriesTrad :: FilePath -> IO [(FilePath, Int)] countEntriesTrad path = do contents <- listDirectory path rest <- forM contents $ \name -> do let newName = path </> name isDir <- doesDirectoryExist newName if isDir then countEntriesTrad newName else return [] return $ (path, length contents) : concat rest
null
https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch18/CountEntries.hs
haskell
file : ch18 / CountEntries.hs module CountEntries (listDirectory, countEntriesTrad) where import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath ((</>)) import Control.Monad (forM, liftM) listDirectory :: FilePath -> IO [String] listDirectory = liftM (filter notDots) . getDirectoryContents where notDots p = p /= "." && p /= ".." countEntriesTrad :: FilePath -> IO [(FilePath, Int)] countEntriesTrad path = do contents <- listDirectory path rest <- forM contents $ \name -> do let newName = path </> name isDir <- doesDirectoryExist newName if isDir then countEntriesTrad newName else return [] return $ (path, length contents) : concat rest
17f41e61497bc0bec311f1d088b9ee1e1aed3828807fe244eb127152cf9daf8e
dbuenzli/astring
test_sub.ml
--------------------------------------------------------------------------- Copyright ( c ) 2015 The astring programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2015 The astring programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open Testing open Astring let pp_str_pair ppf (a, b) = Format.fprintf ppf "@[<1>(%a,%a)@]" String.dump a String.dump b let pp_pair ppf (a, b) = Format.fprintf ppf "@[<1>(%a,%a)@]" String.Sub.dump a String.Sub.dump b let eq_pair (l0, r0) (l1, r1) = String.Sub.equal l0 l1 && String.Sub.equal r0 r1 let eq_sub = eq ~eq:String.Sub.equal ~pp:String.Sub.dump let eq_sub_raw = eq ~eq:String.Sub.equal ~pp:String.Sub.dump_raw let eqs sub s = eq_str (String.Sub.to_string sub) s let eqb sub s = eq_str (String.Sub.base_string sub) s let eqs_opt sub os = let sub_to_str = function | Some sub -> Some (String.Sub.to_string sub) | None -> None in eq_option ~eq:(=) ~pp:pp_str (sub_to_str sub) os let eqs_pair_opt subs_pair pair = let subs_to_str = function | None -> None | Some (sub, sub') -> Some (String.Sub.to_string sub, String.Sub.to_string sub') in eq_option ~eq:(=) ~pp:pp_str_pair (subs_to_str subs_pair) pair let empty_pos s pos = eq_int (String.Sub.length s) 0; eq_int (String.Sub.start_pos s) pos (* Base functions *) let misc = test "String.Sub misc. base functions" @@ fun () -> eqs String.Sub.empty ""; eqs (String.Sub.v "abc") "abc"; eqs (String.Sub.v ~start:0 ~stop:1 "abc") "a"; eqs (String.Sub.v ~start:1 ~stop:2 "abc") "b"; eqs (String.Sub.v ~start:1 ~stop:3 "abc") "bc"; eqs (String.Sub.v ~start:2 ~stop:3 "abc") "c"; eqs (String.Sub.v ~start:3 ~stop:3 "abc") ""; let sub = String.Sub.v ~start:2 ~stop:3 "abc" in eq_int (String.Sub.start_pos sub) 2; eq_int (String.Sub.stop_pos sub) 3; eq_int (String.Sub.length sub) 1; app_invalid ~pp:pp_char (String.Sub.get sub) 3; app_invalid ~pp:pp_char (String.Sub.get sub) 2; app_invalid ~pp:pp_char (String.Sub.get sub) 1; eq_char (String.Sub.get sub 0) 'c'; eq_int (String.Sub.get_byte sub 0) 0x63; eqb (String.Sub.(rebase (v ~stop:2 "abc"))) "ab"; () let head = test "String.[get_]head" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "abc" in let bc = String.Sub.v ~start:1 ~stop:3 "abc" in let eq_ochar = eq_option ~eq:(=) ~pp:pp_char in eq_ochar (String.Sub.head empty) None; eq_ochar (String.Sub.head ~rev:true empty) None; eq_ochar (String.Sub.head bc) (Some 'b'); eq_ochar (String.Sub.head ~rev:true bc) (Some 'c'); eq_char (String.Sub.get_head bc) 'b'; eq_char (String.Sub.get_head ~rev:true bc) 'c'; app_invalid ~pp:pp_char String.Sub.get_head empty; () let to_string = test "String.Sub.to_string" @@ fun () -> let no_alloc s = let r = String.Sub.to_string s in eq_bool (r == (String.Sub.base_string s) || r == String.empty) true in no_alloc (String.Sub.v ~start:0 ~stop:0 "abc"); eq_str (String.Sub.(to_string (v ~start:0 ~stop:1 "abc"))) "a"; eq_str (String.Sub.(to_string (v ~start:0 ~stop:2 "abc"))) "ab"; no_alloc (String.Sub.v ~start:0 ~stop:3 "abc"); no_alloc (String.Sub.v ~start:1 ~stop:1 "abc"); eq_str (String.Sub.(to_string (v ~start:1 ~stop:2 "abc"))) "b"; eq_str (String.Sub.(to_string (v ~start:1 ~stop:3 "abc"))) "bc"; no_alloc (String.Sub.v ~start:2 ~stop:2 "abc"); eq_str (String.Sub.(to_string (v ~start:2 ~stop:3 "abc"))) "c"; no_alloc (String.Sub.v ~start:3 ~stop:3 "abc"); () (* Stretching substrings *) let start = test "String.Sub.start" @@ fun () -> empty_pos String.Sub.(start @@ v "") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:0 "abc") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:1 "abc") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:2 "abc") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:3 "abc") 0; empty_pos String.Sub.(start @@ v ~start:1 ~stop:1 "abc") 1; empty_pos String.Sub.(start @@ v ~start:1 ~stop:2 "abc") 1; empty_pos String.Sub.(start @@ v ~start:1 ~stop:3 "abc") 1; empty_pos String.Sub.(start @@ v ~start:2 ~stop:2 "abc") 2; empty_pos String.Sub.(start @@ v ~start:2 ~stop:3 "abc") 2; empty_pos String.Sub.(start @@ v ~start:3 ~stop:3 "abc") 3; () let stop = test "String.Sub.stop" @@ fun () -> empty_pos String.Sub.(stop @@ v "") 0; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:0 "abc") 0; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:1 "abc") 1; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:2 "abc") 2; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:3 "abc") 3; empty_pos String.Sub.(stop @@ v ~start:1 ~stop:1 "abc") 1; empty_pos String.Sub.(stop @@ v ~start:1 ~stop:2 "abc") 2; empty_pos String.Sub.(stop @@ v ~start:1 ~stop:3 "abc") 3; empty_pos String.Sub.(stop @@ v ~start:2 ~stop:2 "abc") 2; empty_pos String.Sub.(stop @@ v ~start:2 ~stop:3 "abc") 3; empty_pos String.Sub.(stop @@ v ~start:3 ~stop:3 "abc") 3; () let tail = test "String.Sub.tail" @@ fun () -> empty_pos String.Sub.(tail @@ v "") 0; empty_pos String.Sub.(tail @@ v ~start:0 ~stop:0 "abc") 0; empty_pos String.Sub.(tail @@ v ~start:0 ~stop:1 "abc") 1; eqs String.Sub.(tail @@ v ~start:0 ~stop:2 "abc") "b"; eqs String.Sub.(tail @@ v ~start:0 ~stop:3 "abc") "bc"; empty_pos String.Sub.(tail @@ v ~start:1 ~stop:1 "abc") 1; empty_pos String.Sub.(tail @@ v ~start:1 ~stop:2 "abc") 2; eqs String.Sub.(tail @@ v ~start:1 ~stop:3 "abc") "c"; empty_pos String.Sub.(tail @@ v ~start:2 ~stop:2 "abc") 2; empty_pos String.Sub.(tail @@ v ~start:2 ~stop:3 "abc") 3; empty_pos String.Sub.(tail @@ v ~start:3 ~stop:3 "abc") 3; () let base = test "String.Sub.base" @@ fun () -> eqs String.Sub.(base @@ v "") ""; eqs String.Sub.(base @@ v ~start:0 ~stop:0 "abc") "abc"; eqs String.Sub.(base @@ v ~start:0 ~stop:1 "abc") "abc"; eqs String.Sub.(base @@ v ~start:0 ~stop:2 "abc") "abc"; eqs String.Sub.(base @@ v ~start:0 ~stop:3 "abc") "abc"; eqs String.Sub.(base @@ v ~start:1 ~stop:1 "abc") "abc"; eqs String.Sub.(base @@ v ~start:1 ~stop:2 "abc") "abc"; eqs String.Sub.(base @@ v ~start:1 ~stop:3 "abc") "abc"; eqs String.Sub.(base @@ v ~start:2 ~stop:2 "abc") "abc"; eqs String.Sub.(base @@ v ~start:2 ~stop:3 "abc") "abc"; eqs String.Sub.(base @@ v ~start:3 ~stop:3 "abc") "abc"; () let extend = test "String.Sub.extend" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "abcdefg" in let abcd = String.Sub.v ~start:0 ~stop:4 "abcdefg" in let cd = String.Sub.v ~start:2 ~stop:4 "abcdefg" in app_invalid ~pp:String.Sub.pp (fun s -> String.Sub.extend ~max:(-1) s) abcd; eqs (String.Sub.extend empty) "cdefg"; eqs (String.Sub.extend ~rev:true empty) "ab"; eqs (String.Sub.extend ~max:2 empty) "cd"; eqs (String.Sub.extend ~sat:(fun c -> c < 'f') empty) "cde"; eqs (String.Sub.extend ~rev:true ~max:1 empty) "b"; eqs (String.Sub.extend abcd) "abcdefg"; eqs (String.Sub.extend ~max:2 abcd) "abcdef"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c < 'e') abcd) "abcd"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c < 'f') abcd) "abcde"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c < 'g') abcd) "abcdef"; eqs (String.Sub.extend ~rev:true abcd) "abcd"; eqs (String.Sub.extend ~rev:true ~max:2 ~sat:(fun c -> c > 'a') cd) "bcd"; eqs (String.Sub.extend ~rev:true ~max:2 ~sat:(fun c -> c >= 'a') cd) "abcd"; eqs (String.Sub.extend ~rev:true ~max:1 ~sat:(fun c -> c >= 'a') cd) "bcd"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c >= 'a') cd) "cdef"; eqs (String.Sub.extend ~sat:(fun c -> c >= 'a') cd) "cdefg"; () let reduce = test "String.Sub.reduce" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "abcdefg" in let abcd = String.Sub.v ~start:0 ~stop:4 "abcdefg" in let cd = String.Sub.v ~start:2 ~stop:4 "abcdefg" in app_invalid ~pp:String.Sub.pp (fun s -> String.Sub.reduce ~max:(-1) s) abcd; empty_pos (String.Sub.reduce ~rev:false empty) 2; empty_pos (String.Sub.reduce ~rev:true empty) 2; empty_pos (String.Sub.reduce ~rev:false ~max:2 empty) 2; empty_pos (String.Sub.reduce ~rev:true ~max:2 empty) 2; empty_pos (String.Sub.reduce ~rev:false ~sat:(fun c -> c < 'f') empty) 2; empty_pos (String.Sub.reduce ~rev:true ~sat:(fun c -> c < 'f') empty) 2; empty_pos (String.Sub.reduce ~rev:false ~max:1 empty) 2; empty_pos (String.Sub.reduce ~rev:true ~max:1 empty) 2; empty_pos (String.Sub.reduce ~rev:false abcd) 0; empty_pos (String.Sub.reduce ~rev:true abcd) 4; eqs (String.Sub.reduce ~rev:false ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:true ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:false ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:true ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:false ~max:2 abcd) "ab"; eqs (String.Sub.reduce ~rev:true ~max:2 abcd) "cd"; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c < 'c') abcd) "abcd"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c < 'c') abcd) "cd"; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c > 'b') abcd) "ab"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c < 'b') abcd) "bcd"; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c > 'a') abcd) "ab"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c < 'a') abcd) "abcd"; empty_pos (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c > 'a') cd) 2; empty_pos (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c > 'a') cd) 4; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c >= 'd') cd) "c"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c >= 'd') cd) "cd"; eqs (String.Sub.reduce ~rev:false ~max:1 ~sat:(fun c -> c > 'c') cd) "c"; eqs (String.Sub.reduce ~rev:true ~max:1 ~sat:(fun c -> c > 'c') cd) "cd"; eqs (String.Sub.reduce ~rev:false ~sat:(fun c -> c > 'c') cd) "c"; eqs (String.Sub.reduce ~rev:true ~sat:(fun c -> c > 'c') cd) "cd"; () let extent = test "String.Sub.extent" @@ fun () -> app_invalid ~pp:String.Sub.dump_raw String.Sub.(extent (v "a")) (String.Sub.(v "b")); let abcd = "abcd" in let e0 = String.Sub.v ~start:0 ~stop:0 abcd in let a = String.Sub.v ~start:0 ~stop:1 abcd in let ab = String.Sub.v ~start:0 ~stop:2 abcd in let abc = String.Sub.v ~start:0 ~stop:3 abcd in let _abcd = String.Sub.v ~start:0 ~stop:4 abcd in let e1 = String.Sub.v ~start:1 ~stop:1 abcd in let b = String.Sub.v ~start:1 ~stop:2 abcd in let bc = String.Sub.v ~start:1 ~stop:3 abcd in let bcd = String.Sub.v ~start:1 ~stop:4 abcd in let e2 = String.Sub.v ~start:2 ~stop:2 abcd in let c = String.Sub.v ~start:2 ~stop:3 abcd in let cd = String.Sub.v ~start:2 ~stop:4 abcd in let e3 = String.Sub.v ~start:3 ~stop:3 abcd in let d = String.Sub.v ~start:3 ~stop:4 abcd in let e4 = String.Sub.v ~start:4 ~stop:4 abcd in empty_pos (String.Sub.extent e0 e0) 0; eqs (String.Sub.extent e0 e1) "a"; eqs (String.Sub.extent e1 e0) "a"; eqs (String.Sub.extent e0 e2) "ab"; eqs (String.Sub.extent e2 e0) "ab"; eqs (String.Sub.extent e0 e3) "abc"; eqs (String.Sub.extent e3 e0) "abc"; eqs (String.Sub.extent e0 e4) "abcd"; eqs (String.Sub.extent e4 e0) "abcd"; empty_pos (String.Sub.extent e1 e1) 1; eqs (String.Sub.extent e1 e2) "b"; eqs (String.Sub.extent e2 e1) "b"; eqs (String.Sub.extent e1 e3) "bc"; eqs (String.Sub.extent e3 e1) "bc"; eqs (String.Sub.extent e1 e4) "bcd"; eqs (String.Sub.extent e4 e1) "bcd"; empty_pos (String.Sub.extent e2 e2) 2; eqs (String.Sub.extent e2 e3) "c"; eqs (String.Sub.extent e3 e2) "c"; eqs (String.Sub.extent e2 e4) "cd"; eqs (String.Sub.extent e4 e2) "cd"; empty_pos (String.Sub.extent e3 e3) 3; eqs (String.Sub.extent e3 e4) "d"; eqs (String.Sub.extent e4 e3) "d"; empty_pos (String.Sub.extent e4 e4) 4; eqs (String.Sub.extent a d) "abcd"; eqs (String.Sub.extent d a) "abcd"; eqs (String.Sub.extent b d) "bcd"; eqs (String.Sub.extent d b) "bcd"; eqs (String.Sub.extent c cd) "cd"; eqs (String.Sub.extent cd c) "cd"; eqs (String.Sub.extent e0 _abcd) "abcd"; eqs (String.Sub.extent _abcd e0) "abcd"; eqs (String.Sub.extent ab c) "abc"; eqs (String.Sub.extent c ab) "abc"; eqs (String.Sub.extent bc c) "bc"; eqs (String.Sub.extent c bc) "bc"; eqs (String.Sub.extent abc d) "abcd"; eqs (String.Sub.extent d abc) "abcd"; eqs (String.Sub.extent d bcd) "bcd"; eqs (String.Sub.extent bcd d) "bcd"; () let overlap = test "String.Sub.overlap" @@ fun () -> let empty_pos sub pos = match sub with | None -> fail "no sub" | Some sub -> empty_pos sub pos in app_invalid ~pp:String.Sub.dump_raw String.Sub.(extent (v "a")) (String.Sub.(v "b")); let abcd = "abcd" in let e0 = String.Sub.v ~start:0 ~stop:0 abcd in let a = String.Sub.v ~start:0 ~stop:1 abcd in let ab = String.Sub.v ~start:0 ~stop:2 abcd in let abc = String.Sub.v ~start:0 ~stop:3 abcd in let _abcd = String.Sub.v ~start:0 ~stop:4 abcd in let e1 = String.Sub.v ~start:1 ~stop:1 abcd in let b = String.Sub.v ~start:1 ~stop:2 abcd in let bc = String.Sub.v ~start:1 ~stop:3 abcd in let bcd = String.Sub.v ~start:1 ~stop:4 abcd in let e2 = String.Sub.v ~start:2 ~stop:2 abcd in let c = String.Sub.v ~start:2 ~stop:3 abcd in let cd = String.Sub.v ~start:2 ~stop:4 abcd in let e3 = String.Sub.v ~start:3 ~stop:3 abcd in let d = String.Sub.v ~start:3 ~stop:4 abcd in let e4 = String.Sub.v ~start:4 ~stop:4 abcd in empty_pos (String.Sub.overlap e0 a) 0; empty_pos (String.Sub.overlap a e0) 0; eqs_opt (String.Sub.overlap e0 b) None; eqs_opt (String.Sub.overlap b e0) None; empty_pos (String.Sub.overlap a b) 1; empty_pos (String.Sub.overlap b a) 1; eqs_opt (String.Sub.overlap a a) (Some "a"); eqs_opt (String.Sub.overlap a ab) (Some "a"); eqs_opt (String.Sub.overlap ab ab) (Some "ab"); eqs_opt (String.Sub.overlap ab abc) (Some "ab"); eqs_opt (String.Sub.overlap abc ab) (Some "ab"); eqs_opt (String.Sub.overlap b abc) (Some "b"); eqs_opt (String.Sub.overlap abc b) (Some "b"); empty_pos (String.Sub.overlap abc e3) 3; empty_pos (String.Sub.overlap e3 abc) 3; eqs_opt (String.Sub.overlap ab bc) (Some "b"); eqs_opt (String.Sub.overlap bc ab) (Some "b"); eqs_opt (String.Sub.overlap bcd bc) (Some "bc"); eqs_opt (String.Sub.overlap bc bcd) (Some "bc"); eqs_opt (String.Sub.overlap bcd d) (Some "d"); eqs_opt (String.Sub.overlap d bcd) (Some "d"); eqs_opt (String.Sub.overlap bcd cd) (Some "cd"); eqs_opt (String.Sub.overlap cd bcd) (Some "cd"); eqs_opt (String.Sub.overlap bcd c) (Some "c"); eqs_opt (String.Sub.overlap c bcd) (Some "c"); empty_pos (String.Sub.overlap e2 bcd) 2; empty_pos (String.Sub.overlap bcd e2) 2; empty_pos (String.Sub.overlap bcd e3) 3; empty_pos (String.Sub.overlap e3 bcd) 3; empty_pos (String.Sub.overlap bcd e4) 4; empty_pos (String.Sub.overlap e4 bcd) 4; empty_pos (String.Sub.overlap e1 e1) 1; eqs_opt (String.Sub.overlap e0 bcd) None; () (* Appending substrings. *) let append = test "String.Sub.append" @@ fun () -> let no_allocl s s' = eq_bool (String.Sub.(base_string @@ append s s') == String.Sub.(base_string s)) true in let no_allocr s s' = eq_bool (String.Sub.(base_string @@ append s s') == String.Sub.(base_string s')) true in no_allocl String.Sub.empty String.Sub.empty; no_allocr String.Sub.empty String.Sub.empty; no_allocl (String.Sub.v "bla") (String.Sub.v ~start:0 ~stop:0 "abcd"); no_allocr (String.Sub.v ~start:1 ~stop:1 "b") (String.Sub.v "bli"); let a = String.sub_with_index_range ~first:0 ~last:0 "abcd" in let ab = String.sub_with_index_range ~first:0 ~last:1 "abcd" in let cd = String.sub_with_index_range ~first:2 ~last:3 "abcd" in let empty = String.Sub.v ~start:4 ~stop:4 "abcd" in eqb (String.Sub.append a empty) "a"; eqb (String.Sub.append empty a) "a"; eqb (String.Sub.append ab empty) "ab"; eqb (String.Sub.append empty ab) "ab"; eqb (String.Sub.append ab cd) "abcd"; eqb (String.Sub.append cd ab) "cdab"; () let concat = test "String.Sub.concat" @@ fun () -> let dash = String.sub_with_range ~first:2 ~len:1 "ab-d" in let ddash = String.sub_with_range ~first:1 ~len:2 "a--d" in let empty = String.sub_with_range ~first:2 ~len:0 "ab-d" in let no_alloc ?sep s = let r = String.Sub.(base_string (concat ?sep [s])) in eq_bool (r == String.Sub.base_string s || r == String.empty) true in no_alloc empty; no_alloc (String.Sub.v "hey"); no_alloc ~sep:empty empty; no_alloc ~sep:dash empty; no_alloc ~sep:empty (String.Sub.v "abc"); no_alloc ~sep:dash (String.Sub.v "abc"); let sempty = String.Sub.v ~start:2 ~stop:2 "abc" in let a = String.Sub.v ~start:2 ~stop:3 "kka" in let b = String.Sub.v ~start:1 ~stop:2 "ubd" in let c = String.Sub.v ~start:0 ~stop:1 "cdd" in let ab = String.Sub.v ~start:1 ~stop:3 "gabi" in let abc = String.Sub.v ~start:5 ~stop:8 "zuuuuabcbb" in eqb (String.Sub.concat ~sep:empty []) ""; eqb (String.Sub.concat ~sep:empty [sempty]) ""; eqb (String.Sub.concat ~sep:empty [sempty;sempty]) ""; eqb (String.Sub.concat ~sep:empty [a;b;]) "ab"; eqb (String.Sub.concat ~sep:empty [a;b;sempty;c]) "abc"; eqb (String.Sub.concat ~sep:dash []) ""; eqb (String.Sub.concat ~sep:dash [sempty]) ""; eqb (String.Sub.concat ~sep:dash [a]) "a"; eqb (String.Sub.concat ~sep:dash [a;sempty]) "a-"; eqb (String.Sub.concat ~sep:dash [sempty;a]) "-a"; eqb (String.Sub.concat ~sep:dash [sempty;a;sempty]) "-a-"; eqb (String.Sub.concat ~sep:dash [a;b;c]) "a-b-c"; eqb (String.Sub.concat ~sep:ddash [a;b;c]) "a--b--c"; eqb (String.Sub.concat ~sep:ab [a;b;c]) "aabbabc"; eqb (String.Sub.concat ~sep:ab [abc;b;c]) "abcabbabc"; () (* Predicates *) let is_empty = test "String.Sub.is_empty" @@ fun () -> eq_bool (String.Sub.is_empty (String.Sub.v "")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:4 ~stop:4 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:0 "huiy")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:1 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:2 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:3 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:4 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:1 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:2 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:3 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:4 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:2 ~stop:2 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:2 ~stop:3 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:3 ~stop:3 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:3 ~stop:4 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:4 ~stop:4 "huiy")) true; () let is_prefix = test "String.Sub.is_prefix" @@ fun () -> let empty = String.sub_with_range ~first:3 ~len:0 "ugoadfj" in let sempty = String.sub_with_range ~first:4 ~len:0 "dfkdjf" in let habla = String.sub_with_range ~first:2 ~len:5 "abhablablu" in let h = String.sub_with_range ~first:0 ~len:1 "hadfdffdf" in let ha = String.sub_with_range ~first:0 ~len:2 "hadfdffdf" in let hab = String.sub_with_range ~first:3 ~len:3 "hadhabdffdf" in let abla = String.sub_with_range ~first:1 ~len:4 "iabla" in eqs empty ""; eqs sempty ""; eqs habla "habla"; eqs h "h"; eqs ha "ha"; eqs hab "hab"; eqs abla "abla"; eq_bool (String.Sub.is_prefix ~affix:empty sempty) true; eq_bool (String.Sub.is_prefix ~affix:empty habla) true; eq_bool (String.Sub.is_prefix ~affix:ha sempty) false; eq_bool (String.Sub.is_prefix ~affix:ha h) false; eq_bool (String.Sub.is_prefix ~affix:ha ha) true; eq_bool (String.Sub.is_prefix ~affix:ha hab) true; eq_bool (String.Sub.is_prefix ~affix:ha habla) true; eq_bool (String.Sub.is_prefix ~affix:ha abla) false; () let is_infix = test "String.Sub.is_infix" @@ fun () -> let empty = String.sub_with_range ~first:1 ~len:0 "ugoadfj" in let sempty = String.sub_with_range ~first:2 ~len:0 "dfkdjf" in let asdf = String.sub_with_range ~first:1 ~len:4 "aasdflablu" in let a = String.sub_with_range ~first:2 ~len:1 "cda" in let h = String.sub_with_range ~first:0 ~len:1 "h" in let ha = String.sub_with_range ~first:1 ~len:2 "uhadfdffdf" in let ah = String.sub_with_range ~first:0 ~len:2 "ah" in let aha = String.sub_with_range ~first:2 ~len:3 "aaaha" in let haha = String.sub_with_range ~first:1 ~len:4 "ahaha" in let hahb = String.sub_with_range ~first:0 ~len:4 "hahbdfdf" in let blhahb = String.sub_with_range ~first:0 ~len:6 "blhahbdfdf" in let blha = String.sub_with_range ~first:1 ~len:4 "fblhahbdfdf" in let blh = String.sub_with_range ~first:1 ~len:3 "fblhahbdfdf" in eqs asdf "asdf"; eqs ha "ha"; eqs h "h"; eqs a "a"; eqs aha "aha"; eqs haha "haha"; eqs hahb "hahb"; eqs blhahb "blhahb"; eqs blha "blha"; eqs blh "blh"; eq_bool (String.Sub.is_infix ~affix:empty sempty) true; eq_bool (String.Sub.is_infix ~affix:empty asdf) true; eq_bool (String.Sub.is_infix ~affix:empty ha) true; eq_bool (String.Sub.is_infix ~affix:ha sempty) false; eq_bool (String.Sub.is_infix ~affix:ha a) false; eq_bool (String.Sub.is_infix ~affix:ha h) false; eq_bool (String.Sub.is_infix ~affix:ha ah) false; eq_bool (String.Sub.is_infix ~affix:ha ha) true; eq_bool (String.Sub.is_infix ~affix:ha aha) true; eq_bool (String.Sub.is_infix ~affix:ha haha) true; eq_bool (String.Sub.is_infix ~affix:ha hahb) true; eq_bool (String.Sub.is_infix ~affix:ha blhahb) true; eq_bool (String.Sub.is_infix ~affix:ha blha) true; eq_bool (String.Sub.is_infix ~affix:ha blh) false; () let is_suffix = test "String.Sub.is_suffix" @@ fun () -> let empty = String.sub_with_range ~first:1 ~len:0 "ugoadfj" in let sempty = String.sub_with_range ~first:2 ~len:0 "dfkdjf" in let asdf = String.sub_with_range ~first:1 ~len:4 "aasdflablu" in let ha = String.sub_with_range ~first:1 ~len:2 "uhadfdffdf" in let h = String.sub_with_range ~first:0 ~len:1 "h" in let a = String.sub_with_range ~first:2 ~len:1 "cda" in let ah = String.sub_with_range ~first:0 ~len:2 "ah" in let aha = String.sub_with_range ~first:2 ~len:3 "aaaha" in let haha = String.sub_with_range ~first:1 ~len:4 "ahaha" in let hahb = String.sub_with_range ~first:0 ~len:4 "hahbdfdf" in eqs asdf "asdf"; eqs ha "ha"; eqs h "h"; eqs a "a"; eqs aha "aha"; eqs haha "haha"; eqs hahb "hahb"; eq_bool (String.Sub.is_suffix ~affix:empty sempty) true; eq_bool (String.Sub.is_suffix ~affix:empty asdf) true; eq_bool (String.Sub.is_suffix ~affix:ha sempty) false; eq_bool (String.Sub.is_suffix ~affix:ha a) false; eq_bool (String.Sub.is_suffix ~affix:ha h) false; eq_bool (String.Sub.is_suffix ~affix:ha ah) false; eq_bool (String.Sub.is_suffix ~affix:ha ha) true; eq_bool (String.Sub.is_suffix ~affix:ha aha) true; eq_bool (String.Sub.is_suffix ~affix:ha haha) true; eq_bool (String.Sub.is_suffix ~affix:ha hahb) false; () let for_all = test "String.Sub.for_all" @@ fun () -> let empty = String.Sub.v ~start:3 ~stop:3 "asldfksaf" in let s123 = String.Sub.v ~start:2 ~stop:5 "sf123df" in let s412 = String.Sub.v "412" in let s142 = String.Sub.v ~start:3 "aaa142" in let s124 = String.Sub.v ~start:3 "aad124" in eqs empty ""; eqs s123 "123"; eqs s412 "412"; eqs s142 "142"; eqs s124 "124"; eq_bool (String.Sub.for_all (fun _ -> false) empty) true; eq_bool (String.Sub.for_all (fun _ -> true) empty) true; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s123) true; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s412) false; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s142) false; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s124) false; () let exists = test "String.Sub.exists" @@ fun () -> let empty = String.Sub.v ~start:3 ~stop:3 "asldfksaf" in let s541 = String.sub_with_index_range ~first:1 ~last:3 "a541" in let s154 = String.sub_with_index_range ~first:1 "a154" in let s654 = String.sub_with_index_range ~last:2 "654adf" in eqs s541 "541"; eqs s154 "154"; eqs s654 "654"; eq_bool (String.Sub.exists (fun _ -> false) empty) false; eq_bool (String.Sub.exists (fun _ -> true) empty) false; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s541) true; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s541) true; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s154) true; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s654) false; () let same_base = test "String.Sub.same_base" @@ fun () -> let abcd = "abcd" in let a = String.sub_with_index_range ~first:0 ~last:0 abcd in let ab = String.sub_with_index_range ~first:0 ~last:1 abcd in let abce = String.sub_with_index_range ~first:0 ~last:1 "abce" in eq_bool (String.Sub.same_base a ab) true; eq_bool (String.Sub.same_base ab a) true; eq_bool (String.Sub.same_base abce a) false; eq_bool (String.Sub.same_base abce a) false; () let equal_bytes = test "String.Sub.equal_bytes" @@ fun () -> let a = String.sub_with_index_range ~first:0 ~last:0 "abcd" in let ab = String.sub_with_index_range ~first:0 ~last:1 "abcd" in let ab' = String.sub_with_index_range ~first:2 ~last:3 "cdab" in let cd = String.sub_with_index_range ~first:2 ~last:3 "abcd" in let empty = String.Sub.v ~start:4 ~stop:4 "abcd" in eq_bool (String.Sub.equal_bytes empty empty) true; eq_bool (String.Sub.equal_bytes empty a) false; eq_bool (String.Sub.equal_bytes a empty) false; eq_bool (String.Sub.equal_bytes a a) true; eq_bool (String.Sub.equal_bytes ab ab') true; eq_bool (String.Sub.equal_bytes cd ab) false; () let compare_bytes = test "String.Sub.compare_bytes" @@ fun () -> let empty = String.Sub.v "" in let ab = String.sub_with_index_range ~first:0 ~last:1 "abcd" in let ab' = String.sub_with_index_range ~first:2 ~last:3 "cdab" in let abc = String.Sub.v ~start:3 ~stop:5 "adabcdd" in eq_int (String.Sub.compare_bytes empty ab) (-1); eq_int (String.Sub.compare_bytes empty empty) (0); eq_int (String.Sub.compare_bytes ab ab') (0); eq_int (String.Sub.compare_bytes ab empty) (1); eq_int (String.Sub.compare_bytes ab abc) (-1); () let equal = test "String.Sub.equal" @@ fun () -> app_invalid ~pp:pp_bool (String.Sub.(equal (v "b"))) (String.Sub.v "a"); let base = "abcd" in let a = String.Sub.v ~start:0 ~stop:1 base in let empty = String.Sub.v ~start:4 ~stop:4 base in let ab = String.sub_with_index_range ~first:0 ~last:1 base in let cd = String.sub_with_index_range ~first:2 ~last:3 base in eq_bool (String.Sub.equal empty empty) true; eq_bool (String.Sub.equal empty a) false; eq_bool (String.Sub.equal a empty) false; eq_bool (String.Sub.equal a a) true; eq_bool (String.Sub.equal ab ab) true; eq_bool (String.Sub.equal cd ab) false; eq_bool (String.Sub.equal ab cd) false; eq_bool (String.Sub.equal cd cd) true; () let compare = test "String.Sub.compare" @@ fun () -> app_invalid ~pp:pp_bool (String.Sub.(equal (v "b"))) (String.Sub.v "a"); let base = "abcd" in let a = String.Sub.v ~start:0 ~stop:1 base in let empty = String.Sub.v ~start:4 ~stop:4 base in let ab = String.sub_with_index_range ~first:0 ~last:1 base in let cd = String.sub_with_index_range ~first:2 ~last:3 base in eq_int (String.Sub.compare empty empty) 0; eq_int (String.Sub.compare empty a) 1; eq_int (String.Sub.compare a empty) (-1); eq_int (String.Sub.compare a a) 0; eq_int (String.Sub.compare ab ab) 0; eq_int (String.Sub.compare cd ab) 1; eq_int (String.Sub.compare ab cd) (-1); eq_int (String.Sub.compare cd cd) 0; () (* Extracting substrings *) let with_range = test "String.Sub.with_range" @@ fun () -> let invalid ?first ?len s = app_invalid ~pp:String.Sub.pp (String.Sub.with_range ?first ?len) s in let empty_pos ?first ?len s pos = empty_pos (String.Sub.with_range ?first ?len s) pos in let base = "00abc1234" in let abc = String.sub ~start:2 ~stop:5 base in let a = String.sub ~start:2 ~stop:3 base in let empty = String.sub ~start:2 ~stop:2 base in empty_pos empty ~first:1 ~len:0 2; empty_pos empty ~first:1 ~len:0 2; empty_pos empty ~first:0 ~len:1 2; empty_pos empty ~first:(-1) ~len:1 2; invalid empty ~first:0 ~len:(-1); eqs (String.Sub.with_range a ~first:0 ~len:0) ""; eqs (String.Sub.with_range a ~first:1 ~len:0) ""; empty_pos a ~first:1 ~len:1 3; empty_pos a ~first:(-1) ~len:1 2; eqs (String.Sub.with_range ~first:1 abc) "bc"; eqs (String.Sub.with_range ~first:2 abc) "c"; eqs (String.Sub.with_range ~first:3 abc) ""; empty_pos ~first:4 abc 5; eqs (String.Sub.with_range abc ~first:0 ~len:0) ""; eqs (String.Sub.with_range abc ~first:0 ~len:1) "a"; eqs (String.Sub.with_range abc ~first:0 ~len:2) "ab"; eqs (String.Sub.with_range abc ~first:0 ~len:4) "abc"; eqs (String.Sub.with_range abc ~first:1 ~len:0) ""; eqs (String.Sub.with_range abc ~first:1 ~len:1) "b"; eqs (String.Sub.with_range abc ~first:1 ~len:2) "bc"; eqs (String.Sub.with_range abc ~first:1 ~len:3) "bc"; eqs (String.Sub.with_range abc ~first:2 ~len:0) ""; eqs (String.Sub.with_range abc ~first:2 ~len:1) "c"; eqs (String.Sub.with_range abc ~first:2 ~len:2) "c"; eqs (String.Sub.with_range abc ~first:3 ~len:0) ""; eqs (String.Sub.with_range abc ~first:1 ~len:4) "bc"; empty_pos abc ~first:(-1) ~len:1 2; () let with_index_range = test "String.Sub.with_index_range" @@ fun () -> let empty_pos ?first ?last s pos = empty_pos (String.Sub.with_index_range ?first ?last s) pos in let base = "00abc1234" in let abc = String.sub ~start:2 ~stop:5 base in let a = String.sub ~start:2 ~stop:3 base in let empty = String.sub ~start:2 ~stop:2 base in empty_pos empty 2; empty_pos empty ~first:0 ~last:0 2; empty_pos empty ~first:1 ~last:0 2; empty_pos empty ~first:0 ~last:1 2; empty_pos empty ~first:(-1) ~last:1 2; empty_pos empty ~first:0 ~last:(-1) 2; eqs (String.Sub.with_index_range ~first:0 ~last:2 a) "a"; empty_pos a ~first:0 ~last:(-1) 2; eqs (String.Sub.with_index_range ~first:0 ~last:2 a) "a"; eqs (String.Sub.with_index_range ~first:(-1) ~last:0 a) "a"; eqs (String.Sub.with_index_range ~first:1 abc) "bc"; eqs (String.Sub.with_index_range ~first:2 abc) "c"; empty_pos ~first:3 abc 5; empty_pos ~first:4 abc 5; eqs (String.Sub.with_index_range abc ~first:0 ~last:0) "a"; eqs (String.Sub.with_index_range abc ~first:0 ~last:1) "ab"; eqs (String.Sub.with_index_range abc ~first:0 ~last:3) "abc"; eqs (String.Sub.with_index_range abc ~first:1 ~last:1) "b"; eqs (String.Sub.with_index_range abc ~first:1 ~last:2) "bc"; empty_pos abc ~first:1 ~last:0 3; eqs (String.Sub.with_index_range abc ~first:1 ~last:3) "bc"; eqs (String.Sub.with_index_range abc ~first:2 ~last:2) "c"; empty_pos abc ~first:2 ~last:0 4; empty_pos abc ~first:2 ~last:1 4; eqs (String.Sub.with_index_range abc ~first:2 ~last:3) "c"; empty_pos abc ~first:3 ~last:0 5; empty_pos abc ~first:3 ~last:1 5; empty_pos abc ~first:3 ~last:2 5; empty_pos abc ~first:3 ~last:3 5; eqs (String.Sub.with_index_range abc ~first:(-1) ~last:0) "a"; () let span = test "String.Sub.{span,take,drop}" @@ fun () -> let eq_pair (l0, r0) (l1, r1) = String.Sub.(equal l0 l1 && equal r0 r1) in let eq_pair = eq ~eq:eq_pair ~pp:pp_pair in let eq ?(rev = false) ?min ?max ?sat s (sl, sr as spec) = let (l, r as pair) = String.Sub.span ~rev ?min ?max ?sat s in let t = String.Sub.take ~rev ?min ?max ?sat s in let d = String.Sub.drop ~rev ?min ?max ?sat s in eq_pair pair spec; eq_sub t (if rev then sr else sl); eq_sub d (if rev then sl else sr); in let invalid ?rev ?min ?max ?sat s = app_invalid ~pp:pp_pair (String.Sub.span ?rev ?min ?max ?sat) s in let base = "0ab cd0" in let empty = String.sub ~start:3 ~stop:3 base in let ab_cd = String.sub ~start:1 ~stop:6 base in let ab = String.sub ~start:1 ~stop:3 base in let _cd = String.sub ~start:3 ~stop:6 base in let cd = String.sub ~start:4 ~stop:6 base in let ab_ = String.sub ~start:1 ~stop:4 base in let a = String.sub ~start:1 ~stop:2 base in let b_cd = String.sub ~start:2 ~stop:6 base in let b = String.sub ~start:2 ~stop:3 base in let d = String.sub ~start:5 ~stop:6 base in let ab_c = String.sub ~start:1 ~stop:5 base in eq ~rev:false ~min:1 ~max:0 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~min:1 ~max:0 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~sat:Char.Ascii.is_white ab_cd (String.Sub.start ab_cd, ab_cd); eq ~sat:Char.Ascii.is_letter ab_cd (ab, _cd); eq ~max:1 ~sat:Char.Ascii.is_letter ab_cd (a, b_cd); eq ~max:0 ~sat:Char.Ascii.is_letter ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_white ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ab_cd (ab_, cd); eq ~rev:true ~max:1 ~sat:Char.Ascii.is_letter ab_cd (ab_c, d); eq ~rev:true ~max:0 ~sat:Char.Ascii.is_letter ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~sat:Char.Ascii.is_letter ab (ab, String.Sub.stop ab); eq ~max:1 ~sat:Char.Ascii.is_letter ab (a, b); eq ~sat:Char.Ascii.is_letter b (b, empty); eq ~rev:true ~max:1 ~sat:Char.Ascii.is_letter ab (a, b); eq ~max:1 ~sat:Char.Ascii.is_white ab (String.Sub.start ab, ab); eq ~rev:true ~sat:Char.Ascii.is_white empty (empty, empty); eq ~sat:Char.Ascii.is_white empty (empty, empty); invalid ~rev:false ~min:(-1) empty; invalid ~rev:true ~min:(-1) empty; invalid ~rev:false ~max:(-1) empty; invalid ~rev:true ~max:(-1) empty; eq ~rev:false empty (empty,empty); eq ~rev:true empty (empty,empty); eq ~rev:false ~min:0 ~max:0 empty (empty,empty); eq ~rev:true ~min:0 ~max:0 empty (empty,empty); eq ~rev:false ~min:1 ~max:0 empty (empty,empty); eq ~rev:true ~min:1 ~max:0 empty (empty,empty); eq ~rev:false ~max:0 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~max:0 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ~max:2 ab_cd (ab, _cd); eq ~rev:true ~max:2 ab_cd (ab_, cd); eq ~rev:false ~min:6 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~min:6 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:true ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:false ~max:30 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:true ~max:30 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:false ~sat:Char.Ascii.is_white ab_cd (String.Sub.start ab_cd,ab_cd); eq ~rev:true ~sat:Char.Ascii.is_white ab_cd (ab_cd,String.Sub.stop ab_cd); eq ~rev:false ~sat:Char.Ascii.is_letter ab_cd (ab, _cd); eq ~rev:true ~sat:Char.Ascii.is_letter ab_cd (ab_, cd); eq ~rev:false ~sat:Char.Ascii.is_letter ~max:0 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~max:0 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ~sat:Char.Ascii.is_letter ~max:1 ab_cd (a, b_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~max:1 ab_cd (ab_c, d); eq ~rev:false ~sat:Char.Ascii.is_letter ~min:2 ~max:1 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~min:2 ~max:1 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ~sat:Char.Ascii.is_letter ~min:3 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~min:3 ab_cd (ab_cd, String.Sub.stop ab_cd); () let trim = test "String.Sub.trim" @@ fun () -> let drop_a c = c = 'a' in let base = "00aaaabcdaaaa00" in let aaaabcdaaaa = String.sub ~start:2 ~stop:13 base in let aaaabcd = String.sub ~start:2 ~stop:9 base in let bcdaaaa = String.sub ~start:6 ~stop:13 base in let aaaa = String.sub ~start:2 ~stop:6 base in eqs (String.Sub.trim (String.sub "\t abcd \r ")) "abcd"; eqs (String.Sub.trim aaaabcdaaaa) "aaaabcdaaaa"; eqs (String.Sub.trim ~drop:drop_a aaaabcdaaaa) "bcd"; eqs (String.Sub.trim ~drop:drop_a aaaabcd) "bcd"; eqs (String.Sub.trim ~drop:drop_a bcdaaaa) "bcd"; empty_pos (String.Sub.trim ~drop:drop_a aaaa) 4; empty_pos (String.Sub.trim (String.sub " ")) 2; () let cut = test "String.Sub.cut" @@ fun () -> let ppp = pp_option pp_pair in let eqo = eqs_pair_opt in let s s = String.sub ~start:1 ~stop:(1 + (String.length s)) (strf "\x00%s\x00" s) in let cut ?rev ~sep str = String.Sub.cut ?rev ~sep:(s sep) (s str) in app_invalid ~pp:ppp (cut ~sep:"") ""; app_invalid ~pp:ppp (cut ~sep:"") "123"; eqo (cut "," "") None; eqo (cut "," ",") (Some ("", "")); eqo (cut "," ",,") (Some ("", ",")); eqo (cut "," ",,,") (Some ("", ",,")); eqo (cut "," "123") None; eqo (cut "," ",123") (Some ("", "123")); eqo (cut "," "123,") (Some ("123", "")); eqo (cut "," "1,2,3") (Some ("1", "2,3")); eqo (cut "," " 1,2,3") (Some (" 1", "2,3")); eqo (cut "<>" "") None; eqo (cut "<>" "<>") (Some ("", "")); eqo (cut "<>" "<><>") (Some ("", "<>")); eqo (cut "<>" "<><><>") (Some ("", "<><>")); eqo (cut ~rev:true ~sep:"<>" "1") None; eqo (cut "<>" "123") None; eqo (cut "<>" "<>123") (Some ("", "123")); eqo (cut "<>" "123<>") (Some ("123", "")); eqo (cut "<>" "1<>2<>3") (Some ("1", "2<>3")); eqo (cut "<>" " 1<>2<>3") (Some (" 1", "2<>3")); eqo (cut "<>" ">>><>>>><>>>><>>>>") (Some (">>>", ">>><>>>><>>>>")); eqo (cut "<->" "<->>->") (Some ("", ">->")); eqo (cut ~rev:true ~sep:"<->" "<-") None; eqo (cut "aa" "aa") (Some ("", "")); eqo (cut "aa" "aaa") (Some ("", "a")); eqo (cut "aa" "aaaa") (Some ("", "aa")); eqo (cut "aa" "aaaaa") (Some ("", "aaa";)); eqo (cut "aa" "aaaaaa") (Some ("", "aaaa")); eqo (cut ~sep:"ab" "faaaa") None; eqo (String.Sub.cut ~sep:(String.sub "/") (String.sub ~start:2 "a/b/c")) (Some ("b", "c")); let rev = true in app_invalid ~pp:ppp (cut ~rev ~sep:"") ""; app_invalid ~pp:ppp (cut ~rev ~sep:"") "123"; eqo (cut ~rev ~sep:"," "") None; eqo (cut ~rev ~sep:"," ",") (Some ("", "")); eqo (cut ~rev ~sep:"," ",,") (Some (",", "")); eqo (cut ~rev ~sep:"," ",,,") (Some (",,", "")); eqo (cut ~rev ~sep:"," "123") None; eqo (cut ~rev ~sep:"," ",123") (Some ("", "123")); eqo (cut ~rev ~sep:"," "123,") (Some ("123", "")); eqo (cut ~rev ~sep:"," "1,2,3") (Some ("1,2", "3")); eqo (cut ~rev ~sep:"," "1,2,3 ") (Some ("1,2", "3 ")); eqo (cut ~rev ~sep:"<>" "") None; eqo (cut ~rev ~sep:"<>" "<>") (Some ("", "")); eqo (cut ~rev ~sep:"<>" "<><>") (Some ("<>", "")); eqo (cut ~rev ~sep:"<>" "<><><>") (Some ("<><>", "")); eqo (cut ~rev ~sep:"<>" "1") None; eqo (cut ~rev ~sep:"<>" "123") None; eqo (cut ~rev ~sep:"<>" "<>123") (Some ("", "123")); eqo (cut ~rev ~sep:"<>" "123<>") (Some ("123", "")); eqo (cut ~rev ~sep:"<>" "1<>2<>3") (Some ("1<>2", "3")); eqo (cut ~rev ~sep:"<>" "1<>2<>3 ") (Some ("1<>2", "3 ")); eqo (cut ~rev ~sep:"<>" ">>><>>>><>>>><>>>>") (Some (">>><>>>><>>>>", ">>>")); eqo (cut ~rev ~sep:"<->" "<->>->") (Some ("", ">->")); eqo (cut ~rev ~sep:"<->" "<-") None; eqo (cut ~rev ~sep:"aa" "aa") (Some ("", "")); eqo (cut ~rev ~sep:"aa" "aaa") (Some ("a", "")); eqo (cut ~rev ~sep:"aa" "aaaa") (Some ("aa", "")); eqo (cut ~rev ~sep:"aa" "aaaaa") (Some ("aaa", "";)); eqo (cut ~rev ~sep:"aa" "aaaaaa") (Some ("aaaa", "")); eqo (cut ~rev ~sep:"ab" "afaaaa") None; eqo (String.Sub.cut ~sep:(String.sub "/") (String.sub ~stop:3 "a/b/c")) (Some ("a", "b")); () let cuts = test "String.Sub.cuts" @@ fun () -> let ppl = pp_list String.Sub.dump in let eql subs l = let subs = List.map String.Sub.to_string subs in eq_list ~eq:String.equal ~pp:String.dump subs l in let s s = String.sub ~start:1 ~stop:(1 + (String.length s)) (strf "\x00%s\x00" s) in let cuts ?rev ?empty ~sep str = String.Sub.cuts ?rev ?empty ~sep:(s sep) (s str) in app_invalid ~pp:ppl (cuts ~sep:"") ""; app_invalid ~pp:ppl (cuts ~sep:"") "123"; eql (cuts ~empty:true ~sep:"," "") [""]; eql (cuts ~empty:false ~sep:"," "") []; eql (cuts ~empty:true ~sep:"," ",") [""; ""]; eql (cuts ~empty:false ~sep:"," ",") []; eql (cuts ~empty:true ~sep:"," ",,") [""; ""; ""]; eql (cuts ~empty:false ~sep:"," ",,") []; eql (cuts ~empty:true ~sep:"," ",,,") [""; ""; ""; ""]; eql (cuts ~empty:false ~sep:"," ",,,") []; eql (cuts ~empty:true ~sep:"," "123") ["123"]; eql (cuts ~empty:false ~sep:"," "123") ["123"]; eql (cuts ~empty:true ~sep:"," ",123") [""; "123"]; eql (cuts ~empty:false ~sep:"," ",123") ["123"]; eql (cuts ~empty:true ~sep:"," "123,") ["123"; ""]; eql (cuts ~empty:false ~sep:"," "123,") ["123";]; eql (cuts ~empty:true ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~empty:false ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~empty:true ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:false ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:true ~sep:"," ",1,2,,3,") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~empty:false ~sep:"," ",1,2,,3,") ["1"; "2"; "3";]; eql (cuts ~empty:true ~sep:"," ", 1, 2,, 3,") [""; " 1"; " 2"; ""; " 3"; ""]; eql (cuts ~empty:false ~sep:"," ", 1, 2,, 3,") [" 1"; " 2";" 3";]; eql (cuts ~empty:true ~sep:"<>" "") [""]; eql (cuts ~empty:false ~sep:"<>" "") []; eql (cuts ~empty:true ~sep:"<>" "<>") [""; ""]; eql (cuts ~empty:false ~sep:"<>" "<>") []; eql (cuts ~empty:true ~sep:"<>" "<><>") [""; ""; ""]; eql (cuts ~empty:false ~sep:"<>" "<><>") []; eql (cuts ~empty:true ~sep:"<>" "<><><>") [""; ""; ""; ""]; eql (cuts ~empty:false ~sep:"<>" "<><><>") []; eql (cuts ~empty:true ~sep:"<>" "123") [ "123" ]; eql (cuts ~empty:false ~sep:"<>" "123") [ "123" ]; eql (cuts ~empty:true ~sep:"<>" "<>123") [""; "123"]; eql (cuts ~empty:false ~sep:"<>" "<>123") ["123"]; eql (cuts ~empty:true ~sep:"<>" "123<>") ["123"; ""]; eql (cuts ~empty:false ~sep:"<>" "123<>") ["123"]; eql (cuts ~empty:true ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~empty:false ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~empty:true ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:false ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:true ~sep:"<>" "<>1<>2<><>3<>") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~empty:false ~sep:"<>" "<>1<>2<><>3<>") ["1"; "2";"3";]; eql (cuts ~empty:true ~sep:"<>" "<> 1<> 2<><> 3<>") [""; " 1"; " 2"; ""; " 3";""]; eql (cuts ~empty:false ~sep:"<>" "<> 1<> 2<><> 3<>")[" 1"; " 2"; " 3"]; eql (cuts ~empty:true ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~empty:false ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~empty:true ~sep:"<->" "<->>->") [""; ">->"]; eql (cuts ~empty:false ~sep:"<->" "<->>->") [">->"]; eql (cuts ~empty:true ~sep:"aa" "aa") [""; ""]; eql (cuts ~empty:false ~sep:"aa" "aa") []; eql (cuts ~empty:true ~sep:"aa" "aaa") [""; "a"]; eql (cuts ~empty:false ~sep:"aa" "aaa") ["a"]; eql (cuts ~empty:true ~sep:"aa" "aaaa") [""; ""; ""]; eql (cuts ~empty:false ~sep:"aa" "aaaa") []; eql (cuts ~empty:true ~sep:"aa" "aaaaa") [""; ""; "a"]; eql (cuts ~empty:false ~sep:"aa" "aaaaa") ["a"]; eql (cuts ~empty:true ~sep:"aa" "aaaaaa") [""; ""; ""; ""]; eql (cuts ~empty:false ~sep:"aa" "aaaaaa") []; let rev = true in app_invalid ~pp:ppl (cuts ~rev ~sep:"") ""; app_invalid ~pp:ppl (cuts ~rev ~sep:"") "123"; eql (cuts ~rev ~empty:true ~sep:"," "") [""]; eql (cuts ~rev ~empty:false ~sep:"," "") []; eql (cuts ~rev ~empty:true ~sep:"," ",") [""; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",") []; eql (cuts ~rev ~empty:true ~sep:"," ",,") [""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",,") []; eql (cuts ~rev ~empty:true ~sep:"," ",,,") [""; ""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",,,") []; eql (cuts ~rev ~empty:true ~sep:"," "123") ["123"]; eql (cuts ~rev ~empty:false ~sep:"," "123") ["123"]; eql (cuts ~rev ~empty:true ~sep:"," ",123") [""; "123"]; eql (cuts ~rev ~empty:false ~sep:"," ",123") ["123"]; eql (cuts ~rev ~empty:true ~sep:"," "123,") ["123"; ""]; eql (cuts ~rev ~empty:false ~sep:"," "123,") ["123";]; eql (cuts ~rev ~empty:true ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:false ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:false ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:true ~sep:"," ",1,2,,3,") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",1,2,,3,") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"," ", 1, 2,, 3,") [""; " 1"; " 2"; ""; " 3"; ""]; eql (cuts ~rev ~empty:false ~sep:"," ", 1, 2,, 3,") [" 1"; " 2"; " 3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "") [""]; eql (cuts ~rev ~empty:false ~sep:"<>" "") []; eql (cuts ~rev ~empty:true ~sep:"<>" "<>") [""; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<>") []; eql (cuts ~rev ~empty:true ~sep:"<>" "<><>") [""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<><>") []; eql (cuts ~rev ~empty:true ~sep:"<>" "<><><>") [""; ""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<><><>") []; eql (cuts ~rev ~empty:true ~sep:"<>" "123") [ "123" ]; eql (cuts ~rev ~empty:false ~sep:"<>" "123") [ "123" ]; eql (cuts ~rev ~empty:true ~sep:"<>" "<>123") [""; "123"]; eql (cuts ~rev ~empty:false ~sep:"<>" "<>123") ["123"]; eql (cuts ~rev ~empty:true ~sep:"<>" "123<>") ["123"; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "123<>") ["123";]; eql (cuts ~rev ~empty:true ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:false ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:false ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "<>1<>2<><>3<>") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<>1<>2<><>3<>") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "<> 1<> 2<><> 3<>") [""; " 1"; " 2"; ""; " 3";""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<> 1<> 2<><> 3<>") [" 1"; " 2"; " 3";]; eql (cuts ~rev ~empty:true ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~rev ~empty:false ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~rev ~empty:true ~sep:"<->" "<->>->") [""; ">->"]; eql (cuts ~rev ~empty:false ~sep:"<->" "<->>->") [">->"]; eql (cuts ~rev ~empty:true ~sep:"aa" "aa") [""; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aa") []; eql (cuts ~rev ~empty:true ~sep:"aa" "aaa") ["a"; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaa") ["a"]; eql (cuts ~rev ~empty:true ~sep:"aa" "aaaa") [""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaaa") []; eql (cuts ~rev ~empty:true ~sep:"aa" "aaaaa") ["a"; ""; "";]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaaaa") ["a";]; eql (cuts ~rev ~empty:true ~sep:"aa" "aaaaaa") [""; ""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaaaaa") []; () let fields = test "String.Sub.fields" @@ fun () -> let eql subs l = let subs = List.map String.Sub.to_string subs in eq_list ~eq:String.equal ~pp:String.dump subs l in let s s = String.sub ~start:1 ~stop:(1 + (String.length s)) (strf "\x00%s\x00" s) in let fields ?empty ?is_sep str = String.Sub.fields ?empty ?is_sep (s str) in let is_a c = c = 'a' in eql (fields ~empty:true "a") ["a"]; eql (fields ~empty:false "a") ["a"]; eql (fields ~empty:true "abc") ["abc"]; eql (fields ~empty:false "abc") ["abc"]; eql (fields ~empty:true ~is_sep:is_a "bcdf") ["bcdf"]; eql (fields ~empty:false ~is_sep:is_a "bcdf") ["bcdf"]; eql (fields ~empty:true "") [""]; eql (fields ~empty:false "") []; eql (fields ~empty:true "\n\r") ["";"";""]; eql (fields ~empty:false "\n\r") []; eql (fields ~empty:true " \n\rabc") ["";"";"";"abc"]; eql (fields ~empty:false " \n\rabc") ["abc"]; eql (fields ~empty:true " \n\racd de") ["";"";"";"acd";"de"]; eql (fields ~empty:false " \n\racd de") ["acd";"de"]; eql (fields ~empty:true " \n\racd de ") ["";"";"";"acd";"de";""]; eql (fields ~empty:false " \n\racd de ") ["acd";"de"]; eql (fields ~empty:true "\n\racd\nde \r") ["";"";"acd";"de";"";""]; eql (fields ~empty:false "\n\racd\nde \r") ["acd";"de"]; eql (fields ~empty:true ~is_sep:is_a "") [""]; eql (fields ~empty:false ~is_sep:is_a "") []; eql (fields ~empty:true ~is_sep:is_a "abaac aaa") ["";"b";"";"c ";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "abaac aaa") ["b"; "c "]; eql (fields ~empty:true ~is_sep:is_a "aaaa") ["";"";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "aaaa") []; eql (fields ~empty:true ~is_sep:is_a "aaaa ") ["";"";"";"";" "]; eql (fields ~empty:false ~is_sep:is_a "aaaa ") [" "]; eql (fields ~empty:true ~is_sep:is_a "aaaab") ["";"";"";"";"b"]; eql (fields ~empty:false ~is_sep:is_a "aaaab") ["b"]; eql (fields ~empty:true ~is_sep:is_a "baaaa") ["b";"";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "baaaa") ["b"]; eql (fields ~empty:true ~is_sep:is_a "abaaaa") ["";"b";"";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "abaaaa") ["b"]; eql (fields ~empty:true ~is_sep:is_a "aba") ["";"b";""]; eql (fields ~empty:false ~is_sep:is_a "aba") ["b"]; eql (fields ~empty:false "tokenize me please") ["tokenize"; "me"; "please"]; () (* Traversing *) let find = test "String.Sub.find" @@ fun () -> let abcbd = "abcbd" in let empty = String.sub ~start:3 ~stop:3 abcbd in let a = String.sub ~start:0 ~stop:1 abcbd in let ab = String.sub ~start:0 ~stop:2 abcbd in let c = String.sub ~start:2 ~stop:3 abcbd in let b0 = String.sub ~start:1 ~stop:2 abcbd in let b1 = String.sub ~start:3 ~stop:4 abcbd in let abcbd = String.sub abcbd in let eq = eq_option ~eq:String.Sub.equal ~pp:String.Sub.dump_raw in eq (String.Sub.find (fun c -> c = 'b') empty) None; eq (String.Sub.find ~rev:true (fun c -> c = 'b') empty) None; eq (String.Sub.find (fun c -> c = 'b') a) None; eq (String.Sub.find ~rev:true (fun c -> c = 'b') a) None; eq (String.Sub.find (fun c -> c = 'b') c) None; eq (String.Sub.find ~rev:true (fun c -> c = 'b') c) None; eq (String.Sub.find (fun c -> c = 'b') abcbd) (Some b0); eq (String.Sub.find ~rev:true (fun c -> c = 'b') abcbd) (Some b1); eq (String.Sub.find (fun c -> c = 'b') ab) (Some b0); eq (String.Sub.find ~rev:true (fun c -> c = 'b') ab) (Some b0); () let find_sub = test "String.Sub.find_sub" @@ fun () -> let abcbd = "abcbd" in let empty = String.sub ~start:3 ~stop:3 abcbd in let ab = String.sub ~start:0 ~stop:2 abcbd in let b0 = String.sub ~start:1 ~stop:2 abcbd in let b1 = String.sub ~start:3 ~stop:4 abcbd in let abcbd = String.sub abcbd in let eq = eq_option ~eq:String.Sub.equal ~pp:String.Sub.dump_raw in eq (String.Sub.find_sub ~sub:ab empty) None; eq (String.Sub.find_sub ~rev:true ~sub:ab empty) None; eq (String.Sub.find_sub ~sub:(String.sub "") empty) (Some empty); eq (String.Sub.find_sub ~rev:true ~sub:(String.sub "") empty) (Some empty); eq (String.Sub.find_sub ~sub:ab abcbd) (Some ab); eq (String.Sub.find_sub ~rev:true ~sub:ab abcbd) (Some ab); eq (String.Sub.find_sub ~sub:empty abcbd) (Some (String.Sub.start abcbd)); eq (String.Sub.find_sub ~rev:true ~sub:empty abcbd) (Some (String.Sub.stop abcbd)); eq (String.Sub.find_sub ~sub:(String.sub "b") abcbd) (Some b0); eq (String.Sub.find_sub ~rev:true ~sub:(String.sub "b") abcbd) (Some b1); eq (String.Sub.find_sub ~sub:b1 ab) (Some b0); eq (String.Sub.find_sub ~rev:true ~sub:b1 ab) (Some b0); () let map = test "String.Sub.map[i]" @@ fun () -> let next_letter c = Char.(of_byte @@ to_int c + 1) in let base = "i34abcdbbb" in let abcd = String.Sub.v ~start:3 ~stop:7 base in let empty = String.Sub.v ~start:2 ~stop:2 base in eqs (String.Sub.map (fun c -> fail "invoked"; c) empty) ""; eqs (String.Sub.map (fun c -> c) abcd) "abcd"; eqs (String.Sub.map next_letter abcd) "bcde"; eq_str String.Sub.(base_string (map next_letter abcd)) "bcde"; eqs (String.Sub.mapi (fun _ c -> fail "invoked"; c) empty) ""; eqs (String.Sub.mapi (fun i c -> Char.(of_byte @@ to_int c + i)) abcd) "aceg"; () let fold = test "String.Sub.fold_{left,right}" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "ab" in let abc = String.Sub.v ~start:3 ~stop:6 "i34abcdbbb" in let eql = eq_list ~eq:(=) ~pp:pp_char in String.Sub.fold_left (fun _ _ -> fail "invoked") () empty; eql (String.Sub.fold_left (fun acc c -> c :: acc) [] empty) []; eql (String.Sub.fold_left (fun acc c -> c :: acc) [] abc) ['c';'b';'a']; String.Sub.fold_right (fun _ _ -> fail "invoked") empty (); eql (String.Sub.fold_right (fun c acc -> c :: acc) empty []) []; eql (String.Sub.fold_right (fun c acc -> c :: acc) abc []) ['a';'b';'c']; () let iter = test "String.Sub.iter[i]" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "ab" in let abc = String.Sub.v ~start:3 ~stop:6 "i34abcdbbb" in String.Sub.iter (fun _ -> fail "invoked") empty; String.Sub.iteri (fun _ _ -> fail "invoked") empty; (let i = ref 0 in String.Sub.iter (fun c -> eq_char (String.Sub.get abc !i) c; incr i) abc); String.Sub.iteri (fun i c -> eq_char (String.Sub.get abc i) c) abc; () (* Suite *) let suite = suite "Base String functions" [ misc; head; to_string; start; stop; tail; base; extend; reduce; extent; overlap; append; concat; is_empty; is_prefix; is_infix; is_suffix; for_all; exists; same_base; equal_bytes; compare_bytes; equal; compare; with_range; with_index_range; span; trim; cut; cuts; fields; find; find_sub; map; fold; iter; ] --------------------------------------------------------------------------- Copyright ( c ) 2015 The astring programmers 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 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) 2015 The astring programmers 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. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/astring/ec7a266a3a680e5d246689855c639da53d713428/test/test_sub.ml
ocaml
Base functions Stretching substrings Appending substrings. Predicates Extracting substrings Traversing Suite
--------------------------------------------------------------------------- Copyright ( c ) 2015 The astring programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2015 The astring programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open Testing open Astring let pp_str_pair ppf (a, b) = Format.fprintf ppf "@[<1>(%a,%a)@]" String.dump a String.dump b let pp_pair ppf (a, b) = Format.fprintf ppf "@[<1>(%a,%a)@]" String.Sub.dump a String.Sub.dump b let eq_pair (l0, r0) (l1, r1) = String.Sub.equal l0 l1 && String.Sub.equal r0 r1 let eq_sub = eq ~eq:String.Sub.equal ~pp:String.Sub.dump let eq_sub_raw = eq ~eq:String.Sub.equal ~pp:String.Sub.dump_raw let eqs sub s = eq_str (String.Sub.to_string sub) s let eqb sub s = eq_str (String.Sub.base_string sub) s let eqs_opt sub os = let sub_to_str = function | Some sub -> Some (String.Sub.to_string sub) | None -> None in eq_option ~eq:(=) ~pp:pp_str (sub_to_str sub) os let eqs_pair_opt subs_pair pair = let subs_to_str = function | None -> None | Some (sub, sub') -> Some (String.Sub.to_string sub, String.Sub.to_string sub') in eq_option ~eq:(=) ~pp:pp_str_pair (subs_to_str subs_pair) pair let empty_pos s pos = eq_int (String.Sub.length s) 0; eq_int (String.Sub.start_pos s) pos let misc = test "String.Sub misc. base functions" @@ fun () -> eqs String.Sub.empty ""; eqs (String.Sub.v "abc") "abc"; eqs (String.Sub.v ~start:0 ~stop:1 "abc") "a"; eqs (String.Sub.v ~start:1 ~stop:2 "abc") "b"; eqs (String.Sub.v ~start:1 ~stop:3 "abc") "bc"; eqs (String.Sub.v ~start:2 ~stop:3 "abc") "c"; eqs (String.Sub.v ~start:3 ~stop:3 "abc") ""; let sub = String.Sub.v ~start:2 ~stop:3 "abc" in eq_int (String.Sub.start_pos sub) 2; eq_int (String.Sub.stop_pos sub) 3; eq_int (String.Sub.length sub) 1; app_invalid ~pp:pp_char (String.Sub.get sub) 3; app_invalid ~pp:pp_char (String.Sub.get sub) 2; app_invalid ~pp:pp_char (String.Sub.get sub) 1; eq_char (String.Sub.get sub 0) 'c'; eq_int (String.Sub.get_byte sub 0) 0x63; eqb (String.Sub.(rebase (v ~stop:2 "abc"))) "ab"; () let head = test "String.[get_]head" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "abc" in let bc = String.Sub.v ~start:1 ~stop:3 "abc" in let eq_ochar = eq_option ~eq:(=) ~pp:pp_char in eq_ochar (String.Sub.head empty) None; eq_ochar (String.Sub.head ~rev:true empty) None; eq_ochar (String.Sub.head bc) (Some 'b'); eq_ochar (String.Sub.head ~rev:true bc) (Some 'c'); eq_char (String.Sub.get_head bc) 'b'; eq_char (String.Sub.get_head ~rev:true bc) 'c'; app_invalid ~pp:pp_char String.Sub.get_head empty; () let to_string = test "String.Sub.to_string" @@ fun () -> let no_alloc s = let r = String.Sub.to_string s in eq_bool (r == (String.Sub.base_string s) || r == String.empty) true in no_alloc (String.Sub.v ~start:0 ~stop:0 "abc"); eq_str (String.Sub.(to_string (v ~start:0 ~stop:1 "abc"))) "a"; eq_str (String.Sub.(to_string (v ~start:0 ~stop:2 "abc"))) "ab"; no_alloc (String.Sub.v ~start:0 ~stop:3 "abc"); no_alloc (String.Sub.v ~start:1 ~stop:1 "abc"); eq_str (String.Sub.(to_string (v ~start:1 ~stop:2 "abc"))) "b"; eq_str (String.Sub.(to_string (v ~start:1 ~stop:3 "abc"))) "bc"; no_alloc (String.Sub.v ~start:2 ~stop:2 "abc"); eq_str (String.Sub.(to_string (v ~start:2 ~stop:3 "abc"))) "c"; no_alloc (String.Sub.v ~start:3 ~stop:3 "abc"); () let start = test "String.Sub.start" @@ fun () -> empty_pos String.Sub.(start @@ v "") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:0 "abc") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:1 "abc") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:2 "abc") 0; empty_pos String.Sub.(start @@ v ~start:0 ~stop:3 "abc") 0; empty_pos String.Sub.(start @@ v ~start:1 ~stop:1 "abc") 1; empty_pos String.Sub.(start @@ v ~start:1 ~stop:2 "abc") 1; empty_pos String.Sub.(start @@ v ~start:1 ~stop:3 "abc") 1; empty_pos String.Sub.(start @@ v ~start:2 ~stop:2 "abc") 2; empty_pos String.Sub.(start @@ v ~start:2 ~stop:3 "abc") 2; empty_pos String.Sub.(start @@ v ~start:3 ~stop:3 "abc") 3; () let stop = test "String.Sub.stop" @@ fun () -> empty_pos String.Sub.(stop @@ v "") 0; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:0 "abc") 0; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:1 "abc") 1; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:2 "abc") 2; empty_pos String.Sub.(stop @@ v ~start:0 ~stop:3 "abc") 3; empty_pos String.Sub.(stop @@ v ~start:1 ~stop:1 "abc") 1; empty_pos String.Sub.(stop @@ v ~start:1 ~stop:2 "abc") 2; empty_pos String.Sub.(stop @@ v ~start:1 ~stop:3 "abc") 3; empty_pos String.Sub.(stop @@ v ~start:2 ~stop:2 "abc") 2; empty_pos String.Sub.(stop @@ v ~start:2 ~stop:3 "abc") 3; empty_pos String.Sub.(stop @@ v ~start:3 ~stop:3 "abc") 3; () let tail = test "String.Sub.tail" @@ fun () -> empty_pos String.Sub.(tail @@ v "") 0; empty_pos String.Sub.(tail @@ v ~start:0 ~stop:0 "abc") 0; empty_pos String.Sub.(tail @@ v ~start:0 ~stop:1 "abc") 1; eqs String.Sub.(tail @@ v ~start:0 ~stop:2 "abc") "b"; eqs String.Sub.(tail @@ v ~start:0 ~stop:3 "abc") "bc"; empty_pos String.Sub.(tail @@ v ~start:1 ~stop:1 "abc") 1; empty_pos String.Sub.(tail @@ v ~start:1 ~stop:2 "abc") 2; eqs String.Sub.(tail @@ v ~start:1 ~stop:3 "abc") "c"; empty_pos String.Sub.(tail @@ v ~start:2 ~stop:2 "abc") 2; empty_pos String.Sub.(tail @@ v ~start:2 ~stop:3 "abc") 3; empty_pos String.Sub.(tail @@ v ~start:3 ~stop:3 "abc") 3; () let base = test "String.Sub.base" @@ fun () -> eqs String.Sub.(base @@ v "") ""; eqs String.Sub.(base @@ v ~start:0 ~stop:0 "abc") "abc"; eqs String.Sub.(base @@ v ~start:0 ~stop:1 "abc") "abc"; eqs String.Sub.(base @@ v ~start:0 ~stop:2 "abc") "abc"; eqs String.Sub.(base @@ v ~start:0 ~stop:3 "abc") "abc"; eqs String.Sub.(base @@ v ~start:1 ~stop:1 "abc") "abc"; eqs String.Sub.(base @@ v ~start:1 ~stop:2 "abc") "abc"; eqs String.Sub.(base @@ v ~start:1 ~stop:3 "abc") "abc"; eqs String.Sub.(base @@ v ~start:2 ~stop:2 "abc") "abc"; eqs String.Sub.(base @@ v ~start:2 ~stop:3 "abc") "abc"; eqs String.Sub.(base @@ v ~start:3 ~stop:3 "abc") "abc"; () let extend = test "String.Sub.extend" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "abcdefg" in let abcd = String.Sub.v ~start:0 ~stop:4 "abcdefg" in let cd = String.Sub.v ~start:2 ~stop:4 "abcdefg" in app_invalid ~pp:String.Sub.pp (fun s -> String.Sub.extend ~max:(-1) s) abcd; eqs (String.Sub.extend empty) "cdefg"; eqs (String.Sub.extend ~rev:true empty) "ab"; eqs (String.Sub.extend ~max:2 empty) "cd"; eqs (String.Sub.extend ~sat:(fun c -> c < 'f') empty) "cde"; eqs (String.Sub.extend ~rev:true ~max:1 empty) "b"; eqs (String.Sub.extend abcd) "abcdefg"; eqs (String.Sub.extend ~max:2 abcd) "abcdef"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c < 'e') abcd) "abcd"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c < 'f') abcd) "abcde"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c < 'g') abcd) "abcdef"; eqs (String.Sub.extend ~rev:true abcd) "abcd"; eqs (String.Sub.extend ~rev:true ~max:2 ~sat:(fun c -> c > 'a') cd) "bcd"; eqs (String.Sub.extend ~rev:true ~max:2 ~sat:(fun c -> c >= 'a') cd) "abcd"; eqs (String.Sub.extend ~rev:true ~max:1 ~sat:(fun c -> c >= 'a') cd) "bcd"; eqs (String.Sub.extend ~max:2 ~sat:(fun c -> c >= 'a') cd) "cdef"; eqs (String.Sub.extend ~sat:(fun c -> c >= 'a') cd) "cdefg"; () let reduce = test "String.Sub.reduce" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "abcdefg" in let abcd = String.Sub.v ~start:0 ~stop:4 "abcdefg" in let cd = String.Sub.v ~start:2 ~stop:4 "abcdefg" in app_invalid ~pp:String.Sub.pp (fun s -> String.Sub.reduce ~max:(-1) s) abcd; empty_pos (String.Sub.reduce ~rev:false empty) 2; empty_pos (String.Sub.reduce ~rev:true empty) 2; empty_pos (String.Sub.reduce ~rev:false ~max:2 empty) 2; empty_pos (String.Sub.reduce ~rev:true ~max:2 empty) 2; empty_pos (String.Sub.reduce ~rev:false ~sat:(fun c -> c < 'f') empty) 2; empty_pos (String.Sub.reduce ~rev:true ~sat:(fun c -> c < 'f') empty) 2; empty_pos (String.Sub.reduce ~rev:false ~max:1 empty) 2; empty_pos (String.Sub.reduce ~rev:true ~max:1 empty) 2; empty_pos (String.Sub.reduce ~rev:false abcd) 0; empty_pos (String.Sub.reduce ~rev:true abcd) 4; eqs (String.Sub.reduce ~rev:false ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:true ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:false ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:true ~max:0 abcd) "abcd"; eqs (String.Sub.reduce ~rev:false ~max:2 abcd) "ab"; eqs (String.Sub.reduce ~rev:true ~max:2 abcd) "cd"; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c < 'c') abcd) "abcd"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c < 'c') abcd) "cd"; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c > 'b') abcd) "ab"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c < 'b') abcd) "bcd"; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c > 'a') abcd) "ab"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c < 'a') abcd) "abcd"; empty_pos (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c > 'a') cd) 2; empty_pos (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c > 'a') cd) 4; eqs (String.Sub.reduce ~rev:false ~max:2 ~sat:(fun c -> c >= 'd') cd) "c"; eqs (String.Sub.reduce ~rev:true ~max:2 ~sat:(fun c -> c >= 'd') cd) "cd"; eqs (String.Sub.reduce ~rev:false ~max:1 ~sat:(fun c -> c > 'c') cd) "c"; eqs (String.Sub.reduce ~rev:true ~max:1 ~sat:(fun c -> c > 'c') cd) "cd"; eqs (String.Sub.reduce ~rev:false ~sat:(fun c -> c > 'c') cd) "c"; eqs (String.Sub.reduce ~rev:true ~sat:(fun c -> c > 'c') cd) "cd"; () let extent = test "String.Sub.extent" @@ fun () -> app_invalid ~pp:String.Sub.dump_raw String.Sub.(extent (v "a")) (String.Sub.(v "b")); let abcd = "abcd" in let e0 = String.Sub.v ~start:0 ~stop:0 abcd in let a = String.Sub.v ~start:0 ~stop:1 abcd in let ab = String.Sub.v ~start:0 ~stop:2 abcd in let abc = String.Sub.v ~start:0 ~stop:3 abcd in let _abcd = String.Sub.v ~start:0 ~stop:4 abcd in let e1 = String.Sub.v ~start:1 ~stop:1 abcd in let b = String.Sub.v ~start:1 ~stop:2 abcd in let bc = String.Sub.v ~start:1 ~stop:3 abcd in let bcd = String.Sub.v ~start:1 ~stop:4 abcd in let e2 = String.Sub.v ~start:2 ~stop:2 abcd in let c = String.Sub.v ~start:2 ~stop:3 abcd in let cd = String.Sub.v ~start:2 ~stop:4 abcd in let e3 = String.Sub.v ~start:3 ~stop:3 abcd in let d = String.Sub.v ~start:3 ~stop:4 abcd in let e4 = String.Sub.v ~start:4 ~stop:4 abcd in empty_pos (String.Sub.extent e0 e0) 0; eqs (String.Sub.extent e0 e1) "a"; eqs (String.Sub.extent e1 e0) "a"; eqs (String.Sub.extent e0 e2) "ab"; eqs (String.Sub.extent e2 e0) "ab"; eqs (String.Sub.extent e0 e3) "abc"; eqs (String.Sub.extent e3 e0) "abc"; eqs (String.Sub.extent e0 e4) "abcd"; eqs (String.Sub.extent e4 e0) "abcd"; empty_pos (String.Sub.extent e1 e1) 1; eqs (String.Sub.extent e1 e2) "b"; eqs (String.Sub.extent e2 e1) "b"; eqs (String.Sub.extent e1 e3) "bc"; eqs (String.Sub.extent e3 e1) "bc"; eqs (String.Sub.extent e1 e4) "bcd"; eqs (String.Sub.extent e4 e1) "bcd"; empty_pos (String.Sub.extent e2 e2) 2; eqs (String.Sub.extent e2 e3) "c"; eqs (String.Sub.extent e3 e2) "c"; eqs (String.Sub.extent e2 e4) "cd"; eqs (String.Sub.extent e4 e2) "cd"; empty_pos (String.Sub.extent e3 e3) 3; eqs (String.Sub.extent e3 e4) "d"; eqs (String.Sub.extent e4 e3) "d"; empty_pos (String.Sub.extent e4 e4) 4; eqs (String.Sub.extent a d) "abcd"; eqs (String.Sub.extent d a) "abcd"; eqs (String.Sub.extent b d) "bcd"; eqs (String.Sub.extent d b) "bcd"; eqs (String.Sub.extent c cd) "cd"; eqs (String.Sub.extent cd c) "cd"; eqs (String.Sub.extent e0 _abcd) "abcd"; eqs (String.Sub.extent _abcd e0) "abcd"; eqs (String.Sub.extent ab c) "abc"; eqs (String.Sub.extent c ab) "abc"; eqs (String.Sub.extent bc c) "bc"; eqs (String.Sub.extent c bc) "bc"; eqs (String.Sub.extent abc d) "abcd"; eqs (String.Sub.extent d abc) "abcd"; eqs (String.Sub.extent d bcd) "bcd"; eqs (String.Sub.extent bcd d) "bcd"; () let overlap = test "String.Sub.overlap" @@ fun () -> let empty_pos sub pos = match sub with | None -> fail "no sub" | Some sub -> empty_pos sub pos in app_invalid ~pp:String.Sub.dump_raw String.Sub.(extent (v "a")) (String.Sub.(v "b")); let abcd = "abcd" in let e0 = String.Sub.v ~start:0 ~stop:0 abcd in let a = String.Sub.v ~start:0 ~stop:1 abcd in let ab = String.Sub.v ~start:0 ~stop:2 abcd in let abc = String.Sub.v ~start:0 ~stop:3 abcd in let _abcd = String.Sub.v ~start:0 ~stop:4 abcd in let e1 = String.Sub.v ~start:1 ~stop:1 abcd in let b = String.Sub.v ~start:1 ~stop:2 abcd in let bc = String.Sub.v ~start:1 ~stop:3 abcd in let bcd = String.Sub.v ~start:1 ~stop:4 abcd in let e2 = String.Sub.v ~start:2 ~stop:2 abcd in let c = String.Sub.v ~start:2 ~stop:3 abcd in let cd = String.Sub.v ~start:2 ~stop:4 abcd in let e3 = String.Sub.v ~start:3 ~stop:3 abcd in let d = String.Sub.v ~start:3 ~stop:4 abcd in let e4 = String.Sub.v ~start:4 ~stop:4 abcd in empty_pos (String.Sub.overlap e0 a) 0; empty_pos (String.Sub.overlap a e0) 0; eqs_opt (String.Sub.overlap e0 b) None; eqs_opt (String.Sub.overlap b e0) None; empty_pos (String.Sub.overlap a b) 1; empty_pos (String.Sub.overlap b a) 1; eqs_opt (String.Sub.overlap a a) (Some "a"); eqs_opt (String.Sub.overlap a ab) (Some "a"); eqs_opt (String.Sub.overlap ab ab) (Some "ab"); eqs_opt (String.Sub.overlap ab abc) (Some "ab"); eqs_opt (String.Sub.overlap abc ab) (Some "ab"); eqs_opt (String.Sub.overlap b abc) (Some "b"); eqs_opt (String.Sub.overlap abc b) (Some "b"); empty_pos (String.Sub.overlap abc e3) 3; empty_pos (String.Sub.overlap e3 abc) 3; eqs_opt (String.Sub.overlap ab bc) (Some "b"); eqs_opt (String.Sub.overlap bc ab) (Some "b"); eqs_opt (String.Sub.overlap bcd bc) (Some "bc"); eqs_opt (String.Sub.overlap bc bcd) (Some "bc"); eqs_opt (String.Sub.overlap bcd d) (Some "d"); eqs_opt (String.Sub.overlap d bcd) (Some "d"); eqs_opt (String.Sub.overlap bcd cd) (Some "cd"); eqs_opt (String.Sub.overlap cd bcd) (Some "cd"); eqs_opt (String.Sub.overlap bcd c) (Some "c"); eqs_opt (String.Sub.overlap c bcd) (Some "c"); empty_pos (String.Sub.overlap e2 bcd) 2; empty_pos (String.Sub.overlap bcd e2) 2; empty_pos (String.Sub.overlap bcd e3) 3; empty_pos (String.Sub.overlap e3 bcd) 3; empty_pos (String.Sub.overlap bcd e4) 4; empty_pos (String.Sub.overlap e4 bcd) 4; empty_pos (String.Sub.overlap e1 e1) 1; eqs_opt (String.Sub.overlap e0 bcd) None; () let append = test "String.Sub.append" @@ fun () -> let no_allocl s s' = eq_bool (String.Sub.(base_string @@ append s s') == String.Sub.(base_string s)) true in let no_allocr s s' = eq_bool (String.Sub.(base_string @@ append s s') == String.Sub.(base_string s')) true in no_allocl String.Sub.empty String.Sub.empty; no_allocr String.Sub.empty String.Sub.empty; no_allocl (String.Sub.v "bla") (String.Sub.v ~start:0 ~stop:0 "abcd"); no_allocr (String.Sub.v ~start:1 ~stop:1 "b") (String.Sub.v "bli"); let a = String.sub_with_index_range ~first:0 ~last:0 "abcd" in let ab = String.sub_with_index_range ~first:0 ~last:1 "abcd" in let cd = String.sub_with_index_range ~first:2 ~last:3 "abcd" in let empty = String.Sub.v ~start:4 ~stop:4 "abcd" in eqb (String.Sub.append a empty) "a"; eqb (String.Sub.append empty a) "a"; eqb (String.Sub.append ab empty) "ab"; eqb (String.Sub.append empty ab) "ab"; eqb (String.Sub.append ab cd) "abcd"; eqb (String.Sub.append cd ab) "cdab"; () let concat = test "String.Sub.concat" @@ fun () -> let dash = String.sub_with_range ~first:2 ~len:1 "ab-d" in let ddash = String.sub_with_range ~first:1 ~len:2 "a--d" in let empty = String.sub_with_range ~first:2 ~len:0 "ab-d" in let no_alloc ?sep s = let r = String.Sub.(base_string (concat ?sep [s])) in eq_bool (r == String.Sub.base_string s || r == String.empty) true in no_alloc empty; no_alloc (String.Sub.v "hey"); no_alloc ~sep:empty empty; no_alloc ~sep:dash empty; no_alloc ~sep:empty (String.Sub.v "abc"); no_alloc ~sep:dash (String.Sub.v "abc"); let sempty = String.Sub.v ~start:2 ~stop:2 "abc" in let a = String.Sub.v ~start:2 ~stop:3 "kka" in let b = String.Sub.v ~start:1 ~stop:2 "ubd" in let c = String.Sub.v ~start:0 ~stop:1 "cdd" in let ab = String.Sub.v ~start:1 ~stop:3 "gabi" in let abc = String.Sub.v ~start:5 ~stop:8 "zuuuuabcbb" in eqb (String.Sub.concat ~sep:empty []) ""; eqb (String.Sub.concat ~sep:empty [sempty]) ""; eqb (String.Sub.concat ~sep:empty [sempty;sempty]) ""; eqb (String.Sub.concat ~sep:empty [a;b;]) "ab"; eqb (String.Sub.concat ~sep:empty [a;b;sempty;c]) "abc"; eqb (String.Sub.concat ~sep:dash []) ""; eqb (String.Sub.concat ~sep:dash [sempty]) ""; eqb (String.Sub.concat ~sep:dash [a]) "a"; eqb (String.Sub.concat ~sep:dash [a;sempty]) "a-"; eqb (String.Sub.concat ~sep:dash [sempty;a]) "-a"; eqb (String.Sub.concat ~sep:dash [sempty;a;sempty]) "-a-"; eqb (String.Sub.concat ~sep:dash [a;b;c]) "a-b-c"; eqb (String.Sub.concat ~sep:ddash [a;b;c]) "a--b--c"; eqb (String.Sub.concat ~sep:ab [a;b;c]) "aabbabc"; eqb (String.Sub.concat ~sep:ab [abc;b;c]) "abcabbabc"; () let is_empty = test "String.Sub.is_empty" @@ fun () -> eq_bool (String.Sub.is_empty (String.Sub.v "")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:4 ~stop:4 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:0 "huiy")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:1 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:2 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:3 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:0 ~stop:4 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:1 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:2 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:3 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:1 ~stop:4 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:2 ~stop:2 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:2 ~stop:3 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:3 ~stop:3 "abcd")) true; eq_bool (String.Sub.is_empty (String.Sub.v ~start:3 ~stop:4 "huiy")) false; eq_bool (String.Sub.is_empty (String.Sub.v ~start:4 ~stop:4 "huiy")) true; () let is_prefix = test "String.Sub.is_prefix" @@ fun () -> let empty = String.sub_with_range ~first:3 ~len:0 "ugoadfj" in let sempty = String.sub_with_range ~first:4 ~len:0 "dfkdjf" in let habla = String.sub_with_range ~first:2 ~len:5 "abhablablu" in let h = String.sub_with_range ~first:0 ~len:1 "hadfdffdf" in let ha = String.sub_with_range ~first:0 ~len:2 "hadfdffdf" in let hab = String.sub_with_range ~first:3 ~len:3 "hadhabdffdf" in let abla = String.sub_with_range ~first:1 ~len:4 "iabla" in eqs empty ""; eqs sempty ""; eqs habla "habla"; eqs h "h"; eqs ha "ha"; eqs hab "hab"; eqs abla "abla"; eq_bool (String.Sub.is_prefix ~affix:empty sempty) true; eq_bool (String.Sub.is_prefix ~affix:empty habla) true; eq_bool (String.Sub.is_prefix ~affix:ha sempty) false; eq_bool (String.Sub.is_prefix ~affix:ha h) false; eq_bool (String.Sub.is_prefix ~affix:ha ha) true; eq_bool (String.Sub.is_prefix ~affix:ha hab) true; eq_bool (String.Sub.is_prefix ~affix:ha habla) true; eq_bool (String.Sub.is_prefix ~affix:ha abla) false; () let is_infix = test "String.Sub.is_infix" @@ fun () -> let empty = String.sub_with_range ~first:1 ~len:0 "ugoadfj" in let sempty = String.sub_with_range ~first:2 ~len:0 "dfkdjf" in let asdf = String.sub_with_range ~first:1 ~len:4 "aasdflablu" in let a = String.sub_with_range ~first:2 ~len:1 "cda" in let h = String.sub_with_range ~first:0 ~len:1 "h" in let ha = String.sub_with_range ~first:1 ~len:2 "uhadfdffdf" in let ah = String.sub_with_range ~first:0 ~len:2 "ah" in let aha = String.sub_with_range ~first:2 ~len:3 "aaaha" in let haha = String.sub_with_range ~first:1 ~len:4 "ahaha" in let hahb = String.sub_with_range ~first:0 ~len:4 "hahbdfdf" in let blhahb = String.sub_with_range ~first:0 ~len:6 "blhahbdfdf" in let blha = String.sub_with_range ~first:1 ~len:4 "fblhahbdfdf" in let blh = String.sub_with_range ~first:1 ~len:3 "fblhahbdfdf" in eqs asdf "asdf"; eqs ha "ha"; eqs h "h"; eqs a "a"; eqs aha "aha"; eqs haha "haha"; eqs hahb "hahb"; eqs blhahb "blhahb"; eqs blha "blha"; eqs blh "blh"; eq_bool (String.Sub.is_infix ~affix:empty sempty) true; eq_bool (String.Sub.is_infix ~affix:empty asdf) true; eq_bool (String.Sub.is_infix ~affix:empty ha) true; eq_bool (String.Sub.is_infix ~affix:ha sempty) false; eq_bool (String.Sub.is_infix ~affix:ha a) false; eq_bool (String.Sub.is_infix ~affix:ha h) false; eq_bool (String.Sub.is_infix ~affix:ha ah) false; eq_bool (String.Sub.is_infix ~affix:ha ha) true; eq_bool (String.Sub.is_infix ~affix:ha aha) true; eq_bool (String.Sub.is_infix ~affix:ha haha) true; eq_bool (String.Sub.is_infix ~affix:ha hahb) true; eq_bool (String.Sub.is_infix ~affix:ha blhahb) true; eq_bool (String.Sub.is_infix ~affix:ha blha) true; eq_bool (String.Sub.is_infix ~affix:ha blh) false; () let is_suffix = test "String.Sub.is_suffix" @@ fun () -> let empty = String.sub_with_range ~first:1 ~len:0 "ugoadfj" in let sempty = String.sub_with_range ~first:2 ~len:0 "dfkdjf" in let asdf = String.sub_with_range ~first:1 ~len:4 "aasdflablu" in let ha = String.sub_with_range ~first:1 ~len:2 "uhadfdffdf" in let h = String.sub_with_range ~first:0 ~len:1 "h" in let a = String.sub_with_range ~first:2 ~len:1 "cda" in let ah = String.sub_with_range ~first:0 ~len:2 "ah" in let aha = String.sub_with_range ~first:2 ~len:3 "aaaha" in let haha = String.sub_with_range ~first:1 ~len:4 "ahaha" in let hahb = String.sub_with_range ~first:0 ~len:4 "hahbdfdf" in eqs asdf "asdf"; eqs ha "ha"; eqs h "h"; eqs a "a"; eqs aha "aha"; eqs haha "haha"; eqs hahb "hahb"; eq_bool (String.Sub.is_suffix ~affix:empty sempty) true; eq_bool (String.Sub.is_suffix ~affix:empty asdf) true; eq_bool (String.Sub.is_suffix ~affix:ha sempty) false; eq_bool (String.Sub.is_suffix ~affix:ha a) false; eq_bool (String.Sub.is_suffix ~affix:ha h) false; eq_bool (String.Sub.is_suffix ~affix:ha ah) false; eq_bool (String.Sub.is_suffix ~affix:ha ha) true; eq_bool (String.Sub.is_suffix ~affix:ha aha) true; eq_bool (String.Sub.is_suffix ~affix:ha haha) true; eq_bool (String.Sub.is_suffix ~affix:ha hahb) false; () let for_all = test "String.Sub.for_all" @@ fun () -> let empty = String.Sub.v ~start:3 ~stop:3 "asldfksaf" in let s123 = String.Sub.v ~start:2 ~stop:5 "sf123df" in let s412 = String.Sub.v "412" in let s142 = String.Sub.v ~start:3 "aaa142" in let s124 = String.Sub.v ~start:3 "aad124" in eqs empty ""; eqs s123 "123"; eqs s412 "412"; eqs s142 "142"; eqs s124 "124"; eq_bool (String.Sub.for_all (fun _ -> false) empty) true; eq_bool (String.Sub.for_all (fun _ -> true) empty) true; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s123) true; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s412) false; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s142) false; eq_bool (String.Sub.for_all (fun c -> Char.to_int c < 0x34) s124) false; () let exists = test "String.Sub.exists" @@ fun () -> let empty = String.Sub.v ~start:3 ~stop:3 "asldfksaf" in let s541 = String.sub_with_index_range ~first:1 ~last:3 "a541" in let s154 = String.sub_with_index_range ~first:1 "a154" in let s654 = String.sub_with_index_range ~last:2 "654adf" in eqs s541 "541"; eqs s154 "154"; eqs s654 "654"; eq_bool (String.Sub.exists (fun _ -> false) empty) false; eq_bool (String.Sub.exists (fun _ -> true) empty) false; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s541) true; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s541) true; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s154) true; eq_bool (String.Sub.exists (fun c -> Char.to_int c < 0x34) s654) false; () let same_base = test "String.Sub.same_base" @@ fun () -> let abcd = "abcd" in let a = String.sub_with_index_range ~first:0 ~last:0 abcd in let ab = String.sub_with_index_range ~first:0 ~last:1 abcd in let abce = String.sub_with_index_range ~first:0 ~last:1 "abce" in eq_bool (String.Sub.same_base a ab) true; eq_bool (String.Sub.same_base ab a) true; eq_bool (String.Sub.same_base abce a) false; eq_bool (String.Sub.same_base abce a) false; () let equal_bytes = test "String.Sub.equal_bytes" @@ fun () -> let a = String.sub_with_index_range ~first:0 ~last:0 "abcd" in let ab = String.sub_with_index_range ~first:0 ~last:1 "abcd" in let ab' = String.sub_with_index_range ~first:2 ~last:3 "cdab" in let cd = String.sub_with_index_range ~first:2 ~last:3 "abcd" in let empty = String.Sub.v ~start:4 ~stop:4 "abcd" in eq_bool (String.Sub.equal_bytes empty empty) true; eq_bool (String.Sub.equal_bytes empty a) false; eq_bool (String.Sub.equal_bytes a empty) false; eq_bool (String.Sub.equal_bytes a a) true; eq_bool (String.Sub.equal_bytes ab ab') true; eq_bool (String.Sub.equal_bytes cd ab) false; () let compare_bytes = test "String.Sub.compare_bytes" @@ fun () -> let empty = String.Sub.v "" in let ab = String.sub_with_index_range ~first:0 ~last:1 "abcd" in let ab' = String.sub_with_index_range ~first:2 ~last:3 "cdab" in let abc = String.Sub.v ~start:3 ~stop:5 "adabcdd" in eq_int (String.Sub.compare_bytes empty ab) (-1); eq_int (String.Sub.compare_bytes empty empty) (0); eq_int (String.Sub.compare_bytes ab ab') (0); eq_int (String.Sub.compare_bytes ab empty) (1); eq_int (String.Sub.compare_bytes ab abc) (-1); () let equal = test "String.Sub.equal" @@ fun () -> app_invalid ~pp:pp_bool (String.Sub.(equal (v "b"))) (String.Sub.v "a"); let base = "abcd" in let a = String.Sub.v ~start:0 ~stop:1 base in let empty = String.Sub.v ~start:4 ~stop:4 base in let ab = String.sub_with_index_range ~first:0 ~last:1 base in let cd = String.sub_with_index_range ~first:2 ~last:3 base in eq_bool (String.Sub.equal empty empty) true; eq_bool (String.Sub.equal empty a) false; eq_bool (String.Sub.equal a empty) false; eq_bool (String.Sub.equal a a) true; eq_bool (String.Sub.equal ab ab) true; eq_bool (String.Sub.equal cd ab) false; eq_bool (String.Sub.equal ab cd) false; eq_bool (String.Sub.equal cd cd) true; () let compare = test "String.Sub.compare" @@ fun () -> app_invalid ~pp:pp_bool (String.Sub.(equal (v "b"))) (String.Sub.v "a"); let base = "abcd" in let a = String.Sub.v ~start:0 ~stop:1 base in let empty = String.Sub.v ~start:4 ~stop:4 base in let ab = String.sub_with_index_range ~first:0 ~last:1 base in let cd = String.sub_with_index_range ~first:2 ~last:3 base in eq_int (String.Sub.compare empty empty) 0; eq_int (String.Sub.compare empty a) 1; eq_int (String.Sub.compare a empty) (-1); eq_int (String.Sub.compare a a) 0; eq_int (String.Sub.compare ab ab) 0; eq_int (String.Sub.compare cd ab) 1; eq_int (String.Sub.compare ab cd) (-1); eq_int (String.Sub.compare cd cd) 0; () let with_range = test "String.Sub.with_range" @@ fun () -> let invalid ?first ?len s = app_invalid ~pp:String.Sub.pp (String.Sub.with_range ?first ?len) s in let empty_pos ?first ?len s pos = empty_pos (String.Sub.with_range ?first ?len s) pos in let base = "00abc1234" in let abc = String.sub ~start:2 ~stop:5 base in let a = String.sub ~start:2 ~stop:3 base in let empty = String.sub ~start:2 ~stop:2 base in empty_pos empty ~first:1 ~len:0 2; empty_pos empty ~first:1 ~len:0 2; empty_pos empty ~first:0 ~len:1 2; empty_pos empty ~first:(-1) ~len:1 2; invalid empty ~first:0 ~len:(-1); eqs (String.Sub.with_range a ~first:0 ~len:0) ""; eqs (String.Sub.with_range a ~first:1 ~len:0) ""; empty_pos a ~first:1 ~len:1 3; empty_pos a ~first:(-1) ~len:1 2; eqs (String.Sub.with_range ~first:1 abc) "bc"; eqs (String.Sub.with_range ~first:2 abc) "c"; eqs (String.Sub.with_range ~first:3 abc) ""; empty_pos ~first:4 abc 5; eqs (String.Sub.with_range abc ~first:0 ~len:0) ""; eqs (String.Sub.with_range abc ~first:0 ~len:1) "a"; eqs (String.Sub.with_range abc ~first:0 ~len:2) "ab"; eqs (String.Sub.with_range abc ~first:0 ~len:4) "abc"; eqs (String.Sub.with_range abc ~first:1 ~len:0) ""; eqs (String.Sub.with_range abc ~first:1 ~len:1) "b"; eqs (String.Sub.with_range abc ~first:1 ~len:2) "bc"; eqs (String.Sub.with_range abc ~first:1 ~len:3) "bc"; eqs (String.Sub.with_range abc ~first:2 ~len:0) ""; eqs (String.Sub.with_range abc ~first:2 ~len:1) "c"; eqs (String.Sub.with_range abc ~first:2 ~len:2) "c"; eqs (String.Sub.with_range abc ~first:3 ~len:0) ""; eqs (String.Sub.with_range abc ~first:1 ~len:4) "bc"; empty_pos abc ~first:(-1) ~len:1 2; () let with_index_range = test "String.Sub.with_index_range" @@ fun () -> let empty_pos ?first ?last s pos = empty_pos (String.Sub.with_index_range ?first ?last s) pos in let base = "00abc1234" in let abc = String.sub ~start:2 ~stop:5 base in let a = String.sub ~start:2 ~stop:3 base in let empty = String.sub ~start:2 ~stop:2 base in empty_pos empty 2; empty_pos empty ~first:0 ~last:0 2; empty_pos empty ~first:1 ~last:0 2; empty_pos empty ~first:0 ~last:1 2; empty_pos empty ~first:(-1) ~last:1 2; empty_pos empty ~first:0 ~last:(-1) 2; eqs (String.Sub.with_index_range ~first:0 ~last:2 a) "a"; empty_pos a ~first:0 ~last:(-1) 2; eqs (String.Sub.with_index_range ~first:0 ~last:2 a) "a"; eqs (String.Sub.with_index_range ~first:(-1) ~last:0 a) "a"; eqs (String.Sub.with_index_range ~first:1 abc) "bc"; eqs (String.Sub.with_index_range ~first:2 abc) "c"; empty_pos ~first:3 abc 5; empty_pos ~first:4 abc 5; eqs (String.Sub.with_index_range abc ~first:0 ~last:0) "a"; eqs (String.Sub.with_index_range abc ~first:0 ~last:1) "ab"; eqs (String.Sub.with_index_range abc ~first:0 ~last:3) "abc"; eqs (String.Sub.with_index_range abc ~first:1 ~last:1) "b"; eqs (String.Sub.with_index_range abc ~first:1 ~last:2) "bc"; empty_pos abc ~first:1 ~last:0 3; eqs (String.Sub.with_index_range abc ~first:1 ~last:3) "bc"; eqs (String.Sub.with_index_range abc ~first:2 ~last:2) "c"; empty_pos abc ~first:2 ~last:0 4; empty_pos abc ~first:2 ~last:1 4; eqs (String.Sub.with_index_range abc ~first:2 ~last:3) "c"; empty_pos abc ~first:3 ~last:0 5; empty_pos abc ~first:3 ~last:1 5; empty_pos abc ~first:3 ~last:2 5; empty_pos abc ~first:3 ~last:3 5; eqs (String.Sub.with_index_range abc ~first:(-1) ~last:0) "a"; () let span = test "String.Sub.{span,take,drop}" @@ fun () -> let eq_pair (l0, r0) (l1, r1) = String.Sub.(equal l0 l1 && equal r0 r1) in let eq_pair = eq ~eq:eq_pair ~pp:pp_pair in let eq ?(rev = false) ?min ?max ?sat s (sl, sr as spec) = let (l, r as pair) = String.Sub.span ~rev ?min ?max ?sat s in let t = String.Sub.take ~rev ?min ?max ?sat s in let d = String.Sub.drop ~rev ?min ?max ?sat s in eq_pair pair spec; eq_sub t (if rev then sr else sl); eq_sub d (if rev then sl else sr); in let invalid ?rev ?min ?max ?sat s = app_invalid ~pp:pp_pair (String.Sub.span ?rev ?min ?max ?sat) s in let base = "0ab cd0" in let empty = String.sub ~start:3 ~stop:3 base in let ab_cd = String.sub ~start:1 ~stop:6 base in let ab = String.sub ~start:1 ~stop:3 base in let _cd = String.sub ~start:3 ~stop:6 base in let cd = String.sub ~start:4 ~stop:6 base in let ab_ = String.sub ~start:1 ~stop:4 base in let a = String.sub ~start:1 ~stop:2 base in let b_cd = String.sub ~start:2 ~stop:6 base in let b = String.sub ~start:2 ~stop:3 base in let d = String.sub ~start:5 ~stop:6 base in let ab_c = String.sub ~start:1 ~stop:5 base in eq ~rev:false ~min:1 ~max:0 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~min:1 ~max:0 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~sat:Char.Ascii.is_white ab_cd (String.Sub.start ab_cd, ab_cd); eq ~sat:Char.Ascii.is_letter ab_cd (ab, _cd); eq ~max:1 ~sat:Char.Ascii.is_letter ab_cd (a, b_cd); eq ~max:0 ~sat:Char.Ascii.is_letter ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_white ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ab_cd (ab_, cd); eq ~rev:true ~max:1 ~sat:Char.Ascii.is_letter ab_cd (ab_c, d); eq ~rev:true ~max:0 ~sat:Char.Ascii.is_letter ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~sat:Char.Ascii.is_letter ab (ab, String.Sub.stop ab); eq ~max:1 ~sat:Char.Ascii.is_letter ab (a, b); eq ~sat:Char.Ascii.is_letter b (b, empty); eq ~rev:true ~max:1 ~sat:Char.Ascii.is_letter ab (a, b); eq ~max:1 ~sat:Char.Ascii.is_white ab (String.Sub.start ab, ab); eq ~rev:true ~sat:Char.Ascii.is_white empty (empty, empty); eq ~sat:Char.Ascii.is_white empty (empty, empty); invalid ~rev:false ~min:(-1) empty; invalid ~rev:true ~min:(-1) empty; invalid ~rev:false ~max:(-1) empty; invalid ~rev:true ~max:(-1) empty; eq ~rev:false empty (empty,empty); eq ~rev:true empty (empty,empty); eq ~rev:false ~min:0 ~max:0 empty (empty,empty); eq ~rev:true ~min:0 ~max:0 empty (empty,empty); eq ~rev:false ~min:1 ~max:0 empty (empty,empty); eq ~rev:true ~min:1 ~max:0 empty (empty,empty); eq ~rev:false ~max:0 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~max:0 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ~max:2 ab_cd (ab, _cd); eq ~rev:true ~max:2 ab_cd (ab_, cd); eq ~rev:false ~min:6 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~min:6 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:true ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:false ~max:30 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:true ~max:30 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:false ~sat:Char.Ascii.is_white ab_cd (String.Sub.start ab_cd,ab_cd); eq ~rev:true ~sat:Char.Ascii.is_white ab_cd (ab_cd,String.Sub.stop ab_cd); eq ~rev:false ~sat:Char.Ascii.is_letter ab_cd (ab, _cd); eq ~rev:true ~sat:Char.Ascii.is_letter ab_cd (ab_, cd); eq ~rev:false ~sat:Char.Ascii.is_letter ~max:0 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~max:0 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ~sat:Char.Ascii.is_letter ~max:1 ab_cd (a, b_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~max:1 ab_cd (ab_c, d); eq ~rev:false ~sat:Char.Ascii.is_letter ~min:2 ~max:1 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~min:2 ~max:1 ab_cd (ab_cd, String.Sub.stop ab_cd); eq ~rev:false ~sat:Char.Ascii.is_letter ~min:3 ab_cd (String.Sub.start ab_cd, ab_cd); eq ~rev:true ~sat:Char.Ascii.is_letter ~min:3 ab_cd (ab_cd, String.Sub.stop ab_cd); () let trim = test "String.Sub.trim" @@ fun () -> let drop_a c = c = 'a' in let base = "00aaaabcdaaaa00" in let aaaabcdaaaa = String.sub ~start:2 ~stop:13 base in let aaaabcd = String.sub ~start:2 ~stop:9 base in let bcdaaaa = String.sub ~start:6 ~stop:13 base in let aaaa = String.sub ~start:2 ~stop:6 base in eqs (String.Sub.trim (String.sub "\t abcd \r ")) "abcd"; eqs (String.Sub.trim aaaabcdaaaa) "aaaabcdaaaa"; eqs (String.Sub.trim ~drop:drop_a aaaabcdaaaa) "bcd"; eqs (String.Sub.trim ~drop:drop_a aaaabcd) "bcd"; eqs (String.Sub.trim ~drop:drop_a bcdaaaa) "bcd"; empty_pos (String.Sub.trim ~drop:drop_a aaaa) 4; empty_pos (String.Sub.trim (String.sub " ")) 2; () let cut = test "String.Sub.cut" @@ fun () -> let ppp = pp_option pp_pair in let eqo = eqs_pair_opt in let s s = String.sub ~start:1 ~stop:(1 + (String.length s)) (strf "\x00%s\x00" s) in let cut ?rev ~sep str = String.Sub.cut ?rev ~sep:(s sep) (s str) in app_invalid ~pp:ppp (cut ~sep:"") ""; app_invalid ~pp:ppp (cut ~sep:"") "123"; eqo (cut "," "") None; eqo (cut "," ",") (Some ("", "")); eqo (cut "," ",,") (Some ("", ",")); eqo (cut "," ",,,") (Some ("", ",,")); eqo (cut "," "123") None; eqo (cut "," ",123") (Some ("", "123")); eqo (cut "," "123,") (Some ("123", "")); eqo (cut "," "1,2,3") (Some ("1", "2,3")); eqo (cut "," " 1,2,3") (Some (" 1", "2,3")); eqo (cut "<>" "") None; eqo (cut "<>" "<>") (Some ("", "")); eqo (cut "<>" "<><>") (Some ("", "<>")); eqo (cut "<>" "<><><>") (Some ("", "<><>")); eqo (cut ~rev:true ~sep:"<>" "1") None; eqo (cut "<>" "123") None; eqo (cut "<>" "<>123") (Some ("", "123")); eqo (cut "<>" "123<>") (Some ("123", "")); eqo (cut "<>" "1<>2<>3") (Some ("1", "2<>3")); eqo (cut "<>" " 1<>2<>3") (Some (" 1", "2<>3")); eqo (cut "<>" ">>><>>>><>>>><>>>>") (Some (">>>", ">>><>>>><>>>>")); eqo (cut "<->" "<->>->") (Some ("", ">->")); eqo (cut ~rev:true ~sep:"<->" "<-") None; eqo (cut "aa" "aa") (Some ("", "")); eqo (cut "aa" "aaa") (Some ("", "a")); eqo (cut "aa" "aaaa") (Some ("", "aa")); eqo (cut "aa" "aaaaa") (Some ("", "aaa";)); eqo (cut "aa" "aaaaaa") (Some ("", "aaaa")); eqo (cut ~sep:"ab" "faaaa") None; eqo (String.Sub.cut ~sep:(String.sub "/") (String.sub ~start:2 "a/b/c")) (Some ("b", "c")); let rev = true in app_invalid ~pp:ppp (cut ~rev ~sep:"") ""; app_invalid ~pp:ppp (cut ~rev ~sep:"") "123"; eqo (cut ~rev ~sep:"," "") None; eqo (cut ~rev ~sep:"," ",") (Some ("", "")); eqo (cut ~rev ~sep:"," ",,") (Some (",", "")); eqo (cut ~rev ~sep:"," ",,,") (Some (",,", "")); eqo (cut ~rev ~sep:"," "123") None; eqo (cut ~rev ~sep:"," ",123") (Some ("", "123")); eqo (cut ~rev ~sep:"," "123,") (Some ("123", "")); eqo (cut ~rev ~sep:"," "1,2,3") (Some ("1,2", "3")); eqo (cut ~rev ~sep:"," "1,2,3 ") (Some ("1,2", "3 ")); eqo (cut ~rev ~sep:"<>" "") None; eqo (cut ~rev ~sep:"<>" "<>") (Some ("", "")); eqo (cut ~rev ~sep:"<>" "<><>") (Some ("<>", "")); eqo (cut ~rev ~sep:"<>" "<><><>") (Some ("<><>", "")); eqo (cut ~rev ~sep:"<>" "1") None; eqo (cut ~rev ~sep:"<>" "123") None; eqo (cut ~rev ~sep:"<>" "<>123") (Some ("", "123")); eqo (cut ~rev ~sep:"<>" "123<>") (Some ("123", "")); eqo (cut ~rev ~sep:"<>" "1<>2<>3") (Some ("1<>2", "3")); eqo (cut ~rev ~sep:"<>" "1<>2<>3 ") (Some ("1<>2", "3 ")); eqo (cut ~rev ~sep:"<>" ">>><>>>><>>>><>>>>") (Some (">>><>>>><>>>>", ">>>")); eqo (cut ~rev ~sep:"<->" "<->>->") (Some ("", ">->")); eqo (cut ~rev ~sep:"<->" "<-") None; eqo (cut ~rev ~sep:"aa" "aa") (Some ("", "")); eqo (cut ~rev ~sep:"aa" "aaa") (Some ("a", "")); eqo (cut ~rev ~sep:"aa" "aaaa") (Some ("aa", "")); eqo (cut ~rev ~sep:"aa" "aaaaa") (Some ("aaa", "";)); eqo (cut ~rev ~sep:"aa" "aaaaaa") (Some ("aaaa", "")); eqo (cut ~rev ~sep:"ab" "afaaaa") None; eqo (String.Sub.cut ~sep:(String.sub "/") (String.sub ~stop:3 "a/b/c")) (Some ("a", "b")); () let cuts = test "String.Sub.cuts" @@ fun () -> let ppl = pp_list String.Sub.dump in let eql subs l = let subs = List.map String.Sub.to_string subs in eq_list ~eq:String.equal ~pp:String.dump subs l in let s s = String.sub ~start:1 ~stop:(1 + (String.length s)) (strf "\x00%s\x00" s) in let cuts ?rev ?empty ~sep str = String.Sub.cuts ?rev ?empty ~sep:(s sep) (s str) in app_invalid ~pp:ppl (cuts ~sep:"") ""; app_invalid ~pp:ppl (cuts ~sep:"") "123"; eql (cuts ~empty:true ~sep:"," "") [""]; eql (cuts ~empty:false ~sep:"," "") []; eql (cuts ~empty:true ~sep:"," ",") [""; ""]; eql (cuts ~empty:false ~sep:"," ",") []; eql (cuts ~empty:true ~sep:"," ",,") [""; ""; ""]; eql (cuts ~empty:false ~sep:"," ",,") []; eql (cuts ~empty:true ~sep:"," ",,,") [""; ""; ""; ""]; eql (cuts ~empty:false ~sep:"," ",,,") []; eql (cuts ~empty:true ~sep:"," "123") ["123"]; eql (cuts ~empty:false ~sep:"," "123") ["123"]; eql (cuts ~empty:true ~sep:"," ",123") [""; "123"]; eql (cuts ~empty:false ~sep:"," ",123") ["123"]; eql (cuts ~empty:true ~sep:"," "123,") ["123"; ""]; eql (cuts ~empty:false ~sep:"," "123,") ["123";]; eql (cuts ~empty:true ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~empty:false ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~empty:true ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:false ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:true ~sep:"," ",1,2,,3,") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~empty:false ~sep:"," ",1,2,,3,") ["1"; "2"; "3";]; eql (cuts ~empty:true ~sep:"," ", 1, 2,, 3,") [""; " 1"; " 2"; ""; " 3"; ""]; eql (cuts ~empty:false ~sep:"," ", 1, 2,, 3,") [" 1"; " 2";" 3";]; eql (cuts ~empty:true ~sep:"<>" "") [""]; eql (cuts ~empty:false ~sep:"<>" "") []; eql (cuts ~empty:true ~sep:"<>" "<>") [""; ""]; eql (cuts ~empty:false ~sep:"<>" "<>") []; eql (cuts ~empty:true ~sep:"<>" "<><>") [""; ""; ""]; eql (cuts ~empty:false ~sep:"<>" "<><>") []; eql (cuts ~empty:true ~sep:"<>" "<><><>") [""; ""; ""; ""]; eql (cuts ~empty:false ~sep:"<>" "<><><>") []; eql (cuts ~empty:true ~sep:"<>" "123") [ "123" ]; eql (cuts ~empty:false ~sep:"<>" "123") [ "123" ]; eql (cuts ~empty:true ~sep:"<>" "<>123") [""; "123"]; eql (cuts ~empty:false ~sep:"<>" "<>123") ["123"]; eql (cuts ~empty:true ~sep:"<>" "123<>") ["123"; ""]; eql (cuts ~empty:false ~sep:"<>" "123<>") ["123"]; eql (cuts ~empty:true ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~empty:false ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~empty:true ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:false ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~empty:true ~sep:"<>" "<>1<>2<><>3<>") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~empty:false ~sep:"<>" "<>1<>2<><>3<>") ["1"; "2";"3";]; eql (cuts ~empty:true ~sep:"<>" "<> 1<> 2<><> 3<>") [""; " 1"; " 2"; ""; " 3";""]; eql (cuts ~empty:false ~sep:"<>" "<> 1<> 2<><> 3<>")[" 1"; " 2"; " 3"]; eql (cuts ~empty:true ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~empty:false ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~empty:true ~sep:"<->" "<->>->") [""; ">->"]; eql (cuts ~empty:false ~sep:"<->" "<->>->") [">->"]; eql (cuts ~empty:true ~sep:"aa" "aa") [""; ""]; eql (cuts ~empty:false ~sep:"aa" "aa") []; eql (cuts ~empty:true ~sep:"aa" "aaa") [""; "a"]; eql (cuts ~empty:false ~sep:"aa" "aaa") ["a"]; eql (cuts ~empty:true ~sep:"aa" "aaaa") [""; ""; ""]; eql (cuts ~empty:false ~sep:"aa" "aaaa") []; eql (cuts ~empty:true ~sep:"aa" "aaaaa") [""; ""; "a"]; eql (cuts ~empty:false ~sep:"aa" "aaaaa") ["a"]; eql (cuts ~empty:true ~sep:"aa" "aaaaaa") [""; ""; ""; ""]; eql (cuts ~empty:false ~sep:"aa" "aaaaaa") []; let rev = true in app_invalid ~pp:ppl (cuts ~rev ~sep:"") ""; app_invalid ~pp:ppl (cuts ~rev ~sep:"") "123"; eql (cuts ~rev ~empty:true ~sep:"," "") [""]; eql (cuts ~rev ~empty:false ~sep:"," "") []; eql (cuts ~rev ~empty:true ~sep:"," ",") [""; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",") []; eql (cuts ~rev ~empty:true ~sep:"," ",,") [""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",,") []; eql (cuts ~rev ~empty:true ~sep:"," ",,,") [""; ""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",,,") []; eql (cuts ~rev ~empty:true ~sep:"," "123") ["123"]; eql (cuts ~rev ~empty:false ~sep:"," "123") ["123"]; eql (cuts ~rev ~empty:true ~sep:"," ",123") [""; "123"]; eql (cuts ~rev ~empty:false ~sep:"," ",123") ["123"]; eql (cuts ~rev ~empty:true ~sep:"," "123,") ["123"; ""]; eql (cuts ~rev ~empty:false ~sep:"," "123,") ["123";]; eql (cuts ~rev ~empty:true ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:false ~sep:"," "1,2,3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:false ~sep:"," "1, 2, 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:true ~sep:"," ",1,2,,3,") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~rev ~empty:false ~sep:"," ",1,2,,3,") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"," ", 1, 2,, 3,") [""; " 1"; " 2"; ""; " 3"; ""]; eql (cuts ~rev ~empty:false ~sep:"," ", 1, 2,, 3,") [" 1"; " 2"; " 3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "") [""]; eql (cuts ~rev ~empty:false ~sep:"<>" "") []; eql (cuts ~rev ~empty:true ~sep:"<>" "<>") [""; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<>") []; eql (cuts ~rev ~empty:true ~sep:"<>" "<><>") [""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<><>") []; eql (cuts ~rev ~empty:true ~sep:"<>" "<><><>") [""; ""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<><><>") []; eql (cuts ~rev ~empty:true ~sep:"<>" "123") [ "123" ]; eql (cuts ~rev ~empty:false ~sep:"<>" "123") [ "123" ]; eql (cuts ~rev ~empty:true ~sep:"<>" "<>123") [""; "123"]; eql (cuts ~rev ~empty:false ~sep:"<>" "<>123") ["123"]; eql (cuts ~rev ~empty:true ~sep:"<>" "123<>") ["123"; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "123<>") ["123";]; eql (cuts ~rev ~empty:true ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:false ~sep:"<>" "1<>2<>3") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:false ~sep:"<>" "1<> 2<> 3") ["1"; " 2"; " 3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "<>1<>2<><>3<>") [""; "1"; "2"; ""; "3"; ""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<>1<>2<><>3<>") ["1"; "2"; "3"]; eql (cuts ~rev ~empty:true ~sep:"<>" "<> 1<> 2<><> 3<>") [""; " 1"; " 2"; ""; " 3";""]; eql (cuts ~rev ~empty:false ~sep:"<>" "<> 1<> 2<><> 3<>") [" 1"; " 2"; " 3";]; eql (cuts ~rev ~empty:true ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~rev ~empty:false ~sep:"<>" ">>><>>>><>>>><>>>>") [">>>"; ">>>"; ">>>"; ">>>" ]; eql (cuts ~rev ~empty:true ~sep:"<->" "<->>->") [""; ">->"]; eql (cuts ~rev ~empty:false ~sep:"<->" "<->>->") [">->"]; eql (cuts ~rev ~empty:true ~sep:"aa" "aa") [""; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aa") []; eql (cuts ~rev ~empty:true ~sep:"aa" "aaa") ["a"; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaa") ["a"]; eql (cuts ~rev ~empty:true ~sep:"aa" "aaaa") [""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaaa") []; eql (cuts ~rev ~empty:true ~sep:"aa" "aaaaa") ["a"; ""; "";]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaaaa") ["a";]; eql (cuts ~rev ~empty:true ~sep:"aa" "aaaaaa") [""; ""; ""; ""]; eql (cuts ~rev ~empty:false ~sep:"aa" "aaaaaa") []; () let fields = test "String.Sub.fields" @@ fun () -> let eql subs l = let subs = List.map String.Sub.to_string subs in eq_list ~eq:String.equal ~pp:String.dump subs l in let s s = String.sub ~start:1 ~stop:(1 + (String.length s)) (strf "\x00%s\x00" s) in let fields ?empty ?is_sep str = String.Sub.fields ?empty ?is_sep (s str) in let is_a c = c = 'a' in eql (fields ~empty:true "a") ["a"]; eql (fields ~empty:false "a") ["a"]; eql (fields ~empty:true "abc") ["abc"]; eql (fields ~empty:false "abc") ["abc"]; eql (fields ~empty:true ~is_sep:is_a "bcdf") ["bcdf"]; eql (fields ~empty:false ~is_sep:is_a "bcdf") ["bcdf"]; eql (fields ~empty:true "") [""]; eql (fields ~empty:false "") []; eql (fields ~empty:true "\n\r") ["";"";""]; eql (fields ~empty:false "\n\r") []; eql (fields ~empty:true " \n\rabc") ["";"";"";"abc"]; eql (fields ~empty:false " \n\rabc") ["abc"]; eql (fields ~empty:true " \n\racd de") ["";"";"";"acd";"de"]; eql (fields ~empty:false " \n\racd de") ["acd";"de"]; eql (fields ~empty:true " \n\racd de ") ["";"";"";"acd";"de";""]; eql (fields ~empty:false " \n\racd de ") ["acd";"de"]; eql (fields ~empty:true "\n\racd\nde \r") ["";"";"acd";"de";"";""]; eql (fields ~empty:false "\n\racd\nde \r") ["acd";"de"]; eql (fields ~empty:true ~is_sep:is_a "") [""]; eql (fields ~empty:false ~is_sep:is_a "") []; eql (fields ~empty:true ~is_sep:is_a "abaac aaa") ["";"b";"";"c ";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "abaac aaa") ["b"; "c "]; eql (fields ~empty:true ~is_sep:is_a "aaaa") ["";"";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "aaaa") []; eql (fields ~empty:true ~is_sep:is_a "aaaa ") ["";"";"";"";" "]; eql (fields ~empty:false ~is_sep:is_a "aaaa ") [" "]; eql (fields ~empty:true ~is_sep:is_a "aaaab") ["";"";"";"";"b"]; eql (fields ~empty:false ~is_sep:is_a "aaaab") ["b"]; eql (fields ~empty:true ~is_sep:is_a "baaaa") ["b";"";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "baaaa") ["b"]; eql (fields ~empty:true ~is_sep:is_a "abaaaa") ["";"b";"";"";"";""]; eql (fields ~empty:false ~is_sep:is_a "abaaaa") ["b"]; eql (fields ~empty:true ~is_sep:is_a "aba") ["";"b";""]; eql (fields ~empty:false ~is_sep:is_a "aba") ["b"]; eql (fields ~empty:false "tokenize me please") ["tokenize"; "me"; "please"]; () let find = test "String.Sub.find" @@ fun () -> let abcbd = "abcbd" in let empty = String.sub ~start:3 ~stop:3 abcbd in let a = String.sub ~start:0 ~stop:1 abcbd in let ab = String.sub ~start:0 ~stop:2 abcbd in let c = String.sub ~start:2 ~stop:3 abcbd in let b0 = String.sub ~start:1 ~stop:2 abcbd in let b1 = String.sub ~start:3 ~stop:4 abcbd in let abcbd = String.sub abcbd in let eq = eq_option ~eq:String.Sub.equal ~pp:String.Sub.dump_raw in eq (String.Sub.find (fun c -> c = 'b') empty) None; eq (String.Sub.find ~rev:true (fun c -> c = 'b') empty) None; eq (String.Sub.find (fun c -> c = 'b') a) None; eq (String.Sub.find ~rev:true (fun c -> c = 'b') a) None; eq (String.Sub.find (fun c -> c = 'b') c) None; eq (String.Sub.find ~rev:true (fun c -> c = 'b') c) None; eq (String.Sub.find (fun c -> c = 'b') abcbd) (Some b0); eq (String.Sub.find ~rev:true (fun c -> c = 'b') abcbd) (Some b1); eq (String.Sub.find (fun c -> c = 'b') ab) (Some b0); eq (String.Sub.find ~rev:true (fun c -> c = 'b') ab) (Some b0); () let find_sub = test "String.Sub.find_sub" @@ fun () -> let abcbd = "abcbd" in let empty = String.sub ~start:3 ~stop:3 abcbd in let ab = String.sub ~start:0 ~stop:2 abcbd in let b0 = String.sub ~start:1 ~stop:2 abcbd in let b1 = String.sub ~start:3 ~stop:4 abcbd in let abcbd = String.sub abcbd in let eq = eq_option ~eq:String.Sub.equal ~pp:String.Sub.dump_raw in eq (String.Sub.find_sub ~sub:ab empty) None; eq (String.Sub.find_sub ~rev:true ~sub:ab empty) None; eq (String.Sub.find_sub ~sub:(String.sub "") empty) (Some empty); eq (String.Sub.find_sub ~rev:true ~sub:(String.sub "") empty) (Some empty); eq (String.Sub.find_sub ~sub:ab abcbd) (Some ab); eq (String.Sub.find_sub ~rev:true ~sub:ab abcbd) (Some ab); eq (String.Sub.find_sub ~sub:empty abcbd) (Some (String.Sub.start abcbd)); eq (String.Sub.find_sub ~rev:true ~sub:empty abcbd) (Some (String.Sub.stop abcbd)); eq (String.Sub.find_sub ~sub:(String.sub "b") abcbd) (Some b0); eq (String.Sub.find_sub ~rev:true ~sub:(String.sub "b") abcbd) (Some b1); eq (String.Sub.find_sub ~sub:b1 ab) (Some b0); eq (String.Sub.find_sub ~rev:true ~sub:b1 ab) (Some b0); () let map = test "String.Sub.map[i]" @@ fun () -> let next_letter c = Char.(of_byte @@ to_int c + 1) in let base = "i34abcdbbb" in let abcd = String.Sub.v ~start:3 ~stop:7 base in let empty = String.Sub.v ~start:2 ~stop:2 base in eqs (String.Sub.map (fun c -> fail "invoked"; c) empty) ""; eqs (String.Sub.map (fun c -> c) abcd) "abcd"; eqs (String.Sub.map next_letter abcd) "bcde"; eq_str String.Sub.(base_string (map next_letter abcd)) "bcde"; eqs (String.Sub.mapi (fun _ c -> fail "invoked"; c) empty) ""; eqs (String.Sub.mapi (fun i c -> Char.(of_byte @@ to_int c + i)) abcd) "aceg"; () let fold = test "String.Sub.fold_{left,right}" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "ab" in let abc = String.Sub.v ~start:3 ~stop:6 "i34abcdbbb" in let eql = eq_list ~eq:(=) ~pp:pp_char in String.Sub.fold_left (fun _ _ -> fail "invoked") () empty; eql (String.Sub.fold_left (fun acc c -> c :: acc) [] empty) []; eql (String.Sub.fold_left (fun acc c -> c :: acc) [] abc) ['c';'b';'a']; String.Sub.fold_right (fun _ _ -> fail "invoked") empty (); eql (String.Sub.fold_right (fun c acc -> c :: acc) empty []) []; eql (String.Sub.fold_right (fun c acc -> c :: acc) abc []) ['a';'b';'c']; () let iter = test "String.Sub.iter[i]" @@ fun () -> let empty = String.Sub.v ~start:2 ~stop:2 "ab" in let abc = String.Sub.v ~start:3 ~stop:6 "i34abcdbbb" in String.Sub.iter (fun _ -> fail "invoked") empty; String.Sub.iteri (fun _ _ -> fail "invoked") empty; (let i = ref 0 in String.Sub.iter (fun c -> eq_char (String.Sub.get abc !i) c; incr i) abc); String.Sub.iteri (fun i c -> eq_char (String.Sub.get abc i) c) abc; () let suite = suite "Base String functions" [ misc; head; to_string; start; stop; tail; base; extend; reduce; extent; overlap; append; concat; is_empty; is_prefix; is_infix; is_suffix; for_all; exists; same_base; equal_bytes; compare_bytes; equal; compare; with_range; with_index_range; span; trim; cut; cuts; fields; find; find_sub; map; fold; iter; ] --------------------------------------------------------------------------- Copyright ( c ) 2015 The astring programmers 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 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) 2015 The astring programmers 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. ---------------------------------------------------------------------------*)
60fdf9086b01fc5d47432ea59839edb76d9b9dbee1602bc75d6121952f6f9f49
MinaProtocol/mina
tick.ml
(* snark_params_nonconsensus.ml *) [%%import "/src/config.mlh"] [%%ifdef consensus_mechanism] [%%error "Snark_params_nonconsensus should not be compiled if there's a consensus \ mechanism"] [%%endif] open Snarkette [%%if curve_size = 255] (* only size we should be building nonconsensus code for *) [%%else] [%%show curve_size] [%%error "invalid value for \"curve_size\""] [%%endif] [%%inject "ledger_depth", ledger_depth] module Field = struct open Core_kernel [%%versioned module Stable = struct [@@@no_toplevel_latest_type] module V1 = struct type t = Pasta.Fp.t [@version_asserted] [@@deriving equal, compare, yojson, sexp, hash] let to_latest x = x end end] include Pasta.Fp let size = order |> Snarkette.Nat.to_string |> Bigint.of_string let size_in_bits = length_in_bits let unpack t = to_bits t let project bits = Core_kernel.Option.value_exn ~message:"project: invalid bits" (of_bits bits) end module Tock = struct module Field = struct type t = Pasta.Fq.t let unpack (t : t) = Pasta.Fq.to_bits t let size_in_bits = Pasta.Fq.length_in_bits let project bits = Core_kernel.Option.value_exn ~message:"Snark_params_nonconsensus.Tock.Field.project" (Pasta.Fq.of_bits bits) end end module Inner_curve = struct module C = Pasta.Pallas type t = C.t [@@deriving sexp] module Coefficients = C.Coefficients let find_y x = let open Field in let y2 = (x * square x) + (Coefficients.a * x) + Coefficients.b in if is_square y2 then Some (sqrt y2) else None [%%define_locally C.(of_affine, to_affine, to_affine_exn, one, ( + ), negate)] module Scalar = struct (* though we have bin_io, not versioned here; this type exists for Private_key.t, where it is versioned-asserted and its serialization tested *) type t = Pasta.Fq.t [@@deriving bin_io_unversioned, sexp] let (_ : (t, Tock.Field.t) Type_equal.t) = Type_equal.T let size = Pasta.Fq.order [%%define_locally Pasta.Fq. ( to_string , of_string , equal , compare , size , zero , one , ( + ) , ( - ) , ( * ) , gen_uniform_incl , negate , hash_fold_t )] Pasta.Fq.gen uses the interval starting at zero here we follow the gen in Snark_params . Make_inner_curve_scalar , using an interval starting at one here we follow the gen in Snark_params.Make_inner_curve_scalar, using an interval starting at one *) let gen = Pasta.Fq.(gen_incl one (zero - one)) let gen_uniform = gen_uniform_incl one (zero - one) let unpack t = Tock.Field.unpack t let of_bits bits = Tock.Field.project bits let project = of_bits end let scale (t : t) (scalar : Scalar.t) = C.scale t (scalar :> Nat.t) let scale_field (t : t) x = scale t (Pasta.Fq.of_bigint x :> Scalar.t) end
null
https://raw.githubusercontent.com/MinaProtocol/mina/465aed0f9c71268e3ebd8428f07005d253a0bde1/src/nonconsensus/snark_params/tick.ml
ocaml
snark_params_nonconsensus.ml only size we should be building nonconsensus code for though we have bin_io, not versioned here; this type exists for Private_key.t, where it is versioned-asserted and its serialization tested
[%%import "/src/config.mlh"] [%%ifdef consensus_mechanism] [%%error "Snark_params_nonconsensus should not be compiled if there's a consensus \ mechanism"] [%%endif] open Snarkette [%%if curve_size = 255] [%%else] [%%show curve_size] [%%error "invalid value for \"curve_size\""] [%%endif] [%%inject "ledger_depth", ledger_depth] module Field = struct open Core_kernel [%%versioned module Stable = struct [@@@no_toplevel_latest_type] module V1 = struct type t = Pasta.Fp.t [@version_asserted] [@@deriving equal, compare, yojson, sexp, hash] let to_latest x = x end end] include Pasta.Fp let size = order |> Snarkette.Nat.to_string |> Bigint.of_string let size_in_bits = length_in_bits let unpack t = to_bits t let project bits = Core_kernel.Option.value_exn ~message:"project: invalid bits" (of_bits bits) end module Tock = struct module Field = struct type t = Pasta.Fq.t let unpack (t : t) = Pasta.Fq.to_bits t let size_in_bits = Pasta.Fq.length_in_bits let project bits = Core_kernel.Option.value_exn ~message:"Snark_params_nonconsensus.Tock.Field.project" (Pasta.Fq.of_bits bits) end end module Inner_curve = struct module C = Pasta.Pallas type t = C.t [@@deriving sexp] module Coefficients = C.Coefficients let find_y x = let open Field in let y2 = (x * square x) + (Coefficients.a * x) + Coefficients.b in if is_square y2 then Some (sqrt y2) else None [%%define_locally C.(of_affine, to_affine, to_affine_exn, one, ( + ), negate)] module Scalar = struct type t = Pasta.Fq.t [@@deriving bin_io_unversioned, sexp] let (_ : (t, Tock.Field.t) Type_equal.t) = Type_equal.T let size = Pasta.Fq.order [%%define_locally Pasta.Fq. ( to_string , of_string , equal , compare , size , zero , one , ( + ) , ( - ) , ( * ) , gen_uniform_incl , negate , hash_fold_t )] Pasta.Fq.gen uses the interval starting at zero here we follow the gen in Snark_params . Make_inner_curve_scalar , using an interval starting at one here we follow the gen in Snark_params.Make_inner_curve_scalar, using an interval starting at one *) let gen = Pasta.Fq.(gen_incl one (zero - one)) let gen_uniform = gen_uniform_incl one (zero - one) let unpack t = Tock.Field.unpack t let of_bits bits = Tock.Field.project bits let project = of_bits end let scale (t : t) (scalar : Scalar.t) = C.scale t (scalar :> Nat.t) let scale_field (t : t) x = scale t (Pasta.Fq.of_bigint x :> Scalar.t) end
a17d73000e8ce0699b0009ef1d648af538060e7ab6ab1e3dcf52c9a9c3c52f74
reanimate/reanimate
showcase.hs
#!/usr/bin/env stack -- stack runghc --package reanimate {-# LANGUAGE ApplicativeDo #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Main (main) where import Codec.Picture import Control.Lens ((^.),(&)) import Control.Monad import Data.Fixed import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Graphics.SvgTree (Number (..), strokeWidth, toUserUnit) import NeatInterpolation import Reanimate import Reanimate.Animation import Reanimate.Builtin.Images import Reanimate.Ease import Reanimate.Effect import Reanimate.Povray import Reanimate.Raster import Reanimate.Scene import Reanimate.Svg SCRIPT Some ideas lend themselves well to be illustrated . Take spheres , for example : It just so happens that the surface of a sphere is exactly 4 times the area of a circle with the same radius . Now , this relationship has already been visually explored by others in mucher greater detail so I 'll leave it at this . But there are countless other ideas and concepts that deserve to be illustrated yet have not . I want to remedy this , in part , by animating ideas I find interesting , but also by encouraging you to make your own animations . Every video on this channel , including this one , will be open - source with the source files linked in the description . If any of the graphics pique your interest then please download the code and play with it . The animations are created with a library called ' reanimate ' which , at its core , is a set of tools for generating individual frames as SVG images . Layered on top of this core are external components such as : * LaTeX , for typesetting equations , * a bitmap tracer , for turning pixel data into vector graphics , * and a raytracer , for generating 3D graphics , is inherently a pixel - based graphics technique but , with a bit of math , it and vector graphics can be overlayed with pixel - perfect precision . Everything is held together by the purely functional language . Haskell is particularlly well suited for this task since animations are inherently immutable . Some ideas lend themselves well to be illustrated. Take spheres, for example: It just so happens that the surface of a sphere is exactly 4 times the area of a circle with the same radius. Now, this relationship has already been visually explored by others in mucher greater detail so I'll leave it at this. But there are countless other ideas and concepts that deserve to be illustrated yet have not. I want to remedy this, in part, by animating ideas I find interesting, but also by encouraging you to make your own animations. Every video on this channel, including this one, will be open-source with the source files linked in the description. If any of the graphics pique your interest then please download the code and play with it. The animations are created with a library called 'reanimate' which, at its core, is a set of tools for generating individual frames as SVG images. Layered on top of this core are external components such as: * LaTeX, for typesetting equations, * a bitmap tracer, for turning pixel data into vector graphics, * and a raytracer, for generating 3D graphics, Raytracing is inherently a pixel-based graphics technique but, with a bit of math, it and vector graphics can be overlayed with pixel-perfect precision. Everything is held together by the purely functional language Haskell. Haskell is particularlly well suited for this task since animations are inherently immutable. -} main :: IO () main = reanimate $ addStatic (mkBackground "black") animate $ const $ checker 10 10 -- rotateSphere -- rotateWireSphere sphereIntro -- introSVG mapA ( scale 2 ) $ setDuration 20 featLaTeX playbackTest :: Animation playbackTest = setDuration 10 feat3D sphereIntro :: Animation sphereIntro = scene $ do -- play $ drawSphere -- # setDuration 15 # pauseAtEnd 2 -- play $ rotateWireSphere -- # setDuration 2 # signalA ( powerS 2 ) fork $ play $ rotateWireSphere & setDuration 1 & repeatA 10 & takeA (2+5) & applyE (delayE 2 fadeOutE) sphereX <- newVar 0 sphereS <- newSpriteA $ rotateSphere & repeatA (5+3+1+2) -- sphereS <- newSprite $ do -- -- xValue <- freezeVar sphereX let a = rotateSphere # setDuration 1 # repeatA ( 5 + 3 + 1 + 2 ) -- return $ \real_t d t -> -- translate ( xValue real_t ) 0 $ -- frameAt t a applyVar sphereX sphereS (\xValue -> translate xValue 0) spriteE sphereS (overBeginning 1 $ constE $ withGroupOpacity 0) spriteE sphereS (delayE 1 $ overBeginning 2 fadeInE) -- fork $ play $ rotateSphere -- # setDuration 1 # repeatA ( 5 + 3 + 1 + 2 ) # applyE ( overBeginning 1 $ constE $ withGroupOpacity 0 ) # applyE ( delayE 1 $ overBeginning 2 fadeInE ) # applyE ( delayE 8 $ translateE ( -3 ) 0 ) wait 5 adjustZ (+1) $ play $ setDuration 3 $ animate $ \t -> partialSvg t $ withFillOpacity 0 $ rotate 180 $ pathify circ playZ 1 $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t - > withFillOpacity t $ -- circ let scaleFactor = 0.05 tweenVar sphereX 1 $ \t x -> fromToS x (-3) (curveS 3 t) fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (1*p) (2*p) $ scale (1-scaleFactor*p) circ fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (1*p) (-2*p) $ scale (1-scaleFactor*p) circ fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (5*p) (2*p) $ scale (1-scaleFactor*p) circ fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (5*p) (-2*p) $ scale (1-scaleFactor*p) circ where circ = withFillColor "blue" $ withStrokeColor "white" $ mkCircle 2 circEq = mkGroup [ circ , withFillColor "white" $ scale 0.5 $ center $ latexAlign "A=\\pi r^2"] mkFeatSprite :: Double -> Double -> Animation -> Scene s (Var s Double, Var s Double, Sprite s) mkFeatSprite xPos yPos ani = do spriteAt <- newVar 0 spriteTMod <- newVar 0 sprite <- newSprite $ do genAt <- unVar spriteAt genT <- unVar spriteTMod t <- spriteT d <- spriteDuration return $ let i = 1-genAt in translate (xPos*i) (yPos*i) $ scale (1+0.5*genAt) $ frameAtT (((t+genT)/d) `mod'` 1) ani return (spriteAt, spriteTMod, sprite) featSVG :: Animation featSVG = animate $ const $ scale 0.4 svgLogo feat3D :: Animation feat3D = rotateSphere & mapA (scale 0.5) & repeatA 10 frameAtT :: Double -> Animation -> SVG frameAtT t ani = getAnimationFrame SyncStretch ani t 1 featLaTeX :: Animation featLaTeX = animate $ \t -> translate 0 0.5 $ mkGroup [ scale 1.5 $ center $ withFillColor "white" $ latex "\\LaTeX" , frameAtT t $ fadeTransitions 0.2 $ map mkEQ [eq1, eq3, eq4, eq5] ] where eq1 = "\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}" eq2 = "e=mc^2" -- eq3 = "\\int_{a}^{b}f'(x)dx=f(b)-f(a)" eq3 = "\\Delta \\times E=- \\frac{\\partial B}{\\partial t}" eq4 = "\\frac{d}{dt}(\\frac{\\partial L}{\\partial \\dot{q}}) = \\frac{\\partial L}{\\partial q}" eq5 = "\\vec{E} = \\frac{\\sigma}{2\\epsilon_0}\\hat{n}" mkEQ txt = drawAnimation $ withStrokeColor "white" $ withFillColor "white" $ withStrokeWidth 0.01 $ translate 0 (-1.5) $ scale 0.5 $ center $ latexAlign txt fadeTransition :: Double -> Animation -> Animation -> Animation fadeTransition overlap a b = (a & pauseAtEnd overlap & applyE (overEnding overlap fadeOutE) ) `seqA` ( b & applyE (overBeginning overlap fadeInE) ) fadeTransitions :: Double -> [Animation] -> Animation fadeTransitions overlap = foldl (fadeTransition overlap) (pause 0) featWireSphere :: Animation featWireSphere = rotateWireSphere & mapA (scale 0.5) & reverseA & repeatA 10 introSVG :: Animation introSVG = scene $ do fork $ play $ animate $ const $ mkBackground "black" -- Title title <- newSprite $ pure $ translate 0 3.5 $ center $ withFillColor "white" $ latex "reanimate" spriteZ title 2 -- Shading shadeOpacity <- newVar 0 shade <- newSprite $ do opacity <- unVar shadeOpacity return $ withFillOpacity (0.8 * opacity) $ withFillColor "black" $ mkRect screenWidth screenHeight spriteZ shade 1 -- Modifier let tweenFeat sp var varT initWait dur = do wait initWait spriteZ sp 2 tweenVar shadeOpacity 1 $ \t i -> fromToS i 1 (curveS 2 t) tweenVar var 1 $ \t i -> fromToS i 1 (curveS 2 t) tweenVar varT 1 $ \t i -> fromToS i 1 (curveS 2 t) wait 1 tweenVar varT dur $ \t i -> fromToS i (1+dur) (t/dur) wait dur tweenVar var 1 $ \t i -> fromToS i 0 (curveS 2 t) tweenVar varT dur $ \t i -> fromToS i (1+dur+1) $ curveS 2 (t/dur) tweenVar shadeOpacity 1 $ \t i -> fromToS i 0 (curveS 2 t) wait 1 spriteZ sp 0 -- SVG (svgAt, svgT, svgS) <- mkFeatSprite (-5.5) 1.5 featSVG fork $ tweenFeat svgS svgAt svgT svgHighlight svgHighlightDur LaTeX (latexAt, latexT, latexS) <- mkFeatSprite 5.5 1.5 featLaTeX fork $ tweenFeat latexS latexAt latexT latexHighlight latexHighlightDur -- Tracing (traceAt, traceT, traceS) <- mkFeatSprite (-5.5) (-2.5) featWireSphere fork $ tweenFeat traceS traceAt traceT traceHighlight traceHighlightDur -- Raytracing (rayAt, rayT, rayS) <- mkFeatSprite 5.5 (-2.5) feat3D fork $ tweenFeat rayS rayAt rayT rayHighlight rayHighlightDur -- wait wait $ rayHighlight + rayHighlightDur + 2 + 10 return () where svgHighlight = 1 svgHighlightDur = 3 latexHighlight = svgHighlight+svgHighlightDur+2 latexHighlightDur = 3 traceHighlight = latexHighlight+latexHighlightDur+2 traceHighlightDur = 3 rayHighlight = traceHighlight+traceHighlightDur+2 rayHighlightDur = 3 drawAnimation :: SVG -> Animation drawAnimation = drawAnimation' 0.5 0.3 drawAnimation' :: Double -> Double -> SVG -> Animation drawAnimation' fillDur step svg = scene $ do forM_ (zip [0..] $ svgGlyphs svg) $ \(n, (fn, attr, tree)) -> do let sWidth = case toUserUnit defaultDPI <$> (attr ^. strokeWidth) of Just (Num d) -> d _ -> defaultStrokeWidth fork $ do wait (n*step) play $ mapA fn (animate (\t -> withFillOpacity 0 $ partialSvg t tree) & applyE (overEnding fillDur $ fadeLineOutE sWidth)) fork $ do wait (n*step+(1-fillDur)) newSprite $ do t <- spriteT return $ withStrokeWidth 0 $ fn $ withFillOpacity (min 1 $ t/fillDur) tree play $ animate ( \t - > withStrokeWidth 0 $ fn $ withFillOpacity t tree ) -- # setDuration fillDur -- # pauseAtEnd ((len-n)*step) where len = fromIntegral $ length $ svgGlyphs svg drawSphere :: Animation drawSphere = animate $ \t -> partialSvg t $ withStrokeColor "white" $ withStrokeWidth 0.01 $ withFillOpacity 0 $ lowerTransformations $ flipYAxis $ translate (-screenWidth/2) (-screenHeight/2) $ scale 0.00625 $ mkPath $ extractPath $ vectorize_ ["-i"] $ povraySlow' [] (script (svgAsPngFile texture) 0) rotateWireSphere :: Animation rotateWireSphere = animate $ \t -> withStrokeColor "white" $ withStrokeWidth 0.01 $ withFillOpacity 0 $ lowerTransformations $ flipYAxis $ translate (-screenWidth/2) (-screenHeight/2) $ scale (screenWidth/2560) $ mkPath $ extractPath $ vectorize_ ["-i"] $ povraySlow' [] (script (svgAsPngFile texture) (t*360/10)) rotateSphere :: Animation rotateSphere = animate $ \t -> povraySlow [] (script (svgAsPngFile texture) (t*360/10)) texture :: SVG texture = checker 10 10 script :: FilePath -> Double -> Text script png s = [text| //EXAMPLE OF SPHERE //Files with predefined colors and textures #include "colors.inc" #include "glass.inc" #include "golds.inc" #include "metals.inc" #include "stones.inc" #include "woods.inc" #include "shapes3.inc" //Place the camera camera { orthographic // angle 50 location <0,0,-10> look_at <0,0,0> //right x*image_width/image_height up <0,9,0> right <16,0,0> } //Ambient light to "brighten up" darker pictures global_settings { ambient_light White*3 } //Set a background color //background { color White } //background { color rgbt <0.1, 0, 0, 0> } // red background { color rgbt <0, 0, 0, 1> } // transparent //Sphere with specified center point and radius sphere { <0,0,0>, 2 texture { //pigment{ color rgbt <0,0,1,0.1> } uv_mapping pigment{ image_map{ png ${png_} } //color rgbt <0,0,1,0.1> } } rotate <0,${s'},0> rotate <-30,0,0> } |] where png_ = T.pack png precision = 0.1 s' = T.pack $ show $ fromIntegral (round (s / precision)) * precision checker :: Int -> Int -> SVG checker w h = withFillColor "white" $ withStrokeColor "white" $ withStrokeWidth 0.1 $ mkGroup [ withFillOpacity 0.8 $ mkBackground "blue" , mkGroup [ translate (stepX*x-offsetX + stepX/2) 0 $ mkLine (0, -screenHeight/2*0.9) (0, screenHeight/2*0.9) | x <- map fromIntegral [0..w-1] ] , mkGroup [ translate 0 (stepY*y-offsetY) $ mkLine (-screenWidth/2, 0) (screenWidth/2, 0) | y <- map fromIntegral [0..h] ] ] where stepX = screenWidth/fromIntegral w stepY = screenHeight/fromIntegral h offsetX = screenWidth/2 offsetY = screenHeight/2
null
https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/videos/showcase/showcase.hs
haskell
stack runghc --package reanimate # LANGUAGE ApplicativeDo # # LANGUAGE OverloadedStrings # # LANGUAGE QuasiQuotes # rotateSphere rotateWireSphere introSVG play $ drawSphere # setDuration 15 play $ rotateWireSphere # setDuration 2 sphereS <- newSprite $ do -- xValue <- freezeVar sphereX return $ \real_t d t -> translate ( xValue real_t ) 0 $ frameAt t a fork $ play $ rotateSphere # setDuration 1 circ eq3 = "\\int_{a}^{b}f'(x)dx=f(b)-f(a)" Title Shading Modifier SVG Tracing Raytracing wait # setDuration fillDur # pauseAtEnd ((len-n)*step)
#!/usr/bin/env stack module Main (main) where import Codec.Picture import Control.Lens ((^.),(&)) import Control.Monad import Data.Fixed import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Graphics.SvgTree (Number (..), strokeWidth, toUserUnit) import NeatInterpolation import Reanimate import Reanimate.Animation import Reanimate.Builtin.Images import Reanimate.Ease import Reanimate.Effect import Reanimate.Povray import Reanimate.Raster import Reanimate.Scene import Reanimate.Svg SCRIPT Some ideas lend themselves well to be illustrated . Take spheres , for example : It just so happens that the surface of a sphere is exactly 4 times the area of a circle with the same radius . Now , this relationship has already been visually explored by others in mucher greater detail so I 'll leave it at this . But there are countless other ideas and concepts that deserve to be illustrated yet have not . I want to remedy this , in part , by animating ideas I find interesting , but also by encouraging you to make your own animations . Every video on this channel , including this one , will be open - source with the source files linked in the description . If any of the graphics pique your interest then please download the code and play with it . The animations are created with a library called ' reanimate ' which , at its core , is a set of tools for generating individual frames as SVG images . Layered on top of this core are external components such as : * LaTeX , for typesetting equations , * a bitmap tracer , for turning pixel data into vector graphics , * and a raytracer , for generating 3D graphics , is inherently a pixel - based graphics technique but , with a bit of math , it and vector graphics can be overlayed with pixel - perfect precision . Everything is held together by the purely functional language . Haskell is particularlly well suited for this task since animations are inherently immutable . Some ideas lend themselves well to be illustrated. Take spheres, for example: It just so happens that the surface of a sphere is exactly 4 times the area of a circle with the same radius. Now, this relationship has already been visually explored by others in mucher greater detail so I'll leave it at this. But there are countless other ideas and concepts that deserve to be illustrated yet have not. I want to remedy this, in part, by animating ideas I find interesting, but also by encouraging you to make your own animations. Every video on this channel, including this one, will be open-source with the source files linked in the description. If any of the graphics pique your interest then please download the code and play with it. The animations are created with a library called 'reanimate' which, at its core, is a set of tools for generating individual frames as SVG images. Layered on top of this core are external components such as: * LaTeX, for typesetting equations, * a bitmap tracer, for turning pixel data into vector graphics, * and a raytracer, for generating 3D graphics, Raytracing is inherently a pixel-based graphics technique but, with a bit of math, it and vector graphics can be overlayed with pixel-perfect precision. Everything is held together by the purely functional language Haskell. Haskell is particularlly well suited for this task since animations are inherently immutable. -} main :: IO () main = reanimate $ addStatic (mkBackground "black") animate $ const $ checker 10 10 sphereIntro mapA ( scale 2 ) $ setDuration 20 featLaTeX playbackTest :: Animation playbackTest = setDuration 10 feat3D sphereIntro :: Animation sphereIntro = scene $ do # pauseAtEnd 2 # signalA ( powerS 2 ) fork $ play $ rotateWireSphere & setDuration 1 & repeatA 10 & takeA (2+5) & applyE (delayE 2 fadeOutE) sphereX <- newVar 0 sphereS <- newSpriteA $ rotateSphere & repeatA (5+3+1+2) let a = rotateSphere # setDuration 1 # repeatA ( 5 + 3 + 1 + 2 ) applyVar sphereX sphereS (\xValue -> translate xValue 0) spriteE sphereS (overBeginning 1 $ constE $ withGroupOpacity 0) spriteE sphereS (delayE 1 $ overBeginning 2 fadeInE) # repeatA ( 5 + 3 + 1 + 2 ) # applyE ( overBeginning 1 $ constE $ withGroupOpacity 0 ) # applyE ( delayE 1 $ overBeginning 2 fadeInE ) # applyE ( delayE 8 $ translateE ( -3 ) 0 ) wait 5 adjustZ (+1) $ play $ setDuration 3 $ animate $ \t -> partialSvg t $ withFillOpacity 0 $ rotate 180 $ pathify circ playZ 1 $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t - > withFillOpacity t $ let scaleFactor = 0.05 tweenVar sphereX 1 $ \t x -> fromToS x (-3) (curveS 3 t) fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (1*p) (2*p) $ scale (1-scaleFactor*p) circ fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (1*p) (-2*p) $ scale (1-scaleFactor*p) circ fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (5*p) (2*p) $ scale (1-scaleFactor*p) circ fork $ adjustZ (+1) $ play $ pauseAtEnd 2 $ setDuration 1 $ animate $ \t -> let p = curveS 3 t in withFillOpacity p $ translate (5*p) (-2*p) $ scale (1-scaleFactor*p) circ where circ = withFillColor "blue" $ withStrokeColor "white" $ mkCircle 2 circEq = mkGroup [ circ , withFillColor "white" $ scale 0.5 $ center $ latexAlign "A=\\pi r^2"] mkFeatSprite :: Double -> Double -> Animation -> Scene s (Var s Double, Var s Double, Sprite s) mkFeatSprite xPos yPos ani = do spriteAt <- newVar 0 spriteTMod <- newVar 0 sprite <- newSprite $ do genAt <- unVar spriteAt genT <- unVar spriteTMod t <- spriteT d <- spriteDuration return $ let i = 1-genAt in translate (xPos*i) (yPos*i) $ scale (1+0.5*genAt) $ frameAtT (((t+genT)/d) `mod'` 1) ani return (spriteAt, spriteTMod, sprite) featSVG :: Animation featSVG = animate $ const $ scale 0.4 svgLogo feat3D :: Animation feat3D = rotateSphere & mapA (scale 0.5) & repeatA 10 frameAtT :: Double -> Animation -> SVG frameAtT t ani = getAnimationFrame SyncStretch ani t 1 featLaTeX :: Animation featLaTeX = animate $ \t -> translate 0 0.5 $ mkGroup [ scale 1.5 $ center $ withFillColor "white" $ latex "\\LaTeX" , frameAtT t $ fadeTransitions 0.2 $ map mkEQ [eq1, eq3, eq4, eq5] ] where eq1 = "\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}" eq2 = "e=mc^2" eq3 = "\\Delta \\times E=- \\frac{\\partial B}{\\partial t}" eq4 = "\\frac{d}{dt}(\\frac{\\partial L}{\\partial \\dot{q}}) = \\frac{\\partial L}{\\partial q}" eq5 = "\\vec{E} = \\frac{\\sigma}{2\\epsilon_0}\\hat{n}" mkEQ txt = drawAnimation $ withStrokeColor "white" $ withFillColor "white" $ withStrokeWidth 0.01 $ translate 0 (-1.5) $ scale 0.5 $ center $ latexAlign txt fadeTransition :: Double -> Animation -> Animation -> Animation fadeTransition overlap a b = (a & pauseAtEnd overlap & applyE (overEnding overlap fadeOutE) ) `seqA` ( b & applyE (overBeginning overlap fadeInE) ) fadeTransitions :: Double -> [Animation] -> Animation fadeTransitions overlap = foldl (fadeTransition overlap) (pause 0) featWireSphere :: Animation featWireSphere = rotateWireSphere & mapA (scale 0.5) & reverseA & repeatA 10 introSVG :: Animation introSVG = scene $ do fork $ play $ animate $ const $ mkBackground "black" title <- newSprite $ pure $ translate 0 3.5 $ center $ withFillColor "white" $ latex "reanimate" spriteZ title 2 shadeOpacity <- newVar 0 shade <- newSprite $ do opacity <- unVar shadeOpacity return $ withFillOpacity (0.8 * opacity) $ withFillColor "black" $ mkRect screenWidth screenHeight spriteZ shade 1 let tweenFeat sp var varT initWait dur = do wait initWait spriteZ sp 2 tweenVar shadeOpacity 1 $ \t i -> fromToS i 1 (curveS 2 t) tweenVar var 1 $ \t i -> fromToS i 1 (curveS 2 t) tweenVar varT 1 $ \t i -> fromToS i 1 (curveS 2 t) wait 1 tweenVar varT dur $ \t i -> fromToS i (1+dur) (t/dur) wait dur tweenVar var 1 $ \t i -> fromToS i 0 (curveS 2 t) tweenVar varT dur $ \t i -> fromToS i (1+dur+1) $ curveS 2 (t/dur) tweenVar shadeOpacity 1 $ \t i -> fromToS i 0 (curveS 2 t) wait 1 spriteZ sp 0 (svgAt, svgT, svgS) <- mkFeatSprite (-5.5) 1.5 featSVG fork $ tweenFeat svgS svgAt svgT svgHighlight svgHighlightDur LaTeX (latexAt, latexT, latexS) <- mkFeatSprite 5.5 1.5 featLaTeX fork $ tweenFeat latexS latexAt latexT latexHighlight latexHighlightDur (traceAt, traceT, traceS) <- mkFeatSprite (-5.5) (-2.5) featWireSphere fork $ tweenFeat traceS traceAt traceT traceHighlight traceHighlightDur (rayAt, rayT, rayS) <- mkFeatSprite 5.5 (-2.5) feat3D fork $ tweenFeat rayS rayAt rayT rayHighlight rayHighlightDur wait $ rayHighlight + rayHighlightDur + 2 + 10 return () where svgHighlight = 1 svgHighlightDur = 3 latexHighlight = svgHighlight+svgHighlightDur+2 latexHighlightDur = 3 traceHighlight = latexHighlight+latexHighlightDur+2 traceHighlightDur = 3 rayHighlight = traceHighlight+traceHighlightDur+2 rayHighlightDur = 3 drawAnimation :: SVG -> Animation drawAnimation = drawAnimation' 0.5 0.3 drawAnimation' :: Double -> Double -> SVG -> Animation drawAnimation' fillDur step svg = scene $ do forM_ (zip [0..] $ svgGlyphs svg) $ \(n, (fn, attr, tree)) -> do let sWidth = case toUserUnit defaultDPI <$> (attr ^. strokeWidth) of Just (Num d) -> d _ -> defaultStrokeWidth fork $ do wait (n*step) play $ mapA fn (animate (\t -> withFillOpacity 0 $ partialSvg t tree) & applyE (overEnding fillDur $ fadeLineOutE sWidth)) fork $ do wait (n*step+(1-fillDur)) newSprite $ do t <- spriteT return $ withStrokeWidth 0 $ fn $ withFillOpacity (min 1 $ t/fillDur) tree play $ animate ( \t - > withStrokeWidth 0 $ fn $ withFillOpacity t tree ) where len = fromIntegral $ length $ svgGlyphs svg drawSphere :: Animation drawSphere = animate $ \t -> partialSvg t $ withStrokeColor "white" $ withStrokeWidth 0.01 $ withFillOpacity 0 $ lowerTransformations $ flipYAxis $ translate (-screenWidth/2) (-screenHeight/2) $ scale 0.00625 $ mkPath $ extractPath $ vectorize_ ["-i"] $ povraySlow' [] (script (svgAsPngFile texture) 0) rotateWireSphere :: Animation rotateWireSphere = animate $ \t -> withStrokeColor "white" $ withStrokeWidth 0.01 $ withFillOpacity 0 $ lowerTransformations $ flipYAxis $ translate (-screenWidth/2) (-screenHeight/2) $ scale (screenWidth/2560) $ mkPath $ extractPath $ vectorize_ ["-i"] $ povraySlow' [] (script (svgAsPngFile texture) (t*360/10)) rotateSphere :: Animation rotateSphere = animate $ \t -> povraySlow [] (script (svgAsPngFile texture) (t*360/10)) texture :: SVG texture = checker 10 10 script :: FilePath -> Double -> Text script png s = [text| //EXAMPLE OF SPHERE //Files with predefined colors and textures #include "colors.inc" #include "glass.inc" #include "golds.inc" #include "metals.inc" #include "stones.inc" #include "woods.inc" #include "shapes3.inc" //Place the camera camera { orthographic // angle 50 location <0,0,-10> look_at <0,0,0> //right x*image_width/image_height up <0,9,0> right <16,0,0> } //Ambient light to "brighten up" darker pictures global_settings { ambient_light White*3 } //Set a background color //background { color White } //background { color rgbt <0.1, 0, 0, 0> } // red background { color rgbt <0, 0, 0, 1> } // transparent //Sphere with specified center point and radius sphere { <0,0,0>, 2 texture { //pigment{ color rgbt <0,0,1,0.1> } uv_mapping pigment{ image_map{ png ${png_} } //color rgbt <0,0,1,0.1> } } rotate <0,${s'},0> rotate <-30,0,0> } |] where png_ = T.pack png precision = 0.1 s' = T.pack $ show $ fromIntegral (round (s / precision)) * precision checker :: Int -> Int -> SVG checker w h = withFillColor "white" $ withStrokeColor "white" $ withStrokeWidth 0.1 $ mkGroup [ withFillOpacity 0.8 $ mkBackground "blue" , mkGroup [ translate (stepX*x-offsetX + stepX/2) 0 $ mkLine (0, -screenHeight/2*0.9) (0, screenHeight/2*0.9) | x <- map fromIntegral [0..w-1] ] , mkGroup [ translate 0 (stepY*y-offsetY) $ mkLine (-screenWidth/2, 0) (screenWidth/2, 0) | y <- map fromIntegral [0..h] ] ] where stepX = screenWidth/fromIntegral w stepY = screenHeight/fromIntegral h offsetX = screenWidth/2 offsetY = screenHeight/2
042dc2079b5c4c97ec7a34f3506f17c90d074403c50552b3e2af17b54397d6b1
DYCI2/om-dyci2
om-preferences.lisp
;;;=================================================== ;;; OM - SuperVP SuperVP sound analysis and processing for OpenMusic ;;; Requires perliminary installation of SuperVP ( also included in AudioSculpt ) Set SuperVP path in OM preferences ( externals ) once the library is loaded . ;;; ;;; ;;; SUPERVP PREFERENCES Integrated in the ' Externals ' tab in OM preferences Authors : ( IRCAM - 2006 - 2010 ) ;;; ;;;=================================================== ; PREFERENCES FOR OM6 File author : ( IRCAM - 2006 - 2010 ) ;===================================================== (in-package :om) (defvar *SVP-PATH* "path to svp") (defvar *param-files-folder* nil) (defvar *delete-param-files* t) ;;;== PARAM FILES === (defmethod! set-svp-paramfiles-folder ((path string)) :icon 186 (setf *param-files-folder* (pathname path))) (defmethod! set-svp-paramfiles-folder ((path pathname)) :icon 186 (setf *param-files-folder* path)) (defmethod! svp-paramfile ((name string)) :icon 186 (make-pathname :directory (pathname-directory *param-files-folder*) :name name :host (pathname-host *param-files-folder*) :device (pathname-device *param-files-folder*))) (defmethod! svp-paramfile ((name null)) *param-files-folder*) = = = SVP PATH = = = (defmethod! set-svp-path ((path string)) :icon 186 (setf *SVP-PATH* (pathname path))) (defmethod! set-svp-path ((path pathname)) :icon 186 (setf *SVP-PATH* path)) (defmethod! svp-path () :icon 186 (namestring *SVP-PATH*)) ;;;===================== SVP PREFS (add-external-pref-module 'svp) (defmethod get-external-name ((module (eql 'svp))) "SuperVP") (defmethod get-external-module-vals ((module (eql 'svp)) modulepref) (get-pref modulepref :svp-options)) (defmethod get-external-module-path ((module (eql 'svp)) modulepref) (get-pref modulepref :svp-path)) (defmethod set-external-module-vals ((module (eql 'svp)) modulepref vals) (set-pref modulepref :svp-options vals)) (defmethod set-external-module-path ((module (eql 'svp)) modulepref path) (set-pref modulepref :svp-path path)) ;;; params folder (defun def-svp-options () (list *om-infiles-folder*)) (defmethod get-external-def-vals ((module (eql 'svp))) (let ((libpath (lib-pathname (find-library "OM-SuperVP")))) (list :svp-path (om-make-pathname :directory (append (pathname-directory libpath) '("bin") #+macosx '("mac" "SuperVP.app" "Contents" "MacOS") #+win32 '("win") #+linux '("linux") ) :host (pathname-host libpath) :device (pathname-device libpath) :name "supervp" #+win32 :type #+win32 "exe") :svp-options (def-svp-options)))) (defmethod save-external-prefs ((module (eql 'svp))) `(:svp-path ,(om-save-pathname *SVP-PATH*) :svp-options (list ,(om-save-pathname *param-files-folder*)))) (defmethod put-external-preferences ((module (eql 'svp)) moduleprefs) (let ((list-prefs (get-pref moduleprefs :svp-options))) (when list-prefs (if (probe-file (nth 0 list-prefs)) (setf *param-files-folder* (nth 0 list-prefs)) (progn (setf (nth 0 list-prefs) (nth 0 (nth (+ 1 (position :svp-options (get-external-def-vals module))) (get-external-def-vals module)))) (set-pref moduleprefs :svp-options list-prefs) ( push : svp - * restore - defaults * ) )) ) (when (get-pref moduleprefs :svp-path) (setf *SVP-PATH* (find-true-external (get-pref moduleprefs :svp-path)))) )) (put-external-pref-values 'svp) (defun forum-authorize (exe-path) (let ((auth-file (om-choose-file-dialog :prompt "Pleas select the .txt file provided by the ForumNet code generator"))) (when (and auth-file (probe-file auth-file)) (om-cmd-line (format nil "~s -init_key_file ~s" (namestring (find-true-external exe-path)) (namestring auth-file)) t t) (print "Authorization... done") ))) (defmethod show-external-prefs-dialog ((module (eql 'svp)) prefvals) (let* ((rep-list (copy-list prefvals)) (dialog (om-make-window 'om-dialog :window-title "SuperVP Options" :size (om-make-point 300 200) :position :centered :resizable nil :maximize nil :close nil)) paramstext (i 0)) (om-add-subviews dialog (om-make-dialog-item 'om-static-text (om-make-point 20 (incf i 20)) (om-make-point 200 20) "SuperVP Forum Activation" :font *om-default-font1*) (om-make-dialog-item 'om-button (om-make-point 180 (- i 4)) (om-make-point 50 20) "Go!" :di-action (om-dialog-item-act item (declare (ignore item)) (if (probe-file *svp-path*) (forum-authorize *svp-path*) (om-message-dialog "Please set SuperVP path first!")))) (om-make-dialog-item 'om-static-text (om-make-point 20 (incf i 55)) (om-make-point 300 20) "Param Files folder (read/write):" :font *om-default-font1b*) (setf paramstext (om-make-dialog-item 'om-static-text (om-make-point 20 (1+ (incf i 16))) (om-make-point 220 50) (om-namestring (nth 0 prefvals)) :font *om-default-font1*)) (om-make-dialog-item 'om-button (om-make-point 240 i) (om-make-point 50 24) "..." :di-action (om-dialog-item-act item (declare (ignore item)) (let ((newpath (om-choose-directory-dialog :directory (om-namestring (nth 0 prefvals))))) (when newpath (om-set-dialog-item-text paramstext (om-namestring newpath)) )))) ;;; boutons (om-make-dialog-item 'om-button (om-make-point 20 (incf i 66)) (om-make-point 80 20) "Restore" :di-action (om-dialog-item-act item (om-set-dialog-item-text paramstext (namestring (nth 0 (def-svp-options)))) )) (om-make-dialog-item 'om-button (om-make-point 130 i) (om-make-point 80 20) "Cancel" :di-action (om-dialog-item-act item (om-return-from-modal-dialog dialog nil))) (om-make-dialog-item 'om-button (om-make-point 210 i) (om-make-point 80 20) "OK" :di-action (om-dialog-item-act item (let ((argerror nil) (partxt (om-dialog-item-text paramstext))) (setf (nth 0 rep-list) partxt) (if argerror (om-message-dialog (format nil "Error in a SuperVP option.~% Preferences could not be recorded.")) (om-return-from-modal-dialog dialog rep-list)) )) :default-button t :focus t) ) (om-modal-dialog dialog)))
null
https://raw.githubusercontent.com/DYCI2/om-dyci2/a51e6c51ec60ffabb799c9ee08d2173c30509ac2/om-dyci2/dependencies/OM-SuperVP%202.13/sources/om-preferences.lisp
lisp
=================================================== SUPERVP PREFERENCES =================================================== PREFERENCES FOR OM6 ===================================================== == PARAM FILES === ===================== params folder boutons
OM - SuperVP SuperVP sound analysis and processing for OpenMusic Requires perliminary installation of SuperVP ( also included in AudioSculpt ) Set SuperVP path in OM preferences ( externals ) once the library is loaded . Integrated in the ' Externals ' tab in OM preferences Authors : ( IRCAM - 2006 - 2010 ) File author : ( IRCAM - 2006 - 2010 ) (in-package :om) (defvar *SVP-PATH* "path to svp") (defvar *param-files-folder* nil) (defvar *delete-param-files* t) (defmethod! set-svp-paramfiles-folder ((path string)) :icon 186 (setf *param-files-folder* (pathname path))) (defmethod! set-svp-paramfiles-folder ((path pathname)) :icon 186 (setf *param-files-folder* path)) (defmethod! svp-paramfile ((name string)) :icon 186 (make-pathname :directory (pathname-directory *param-files-folder*) :name name :host (pathname-host *param-files-folder*) :device (pathname-device *param-files-folder*))) (defmethod! svp-paramfile ((name null)) *param-files-folder*) = = = SVP PATH = = = (defmethod! set-svp-path ((path string)) :icon 186 (setf *SVP-PATH* (pathname path))) (defmethod! set-svp-path ((path pathname)) :icon 186 (setf *SVP-PATH* path)) (defmethod! svp-path () :icon 186 (namestring *SVP-PATH*)) SVP PREFS (add-external-pref-module 'svp) (defmethod get-external-name ((module (eql 'svp))) "SuperVP") (defmethod get-external-module-vals ((module (eql 'svp)) modulepref) (get-pref modulepref :svp-options)) (defmethod get-external-module-path ((module (eql 'svp)) modulepref) (get-pref modulepref :svp-path)) (defmethod set-external-module-vals ((module (eql 'svp)) modulepref vals) (set-pref modulepref :svp-options vals)) (defmethod set-external-module-path ((module (eql 'svp)) modulepref path) (set-pref modulepref :svp-path path)) (defun def-svp-options () (list *om-infiles-folder*)) (defmethod get-external-def-vals ((module (eql 'svp))) (let ((libpath (lib-pathname (find-library "OM-SuperVP")))) (list :svp-path (om-make-pathname :directory (append (pathname-directory libpath) '("bin") #+macosx '("mac" "SuperVP.app" "Contents" "MacOS") #+win32 '("win") #+linux '("linux") ) :host (pathname-host libpath) :device (pathname-device libpath) :name "supervp" #+win32 :type #+win32 "exe") :svp-options (def-svp-options)))) (defmethod save-external-prefs ((module (eql 'svp))) `(:svp-path ,(om-save-pathname *SVP-PATH*) :svp-options (list ,(om-save-pathname *param-files-folder*)))) (defmethod put-external-preferences ((module (eql 'svp)) moduleprefs) (let ((list-prefs (get-pref moduleprefs :svp-options))) (when list-prefs (if (probe-file (nth 0 list-prefs)) (setf *param-files-folder* (nth 0 list-prefs)) (progn (setf (nth 0 list-prefs) (nth 0 (nth (+ 1 (position :svp-options (get-external-def-vals module))) (get-external-def-vals module)))) (set-pref moduleprefs :svp-options list-prefs) ( push : svp - * restore - defaults * ) )) ) (when (get-pref moduleprefs :svp-path) (setf *SVP-PATH* (find-true-external (get-pref moduleprefs :svp-path)))) )) (put-external-pref-values 'svp) (defun forum-authorize (exe-path) (let ((auth-file (om-choose-file-dialog :prompt "Pleas select the .txt file provided by the ForumNet code generator"))) (when (and auth-file (probe-file auth-file)) (om-cmd-line (format nil "~s -init_key_file ~s" (namestring (find-true-external exe-path)) (namestring auth-file)) t t) (print "Authorization... done") ))) (defmethod show-external-prefs-dialog ((module (eql 'svp)) prefvals) (let* ((rep-list (copy-list prefvals)) (dialog (om-make-window 'om-dialog :window-title "SuperVP Options" :size (om-make-point 300 200) :position :centered :resizable nil :maximize nil :close nil)) paramstext (i 0)) (om-add-subviews dialog (om-make-dialog-item 'om-static-text (om-make-point 20 (incf i 20)) (om-make-point 200 20) "SuperVP Forum Activation" :font *om-default-font1*) (om-make-dialog-item 'om-button (om-make-point 180 (- i 4)) (om-make-point 50 20) "Go!" :di-action (om-dialog-item-act item (declare (ignore item)) (if (probe-file *svp-path*) (forum-authorize *svp-path*) (om-message-dialog "Please set SuperVP path first!")))) (om-make-dialog-item 'om-static-text (om-make-point 20 (incf i 55)) (om-make-point 300 20) "Param Files folder (read/write):" :font *om-default-font1b*) (setf paramstext (om-make-dialog-item 'om-static-text (om-make-point 20 (1+ (incf i 16))) (om-make-point 220 50) (om-namestring (nth 0 prefvals)) :font *om-default-font1*)) (om-make-dialog-item 'om-button (om-make-point 240 i) (om-make-point 50 24) "..." :di-action (om-dialog-item-act item (declare (ignore item)) (let ((newpath (om-choose-directory-dialog :directory (om-namestring (nth 0 prefvals))))) (when newpath (om-set-dialog-item-text paramstext (om-namestring newpath)) )))) (om-make-dialog-item 'om-button (om-make-point 20 (incf i 66)) (om-make-point 80 20) "Restore" :di-action (om-dialog-item-act item (om-set-dialog-item-text paramstext (namestring (nth 0 (def-svp-options)))) )) (om-make-dialog-item 'om-button (om-make-point 130 i) (om-make-point 80 20) "Cancel" :di-action (om-dialog-item-act item (om-return-from-modal-dialog dialog nil))) (om-make-dialog-item 'om-button (om-make-point 210 i) (om-make-point 80 20) "OK" :di-action (om-dialog-item-act item (let ((argerror nil) (partxt (om-dialog-item-text paramstext))) (setf (nth 0 rep-list) partxt) (if argerror (om-message-dialog (format nil "Error in a SuperVP option.~% Preferences could not be recorded.")) (om-return-from-modal-dialog dialog rep-list)) )) :default-button t :focus t) ) (om-modal-dialog dialog)))
fc32e7e5b708a48d2b7b8a50f5960db22fa79c1034640e194e7f91ca6c6cc290
xively/clj-mqtt
unsubscribe_test.clj
(ns mqtt.packets.unsubscribe-test (:use clojure.test mqtt.test-helpers mqtt.decoder mqtt.encoder mqtt.packets.common mqtt.packets.unsubscribe) (:import [io.netty.buffer Unpooled])) (deftest unsubscribe-validate-message-test (testing "returns when valid" (let [packet {:type :unsubscribe}] (is (= packet (validate-message packet)))))) (deftest encoding-unsubscribe-packet-test (testing "when encoding a simple unsubscribe packet" (let [encoder (make-encoder) packet {:type :unsubscribe :message-id 1 :topics ["a/b"]} out (Unpooled/buffer 9)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) (into [] (bytes-to-byte-array ;; fixed header 0xA2 ;; remaining length 0x07 ;; message id 0x00 0x01 ;; topic 0x00 0x03 "a/b")))))) (testing "when encoding an unsubscribe packet with two packets" (let [encoder (make-encoder) packet {:type :unsubscribe :message-id 5 :topics ["a/b", "c/d"]} out (Unpooled/buffer 14)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) (into [] (bytes-to-byte-array ;; fixed header 0xA2 ;; remaining length 12 ;; message id 0x00 0x05 ;; topics 0x00 0x03 "a/b" 0x00 0x03 "c/d"))))))) (deftest decoding-unsubscribe-packet-test (testing "when parsing a packet with a single topic" (let [decoder (make-decoder) packet (bytes-to-byte-buffer ;; fixed header 0xA2 ;; remaining length 0x07 ;; message id 0x00 0x01 ;; topic 0x00 0x03 "a/b") out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :unsubscribe (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 1 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 1 (:message-id decoded)))) (testing "parses the topics" (is (= ["a/b"] (:topics decoded)))))) (testing "when parsing a packet with two topics" (let [decoder (make-decoder) packet (bytes-to-byte-buffer ;; fixed header 0xA2 ;; remaining length 12 ;; message id 0x00 0x06 ;; topic 0x00 0x03 "a/b" 0x00 0x03 "c/d") out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :unsubscribe (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 1 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 6 (:message-id decoded)))) (testing "parses the topics" (is (= ["a/b", "c/d"] (:topics decoded)))))))
null
https://raw.githubusercontent.com/xively/clj-mqtt/74964112505da717ea88279b62f239146450528c/test/mqtt/packets/unsubscribe_test.clj
clojure
fixed header remaining length message id topic fixed header remaining length message id topics fixed header remaining length message id topic fixed header remaining length message id topic
(ns mqtt.packets.unsubscribe-test (:use clojure.test mqtt.test-helpers mqtt.decoder mqtt.encoder mqtt.packets.common mqtt.packets.unsubscribe) (:import [io.netty.buffer Unpooled])) (deftest unsubscribe-validate-message-test (testing "returns when valid" (let [packet {:type :unsubscribe}] (is (= packet (validate-message packet)))))) (deftest encoding-unsubscribe-packet-test (testing "when encoding a simple unsubscribe packet" (let [encoder (make-encoder) packet {:type :unsubscribe :message-id 1 :topics ["a/b"]} out (Unpooled/buffer 9)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) (into [] (bytes-to-byte-array 0xA2 0x07 0x00 0x01 0x00 0x03 "a/b")))))) (testing "when encoding an unsubscribe packet with two packets" (let [encoder (make-encoder) packet {:type :unsubscribe :message-id 5 :topics ["a/b", "c/d"]} out (Unpooled/buffer 14)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) (into [] (bytes-to-byte-array 0xA2 12 0x00 0x05 0x00 0x03 "a/b" 0x00 0x03 "c/d"))))))) (deftest decoding-unsubscribe-packet-test (testing "when parsing a packet with a single topic" (let [decoder (make-decoder) 0xA2 0x07 0x00 0x01 0x00 0x03 "a/b") out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :unsubscribe (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 1 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 1 (:message-id decoded)))) (testing "parses the topics" (is (= ["a/b"] (:topics decoded)))))) (testing "when parsing a packet with two topics" (let [decoder (make-decoder) 0xA2 12 0x00 0x06 0x00 0x03 "a/b" 0x00 0x03 "c/d") out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :unsubscribe (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 1 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 6 (:message-id decoded)))) (testing "parses the topics" (is (= ["a/b", "c/d"] (:topics decoded)))))))
aef2198d43c73d0c0661b19b172bfc6ea6e64f9acb6a58071b2acce7646e7ef0
tezos/tezos-mirror
test_sc_rollup_tick_repr.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2022 Nomadic Labs < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) (** Testing ------- Component: Protocol Library Invocation: dune exec \ src/proto_alpha/lib_protocol/test/pbt/test_sc_rollup_tick_repr.exe Subject: Operations in Tick_repr *) open Protocol.Alpha_context.Sc_rollup open QCheck2 (** A generator for ticks *) let tick = let open Gen in let+ n = nat in Option.value ~default:Tick.initial (Tick.of_int n) * For all x , x = initial \/ x > initial . let test_initial_is_bottom = Test.make ~name:"x = initial \\/ x > initial" tick @@ fun x -> Tick.(x = initial || x > initial) (** For all x, next x > x. *) let test_next_is_monotonic = Test.make ~name:"next x > x" tick @@ fun x -> Tick.(next x > x) * Distance from self to self is zero let test_distance_from_self = Test.make ~name:"distance from x to x is 0" tick (fun x -> Z.(equal (Tick.distance x x) zero)) (** Distance from non-self is non-zero. *) let test_distance_from_non_self = Test.make ~name:"distance from non-self is non-zero" (Gen.pair tick tick) (fun (x, y) -> let dist = Tick.distance x y in if x = y then Compare.Z.(dist = Z.zero) else Compare.Z.(dist <> Z.zero)) (** Distance is symmetric . *) let test_distance_symmetry = Test.make ~name:"distance is a distance (symmetry)" (Gen.pair tick tick) (fun (x, y) -> Z.(equal (Tick.distance x y) (Tick.distance y x))) (** Distance satisfies triangular inequality. *) let test_distance_triangle_inequality = Test.make ~name:"distance is a distance (triangle inequality)" (Gen.triple tick tick tick) (fun (x, y, z) -> Tick.(Z.(geq (distance x y + distance y z) (distance x z)))) (** Test that [of_int x = Some t] iff [x >= 0] *) let test_of_int = Test.make ~name:"of_int only accepts natural numbers" Gen.int (fun x -> match Tick.of_int x with None -> x < 0 | Some _ -> x >= 0) (** Test [of_int o to_int = identity]. *) let test_of_int_to_int = Test.make ~name:"to_int o of_int = identity" tick @@ fun x -> Tick.( match to_int x with | None -> (* by the tick generator definition. *) assert false | Some i -> ( match of_int i with Some y -> y = x | None -> false)) let tests = [ test_next_is_monotonic; test_initial_is_bottom; test_distance_from_self; test_distance_from_non_self; test_distance_symmetry; test_distance_triangle_inequality; test_of_int; test_of_int_to_int; ] let () = Alcotest.run "Tick_repr" [(Protocol.name ^ ": Tick_repr", Qcheck2_helpers.qcheck_wrap tests)]
null
https://raw.githubusercontent.com/tezos/tezos-mirror/39e976ad6eae6446af8ca17ef4a63475ab9fe2b9/src/proto_016_PtMumbai/lib_protocol/test/pbt/test_sc_rollup_tick_repr.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Testing ------- Component: Protocol Library Invocation: dune exec \ src/proto_alpha/lib_protocol/test/pbt/test_sc_rollup_tick_repr.exe Subject: Operations in Tick_repr * A generator for ticks * For all x, next x > x. * Distance from non-self is non-zero. * Distance is symmetric . * Distance satisfies triangular inequality. * Test that [of_int x = Some t] iff [x >= 0] * Test [of_int o to_int = identity]. by the tick generator definition.
Copyright ( c ) 2022 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Protocol.Alpha_context.Sc_rollup open QCheck2 let tick = let open Gen in let+ n = nat in Option.value ~default:Tick.initial (Tick.of_int n) * For all x , x = initial \/ x > initial . let test_initial_is_bottom = Test.make ~name:"x = initial \\/ x > initial" tick @@ fun x -> Tick.(x = initial || x > initial) let test_next_is_monotonic = Test.make ~name:"next x > x" tick @@ fun x -> Tick.(next x > x) * Distance from self to self is zero let test_distance_from_self = Test.make ~name:"distance from x to x is 0" tick (fun x -> Z.(equal (Tick.distance x x) zero)) let test_distance_from_non_self = Test.make ~name:"distance from non-self is non-zero" (Gen.pair tick tick) (fun (x, y) -> let dist = Tick.distance x y in if x = y then Compare.Z.(dist = Z.zero) else Compare.Z.(dist <> Z.zero)) let test_distance_symmetry = Test.make ~name:"distance is a distance (symmetry)" (Gen.pair tick tick) (fun (x, y) -> Z.(equal (Tick.distance x y) (Tick.distance y x))) let test_distance_triangle_inequality = Test.make ~name:"distance is a distance (triangle inequality)" (Gen.triple tick tick tick) (fun (x, y, z) -> Tick.(Z.(geq (distance x y + distance y z) (distance x z)))) let test_of_int = Test.make ~name:"of_int only accepts natural numbers" Gen.int (fun x -> match Tick.of_int x with None -> x < 0 | Some _ -> x >= 0) let test_of_int_to_int = Test.make ~name:"to_int o of_int = identity" tick @@ fun x -> Tick.( match to_int x with | Some i -> ( match of_int i with Some y -> y = x | None -> false)) let tests = [ test_next_is_monotonic; test_initial_is_bottom; test_distance_from_self; test_distance_from_non_self; test_distance_symmetry; test_distance_triangle_inequality; test_of_int; test_of_int_to_int; ] let () = Alcotest.run "Tick_repr" [(Protocol.name ^ ": Tick_repr", Qcheck2_helpers.qcheck_wrap tests)]
158da65bbdcb9fd458352f4736e7f91f109dd18674ce3b22fe41c725096a7b03
deadtrickster/prometheus.cl
int-counter.lisp
(in-package #:prometheus) (define-constant +counter-default+ 0) (defclass int-counter (counter) () (:default-initargs :type "counter")) (defmethod mf-make-metric ((metric int-counter) labels) (make-instance 'int-counter-metric :labels labels)) (defstruct int-counter-storage (value 0 :type (unsigned-byte 64))) (defclass int-counter-metric (simple-metric) ((value :initform (make-int-counter-storage)))) (defmethod metric-value ((m int-counter-metric)) #-sbcl (call-next-method) #+sbcl (int-counter-storage-value (slot-value m 'value))) (defun check-int-counter-value (value) ) (defmethod counter.inc% ((int-counter int-counter-metric) n labels) (declare (optimize (speed 3) (safety 0) (debug 0))) (unless (typep n '(unsigned-byte 64)) (error 'invalid-value-error :value n :reason "value is not an uint64")) #-sbcl (call-next-method) #+sbcl (sb-ext:atomic-incf (int-counter-storage-value (slot-value int-counter 'value)) n)) (defmethod counter.reset ((int-counter int-counter-metric) &key labels) (declare (ignore labels)) (synchronize int-counter (setf (slot-value int-counter 'value) (make-int-counter-storage)))) (defun make-int-counter (&key name help labels value (registry *default-registry*)) (check-value-or-labels value labels) (let ((int-counter (make-instance 'int-counter :name name :help help :labels labels :registry registry))) (when value (counter.inc int-counter :value value)) int-counter))
null
https://raw.githubusercontent.com/deadtrickster/prometheus.cl/60572b793135e8ab5a857d47cc1a5fe0af3a2d53/src/prometheus/metrics/int-counter.lisp
lisp
(in-package #:prometheus) (define-constant +counter-default+ 0) (defclass int-counter (counter) () (:default-initargs :type "counter")) (defmethod mf-make-metric ((metric int-counter) labels) (make-instance 'int-counter-metric :labels labels)) (defstruct int-counter-storage (value 0 :type (unsigned-byte 64))) (defclass int-counter-metric (simple-metric) ((value :initform (make-int-counter-storage)))) (defmethod metric-value ((m int-counter-metric)) #-sbcl (call-next-method) #+sbcl (int-counter-storage-value (slot-value m 'value))) (defun check-int-counter-value (value) ) (defmethod counter.inc% ((int-counter int-counter-metric) n labels) (declare (optimize (speed 3) (safety 0) (debug 0))) (unless (typep n '(unsigned-byte 64)) (error 'invalid-value-error :value n :reason "value is not an uint64")) #-sbcl (call-next-method) #+sbcl (sb-ext:atomic-incf (int-counter-storage-value (slot-value int-counter 'value)) n)) (defmethod counter.reset ((int-counter int-counter-metric) &key labels) (declare (ignore labels)) (synchronize int-counter (setf (slot-value int-counter 'value) (make-int-counter-storage)))) (defun make-int-counter (&key name help labels value (registry *default-registry*)) (check-value-or-labels value labels) (let ((int-counter (make-instance 'int-counter :name name :help help :labels labels :registry registry))) (when value (counter.inc int-counter :value value)) int-counter))
690cca9208de59a7551a4ee8613310b022b5ae8e5b51be54c7a76ba6b6288750
imitator-model-checker/imitator
Cache.mli
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification ( ENS Cachan & CNRS , France ) * Université Paris 13 , LIPN , CNRS , France * * Module description : Cache * * File contributors : , * Created : 2010 ( ? ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification (ENS Cachan & CNRS, France) * Université Paris 13, LIPN, CNRS, France * * Module description: Cache * * File contributors : Ulrich Kühne, Étienne André * Created : 2010 (?) * ************************************************************) open LinearConstraint open Automaton type ('a, 'b) t (** construct a cache given a hash function and the maximum size *) val make: ('a -> int) -> int -> ('a, 'b) t (** remove all entries *) val flush: ('a, 'b) t -> unit (** change the size of the cache, flushing all entries *) val resize: ('a, 'b) t -> int -> unit (** find an item corresponding to a given key *) val find: ('a, 'b) t -> 'a -> 'b option (** store an item associated with a key *) val store: ('a, 'b) t -> 'a -> 'b -> unit (*(** print statistics *) val print_stats: ('a, 'b) t -> unit*)
null
https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/Cache.mli
ocaml
* construct a cache given a hash function and the maximum size * remove all entries * change the size of the cache, flushing all entries * find an item corresponding to a given key * store an item associated with a key (** print statistics
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification ( ENS Cachan & CNRS , France ) * Université Paris 13 , LIPN , CNRS , France * * Module description : Cache * * File contributors : , * Created : 2010 ( ? ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification (ENS Cachan & CNRS, France) * Université Paris 13, LIPN, CNRS, France * * Module description: Cache * * File contributors : Ulrich Kühne, Étienne André * Created : 2010 (?) * ************************************************************) open LinearConstraint open Automaton type ('a, 'b) t val make: ('a -> int) -> int -> ('a, 'b) t val flush: ('a, 'b) t -> unit val resize: ('a, 'b) t -> int -> unit val find: ('a, 'b) t -> 'a -> 'b option val store: ('a, 'b) t -> 'a -> 'b -> unit val print_stats: ('a, 'b) t -> unit*)
da0c037d948d73861e874765cf3abd4f8c175470517f58d283b3c57394c4980a
typeclasses/haskell-phrasebook
logging.hs
import Control.Exception.Safe (displayException, tryAny) import Data.Foldable (fold) import System.Directory (getPermissions, writable) import System.Environment (getEnv) import System.IO (hPutStr, stdout, stderr) data Level = Info | Error data Event = Event Level String data Log = Log { record :: Event -> IO () } consoleLog = Log $ \(Event level message) -> hPutStr (standardStream level) (message <> "\n") standardStream Info = stdout standardStream Error = stderr fileLog path = Log $ \(Event level message) -> appendFile (path level) (message <> "\n") formattedLog topic log = Log $ \event -> record log (formatEvent topic event) formatEvent topic (Event level msg) = Event level msg' where msg' = paren (topic ! levelString level) ! msg paren x = "(" <> x <> ")" x ! y = x <> " " <> y levelString Info = "info" levelString Error = "error" nullLog = Log (\_ -> return ()) multiLog log1 log2 = Log $ \event -> do record log1 event record log2 event instance Semigroup Log where (<>) = multiLog instance Monoid Log where mempty = nullLog recoverFromException log action = do result <- tryAny action case result of Left e -> do record log (Event Error (displayException e)) return Nothing Right x -> return (Just x) main = do let bootLog = formattedLog "Boot" consoleLog record bootLog (Event Info "Starting") fileLog <- recoverFromException bootLog initFileLog let appLog = formattedLog "App" consoleLog <> fold fileLog record appLog (Event Info "Application started") -- ... initFileLog = do infoPath <- envLogPath "INFO" errorPath <- envLogPath "ERROR" let path Info = infoPath path Error = errorPath return (fileLog path) envLogPath varName = do path <- getEnv varName assertWritable path return path assertWritable path = do permissions <- getPermissions path case writable permissions of True -> return () False -> fail ("Log path" ! path ! "is not writable")
null
https://raw.githubusercontent.com/typeclasses/haskell-phrasebook/61ee6a7e63e4d6fc0e86c0cb9dc2c0d9f06b9537/logging.hs
haskell
...
import Control.Exception.Safe (displayException, tryAny) import Data.Foldable (fold) import System.Directory (getPermissions, writable) import System.Environment (getEnv) import System.IO (hPutStr, stdout, stderr) data Level = Info | Error data Event = Event Level String data Log = Log { record :: Event -> IO () } consoleLog = Log $ \(Event level message) -> hPutStr (standardStream level) (message <> "\n") standardStream Info = stdout standardStream Error = stderr fileLog path = Log $ \(Event level message) -> appendFile (path level) (message <> "\n") formattedLog topic log = Log $ \event -> record log (formatEvent topic event) formatEvent topic (Event level msg) = Event level msg' where msg' = paren (topic ! levelString level) ! msg paren x = "(" <> x <> ")" x ! y = x <> " " <> y levelString Info = "info" levelString Error = "error" nullLog = Log (\_ -> return ()) multiLog log1 log2 = Log $ \event -> do record log1 event record log2 event instance Semigroup Log where (<>) = multiLog instance Monoid Log where mempty = nullLog recoverFromException log action = do result <- tryAny action case result of Left e -> do record log (Event Error (displayException e)) return Nothing Right x -> return (Just x) main = do let bootLog = formattedLog "Boot" consoleLog record bootLog (Event Info "Starting") fileLog <- recoverFromException bootLog initFileLog let appLog = formattedLog "App" consoleLog <> fold fileLog record appLog (Event Info "Application started") initFileLog = do infoPath <- envLogPath "INFO" errorPath <- envLogPath "ERROR" let path Info = infoPath path Error = errorPath return (fileLog path) envLogPath varName = do path <- getEnv varName assertWritable path return path assertWritable path = do permissions <- getPermissions path case writable permissions of True -> return () False -> fail ("Log path" ! path ! "is not writable")
3ace4a18878d82b87a18363d3aec7e10b6cef1b47e11b627ac9fb5ff0f496ad6
benzap/eden
expression.cljc
(ns eden.std.expression (:require [eden.std.token :refer [TokenType token-type]])) (defprotocol Expression (evaluate-expression [this])) (def EXPRESSION## ::expression) (defn isa-expression? [obj] (when (satisfies? TokenType obj) (= EXPRESSION## (token-type obj))))
null
https://raw.githubusercontent.com/benzap/eden/dbfa63dc18dbc5ef18a9b2b16dbb7af0e633f6d0/src/eden/std/expression.cljc
clojure
(ns eden.std.expression (:require [eden.std.token :refer [TokenType token-type]])) (defprotocol Expression (evaluate-expression [this])) (def EXPRESSION## ::expression) (defn isa-expression? [obj] (when (satisfies? TokenType obj) (= EXPRESSION## (token-type obj))))