_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
ce26b3553d9b97b30a0da7297d57d3a58fda58a4c78e148c7e2710683b95c0e0
hamidreza-s/Tecipe
echo_server_app.erl
-module(echo_server_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> application:ensure_started(tecipe), tecipe:start_listener(echo_server, 8080, {echo_handler, echo, []}, [{monitor, true}], [{reuseaddr, true}]), echo_server_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/hamidreza-s/Tecipe/bcafcafec4c9c5981e6b89537808f3c9e94ea290/examples/echo_server/src/echo_server_app.erl
erlang
-module(echo_server_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> application:ensure_started(tecipe), tecipe:start_listener(echo_server, 8080, {echo_handler, echo, []}, [{monitor, true}], [{reuseaddr, true}]), echo_server_sup:start_link(). stop(_State) -> ok.
134300d630cf9ec3384b61553689254a71081ad08f770821b7dcf9725c8ef4d7
manuel-serrano/hop
propagation.scm
;*=====================================================================*/ * serrano / prgm / project / hop/2.5.x / scheme2js / propagation.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : 2007 - 12 * / * Last change : Fri Jul 19 15:31:15 2013 ( serrano ) * / * Copyright : 2013 * / ;* ------------------------------------------------------------- */ * / Variable propagation * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module propagation (import config tools nodes export-desc walk var-ref-util free-vars side verbose mutable-strings) (static (class Prop-Env call/cc?::bool suspend/resume?::bool bigloo-runtime-eval?::bool) (wide-class Prop-Call/cc-Call::Call mutated-vars ;; vars that are mutated after the call visible-whiles) (wide-class Prop-While::While mutated-vars) ;; vars that are mutated inside the while. (wide-class Prop-Label::Label var/vals-list) (wide-class Prop-Var::Var (escaping-mutated?::bool (default #f)) (current (default #f))) (class Prop-List-Box v::pair-nil)) (export (propagation! tree::Module))) ;*---------------------------------------------------------------------*/ ;* propagation! ... */ ;*---------------------------------------------------------------------*/ ;; uses While -> must be after while-pass ;; ;; locally propagate variables/constants. -> Removes var-count. ;; first pass : determine which variables are modified inside loops . ;; call/cc-calls count as loops. suspend/resumes don't. ;; each of these loops have a list of all mutated vars. ;; Also determine if a variable is changed outside its local scope (that is, if ;; it escapes, is it modified in these functions). -> .escaping-mutated? ;; second pass : linearly walk through the code . the variables ' current ' holds ;; the current value. a set! obviously updates it. a loop kills all the ;; variables that are affected. ;; if we have a binding x = y, and this is the only use of y (see ;; var-elimination), then we replace x by y. Exception applies for call/cc. (define (propagation! tree) (when (config 'propagation) (verbose "propagation") (side-effect tree) (free-vars tree) (pass1 tree) (pass2! tree))) ;*---------------------------------------------------------------------*/ ;* pass1 ... */ ;*---------------------------------------------------------------------*/ (define (pass1 tree) (verbose " propagation1") (changed tree (instantiate::Prop-Env (call/cc? (config 'call/cc)) (suspend/resume? (config 'suspend/resume)) (bigloo-runtime-eval? (config 'bigloo-runtime-eval))) #f '() #f)) ;*---------------------------------------------------------------------*/ ;* widen-vars! ... */ ;*---------------------------------------------------------------------*/ (define (widen-vars! vars) (for-each (lambda (v) (widen!::Prop-Var v (escaping-mutated? #f) (current #f))) vars)) ;*---------------------------------------------------------------------*/ ;* widen-scope-vars! ... */ ;*---------------------------------------------------------------------*/ (define (widen-scope-vars! s::Scope) (with-access::Scope s (scope-vars) (widen-vars! scope-vars))) ;; surrounding-fun might be the Module. Used to detect free-vars. (that's all) ;; surrounding-whiles are the active whiles. ;; call/ccs are all encountered call-locations (of the current function), that ;; might reach call/ccs. call/ccs is boxed. It is continually updated and ;; represents the entry-point for call/cc-loops which extend up to the end of ;; the function. (define-nmethod (Node.changed surrounding-fun surrounding-whiles call/ccs) (default-walk this surrounding-fun surrounding-whiles call/ccs)) (define-nmethod (Module.changed surrounding-fun surrounding-whiles call/ccs) (with-access::Module this (scope-vars runtime-vars imported-vars this-var) (for-each (lambda (v) (with-access::Var v (constant?) (widen!::Prop-Var v (escaping-mutated? (not constant?)) (current #f)))) scope-vars) (widen-vars! runtime-vars) (widen-vars! imported-vars) (widen!::Prop-Var this-var)) (default-walk this this '() (instantiate::Prop-List-Box (v '())))) (define-nmethod (Lambda.changed surrounding-fun surrounding-whiles call/ccs) (widen-scope-vars! this) (widen!::Prop-Var (with-access::Lambda this (this-var) this-var)) (default-walk this this '() (instantiate::Prop-List-Box (v '())))) ;; result will be merged into orig ;; relies on the fact that all boxes will only append elements in front (using ;; cons). Searches for the 'orig'-list in all boxes, and simply merges the ;; elements that are before the 'orig'. (define (merge-call/ccs! orig::Prop-List-Box boxes::pair-nil) (with-access::Prop-List-Box orig (v) (let ((orig-list v)) (for-each (lambda (b) (let loop ((other-v (with-access::Prop-List-Box b (v) v)) (last #f)) (cond ((and (eq? orig-list other-v) (not last)) ;; no call/cc has been added to this branch. 'do-nothing) ((eq? orig-list other-v) ;; replace tail with the current v (set-cdr! last v) (set! v (with-access::Prop-List-Box b (v) v))) (else (loop (cdr other-v) other-v))))) boxes)))) (define-nmethod (If.changed surrounding-fun surrounding-whiles call/ccs) (if (with-access::Prop-Env env (call/cc?) call/cc?) ;; the default-method works fine, but is not optimized: if there's a ;; call/cc in the 'then'-branch, then any var-update in the else-branch ;; would be seen as an update inside the call/cc-loop. (with-access::If this (test then else) (walk test surrounding-fun surrounding-whiles call/ccs) (let ((then-call/ccs (duplicate::Prop-List-Box call/ccs)) (else-call/ccs (duplicate::Prop-List-Box call/ccs))) (walk then surrounding-fun surrounding-whiles then-call/ccs) (walk else surrounding-fun surrounding-whiles else-call/ccs) (merge-call/ccs! call/ccs (list then-call/ccs else-call/ccs)))) (default-walk this surrounding-fun surrounding-whiles call/ccs))) (define-nmethod (Case.changed surrounding-fun surrounding-whiles call/ccs) (if (with-access::Prop-Env env (call/cc?) call/cc?) ;; default-walk would work here too (as for the If), but optimized... (with-access::Case this (key clauses) (walk key surrounding-fun surrounding-whiles call/ccs) (let ((call/ccs-clauses (map (lambda (ign) (duplicate::Prop-List-Box call/ccs)) clauses))) (for-each (lambda (clause call/ccs-clause) (walk clause surrounding-fun surrounding-whiles call/ccs-clause)) clauses call/ccs-clauses) (merge-call/ccs! call/ccs call/ccs-clauses))) (default-walk this surrounding-fun surrounding-whiles call/ccs))) (define-nmethod (Call.changed surrounding-fun surrounding-whiles call/ccs) (default-walk this surrounding-fun surrounding-whiles call/ccs) (when (and (with-access::Call this (call/cc?) call/cc?) (with-access::Prop-Env env (call/cc?) call/cc?)) (with-access::Prop-List-Box call/ccs (v) (cons-set! v this) ;; the call/cc might come back into the while-loop -> the variables ;; inside the while are not "safe" anymore. ;; Ex: var x = 3 ; ;; while(..) { ;; print(x); ;; call/cc(..); ;; } var x = 5 ; // < ---- ;; invoke_continuation ;; ;; x is changed outside the while, but the call/cc can bring the change ;; back into the loop. (widen!::Prop-Call/cc-Call this (mutated-vars '()) (visible-whiles surrounding-whiles))))) (define-nmethod (Let.changed surrounding-fun surrounding-whiles call/ccs) (widen-scope-vars! this) (default-walk this surrounding-fun surrounding-whiles call/ccs)) (define-nmethod (While.changed surrounding-fun surrounding-whiles call/ccs) (widen-scope-vars! this) (with-access::While this (init test body) (walk init surrounding-fun surrounding-whiles call/ccs) (widen!::Prop-While this (mutated-vars '())) (let ((new-surround-whiles (cons this surrounding-whiles))) (walk test surrounding-fun new-surround-whiles call/ccs) (walk body surrounding-fun new-surround-whiles call/ccs)))) (define-nmethod (Set!.changed surrounding-fun surrounding-whiles call/ccs) (define (update-while while) (with-access::Set! this (lvalue) (with-access::Ref lvalue (var) (with-access::Prop-While while (mutated-vars) (unless (memq var mutated-vars) (cons-set! mutated-vars var)))))) (define (update-call/cc-call cc-call) (with-access::Set! this (lvalue) (with-access::Ref lvalue (var) (with-access::Prop-Call/cc-Call cc-call (mutated-vars visible-whiles) (unless (memq var mutated-vars) (cons-set! mutated-vars var)) (for-each update-while visible-whiles))))) (default-walk this surrounding-fun surrounding-whiles call/ccs) (with-access::Set! this (lvalue) (with-access::Ref lvalue (var) if the lvar is modified outside its scope , mark it as such . (with-access::Execution-Unit surrounding-fun (free-vars) (with-access::Prop-Var var (escaping-mutated? escapes?) (when (and escapes? (not escaping-mutated?) ;; already marked (memq var free-vars)) (set! escaping-mutated? #t)))) ;; store us inside the surrounding whiles (for-each update-while surrounding-whiles) ;; update the call/ccs (which in turn will update their whiles (for-each update-call/cc-call (with-access::Prop-List-Box call/ccs (v) v))))) (define (pass2! tree) (verbose " propagation2") (propagate! tree (instantiate::Prop-Env (call/cc? (config 'call/cc)) (suspend/resume? (config 'suspend/resume)) (bigloo-runtime-eval? (config 'bigloo-runtime-eval))) (instantiate::Prop-List-Box (v '())))) ;; b1 will be the result-box (define (merge-vals! b1::Prop-List-Box boxes::pair-nil) (define *all-vars* '()) (define (get-vars b::Prop-List-Box) (with-access::Prop-List-Box b (v) (for-each (lambda (p) (let ((var (car p))) (when (not (memq var *all-vars*)) ;; add to *all-vars* (cons-set! *all-vars* var)))) v))) (define (merge b::Prop-List-Box) (with-access::Prop-List-Box b (v) (for-each (lambda (p) (let ((var (car p)) (val (cdr p))) (with-access::Prop-Var var (current) (cond ((eq? val 'unknown) (set! current 'unknown)) ((eq? val current) 'do-nothing) ((not current) (set! current val)) ((and (isa? val Const) (isa? current Const)) (unless (eqv? (with-access::Const val (value) value) (with-access::Const current (value) value)) (set! current 'unknown))) ((and (isa? val Ref) (isa? current Ref)) (unless (eq? (with-access::Ref val (var) var) (with-access::Ref current (var) var)) (set! current 'unknown))) (else (set! current 'unknown)))))) v))) (get-vars b1) (for-each (lambda (b) (get-vars b)) boxes) (merge b1) (for-each (lambda (b) (merge b)) boxes) (with-access::Prop-List-Box b1 (v) (set! v (map (lambda (var) (with-access::Prop-Var var (current) (let ((tmp current)) (set! current #f) (cons var tmp)))) *all-vars*)))) (define (assq-val x b::Prop-List-Box) (let ((tmp (assq x (with-access::Prop-List-Box b (v) v)))) (and tmp (cdr tmp)))) (define (update-val b::Prop-List-Box x val) (with-access::Prop-List-Box b (v) (cons-set! v (cons x val)))) (define (kill-var b::Prop-List-Box var) (with-access::Prop-List-Box b (v) (set! v (map (lambda (p) (let ((other-var (car p)) (other-val (cdr p))) (if (and (isa? other-val Ref) (eq? var (with-access::Ref other-val (var) var)) (not (eq? other-var var))) (cons other-var 'unknown) p))) v)))) (define-nmethod (Node.propagate! var/vals::Prop-List-Box) (error "propagate" "Internal Error: forgot node type" this)) (define-nmethod (Const.propagate! var/vals) this) (define-nmethod (Ref.propagate! var/vals) (with-access::Ref this (var) (with-access::Prop-Var var (escaping-mutated?) (let* ((val (assq-val var var/vals))) (cond ((or (not val) (eq? val 'unknown) escaping-mutated?) this) ;; do not propagate variable-references when in suspend/call/cc ;; mode. ;; i.e. avoid things like ;; (let ((x y)) (if x (set! y (not y)))) ;; -> ;; (if y (set! y (not y))) ((and (not (with-access::Prop-Env env (suspend/resume?) suspend/resume?)) (isa? val Ref) (not (with-access::Ref val (var) (with-access::Prop-Var var (escaping-mutated?) escaping-mutated?)))) (var-reference (with-access::Ref val (var) var) :location val)) ((and (isa? val Const) (with-access::Const val (value) (or (number? value) (symbol? value) (char? value) (boolean? value) (and (not (use-mutable-strings?)) (string? value) (not (>fx (string-length value) 15))) (eqv? #unspecified value)))) (instantiate::Const (location (with-access::Node val (location) location)) (value (with-access::Const val (value) value)))) (else this)))))) (define-nmethod (Module.propagate! var/vals) (default-walk! this (instantiate::Prop-List-Box (v '())))) (define-nmethod (Lambda.propagate! var/vals) (with-access::Lambda this (formals) (for-each (lambda (formal) (with-access::Ref formal (var) (with-access::Prop-Var var (current) (set! current 'unknown)))) formals) (let ((lb (instantiate::Prop-List-Box (v (map (lambda (formal) (with-access::Ref formal (var) (cons var 'unknown))) formals))))) (default-walk! this lb)))) (define-nmethod (If.propagate! var/vals) (with-access::If this (test then else) (set! test (walk! test var/vals)) (let ((tmp-var/vals (duplicate::Prop-List-Box var/vals))) (set! then (walk! then var/vals)) (set! else (walk! else tmp-var/vals)) (merge-vals! var/vals (list tmp-var/vals)) this))) (define-nmethod (Case.propagate! var/vals) (with-access::Case this (key clauses) (set! key (walk! key var/vals)) (let ((var/vals-clauses (map (lambda (ign) (duplicate::Prop-List-Box var/vals)) clauses))) (set! clauses (map! (lambda (clause var/vals-clause) (walk! clause var/vals-clause)) clauses var/vals-clauses)) (merge-vals! var/vals var/vals-clauses) this))) (define-nmethod (Clause.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Set!.propagate! var/vals) (define (transitive-value val) (if (isa? val Begin) (transitive-value (car (last-pair (with-access::Begin val (exprs) exprs)))) val)) (with-access::Set! this (lvalue val) (with-access::Ref lvalue (var) (set! val (walk! val var/vals)) (update-val var/vals var (transitive-value val)) ;; kill all vars that depend on lvalue.var (kill-var var/vals var) this))) (define-nmethod (Let.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Begin.propagate! var/vals) ;; walk ensures left to right order. (default-walk! this var/vals)) (define-nmethod (Call.propagate! var/vals) (define (constant-value? n) (or (isa? n Const) (and (isa? n Ref) (with-access::Ref n (var) (with-access::Var var (constant? value id) (and constant? value (isa? value Const) (with-access::Const value (value) (or (pair? value) (vector? value))) #t)))))) (default-walk! this var/vals) (with-access::Call this (operator operands) (if (and (with-access::Prop-Env env (bigloo-runtime-eval?) bigloo-runtime-eval?) (isa? operator Ref) (runtime-ref? operator) (every constant-value? operands)) ;; for most runtime-functions we should be able to compute the result ;; right now. (obviously a "print" won't work now...) ;; ;; optimize-runtime-op is at bottom of file. (with-access::Ref operator (var) (with-access::Var var (id) (or (optimize-runtime-op id operands (with-access::Node operator (location) location)) this))) this))) (define-nmethod (Frame-alloc.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Frame-push.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Return.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Labeled.propagate! var/vals) (with-access::Labeled this (label body) (widen!::Prop-Label label (var/vals-list '())) (set! body (walk! body var/vals)) (with-access::Prop-Label label (var/vals-list) (merge-vals! var/vals var/vals-list) (shrink! label) this))) (define-nmethod (Break.propagate! var/vals) (with-access::Break this (val label) (set! val (walk! val var/vals)) (with-access::Prop-Label label (var/vals-list) (cons-set! var/vals-list (duplicate::Prop-List-Box var/vals))) this)) (define-nmethod (Continue.propagate! var/vals) this) (define-nmethod (Pragma.propagate! var/vals) (with-access::Pragma this (args) (for-each (lambda (a) (walk! a var/vals)) args)) (default-walk! this var/vals)) Tail - rec and Tail - rec - Call must not exist anymore . (define-nmethod (Prop-While.propagate! var/vals) (with-access::Prop-While this (init test body mutated-vars label) ;; inits are outside of the loop. (set! init (walk! init var/vals)) ;; if the test is true (which is currently the case), then we can't exit ;; the loop only by a break. -> clear the current var/vals. Any ;; surrounding Labeled will therefore ignore the result of var/vals. (when (and (isa? test Const) (with-access::Const test (value) value)) (let ((tmp (duplicate::Prop-List-Box var/vals))) (with-access::Prop-List-Box var/vals (v) (set! v '())) (set! var/vals tmp))) ;; <== we replace the var/vals given as param ;; ------ var/vals is not the var/vals given as parameter anymore !!! (for-each (lambda (var) (update-val var/vals var 'unknown)) mutated-vars) (widen!::Prop-Label label (var/vals-list '())) (set! test (walk! test var/vals)) (set! body (walk! body var/vals)) this)) (define-nmethod (Prop-Call/cc-Call.propagate! var/vals) (with-access::Prop-Call/cc-Call this (mutated-vars) (default-walk! this var/vals) (for-each (lambda (var) (update-val var/vals var 'unknown)) mutated-vars) this)) (define-nmethod (Call/cc-Resume.propagate! var/vals) (default-walk! this var/vals)) (define (optimize-runtime-op op operands location) (define (operand->val op) (let ((tmp (if (isa? op Const) (with-access::Const op (value) value) (with-access::Ref op (var) (with-access::Var var (value) (with-access::Const value (value) value)))))) (cond ((or (number? tmp) (char? tmp) (string? tmp) (symbol? tmp) (boolean? tmp) (keyword? tmp) (eq? tmp #unspecified)) tmp) (else (list 'quote tmp))))) (case op ((eqv? eq?) ;; ignore cases where we need to know the pointer-location. ;; we could do better here, but just don't take the risk. not worth it. (if (null? operands) #f (let ((fst-operand (operand->val (car operands)))) (if (or (number? fst-operand) (char? fst-operand) (and (not (use-mutable-strings?)) (string? fst-operand)) (symbol? fst-operand) (boolean? fst-operand) (keyword? fst-operand) (eq? fst-operand #unspecified)) (with-handler (lambda (e) (exception-notify e) #f) (instantiate::Const (location location) (value (apply equal? (map operand->val operands))))) #f)))) ((equal? number? = < > <= >= zero? zerofx? negative? odd? even? max min + * - / remainder modulo gcd lcm floor ceiling truncate round exp log sin cos tan asin acos atan sqrt expt not boolean? pair? null? char-numeric? char-whitespace? char-upper-case? char-lower-case? char->integer char-upcase char-downcase char<? char>? char<=? char>=? char=? char-ci<? char-ci>? char-ci<=? char-ci>=? char-ci=? string<? string>? string<=? string>=? string=? string-ci<? string-ci>? string-ci<=? string-ci>=? string-ci=? string->list vector? vector-ref vector->list list->vector number->string string->number symbol? string? string-append symbol-append string-length substring keyword->string string->keyword string-ref string-copy bit-not bit-and bit-or bit-xor bit-lsh bit-rsh bit-ursh length) (with-handler (lambda (e) (exception-notify e) #f) (let ((res (eval `(,op ,@(map operand->val operands))))) (instantiate::Const (location location) (value res))))) ((car cdr cadr cddr caar cdar cadar cddar caaar cdaar caddr cdddr caadr cdadr member memq memv length assoc assq assv) (with-handler (lambda (e) (exception-notify e) #f) (let ((res (eval `(,op ,@(map operand->val operands))))) ;; if the result is a pair, ... we ignore it. (in case it has been shared ... ex : ( cdr ' ( 1 2 ) ) would yield ' ( 2 ) . But when producing the JS - code the new ' ( 2 ) would not be equal to the one of ' ( 1 2 ) . - > Just do n't take any risk ... ;; member, assoc, ... therefore can only yield #f here. (if (or (number? res) (char? res) (and (not (use-mutable-strings?)) (string? res)) (symbol? res) (boolean? res) (keyword? res) (eq? res #unspecified)) (instantiate::Const (location location) (value res)) #f)))) (else #f)))
null
https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/scheme2js/propagation.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ vars that are mutated after the call vars that are mutated inside the while. *---------------------------------------------------------------------*/ * propagation! ... */ *---------------------------------------------------------------------*/ uses While -> must be after while-pass locally propagate variables/constants. -> Removes var-count. call/cc-calls count as loops. suspend/resumes don't. each of these loops have a list of all mutated vars. Also determine if a variable is changed outside its local scope (that is, if it escapes, is it modified in these functions). -> .escaping-mutated? the current value. a set! obviously updates it. a loop kills all the variables that are affected. if we have a binding x = y, and this is the only use of y (see var-elimination), then we replace x by y. Exception applies for call/cc. *---------------------------------------------------------------------*/ * pass1 ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * widen-vars! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * widen-scope-vars! ... */ *---------------------------------------------------------------------*/ surrounding-fun might be the Module. Used to detect free-vars. (that's all) surrounding-whiles are the active whiles. call/ccs are all encountered call-locations (of the current function), that might reach call/ccs. call/ccs is boxed. It is continually updated and represents the entry-point for call/cc-loops which extend up to the end of the function. result will be merged into orig relies on the fact that all boxes will only append elements in front (using cons). Searches for the 'orig'-list in all boxes, and simply merges the elements that are before the 'orig'. no call/cc has been added to this branch. replace tail with the current v the default-method works fine, but is not optimized: if there's a call/cc in the 'then'-branch, then any var-update in the else-branch would be seen as an update inside the call/cc-loop. default-walk would work here too (as for the If), but optimized... the call/cc might come back into the while-loop -> the variables inside the while are not "safe" anymore. Ex: while(..) { print(x); call/cc(..); } // < ---- invoke_continuation x is changed outside the while, but the call/cc can bring the change back into the loop. already marked store us inside the surrounding whiles update the call/ccs (which in turn will update their whiles b1 will be the result-box add to *all-vars* do not propagate variable-references when in suspend/call/cc mode. i.e. avoid things like (let ((x y)) (if x (set! y (not y)))) -> (if y (set! y (not y))) kill all vars that depend on lvalue.var walk ensures left to right order. for most runtime-functions we should be able to compute the result right now. (obviously a "print" won't work now...) optimize-runtime-op is at bottom of file. inits are outside of the loop. if the test is true (which is currently the case), then we can't exit the loop only by a break. -> clear the current var/vals. Any surrounding Labeled will therefore ignore the result of var/vals. <== we replace the var/vals given as param ------ var/vals is not the var/vals given as parameter anymore !!! ignore cases where we need to know the pointer-location. we could do better here, but just don't take the risk. not worth it. if the result is a pair, ... we ignore it. (in case it has been member, assoc, ... therefore can only yield #f here.
* serrano / prgm / project / hop/2.5.x / scheme2js / propagation.scm * / * Author : * / * Creation : 2007 - 12 * / * Last change : Fri Jul 19 15:31:15 2013 ( serrano ) * / * Copyright : 2013 * / * / Variable propagation * / (module propagation (import config tools nodes export-desc walk var-ref-util free-vars side verbose mutable-strings) (static (class Prop-Env call/cc?::bool suspend/resume?::bool bigloo-runtime-eval?::bool) (wide-class Prop-Call/cc-Call::Call visible-whiles) (wide-class Prop-While::While (wide-class Prop-Label::Label var/vals-list) (wide-class Prop-Var::Var (escaping-mutated?::bool (default #f)) (current (default #f))) (class Prop-List-Box v::pair-nil)) (export (propagation! tree::Module))) first pass : determine which variables are modified inside loops . second pass : linearly walk through the code . the variables ' current ' holds (define (propagation! tree) (when (config 'propagation) (verbose "propagation") (side-effect tree) (free-vars tree) (pass1 tree) (pass2! tree))) (define (pass1 tree) (verbose " propagation1") (changed tree (instantiate::Prop-Env (call/cc? (config 'call/cc)) (suspend/resume? (config 'suspend/resume)) (bigloo-runtime-eval? (config 'bigloo-runtime-eval))) #f '() #f)) (define (widen-vars! vars) (for-each (lambda (v) (widen!::Prop-Var v (escaping-mutated? #f) (current #f))) vars)) (define (widen-scope-vars! s::Scope) (with-access::Scope s (scope-vars) (widen-vars! scope-vars))) (define-nmethod (Node.changed surrounding-fun surrounding-whiles call/ccs) (default-walk this surrounding-fun surrounding-whiles call/ccs)) (define-nmethod (Module.changed surrounding-fun surrounding-whiles call/ccs) (with-access::Module this (scope-vars runtime-vars imported-vars this-var) (for-each (lambda (v) (with-access::Var v (constant?) (widen!::Prop-Var v (escaping-mutated? (not constant?)) (current #f)))) scope-vars) (widen-vars! runtime-vars) (widen-vars! imported-vars) (widen!::Prop-Var this-var)) (default-walk this this '() (instantiate::Prop-List-Box (v '())))) (define-nmethod (Lambda.changed surrounding-fun surrounding-whiles call/ccs) (widen-scope-vars! this) (widen!::Prop-Var (with-access::Lambda this (this-var) this-var)) (default-walk this this '() (instantiate::Prop-List-Box (v '())))) (define (merge-call/ccs! orig::Prop-List-Box boxes::pair-nil) (with-access::Prop-List-Box orig (v) (let ((orig-list v)) (for-each (lambda (b) (let loop ((other-v (with-access::Prop-List-Box b (v) v)) (last #f)) (cond ((and (eq? orig-list other-v) (not last)) 'do-nothing) ((eq? orig-list other-v) (set-cdr! last v) (set! v (with-access::Prop-List-Box b (v) v))) (else (loop (cdr other-v) other-v))))) boxes)))) (define-nmethod (If.changed surrounding-fun surrounding-whiles call/ccs) (if (with-access::Prop-Env env (call/cc?) call/cc?) (with-access::If this (test then else) (walk test surrounding-fun surrounding-whiles call/ccs) (let ((then-call/ccs (duplicate::Prop-List-Box call/ccs)) (else-call/ccs (duplicate::Prop-List-Box call/ccs))) (walk then surrounding-fun surrounding-whiles then-call/ccs) (walk else surrounding-fun surrounding-whiles else-call/ccs) (merge-call/ccs! call/ccs (list then-call/ccs else-call/ccs)))) (default-walk this surrounding-fun surrounding-whiles call/ccs))) (define-nmethod (Case.changed surrounding-fun surrounding-whiles call/ccs) (if (with-access::Prop-Env env (call/cc?) call/cc?) (with-access::Case this (key clauses) (walk key surrounding-fun surrounding-whiles call/ccs) (let ((call/ccs-clauses (map (lambda (ign) (duplicate::Prop-List-Box call/ccs)) clauses))) (for-each (lambda (clause call/ccs-clause) (walk clause surrounding-fun surrounding-whiles call/ccs-clause)) clauses call/ccs-clauses) (merge-call/ccs! call/ccs call/ccs-clauses))) (default-walk this surrounding-fun surrounding-whiles call/ccs))) (define-nmethod (Call.changed surrounding-fun surrounding-whiles call/ccs) (default-walk this surrounding-fun surrounding-whiles call/ccs) (when (and (with-access::Call this (call/cc?) call/cc?) (with-access::Prop-Env env (call/cc?) call/cc?)) (with-access::Prop-List-Box call/ccs (v) (cons-set! v this) (widen!::Prop-Call/cc-Call this (mutated-vars '()) (visible-whiles surrounding-whiles))))) (define-nmethod (Let.changed surrounding-fun surrounding-whiles call/ccs) (widen-scope-vars! this) (default-walk this surrounding-fun surrounding-whiles call/ccs)) (define-nmethod (While.changed surrounding-fun surrounding-whiles call/ccs) (widen-scope-vars! this) (with-access::While this (init test body) (walk init surrounding-fun surrounding-whiles call/ccs) (widen!::Prop-While this (mutated-vars '())) (let ((new-surround-whiles (cons this surrounding-whiles))) (walk test surrounding-fun new-surround-whiles call/ccs) (walk body surrounding-fun new-surround-whiles call/ccs)))) (define-nmethod (Set!.changed surrounding-fun surrounding-whiles call/ccs) (define (update-while while) (with-access::Set! this (lvalue) (with-access::Ref lvalue (var) (with-access::Prop-While while (mutated-vars) (unless (memq var mutated-vars) (cons-set! mutated-vars var)))))) (define (update-call/cc-call cc-call) (with-access::Set! this (lvalue) (with-access::Ref lvalue (var) (with-access::Prop-Call/cc-Call cc-call (mutated-vars visible-whiles) (unless (memq var mutated-vars) (cons-set! mutated-vars var)) (for-each update-while visible-whiles))))) (default-walk this surrounding-fun surrounding-whiles call/ccs) (with-access::Set! this (lvalue) (with-access::Ref lvalue (var) if the lvar is modified outside its scope , mark it as such . (with-access::Execution-Unit surrounding-fun (free-vars) (with-access::Prop-Var var (escaping-mutated? escapes?) (when (and escapes? (memq var free-vars)) (set! escaping-mutated? #t)))) (for-each update-while surrounding-whiles) (for-each update-call/cc-call (with-access::Prop-List-Box call/ccs (v) v))))) (define (pass2! tree) (verbose " propagation2") (propagate! tree (instantiate::Prop-Env (call/cc? (config 'call/cc)) (suspend/resume? (config 'suspend/resume)) (bigloo-runtime-eval? (config 'bigloo-runtime-eval))) (instantiate::Prop-List-Box (v '())))) (define (merge-vals! b1::Prop-List-Box boxes::pair-nil) (define *all-vars* '()) (define (get-vars b::Prop-List-Box) (with-access::Prop-List-Box b (v) (for-each (lambda (p) (let ((var (car p))) (when (not (memq var *all-vars*)) (cons-set! *all-vars* var)))) v))) (define (merge b::Prop-List-Box) (with-access::Prop-List-Box b (v) (for-each (lambda (p) (let ((var (car p)) (val (cdr p))) (with-access::Prop-Var var (current) (cond ((eq? val 'unknown) (set! current 'unknown)) ((eq? val current) 'do-nothing) ((not current) (set! current val)) ((and (isa? val Const) (isa? current Const)) (unless (eqv? (with-access::Const val (value) value) (with-access::Const current (value) value)) (set! current 'unknown))) ((and (isa? val Ref) (isa? current Ref)) (unless (eq? (with-access::Ref val (var) var) (with-access::Ref current (var) var)) (set! current 'unknown))) (else (set! current 'unknown)))))) v))) (get-vars b1) (for-each (lambda (b) (get-vars b)) boxes) (merge b1) (for-each (lambda (b) (merge b)) boxes) (with-access::Prop-List-Box b1 (v) (set! v (map (lambda (var) (with-access::Prop-Var var (current) (let ((tmp current)) (set! current #f) (cons var tmp)))) *all-vars*)))) (define (assq-val x b::Prop-List-Box) (let ((tmp (assq x (with-access::Prop-List-Box b (v) v)))) (and tmp (cdr tmp)))) (define (update-val b::Prop-List-Box x val) (with-access::Prop-List-Box b (v) (cons-set! v (cons x val)))) (define (kill-var b::Prop-List-Box var) (with-access::Prop-List-Box b (v) (set! v (map (lambda (p) (let ((other-var (car p)) (other-val (cdr p))) (if (and (isa? other-val Ref) (eq? var (with-access::Ref other-val (var) var)) (not (eq? other-var var))) (cons other-var 'unknown) p))) v)))) (define-nmethod (Node.propagate! var/vals::Prop-List-Box) (error "propagate" "Internal Error: forgot node type" this)) (define-nmethod (Const.propagate! var/vals) this) (define-nmethod (Ref.propagate! var/vals) (with-access::Ref this (var) (with-access::Prop-Var var (escaping-mutated?) (let* ((val (assq-val var var/vals))) (cond ((or (not val) (eq? val 'unknown) escaping-mutated?) this) ((and (not (with-access::Prop-Env env (suspend/resume?) suspend/resume?)) (isa? val Ref) (not (with-access::Ref val (var) (with-access::Prop-Var var (escaping-mutated?) escaping-mutated?)))) (var-reference (with-access::Ref val (var) var) :location val)) ((and (isa? val Const) (with-access::Const val (value) (or (number? value) (symbol? value) (char? value) (boolean? value) (and (not (use-mutable-strings?)) (string? value) (not (>fx (string-length value) 15))) (eqv? #unspecified value)))) (instantiate::Const (location (with-access::Node val (location) location)) (value (with-access::Const val (value) value)))) (else this)))))) (define-nmethod (Module.propagate! var/vals) (default-walk! this (instantiate::Prop-List-Box (v '())))) (define-nmethod (Lambda.propagate! var/vals) (with-access::Lambda this (formals) (for-each (lambda (formal) (with-access::Ref formal (var) (with-access::Prop-Var var (current) (set! current 'unknown)))) formals) (let ((lb (instantiate::Prop-List-Box (v (map (lambda (formal) (with-access::Ref formal (var) (cons var 'unknown))) formals))))) (default-walk! this lb)))) (define-nmethod (If.propagate! var/vals) (with-access::If this (test then else) (set! test (walk! test var/vals)) (let ((tmp-var/vals (duplicate::Prop-List-Box var/vals))) (set! then (walk! then var/vals)) (set! else (walk! else tmp-var/vals)) (merge-vals! var/vals (list tmp-var/vals)) this))) (define-nmethod (Case.propagate! var/vals) (with-access::Case this (key clauses) (set! key (walk! key var/vals)) (let ((var/vals-clauses (map (lambda (ign) (duplicate::Prop-List-Box var/vals)) clauses))) (set! clauses (map! (lambda (clause var/vals-clause) (walk! clause var/vals-clause)) clauses var/vals-clauses)) (merge-vals! var/vals var/vals-clauses) this))) (define-nmethod (Clause.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Set!.propagate! var/vals) (define (transitive-value val) (if (isa? val Begin) (transitive-value (car (last-pair (with-access::Begin val (exprs) exprs)))) val)) (with-access::Set! this (lvalue val) (with-access::Ref lvalue (var) (set! val (walk! val var/vals)) (update-val var/vals var (transitive-value val)) (kill-var var/vals var) this))) (define-nmethod (Let.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Begin.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Call.propagate! var/vals) (define (constant-value? n) (or (isa? n Const) (and (isa? n Ref) (with-access::Ref n (var) (with-access::Var var (constant? value id) (and constant? value (isa? value Const) (with-access::Const value (value) (or (pair? value) (vector? value))) #t)))))) (default-walk! this var/vals) (with-access::Call this (operator operands) (if (and (with-access::Prop-Env env (bigloo-runtime-eval?) bigloo-runtime-eval?) (isa? operator Ref) (runtime-ref? operator) (every constant-value? operands)) (with-access::Ref operator (var) (with-access::Var var (id) (or (optimize-runtime-op id operands (with-access::Node operator (location) location)) this))) this))) (define-nmethod (Frame-alloc.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Frame-push.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Return.propagate! var/vals) (default-walk! this var/vals)) (define-nmethod (Labeled.propagate! var/vals) (with-access::Labeled this (label body) (widen!::Prop-Label label (var/vals-list '())) (set! body (walk! body var/vals)) (with-access::Prop-Label label (var/vals-list) (merge-vals! var/vals var/vals-list) (shrink! label) this))) (define-nmethod (Break.propagate! var/vals) (with-access::Break this (val label) (set! val (walk! val var/vals)) (with-access::Prop-Label label (var/vals-list) (cons-set! var/vals-list (duplicate::Prop-List-Box var/vals))) this)) (define-nmethod (Continue.propagate! var/vals) this) (define-nmethod (Pragma.propagate! var/vals) (with-access::Pragma this (args) (for-each (lambda (a) (walk! a var/vals)) args)) (default-walk! this var/vals)) Tail - rec and Tail - rec - Call must not exist anymore . (define-nmethod (Prop-While.propagate! var/vals) (with-access::Prop-While this (init test body mutated-vars label) (set! init (walk! init var/vals)) (when (and (isa? test Const) (with-access::Const test (value) value)) (let ((tmp (duplicate::Prop-List-Box var/vals))) (with-access::Prop-List-Box var/vals (v) (set! v '())) (for-each (lambda (var) (update-val var/vals var 'unknown)) mutated-vars) (widen!::Prop-Label label (var/vals-list '())) (set! test (walk! test var/vals)) (set! body (walk! body var/vals)) this)) (define-nmethod (Prop-Call/cc-Call.propagate! var/vals) (with-access::Prop-Call/cc-Call this (mutated-vars) (default-walk! this var/vals) (for-each (lambda (var) (update-val var/vals var 'unknown)) mutated-vars) this)) (define-nmethod (Call/cc-Resume.propagate! var/vals) (default-walk! this var/vals)) (define (optimize-runtime-op op operands location) (define (operand->val op) (let ((tmp (if (isa? op Const) (with-access::Const op (value) value) (with-access::Ref op (var) (with-access::Var var (value) (with-access::Const value (value) value)))))) (cond ((or (number? tmp) (char? tmp) (string? tmp) (symbol? tmp) (boolean? tmp) (keyword? tmp) (eq? tmp #unspecified)) tmp) (else (list 'quote tmp))))) (case op ((eqv? eq?) (if (null? operands) #f (let ((fst-operand (operand->val (car operands)))) (if (or (number? fst-operand) (char? fst-operand) (and (not (use-mutable-strings?)) (string? fst-operand)) (symbol? fst-operand) (boolean? fst-operand) (keyword? fst-operand) (eq? fst-operand #unspecified)) (with-handler (lambda (e) (exception-notify e) #f) (instantiate::Const (location location) (value (apply equal? (map operand->val operands))))) #f)))) ((equal? number? = < > <= >= zero? zerofx? negative? odd? even? max min + * - / remainder modulo gcd lcm floor ceiling truncate round exp log sin cos tan asin acos atan sqrt expt not boolean? pair? null? char-numeric? char-whitespace? char-upper-case? char-lower-case? char->integer char-upcase char-downcase char<? char>? char<=? char>=? char=? char-ci<? char-ci>? char-ci<=? char-ci>=? char-ci=? string<? string>? string<=? string>=? string=? string-ci<? string-ci>? string-ci<=? string-ci>=? string-ci=? string->list vector? vector-ref vector->list list->vector number->string string->number symbol? string? string-append symbol-append string-length substring keyword->string string->keyword string-ref string-copy bit-not bit-and bit-or bit-xor bit-lsh bit-rsh bit-ursh length) (with-handler (lambda (e) (exception-notify e) #f) (let ((res (eval `(,op ,@(map operand->val operands))))) (instantiate::Const (location location) (value res))))) ((car cdr cadr cddr caar cdar cadar cddar caaar cdaar caddr cdddr caadr cdadr member memq memv length assoc assq assv) (with-handler (lambda (e) (exception-notify e) #f) (let ((res (eval `(,op ,@(map operand->val operands))))) shared ... ex : ( cdr ' ( 1 2 ) ) would yield ' ( 2 ) . But when producing the JS - code the new ' ( 2 ) would not be equal to the one of ' ( 1 2 ) . - > Just do n't take any risk ... (if (or (number? res) (char? res) (and (not (use-mutable-strings?)) (string? res)) (symbol? res) (boolean? res) (keyword? res) (eq? res #unspecified)) (instantiate::Const (location location) (value res)) #f)))) (else #f)))
8eb0825376c53dc541f3c1a3f9ca9051c2509680a194944c529bbeb5da65d36c
hellopatrick/xmas
main.ml
open Containers let input = IO.read_lines_l stdin module C = struct type t = int * int * int let compare (x0, y0, z0) (x1, y1, z1) = match Int.compare x0 x1 with | 0 -> ( match Int.compare y0 y1 with | 0 -> ( match Int.compare z0 z1 with 0 -> 0 | e -> e) | e -> e) | e -> e let neighbors (x, y, z) = [ (x + 1, y, z); (x - 1, y, z); (x, y + 1, z); (x, y - 1, z); (x, y, z - 1); (x, y, z + 1); ] end module R = struct type t = { min : int; max : int } let contains t v = t.min <= v && v <= t.max end module S = struct include Set.Make (C) let nmem elt t = not @@ mem elt t let exclude f t = filter (fun elt -> not @@ f elt) t let bounds t = let minx, maxx = fold (fun (x, _, _) (mn, mx) -> (Int.min x mn, Int.max x mx)) t (Int.max_int, Int.min_int) in let miny, maxy = fold (fun (_, y, _) (mn, mx) -> (Int.min y mn, Int.max y mx)) t (Int.max_int, Int.min_int) in let minz, maxz = fold (fun (_, _, z) (mn, mx) -> (Int.min z mn, Int.max z mx)) t (Int.max_int, Int.min_int) in R. ( { min = minx - 1; max = maxx + 1 }, { min = miny - 1; max = maxy + 1 }, { min = minz - 1; max = maxz + 1 } ) end let parse input = let parse_line line = Scanf.sscanf line "%d,%d,%d" (fun x y z -> (x, y, z)) in List.map parse_line input |> S.of_list let part1 input = let cubes = parse input in S.fold (fun c acc -> C.neighbors c |> List.fold_left (fun acc c -> if S.mem c cubes then acc else acc + 1) acc) cubes 0 let part2 input = let cubes = parse input in let rx, ry, rz = S.bounds cubes in let start = (rx.min, ry.min, rz.min) in let rec loop q v = match q with | [] -> v | cube :: q -> let visited = S.add cube v in let next = C.neighbors cube |> List.filter (fun (x, y, z) -> R.contains rx x && R.contains ry y && R.contains rz z && (not @@ S.mem (x, y, z) cubes) && (not @@ S.mem (x, y, z) visited)) in let visited = S.add_list visited next in loop (next @ q) visited in let visited = loop [ start ] (S.singleton start) in S.fold (fun c acc -> C.neighbors c |> List.fold_left (fun acc c -> if S.mem c visited then acc + 1 else acc) acc) cubes 0 let _ = Printf.printf "part1=%d;part2=%d" (part1 input) (part2 input)
null
https://raw.githubusercontent.com/hellopatrick/xmas/ff2cbbfb2d569aabd33905e1caece50f88c8c54e/2022/day18/main.ml
ocaml
open Containers let input = IO.read_lines_l stdin module C = struct type t = int * int * int let compare (x0, y0, z0) (x1, y1, z1) = match Int.compare x0 x1 with | 0 -> ( match Int.compare y0 y1 with | 0 -> ( match Int.compare z0 z1 with 0 -> 0 | e -> e) | e -> e) | e -> e let neighbors (x, y, z) = [ (x + 1, y, z); (x - 1, y, z); (x, y + 1, z); (x, y - 1, z); (x, y, z - 1); (x, y, z + 1); ] end module R = struct type t = { min : int; max : int } let contains t v = t.min <= v && v <= t.max end module S = struct include Set.Make (C) let nmem elt t = not @@ mem elt t let exclude f t = filter (fun elt -> not @@ f elt) t let bounds t = let minx, maxx = fold (fun (x, _, _) (mn, mx) -> (Int.min x mn, Int.max x mx)) t (Int.max_int, Int.min_int) in let miny, maxy = fold (fun (_, y, _) (mn, mx) -> (Int.min y mn, Int.max y mx)) t (Int.max_int, Int.min_int) in let minz, maxz = fold (fun (_, _, z) (mn, mx) -> (Int.min z mn, Int.max z mx)) t (Int.max_int, Int.min_int) in R. ( { min = minx - 1; max = maxx + 1 }, { min = miny - 1; max = maxy + 1 }, { min = minz - 1; max = maxz + 1 } ) end let parse input = let parse_line line = Scanf.sscanf line "%d,%d,%d" (fun x y z -> (x, y, z)) in List.map parse_line input |> S.of_list let part1 input = let cubes = parse input in S.fold (fun c acc -> C.neighbors c |> List.fold_left (fun acc c -> if S.mem c cubes then acc else acc + 1) acc) cubes 0 let part2 input = let cubes = parse input in let rx, ry, rz = S.bounds cubes in let start = (rx.min, ry.min, rz.min) in let rec loop q v = match q with | [] -> v | cube :: q -> let visited = S.add cube v in let next = C.neighbors cube |> List.filter (fun (x, y, z) -> R.contains rx x && R.contains ry y && R.contains rz z && (not @@ S.mem (x, y, z) cubes) && (not @@ S.mem (x, y, z) visited)) in let visited = S.add_list visited next in loop (next @ q) visited in let visited = loop [ start ] (S.singleton start) in S.fold (fun c acc -> C.neighbors c |> List.fold_left (fun acc c -> if S.mem c visited then acc + 1 else acc) acc) cubes 0 let _ = Printf.printf "part1=%d;part2=%d" (part1 input) (part2 input)
fd0b572c28f4a400806cb29565d5b56dd20baae782734a695936bcf170be554e
2600hz-archive/whistle
rebar_xref.erl
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- %% ex: ts=4 sw=4 et %% ------------------------------------------------------------------- %% rebar : Erlang Build Tools %% Copyright ( c ) 2009 ( ) %% %% 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. %% %% ------------------------------------------------------------------- %% ------------------------------------------------------------------- %% This module borrows heavily from project as written by < > , and others . %% ------------------------------------------------------------------- -module(rebar_xref). -include("rebar.hrl"). -export([xref/2]). %% =================================================================== %% Public API %% =================================================================== xref(Config, _) -> %% Spin up xref {ok, _} = xref:start(xref), ok = xref:set_library_path(xref, code_path()), xref:set_default(xref, [{warnings, rebar_config:get(Config, xref_warnings, false)}, {verbose, rebar_config:is_verbose()}]), {ok, _} = xref:add_directory(xref, "ebin"), %% Save the code path prior to doing anything OrigPath = code:get_path(), true = code:add_path(filename:join(rebar_utils:get_cwd(), "ebin")), %% Get list of xref checks we want to run XrefChecks = rebar_config:get(Config, xref_checks, [exports_not_used, undefined_function_calls]), %% Look for exports that are unused by anything ExportsNoWarn = case lists:member(exports_not_used, XrefChecks) of true -> check_exports_not_used(); false -> true end, %% Look for calls to undefined functions UndefNoWarn = case lists:member(undefined_function_calls, XrefChecks) of true -> check_undefined_function_calls(); false -> true end, %% Restore the original code path true = code:set_path(OrigPath), %% Stop xref stopped = xref:stop(xref), case lists:all(fun(NoWarn) -> NoWarn end, [ExportsNoWarn, UndefNoWarn]) of true -> ok; false -> ?FAIL end. %% =================================================================== Internal functions %% =================================================================== check_exports_not_used() -> {ok, UnusedExports0} = xref:analyze(xref, exports_not_used), UnusedExports = filter_away_ignored(UnusedExports0), %% Report all the unused functions display_mfas(UnusedExports, "is unused export (Xref)"), UnusedExports =:= []. check_undefined_function_calls() -> {ok, UndefinedCalls0} = xref:analyze(xref, undefined_function_calls), UndefinedCalls = [{find_mfa_source(Caller), format_fa(Caller), format_mfa(Target)} || {Caller, Target} <- UndefinedCalls0], lists:foreach( fun({{Source, Line}, FunStr, Target}) -> ?CONSOLE("~s:~w: Warning ~s calls undefined function ~s\n", [Source, Line, FunStr, Target]) end, UndefinedCalls), UndefinedCalls =:= []. code_path() -> [P || P <- code:get_path(), filelib:is_dir(P)] ++ [filename:join(rebar_utils:get_cwd(), "ebin")]. %% %% Ignore behaviour functions, and explicitly marked functions %% filter_away_ignored(UnusedExports) -> %% Functions can be ignored by using %% -ignore_xref([{F, A}, ...]). %% Setup a filter function that builds a list of behaviour callbacks and/or %% any functions marked to ignore. We then use this list to mask any %% functions marked as unused exports by xref F = fun(Mod) -> Attrs = kf(attributes, Mod:module_info()), Ignore = kf(ignore_xref, Attrs), Callbacks = [B:behaviour_info(callbacks) || B <- kf(behaviour, Attrs)], [{Mod, F, A} || {F, A} <- Ignore ++ lists:flatten(Callbacks)] end, AttrIgnore = lists:flatten( lists:map(F, lists:usort([M || {M, _, _} <- UnusedExports]))), [X || X <- UnusedExports, not lists:member(X, AttrIgnore)]. kf(Key, List) -> case lists:keyfind(Key, 1, List) of {Key, Value} -> Value; false -> [] end. display_mfas([], _Message) -> ok; display_mfas([{_Mod, Fun, Args} = MFA | Rest], Message) -> {Source, Line} = find_mfa_source(MFA), ?CONSOLE("~s:~w: Warning: function ~s/~w ~s\n", [Source, Line, Fun, Args, Message]), display_mfas(Rest, Message). format_mfa({M, F, A}) -> ?FMT("~s:~s/~w", [M, F, A]). format_fa({_M, F, A}) -> ?FMT("~s/~w", [F, A]). %% %% Extract an element from a tuple, or undefined if N > tuple size %% safe_element(N, Tuple) -> case catch(element(N, Tuple)) of {'EXIT', {badarg, _}} -> undefined; Value -> Value end. %% Given a MFA , find the file and LOC where it 's defined . Note that %% xref doesn't work if there is no abstract_code, so we can avoid %% being too paranoid here. %% find_mfa_source({M, F, A}) -> {M, Bin, _} = code:get_object_code(M), AbstractCode = beam_lib:chunks(Bin, [abstract_code]), {ok, {M, [{abstract_code, {raw_abstract_v1, Code}}]}} = AbstractCode, %% Extract the original source filename from the abstract code [{attribute, 1, file, {Source, _}} | _] = Code, %% Extract the line number for a given function def [{function, Line, F, _, _}] = [E || E <- Code, safe_element(1, E) == function, safe_element(3, E) == F, safe_element(4, E) == A], {Source, Line}.
null
https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/utils/rebar/src/rebar_xref.erl
erlang
ex: ts=4 sw=4 et ------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------- ------------------------------------------------------------------- This module borrows heavily from project as ------------------------------------------------------------------- =================================================================== Public API =================================================================== Spin up xref Save the code path prior to doing anything Get list of xref checks we want to run Look for exports that are unused by anything Look for calls to undefined functions Restore the original code path Stop xref =================================================================== =================================================================== Report all the unused functions Ignore behaviour functions, and explicitly marked functions Functions can be ignored by using -ignore_xref([{F, A}, ...]). Setup a filter function that builds a list of behaviour callbacks and/or any functions marked to ignore. We then use this list to mask any functions marked as unused exports by xref Extract an element from a tuple, or undefined if N > tuple size xref doesn't work if there is no abstract_code, so we can avoid being too paranoid here. Extract the original source filename from the abstract code Extract the line number for a given function def
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- rebar : Erlang Build Tools Copyright ( c ) 2009 ( ) in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , written by < > , and others . -module(rebar_xref). -include("rebar.hrl"). -export([xref/2]). xref(Config, _) -> {ok, _} = xref:start(xref), ok = xref:set_library_path(xref, code_path()), xref:set_default(xref, [{warnings, rebar_config:get(Config, xref_warnings, false)}, {verbose, rebar_config:is_verbose()}]), {ok, _} = xref:add_directory(xref, "ebin"), OrigPath = code:get_path(), true = code:add_path(filename:join(rebar_utils:get_cwd(), "ebin")), XrefChecks = rebar_config:get(Config, xref_checks, [exports_not_used, undefined_function_calls]), ExportsNoWarn = case lists:member(exports_not_used, XrefChecks) of true -> check_exports_not_used(); false -> true end, UndefNoWarn = case lists:member(undefined_function_calls, XrefChecks) of true -> check_undefined_function_calls(); false -> true end, true = code:set_path(OrigPath), stopped = xref:stop(xref), case lists:all(fun(NoWarn) -> NoWarn end, [ExportsNoWarn, UndefNoWarn]) of true -> ok; false -> ?FAIL end. Internal functions check_exports_not_used() -> {ok, UnusedExports0} = xref:analyze(xref, exports_not_used), UnusedExports = filter_away_ignored(UnusedExports0), display_mfas(UnusedExports, "is unused export (Xref)"), UnusedExports =:= []. check_undefined_function_calls() -> {ok, UndefinedCalls0} = xref:analyze(xref, undefined_function_calls), UndefinedCalls = [{find_mfa_source(Caller), format_fa(Caller), format_mfa(Target)} || {Caller, Target} <- UndefinedCalls0], lists:foreach( fun({{Source, Line}, FunStr, Target}) -> ?CONSOLE("~s:~w: Warning ~s calls undefined function ~s\n", [Source, Line, FunStr, Target]) end, UndefinedCalls), UndefinedCalls =:= []. code_path() -> [P || P <- code:get_path(), filelib:is_dir(P)] ++ [filename:join(rebar_utils:get_cwd(), "ebin")]. filter_away_ignored(UnusedExports) -> F = fun(Mod) -> Attrs = kf(attributes, Mod:module_info()), Ignore = kf(ignore_xref, Attrs), Callbacks = [B:behaviour_info(callbacks) || B <- kf(behaviour, Attrs)], [{Mod, F, A} || {F, A} <- Ignore ++ lists:flatten(Callbacks)] end, AttrIgnore = lists:flatten( lists:map(F, lists:usort([M || {M, _, _} <- UnusedExports]))), [X || X <- UnusedExports, not lists:member(X, AttrIgnore)]. kf(Key, List) -> case lists:keyfind(Key, 1, List) of {Key, Value} -> Value; false -> [] end. display_mfas([], _Message) -> ok; display_mfas([{_Mod, Fun, Args} = MFA | Rest], Message) -> {Source, Line} = find_mfa_source(MFA), ?CONSOLE("~s:~w: Warning: function ~s/~w ~s\n", [Source, Line, Fun, Args, Message]), display_mfas(Rest, Message). format_mfa({M, F, A}) -> ?FMT("~s:~s/~w", [M, F, A]). format_fa({_M, F, A}) -> ?FMT("~s/~w", [F, A]). safe_element(N, Tuple) -> case catch(element(N, Tuple)) of {'EXIT', {badarg, _}} -> undefined; Value -> Value end. Given a MFA , find the file and LOC where it 's defined . Note that find_mfa_source({M, F, A}) -> {M, Bin, _} = code:get_object_code(M), AbstractCode = beam_lib:chunks(Bin, [abstract_code]), {ok, {M, [{abstract_code, {raw_abstract_v1, Code}}]}} = AbstractCode, [{attribute, 1, file, {Source, _}} | _] = Code, [{function, Line, F, _, _}] = [E || E <- Code, safe_element(1, E) == function, safe_element(3, E) == F, safe_element(4, E) == A], {Source, Line}.
f3223f1c476e9cf7919b1d8af4a7e8b379a459aae6a930edecdcf27cebd524ee
bgusach/exercises-htdp2e
ex-147.rkt
#lang htdp/bsl A NEList - of - bools is one of - ( cons Boolean ' ( ) ) - ( cons Boolean NEList - of - bools ) NEList - of - bools - > Boolean ; Returns whether all the elements of the list are true (check-expect (all-true (cons #true '())) #true) (check-expect (all-true (cons #false '())) #false) (check-expect (all-true (cons #true (cons #true '()))) #true) (check-expect (all-true (cons #true (cons #false '()))) #false) (define (all-true lob) (cond [(empty? (rest lob)) (first lob)] [else (and (first lob) (all-true (rest lob)) )])) NEList - of - bools - > Boolean Returns whether at least one element of the list is # true (check-expect (one-true (cons #true '())) #true) (check-expect (one-true (cons #false '())) #false) (check-expect (one-true (cons #true (cons #true '()))) #true) (check-expect (one-true (cons #true (cons #false '()))) #true) (define (one-true lob) (cond [(empty? (rest lob)) (first lob)] [else (or (first lob) (one-true (rest lob)) )])) (require test-engine/racket-tests) (test)
null
https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/ex-147.rkt
racket
Returns whether all the elements of the list are true
#lang htdp/bsl A NEList - of - bools is one of - ( cons Boolean ' ( ) ) - ( cons Boolean NEList - of - bools ) NEList - of - bools - > Boolean (check-expect (all-true (cons #true '())) #true) (check-expect (all-true (cons #false '())) #false) (check-expect (all-true (cons #true (cons #true '()))) #true) (check-expect (all-true (cons #true (cons #false '()))) #false) (define (all-true lob) (cond [(empty? (rest lob)) (first lob)] [else (and (first lob) (all-true (rest lob)) )])) NEList - of - bools - > Boolean Returns whether at least one element of the list is # true (check-expect (one-true (cons #true '())) #true) (check-expect (one-true (cons #false '())) #false) (check-expect (one-true (cons #true (cons #true '()))) #true) (check-expect (one-true (cons #true (cons #false '()))) #true) (define (one-true lob) (cond [(empty? (rest lob)) (first lob)] [else (or (first lob) (one-true (rest lob)) )])) (require test-engine/racket-tests) (test)
edac308b0dc26cad916949f861f941e856e3d8e76f572ffd364f71f7f1f8c11c
OtpChatBot/Ybot
ybot_plugin_memory_app.erl
%%%----------------------------------------------------------------------------- @author < > %%% @doc Ybot memory plugin using OTP application %%% @end Created : 20 Mar 2013 by tgrk < > %%%----------------------------------------------------------------------------- -module(ybot_plugin_memory_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %%============================================================================= %% Application callbacks %%============================================================================= start(_StartType, _StartArgs) -> ybot_plugin_memory_sup:start_link(). stop(_State) -> ok. %%%============================================================================= Internal functionality %%%=============================================================================
null
https://raw.githubusercontent.com/OtpChatBot/Ybot/5ce05fea0eb9001d1c0ff89702729f4c80743872/plugins/memory/src/ybot_plugin_memory_app.erl
erlang
----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- Application callbacks ============================================================================= Application callbacks ============================================================================= ============================================================================= =============================================================================
@author < > Ybot memory plugin using OTP application Created : 20 Mar 2013 by tgrk < > -module(ybot_plugin_memory_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> ybot_plugin_memory_sup:start_link(). stop(_State) -> ok. Internal functionality
8dff5281e42ef86a0559afb04ca9055839e029ad9de05903308b3540d5d33c51
arohner/spectrum
recur_bad_arity.clj
(ns spectrum.examples.bad.loop-change-type (:require [clojure.spec.alpha :as s])) (s/fdef foo :args (s/cat :i int?) :ret int?) (defn foo [x] (let [y 3] (if (even? x) (recur x y) (inc x))))
null
https://raw.githubusercontent.com/arohner/spectrum/72b47a91a5ce4567eed547507d25b2528f48c2d1/test/spectrum/examples/bad/recur_bad_arity.clj
clojure
(ns spectrum.examples.bad.loop-change-type (:require [clojure.spec.alpha :as s])) (s/fdef foo :args (s/cat :i int?) :ret int?) (defn foo [x] (let [y 3] (if (even? x) (recur x y) (inc x))))
24b13e8dea8bcdd84f1bbb8125457a552e00f38964810fc763ae386a1e768cec
andrenth/routemachine
rtm_config.erl
-module(rtm_config). -export([parse/1, peers/1, get/2, get/3, networks/1]). -include_lib("bgp.hrl"). -include_lib("session.hrl"). -type(conf() :: [term()]). -spec parse(file:name()) -> conf(). parse(File) -> {ok, Conf} = file:consult(File), Conf. -spec peers(conf()) -> [#session{}]. peers(Conf) -> {local, Local} = get(local, Conf), Peers = get_all(peer, Conf), build_session(Local, Peers). -spec networks(conf()) -> [prefix()]. networks(Conf) -> {local, Local} = get(local, Conf), Networks = get_all(network, Local), lists:map(fun({Net, Len}) -> {rtm_util:ip_to_num(Net, Len), Len} end, Networks). -spec get(atom(), conf()) -> none | tuple(). get(Key, Conf) -> proplists:lookup(Key, Conf). -spec get(atom(), conf(), term()) -> term(). get(Key, Conf, Default) -> proplists:get_value(Key, Conf, Default). get_all(Key, Conf) -> proplists:get_all_values(Key, Conf). build_session(Local, Peers) -> build_session(Local, Peers, []). build_session(_Local, [], Sessions) -> Sessions; build_session(Local, [Peer | Rest], Sessions) -> {asn, LocalAsn} = get(asn, Local), {address, LocalAddr} = get(address, Local), {asn, PeerAsn} = get(asn, Peer), {address, PeerAddr} = get(address, Peer), Session = #session{ local_asn = LocalAsn, local_addr = LocalAddr, peer_asn = PeerAsn, peer_addr = PeerAddr, hold_time = get(hold_time, Peer, ?BGP_TIMER_HOLD), keepalive_time = get(keepalive_time, Peer, ?BGP_TIMER_KEEPALIVE), conn_retry_time = get(conn_retry_time, Peer, ?BGP_TIMER_CONN_RETRY), idle_time = get(idle_time, Peer, ?BGP_TIMER_IDLE), establishment = get(establishment, Peer, active) }, build_session(Local, Rest, [Session | Sessions]).
null
https://raw.githubusercontent.com/andrenth/routemachine/97fbc4997ac9bbe7d14c2b174aa84bc4a2fd5d20/src/rtm_config.erl
erlang
-module(rtm_config). -export([parse/1, peers/1, get/2, get/3, networks/1]). -include_lib("bgp.hrl"). -include_lib("session.hrl"). -type(conf() :: [term()]). -spec parse(file:name()) -> conf(). parse(File) -> {ok, Conf} = file:consult(File), Conf. -spec peers(conf()) -> [#session{}]. peers(Conf) -> {local, Local} = get(local, Conf), Peers = get_all(peer, Conf), build_session(Local, Peers). -spec networks(conf()) -> [prefix()]. networks(Conf) -> {local, Local} = get(local, Conf), Networks = get_all(network, Local), lists:map(fun({Net, Len}) -> {rtm_util:ip_to_num(Net, Len), Len} end, Networks). -spec get(atom(), conf()) -> none | tuple(). get(Key, Conf) -> proplists:lookup(Key, Conf). -spec get(atom(), conf(), term()) -> term(). get(Key, Conf, Default) -> proplists:get_value(Key, Conf, Default). get_all(Key, Conf) -> proplists:get_all_values(Key, Conf). build_session(Local, Peers) -> build_session(Local, Peers, []). build_session(_Local, [], Sessions) -> Sessions; build_session(Local, [Peer | Rest], Sessions) -> {asn, LocalAsn} = get(asn, Local), {address, LocalAddr} = get(address, Local), {asn, PeerAsn} = get(asn, Peer), {address, PeerAddr} = get(address, Peer), Session = #session{ local_asn = LocalAsn, local_addr = LocalAddr, peer_asn = PeerAsn, peer_addr = PeerAddr, hold_time = get(hold_time, Peer, ?BGP_TIMER_HOLD), keepalive_time = get(keepalive_time, Peer, ?BGP_TIMER_KEEPALIVE), conn_retry_time = get(conn_retry_time, Peer, ?BGP_TIMER_CONN_RETRY), idle_time = get(idle_time, Peer, ?BGP_TIMER_IDLE), establishment = get(establishment, Peer, active) }, build_session(Local, Rest, [Session | Sessions]).
35a38e4b2968e4e9c3ff70630a85bba390881bfe76c5112675ed2a1a7be36e9c
jonatack/cl-kraken
trades.lisp
;;;; cl-kraken/tests/trades.lisp (defpackage #:cl-kraken/tests/trades (:use #:cl #:cl-kraken #:rove) (:import-from #:jsown #:filter) (:import-from #:parse-float #:parse-float) (:import-from #:cl-kraken #:server-time)) (in-package #:cl-kraken/tests/trades) (deftest trades (testing "when passed \"xbtUSD\", evaluates to data on 1000 XBTUSD trades" (let* ((response (cl-kraken:trades "xbtUSD")) (error! (filter response "error")) (result (filter response "result")) (last (filter result "last")) (pair (filter result "XXBTZUSD")) (trade (first pair))) (ok (consp response)) (ok (= (length response) 3)) (ok (eq (first response) :OBJ)) (ok (equal (second response) '("error"))) (ok (null error!)) (ok (consp result)) (ok (= (length result) 3)) (ok (simple-string-p last)) (ok (= (length last) 19)) (ok (listp pair)) (ok (= (length pair) 1000)) (ok (listp trade)) (ok (= (length trade) 6)) (destructuring-bind (price volume time buy/sell market/limit misc) trade (ok (simple-string-p price)) (ok (simple-string-p volume)) (ok (floatp (parse-float price))) (ok (floatp (parse-float volume))) (ok (typep time 'ratio)) (ok (or (string= buy/sell "b") (string= buy/sell "s"))) (ok (or (string= market/limit "m") (string= market/limit "l"))) (ok (string= misc ""))))) ;; Test invalid PAIR values. (testing "when passed a multiple PAIR, evaluates to unknown asset pair error" (ok (equal (cl-kraken:trades "xbteur,xbtusd") '(:OBJ ("error" "EQuery:Unknown asset pair"))))) (testing "when passed an invalid PAIR, evaluates to unknown asset pair error" (ok (equal (cl-kraken:trades "abc") '(:OBJ ("error" "EQuery:Unknown asset pair"))))) (testing "when passed an empty PAIR, evaluates to invalid arguments error" (ok (equal (cl-kraken:trades "") '(:OBJ ("error" "EGeneral:Invalid arguments"))))) (testing "when passed a valid PAIR with spaces -> unknown asset pair error" (ok (equal (cl-kraken:trades " xbtusd") '(:OBJ ("error" "EQuery:Unknown asset pair"))))) (testing "when passed a symbol PAIR, a type error is signaled" (ok (signals (cl-kraken:trades 'xbteur) 'type-error) "The value of PAIR is XBTEUR, which is not of type SIMPLE-STRING.")) (testing "when passed a keyword PAIR, a type error is signaled" (ok (signals (cl-kraken:trades :xbteur) 'type-error) "The value of PAIR is :XBTEUR, which is not of type SIMPLE-STRING.")) Test correct handling of SINCE keyword parameter to query params . (testing "when no SINCE is passed, it is absent from the query params" (let ((headers (with-output-to-string (*standard-output*) (cl-kraken:trades "xbteur" :verbose t)))) (ok (string= headers "Trades?pair=xbteur " :start1 65 :end1 84)))) (testing "when passed an integer SINCE, it is present in the query params" (let* ((server-time (filter (server-time) "result" "unixtime")) (kraken-time (* server-time 1000 1000 1000)) (since (princ-to-string kraken-time)) (headers (with-output-to-string (*standard-output*) (cl-kraken:trades "xbteur" :since kraken-time :verbose t))) (expected (concatenate 'string "Trades?since=" since "&pair=xbteur"))) (ok (string= headers expected :start1 65 :end1 (+ 90 (length since)))))) Test invalid SINCE values . (testing "when passed a string SINCE, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :since "1") 'type-error) "The value of SINCE is \"1\", which is not of type INTEGER.")) (testing "when passed a symbol SINCE, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :since 'a) 'type-error) "The value of SINCE is 'a, which is not of type INTEGER.")) (testing "when passed a keyword SINCE, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :since :1) 'type-error) "The value of SINCE is :|1|, which is not of type INTEGER.")) ;; Test RAW parameter. (testing "when passed RAW T, evaluates to the raw response string" (let ((response (cl-kraken:trades "xbteur" :raw t)) (expected "{\"error\":[],\"result\":{\"XXBTZEUR\":[[")) (ok (stringp response)) (ok (string= response expected :start1 0 :end1 35 )))) (testing "when passed RAW NIL, evaluates as if no RAW argument was passed" (let* ((response (cl-kraken:trades "xbtusd" :raw nil)) (error! (filter response "error")) (result (filter response "result")) (last (filter result "last")) (pair (filter result "XXBTZUSD")) (trade (first pair))) (ok (consp response)) (ok (= (length response) 3)) (ok (eq (first response) :OBJ)) (ok (equal (second response) '("error"))) (ok (null error!)) (ok (consp result)) (ok (= (length result) 3)) (ok (simple-string-p last)) (ok (= (length last) 19)) (ok (listp pair)) (ok (= (length pair) 1000)) (ok (listp trade)) (ok (= (length trade) 6)))) ;; Test invalid RAW values. (testing "when passed a string RAW, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :raw "1") 'type-error) "The value of RAW is \"1\", which is not of type (MEMBER T NIL).")) (testing "when passed a symbol RAW, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :raw 'a) 'type-error) "The value of RAW is 'a, which is not of type (MEMBER T NIL).")) (testing "when passed a keyword RAW, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :raw :1) 'type-error) "The value of RAW is :|1|, which is not of type (MEMBER T NIL).")))
null
https://raw.githubusercontent.com/jonatack/cl-kraken/e5b438eb821bf7dc3514a44ff84f15f393b4e393/tests/trades.lisp
lisp
cl-kraken/tests/trades.lisp Test invalid PAIR values. Test RAW parameter. Test invalid RAW values.
(defpackage #:cl-kraken/tests/trades (:use #:cl #:cl-kraken #:rove) (:import-from #:jsown #:filter) (:import-from #:parse-float #:parse-float) (:import-from #:cl-kraken #:server-time)) (in-package #:cl-kraken/tests/trades) (deftest trades (testing "when passed \"xbtUSD\", evaluates to data on 1000 XBTUSD trades" (let* ((response (cl-kraken:trades "xbtUSD")) (error! (filter response "error")) (result (filter response "result")) (last (filter result "last")) (pair (filter result "XXBTZUSD")) (trade (first pair))) (ok (consp response)) (ok (= (length response) 3)) (ok (eq (first response) :OBJ)) (ok (equal (second response) '("error"))) (ok (null error!)) (ok (consp result)) (ok (= (length result) 3)) (ok (simple-string-p last)) (ok (= (length last) 19)) (ok (listp pair)) (ok (= (length pair) 1000)) (ok (listp trade)) (ok (= (length trade) 6)) (destructuring-bind (price volume time buy/sell market/limit misc) trade (ok (simple-string-p price)) (ok (simple-string-p volume)) (ok (floatp (parse-float price))) (ok (floatp (parse-float volume))) (ok (typep time 'ratio)) (ok (or (string= buy/sell "b") (string= buy/sell "s"))) (ok (or (string= market/limit "m") (string= market/limit "l"))) (ok (string= misc ""))))) (testing "when passed a multiple PAIR, evaluates to unknown asset pair error" (ok (equal (cl-kraken:trades "xbteur,xbtusd") '(:OBJ ("error" "EQuery:Unknown asset pair"))))) (testing "when passed an invalid PAIR, evaluates to unknown asset pair error" (ok (equal (cl-kraken:trades "abc") '(:OBJ ("error" "EQuery:Unknown asset pair"))))) (testing "when passed an empty PAIR, evaluates to invalid arguments error" (ok (equal (cl-kraken:trades "") '(:OBJ ("error" "EGeneral:Invalid arguments"))))) (testing "when passed a valid PAIR with spaces -> unknown asset pair error" (ok (equal (cl-kraken:trades " xbtusd") '(:OBJ ("error" "EQuery:Unknown asset pair"))))) (testing "when passed a symbol PAIR, a type error is signaled" (ok (signals (cl-kraken:trades 'xbteur) 'type-error) "The value of PAIR is XBTEUR, which is not of type SIMPLE-STRING.")) (testing "when passed a keyword PAIR, a type error is signaled" (ok (signals (cl-kraken:trades :xbteur) 'type-error) "The value of PAIR is :XBTEUR, which is not of type SIMPLE-STRING.")) Test correct handling of SINCE keyword parameter to query params . (testing "when no SINCE is passed, it is absent from the query params" (let ((headers (with-output-to-string (*standard-output*) (cl-kraken:trades "xbteur" :verbose t)))) (ok (string= headers "Trades?pair=xbteur " :start1 65 :end1 84)))) (testing "when passed an integer SINCE, it is present in the query params" (let* ((server-time (filter (server-time) "result" "unixtime")) (kraken-time (* server-time 1000 1000 1000)) (since (princ-to-string kraken-time)) (headers (with-output-to-string (*standard-output*) (cl-kraken:trades "xbteur" :since kraken-time :verbose t))) (expected (concatenate 'string "Trades?since=" since "&pair=xbteur"))) (ok (string= headers expected :start1 65 :end1 (+ 90 (length since)))))) Test invalid SINCE values . (testing "when passed a string SINCE, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :since "1") 'type-error) "The value of SINCE is \"1\", which is not of type INTEGER.")) (testing "when passed a symbol SINCE, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :since 'a) 'type-error) "The value of SINCE is 'a, which is not of type INTEGER.")) (testing "when passed a keyword SINCE, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :since :1) 'type-error) "The value of SINCE is :|1|, which is not of type INTEGER.")) (testing "when passed RAW T, evaluates to the raw response string" (let ((response (cl-kraken:trades "xbteur" :raw t)) (expected "{\"error\":[],\"result\":{\"XXBTZEUR\":[[")) (ok (stringp response)) (ok (string= response expected :start1 0 :end1 35 )))) (testing "when passed RAW NIL, evaluates as if no RAW argument was passed" (let* ((response (cl-kraken:trades "xbtusd" :raw nil)) (error! (filter response "error")) (result (filter response "result")) (last (filter result "last")) (pair (filter result "XXBTZUSD")) (trade (first pair))) (ok (consp response)) (ok (= (length response) 3)) (ok (eq (first response) :OBJ)) (ok (equal (second response) '("error"))) (ok (null error!)) (ok (consp result)) (ok (= (length result) 3)) (ok (simple-string-p last)) (ok (= (length last) 19)) (ok (listp pair)) (ok (= (length pair) 1000)) (ok (listp trade)) (ok (= (length trade) 6)))) (testing "when passed a string RAW, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :raw "1") 'type-error) "The value of RAW is \"1\", which is not of type (MEMBER T NIL).")) (testing "when passed a symbol RAW, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :raw 'a) 'type-error) "The value of RAW is 'a, which is not of type (MEMBER T NIL).")) (testing "when passed a keyword RAW, a type error is signaled" (ok (signals (cl-kraken:trades "xbteur" :raw :1) 'type-error) "The value of RAW is :|1|, which is not of type (MEMBER T NIL).")))
b25200cd3b6069095e229bd7e4ea1a27b341ff0c924961d5966a2a0c13d54291
SamirTalwar/advent-of-code
AOC_10_2.hs
# LANGUAGE ScopedTypeVariables # import Data.Array import qualified Data.List as List import qualified Data.Maybe as Maybe import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as IO import Text.Parsec import Text.Parsec.Text data Instruction = StartingValue Carrier Value | Give Carrier Carrier Carrier deriving (Eq, Show) data Carrier = Bot Int | Output Int deriving (Eq, Show) data Value = Value Int deriving (Eq, Ord, Show) data BotState = BotState (Maybe Value) (Maybe Value) deriving (Eq, Show) data OutputState = OutputState {unOutputState :: Maybe Value} deriving (Eq, Show) data Operation = Gave Carrier (Value, Carrier) (Value, Carrier) deriving (Eq, Show) main = do input <- Text.lines <$> IO.getContents let instructions = map parseInput input let theBotRange = botRange instructions let botsWithNothing = listArray theBotRange $ repeat (BotState Nothing Nothing) let theOutputRange = outputRange instructions let startingOutputs = listArray theOutputRange $ repeat (OutputState Nothing) let (startingValues, gives) = splitUp instructions let startingBots = disseminate startingValues botsWithNothing let outputs = run (cycle gives) startingBots startingOutputs print $ do Value a <- unOutputState $ outputs ! 0 Value b <- unOutputState $ outputs ! 1 Value c <- unOutputState $ outputs ! 2 return $ a * b * c parseInput :: Text -> Instruction parseInput text = either (error . show) id $ parse parser "" text where parser = try startingValue <|> try give startingValue = do v <- value string " goes to " c <- carrier return $ StartingValue c v give = do source <- carrier string " gives low to " lowDestination <- carrier string " and high to " highDestination <- carrier return $ Give source lowDestination highDestination value = Value <$> (string "value " >> number) carrier = try bot <|> try output bot = Bot <$> (string "bot " >> number) output = Output <$> (string "output " >> number) number = read <$> many1 digit botRange :: [Instruction] -> (Int, Int) botRange instructions = (Set.findMin bots, Set.findMax bots) where bots = Set.fromList $ concatMap identifyBots instructions identifyBots (StartingValue (Bot bot) _) = [bot] identifyBots (Give (Bot source) (Bot lowDestination) (Bot highDestination)) = [source, lowDestination, highDestination] identifyBots (Give (Bot source) (Bot lowDestination) _) = [source, lowDestination] identifyBots (Give (Bot source) _ (Bot highDestination)) = [source, highDestination] identifyBots (Give _ (Bot lowDestination) (Bot highDestination)) = [lowDestination, highDestination] identifyBots (Give (Bot source) _ _) = [source] identifyBots (Give _ (Bot lowDestination) _) = [lowDestination] identifyBots (Give _ _ (Bot highDestination)) = [highDestination] identifyBots _ = [] outputRange :: [Instruction] -> (Int, Int) outputRange instructions = (Set.findMin outputs, Set.findMax outputs) where outputs = Set.fromList $ concatMap identifyOutputs instructions identifyOutputs (Give _ (Output lowDestination) (Output highDestination)) = [lowDestination, highDestination] identifyOutputs (Give _ (Output lowDestination) _) = [lowDestination] identifyOutputs (Give _ _ (Output highDestination)) = [highDestination] identifyOutputs _ = [] splitUp :: [Instruction] -> ([Instruction], [Instruction]) splitUp instructions = List.partition isStartingValue instructions where isStartingValue (StartingValue _ _) = True isStartingValue _ = False disseminate :: [Instruction] -> Array Int BotState -> Array Int BotState disseminate startingValues bots = accum give bots startingValuesByBot where startingValuesByBot = map (\(StartingValue (Bot bot) value) -> (bot, value)) startingValues run :: [Instruction] -> Array Int BotState -> Array Int OutputState -> Array Int OutputState run [] bots outputs = outputs run (Give carrier@(Bot bot) lowDestination highDestination : next) bots outputs = if all (\(BotState low high) -> Maybe.isNothing low || Maybe.isNothing high) (elems bots) then outputs else case bots ! bot of BotState (Just valueA) (Just valueB) -> let lowValue = min valueA valueB highValue = max valueA valueB in case (lowDestination, highDestination) of (Bot low, Bot high) -> run next ( bots // [ (low, give (bots ! low) lowValue), (high, give (bots ! high) highValue), (bot, BotState Nothing Nothing) ] ) outputs (Bot low, Output high) -> run next ( bots // [ (low, give (bots ! low) lowValue), (bot, BotState Nothing Nothing) ] ) ( outputs // [ (high, OutputState (Just highValue)) ] ) (Output low, Bot high) -> run next ( bots // [ (high, give (bots ! high) highValue), (bot, BotState Nothing Nothing) ] ) ( outputs // [ (low, OutputState (Just lowValue)) ] ) (Output low, Output high) -> run next ( bots // [ (bot, BotState Nothing Nothing) ] ) ( outputs // [ (low, OutputState (Just lowValue)), (high, OutputState (Just highValue)) ] ) _ -> run next bots outputs give (BotState Nothing Nothing) value = BotState (Just value) Nothing give (BotState (Just value1) Nothing) value2 = BotState (Just value1) (Just value2) give (BotState (Just value1) (Just value2)) value3 = error $ "Tried to give a bot " ++ show value3 ++ ", but it already had " ++ show value1 ++ " and " ++ show value2 ++ "."
null
https://raw.githubusercontent.com/SamirTalwar/advent-of-code/66bd9e31f078c9b81ece0264fb869e48964afa63/2016/AOC_10_2.hs
haskell
# LANGUAGE ScopedTypeVariables # import Data.Array import qualified Data.List as List import qualified Data.Maybe as Maybe import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as IO import Text.Parsec import Text.Parsec.Text data Instruction = StartingValue Carrier Value | Give Carrier Carrier Carrier deriving (Eq, Show) data Carrier = Bot Int | Output Int deriving (Eq, Show) data Value = Value Int deriving (Eq, Ord, Show) data BotState = BotState (Maybe Value) (Maybe Value) deriving (Eq, Show) data OutputState = OutputState {unOutputState :: Maybe Value} deriving (Eq, Show) data Operation = Gave Carrier (Value, Carrier) (Value, Carrier) deriving (Eq, Show) main = do input <- Text.lines <$> IO.getContents let instructions = map parseInput input let theBotRange = botRange instructions let botsWithNothing = listArray theBotRange $ repeat (BotState Nothing Nothing) let theOutputRange = outputRange instructions let startingOutputs = listArray theOutputRange $ repeat (OutputState Nothing) let (startingValues, gives) = splitUp instructions let startingBots = disseminate startingValues botsWithNothing let outputs = run (cycle gives) startingBots startingOutputs print $ do Value a <- unOutputState $ outputs ! 0 Value b <- unOutputState $ outputs ! 1 Value c <- unOutputState $ outputs ! 2 return $ a * b * c parseInput :: Text -> Instruction parseInput text = either (error . show) id $ parse parser "" text where parser = try startingValue <|> try give startingValue = do v <- value string " goes to " c <- carrier return $ StartingValue c v give = do source <- carrier string " gives low to " lowDestination <- carrier string " and high to " highDestination <- carrier return $ Give source lowDestination highDestination value = Value <$> (string "value " >> number) carrier = try bot <|> try output bot = Bot <$> (string "bot " >> number) output = Output <$> (string "output " >> number) number = read <$> many1 digit botRange :: [Instruction] -> (Int, Int) botRange instructions = (Set.findMin bots, Set.findMax bots) where bots = Set.fromList $ concatMap identifyBots instructions identifyBots (StartingValue (Bot bot) _) = [bot] identifyBots (Give (Bot source) (Bot lowDestination) (Bot highDestination)) = [source, lowDestination, highDestination] identifyBots (Give (Bot source) (Bot lowDestination) _) = [source, lowDestination] identifyBots (Give (Bot source) _ (Bot highDestination)) = [source, highDestination] identifyBots (Give _ (Bot lowDestination) (Bot highDestination)) = [lowDestination, highDestination] identifyBots (Give (Bot source) _ _) = [source] identifyBots (Give _ (Bot lowDestination) _) = [lowDestination] identifyBots (Give _ _ (Bot highDestination)) = [highDestination] identifyBots _ = [] outputRange :: [Instruction] -> (Int, Int) outputRange instructions = (Set.findMin outputs, Set.findMax outputs) where outputs = Set.fromList $ concatMap identifyOutputs instructions identifyOutputs (Give _ (Output lowDestination) (Output highDestination)) = [lowDestination, highDestination] identifyOutputs (Give _ (Output lowDestination) _) = [lowDestination] identifyOutputs (Give _ _ (Output highDestination)) = [highDestination] identifyOutputs _ = [] splitUp :: [Instruction] -> ([Instruction], [Instruction]) splitUp instructions = List.partition isStartingValue instructions where isStartingValue (StartingValue _ _) = True isStartingValue _ = False disseminate :: [Instruction] -> Array Int BotState -> Array Int BotState disseminate startingValues bots = accum give bots startingValuesByBot where startingValuesByBot = map (\(StartingValue (Bot bot) value) -> (bot, value)) startingValues run :: [Instruction] -> Array Int BotState -> Array Int OutputState -> Array Int OutputState run [] bots outputs = outputs run (Give carrier@(Bot bot) lowDestination highDestination : next) bots outputs = if all (\(BotState low high) -> Maybe.isNothing low || Maybe.isNothing high) (elems bots) then outputs else case bots ! bot of BotState (Just valueA) (Just valueB) -> let lowValue = min valueA valueB highValue = max valueA valueB in case (lowDestination, highDestination) of (Bot low, Bot high) -> run next ( bots // [ (low, give (bots ! low) lowValue), (high, give (bots ! high) highValue), (bot, BotState Nothing Nothing) ] ) outputs (Bot low, Output high) -> run next ( bots // [ (low, give (bots ! low) lowValue), (bot, BotState Nothing Nothing) ] ) ( outputs // [ (high, OutputState (Just highValue)) ] ) (Output low, Bot high) -> run next ( bots // [ (high, give (bots ! high) highValue), (bot, BotState Nothing Nothing) ] ) ( outputs // [ (low, OutputState (Just lowValue)) ] ) (Output low, Output high) -> run next ( bots // [ (bot, BotState Nothing Nothing) ] ) ( outputs // [ (low, OutputState (Just lowValue)), (high, OutputState (Just highValue)) ] ) _ -> run next bots outputs give (BotState Nothing Nothing) value = BotState (Just value) Nothing give (BotState (Just value1) Nothing) value2 = BotState (Just value1) (Just value2) give (BotState (Just value1) (Just value2)) value3 = error $ "Tried to give a bot " ++ show value3 ++ ", but it already had " ++ show value1 ++ " and " ++ show value2 ++ "."
13eacf8e334f3790899751cbc55f6c0dae35adcd8a62c1f00eb263667ffa2277
LLNL/rhizome
project.clj
(defproject rhizome "1.0.0-SNAPSHOT" :description "Learn and process LDA topics for use in IRIS system" :dependencies [[org.clojure/clojure "1.2.1"] [org.clojure/clojure-contrib "1.2.0"] [solrclj/solrclj "0.1.1"] [incanter "1.2.2"] [congomongo "0.1.4-SNAPSHOT"] [log4j "1.2.15" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]] [token "1.0.0-SNAPSHOT"] [semco "1.0.0-SNAPSHOT"] [chisel "1.0.0-SNAPSHOT"]] :dev-dependencies [[swank-clojure "1.3.1"] [marginalia "0.3.2"]] :main rhizome.app)
null
https://raw.githubusercontent.com/LLNL/rhizome/af8e00ac89a98e2d07fe7a6272857951c2781182/project.clj
clojure
(defproject rhizome "1.0.0-SNAPSHOT" :description "Learn and process LDA topics for use in IRIS system" :dependencies [[org.clojure/clojure "1.2.1"] [org.clojure/clojure-contrib "1.2.0"] [solrclj/solrclj "0.1.1"] [incanter "1.2.2"] [congomongo "0.1.4-SNAPSHOT"] [log4j "1.2.15" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]] [token "1.0.0-SNAPSHOT"] [semco "1.0.0-SNAPSHOT"] [chisel "1.0.0-SNAPSHOT"]] :dev-dependencies [[swank-clojure "1.3.1"] [marginalia "0.3.2"]] :main rhizome.app)
e9f1a6c5acb64b136838e5259dc9002e02c59cd17d36912f3871016a0c483a99
pascalh/Astview
Types.hs
{- contains the GUI data types - -} module Language.Astview.Gui.Types where import Data.Label import Data.IORef import Control.Monad.Reader import Graphics.UI.Gtk hiding (Language,get,set) import Graphics.UI.Gtk.SourceView (SourceBuffer) import Language.Astview.Language(Language,SrcSpan,Path,position) |a type class for default values , compareable to in class ' Monoid ' class Default a where defaultValue :: a type AstAction a = ReaderT (IORef AstState) (ReaderT GUI IO) a -- |run a 'AstAction' by providing values for the reader monad. -- (in most cases 'ioRunner' is more useful) runAsIo :: GUI -> IORef AstState -> AstAction a -> IO a runAsIo gui st f = runReaderT (runReaderT f st) gui -- |returns a transformer from 'AstAction' to 'IO' ioRunner :: AstAction (AstAction a -> IO a) ioRunner = do ioref <- ask gui <- lift ask return $ \f -> runAsIo gui ioref f -- |internal program state data AstState = AstState { state :: State -- ^ intern program state , options :: Options -- ^ global program options } -- |data type for global options, which can be directly changed in the gui -- (...or at least should be. Menu for changing font and font size not yet -- implemented) data Options = Options ^ font name of textbuffer ^ font size of textbuffer , flattenLists :: Bool -- ^should lists be flattened } instance Default Options where defaultValue = Options "Monospace" 9 True -- |data type for the internal program state data State = State { currentFile :: String -- ^ current file , textchanged :: Bool -- ^ true if buffer changed after last save , lastSelectionInText :: SrcSpan -- ^ last active cursor position , lastSelectionInTree :: Path -- ^ last clicked tree cell , knownLanguages :: [Language] -- ^ known languages, which can be parsed , activeLanguage :: Maybe Language -- ^the currently selected language or Nothing if language is selected by file extension } instance Default State where defaultValue = State { currentFile = unsavedDoc , textchanged = False , lastSelectionInText = position 0 0 , lastSelectionInTree = [] , knownLanguages = [] , activeLanguage = Nothing } -- |unsaved document unsavedDoc :: String unsavedDoc = "Unsaved document" |main gui data type , contains gtk components data GUI = GUI { window :: Window -- ^ main window , tv :: TreeView -- ^ treeview , sb :: SourceBuffer -- ^ sourceview } -- * getAstStateter functions mkLabels [ ''AstState , ''Options , ''State , ''GUI ] getAstState :: AstAction AstState getAstState = do ioRef <- ask liftIO (readIORef ioRef) getSourceBuffer :: AstAction SourceBuffer getSourceBuffer = sb <$> getGui getTreeView :: AstAction TreeView getTreeView = tv <$> getGui getGui :: AstAction GUI getGui = lift ask getState :: AstAction State getState = state <$> getAstState getKnownLanguages :: AstAction [Language] getKnownLanguages = (knownLanguages . state) <$> getAstState getChanged :: AstAction Bool getChanged = (textchanged . state) <$> getAstState getCursor :: AstAction SrcSpan getCursor = (lastSelectionInText . state) <$> getAstState getPath :: AstAction TreePath getPath = (lastSelectionInTree . state) <$> getAstState getCurrentFile :: AstAction String getCurrentFile = (currentFile . state) <$> getAstState getActiveLanguage :: AstAction (Maybe Language) getActiveLanguage = (activeLanguage . state) <$> getAstState getWindow :: AstAction Window getWindow = window <$> getGui getFlattenLists :: AstAction Bool getFlattenLists = (flattenLists . options) <$> getAstState getFontsize :: AstAction Int getFontsize = (fsize . options) <$> getAstState -- * setter functions lensSetIoRef :: (AstState :-> a) -> (a :-> b) -> b -> AstAction () lensSetIoRef outerLens innerLens value = do ref <- ask liftIO $ modifyIORef ref m where m :: AstState -> AstState m = modify outerLens (set innerLens value) -- |stores the given cursor selection setCursor :: SrcSpan -> AstAction () setCursor = lensSetIoRef lState lLastSelectionInText -- |stores the given tree selection setTreePath :: Path -> AstAction () setTreePath = lensSetIoRef lState lLastSelectionInTree -- |stores file path of current opened file setCurrentFile :: FilePath -> AstAction () setCurrentFile = lensSetIoRef lState lCurrentFile -- |stores whether the current file buffer has been changed setChanged :: Bool -> AstAction () setChanged = lensSetIoRef lState lTextchanged -- |stores whether the lists in trees should be flattened setFlattenLists :: Bool -> AstAction () setFlattenLists = lensSetIoRef lOptions lFlattenLists setActiveLanguage :: Maybe Language -> AstAction () setActiveLanguage = lensSetIoRef lState lActiveLanguage
null
https://raw.githubusercontent.com/pascalh/Astview/3c0677b033a1d0366202048be273861e98a04e2a/src/gui/Language/Astview/Gui/Types.hs
haskell
contains the GUI data types - |run a 'AstAction' by providing values for the reader monad. (in most cases 'ioRunner' is more useful) |returns a transformer from 'AstAction' to 'IO' |internal program state ^ intern program state ^ global program options |data type for global options, which can be directly changed in the gui (...or at least should be. Menu for changing font and font size not yet implemented) ^should lists be flattened |data type for the internal program state ^ current file ^ true if buffer changed after last save ^ last active cursor position ^ last clicked tree cell ^ known languages, which can be parsed ^the currently selected language or Nothing if language is selected by file extension |unsaved document ^ main window ^ treeview ^ sourceview * getAstStateter functions * setter functions |stores the given cursor selection |stores the given tree selection |stores file path of current opened file |stores whether the current file buffer has been changed |stores whether the lists in trees should be flattened
module Language.Astview.Gui.Types where import Data.Label import Data.IORef import Control.Monad.Reader import Graphics.UI.Gtk hiding (Language,get,set) import Graphics.UI.Gtk.SourceView (SourceBuffer) import Language.Astview.Language(Language,SrcSpan,Path,position) |a type class for default values , compareable to in class ' Monoid ' class Default a where defaultValue :: a type AstAction a = ReaderT (IORef AstState) (ReaderT GUI IO) a runAsIo :: GUI -> IORef AstState -> AstAction a -> IO a runAsIo gui st f = runReaderT (runReaderT f st) gui ioRunner :: AstAction (AstAction a -> IO a) ioRunner = do ioref <- ask gui <- lift ask return $ \f -> runAsIo gui ioref f data AstState = AstState } data Options = Options ^ font name of textbuffer ^ font size of textbuffer } instance Default Options where defaultValue = Options "Monospace" 9 True data State = State } instance Default State where defaultValue = State { currentFile = unsavedDoc , textchanged = False , lastSelectionInText = position 0 0 , lastSelectionInTree = [] , knownLanguages = [] , activeLanguage = Nothing } unsavedDoc :: String unsavedDoc = "Unsaved document" |main gui data type , contains gtk components data GUI = GUI } mkLabels [ ''AstState , ''Options , ''State , ''GUI ] getAstState :: AstAction AstState getAstState = do ioRef <- ask liftIO (readIORef ioRef) getSourceBuffer :: AstAction SourceBuffer getSourceBuffer = sb <$> getGui getTreeView :: AstAction TreeView getTreeView = tv <$> getGui getGui :: AstAction GUI getGui = lift ask getState :: AstAction State getState = state <$> getAstState getKnownLanguages :: AstAction [Language] getKnownLanguages = (knownLanguages . state) <$> getAstState getChanged :: AstAction Bool getChanged = (textchanged . state) <$> getAstState getCursor :: AstAction SrcSpan getCursor = (lastSelectionInText . state) <$> getAstState getPath :: AstAction TreePath getPath = (lastSelectionInTree . state) <$> getAstState getCurrentFile :: AstAction String getCurrentFile = (currentFile . state) <$> getAstState getActiveLanguage :: AstAction (Maybe Language) getActiveLanguage = (activeLanguage . state) <$> getAstState getWindow :: AstAction Window getWindow = window <$> getGui getFlattenLists :: AstAction Bool getFlattenLists = (flattenLists . options) <$> getAstState getFontsize :: AstAction Int getFontsize = (fsize . options) <$> getAstState lensSetIoRef :: (AstState :-> a) -> (a :-> b) -> b -> AstAction () lensSetIoRef outerLens innerLens value = do ref <- ask liftIO $ modifyIORef ref m where m :: AstState -> AstState m = modify outerLens (set innerLens value) setCursor :: SrcSpan -> AstAction () setCursor = lensSetIoRef lState lLastSelectionInText setTreePath :: Path -> AstAction () setTreePath = lensSetIoRef lState lLastSelectionInTree setCurrentFile :: FilePath -> AstAction () setCurrentFile = lensSetIoRef lState lCurrentFile setChanged :: Bool -> AstAction () setChanged = lensSetIoRef lState lTextchanged setFlattenLists :: Bool -> AstAction () setFlattenLists = lensSetIoRef lOptions lFlattenLists setActiveLanguage :: Maybe Language -> AstAction () setActiveLanguage = lensSetIoRef lState lActiveLanguage
afb215c0b9467b7d7278f9f153fac33e599b63a11351f908a39b3860a5385c92
JustusAdam/language-haskell
T0073b.hs
SYNTAX TEST " source.haskell " " Visible kind application " type TF l = F @_ @(l :: Nat) A -- ^ ^ meta.type-application.haskell
null
https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tickets/T0073b.hs
haskell
^ ^ meta.type-application.haskell
SYNTAX TEST " source.haskell " " Visible kind application " type TF l = F @_ @(l :: Nat) A
1702a51beba4641b1d75fd66f4d8d6e567e6568f6a2ec493b0c4f0f9da2988e2
mathematical-systems/clml
dgebal.lisp
;;; Compiled by f2cl version: ( " $ I d : f2cl1.l , v 1.209 2008/09/11 14:59:55 rtoy Exp $ " " $ I d : f2cl2.l , v 1.37 2008/02/22 22:19:33 " " $ I d : f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Rel $ " " $ I d : f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Rel $ " " $ I d : f2cl5.l , v 1.197 2008/09/11 15:03:25 rtoy Exp $ " " $ I d : f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " $ I d : macros.l , v 1.106 2008/09/15 15:27:36 " ) Using Lisp International Allegro CL Enterprise Edition 8.1 [ 64 - bit Linux ( x86 - 64 ) ] ( Oct 7 , 2008 17:13 ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) ;;; (:relaxed-array-decls t) (:coerce-assigns :as-needed) ;;; (:array-type ':array) (:array-slicing t) ;;; (:declare-common nil) (:float-format double-float)) (in-package "LAPACK") (let* ((zero 0.0) (one 1.0) (sclfac 8.0) (factor 0.95)) (declare (type (double-float 0.0 0.0) zero) (type (double-float 1.0 1.0) one) (type (double-float 8.0 8.0) sclfac) (type (double-float 0.95 0.95) factor) (ignorable zero one sclfac factor)) (defun dgebal (job n a lda ilo ihi scale info) (declare (type (array double-float (*)) scale a) (type (simple-array character (*)) job) (type (f2cl-lib:integer4) info ihi ilo lda n)) (f2cl-lib:with-multi-array-data ((job character job-%data% job-%offset%) (a double-float a-%data% a-%offset%) (scale double-float scale-%data% scale-%offset%)) (prog ((c 0.0) (ca 0.0) (f 0.0) (g 0.0) (r 0.0) (ra 0.0) (s 0.0) (sfmax1 0.0) (sfmax2 0.0) (sfmin1 0.0) (sfmin2 0.0) (i 0) (ica 0) (iexc 0) (ira 0) (j 0) (k 0) (l 0) (m 0) (noconv nil)) (declare (type (double-float) c ca f g r ra s sfmax1 sfmax2 sfmin1 sfmin2) (type f2cl-lib:logical noconv) (type (f2cl-lib:integer4) i ica iexc ira j k l m)) (setf info 0) (cond ((and (not (lsame job "N")) (not (lsame job "P")) (not (lsame job "S")) (not (lsame job "B"))) (setf info -1)) ((< n 0) (setf info -2)) ((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 n))) (setf info -4))) (cond ((/= info 0) (xerbla "DGEBAL" (f2cl-lib:int-sub info)) (go end_label))) (setf k 1) (setf l n) (if (= n 0) (go label210)) (cond ((lsame job "N") (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) one) label10)) (go label210))) (if (lsame job "S") (go label120)) (go label50) label20 (setf (f2cl-lib:fref scale-%data% (m) ((1 *)) scale-%offset%) (coerce (the f2cl-lib:integer4 j) 'double-float)) (if (= j m) (go label30)) (dswap l (f2cl-lib:array-slice a double-float (1 j) ((1 lda) (1 *))) 1 (f2cl-lib:array-slice a double-float (1 m) ((1 lda) (1 *))) 1) (dswap (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1) (f2cl-lib:array-slice a double-float (j k) ((1 lda) (1 *))) lda (f2cl-lib:array-slice a double-float (m k) ((1 lda) (1 *))) lda) label30 (f2cl-lib:computed-goto (label40 label80) iexc) label40 (if (= l 1) (go label210)) (setf l (f2cl-lib:int-sub l 1)) label50 (f2cl-lib:fdo (j l (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (if (= i j) (go label60)) (if (/= (f2cl-lib:fref a-%data% (j i) ((1 lda) (1 *)) a-%offset%) zero) (go label70)) label60)) (setf m l) (setf iexc 1) (go label20) label70)) (go label90) label80 (setf k (f2cl-lib:int-add k 1)) label90 (f2cl-lib:fdo (j k (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (f2cl-lib:fdo (i k (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (if (= i j) (go label100)) (if (/= (f2cl-lib:fref a-%data% (i j) ((1 lda) (1 *)) a-%offset%) zero) (go label110)) label100)) (setf m k) (setf iexc 2) (go label20) label110)) label120 (f2cl-lib:fdo (i k (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (setf (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) one) label130)) (if (lsame job "P") (go label210)) (setf sfmin1 (/ (dlamch "S") (dlamch "P"))) (setf sfmax1 (/ one sfmin1)) (setf sfmin2 (* sfmin1 sclfac)) (setf sfmax2 (/ one sfmin2)) label140 (setf noconv f2cl-lib:%false%) (f2cl-lib:fdo (i k (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (setf c zero) (setf r zero) (f2cl-lib:fdo (j k (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (if (= j i) (go label150)) (setf c (+ c (abs (f2cl-lib:fref a-%data% (j i) ((1 lda) (1 *)) a-%offset%)))) (setf r (+ r (abs (f2cl-lib:fref a-%data% (i j) ((1 lda) (1 *)) a-%offset%)))) label150)) (setf ica (idamax l (f2cl-lib:array-slice a double-float (1 i) ((1 lda) (1 *))) 1)) (setf ca (abs (f2cl-lib:fref a-%data% (ica i) ((1 lda) (1 *)) a-%offset%))) (setf ira (idamax (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1) (f2cl-lib:array-slice a double-float (i k) ((1 lda) (1 *))) lda)) (setf ra (abs (f2cl-lib:fref a-%data% (i (f2cl-lib:int-sub (f2cl-lib:int-add ira k) 1)) ((1 lda) (1 *)) a-%offset%))) (if (or (= c zero) (= r zero)) (go label200)) (setf g (/ r sclfac)) (setf f one) (setf s (+ c r)) label160 (if (or (>= c g) (>= (max f c ca) sfmax2) (<= (min r g ra) sfmin2)) (go label170)) (setf f (* f sclfac)) (setf c (* c sclfac)) (setf ca (* ca sclfac)) (setf r (/ r sclfac)) (setf g (/ g sclfac)) (setf ra (/ ra sclfac)) (go label160) label170 (setf g (/ c sclfac)) label180 (if (or (< g r) (>= (max r ra) sfmax2) (<= (min f c g ca) sfmin2)) (go label190)) (setf f (/ f sclfac)) (setf c (/ c sclfac)) (setf g (/ g sclfac)) (setf ca (/ ca sclfac)) (setf r (* r sclfac)) (setf ra (* ra sclfac)) (go label180) label190 (if (>= (+ c r) (* factor s)) (go label200)) (cond ((and (< f one) (< (f2cl-lib:fref scale (i) ((1 *))) one)) (if (<= (* f (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%)) sfmin1) (go label200)))) (cond ((and (> f one) (> (f2cl-lib:fref scale (i) ((1 *))) one)) (if (>= (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) (/ sfmax1 f)) (go label200)))) (setf g (/ one f)) (setf (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) (* (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) f)) (setf noconv f2cl-lib:%true%) (dscal (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1) g (f2cl-lib:array-slice a double-float (i k) ((1 lda) (1 *))) lda) (dscal l f (f2cl-lib:array-slice a double-float (1 i) ((1 lda) (1 *))) 1) label200)) (if noconv (go label140)) label210 (setf ilo k) (setf ihi l) (go end_label) end_label (return (values nil nil nil nil ilo ihi nil info)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dgebal fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((simple-array character (1)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil fortran-to-lisp::ilo fortran-to-lisp::ihi nil fortran-to-lisp::info) :calls '(fortran-to-lisp::dscal fortran-to-lisp::idamax fortran-to-lisp::dlamch fortran-to-lisp::dswap fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
null
https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/lapack/dgebal.lisp
lisp
Compiled by f2cl version: Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format double-float))
( " $ I d : f2cl1.l , v 1.209 2008/09/11 14:59:55 rtoy Exp $ " " $ I d : f2cl2.l , v 1.37 2008/02/22 22:19:33 " " $ I d : f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Rel $ " " $ I d : f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Rel $ " " $ I d : f2cl5.l , v 1.197 2008/09/11 15:03:25 rtoy Exp $ " " $ I d : f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " $ I d : macros.l , v 1.106 2008/09/15 15:27:36 " ) Using Lisp International Allegro CL Enterprise Edition 8.1 [ 64 - bit Linux ( x86 - 64 ) ] ( Oct 7 , 2008 17:13 ) (in-package "LAPACK") (let* ((zero 0.0) (one 1.0) (sclfac 8.0) (factor 0.95)) (declare (type (double-float 0.0 0.0) zero) (type (double-float 1.0 1.0) one) (type (double-float 8.0 8.0) sclfac) (type (double-float 0.95 0.95) factor) (ignorable zero one sclfac factor)) (defun dgebal (job n a lda ilo ihi scale info) (declare (type (array double-float (*)) scale a) (type (simple-array character (*)) job) (type (f2cl-lib:integer4) info ihi ilo lda n)) (f2cl-lib:with-multi-array-data ((job character job-%data% job-%offset%) (a double-float a-%data% a-%offset%) (scale double-float scale-%data% scale-%offset%)) (prog ((c 0.0) (ca 0.0) (f 0.0) (g 0.0) (r 0.0) (ra 0.0) (s 0.0) (sfmax1 0.0) (sfmax2 0.0) (sfmin1 0.0) (sfmin2 0.0) (i 0) (ica 0) (iexc 0) (ira 0) (j 0) (k 0) (l 0) (m 0) (noconv nil)) (declare (type (double-float) c ca f g r ra s sfmax1 sfmax2 sfmin1 sfmin2) (type f2cl-lib:logical noconv) (type (f2cl-lib:integer4) i ica iexc ira j k l m)) (setf info 0) (cond ((and (not (lsame job "N")) (not (lsame job "P")) (not (lsame job "S")) (not (lsame job "B"))) (setf info -1)) ((< n 0) (setf info -2)) ((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 n))) (setf info -4))) (cond ((/= info 0) (xerbla "DGEBAL" (f2cl-lib:int-sub info)) (go end_label))) (setf k 1) (setf l n) (if (= n 0) (go label210)) (cond ((lsame job "N") (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) one) label10)) (go label210))) (if (lsame job "S") (go label120)) (go label50) label20 (setf (f2cl-lib:fref scale-%data% (m) ((1 *)) scale-%offset%) (coerce (the f2cl-lib:integer4 j) 'double-float)) (if (= j m) (go label30)) (dswap l (f2cl-lib:array-slice a double-float (1 j) ((1 lda) (1 *))) 1 (f2cl-lib:array-slice a double-float (1 m) ((1 lda) (1 *))) 1) (dswap (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1) (f2cl-lib:array-slice a double-float (j k) ((1 lda) (1 *))) lda (f2cl-lib:array-slice a double-float (m k) ((1 lda) (1 *))) lda) label30 (f2cl-lib:computed-goto (label40 label80) iexc) label40 (if (= l 1) (go label210)) (setf l (f2cl-lib:int-sub l 1)) label50 (f2cl-lib:fdo (j l (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (if (= i j) (go label60)) (if (/= (f2cl-lib:fref a-%data% (j i) ((1 lda) (1 *)) a-%offset%) zero) (go label70)) label60)) (setf m l) (setf iexc 1) (go label20) label70)) (go label90) label80 (setf k (f2cl-lib:int-add k 1)) label90 (f2cl-lib:fdo (j k (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (f2cl-lib:fdo (i k (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (if (= i j) (go label100)) (if (/= (f2cl-lib:fref a-%data% (i j) ((1 lda) (1 *)) a-%offset%) zero) (go label110)) label100)) (setf m k) (setf iexc 2) (go label20) label110)) label120 (f2cl-lib:fdo (i k (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (setf (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) one) label130)) (if (lsame job "P") (go label210)) (setf sfmin1 (/ (dlamch "S") (dlamch "P"))) (setf sfmax1 (/ one sfmin1)) (setf sfmin2 (* sfmin1 sclfac)) (setf sfmax2 (/ one sfmin2)) label140 (setf noconv f2cl-lib:%false%) (f2cl-lib:fdo (i k (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody (setf c zero) (setf r zero) (f2cl-lib:fdo (j k (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (if (= j i) (go label150)) (setf c (+ c (abs (f2cl-lib:fref a-%data% (j i) ((1 lda) (1 *)) a-%offset%)))) (setf r (+ r (abs (f2cl-lib:fref a-%data% (i j) ((1 lda) (1 *)) a-%offset%)))) label150)) (setf ica (idamax l (f2cl-lib:array-slice a double-float (1 i) ((1 lda) (1 *))) 1)) (setf ca (abs (f2cl-lib:fref a-%data% (ica i) ((1 lda) (1 *)) a-%offset%))) (setf ira (idamax (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1) (f2cl-lib:array-slice a double-float (i k) ((1 lda) (1 *))) lda)) (setf ra (abs (f2cl-lib:fref a-%data% (i (f2cl-lib:int-sub (f2cl-lib:int-add ira k) 1)) ((1 lda) (1 *)) a-%offset%))) (if (or (= c zero) (= r zero)) (go label200)) (setf g (/ r sclfac)) (setf f one) (setf s (+ c r)) label160 (if (or (>= c g) (>= (max f c ca) sfmax2) (<= (min r g ra) sfmin2)) (go label170)) (setf f (* f sclfac)) (setf c (* c sclfac)) (setf ca (* ca sclfac)) (setf r (/ r sclfac)) (setf g (/ g sclfac)) (setf ra (/ ra sclfac)) (go label160) label170 (setf g (/ c sclfac)) label180 (if (or (< g r) (>= (max r ra) sfmax2) (<= (min f c g ca) sfmin2)) (go label190)) (setf f (/ f sclfac)) (setf c (/ c sclfac)) (setf g (/ g sclfac)) (setf ca (/ ca sclfac)) (setf r (* r sclfac)) (setf ra (* ra sclfac)) (go label180) label190 (if (>= (+ c r) (* factor s)) (go label200)) (cond ((and (< f one) (< (f2cl-lib:fref scale (i) ((1 *))) one)) (if (<= (* f (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%)) sfmin1) (go label200)))) (cond ((and (> f one) (> (f2cl-lib:fref scale (i) ((1 *))) one)) (if (>= (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) (/ sfmax1 f)) (go label200)))) (setf g (/ one f)) (setf (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) (* (f2cl-lib:fref scale-%data% (i) ((1 *)) scale-%offset%) f)) (setf noconv f2cl-lib:%true%) (dscal (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1) g (f2cl-lib:array-slice a double-float (i k) ((1 lda) (1 *))) lda) (dscal l f (f2cl-lib:array-slice a double-float (1 i) ((1 lda) (1 *))) 1) label200)) (if noconv (go label140)) label210 (setf ilo k) (setf ihi l) (go end_label) end_label (return (values nil nil nil nil ilo ihi nil info)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dgebal fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((simple-array character (1)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil fortran-to-lisp::ilo fortran-to-lisp::ihi nil fortran-to-lisp::info) :calls '(fortran-to-lisp::dscal fortran-to-lisp::idamax fortran-to-lisp::dlamch fortran-to-lisp::dswap fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
5e6b5b1b21c8ee062612118a5c79008bf1597e701cb9fbbdd8775efdb34c37ce
haskell-haskey/haskey
Integration.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE RankNTypes #-} module Main (main) where import Test.Framework (Test, defaultMain) import qualified Integration.CreateAndOpen import qualified Integration.WriteOpenRead.Concurrent tests :: [Test] tests = [ Integration.CreateAndOpen.tests , Integration.WriteOpenRead.Concurrent.tests ] main :: IO () main = defaultMain tests
null
https://raw.githubusercontent.com/haskell-haskey/haskey/299f070fcb0d287404d78399f903cecf7ad48cdd/tests/Integration.hs
haskell
# LANGUAGE RankNTypes #
# LANGUAGE FlexibleInstances # module Main (main) where import Test.Framework (Test, defaultMain) import qualified Integration.CreateAndOpen import qualified Integration.WriteOpenRead.Concurrent tests :: [Test] tests = [ Integration.CreateAndOpen.tests , Integration.WriteOpenRead.Concurrent.tests ] main :: IO () main = defaultMain tests
b8f9f9131cec14dcc4faa1a3ef4f3b23d0a89115a14de3a02c8f0cdd1075bd9d
Decentralized-Pictures/T4L3NT
tezos_client.ml
open Internal_pervasives type t = {id: string; port: int; exec: Tezos_executable.t} type client = t let no_node_client ~exec = {id= "C-null"; port= 0; exec} let of_node ~exec n = let id = sprintf "C-%s" n.Tezos_node.id in let port = n.Tezos_node.rpc_port in {id; port; exec} let base_dir t ~state = Paths.root state // sprintf "Client-base-%s" t.id open Tezos_executable.Make_cli let client_call ?(wait = "none") state t args = "--wait" :: wait :: optf "port" "%d" t.port @ opt "base-dir" (base_dir ~state t) @ args let client_command ?wait state t args = Tezos_executable.call state t.exec ~path:(base_dir t ~state // "exec-client") (client_call ?wait state t args) module Command_error = struct let failf ?result ?client ?args fmt = let attach = Option.value_map ~default:[] args ~f:(fun l -> [("arguments", `String_list l)] ) @ Option.value_map ~default:[] client ~f:(fun c -> [("client-id", `String_value c.id)] ) @ Option.value_map ~default:[] result ~f:(fun res -> [("stdout", `Verbatim res#out); ("stderr", `Verbatim res#err)] ) in Process_result.Error.wrong_behavior ~attach fmt end open Command_error open Console let run_client_cmd ?id_prefix ?wait state client args = Running_processes.run_cmdf ?id_prefix state "sh -c %s" ( client_command ?wait state client args |> Genspio.Compile.to_one_liner |> Caml.Filename.quote ) let client_cmd ?id_prefix ?(verbose = true) ?wait state ~client args = Running_processes.run_cmdf ?id_prefix state "sh -c %s" ( client_command ?wait state client args |> Genspio.Compile.to_one_liner |> Caml.Filename.quote ) >>= fun res -> let unix_success = Poly.equal res#status (Lwt_unix.WEXITED 0) in ( if verbose then Console.display_errors_of_command state res >>= fun _ -> return () else return () ) >>= fun () -> return (unix_success, res) let successful_client_cmd ?id_prefix ?(verbose = true) ?wait state ~client args = client_cmd ?id_prefix ~verbose state ?wait ~client args >>= fun (success, result) -> match success with | true -> return result | false -> failf ~result ~client ~args "Client-command failure: %s" (String.concat ~sep:" " args) let wait_for_node_bootstrap state client = let try_once () = run_client_cmd ~id_prefix:(client.id ^ "-bootstrapped") state client ["bootstrapped"] >>= fun res -> return Poly.(res#status = Unix.WEXITED 0) in let attempts = 20 in let rec loop nth = if nth >= attempts then failf "Bootstrapping failed %d times." nth else try_once () >>= function | true -> return () | false -> System.sleep Float.(0.3 + (of_int nth * 0.6)) >>= fun () -> loop (nth + 1) in loop 1 let import_secret_key state client ~name ~key = successful_client_cmd state ~client ["import"; "secret"; "key"; name; key; "--force"] >>= fun _ -> return () let register_as_delegate state client ~key_name = successful_client_cmd state ~client ["register"; "key"; key_name; "as"; "delegate"] >>= fun _ -> return () let rpc state ~client meth ~path = let args = match meth with | `Get -> ["rpc"; "get"; path] | `Post s -> ["rpc"; "post"; path; "with"; s] in successful_client_cmd state ~client args >>= fun res -> let output = String.concat ~sep:"\n" res#out in try let json = Jqo.of_string output in return json with e -> ( try Ezjsonm.from_string (sprintf "[ %s ]" output) |> function `A [one] -> return one | _ -> raise e with e -> say state EF.( list [ desc (shout "Output:") (markdown_verbatim output) ; desc (shout "Error:") (markdown_verbatim (String.concat ~sep:"\n" res#err)) ]) >>= fun () -> failf ~args "RPC failure cannot parse json: %s" Exn.(to_string e) ) let activate_protocol state client protocol = let timestamp = match protocol.Tezos_protocol.timestamp_delay with | None -> [] | Some delay -> ( let now = Ptime_clock.now () in match Ptime.add_span now (Ptime.Span.of_int_s delay) with | None -> invalid_arg "activate_protocol_script: protocol.timestamp_delay" | Some x -> ["--timestamp"; Ptime.to_rfc3339 x] ) in Console.say state EF.(wf "Activating protocol %s" protocol.Tezos_protocol.hash) >>= fun () -> import_secret_key state client ~name:(Tezos_protocol.dictator_name protocol) ~key:(Tezos_protocol.dictator_secret_key protocol) >>= fun () -> successful_client_cmd state ~client ( opt "block" "genesis" @ [ "activate"; "protocol"; protocol.Tezos_protocol.hash; "with"; "fitness" ; sprintf "%d" protocol.Tezos_protocol.expected_pow; "and"; "key" ; Tezos_protocol.dictator_name protocol; "and"; "parameters" ; Tezos_protocol.protocol_parameters_path state protocol ] @ timestamp ) >>= fun _ -> rpc state ~client `Get ~path:"/chains/main/blocks/head/metadata" >>= fun metadata_json -> ( match Jqo.field metadata_json ~k:"next_protocol" with | `String hash when String.equal hash protocol.Tezos_protocol.hash -> return () | exception e -> System_error.fail_fatalf "Error getting protocol metadata: %a" Exn.pp e | other_value -> System_error.fail_fatalf "Error activating protocol: %s Vs %s" (Ezjsonm.value_to_string other_value) protocol.Tezos_protocol.hash ) >>= fun () -> return () let find_applied_in_mempool state ~client ~f = successful_client_cmd state ~client ["rpc"; "get"; "/chains/main/mempool/pending_operations"] >>= fun res -> try let json = Jqo.of_string (String.concat ~sep:"\n" res#out) in let found = Jqo.field ~k:"applied" json |> Jqo.list_find ~f in say state EF.( desc (af "piece of mempool found (client %s):" client.id) (markdown_verbatim (Ezjsonm.to_string json))) >>= fun () -> return (Some found) with e -> say state EF.(desc (shout "not found in mempool") (af "%s" (Exn.to_string e))) >>= fun () -> return None let mempool_has_operation state ~client ~kind = find_applied_in_mempool state ~client ~f:(fun o -> Jqo.field o ~k:"contents" |> Jqo.list_exists ~f:Poly.(fun op -> Jqo.field op ~k:"kind" = `String kind) ) >>= fun found_or_not -> return Poly.(found_or_not <> None) let block_has_operation state ~client ~level ~kind = successful_client_cmd state ~client ["rpc"; "get"; sprintf "/chains/main/blocks/%d/operations" level] >>= fun res -> try let json = Jqo.of_string (String.concat ~sep:"\n" res#out) in let found = Jqo.list_exists json ~f:(fun olist -> Jqo.list_exists olist ~f:(fun o -> Jqo.field o ~k:"contents" |> Jqo.list_exists ~f:Poly.(fun op -> Jqo.field op ~k:"kind" = `String kind) ) ) in say state EF.( desc (af "looking for %S in block %d: %sfound" kind level (if found then "" else "not ") ) (af "%s" (Ezjsonm.to_string json))) >>= fun () -> return found with e -> say state EF.( desc (ksprintf shout "Operation %S not found in block" kind) (af "%s" (Exn.to_string e))) >>= fun () -> return false let get_block_header state ~client block = let path = sprintf "/chains/main/blocks/%s/header" (match block with `Head -> "head" | `Level i -> Int.to_string i) in rpc state ~client `Get ~path let list_known_addresses state ~client = successful_client_cmd state ~client ["list"; "known"; "addresses"] >>= fun res -> let re = Re.( compile (seq [ group (rep1 (alt [alnum; char '_'])); str ": "; group (rep1 alnum) ; alt [space; eol; eos] ] )) in return (List.filter_map res#out ~f: Re.( fun line -> match exec_opt re line with | None -> None | Some matches -> Some (Group.get matches 1, Group.get matches 2)) ) module Ledger = struct type hwm = {main: int; test: int; chain: Tezos_crypto.Chain_id.t option} let set_hwm state ~client ~uri ~level = successful_client_cmd state ~client [ "set"; "ledger"; "high"; "watermark"; "for"; uri; "to" ; Int.to_string level ] >>= fun _ -> return () let get_hwm state ~client ~uri = successful_client_cmd state ~client [ "get"; "ledger"; "high"; "watermark"; "for"; uri ; "--no-legacy-instructions" ] (* TODO: Use --for-script when available *) >>= fun res -> e.g. The high water mark values for married - bison - ill - burmese / P-256 are 0 for the main - chain ( NetXH12Aer3be93 ) and 0 for the test - chain . 0 for the main-chain (NetXH12Aer3be93) and 0 for the test-chain. *) let re = Re.( let num = rep1 digit in compile (seq [ group num; str " for the main-chain ("; group (rep1 alnum) ; str ") and "; group num; str " for the test-chain." ] )) in let matches = Re.exec re (String.concat ~sep:" " res#out) in try return { main= Int.of_string (Re.Group.get matches 1) ; chain= (let v = Re.Group.get matches 2 in if String.equal v "'Unspecified'" then None else Some (Tezos_crypto.Chain_id.of_b58check_exn v) ) ; test= Int.of_string (Re.Group.get matches 3) } with e -> failf "Couldn't understand result of 'get high watermark for %S': error %S: \ from %S" uri (Exn.to_string e) (String.concat ~sep:"\n" res#out) let show_ledger state ~client ~uri = successful_client_cmd state ~client ["show"; "ledger"; uri] (* TODO: Use --for-script when available *) >>= fun res -> list_known_addresses state ~client >>= fun known_addresses -> let pk = Re.(rep1 alnum) in let addr_re = Re.(compile (seq [str "* Public Key Hash: "; group pk])) in let pubkey_re = Re.(compile (seq [str "* Public Key: "; group pk])) in let out = String.concat ~sep:" " res#out in try let pubkey = Re.(Group.get (exec pubkey_re out) 1) in let pubkey_hash = Re.(Group.get (exec addr_re out) 1) in let name = match List.find known_addresses ~f:(fun (_, pkh) -> String.equal pkh pubkey_hash ) with | None -> "" | Some (alias, _) -> alias in return (Tezos_protocol.Account.key_pair name ~pubkey ~pubkey_hash ~private_key:uri ) with e -> failf "Couldn't understand result of 'show ledger %S': error %S: from %S" uri (Exn.to_string e) (String.concat ~sep:"\n" res#out) let deauthorize_baking state ~client ~uri = successful_client_cmd state ~client ["deauthorize"; "ledger"; "baking"; "for"; uri] >>= fun _ -> return () let get_authorized_key state ~client ~uri = successful_client_cmd state ~client ["get"; "ledger"; "authorized"; "path"; "for"; uri] >>= fun res -> let re_uri = Re.(compile (seq [str "Authorized baking URI: "; group (rep1 any); eol])) in let re_none = Re.(compile (str "No baking key authorized")) in let out = String.concat ~sep:" " res#out in return Re.( match exec_opt re_none out with | Some _ -> None | None -> Some (Group.get (exec re_uri out) 1)) end module Keyed = struct type t = {client: client; key_name: string; secret_key: string} let make client ~key_name ~secret_key = {client; key_name; secret_key} let initialize state {client; key_name; secret_key} = successful_client_cmd state ~client ["import"; "secret"; "key"; key_name; secret_key; "--force"] let bake ?chain state baker msg = let chain_arg = Option.value_map chain ~default:[] ~f:(fun c -> ["--chain"; c]) in successful_client_cmd state ~client:baker.client ( chain_arg @ ["bake"; "for"; baker.key_name; "--force"; "--minimal-timestamp"] ) >>= fun res -> Log_recorder.Operations.bake state ~client:baker.client.id ~output:res#out msg ; say state EF.( desc (af "Successful bake (%s: %s):" baker.client.id msg) (ocaml_string_list res#out)) let endorse state baker msg = successful_client_cmd state ~client:baker.client ["endorse"; "for"; baker.key_name] >>= fun res -> Log_recorder.Operations.endorse state ~client:baker.client.id ~output:res#out msg ; say state EF.( desc (af "Successful endorse (%s: %s):" baker.client.id msg) (ocaml_string_list res#out)) let generate_nonce state {client; key_name; _} data = successful_client_cmd state ~client ["generate"; "nonce"; "hash"; "for"; key_name; "from"; data] >>= fun res -> return (List.hd_exn res#out) let forge_and_inject state {client; key_name; _} ~json = rpc state ~client ~path:"/chains/main/blocks/head/helpers/forge/operations" (`Post (Ezjsonm.value_to_string json)) >>= fun res -> let operation_bytes = match res with `String s -> s | _ -> assert false in let bytes_to_sign = "0x03" ^ operation_bytes in successful_client_cmd state ~client ["sign"; "bytes"; bytes_to_sign; "for"; key_name] >>= fun sign_res -> let to_decode = List.hd_exn sign_res#out |> String.chop_prefix_exn ~prefix:"Signature:" |> String.strip in say state EF.(desc (shout "TO DECODE:") (af "%S" to_decode)) >>= fun () -> let decoded = Option.value_exn ~message:"base58 dec" (Tezos_crypto.Base58.safe_decode to_decode) |> Hex.of_string ?ignore:None |> Hex.show in say state EF.(desc (shout "DECODED:") (af "%S" decoded)) >>= fun () -> let actual_signature = String.chop_prefix_exn ~prefix:"09f5cd8612" decoded in say state EF.( desc_list (af "Injecting Operation") [ ef_json "Injecting" (json :> Ezjsonm.value) ; desc (haf "op:") (af "%d: %S" (String.length operation_bytes) operation_bytes) ; desc (haf "sign:") (af "%d: %S" (String.length actual_signature) actual_signature) ]) >>= fun () -> rpc state ~client ~path:"/injection/operation?chain=main" (`Post (sprintf "\"%s%s\"" operation_bytes actual_signature)) end
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/vendors/flextesa-lib/tezos_client.ml
ocaml
TODO: Use --for-script when available TODO: Use --for-script when available
open Internal_pervasives type t = {id: string; port: int; exec: Tezos_executable.t} type client = t let no_node_client ~exec = {id= "C-null"; port= 0; exec} let of_node ~exec n = let id = sprintf "C-%s" n.Tezos_node.id in let port = n.Tezos_node.rpc_port in {id; port; exec} let base_dir t ~state = Paths.root state // sprintf "Client-base-%s" t.id open Tezos_executable.Make_cli let client_call ?(wait = "none") state t args = "--wait" :: wait :: optf "port" "%d" t.port @ opt "base-dir" (base_dir ~state t) @ args let client_command ?wait state t args = Tezos_executable.call state t.exec ~path:(base_dir t ~state // "exec-client") (client_call ?wait state t args) module Command_error = struct let failf ?result ?client ?args fmt = let attach = Option.value_map ~default:[] args ~f:(fun l -> [("arguments", `String_list l)] ) @ Option.value_map ~default:[] client ~f:(fun c -> [("client-id", `String_value c.id)] ) @ Option.value_map ~default:[] result ~f:(fun res -> [("stdout", `Verbatim res#out); ("stderr", `Verbatim res#err)] ) in Process_result.Error.wrong_behavior ~attach fmt end open Command_error open Console let run_client_cmd ?id_prefix ?wait state client args = Running_processes.run_cmdf ?id_prefix state "sh -c %s" ( client_command ?wait state client args |> Genspio.Compile.to_one_liner |> Caml.Filename.quote ) let client_cmd ?id_prefix ?(verbose = true) ?wait state ~client args = Running_processes.run_cmdf ?id_prefix state "sh -c %s" ( client_command ?wait state client args |> Genspio.Compile.to_one_liner |> Caml.Filename.quote ) >>= fun res -> let unix_success = Poly.equal res#status (Lwt_unix.WEXITED 0) in ( if verbose then Console.display_errors_of_command state res >>= fun _ -> return () else return () ) >>= fun () -> return (unix_success, res) let successful_client_cmd ?id_prefix ?(verbose = true) ?wait state ~client args = client_cmd ?id_prefix ~verbose state ?wait ~client args >>= fun (success, result) -> match success with | true -> return result | false -> failf ~result ~client ~args "Client-command failure: %s" (String.concat ~sep:" " args) let wait_for_node_bootstrap state client = let try_once () = run_client_cmd ~id_prefix:(client.id ^ "-bootstrapped") state client ["bootstrapped"] >>= fun res -> return Poly.(res#status = Unix.WEXITED 0) in let attempts = 20 in let rec loop nth = if nth >= attempts then failf "Bootstrapping failed %d times." nth else try_once () >>= function | true -> return () | false -> System.sleep Float.(0.3 + (of_int nth * 0.6)) >>= fun () -> loop (nth + 1) in loop 1 let import_secret_key state client ~name ~key = successful_client_cmd state ~client ["import"; "secret"; "key"; name; key; "--force"] >>= fun _ -> return () let register_as_delegate state client ~key_name = successful_client_cmd state ~client ["register"; "key"; key_name; "as"; "delegate"] >>= fun _ -> return () let rpc state ~client meth ~path = let args = match meth with | `Get -> ["rpc"; "get"; path] | `Post s -> ["rpc"; "post"; path; "with"; s] in successful_client_cmd state ~client args >>= fun res -> let output = String.concat ~sep:"\n" res#out in try let json = Jqo.of_string output in return json with e -> ( try Ezjsonm.from_string (sprintf "[ %s ]" output) |> function `A [one] -> return one | _ -> raise e with e -> say state EF.( list [ desc (shout "Output:") (markdown_verbatim output) ; desc (shout "Error:") (markdown_verbatim (String.concat ~sep:"\n" res#err)) ]) >>= fun () -> failf ~args "RPC failure cannot parse json: %s" Exn.(to_string e) ) let activate_protocol state client protocol = let timestamp = match protocol.Tezos_protocol.timestamp_delay with | None -> [] | Some delay -> ( let now = Ptime_clock.now () in match Ptime.add_span now (Ptime.Span.of_int_s delay) with | None -> invalid_arg "activate_protocol_script: protocol.timestamp_delay" | Some x -> ["--timestamp"; Ptime.to_rfc3339 x] ) in Console.say state EF.(wf "Activating protocol %s" protocol.Tezos_protocol.hash) >>= fun () -> import_secret_key state client ~name:(Tezos_protocol.dictator_name protocol) ~key:(Tezos_protocol.dictator_secret_key protocol) >>= fun () -> successful_client_cmd state ~client ( opt "block" "genesis" @ [ "activate"; "protocol"; protocol.Tezos_protocol.hash; "with"; "fitness" ; sprintf "%d" protocol.Tezos_protocol.expected_pow; "and"; "key" ; Tezos_protocol.dictator_name protocol; "and"; "parameters" ; Tezos_protocol.protocol_parameters_path state protocol ] @ timestamp ) >>= fun _ -> rpc state ~client `Get ~path:"/chains/main/blocks/head/metadata" >>= fun metadata_json -> ( match Jqo.field metadata_json ~k:"next_protocol" with | `String hash when String.equal hash protocol.Tezos_protocol.hash -> return () | exception e -> System_error.fail_fatalf "Error getting protocol metadata: %a" Exn.pp e | other_value -> System_error.fail_fatalf "Error activating protocol: %s Vs %s" (Ezjsonm.value_to_string other_value) protocol.Tezos_protocol.hash ) >>= fun () -> return () let find_applied_in_mempool state ~client ~f = successful_client_cmd state ~client ["rpc"; "get"; "/chains/main/mempool/pending_operations"] >>= fun res -> try let json = Jqo.of_string (String.concat ~sep:"\n" res#out) in let found = Jqo.field ~k:"applied" json |> Jqo.list_find ~f in say state EF.( desc (af "piece of mempool found (client %s):" client.id) (markdown_verbatim (Ezjsonm.to_string json))) >>= fun () -> return (Some found) with e -> say state EF.(desc (shout "not found in mempool") (af "%s" (Exn.to_string e))) >>= fun () -> return None let mempool_has_operation state ~client ~kind = find_applied_in_mempool state ~client ~f:(fun o -> Jqo.field o ~k:"contents" |> Jqo.list_exists ~f:Poly.(fun op -> Jqo.field op ~k:"kind" = `String kind) ) >>= fun found_or_not -> return Poly.(found_or_not <> None) let block_has_operation state ~client ~level ~kind = successful_client_cmd state ~client ["rpc"; "get"; sprintf "/chains/main/blocks/%d/operations" level] >>= fun res -> try let json = Jqo.of_string (String.concat ~sep:"\n" res#out) in let found = Jqo.list_exists json ~f:(fun olist -> Jqo.list_exists olist ~f:(fun o -> Jqo.field o ~k:"contents" |> Jqo.list_exists ~f:Poly.(fun op -> Jqo.field op ~k:"kind" = `String kind) ) ) in say state EF.( desc (af "looking for %S in block %d: %sfound" kind level (if found then "" else "not ") ) (af "%s" (Ezjsonm.to_string json))) >>= fun () -> return found with e -> say state EF.( desc (ksprintf shout "Operation %S not found in block" kind) (af "%s" (Exn.to_string e))) >>= fun () -> return false let get_block_header state ~client block = let path = sprintf "/chains/main/blocks/%s/header" (match block with `Head -> "head" | `Level i -> Int.to_string i) in rpc state ~client `Get ~path let list_known_addresses state ~client = successful_client_cmd state ~client ["list"; "known"; "addresses"] >>= fun res -> let re = Re.( compile (seq [ group (rep1 (alt [alnum; char '_'])); str ": "; group (rep1 alnum) ; alt [space; eol; eos] ] )) in return (List.filter_map res#out ~f: Re.( fun line -> match exec_opt re line with | None -> None | Some matches -> Some (Group.get matches 1, Group.get matches 2)) ) module Ledger = struct type hwm = {main: int; test: int; chain: Tezos_crypto.Chain_id.t option} let set_hwm state ~client ~uri ~level = successful_client_cmd state ~client [ "set"; "ledger"; "high"; "watermark"; "for"; uri; "to" ; Int.to_string level ] >>= fun _ -> return () let get_hwm state ~client ~uri = successful_client_cmd state ~client [ "get"; "ledger"; "high"; "watermark"; "for"; uri ; "--no-legacy-instructions" ] >>= fun res -> e.g. The high water mark values for married - bison - ill - burmese / P-256 are 0 for the main - chain ( NetXH12Aer3be93 ) and 0 for the test - chain . 0 for the main-chain (NetXH12Aer3be93) and 0 for the test-chain. *) let re = Re.( let num = rep1 digit in compile (seq [ group num; str " for the main-chain ("; group (rep1 alnum) ; str ") and "; group num; str " for the test-chain." ] )) in let matches = Re.exec re (String.concat ~sep:" " res#out) in try return { main= Int.of_string (Re.Group.get matches 1) ; chain= (let v = Re.Group.get matches 2 in if String.equal v "'Unspecified'" then None else Some (Tezos_crypto.Chain_id.of_b58check_exn v) ) ; test= Int.of_string (Re.Group.get matches 3) } with e -> failf "Couldn't understand result of 'get high watermark for %S': error %S: \ from %S" uri (Exn.to_string e) (String.concat ~sep:"\n" res#out) let show_ledger state ~client ~uri = successful_client_cmd state ~client ["show"; "ledger"; uri] >>= fun res -> list_known_addresses state ~client >>= fun known_addresses -> let pk = Re.(rep1 alnum) in let addr_re = Re.(compile (seq [str "* Public Key Hash: "; group pk])) in let pubkey_re = Re.(compile (seq [str "* Public Key: "; group pk])) in let out = String.concat ~sep:" " res#out in try let pubkey = Re.(Group.get (exec pubkey_re out) 1) in let pubkey_hash = Re.(Group.get (exec addr_re out) 1) in let name = match List.find known_addresses ~f:(fun (_, pkh) -> String.equal pkh pubkey_hash ) with | None -> "" | Some (alias, _) -> alias in return (Tezos_protocol.Account.key_pair name ~pubkey ~pubkey_hash ~private_key:uri ) with e -> failf "Couldn't understand result of 'show ledger %S': error %S: from %S" uri (Exn.to_string e) (String.concat ~sep:"\n" res#out) let deauthorize_baking state ~client ~uri = successful_client_cmd state ~client ["deauthorize"; "ledger"; "baking"; "for"; uri] >>= fun _ -> return () let get_authorized_key state ~client ~uri = successful_client_cmd state ~client ["get"; "ledger"; "authorized"; "path"; "for"; uri] >>= fun res -> let re_uri = Re.(compile (seq [str "Authorized baking URI: "; group (rep1 any); eol])) in let re_none = Re.(compile (str "No baking key authorized")) in let out = String.concat ~sep:" " res#out in return Re.( match exec_opt re_none out with | Some _ -> None | None -> Some (Group.get (exec re_uri out) 1)) end module Keyed = struct type t = {client: client; key_name: string; secret_key: string} let make client ~key_name ~secret_key = {client; key_name; secret_key} let initialize state {client; key_name; secret_key} = successful_client_cmd state ~client ["import"; "secret"; "key"; key_name; secret_key; "--force"] let bake ?chain state baker msg = let chain_arg = Option.value_map chain ~default:[] ~f:(fun c -> ["--chain"; c]) in successful_client_cmd state ~client:baker.client ( chain_arg @ ["bake"; "for"; baker.key_name; "--force"; "--minimal-timestamp"] ) >>= fun res -> Log_recorder.Operations.bake state ~client:baker.client.id ~output:res#out msg ; say state EF.( desc (af "Successful bake (%s: %s):" baker.client.id msg) (ocaml_string_list res#out)) let endorse state baker msg = successful_client_cmd state ~client:baker.client ["endorse"; "for"; baker.key_name] >>= fun res -> Log_recorder.Operations.endorse state ~client:baker.client.id ~output:res#out msg ; say state EF.( desc (af "Successful endorse (%s: %s):" baker.client.id msg) (ocaml_string_list res#out)) let generate_nonce state {client; key_name; _} data = successful_client_cmd state ~client ["generate"; "nonce"; "hash"; "for"; key_name; "from"; data] >>= fun res -> return (List.hd_exn res#out) let forge_and_inject state {client; key_name; _} ~json = rpc state ~client ~path:"/chains/main/blocks/head/helpers/forge/operations" (`Post (Ezjsonm.value_to_string json)) >>= fun res -> let operation_bytes = match res with `String s -> s | _ -> assert false in let bytes_to_sign = "0x03" ^ operation_bytes in successful_client_cmd state ~client ["sign"; "bytes"; bytes_to_sign; "for"; key_name] >>= fun sign_res -> let to_decode = List.hd_exn sign_res#out |> String.chop_prefix_exn ~prefix:"Signature:" |> String.strip in say state EF.(desc (shout "TO DECODE:") (af "%S" to_decode)) >>= fun () -> let decoded = Option.value_exn ~message:"base58 dec" (Tezos_crypto.Base58.safe_decode to_decode) |> Hex.of_string ?ignore:None |> Hex.show in say state EF.(desc (shout "DECODED:") (af "%S" decoded)) >>= fun () -> let actual_signature = String.chop_prefix_exn ~prefix:"09f5cd8612" decoded in say state EF.( desc_list (af "Injecting Operation") [ ef_json "Injecting" (json :> Ezjsonm.value) ; desc (haf "op:") (af "%d: %S" (String.length operation_bytes) operation_bytes) ; desc (haf "sign:") (af "%d: %S" (String.length actual_signature) actual_signature) ]) >>= fun () -> rpc state ~client ~path:"/injection/operation?chain=main" (`Post (sprintf "\"%s%s\"" operation_bytes actual_signature)) end
dfa4585d79a7a3341a1b6cc1b64ea1d227b24f4171a1a655131986703bb58128
mitchellwrosen/dohaskell
Foundation.hs
module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Yesod.Auth.GoogleEmail2 import Yesod.Core.Types (Logger) import Yesod.Default.Util (addStaticContentExternal) import qualified Yesod.Core.Unsafe as Unsafe data App = App { appSettings :: AppSettings , appStatic :: Static , appConnPool :: ConnectionPool , appHttpManager :: Manager , appLogger :: Logger , appNavbar :: WidgetT App IO () } instance HasHttpManager App where getHttpManager = appHttpManager mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) instance Yesod App where approot = ApprootMaster $ appRoot . appSettings makeSessionBackend _ = Just <$> defaultClientSessionBackend timeoutMins keyFile where 1 week keyFile = "config/client_session_key.aes" defaultLayout innerWidget = do mmsg <- getMessage navbarWidget <- appNavbar <$> getYesod pc <- widgetToPageContent $ do $(combineStylesheets 'StaticR [ css_normalize_css , css_bootstrap_css ]) addScriptRemote "" $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") authRoute _ = Just $ AuthR LoginR Gave up trying to use this function because Foundation ca n't import -- anything that imports Import (which is everything). isAuthorized _ _ = return Authorized addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where genFileName lbs = "autogen-" ++ base64md5 lbs shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger requiresAuthorization :: Handler AuthResult requiresAuthorization = maybe AuthenticationRequired (const Authorized) <$> maybeAuthId -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = getYesod >>= runSqlPool action . appConnPool instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId loginDest _ = HomeR logoutDest _ = HomeR redirectToReferer _ = True authenticate creds = case credsPlugin creds of "googleemail2" -> runDB $ getBy (UniqueUserName $ credsIdent creds) >>= \case Just (Entity uid _) -> pure (Authenticated uid) Nothing -> liftIO getCurrentTime >>= insert . User (credsIdent creds) "anonymous" False >>= pure . Authenticated authPlugins app = [ authGoogleEmail "841602685019-ekt6mj8rcr10lvhgvbso3e21qviirq5b.apps.googleusercontent.com" (appOauthClientSecret (appSettings app)) ] authHttpManager = appHttpManager instance YesodAuthPersist App instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
null
https://raw.githubusercontent.com/mitchellwrosen/dohaskell/69aea7a42112557ac3e835b9dbdb9bf60a81f780/src/Foundation.hs
haskell
anything that imports Import (which is everything). How to run database actions.
module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Yesod.Auth.GoogleEmail2 import Yesod.Core.Types (Logger) import Yesod.Default.Util (addStaticContentExternal) import qualified Yesod.Core.Unsafe as Unsafe data App = App { appSettings :: AppSettings , appStatic :: Static , appConnPool :: ConnectionPool , appHttpManager :: Manager , appLogger :: Logger , appNavbar :: WidgetT App IO () } instance HasHttpManager App where getHttpManager = appHttpManager mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) instance Yesod App where approot = ApprootMaster $ appRoot . appSettings makeSessionBackend _ = Just <$> defaultClientSessionBackend timeoutMins keyFile where 1 week keyFile = "config/client_session_key.aes" defaultLayout innerWidget = do mmsg <- getMessage navbarWidget <- appNavbar <$> getYesod pc <- widgetToPageContent $ do $(combineStylesheets 'StaticR [ css_normalize_css , css_bootstrap_css ]) addScriptRemote "" $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") authRoute _ = Just $ AuthR LoginR Gave up trying to use this function because Foundation ca n't import isAuthorized _ _ = return Authorized addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where genFileName lbs = "autogen-" ++ base64md5 lbs shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger requiresAuthorization :: Handler AuthResult requiresAuthorization = maybe AuthenticationRequired (const Authorized) <$> maybeAuthId instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = getYesod >>= runSqlPool action . appConnPool instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId loginDest _ = HomeR logoutDest _ = HomeR redirectToReferer _ = True authenticate creds = case credsPlugin creds of "googleemail2" -> runDB $ getBy (UniqueUserName $ credsIdent creds) >>= \case Just (Entity uid _) -> pure (Authenticated uid) Nothing -> liftIO getCurrentTime >>= insert . User (credsIdent creds) "anonymous" False >>= pure . Authenticated authPlugins app = [ authGoogleEmail "841602685019-ekt6mj8rcr10lvhgvbso3e21qviirq5b.apps.googleusercontent.com" (appOauthClientSecret (appSettings app)) ] authHttpManager = appHttpManager instance YesodAuthPersist App instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
47a727ef0f1739194abfbffc36da3c9c0184fbbfda923ab7bfb5f6b97bc1ff18
facebook/infer
TextualBasicVerification.mli
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd type error val pp_error : Textual.SourceFile.t -> Format.formatter -> error -> unit val run : Textual.Module.t -> TextualDecls.t -> error list
null
https://raw.githubusercontent.com/facebook/infer/8a02f19fb30b9d4f8d74a8b31dc8d7206070f419/infer/src/textual/TextualBasicVerification.mli
ocaml
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd type error val pp_error : Textual.SourceFile.t -> Format.formatter -> error -> unit val run : Textual.Module.t -> TextualDecls.t -> error list
95868a230cb7c7677beb175da67babbe2c3477347fcc00e5afa34a24028ba8b6
brianhempel/maniposynth
weak.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Para , INRIA Rocquencourt (* *) Copyright 1997 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. *) (* *) (**************************************************************************) (** Weak array operations *) type 'a t external create : int -> 'a t = "caml_weak_create" (** number of additional values in a weak pointer *) let additional_values = 2 let length x = Obj.size(Obj.repr x) - additional_values external set : 'a t -> int -> 'a option -> unit = "caml_weak_set" external get : 'a t -> int -> 'a option = "caml_weak_get" external get_copy : 'a t -> int -> 'a option = "caml_weak_get_copy" external check : 'a t -> int -> bool = "caml_weak_check" external blit : 'a t -> int -> 'a t -> int -> int -> unit = "caml_weak_blit" blit : let fill ar ofs len x = if ofs < 0 || len < 0 || ofs + len > length ar then raise (Invalid_argument "Weak.fill") else begin for i = ofs to (ofs + len - 1) do set ar i x done end (** Weak hash tables *) module type S = sig type data type t val create : int -> t val clear : t -> unit val merge : t -> data -> data val add : t -> data -> unit val remove : t -> data -> unit val find : t -> data -> data val find_opt : t -> data -> data option val find_all : t -> data -> data list val mem : t -> data -> bool val iter : (data -> unit) -> t -> unit val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a val count : t -> int val stats : t -> int * int * int * int * int * int end module Make (H : Hashtbl.HashedType) : (S with type data = H.t) = struct type 'a weak_t = 'a t let weak_create = create let emptybucket = weak_create 0 type data = H.t type t = { mutable table : data weak_t array; mutable hashes : int array array; mutable limit : int; (* bucket size limit *) mutable oversize : int; (* number of oversize buckets *) mutable rover : int; (* for internal bookkeeping *) } let get_index t h = (h land max_int) mod (Array.length t.table) let limit = 7 let over_limit = 2 let create sz = let sz = if sz < 7 then 7 else sz in let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in { table = Array.make sz emptybucket; hashes = Array.make sz [| |]; limit = limit; oversize = 0; rover = 0; } let clear t = for i = 0 to Array.length t.table - 1 do t.table.(i) <- emptybucket; t.hashes.(i) <- [| |]; done; t.limit <- limit; t.oversize <- 0 let fold f t init = let rec fold_bucket i b accu = if i >= length b then accu else match get b i with | Some v -> fold_bucket (i+1) b (f v accu) | None -> fold_bucket (i+1) b accu in Array.fold_right (fold_bucket 0) t.table init let iter f t = let rec iter_bucket i b = if i >= length b then () else match get b i with | Some v -> f v; iter_bucket (i+1) b | None -> iter_bucket (i+1) b in Array.iter (iter_bucket 0) t.table let iter_weak f t = let rec iter_bucket i j b = if i >= length b then () else match check b i with | true -> f b t.hashes.(j) i; iter_bucket (i+1) j b | false -> iter_bucket (i+1) j b in Array.iteri (iter_bucket 0) t.table let rec count_bucket i b accu = if i >= length b then accu else count_bucket (i+1) b (accu + (if check b i then 1 else 0)) let count t = Array.fold_right (count_bucket 0) t.table 0 let next_sz n = min (3 * n / 2 + 3) Sys.max_array_length let prev_sz n = ((n - 3) * 2 + 2) / 3 let test_shrink_bucket t = let bucket = t.table.(t.rover) in let hbucket = t.hashes.(t.rover) in let len = length bucket in let prev_len = prev_sz len in let live = count_bucket 0 bucket 0 in if live <= prev_len then begin let rec loop i j = if j >= prev_len then begin if check bucket i then loop (i + 1) j else if check bucket j then begin blit bucket j bucket i 1; hbucket.(i) <- hbucket.(j); loop (i + 1) (j - 1); end else loop i (j - 1); end; in loop 0 (length bucket - 1); if prev_len = 0 then begin t.table.(t.rover) <- emptybucket; t.hashes.(t.rover) <- [| |]; end else begin Obj.truncate (Obj.repr bucket) (prev_len + additional_values); Obj.truncate (Obj.repr hbucket) prev_len; end; if len > t.limit && prev_len <= t.limit then t.oversize <- t.oversize - 1; end; t.rover <- (t.rover + 1) mod (Array.length t.table) let rec resize t = let oldlen = Array.length t.table in let newlen = next_sz oldlen in if newlen > oldlen then begin let newt = create newlen in let add_weak ob oh oi = let setter nb ni _ = blit ob oi nb ni 1 in let h = oh.(oi) in add_aux newt setter None h (get_index newt h); in iter_weak add_weak t; t.table <- newt.table; t.hashes <- newt.hashes; t.limit <- newt.limit; t.oversize <- newt.oversize; t.rover <- t.rover mod Array.length newt.table; end else begin t.limit <- max_int; (* maximum size already reached *) t.oversize <- 0; end and add_aux t setter d h index = let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then begin let newsz = min (3 * sz / 2 + 3) (Sys.max_array_length - additional_values) in if newsz <= sz then failwith "Weak.Make: hash bucket cannot grow more"; let newbucket = weak_create newsz in let newhashes = Array.make newsz 0 in blit bucket 0 newbucket 0 sz; Array.blit hashes 0 newhashes 0 sz; setter newbucket sz d; newhashes.(sz) <- h; t.table.(index) <- newbucket; t.hashes.(index) <- newhashes; if sz <= t.limit && newsz > t.limit then begin t.oversize <- t.oversize + 1; for _i = 0 to over_limit do test_shrink_bucket t done; end; if t.oversize > Array.length t.table / over_limit then resize t; end else if check bucket i then begin loop (i + 1) end else begin setter bucket i d; hashes.(i) <- h; end; in loop 0 let add t d = let h = H.hash d in add_aux t set (Some d) h (get_index t h) let find_or t d ifnotfound = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then ifnotfound h index else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> begin match get bucket i with | Some v -> v | None -> loop (i + 1) end | _ -> loop (i + 1) end else loop (i + 1) in loop 0 let merge t d = find_or t d (fun h index -> add_aux t set (Some d) h index; d) let find t d = find_or t d (fun _h _index -> raise Not_found) let find_opt t d = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then None else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> begin match get bucket i with | Some _ as v -> v | None -> loop (i + 1) end | _ -> loop (i + 1) end else loop (i + 1) in loop 0 let find_shadow t d iffound ifnotfound = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then ifnotfound else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> iffound bucket i | _ -> loop (i + 1) end else loop (i + 1) in loop 0 let remove t d = find_shadow t d (fun w i -> set w i None) () let mem t d = find_shadow t d (fun _w _i -> true) false let find_all t d = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i accu = if i >= sz then accu else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> begin match get bucket i with | Some v -> loop (i + 1) (v :: accu) | None -> loop (i + 1) accu end | _ -> loop (i + 1) accu end else loop (i + 1) accu in loop 0 [] let stats t = let len = Array.length t.table in let lens = Array.map length t.table in Array.sort compare lens; let totlen = Array.fold_left ( + ) 0 lens in (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1)) end
null
https://raw.githubusercontent.com/brianhempel/maniposynth/8c8e72f2459f1ec05fefcb994253f99620e377f3/ocaml-4.07.1/stdlib/weak.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Weak array operations * number of additional values in a weak pointer * Weak hash tables bucket size limit number of oversize buckets for internal bookkeeping maximum size already reached
, projet Para , INRIA Rocquencourt Copyright 1997 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the type 'a t external create : int -> 'a t = "caml_weak_create" let additional_values = 2 let length x = Obj.size(Obj.repr x) - additional_values external set : 'a t -> int -> 'a option -> unit = "caml_weak_set" external get : 'a t -> int -> 'a option = "caml_weak_get" external get_copy : 'a t -> int -> 'a option = "caml_weak_get_copy" external check : 'a t -> int -> bool = "caml_weak_check" external blit : 'a t -> int -> 'a t -> int -> int -> unit = "caml_weak_blit" blit : let fill ar ofs len x = if ofs < 0 || len < 0 || ofs + len > length ar then raise (Invalid_argument "Weak.fill") else begin for i = ofs to (ofs + len - 1) do set ar i x done end module type S = sig type data type t val create : int -> t val clear : t -> unit val merge : t -> data -> data val add : t -> data -> unit val remove : t -> data -> unit val find : t -> data -> data val find_opt : t -> data -> data option val find_all : t -> data -> data list val mem : t -> data -> bool val iter : (data -> unit) -> t -> unit val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a val count : t -> int val stats : t -> int * int * int * int * int * int end module Make (H : Hashtbl.HashedType) : (S with type data = H.t) = struct type 'a weak_t = 'a t let weak_create = create let emptybucket = weak_create 0 type data = H.t type t = { mutable table : data weak_t array; mutable hashes : int array array; } let get_index t h = (h land max_int) mod (Array.length t.table) let limit = 7 let over_limit = 2 let create sz = let sz = if sz < 7 then 7 else sz in let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in { table = Array.make sz emptybucket; hashes = Array.make sz [| |]; limit = limit; oversize = 0; rover = 0; } let clear t = for i = 0 to Array.length t.table - 1 do t.table.(i) <- emptybucket; t.hashes.(i) <- [| |]; done; t.limit <- limit; t.oversize <- 0 let fold f t init = let rec fold_bucket i b accu = if i >= length b then accu else match get b i with | Some v -> fold_bucket (i+1) b (f v accu) | None -> fold_bucket (i+1) b accu in Array.fold_right (fold_bucket 0) t.table init let iter f t = let rec iter_bucket i b = if i >= length b then () else match get b i with | Some v -> f v; iter_bucket (i+1) b | None -> iter_bucket (i+1) b in Array.iter (iter_bucket 0) t.table let iter_weak f t = let rec iter_bucket i j b = if i >= length b then () else match check b i with | true -> f b t.hashes.(j) i; iter_bucket (i+1) j b | false -> iter_bucket (i+1) j b in Array.iteri (iter_bucket 0) t.table let rec count_bucket i b accu = if i >= length b then accu else count_bucket (i+1) b (accu + (if check b i then 1 else 0)) let count t = Array.fold_right (count_bucket 0) t.table 0 let next_sz n = min (3 * n / 2 + 3) Sys.max_array_length let prev_sz n = ((n - 3) * 2 + 2) / 3 let test_shrink_bucket t = let bucket = t.table.(t.rover) in let hbucket = t.hashes.(t.rover) in let len = length bucket in let prev_len = prev_sz len in let live = count_bucket 0 bucket 0 in if live <= prev_len then begin let rec loop i j = if j >= prev_len then begin if check bucket i then loop (i + 1) j else if check bucket j then begin blit bucket j bucket i 1; hbucket.(i) <- hbucket.(j); loop (i + 1) (j - 1); end else loop i (j - 1); end; in loop 0 (length bucket - 1); if prev_len = 0 then begin t.table.(t.rover) <- emptybucket; t.hashes.(t.rover) <- [| |]; end else begin Obj.truncate (Obj.repr bucket) (prev_len + additional_values); Obj.truncate (Obj.repr hbucket) prev_len; end; if len > t.limit && prev_len <= t.limit then t.oversize <- t.oversize - 1; end; t.rover <- (t.rover + 1) mod (Array.length t.table) let rec resize t = let oldlen = Array.length t.table in let newlen = next_sz oldlen in if newlen > oldlen then begin let newt = create newlen in let add_weak ob oh oi = let setter nb ni _ = blit ob oi nb ni 1 in let h = oh.(oi) in add_aux newt setter None h (get_index newt h); in iter_weak add_weak t; t.table <- newt.table; t.hashes <- newt.hashes; t.limit <- newt.limit; t.oversize <- newt.oversize; t.rover <- t.rover mod Array.length newt.table; end else begin t.oversize <- 0; end and add_aux t setter d h index = let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then begin let newsz = min (3 * sz / 2 + 3) (Sys.max_array_length - additional_values) in if newsz <= sz then failwith "Weak.Make: hash bucket cannot grow more"; let newbucket = weak_create newsz in let newhashes = Array.make newsz 0 in blit bucket 0 newbucket 0 sz; Array.blit hashes 0 newhashes 0 sz; setter newbucket sz d; newhashes.(sz) <- h; t.table.(index) <- newbucket; t.hashes.(index) <- newhashes; if sz <= t.limit && newsz > t.limit then begin t.oversize <- t.oversize + 1; for _i = 0 to over_limit do test_shrink_bucket t done; end; if t.oversize > Array.length t.table / over_limit then resize t; end else if check bucket i then begin loop (i + 1) end else begin setter bucket i d; hashes.(i) <- h; end; in loop 0 let add t d = let h = H.hash d in add_aux t set (Some d) h (get_index t h) let find_or t d ifnotfound = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then ifnotfound h index else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> begin match get bucket i with | Some v -> v | None -> loop (i + 1) end | _ -> loop (i + 1) end else loop (i + 1) in loop 0 let merge t d = find_or t d (fun h index -> add_aux t set (Some d) h index; d) let find t d = find_or t d (fun _h _index -> raise Not_found) let find_opt t d = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then None else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> begin match get bucket i with | Some _ as v -> v | None -> loop (i + 1) end | _ -> loop (i + 1) end else loop (i + 1) in loop 0 let find_shadow t d iffound ifnotfound = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i = if i >= sz then ifnotfound else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> iffound bucket i | _ -> loop (i + 1) end else loop (i + 1) in loop 0 let remove t d = find_shadow t d (fun w i -> set w i None) () let mem t d = find_shadow t d (fun _w _i -> true) false let find_all t d = let h = H.hash d in let index = get_index t h in let bucket = t.table.(index) in let hashes = t.hashes.(index) in let sz = length bucket in let rec loop i accu = if i >= sz then accu else if h = hashes.(i) then begin match get_copy bucket i with | Some v when H.equal v d -> begin match get bucket i with | Some v -> loop (i + 1) (v :: accu) | None -> loop (i + 1) accu end | _ -> loop (i + 1) accu end else loop (i + 1) accu in loop 0 [] let stats t = let len = Array.length t.table in let lens = Array.map length t.table in Array.sort compare lens; let totlen = Array.fold_left ( + ) 0 lens in (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1)) end
2a4edadaf8a4baf4af5f2f5c15ecb8f7145ac0962a5921475bb9493ad88416b4
mochi/eswf
eswf_redir.erl
@author < > 2006 @doc Create URL redirect SWF files . -module(eswf_redir). -export([actions/2, swf/2, swf/4]). %% @type iolist() = [char() | binary() | iolist()] @type iodata ( ) = iolist ( ) | binary ( ) , { Width , } ) - > iodata ( ) @equiv swf(Url , { Width , , 12 , 6 ) swf(Url, Dimensions) -> swf(Url, Dimensions, 12, 6). , { Width , , Fps , FlashVersion ) - > iodata ( ) @doc Return a SWF that does a loadMovie to Url with a registration point %% at the center. The center of the loaded movie clip will be at (0, 0). swf(Url, Dimensions, Fps, FlashVersion) -> Tags = [{file_attributes, 1}, {set_background_color, {rgb, 255, 255, 255}}, {do_action, actions(Url, Dimensions)}, show_frame], eswf:encswf(FlashVersion, Dimensions, Fps, Tags). actions(Url , { Width , } ) - > [ Action ] %% @doc Return actions for a do_action tag that does a loadMovie to Url with a %% registration point at the center. The center of the loaded movie clip %% will be at (0, 0). actions(Url, {Width, Height}) -> Left = -(Width * 0.5), Top = -(Height * 0.5), [{push, [Url, 1, 1, "ad", 2, "this"]}, get_variable, {push, ["createEmptyMovieClip"]}, call_method, push_duplicate, push_duplicate, {push, ["_x", Left]}, set_member, {push, ["_y", Top]}, set_member, {push, ["loadMovie"]}, call_method, pop].
null
https://raw.githubusercontent.com/mochi/eswf/51b60942cb34b8490aefe6f05e88852454681eee/src/eswf_redir.erl
erlang
@type iolist() = [char() | binary() | iolist()] at the center. The center of the loaded movie clip will be at (0, 0). @doc Return actions for a do_action tag that does a loadMovie to Url with a registration point at the center. The center of the loaded movie clip will be at (0, 0).
@author < > 2006 @doc Create URL redirect SWF files . -module(eswf_redir). -export([actions/2, swf/2, swf/4]). @type iodata ( ) = iolist ( ) | binary ( ) , { Width , } ) - > iodata ( ) @equiv swf(Url , { Width , , 12 , 6 ) swf(Url, Dimensions) -> swf(Url, Dimensions, 12, 6). , { Width , , Fps , FlashVersion ) - > iodata ( ) @doc Return a SWF that does a loadMovie to Url with a registration point swf(Url, Dimensions, Fps, FlashVersion) -> Tags = [{file_attributes, 1}, {set_background_color, {rgb, 255, 255, 255}}, {do_action, actions(Url, Dimensions)}, show_frame], eswf:encswf(FlashVersion, Dimensions, Fps, Tags). actions(Url , { Width , } ) - > [ Action ] actions(Url, {Width, Height}) -> Left = -(Width * 0.5), Top = -(Height * 0.5), [{push, [Url, 1, 1, "ad", 2, "this"]}, get_variable, {push, ["createEmptyMovieClip"]}, call_method, push_duplicate, push_duplicate, {push, ["_x", Left]}, set_member, {push, ["_y", Top]}, set_member, {push, ["loadMovie"]}, call_method, pop].
3fcdd569833775595e753f8562827e38ceeba5eb820b4bf4ca976c2d3a0aad3c
facjure/mesh
project.clj
(defproject facjure/mesh "0.6.0" :description "A toolkit for responsive grids and web typography" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :scm {:name "git" :url ""} :min-lein-version "2.8.1" :global-vars {*warn-on-reflection* false *assert* false} :dependencies [[org.clojure/clojure "1.10.0" :scope "provided"] [org.clojure/clojurescript "1.10.439" :scope "provided"] [com.gfredericks/cljs-numbers "0.1.2"] [garden "1.3.6"]] :node-dependencies [[autoprefixer "9.4.3"] [css-min "0.4.3"]] :source-paths ["src" "target/classes"] :clean-targets ^{:protect false} ["resources/public/js" "target/classes"] :cljsbuild {:builds [{:id "dev" :source-paths ["examples" "dev"] :compiler {:main repl :output-to "resources/public/js/mesh.js" :output-dir "resources/public/js/out" :asset-path "js/out" :optimizations :none :source-map-timestamp true :install-deps true :npm-deps {:create-react-class "15.6.0"} :preloads [devtools.preload]} :figwheel {}} {:id "prod" :source-paths ["src"] :compiler {:output-to "dist/mesh.min.js" :optimizations :advanced :pretty-print false}}]} :garden {:builds [{:id "typography" :source-paths [x"examples"] :stylesheet typography.styles/index :compiler {:output-to "resources/public/css/typography.css" :pretty-print true}} {:id "grids" :source-paths ["src" "examples"] :stylesheet grids.styles/index :compiler {:output-to "resources/public/css/grids.css" :pretty-print true}}]} :plugins [[lein-cljsbuild "1.1.7"] [lein-figwheel "0.5.16"] [lein-garden "0.2.8"] [lein-npm "0.6.2"] [lein-pdo "0.1.1"] [lein-doo "0.1.9"]] :repl-options {:nrepl-middleware [cider.piggieback/wrap-cljs-repl]} :profiles {:dev {:dependencies [[cider/piggieback "0.3.10" :exclude [org.clojure/tools.nrepl]] [binaryage/devtools "0.9.9"] [figwheel-sidecar "0.5.16"] [sablono "0.3.4"] [org.omcljs/om "0.9.0"]] :figwheel {:http-server-root "public" :server-port 3449 :nrepl-port 7888 :css-dirs ["resources/public/css"] }}} :aliases {"init" ["pdo" "clean," "garden" "clean"] "dev" ["pdo" "garden" "auto," "figwheel"] "release" ["pdo" "clean," "cljsbuild" "once" "prod"]})
null
https://raw.githubusercontent.com/facjure/mesh/e37887304c271bacfc017055180f56935f893682/project.clj
clojure
(defproject facjure/mesh "0.6.0" :description "A toolkit for responsive grids and web typography" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :scm {:name "git" :url ""} :min-lein-version "2.8.1" :global-vars {*warn-on-reflection* false *assert* false} :dependencies [[org.clojure/clojure "1.10.0" :scope "provided"] [org.clojure/clojurescript "1.10.439" :scope "provided"] [com.gfredericks/cljs-numbers "0.1.2"] [garden "1.3.6"]] :node-dependencies [[autoprefixer "9.4.3"] [css-min "0.4.3"]] :source-paths ["src" "target/classes"] :clean-targets ^{:protect false} ["resources/public/js" "target/classes"] :cljsbuild {:builds [{:id "dev" :source-paths ["examples" "dev"] :compiler {:main repl :output-to "resources/public/js/mesh.js" :output-dir "resources/public/js/out" :asset-path "js/out" :optimizations :none :source-map-timestamp true :install-deps true :npm-deps {:create-react-class "15.6.0"} :preloads [devtools.preload]} :figwheel {}} {:id "prod" :source-paths ["src"] :compiler {:output-to "dist/mesh.min.js" :optimizations :advanced :pretty-print false}}]} :garden {:builds [{:id "typography" :source-paths [x"examples"] :stylesheet typography.styles/index :compiler {:output-to "resources/public/css/typography.css" :pretty-print true}} {:id "grids" :source-paths ["src" "examples"] :stylesheet grids.styles/index :compiler {:output-to "resources/public/css/grids.css" :pretty-print true}}]} :plugins [[lein-cljsbuild "1.1.7"] [lein-figwheel "0.5.16"] [lein-garden "0.2.8"] [lein-npm "0.6.2"] [lein-pdo "0.1.1"] [lein-doo "0.1.9"]] :repl-options {:nrepl-middleware [cider.piggieback/wrap-cljs-repl]} :profiles {:dev {:dependencies [[cider/piggieback "0.3.10" :exclude [org.clojure/tools.nrepl]] [binaryage/devtools "0.9.9"] [figwheel-sidecar "0.5.16"] [sablono "0.3.4"] [org.omcljs/om "0.9.0"]] :figwheel {:http-server-root "public" :server-port 3449 :nrepl-port 7888 :css-dirs ["resources/public/css"] }}} :aliases {"init" ["pdo" "clean," "garden" "clean"] "dev" ["pdo" "garden" "auto," "figwheel"] "release" ["pdo" "clean," "cljsbuild" "once" "prod"]})
6f5d6e2e7a3a9c5ea404aa2a5b5306d11c64da626458f82fcccbde2ac9c13613
racket/web-server
dispatch-passwords.rkt
#lang racket/base (require racket/list net/url racket/contract) (require web-server/dispatchers/dispatch web-server/private/util web-server/configuration/responders web-server/http web-server/http/response) (define denied?/c (request? . -> . (or/c false/c string?))) (define authorized?/c (string? (or/c false/c bytes?) (or/c false/c bytes?) . -> . (or/c false/c string?))) (provide/contract [interface-version dispatcher-interface-version/c] [denied?/c contract?] [make (->* (denied?/c) (#:authentication-responder (url? header? . -> . response?)) dispatcher/c)] [authorized?/c contract?] [make-basic-denied?/path (authorized?/c . -> . denied?/c)] [password-file->authorized? (path-string? . -> . (values (-> void) authorized?/c))]) (define interface-version 'v1) (define (make denied? #:authentication-responder [authentication-responder (gen-authentication-responder "forbidden.html")]) (lambda (conn req) (define uri (request-uri req)) (define method (request-method req)) (cond [(denied? req) => (lambda (realm) (request-authentication conn method uri authentication-responder realm))] [else (next-dispatcher)]))) (define (make-basic-denied?/path authorized?) (lambda (req) (define path (url-path->string (url-path (request-uri req)))) (cond [(request->basic-credentials req) => (lambda (user*pass) (authorized? path (car user*pass) (cdr user*pass)))] [else (authorized? path #f #f)]))) (define (password-file->authorized? password-file) (define last-read-time (box #f)) (define password-cache (box #f)) (define (update-password-cache!) (when (and (file-exists? password-file) (memq 'read (file-or-directory-permissions password-file))) (let ([cur-mtime (file-or-directory-modify-seconds password-file)]) (when (or (not (unbox last-read-time)) (cur-mtime . > . (unbox last-read-time)) (not (unbox password-cache))) (set-box! last-read-time cur-mtime) (set-box! password-cache (read-passwords password-file)))))) (define (read-password-cache) (update-password-cache!) (unbox password-cache)) (values update-password-cache! (lambda (path user pass) (define denied? (read-password-cache)) (if denied? (denied? path (if user (lowercase-symbol! user) #f) pass) ; Fail un-safe #f)))) pass - entry = ( make - pass - entry str regexp ( list ) ) (define-struct pass-entry (domain pattern users)) (define-struct (exn:password-file exn) ()) : host - > ( ( or / c str # f ) ) ;; to produce a function that checks if a given url path is accessible by a given user with a given ;; password. If not, the produced function returns a string, prompting for the password. ;; If the password file does not exist, all accesses are allowed. If the file is malformed, an ;; exn:password-file is raised. (define (read-passwords password-path) (with-handlers ([void (lambda (exn) (raise (make-exn:password-file (format "could not load password file ~a" password-path) (current-continuation-marks))))]) (let ([passwords (with-input-from-file password-path (lambda () (let ([raw (second (read))]) (unless (password-list? raw) (raise "malformed passwords")) (map (lambda (x) (make-pass-entry (car x) (regexp (cadr x)) (cddr x))) raw))))]) ;; string symbol bytes -> (or/c #f string) (lambda (request-path user-name password) (ormap (lambda (x) (and (regexp-match (pass-entry-pattern x) request-path) (let ([name-pass (assq user-name (pass-entry-users x))]) (if (and name-pass (string=? (cadr name-pass) (bytes->string/utf-8 password))) #f (pass-entry-domain x))))) passwords))))) password - list ? : TST - > bool Note : andmap fails for dotted pairs at end . ;; This is okay, since #f ends up raising a caught exception anyway. (define (password-list? passwords) (and (list? passwords) (andmap (lambda (domain) (and (pair? domain) (pair? (cdr domain)) (list (cddr domain)) (string? (car domain)) (string? (cadr domain)) (andmap (lambda (x) (and (pair? x) (pair? (cdr x)) (null? (cddr x)) (symbol? (car x)) (string? (cadr x)))) (cddr domain)))) passwords))) request - authentication : connection Method URL iport oport host bool : at first look , it seems that this gets called when the user ;; has supplied bad authentication credentials. (define (request-authentication conn method uri authentication-responder realm) (output-response/method conn (authentication-responder uri (make-basic-auth-header realm)) method))
null
https://raw.githubusercontent.com/racket/web-server/f718800b5b3f407f7935adf85dfa663c4bba1651/web-server-lib/web-server/dispatchers/dispatch-passwords.rkt
racket
Fail un-safe to produce a function that checks if a given url path is accessible by a given user with a given password. If not, the produced function returns a string, prompting for the password. If the password file does not exist, all accesses are allowed. If the file is malformed, an exn:password-file is raised. string symbol bytes -> (or/c #f string) This is okay, since #f ends up raising a caught exception anyway. has supplied bad authentication credentials.
#lang racket/base (require racket/list net/url racket/contract) (require web-server/dispatchers/dispatch web-server/private/util web-server/configuration/responders web-server/http web-server/http/response) (define denied?/c (request? . -> . (or/c false/c string?))) (define authorized?/c (string? (or/c false/c bytes?) (or/c false/c bytes?) . -> . (or/c false/c string?))) (provide/contract [interface-version dispatcher-interface-version/c] [denied?/c contract?] [make (->* (denied?/c) (#:authentication-responder (url? header? . -> . response?)) dispatcher/c)] [authorized?/c contract?] [make-basic-denied?/path (authorized?/c . -> . denied?/c)] [password-file->authorized? (path-string? . -> . (values (-> void) authorized?/c))]) (define interface-version 'v1) (define (make denied? #:authentication-responder [authentication-responder (gen-authentication-responder "forbidden.html")]) (lambda (conn req) (define uri (request-uri req)) (define method (request-method req)) (cond [(denied? req) => (lambda (realm) (request-authentication conn method uri authentication-responder realm))] [else (next-dispatcher)]))) (define (make-basic-denied?/path authorized?) (lambda (req) (define path (url-path->string (url-path (request-uri req)))) (cond [(request->basic-credentials req) => (lambda (user*pass) (authorized? path (car user*pass) (cdr user*pass)))] [else (authorized? path #f #f)]))) (define (password-file->authorized? password-file) (define last-read-time (box #f)) (define password-cache (box #f)) (define (update-password-cache!) (when (and (file-exists? password-file) (memq 'read (file-or-directory-permissions password-file))) (let ([cur-mtime (file-or-directory-modify-seconds password-file)]) (when (or (not (unbox last-read-time)) (cur-mtime . > . (unbox last-read-time)) (not (unbox password-cache))) (set-box! last-read-time cur-mtime) (set-box! password-cache (read-passwords password-file)))))) (define (read-password-cache) (update-password-cache!) (unbox password-cache)) (values update-password-cache! (lambda (path user pass) (define denied? (read-password-cache)) (if denied? (denied? path (if user (lowercase-symbol! user) #f) pass) #f)))) pass - entry = ( make - pass - entry str regexp ( list ) ) (define-struct pass-entry (domain pattern users)) (define-struct (exn:password-file exn) ()) : host - > ( ( or / c str # f ) ) (define (read-passwords password-path) (with-handlers ([void (lambda (exn) (raise (make-exn:password-file (format "could not load password file ~a" password-path) (current-continuation-marks))))]) (let ([passwords (with-input-from-file password-path (lambda () (let ([raw (second (read))]) (unless (password-list? raw) (raise "malformed passwords")) (map (lambda (x) (make-pass-entry (car x) (regexp (cadr x)) (cddr x))) raw))))]) (lambda (request-path user-name password) (ormap (lambda (x) (and (regexp-match (pass-entry-pattern x) request-path) (let ([name-pass (assq user-name (pass-entry-users x))]) (if (and name-pass (string=? (cadr name-pass) (bytes->string/utf-8 password))) #f (pass-entry-domain x))))) passwords))))) password - list ? : TST - > bool Note : andmap fails for dotted pairs at end . (define (password-list? passwords) (and (list? passwords) (andmap (lambda (domain) (and (pair? domain) (pair? (cdr domain)) (list (cddr domain)) (string? (car domain)) (string? (cadr domain)) (andmap (lambda (x) (and (pair? x) (pair? (cdr x)) (null? (cddr x)) (symbol? (car x)) (string? (cadr x)))) (cddr domain)))) passwords))) request - authentication : connection Method URL iport oport host bool : at first look , it seems that this gets called when the user (define (request-authentication conn method uri authentication-responder realm) (output-response/method conn (authentication-responder uri (make-basic-auth-header realm)) method))
0454af91bd8c958b573f04b3b792555f1a92e0dc06d668e1ae1dcc6a15638c68
kcsongor/generic-lens
Types.hs
{-# LANGUAGE PackageImports #-} # LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # module Data.Generics.Product.Internal.Types where import Data.Kind import Data.Int (Int8, Int16, Int32, Int64) import Data.Word (Word8, Word16, Word32, Word64) import qualified Data.Text as T import GHC.Generics import Data.Generics.Internal.GenericN import GHC.TypeLits import Data.Generics.Internal.Errors import "this" Data.Generics.Internal.VL.Traversal -- | The children of a type are the types of its fields. -- The 'Children' type family maps a type @a@ to its set of children. -- This type family is parameterized by a symbol ( that can be declared as -- an empty data type). The symbol ' ' provides a default definition . You can create new -- symbols to override the set of children of abstract, non-generic types. -- -- The following example declares a @Custom@ symbol to redefine 'Children' -- for some abstract types from the @time@ library. -- -- @ -- data Custom -- type instance 'Children' Custom a = ChildrenCustom a -- type family ( a : : Type ) where -- ChildrenCustom DiffTime = '[] -- ChildrenCustom NominalDiffTime = '[] -- -- Add more custom mappings here. -- -- ChildrenCustom a = Children ChGeneric a -- @ -- -- To use this definition, replace 'types' with @'typesUsing' \@Custom@. type family Children (ch :: Type) (a :: Type) :: [Type] -- | The default definition of 'Children'. -- Primitive types from core libraries have no children, and other types are -- assumed to be 'Generic'. data ChGeneric type instance Children ChGeneric a = ChildrenDefault a type family ChildrenDefault (a :: Type) :: [Type] where ChildrenDefault Char = '[] ChildrenDefault Double = '[] ChildrenDefault Float = '[] ChildrenDefault Integer = '[] ChildrenDefault Int = '[] ChildrenDefault Int8 = '[] ChildrenDefault Int16 = '[] ChildrenDefault Int32 = '[] ChildrenDefault Int64 = '[] ChildrenDefault Word = '[] ChildrenDefault Word8 = '[] ChildrenDefault Word16 = '[] ChildrenDefault Word32 = '[] ChildrenDefault Word64 = '[] ChildrenDefault T.Text = '[] ChildrenDefault (Param n _) = '[] ChildrenDefault a = Defined (Rep a) (NoGeneric a '[ 'Text "arising from a generic traversal." , 'Text "Either derive the instance, or define a custom traversal using HasTypesCustom" ]) (ChildrenGeneric (Rep a) '[]) type family ChildrenGeneric (f :: k -> Type) (cs :: [Type]) :: [Type] where ChildrenGeneric (M1 _ _ f) cs = ChildrenGeneric f cs ChildrenGeneric (l :*: r) cs = ChildrenGeneric l (ChildrenGeneric r cs) ChildrenGeneric (l :+: r) cs = ChildrenGeneric l (ChildrenGeneric r cs) ChildrenGeneric (Rec0 a) cs = a ': cs ChildrenGeneric _ cs = cs type Interesting (ch :: Type) (a :: Type) (t :: Type) = Defined_list (Children ch t) (NoChildren ch t) (IsNothing (Interesting' ch a '[t] (Children ch t))) type family NoChildren (ch :: Type) (a :: Type) :: Constraint where NoChildren ch a = PrettyError '[ 'Text "No type family instance for " ':<>: QuoteType (Children ch a) , 'Text "arising from a traversal over " ':<>: QuoteType a , 'Text "with custom strategy " ':<>: QuoteType ch ] type family Interesting' (ch :: Type) (a :: Type) (seen :: [Type]) (ts :: [Type]) :: Maybe [Type] where Interesting' ch _ seen '[] = 'Just seen Interesting' ch a seen (t ': ts) = InterestingOr ch a (InterestingUnless ch a seen t (Elem t seen)) ts -- Short circuit -- Note: we only insert 't' to the seen list if it's not already there (which is precisely when `s` is 'False) type family InterestingUnless (ch :: Type) (a :: Type) (seen :: [Type]) (t :: Type) (alreadySeen :: Bool) :: Maybe [Type] where InterestingUnless ch a seen a _ = 'Nothing InterestingUnless ch a seen t 'True = 'Just seen InterestingUnless ch a seen t 'False = Defined_list (Children ch t) (NoChildren ch t) (Interesting' ch a (t ': seen) (Children ch t)) -- Short circuit type family InterestingOr (ch :: Type) (a :: Type) (seen' :: Maybe [Type]) (ts :: [Type]) :: Maybe [Type] where InterestingOr ch a 'Nothing _ = 'Nothing InterestingOr ch a ('Just seen) ts = Interesting' ch a seen ts type family Elem a as where Elem a (a ': _) = 'True Elem a (_ ': as) = Elem a as Elem a '[] = 'False type family IsNothing a where IsNothing ('Just _) = 'False IsNothing 'Nothing = 'True -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- HasTypes -------------------------------------------------------------------------------- class HasTypes s a where types_ :: Traversal' s a types_ _ = pure {-# INLINE types_ #-} instance ( HasTypesUsing ChGeneric s s a a ) => HasTypes s a where types_ = typesUsing_ @ChGeneric {-# INLINE types_ #-} -------------------------------------------------------------------------------- data Void instance {-# OVERLAPPING #-} HasTypes Void a where types_ _ = pure instance {-# OVERLAPPING #-} HasTypes s Void where types_ _ = pure instance {-# OVERLAPPING #-} HasTypesUsing ch Void Void a b where typesUsing_ _ = pure instance {-# OVERLAPPING #-} HasTypesUsing ch s s Void Void where typesUsing_ _ = pure -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- HasTypesUsing -------------------------------------------------------------------------------- | @since 1.2.0.0 class HasTypesUsing (ch :: Type) s t a b where typesUsing_ :: Traversal s t a b instance {-# OVERLAPPABLE #-} ( HasTypesOpt ch (Interesting ch a s) s t a b ) => HasTypesUsing ch s t a b where typesUsing_ = typesOpt @ch @(Interesting ch a s) # INLINE typesUsing _ # instance {-# OVERLAPPABLE #-} HasTypesUsing ch a b a b where typesUsing_ = id -- | By adding instances to this class, we can override the default -- behaviour in an ad-hoc manner. -- For example: -- -- @ -- instance HasTypesCustom Custom Opaque Opaque String String where -- typesCustom f (Opaque str) = Opaque <$> f str -- @ -- @since 1.2.0.0 class HasTypesCustom (ch :: Type) s t a b where -- | This function should never be used directly, only to override -- the default traversal behaviour. To actually use the custom -- traversal strategy, see 'typesUsing'. This is because 'typesUsing' does -- additional optimisations, like ensuring that nodes with no relevant members will -- not be traversed at runtime. typesCustom :: Traversal s t a b instance {-# OVERLAPPABLE #-} ( GHasTypes ch (Rep s) (Rep t) a b , Generic s , Generic t if there 's no Generic instance here , it means we got through the -- Children check by a user-defined custom strategy. Therefore , we can ignore the missing Generic instance , and -- instead report a missing HasTypesCustom instance , Defined (Rep s) (PrettyError '[ 'Text "No instance " ':<>: QuoteType (HasTypesCustom ch s t a b)]) (() :: Constraint) ) => HasTypesCustom ch s t a b where typesCustom f s = to <$> gtypes_ @ch f (from s) -------------------------------------------------------------------------------- -- Internals -------------------------------------------------------------------------------- -- TODO: these should never leak out in error messages class HasTypesOpt (ch :: Type) (p :: Bool) s t a b where typesOpt :: Traversal s t a b instance HasTypesCustom ch s t a b => HasTypesOpt ch 'True s t a b where typesOpt = typesCustom @ch instance HasTypesOpt ch 'False s s a b where typesOpt _ = pure -------------------------------------------------------------------------------- -- TODO: pull out recursion here. class GHasTypes ch s t a b where gtypes_ :: Traversal (s x) (t x) a b instance ( GHasTypes ch l l' a b , GHasTypes ch r r' a b ) => GHasTypes ch (l :*: r) (l' :*: r') a b where gtypes_ f (l :*: r) = (:*:) <$> gtypes_ @ch f l <*> gtypes_ @ch f r {-# INLINE gtypes_ #-} instance ( GHasTypes ch l l' a b , GHasTypes ch r r' a b ) => GHasTypes ch (l :+: r) (l' :+: r') a b where gtypes_ f (L1 l) = L1 <$> gtypes_ @ch f l gtypes_ f (R1 r) = R1 <$> gtypes_ @ch f r {-# INLINE gtypes_ #-} instance GHasTypes ch s t a b => GHasTypes ch (M1 m meta s) (M1 m meta t) a b where gtypes_ f (M1 s) = M1 <$> gtypes_ @ch f s {-# INLINE gtypes_ #-} -- In the recursive case, we invoke 'HasTypesUsing' again, using the -- same strategy This instance is marked INCOHERENT , because # INCOHERENT # gtypes_ f (K1 x) = K1 <$> typesUsing_ @ch f x {-# INLINE gtypes_ #-} | The default instance for ' HasTypes ' acts as a synonym for ' HasTypesUsing ' , so in most cases this instance should -- behave the same as the one above. -- However, there might be overlapping instances defined for ' HasTypes ' directly , in which case we want to prefer those -- instances (even though the custom instances should always be added to 'HasTypesCustom') instance {-# OVERLAPPING #-} HasTypes b a => GHasTypes ChGeneric (Rec0 b) (Rec0 b) a a where gtypes_ f (K1 x) = K1 <$> types_ @b @a f x {-# INLINE gtypes_ #-} instance GHasTypes ch U1 U1 a b where gtypes_ _ _ = pure U1 {-# INLINE gtypes_ #-} instance GHasTypes ch V1 V1 a b where gtypes_ _ = pure {-# INLINE gtypes_ #-}
null
https://raw.githubusercontent.com/kcsongor/generic-lens/de57d7a8ce7ce9f5b93f27565ec6fc98d659e03f/generic-lens-core/src/Data/Generics/Product/Internal/Types.hs
haskell
# LANGUAGE PackageImports # # LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts # # LANGUAGE Rank2Types # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeOperators # | The children of a type are the types of its fields. The 'Children' type family maps a type @a@ to its set of children. an empty data type). symbols to override the set of children of abstract, non-generic types. The following example declares a @Custom@ symbol to redefine 'Children' for some abstract types from the @time@ library. @ data Custom type instance 'Children' Custom a = ChildrenCustom a ChildrenCustom DiffTime = '[] ChildrenCustom NominalDiffTime = '[] -- Add more custom mappings here. ChildrenCustom a = Children ChGeneric a @ To use this definition, replace 'types' with @'typesUsing' \@Custom@. | The default definition of 'Children'. Primitive types from core libraries have no children, and other types are assumed to be 'Generic'. Short circuit Note: we only insert 't' to the seen list if it's not already there (which is precisely when `s` is 'False) Short circuit ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ # INLINE types_ # # INLINE types_ # ------------------------------------------------------------------------------ # OVERLAPPING # # OVERLAPPING # # OVERLAPPING # # OVERLAPPING # ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ HasTypesUsing ------------------------------------------------------------------------------ # OVERLAPPABLE # # OVERLAPPABLE # | By adding instances to this class, we can override the default behaviour in an ad-hoc manner. For example: @ instance HasTypesCustom Custom Opaque Opaque String String where typesCustom f (Opaque str) = Opaque <$> f str @ | This function should never be used directly, only to override the default traversal behaviour. To actually use the custom traversal strategy, see 'typesUsing'. This is because 'typesUsing' does additional optimisations, like ensuring that nodes with no relevant members will not be traversed at runtime. # OVERLAPPABLE # Children check by a user-defined custom strategy. instead report a missing HasTypesCustom instance ------------------------------------------------------------------------------ Internals ------------------------------------------------------------------------------ TODO: these should never leak out in error messages ------------------------------------------------------------------------------ TODO: pull out recursion here. # INLINE gtypes_ # # INLINE gtypes_ # # INLINE gtypes_ # In the recursive case, we invoke 'HasTypesUsing' again, using the same strategy # INLINE gtypes_ # behave the same as the one above. However, there might be overlapping instances defined for instances (even though the custom instances should always be added to 'HasTypesCustom') # OVERLAPPING # # INLINE gtypes_ # # INLINE gtypes_ # # INLINE gtypes_ #
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Data.Generics.Product.Internal.Types where import Data.Kind import Data.Int (Int8, Int16, Int32, Int64) import Data.Word (Word8, Word16, Word32, Word64) import qualified Data.Text as T import GHC.Generics import Data.Generics.Internal.GenericN import GHC.TypeLits import Data.Generics.Internal.Errors import "this" Data.Generics.Internal.VL.Traversal This type family is parameterized by a symbol ( that can be declared as The symbol ' ' provides a default definition . You can create new type family ( a : : Type ) where type family Children (ch :: Type) (a :: Type) :: [Type] data ChGeneric type instance Children ChGeneric a = ChildrenDefault a type family ChildrenDefault (a :: Type) :: [Type] where ChildrenDefault Char = '[] ChildrenDefault Double = '[] ChildrenDefault Float = '[] ChildrenDefault Integer = '[] ChildrenDefault Int = '[] ChildrenDefault Int8 = '[] ChildrenDefault Int16 = '[] ChildrenDefault Int32 = '[] ChildrenDefault Int64 = '[] ChildrenDefault Word = '[] ChildrenDefault Word8 = '[] ChildrenDefault Word16 = '[] ChildrenDefault Word32 = '[] ChildrenDefault Word64 = '[] ChildrenDefault T.Text = '[] ChildrenDefault (Param n _) = '[] ChildrenDefault a = Defined (Rep a) (NoGeneric a '[ 'Text "arising from a generic traversal." , 'Text "Either derive the instance, or define a custom traversal using HasTypesCustom" ]) (ChildrenGeneric (Rep a) '[]) type family ChildrenGeneric (f :: k -> Type) (cs :: [Type]) :: [Type] where ChildrenGeneric (M1 _ _ f) cs = ChildrenGeneric f cs ChildrenGeneric (l :*: r) cs = ChildrenGeneric l (ChildrenGeneric r cs) ChildrenGeneric (l :+: r) cs = ChildrenGeneric l (ChildrenGeneric r cs) ChildrenGeneric (Rec0 a) cs = a ': cs ChildrenGeneric _ cs = cs type Interesting (ch :: Type) (a :: Type) (t :: Type) = Defined_list (Children ch t) (NoChildren ch t) (IsNothing (Interesting' ch a '[t] (Children ch t))) type family NoChildren (ch :: Type) (a :: Type) :: Constraint where NoChildren ch a = PrettyError '[ 'Text "No type family instance for " ':<>: QuoteType (Children ch a) , 'Text "arising from a traversal over " ':<>: QuoteType a , 'Text "with custom strategy " ':<>: QuoteType ch ] type family Interesting' (ch :: Type) (a :: Type) (seen :: [Type]) (ts :: [Type]) :: Maybe [Type] where Interesting' ch _ seen '[] = 'Just seen Interesting' ch a seen (t ': ts) = InterestingOr ch a (InterestingUnless ch a seen t (Elem t seen)) ts type family InterestingUnless (ch :: Type) (a :: Type) (seen :: [Type]) (t :: Type) (alreadySeen :: Bool) :: Maybe [Type] where InterestingUnless ch a seen a _ = 'Nothing InterestingUnless ch a seen t 'True = 'Just seen InterestingUnless ch a seen t 'False = Defined_list (Children ch t) (NoChildren ch t) (Interesting' ch a (t ': seen) (Children ch t)) type family InterestingOr (ch :: Type) (a :: Type) (seen' :: Maybe [Type]) (ts :: [Type]) :: Maybe [Type] where InterestingOr ch a 'Nothing _ = 'Nothing InterestingOr ch a ('Just seen) ts = Interesting' ch a seen ts type family Elem a as where Elem a (a ': _) = 'True Elem a (_ ': as) = Elem a as Elem a '[] = 'False type family IsNothing a where IsNothing ('Just _) = 'False IsNothing 'Nothing = 'True HasTypes class HasTypes s a where types_ :: Traversal' s a types_ _ = pure instance ( HasTypesUsing ChGeneric s s a a ) => HasTypes s a where types_ = typesUsing_ @ChGeneric data Void types_ _ = pure types_ _ = pure typesUsing_ _ = pure typesUsing_ _ = pure | @since 1.2.0.0 class HasTypesUsing (ch :: Type) s t a b where typesUsing_ :: Traversal s t a b ( HasTypesOpt ch (Interesting ch a s) s t a b ) => HasTypesUsing ch s t a b where typesUsing_ = typesOpt @ch @(Interesting ch a s) # INLINE typesUsing _ # typesUsing_ = id @since 1.2.0.0 class HasTypesCustom (ch :: Type) s t a b where typesCustom :: Traversal s t a b ( GHasTypes ch (Rep s) (Rep t) a b , Generic s , Generic t if there 's no Generic instance here , it means we got through the Therefore , we can ignore the missing Generic instance , and , Defined (Rep s) (PrettyError '[ 'Text "No instance " ':<>: QuoteType (HasTypesCustom ch s t a b)]) (() :: Constraint) ) => HasTypesCustom ch s t a b where typesCustom f s = to <$> gtypes_ @ch f (from s) class HasTypesOpt (ch :: Type) (p :: Bool) s t a b where typesOpt :: Traversal s t a b instance HasTypesCustom ch s t a b => HasTypesOpt ch 'True s t a b where typesOpt = typesCustom @ch instance HasTypesOpt ch 'False s s a b where typesOpt _ = pure class GHasTypes ch s t a b where gtypes_ :: Traversal (s x) (t x) a b instance ( GHasTypes ch l l' a b , GHasTypes ch r r' a b ) => GHasTypes ch (l :*: r) (l' :*: r') a b where gtypes_ f (l :*: r) = (:*:) <$> gtypes_ @ch f l <*> gtypes_ @ch f r instance ( GHasTypes ch l l' a b , GHasTypes ch r r' a b ) => GHasTypes ch (l :+: r) (l' :+: r') a b where gtypes_ f (L1 l) = L1 <$> gtypes_ @ch f l gtypes_ f (R1 r) = R1 <$> gtypes_ @ch f r instance GHasTypes ch s t a b => GHasTypes ch (M1 m meta s) (M1 m meta t) a b where gtypes_ f (M1 s) = M1 <$> gtypes_ @ch f s This instance is marked INCOHERENT , because # INCOHERENT # gtypes_ f (K1 x) = K1 <$> typesUsing_ @ch f x | The default instance for ' HasTypes ' acts as a synonym for ' HasTypesUsing ' , so in most cases this instance should ' HasTypes ' directly , in which case we want to prefer those gtypes_ f (K1 x) = K1 <$> types_ @b @a f x instance GHasTypes ch U1 U1 a b where gtypes_ _ _ = pure U1 instance GHasTypes ch V1 V1 a b where gtypes_ _ = pure
17122f1c2917d2c595ef37adbadd7a86ad278cbda19d82f962166e96fac7e8ae
pfeodrippe/orchardia
info.clj
(ns nrepl.middleware.info ;; originally cider.nrepl.middleware.info (:require [clojure.string :as str] [orchard.eldoc :as eldoc] [orchard.info :as clj-info] [orchard.misc :as u])) (defn info [{:keys [ns symbol class member] :as msg}] (let [[ns symbol class member] (map u/as-sym [ns symbol class member])] (let [var-info (cond (and ns symbol) (clj-info/info ns symbol) (and class member) (clj-info/info-clr class member) :else (throw (Exception. "Either \"symbol\", or (\"class\", \"member\") must be supplied"))) ;; we have to use the resolved (real) namespace and name here see-also [] #_(clj-info/see-also (:ns var-info) (:name var-info))] (if (seq see-also) (merge {:see-also see-also} var-info) var-info)))) (defn eldoc-reply [msg] (if-let [info (info msg)] (eldoc/eldoc info) {:status :no-eldoc}))
null
https://raw.githubusercontent.com/pfeodrippe/orchardia/42cb2b663f59e3ee314e3e2fe128407162a0183a/src/nrepl/middleware/info.clj
clojure
originally cider.nrepl.middleware.info we have to use the resolved (real) namespace and name here
(:require [clojure.string :as str] [orchard.eldoc :as eldoc] [orchard.info :as clj-info] [orchard.misc :as u])) (defn info [{:keys [ns symbol class member] :as msg}] (let [[ns symbol class member] (map u/as-sym [ns symbol class member])] (let [var-info (cond (and ns symbol) (clj-info/info ns symbol) (and class member) (clj-info/info-clr class member) :else (throw (Exception. "Either \"symbol\", or (\"class\", \"member\") must be supplied"))) see-also [] #_(clj-info/see-also (:ns var-info) (:name var-info))] (if (seq see-also) (merge {:see-also see-also} var-info) var-info)))) (defn eldoc-reply [msg] (if-let [info (info msg)] (eldoc/eldoc info) {:status :no-eldoc}))
1d8a439b4b62c1683a6117194b6c631ea457e0690d636a6d730f32653ddf9869
twosigma/waiter
spnego.clj
;; Copyright ( c ) Two Sigma Open Source , LLC ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns token-syncer.spnego (:require [clojure.tools.logging :as log]) (:import (java.net URI) (org.apache.commons.codec.binary Base64) (org.eclipse.jetty.client.api Authentication$Result Request) (org.eclipse.jetty.http HttpHeader) (org.ietf.jgss GSSContext GSSManager GSSName Oid))) (def ^Oid spnego-oid (Oid. "1.3.6.1.5.5.2")) (def ^Base64 base64 (Base64.)) (defn spnego-authentication "Returns an Authentication$Result for endpoint which will use SPNEGO to generate an Authorization header" [^URI endpoint] (reify Authentication$Result (getURI [_] endpoint) (^void apply [_ ^Request request] (try (let [gss-manager (GSSManager/getInstance) server-princ (str "HTTP@" (.getHost endpoint)) server-name (.createName gss-manager server-princ GSSName/NT_HOSTBASED_SERVICE spnego-oid) gss-context (.createContext gss-manager server-name spnego-oid nil GSSContext/DEFAULT_LIFETIME) _ (.requestMutualAuth gss-context true) token (.initSecContext gss-context (make-array Byte/TYPE 0) 0 0) header (str "Negotiate " (String. (.encode base64 token)))] (.header request HttpHeader/AUTHORIZATION header)) (catch Exception e (log/error e "failure during spnego authentication"))))))
null
https://raw.githubusercontent.com/twosigma/waiter/8d3cdaed90078c188095ae1e65714edc72f9122c/token-syncer/src/token_syncer/spnego.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright ( c ) Two Sigma Open Source , LLC distributed under the License is distributed on an " AS IS " BASIS , (ns token-syncer.spnego (:require [clojure.tools.logging :as log]) (:import (java.net URI) (org.apache.commons.codec.binary Base64) (org.eclipse.jetty.client.api Authentication$Result Request) (org.eclipse.jetty.http HttpHeader) (org.ietf.jgss GSSContext GSSManager GSSName Oid))) (def ^Oid spnego-oid (Oid. "1.3.6.1.5.5.2")) (def ^Base64 base64 (Base64.)) (defn spnego-authentication "Returns an Authentication$Result for endpoint which will use SPNEGO to generate an Authorization header" [^URI endpoint] (reify Authentication$Result (getURI [_] endpoint) (^void apply [_ ^Request request] (try (let [gss-manager (GSSManager/getInstance) server-princ (str "HTTP@" (.getHost endpoint)) server-name (.createName gss-manager server-princ GSSName/NT_HOSTBASED_SERVICE spnego-oid) gss-context (.createContext gss-manager server-name spnego-oid nil GSSContext/DEFAULT_LIFETIME) _ (.requestMutualAuth gss-context true) token (.initSecContext gss-context (make-array Byte/TYPE 0) 0 0) header (str "Negotiate " (String. (.encode base64 token)))] (.header request HttpHeader/AUTHORIZATION header)) (catch Exception e (log/error e "failure during spnego authentication"))))))
05c234ee42e01ef74350bb229bb8a2b197b73df0f8ae6c37c6cf0b2c5e8b951a
jmfirth/cljs-react-bootstrap
config.cljs
(ns cljs-react-bootstrap.config) (def debug? ^boolean js/goog.DEBUG) (when debug? (enable-console-print!))
null
https://raw.githubusercontent.com/jmfirth/cljs-react-bootstrap/4ef8383b7c6786f7093eb3a10f6983666c632ae2/src/cljs/cljs-react-bootstrap/config.cljs
clojure
(ns cljs-react-bootstrap.config) (def debug? ^boolean js/goog.DEBUG) (when debug? (enable-console-print!))
dbbc3c83545ce39488e965ab515a166ccd56375cb0c9e15819aa23e6b350403a
clj-commons/rewrite-clj
test_clj.clj
#!/usr/bin/env bb (ns test-clj (:require [helper.main :as main] [helper.shell :as shell] [lread.status-line :as status])) (def allowed-clojure-versions '("1.8" "1.9" "1.10" "1.11")) (defn run-unit-tests [clojure-version] (status/line :head (str "testing clojure source against clojure v" clojure-version)) (if (= "1.8" clojure-version) (shell/command "clojure" (str "-M:test-common:clj-test-runner:" clojure-version)) (shell/command "clojure" (str "-M:test-common:kaocha:" clojure-version) "--reporter" "documentation"))) (defn run-isolated-tests[clojure-version] (status/line :head (str "running isolated tests against clojure v" clojure-version)) (if (= "1.8" clojure-version) (shell/command "clojure" (str "-M:clj-test-runner:test-isolated:" clojure-version) "--dir" "test-isolated") (shell/command "clojure" (str "-M:kaocha:" clojure-version) "--profile" "test-isolated" "--reporter" "documentation"))) (def args-usage "Valid args: [options] Options: -v, --clojure-version VERSION Test with Clojure [1.8, 1.9, 1.10, 1.11] [default: 1.8] --help Show this help") (defn -main [& args] (when-let [opts (main/doc-arg-opt args-usage args)] (let [clojure-version (get opts "--clojure-version")] (if (not (some #{clojure-version} allowed-clojure-versions)) (status/die 1 args-usage) (do (run-unit-tests clojure-version) (run-isolated-tests clojure-version))))) nil) (main/when-invoked-as-script (apply -main *command-line-args*))
null
https://raw.githubusercontent.com/clj-commons/rewrite-clj/b879fe8cf7fe782929e896123e6b53ebd87d0bfe/script/test_clj.clj
clojure
#!/usr/bin/env bb (ns test-clj (:require [helper.main :as main] [helper.shell :as shell] [lread.status-line :as status])) (def allowed-clojure-versions '("1.8" "1.9" "1.10" "1.11")) (defn run-unit-tests [clojure-version] (status/line :head (str "testing clojure source against clojure v" clojure-version)) (if (= "1.8" clojure-version) (shell/command "clojure" (str "-M:test-common:clj-test-runner:" clojure-version)) (shell/command "clojure" (str "-M:test-common:kaocha:" clojure-version) "--reporter" "documentation"))) (defn run-isolated-tests[clojure-version] (status/line :head (str "running isolated tests against clojure v" clojure-version)) (if (= "1.8" clojure-version) (shell/command "clojure" (str "-M:clj-test-runner:test-isolated:" clojure-version) "--dir" "test-isolated") (shell/command "clojure" (str "-M:kaocha:" clojure-version) "--profile" "test-isolated" "--reporter" "documentation"))) (def args-usage "Valid args: [options] Options: -v, --clojure-version VERSION Test with Clojure [1.8, 1.9, 1.10, 1.11] [default: 1.8] --help Show this help") (defn -main [& args] (when-let [opts (main/doc-arg-opt args-usage args)] (let [clojure-version (get opts "--clojure-version")] (if (not (some #{clojure-version} allowed-clojure-versions)) (status/die 1 args-usage) (do (run-unit-tests clojure-version) (run-isolated-tests clojure-version))))) nil) (main/when-invoked-as-script (apply -main *command-line-args*))
89394b1263f374aa0bc0215c036050061bd6e18683d603d94191efb3ab953600
scull7/bs-sql-common
SqlCommon_sql.ml
let commentsRe = [%re {|/(\/\*[\s\S]*?\*\/)|([^#:]|^)#.*$|(COMMENT ".*(.*)")/gmi|}] let inRe = [%re "/\\bin\\b/i"] let contains_in sql = Js.String.replaceByRe commentsRe "" sql |> Js.String.trim |. Js.Re.test inRe external format : string -> 'a Js.Array.t -> string = "format" [@@bs.module "sqlstring"]
null
https://raw.githubusercontent.com/scull7/bs-sql-common/803c82d7438e94a55c67951358ee2077521c9341/src/SqlCommon_sql.ml
ocaml
let commentsRe = [%re {|/(\/\*[\s\S]*?\*\/)|([^#:]|^)#.*$|(COMMENT ".*(.*)")/gmi|}] let inRe = [%re "/\\bin\\b/i"] let contains_in sql = Js.String.replaceByRe commentsRe "" sql |> Js.String.trim |. Js.Re.test inRe external format : string -> 'a Js.Array.t -> string = "format" [@@bs.module "sqlstring"]
4cd5802662e403348036a222693f59bf78cff15986da0c3883c995ff4fbbc2e4
matsumonkie/izuna
Type.hs
{- | This module re export common used external types in this project for convenience -} module IzunaBuilder.Type where import qualified Data.Array as Array import qualified Data.ByteString as ByteString import qualified Data.List.NonEmpty as NE import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Text as T import qualified DynFlags as Ghc import qualified HieTypes as Ghc import Numeric.Natural as Natural type ByteString = ByteString.ByteString type HieTypeFlat = Ghc.HieTypeFlat type HieFile = Ghc.HieFile type HieAST = Ghc.HieAST type TypeIndex = Int type PrintedType = String type DynFlags = Ghc.DynFlags type Set = S.Set type NodeIdentifiers = Ghc.NodeIdentifiers String type Text = T.Text type Map = M.Map type Nat = Natural.Natural type NonEmpty = NE.NonEmpty type Array = Array.Array data GhcVersion data Username data Repo data Commit data CommitId data ProjectRoot
null
https://raw.githubusercontent.com/matsumonkie/izuna/b21915617c4e3bb7d14d75814f72b8258689fb9b/izuna-builder/src/IzunaBuilder/Type.hs
haskell
| This module re export common used external types in this project for convenience
module IzunaBuilder.Type where import qualified Data.Array as Array import qualified Data.ByteString as ByteString import qualified Data.List.NonEmpty as NE import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Text as T import qualified DynFlags as Ghc import qualified HieTypes as Ghc import Numeric.Natural as Natural type ByteString = ByteString.ByteString type HieTypeFlat = Ghc.HieTypeFlat type HieFile = Ghc.HieFile type HieAST = Ghc.HieAST type TypeIndex = Int type PrintedType = String type DynFlags = Ghc.DynFlags type Set = S.Set type NodeIdentifiers = Ghc.NodeIdentifiers String type Text = T.Text type Map = M.Map type Nat = Natural.Natural type NonEmpty = NE.NonEmpty type Array = Array.Array data GhcVersion data Username data Repo data Commit data CommitId data ProjectRoot
3ec45d378cdad5ebfd5aadd822550461636a313b2d747d033d2f257ae6875157
puppetlabs/puppetdb
anonymizer_test.clj
(ns puppetlabs.puppetdb.anonymizer-test (:require [clojure.test :refer :all] [puppetlabs.puppetdb.anonymizer :as anon :refer [anonymize-aliases anonymize-catalog anonymize-catalog-inputs-input anonymize-catalog-inputs-inputs anonymize-catalog-resource anonymize-catalog-resources anonymize-edge anonymize-edges anonymize-event anonymize-fact-values anonymize-leaf anonymize-leaf-memoize anonymize-leaf-value anonymize-lowercase-type anonymize-parameter anonymize-parameters anonymize-reference anonymize-references anonymize-report-resource anonymize-tags capitalize-resource-type matcher-match? pattern->regexp pattern-string? rule-match? rules-match]] [puppetlabs.kitchensink.core :as ks])) (def anon-true {"context" {} "anonymize" true}) (def anon-false {"context" {} "anonymize" false}) (deftest test-pattern-string? (testing "should return true if pattern" (is (pattern-string? "/asdf/"))) (testing "should return false if not" (is (not (pattern-string? "asdf"))))) (deftest test-pattern->regexp (testing "should convert a string of /asdf/ to regexp" (is (re-find (pattern->regexp "/asdf/") "asdf")))) (deftest test-matcher-match? (testing "test it matches with a regexp" (is (true? (matcher-match? "/foo/" "foobarbaz")))) (testing "test it does not match with a regexp" (is (false? (matcher-match? "/barry/" "foobarbaz")))) (testing "test it does not match with a regexp if value is nil" (is (false? (matcher-match? "/barry/" nil)))) (testing "test it matches with an array of regexp" (is (true? (matcher-match? ["/foo/" "/something/"] "foobarbaz")))) (testing "test it does not match with an array of regexp" (is (false? (matcher-match? ["/barry/" "/suzan/"] "foobarbaz")))) (testing "test it matches with an exact string" (is (true? (matcher-match? "foobarbaz" "foobarbaz")))) (testing "test it does not matches with an exact string" (is (false? (matcher-match? "barry" "foobarbaz")))) (testing "test it matches with an array of strings" (is (true? (matcher-match? ["foo" "bar" "baz"] "bar")))) (testing "test it does not match with an array of strings" (is (false? (matcher-match? ["foo" "bar" "baz"] "barry")))) (testing "test it matches with an array of mixed strings and regexps" (is (true? (matcher-match? ["foo" "/bar/" "baz"] "bar"))) (is (true? (matcher-match? ["foo" "bar" "/baz/"] "bar"))))) (deftest test-rule-match? (testing "no context in rule should match anything" (let [rule {"context" {} "anonymize" true} context {"node" "foo" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context))))) (testing "match against node should match" (let [rule {"context" {"node" "foo"} "anonymize" true} context {"node" "foo" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context))))) (testing "match against node with array should match" (let [rule {"context" {"node" ["foobarbaz", "baz"]} "anonymize" true} context {"node" "foobarbaz" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context))))) (testing "match against element not in context should not match" (let [rule {"context" {"type" "User"} "anonymize" true} context {"node" "foobarbaz"}] (is (false? (rule-match? rule context))))) (testing "rule with incorrect value should not match" (let [rule {"context" {"type" "User"} "anonymize" true} context {"node" "foobarbaz" "type" "File"}] (is (false? (rule-match? rule context))))) (testing "match against node with regexp should match" (let [rule {"context" {"node" "/bar/"} "anonymize" true} context {"node" "foobarbaz" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context)))))) (deftest test-rules-match (testing "ensure we match on the first rule block" (let [rules [{"context" {"node" "/forge/"} "anonymize" true} {"context" {"node" "/puppetlabs/"} "anonymize" false} {"context" {} "anonymize" true}] context {"node" "forge.puppetlabs.com"}] (is (true? (rules-match rules context))))) (testing "ensure we match on the second rule block" (let [rules [{"context" {"node" "/forge/"} "anonymize" true} {"context" {"node" "/puppetlabs/"} "anonymize" false} {"context" {} "anonymize" true}] context {"node" "heyjude.puppetlabs.com"}] (is (false? (rules-match rules context))))) (testing "ensure we work with the default trailing rule" (let [rules [{"context" {"node" "/forge/"} "anonymize" false} {"context" {"node" "/puppetlabs/"} "anonymize" false} {"context" {} "anonymize" true}] context {"node" "myhost.mynode.com"}] (is (true? (rules-match rules context)))))) (deftest test-anonymize-leaf-node (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :node "test string") (anonymize-leaf-memoize :node "test string")))) (testing "should return a string 30 characters long" (is (string? (anonymize-leaf-memoize :node "good old string"))) (is (= 30 (count (anonymize-leaf-memoize :node "good old string")))))) (deftest test-anonymize-leaf-type (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :type "test string") (anonymize-leaf-memoize :type "test string")))) (testing "should return a string 10 characters long" (is (string? (anonymize-leaf-memoize :type "good old string"))) (is (= 10 (count (anonymize-leaf-memoize :type "good old string")))))) (deftest test-anonymize-leaf-title (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :title "test string") (anonymize-leaf-memoize :title "test string")))) (testing "should return a string 15 characters long" (is (string? (anonymize-leaf-memoize :title "good old string"))) (is (= 15 (count (anonymize-leaf-memoize :title "good old string")))))) (deftest test-anonymize-leaf-parameter-name (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :parameter-name "test string") (anonymize-leaf-memoize :parameter-name "test string")))) (testing "should return a string of equal length" (is (string? (anonymize-leaf-memoize :parameter-name "good old string!"))) (is (= 16 (count (anonymize-leaf-memoize :parameter-name "good old string!")))))) (deftest anonymize-fact-value (testing "identical paths with different values should be memoized" (let [facts1 {:b {:baz 3000}} facts2 {:b {:baz 2000}} anon1 (anonymize-fact-values facts1 {} {}) anon2 (anonymize-fact-values facts2 {} {})] (is (= (keys anon1) (keys anon2))) (is (= (keys (first (vals anon1))) (keys (first (vals anon2))))) (is (not= anon1 anon2))))) (deftest test-anonymize-leaf-value (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :parameter-value "test string") (anonymize-leaf-memoize :parameter-value "test string")))) (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :fact-value {"a" "b"}) (anonymize-leaf-memoize :fact-value {"a" "b"})))) (testing "should return a string of equal length when passed a string >= 10" (is (= 15 (count (anonymize-leaf-value "good old string")))) (is (string? (anonymize-leaf-value "some string")))) (testing "should return a string of length 10 when passed a string < 10" (is (= 10 (count (anonymize-leaf-value "hello"))))) (testing "should return a boolean when passed a boolean" (is (boolean? (anonymize-leaf-value true)))) (testing "should return an integer when passed an integer" (is (integer? (anonymize-leaf-value 100)))) (testing "should return an float when passed an float" (is (float? (anonymize-leaf-value 3.14)))) (testing "should return a map when passed a map" (is (map? (anonymize-leaf-value {"foo" "bar"})))) (testing "maps should retain their child types" (let [mymap {"a" {"b" 1} "c" 3.14 "d" [1 2] "e" 3}] (is (= (sort (map (comp str type) mymap)) (sort (map (comp str type) (anonymize-leaf-value mymap)))))))) (deftest test-anonymize-leaf-message (testing "should return a string of equal length" (is (string? (anonymize-leaf-memoize :message "good old string"))) (is (= 15 (count (anonymize-leaf-memoize :message "good old string")))) (is (= "???????????????" (anonymize-leaf-memoize :text "good old string"))) (is (= 15 (count (anonymize-leaf-memoize :text "good old string")))))) (deftest test-memoized-vector-elements (testing "should memoize individual vector elements" (is (= (take 2 (anonymize-leaf-memoize :fact-value [1 2 3])) (take 2 (anonymize-leaf-memoize :fact-value [1 2 10])))))) (deftest test-anonymize-leaf-file (testing "should return a string 54 characters long" (is (string? (anonymize-leaf-memoize :file "good old string"))) (is (= 54 (count (anonymize-leaf-memoize :file "good old string"))))) (testing "starting with a /etc/puppet/modules ending in .pp" (is (re-find #"^/etc/puppet/modules/.+/manifests/.+\.pp$" (anonymize-leaf-memoize :file "good old string"))))) (deftest test-anonymize-leaf-line (testing "should return a number" (is (integer? (anonymize-leaf-memoize :line 10))))) (deftest test-anonymize-leaf-transaction-uuid (testing "should return a string 36 characters long" (is (string? (anonymize-leaf-memoize :transaction_uuid "0fc3241f-35f7-43c8-bcbb-d79fb626be3f"))) (is (= 36 (count (anonymize-leaf-memoize :transaction_uuid "0fc3241f-35f7-43c8-bcbb-d79fb626be3f"))))) (testing "should not return the input string" (is (not (= "0fc3241f-35f7-43c8-bcbb-d79fb626be3f" (anonymize-leaf-memoize :transaction_uuid "0fc3241f-35f7-43c8-bcbb-d79fb626be3f")))))) (deftest test-anonymize-leaf (testing "should return a random string when type 'node' and rule returns true" (let [anon-config {"rules" {"node" [anon-true]}}] (is (string? (anonymize-leaf "mynode" :node {} anon-config))) (is (not (= "mynode" (anonymize-leaf "mynode" :node {} anon-config)))))) (testing "should not return a random string when type 'node' and rule returns false" (let [anon-config {"rules" {"node" [anon-false]}}] (is (string? (anonymize-leaf "mynode" :node {} anon-config))) (is (= "mynode" (anonymize-leaf "mynode" :node {} anon-config))))) (testing "should not return a random string when type 'node' and rule returns false" (let [anon-config {"rules" {"node" [{"context" {"node" "mynode"} "anonymize" false}]}}] (is (string? (anonymize-leaf "mynode" :node {"node" "mynode"} anon-config))) (is (= "mynode" (anonymize-leaf "mynode" :node {"node" "mynode"} anon-config))))) (testing "should anonymize by default when there is no rule match" (let [anon-config {}] (is (string? (anonymize-leaf "mynode" :node {} anon-config))) (is (not (= "mynode" (anonymize-leaf "mynode" :node {} anon-config))))))) (deftest test-anonymize-reference (testing "should anonymize both type and title based on rule" (let [anon-config {"rules" {"type" [anon-true] "title" [anon-true]}} result (anonymize-reference "File[/etc/foo]" {} anon-config)] (is (string? result)) (is (re-find #"^[A-Z][a-z]+\[.+\]$" result)))) (testing "should anonymize just the title if rule specifies" (let [anon-config {"rules" {"type" [anon-false] "title" [anon-true]}} result (anonymize-reference "File[/etc/foo]" {} anon-config)] (is (string? result)) (is (re-find #"^File\[.+\]$" result))))) (deftest test-anonymize-references (testing "should return a collection when passed a colection" (is (coll? (anonymize-references ["File[/etc/foo]" "Host[localhost]"] {} {})))) (testing "should return a string when passed a single string" (is (string? (anonymize-references "File[/etc/foo]" {} {}))))) (deftest test-anonymize-aliases (testing "should return a collection when passed a colection" (is (coll? (anonymize-aliases ["test1" "test2"] {} {})))) (testing "should return a string when passed a single string" (is (string? (anonymize-aliases "test1" {} {}))))) (deftest test-anonymizer-parameter (testing "should return a collection of 2" (is (coll? (anonymize-parameter ["param" "value"] {} {}))) (is (= 2 (count (anonymize-parameter ["param" "value"] {} {})))))) (deftest test-anonymizer-parameters (testing "should return a collection of the same length" (let [input {"param1" "value", "param2" "value"} result (anonymize-parameters input {} {})] (is (map? result)) (is (= 2 (count result))) (is (not (= input result)))))) (deftest test-anonymize-catalog-inputs-input (testing "should return a collection of 2" (is (coll? (anonymize-catalog-inputs-input ["type" "value"] {} {}))) (is (= 2 (count (anonymize-catalog-inputs-input ["type" "value"] {} {})))))) (deftest test-anonymize-catalog-inputs-inputs (testing "should return a collection of the same length" (let [input [["type1" "val1"] ["type2" "val2"]] result (anonymize-catalog-inputs-inputs input {} {})] (is (vector? result)) (is (= 2 (count result))) (is (not (= input result)))))) (deftest test-capitalize-resource-type (testing "should change a resource type to upcase format like Foo::Bar" (let [input "foo::bar" result (capitalize-resource-type input)] (is (= "Foo::Bar" result))))) (deftest test-anonymize-tag (testing "should anonymize a tag" (let [input "my::class" result (anonymize-lowercase-type input {} {})] (is (not (= input result))) (is (string? result))))) (deftest test-anonymize-tags (testing "return a collection" (is (coll? (anonymize-tags ["first" "second"] {} {}))) (is (= 2 (count (anonymize-tags ["first" "second"] {} {})))))) (deftest test-anonymize-edge (testing "should return anonymized data" (let [test-edge {"source" {"title" "/etc/ntp.conf" "type" "File"} "target" {"title" "ntp" "type" "Package"} "relationship" "requires"}] (is (map? (anonymize-edge test-edge {} {})))))) (deftest test-anonymize-edges (testing "should handle a collection of edges" (let [test-edge {"source" {"title" "/etc/ntp.conf" "type" "File"} "target" {"title" "ntp" "type" "Package"} "relationship" "requires"}] (is (coll? (anonymize-edges [test-edge] {} {}))) (is (= 1 (count (anonymize-edges [test-edge] {} {}))))))) (deftest test-anonymize-catalog-resource (testing "should handle a resource" (let [test-resource {"parameters" {"ensure" "present"} "exported" true "file" "/etc/puppet/modules/foo/manifests/init.pp" "line" 25000000 "tags" ["package"] "title" "foo" "type" "Package"} result (anonymize-catalog-resource test-resource {} {})] (is (map? result)) (is (= #{"parameters" "exported" "line" "title" "tags" "type" "file"} (ks/keyset result))))) (testing "should handle nil for file and line" (let [test-resource {"parameters" {"ensure" "present"} "exported" true "tags" ["package"] "title" "foo" "type" "Package"} result (anonymize-catalog-resource test-resource {} {})] (is (map? result)) (is (= #{"parameters" "exported" "title" "tags" "type"} (ks/keyset result)))))) (deftest test-anonymize-catalog-resources (testing "should handle a resource" (let [test-resource {"parameters" {"ensure" "present"} "exported" true "file" "/etc/puppet/modules/foo/manifests/init.pp" "line" 25000000 "tags" ["package"] "title" "foo" "type" "Package"} result (first (anonymize-catalog-resources [test-resource] {} {}))] (is (= (ks/keyset test-resource) (ks/keyset result))) (are [k] (not= (get test-resource k) (get result k)) "parameters" "line" "title" "tags" "type" "file")))) (deftest test-anonymize-event (testing "should handle a event" (let [test-event {"status" "noop" "timestamp" "2013-03-04T19:56:34.000Z" "property" "ensure" "message" "Ensure was absent now present" "new_value" "present" "old_value" "absent"} anonymized-event (anonymize-event test-event {} {})] (is (map? anonymized-event)) (is (= (keys test-event) (keys anonymized-event)))))) (deftest test-anonymize-report-resource (testing "should handle a resource event" (let [test-resource {"events" [{"status" "noop" "timestamp" "2013-03-04T19:56:34.000Z" "property" "ensure" "message" "Ensure was absent now present" "new_value" "present" "old_value" "absent"}] "timestamp" "2013-03-04T19:56:34.000Z" "resource_title" "foo" "resource_type" "Package" "skipped" false "file" "/home/user/site.pp" "line" 1 "containment_path" ["Stage[main]" "Foo" "Notify[hi]"]} anonymized-resource (anonymize-report-resource test-resource {} {})] (is (map? anonymized-resource)) (is (= (keys test-resource) (keys anonymized-resource))))) (testing "should handle a resource event with optionals" (let [test-resource {"timestamp" "2013-03-04T19:56:34.000Z" "resource_title" "foo" "events" [] "resource_type" "Package" "skipped" true "file" nil "line" nil "containment_path" nil} anonymized-resource (anonymize-report-resource test-resource {} {})] (is (map? anonymized-resource)) (is (= (keys test-resource) (keys anonymized-resource)))))) (deftest test-anonymize-catalog (testing "should accept basic valid data" (anonymize-catalog {} {"certname" "my.node" "version" "some version" "resources" [] "edges" []})))
null
https://raw.githubusercontent.com/puppetlabs/puppetdb/b3d6d10555561657150fa70b6d1e609fba9c0eda/test/puppetlabs/puppetdb/anonymizer_test.clj
clojure
(ns puppetlabs.puppetdb.anonymizer-test (:require [clojure.test :refer :all] [puppetlabs.puppetdb.anonymizer :as anon :refer [anonymize-aliases anonymize-catalog anonymize-catalog-inputs-input anonymize-catalog-inputs-inputs anonymize-catalog-resource anonymize-catalog-resources anonymize-edge anonymize-edges anonymize-event anonymize-fact-values anonymize-leaf anonymize-leaf-memoize anonymize-leaf-value anonymize-lowercase-type anonymize-parameter anonymize-parameters anonymize-reference anonymize-references anonymize-report-resource anonymize-tags capitalize-resource-type matcher-match? pattern->regexp pattern-string? rule-match? rules-match]] [puppetlabs.kitchensink.core :as ks])) (def anon-true {"context" {} "anonymize" true}) (def anon-false {"context" {} "anonymize" false}) (deftest test-pattern-string? (testing "should return true if pattern" (is (pattern-string? "/asdf/"))) (testing "should return false if not" (is (not (pattern-string? "asdf"))))) (deftest test-pattern->regexp (testing "should convert a string of /asdf/ to regexp" (is (re-find (pattern->regexp "/asdf/") "asdf")))) (deftest test-matcher-match? (testing "test it matches with a regexp" (is (true? (matcher-match? "/foo/" "foobarbaz")))) (testing "test it does not match with a regexp" (is (false? (matcher-match? "/barry/" "foobarbaz")))) (testing "test it does not match with a regexp if value is nil" (is (false? (matcher-match? "/barry/" nil)))) (testing "test it matches with an array of regexp" (is (true? (matcher-match? ["/foo/" "/something/"] "foobarbaz")))) (testing "test it does not match with an array of regexp" (is (false? (matcher-match? ["/barry/" "/suzan/"] "foobarbaz")))) (testing "test it matches with an exact string" (is (true? (matcher-match? "foobarbaz" "foobarbaz")))) (testing "test it does not matches with an exact string" (is (false? (matcher-match? "barry" "foobarbaz")))) (testing "test it matches with an array of strings" (is (true? (matcher-match? ["foo" "bar" "baz"] "bar")))) (testing "test it does not match with an array of strings" (is (false? (matcher-match? ["foo" "bar" "baz"] "barry")))) (testing "test it matches with an array of mixed strings and regexps" (is (true? (matcher-match? ["foo" "/bar/" "baz"] "bar"))) (is (true? (matcher-match? ["foo" "bar" "/baz/"] "bar"))))) (deftest test-rule-match? (testing "no context in rule should match anything" (let [rule {"context" {} "anonymize" true} context {"node" "foo" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context))))) (testing "match against node should match" (let [rule {"context" {"node" "foo"} "anonymize" true} context {"node" "foo" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context))))) (testing "match against node with array should match" (let [rule {"context" {"node" ["foobarbaz", "baz"]} "anonymize" true} context {"node" "foobarbaz" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context))))) (testing "match against element not in context should not match" (let [rule {"context" {"type" "User"} "anonymize" true} context {"node" "foobarbaz"}] (is (false? (rule-match? rule context))))) (testing "rule with incorrect value should not match" (let [rule {"context" {"type" "User"} "anonymize" true} context {"node" "foobarbaz" "type" "File"}] (is (false? (rule-match? rule context))))) (testing "match against node with regexp should match" (let [rule {"context" {"node" "/bar/"} "anonymize" true} context {"node" "foobarbaz" "type" "User" "title" "/tmp/foo"}] (is (true? (rule-match? rule context)))))) (deftest test-rules-match (testing "ensure we match on the first rule block" (let [rules [{"context" {"node" "/forge/"} "anonymize" true} {"context" {"node" "/puppetlabs/"} "anonymize" false} {"context" {} "anonymize" true}] context {"node" "forge.puppetlabs.com"}] (is (true? (rules-match rules context))))) (testing "ensure we match on the second rule block" (let [rules [{"context" {"node" "/forge/"} "anonymize" true} {"context" {"node" "/puppetlabs/"} "anonymize" false} {"context" {} "anonymize" true}] context {"node" "heyjude.puppetlabs.com"}] (is (false? (rules-match rules context))))) (testing "ensure we work with the default trailing rule" (let [rules [{"context" {"node" "/forge/"} "anonymize" false} {"context" {"node" "/puppetlabs/"} "anonymize" false} {"context" {} "anonymize" true}] context {"node" "myhost.mynode.com"}] (is (true? (rules-match rules context)))))) (deftest test-anonymize-leaf-node (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :node "test string") (anonymize-leaf-memoize :node "test string")))) (testing "should return a string 30 characters long" (is (string? (anonymize-leaf-memoize :node "good old string"))) (is (= 30 (count (anonymize-leaf-memoize :node "good old string")))))) (deftest test-anonymize-leaf-type (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :type "test string") (anonymize-leaf-memoize :type "test string")))) (testing "should return a string 10 characters long" (is (string? (anonymize-leaf-memoize :type "good old string"))) (is (= 10 (count (anonymize-leaf-memoize :type "good old string")))))) (deftest test-anonymize-leaf-title (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :title "test string") (anonymize-leaf-memoize :title "test string")))) (testing "should return a string 15 characters long" (is (string? (anonymize-leaf-memoize :title "good old string"))) (is (= 15 (count (anonymize-leaf-memoize :title "good old string")))))) (deftest test-anonymize-leaf-parameter-name (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :parameter-name "test string") (anonymize-leaf-memoize :parameter-name "test string")))) (testing "should return a string of equal length" (is (string? (anonymize-leaf-memoize :parameter-name "good old string!"))) (is (= 16 (count (anonymize-leaf-memoize :parameter-name "good old string!")))))) (deftest anonymize-fact-value (testing "identical paths with different values should be memoized" (let [facts1 {:b {:baz 3000}} facts2 {:b {:baz 2000}} anon1 (anonymize-fact-values facts1 {} {}) anon2 (anonymize-fact-values facts2 {} {})] (is (= (keys anon1) (keys anon2))) (is (= (keys (first (vals anon1))) (keys (first (vals anon2))))) (is (not= anon1 anon2))))) (deftest test-anonymize-leaf-value (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :parameter-value "test string") (anonymize-leaf-memoize :parameter-value "test string")))) (testing "should return the same string twice" (is (= (anonymize-leaf-memoize :fact-value {"a" "b"}) (anonymize-leaf-memoize :fact-value {"a" "b"})))) (testing "should return a string of equal length when passed a string >= 10" (is (= 15 (count (anonymize-leaf-value "good old string")))) (is (string? (anonymize-leaf-value "some string")))) (testing "should return a string of length 10 when passed a string < 10" (is (= 10 (count (anonymize-leaf-value "hello"))))) (testing "should return a boolean when passed a boolean" (is (boolean? (anonymize-leaf-value true)))) (testing "should return an integer when passed an integer" (is (integer? (anonymize-leaf-value 100)))) (testing "should return an float when passed an float" (is (float? (anonymize-leaf-value 3.14)))) (testing "should return a map when passed a map" (is (map? (anonymize-leaf-value {"foo" "bar"})))) (testing "maps should retain their child types" (let [mymap {"a" {"b" 1} "c" 3.14 "d" [1 2] "e" 3}] (is (= (sort (map (comp str type) mymap)) (sort (map (comp str type) (anonymize-leaf-value mymap)))))))) (deftest test-anonymize-leaf-message (testing "should return a string of equal length" (is (string? (anonymize-leaf-memoize :message "good old string"))) (is (= 15 (count (anonymize-leaf-memoize :message "good old string")))) (is (= "???????????????" (anonymize-leaf-memoize :text "good old string"))) (is (= 15 (count (anonymize-leaf-memoize :text "good old string")))))) (deftest test-memoized-vector-elements (testing "should memoize individual vector elements" (is (= (take 2 (anonymize-leaf-memoize :fact-value [1 2 3])) (take 2 (anonymize-leaf-memoize :fact-value [1 2 10])))))) (deftest test-anonymize-leaf-file (testing "should return a string 54 characters long" (is (string? (anonymize-leaf-memoize :file "good old string"))) (is (= 54 (count (anonymize-leaf-memoize :file "good old string"))))) (testing "starting with a /etc/puppet/modules ending in .pp" (is (re-find #"^/etc/puppet/modules/.+/manifests/.+\.pp$" (anonymize-leaf-memoize :file "good old string"))))) (deftest test-anonymize-leaf-line (testing "should return a number" (is (integer? (anonymize-leaf-memoize :line 10))))) (deftest test-anonymize-leaf-transaction-uuid (testing "should return a string 36 characters long" (is (string? (anonymize-leaf-memoize :transaction_uuid "0fc3241f-35f7-43c8-bcbb-d79fb626be3f"))) (is (= 36 (count (anonymize-leaf-memoize :transaction_uuid "0fc3241f-35f7-43c8-bcbb-d79fb626be3f"))))) (testing "should not return the input string" (is (not (= "0fc3241f-35f7-43c8-bcbb-d79fb626be3f" (anonymize-leaf-memoize :transaction_uuid "0fc3241f-35f7-43c8-bcbb-d79fb626be3f")))))) (deftest test-anonymize-leaf (testing "should return a random string when type 'node' and rule returns true" (let [anon-config {"rules" {"node" [anon-true]}}] (is (string? (anonymize-leaf "mynode" :node {} anon-config))) (is (not (= "mynode" (anonymize-leaf "mynode" :node {} anon-config)))))) (testing "should not return a random string when type 'node' and rule returns false" (let [anon-config {"rules" {"node" [anon-false]}}] (is (string? (anonymize-leaf "mynode" :node {} anon-config))) (is (= "mynode" (anonymize-leaf "mynode" :node {} anon-config))))) (testing "should not return a random string when type 'node' and rule returns false" (let [anon-config {"rules" {"node" [{"context" {"node" "mynode"} "anonymize" false}]}}] (is (string? (anonymize-leaf "mynode" :node {"node" "mynode"} anon-config))) (is (= "mynode" (anonymize-leaf "mynode" :node {"node" "mynode"} anon-config))))) (testing "should anonymize by default when there is no rule match" (let [anon-config {}] (is (string? (anonymize-leaf "mynode" :node {} anon-config))) (is (not (= "mynode" (anonymize-leaf "mynode" :node {} anon-config))))))) (deftest test-anonymize-reference (testing "should anonymize both type and title based on rule" (let [anon-config {"rules" {"type" [anon-true] "title" [anon-true]}} result (anonymize-reference "File[/etc/foo]" {} anon-config)] (is (string? result)) (is (re-find #"^[A-Z][a-z]+\[.+\]$" result)))) (testing "should anonymize just the title if rule specifies" (let [anon-config {"rules" {"type" [anon-false] "title" [anon-true]}} result (anonymize-reference "File[/etc/foo]" {} anon-config)] (is (string? result)) (is (re-find #"^File\[.+\]$" result))))) (deftest test-anonymize-references (testing "should return a collection when passed a colection" (is (coll? (anonymize-references ["File[/etc/foo]" "Host[localhost]"] {} {})))) (testing "should return a string when passed a single string" (is (string? (anonymize-references "File[/etc/foo]" {} {}))))) (deftest test-anonymize-aliases (testing "should return a collection when passed a colection" (is (coll? (anonymize-aliases ["test1" "test2"] {} {})))) (testing "should return a string when passed a single string" (is (string? (anonymize-aliases "test1" {} {}))))) (deftest test-anonymizer-parameter (testing "should return a collection of 2" (is (coll? (anonymize-parameter ["param" "value"] {} {}))) (is (= 2 (count (anonymize-parameter ["param" "value"] {} {})))))) (deftest test-anonymizer-parameters (testing "should return a collection of the same length" (let [input {"param1" "value", "param2" "value"} result (anonymize-parameters input {} {})] (is (map? result)) (is (= 2 (count result))) (is (not (= input result)))))) (deftest test-anonymize-catalog-inputs-input (testing "should return a collection of 2" (is (coll? (anonymize-catalog-inputs-input ["type" "value"] {} {}))) (is (= 2 (count (anonymize-catalog-inputs-input ["type" "value"] {} {})))))) (deftest test-anonymize-catalog-inputs-inputs (testing "should return a collection of the same length" (let [input [["type1" "val1"] ["type2" "val2"]] result (anonymize-catalog-inputs-inputs input {} {})] (is (vector? result)) (is (= 2 (count result))) (is (not (= input result)))))) (deftest test-capitalize-resource-type (testing "should change a resource type to upcase format like Foo::Bar" (let [input "foo::bar" result (capitalize-resource-type input)] (is (= "Foo::Bar" result))))) (deftest test-anonymize-tag (testing "should anonymize a tag" (let [input "my::class" result (anonymize-lowercase-type input {} {})] (is (not (= input result))) (is (string? result))))) (deftest test-anonymize-tags (testing "return a collection" (is (coll? (anonymize-tags ["first" "second"] {} {}))) (is (= 2 (count (anonymize-tags ["first" "second"] {} {})))))) (deftest test-anonymize-edge (testing "should return anonymized data" (let [test-edge {"source" {"title" "/etc/ntp.conf" "type" "File"} "target" {"title" "ntp" "type" "Package"} "relationship" "requires"}] (is (map? (anonymize-edge test-edge {} {})))))) (deftest test-anonymize-edges (testing "should handle a collection of edges" (let [test-edge {"source" {"title" "/etc/ntp.conf" "type" "File"} "target" {"title" "ntp" "type" "Package"} "relationship" "requires"}] (is (coll? (anonymize-edges [test-edge] {} {}))) (is (= 1 (count (anonymize-edges [test-edge] {} {}))))))) (deftest test-anonymize-catalog-resource (testing "should handle a resource" (let [test-resource {"parameters" {"ensure" "present"} "exported" true "file" "/etc/puppet/modules/foo/manifests/init.pp" "line" 25000000 "tags" ["package"] "title" "foo" "type" "Package"} result (anonymize-catalog-resource test-resource {} {})] (is (map? result)) (is (= #{"parameters" "exported" "line" "title" "tags" "type" "file"} (ks/keyset result))))) (testing "should handle nil for file and line" (let [test-resource {"parameters" {"ensure" "present"} "exported" true "tags" ["package"] "title" "foo" "type" "Package"} result (anonymize-catalog-resource test-resource {} {})] (is (map? result)) (is (= #{"parameters" "exported" "title" "tags" "type"} (ks/keyset result)))))) (deftest test-anonymize-catalog-resources (testing "should handle a resource" (let [test-resource {"parameters" {"ensure" "present"} "exported" true "file" "/etc/puppet/modules/foo/manifests/init.pp" "line" 25000000 "tags" ["package"] "title" "foo" "type" "Package"} result (first (anonymize-catalog-resources [test-resource] {} {}))] (is (= (ks/keyset test-resource) (ks/keyset result))) (are [k] (not= (get test-resource k) (get result k)) "parameters" "line" "title" "tags" "type" "file")))) (deftest test-anonymize-event (testing "should handle a event" (let [test-event {"status" "noop" "timestamp" "2013-03-04T19:56:34.000Z" "property" "ensure" "message" "Ensure was absent now present" "new_value" "present" "old_value" "absent"} anonymized-event (anonymize-event test-event {} {})] (is (map? anonymized-event)) (is (= (keys test-event) (keys anonymized-event)))))) (deftest test-anonymize-report-resource (testing "should handle a resource event" (let [test-resource {"events" [{"status" "noop" "timestamp" "2013-03-04T19:56:34.000Z" "property" "ensure" "message" "Ensure was absent now present" "new_value" "present" "old_value" "absent"}] "timestamp" "2013-03-04T19:56:34.000Z" "resource_title" "foo" "resource_type" "Package" "skipped" false "file" "/home/user/site.pp" "line" 1 "containment_path" ["Stage[main]" "Foo" "Notify[hi]"]} anonymized-resource (anonymize-report-resource test-resource {} {})] (is (map? anonymized-resource)) (is (= (keys test-resource) (keys anonymized-resource))))) (testing "should handle a resource event with optionals" (let [test-resource {"timestamp" "2013-03-04T19:56:34.000Z" "resource_title" "foo" "events" [] "resource_type" "Package" "skipped" true "file" nil "line" nil "containment_path" nil} anonymized-resource (anonymize-report-resource test-resource {} {})] (is (map? anonymized-resource)) (is (= (keys test-resource) (keys anonymized-resource)))))) (deftest test-anonymize-catalog (testing "should accept basic valid data" (anonymize-catalog {} {"certname" "my.node" "version" "some version" "resources" [] "edges" []})))
e4ff1cfa068caada4a3c3e181e27352d8534ec75fb187722a2d7b82d286a69a4
jfischoff/hasql-queue
AtMostOnceSpec.hs
module Hasql.Queue.High.AtMostOnceSpec where import Hasql.Queue.High.AtMostOnce import qualified Hasql.Encoders as E import qualified Hasql.Decoders as D import Test.Hspec (Spec, describe, parallel, it) import Test.Hspec.Expectations.Lifted import Test.Hspec.Core.Spec (sequential) import Hasql.Queue.TestUtils spec :: Spec spec = describe "Hasql.Queue.High.AtMostOnce" $ parallel $ do sequential $ aroundAll withSetup $ describe "enqueue/dequeue" $ do it "enqueue nothing gives nothing" $ withConnection $ \conn -> do enqueue conn E.int4 [] dequeue conn D.int4 1 `shouldReturn` [] it "enqueue 1 gives 1" $ withConnection $ \conn -> do enqueue conn E.int4 [1] dequeue conn D.int4 1 `shouldReturn` [1] it "dequeue give nothing after enqueueing everything" $ withConnection $ \conn -> do dequeue conn D.int4 1 `shouldReturn` [] it "dequeueing is in FIFO order" $ withConnection $ \conn -> do enqueue conn E.int4 [1] enqueue conn E.int4 [2] dequeue conn D.int4 1 `shouldReturn` [1] dequeue conn D.int4 1 `shouldReturn` [2] it "dequeueing a batch of elements works" $ withConnection $ \conn -> do enqueue conn E.int4 [1, 2, 3] dequeue conn D.int4 2 `shouldReturn` [1, 2] dequeue conn D.int4 2 `shouldReturn` [3]
null
https://raw.githubusercontent.com/jfischoff/hasql-queue/49f4cba713bedf6ce907cc89794f2567befed396/test/Hasql/Queue/High/AtMostOnceSpec.hs
haskell
module Hasql.Queue.High.AtMostOnceSpec where import Hasql.Queue.High.AtMostOnce import qualified Hasql.Encoders as E import qualified Hasql.Decoders as D import Test.Hspec (Spec, describe, parallel, it) import Test.Hspec.Expectations.Lifted import Test.Hspec.Core.Spec (sequential) import Hasql.Queue.TestUtils spec :: Spec spec = describe "Hasql.Queue.High.AtMostOnce" $ parallel $ do sequential $ aroundAll withSetup $ describe "enqueue/dequeue" $ do it "enqueue nothing gives nothing" $ withConnection $ \conn -> do enqueue conn E.int4 [] dequeue conn D.int4 1 `shouldReturn` [] it "enqueue 1 gives 1" $ withConnection $ \conn -> do enqueue conn E.int4 [1] dequeue conn D.int4 1 `shouldReturn` [1] it "dequeue give nothing after enqueueing everything" $ withConnection $ \conn -> do dequeue conn D.int4 1 `shouldReturn` [] it "dequeueing is in FIFO order" $ withConnection $ \conn -> do enqueue conn E.int4 [1] enqueue conn E.int4 [2] dequeue conn D.int4 1 `shouldReturn` [1] dequeue conn D.int4 1 `shouldReturn` [2] it "dequeueing a batch of elements works" $ withConnection $ \conn -> do enqueue conn E.int4 [1, 2, 3] dequeue conn D.int4 2 `shouldReturn` [1, 2] dequeue conn D.int4 2 `shouldReturn` [3]
ef1fcb1b1b31f6aa395adebb628ab3ae37242cc6894a377e6f1a8262c8639449
formal-land/coq-of-ocaml
interface.mli
type t val foo : t type ('a, 'b) arg val x : 'a -> 'b -> ('a, 'b) arg module M : sig type 'a l = | Nil | Cons of 'a * 'a l val b : bool end
null
https://raw.githubusercontent.com/formal-land/coq-of-ocaml/c9c86b08eb19d7fd023f48029cc5f9bf53f6a11c/tests/interface.mli
ocaml
type t val foo : t type ('a, 'b) arg val x : 'a -> 'b -> ('a, 'b) arg module M : sig type 'a l = | Nil | Cons of 'a * 'a l val b : bool end
48b4d024a4cab0d6806976ce080c9e8f4edf4ed8dbff477147db88d30859c676
zenhack/mule
build_js.ml
open Common_ast module DC = Desugared_ast_common module DT = Desugared_ast_type ` import " ffi / js".main ` : The type the entry point must let js_main_type = DT.Path { p_info = `Type; p_var = `Import (DC.import_abs `Generated "ffi/js"); p_src = `Generated; p_lbls = [Label.of_string "main"]; } let build src dest = let dest = match dest with | Some d -> d | None -> src ^ ".js" in let loader = Load.new_loader () in let Load.{var = main_var; _} = Load.load_file loader ~base_path:src ~export:true (* Arbitrary, since we don't use the type directly. *) ~types:(if Config.no_js_type_requirement () then [] else [(`Main, js_main_type)] ) in let files = Load.all_files loader |> List.map ~f:(fun (_, Load.{var; js_expr; _}) -> Js_ast.VarDecl(Var.to_string var, Lazy.force js_expr) ) |> Js_ast.stmts in let text = Fmt.(concat [ s "const mule = (() => {"; s Js_runtime_gen.src; s "\n"; files; s "mule.main = () => $exec("; s (Var.to_string main_var); s ", $js, globalThis)\n"; s "return mule\n"; s "})()\n"; s "mule.main();\n" ]) |> Fmt.to_string in Stdio.Out_channel.write_all dest ~data:text
null
https://raw.githubusercontent.com/zenhack/mule/f3e23342906d834abb9659c72a67c1405c936a00/src/mule/lib/build_js.ml
ocaml
Arbitrary, since we don't use the type directly.
open Common_ast module DC = Desugared_ast_common module DT = Desugared_ast_type ` import " ffi / js".main ` : The type the entry point must let js_main_type = DT.Path { p_info = `Type; p_var = `Import (DC.import_abs `Generated "ffi/js"); p_src = `Generated; p_lbls = [Label.of_string "main"]; } let build src dest = let dest = match dest with | Some d -> d | None -> src ^ ".js" in let loader = Load.new_loader () in let Load.{var = main_var; _} = Load.load_file loader ~base_path:src ~types:(if Config.no_js_type_requirement () then [] else [(`Main, js_main_type)] ) in let files = Load.all_files loader |> List.map ~f:(fun (_, Load.{var; js_expr; _}) -> Js_ast.VarDecl(Var.to_string var, Lazy.force js_expr) ) |> Js_ast.stmts in let text = Fmt.(concat [ s "const mule = (() => {"; s Js_runtime_gen.src; s "\n"; files; s "mule.main = () => $exec("; s (Var.to_string main_var); s ", $js, globalThis)\n"; s "return mule\n"; s "})()\n"; s "mule.main();\n" ]) |> Fmt.to_string in Stdio.Out_channel.write_all dest ~data:text
961d16a09426d5102acf6bf2db04d2363f4633da2cac5a96f116c23a9a84f6df
chrisdone/sandbox
proj.hs
# LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # # LANGUAGE DataKinds # # LANGUAGE OverloadedLists # # LANGUAGE LambdaCase # # OPTIONS_GHC -Wall # import Data.List.NonEmpty (NonEmpty(..)) import Data.String newtype Title = Title String deriving (IsString, Show) data CompletionKey = VariableName | OperatorName deriving (Show) newtype Delim = Delim String deriving (Show, IsString) data Tree = Keyword String | IntLit (Maybe Int) | ArbitraryText (Maybe String) | Variable CompletionKey (Maybe String) | Choice Title (NonEmpty Tree) (Maybe Tree) | List Title Tree Delim (Maybe (NonEmpty Tree)) | Composite Title (NonEmpty Tree) (Maybe (NonEmpty Tree)) deriving (Show) data Cursor = InList Int Cursor | InComposite Int Cursor | InChoice Cursor | Here deriving (Show) data Preview = KeywordPreview String | CompletionType String | Choices Title | ListOf Title | CompositePreview Title | IntLitPreview | ArbitraryTextPreview deriving (Show) grammar :: Tree grammar = expr where expr = Choice "expression" [let', app, op, list, tuple, parens, lit] Nothing parens = Composite "(..)" [Keyword "(", expr, Keyword ")"] Nothing let' = Composite "let" [Keyword "let", List "definitions" def ";" Nothing] Nothing def = Composite "definition" [Variable VariableName Nothing, Keyword "=", expr, Keyword "in", expr] Nothing app = Composite "application" [expr, expr] Nothing op = Composite "infix" [expr, Variable OperatorName Nothing, expr] Nothing list = Composite "list" [Keyword "[", List "list" expr "," Nothing, Keyword "]"] Nothing tuple = Composite "tuple" [Keyword "(", List "tuple" expr "," Nothing, Keyword ")"] Nothing lit = Choice "literal" [int, string] Nothing int = IntLit Nothing string = Composite "string" [Keyword "\"", ArbitraryText Nothing, Keyword "\""] Nothing previewTree :: Tree -> Preview previewTree = \case Keyword kw -> KeywordPreview kw Variable completionKey _ -> previewCompletionKey completionKey Choice title _ _ -> Choices title List title _ _ _ -> ListOf title Composite title _ _ -> CompositePreview title IntLit _ -> IntLitPreview ArbitraryText _ -> ArbitraryTextPreview previewCompletionKey :: CompletionKey -> Preview previewCompletionKey = \case VariableName -> CompletionType "variable-name" OperatorName -> CompletionType "operator"
null
https://raw.githubusercontent.com/chrisdone/sandbox/c43975a01119a7c70ffe83c49a629c45f7f2543a/proj.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # # LANGUAGE DataKinds # # LANGUAGE OverloadedLists # # LANGUAGE LambdaCase # # OPTIONS_GHC -Wall # import Data.List.NonEmpty (NonEmpty(..)) import Data.String newtype Title = Title String deriving (IsString, Show) data CompletionKey = VariableName | OperatorName deriving (Show) newtype Delim = Delim String deriving (Show, IsString) data Tree = Keyword String | IntLit (Maybe Int) | ArbitraryText (Maybe String) | Variable CompletionKey (Maybe String) | Choice Title (NonEmpty Tree) (Maybe Tree) | List Title Tree Delim (Maybe (NonEmpty Tree)) | Composite Title (NonEmpty Tree) (Maybe (NonEmpty Tree)) deriving (Show) data Cursor = InList Int Cursor | InComposite Int Cursor | InChoice Cursor | Here deriving (Show) data Preview = KeywordPreview String | CompletionType String | Choices Title | ListOf Title | CompositePreview Title | IntLitPreview | ArbitraryTextPreview deriving (Show) grammar :: Tree grammar = expr where expr = Choice "expression" [let', app, op, list, tuple, parens, lit] Nothing parens = Composite "(..)" [Keyword "(", expr, Keyword ")"] Nothing let' = Composite "let" [Keyword "let", List "definitions" def ";" Nothing] Nothing def = Composite "definition" [Variable VariableName Nothing, Keyword "=", expr, Keyword "in", expr] Nothing app = Composite "application" [expr, expr] Nothing op = Composite "infix" [expr, Variable OperatorName Nothing, expr] Nothing list = Composite "list" [Keyword "[", List "list" expr "," Nothing, Keyword "]"] Nothing tuple = Composite "tuple" [Keyword "(", List "tuple" expr "," Nothing, Keyword ")"] Nothing lit = Choice "literal" [int, string] Nothing int = IntLit Nothing string = Composite "string" [Keyword "\"", ArbitraryText Nothing, Keyword "\""] Nothing previewTree :: Tree -> Preview previewTree = \case Keyword kw -> KeywordPreview kw Variable completionKey _ -> previewCompletionKey completionKey Choice title _ _ -> Choices title List title _ _ _ -> ListOf title Composite title _ _ -> CompositePreview title IntLit _ -> IntLitPreview ArbitraryText _ -> ArbitraryTextPreview previewCompletionKey :: CompletionKey -> Preview previewCompletionKey = \case VariableName -> CompletionType "variable-name" OperatorName -> CompletionType "operator"
2ad93d4401903c0a70004261d4f959e380f24b02618dc059f3b7e643ff1cb472
ptal/AbSolute
transformer.ml
Copyright 2019 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *) open Domains.Abstract_domain open Lang.Ast open Typing.Tast open Core type global_statistics = { start: Mtime_clock.counter; elapsed: Mtime.span; nodes: int; fails: int; sols: int; nodes_before_last_sol: int; prunes: int; depth_max: int; restarts: int; } let init_global_stats () = { start = Mtime_clock.counter (); elapsed = Mtime.Span.zero; nodes=0; fails=0; sols=0; nodes_before_last_sol=0; prunes=0; depth_max=0; restarts=0; } type bt_statistics = { depth: int; } let init_bt_stats () = { depth=0; } module Make(A: Abstract_domain) = struct type bab = { kind: cmpop; objective: (A.I.var_id * vname); best: (A.snapshot * tqformula) option; } type printer = { print_node: (string -> int -> A.t -> unit); print_sol: (A.t -> unit); } type transformer = | Printer of printer | BAB of bab | Timeout of Mtime.span | BoundSolutions of int let make_bab kind objective = BAB { kind; objective; best=None } let minimize_bab = make_bab LT let maximize_bab = make_bab GT type gs = { transformers: transformer list; stats: global_statistics; domain: A.t; } type bs = { snapshot: A.snapshot; bt_stats: bt_statistics } type t = (gs * bs) let init domain transformers = { transformers=transformers; stats=init_global_stats (); domain=domain; },{ snapshot=List.hd (A.lazy_copy domain 1); bt_stats=init_bt_stats (); } let unwrap_best gs = let rec aux = function | [] -> raise Not_found | BAB bab::_ -> begin match bab.best with | Some (_, (TQFFormula (_,TCmp (Var _, _, Cst (best,_))))) -> Some best | Some (_,_) -> failwith "[Transformer.unwrap_best] Best formula is suppose to be formatted as `v <op> best` where best is a constant." | None -> None end | _::l -> aux l in aux gs.transformers exception StopSearch of t exception Backjump of (int * t) let wrap_exception t f = try f t with | Bot.Bot_found -> raise (Backjump (0, t)) | Conflict n -> raise (Backjump (n, t)) let optimize (gs,bs) bab = match bab.best with | None -> (gs,bs) | Some (_,tf) -> wrap_exception (gs,bs) (fun (gs, bs) -> let domain, constraints = A.interpret gs.domain OverApprox tf in let domain = List.fold_left A.weak_incremental_closure domain constraints in ({gs with domain}, bs)) let stop_if t = function | true -> raise (StopSearch t) | false -> t let on_node (gs,bs) = let nodes, depth = gs.stats.nodes+1, bs.bt_stats.depth+1 in let gs:gs = {gs with stats={gs.stats with nodes}} in let bs:bs = {bs with bt_stats={depth}} in let apply (gs,bs) = function | BAB bab -> (optimize (gs,bs) bab) | Timeout timeout -> let elapsed = Mtime_clock.count gs.stats.start in let gs = {gs with stats={gs.stats with elapsed}} in stop_if (gs,bs) ((Mtime.Span.compare timeout elapsed) <= 0) | _ -> gs,bs in List.fold_left apply (gs,bs) gs.transformers let on_fail (gs,bs) = let fails = gs.stats.fails+1 in let gs = {gs with stats={gs.stats with fails}} in let apply (gs,bs) = function | Printer printer -> printer.print_node "false" bs.bt_stats.depth gs.domain; (gs,bs) | _ -> gs,bs in List.fold_left apply (gs,bs) gs.transformers let on_solution (gs,bs) = let sols = gs.stats.sols+1 in let nodes_before_last_sol = gs.stats.nodes in let gs = {gs with stats={gs.stats with sols; nodes_before_last_sol}} in let apply (gs,bs) transformer = match transformer with | BAB bab -> let v = fst bab.objective in let tv = A.I.to_logic_var (A.interpretation gs.domain) v in let (lb,ub) = A.project gs.domain v in let bound = let _ = " new solution : [ % a .. %a]\n " A.B.pp_print lb A.B.pp_print ub in match bab.kind with | LT | LEQ -> lb | GT | GEQ -> ub | _ -> failwith "BAB kind should be < or >." in let bound = Cst (A.B.to_rat bound, Types.to_concrete_ty tv.ty) in let _ = " Solution : [ % a .. %a ] - % d\n " A.B.pp_print lb A.B.pp_print ub gs.stats.nodes ; flush_all ( ) in let tqf = TQFFormula (tv.uid, TCmp (Var (snd bab.objective), bab.kind, bound)) in let a = List.hd (A.lazy_copy gs.domain 1) in (gs,bs), BAB {bab with best=Some(a, tqf)} | Printer printer -> printer.print_sol gs.domain; printer.print_node "true" bs.bt_stats.depth gs.domain; (gs,bs), transformer | BoundSolutions s when s == gs.stats.sols -> raise (StopSearch (gs,bs)) | _ -> (gs,bs), transformer in let (gs,bs), transformers = Tools.fold_map apply (gs,bs) gs.transformers in ({gs with transformers},bs) let on_unknown (gs,bs) = let apply (gs,bs) = function | Printer printer -> printer.print_node "unknown" bs.bt_stats.depth gs.domain; (gs,bs) | _ -> (gs,bs) in List.fold_left apply (gs,bs) gs.transformers end
null
https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/fixpoint/transformer.ml
ocaml
Copyright 2019 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *) open Domains.Abstract_domain open Lang.Ast open Typing.Tast open Core type global_statistics = { start: Mtime_clock.counter; elapsed: Mtime.span; nodes: int; fails: int; sols: int; nodes_before_last_sol: int; prunes: int; depth_max: int; restarts: int; } let init_global_stats () = { start = Mtime_clock.counter (); elapsed = Mtime.Span.zero; nodes=0; fails=0; sols=0; nodes_before_last_sol=0; prunes=0; depth_max=0; restarts=0; } type bt_statistics = { depth: int; } let init_bt_stats () = { depth=0; } module Make(A: Abstract_domain) = struct type bab = { kind: cmpop; objective: (A.I.var_id * vname); best: (A.snapshot * tqformula) option; } type printer = { print_node: (string -> int -> A.t -> unit); print_sol: (A.t -> unit); } type transformer = | Printer of printer | BAB of bab | Timeout of Mtime.span | BoundSolutions of int let make_bab kind objective = BAB { kind; objective; best=None } let minimize_bab = make_bab LT let maximize_bab = make_bab GT type gs = { transformers: transformer list; stats: global_statistics; domain: A.t; } type bs = { snapshot: A.snapshot; bt_stats: bt_statistics } type t = (gs * bs) let init domain transformers = { transformers=transformers; stats=init_global_stats (); domain=domain; },{ snapshot=List.hd (A.lazy_copy domain 1); bt_stats=init_bt_stats (); } let unwrap_best gs = let rec aux = function | [] -> raise Not_found | BAB bab::_ -> begin match bab.best with | Some (_, (TQFFormula (_,TCmp (Var _, _, Cst (best,_))))) -> Some best | Some (_,_) -> failwith "[Transformer.unwrap_best] Best formula is suppose to be formatted as `v <op> best` where best is a constant." | None -> None end | _::l -> aux l in aux gs.transformers exception StopSearch of t exception Backjump of (int * t) let wrap_exception t f = try f t with | Bot.Bot_found -> raise (Backjump (0, t)) | Conflict n -> raise (Backjump (n, t)) let optimize (gs,bs) bab = match bab.best with | None -> (gs,bs) | Some (_,tf) -> wrap_exception (gs,bs) (fun (gs, bs) -> let domain, constraints = A.interpret gs.domain OverApprox tf in let domain = List.fold_left A.weak_incremental_closure domain constraints in ({gs with domain}, bs)) let stop_if t = function | true -> raise (StopSearch t) | false -> t let on_node (gs,bs) = let nodes, depth = gs.stats.nodes+1, bs.bt_stats.depth+1 in let gs:gs = {gs with stats={gs.stats with nodes}} in let bs:bs = {bs with bt_stats={depth}} in let apply (gs,bs) = function | BAB bab -> (optimize (gs,bs) bab) | Timeout timeout -> let elapsed = Mtime_clock.count gs.stats.start in let gs = {gs with stats={gs.stats with elapsed}} in stop_if (gs,bs) ((Mtime.Span.compare timeout elapsed) <= 0) | _ -> gs,bs in List.fold_left apply (gs,bs) gs.transformers let on_fail (gs,bs) = let fails = gs.stats.fails+1 in let gs = {gs with stats={gs.stats with fails}} in let apply (gs,bs) = function | Printer printer -> printer.print_node "false" bs.bt_stats.depth gs.domain; (gs,bs) | _ -> gs,bs in List.fold_left apply (gs,bs) gs.transformers let on_solution (gs,bs) = let sols = gs.stats.sols+1 in let nodes_before_last_sol = gs.stats.nodes in let gs = {gs with stats={gs.stats with sols; nodes_before_last_sol}} in let apply (gs,bs) transformer = match transformer with | BAB bab -> let v = fst bab.objective in let tv = A.I.to_logic_var (A.interpretation gs.domain) v in let (lb,ub) = A.project gs.domain v in let bound = let _ = " new solution : [ % a .. %a]\n " A.B.pp_print lb A.B.pp_print ub in match bab.kind with | LT | LEQ -> lb | GT | GEQ -> ub | _ -> failwith "BAB kind should be < or >." in let bound = Cst (A.B.to_rat bound, Types.to_concrete_ty tv.ty) in let _ = " Solution : [ % a .. %a ] - % d\n " A.B.pp_print lb A.B.pp_print ub gs.stats.nodes ; flush_all ( ) in let tqf = TQFFormula (tv.uid, TCmp (Var (snd bab.objective), bab.kind, bound)) in let a = List.hd (A.lazy_copy gs.domain 1) in (gs,bs), BAB {bab with best=Some(a, tqf)} | Printer printer -> printer.print_sol gs.domain; printer.print_node "true" bs.bt_stats.depth gs.domain; (gs,bs), transformer | BoundSolutions s when s == gs.stats.sols -> raise (StopSearch (gs,bs)) | _ -> (gs,bs), transformer in let (gs,bs), transformers = Tools.fold_map apply (gs,bs) gs.transformers in ({gs with transformers},bs) let on_unknown (gs,bs) = let apply (gs,bs) = function | Printer printer -> printer.print_node "unknown" bs.bt_stats.depth gs.domain; (gs,bs) | _ -> (gs,bs) in List.fold_left apply (gs,bs) gs.transformers end
2536006c053aba1340ed84ba9ae4ecfc006759e42d3cba4594358053d93ced0f
kupl/FixML
sub1.ml
type formula = TRUE | FALSE | NOT of formula | ANDALSO of formula * formula | ORELSE of formula * formula | IMPLY of formula * formula | LESS of expr * expr and expr = NUM of int | PLUS of expr * expr | MINUS of expr * expr let rec eval f = let rec eval2 e = match e with (NUM n) -> n | (PLUS (n1, n2)) -> (eval2 n1) + (eval2 n2) | (MINUS (n1, n2)) -> (eval2 n1) - (eval2 n2) in match f with TRUE -> true | FALSE -> false | (NOT f2) -> (eval f2) | (ANDALSO (f1, f2)) -> (eval f1) & (eval f2) | (ORELSE (f1, f2)) -> (eval f1) || (eval f2) | (IMPLY (f1, f2)) -> (if (eval f1) then (eval f2) else true) | (LESS (e1, e2)) -> (eval2 e1) < (eval2 e2)
null
https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/formula/formula/submissions/sub1.ml
ocaml
type formula = TRUE | FALSE | NOT of formula | ANDALSO of formula * formula | ORELSE of formula * formula | IMPLY of formula * formula | LESS of expr * expr and expr = NUM of int | PLUS of expr * expr | MINUS of expr * expr let rec eval f = let rec eval2 e = match e with (NUM n) -> n | (PLUS (n1, n2)) -> (eval2 n1) + (eval2 n2) | (MINUS (n1, n2)) -> (eval2 n1) - (eval2 n2) in match f with TRUE -> true | FALSE -> false | (NOT f2) -> (eval f2) | (ANDALSO (f1, f2)) -> (eval f1) & (eval f2) | (ORELSE (f1, f2)) -> (eval f1) || (eval f2) | (IMPLY (f1, f2)) -> (if (eval f1) then (eval f2) else true) | (LESS (e1, e2)) -> (eval2 e1) < (eval2 e2)
3ce3fdebc3c435d40ff06785b301623290c2e26bda7f4fc3d2f0c110b1595af8
gvolpe/exchange-rates
Time.hs
module Time where data TimeUnit = Seconds | Minutes | Hours deriving Show data Duration = Duration { unit :: Int , timeunit :: TimeUnit } deriving Show seconds :: Int -> Duration seconds n = Duration n Seconds minutes :: Int -> Duration minutes n = Duration n Minutes hours :: Int -> Duration hours n = Duration n Hours toMicroSeconds :: Duration -> Int toMicroSeconds (Duration n Seconds) = n * 1000000 toMicroSeconds (Duration n Minutes) = n * 60 * 1000000 toMicroSeconds (Duration n Hours ) = n * 60 * 60 * 1000000
null
https://raw.githubusercontent.com/gvolpe/exchange-rates/161108bfc859f399f06df7a8ce10e786f01af533/src/Time.hs
haskell
module Time where data TimeUnit = Seconds | Minutes | Hours deriving Show data Duration = Duration { unit :: Int , timeunit :: TimeUnit } deriving Show seconds :: Int -> Duration seconds n = Duration n Seconds minutes :: Int -> Duration minutes n = Duration n Minutes hours :: Int -> Duration hours n = Duration n Hours toMicroSeconds :: Duration -> Int toMicroSeconds (Duration n Seconds) = n * 1000000 toMicroSeconds (Duration n Minutes) = n * 60 * 1000000 toMicroSeconds (Duration n Hours ) = n * 60 * 60 * 1000000
69667298b47788e34e9dd3c3017679855b3bb2531bb0af07debf1b0058d37862
nilenso/kulu-backend
20150313160250630-add-role-to-orgs-users.clj
;; migrations/20150313160250630-add-role-to-orgs-users.clj (defn up [] ["ALTER TABLE organizations_users ADD COLUMN role VARCHAR (50)"]) (defn down [] ["ALTER TABLE organizations_users DROP COLUMN role"])
null
https://raw.githubusercontent.com/nilenso/kulu-backend/0b404f76643e77219432dcbffa681172a61e591b/migrations/20150313160250630-add-role-to-orgs-users.clj
clojure
migrations/20150313160250630-add-role-to-orgs-users.clj
(defn up [] ["ALTER TABLE organizations_users ADD COLUMN role VARCHAR (50)"]) (defn down [] ["ALTER TABLE organizations_users DROP COLUMN role"])
10029a4ab2a2fbcedae4f92884c69475145f44b64a25f4c42deecd8539495ead
xh4/web-toolkit
main-example.lisp
(in-package #:cffi-example) (defcfun "puts" :int "Put a string to standard output, return non-negative length output, or EOF" (string :string)) (defun check-groveller () (assert (equal (list +a0+ +a1+ +a2+ +a3+ +a4+) '(2 4 8 16 32))) (assert (equal (bn 1) 32))) (defun entry-point () (when uiop:*command-line-arguments* (uiop:format! t "Arguments: ~A~%" (uiop:escape-command uiop:*command-line-arguments*))) (puts "hello, world!") (check-groveller) (uiop:finish-outputs) (uiop:quit 0))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/cffi_0.20.1/examples/main-example.lisp
lisp
(in-package #:cffi-example) (defcfun "puts" :int "Put a string to standard output, return non-negative length output, or EOF" (string :string)) (defun check-groveller () (assert (equal (list +a0+ +a1+ +a2+ +a3+ +a4+) '(2 4 8 16 32))) (assert (equal (bn 1) 32))) (defun entry-point () (when uiop:*command-line-arguments* (uiop:format! t "Arguments: ~A~%" (uiop:escape-command uiop:*command-line-arguments*))) (puts "hello, world!") (check-groveller) (uiop:finish-outputs) (uiop:quit 0))
2a403bd6586fcee933685ab6163eca70c3f247185a72b7f623dddb9e7223cf66
Tatsuki-I/Vihs
Insert.hs
module Insert where insert :: String -> String -> Int -> String insert buff c x = take x buff ++ c ++ reverse (take (length buff - x) (reverse buff)) insertBuff :: [String] -> String -> Int -> Int -> [String] insertBuff buff c x y = take y buff ++ [insert (buff !! y) c x] ++ reverse (take (length buff - y - 1) (reverse buff)) main :: IO () main = do print $ take 1 str print $ insertBuff str "b" 1 2 where str = ["AAA", "BBB", "CCC"]
null
https://raw.githubusercontent.com/Tatsuki-I/Vihs/18543d0e2d2970d28a72674d5c502384bb41d98d/src/Insert.hs
haskell
module Insert where insert :: String -> String -> Int -> String insert buff c x = take x buff ++ c ++ reverse (take (length buff - x) (reverse buff)) insertBuff :: [String] -> String -> Int -> Int -> [String] insertBuff buff c x y = take y buff ++ [insert (buff !! y) c x] ++ reverse (take (length buff - y - 1) (reverse buff)) main :: IO () main = do print $ take 1 str print $ insertBuff str "b" 1 2 where str = ["AAA", "BBB", "CCC"]
7f1eabde780278fa2789e95cc0624f0798212467e0fb6944af4abc4bab9d7a69
ocharles/hadoom
TestWorld.hs
{-# LANGUAGE GADTs #-} # LANGUAGE DataKinds # module TestWorld where import BasePrelude import Data.TList import Hadoom.World import Linear import Linear.Affine import Material testWorld :: PWorld TWorld testWorld = PWorld (letrec (\_ -> Texture "flat.jpg" Linear ::: TNil) (\(flat ::: _) -> letrec (\_ -> Hadoom.World.Material (Texture "DHTP/textures/gstone2.png" SRGB) (Just flat) ::: Hadoom.World.Material (Texture "DHTP/flats/flat5.png" SRGB) (Just flat) ::: Hadoom.World.Material (Texture "DHTP/flats/ceil3_3.png" SRGB) (Just flat) ::: Hadoom.World.Material (Texture "DHTP/textures/bigdoor2.png" SRGB) (Just flat) ::: Vertex (P (V2 (-2) (-2))) ::: Vertex (P (V2 (-1.2) (-2))) ::: Vertex (P (V2 1.2 (-2))) ::: Vertex (P (V2 2 (-2))) ::: Vertex (P (V2 2 2)) ::: Vertex (P (V2 (-2) 2)) ::: Vertex (P (V2 1.2 (-40))) ::: Vertex (P (V2 (-1.2) (-40))) ::: TNil) (\(wt ::: ft ::: ct ::: lt ::: v1 ::: v2 ::: v3 ::: v4 ::: v5 ::: v6 ::: v7 ::: v8 ::: _) -> letrec (\_ -> Sector (SectorProperties 0 3) [v1,v2,v3,v4,v5,v6] ft ct ::: Sector (SectorProperties 0 2.5) [v2,v8,v7,v3] ft ct ::: TNil) (\(s1 ::: s2 ::: TNil) -> World [s1,s2] [Wall v1 v2 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v2 v3 (WallFace s1 (Just lt) (Just wt) (Just lt)) (Just (WallFace s2 Nothing Nothing Nothing)) ,Wall v3 v4 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v4 v5 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v5 v6 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v6 v1 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v2 v8 (WallFace s2 Nothing Nothing (Just wt)) Nothing ,Wall v8 v7 (WallFace s2 Nothing Nothing (Just wt)) Nothing ,Wall v7 v3 (WallFace s2 Nothing Nothing (Just wt)) Nothing]))))
null
https://raw.githubusercontent.com/ocharles/hadoom/13d5ea590282cdbbd343fa4a3d9144d7a1bcf9fd/hadoom/TestWorld.hs
haskell
# LANGUAGE GADTs #
# LANGUAGE DataKinds # module TestWorld where import BasePrelude import Data.TList import Hadoom.World import Linear import Linear.Affine import Material testWorld :: PWorld TWorld testWorld = PWorld (letrec (\_ -> Texture "flat.jpg" Linear ::: TNil) (\(flat ::: _) -> letrec (\_ -> Hadoom.World.Material (Texture "DHTP/textures/gstone2.png" SRGB) (Just flat) ::: Hadoom.World.Material (Texture "DHTP/flats/flat5.png" SRGB) (Just flat) ::: Hadoom.World.Material (Texture "DHTP/flats/ceil3_3.png" SRGB) (Just flat) ::: Hadoom.World.Material (Texture "DHTP/textures/bigdoor2.png" SRGB) (Just flat) ::: Vertex (P (V2 (-2) (-2))) ::: Vertex (P (V2 (-1.2) (-2))) ::: Vertex (P (V2 1.2 (-2))) ::: Vertex (P (V2 2 (-2))) ::: Vertex (P (V2 2 2)) ::: Vertex (P (V2 (-2) 2)) ::: Vertex (P (V2 1.2 (-40))) ::: Vertex (P (V2 (-1.2) (-40))) ::: TNil) (\(wt ::: ft ::: ct ::: lt ::: v1 ::: v2 ::: v3 ::: v4 ::: v5 ::: v6 ::: v7 ::: v8 ::: _) -> letrec (\_ -> Sector (SectorProperties 0 3) [v1,v2,v3,v4,v5,v6] ft ct ::: Sector (SectorProperties 0 2.5) [v2,v8,v7,v3] ft ct ::: TNil) (\(s1 ::: s2 ::: TNil) -> World [s1,s2] [Wall v1 v2 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v2 v3 (WallFace s1 (Just lt) (Just wt) (Just lt)) (Just (WallFace s2 Nothing Nothing Nothing)) ,Wall v3 v4 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v4 v5 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v5 v6 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v6 v1 (WallFace s1 Nothing Nothing (Just wt)) Nothing ,Wall v2 v8 (WallFace s2 Nothing Nothing (Just wt)) Nothing ,Wall v8 v7 (WallFace s2 Nothing Nothing (Just wt)) Nothing ,Wall v7 v3 (WallFace s2 Nothing Nothing (Just wt)) Nothing]))))
7b09b8751f936203ddac44d8635f0c903707b7ddb94572b560b2ed3782dd59d9
serokell/qtah
QList.hs
This file is part of Qtah . -- Copyright 2015 - 2018 The Qtah Authors . -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation , either version 3 of the License , or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . -- You should have received a copy of the GNU Lesser General Public License -- along with this program. If not, see </>. | Bindings for @QList@. module Graphics.UI.Qtah.Generator.Interface.Core.QList ( -- * Template Options (..), defaultOptions, Contents (..), inheritHasContents, instantiate, -- * Instantiations allModules, c_QListInt, c_QListQAbstractButton, c_QListQByteArray, c_QListQItemSelectionRange, c_QListQModelIndex, c_QListQObject, c_QListQSize, c_QListQString, c_QListQVariant, c_QListQWidget, ) where import Control.Monad (forM_, when) import Foreign.Hoppy.Generator.Language.Haskell ( Generator, HsTypeSide (HsHsSide), addImports, cppTypeToHsTypeAndUse, indent, ln, prettyPrint, sayLn, saysLn, toHsCastMethodName, toHsClassEntityName', toHsDataTypeName, ) import Foreign.Hoppy.Generator.Spec ( Class, ClassHaskellConversion ( ClassHaskellConversion, classHaskellConversionFromCppFn, classHaskellConversionToCppFn, classHaskellConversionType ), Constness (Const, Nonconst), Export (ExportClass), Operator (OpAdd, OpArray), Reqs, Type, addReqs, addAddendumHaskell, classSetEntityPrefix, classSetHaskellConversion, classSetMonomorphicSuperclass, hsImport1, identT, includeStd, makeClass, mkConstMethod, mkConstMethod', mkCtor, mkMethod, mkMethod', reqInclude, toExtName, ) import Foreign.Hoppy.Generator.Spec.ClassFeature ( ClassFeature (Assignable, Copyable), classAddFeatures, ) import Foreign.Hoppy.Generator.Types (boolT, constT, intT, objT, ptrT, refT, toGcT, voidT) import Foreign.Hoppy.Generator.Version (collect, just, test) import Graphics.UI.Qtah.Generator.Flags (qtVersion) import Graphics.UI.Qtah.Generator.Interface.Core.QByteArray (c_QByteArray) import Graphics.UI.Qtah.Generator.Interface.Core.QItemSelectionRange (c_QItemSelectionRange) import Graphics.UI.Qtah.Generator.Interface.Core.QModelIndex (c_QModelIndex) import Graphics.UI.Qtah.Generator.Interface.Core.QObject (c_QObject) import Graphics.UI.Qtah.Generator.Interface.Core.QSize (c_QSize) import Graphics.UI.Qtah.Generator.Interface.Core.QString (c_QString) import {-# SOURCE #-} Graphics.UI.Qtah.Generator.Interface.Core.QVariant (c_QVariant) import Graphics.UI.Qtah.Generator.Interface.Imports import {-# SOURCE #-} Graphics.UI.Qtah.Generator.Interface.Widgets.QAbstractButton ( c_QAbstractButton, ) import {-# SOURCE #-} Graphics.UI.Qtah.Generator.Interface.Widgets.QWidget (c_QWidget) import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), QtModule, makeQtModule) import Graphics.UI.Qtah.Generator.Types import Language.Haskell.Syntax ( HsQName (Special), HsSpecialCon (HsListCon), HsType (HsTyApp, HsTyCon), ) {-# ANN module "HLint: ignore Use camelCase" #-} -- | Options for instantiating the list classes. newtype Options = Options { optListClassFeatures :: [ClassFeature] -- ^ Additional features to add to the @QList@ class. Lists are always ' Assignable ' and , but you may want to add ' ' if your -- value type supports it. } | The default options have no additional ' ClassFeature 's . defaultOptions :: Options defaultOptions = Options [] -- | A set of instantiated classes. newtype Contents = Contents { c_QList :: Class -- ^ @QList\<T>@ } -- | @instantiate className t tReqs@ creates a set of bindings for an -- instantiation of @QList@ and associated types (e.g. iterators). In the result , the ' c_QList ' class has an external name of @className@. instantiate :: String -> Type -> Reqs -> Contents instantiate listName t tReqs = instantiate' listName t tReqs defaultOptions -- | 'instantiate' with additional options. instantiate' :: String -> Type -> Reqs -> Options -> Contents instantiate' listName t tReqs opts = let reqs = mconcat [ tReqs , reqInclude $ includeStd "QList" ] features = Assignable : Copyable : optListClassFeatures opts hasReserve = qtVersion >= [4, 7] list = addReqs reqs $ addAddendumHaskell addendum $ classSetHaskellConversion conversion $ classAddFeatures features $ classSetMonomorphicSuperclass $ classSetEntityPrefix "" $ makeClass (identT "QList" [t]) (Just $ toExtName listName) [] $ collect [ just $ mkCtor "new" [] , just $ mkMethod' "append" "append" [t] voidT , test (qtVersion >= [4, 5]) $ mkMethod' "append" "appendList" [objT list] voidT , just $ mkMethod' OpArray "at" [intT] $ refT t , just $ mkConstMethod' "at" "atConst" [intT] $ refT $ constT t -- OMIT back -- OMIT begin , just $ mkMethod "clear" [] voidT , just $ mkConstMethod "contains" [t] boolT -- OMIT count() , just $ mkConstMethod "count" [t] intT , test (qtVersion >= [4, 5]) $ mkConstMethod "endsWith" [t] boolT -- OMIT erase , just $ mkMethod' "first" "first" [] $ refT t , just $ mkConstMethod' "first" "firstConst" [] $ refT $ constT t , just $ mkConstMethod' OpArray "get" [intT] t , just $ mkConstMethod' "indexOf" "indexOf" [t] intT , just $ mkConstMethod' "indexOf" "indexOfFrom" [t, intT] intT , just $ mkMethod "insert" [intT, t] voidT , just $ mkConstMethod "isEmpty" [] boolT , just $ mkMethod' "last" "last" [] $ refT t , just $ mkConstMethod' "last" "lastConst" [] $ refT $ constT t , just $ mkConstMethod' "lastIndexOf" "lastIndexOf" [t] intT , just $ mkConstMethod' "lastIndexOf" "lastIndexOfFrom" [t, intT] intT -- OMIT length , just $ mkConstMethod' "mid" "mid" [intT] $ toGcT $ objT list , just $ mkConstMethod' "mid" "midLength" [intT, intT] $ toGcT $ objT list , just $ mkMethod "move" [intT, intT] voidT , just $ mkMethod "prepend" [t] voidT , just $ mkMethod "removeAll" [t] intT , just $ mkMethod "removeAt" [intT] voidT , just $ mkMethod "removeFirst" [] voidT , just $ mkMethod "removeLast" [] voidT , test (qtVersion >= [4, 4]) $ mkMethod "removeOne" [t] boolT , just $ mkMethod "replace" [intT, t] voidT , test hasReserve $ mkMethod "reserve" [intT] voidT , just $ mkConstMethod "size" [] intT , test (qtVersion >= [4, 5]) $ mkConstMethod "startsWith" [t] boolT , just $ mkMethod "swap" [intT, intT] voidT -- OMIT swap(QList<T>&) , just $ mkMethod "takeAt" [intT] t , just $ mkMethod "takeFirst" [] t , just $ mkMethod "takeLast" [] t TODO toSet -- TODO toStdList TODO toVector , just $ mkConstMethod' "value" "value" [intT] t , just $ mkConstMethod' "value" "valueOr" [intT, t] t , just $ mkConstMethod OpAdd [objT list] $ toGcT $ objT list ] The addendum for the list class contains HasContents and FromContents -- instances. addendum = do addImports $ mconcat [hsImport1 "Prelude" "(-)", hsImport1 "Control.Monad" "(<=<)", importForPrelude, importForRuntime] when hasReserve $ addImports $ hsImport1 "Prelude" "($)" forM_ [Const, Nonconst] $ \cst -> do hsDataTypeName <- toHsDataTypeName cst list hsValueType <- cppTypeToHsTypeAndUse HsHsSide $ case cst of Const -> constT t Nonconst -> t Generate const and nonconst HasContents instances . ln saysLn ["instance QtahFHR.HasContents ", hsDataTypeName, " (", prettyPrint hsValueType, ") where"] indent $ do sayLn "toContents this' = do" indent $ do let listAt = case cst of Const -> "atConst" Nonconst -> "at" saysLn ["size' <- ", toHsClassEntityName' list "size", " this'"] saysLn ["QtahP.mapM (QtahFHR.decode <=< ", toHsClassEntityName' list listAt, " this') [0..size'-1]"] Only generate a nonconst FromContents instance . when (cst == Nonconst) $ do ln saysLn ["instance QtahFHR.FromContents ", hsDataTypeName, " (", prettyPrint hsValueType, ") where"] indent $ do sayLn "fromContents values' = do" indent $ do saysLn ["list' <- ", toHsClassEntityName' list "new"] when hasReserve $ saysLn [toHsClassEntityName' list "reserve", " list' $ QtahFHR.coerceIntegral $ QtahP.length values'"] saysLn ["QtahP.mapM_ (", toHsClassEntityName' list "append", " list') values'"] sayLn "QtahP.return list'" A QList of some type converts into a list of the corresponding type using HasContents / FromContents . conversion = ClassHaskellConversion { classHaskellConversionType = Just $ do hsType <- cppTypeToHsTypeAndUse HsHsSide t return $ HsTyApp (HsTyCon $ Special HsListCon) hsType , classHaskellConversionToCppFn = Just $ do addImports importForRuntime sayLn "QtahFHR.fromContents" , classHaskellConversionFromCppFn = Just $ do addImports importForRuntime sayLn "QtahFHR.toContents" } in Contents { c_QList = list } | Used in an addendum for a class that inherits from QList , this generates a HasContents instance that uses the HasContents instance on the parent list -- class. inheritHasContents :: Class -> Class -> Type -> Generator () inheritHasContents cls listClass t = forM_ [Const, Nonconst] $ \cst -> do hsDataTypeName <- toHsDataTypeName cst cls hsValueType <- cppTypeToHsTypeAndUse HsHsSide $ case cst of Const -> constT t Nonconst -> t castToListFn <- toHsCastMethodName cst listClass addImports importForRuntime saysLn ["instance QtahFHR.HasContents ", hsDataTypeName, " (", prettyPrint hsValueType, ") where"] indent $ saysLn ["toContents = QtahFHR.toContents . ", castToListFn] -- | Converts an instantiation into a list of exports to be included in a -- module. toExports :: Contents -> [QtExport] toExports m = [QtExport $ ExportClass $ c_QList m] createModule :: String -> Contents -> QtModule createModule name contents = makeQtModule ["Core", "QList", name] $ toExports contents allModules :: [AModule] allModules = map AQtModule [ qmod_Int , qmod_QAbstractButton , qmod_QByteArray , qmod_QItemSelectionRange , qmod_QModelIndex , qmod_QObject , qmod_QSize , qmod_QString , qmod_QVariant , qmod_QWidget ] qmod_Int :: QtModule qmod_Int = createModule "Int" contents_Int contents_Int :: Contents contents_Int = instantiate "QListInt" intT mempty c_QListInt :: Class c_QListInt = c_QList contents_Int qmod_QAbstractButton :: QtModule qmod_QAbstractButton = createModule "QAbstractButton" contents_QAbstractButton contents_QAbstractButton :: Contents contents_QAbstractButton = instantiate "QListQAbstractButton" (ptrT $ objT c_QAbstractButton) mempty c_QListQAbstractButton :: Class c_QListQAbstractButton = c_QList contents_QAbstractButton qmod_QByteArray :: QtModule qmod_QByteArray = createModule "QByteArray" contents_QByteArray contents_QByteArray :: Contents contents_QByteArray = instantiate "QListQByteArray" (objT c_QByteArray) mempty c_QListQByteArray :: Class c_QListQByteArray = c_QList contents_QByteArray qmod_QItemSelectionRange :: QtModule qmod_QItemSelectionRange = createModule "QItemSelectionRange" contents_QItemSelectionRange contents_QItemSelectionRange :: Contents contents_QItemSelectionRange = instantiate "QListQItemSelectionRange" (objT c_QItemSelectionRange) mempty c_QListQItemSelectionRange :: Class c_QListQItemSelectionRange = c_QList contents_QItemSelectionRange qmod_QModelIndex :: QtModule qmod_QModelIndex = createModule "QModelIndex" contents_QModelIndex contents_QModelIndex :: Contents contents_QModelIndex = instantiate "QListQModelIndex" (objT c_QModelIndex) mempty c_QListQModelIndex :: Class c_QListQModelIndex = c_QList contents_QModelIndex qmod_QObject :: QtModule qmod_QObject = createModule "QObject" contents_QObject contents_QObject :: Contents contents_QObject = instantiate "QListQObject" (ptrT $ objT c_QObject) mempty c_QListQObject :: Class c_QListQObject = c_QList contents_QObject qmod_QSize :: QtModule qmod_QSize = createModule "QSize" contents_QSize contents_QSize :: Contents contents_QSize = instantiate "QListQSize" (objT c_QSize) mempty c_QListQSize :: Class c_QListQSize = c_QList contents_QSize qmod_QString :: QtModule qmod_QString = createModule "QString" contents_QString contents_QString :: Contents contents_QString = instantiate "QListQString" (objT c_QString) mempty c_QListQString :: Class c_QListQString = c_QList contents_QString qmod_QVariant :: QtModule qmod_QVariant = createModule "QVariant" contents_QVariant contents_QVariant :: Contents contents_QVariant = instantiate "QListQVariant" (objT c_QVariant) mempty c_QListQVariant :: Class c_QListQVariant = c_QList contents_QVariant qmod_QWidget :: QtModule qmod_QWidget = createModule "QWidget" contents_QWidget contents_QWidget :: Contents contents_QWidget = instantiate "QListQWidget" (ptrT $ objT c_QWidget) mempty c_QListQWidget :: Class c_QListQWidget = c_QList contents_QWidget
null
https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Core/QList.hs
haskell
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see </>. * Template * Instantiations # SOURCE # # SOURCE # # SOURCE # # ANN module "HLint: ignore Use camelCase" # | Options for instantiating the list classes. ^ Additional features to add to the @QList@ class. Lists are always value type supports it. | A set of instantiated classes. ^ @QList\<T>@ | @instantiate className t tReqs@ creates a set of bindings for an instantiation of @QList@ and associated types (e.g. iterators). In the | 'instantiate' with additional options. OMIT back OMIT begin OMIT count() OMIT erase OMIT length OMIT swap(QList<T>&) TODO toStdList instances. class. | Converts an instantiation into a list of exports to be included in a module.
This file is part of Qtah . Copyright 2015 - 2018 The Qtah Authors . the Free Software Foundation , either version 3 of the License , or GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License | Bindings for @QList@. module Graphics.UI.Qtah.Generator.Interface.Core.QList ( Options (..), defaultOptions, Contents (..), inheritHasContents, instantiate, allModules, c_QListInt, c_QListQAbstractButton, c_QListQByteArray, c_QListQItemSelectionRange, c_QListQModelIndex, c_QListQObject, c_QListQSize, c_QListQString, c_QListQVariant, c_QListQWidget, ) where import Control.Monad (forM_, when) import Foreign.Hoppy.Generator.Language.Haskell ( Generator, HsTypeSide (HsHsSide), addImports, cppTypeToHsTypeAndUse, indent, ln, prettyPrint, sayLn, saysLn, toHsCastMethodName, toHsClassEntityName', toHsDataTypeName, ) import Foreign.Hoppy.Generator.Spec ( Class, ClassHaskellConversion ( ClassHaskellConversion, classHaskellConversionFromCppFn, classHaskellConversionToCppFn, classHaskellConversionType ), Constness (Const, Nonconst), Export (ExportClass), Operator (OpAdd, OpArray), Reqs, Type, addReqs, addAddendumHaskell, classSetEntityPrefix, classSetHaskellConversion, classSetMonomorphicSuperclass, hsImport1, identT, includeStd, makeClass, mkConstMethod, mkConstMethod', mkCtor, mkMethod, mkMethod', reqInclude, toExtName, ) import Foreign.Hoppy.Generator.Spec.ClassFeature ( ClassFeature (Assignable, Copyable), classAddFeatures, ) import Foreign.Hoppy.Generator.Types (boolT, constT, intT, objT, ptrT, refT, toGcT, voidT) import Foreign.Hoppy.Generator.Version (collect, just, test) import Graphics.UI.Qtah.Generator.Flags (qtVersion) import Graphics.UI.Qtah.Generator.Interface.Core.QByteArray (c_QByteArray) import Graphics.UI.Qtah.Generator.Interface.Core.QItemSelectionRange (c_QItemSelectionRange) import Graphics.UI.Qtah.Generator.Interface.Core.QModelIndex (c_QModelIndex) import Graphics.UI.Qtah.Generator.Interface.Core.QObject (c_QObject) import Graphics.UI.Qtah.Generator.Interface.Core.QSize (c_QSize) import Graphics.UI.Qtah.Generator.Interface.Core.QString (c_QString) import Graphics.UI.Qtah.Generator.Interface.Imports c_QAbstractButton, ) import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), QtModule, makeQtModule) import Graphics.UI.Qtah.Generator.Types import Language.Haskell.Syntax ( HsQName (Special), HsSpecialCon (HsListCon), HsType (HsTyApp, HsTyCon), ) newtype Options = Options { optListClassFeatures :: [ClassFeature] ' Assignable ' and , but you may want to add ' ' if your } | The default options have no additional ' ClassFeature 's . defaultOptions :: Options defaultOptions = Options [] newtype Contents = Contents } result , the ' c_QList ' class has an external name of @className@. instantiate :: String -> Type -> Reqs -> Contents instantiate listName t tReqs = instantiate' listName t tReqs defaultOptions instantiate' :: String -> Type -> Reqs -> Options -> Contents instantiate' listName t tReqs opts = let reqs = mconcat [ tReqs , reqInclude $ includeStd "QList" ] features = Assignable : Copyable : optListClassFeatures opts hasReserve = qtVersion >= [4, 7] list = addReqs reqs $ addAddendumHaskell addendum $ classSetHaskellConversion conversion $ classAddFeatures features $ classSetMonomorphicSuperclass $ classSetEntityPrefix "" $ makeClass (identT "QList" [t]) (Just $ toExtName listName) [] $ collect [ just $ mkCtor "new" [] , just $ mkMethod' "append" "append" [t] voidT , test (qtVersion >= [4, 5]) $ mkMethod' "append" "appendList" [objT list] voidT , just $ mkMethod' OpArray "at" [intT] $ refT t , just $ mkConstMethod' "at" "atConst" [intT] $ refT $ constT t , just $ mkMethod "clear" [] voidT , just $ mkConstMethod "contains" [t] boolT , just $ mkConstMethod "count" [t] intT , test (qtVersion >= [4, 5]) $ mkConstMethod "endsWith" [t] boolT , just $ mkMethod' "first" "first" [] $ refT t , just $ mkConstMethod' "first" "firstConst" [] $ refT $ constT t , just $ mkConstMethod' OpArray "get" [intT] t , just $ mkConstMethod' "indexOf" "indexOf" [t] intT , just $ mkConstMethod' "indexOf" "indexOfFrom" [t, intT] intT , just $ mkMethod "insert" [intT, t] voidT , just $ mkConstMethod "isEmpty" [] boolT , just $ mkMethod' "last" "last" [] $ refT t , just $ mkConstMethod' "last" "lastConst" [] $ refT $ constT t , just $ mkConstMethod' "lastIndexOf" "lastIndexOf" [t] intT , just $ mkConstMethod' "lastIndexOf" "lastIndexOfFrom" [t, intT] intT , just $ mkConstMethod' "mid" "mid" [intT] $ toGcT $ objT list , just $ mkConstMethod' "mid" "midLength" [intT, intT] $ toGcT $ objT list , just $ mkMethod "move" [intT, intT] voidT , just $ mkMethod "prepend" [t] voidT , just $ mkMethod "removeAll" [t] intT , just $ mkMethod "removeAt" [intT] voidT , just $ mkMethod "removeFirst" [] voidT , just $ mkMethod "removeLast" [] voidT , test (qtVersion >= [4, 4]) $ mkMethod "removeOne" [t] boolT , just $ mkMethod "replace" [intT, t] voidT , test hasReserve $ mkMethod "reserve" [intT] voidT , just $ mkConstMethod "size" [] intT , test (qtVersion >= [4, 5]) $ mkConstMethod "startsWith" [t] boolT , just $ mkMethod "swap" [intT, intT] voidT , just $ mkMethod "takeAt" [intT] t , just $ mkMethod "takeFirst" [] t , just $ mkMethod "takeLast" [] t TODO toSet TODO toVector , just $ mkConstMethod' "value" "value" [intT] t , just $ mkConstMethod' "value" "valueOr" [intT, t] t , just $ mkConstMethod OpAdd [objT list] $ toGcT $ objT list ] The addendum for the list class contains HasContents and FromContents addendum = do addImports $ mconcat [hsImport1 "Prelude" "(-)", hsImport1 "Control.Monad" "(<=<)", importForPrelude, importForRuntime] when hasReserve $ addImports $ hsImport1 "Prelude" "($)" forM_ [Const, Nonconst] $ \cst -> do hsDataTypeName <- toHsDataTypeName cst list hsValueType <- cppTypeToHsTypeAndUse HsHsSide $ case cst of Const -> constT t Nonconst -> t Generate const and nonconst HasContents instances . ln saysLn ["instance QtahFHR.HasContents ", hsDataTypeName, " (", prettyPrint hsValueType, ") where"] indent $ do sayLn "toContents this' = do" indent $ do let listAt = case cst of Const -> "atConst" Nonconst -> "at" saysLn ["size' <- ", toHsClassEntityName' list "size", " this'"] saysLn ["QtahP.mapM (QtahFHR.decode <=< ", toHsClassEntityName' list listAt, " this') [0..size'-1]"] Only generate a nonconst FromContents instance . when (cst == Nonconst) $ do ln saysLn ["instance QtahFHR.FromContents ", hsDataTypeName, " (", prettyPrint hsValueType, ") where"] indent $ do sayLn "fromContents values' = do" indent $ do saysLn ["list' <- ", toHsClassEntityName' list "new"] when hasReserve $ saysLn [toHsClassEntityName' list "reserve", " list' $ QtahFHR.coerceIntegral $ QtahP.length values'"] saysLn ["QtahP.mapM_ (", toHsClassEntityName' list "append", " list') values'"] sayLn "QtahP.return list'" A QList of some type converts into a list of the corresponding type using HasContents / FromContents . conversion = ClassHaskellConversion { classHaskellConversionType = Just $ do hsType <- cppTypeToHsTypeAndUse HsHsSide t return $ HsTyApp (HsTyCon $ Special HsListCon) hsType , classHaskellConversionToCppFn = Just $ do addImports importForRuntime sayLn "QtahFHR.fromContents" , classHaskellConversionFromCppFn = Just $ do addImports importForRuntime sayLn "QtahFHR.toContents" } in Contents { c_QList = list } | Used in an addendum for a class that inherits from QList , this generates a HasContents instance that uses the HasContents instance on the parent list inheritHasContents :: Class -> Class -> Type -> Generator () inheritHasContents cls listClass t = forM_ [Const, Nonconst] $ \cst -> do hsDataTypeName <- toHsDataTypeName cst cls hsValueType <- cppTypeToHsTypeAndUse HsHsSide $ case cst of Const -> constT t Nonconst -> t castToListFn <- toHsCastMethodName cst listClass addImports importForRuntime saysLn ["instance QtahFHR.HasContents ", hsDataTypeName, " (", prettyPrint hsValueType, ") where"] indent $ saysLn ["toContents = QtahFHR.toContents . ", castToListFn] toExports :: Contents -> [QtExport] toExports m = [QtExport $ ExportClass $ c_QList m] createModule :: String -> Contents -> QtModule createModule name contents = makeQtModule ["Core", "QList", name] $ toExports contents allModules :: [AModule] allModules = map AQtModule [ qmod_Int , qmod_QAbstractButton , qmod_QByteArray , qmod_QItemSelectionRange , qmod_QModelIndex , qmod_QObject , qmod_QSize , qmod_QString , qmod_QVariant , qmod_QWidget ] qmod_Int :: QtModule qmod_Int = createModule "Int" contents_Int contents_Int :: Contents contents_Int = instantiate "QListInt" intT mempty c_QListInt :: Class c_QListInt = c_QList contents_Int qmod_QAbstractButton :: QtModule qmod_QAbstractButton = createModule "QAbstractButton" contents_QAbstractButton contents_QAbstractButton :: Contents contents_QAbstractButton = instantiate "QListQAbstractButton" (ptrT $ objT c_QAbstractButton) mempty c_QListQAbstractButton :: Class c_QListQAbstractButton = c_QList contents_QAbstractButton qmod_QByteArray :: QtModule qmod_QByteArray = createModule "QByteArray" contents_QByteArray contents_QByteArray :: Contents contents_QByteArray = instantiate "QListQByteArray" (objT c_QByteArray) mempty c_QListQByteArray :: Class c_QListQByteArray = c_QList contents_QByteArray qmod_QItemSelectionRange :: QtModule qmod_QItemSelectionRange = createModule "QItemSelectionRange" contents_QItemSelectionRange contents_QItemSelectionRange :: Contents contents_QItemSelectionRange = instantiate "QListQItemSelectionRange" (objT c_QItemSelectionRange) mempty c_QListQItemSelectionRange :: Class c_QListQItemSelectionRange = c_QList contents_QItemSelectionRange qmod_QModelIndex :: QtModule qmod_QModelIndex = createModule "QModelIndex" contents_QModelIndex contents_QModelIndex :: Contents contents_QModelIndex = instantiate "QListQModelIndex" (objT c_QModelIndex) mempty c_QListQModelIndex :: Class c_QListQModelIndex = c_QList contents_QModelIndex qmod_QObject :: QtModule qmod_QObject = createModule "QObject" contents_QObject contents_QObject :: Contents contents_QObject = instantiate "QListQObject" (ptrT $ objT c_QObject) mempty c_QListQObject :: Class c_QListQObject = c_QList contents_QObject qmod_QSize :: QtModule qmod_QSize = createModule "QSize" contents_QSize contents_QSize :: Contents contents_QSize = instantiate "QListQSize" (objT c_QSize) mempty c_QListQSize :: Class c_QListQSize = c_QList contents_QSize qmod_QString :: QtModule qmod_QString = createModule "QString" contents_QString contents_QString :: Contents contents_QString = instantiate "QListQString" (objT c_QString) mempty c_QListQString :: Class c_QListQString = c_QList contents_QString qmod_QVariant :: QtModule qmod_QVariant = createModule "QVariant" contents_QVariant contents_QVariant :: Contents contents_QVariant = instantiate "QListQVariant" (objT c_QVariant) mempty c_QListQVariant :: Class c_QListQVariant = c_QList contents_QVariant qmod_QWidget :: QtModule qmod_QWidget = createModule "QWidget" contents_QWidget contents_QWidget :: Contents contents_QWidget = instantiate "QListQWidget" (ptrT $ objT c_QWidget) mempty c_QListQWidget :: Class c_QListQWidget = c_QList contents_QWidget
3563d324bceaccef4ff3abd8dc39bf8c73a9f0efcaece98b19c2e94499212e2e
chef/chef-server
bifrost_wm_bulk_resource.erl
-module(bifrost_wm_bulk_resource). -include("bifrost_wm_rest_endpoint.hrl"). -include_lib("stats_hero/include/stats_hero.hrl"). -mixin([{bifrost_wm_base, [create_path/2]}]). -export([ post_is_create/2, process_post/2 ]). init(Config) -> bifrost_wm_base:init(?MODULE, Config). post_is_create(Req, State) -> % We're not creating anything (for a change), just processing information, so we want to return 200 's instead of 201 's here ; also , instead of from_json , we 'll % be using process_post below {false, Req, State}. allowed_methods(Req, State) -> {['POST'], Req, State}. validate_request(Req, State) -> % We really don't care if there's a requestor or not, because (1) we're not % limiting access permissions on this endpoint to any particular requestors, and ( 2 ) the requesting actor in the header and the requestor for which we are % requesting information need not be the same. {false, Req, State}. auth_info(_Method) -> ignore. process_post(Req, State) -> try Body = wrq:req_body(Req), {ReqId, Permission, Type, Collection} = parse_body(Body), case ?SH_TIME(ReqId, bifrost_db, bulk_permission, (ReqId, Collection, Permission, Type)) of Authorized when is_list(Authorized) -> %% The query above returns which of the supplied targets in the %% parsed collection have permission, but we need to return the %% opposite, so we do this: Unauthorized = sets:to_list(sets:subtract(sets:from_list(Collection), sets:from_list(Authorized))), case Unauthorized of [] -> % If we don't set a body here (or anywhere else, of course, % but that shouldn't happen anyway), web machine should return 204 , which is exactly the behavior we want . {true, Req, State}; Unauthorized -> Req0 = bifrost_wm_util:set_json_body(Req, {[{<<"unauthorized">>, Unauthorized}]}), {true, Req0, State} end; {error, Error} -> bifrost_wm_error:set_db_exception(Req, State, Error) end catch error:ErrorType -> {_Return, ErrReq, _State} = bifrost_wm_error:set_malformed_request(Req, State, ErrorType), {{halt, 400}, ErrReq, State}; throw:{db_error, ErrorType} -> bifrost_wm_error:set_db_exception(Req, State, ErrorType) end. valid_perm(<<"create">>) -> ok; valid_perm(<<"read">>) -> ok; valid_perm(<<"update">>) -> ok; valid_perm(<<"delete">>) -> ok; valid_perm(<<"grant">>) -> ok; valid_perm(_) -> error. valid_type(<<"actor">>) -> ok; valid_type(<<"container">>) -> ok; valid_type(<<"group">>) -> ok; valid_type(<<"object">>) -> ok; valid_type(_) -> error. regex_for(authz_id) -> {ok, Regex} = re:compile("^[a-fA-F0-9]{32}$"), {Regex, <<"invalid authz ID, must be 32-digit hex string">>}. bulk_spec() -> {[ {<<"requestor_id">>, {string_match, regex_for(authz_id)}}, {<<"permission">>, {fun_match, {fun valid_perm/1, string, <<"invalid permission type, must be 'create'," " 'read', 'update', 'delete', or 'grant'">>}}}, {<<"type">>, {fun_match, {fun valid_type/1, string, <<"invalid authz type, must be 'actor', 'container'," " 'group', or 'object'">>}}}, {<<"collection">>, {array_map, {string_match, regex_for(authz_id)}}} ]}. parse_body(Body) -> try Ejson = bifrost_wm_util:decode(Body), case ej:valid(bulk_spec(), Ejson) of ok -> ReqId = ej:get({<<"requestor_id">>}, Ejson), Permission = binary_to_atom(ej:get({<<"permission">>}, Ejson), utf8), AuthType = binary_to_atom(ej:get({<<"type">>}, Ejson), utf8), Collection = ej:get({<<"collection">>}, Ejson), {ReqId, Permission, AuthType, Collection}; BadSpec -> throw(BadSpec) end catch error:{_, invalid_json} -> error(invalid_json); error:{_, truncated_json} -> error(invalid_json); throw:{ej_invalid, string_match, _, _, _, _, Message} -> error({ej_invalid, Message}); throw:{ej_invalid, fun_match, _, _, _, _, Message} -> error({ej_invalid, Message}); throw:{ej_invalid, array_elt, _, _, _, _, Message} -> error({ej_invalid, Message}); throw:{ej_invalid, missing, Type, _, _, _, _} -> error({missing, Type}); throw:{ej_invalid, json_type, Type, _, _, _, _} -> error({json_type, Type}) end.
null
https://raw.githubusercontent.com/chef/chef-server/437177e87677d116c0871e7269a509440e07e3e2/src/oc_bifrost/apps/bifrost/src/bifrost_wm_bulk_resource.erl
erlang
We're not creating anything (for a change), just processing information, so be using process_post below We really don't care if there's a requestor or not, because (1) we're not limiting access permissions on this endpoint to any particular requestors, and requesting information need not be the same. The query above returns which of the supplied targets in the parsed collection have permission, but we need to return the opposite, so we do this: If we don't set a body here (or anywhere else, of course, but that shouldn't happen anyway), web machine should
-module(bifrost_wm_bulk_resource). -include("bifrost_wm_rest_endpoint.hrl"). -include_lib("stats_hero/include/stats_hero.hrl"). -mixin([{bifrost_wm_base, [create_path/2]}]). -export([ post_is_create/2, process_post/2 ]). init(Config) -> bifrost_wm_base:init(?MODULE, Config). post_is_create(Req, State) -> we want to return 200 's instead of 201 's here ; also , instead of from_json , we 'll {false, Req, State}. allowed_methods(Req, State) -> {['POST'], Req, State}. validate_request(Req, State) -> ( 2 ) the requesting actor in the header and the requestor for which we are {false, Req, State}. auth_info(_Method) -> ignore. process_post(Req, State) -> try Body = wrq:req_body(Req), {ReqId, Permission, Type, Collection} = parse_body(Body), case ?SH_TIME(ReqId, bifrost_db, bulk_permission, (ReqId, Collection, Permission, Type)) of Authorized when is_list(Authorized) -> Unauthorized = sets:to_list(sets:subtract(sets:from_list(Collection), sets:from_list(Authorized))), case Unauthorized of [] -> return 204 , which is exactly the behavior we want . {true, Req, State}; Unauthorized -> Req0 = bifrost_wm_util:set_json_body(Req, {[{<<"unauthorized">>, Unauthorized}]}), {true, Req0, State} end; {error, Error} -> bifrost_wm_error:set_db_exception(Req, State, Error) end catch error:ErrorType -> {_Return, ErrReq, _State} = bifrost_wm_error:set_malformed_request(Req, State, ErrorType), {{halt, 400}, ErrReq, State}; throw:{db_error, ErrorType} -> bifrost_wm_error:set_db_exception(Req, State, ErrorType) end. valid_perm(<<"create">>) -> ok; valid_perm(<<"read">>) -> ok; valid_perm(<<"update">>) -> ok; valid_perm(<<"delete">>) -> ok; valid_perm(<<"grant">>) -> ok; valid_perm(_) -> error. valid_type(<<"actor">>) -> ok; valid_type(<<"container">>) -> ok; valid_type(<<"group">>) -> ok; valid_type(<<"object">>) -> ok; valid_type(_) -> error. regex_for(authz_id) -> {ok, Regex} = re:compile("^[a-fA-F0-9]{32}$"), {Regex, <<"invalid authz ID, must be 32-digit hex string">>}. bulk_spec() -> {[ {<<"requestor_id">>, {string_match, regex_for(authz_id)}}, {<<"permission">>, {fun_match, {fun valid_perm/1, string, <<"invalid permission type, must be 'create'," " 'read', 'update', 'delete', or 'grant'">>}}}, {<<"type">>, {fun_match, {fun valid_type/1, string, <<"invalid authz type, must be 'actor', 'container'," " 'group', or 'object'">>}}}, {<<"collection">>, {array_map, {string_match, regex_for(authz_id)}}} ]}. parse_body(Body) -> try Ejson = bifrost_wm_util:decode(Body), case ej:valid(bulk_spec(), Ejson) of ok -> ReqId = ej:get({<<"requestor_id">>}, Ejson), Permission = binary_to_atom(ej:get({<<"permission">>}, Ejson), utf8), AuthType = binary_to_atom(ej:get({<<"type">>}, Ejson), utf8), Collection = ej:get({<<"collection">>}, Ejson), {ReqId, Permission, AuthType, Collection}; BadSpec -> throw(BadSpec) end catch error:{_, invalid_json} -> error(invalid_json); error:{_, truncated_json} -> error(invalid_json); throw:{ej_invalid, string_match, _, _, _, _, Message} -> error({ej_invalid, Message}); throw:{ej_invalid, fun_match, _, _, _, _, Message} -> error({ej_invalid, Message}); throw:{ej_invalid, array_elt, _, _, _, _, Message} -> error({ej_invalid, Message}); throw:{ej_invalid, missing, Type, _, _, _, _} -> error({missing, Type}); throw:{ej_invalid, json_type, Type, _, _, _, _} -> error({json_type, Type}) end.
9747f77cca138183aeb7d6213343034490b802684529bfa9cd9901fb062d97bd
paurkedal/ocaml-prime
prime.mli
Copyright ( C ) 2013 - -2022 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) (** Primitives. *) * { 2 The Empty Type } type counit = | (** A type which is uninhabited by well-founded code. This is equivalent to a variant type with no constructors, though syntax forbids naming or defining such types. *) val absurd : counit -> 'a (** Computations in the scope of a variable [x : counit] can be assumed dead, and thus be shortcut as [absurd x]. This is the analogue of pattern-matching a variant with no constructors. *) (** {2 Combinators} *) val ident : 'a -> 'a (** The I combinator: [ident x] is [x]. *) val konst : 'a -> 'b -> 'a (** The K combinator: [konst x y] is [x]. *) val (%) : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c (** Function composition: [(g % f) x] is [g (f x)]. *) val (%>) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c * Reversed function composition : [ ( f % > g ) x ] is [ g ( f x ) ] . * { 2 Currying } val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c (** [curry f x y] is [f (x, y)]. *) val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c (** [uncurry f (x, y)] is [f x y]. *) * { 2 Exceptions } val finally : (unit -> unit) -> (unit -> 'a) -> 'a
null
https://raw.githubusercontent.com/paurkedal/ocaml-prime/5e527c03190474e7fdc87114c6bc9e8e4ddd0759/lib/prime.mli
ocaml
* Primitives. * A type which is uninhabited by well-founded code. This is equivalent to a variant type with no constructors, though syntax forbids naming or defining such types. * Computations in the scope of a variable [x : counit] can be assumed dead, and thus be shortcut as [absurd x]. This is the analogue of pattern-matching a variant with no constructors. * {2 Combinators} * The I combinator: [ident x] is [x]. * The K combinator: [konst x y] is [x]. * Function composition: [(g % f) x] is [g (f x)]. * [curry f x y] is [f (x, y)]. * [uncurry f (x, y)] is [f x y].
Copyright ( C ) 2013 - -2022 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) * { 2 The Empty Type } type counit = | val absurd : counit -> 'a val ident : 'a -> 'a val konst : 'a -> 'b -> 'a val (%) : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c val (%>) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c * Reversed function composition : [ ( f % > g ) x ] is [ g ( f x ) ] . * { 2 Currying } val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c * { 2 Exceptions } val finally : (unit -> unit) -> (unit -> 'a) -> 'a
093d9a8867719b061e06eff5791ef0b6dc7ec42762b2e8bdefe9d617186339ae
wedesoft/aiscm
compile.scm
(define-module (aiscm compile) #:use-module (oop goops) #:use-module (srfi srfi-1) #:use-module (aiscm element) #:use-module (aiscm int) #:export (expr->params expr->descr expr->temps expr->call expr->method) #:export-syntax (comp)) (define (expr->params expr) (cond ((null? expr) '()) ((pair? expr) (append-map expr->params (cdr expr))) (else (list expr)))) (define (expr->descr expr) (letrec [(expr->str (lambda (expr) (cond ((null? expr) "") ((pair? expr) (format #f "<~a_~a>" (car expr) (string-join (map expr->str (cdr expr)) "_"))) (else "?"))))] (string->symbol (expr->str expr)))) (define (expr->temps expr) (syntax->datum (generate-temporaries (expr->params expr)))) (define (expr->call expr) (cons (expr->descr expr) (expr->params expr))) (define (expr->method expr) (let [(descr (expr->descr expr)) (temps (expr->temps expr)) (param (lambda (arg) `(,arg <element>))) (extract (lambda (arg) `(get ,arg)))] `(define-method (,descr ,@(map param temps)) (make <int> #:value (+ ,@(map extract temps)))))) (define-syntax comp (lambda (x) (syntax-case x () ((k expr) #`(begin #,(datum->syntax #'k (expr->method (syntax->datum #'expr))) #,(datum->syntax #'k (expr->call (syntax->datum #'expr))))))))
null
https://raw.githubusercontent.com/wedesoft/aiscm/2c3db8d00cad6e042150714ada85da19cf4338ad/etc/compile.scm
scheme
(define-module (aiscm compile) #:use-module (oop goops) #:use-module (srfi srfi-1) #:use-module (aiscm element) #:use-module (aiscm int) #:export (expr->params expr->descr expr->temps expr->call expr->method) #:export-syntax (comp)) (define (expr->params expr) (cond ((null? expr) '()) ((pair? expr) (append-map expr->params (cdr expr))) (else (list expr)))) (define (expr->descr expr) (letrec [(expr->str (lambda (expr) (cond ((null? expr) "") ((pair? expr) (format #f "<~a_~a>" (car expr) (string-join (map expr->str (cdr expr)) "_"))) (else "?"))))] (string->symbol (expr->str expr)))) (define (expr->temps expr) (syntax->datum (generate-temporaries (expr->params expr)))) (define (expr->call expr) (cons (expr->descr expr) (expr->params expr))) (define (expr->method expr) (let [(descr (expr->descr expr)) (temps (expr->temps expr)) (param (lambda (arg) `(,arg <element>))) (extract (lambda (arg) `(get ,arg)))] `(define-method (,descr ,@(map param temps)) (make <int> #:value (+ ,@(map extract temps)))))) (define-syntax comp (lambda (x) (syntax-case x () ((k expr) #`(begin #,(datum->syntax #'k (expr->method (syntax->datum #'expr))) #,(datum->syntax #'k (expr->call (syntax->datum #'expr))))))))
bac5327235f8e76f8afb6ca6925ec9ac346a7a36512e4530cd66e4dc81e5e4d6
janestreet/core
deque.ml
open! Import open Std_internal type 'a t = { (* [arr] is a cyclic buffer *) mutable arr : 'a Option_array.t ; (* [front_index] and [back_index] are the positions in which new elements may be enqueued. This makes the active part of [arr] the range from [front_index+1] to [back_index-1] (modulo the length of [arr] and wrapping around if necessary). Note that this means the active range is maximized when [front_index = back_index], which occurs when there are [Array.length arr - 1] active elements. *) mutable front_index : int ; mutable back_index : int ; (* apparent_front_index is what is exposed as the front index externally. It has no real relation to the array -- every enqueue to the front decrements it and every dequeue from the front increments it. *) mutable apparent_front_index : int ; mutable length : int We keep arr_length here as a speed hack . Calling Array.length on is actually meaningfully slower . meaningfully slower. *) mutable arr_length : int ; never_shrink : bool } let create ?initial_length ?never_shrink () = let never_shrink = match never_shrink with | None -> Option.is_some initial_length | Some b -> b in let initial_length = Option.value ~default:7 initial_length in if initial_length < 0 then invalid_argf "passed negative initial_length to Deque.create: %i" initial_length (); (* Make the initial array length be [initial_length + 1] so we can fit [initial_length] elements without growing. We never quite use the whole array. *) let arr_length = initial_length + 1 in { arr = Option_array.create ~len:arr_length ; front_index = 0 ; back_index = 1 ; apparent_front_index = 0 ; length = 0 ; arr_length ; never_shrink } ;; let length t = t.length let is_empty t = length t = 0 (* We keep track of the length in a mutable field for speed, but this calculation should be correct by construction, and can be used for testing. *) let _invariant_length t = let constructed_length = if t.front_index < t.back_index then t.back_index - t.front_index - 1 else t.back_index - t.front_index - 1 + t.arr_length in assert (length t = constructed_length) ;; (* The various "when_not_empty" functions return misleading numbers when the dequeue is empty. They are safe to call if it is known that the dequeue is non-empty. *) let apparent_front_index_when_not_empty t = t.apparent_front_index let apparent_back_index_when_not_empty t = t.apparent_front_index + length t - 1 let actual_front_index_when_not_empty t = if t.front_index = t.arr_length - 1 then 0 else t.front_index + 1 ;; let actual_back_index_when_not_empty t = if t.back_index = 0 then t.arr_length - 1 else t.back_index - 1 ;; let checked t f = if is_empty t then None else Some (f t) let apparent_front_index t = checked t apparent_front_index_when_not_empty let apparent_back_index t = checked t apparent_back_index_when_not_empty let foldi' t dir ~init ~f = if is_empty t then init else ( let apparent_front = apparent_front_index_when_not_empty t in let apparent_back = apparent_back_index_when_not_empty t in let actual_front = actual_front_index_when_not_empty t in let actual_back = actual_back_index_when_not_empty t in let rec loop acc ~apparent_i ~real_i ~stop_pos ~step = if real_i = stop_pos then acc, apparent_i else loop (f apparent_i acc (Option_array.get_some_exn t.arr real_i)) ~apparent_i:(apparent_i + step) ~real_i:(real_i + step) ~stop_pos ~step in We want to iterate from actual_front to actual_back ( or vice versa ) , but we may need to wrap around the array to do so . Thus we do the following : 1 . If the active range is contiguous ( i.e. actual_front < = actual_back ) , then loop starting at the appropriate end of the active range until we reach the first element outside of it . 2 . If it is not contiguous ( actual_front > actual_back ) , then first loop from the appropriate end of the active range to the end of the array . Then , loop from the opposite end of the array to the opposite end of the active range . need to wrap around the array to do so. Thus we do the following: 1. If the active range is contiguous (i.e. actual_front <= actual_back), then loop starting at the appropriate end of the active range until we reach the first element outside of it. 2. If it is not contiguous (actual_front > actual_back), then first loop from the appropriate end of the active range to the end of the array. Then, loop from the opposite end of the array to the opposite end of the active range. *) match dir with | `front_to_back -> if actual_front <= actual_back then ( let acc, _ = loop init ~apparent_i:apparent_front ~real_i:actual_front ~stop_pos:(actual_back + 1) ~step:1 in acc) else ( let acc, apparent_i = loop init ~apparent_i:apparent_front ~real_i:actual_front ~stop_pos:t.arr_length ~step:1 in let acc, _ = loop acc ~apparent_i ~real_i:0 ~stop_pos:(actual_back + 1) ~step:1 in acc) | `back_to_front -> if actual_front <= actual_back then ( let acc, _ = loop init ~apparent_i:apparent_back ~real_i:actual_back ~stop_pos:(actual_front - 1) ~step:(-1) in acc) else ( let acc, apparent_i = loop init ~apparent_i:apparent_back ~real_i:actual_back ~stop_pos:(-1) ~step:(-1) in let acc, _ = loop acc ~apparent_i ~real_i:(t.arr_length - 1) ~stop_pos:(actual_front - 1) ~step:(-1) in acc)) ;; let fold' t dir ~init ~f = foldi' t dir ~init ~f:(fun _ acc v -> f acc v) [@nontail] let iteri' t dir ~f = foldi' t dir ~init:() ~f:(fun i () v -> f i v) let iter' t dir ~f = foldi' t dir ~init:() ~f:(fun _ () v -> f v) let fold t ~init ~f = fold' t `front_to_back ~init ~f let foldi t ~init ~f = foldi' t `front_to_back ~init ~f let iteri t ~f = iteri' t `front_to_back ~f let iteri_internal t ~f = if not (is_empty t) then ( let actual_front = actual_front_index_when_not_empty t in let actual_back = actual_back_index_when_not_empty t in let rec loop ~real_i ~stop_pos = if real_i < stop_pos then ( f t.arr real_i; loop ~real_i:(real_i + 1) ~stop_pos) in if actual_front <= actual_back then loop ~real_i:actual_front ~stop_pos:(actual_back + 1) [@nontail] else ( loop ~real_i:actual_front ~stop_pos:t.arr_length; loop ~real_i:0 ~stop_pos:(actual_back + 1) [@nontail])) ;; let iter t ~f = iteri_internal t ~f:(fun arr i -> Option_array.get_some_exn arr i |> f) [@nontail] ;; let clear t = if t.never_shrink then (* clear the array to allow elements to be garbage collected *) iteri_internal t ~f:Option_array.unsafe_set_none else t.arr <- Option_array.create ~len:8; t.front_index <- 0; t.back_index <- 1; t.length <- 0; t.arr_length <- Option_array.length t.arr ;; We have to be careful here , importing all of Container . Make would change the runtime of some functions ( [ length ] minimally ) silently without changing the semantics . We get around that by importing things explicitly . some functions ([length] minimally) silently without changing the semantics. We get around that by importing things explicitly. *) module C = Container.Make (struct type nonrec 'a t = 'a t let fold = fold let iter = `Custom iter let length = `Custom length end) let count = C.count let sum = C.sum let exists = C.exists let mem = C.mem let for_all = C.for_all let find_map = C.find_map let find = C.find let to_list = C.to_list let min_elt = C.min_elt let max_elt = C.max_elt let fold_result = C.fold_result let fold_until = C.fold_until let blit new_arr t = assert (not (is_empty t)); let actual_front = actual_front_index_when_not_empty t in let actual_back = actual_back_index_when_not_empty t in let old_arr = t.arr in if actual_front <= actual_back then Option_array.blit ~src:old_arr ~dst:new_arr ~src_pos:actual_front ~dst_pos:0 ~len:(length t) else ( let break_pos = Option_array.length old_arr - actual_front in Option_array.blit ~src:old_arr ~dst:new_arr ~src_pos:actual_front ~dst_pos:0 ~len:break_pos; Option_array.blit ~src:old_arr ~dst:new_arr ~src_pos:0 ~dst_pos:break_pos ~len:(actual_back + 1)); length depends on and t.front_index , so this needs to be first t.back_index <- length t; t.arr <- new_arr; t.arr_length <- Option_array.length new_arr; t.front_index <- Option_array.length new_arr - 1; Since t.front_index = Option_array.length new_arr - 1 , this is asserting that t.back_index is a valid index in the array and that the array can support at least one more element -- recall , if t.front_index = t.back_index then the array is full . Note that this is true if and only if Option_array.length > length t + 1 . is a valid index in the array and that the array can support at least one more element -- recall, if t.front_index = t.back_index then the array is full. Note that this is true if and only if Option_array.length new_arr > length t + 1. *) assert (t.front_index > t.back_index) ;; let maybe_shrink_underlying t = if (not t.never_shrink) && t.arr_length > 10 && t.arr_length / 3 > length t then ( let new_arr = Option_array.create ~len:(t.arr_length / 2) in blit new_arr t) ;; let grow_underlying t = let new_arr = Option_array.create ~len:(t.arr_length * 2) in blit new_arr t ;; let enqueue_back t v = if t.front_index = t.back_index then grow_underlying t; Option_array.set_some t.arr t.back_index v; t.back_index <- (if t.back_index = t.arr_length - 1 then 0 else t.back_index + 1); t.length <- t.length + 1 ;; let enqueue_front t v = if t.front_index = t.back_index then grow_underlying t; Option_array.set_some t.arr t.front_index v; t.front_index <- (if t.front_index = 0 then t.arr_length - 1 else t.front_index - 1); t.apparent_front_index <- t.apparent_front_index - 1; t.length <- t.length + 1 ;; let enqueue t back_or_front v = match back_or_front with | `back -> enqueue_back t v | `front -> enqueue_front t v ;; let peek_front_nonempty t = Option_array.get_some_exn t.arr (actual_front_index_when_not_empty t) ;; let peek_front_exn t = if is_empty t then failwith "Deque.peek_front_exn passed an empty queue" else peek_front_nonempty t ;; let peek_front t = if is_empty t then None else Some (peek_front_nonempty t) let peek_back_nonempty t = Option_array.get_some_exn t.arr (actual_back_index_when_not_empty t) ;; let peek_back_exn t = if is_empty t then failwith "Deque.peek_back_exn passed an empty queue" else peek_back_nonempty t ;; let peek_back t = if is_empty t then None else Some (peek_back_nonempty t) let peek t back_or_front = match back_or_front with | `back -> peek_back t | `front -> peek_front t ;; let dequeue_front_nonempty t = let i = actual_front_index_when_not_empty t in let res = Option_array.get_some_exn t.arr i in Option_array.set_none t.arr i; t.front_index <- i; t.apparent_front_index <- t.apparent_front_index + 1; t.length <- t.length - 1; maybe_shrink_underlying t; res ;; let dequeue_front_exn t = if is_empty t then failwith "Deque.dequeue_front_exn passed an empty queue" else dequeue_front_nonempty t ;; let dequeue_front t = if is_empty t then None else Some (dequeue_front_nonempty t) let dequeue_back_nonempty t = let i = actual_back_index_when_not_empty t in let res = Option_array.get_some_exn t.arr i in Option_array.set_none t.arr i; t.back_index <- i; t.length <- t.length - 1; maybe_shrink_underlying t; res ;; let dequeue_back_exn t = if is_empty t then failwith "Deque.dequeue_back_exn passed an empty queue" else dequeue_back_nonempty t ;; let dequeue_back t = if is_empty t then None else Some (dequeue_back_nonempty t) let dequeue_exn t back_or_front = match back_or_front with | `front -> dequeue_front_exn t | `back -> dequeue_back_exn t ;; let dequeue t back_or_front = match back_or_front with | `front -> dequeue_front t | `back -> dequeue_back t ;; let drop_gen ?(n = 1) ~dequeue t = if n < 0 then invalid_argf "Deque.drop: negative input (%d)" n (); let rec loop n = if n > 0 then ( match dequeue t with | None -> () | Some _ -> loop (n - 1)) in loop n ;; let drop_front ?n t = drop_gen ?n ~dequeue:dequeue_front t let drop_back ?n t = drop_gen ?n ~dequeue:dequeue_back t let drop ?n t back_or_front = match back_or_front with | `back -> drop_back ?n t | `front -> drop_front ?n t ;; let assert_not_empty t name = if is_empty t then failwithf "%s: Deque.t is empty" name () let true_index_exn t i = let i_from_zero = i - t.apparent_front_index in if i_from_zero < 0 || length t <= i_from_zero then ( assert_not_empty t "Deque.true_index_exn"; let apparent_front = apparent_front_index_when_not_empty t in let apparent_back = apparent_back_index_when_not_empty t in invalid_argf "invalid index: %i for array with indices (%i,%i)" i apparent_front apparent_back ()); let true_i = t.front_index + 1 + i_from_zero in if true_i >= t.arr_length then true_i - t.arr_length else true_i ;; let get t i = Option_array.get_some_exn t.arr (true_index_exn t i) let get_opt t i = try Some (get t i) with | _ -> None ;; let set_exn t i v = Option_array.set_some t.arr (true_index_exn t i) v let to_array t = match peek_front t with | None -> [||] | Some front -> let arr = Array.create ~len:(length t) front in ignore (fold t ~init:0 ~f:(fun i v -> arr.(i) <- v; i + 1) : int); arr ;; let of_array arr = let t = create ~initial_length:(Array.length arr + 1) () in Array.iter arr ~f:(fun v -> enqueue_back t v); t ;; include Bin_prot.Utils.Make_iterable_binable1 (struct type nonrec 'a t = 'a t type 'a el = 'a [@@deriving bin_io] let caller_identity = Bin_prot.Shape.Uuid.of_string "34c1e9ca-4992-11e6-a686-8b4bd4f87796" ;; let module_name = Some "Core.Deque" let length = length let iter t ~f = iter t ~f let init ~len ~next = let t = create ~initial_length:len () in for _i = 0 to len - 1 do let x = next () in enqueue_back t x done; t ;; end) let t_of_sexp f sexp = of_array (Array.t_of_sexp f sexp) let sexp_of_t f t = Array.sexp_of_t f (to_array t) let t_sexp_grammar elt_grammar = Sexplib.Sexp_grammar.coerce (Array.t_sexp_grammar elt_grammar) ;; (* re-expose these here under a different name to avoid internal confusion *) let back_index = apparent_back_index let front_index = apparent_front_index let back_index_exn t = assert_not_empty t "Deque.back_index_exn"; apparent_back_index_when_not_empty t ;; let front_index_exn t = assert_not_empty t "Deque.front_index_exn"; apparent_front_index_when_not_empty t ;; module Binary_searchable = Test_binary_searchable.Make1_and_test (struct type nonrec 'a t = 'a t let get t i = get t (front_index_exn t + i) let length = length module For_test = struct let of_array = of_array end end) The " stable " indices used in this module make the application of the [ Binary_searchable ] functor awkward . We need to be sure to translate incoming positions from stable space to the expected 0 - > length - 1 space and then we need to translate them back on return . [Binary_searchable] functor awkward. We need to be sure to translate incoming positions from stable space to the expected 0 -> length - 1 space and then we need to translate them back on return. *) let binary_search ?pos ?len t ~compare how v = let pos = match pos with | None -> None | Some pos -> Some (pos - t.apparent_front_index) in match Binary_searchable.binary_search ?pos ?len t ~compare how v with | None -> None | Some untranslated_i -> Some (t.apparent_front_index + untranslated_i) ;; let binary_search_segmented ?pos ?len t ~segment_of how = let pos = match pos with | None -> None | Some pos -> Some (pos - t.apparent_front_index) in match Binary_searchable.binary_search_segmented ?pos ?len t ~segment_of how with | None -> None | Some untranslated_i -> Some (t.apparent_front_index + untranslated_i) ;;
null
https://raw.githubusercontent.com/janestreet/core/d0d1b3915c9350d8e9f2b395a817659e539e6155/core/src/deque.ml
ocaml
[arr] is a cyclic buffer [front_index] and [back_index] are the positions in which new elements may be enqueued. This makes the active part of [arr] the range from [front_index+1] to [back_index-1] (modulo the length of [arr] and wrapping around if necessary). Note that this means the active range is maximized when [front_index = back_index], which occurs when there are [Array.length arr - 1] active elements. apparent_front_index is what is exposed as the front index externally. It has no real relation to the array -- every enqueue to the front decrements it and every dequeue from the front increments it. Make the initial array length be [initial_length + 1] so we can fit [initial_length] elements without growing. We never quite use the whole array. We keep track of the length in a mutable field for speed, but this calculation should be correct by construction, and can be used for testing. The various "when_not_empty" functions return misleading numbers when the dequeue is empty. They are safe to call if it is known that the dequeue is non-empty. clear the array to allow elements to be garbage collected re-expose these here under a different name to avoid internal confusion
open! Import open Std_internal type 'a t = mutable arr : 'a Option_array.t mutable front_index : int ; mutable back_index : int mutable apparent_front_index : int ; mutable length : int We keep arr_length here as a speed hack . Calling Array.length on is actually meaningfully slower . meaningfully slower. *) mutable arr_length : int ; never_shrink : bool } let create ?initial_length ?never_shrink () = let never_shrink = match never_shrink with | None -> Option.is_some initial_length | Some b -> b in let initial_length = Option.value ~default:7 initial_length in if initial_length < 0 then invalid_argf "passed negative initial_length to Deque.create: %i" initial_length (); let arr_length = initial_length + 1 in { arr = Option_array.create ~len:arr_length ; front_index = 0 ; back_index = 1 ; apparent_front_index = 0 ; length = 0 ; arr_length ; never_shrink } ;; let length t = t.length let is_empty t = length t = 0 let _invariant_length t = let constructed_length = if t.front_index < t.back_index then t.back_index - t.front_index - 1 else t.back_index - t.front_index - 1 + t.arr_length in assert (length t = constructed_length) ;; let apparent_front_index_when_not_empty t = t.apparent_front_index let apparent_back_index_when_not_empty t = t.apparent_front_index + length t - 1 let actual_front_index_when_not_empty t = if t.front_index = t.arr_length - 1 then 0 else t.front_index + 1 ;; let actual_back_index_when_not_empty t = if t.back_index = 0 then t.arr_length - 1 else t.back_index - 1 ;; let checked t f = if is_empty t then None else Some (f t) let apparent_front_index t = checked t apparent_front_index_when_not_empty let apparent_back_index t = checked t apparent_back_index_when_not_empty let foldi' t dir ~init ~f = if is_empty t then init else ( let apparent_front = apparent_front_index_when_not_empty t in let apparent_back = apparent_back_index_when_not_empty t in let actual_front = actual_front_index_when_not_empty t in let actual_back = actual_back_index_when_not_empty t in let rec loop acc ~apparent_i ~real_i ~stop_pos ~step = if real_i = stop_pos then acc, apparent_i else loop (f apparent_i acc (Option_array.get_some_exn t.arr real_i)) ~apparent_i:(apparent_i + step) ~real_i:(real_i + step) ~stop_pos ~step in We want to iterate from actual_front to actual_back ( or vice versa ) , but we may need to wrap around the array to do so . Thus we do the following : 1 . If the active range is contiguous ( i.e. actual_front < = actual_back ) , then loop starting at the appropriate end of the active range until we reach the first element outside of it . 2 . If it is not contiguous ( actual_front > actual_back ) , then first loop from the appropriate end of the active range to the end of the array . Then , loop from the opposite end of the array to the opposite end of the active range . need to wrap around the array to do so. Thus we do the following: 1. If the active range is contiguous (i.e. actual_front <= actual_back), then loop starting at the appropriate end of the active range until we reach the first element outside of it. 2. If it is not contiguous (actual_front > actual_back), then first loop from the appropriate end of the active range to the end of the array. Then, loop from the opposite end of the array to the opposite end of the active range. *) match dir with | `front_to_back -> if actual_front <= actual_back then ( let acc, _ = loop init ~apparent_i:apparent_front ~real_i:actual_front ~stop_pos:(actual_back + 1) ~step:1 in acc) else ( let acc, apparent_i = loop init ~apparent_i:apparent_front ~real_i:actual_front ~stop_pos:t.arr_length ~step:1 in let acc, _ = loop acc ~apparent_i ~real_i:0 ~stop_pos:(actual_back + 1) ~step:1 in acc) | `back_to_front -> if actual_front <= actual_back then ( let acc, _ = loop init ~apparent_i:apparent_back ~real_i:actual_back ~stop_pos:(actual_front - 1) ~step:(-1) in acc) else ( let acc, apparent_i = loop init ~apparent_i:apparent_back ~real_i:actual_back ~stop_pos:(-1) ~step:(-1) in let acc, _ = loop acc ~apparent_i ~real_i:(t.arr_length - 1) ~stop_pos:(actual_front - 1) ~step:(-1) in acc)) ;; let fold' t dir ~init ~f = foldi' t dir ~init ~f:(fun _ acc v -> f acc v) [@nontail] let iteri' t dir ~f = foldi' t dir ~init:() ~f:(fun i () v -> f i v) let iter' t dir ~f = foldi' t dir ~init:() ~f:(fun _ () v -> f v) let fold t ~init ~f = fold' t `front_to_back ~init ~f let foldi t ~init ~f = foldi' t `front_to_back ~init ~f let iteri t ~f = iteri' t `front_to_back ~f let iteri_internal t ~f = if not (is_empty t) then ( let actual_front = actual_front_index_when_not_empty t in let actual_back = actual_back_index_when_not_empty t in let rec loop ~real_i ~stop_pos = if real_i < stop_pos then ( f t.arr real_i; loop ~real_i:(real_i + 1) ~stop_pos) in if actual_front <= actual_back then loop ~real_i:actual_front ~stop_pos:(actual_back + 1) [@nontail] else ( loop ~real_i:actual_front ~stop_pos:t.arr_length; loop ~real_i:0 ~stop_pos:(actual_back + 1) [@nontail])) ;; let iter t ~f = iteri_internal t ~f:(fun arr i -> Option_array.get_some_exn arr i |> f) [@nontail] ;; let clear t = if t.never_shrink then iteri_internal t ~f:Option_array.unsafe_set_none else t.arr <- Option_array.create ~len:8; t.front_index <- 0; t.back_index <- 1; t.length <- 0; t.arr_length <- Option_array.length t.arr ;; We have to be careful here , importing all of Container . Make would change the runtime of some functions ( [ length ] minimally ) silently without changing the semantics . We get around that by importing things explicitly . some functions ([length] minimally) silently without changing the semantics. We get around that by importing things explicitly. *) module C = Container.Make (struct type nonrec 'a t = 'a t let fold = fold let iter = `Custom iter let length = `Custom length end) let count = C.count let sum = C.sum let exists = C.exists let mem = C.mem let for_all = C.for_all let find_map = C.find_map let find = C.find let to_list = C.to_list let min_elt = C.min_elt let max_elt = C.max_elt let fold_result = C.fold_result let fold_until = C.fold_until let blit new_arr t = assert (not (is_empty t)); let actual_front = actual_front_index_when_not_empty t in let actual_back = actual_back_index_when_not_empty t in let old_arr = t.arr in if actual_front <= actual_back then Option_array.blit ~src:old_arr ~dst:new_arr ~src_pos:actual_front ~dst_pos:0 ~len:(length t) else ( let break_pos = Option_array.length old_arr - actual_front in Option_array.blit ~src:old_arr ~dst:new_arr ~src_pos:actual_front ~dst_pos:0 ~len:break_pos; Option_array.blit ~src:old_arr ~dst:new_arr ~src_pos:0 ~dst_pos:break_pos ~len:(actual_back + 1)); length depends on and t.front_index , so this needs to be first t.back_index <- length t; t.arr <- new_arr; t.arr_length <- Option_array.length new_arr; t.front_index <- Option_array.length new_arr - 1; Since t.front_index = Option_array.length new_arr - 1 , this is asserting that t.back_index is a valid index in the array and that the array can support at least one more element -- recall , if t.front_index = t.back_index then the array is full . Note that this is true if and only if Option_array.length > length t + 1 . is a valid index in the array and that the array can support at least one more element -- recall, if t.front_index = t.back_index then the array is full. Note that this is true if and only if Option_array.length new_arr > length t + 1. *) assert (t.front_index > t.back_index) ;; let maybe_shrink_underlying t = if (not t.never_shrink) && t.arr_length > 10 && t.arr_length / 3 > length t then ( let new_arr = Option_array.create ~len:(t.arr_length / 2) in blit new_arr t) ;; let grow_underlying t = let new_arr = Option_array.create ~len:(t.arr_length * 2) in blit new_arr t ;; let enqueue_back t v = if t.front_index = t.back_index then grow_underlying t; Option_array.set_some t.arr t.back_index v; t.back_index <- (if t.back_index = t.arr_length - 1 then 0 else t.back_index + 1); t.length <- t.length + 1 ;; let enqueue_front t v = if t.front_index = t.back_index then grow_underlying t; Option_array.set_some t.arr t.front_index v; t.front_index <- (if t.front_index = 0 then t.arr_length - 1 else t.front_index - 1); t.apparent_front_index <- t.apparent_front_index - 1; t.length <- t.length + 1 ;; let enqueue t back_or_front v = match back_or_front with | `back -> enqueue_back t v | `front -> enqueue_front t v ;; let peek_front_nonempty t = Option_array.get_some_exn t.arr (actual_front_index_when_not_empty t) ;; let peek_front_exn t = if is_empty t then failwith "Deque.peek_front_exn passed an empty queue" else peek_front_nonempty t ;; let peek_front t = if is_empty t then None else Some (peek_front_nonempty t) let peek_back_nonempty t = Option_array.get_some_exn t.arr (actual_back_index_when_not_empty t) ;; let peek_back_exn t = if is_empty t then failwith "Deque.peek_back_exn passed an empty queue" else peek_back_nonempty t ;; let peek_back t = if is_empty t then None else Some (peek_back_nonempty t) let peek t back_or_front = match back_or_front with | `back -> peek_back t | `front -> peek_front t ;; let dequeue_front_nonempty t = let i = actual_front_index_when_not_empty t in let res = Option_array.get_some_exn t.arr i in Option_array.set_none t.arr i; t.front_index <- i; t.apparent_front_index <- t.apparent_front_index + 1; t.length <- t.length - 1; maybe_shrink_underlying t; res ;; let dequeue_front_exn t = if is_empty t then failwith "Deque.dequeue_front_exn passed an empty queue" else dequeue_front_nonempty t ;; let dequeue_front t = if is_empty t then None else Some (dequeue_front_nonempty t) let dequeue_back_nonempty t = let i = actual_back_index_when_not_empty t in let res = Option_array.get_some_exn t.arr i in Option_array.set_none t.arr i; t.back_index <- i; t.length <- t.length - 1; maybe_shrink_underlying t; res ;; let dequeue_back_exn t = if is_empty t then failwith "Deque.dequeue_back_exn passed an empty queue" else dequeue_back_nonempty t ;; let dequeue_back t = if is_empty t then None else Some (dequeue_back_nonempty t) let dequeue_exn t back_or_front = match back_or_front with | `front -> dequeue_front_exn t | `back -> dequeue_back_exn t ;; let dequeue t back_or_front = match back_or_front with | `front -> dequeue_front t | `back -> dequeue_back t ;; let drop_gen ?(n = 1) ~dequeue t = if n < 0 then invalid_argf "Deque.drop: negative input (%d)" n (); let rec loop n = if n > 0 then ( match dequeue t with | None -> () | Some _ -> loop (n - 1)) in loop n ;; let drop_front ?n t = drop_gen ?n ~dequeue:dequeue_front t let drop_back ?n t = drop_gen ?n ~dequeue:dequeue_back t let drop ?n t back_or_front = match back_or_front with | `back -> drop_back ?n t | `front -> drop_front ?n t ;; let assert_not_empty t name = if is_empty t then failwithf "%s: Deque.t is empty" name () let true_index_exn t i = let i_from_zero = i - t.apparent_front_index in if i_from_zero < 0 || length t <= i_from_zero then ( assert_not_empty t "Deque.true_index_exn"; let apparent_front = apparent_front_index_when_not_empty t in let apparent_back = apparent_back_index_when_not_empty t in invalid_argf "invalid index: %i for array with indices (%i,%i)" i apparent_front apparent_back ()); let true_i = t.front_index + 1 + i_from_zero in if true_i >= t.arr_length then true_i - t.arr_length else true_i ;; let get t i = Option_array.get_some_exn t.arr (true_index_exn t i) let get_opt t i = try Some (get t i) with | _ -> None ;; let set_exn t i v = Option_array.set_some t.arr (true_index_exn t i) v let to_array t = match peek_front t with | None -> [||] | Some front -> let arr = Array.create ~len:(length t) front in ignore (fold t ~init:0 ~f:(fun i v -> arr.(i) <- v; i + 1) : int); arr ;; let of_array arr = let t = create ~initial_length:(Array.length arr + 1) () in Array.iter arr ~f:(fun v -> enqueue_back t v); t ;; include Bin_prot.Utils.Make_iterable_binable1 (struct type nonrec 'a t = 'a t type 'a el = 'a [@@deriving bin_io] let caller_identity = Bin_prot.Shape.Uuid.of_string "34c1e9ca-4992-11e6-a686-8b4bd4f87796" ;; let module_name = Some "Core.Deque" let length = length let iter t ~f = iter t ~f let init ~len ~next = let t = create ~initial_length:len () in for _i = 0 to len - 1 do let x = next () in enqueue_back t x done; t ;; end) let t_of_sexp f sexp = of_array (Array.t_of_sexp f sexp) let sexp_of_t f t = Array.sexp_of_t f (to_array t) let t_sexp_grammar elt_grammar = Sexplib.Sexp_grammar.coerce (Array.t_sexp_grammar elt_grammar) ;; let back_index = apparent_back_index let front_index = apparent_front_index let back_index_exn t = assert_not_empty t "Deque.back_index_exn"; apparent_back_index_when_not_empty t ;; let front_index_exn t = assert_not_empty t "Deque.front_index_exn"; apparent_front_index_when_not_empty t ;; module Binary_searchable = Test_binary_searchable.Make1_and_test (struct type nonrec 'a t = 'a t let get t i = get t (front_index_exn t + i) let length = length module For_test = struct let of_array = of_array end end) The " stable " indices used in this module make the application of the [ Binary_searchable ] functor awkward . We need to be sure to translate incoming positions from stable space to the expected 0 - > length - 1 space and then we need to translate them back on return . [Binary_searchable] functor awkward. We need to be sure to translate incoming positions from stable space to the expected 0 -> length - 1 space and then we need to translate them back on return. *) let binary_search ?pos ?len t ~compare how v = let pos = match pos with | None -> None | Some pos -> Some (pos - t.apparent_front_index) in match Binary_searchable.binary_search ?pos ?len t ~compare how v with | None -> None | Some untranslated_i -> Some (t.apparent_front_index + untranslated_i) ;; let binary_search_segmented ?pos ?len t ~segment_of how = let pos = match pos with | None -> None | Some pos -> Some (pos - t.apparent_front_index) in match Binary_searchable.binary_search_segmented ?pos ?len t ~segment_of how with | None -> None | Some untranslated_i -> Some (t.apparent_front_index + untranslated_i) ;;
d947d6f93bf427692ea66ffabc6057f6dbb7e432c4c904d223a0292a4d893ce6
MinaProtocol/mina
endo.mli
(* Endo coefficients *) (** [Step_inner_curve] contains the endo coefficients used by the step proof system *) module Step_inner_curve : sig val base : Backend.Tick.Field.t val scalar : Backend.Tock.Field.t val to_field : Import.Challenge.Constant.t Import.Scalar_challenge.t -> Backend.Tock.Field.t end (** [Wrap_inner_curve] contains the endo coefficients used by the wrap proof system *) module Wrap_inner_curve : sig val base : Backend.Tock.Field.t val scalar : Backend.Tick.Field.t val to_field : Import.Challenge.Constant.t Import.Scalar_challenge.t -> Backend.Tick.Field.t end
null
https://raw.githubusercontent.com/MinaProtocol/mina/b19a220d87caa129ed5dcffc94f89204ae874661/src/lib/pickles/endo.mli
ocaml
Endo coefficients * [Step_inner_curve] contains the endo coefficients used by the step proof system * [Wrap_inner_curve] contains the endo coefficients used by the wrap proof system
module Step_inner_curve : sig val base : Backend.Tick.Field.t val scalar : Backend.Tock.Field.t val to_field : Import.Challenge.Constant.t Import.Scalar_challenge.t -> Backend.Tock.Field.t end module Wrap_inner_curve : sig val base : Backend.Tock.Field.t val scalar : Backend.Tick.Field.t val to_field : Import.Challenge.Constant.t Import.Scalar_challenge.t -> Backend.Tick.Field.t end
225c2e973c85eb32ec9d3de1d3a298db1368cd8816ddfe229a039ed31066d652
pbrisbin/yesod-goodies
SimpleSearch.hs
------------------------------------------------------------------------------- -- | Module : Data . SimpleSearch Copyright : ( c ) 2010 -- License : as-is -- -- Maintainer : -- Stability : unstable -- Portability : unportable -- ------------------------------------------------------------------------------- module Data.SimpleSearch ( SearchResult(..) , Search(..) , search , search_ , weightedSearch , weightedSearch_ -- * predefined , TextSearch(..) , keywordMatch ) where import Data.List (sortBy, intersect) import Data.Ord (comparing) import Data.Maybe (catMaybes) import Data.Text (Text) import qualified Data.Text as T -- | A ranked search result data SearchResult a = SearchResult { searchRank :: Double , searchResult :: a } -- | Any item can be searched by providing a @'match'@ function. class Search a where | If two results have the same rank , optionally lend preference to one . The /greater/ value will appear first . preference :: SearchResult a -> SearchResult a -> Ordering preference _ _ = EQ -- | Given a search term and some @a@, provide @Just@ a ranked result or @Nothing@. match :: Text -> a -> Maybe (SearchResult a) | Excute a search on a list of @a@s and rank the results search :: Search a => Text -> [a] -> [SearchResult a] search t = rankResults . catMaybes . map (match t) -- | Identical but discards the actual rank values. search_ :: Search a => Text -> [a] -> [a] search_ t = map searchResult . search t -- | Add (or remove) weight from items that have certian properties. weightedSearch :: Search a => (a -> Double) -> Text -> [a] -> [SearchResult a] weightedSearch f t = rankResults . map (applyFactor f) . catMaybes . map (match t) where applyFactor :: (a -> Double) -> SearchResult a -> SearchResult a applyFactor f' (SearchResult d v) = SearchResult (d * f' v) v weightedSearch_ :: Search a => (a -> Double) -> Text -> [a] -> [a] weightedSearch_ f t = map searchResult . weightedSearch f t -- | Reverse sort the results by rank and then preference. rankResults :: Search a => [SearchResult a] -> [SearchResult a] rankResults = reverse . sortBy (comparing searchRank `andthen` preference) -- | Compare values in a compound way -- > sortBy ( comparing snd ` andthen ` comparing fst ) -- andthen :: (a -> a -> Ordering) -> (a -> a -> Ordering) -> a -> a -> Ordering andthen f g a b = case f a b of EQ -> g a b x -> x -- | Being a member of this class means defining the way to represent -- your type as pure text so it can be searched by keyword, etc. class TextSearch a where toText :: a -> Text -- | Search term is interpreted as keywords. Results are ranked by the number of words that appear in the source text , a rank of 0 returns -- Nothing. keywordMatch :: TextSearch a => Text -> a -> Maybe (SearchResult a) keywordMatch t v = go $ fix (toText v) `intersect` fix t where go [] = Nothing go ms = Just $ SearchResult (fromIntegral $ length ms) v fix :: Text -> [Text] fix = filter (not . T.null) . map T.strip . T.words . T.toCaseFold . T.filter (`notElem` ",.-")
null
https://raw.githubusercontent.com/pbrisbin/yesod-goodies/effa9f67b45e7be236ae8037a60a21b406ef05f8/simple-search/Data/SimpleSearch.hs
haskell
----------------------------------------------------------------------------- | License : as-is Maintainer : Stability : unstable Portability : unportable ----------------------------------------------------------------------------- * predefined | A ranked search result | Any item can be searched by providing a @'match'@ function. | Given a search term and some @a@, provide @Just@ a ranked | Identical but discards the actual rank values. | Add (or remove) weight from items that have certian properties. | Reverse sort the results by rank and then preference. | Compare values in a compound way | Being a member of this class means defining the way to represent your type as pure text so it can be searched by keyword, etc. | Search term is interpreted as keywords. Results are ranked by the Nothing.
Module : Data . SimpleSearch Copyright : ( c ) 2010 module Data.SimpleSearch ( SearchResult(..) , Search(..) , search , search_ , weightedSearch , weightedSearch_ , TextSearch(..) , keywordMatch ) where import Data.List (sortBy, intersect) import Data.Ord (comparing) import Data.Maybe (catMaybes) import Data.Text (Text) import qualified Data.Text as T data SearchResult a = SearchResult { searchRank :: Double , searchResult :: a } class Search a where | If two results have the same rank , optionally lend preference to one . The /greater/ value will appear first . preference :: SearchResult a -> SearchResult a -> Ordering preference _ _ = EQ result or @Nothing@. match :: Text -> a -> Maybe (SearchResult a) | Excute a search on a list of @a@s and rank the results search :: Search a => Text -> [a] -> [SearchResult a] search t = rankResults . catMaybes . map (match t) search_ :: Search a => Text -> [a] -> [a] search_ t = map searchResult . search t weightedSearch :: Search a => (a -> Double) -> Text -> [a] -> [SearchResult a] weightedSearch f t = rankResults . map (applyFactor f) . catMaybes . map (match t) where applyFactor :: (a -> Double) -> SearchResult a -> SearchResult a applyFactor f' (SearchResult d v) = SearchResult (d * f' v) v weightedSearch_ :: Search a => (a -> Double) -> Text -> [a] -> [a] weightedSearch_ f t = map searchResult . weightedSearch f t rankResults :: Search a => [SearchResult a] -> [SearchResult a] rankResults = reverse . sortBy (comparing searchRank `andthen` preference) > sortBy ( comparing snd ` andthen ` comparing fst ) andthen :: (a -> a -> Ordering) -> (a -> a -> Ordering) -> a -> a -> Ordering andthen f g a b = case f a b of EQ -> g a b x -> x class TextSearch a where toText :: a -> Text number of words that appear in the source text , a rank of 0 returns keywordMatch :: TextSearch a => Text -> a -> Maybe (SearchResult a) keywordMatch t v = go $ fix (toText v) `intersect` fix t where go [] = Nothing go ms = Just $ SearchResult (fromIntegral $ length ms) v fix :: Text -> [Text] fix = filter (not . T.null) . map T.strip . T.words . T.toCaseFold . T.filter (`notElem` ",.-")
60cb69287b77382189bef6cad24e7ab45df8962daae93debc2ef45f352f04564
dimitri/pgloader
queries.lisp
;;; ;;; Load SQL queries at load-time into an hash table and offer a function to ;;; get the SQL query text from the source code. This allows to maintain ;;; proper .sql files in the source code, for easier maintenance. ;;; (in-package :pgloader.queries) (defparameter *src* (uiop:pathname-directory-pathname (asdf:system-relative-pathname :pgloader "src/")) "Source directory where to look for .sql query files.") (defun load-static-file (fs pathname url) "Load given PATHNAME contents at URL-PATH in FS." (setf (gethash url fs) (alexandria:read-file-into-string pathname))) (defun pathname-to-url (pathname &optional (root *src*)) "Transform given PATHNAME into an URL at which to serve it within URL-PATH." (multiple-value-bind (flag path-list last-component file-namestring-p) (uiop:split-unix-namestring-directory-components (uiop:unix-namestring (uiop:enough-pathname pathname root))) (declare (ignore flag file-namestring-p)) ;; ;; we store SQL queries in a sql/ subdirectory because it's easier to ;; manage the code that way, but it's an implementation detail that we ;; are hiding in the query url abstraction... ;; ;; then do the same thing with the "sources" in /src/sources/.../sql/... ;; (let ((no-sql-path-list (remove-if (lambda (path) (member path (list "sources" "sql") :test #'string=)) path-list))) (format nil "~{/~a~}/~a" no-sql-path-list last-component)))) (defun load-static-directory (fs &optional (root *src*)) "Walk PATH and load all files found in there as binary sequence, FS being an hash table referencing the full path against the bytes." (flet ((collectp (dir) (declare (ignore dir)) t) (recursep (dir) (declare (ignore dir)) t) (collector (dir) (loop :for pathname :in (uiop:directory-files dir) :do (when (string= "sql" (pathname-type pathname)) (let ((url (pathname-to-url pathname root))) (load-static-file fs pathname url)))))) (uiop:collect-sub*directories root #'collectp #'recursep #'collector))) (defun walk-sources-and-build-fs () (let ((fs (make-hash-table :test #'equal))) (load-static-directory fs) fs)) (defparameter *fs* (walk-sources-and-build-fs) "File system as an hash-table in memory.") (defun sql (url &rest args) "Abstract the hash-table based implementation of our SQL file system." (restart-case (apply #'format nil (or (gethash url *fs*) (error "URL ~s not found!" url)) args) (recompute-fs-and-retry () (setf *fs* (walk-sources-and-build-fs)) (sql url)))) (defun sql-url-for-variant (base filename &optional variant) "Build a SQL URL for given VARIANT" (flet ((sql-base-url (base filename) (format nil "/~a/~a" base filename))) (if variant (let ((sql-variant-url (format nil "/~a/~a/~a" base (string-downcase (typecase variant (symbol (symbol-name variant)) (string variant) (t (princ-to-string variant)))) filename))) (if (gethash sql-variant-url *fs*) sql-variant-url (sql-base-url base filename))) (sql-base-url base filename))))
null
https://raw.githubusercontent.com/dimitri/pgloader/75c00b5ff47c46c77ed22e84730ebdcb1fcfe7a1/src/utils/queries.lisp
lisp
Load SQL queries at load-time into an hash table and offer a function to get the SQL query text from the source code. This allows to maintain proper .sql files in the source code, for easier maintenance. we store SQL queries in a sql/ subdirectory because it's easier to manage the code that way, but it's an implementation detail that we are hiding in the query url abstraction... then do the same thing with the "sources" in /src/sources/.../sql/...
(in-package :pgloader.queries) (defparameter *src* (uiop:pathname-directory-pathname (asdf:system-relative-pathname :pgloader "src/")) "Source directory where to look for .sql query files.") (defun load-static-file (fs pathname url) "Load given PATHNAME contents at URL-PATH in FS." (setf (gethash url fs) (alexandria:read-file-into-string pathname))) (defun pathname-to-url (pathname &optional (root *src*)) "Transform given PATHNAME into an URL at which to serve it within URL-PATH." (multiple-value-bind (flag path-list last-component file-namestring-p) (uiop:split-unix-namestring-directory-components (uiop:unix-namestring (uiop:enough-pathname pathname root))) (declare (ignore flag file-namestring-p)) (let ((no-sql-path-list (remove-if (lambda (path) (member path (list "sources" "sql") :test #'string=)) path-list))) (format nil "~{/~a~}/~a" no-sql-path-list last-component)))) (defun load-static-directory (fs &optional (root *src*)) "Walk PATH and load all files found in there as binary sequence, FS being an hash table referencing the full path against the bytes." (flet ((collectp (dir) (declare (ignore dir)) t) (recursep (dir) (declare (ignore dir)) t) (collector (dir) (loop :for pathname :in (uiop:directory-files dir) :do (when (string= "sql" (pathname-type pathname)) (let ((url (pathname-to-url pathname root))) (load-static-file fs pathname url)))))) (uiop:collect-sub*directories root #'collectp #'recursep #'collector))) (defun walk-sources-and-build-fs () (let ((fs (make-hash-table :test #'equal))) (load-static-directory fs) fs)) (defparameter *fs* (walk-sources-and-build-fs) "File system as an hash-table in memory.") (defun sql (url &rest args) "Abstract the hash-table based implementation of our SQL file system." (restart-case (apply #'format nil (or (gethash url *fs*) (error "URL ~s not found!" url)) args) (recompute-fs-and-retry () (setf *fs* (walk-sources-and-build-fs)) (sql url)))) (defun sql-url-for-variant (base filename &optional variant) "Build a SQL URL for given VARIANT" (flet ((sql-base-url (base filename) (format nil "/~a/~a" base filename))) (if variant (let ((sql-variant-url (format nil "/~a/~a/~a" base (string-downcase (typecase variant (symbol (symbol-name variant)) (string variant) (t (princ-to-string variant)))) filename))) (if (gethash sql-variant-url *fs*) sql-variant-url (sql-base-url base filename))) (sql-base-url base filename))))
28c9a2c826653d40040156a28ad113374c934c66937a9745f3a539c761f4b8b8
lpeterse/koka
ColorScheme.hs
----------------------------------------------------------------------------- Copyright 2012 Microsoft Corporation . -- -- This is free software; you can redistribute it and/or modify it under the terms of the Apache License , Version 2.0 . A copy of the License can be found in the file " license.txt " at the root of this distribution . ----------------------------------------------------------------------------- {- | Global color scheme used for pretty printing. -} module Common.ColorScheme( ColorScheme(..) , Color(..) , defaultColorScheme -- * Flags , readColorFlags ) where import Data.Char( toLower, isSpace ) import Lib.PPrint import Lib.Printer ------------------------------------------------------------------------- ------------------------------------------------------------------------- ColorScheme --------------------------------------------------------------------------} -- | Color scheme for the interpreter data ColorScheme = ColorScheme { colorType :: Color , colorParameter :: Color , colorKind :: Color , colorMarker :: Color , colorWarning :: Color , colorError :: Color , colorSource :: Color , colorInterpreter :: Color , colorKeyword :: Color , colorEffect :: Color , colorRange :: Color , colorSep :: Color -- syntax coloring , colorComment :: Color , colorReserved:: Color , colorReservedOp:: Color , colorSpecial :: Color , colorString :: Color , colorNumber :: Color , colorModule :: Color , colorCons :: Color , colorTypeCon :: Color , colorTypeVar :: Color , colorTypeKeyword :: Color , colorTypeKeywordOp :: Color , colorTypeSpecial :: Color , colorTypeParam :: Color } -- | The default color scheme defaultColorScheme :: ColorScheme defaultColorScheme = let c = emptyColorScheme{ colorInterpreter = Red , colorError = Red , colorComment = DarkGreen , colorReserved = White , colorModule = White , colorString = DarkRed , colorSource = Gray , colorParameter = DarkGray , colorRange = colorInterpreter c , colorMarker = colorInterpreter c , colorWarning = colorError c colorSource c , colorEffect = colorType c , colorTypeVar = colorType c , colorTypeCon = colorType c , colorKeyword = colorReserved c , colorTypeSpecial = colorType c , colorTypeKeyword = Cyan -- colorReserved c , colorTypeKeywordOp = colorType c -- colorReservedOp c , colorTypeParam = colorParameter c , colorCons = DarkMagenta } in c emptyColorScheme = ColorScheme ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault {-------------------------------------------------------------------------- Read colors --------------------------------------------------------------------------} -- | Read a comma seperated list of name=color pairs. readColorFlags :: String -> ColorScheme -> ColorScheme readColorFlags s scheme = foldl (flip readColorFlag) scheme (split s) where split :: String -> [String] split xs = let (pre,ys) = span (/=',') xs in case ys of (',':post) -> pre : split post [] -> [pre] _ -> [pre,ys] -- impossible case -- | Read a name=color flag. readColorFlag :: String -> ColorScheme -> ColorScheme readColorFlag s scheme = let (name,xs) = span (/='=') s in case xs of ('=':clr) -> case (readUpdate name, readColor clr) of (Just update,Just color) -> update color scheme _ -> scheme _ -> scheme readUpdate :: String -> Maybe (Color -> ColorScheme -> ColorScheme) readUpdate s = lookup (norm s) updaters readColor :: String -> Maybe Color readColor s = lookup (norm s) colors norm :: String -> String norm s = map toLower (reverse (nowhite (reverse (nowhite s)))) where nowhite s = dropWhile isSpace s {-------------------------------------------------------------------------- Tables --------------------------------------------------------------------------} updaters = [("type", \color scheme -> scheme{ colorType = color, colorTypeCon = color, colorTypeVar = color, colorTypeKeyword = color, colorEffect = color }) ,("kind", \color scheme -> scheme{ colorKind = color }) ,("marker", \color scheme -> scheme{ colorMarker = color }) ,("warning", \color scheme -> scheme{ colorWarning = color }) ,("error", \color scheme -> scheme{ colorError = color }) ,("source", \color scheme -> scheme{ colorSource = color }) ,("interpreter", \color scheme -> scheme{ colorInterpreter = color }) ,("keyword", \color scheme -> scheme{ colorKeyword = color, colorTypeKeyword = color }) ,("typecon", \color scheme -> scheme{ colorTypeCon = color }) ,("typevar", \color scheme -> scheme{ colorTypeVar = color }) ,("typekeyword", \color scheme -> scheme{ colorTypeKeyword = color }) ,("range", \color scheme -> scheme{ colorRange = color }) ,("sep", \color scheme -> scheme{ colorSep = color }) ,("comment", \color scheme -> scheme{ colorComment = color }) ,("reserved", \color scheme -> scheme{ colorReserved = color }) ,("reservedop", \color scheme -> scheme{ colorReservedOp = color }) ,("special", \color scheme -> scheme{ colorSpecial = color }) ,("string", \color scheme -> scheme{ colorString = color }) ,("number", \color scheme -> scheme{ colorNumber = color }) ,("module", \color scheme -> scheme{ colorModule = color }) ,("effect", \color scheme -> scheme{ colorEffect = color }) ,("parameter",\color scheme -> scheme{ colorParameter = color }) ,("cons",\color scheme -> scheme{ colorCons = color }) ] colors = [("black",Black) ,("darkred",DarkRed) ,("darkgreen",DarkGreen) ,("darkyellow",DarkYellow) ,("darkblue",DarkBlue) ,("darkmagenta",DarkMagenta) ,("darkcyan",DarkCyan) ,("lightgray",Gray) ,("gray",DarkGray) ,("red",Red) ,("green",Green) ,("yellow",Yellow) ,("blue",Blue) ,("magenta",Magenta) ,("cyan",Cyan) ,("white",White) ,("default",ColorDefault) -- other spellings ,("lightgrey",Gray) ,("grey",DarkGray) ,("darkgrey",DarkGray) -- other words ,("navy",DarkBlue) ,("teal",DarkCyan) ,("maroon",DarkRed) ,("purple",DarkMagenta) ,("olive",DarkYellow) ,("silver",Gray) ,("lime",Green) ,("aqua",Cyan) ,("fuchsia",Magenta) ,("darkgray",DarkGray) ]
null
https://raw.githubusercontent.com/lpeterse/koka/43feefed258b9a533f07967d3f8867b02384df0e/src/Common/ColorScheme.hs
haskell
--------------------------------------------------------------------------- This is free software; you can redistribute it and/or modify it under the --------------------------------------------------------------------------- | Global color scheme used for pretty printing. * Flags ----------------------------------------------------------------------- ----------------------------------------------------------------------- ------------------------------------------------------------------------} | Color scheme for the interpreter syntax coloring | The default color scheme colorReserved c colorReservedOp c ------------------------------------------------------------------------- Read colors ------------------------------------------------------------------------- | Read a comma seperated list of name=color pairs. impossible case | Read a name=color flag. ------------------------------------------------------------------------- Tables ------------------------------------------------------------------------- other spellings other words
Copyright 2012 Microsoft Corporation . terms of the Apache License , Version 2.0 . A copy of the License can be found in the file " license.txt " at the root of this distribution . module Common.ColorScheme( ColorScheme(..) , Color(..) , defaultColorScheme , readColorFlags ) where import Data.Char( toLower, isSpace ) import Lib.PPrint import Lib.Printer ColorScheme data ColorScheme = ColorScheme { colorType :: Color , colorParameter :: Color , colorKind :: Color , colorMarker :: Color , colorWarning :: Color , colorError :: Color , colorSource :: Color , colorInterpreter :: Color , colorKeyword :: Color , colorEffect :: Color , colorRange :: Color , colorSep :: Color , colorComment :: Color , colorReserved:: Color , colorReservedOp:: Color , colorSpecial :: Color , colorString :: Color , colorNumber :: Color , colorModule :: Color , colorCons :: Color , colorTypeCon :: Color , colorTypeVar :: Color , colorTypeKeyword :: Color , colorTypeKeywordOp :: Color , colorTypeSpecial :: Color , colorTypeParam :: Color } defaultColorScheme :: ColorScheme defaultColorScheme = let c = emptyColorScheme{ colorInterpreter = Red , colorError = Red , colorComment = DarkGreen , colorReserved = White , colorModule = White , colorString = DarkRed , colorSource = Gray , colorParameter = DarkGray , colorRange = colorInterpreter c , colorMarker = colorInterpreter c , colorWarning = colorError c colorSource c , colorEffect = colorType c , colorTypeVar = colorType c , colorTypeCon = colorType c , colorKeyword = colorReserved c , colorTypeSpecial = colorType c , colorTypeParam = colorParameter c , colorCons = DarkMagenta } in c emptyColorScheme = ColorScheme ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault ColorDefault readColorFlags :: String -> ColorScheme -> ColorScheme readColorFlags s scheme = foldl (flip readColorFlag) scheme (split s) where split :: String -> [String] split xs = let (pre,ys) = span (/=',') xs in case ys of (',':post) -> pre : split post [] -> [pre] readColorFlag :: String -> ColorScheme -> ColorScheme readColorFlag s scheme = let (name,xs) = span (/='=') s in case xs of ('=':clr) -> case (readUpdate name, readColor clr) of (Just update,Just color) -> update color scheme _ -> scheme _ -> scheme readUpdate :: String -> Maybe (Color -> ColorScheme -> ColorScheme) readUpdate s = lookup (norm s) updaters readColor :: String -> Maybe Color readColor s = lookup (norm s) colors norm :: String -> String norm s = map toLower (reverse (nowhite (reverse (nowhite s)))) where nowhite s = dropWhile isSpace s updaters = [("type", \color scheme -> scheme{ colorType = color, colorTypeCon = color, colorTypeVar = color, colorTypeKeyword = color, colorEffect = color }) ,("kind", \color scheme -> scheme{ colorKind = color }) ,("marker", \color scheme -> scheme{ colorMarker = color }) ,("warning", \color scheme -> scheme{ colorWarning = color }) ,("error", \color scheme -> scheme{ colorError = color }) ,("source", \color scheme -> scheme{ colorSource = color }) ,("interpreter", \color scheme -> scheme{ colorInterpreter = color }) ,("keyword", \color scheme -> scheme{ colorKeyword = color, colorTypeKeyword = color }) ,("typecon", \color scheme -> scheme{ colorTypeCon = color }) ,("typevar", \color scheme -> scheme{ colorTypeVar = color }) ,("typekeyword", \color scheme -> scheme{ colorTypeKeyword = color }) ,("range", \color scheme -> scheme{ colorRange = color }) ,("sep", \color scheme -> scheme{ colorSep = color }) ,("comment", \color scheme -> scheme{ colorComment = color }) ,("reserved", \color scheme -> scheme{ colorReserved = color }) ,("reservedop", \color scheme -> scheme{ colorReservedOp = color }) ,("special", \color scheme -> scheme{ colorSpecial = color }) ,("string", \color scheme -> scheme{ colorString = color }) ,("number", \color scheme -> scheme{ colorNumber = color }) ,("module", \color scheme -> scheme{ colorModule = color }) ,("effect", \color scheme -> scheme{ colorEffect = color }) ,("parameter",\color scheme -> scheme{ colorParameter = color }) ,("cons",\color scheme -> scheme{ colorCons = color }) ] colors = [("black",Black) ,("darkred",DarkRed) ,("darkgreen",DarkGreen) ,("darkyellow",DarkYellow) ,("darkblue",DarkBlue) ,("darkmagenta",DarkMagenta) ,("darkcyan",DarkCyan) ,("lightgray",Gray) ,("gray",DarkGray) ,("red",Red) ,("green",Green) ,("yellow",Yellow) ,("blue",Blue) ,("magenta",Magenta) ,("cyan",Cyan) ,("white",White) ,("default",ColorDefault) ,("lightgrey",Gray) ,("grey",DarkGray) ,("darkgrey",DarkGray) ,("navy",DarkBlue) ,("teal",DarkCyan) ,("maroon",DarkRed) ,("purple",DarkMagenta) ,("olive",DarkYellow) ,("silver",Gray) ,("lime",Green) ,("aqua",Cyan) ,("fuchsia",Magenta) ,("darkgray",DarkGray) ]
12495289a353a79d7cd9441fda23d1463a041bec6dbd9c87fdc74f08a7e06716
ocsigen/js_of_ocaml
webSockets.mli
Js_of_ocaml library * / * Copyright ( C ) 2012 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2012 Jacques-Pascal Deplaix * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (** WebSocket binding *) type readyState = | CONNECTING | OPEN | CLOSING | CLOSED class type ['a] closeEvent = object inherit ['a] Dom.event method code : int Js.readonly_prop method reason : Js.js_string Js.t Js.readonly_prop method wasClean : bool Js.t Js.readonly_prop end class type ['a] messageEvent = object inherit ['a] Dom.event method data : Js.js_string Js.t Js.readonly_prop method data_buffer : Typed_array.arrayBuffer Js.t Js.readonly_prop method data_blob : File.blob Js.t Js.readonly_prop end class type webSocket = object ('self) inherit Dom_html.eventTarget method url : Js.js_string Js.t Js.readonly_prop method readyState : readyState Js.readonly_prop method bufferedAmount : int Js.readonly_prop method onopen : ('self Js.t, 'self Dom.event Js.t) Dom.event_listener Js.writeonly_prop method onclose : ('self Js.t, 'self closeEvent Js.t) Dom.event_listener Js.writeonly_prop method onerror : ('self Js.t, 'self Dom.event Js.t) Dom.event_listener Js.writeonly_prop method extensions : Js.js_string Js.t Js.readonly_prop method protocol : Js.js_string Js.t Js.readonly_prop method close : unit Js.meth method close_withCode : int -> unit Js.meth method close_withCodeAndReason : int -> Js.js_string Js.t -> unit Js.meth method onmessage : ('self Js.t, 'self messageEvent Js.t) Dom.event_listener Js.writeonly_prop method binaryType : Js.js_string Js.t Js.prop method send : Js.js_string Js.t -> unit Js.meth method send_buffer : Typed_array.arrayBuffer Js.t -> unit Js.meth method send_blob : File.blob Js.t -> unit Js.meth end val webSocket : (Js.js_string Js.t -> webSocket Js.t) Js.constr val webSocket_withProtocol : (Js.js_string Js.t -> Js.js_string Js.t -> webSocket Js.t) Js.constr val webSocket_withProtocols : (Js.js_string Js.t -> Js.js_string Js.t Js.js_array Js.t -> webSocket Js.t) Js.constr val is_supported : unit -> bool
null
https://raw.githubusercontent.com/ocsigen/js_of_ocaml/58210fabc947c4839b6e71ffbbf353a4ede0dbb7/lib/js_of_ocaml/webSockets.mli
ocaml
* WebSocket binding
Js_of_ocaml library * / * Copyright ( C ) 2012 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2012 Jacques-Pascal Deplaix * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) type readyState = | CONNECTING | OPEN | CLOSING | CLOSED class type ['a] closeEvent = object inherit ['a] Dom.event method code : int Js.readonly_prop method reason : Js.js_string Js.t Js.readonly_prop method wasClean : bool Js.t Js.readonly_prop end class type ['a] messageEvent = object inherit ['a] Dom.event method data : Js.js_string Js.t Js.readonly_prop method data_buffer : Typed_array.arrayBuffer Js.t Js.readonly_prop method data_blob : File.blob Js.t Js.readonly_prop end class type webSocket = object ('self) inherit Dom_html.eventTarget method url : Js.js_string Js.t Js.readonly_prop method readyState : readyState Js.readonly_prop method bufferedAmount : int Js.readonly_prop method onopen : ('self Js.t, 'self Dom.event Js.t) Dom.event_listener Js.writeonly_prop method onclose : ('self Js.t, 'self closeEvent Js.t) Dom.event_listener Js.writeonly_prop method onerror : ('self Js.t, 'self Dom.event Js.t) Dom.event_listener Js.writeonly_prop method extensions : Js.js_string Js.t Js.readonly_prop method protocol : Js.js_string Js.t Js.readonly_prop method close : unit Js.meth method close_withCode : int -> unit Js.meth method close_withCodeAndReason : int -> Js.js_string Js.t -> unit Js.meth method onmessage : ('self Js.t, 'self messageEvent Js.t) Dom.event_listener Js.writeonly_prop method binaryType : Js.js_string Js.t Js.prop method send : Js.js_string Js.t -> unit Js.meth method send_buffer : Typed_array.arrayBuffer Js.t -> unit Js.meth method send_blob : File.blob Js.t -> unit Js.meth end val webSocket : (Js.js_string Js.t -> webSocket Js.t) Js.constr val webSocket_withProtocol : (Js.js_string Js.t -> Js.js_string Js.t -> webSocket Js.t) Js.constr val webSocket_withProtocols : (Js.js_string Js.t -> Js.js_string Js.t Js.js_array Js.t -> webSocket Js.t) Js.constr val is_supported : unit -> bool
4c23d34513330d5fbe57127dc775bd70c04d127d13d1abb704fb64be0b822b49
halgari/mjolnir
ssa_rules.clj
(ns mjolnir.ssa-rules (:require [clojure.pprint :refer [pprint]] [datomic.api :refer [db q] :as d])) (def rules (atom [])) (defmacro defrule [name args doc & body] #_(println "Registered rule" name ) (swap! rules conj `[(~name ~@args) ~@body]) nil) ;; Utility (defrule global-def [?id ?name ?type] "Functions are global entities" [?id :node/type :node.type/fn] [?id :fn/name ?name] [?id :fn/type ?type]) (defrule global-def [?id ?name ?type] "Functions are global entities" [?id :global/name ?name] [?id :global/type ?type]) ;; Inference Rules (defrule infer-node [?id ?attr ?val] "infer return-types" [?no-type :node/type :node.type/unknown] [?id :node/return-type ?no-type] (return-type ?id ?val) [(identity :node/return-type) ?attr]) #_(defrule infer-binop-node [?id ?attr ?val] "infer binop subtypes" (infer-binop ?id ?val) [(identity :inst.binop/sub-type) ?attr]) #_(defrule infer-node [?id ?attr ?val] "infer cmp" (infer-cmp-node ?id ?attr ?val)) (defrule infer-node [?id ?attr ?val] "infer casts" [?id :inst/type :inst.type/cast] [?id :inst.cast/type :inst.cast/unknown] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?arg0-t) [?id :node/return-type ?arg1-t] (cast-subtype ?id ?arg0-t ?arg1-t ?val) [(identity :inst.cast/type) ?attr]) ;; (defrule return-type [?id ?type] "Anything with :node/return-type returns that type" [?id :node/return-type ?type] [?no-type :node/type :node.type/unknown] [(not= ?type ?no-type)]) (defrule return-type [?id ?type] "Consts return their given type, if it exists" [?id :inst/type :inst.type/const] [?id :const/type ?type]) (defrule return-type [?id ?type] "Binops return the same type as their args" [?id :inst/type :inst.type/binop] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] #_(return-type ?arg0 ?type) (return-type ?arg1 ?type)) (defrule infer-phi-return-type [?id ?type] "Phi nodes always return the return type of one of their values" [?phi :phi.value/node ?id] [?phi :phi.value/value ?arg] [?arg :node/return-type ?type] #_(return-type ?arg ?type)) (defrule return-type [?id ?type] "Phi nodes always return the return type of one of their values" [?phi :phi.value/node ?id] [?phi :phi.value/value ?arg] #_[?arg :node/return-type ?type] (return-type ?arg ?type)) (defrule return-type [?id ?type] "Globals return the type of the matching global" [?id :inst/type :inst.type/gbl] [?id :inst.gbl/name ?name] (global-def ?gbl ?name ?type)) (defrule return-type [?id ?type] "Function calls return the return type of the function they are calling" [?id :inst/type :inst.type/call] [?id :inst.call/fn ?fn-src] (return-type ?fn-src ?fn-t) [?fn-t :type.fn/return ?type]) (defrule return-type [?id ?type] "Function pointer calls return the return type of the function they are calling" [?id :inst/type :inst.type/callp] [?id :inst.callp/fn ?fn-src] (return-type ?fn-src ?ptr-t) [?ptr-t :type/element-type ?fn-t] [?fn-t :type.fn/return ?type]) (defrule return-type [?id ?type] "Arg instructions return the type from the function type" [?id :inst/type :inst.type/arg] [?id :inst/block ?block] [?block :block/fn ?fn] [?fn :fn/type ?fn-t] [?arg-node :fn.arg/fn ?fn-t] [?id :inst.arg/idx ?idx] [?arg-node :fn.arg/idx ?idx] [?arg-node :fn.arg/type ?type]) (defrule return-type [?id ?type] "Store returns the ptr type" [?id :inst/type :inst.type/store] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?type)) (defrule return-type [?id ?type] "ASet returns the arr type" [?id :inst/type :inst.type/aset] [?id :inst.arg/arg0 ?arg0] [?arg0 :inst/type ?v] (return-type ?arg0 ?type)) (defrule return-type [?id ?type] "AGet returns the element type" [?id :inst/type :inst.type/aget] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?arg0-t) [?arg0-t :type/element-type ?type] [?type :node/type ?nt]) (defrule return-type [?id ?type] "Nth returns the same type as the input" [?id :inst/type :inst.type/nth] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?type)) (defrule member-idx [?tp ?nm ?idx ?member-tp] "Gets the idx of a member" [?mbr :type.member/struct ?tp] [?mbr :type.member/idx ?idx] [?mbr :type.member/name ?nm] [?mbr :type.member/type ?member-tp]) (defrule return-type [?id ?type] "Set returns the same type as the ptr" [?id :inst/type :inst.type/set] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?type)) (defrule return-type [?id ?type] "Get returns the member type" [?id :inst/type :inst.type/get] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?arg0-t) [?arg0-t :type/element-type ?etype] [?id :inst.get/member ?nm] (member-idx ?etype ?nm ?idx ?type)) (defrule return-type [?id ?type] "Atomic ops return the same type as the input value" [?id :inst/type :inst.type/atomic] [?id :inst.arg/arg1 ?arg1] (return-type ?arg1 ?type)) (defrule validate [?id ?msg] "Binops must have the same types for all args" [?id :inst/type :inst.type/binop] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] (return-type ?arg0 ?arg0-tp) (return-type ?arg1 ?arg1-tp) #_(return-type ?id ?this-tp) [(not= ?arg0-tp ?arg1-tp)] [(identity "Binop args must match return type") ?msg]) (defn func-arg-count-dont-match? [db tp-id call-id] (let [call-ent (d/entity db call-id) tp-ent (d/entity db tp-id)] (not= (count (:fn.arg/_fn tp-ent)) ;; decrement this, as we include :inst.call/fn (dec (count (:inst/args call-ent)))))) (defrule validate [?id ?msg] "Calls must match argument counts" [?id :inst/type :inst.type/call] [?id :inst.call/fn ?gbl] [?gbl :inst.gbl/name ?name] [?gbl :node/return-type ?tp] [(mjolnir.ssa-rules/func-arg-count-dont-match? $ ?tp ?id)] [(str "Call signature doesn't match function, calling " ?name) ?msg]) (defrule validate [?id ?msg] "Args must match types" [?id :inst/type :inst.type/call] [?id :inst.arg/arg0 ?arg] [?arg :node/return-type ?arg-t] [?id :inst.call/fn ?fn] [?fn :inst.gbl/name ?name] [?fn :node/return-type ?fn-t] [?fn-arg :fn.arg/fn ?fn-t] [?fn-arg :fn.arg/idx 0] [?fn-arg :fn.arg/type ?fn-arg-t] [(not= ?fn-arg-t ?arg-t)] [?fn-arg-t :node/type ?fn-arg-t-node] [?arg-t :node/type ?arg-t-node] [?id :inst/block ?block] [?block :block/fn ?parent-fn] [?parent-fn :fn/name ?parent-fn-name] [(str "Arg0 doesn't match in call to " ?name " types " ?fn-arg-t-node " " ?arg-t-node " in " ?parent-fn-name) ?msg]) (defrule validate [?id ?msg] "Args must match types" [?id :inst/type :inst.type/call] [?id :inst.arg/arg1 ?arg] [?arg :node/return-type ?arg-t] [?id :inst.call/fn ?fn] [?fn :inst.gbl/name ?name] [?fn :node/return-type ?fn-t] [?fn-arg :fn.arg/fn ?fn-t] [?fn-arg :fn.arg/idx 1] [?fn-arg :fn.arg/type ?fn-arg-t] [(not= ?fn-arg-t ?arg-t)] [(str "Arg1 doesn't match in call to " ?name) ?msg]) (defrule validate [?id ?msg] "Args must match types" [?id :inst/type :inst.type/call] [?id :inst.arg/arg2 ?arg] [?arg :node/return-type ?arg-t] [?id :inst.call/fn ?fn] [?fn :inst.gbl/name ?name] [?fn :node/return-type ?fn-t] [?fn-arg :fn.arg/fn ?fn-t] [?fn-arg :fn.arg/idx 2] [?fn-arg :fn.arg/type ?fn-arg-t] [(not= ?fn-arg-t ?arg-t)] [(str "Arg2 doesn't match in call to " ?name) ?msg]) rules - These rules define an attribute that helps emitters decide if a binop is a Float or Int operation . FMul is different from IMul , so this code specializes that information . (comment (defrule infer-binop [?id ?op] "A binop of two ints " [?id :inst/type :inst.type/binop] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] (return-type ?arg0 ?arg0-t) (return-type ?arg1 ?arg1-t) (binop-subtype ?id ?arg0-t ?arg1-t ?op)) (defrule binop-subtype [?type ?arg0-t ?arg1-t ?op] "Int + resolves to :iadd" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/int] [?type :inst.binop/type ?binop] [(mjolnir.ssa-rules/binop-int-translation ?binop) ?op]) (defrule binop-subtype [?type ?arg0-t ?arg1-t ?op] "Float + resolves to :iadd" [?arg0-t :node/type :type/float] [?arg1-t :node/type :type/float] [?type :inst.binop/type ?binop] [(mjolnir.ssa-rules/binop-float-translation ?binop) ?op])) ;; Cast subtype (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/int] [?arg0-t :type/length ?arg0-length] [?arg1-t :type/length ?arg1-length] [(> ?arg0-length ?arg1-length)] [(identity :inst.cast.type/trunc) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/int] [?arg0-t :type/length ?arg0-length] [?arg1-t :type/length ?arg1-length] [(< ?arg0-length ?arg1-length)] [(identity :inst.cast.type/zext) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Floats cast to int" [?arg0-t :node/type :type/float] [?arg1-t :node/type :type/int] [(identity :inst.cast.type/fp-to-si) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Ints cast to floats" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/float] [(identity :inst.cast.type/si-to-fp) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Pointers are bitcast" [?arg0-t :node/type :type/pointer] [?arg1-t :node/type :type/pointer] [(identity :inst.cast.type/bitcast) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Functions can be bitcast" [?arg0-t :node/type :type/fn] [?arg1-t :node/type :type/pointer] [(identity :inst.cast.type/bitcast) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/pointer] [?arg1-t :node/type :type/int] [(identity :inst.cast.type/ptr-to-int) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/pointer] [(identity :inst.cast.type/int-to-ptr) ?op]) ;; Cmp predicate inference (def cmp-map {[:type/int :type/int :inst.cmp.pred/=] :inst.cmp.sub-pred/int-eq [:type/int :type/int :inst.cmp.pred/not=] :inst.cmp.sub-pred/int-ne [:type/int :type/int :inst.cmp.pred/>] :inst.cmp.sub-pred/int-sgt [:type/int :type/int :inst.cmp.pred/<] :inst.cmp.sub-pred/int-slt [:type/int :type/int :inst.cmp.pred/<=] :inst.cmp.sub-pred/int-sle [:type/int :type/int :inst.cmp.pred/>=] :inst.cmp.sub-pred/int-sge [:type/float :type/float :inst.cmp.pred/=] :inst.cmp.sub-pred/real-oeq [:type/float :type/float :inst.cmp.pred/not=] :inst.cmp.sub-pred/real-one [:type/float :type/float :inst.cmp.pred/>] :inst.cmp.sub-pred/real-ogt [:type/float :type/float :inst.cmp.pred/<] :inst.cmp.sub-pred/real-olt [:type/float :type/float :inst.cmp.pred/<=] :inst.cmp.sub-pred/real-ole [:type/float :type/float :inst.cmp.pred/>=] :inst.cmp.sub-pred/real-oge}) #_(defrule infer-cmp-node [?id ?attr ?val] "Infer cmp predicate" [?id :inst/type :inst.type/cmp] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] [?id :inst.cmp/pred ?pred] (return-type ?arg0 ?arg0-t) (return-type ?arg1 ?arg1-t) [?arg0-t :node/type ?arg0-tg] [?arg1-t :node/type ?arg1-tg] [(vector ?arg0-tg ?arg1-tg ?pred) ?key] [(mjolnir.ssa-rules/cmp-map ?key) ?val] [(identity :inst.cmp/sub-pred) ?attr]) (comment ;; For a block, gets the instructions in the block (defrule instruction-seq [?block ?inst] "All instructions attached to the block should be considered" [?block :inst/block ?inst]) (defrule instruction-seq [?block ?inst] "Terminator instructions should be considered" [?block :block/terminator-inst ?inst]) (defrule depends-on [?block-a ?block-b] "Rule passes if block-a requires block-b before it can be built" [(mjolnir.ssa-rules/arg-k) [?attr ...]] (instruction-seq ?block-a ?inst-a) [?inst-a ?attr ?inst-b] [?inst-b :inst/block ?block-b] [(not= ?block-a ?block-b)]) (defrule depends-on [?block-a ?block-b] "Rule passes if block-a requires block-b before it can be built" [(mjolnir.ssa-rules/arg-k) [?attr ...]] (instruction-seq ?block-a ?inst-a) [?inst-a ?attr ?inst-b] [?inst-b :phi/block ?block-b] [(not= ?block-a ?block-b)]))
null
https://raw.githubusercontent.com/halgari/mjolnir/cfb82a55bc316a6a0e235b46f6ee04c6b55c8cc5/src/mjolnir/ssa_rules.clj
clojure
Utility Inference Rules decrement this, as we include :inst.call/fn Cast subtype Cmp predicate inference For a block, gets the instructions in the block
(ns mjolnir.ssa-rules (:require [clojure.pprint :refer [pprint]] [datomic.api :refer [db q] :as d])) (def rules (atom [])) (defmacro defrule [name args doc & body] #_(println "Registered rule" name ) (swap! rules conj `[(~name ~@args) ~@body]) nil) (defrule global-def [?id ?name ?type] "Functions are global entities" [?id :node/type :node.type/fn] [?id :fn/name ?name] [?id :fn/type ?type]) (defrule global-def [?id ?name ?type] "Functions are global entities" [?id :global/name ?name] [?id :global/type ?type]) (defrule infer-node [?id ?attr ?val] "infer return-types" [?no-type :node/type :node.type/unknown] [?id :node/return-type ?no-type] (return-type ?id ?val) [(identity :node/return-type) ?attr]) #_(defrule infer-binop-node [?id ?attr ?val] "infer binop subtypes" (infer-binop ?id ?val) [(identity :inst.binop/sub-type) ?attr]) #_(defrule infer-node [?id ?attr ?val] "infer cmp" (infer-cmp-node ?id ?attr ?val)) (defrule infer-node [?id ?attr ?val] "infer casts" [?id :inst/type :inst.type/cast] [?id :inst.cast/type :inst.cast/unknown] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?arg0-t) [?id :node/return-type ?arg1-t] (cast-subtype ?id ?arg0-t ?arg1-t ?val) [(identity :inst.cast/type) ?attr]) (defrule return-type [?id ?type] "Anything with :node/return-type returns that type" [?id :node/return-type ?type] [?no-type :node/type :node.type/unknown] [(not= ?type ?no-type)]) (defrule return-type [?id ?type] "Consts return their given type, if it exists" [?id :inst/type :inst.type/const] [?id :const/type ?type]) (defrule return-type [?id ?type] "Binops return the same type as their args" [?id :inst/type :inst.type/binop] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] #_(return-type ?arg0 ?type) (return-type ?arg1 ?type)) (defrule infer-phi-return-type [?id ?type] "Phi nodes always return the return type of one of their values" [?phi :phi.value/node ?id] [?phi :phi.value/value ?arg] [?arg :node/return-type ?type] #_(return-type ?arg ?type)) (defrule return-type [?id ?type] "Phi nodes always return the return type of one of their values" [?phi :phi.value/node ?id] [?phi :phi.value/value ?arg] #_[?arg :node/return-type ?type] (return-type ?arg ?type)) (defrule return-type [?id ?type] "Globals return the type of the matching global" [?id :inst/type :inst.type/gbl] [?id :inst.gbl/name ?name] (global-def ?gbl ?name ?type)) (defrule return-type [?id ?type] "Function calls return the return type of the function they are calling" [?id :inst/type :inst.type/call] [?id :inst.call/fn ?fn-src] (return-type ?fn-src ?fn-t) [?fn-t :type.fn/return ?type]) (defrule return-type [?id ?type] "Function pointer calls return the return type of the function they are calling" [?id :inst/type :inst.type/callp] [?id :inst.callp/fn ?fn-src] (return-type ?fn-src ?ptr-t) [?ptr-t :type/element-type ?fn-t] [?fn-t :type.fn/return ?type]) (defrule return-type [?id ?type] "Arg instructions return the type from the function type" [?id :inst/type :inst.type/arg] [?id :inst/block ?block] [?block :block/fn ?fn] [?fn :fn/type ?fn-t] [?arg-node :fn.arg/fn ?fn-t] [?id :inst.arg/idx ?idx] [?arg-node :fn.arg/idx ?idx] [?arg-node :fn.arg/type ?type]) (defrule return-type [?id ?type] "Store returns the ptr type" [?id :inst/type :inst.type/store] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?type)) (defrule return-type [?id ?type] "ASet returns the arr type" [?id :inst/type :inst.type/aset] [?id :inst.arg/arg0 ?arg0] [?arg0 :inst/type ?v] (return-type ?arg0 ?type)) (defrule return-type [?id ?type] "AGet returns the element type" [?id :inst/type :inst.type/aget] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?arg0-t) [?arg0-t :type/element-type ?type] [?type :node/type ?nt]) (defrule return-type [?id ?type] "Nth returns the same type as the input" [?id :inst/type :inst.type/nth] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?type)) (defrule member-idx [?tp ?nm ?idx ?member-tp] "Gets the idx of a member" [?mbr :type.member/struct ?tp] [?mbr :type.member/idx ?idx] [?mbr :type.member/name ?nm] [?mbr :type.member/type ?member-tp]) (defrule return-type [?id ?type] "Set returns the same type as the ptr" [?id :inst/type :inst.type/set] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?type)) (defrule return-type [?id ?type] "Get returns the member type" [?id :inst/type :inst.type/get] [?id :inst.arg/arg0 ?arg0] (return-type ?arg0 ?arg0-t) [?arg0-t :type/element-type ?etype] [?id :inst.get/member ?nm] (member-idx ?etype ?nm ?idx ?type)) (defrule return-type [?id ?type] "Atomic ops return the same type as the input value" [?id :inst/type :inst.type/atomic] [?id :inst.arg/arg1 ?arg1] (return-type ?arg1 ?type)) (defrule validate [?id ?msg] "Binops must have the same types for all args" [?id :inst/type :inst.type/binop] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] (return-type ?arg0 ?arg0-tp) (return-type ?arg1 ?arg1-tp) #_(return-type ?id ?this-tp) [(not= ?arg0-tp ?arg1-tp)] [(identity "Binop args must match return type") ?msg]) (defn func-arg-count-dont-match? [db tp-id call-id] (let [call-ent (d/entity db call-id) tp-ent (d/entity db tp-id)] (not= (count (:fn.arg/_fn tp-ent)) (dec (count (:inst/args call-ent)))))) (defrule validate [?id ?msg] "Calls must match argument counts" [?id :inst/type :inst.type/call] [?id :inst.call/fn ?gbl] [?gbl :inst.gbl/name ?name] [?gbl :node/return-type ?tp] [(mjolnir.ssa-rules/func-arg-count-dont-match? $ ?tp ?id)] [(str "Call signature doesn't match function, calling " ?name) ?msg]) (defrule validate [?id ?msg] "Args must match types" [?id :inst/type :inst.type/call] [?id :inst.arg/arg0 ?arg] [?arg :node/return-type ?arg-t] [?id :inst.call/fn ?fn] [?fn :inst.gbl/name ?name] [?fn :node/return-type ?fn-t] [?fn-arg :fn.arg/fn ?fn-t] [?fn-arg :fn.arg/idx 0] [?fn-arg :fn.arg/type ?fn-arg-t] [(not= ?fn-arg-t ?arg-t)] [?fn-arg-t :node/type ?fn-arg-t-node] [?arg-t :node/type ?arg-t-node] [?id :inst/block ?block] [?block :block/fn ?parent-fn] [?parent-fn :fn/name ?parent-fn-name] [(str "Arg0 doesn't match in call to " ?name " types " ?fn-arg-t-node " " ?arg-t-node " in " ?parent-fn-name) ?msg]) (defrule validate [?id ?msg] "Args must match types" [?id :inst/type :inst.type/call] [?id :inst.arg/arg1 ?arg] [?arg :node/return-type ?arg-t] [?id :inst.call/fn ?fn] [?fn :inst.gbl/name ?name] [?fn :node/return-type ?fn-t] [?fn-arg :fn.arg/fn ?fn-t] [?fn-arg :fn.arg/idx 1] [?fn-arg :fn.arg/type ?fn-arg-t] [(not= ?fn-arg-t ?arg-t)] [(str "Arg1 doesn't match in call to " ?name) ?msg]) (defrule validate [?id ?msg] "Args must match types" [?id :inst/type :inst.type/call] [?id :inst.arg/arg2 ?arg] [?arg :node/return-type ?arg-t] [?id :inst.call/fn ?fn] [?fn :inst.gbl/name ?name] [?fn :node/return-type ?fn-t] [?fn-arg :fn.arg/fn ?fn-t] [?fn-arg :fn.arg/idx 2] [?fn-arg :fn.arg/type ?fn-arg-t] [(not= ?fn-arg-t ?arg-t)] [(str "Arg2 doesn't match in call to " ?name) ?msg]) rules - These rules define an attribute that helps emitters decide if a binop is a Float or Int operation . FMul is different from IMul , so this code specializes that information . (comment (defrule infer-binop [?id ?op] "A binop of two ints " [?id :inst/type :inst.type/binop] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] (return-type ?arg0 ?arg0-t) (return-type ?arg1 ?arg1-t) (binop-subtype ?id ?arg0-t ?arg1-t ?op)) (defrule binop-subtype [?type ?arg0-t ?arg1-t ?op] "Int + resolves to :iadd" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/int] [?type :inst.binop/type ?binop] [(mjolnir.ssa-rules/binop-int-translation ?binop) ?op]) (defrule binop-subtype [?type ?arg0-t ?arg1-t ?op] "Float + resolves to :iadd" [?arg0-t :node/type :type/float] [?arg1-t :node/type :type/float] [?type :inst.binop/type ?binop] [(mjolnir.ssa-rules/binop-float-translation ?binop) ?op])) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/int] [?arg0-t :type/length ?arg0-length] [?arg1-t :type/length ?arg1-length] [(> ?arg0-length ?arg1-length)] [(identity :inst.cast.type/trunc) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/int] [?arg0-t :type/length ?arg0-length] [?arg1-t :type/length ?arg1-length] [(< ?arg0-length ?arg1-length)] [(identity :inst.cast.type/zext) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Floats cast to int" [?arg0-t :node/type :type/float] [?arg1-t :node/type :type/int] [(identity :inst.cast.type/fp-to-si) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Ints cast to floats" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/float] [(identity :inst.cast.type/si-to-fp) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Pointers are bitcast" [?arg0-t :node/type :type/pointer] [?arg1-t :node/type :type/pointer] [(identity :inst.cast.type/bitcast) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Functions can be bitcast" [?arg0-t :node/type :type/fn] [?arg1-t :node/type :type/pointer] [(identity :inst.cast.type/bitcast) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/pointer] [?arg1-t :node/type :type/int] [(identity :inst.cast.type/ptr-to-int) ?op]) (defrule cast-subtype [?id ?arg0-t ?arg1-t ?op] "Larger Ints truncate to smaller ints" [?arg0-t :node/type :type/int] [?arg1-t :node/type :type/pointer] [(identity :inst.cast.type/int-to-ptr) ?op]) (def cmp-map {[:type/int :type/int :inst.cmp.pred/=] :inst.cmp.sub-pred/int-eq [:type/int :type/int :inst.cmp.pred/not=] :inst.cmp.sub-pred/int-ne [:type/int :type/int :inst.cmp.pred/>] :inst.cmp.sub-pred/int-sgt [:type/int :type/int :inst.cmp.pred/<] :inst.cmp.sub-pred/int-slt [:type/int :type/int :inst.cmp.pred/<=] :inst.cmp.sub-pred/int-sle [:type/int :type/int :inst.cmp.pred/>=] :inst.cmp.sub-pred/int-sge [:type/float :type/float :inst.cmp.pred/=] :inst.cmp.sub-pred/real-oeq [:type/float :type/float :inst.cmp.pred/not=] :inst.cmp.sub-pred/real-one [:type/float :type/float :inst.cmp.pred/>] :inst.cmp.sub-pred/real-ogt [:type/float :type/float :inst.cmp.pred/<] :inst.cmp.sub-pred/real-olt [:type/float :type/float :inst.cmp.pred/<=] :inst.cmp.sub-pred/real-ole [:type/float :type/float :inst.cmp.pred/>=] :inst.cmp.sub-pred/real-oge}) #_(defrule infer-cmp-node [?id ?attr ?val] "Infer cmp predicate" [?id :inst/type :inst.type/cmp] [?id :inst.arg/arg0 ?arg0] [?id :inst.arg/arg1 ?arg1] [?id :inst.cmp/pred ?pred] (return-type ?arg0 ?arg0-t) (return-type ?arg1 ?arg1-t) [?arg0-t :node/type ?arg0-tg] [?arg1-t :node/type ?arg1-tg] [(vector ?arg0-tg ?arg1-tg ?pred) ?key] [(mjolnir.ssa-rules/cmp-map ?key) ?val] [(identity :inst.cmp/sub-pred) ?attr]) (comment (defrule instruction-seq [?block ?inst] "All instructions attached to the block should be considered" [?block :inst/block ?inst]) (defrule instruction-seq [?block ?inst] "Terminator instructions should be considered" [?block :block/terminator-inst ?inst]) (defrule depends-on [?block-a ?block-b] "Rule passes if block-a requires block-b before it can be built" [(mjolnir.ssa-rules/arg-k) [?attr ...]] (instruction-seq ?block-a ?inst-a) [?inst-a ?attr ?inst-b] [?inst-b :inst/block ?block-b] [(not= ?block-a ?block-b)]) (defrule depends-on [?block-a ?block-b] "Rule passes if block-a requires block-b before it can be built" [(mjolnir.ssa-rules/arg-k) [?attr ...]] (instruction-seq ?block-a ?inst-a) [?inst-a ?attr ?inst-b] [?inst-b :phi/block ?block-b] [(not= ?block-a ?block-b)]))
f15838802b9075471cf0f6dd35ca6b9aabf71a2b72559c0ee8fb5c1cd635df5b
8c6794b6/guile-tjit
x-triangle.scm
;;; TRIANG from racket benchmark. (define *board* (make-vector 16 1)) (define *sequence* (make-vector 14 0)) (define *a* (make-vector 37)) (define *b* (make-vector 37)) (define *c* (make-vector 37)) (define *answer* '()) (define *final* '()) (define (last-position) (do ((i 1 (+ i 1))) ((or (= i 16) (= 1 (vector-ref *board* i))) (if (= i 16) 0 i)))) (define (ttry i depth) (cond ((= depth 14) (let ((lp (last-position))) (if (not (member lp *final*)) (set! *final* (cons lp *final*)) #t)) (set! *answer* (cons (cdr (vector->list *sequence*)) *answer*)) #t) ((and (= 1 (vector-ref *board* (vector-ref *a* i))) (= 1 (vector-ref *board* (vector-ref *b* i))) (= 0 (vector-ref *board* (vector-ref *c* i)))) (vector-set! *board* (vector-ref *a* i) 0) (vector-set! *board* (vector-ref *b* i) 0) (vector-set! *board* (vector-ref *c* i) 1) (vector-set! *sequence* depth i) (do ((j 0 (+ j 1)) (depth (+ depth 1))) ((or (= j 36) (ttry j depth)) #f)) (vector-set! *board* (vector-ref *a* i) 1) (vector-set! *board* (vector-ref *b* i) 1) (vector-set! *board* (vector-ref *c* i) 0) '()) (else #f))) (define (gogogo i) (let ((*answer* '()) (*final* '())) (ttry i 1))) (for-each (lambda (i x) (vector-set! *a* i x)) '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36) '(1 2 4 3 5 6 1 3 6 2 5 4 11 12 13 7 8 4 4 7 11 8 12 13 6 10 15 9 14 13 13 14 15 9 10 6 6)) (for-each (lambda (i x) (vector-set! *b* i x)) '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36) '(2 4 7 5 8 9 3 6 10 5 9 8 12 13 14 8 9 5 2 4 7 5 8 9 3 6 10 5 9 8 12 13 14 8 9 5 5)) (for-each (lambda (i x) (vector-set! *c* i x)) '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36) '(4 7 11 8 12 13 6 10 15 9 14 13 13 14 15 9 10 6 1 2 4 3 5 6 1 3 6 2 5 4 11 12 13 7 8 4 4)) (vector-set! *board* 5 0) (define (run) (do ((i 0 (+ i 1)) (acc '() (cons (gogogo 22) acc))) ((= i 100) acc))) (run)
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/test-suite/tjit/x-triangle.scm
scheme
TRIANG from racket benchmark.
(define *board* (make-vector 16 1)) (define *sequence* (make-vector 14 0)) (define *a* (make-vector 37)) (define *b* (make-vector 37)) (define *c* (make-vector 37)) (define *answer* '()) (define *final* '()) (define (last-position) (do ((i 1 (+ i 1))) ((or (= i 16) (= 1 (vector-ref *board* i))) (if (= i 16) 0 i)))) (define (ttry i depth) (cond ((= depth 14) (let ((lp (last-position))) (if (not (member lp *final*)) (set! *final* (cons lp *final*)) #t)) (set! *answer* (cons (cdr (vector->list *sequence*)) *answer*)) #t) ((and (= 1 (vector-ref *board* (vector-ref *a* i))) (= 1 (vector-ref *board* (vector-ref *b* i))) (= 0 (vector-ref *board* (vector-ref *c* i)))) (vector-set! *board* (vector-ref *a* i) 0) (vector-set! *board* (vector-ref *b* i) 0) (vector-set! *board* (vector-ref *c* i) 1) (vector-set! *sequence* depth i) (do ((j 0 (+ j 1)) (depth (+ depth 1))) ((or (= j 36) (ttry j depth)) #f)) (vector-set! *board* (vector-ref *a* i) 1) (vector-set! *board* (vector-ref *b* i) 1) (vector-set! *board* (vector-ref *c* i) 0) '()) (else #f))) (define (gogogo i) (let ((*answer* '()) (*final* '())) (ttry i 1))) (for-each (lambda (i x) (vector-set! *a* i x)) '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36) '(1 2 4 3 5 6 1 3 6 2 5 4 11 12 13 7 8 4 4 7 11 8 12 13 6 10 15 9 14 13 13 14 15 9 10 6 6)) (for-each (lambda (i x) (vector-set! *b* i x)) '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36) '(2 4 7 5 8 9 3 6 10 5 9 8 12 13 14 8 9 5 2 4 7 5 8 9 3 6 10 5 9 8 12 13 14 8 9 5 5)) (for-each (lambda (i x) (vector-set! *c* i x)) '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36) '(4 7 11 8 12 13 6 10 15 9 14 13 13 14 15 9 10 6 1 2 4 3 5 6 1 3 6 2 5 4 11 12 13 7 8 4 4)) (vector-set! *board* 5 0) (define (run) (do ((i 0 (+ i 1)) (acc '() (cons (gogogo 22) acc))) ((= i 100) acc))) (run)
307e8753a01cf7642d43b0e0bf60ed87666734c63069d7fe33d069ad4557f3cc
qfpl/applied-fp-course
CommentText.hs
module Level07.Types.CommentText ( CommentText , mkCommentText , getCommentText , encodeCommentText ) where import Waargonaut.Encode (Encoder) import qualified Waargonaut.Encode as E import Data.Functor.Contravariant ((>$<)) import Data.Text (Text) import Level07.Types.Error (Error (EmptyCommentText), nonEmptyText) newtype CommentText = CommentText Text deriving (Show) encodeCommentText :: Applicative f => Encoder f CommentText encodeCommentText = getCommentText >$< E.text mkCommentText :: Text -> Either Error CommentText mkCommentText = nonEmptyText CommentText EmptyCommentText getCommentText :: CommentText -> Text getCommentText (CommentText t) = t
null
https://raw.githubusercontent.com/qfpl/applied-fp-course/d5a94a9dcee677bc95a5184c2ed13329c9f07559/src/Level07/Types/CommentText.hs
haskell
module Level07.Types.CommentText ( CommentText , mkCommentText , getCommentText , encodeCommentText ) where import Waargonaut.Encode (Encoder) import qualified Waargonaut.Encode as E import Data.Functor.Contravariant ((>$<)) import Data.Text (Text) import Level07.Types.Error (Error (EmptyCommentText), nonEmptyText) newtype CommentText = CommentText Text deriving (Show) encodeCommentText :: Applicative f => Encoder f CommentText encodeCommentText = getCommentText >$< E.text mkCommentText :: Text -> Either Error CommentText mkCommentText = nonEmptyText CommentText EmptyCommentText getCommentText :: CommentText -> Text getCommentText (CommentText t) = t
d5b7374fe7b00c5b16a38cfd6f689656c990ce928baa16e3fd6d776a9e9acb07
avatar29A/hs-aitubots-api
EditContainerMessage.hs
# LANGUAGE RecordWildCards # # LANGUAGE DuplicateRecordFields # {-# LANGUAGE OverloadedStrings #-} module Aitu.Bot.Commands.EditContainerMessage ( EditContainerMessage(..) ) where import Data.Aeson import Data.Text import Data.Maybe import Data.UUID.Types import Aitu.Bot.Types.Peer ( Peer ) import Aitu.Bot.Types.UIState ( UIState ) import Aitu.Bot.Types.InputMedia ( InputMedia ) import Aitu.Bot.Types.InlineCommand ( InlineCommand , RowInlineCommands ) -- doc: -api-contract/EditContainerMessage.html data EditContainerMessage = EditContainerMessage { recipient :: Peer , content :: Text } deriving (Show) instance ToJSON EditContainerMessage where toJSON EditContainerMessage {..} = object [ "type" .= ("EditContainerMessage" :: Text) , "recipient" .= recipient , "content" .= content ]
null
https://raw.githubusercontent.com/avatar29A/hs-aitubots-api/9cc3fd1e4e9e81491628741a6bbb68afbb85704e/src/Aitu/Bot/Commands/EditContainerMessage.hs
haskell
# LANGUAGE OverloadedStrings # doc: -api-contract/EditContainerMessage.html
# LANGUAGE RecordWildCards # # LANGUAGE DuplicateRecordFields # module Aitu.Bot.Commands.EditContainerMessage ( EditContainerMessage(..) ) where import Data.Aeson import Data.Text import Data.Maybe import Data.UUID.Types import Aitu.Bot.Types.Peer ( Peer ) import Aitu.Bot.Types.UIState ( UIState ) import Aitu.Bot.Types.InputMedia ( InputMedia ) import Aitu.Bot.Types.InlineCommand ( InlineCommand , RowInlineCommands ) data EditContainerMessage = EditContainerMessage { recipient :: Peer , content :: Text } deriving (Show) instance ToJSON EditContainerMessage where toJSON EditContainerMessage {..} = object [ "type" .= ("EditContainerMessage" :: Text) , "recipient" .= recipient , "content" .= content ]
6af9c6710bce7310f85cac61b8efb54d6cfefbecbe3e66c0cb22568714285e68
lilactown/apollo-cljs-example
core.cljs
(ns apollo-example.core (:require [helix.core :refer [defnc $]] [helix.dom :as d] ["react-dom" :as rdom] ["apollo-boost" :default ApolloClient :refer [gql]] ["@apollo/react-hooks" :as apollo :refer [useQuery]] [cljs-bean.core :as b])) (def client (ApolloClient. #js {:uri ""})) (def exchange-query (gql "{ rates(currency: \"USD\") { currency rate } }")) (defnc ExchangeRates [_] (let [{:keys [loading error data]} (-> (useQuery exchange-query) ;; wrap result in a bean to destructure (b/bean :recursive true))] (cond loading (d/div "Loading...") error (d/div "Error :(") :else (d/div "Success" (for [entry (:rates data)] (let [{:keys [currency rate]} entry] (d/div {:key currency} (d/p currency ": " rate)))))))) (defnc App [_] ($ apollo/ApolloProvider {:client client} (d/div ($ ExchangeRates)))) (defn ^:dev/after-load start [] (rdom/render ($ App) (.getElementById js/document "app")))
null
https://raw.githubusercontent.com/lilactown/apollo-cljs-example/b769aa6a526e8ba21515c43521389e2a1f9ec307/src/apollo_example/core.cljs
clojure
wrap result in a bean to destructure
(ns apollo-example.core (:require [helix.core :refer [defnc $]] [helix.dom :as d] ["react-dom" :as rdom] ["apollo-boost" :default ApolloClient :refer [gql]] ["@apollo/react-hooks" :as apollo :refer [useQuery]] [cljs-bean.core :as b])) (def client (ApolloClient. #js {:uri ""})) (def exchange-query (gql "{ rates(currency: \"USD\") { currency rate } }")) (defnc ExchangeRates [_] (let [{:keys [loading error data]} (-> (useQuery exchange-query) (b/bean :recursive true))] (cond loading (d/div "Loading...") error (d/div "Error :(") :else (d/div "Success" (for [entry (:rates data)] (let [{:keys [currency rate]} entry] (d/div {:key currency} (d/p currency ": " rate)))))))) (defnc App [_] ($ apollo/ApolloProvider {:client client} (d/div ($ ExchangeRates)))) (defn ^:dev/after-load start [] (rdom/render ($ App) (.getElementById js/document "app")))
74d00d1aec5ff736e8d900e956fb85bf950a5fed8522cc940ccf2dbe4f6dde4c
aitorres/firelink
ScalarTypesSpec.hs
module ScalarTypesSpec where import FireLink.FrontEnd.Tokens import Test.Hspec import Utils (scanToken) spec :: Spec spec = describe "Lexer" $ do -- Integers it "accepts `humanity` as a valid token" $ do let x = "humanity" let atok = scanToken x atok `shouldBe` TkBigInt it "accepts `big humanity` as a valid token" $ do let x = "big humanity" let atok = scanToken x atok `shouldBe` TkBigInt it "accepts `small humanity` as a valid token" $ do let x = "small humanity" let atok = scanToken x atok `shouldBe` TkSmallInt -- Tri-booleans it "accepts `bonfire` as a valid token" $ do let x = "bonfire" let atok = scanToken x atok `shouldBe` TkBool it "accepts `lit` as a valid token" $ do let x = "lit" let atok = scanToken x atok `shouldBe` TkLit it "accepts `unlit` as a valid token" $ do let x = "unlit" let atok = scanToken x atok `shouldBe` TkUnlit it "accepts `undiscovered` as a valid token" $ do let x = "undiscovered" let atok = scanToken x atok `shouldBe` TkUndiscovered -- Hollow it "accepts `hollow` as a valid token" $ do let x = "hollow" let atok = scanToken x atok `shouldBe` TkFloat -- Sign it "accepts `sign` as a valid token" $ do let x = "sign" let atok = scanToken x atok `shouldBe` TkChar it "accepts `ascii_of` as a valid token" $ do let x = "ascii_of" let atok = scanToken x atok `shouldBe` TkAsciiOf
null
https://raw.githubusercontent.com/aitorres/firelink/075d7aad1c053a54e39a27d8db7c3c719d243225/test/Lexer/ScalarTypesSpec.hs
haskell
Integers Tri-booleans Hollow Sign
module ScalarTypesSpec where import FireLink.FrontEnd.Tokens import Test.Hspec import Utils (scanToken) spec :: Spec spec = describe "Lexer" $ do it "accepts `humanity` as a valid token" $ do let x = "humanity" let atok = scanToken x atok `shouldBe` TkBigInt it "accepts `big humanity` as a valid token" $ do let x = "big humanity" let atok = scanToken x atok `shouldBe` TkBigInt it "accepts `small humanity` as a valid token" $ do let x = "small humanity" let atok = scanToken x atok `shouldBe` TkSmallInt it "accepts `bonfire` as a valid token" $ do let x = "bonfire" let atok = scanToken x atok `shouldBe` TkBool it "accepts `lit` as a valid token" $ do let x = "lit" let atok = scanToken x atok `shouldBe` TkLit it "accepts `unlit` as a valid token" $ do let x = "unlit" let atok = scanToken x atok `shouldBe` TkUnlit it "accepts `undiscovered` as a valid token" $ do let x = "undiscovered" let atok = scanToken x atok `shouldBe` TkUndiscovered it "accepts `hollow` as a valid token" $ do let x = "hollow" let atok = scanToken x atok `shouldBe` TkFloat it "accepts `sign` as a valid token" $ do let x = "sign" let atok = scanToken x atok `shouldBe` TkChar it "accepts `ascii_of` as a valid token" $ do let x = "ascii_of" let atok = scanToken x atok `shouldBe` TkAsciiOf
4d36d1ca4dc77959549ab2aa40c9a69f3eb5612751bc907fb2f4c4b200307140
lambduli/frea
Evaluate.hs
module Interpreter.Evaluate where import Data.Either import Data.List import Data.Map.Strict ((!?), (!)) import qualified Data.Map.Strict as Map import Control.Monad.State.Lazy import Compiler.Syntax.Expression import Compiler.Syntax.Declaration import Compiler.Syntax.Literal import Interpreter.Value (EvaluationError(..), Env(..)) import qualified Interpreter.Value as Val import Interpreter.Address import Debug.Trace force'val :: Val.Value -> State Val.Memory (Either EvaluationError Val.Value) force'val (Val.Thunk force'f env addr) = do result <- force'f env case result of Left err -> return $ Left err Right val -> do mem <- get let mem' = Map.insert addr val mem put mem' force'val val force'val val = return $ Right val force :: Expression -> Env -> State Val.Memory (Either EvaluationError Val.Value) force expr env = do result <- evaluate expr env case result of Right (Val.Thunk force'f env addr) -> do result <- force'f env case result of Left err -> return $ Left err Right val -> do mem <- get let mem' = Map.insert addr val mem put mem' force'val val Right val -> return $ Right val Left err -> return $ Left err construct'bindings :: [(String, Expression)] -> Env -> State Val.Memory () construct'bindings [] _ = return () construct'bindings ((name, expr) : rest) env = do mem <- get let addr = env Map.! name val = Val.Thunk (\ env -> force expr env) env addr mem' = Map.insert addr val mem put mem' construct'bindings rest env evaluate :: Expression -> Env -> State Val.Memory (Either EvaluationError Val.Value) evaluate expr env = case expr of Var name -> do mem <- get case env !? name of Just addr -> case mem !? addr of Just val -> return $ Right val Nothing -> return $ Left $ Unexpected $ "Value of " ++ name ++ " not found in the memory for some reason." Nothing -> return $ Left $ UnboundVar name -- can't really happen thanks to the type system Op name -> return $ Right $ Val.Op name Lit lit -> return $ Right $ Val.Lit lit Tuple exprs -> return $ Right $ Val.Tuple $ map (\ expr -> Val.Thunk (\ env -> evaluate expr env) env (Addr (-1))) exprs Let bind'pairs expr -> do let env' = foldl register'binding env bind'pairs register'binding env (name, _) = let addr = Addr $ Map.size env in Map.insert name addr env construct'bindings bind'pairs env' -- TODO: do the same thing as for global bindings -- first collect them all to the env -- then store them all in the memory -- then set new memory and evaluate the expr with the new env evaluate expr env' Lam par body -> return $ Right $ Val.Lam par body env App (Lam par body) right -> do mem <- get let addr = Addr $ Map.size mem right'val = Val.Thunk (\ env -> force right env) env addr env' = Map.insert par addr env mem' = Map.insert addr right'val mem put mem' evaluate body env' App (Op op) right -> do res <- force right env case res of Right r'val -> apply'operator op r'val env Left err -> return $ Left err App left right -> do res <- force left env case res of Left err -> return $ Left err Right (Val.Lam par body env') -> do mem <- get let addr = Addr $ Map.size mem env'' = Map.insert par addr env' right'val = Val.Thunk (\ env -> force right env) env addr mem' = Map.insert addr right'val mem put mem' evaluate body env'' Right (Val.Op name) -> evaluate (App (Op name) right) env If cond' then' else' -> do res <- force cond' env case res of Left err -> return $ Left err wiring the into the type checker | con'name == "True" -> evaluate then' env | otherwise -> evaluate else' env Intro name exprs -> do let values = map (\ expr -> Val.Thunk (\ env -> evaluate expr env) env (Addr (-1))) exprs return . Right $ Val.Data name values Elim constructors value'to'elim destructors -> do res <- force value'to'elim env case res of Right (Val.Data tag arguments) -> do let [(_, destr)] = filter (\ (ConDecl name _, _) -> tag == name) (zip constructors destructors) res <- force destr env case res of Left err -> return $ Left err Right val | [] <- arguments -> return $ Right val Right lam@(Val.Lam par body _) -> apply'closure arguments lam Right (Val.Op op) | [right] <- arguments -> do res <- force'val right case res of Left err -> return $ Left err Right r'val -> apply'operator op r'val env Left err -> return $ Left err Ann _ expr -> evaluate expr env apply'closure :: [Val.Value] -> Val.Value -> State Val.Memory (Either EvaluationError Val.Value) apply'closure [] val = return $ Right val apply'closure (val : vals) (Val.Lam par body env) = do mem <- get let addr = Addr $ Map.size mem env' = Map.insert par addr env mem' = Map.insert addr val mem put mem' res <- force body env' case res of Left err -> return $ Left err Right body'val -> apply'closure vals body'val apply'operator :: String -> Val.Value -> Env -> State Val.Memory (Either EvaluationError Val.Value) apply'operator "#=" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit lit'l), Right (Val.Lit lit'r)) -> wiring the into the typechecker (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#<" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of wiring the into the typechecker return $ Right $ Val.to'val'bool (lit'l < lit'r) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#>" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of wiring the into the typechecker return $ Right $ Val.to'val'bool (lit'l > lit'r) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#+" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l + i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#+." (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l + d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#*" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l * i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#*." (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l * d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#-" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l - i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#-." (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l - d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#div" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt 0))) -> return $ Left $ DivisionByZero i'l (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l `div` i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#/" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble 0))) -> return $ Left $ DivisionByZero 0 (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l / d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#fst" (Val.Tuple [f, s]) env = return $ Right f apply'operator "#snd" (Val.Tuple [f, s]) env = return $ Right s apply'operator "#show" val env = do res <- force'val val case res of Left err -> return $ Left err Right val -> return $ Right $ Val.str'to'value $ show val -- wiring the String into the compiler apply'operator "#debug" val env = do res <- force'val val case res of Left err -> return $ Left err Right val -> let v = trace ("@debug: `" ++ show val ++ "`") val in return $ Right v apply'operator name expr env = return $ Left $ BadOperatorApplication name expr
null
https://raw.githubusercontent.com/lambduli/frea/3c227062e744d4df280987cc7b9680590da56e1f/src/Interpreter/Evaluate.hs
haskell
can't really happen thanks to the type system TODO: do the same thing as for global bindings first collect them all to the env then store them all in the memory then set new memory and evaluate the expr with the new env wiring the String into the compiler
module Interpreter.Evaluate where import Data.Either import Data.List import Data.Map.Strict ((!?), (!)) import qualified Data.Map.Strict as Map import Control.Monad.State.Lazy import Compiler.Syntax.Expression import Compiler.Syntax.Declaration import Compiler.Syntax.Literal import Interpreter.Value (EvaluationError(..), Env(..)) import qualified Interpreter.Value as Val import Interpreter.Address import Debug.Trace force'val :: Val.Value -> State Val.Memory (Either EvaluationError Val.Value) force'val (Val.Thunk force'f env addr) = do result <- force'f env case result of Left err -> return $ Left err Right val -> do mem <- get let mem' = Map.insert addr val mem put mem' force'val val force'val val = return $ Right val force :: Expression -> Env -> State Val.Memory (Either EvaluationError Val.Value) force expr env = do result <- evaluate expr env case result of Right (Val.Thunk force'f env addr) -> do result <- force'f env case result of Left err -> return $ Left err Right val -> do mem <- get let mem' = Map.insert addr val mem put mem' force'val val Right val -> return $ Right val Left err -> return $ Left err construct'bindings :: [(String, Expression)] -> Env -> State Val.Memory () construct'bindings [] _ = return () construct'bindings ((name, expr) : rest) env = do mem <- get let addr = env Map.! name val = Val.Thunk (\ env -> force expr env) env addr mem' = Map.insert addr val mem put mem' construct'bindings rest env evaluate :: Expression -> Env -> State Val.Memory (Either EvaluationError Val.Value) evaluate expr env = case expr of Var name -> do mem <- get case env !? name of Just addr -> case mem !? addr of Just val -> return $ Right val Nothing -> return $ Left $ Unexpected $ "Value of " ++ name ++ " not found in the memory for some reason." Op name -> return $ Right $ Val.Op name Lit lit -> return $ Right $ Val.Lit lit Tuple exprs -> return $ Right $ Val.Tuple $ map (\ expr -> Val.Thunk (\ env -> evaluate expr env) env (Addr (-1))) exprs Let bind'pairs expr -> do let env' = foldl register'binding env bind'pairs register'binding env (name, _) = let addr = Addr $ Map.size env in Map.insert name addr env construct'bindings bind'pairs env' evaluate expr env' Lam par body -> return $ Right $ Val.Lam par body env App (Lam par body) right -> do mem <- get let addr = Addr $ Map.size mem right'val = Val.Thunk (\ env -> force right env) env addr env' = Map.insert par addr env mem' = Map.insert addr right'val mem put mem' evaluate body env' App (Op op) right -> do res <- force right env case res of Right r'val -> apply'operator op r'val env Left err -> return $ Left err App left right -> do res <- force left env case res of Left err -> return $ Left err Right (Val.Lam par body env') -> do mem <- get let addr = Addr $ Map.size mem env'' = Map.insert par addr env' right'val = Val.Thunk (\ env -> force right env) env addr mem' = Map.insert addr right'val mem put mem' evaluate body env'' Right (Val.Op name) -> evaluate (App (Op name) right) env If cond' then' else' -> do res <- force cond' env case res of Left err -> return $ Left err wiring the into the type checker | con'name == "True" -> evaluate then' env | otherwise -> evaluate else' env Intro name exprs -> do let values = map (\ expr -> Val.Thunk (\ env -> evaluate expr env) env (Addr (-1))) exprs return . Right $ Val.Data name values Elim constructors value'to'elim destructors -> do res <- force value'to'elim env case res of Right (Val.Data tag arguments) -> do let [(_, destr)] = filter (\ (ConDecl name _, _) -> tag == name) (zip constructors destructors) res <- force destr env case res of Left err -> return $ Left err Right val | [] <- arguments -> return $ Right val Right lam@(Val.Lam par body _) -> apply'closure arguments lam Right (Val.Op op) | [right] <- arguments -> do res <- force'val right case res of Left err -> return $ Left err Right r'val -> apply'operator op r'val env Left err -> return $ Left err Ann _ expr -> evaluate expr env apply'closure :: [Val.Value] -> Val.Value -> State Val.Memory (Either EvaluationError Val.Value) apply'closure [] val = return $ Right val apply'closure (val : vals) (Val.Lam par body env) = do mem <- get let addr = Addr $ Map.size mem env' = Map.insert par addr env mem' = Map.insert addr val mem put mem' res <- force body env' case res of Left err -> return $ Left err Right body'val -> apply'closure vals body'val apply'operator :: String -> Val.Value -> Env -> State Val.Memory (Either EvaluationError Val.Value) apply'operator "#=" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit lit'l), Right (Val.Lit lit'r)) -> wiring the into the typechecker (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#<" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of wiring the into the typechecker return $ Right $ Val.to'val'bool (lit'l < lit'r) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#>" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of wiring the into the typechecker return $ Right $ Val.to'val'bool (lit'l > lit'r) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#+" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l + i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#+." (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l + d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#*" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l * i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#*." (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l * d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#-" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l - i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#-." (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l - d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#div" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt 0))) -> return $ Left $ DivisionByZero i'l (Right (Val.Lit (LitInt i'l)), Right (Val.Lit (LitInt i'r))) -> return $ Right $ Val.Lit (LitInt (i'l `div` i'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#/" (Val.Tuple [val'l, val'r]) env = do res'l <- force'val val'l res'r <- force'val val'r case (res'l, res'r) of (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble 0))) -> return $ Left $ DivisionByZero 0 (Right (Val.Lit (LitDouble d'l)), Right (Val.Lit (LitDouble d'r))) -> return $ Right $ Val.Lit (LitDouble (d'l / d'r)) (Right _, Left err) -> return $ Left err (Left err, _) -> return $ Left err apply'operator "#fst" (Val.Tuple [f, s]) env = return $ Right f apply'operator "#snd" (Val.Tuple [f, s]) env = return $ Right s apply'operator "#show" val env = do res <- force'val val case res of Left err -> return $ Left err apply'operator "#debug" val env = do res <- force'val val case res of Left err -> return $ Left err Right val -> let v = trace ("@debug: `" ++ show val ++ "`") val in return $ Right v apply'operator name expr env = return $ Left $ BadOperatorApplication name expr
f9d580767457ac79a016807479dcab9bf8ce169b147a1595f35fba41716f0da8
jwiegley/notes
Koz.hs
cocataM :: (Monad m, Traversable f) => (a -> f b -> m b) -> Cofree f a -> m b cocataM k (x :< xs) = k x =<< traverse (cocataM k) xs
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/8d692e70cadbe4a3a4336825daa61f65/Koz.hs
haskell
cocataM :: (Monad m, Traversable f) => (a -> f b -> m b) -> Cofree f a -> m b cocataM k (x :< xs) = k x =<< traverse (cocataM k) xs
2f076e575191784a35abda1884006fb1cd52fd60904f752b2affb15d18e43649
well-typed/large-records
R010.hs
#if PROFILE_CORESIZE {-# OPTIONS_GHC -ddump-to-file -ddump-simpl #-} #endif #if PROFILE_TIMING {-# OPTIONS_GHC -ddump-to-file -ddump-timings #-} #endif # LANGUAGE OverloadedLabels # # LANGUAGE RecordWildCards # module Experiment.SR_SetEvens.Sized.R010 where import SuperRecord (Rec) import qualified SuperRecord as SR import Bench.EvensOfSize.Evens010 import Common.RowOfSize.Row010 setEvens :: Evens -> Rec ExampleRow -> Rec ExampleRow setEvens Evens{..} r = -- 00 .. 09 SR.set #t00 evens00 . SR.set #t02 evens02 . SR.set #t04 evens04 . SR.set #t06 evens06 . SR.set #t08 evens08 $ r
null
https://raw.githubusercontent.com/well-typed/large-records/78d0966e4871847e2c17a0aa821bacf38bdf96bc/large-records-benchmarks/bench/superrecord/Experiment/SR_SetEvens/Sized/R010.hs
haskell
# OPTIONS_GHC -ddump-to-file -ddump-simpl # # OPTIONS_GHC -ddump-to-file -ddump-timings # 00 .. 09
#if PROFILE_CORESIZE #endif #if PROFILE_TIMING #endif # LANGUAGE OverloadedLabels # # LANGUAGE RecordWildCards # module Experiment.SR_SetEvens.Sized.R010 where import SuperRecord (Rec) import qualified SuperRecord as SR import Bench.EvensOfSize.Evens010 import Common.RowOfSize.Row010 setEvens :: Evens -> Rec ExampleRow -> Rec ExampleRow setEvens Evens{..} r = SR.set #t00 evens00 . SR.set #t02 evens02 . SR.set #t04 evens04 . SR.set #t06 evens06 . SR.set #t08 evens08 $ r
f91e2956f9753a1cd4373a99c832b145fd9fa814d329c9c0177add14c765aa29
NorfairKing/intray
DoneSpec.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Intray.Cli.Commands.DoneSpec (spec) where import qualified Data.List.NonEmpty as NE import Intray.API.Gen () import Intray.Cli.OptParse import Intray.Cli.Sqlite import Intray.Cli.TestUtils import Intray.Data import TestImport spec :: Spec spec = do cliMSpec $ do it "can always done a local item" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings intray $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = False } intray DispatchShowItem intray DispatchDoneItem s <- testCliM settings getStoreSize s `shouldBe` 0 it "can always done a local item, even with an explicit sync inbetween" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings forM_ (setBaseUrl settings) $ \_ -> do intray $ DispatchRegister RegisterSettings { registerSetUsername = parseUsername "testuser", registerSetPassword = Just "testpassword" } intray $ DispatchLogin LoginSettings { loginSetUsername = parseUsername "testuser", loginSetPassword = Just "testpassword" } intray $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = False } intray DispatchSync intray DispatchShowItem intray DispatchDoneItem s <- testCliM settings getStoreSize s `shouldBe` 0 it "can always done a local item, even with an explicit sync inbetween, even after syncing again" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings forM_ (setBaseUrl settings) $ \_ -> do intray $ DispatchRegister RegisterSettings { registerSetUsername = parseUsername "testuser", registerSetPassword = Just "testpassword" } intray $ DispatchLogin LoginSettings { loginSetUsername = parseUsername "testuser", loginSetPassword = Just "testpassword" } intray $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = False } intray DispatchSync intray DispatchShowItem intray DispatchDoneItem intray DispatchSync s <- testCliM settings getStoreSize s `shouldBe` 0 it "can always done a remote item" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings forM_ (setBaseUrl settings) $ \_ -> do intray $ DispatchRegister RegisterSettings { registerSetUsername = parseUsername "testuser", registerSetPassword = Just "testpassword" } intray $ DispatchLogin LoginSettings { loginSetUsername = parseUsername "testuser", loginSetPassword = Just "testpassword" } testIntray settings $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = True } intray DispatchSync intray DispatchShowItem intray DispatchDoneItem s <- testCliM settings getStoreSize s `shouldBe` 0
null
https://raw.githubusercontent.com/NorfairKing/intray/3335692a5445e86bf308420d4ab025d6ab11b10d/intray-cli/test/Intray/Cli/Commands/DoneSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables # module Intray.Cli.Commands.DoneSpec (spec) where import qualified Data.List.NonEmpty as NE import Intray.API.Gen () import Intray.Cli.OptParse import Intray.Cli.Sqlite import Intray.Cli.TestUtils import Intray.Data import TestImport spec :: Spec spec = do cliMSpec $ do it "can always done a local item" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings intray $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = False } intray DispatchShowItem intray DispatchDoneItem s <- testCliM settings getStoreSize s `shouldBe` 0 it "can always done a local item, even with an explicit sync inbetween" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings forM_ (setBaseUrl settings) $ \_ -> do intray $ DispatchRegister RegisterSettings { registerSetUsername = parseUsername "testuser", registerSetPassword = Just "testpassword" } intray $ DispatchLogin LoginSettings { loginSetUsername = parseUsername "testuser", loginSetPassword = Just "testpassword" } intray $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = False } intray DispatchSync intray DispatchShowItem intray DispatchDoneItem s <- testCliM settings getStoreSize s `shouldBe` 0 it "can always done a local item, even with an explicit sync inbetween, even after syncing again" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings forM_ (setBaseUrl settings) $ \_ -> do intray $ DispatchRegister RegisterSettings { registerSetUsername = parseUsername "testuser", registerSetPassword = Just "testpassword" } intray $ DispatchLogin LoginSettings { loginSetUsername = parseUsername "testuser", loginSetPassword = Just "testpassword" } intray $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = False } intray DispatchSync intray DispatchShowItem intray DispatchDoneItem intray DispatchSync s <- testCliM settings getStoreSize s `shouldBe` 0 it "can always done a remote item" $ \settings -> forAllValid $ \parts -> do let intray = testIntray settings forM_ (setBaseUrl settings) $ \_ -> do intray $ DispatchRegister RegisterSettings { registerSetUsername = parseUsername "testuser", registerSetPassword = Just "testpassword" } intray $ DispatchLogin LoginSettings { loginSetUsername = parseUsername "testuser", loginSetPassword = Just "testpassword" } testIntray settings $ DispatchAddItem AddSettings { addSetContents = NE.toList parts, addSetReadStdin = False, addSetRemote = True } intray DispatchSync intray DispatchShowItem intray DispatchDoneItem s <- testCliM settings getStoreSize s `shouldBe` 0
565c95efbcf80aa9df4f83053c89abcaf6eeabd22574e6f4fb27933accf64d98
ygrek/ocaml-extlib
check_stdlib.ml
(* check compatibility of interfaces *) #directory "src";; #load "extLib.cma";; module XS = (struct include ExtLib.String external length : string -> int = "%string_length" external get : string -> int -> char = "%string_safe_get" external set : bytes -> int -> char -> unit = "%string_safe_set" external create : int -> bytes = "caml_create_string" external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set" external unsafe_blit : string -> int -> bytes -> int -> int -> unit = "caml_blit_string" [@@noalloc] external unsafe_fill : bytes -> int -> int -> char -> unit = "caml_fill_string" [@@noalloc] end : module type of String) module XL = (struct include ExtLib.List let sort = List.sort end : module type of List) module XA = (ExtLib.Array : module type of Array) module XB = (ExtLib.Buffer : module type of Buffer) module XH = (ExtLib.Hashtbl : module type of Hashtbl)
null
https://raw.githubusercontent.com/ygrek/ocaml-extlib/cfb2d9632d117020f9c9bfdabea679ae9222a620/check_stdlib.ml
ocaml
check compatibility of interfaces
#directory "src";; #load "extLib.cma";; module XS = (struct include ExtLib.String external length : string -> int = "%string_length" external get : string -> int -> char = "%string_safe_get" external set : bytes -> int -> char -> unit = "%string_safe_set" external create : int -> bytes = "caml_create_string" external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set" external unsafe_blit : string -> int -> bytes -> int -> int -> unit = "caml_blit_string" [@@noalloc] external unsafe_fill : bytes -> int -> int -> char -> unit = "caml_fill_string" [@@noalloc] end : module type of String) module XL = (struct include ExtLib.List let sort = List.sort end : module type of List) module XA = (ExtLib.Array : module type of Array) module XB = (ExtLib.Buffer : module type of Buffer) module XH = (ExtLib.Hashtbl : module type of Hashtbl)
cb1a00eee232da4c1957ffb782dced6e366857817888f84dc626a10b38f10329
elastic/eui-cljs
icon_logo_metrics.cljs
(ns eui.icon-logo-metrics (:require ["@elastic/eui/lib/components/icon/assets/logo_metrics.js" :as eui])) (def logoMetrics eui/icon)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_logo_metrics.cljs
clojure
(ns eui.icon-logo-metrics (:require ["@elastic/eui/lib/components/icon/assets/logo_metrics.js" :as eui])) (def logoMetrics eui/icon)
ed0bde06a159c05a0b38f621d41656de060031078a12c8b2d117e6ff7f4e8fef
pentlandedge/s4607
job_req_tests.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright 2018 Pentland Edge Ltd. %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not %% use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT %% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the %% License for the specific language governing permissions and limitations %% under the License. %% -module(job_req_tests). -include_lib("eunit/include/eunit.hrl"). -export([sample_params/0, sample_job_request/0, sample_job_request_params/0]). %% Define a test generator for the Job Request segment functions. job_req_test_() -> [valid_checks(), valid_checks2(), new_checks(), encode_checks()]. valid_checks() -> Bin = sample_job_request(), {ok, JR} = job_req:decode(Bin), job_req:display(JR), ReqID = job_req:get_requestor_id(JR), TaskID = job_req:get_requestor_task_id(JR), Pri = job_req:get_requestor_priority(JR), Mode = job_req:get_radar_mode(JR), RangeRes = job_req:get_radar_range_res(JR), XRangeRes = job_req:get_radar_cross_range_res(JR), Yr = job_req:get_earliest_start_year(JR), Mth = job_req:get_earliest_start_month(JR), Day = job_req:get_earliest_start_day(JR), Hr = job_req:get_earliest_start_hour(JR), Min = job_req:get_earliest_start_min(JR), Sec = job_req:get_earliest_start_sec(JR), DelaySec = job_req:get_allowed_delay(JR), Duration = job_req:get_duration(JR), RevInt = job_req:get_revisit_interval(JR), SensorType = job_req:get_sensor_id_type(JR), SensorModel = job_req:get_sensor_id_model(JR), ReqType = job_req:get_request_type(JR), [?_assertEqual("Job Req ID", ReqID), ?_assertEqual("JReqTaskID", TaskID), ?_assertEqual(default_priority, Pri), ?_assert(almost_equal(45.0, job_req:get_bounding_a_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_a_lon(JR), 0.00001)), ?_assert(almost_equal(45.0, job_req:get_bounding_b_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_b_lon(JR), 0.00001)), ?_assert(almost_equal(45.0, job_req:get_bounding_c_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_c_lon(JR), 0.00001)), ?_assert(almost_equal(45.0, job_req:get_bounding_d_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_d_lon(JR), 0.00001)), ?_assertEqual({maritime_mti_low_res, joint_stars}, Mode), ?_assertEqual(300, RangeRes), ?_assertEqual(dont_care, XRangeRes), ?_assertEqual(2018, Yr), ?_assertEqual(5, Mth), ?_assertEqual(23, Day), ?_assertEqual(10, Hr), ?_assertEqual(11, Min), ?_assertEqual(50, Sec), ?_assertEqual(65000, DelaySec), ?_assertEqual(continuous, Duration), ?_assertEqual(default_interval, RevInt), ?_assertEqual(no_statement, SensorType), ?_assertEqual(no_statement, SensorModel), ?_assertEqual(initial_request, ReqType) ]. valid_checks2() -> Bin = sample_job_request2(), {ok, JR} = job_req:decode(Bin), Duration = job_req:get_duration(JR), RevInt = job_req:get_revisit_interval(JR), SensorType = job_req:get_sensor_id_type(JR), SensorModel = job_req:get_sensor_id_model(JR), ReqType = job_req:get_request_type(JR), [?_assertEqual(54321, Duration), ?_assertEqual(21314, RevInt), ?_assertEqual(global_hawk_sensor, SensorType), ?_assertEqual("HawkV1", SensorModel), ?_assertEqual(cancel_job, ReqType) ]. %% Test the construction of new job request segments. new_checks() -> ParamList = sample_params(), JR = job_req:new(ParamList), [?_assertEqual("Hawkstream", job_req:get_requestor_id(JR)), ?_assertEqual("Test Run 1", job_req:get_requestor_task_id(JR)), ?_assertEqual(99, job_req:get_requestor_priority(JR)), ?_assert(almost_equal(56.36061, job_req:get_bounding_a_lat(JR), 0.00001)), ?_assert(almost_equal(-2.82458, job_req:get_bounding_a_lon(JR), 0.00001)), ?_assert(almost_equal(56.36070, job_req:get_bounding_b_lat(JR), 0.00001)), ?_assert(almost_equal(-2.81774, job_req:get_bounding_b_lon(JR), 0.00001)), ?_assert(almost_equal(56.35773, job_req:get_bounding_c_lat(JR), 0.00001)), ?_assert(almost_equal(-2.81795, job_req:get_bounding_c_lon(JR), 0.00001)), ?_assert(almost_equal(56.35769, job_req:get_bounding_d_lat(JR), 0.00001)), ?_assert(almost_equal(-2.82527, job_req:get_bounding_d_lon(JR), 0.00001)), ?_assertEqual({attack_planning, joint_stars}, job_req:get_radar_mode(JR)), ?_assertEqual(15, job_req:get_radar_range_res(JR)), ?_assertEqual(42, job_req:get_radar_cross_range_res(JR)), ?_assertEqual(2018, job_req:get_earliest_start_year(JR)), ?_assertEqual(2, job_req:get_earliest_start_month(JR)), ?_assertEqual(10, job_req:get_earliest_start_day(JR)), ?_assertEqual(21, job_req:get_earliest_start_hour(JR)), ?_assertEqual(22, job_req:get_earliest_start_min(JR)), ?_assertEqual(13, job_req:get_earliest_start_sec(JR)), ?_assertEqual(3600, job_req:get_allowed_delay(JR)), ?_assertEqual(30, job_req:get_duration(JR)), ?_assertEqual(default_interval, job_req:get_revisit_interval(JR)), ?_assertEqual(global_hawk_sensor, job_req:get_sensor_id_type(JR)), ?_assertEqual("HawkV2", job_req:get_sensor_id_model(JR)), ?_assertEqual(initial_request, job_req:get_request_type(JR)) ]. %% Test the ability to encode job request segments. Create a new segment with %% parameters that when encoded should match sample_job_request(). encode_checks() -> ParamList = sample_job_request_params(), JR = job_req:new(ParamList), EJR = job_req:encode(JR), Bin = iolist_to_binary(EJR), [?_assertEqual(Bin, sample_job_request())]. %% Return a binary job request segment to use as test data. sample_job_request() -> <<"Job Req ID","JReqTaskID",0, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 24, 16#12C:16, 0:16, 2018:16,5,23,10,11,50,65000:16,0:16,0:16,255,"None ",0>>. %% Alternate test data: non defaults in the later parameters. sample_job_request2() -> <<"Job Req ID","JReqTaskID",0, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 24, 16#12C:16, 0:16, 2018:16,5,23,10,11,50,65000:16,54321:16,21314:16,5,"HawkV1",1>>. %% Define a sample parameter list to use with new/1. sample_params() -> [{requestor_id, "Hawkstream"}, {requestor_task_id, "Test Run 1"}, {requestor_priority, 99}, {bounding_a_lat, 56.36061}, {bounding_a_lon, -2.82458}, {bounding_b_lat, 56.36070}, {bounding_b_lon, -2.81774}, {bounding_c_lat, 56.35773}, {bounding_c_lon, -2.81795}, {bounding_d_lat, 56.35769}, {bounding_d_lon, -2.82527}, {radar_mode, {attack_planning, joint_stars}}, {radar_range_res, 15}, {radar_cross_range_res, 42}, {earliest_start_year, 2018}, {earliest_start_month, 2}, {earliest_start_day, 10}, {earliest_start_hour, 21}, {earliest_start_min, 22}, {earliest_start_sec, 13}, {allowed_delay, 3600}, {duration, 30}, {revisit_interval, default_interval}, {sensor_id_type, global_hawk_sensor}, {sensor_id_model, "HawkV2"}, {request_type, initial_request} ]. Define a sample parameter list to use with new/1 . This should encode to %% match the binary sample_job_request(). sample_job_request_params() -> [{requestor_id, "Job Req ID"}, {requestor_task_id, "JReqTaskID"}, {requestor_priority, default_priority}, {bounding_a_lat, 45.0}, {bounding_a_lon, 345.0}, {bounding_b_lat, 45.0}, {bounding_b_lon, 345.0}, {bounding_c_lat, 45.0}, {bounding_c_lon, 345.0}, {bounding_d_lat, 45.0}, {bounding_d_lon, 345.0}, {radar_mode, {maritime_mti_low_res, joint_stars}}, {radar_range_res, 300}, {radar_cross_range_res, dont_care}, {earliest_start_year, 2018}, {earliest_start_month, 5}, {earliest_start_day, 23}, {earliest_start_hour, 10}, {earliest_start_min, 11}, {earliest_start_sec, 50}, {allowed_delay, 65000}, {duration, continuous}, {revisit_interval, default_interval}, {sensor_id_type, no_statement}, {sensor_id_model, no_statement}, {request_type, initial_request} ]. %% Utility function to compare whether floating point values are within a %% specified range. almost_equal(V1, V2, Delta) -> abs(V1 - V2) =< Delta.
null
https://raw.githubusercontent.com/pentlandedge/s4607/b3cdae404ac5bd50419f33259dfa62af9d1a8d60/test/job_req_tests.erl
erlang
use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Define a test generator for the Job Request segment functions. Test the construction of new job request segments. Test the ability to encode job request segments. Create a new segment with parameters that when encoded should match sample_job_request(). Return a binary job request segment to use as test data. Alternate test data: non defaults in the later parameters. Define a sample parameter list to use with new/1. match the binary sample_job_request(). Utility function to compare whether floating point values are within a specified range.
Copyright 2018 Pentland Edge Ltd. Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -module(job_req_tests). -include_lib("eunit/include/eunit.hrl"). -export([sample_params/0, sample_job_request/0, sample_job_request_params/0]). job_req_test_() -> [valid_checks(), valid_checks2(), new_checks(), encode_checks()]. valid_checks() -> Bin = sample_job_request(), {ok, JR} = job_req:decode(Bin), job_req:display(JR), ReqID = job_req:get_requestor_id(JR), TaskID = job_req:get_requestor_task_id(JR), Pri = job_req:get_requestor_priority(JR), Mode = job_req:get_radar_mode(JR), RangeRes = job_req:get_radar_range_res(JR), XRangeRes = job_req:get_radar_cross_range_res(JR), Yr = job_req:get_earliest_start_year(JR), Mth = job_req:get_earliest_start_month(JR), Day = job_req:get_earliest_start_day(JR), Hr = job_req:get_earliest_start_hour(JR), Min = job_req:get_earliest_start_min(JR), Sec = job_req:get_earliest_start_sec(JR), DelaySec = job_req:get_allowed_delay(JR), Duration = job_req:get_duration(JR), RevInt = job_req:get_revisit_interval(JR), SensorType = job_req:get_sensor_id_type(JR), SensorModel = job_req:get_sensor_id_model(JR), ReqType = job_req:get_request_type(JR), [?_assertEqual("Job Req ID", ReqID), ?_assertEqual("JReqTaskID", TaskID), ?_assertEqual(default_priority, Pri), ?_assert(almost_equal(45.0, job_req:get_bounding_a_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_a_lon(JR), 0.00001)), ?_assert(almost_equal(45.0, job_req:get_bounding_b_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_b_lon(JR), 0.00001)), ?_assert(almost_equal(45.0, job_req:get_bounding_c_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_c_lon(JR), 0.00001)), ?_assert(almost_equal(45.0, job_req:get_bounding_d_lat(JR), 0.00001)), ?_assert(almost_equal(345.0, job_req:get_bounding_d_lon(JR), 0.00001)), ?_assertEqual({maritime_mti_low_res, joint_stars}, Mode), ?_assertEqual(300, RangeRes), ?_assertEqual(dont_care, XRangeRes), ?_assertEqual(2018, Yr), ?_assertEqual(5, Mth), ?_assertEqual(23, Day), ?_assertEqual(10, Hr), ?_assertEqual(11, Min), ?_assertEqual(50, Sec), ?_assertEqual(65000, DelaySec), ?_assertEqual(continuous, Duration), ?_assertEqual(default_interval, RevInt), ?_assertEqual(no_statement, SensorType), ?_assertEqual(no_statement, SensorModel), ?_assertEqual(initial_request, ReqType) ]. valid_checks2() -> Bin = sample_job_request2(), {ok, JR} = job_req:decode(Bin), Duration = job_req:get_duration(JR), RevInt = job_req:get_revisit_interval(JR), SensorType = job_req:get_sensor_id_type(JR), SensorModel = job_req:get_sensor_id_model(JR), ReqType = job_req:get_request_type(JR), [?_assertEqual(54321, Duration), ?_assertEqual(21314, RevInt), ?_assertEqual(global_hawk_sensor, SensorType), ?_assertEqual("HawkV1", SensorModel), ?_assertEqual(cancel_job, ReqType) ]. new_checks() -> ParamList = sample_params(), JR = job_req:new(ParamList), [?_assertEqual("Hawkstream", job_req:get_requestor_id(JR)), ?_assertEqual("Test Run 1", job_req:get_requestor_task_id(JR)), ?_assertEqual(99, job_req:get_requestor_priority(JR)), ?_assert(almost_equal(56.36061, job_req:get_bounding_a_lat(JR), 0.00001)), ?_assert(almost_equal(-2.82458, job_req:get_bounding_a_lon(JR), 0.00001)), ?_assert(almost_equal(56.36070, job_req:get_bounding_b_lat(JR), 0.00001)), ?_assert(almost_equal(-2.81774, job_req:get_bounding_b_lon(JR), 0.00001)), ?_assert(almost_equal(56.35773, job_req:get_bounding_c_lat(JR), 0.00001)), ?_assert(almost_equal(-2.81795, job_req:get_bounding_c_lon(JR), 0.00001)), ?_assert(almost_equal(56.35769, job_req:get_bounding_d_lat(JR), 0.00001)), ?_assert(almost_equal(-2.82527, job_req:get_bounding_d_lon(JR), 0.00001)), ?_assertEqual({attack_planning, joint_stars}, job_req:get_radar_mode(JR)), ?_assertEqual(15, job_req:get_radar_range_res(JR)), ?_assertEqual(42, job_req:get_radar_cross_range_res(JR)), ?_assertEqual(2018, job_req:get_earliest_start_year(JR)), ?_assertEqual(2, job_req:get_earliest_start_month(JR)), ?_assertEqual(10, job_req:get_earliest_start_day(JR)), ?_assertEqual(21, job_req:get_earliest_start_hour(JR)), ?_assertEqual(22, job_req:get_earliest_start_min(JR)), ?_assertEqual(13, job_req:get_earliest_start_sec(JR)), ?_assertEqual(3600, job_req:get_allowed_delay(JR)), ?_assertEqual(30, job_req:get_duration(JR)), ?_assertEqual(default_interval, job_req:get_revisit_interval(JR)), ?_assertEqual(global_hawk_sensor, job_req:get_sensor_id_type(JR)), ?_assertEqual("HawkV2", job_req:get_sensor_id_model(JR)), ?_assertEqual(initial_request, job_req:get_request_type(JR)) ]. encode_checks() -> ParamList = sample_job_request_params(), JR = job_req:new(ParamList), EJR = job_req:encode(JR), Bin = iolist_to_binary(EJR), [?_assertEqual(Bin, sample_job_request())]. sample_job_request() -> <<"Job Req ID","JReqTaskID",0, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 24, 16#12C:16, 0:16, 2018:16,5,23,10,11,50,65000:16,0:16,0:16,255,"None ",0>>. sample_job_request2() -> <<"Job Req ID","JReqTaskID",0, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 64,0,0,0, 245,85,85,85, 24, 16#12C:16, 0:16, 2018:16,5,23,10,11,50,65000:16,54321:16,21314:16,5,"HawkV1",1>>. sample_params() -> [{requestor_id, "Hawkstream"}, {requestor_task_id, "Test Run 1"}, {requestor_priority, 99}, {bounding_a_lat, 56.36061}, {bounding_a_lon, -2.82458}, {bounding_b_lat, 56.36070}, {bounding_b_lon, -2.81774}, {bounding_c_lat, 56.35773}, {bounding_c_lon, -2.81795}, {bounding_d_lat, 56.35769}, {bounding_d_lon, -2.82527}, {radar_mode, {attack_planning, joint_stars}}, {radar_range_res, 15}, {radar_cross_range_res, 42}, {earliest_start_year, 2018}, {earliest_start_month, 2}, {earliest_start_day, 10}, {earliest_start_hour, 21}, {earliest_start_min, 22}, {earliest_start_sec, 13}, {allowed_delay, 3600}, {duration, 30}, {revisit_interval, default_interval}, {sensor_id_type, global_hawk_sensor}, {sensor_id_model, "HawkV2"}, {request_type, initial_request} ]. Define a sample parameter list to use with new/1 . This should encode to sample_job_request_params() -> [{requestor_id, "Job Req ID"}, {requestor_task_id, "JReqTaskID"}, {requestor_priority, default_priority}, {bounding_a_lat, 45.0}, {bounding_a_lon, 345.0}, {bounding_b_lat, 45.0}, {bounding_b_lon, 345.0}, {bounding_c_lat, 45.0}, {bounding_c_lon, 345.0}, {bounding_d_lat, 45.0}, {bounding_d_lon, 345.0}, {radar_mode, {maritime_mti_low_res, joint_stars}}, {radar_range_res, 300}, {radar_cross_range_res, dont_care}, {earliest_start_year, 2018}, {earliest_start_month, 5}, {earliest_start_day, 23}, {earliest_start_hour, 10}, {earliest_start_min, 11}, {earliest_start_sec, 50}, {allowed_delay, 65000}, {duration, continuous}, {revisit_interval, default_interval}, {sensor_id_type, no_statement}, {sensor_id_model, no_statement}, {request_type, initial_request} ]. almost_equal(V1, V2, Delta) -> abs(V1 - V2) =< Delta.
cf1101bc52afcf76c2413c6e06e1a3fd36209be286257ffc0681b4a6f8e44ac7
ott-lang/ott
new_term_parser.ml
(**************************************************************************) (* new_term_parser *) (* *) , Computer Laboratory , University of Cambridge (* *) Copyright 2007 (* *) (* Redistribution and use in source and binary forms, with or without *) (* modification, are permitted provided that the following conditions *) (* are met: *) 1 . Redistributions of source code must retain the above copyright (* notice, this list of conditions and the following disclaimer. *) 2 . Redistributions in binary form must reproduce the above copyright (* notice, this list of conditions and the following disclaimer in the *) (* documentation and/or other materials provided with the distribution. *) 3 . The names of the authors may not be used to endorse or promote (* products derived from this software without specific prior written *) (* permission. *) (* *) THIS SOFTWARE IS PROVIDED BY THE AUTHORS ` ` 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 AUTHORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL (* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE *) (* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *) INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER (* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR *) (* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *) (* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) (**************************************************************************) Build a parser for symterms and concrete terms using glr.ml (* Not yet implemented: * Better performance * Fix weird ambiguity with ":concrete" *) let fast_parse = ref false (* true: do not add pseudoterminals :rulename: and :concrete: to grammar *) open Types;; exception Parse_error of loc * string;; let error_string s0 s c = s0 ^ let c=c+0 in if c > String.length s then "(internal overflow in building error string)" else let s1 = String.sub s 0 c in let s2 = String.sub s c (String.length s - c) in " (char "^string_of_int c^"): "^s1^"***"^s2^" ";; let no_parses_error_string s l = error_string "no parses" s l;; let parse_error2 loc s msg = raise (Parse_error (loc, msg));; module type NTsig = sig type t type nt = Orig_nt of string * bool | Term_nt of string | Metavar_nt of string * bool | Builtin_nt of string | Gen_nt of t val compare : t -> t -> int val to_string : t -> string val make_build : unit -> nt -> t val whitespace : nt val fail : nt val suffix : nt val suffix_item : nt val digit : nt val digit_plus : nt val digit_plus2 : nt val dots : nt val alphanum0 : nt val alphanum : nt val cap_alphanum : nt val cap_az : nt val az : nt val alpha_follow : nt val indexvar : nt val indexvar_fancy_suffix : nt val number : nt val nt_or_mv : nt end;; module Gtp = struct module Terminal = struct type t = char let compare = Char.compare let eof = '\xFF' let is_eof c = c == eof let to_string c = "'" ^ Char.escaped c ^ "'" let to_int = Char.code end;; module Nonterminal : NTsig = struct type nt = Orig_nt of string * bool | Term_nt of string | Metavar_nt of string * bool | Builtin_nt of string | Gen_nt of t and t = int * nt;; let compare_nt nt1 nt2 = match nt1 with | Orig_nt (s1, b1) -> (match nt2 with | Orig_nt (s2, b2) -> let n = String.compare s1 s2 in if n = 0 then Obj.magic b1 - Obj.magic b2 else n | _ -> -1) | Term_nt s1 -> (match nt2 with | Orig_nt _ -> 1 | Term_nt s2 -> String.compare s1 s2 | _ -> -1) | Metavar_nt (s1, b1) -> (match nt2 with | Orig_nt _ | Term_nt _ -> 1 | Metavar_nt (s2, b2) -> let n = String.compare s1 s2 in if n = 0 then Obj.magic b1 - Obj.magic b2 else n | _ -> -1) | Builtin_nt s1 -> (match nt2 with | Orig_nt _ | Term_nt _ | Metavar_nt _ -> 1 | Builtin_nt s2 -> String.compare s1 s2 | _ -> -1) | Gen_nt (i1,t1) -> (match nt2 with Gen_nt (i2,t2) -> i1 - i2 | _ -> 1) module Ntmap = Map.Make (struct type t = nt;; let compare x y = compare_nt x y;; end);; let compare (i1, _) (i2, _) = i1 - i2;; let encode_string_chars s = let open Str in global_substitute (regexp "[][!\"#$%&()*+,./:;<=>?@\\^`{}|~-]") (function | "[" -> "lbrac" | "]" -> "rbrac" | "!" -> "excl" | "\"" -> "doublequote" | "#" -> "hash" | "$" -> "dollar" | "(" -> "lparen" | ")" -> "rparen" | "*" -> "times" | "+" -> "plus" | "," -> "comma" | "/" -> "slash" | ":" -> "colon" | ";" -> "semi" | "<" -> "lt" | "=" -> "eq" | ">" -> "gt" | "?" -> "question" | "@" -> "at" | "\\" -> "backslash" | "^" -> "caret" | "`" -> "singlequote" | "{" -> "lcurly" | "}" -> "rcurly" | "|" -> "bar" | "~" -> "tilde" | "-" -> "minus") s let rec to_string (i, nt) = match nt with Orig_nt (s, con) -> (if con then "concrete_" else "") ^ s | Term_nt s -> "terminal_" ^ s | Metavar_nt (s, con) -> (if con then "concrete_" else "") ^ s | Builtin_nt s -> s | Gen_nt t -> to_string t ^ string_of_int i let make_build () = let c = ref 0 in let m = ref Ntmap.empty in function Gen_nt s -> let res = (!c, Gen_nt s) in incr c; res | nt -> try Ntmap.find nt !m with Not_found -> let res = (!c, nt) in m := Ntmap.add nt res !m; incr c; res;; let whitespace = Builtin_nt "whitespace";; let fail = Builtin_nt "fail";; let suffix = Builtin_nt "suffix";; let suffix_item = Builtin_nt "suffix_item";; let digit = Builtin_nt "digit";; let digit_plus = Builtin_nt "digit_plus";; let digit_plus2 = Builtin_nt "digit_plus2";; let dots = Builtin_nt "dots";; let alphanum0 = Builtin_nt "alphanum0";; let alphanum = Builtin_nt "alphanum";; let cap_alphanum = Builtin_nt "Alphanum";; let cap_az = Builtin_nt "cap_az";; let az = Builtin_nt "az";; let alpha_follow = Builtin_nt "alpha_follow";; let indexvar = Builtin_nt "indexvar";; let indexvar_fancy_suffix = Builtin_nt "indexvar_fancy_suffix";; let number = Builtin_nt "number";; let nt_or_mv = Builtin_nt "nt_or_mv";; end;; type result = Res_st of symterm | Res_ste of symterm_element | Res_stli of symterm_list_item | Res_stlil of symterm_list_item list | Res_ignore | Res_char of char | Res_charl of char list | Res_string of string | Res_int of int | Res_si of suffix_item | Res_sil of suffix_item list | Res_none;; exception BadInputGrammar of string;; let signal_error s = raise (BadInputGrammar s);; end;; open Gtp;; module Nt = Nonterminal;; module GramTypes = Parse_table.MakeTypes (Gtp);; open GramTypes;; exception Reject_parse exception Reject_all_parses let rec split l n = if n = 0 then ([], l) else match l with [] -> raise (Invalid_argument "List too short") | x::y -> let (f, r) = split y (n - 1) in (x::f, r);; let split_last l n = let (f, r) = split (List.rev l) n in (List.rev r, List.rev f);; let string_to_terms s = let res = ref [] in for i = String.length s - 1 downto 0 do res := T (String.get s i) :: !res done; !res;; Str.regexp function mvd -> try match List.assoc "lex" mvd.mvd_rep with | Hom_string s::[] -> Some s | _ -> failwith "malformed lex specification" with Not_found -> None;; let concrete_parsers = [ "alphanum0", Nt.alphanum0; "alphanum", Nt.alphanum; "Alphanum", Nt.cap_alphanum; "numeral", Nt.digit_plus2 ] let res_ignore _ = Res_ignore;; let res_charl [Res_char c; Res_charl l] = Res_charl (c::l);; let res_cons_string [Res_char c; Res_charl l] = Res_string (Auxl.string_of_char_list (c::l));; let res_stlil [Res_stli a; Res_stlil b] = Res_stlil (a::b);; let build_grammar (xd : syntaxdefn) : (grammar * (Nonterminal.t * follow) list * priority list * Nt.t list * (Nt.nt -> Nt.t)) = let ntr_synonyms = Auxl.ntr_synonyms xd in let index_count = ref 0 in let (prods : production list ref) = ref [] in let add_prod_idx_reject t r x y z = prods := {prod_left=x; prod_right=y; prod_action=z; reject=r; transparent=t; index=(!index_count)} :: !prods; incr index_count; !index_count - 1 in let add_prod_idx x y z = add_prod_idx_reject false false x y z in let add_prod_reject x y z = ignore(add_prod_idx_reject false true x y z); () in let add_prod x y z = ignore(add_prod_idx x y z); () in let add_prod_transp x y z = add_prod_idx_reject true false x y z in let prodname_to_index1 = Hashtbl.create 101 in let prodname_to_index2 = Hashtbl.create 101 in let ((mknt : Nt.nt -> Nt.t), (mkNT : Nt.nt -> grammar_symbol)) = let f = Nt.make_build () in (f, fun x -> NT (f x)) in (* The string is just for printing out the grammar *) let (follows : (Nonterminal.t * follow * string) list ref) = ref [] in let add_alphanum_restr x = follows := (x, Single Auxl.isalphanum, "[a-zA-Z0-9]") :: !follows in let add_num_restr x = follows := (x, Single (fun c -> c >= '0' && c <= '9'), "[0-9]") :: !follows in let (priorities : priority list ref) = ref [] in let add_right_assoc (i1 : int) (i2 : int) = priorities := Right (i1, i2)::!priorities in let add_greater_prior (i1 : int) (i2 : int) = priorities := Greater (i1, i2)::!priorities in let rec process_prod_res : result list -> symterm_element list = function [] -> [] | Res_ignore::rl -> process_prod_res rl | Res_ste ste::rl -> ste::process_prod_res rl | Res_st st::rl -> Ste_st (dummy_loc, st)::process_prod_res rl in let enforce_length_constraint elb = let (length_constraint : int option) = (match elb.elb_boundo with | Some(Bound_dotform bd) -> Some bd.bd_length | Some(Bound_comp_lu bclu) -> Some bclu.bclu_length | _ -> None) in fun stlis -> if (match length_constraint with | Some lc -> Auxl.min_length_of_stlis stlis >= lc | None -> true ) then Res_ste (Ste_list (dummy_loc, stlis)) else raise Reject_parse in let rec process_element (concrete : bool) (nt : Nonterminal.t) (pn : prodname) : element -> grammar_symbol = function Lang_terminal t' -> mkNT (Nt.Term_nt t') | Lang_nonterm (ntrp, nt) -> mkNT (Nt.Orig_nt (ntrp, concrete)) | Lang_metavar (mvrp, mv) -> let mvd = Auxl.mvd_of_mvr xd mvrp in mkNT (Nt.Metavar_nt (mvd.mvd_name, concrete)) | Lang_list elb -> let elc = enforce_length_constraint elb in let list_nt = mknt (Nt.Gen_nt nt) in (* list_nt : Res_ste *) list_help_nt : add_prod list_nt [] (fun _ -> elc []); add_prod list_nt [NT (process_list_form concrete nt pn elb)] (fun [Res_stlil x] -> elc x); NT list_nt | (Lang_option _ | Lang_sugaroption _) -> mkNT Nt.fail and process_elements (concrete: bool) (nt : Nonterminal.t) (pn : prodname) (es : element list) : grammar_symbol list = List.map (process_element concrete nt pn) es and process_list_form (concrete : bool) (nt : Nonterminal.t) (pn : prodname) (elb : element_list_body) : Nonterminal.t = let list_help_nt = mknt (Nt.Gen_nt nt) in let concrete_list_entry_nt = mknt (Nt.Gen_nt nt) in concrete_list_entry_nt : Res_stli add_prod concrete_list_entry_nt (process_elements concrete nt pn elb.elb_es) (fun rl -> Res_stli (Stli_single (dummy_loc, process_prod_res rl))); add_prod list_help_nt [NT concrete_list_entry_nt] (fun [Res_stli x]-> Res_stlil [x]); let idx = match elb.elb_tmo with None -> add_prod_reject list_help_nt [] (fun _ -> assert false); add_prod_transp list_help_nt [NT concrete_list_entry_nt; NT list_help_nt] res_stlil | Some t -> add_prod_transp list_help_nt ([NT concrete_list_entry_nt; mkNT Nt.whitespace] @ string_to_terms t @ [NT list_help_nt]) (fun [x; _; y] -> res_stlil [x; y]) in add_right_assoc idx idx; if not concrete then begin let list_form_nt = mknt (Nt.Gen_nt nt) in let make_listform_token (t : string) : grammar_symbol list = mkNT Nt.whitespace :: string_to_terms t in let wsidxvar_nt = [mkNT Nt.whitespace; mkNT Nt.indexvar] in let list_form_prefix = make_listform_token Grammar_pp.pp_COMP_LEFT @ [NT concrete_list_entry_nt] @ make_listform_token Grammar_pp.pp_COMP_MIDDLE @ wsidxvar_nt in list_form_nt : Res_stli let process_dot_listform_res es1 n' es2 = try let (bo'', es'') = Merge.merge_symterm_element_list 0 (es1,es2) in match bo'' with | None -> (* no index changed - so ill-formed *) raise Reject_parse | Some (si1,si2) -> let b = Bound_dotform {bd_lower = si1; bd_upper = si2; bd_length = n'} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb) with Merge.Merge s -> raise Reject_parse in begin match elb.elb_tmo with None -> add_prod list_form_nt [NT concrete_list_entry_nt; mkNT Nt.whitespace; mkNT Nt.dots; NT concrete_list_entry_nt] (fun [Res_stli (Stli_single (_, es1)); _; Res_int n'; Res_stli (Stli_single (_, es2))] -> process_dot_listform_res es1 n' es2) | Some t -> add_prod list_form_nt ([NT concrete_list_entry_nt; mkNT Nt.whitespace] @ string_to_terms t @ [mkNT Nt.whitespace; mkNT Nt.dots; mkNT Nt.whitespace] @ string_to_terms t @ [NT concrete_list_entry_nt]) (fun [Res_stli (Stli_single (_, es1)); _; _; Res_int n'; _; Res_stli (Stli_single (_, es2))] -> process_dot_listform_res es1 n' es2) end; add_prod list_form_nt (list_form_prefix @ make_listform_token Grammar_pp.pp_COMP_RIGHT) (fun [_; Res_stli (Stli_single (_, es)); _; _; Res_string ivr; _] -> let es'' = List.map (Merge.abstract_indexvar_symterm_element ivr 0) es in let b = Bound_comp {bc_variable=ivr} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb)); add_prod list_form_nt (list_form_prefix @ make_listform_token Grammar_pp.pp_COMP_IN @ wsidxvar_nt @ make_listform_token Grammar_pp.pp_COMP_RIGHT) (fun [_; Res_stli (Stli_single (_, es)); _; _; Res_string ivr; _; _; Res_string ivr'; _] -> let es'' = List.map (Merge.abstract_indexvar_symterm_element ivr 0) es in let b = Bound_comp_u {bcu_variable=ivr;bcu_upper=Si_var (ivr',0)} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb)); add_prod list_form_nt (list_form_prefix @ make_listform_token Grammar_pp.pp_COMP_IN @ [mkNT Nt.whitespace; mkNT Nt.number; mkNT Nt.whitespace; mkNT Nt.dots; mkNT Nt.whitespace; mkNT Nt.indexvar_fancy_suffix] @ make_listform_token Grammar_pp.pp_COMP_RIGHT) (fun [_; Res_stli (Stli_single (_, es)); _; _; Res_string ivr; _; _; Res_string lower; _; Res_int dotlength; _; Res_si si'; _] -> let es'' = List.map (Merge.abstract_indexvar_symterm_element ivr 0) es in let b = Bound_comp_lu {bclu_variable=ivr; bclu_lower=Si_num lower; bclu_upper=si'; bclu_length=dotlength} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb)); ignore(add_prod_idx list_help_nt [NT list_form_nt] (fun [Res_stli x] -> Res_stlil [x])); match elb.elb_tmo with None -> ignore(add_prod_transp list_help_nt [NT list_form_nt; NT list_help_nt] res_stlil); () | Some t -> ignore(add_prod_transp list_help_nt ([NT list_form_nt; mkNT Nt.whitespace] @ string_to_terms t @ [NT list_help_nt]) (fun [x; _; y] -> res_stlil [x; y])); () end; list_help_nt in let process_prod (concrete : bool) (nt : Nonterminal.t) (ntr : nontermroot) (p : prod) : unit = let build_res rl = Res_st (St_node (dummy_loc, {st_rule_ntr_name = ntr; st_prod_name = p.prod_name; st_es = process_prod_res rl; st_loc = dummy_loc})) in let rhs = process_elements concrete nt p.prod_name p.prod_es in let index = add_prod_idx nt rhs build_res in if concrete then Hashtbl.add prodname_to_index1 p.prod_name index else match p.prod_disambiguate with | None -> if !fast_parse then Hashtbl.add prodname_to_index1 p.prod_name index else let index2 = add_prod_idx nt (mkNT Nt.whitespace :: (string_to_terms (Auxl.psuedo_terminal_of_prod_name p.prod_name) @ rhs)) (fun (_::rl) -> build_res rl) in Hashtbl.add prodname_to_index2 p.prod_name (index, index2) | Some (s1, s2) -> let index2 = add_prod_idx nt (mkNT Nt.whitespace :: string_to_terms s1 @ (rhs @ string_to_terms s2)) (fun (_::rl) -> build_res rl) in Hashtbl.add prodname_to_index2 p.prod_name (index, index2) in Orig_nt : Res_st let process_rule (r : rule) : unit = let ntr = r.rule_ntr_name in let nt = mknt (Nt.Orig_nt (r.rule_ntr_name, false)) in if not r.rule_meta && not !fast_parse then begin let concrete_prods = List.filter (fun p -> not p.prod_meta || p.prod_sugar) r.rule_ps in let nt_c = mknt (Nt.Orig_nt (r.rule_ntr_name, true)) in List.iter (process_prod true nt_c ntr) concrete_prods; add_prod nt (mkNT Nt.whitespace:: string_to_terms Auxl.parse_as_concrete@ [NT nt_c]) (fun [_; x] -> x) end; the productions from the grammar List.iter (process_prod false nt ntr) r.rule_ps; (* productions for mentioning the nonterminal name *) List.iter (fun nt' -> add_prod nt (mkNT Nt.whitespace::string_to_terms nt' @ [mkNT Nt.suffix]) (fun [_; Res_sil l] -> Res_st (St_nonterm (dummy_loc, ntr, (nt', l))))) (ntr_synonyms r.rule_ntr_name); (* productions for mentioning the nonterminal name of subrules *) List.iter (fun ntl -> List.iter (fun nt' -> add_prod nt (mkNT Nt.whitespace::string_to_terms nt' @ [mkNT Nt.suffix]) (fun [_; Res_sil l] -> Res_st (St_nontermsub (dummy_loc, ntl, Auxl.promote_ntr xd ntr, (nt', l))))) (ntr_synonyms ntl)) (Auxl.ntr_proper_subs xd r.rule_ntr_name); if not r.rule_meta then begin end in let add_mvr_idx nt name mvr = add_prod nt (mkNT Nt.whitespace::string_to_terms mvr @ [mkNT Nt.suffix]) (fun [_; Res_sil x] -> Res_ste (Ste_metavar (dummy_loc, name, (mvr, x)))) in let add_mvr_nonidx nt name mvr = add_prod nt (mkNT Nt.whitespace :: string_to_terms mvr) (fun _ -> Res_ste (Ste_metavar (dummy_loc, name, (mvr, [])))); add_alphanum_restr nt in let terminals = Auxl.terminals_of_syntaxdefn xd in let is_tm s = List.mem s terminals in (* Metavar_nt : Res_ste *) let process_metavar (mvd : metavardefn) : unit = let nt = mknt (Nt.Metavar_nt (mvd.mvd_name, false)) in List.iter (fun (mvr, _) -> if mvd.mvd_indexvar then add_mvr_nonidx nt mvd.mvd_name mvr else add_mvr_idx nt mvd.mvd_name mvr; ) mvd.mvd_names; match lex_regexp_of_mvd mvd with None -> () | Some r -> begin try add_prod nt (mkNT Nt.whitespace :: T ':' :: string_to_terms mvd.mvd_name @ [T ':'; mkNT (List.assoc r concrete_parsers)]) (fun (_::Res_string s::_) -> Res_ste (Ste_metavar (dummy_loc, mvd.mvd_name, (s, [])))) with Not_found -> () end; let nt_aux = mknt (Nt.Gen_nt nt) in let nt_c = mknt (Nt.Metavar_nt (mvd.mvd_name, true)) in if not !fast_parse then try add_prod nt_c [mkNT Nt.whitespace; mkNT (List.assoc r concrete_parsers)] (fun [_; Res_string s] -> if is_tm s then raise Reject_parse else Res_ste (Ste_var (dummy_loc, mvd.mvd_name, s))); add_prod nt_aux [mkNT Nt.whitespace; mkNT (List.assoc r concrete_parsers)] (fun [_; Res_string s] -> Res_ste (Ste_var (dummy_loc, mvd.mvd_name, s))); add_prod_reject nt_aux [mkNT Nt.nt_or_mv] (fun _ -> assert false); add_prod nt [NT nt_aux] (fun [((Res_ste (Ste_var (_, _, s))) as x)] -> if is_tm s then raise Reject_parse else x) with Not_found -> () in (* whitespace = (' '|'\010'|'\009'|'\013'|'\012')* *) (* Nt.whitespace : Res_ignore *) add_prod (mknt Nt.whitespace) [] res_ignore; List.iter (fun t -> add_prod (mknt Nt.whitespace) [mkNT Nt.whitespace; t] res_ignore) (string_to_terms " \n\t\013\012"); digit = [ 0 - 9 ] Nt.digit : Auxl.string_iter (let n = mknt Nt.digit in fun c -> add_prod n [T c] (fun _ -> Res_char c)) "0123456789"; (* digit_plus = [0-9]+ *) (* Nt.digit_plus : Res_charl *) add_prod (mknt Nt.digit_plus) [mkNT Nt.digit] (fun [Res_char c] -> Res_charl [c]); add_prod (mknt Nt.digit_plus) [mkNT Nt.digit; mkNT Nt.digit_plus] res_charl; add_num_restr (mknt Nt.digit_plus); (* digit_plus2 : Res_string *) add_prod (mknt Nt.digit_plus2) [mkNT Nt.digit_plus] (fun [Res_charl s] -> Res_string (Auxl.string_of_char_list s)); add_alphanum_restr (mknt Nt.digit_plus2); (* dots = ..|...|.... *) Nt.dots : add_prod (mknt Nt.dots) (string_to_terms "..") (fun _ -> Res_int 0); add_prod (mknt Nt.dots) (string_to_terms "...") (fun _ -> Res_int 1); add_prod (mknt Nt.dots) (string_to_terms "....") (fun _ -> Res_int 2); (* suffix = suffix_item* *) (* Nt.suffix : Res_sil *) add_prod (mknt Nt.suffix) [] (fun _ -> Res_sil []); add_prod (mknt Nt.suffix) [mkNT Nt.suffix_item; mkNT Nt.suffix] (fun [Res_si s; Res_sil sl] -> Res_sil (s::sl)); add_alphanum_restr (mknt Nt.suffix); suffix_item = [ 0 - 9]+|_|'|indexvar_fancy_suffix (* Nt.suffix_item : Res_si *) add_prod (mknt Nt.suffix_item) [mkNT Nt.digit_plus] (fun [Res_charl l] -> Res_si (Si_num (Auxl.string_of_char_list l))); add_prod (mknt Nt.suffix_item) [T '_'] (fun _ -> Res_si (Si_punct "_")); add_prod (mknt Nt.suffix_item) [T '\''] (fun _ -> Res_si (Si_punct "'")); add_prod (mknt Nt.suffix_item) [mkNT Nt.indexvar_fancy_suffix] (fun [rsi] -> rsi); (* cap_az = [A-Z] *) Nt.cap_az : Auxl.string_iter (let n = mknt Nt.cap_az in fun c -> add_prod n [T c] (fun _ -> Res_char c)) "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; (* az = [a-z] *) Nt.az : Auxl.string_iter (let n = mknt Nt.az in fun c -> add_prod n [T c] (fun _ -> Res_char c)) "abcdefghijklmnopqrstuvwxyz"; (* alpha_follow = ([A-Z]|[a-z]|[0-9]|['_])* *) Nt.alpha_follow : Res_charl add_prod (mknt Nt.alpha_follow) [] (fun _ -> Res_charl []); add_prod (mknt Nt.alpha_follow) [mkNT Nt.az; mkNT Nt.alpha_follow] res_charl; add_prod (mknt Nt.alpha_follow) [mkNT Nt.cap_az; mkNT Nt.alpha_follow] res_charl; add_prod (mknt Nt.alpha_follow) [mkNT Nt.digit; mkNT Nt.alpha_follow] res_charl; add_prod (mknt Nt.alpha_follow) [T '_'; mkNT Nt.alpha_follow] (fun [Res_charl c] -> Res_charl ('_'::c)); add_prod (mknt Nt.alpha_follow) [T '\''; mkNT Nt.alpha_follow] (fun [Res_charl c] -> Res_charl ('\''::c)); (* alphanum0 = [a-z]alpha_follow *) (* alphanum0 : Res_string *) add_prod (mknt Nt.alphanum0) [mkNT Nt.az; mkNT Nt.alpha_follow] res_cons_string; add_alphanum_restr (mknt Nt.alphanum0); (* alphanum = [a-z][A-Z]alpha_follow*) (* alphanum : Res_string *) add_prod (mknt Nt.alphanum) [mkNT Nt.az; mkNT Nt.alpha_follow] res_cons_string; add_prod (mknt Nt.alphanum) [mkNT Nt.cap_az; mkNT Nt.alpha_follow] res_cons_string; add_alphanum_restr (mknt Nt.alphanum); (* cap_alphanum = [A-Z]alpha_follow *) (* cap_alphanum : Res_string *) add_prod (mknt Nt.cap_alphanum) [mkNT Nt.cap_az; mkNT Nt.alpha_follow] res_cons_string; add_alphanum_restr (mknt Nt.cap_alphanum); number = 0|1 Nt.number : Res_string add_prod (mknt Nt.number) [T '0'] (fun _ -> Res_string "0"); add_prod (mknt Nt.number) [T '1'] (fun _ -> Res_string "1"); add_alphanum_restr (mknt Nt.number); (* Nt.indexvar : Res_string *) List.iter (fun iv -> add_prod (mknt Nt.indexvar) (string_to_terms iv) (fun _ -> Res_string iv)) (Auxl.all_indexvar_synonyms xd); (* indexvar_fancy_suffix = indexvar | indexvar-1 *) (* Nt.indexvar_fancy_suffix : Res_si *) add_prod (mknt Nt.indexvar_fancy_suffix) [mkNT Nt.indexvar] (fun [Res_string s] -> Res_si (Si_var (s, 0))); add_prod (mknt Nt.indexvar_fancy_suffix) (mkNT Nt.indexvar :: string_to_terms "-1") (fun [Res_string s] -> Res_si (Si_var (s, -1))); if not !fast_parse then begin List.iter (add_mvr_nonidx (mknt Nt.nt_or_mv) "") (Auxl.all_index_mvrs_defined_by_syntaxdefn xd); List.iter (add_mvr_idx (mknt Nt.nt_or_mv) "") (Auxl.all_nonindex_mvrs_defined_by_syntaxdefn xd); List.iter (fun nt -> add_prod (mknt Nt.nt_or_mv) (mkNT Nt.whitespace::string_to_terms nt @ [mkNT Nt.suffix]) (fun [_; Res_sil x] -> Res_st (St_nonterm (dummy_loc, "", (nt, x))))) (Auxl.all_ntrs_defined_by_syntaxdefn xd); end; List.iter process_metavar xd.xd_mds; List.iter process_rule xd.xd_rs; List.iter (fun term -> let term_nt = mknt (Nt.Term_nt term) in add_prod term_nt (mkNT Nt.whitespace::string_to_terms term) (fun [x] -> x); if Auxl.last_char_isalphanum term then add_alphanum_restr term_nt) (Auxl.terminals_of_syntaxdefn xd); if !Global_option.do_pp_grammar then begin print_string "\n----------------- Grammar -----------------\n"; List.iter (fun p -> print_string (Nonterminal.to_string p.prod_left); print_string " ::= "; List.iter (function (T t) -> print_string (Terminal.to_string t ^ " ") | (NT nt) -> print_string (Nonterminal.to_string nt ^ " ")) p.prod_right; print_string "(** #"; print_string (string_of_int p.index); print_string (if p.reject then "reject" else " "); print_string (if p.transparent then "transparent" else " "); print_string "**) "; print_string "\n") !prods; print_string "\n----------------- Follow restrictions -----------------\n"; print_string "nonterminal cannot be followed by character set\n\n"; List.iter (function | (nt,Single follow, s) -> print_string (Nonterminal.to_string nt ^ " cannot be followed by " ^ s ^ "\n") | (nt, Multi _, s) -> print_string (Nonterminal.to_string nt ^ " unsupported multi-term follow restriction\n")) !follows; print_string "\n----------------- Priorities -----------------\n"; List.iter (function | Right(x,y) -> Format.printf "Right #%d #%d\n" x y | Left(x,y) -> Format.printf "Left #%d #%d\n" x y | Greater(x,y) -> Format.printf "Greater #%d #%d\n" x y | Nonassoc(x,y) -> Format.printf "Nonassoc #%d #%d\n" x y) !priorities; end; List.iter (fun (pn1, annot, pn2, loc) -> let (i1, i1') = Hashtbl.find prodname_to_index2 pn1 in let (i2, i2') = Hashtbl.find prodname_to_index2 pn2 in let entry = match annot with Types.LTEQ -> [Greater (i2, i1); Greater (i2', i1)] | Types.Left -> [Left (i1, i2); Left (i1', i2)] | Types.Right -> [Right (i1, i2); Right (i1', i2)] | Types.Non -> [Nonassoc (i1, i2); Nonassoc (i1', i2)] in let entry = try let c1 = Hashtbl.find prodname_to_index1 pn1 in let c2 = Hashtbl.find prodname_to_index1 pn2 in match annot with Types.LTEQ -> [Greater (c2, c1)]@entry | Types.Left -> [Left (c1, c2)]@entry | Types.Right -> [Right (c1, c2)]@entry | Types.Non -> [Nonassoc (c1, c2)]@entry with Not_found -> entry in priorities := entry @ !priorities) xd.xd_pas.pa_data; let inits = List.fold_right (fun r acc -> let s1 = mknt (Nt.Orig_nt (r.rule_ntr_name, false)) in if r.rule_meta || !fast_parse then s1 :: acc else s1 :: mknt (Nt.Orig_nt (r.rule_ntr_name, true)) :: acc) xd.xd_rs [] in if !Global_option.do_pp_grammar then begin print_string "\n----------------- Initial non-terminals -----------------\n"; print_string "The non-terminals that we want parsers for\n"; List.iter (fun init -> print_string (Nonterminal.to_string init ^ "\n")) inits end; (!prods, (List.map (fun (a,b,c) -> (a,b)) !follows), !priorities, inits, mknt);;
null
https://raw.githubusercontent.com/ott-lang/ott/29ac9ef84967686da35b9b42608b3aec3539a689/src/new_term_parser.ml
ocaml
************************************************************************ new_term_parser 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. products derived from this software without specific prior written permission. OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 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. ************************************************************************ Not yet implemented: * Better performance * Fix weird ambiguity with ":concrete" true: do not add pseudoterminals :rulename: and :concrete: to grammar The string is just for printing out the grammar list_nt : Res_ste no index changed - so ill-formed productions for mentioning the nonterminal name productions for mentioning the nonterminal name of subrules Metavar_nt : Res_ste whitespace = (' '|'\010'|'\009'|'\013'|'\012')* Nt.whitespace : Res_ignore digit_plus = [0-9]+ Nt.digit_plus : Res_charl digit_plus2 : Res_string dots = ..|...|.... suffix = suffix_item* Nt.suffix : Res_sil Nt.suffix_item : Res_si cap_az = [A-Z] az = [a-z] alpha_follow = ([A-Z]|[a-z]|[0-9]|['_])* alphanum0 = [a-z]alpha_follow alphanum0 : Res_string alphanum = [a-z][A-Z]alpha_follow alphanum : Res_string cap_alphanum = [A-Z]alpha_follow cap_alphanum : Res_string Nt.indexvar : Res_string indexvar_fancy_suffix = indexvar | indexvar-1 Nt.indexvar_fancy_suffix : Res_si
, Computer Laboratory , University of Cambridge Copyright 2007 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright 3 . The names of the authors may not be used to endorse or promote THIS SOFTWARE IS PROVIDED BY THE AUTHORS ` ` AS IS '' AND ANY EXPRESS ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER Build a parser for symterms and concrete terms using glr.ml let fast_parse = ref false open Types;; exception Parse_error of loc * string;; let error_string s0 s c = s0 ^ let c=c+0 in if c > String.length s then "(internal overflow in building error string)" else let s1 = String.sub s 0 c in let s2 = String.sub s c (String.length s - c) in " (char "^string_of_int c^"): "^s1^"***"^s2^" ";; let no_parses_error_string s l = error_string "no parses" s l;; let parse_error2 loc s msg = raise (Parse_error (loc, msg));; module type NTsig = sig type t type nt = Orig_nt of string * bool | Term_nt of string | Metavar_nt of string * bool | Builtin_nt of string | Gen_nt of t val compare : t -> t -> int val to_string : t -> string val make_build : unit -> nt -> t val whitespace : nt val fail : nt val suffix : nt val suffix_item : nt val digit : nt val digit_plus : nt val digit_plus2 : nt val dots : nt val alphanum0 : nt val alphanum : nt val cap_alphanum : nt val cap_az : nt val az : nt val alpha_follow : nt val indexvar : nt val indexvar_fancy_suffix : nt val number : nt val nt_or_mv : nt end;; module Gtp = struct module Terminal = struct type t = char let compare = Char.compare let eof = '\xFF' let is_eof c = c == eof let to_string c = "'" ^ Char.escaped c ^ "'" let to_int = Char.code end;; module Nonterminal : NTsig = struct type nt = Orig_nt of string * bool | Term_nt of string | Metavar_nt of string * bool | Builtin_nt of string | Gen_nt of t and t = int * nt;; let compare_nt nt1 nt2 = match nt1 with | Orig_nt (s1, b1) -> (match nt2 with | Orig_nt (s2, b2) -> let n = String.compare s1 s2 in if n = 0 then Obj.magic b1 - Obj.magic b2 else n | _ -> -1) | Term_nt s1 -> (match nt2 with | Orig_nt _ -> 1 | Term_nt s2 -> String.compare s1 s2 | _ -> -1) | Metavar_nt (s1, b1) -> (match nt2 with | Orig_nt _ | Term_nt _ -> 1 | Metavar_nt (s2, b2) -> let n = String.compare s1 s2 in if n = 0 then Obj.magic b1 - Obj.magic b2 else n | _ -> -1) | Builtin_nt s1 -> (match nt2 with | Orig_nt _ | Term_nt _ | Metavar_nt _ -> 1 | Builtin_nt s2 -> String.compare s1 s2 | _ -> -1) | Gen_nt (i1,t1) -> (match nt2 with Gen_nt (i2,t2) -> i1 - i2 | _ -> 1) module Ntmap = Map.Make (struct type t = nt;; let compare x y = compare_nt x y;; end);; let compare (i1, _) (i2, _) = i1 - i2;; let encode_string_chars s = let open Str in global_substitute (regexp "[][!\"#$%&()*+,./:;<=>?@\\^`{}|~-]") (function | "[" -> "lbrac" | "]" -> "rbrac" | "!" -> "excl" | "\"" -> "doublequote" | "#" -> "hash" | "$" -> "dollar" | "(" -> "lparen" | ")" -> "rparen" | "*" -> "times" | "+" -> "plus" | "," -> "comma" | "/" -> "slash" | ":" -> "colon" | ";" -> "semi" | "<" -> "lt" | "=" -> "eq" | ">" -> "gt" | "?" -> "question" | "@" -> "at" | "\\" -> "backslash" | "^" -> "caret" | "`" -> "singlequote" | "{" -> "lcurly" | "}" -> "rcurly" | "|" -> "bar" | "~" -> "tilde" | "-" -> "minus") s let rec to_string (i, nt) = match nt with Orig_nt (s, con) -> (if con then "concrete_" else "") ^ s | Term_nt s -> "terminal_" ^ s | Metavar_nt (s, con) -> (if con then "concrete_" else "") ^ s | Builtin_nt s -> s | Gen_nt t -> to_string t ^ string_of_int i let make_build () = let c = ref 0 in let m = ref Ntmap.empty in function Gen_nt s -> let res = (!c, Gen_nt s) in incr c; res | nt -> try Ntmap.find nt !m with Not_found -> let res = (!c, nt) in m := Ntmap.add nt res !m; incr c; res;; let whitespace = Builtin_nt "whitespace";; let fail = Builtin_nt "fail";; let suffix = Builtin_nt "suffix";; let suffix_item = Builtin_nt "suffix_item";; let digit = Builtin_nt "digit";; let digit_plus = Builtin_nt "digit_plus";; let digit_plus2 = Builtin_nt "digit_plus2";; let dots = Builtin_nt "dots";; let alphanum0 = Builtin_nt "alphanum0";; let alphanum = Builtin_nt "alphanum";; let cap_alphanum = Builtin_nt "Alphanum";; let cap_az = Builtin_nt "cap_az";; let az = Builtin_nt "az";; let alpha_follow = Builtin_nt "alpha_follow";; let indexvar = Builtin_nt "indexvar";; let indexvar_fancy_suffix = Builtin_nt "indexvar_fancy_suffix";; let number = Builtin_nt "number";; let nt_or_mv = Builtin_nt "nt_or_mv";; end;; type result = Res_st of symterm | Res_ste of symterm_element | Res_stli of symterm_list_item | Res_stlil of symterm_list_item list | Res_ignore | Res_char of char | Res_charl of char list | Res_string of string | Res_int of int | Res_si of suffix_item | Res_sil of suffix_item list | Res_none;; exception BadInputGrammar of string;; let signal_error s = raise (BadInputGrammar s);; end;; open Gtp;; module Nt = Nonterminal;; module GramTypes = Parse_table.MakeTypes (Gtp);; open GramTypes;; exception Reject_parse exception Reject_all_parses let rec split l n = if n = 0 then ([], l) else match l with [] -> raise (Invalid_argument "List too short") | x::y -> let (f, r) = split y (n - 1) in (x::f, r);; let split_last l n = let (f, r) = split (List.rev l) n in (List.rev r, List.rev f);; let string_to_terms s = let res = ref [] in for i = String.length s - 1 downto 0 do res := T (String.get s i) :: !res done; !res;; Str.regexp function mvd -> try match List.assoc "lex" mvd.mvd_rep with | Hom_string s::[] -> Some s | _ -> failwith "malformed lex specification" with Not_found -> None;; let concrete_parsers = [ "alphanum0", Nt.alphanum0; "alphanum", Nt.alphanum; "Alphanum", Nt.cap_alphanum; "numeral", Nt.digit_plus2 ] let res_ignore _ = Res_ignore;; let res_charl [Res_char c; Res_charl l] = Res_charl (c::l);; let res_cons_string [Res_char c; Res_charl l] = Res_string (Auxl.string_of_char_list (c::l));; let res_stlil [Res_stli a; Res_stlil b] = Res_stlil (a::b);; let build_grammar (xd : syntaxdefn) : (grammar * (Nonterminal.t * follow) list * priority list * Nt.t list * (Nt.nt -> Nt.t)) = let ntr_synonyms = Auxl.ntr_synonyms xd in let index_count = ref 0 in let (prods : production list ref) = ref [] in let add_prod_idx_reject t r x y z = prods := {prod_left=x; prod_right=y; prod_action=z; reject=r; transparent=t; index=(!index_count)} :: !prods; incr index_count; !index_count - 1 in let add_prod_idx x y z = add_prod_idx_reject false false x y z in let add_prod_reject x y z = ignore(add_prod_idx_reject false true x y z); () in let add_prod x y z = ignore(add_prod_idx x y z); () in let add_prod_transp x y z = add_prod_idx_reject true false x y z in let prodname_to_index1 = Hashtbl.create 101 in let prodname_to_index2 = Hashtbl.create 101 in let ((mknt : Nt.nt -> Nt.t), (mkNT : Nt.nt -> grammar_symbol)) = let f = Nt.make_build () in (f, fun x -> NT (f x)) in let (follows : (Nonterminal.t * follow * string) list ref) = ref [] in let add_alphanum_restr x = follows := (x, Single Auxl.isalphanum, "[a-zA-Z0-9]") :: !follows in let add_num_restr x = follows := (x, Single (fun c -> c >= '0' && c <= '9'), "[0-9]") :: !follows in let (priorities : priority list ref) = ref [] in let add_right_assoc (i1 : int) (i2 : int) = priorities := Right (i1, i2)::!priorities in let add_greater_prior (i1 : int) (i2 : int) = priorities := Greater (i1, i2)::!priorities in let rec process_prod_res : result list -> symterm_element list = function [] -> [] | Res_ignore::rl -> process_prod_res rl | Res_ste ste::rl -> ste::process_prod_res rl | Res_st st::rl -> Ste_st (dummy_loc, st)::process_prod_res rl in let enforce_length_constraint elb = let (length_constraint : int option) = (match elb.elb_boundo with | Some(Bound_dotform bd) -> Some bd.bd_length | Some(Bound_comp_lu bclu) -> Some bclu.bclu_length | _ -> None) in fun stlis -> if (match length_constraint with | Some lc -> Auxl.min_length_of_stlis stlis >= lc | None -> true ) then Res_ste (Ste_list (dummy_loc, stlis)) else raise Reject_parse in let rec process_element (concrete : bool) (nt : Nonterminal.t) (pn : prodname) : element -> grammar_symbol = function Lang_terminal t' -> mkNT (Nt.Term_nt t') | Lang_nonterm (ntrp, nt) -> mkNT (Nt.Orig_nt (ntrp, concrete)) | Lang_metavar (mvrp, mv) -> let mvd = Auxl.mvd_of_mvr xd mvrp in mkNT (Nt.Metavar_nt (mvd.mvd_name, concrete)) | Lang_list elb -> let elc = enforce_length_constraint elb in let list_nt = mknt (Nt.Gen_nt nt) in list_help_nt : add_prod list_nt [] (fun _ -> elc []); add_prod list_nt [NT (process_list_form concrete nt pn elb)] (fun [Res_stlil x] -> elc x); NT list_nt | (Lang_option _ | Lang_sugaroption _) -> mkNT Nt.fail and process_elements (concrete: bool) (nt : Nonterminal.t) (pn : prodname) (es : element list) : grammar_symbol list = List.map (process_element concrete nt pn) es and process_list_form (concrete : bool) (nt : Nonterminal.t) (pn : prodname) (elb : element_list_body) : Nonterminal.t = let list_help_nt = mknt (Nt.Gen_nt nt) in let concrete_list_entry_nt = mknt (Nt.Gen_nt nt) in concrete_list_entry_nt : Res_stli add_prod concrete_list_entry_nt (process_elements concrete nt pn elb.elb_es) (fun rl -> Res_stli (Stli_single (dummy_loc, process_prod_res rl))); add_prod list_help_nt [NT concrete_list_entry_nt] (fun [Res_stli x]-> Res_stlil [x]); let idx = match elb.elb_tmo with None -> add_prod_reject list_help_nt [] (fun _ -> assert false); add_prod_transp list_help_nt [NT concrete_list_entry_nt; NT list_help_nt] res_stlil | Some t -> add_prod_transp list_help_nt ([NT concrete_list_entry_nt; mkNT Nt.whitespace] @ string_to_terms t @ [NT list_help_nt]) (fun [x; _; y] -> res_stlil [x; y]) in add_right_assoc idx idx; if not concrete then begin let list_form_nt = mknt (Nt.Gen_nt nt) in let make_listform_token (t : string) : grammar_symbol list = mkNT Nt.whitespace :: string_to_terms t in let wsidxvar_nt = [mkNT Nt.whitespace; mkNT Nt.indexvar] in let list_form_prefix = make_listform_token Grammar_pp.pp_COMP_LEFT @ [NT concrete_list_entry_nt] @ make_listform_token Grammar_pp.pp_COMP_MIDDLE @ wsidxvar_nt in list_form_nt : Res_stli let process_dot_listform_res es1 n' es2 = try let (bo'', es'') = Merge.merge_symterm_element_list 0 (es1,es2) in match bo'' with | None -> raise Reject_parse | Some (si1,si2) -> let b = Bound_dotform {bd_lower = si1; bd_upper = si2; bd_length = n'} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb) with Merge.Merge s -> raise Reject_parse in begin match elb.elb_tmo with None -> add_prod list_form_nt [NT concrete_list_entry_nt; mkNT Nt.whitespace; mkNT Nt.dots; NT concrete_list_entry_nt] (fun [Res_stli (Stli_single (_, es1)); _; Res_int n'; Res_stli (Stli_single (_, es2))] -> process_dot_listform_res es1 n' es2) | Some t -> add_prod list_form_nt ([NT concrete_list_entry_nt; mkNT Nt.whitespace] @ string_to_terms t @ [mkNT Nt.whitespace; mkNT Nt.dots; mkNT Nt.whitespace] @ string_to_terms t @ [NT concrete_list_entry_nt]) (fun [Res_stli (Stli_single (_, es1)); _; _; Res_int n'; _; Res_stli (Stli_single (_, es2))] -> process_dot_listform_res es1 n' es2) end; add_prod list_form_nt (list_form_prefix @ make_listform_token Grammar_pp.pp_COMP_RIGHT) (fun [_; Res_stli (Stli_single (_, es)); _; _; Res_string ivr; _] -> let es'' = List.map (Merge.abstract_indexvar_symterm_element ivr 0) es in let b = Bound_comp {bc_variable=ivr} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb)); add_prod list_form_nt (list_form_prefix @ make_listform_token Grammar_pp.pp_COMP_IN @ wsidxvar_nt @ make_listform_token Grammar_pp.pp_COMP_RIGHT) (fun [_; Res_stli (Stli_single (_, es)); _; _; Res_string ivr; _; _; Res_string ivr'; _] -> let es'' = List.map (Merge.abstract_indexvar_symterm_element ivr 0) es in let b = Bound_comp_u {bcu_variable=ivr;bcu_upper=Si_var (ivr',0)} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb)); add_prod list_form_nt (list_form_prefix @ make_listform_token Grammar_pp.pp_COMP_IN @ [mkNT Nt.whitespace; mkNT Nt.number; mkNT Nt.whitespace; mkNT Nt.dots; mkNT Nt.whitespace; mkNT Nt.indexvar_fancy_suffix] @ make_listform_token Grammar_pp.pp_COMP_RIGHT) (fun [_; Res_stli (Stli_single (_, es)); _; _; Res_string ivr; _; _; Res_string lower; _; Res_int dotlength; _; Res_si si'; _] -> let es'' = List.map (Merge.abstract_indexvar_symterm_element ivr 0) es in let b = Bound_comp_lu {bclu_variable=ivr; bclu_lower=Si_num lower; bclu_upper=si'; bclu_length=dotlength} in let stlb = {stl_bound = b; stl_elements = es''; stl_loc = dummy_loc} in Res_stli (Stli_listform stlb)); ignore(add_prod_idx list_help_nt [NT list_form_nt] (fun [Res_stli x] -> Res_stlil [x])); match elb.elb_tmo with None -> ignore(add_prod_transp list_help_nt [NT list_form_nt; NT list_help_nt] res_stlil); () | Some t -> ignore(add_prod_transp list_help_nt ([NT list_form_nt; mkNT Nt.whitespace] @ string_to_terms t @ [NT list_help_nt]) (fun [x; _; y] -> res_stlil [x; y])); () end; list_help_nt in let process_prod (concrete : bool) (nt : Nonterminal.t) (ntr : nontermroot) (p : prod) : unit = let build_res rl = Res_st (St_node (dummy_loc, {st_rule_ntr_name = ntr; st_prod_name = p.prod_name; st_es = process_prod_res rl; st_loc = dummy_loc})) in let rhs = process_elements concrete nt p.prod_name p.prod_es in let index = add_prod_idx nt rhs build_res in if concrete then Hashtbl.add prodname_to_index1 p.prod_name index else match p.prod_disambiguate with | None -> if !fast_parse then Hashtbl.add prodname_to_index1 p.prod_name index else let index2 = add_prod_idx nt (mkNT Nt.whitespace :: (string_to_terms (Auxl.psuedo_terminal_of_prod_name p.prod_name) @ rhs)) (fun (_::rl) -> build_res rl) in Hashtbl.add prodname_to_index2 p.prod_name (index, index2) | Some (s1, s2) -> let index2 = add_prod_idx nt (mkNT Nt.whitespace :: string_to_terms s1 @ (rhs @ string_to_terms s2)) (fun (_::rl) -> build_res rl) in Hashtbl.add prodname_to_index2 p.prod_name (index, index2) in Orig_nt : Res_st let process_rule (r : rule) : unit = let ntr = r.rule_ntr_name in let nt = mknt (Nt.Orig_nt (r.rule_ntr_name, false)) in if not r.rule_meta && not !fast_parse then begin let concrete_prods = List.filter (fun p -> not p.prod_meta || p.prod_sugar) r.rule_ps in let nt_c = mknt (Nt.Orig_nt (r.rule_ntr_name, true)) in List.iter (process_prod true nt_c ntr) concrete_prods; add_prod nt (mkNT Nt.whitespace:: string_to_terms Auxl.parse_as_concrete@ [NT nt_c]) (fun [_; x] -> x) end; the productions from the grammar List.iter (process_prod false nt ntr) r.rule_ps; List.iter (fun nt' -> add_prod nt (mkNT Nt.whitespace::string_to_terms nt' @ [mkNT Nt.suffix]) (fun [_; Res_sil l] -> Res_st (St_nonterm (dummy_loc, ntr, (nt', l))))) (ntr_synonyms r.rule_ntr_name); List.iter (fun ntl -> List.iter (fun nt' -> add_prod nt (mkNT Nt.whitespace::string_to_terms nt' @ [mkNT Nt.suffix]) (fun [_; Res_sil l] -> Res_st (St_nontermsub (dummy_loc, ntl, Auxl.promote_ntr xd ntr, (nt', l))))) (ntr_synonyms ntl)) (Auxl.ntr_proper_subs xd r.rule_ntr_name); if not r.rule_meta then begin end in let add_mvr_idx nt name mvr = add_prod nt (mkNT Nt.whitespace::string_to_terms mvr @ [mkNT Nt.suffix]) (fun [_; Res_sil x] -> Res_ste (Ste_metavar (dummy_loc, name, (mvr, x)))) in let add_mvr_nonidx nt name mvr = add_prod nt (mkNT Nt.whitespace :: string_to_terms mvr) (fun _ -> Res_ste (Ste_metavar (dummy_loc, name, (mvr, [])))); add_alphanum_restr nt in let terminals = Auxl.terminals_of_syntaxdefn xd in let is_tm s = List.mem s terminals in let process_metavar (mvd : metavardefn) : unit = let nt = mknt (Nt.Metavar_nt (mvd.mvd_name, false)) in List.iter (fun (mvr, _) -> if mvd.mvd_indexvar then add_mvr_nonidx nt mvd.mvd_name mvr else add_mvr_idx nt mvd.mvd_name mvr; ) mvd.mvd_names; match lex_regexp_of_mvd mvd with None -> () | Some r -> begin try add_prod nt (mkNT Nt.whitespace :: T ':' :: string_to_terms mvd.mvd_name @ [T ':'; mkNT (List.assoc r concrete_parsers)]) (fun (_::Res_string s::_) -> Res_ste (Ste_metavar (dummy_loc, mvd.mvd_name, (s, [])))) with Not_found -> () end; let nt_aux = mknt (Nt.Gen_nt nt) in let nt_c = mknt (Nt.Metavar_nt (mvd.mvd_name, true)) in if not !fast_parse then try add_prod nt_c [mkNT Nt.whitespace; mkNT (List.assoc r concrete_parsers)] (fun [_; Res_string s] -> if is_tm s then raise Reject_parse else Res_ste (Ste_var (dummy_loc, mvd.mvd_name, s))); add_prod nt_aux [mkNT Nt.whitespace; mkNT (List.assoc r concrete_parsers)] (fun [_; Res_string s] -> Res_ste (Ste_var (dummy_loc, mvd.mvd_name, s))); add_prod_reject nt_aux [mkNT Nt.nt_or_mv] (fun _ -> assert false); add_prod nt [NT nt_aux] (fun [((Res_ste (Ste_var (_, _, s))) as x)] -> if is_tm s then raise Reject_parse else x) with Not_found -> () in add_prod (mknt Nt.whitespace) [] res_ignore; List.iter (fun t -> add_prod (mknt Nt.whitespace) [mkNT Nt.whitespace; t] res_ignore) (string_to_terms " \n\t\013\012"); digit = [ 0 - 9 ] Nt.digit : Auxl.string_iter (let n = mknt Nt.digit in fun c -> add_prod n [T c] (fun _ -> Res_char c)) "0123456789"; add_prod (mknt Nt.digit_plus) [mkNT Nt.digit] (fun [Res_char c] -> Res_charl [c]); add_prod (mknt Nt.digit_plus) [mkNT Nt.digit; mkNT Nt.digit_plus] res_charl; add_num_restr (mknt Nt.digit_plus); add_prod (mknt Nt.digit_plus2) [mkNT Nt.digit_plus] (fun [Res_charl s] -> Res_string (Auxl.string_of_char_list s)); add_alphanum_restr (mknt Nt.digit_plus2); Nt.dots : add_prod (mknt Nt.dots) (string_to_terms "..") (fun _ -> Res_int 0); add_prod (mknt Nt.dots) (string_to_terms "...") (fun _ -> Res_int 1); add_prod (mknt Nt.dots) (string_to_terms "....") (fun _ -> Res_int 2); add_prod (mknt Nt.suffix) [] (fun _ -> Res_sil []); add_prod (mknt Nt.suffix) [mkNT Nt.suffix_item; mkNT Nt.suffix] (fun [Res_si s; Res_sil sl] -> Res_sil (s::sl)); add_alphanum_restr (mknt Nt.suffix); suffix_item = [ 0 - 9]+|_|'|indexvar_fancy_suffix add_prod (mknt Nt.suffix_item) [mkNT Nt.digit_plus] (fun [Res_charl l] -> Res_si (Si_num (Auxl.string_of_char_list l))); add_prod (mknt Nt.suffix_item) [T '_'] (fun _ -> Res_si (Si_punct "_")); add_prod (mknt Nt.suffix_item) [T '\''] (fun _ -> Res_si (Si_punct "'")); add_prod (mknt Nt.suffix_item) [mkNT Nt.indexvar_fancy_suffix] (fun [rsi] -> rsi); Nt.cap_az : Auxl.string_iter (let n = mknt Nt.cap_az in fun c -> add_prod n [T c] (fun _ -> Res_char c)) "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Nt.az : Auxl.string_iter (let n = mknt Nt.az in fun c -> add_prod n [T c] (fun _ -> Res_char c)) "abcdefghijklmnopqrstuvwxyz"; Nt.alpha_follow : Res_charl add_prod (mknt Nt.alpha_follow) [] (fun _ -> Res_charl []); add_prod (mknt Nt.alpha_follow) [mkNT Nt.az; mkNT Nt.alpha_follow] res_charl; add_prod (mknt Nt.alpha_follow) [mkNT Nt.cap_az; mkNT Nt.alpha_follow] res_charl; add_prod (mknt Nt.alpha_follow) [mkNT Nt.digit; mkNT Nt.alpha_follow] res_charl; add_prod (mknt Nt.alpha_follow) [T '_'; mkNT Nt.alpha_follow] (fun [Res_charl c] -> Res_charl ('_'::c)); add_prod (mknt Nt.alpha_follow) [T '\''; mkNT Nt.alpha_follow] (fun [Res_charl c] -> Res_charl ('\''::c)); add_prod (mknt Nt.alphanum0) [mkNT Nt.az; mkNT Nt.alpha_follow] res_cons_string; add_alphanum_restr (mknt Nt.alphanum0); add_prod (mknt Nt.alphanum) [mkNT Nt.az; mkNT Nt.alpha_follow] res_cons_string; add_prod (mknt Nt.alphanum) [mkNT Nt.cap_az; mkNT Nt.alpha_follow] res_cons_string; add_alphanum_restr (mknt Nt.alphanum); add_prod (mknt Nt.cap_alphanum) [mkNT Nt.cap_az; mkNT Nt.alpha_follow] res_cons_string; add_alphanum_restr (mknt Nt.cap_alphanum); number = 0|1 Nt.number : Res_string add_prod (mknt Nt.number) [T '0'] (fun _ -> Res_string "0"); add_prod (mknt Nt.number) [T '1'] (fun _ -> Res_string "1"); add_alphanum_restr (mknt Nt.number); List.iter (fun iv -> add_prod (mknt Nt.indexvar) (string_to_terms iv) (fun _ -> Res_string iv)) (Auxl.all_indexvar_synonyms xd); add_prod (mknt Nt.indexvar_fancy_suffix) [mkNT Nt.indexvar] (fun [Res_string s] -> Res_si (Si_var (s, 0))); add_prod (mknt Nt.indexvar_fancy_suffix) (mkNT Nt.indexvar :: string_to_terms "-1") (fun [Res_string s] -> Res_si (Si_var (s, -1))); if not !fast_parse then begin List.iter (add_mvr_nonidx (mknt Nt.nt_or_mv) "") (Auxl.all_index_mvrs_defined_by_syntaxdefn xd); List.iter (add_mvr_idx (mknt Nt.nt_or_mv) "") (Auxl.all_nonindex_mvrs_defined_by_syntaxdefn xd); List.iter (fun nt -> add_prod (mknt Nt.nt_or_mv) (mkNT Nt.whitespace::string_to_terms nt @ [mkNT Nt.suffix]) (fun [_; Res_sil x] -> Res_st (St_nonterm (dummy_loc, "", (nt, x))))) (Auxl.all_ntrs_defined_by_syntaxdefn xd); end; List.iter process_metavar xd.xd_mds; List.iter process_rule xd.xd_rs; List.iter (fun term -> let term_nt = mknt (Nt.Term_nt term) in add_prod term_nt (mkNT Nt.whitespace::string_to_terms term) (fun [x] -> x); if Auxl.last_char_isalphanum term then add_alphanum_restr term_nt) (Auxl.terminals_of_syntaxdefn xd); if !Global_option.do_pp_grammar then begin print_string "\n----------------- Grammar -----------------\n"; List.iter (fun p -> print_string (Nonterminal.to_string p.prod_left); print_string " ::= "; List.iter (function (T t) -> print_string (Terminal.to_string t ^ " ") | (NT nt) -> print_string (Nonterminal.to_string nt ^ " ")) p.prod_right; print_string "(** #"; print_string (string_of_int p.index); print_string (if p.reject then "reject" else " "); print_string (if p.transparent then "transparent" else " "); print_string "**) "; print_string "\n") !prods; print_string "\n----------------- Follow restrictions -----------------\n"; print_string "nonterminal cannot be followed by character set\n\n"; List.iter (function | (nt,Single follow, s) -> print_string (Nonterminal.to_string nt ^ " cannot be followed by " ^ s ^ "\n") | (nt, Multi _, s) -> print_string (Nonterminal.to_string nt ^ " unsupported multi-term follow restriction\n")) !follows; print_string "\n----------------- Priorities -----------------\n"; List.iter (function | Right(x,y) -> Format.printf "Right #%d #%d\n" x y | Left(x,y) -> Format.printf "Left #%d #%d\n" x y | Greater(x,y) -> Format.printf "Greater #%d #%d\n" x y | Nonassoc(x,y) -> Format.printf "Nonassoc #%d #%d\n" x y) !priorities; end; List.iter (fun (pn1, annot, pn2, loc) -> let (i1, i1') = Hashtbl.find prodname_to_index2 pn1 in let (i2, i2') = Hashtbl.find prodname_to_index2 pn2 in let entry = match annot with Types.LTEQ -> [Greater (i2, i1); Greater (i2', i1)] | Types.Left -> [Left (i1, i2); Left (i1', i2)] | Types.Right -> [Right (i1, i2); Right (i1', i2)] | Types.Non -> [Nonassoc (i1, i2); Nonassoc (i1', i2)] in let entry = try let c1 = Hashtbl.find prodname_to_index1 pn1 in let c2 = Hashtbl.find prodname_to_index1 pn2 in match annot with Types.LTEQ -> [Greater (c2, c1)]@entry | Types.Left -> [Left (c1, c2)]@entry | Types.Right -> [Right (c1, c2)]@entry | Types.Non -> [Nonassoc (c1, c2)]@entry with Not_found -> entry in priorities := entry @ !priorities) xd.xd_pas.pa_data; let inits = List.fold_right (fun r acc -> let s1 = mknt (Nt.Orig_nt (r.rule_ntr_name, false)) in if r.rule_meta || !fast_parse then s1 :: acc else s1 :: mknt (Nt.Orig_nt (r.rule_ntr_name, true)) :: acc) xd.xd_rs [] in if !Global_option.do_pp_grammar then begin print_string "\n----------------- Initial non-terminals -----------------\n"; print_string "The non-terminals that we want parsers for\n"; List.iter (fun init -> print_string (Nonterminal.to_string init ^ "\n")) inits end; (!prods, (List.map (fun (a,b,c) -> (a,b)) !follows), !priorities, inits, mknt);;
21cc07e41e7ba80dcc65ae0f10f668db5b16854fa730841002a13f3b903a46a7
facebook/flow
reason.mli
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val mk_id : unit -> int type name = | OrdinaryName of string | InternalName of string | InternalModuleName of string [@@deriving eq, ord, show] type 'loc virtual_reason_desc = | RTrusted of 'loc virtual_reason_desc | RPrivate of 'loc virtual_reason_desc | RAnyExplicit | RAnyImplicit | RNumber | RBigInt | RString | RBoolean | RMixed | REmpty | REmptyArrayElement | RVoid | RNull | RVoidedNull | RSymbol | RExports | RNullOrVoid length | RStringLit of name | RNumberLit of string | RBigIntLit of string | RBooleanLit of bool | RIndexedAccess of { optional: bool } | RMatchingProp of string * 'loc virtual_reason_desc | RObject | RObjectLit | RObjectType | RObjectClassName | RInterfaceType | RArray | RArrayLit | REmptyArrayLit | RArrayType | RROArrayType | RTupleType | RTupleElement | RTupleLength of int | RTupleOutOfBoundsAccess of int | RFunction of reason_desc_function | RFunctionType | RFunctionBody | RFunctionCall of 'loc virtual_reason_desc | RFunctionCallType | RFunctionUnusedArgument | RJSXFunctionCall of string | RJSXIdentifier of string * string | RJSXElementProps of string | RJSXElement of string option | RJSXText | RFbt | RUnaryOperator of string * 'loc virtual_reason_desc | RBinaryOperator of string * 'loc virtual_reason_desc * 'loc virtual_reason_desc | RLogical of string * 'loc virtual_reason_desc * 'loc virtual_reason_desc | RTemplateString | RUnknownString | RUnionEnum | REnum of string | REnumRepresentation of 'loc virtual_reason_desc | RGetterSetterProperty | RThis | RThisType | RImplicitInstantiation | RTooFewArgs | RTooFewArgsExpectedRest | RConstructorVoidReturn | RNewObject | RUnion | RUnionType | RIntersection | RIntersectionType | RKeySet | RAnd | RConditional | RPrototype | RObjectPrototype | RFunctionPrototype | RDestructuring | RDefaultValue | RConstructor | RDefaultConstructor | RConstructorCall of 'loc virtual_reason_desc | RReturn | RRegExp | RSuper | RNoSuper | RDummyPrototype | RDummyThis | RImplicitThis of 'loc virtual_reason_desc | RTupleMap | RObjectMap | RObjectMapi | RObjectKeyMirror | RObjectMapConst | RType of name | RTypeAlias of string * 'loc option * 'loc virtual_reason_desc | ROpaqueType of string | RTypeParam of Subst_name.t * ('loc virtual_reason_desc * 'loc) * ('loc virtual_reason_desc * 'loc) | RTypeParamDefault of 'loc virtual_reason_desc | RTypeParamBound of 'loc virtual_reason_desc | RTypeof of string | RMethod of string option | RMethodCall of string option | RParameter of string option | RRestParameter of string option | RIdentifier of name | RUnknownParameter of string | RIdentifierAssignment of string | RPropertyAssignment of string option | RProperty of name option | RPrivateProperty of string | RMember of { object_: string; property: string; } | RPropertyOf of name * 'loc virtual_reason_desc | RPropertyIsAString of name | RMissingProperty of name option | RUnknownProperty of name option | RUnknownUnspecifiedProperty of 'loc virtual_reason_desc | RUndefinedProperty of name | RSomeProperty | RNameProperty of 'loc virtual_reason_desc | RMissingAbstract of 'loc virtual_reason_desc | RFieldInitializer of string | RUntypedModule of string | RNamedImportedType of string * string | RImportStarType of string | RImportStarTypeOf of string | RImportStar of string | RDefaultImportedType of string * string | RAsyncImport | RCode of string | RCustom of string | RPolyType of 'loc virtual_reason_desc | RExactType of 'loc virtual_reason_desc | RReadOnlyType | ROptional of 'loc virtual_reason_desc | RMaybe of 'loc virtual_reason_desc | RRestArrayLit of 'loc virtual_reason_desc | RAbstract of 'loc virtual_reason_desc | RTypeApp of 'loc virtual_reason_desc | RTypeAppImplicit of 'loc virtual_reason_desc | RThisTypeApp of 'loc virtual_reason_desc | RExtends of 'loc virtual_reason_desc | RClass of 'loc virtual_reason_desc | RStatics of 'loc virtual_reason_desc | RSuperOf of 'loc virtual_reason_desc | RFrozen of 'loc virtual_reason_desc | RBound of 'loc virtual_reason_desc | RPredicateOf of 'loc virtual_reason_desc | RPredicateCall of 'loc virtual_reason_desc | RPredicateCallNeg of 'loc virtual_reason_desc | RRefined of 'loc virtual_reason_desc | RRefinedElement of 'loc virtual_reason_desc | RIncompatibleInstantiation of string | RSpreadOf of 'loc virtual_reason_desc | RShapeOf of 'loc virtual_reason_desc | RPartialOf of 'loc virtual_reason_desc | RRequiredOf of 'loc virtual_reason_desc | RObjectPatternRestProp | RArrayPatternRestProp | RCommonJSExports of string | RModule of name | ROptionalChain | RReactProps | RReactElement of name option | RReactClass | RReactComponent | RReactStatics | RReactDefaultProps | RReactState | RReactPropTypes | RReactChildren | RReactChildrenOrType of 'loc virtual_reason_desc | RReactChildrenOrUndefinedOrType of 'loc virtual_reason_desc | RReactSFC | RReactConfig | RPossiblyMissingPropFromObj of name * 'loc virtual_reason_desc | RWidenedObjProp of 'loc virtual_reason_desc | RUnionBranching of 'loc virtual_reason_desc * int | RUninitialized | RPossiblyUninitialized | RUnannotatedNext and reason_desc_function = | RAsync | RGenerator | RAsyncGenerator | RNormal | RUnknown type reason_desc = ALoc.t virtual_reason_desc type 'loc virtual_reason type reason = ALoc.t virtual_reason type concrete_reason = Loc.t virtual_reason type t = reason (* convenience *) (* reason constructor *) val mk_reason : 'loc virtual_reason_desc -> 'loc -> 'loc virtual_reason (* ranges *) val in_range : Loc.t -> Loc.t -> bool val string_of_desc : 'loc virtual_reason_desc -> string val map_reason_locs : ('a -> 'b) -> 'a virtual_reason -> 'b virtual_reason val map_desc_locs : ('a -> 'b) -> 'a virtual_reason_desc -> 'b virtual_reason_desc val string_of_loc : ?strip_root:Path.t option -> Loc.t -> string val string_of_aloc : ?strip_root:Path.t option -> ALoc.t -> string val json_of_loc : ?strip_root:Path.t option -> ?catch_offset_errors:bool -> offset_table:Offset_utils.t option -> Loc.t -> Hh_json.json val json_of_loc_props : ?strip_root:Path.t option -> ?catch_offset_errors:bool -> offset_table:Offset_utils.t option -> Loc.t -> (string * Hh_json.json) list val json_of_source : ?strip_root:Path.t option -> File_key.t option -> Hh_json.json val json_source_type_of_source : File_key.t option -> Hh_json.json val locationless_reason : reason_desc -> reason val func_reason : async:bool -> generator:bool -> ALoc.t -> reason val display_string_of_name : name -> string val is_internal_name : name -> bool val internal_name : string -> name val internal_name_of_name : name -> name val is_internal_module_name : name -> bool val internal_module_name : string -> name val uninternal_name : name -> string val is_instantiable_reason : 'loc virtual_reason -> bool val is_constant_reason : 'loc virtual_reason -> bool val is_nullish_reason : 'loc virtual_reason -> bool val is_scalar_reason : 'loc virtual_reason -> bool val is_array_reason : 'loc virtual_reason -> bool val is_literal_object_reason : 'loc virtual_reason -> bool val is_lib_reason : reason -> bool val is_lib_reason_def : reason -> bool val is_blamable_reason : reason -> bool val string_of_source : ?strip_root:Path.t option -> File_key.t -> string val string_of_reason : ?strip_root:Path.t option -> reason -> string val dump_reason : ?strip_root:Path.t option -> reason -> string (* accessors *) val poly_loc_of_reason : 'loc virtual_reason -> 'loc val loc_of_reason : concrete_reason -> Loc.t val aloc_of_reason : reason -> ALoc.t val def_aloc_of_reason : reason -> ALoc.t val def_loc_of_reason : concrete_reason -> Loc.t val annot_aloc_of_reason : reason -> ALoc.t option val desc_of_reason : ?unwrap:bool -> 'loc virtual_reason -> 'loc virtual_reason_desc val annot_loc_of_reason : concrete_reason -> Loc.t option (* simple way to get derived reasons whose descriptions are simple replacements of the original *) (* replace desc, but keep loc, def_loc, annot_loc *) val update_desc_reason : ('loc virtual_reason_desc -> 'loc virtual_reason_desc) -> 'loc virtual_reason -> 'loc virtual_reason replace desc , keep loc , but clobber def_loc , annot_loc as in new reason val update_desc_new_reason : ('loc virtual_reason_desc -> 'loc virtual_reason_desc) -> 'loc virtual_reason -> 'loc virtual_reason (* replace desc, but keep loc, def_loc, annot_loc *) val replace_desc_reason : 'loc virtual_reason_desc -> 'loc virtual_reason -> 'loc virtual_reason replace desc , keep loc , but clobber def_loc , annot_loc as in new reason val replace_desc_new_reason : 'loc virtual_reason_desc -> 'loc virtual_reason -> 'loc virtual_reason replace loc , but keep def_loc val repos_reason : 'loc -> 'loc virtual_reason -> 'loc virtual_reason add / replace annot_loc , but keep loc and def_loc val annot_reason : annot_loc:'loc -> 'loc virtual_reason -> 'loc virtual_reason when annot_loc is given , same as ; otherwise , identity val opt_annot_reason : ?annot_loc:'loc -> 'loc virtual_reason -> 'loc virtual_reason create a new reason with annot_loc = loc : same as followed by annot_reason val mk_annot_reason : 'loc virtual_reason_desc -> 'loc -> 'loc virtual_reason module ReasonMap : WrappedMap.S with type key = reason module ImplicitInstantiationReasonMap : WrappedMap.S with type key = reason * reason * reason Nel.t val mk_expression_reason : (ALoc.t, ALoc.t) Flow_ast.Expression.t -> reason val mk_pattern_reason : (ALoc.t, ALoc.t) Flow_ast.Pattern.t -> reason val unknown_elem_empty_array_desc : reason_desc val inferred_union_elem_array_desc : reason_desc val invalidate_rtype_alias : 'loc virtual_reason_desc -> 'loc virtual_reason_desc val code_desc_of_literal : 'loc Flow_ast.Literal.t -> string val code_desc_of_expression : wrap:bool -> ('a, 'b) Flow_ast.Expression.t -> string val code_desc_of_pattern : ('a, 'b) Flow_ast.Pattern.t -> string Pass in any available aloc tables to be used when comparing abstract and concrete locations from * the same file . Usually ` Context.aloc_tables ` is a good choice , but if the context is not * available , the empty map may be appropriate . * the same file. Usually `Context.aloc_tables` is a good choice, but if the context is not * available, the empty map may be appropriate. *) val concretize_equal : ALoc.table Lazy.t Utils_js.FilenameMap.t -> t -> t -> bool val pp_virtual_reason_desc : (Format.formatter -> 'loc -> Ppx_deriving_runtime.unit) -> Format.formatter -> 'loc virtual_reason_desc -> Ppx_deriving_runtime.unit val show_virtual_reason_desc : (Format.formatter -> 'loc -> Ppx_deriving_runtime.unit) -> 'loc virtual_reason_desc -> string val show_reason_desc_function : reason_desc_function -> string
null
https://raw.githubusercontent.com/facebook/flow/95b167abfb0c84213e10339ab40381f9f86a4442/src/common/reason.mli
ocaml
convenience reason constructor ranges accessors simple way to get derived reasons whose descriptions are simple replacements of the original replace desc, but keep loc, def_loc, annot_loc replace desc, but keep loc, def_loc, annot_loc
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val mk_id : unit -> int type name = | OrdinaryName of string | InternalName of string | InternalModuleName of string [@@deriving eq, ord, show] type 'loc virtual_reason_desc = | RTrusted of 'loc virtual_reason_desc | RPrivate of 'loc virtual_reason_desc | RAnyExplicit | RAnyImplicit | RNumber | RBigInt | RString | RBoolean | RMixed | REmpty | REmptyArrayElement | RVoid | RNull | RVoidedNull | RSymbol | RExports | RNullOrVoid length | RStringLit of name | RNumberLit of string | RBigIntLit of string | RBooleanLit of bool | RIndexedAccess of { optional: bool } | RMatchingProp of string * 'loc virtual_reason_desc | RObject | RObjectLit | RObjectType | RObjectClassName | RInterfaceType | RArray | RArrayLit | REmptyArrayLit | RArrayType | RROArrayType | RTupleType | RTupleElement | RTupleLength of int | RTupleOutOfBoundsAccess of int | RFunction of reason_desc_function | RFunctionType | RFunctionBody | RFunctionCall of 'loc virtual_reason_desc | RFunctionCallType | RFunctionUnusedArgument | RJSXFunctionCall of string | RJSXIdentifier of string * string | RJSXElementProps of string | RJSXElement of string option | RJSXText | RFbt | RUnaryOperator of string * 'loc virtual_reason_desc | RBinaryOperator of string * 'loc virtual_reason_desc * 'loc virtual_reason_desc | RLogical of string * 'loc virtual_reason_desc * 'loc virtual_reason_desc | RTemplateString | RUnknownString | RUnionEnum | REnum of string | REnumRepresentation of 'loc virtual_reason_desc | RGetterSetterProperty | RThis | RThisType | RImplicitInstantiation | RTooFewArgs | RTooFewArgsExpectedRest | RConstructorVoidReturn | RNewObject | RUnion | RUnionType | RIntersection | RIntersectionType | RKeySet | RAnd | RConditional | RPrototype | RObjectPrototype | RFunctionPrototype | RDestructuring | RDefaultValue | RConstructor | RDefaultConstructor | RConstructorCall of 'loc virtual_reason_desc | RReturn | RRegExp | RSuper | RNoSuper | RDummyPrototype | RDummyThis | RImplicitThis of 'loc virtual_reason_desc | RTupleMap | RObjectMap | RObjectMapi | RObjectKeyMirror | RObjectMapConst | RType of name | RTypeAlias of string * 'loc option * 'loc virtual_reason_desc | ROpaqueType of string | RTypeParam of Subst_name.t * ('loc virtual_reason_desc * 'loc) * ('loc virtual_reason_desc * 'loc) | RTypeParamDefault of 'loc virtual_reason_desc | RTypeParamBound of 'loc virtual_reason_desc | RTypeof of string | RMethod of string option | RMethodCall of string option | RParameter of string option | RRestParameter of string option | RIdentifier of name | RUnknownParameter of string | RIdentifierAssignment of string | RPropertyAssignment of string option | RProperty of name option | RPrivateProperty of string | RMember of { object_: string; property: string; } | RPropertyOf of name * 'loc virtual_reason_desc | RPropertyIsAString of name | RMissingProperty of name option | RUnknownProperty of name option | RUnknownUnspecifiedProperty of 'loc virtual_reason_desc | RUndefinedProperty of name | RSomeProperty | RNameProperty of 'loc virtual_reason_desc | RMissingAbstract of 'loc virtual_reason_desc | RFieldInitializer of string | RUntypedModule of string | RNamedImportedType of string * string | RImportStarType of string | RImportStarTypeOf of string | RImportStar of string | RDefaultImportedType of string * string | RAsyncImport | RCode of string | RCustom of string | RPolyType of 'loc virtual_reason_desc | RExactType of 'loc virtual_reason_desc | RReadOnlyType | ROptional of 'loc virtual_reason_desc | RMaybe of 'loc virtual_reason_desc | RRestArrayLit of 'loc virtual_reason_desc | RAbstract of 'loc virtual_reason_desc | RTypeApp of 'loc virtual_reason_desc | RTypeAppImplicit of 'loc virtual_reason_desc | RThisTypeApp of 'loc virtual_reason_desc | RExtends of 'loc virtual_reason_desc | RClass of 'loc virtual_reason_desc | RStatics of 'loc virtual_reason_desc | RSuperOf of 'loc virtual_reason_desc | RFrozen of 'loc virtual_reason_desc | RBound of 'loc virtual_reason_desc | RPredicateOf of 'loc virtual_reason_desc | RPredicateCall of 'loc virtual_reason_desc | RPredicateCallNeg of 'loc virtual_reason_desc | RRefined of 'loc virtual_reason_desc | RRefinedElement of 'loc virtual_reason_desc | RIncompatibleInstantiation of string | RSpreadOf of 'loc virtual_reason_desc | RShapeOf of 'loc virtual_reason_desc | RPartialOf of 'loc virtual_reason_desc | RRequiredOf of 'loc virtual_reason_desc | RObjectPatternRestProp | RArrayPatternRestProp | RCommonJSExports of string | RModule of name | ROptionalChain | RReactProps | RReactElement of name option | RReactClass | RReactComponent | RReactStatics | RReactDefaultProps | RReactState | RReactPropTypes | RReactChildren | RReactChildrenOrType of 'loc virtual_reason_desc | RReactChildrenOrUndefinedOrType of 'loc virtual_reason_desc | RReactSFC | RReactConfig | RPossiblyMissingPropFromObj of name * 'loc virtual_reason_desc | RWidenedObjProp of 'loc virtual_reason_desc | RUnionBranching of 'loc virtual_reason_desc * int | RUninitialized | RPossiblyUninitialized | RUnannotatedNext and reason_desc_function = | RAsync | RGenerator | RAsyncGenerator | RNormal | RUnknown type reason_desc = ALoc.t virtual_reason_desc type 'loc virtual_reason type reason = ALoc.t virtual_reason type concrete_reason = Loc.t virtual_reason val mk_reason : 'loc virtual_reason_desc -> 'loc -> 'loc virtual_reason val in_range : Loc.t -> Loc.t -> bool val string_of_desc : 'loc virtual_reason_desc -> string val map_reason_locs : ('a -> 'b) -> 'a virtual_reason -> 'b virtual_reason val map_desc_locs : ('a -> 'b) -> 'a virtual_reason_desc -> 'b virtual_reason_desc val string_of_loc : ?strip_root:Path.t option -> Loc.t -> string val string_of_aloc : ?strip_root:Path.t option -> ALoc.t -> string val json_of_loc : ?strip_root:Path.t option -> ?catch_offset_errors:bool -> offset_table:Offset_utils.t option -> Loc.t -> Hh_json.json val json_of_loc_props : ?strip_root:Path.t option -> ?catch_offset_errors:bool -> offset_table:Offset_utils.t option -> Loc.t -> (string * Hh_json.json) list val json_of_source : ?strip_root:Path.t option -> File_key.t option -> Hh_json.json val json_source_type_of_source : File_key.t option -> Hh_json.json val locationless_reason : reason_desc -> reason val func_reason : async:bool -> generator:bool -> ALoc.t -> reason val display_string_of_name : name -> string val is_internal_name : name -> bool val internal_name : string -> name val internal_name_of_name : name -> name val is_internal_module_name : name -> bool val internal_module_name : string -> name val uninternal_name : name -> string val is_instantiable_reason : 'loc virtual_reason -> bool val is_constant_reason : 'loc virtual_reason -> bool val is_nullish_reason : 'loc virtual_reason -> bool val is_scalar_reason : 'loc virtual_reason -> bool val is_array_reason : 'loc virtual_reason -> bool val is_literal_object_reason : 'loc virtual_reason -> bool val is_lib_reason : reason -> bool val is_lib_reason_def : reason -> bool val is_blamable_reason : reason -> bool val string_of_source : ?strip_root:Path.t option -> File_key.t -> string val string_of_reason : ?strip_root:Path.t option -> reason -> string val dump_reason : ?strip_root:Path.t option -> reason -> string val poly_loc_of_reason : 'loc virtual_reason -> 'loc val loc_of_reason : concrete_reason -> Loc.t val aloc_of_reason : reason -> ALoc.t val def_aloc_of_reason : reason -> ALoc.t val def_loc_of_reason : concrete_reason -> Loc.t val annot_aloc_of_reason : reason -> ALoc.t option val desc_of_reason : ?unwrap:bool -> 'loc virtual_reason -> 'loc virtual_reason_desc val annot_loc_of_reason : concrete_reason -> Loc.t option val update_desc_reason : ('loc virtual_reason_desc -> 'loc virtual_reason_desc) -> 'loc virtual_reason -> 'loc virtual_reason replace desc , keep loc , but clobber def_loc , annot_loc as in new reason val update_desc_new_reason : ('loc virtual_reason_desc -> 'loc virtual_reason_desc) -> 'loc virtual_reason -> 'loc virtual_reason val replace_desc_reason : 'loc virtual_reason_desc -> 'loc virtual_reason -> 'loc virtual_reason replace desc , keep loc , but clobber def_loc , annot_loc as in new reason val replace_desc_new_reason : 'loc virtual_reason_desc -> 'loc virtual_reason -> 'loc virtual_reason replace loc , but keep def_loc val repos_reason : 'loc -> 'loc virtual_reason -> 'loc virtual_reason add / replace annot_loc , but keep loc and def_loc val annot_reason : annot_loc:'loc -> 'loc virtual_reason -> 'loc virtual_reason when annot_loc is given , same as ; otherwise , identity val opt_annot_reason : ?annot_loc:'loc -> 'loc virtual_reason -> 'loc virtual_reason create a new reason with annot_loc = loc : same as followed by annot_reason val mk_annot_reason : 'loc virtual_reason_desc -> 'loc -> 'loc virtual_reason module ReasonMap : WrappedMap.S with type key = reason module ImplicitInstantiationReasonMap : WrappedMap.S with type key = reason * reason * reason Nel.t val mk_expression_reason : (ALoc.t, ALoc.t) Flow_ast.Expression.t -> reason val mk_pattern_reason : (ALoc.t, ALoc.t) Flow_ast.Pattern.t -> reason val unknown_elem_empty_array_desc : reason_desc val inferred_union_elem_array_desc : reason_desc val invalidate_rtype_alias : 'loc virtual_reason_desc -> 'loc virtual_reason_desc val code_desc_of_literal : 'loc Flow_ast.Literal.t -> string val code_desc_of_expression : wrap:bool -> ('a, 'b) Flow_ast.Expression.t -> string val code_desc_of_pattern : ('a, 'b) Flow_ast.Pattern.t -> string Pass in any available aloc tables to be used when comparing abstract and concrete locations from * the same file . Usually ` Context.aloc_tables ` is a good choice , but if the context is not * available , the empty map may be appropriate . * the same file. Usually `Context.aloc_tables` is a good choice, but if the context is not * available, the empty map may be appropriate. *) val concretize_equal : ALoc.table Lazy.t Utils_js.FilenameMap.t -> t -> t -> bool val pp_virtual_reason_desc : (Format.formatter -> 'loc -> Ppx_deriving_runtime.unit) -> Format.formatter -> 'loc virtual_reason_desc -> Ppx_deriving_runtime.unit val show_virtual_reason_desc : (Format.formatter -> 'loc -> Ppx_deriving_runtime.unit) -> 'loc virtual_reason_desc -> string val show_reason_desc_function : reason_desc_function -> string
e96c80464cb2ec54fa8a98cae87d023318d7857102e86baedacccda021e65fb7
flodihn/NextGen
libdist_migrate.erl
-module(libdist_migrate). -include("obj.hrl"). -define(MAX_MESSAGES, 1000). % API -export([ init/0, migrate/2 ]). % handlers -export([ ]). % internal exports -export([ migrate_loop/4 ]). init() -> ok. migrate(AreaSrv, ObjState) -> Reply = rpc:call(AreaSrv, obj_sup, start, [ObjState#obj.type, ObjState]), case Reply of {ok, NewPid} -> ?MODULE:migrate_loop(AreaSrv, NewPid, 0, ObjState); {error, Reason} -> {migration_failed, Reason} end. % Migrated objects enter this loop to die gracefully. migrate_loop(AreaSrv, NewPid, NrMsg, #obj{id=Id} = State) -> receive Event -> NewPid ! Event, ?MODULE:migrate_loop(AreaSrv, NewPid, NrMsg + 1, State) after 1000 -> % If we migrated to a new area, unregister from the shared obj % registry. case libstd_srv:area_name() == libstd_srv:area_name(AreaSrv) of true -> ok; false -> libdist_srv:unregister_obj(Id) end, libstd_srv:unregister_obj(Id), error_logger:info_report([{migration_successful, Id}]), exit(normal) end; Force shutdow after 1000 relayed messages migrate_loop(_AreaSrv, _NewPid, ?MAX_MESSAGES, _State) -> error_logger:info_report([{migration_forced, {max_messages, ?MAX_MESSAGES}}]), exit(normal).
null
https://raw.githubusercontent.com/flodihn/NextGen/3da1c3ee0d8f658383bdf5fccbdd49ace3cdb323/AreaServer/src/libdist/libdist_migrate.erl
erlang
API handlers internal exports Migrated objects enter this loop to die gracefully. If we migrated to a new area, unregister from the shared obj registry.
-module(libdist_migrate). -include("obj.hrl"). -define(MAX_MESSAGES, 1000). -export([ init/0, migrate/2 ]). -export([ ]). -export([ migrate_loop/4 ]). init() -> ok. migrate(AreaSrv, ObjState) -> Reply = rpc:call(AreaSrv, obj_sup, start, [ObjState#obj.type, ObjState]), case Reply of {ok, NewPid} -> ?MODULE:migrate_loop(AreaSrv, NewPid, 0, ObjState); {error, Reason} -> {migration_failed, Reason} end. migrate_loop(AreaSrv, NewPid, NrMsg, #obj{id=Id} = State) -> receive Event -> NewPid ! Event, ?MODULE:migrate_loop(AreaSrv, NewPid, NrMsg + 1, State) after 1000 -> case libstd_srv:area_name() == libstd_srv:area_name(AreaSrv) of true -> ok; false -> libdist_srv:unregister_obj(Id) end, libstd_srv:unregister_obj(Id), error_logger:info_report([{migration_successful, Id}]), exit(normal) end; Force shutdow after 1000 relayed messages migrate_loop(_AreaSrv, _NewPid, ?MAX_MESSAGES, _State) -> error_logger:info_report([{migration_forced, {max_messages, ?MAX_MESSAGES}}]), exit(normal).
7bf2ad0ca5c58275db3cda06d9b5e798f3b9d552976ea001902f09d0ca394ded
avsm/melange
hashcons.ml
* hashcons : hash tables for hash consing * Copyright ( C ) 2000 FILLIATRE * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 , as published by the Free Software Foundation . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . * * See the GNU Library General Public License version 2 for more details * ( enclosed in the file LGPL ) . * hashcons: hash tables for hash consing * Copyright (C) 2000 Jean-Christophe FILLIATRE * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Library General Public License version 2 for more details * (enclosed in the file LGPL). *) s Hash tables for hash - consing . ( Some code is borrowed from the ocaml standard library , which is copyright 1996 INRIA . ) standard library, which is copyright 1996 INRIA.) *) type 'a hash_consed = { hkey : int; tag : int; node : 'a } let gentag = let r = ref 0 in fun () -> incr r; !r type 'a t = { mutable table : 'a hash_consed Weak.t array; mutable totsize : int; (* sum of the bucket sizes *) mutable limit : int; (* max ratio totsize/table length *) } let create sz = let sz = if sz < 7 then 7 else sz in let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in let emptybucket = Weak.create 0 in { table = Array.create sz emptybucket; totsize = 0; limit = 3; } let clear t = let emptybucket = Weak.create 0 in for i = 0 to Array.length t.table - 1 do t.table.(i) <- emptybucket done; t.totsize <- 0; t.limit <- 3 let fold f t init = let rec fold_bucket i b accu = if i >= Weak.length b then accu else match Weak.get b i with | Some v -> fold_bucket (i+1) b (f v accu) | None -> fold_bucket (i+1) b accu in Array.fold_right (fold_bucket 0) t.table init let iter f t = let rec iter_bucket i b = if i >= Weak.length b then () else match Weak.get b i with | Some v -> f v; iter_bucket (i+1) b | None -> iter_bucket (i+1) b in Array.iter (iter_bucket 0) t.table let count t = let rec count_bucket i b accu = if i >= Weak.length b then accu else count_bucket (i+1) b (accu + (if Weak.check b i then 1 else 0)) in Array.fold_right (count_bucket 0) t.table 0 let next_sz n = min (3*n/2 + 3) (Sys.max_array_length - 1) let rec resize t = let oldlen = Array.length t.table in let newlen = next_sz oldlen in if newlen > oldlen then begin let newt = create newlen in newt.limit <- t.limit + 100; (* prevent resizing of newt *) fold (fun d () -> add newt d) t (); t.table <- newt.table; t.limit <- t.limit + 2; end and add t d = let index = d.hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let newsz = min (sz + 3) (Sys.max_array_length - 1) in if newsz <= sz then failwith "Hashcons.Make: hash bucket cannot grow more"; let newbucket = Weak.create newsz in Weak.blit bucket 0 newbucket 0 sz; Weak.set newbucket i (Some d); t.table.(index) <- newbucket; t.totsize <- t.totsize + (newsz - sz); if t.totsize > t.limit * Array.length t.table then resize t; end else begin if Weak.check bucket i then loop (i+1) else Weak.set bucket i (Some d) end in loop 0 let hashcons t d = let hkey = Hashtbl.hash d in let index = hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let hnode = { hkey = hkey; tag = gentag (); node = d } in add t hnode; hnode end else begin match Weak.get_copy bucket i with | Some v when v.node = d -> begin match Weak.get bucket i with | Some v -> v | None -> loop (i+1) end | _ -> loop (i+1) end in loop 0 let stats t = let len = Array.length t.table in let lens = Array.map Weak.length t.table in Array.sort compare lens; let totlen = Array.fold_left ( + ) 0 lens in (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1)) Functorial interface module type HashedType = sig type t val equal : t -> t -> bool val hash : t -> int end module type S = sig type key type t val create : int -> t val clear : t -> unit val hashcons : t -> key -> key hash_consed val iter : (key hash_consed -> unit) -> t -> unit val stats : t -> int * int * int * int * int * int end module Make(H : HashedType) : (S with type key = H.t) = struct type key = H.t type data = H.t hash_consed type t = { mutable table : data Weak.t array; mutable totsize : int; (* sum of the bucket sizes *) mutable limit : int; (* max ratio totsize/table length *) } let emptybucket = Weak.create 0 let create sz = let sz = if sz < 7 then 7 else sz in let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in { table = Array.create sz emptybucket; totsize = 0; limit = 3; } let clear t = for i = 0 to Array.length t.table - 1 do t.table.(i) <- emptybucket done; t.totsize <- 0; t.limit <- 3 let fold f t init = let rec fold_bucket i b accu = if i >= Weak.length b then accu else match Weak.get b i with | Some v -> fold_bucket (i+1) b (f v accu) | None -> fold_bucket (i+1) b accu in Array.fold_right (fold_bucket 0) t.table init let iter f t = let rec iter_bucket i b = if i >= Weak.length b then () else match Weak.get b i with | Some v -> f v; iter_bucket (i+1) b | None -> iter_bucket (i+1) b in Array.iter (iter_bucket 0) t.table let count t = let rec count_bucket i b accu = if i >= Weak.length b then accu else count_bucket (i+1) b (accu + (if Weak.check b i then 1 else 0)) in Array.fold_right (count_bucket 0) t.table 0 let next_sz n = min (3*n/2 + 3) (Sys.max_array_length - 1) let rec resize t = let oldlen = Array.length t.table in let newlen = next_sz oldlen in if newlen > oldlen then begin let newt = create newlen in newt.limit <- t.limit + 100; (* prevent resizing of newt *) fold (fun d () -> add newt d) t (); t.table <- newt.table; t.limit <- t.limit + 2; end and add t d = let index = d.hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let newsz = min (sz + 3) (Sys.max_array_length - 1) in if newsz <= sz then failwith "Hashcons.Make: hash bucket cannot grow more"; let newbucket = Weak.create newsz in Weak.blit bucket 0 newbucket 0 sz; Weak.set newbucket i (Some d); t.table.(index) <- newbucket; t.totsize <- t.totsize + (newsz - sz); if t.totsize > t.limit * Array.length t.table then resize t; end else begin if Weak.check bucket i then loop (i+1) else Weak.set bucket i (Some d) end in loop 0 let hashcons t d = let hkey = H.hash d in let index = hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let hnode = { hkey = hkey; tag = gentag (); node = d } in add t hnode; hnode end else begin match Weak.get_copy bucket i with | Some v when H.equal v.node d -> begin match Weak.get bucket i with | Some v -> v | None -> loop (i+1) end | _ -> loop (i+1) end in loop 0 let stats t = let len = Array.length t.table in let lens = Array.map Weak.length t.table in Array.sort compare lens; let totlen = Array.fold_left ( + ) 0 lens in (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1)) end
null
https://raw.githubusercontent.com/avsm/melange/e92240e6dc8a440cafa91488a1fc367e2ba57de1/lib/dns/hashcons.ml
ocaml
sum of the bucket sizes max ratio totsize/table length prevent resizing of newt sum of the bucket sizes max ratio totsize/table length prevent resizing of newt
* hashcons : hash tables for hash consing * Copyright ( C ) 2000 FILLIATRE * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 , as published by the Free Software Foundation . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . * * See the GNU Library General Public License version 2 for more details * ( enclosed in the file LGPL ) . * hashcons: hash tables for hash consing * Copyright (C) 2000 Jean-Christophe FILLIATRE * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Library General Public License version 2 for more details * (enclosed in the file LGPL). *) s Hash tables for hash - consing . ( Some code is borrowed from the ocaml standard library , which is copyright 1996 INRIA . ) standard library, which is copyright 1996 INRIA.) *) type 'a hash_consed = { hkey : int; tag : int; node : 'a } let gentag = let r = ref 0 in fun () -> incr r; !r type 'a t = { mutable table : 'a hash_consed Weak.t array; } let create sz = let sz = if sz < 7 then 7 else sz in let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in let emptybucket = Weak.create 0 in { table = Array.create sz emptybucket; totsize = 0; limit = 3; } let clear t = let emptybucket = Weak.create 0 in for i = 0 to Array.length t.table - 1 do t.table.(i) <- emptybucket done; t.totsize <- 0; t.limit <- 3 let fold f t init = let rec fold_bucket i b accu = if i >= Weak.length b then accu else match Weak.get b i with | Some v -> fold_bucket (i+1) b (f v accu) | None -> fold_bucket (i+1) b accu in Array.fold_right (fold_bucket 0) t.table init let iter f t = let rec iter_bucket i b = if i >= Weak.length b then () else match Weak.get b i with | Some v -> f v; iter_bucket (i+1) b | None -> iter_bucket (i+1) b in Array.iter (iter_bucket 0) t.table let count t = let rec count_bucket i b accu = if i >= Weak.length b then accu else count_bucket (i+1) b (accu + (if Weak.check b i then 1 else 0)) in Array.fold_right (count_bucket 0) t.table 0 let next_sz n = min (3*n/2 + 3) (Sys.max_array_length - 1) let rec resize t = let oldlen = Array.length t.table in let newlen = next_sz oldlen in if newlen > oldlen then begin let newt = create newlen in fold (fun d () -> add newt d) t (); t.table <- newt.table; t.limit <- t.limit + 2; end and add t d = let index = d.hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let newsz = min (sz + 3) (Sys.max_array_length - 1) in if newsz <= sz then failwith "Hashcons.Make: hash bucket cannot grow more"; let newbucket = Weak.create newsz in Weak.blit bucket 0 newbucket 0 sz; Weak.set newbucket i (Some d); t.table.(index) <- newbucket; t.totsize <- t.totsize + (newsz - sz); if t.totsize > t.limit * Array.length t.table then resize t; end else begin if Weak.check bucket i then loop (i+1) else Weak.set bucket i (Some d) end in loop 0 let hashcons t d = let hkey = Hashtbl.hash d in let index = hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let hnode = { hkey = hkey; tag = gentag (); node = d } in add t hnode; hnode end else begin match Weak.get_copy bucket i with | Some v when v.node = d -> begin match Weak.get bucket i with | Some v -> v | None -> loop (i+1) end | _ -> loop (i+1) end in loop 0 let stats t = let len = Array.length t.table in let lens = Array.map Weak.length t.table in Array.sort compare lens; let totlen = Array.fold_left ( + ) 0 lens in (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1)) Functorial interface module type HashedType = sig type t val equal : t -> t -> bool val hash : t -> int end module type S = sig type key type t val create : int -> t val clear : t -> unit val hashcons : t -> key -> key hash_consed val iter : (key hash_consed -> unit) -> t -> unit val stats : t -> int * int * int * int * int * int end module Make(H : HashedType) : (S with type key = H.t) = struct type key = H.t type data = H.t hash_consed type t = { mutable table : data Weak.t array; } let emptybucket = Weak.create 0 let create sz = let sz = if sz < 7 then 7 else sz in let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in { table = Array.create sz emptybucket; totsize = 0; limit = 3; } let clear t = for i = 0 to Array.length t.table - 1 do t.table.(i) <- emptybucket done; t.totsize <- 0; t.limit <- 3 let fold f t init = let rec fold_bucket i b accu = if i >= Weak.length b then accu else match Weak.get b i with | Some v -> fold_bucket (i+1) b (f v accu) | None -> fold_bucket (i+1) b accu in Array.fold_right (fold_bucket 0) t.table init let iter f t = let rec iter_bucket i b = if i >= Weak.length b then () else match Weak.get b i with | Some v -> f v; iter_bucket (i+1) b | None -> iter_bucket (i+1) b in Array.iter (iter_bucket 0) t.table let count t = let rec count_bucket i b accu = if i >= Weak.length b then accu else count_bucket (i+1) b (accu + (if Weak.check b i then 1 else 0)) in Array.fold_right (count_bucket 0) t.table 0 let next_sz n = min (3*n/2 + 3) (Sys.max_array_length - 1) let rec resize t = let oldlen = Array.length t.table in let newlen = next_sz oldlen in if newlen > oldlen then begin let newt = create newlen in fold (fun d () -> add newt d) t (); t.table <- newt.table; t.limit <- t.limit + 2; end and add t d = let index = d.hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let newsz = min (sz + 3) (Sys.max_array_length - 1) in if newsz <= sz then failwith "Hashcons.Make: hash bucket cannot grow more"; let newbucket = Weak.create newsz in Weak.blit bucket 0 newbucket 0 sz; Weak.set newbucket i (Some d); t.table.(index) <- newbucket; t.totsize <- t.totsize + (newsz - sz); if t.totsize > t.limit * Array.length t.table then resize t; end else begin if Weak.check bucket i then loop (i+1) else Weak.set bucket i (Some d) end in loop 0 let hashcons t d = let hkey = H.hash d in let index = hkey mod (Array.length t.table) in let bucket = t.table.(index) in let sz = Weak.length bucket in let rec loop i = if i >= sz then begin let hnode = { hkey = hkey; tag = gentag (); node = d } in add t hnode; hnode end else begin match Weak.get_copy bucket i with | Some v when H.equal v.node d -> begin match Weak.get bucket i with | Some v -> v | None -> loop (i+1) end | _ -> loop (i+1) end in loop 0 let stats t = let len = Array.length t.table in let lens = Array.map Weak.length t.table in Array.sort compare lens; let totlen = Array.fold_left ( + ) 0 lens in (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1)) end
3304499eba07b9a18e3750f56ebe215cb3a4aff0591cf3481479bbd43c6914a4
lambdacube3d/lambdacube-quake3
Md3Show.hs
import Control.Monad import System.Environment import Text.Show.Pretty import GameEngine.Loader.MD3 main = getArgs >>= mapM_ (loadMD3 >=> pPrint)
null
https://raw.githubusercontent.com/lambdacube3d/lambdacube-quake3/2fbc17eeea7567f2876d86a7ccce4bd8c8e1927c/tools/md3-show/Md3Show.hs
haskell
import Control.Monad import System.Environment import Text.Show.Pretty import GameEngine.Loader.MD3 main = getArgs >>= mapM_ (loadMD3 >=> pPrint)
510fee712fca5cb9b0203ad603f4125c6fea1aa20fed6083ccfc56df215a5f59
tenpureto/tenpureto
TenpuretoTest.hs
module TenpuretoTest where import Test.Tasty import Test.Tasty.HUnit import Tenpureto.Effects.Git ( Committish(..) ) import Tenpureto.Messages import qualified Tenpureto.OrderedMap as OrderedMap import Tenpureto test_extractTemplateName :: [TestTree] test_extractTemplateName = [ testCase "should extract from create message" $ extractTemplateName (commitCreateMessage "foo/bar" ["1", "2"]) @?= Just "foo/bar" , testCase "should extract from update message" $ extractTemplateName (commitUpdateMessage "foo/bar" ["1", "2"]) @?= Just "foo/bar" , testCase "should extract from create message with additional text" $ extractTemplateName (commitCreateMessage "foo/bar" ["1", "2"] <> "Foo foo foo") @?= Just "foo/bar" , testCase "should not extract from other messages" $ extractTemplateName "A\n\nTemplate foo/bar" @?= Nothing ] test_extractTemplateCommits :: [TestTree] test_extractTemplateCommits = [ testCase "should extract from create message" $ extractTemplateCommits (commitCreateMessage "foo/bar" ["1", "2"]) @?= [Committish "1", Committish "2"] , testCase "should extract empty list from create message" $ extractTemplateCommits (commitCreateMessage "foo/bar" []) @?= [] , testCase "should extract from update message" $ extractTemplateCommits (commitUpdateMessage "foo/bar" ["1", "2"]) @?= [Committish "1", Committish "2"] , testCase "should extract from create message with additional text" $ extractTemplateCommits (commitCreateMessage "foo/bar" ["1", "2"] <> "Foo foo foo") @?= [Committish "1", Committish "2"] , testCase "should not extract from other messages" $ extractTemplateCommits "A\n\nTemplate foo/bar" @?= [] ] test_templateNameDefaultReplacement :: [TestTree] test_templateNameDefaultReplacement = [ testCase "should map ssh git url repo name" $ templateNameDefaultReplacement ":x/foo.git" "/tmp/bar" @?= OrderedMap.singleton "foo" "bar" , testCase "should map http git url repo name" $ templateNameDefaultReplacement "" "/tmp/bar" @?= OrderedMap.singleton "foo" "bar" , testCase "should map local git url repo name" $ templateNameDefaultReplacement "/tmp/foo" "/tmp/bar" @?= OrderedMap.singleton "foo" "bar" ]
null
https://raw.githubusercontent.com/tenpureto/tenpureto/886df860200e1a6f44ce07c24a5e7597009f71ef/test/TenpuretoTest.hs
haskell
module TenpuretoTest where import Test.Tasty import Test.Tasty.HUnit import Tenpureto.Effects.Git ( Committish(..) ) import Tenpureto.Messages import qualified Tenpureto.OrderedMap as OrderedMap import Tenpureto test_extractTemplateName :: [TestTree] test_extractTemplateName = [ testCase "should extract from create message" $ extractTemplateName (commitCreateMessage "foo/bar" ["1", "2"]) @?= Just "foo/bar" , testCase "should extract from update message" $ extractTemplateName (commitUpdateMessage "foo/bar" ["1", "2"]) @?= Just "foo/bar" , testCase "should extract from create message with additional text" $ extractTemplateName (commitCreateMessage "foo/bar" ["1", "2"] <> "Foo foo foo") @?= Just "foo/bar" , testCase "should not extract from other messages" $ extractTemplateName "A\n\nTemplate foo/bar" @?= Nothing ] test_extractTemplateCommits :: [TestTree] test_extractTemplateCommits = [ testCase "should extract from create message" $ extractTemplateCommits (commitCreateMessage "foo/bar" ["1", "2"]) @?= [Committish "1", Committish "2"] , testCase "should extract empty list from create message" $ extractTemplateCommits (commitCreateMessage "foo/bar" []) @?= [] , testCase "should extract from update message" $ extractTemplateCommits (commitUpdateMessage "foo/bar" ["1", "2"]) @?= [Committish "1", Committish "2"] , testCase "should extract from create message with additional text" $ extractTemplateCommits (commitCreateMessage "foo/bar" ["1", "2"] <> "Foo foo foo") @?= [Committish "1", Committish "2"] , testCase "should not extract from other messages" $ extractTemplateCommits "A\n\nTemplate foo/bar" @?= [] ] test_templateNameDefaultReplacement :: [TestTree] test_templateNameDefaultReplacement = [ testCase "should map ssh git url repo name" $ templateNameDefaultReplacement ":x/foo.git" "/tmp/bar" @?= OrderedMap.singleton "foo" "bar" , testCase "should map http git url repo name" $ templateNameDefaultReplacement "" "/tmp/bar" @?= OrderedMap.singleton "foo" "bar" , testCase "should map local git url repo name" $ templateNameDefaultReplacement "/tmp/foo" "/tmp/bar" @?= OrderedMap.singleton "foo" "bar" ]
f511ee19130ffeb382dfecf39e20b2b59e93c9d4e754d46b3aaaf304c7bd3064
wireless-net/erlang-nommu
shell_default.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2010 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %% This is just a empty template which calls routines in the module c %% to do all the work! -module(shell_default). -export([help/0,lc/1,c/1,c/2,nc/1,nl/1,l/1,i/0,pid/3,i/3,m/0,m/1, memory/0,memory/1, erlangrc/1,bi/1, regs/0, flush/0,pwd/0,ls/0,ls/1,cd/1, y/1, y/2, xm/1, bt/1, q/0, ni/0, nregs/0]). -export([ih/0,iv/0,im/0,ii/1,ii/2,iq/1,ini/1,ini/2,inq/1,ib/2,ib/3, ir/2,ir/3,ibd/2,ibe/2,iba/3,ibc/3, ic/0,ir/1,ir/0,il/0,ipb/0,ipb/1,iaa/1,iaa/2,ist/1,ia/1,ia/2,ia/3, ia/4,ip/0]). -import(io, [format/1]). help() -> format("** shell internal commands **~n"), format("b() -- display all variable bindings\n"), format("e(N) -- repeat the expression in query <N>\n"), format("f() -- forget all variable bindings\n"), format("f(X) -- forget the binding of variable X\n"), format("h() -- history\n"), format("history(N) -- set how many previous commands to keep\n"), format("results(N) -- set how many previous command results to keep\n"), format("catch_exception(B) -- how exceptions are handled\n"), format("v(N) -- use the value of query <N>\n"), format("rd(R,D) -- define a record\n"), format("rf() -- remove all record information\n"), format("rf(R) -- remove record information about R\n"), format("rl() -- display all record information\n"), format("rl(R) -- display record information about R\n"), format("rp(Term) -- display Term using the shell's record information\n"), format("rr(File) -- read record information from File (wildcards allowed)\n"), format("rr(F,R) -- read selected record information from file(s)\n"), format("rr(F,R,O) -- read selected record information with options\n"), format("** commands in module c **\n"), c:help(), format("** commands in module i (interpreter interface) **\n"), format("ih() -- print help for the i module\n"), %% format("** private commands ** \n"), %% format("myfunc() -- does my operation ...\n"), true. %% these are in alphabetic order it would be nice if they %% were to *stay* so! bi(I) -> c:bi(I). bt(Pid) -> c:bt(Pid). c(File) -> c:c(File). c(File, Opt) -> c:c(File, Opt). cd(D) -> c:cd(D). erlangrc(X) -> c:erlangrc(X). flush() -> c:flush(). i() -> c:i(). i(X,Y,Z) -> c:i(X,Y,Z). l(Mod) -> c:l(Mod). lc(X) -> c:lc(X). ls() -> c:ls(). ls(S) -> c:ls(S). m() -> c:m(). m(Mod) -> c:m(Mod). memory() -> c:memory(). memory(Type) -> c:memory(Type). nc(X) -> c:nc(X). ni() -> c:ni(). nl(Mod) -> c:nl(Mod). nregs() -> c:nregs(). pid(X,Y,Z) -> c:pid(X,Y,Z). pwd() -> c:pwd(). q() -> c:q(). regs() -> c:regs(). xm(Mod) -> c:xm(Mod). y(File) -> c:y(File). y(File, Opts) -> c:y(File, Opts). iaa(Flag) -> calli(iaa, [Flag]). iaa(Flag,Fnk) -> calli(iaa, [Flag,Fnk]). ist(Flag) -> calli(ist, [Flag]). ia(Pid) -> calli(ia, [Pid]). ia(X,Y,Z) -> calli(ia, [X,Y,Z]). ia(Pid,Fnk) -> calli(ia, [Pid,Fnk]). ia(X,Y,Z,Fnk) -> calli(ia, [X,Y,Z,Fnk]). ib(Mod,Line) -> calli(ib, [Mod,Line]). ib(Mod,Fnk,Arity) -> calli(ib, [Mod,Fnk,Arity]). ibd(Mod,Line) -> calli(ibd, [Mod,Line]). ibe(Mod,Line) -> calli(ibe, [Mod,Line]). iba(M,L,Action) -> calli(iba, [M,L,Action]). ibc(M,L,Cond) -> calli(ibc, [M,L,Cond]). ic() -> calli(ic, []). ih() -> calli(help, []). ii(Mod) -> calli(ii, [Mod]). ii(Mod,Op) -> calli(ii, [Mod,Op]). il() -> calli(il, []). im() -> calli(im, []). ini(Mod) -> calli(ini, [Mod]). ini(Mod,Op) -> calli(ini, [Mod,Op]). inq(Mod) -> calli(inq, [Mod]). ip() -> calli(ip, []). ipb() -> calli(ipb, []). ipb(Mod) -> calli(ipb, [Mod]). iq(Mod) -> calli(iq, [Mod]). ir(Mod,Line) -> calli(ir, [Mod,Line]). ir(Mod,Fnk,Arity) -> calli(ir, [Mod,Fnk,Arity]). ir(Mod) -> calli(ir, [Mod]). ir() -> calli(ir, []). iv() -> calli(iv, []). calli(F, Args) -> c:appcall(debugger, i, F, Args).
null
https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/stdlib/src/shell_default.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% This is just a empty template which calls routines in the module c to do all the work! format("** private commands ** \n"), format("myfunc() -- does my operation ...\n"), these are in alphabetic order it would be nice if they were to *stay* so!
Copyright Ericsson AB 1996 - 2010 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(shell_default). -export([help/0,lc/1,c/1,c/2,nc/1,nl/1,l/1,i/0,pid/3,i/3,m/0,m/1, memory/0,memory/1, erlangrc/1,bi/1, regs/0, flush/0,pwd/0,ls/0,ls/1,cd/1, y/1, y/2, xm/1, bt/1, q/0, ni/0, nregs/0]). -export([ih/0,iv/0,im/0,ii/1,ii/2,iq/1,ini/1,ini/2,inq/1,ib/2,ib/3, ir/2,ir/3,ibd/2,ibe/2,iba/3,ibc/3, ic/0,ir/1,ir/0,il/0,ipb/0,ipb/1,iaa/1,iaa/2,ist/1,ia/1,ia/2,ia/3, ia/4,ip/0]). -import(io, [format/1]). help() -> format("** shell internal commands **~n"), format("b() -- display all variable bindings\n"), format("e(N) -- repeat the expression in query <N>\n"), format("f() -- forget all variable bindings\n"), format("f(X) -- forget the binding of variable X\n"), format("h() -- history\n"), format("history(N) -- set how many previous commands to keep\n"), format("results(N) -- set how many previous command results to keep\n"), format("catch_exception(B) -- how exceptions are handled\n"), format("v(N) -- use the value of query <N>\n"), format("rd(R,D) -- define a record\n"), format("rf() -- remove all record information\n"), format("rf(R) -- remove record information about R\n"), format("rl() -- display all record information\n"), format("rl(R) -- display record information about R\n"), format("rp(Term) -- display Term using the shell's record information\n"), format("rr(File) -- read record information from File (wildcards allowed)\n"), format("rr(F,R) -- read selected record information from file(s)\n"), format("rr(F,R,O) -- read selected record information with options\n"), format("** commands in module c **\n"), c:help(), format("** commands in module i (interpreter interface) **\n"), format("ih() -- print help for the i module\n"), true. bi(I) -> c:bi(I). bt(Pid) -> c:bt(Pid). c(File) -> c:c(File). c(File, Opt) -> c:c(File, Opt). cd(D) -> c:cd(D). erlangrc(X) -> c:erlangrc(X). flush() -> c:flush(). i() -> c:i(). i(X,Y,Z) -> c:i(X,Y,Z). l(Mod) -> c:l(Mod). lc(X) -> c:lc(X). ls() -> c:ls(). ls(S) -> c:ls(S). m() -> c:m(). m(Mod) -> c:m(Mod). memory() -> c:memory(). memory(Type) -> c:memory(Type). nc(X) -> c:nc(X). ni() -> c:ni(). nl(Mod) -> c:nl(Mod). nregs() -> c:nregs(). pid(X,Y,Z) -> c:pid(X,Y,Z). pwd() -> c:pwd(). q() -> c:q(). regs() -> c:regs(). xm(Mod) -> c:xm(Mod). y(File) -> c:y(File). y(File, Opts) -> c:y(File, Opts). iaa(Flag) -> calli(iaa, [Flag]). iaa(Flag,Fnk) -> calli(iaa, [Flag,Fnk]). ist(Flag) -> calli(ist, [Flag]). ia(Pid) -> calli(ia, [Pid]). ia(X,Y,Z) -> calli(ia, [X,Y,Z]). ia(Pid,Fnk) -> calli(ia, [Pid,Fnk]). ia(X,Y,Z,Fnk) -> calli(ia, [X,Y,Z,Fnk]). ib(Mod,Line) -> calli(ib, [Mod,Line]). ib(Mod,Fnk,Arity) -> calli(ib, [Mod,Fnk,Arity]). ibd(Mod,Line) -> calli(ibd, [Mod,Line]). ibe(Mod,Line) -> calli(ibe, [Mod,Line]). iba(M,L,Action) -> calli(iba, [M,L,Action]). ibc(M,L,Cond) -> calli(ibc, [M,L,Cond]). ic() -> calli(ic, []). ih() -> calli(help, []). ii(Mod) -> calli(ii, [Mod]). ii(Mod,Op) -> calli(ii, [Mod,Op]). il() -> calli(il, []). im() -> calli(im, []). ini(Mod) -> calli(ini, [Mod]). ini(Mod,Op) -> calli(ini, [Mod,Op]). inq(Mod) -> calli(inq, [Mod]). ip() -> calli(ip, []). ipb() -> calli(ipb, []). ipb(Mod) -> calli(ipb, [Mod]). iq(Mod) -> calli(iq, [Mod]). ir(Mod,Line) -> calli(ir, [Mod,Line]). ir(Mod,Fnk,Arity) -> calli(ir, [Mod,Fnk,Arity]). ir(Mod) -> calli(ir, [Mod]). ir() -> calli(ir, []). iv() -> calli(iv, []). calli(F, Args) -> c:appcall(debugger, i, F, Args).
94e3f9148850444d978ba0870564de1f588297aefbe35f020b155b9ccca65e41
janestreet/core
validated.ml
open! Import open Std_internal open Validated_intf module type Raw = Raw type ('raw, 'witness) t = 'raw module type S = S with type ('a, 'b) validated := ('a, 'b) t module type S_allowing_substitution = S_allowing_substitution with type ('a, 'b) validated := ('a, 'b) t module type S_bin_io = S_bin_io with type ('a, 'b) validated := ('a, 'b) t module type S_bin_io_compare_hash_sexp = S_bin_io_compare_hash_sexp with type ('a, 'b) validated := ('a, 'b) t let raw t = t module Make (Raw : Raw) = struct type witness type t = Raw.t [@@deriving sexp_of] let validation_failed t error = Error.create "validation failed" (t, error, Raw.here) [%sexp_of: Raw.t * Error.t * Source_code_position.t] ;; let create_exn t = match Validate.result (Raw.validate t) with | Ok () -> t | Error error -> Error.raise (validation_failed t error) ;; let create t = match Validate.result (Raw.validate t) with | Ok () -> Ok t | Error error -> Error (validation_failed t error) ;; let t_of_sexp sexp = create_exn (Raw.t_of_sexp sexp) let raw t = t let create_stable_witness raw_stable_witness = Stable_witness.of_serializable raw_stable_witness create_exn raw ;; let type_equal = Type_equal.T end module Add_bin_io (Raw : sig type t [@@deriving bin_io] include Raw_bin_io with type t := t end) (Validated : S with type raw := Raw.t) = struct include Binable.Of_binable_without_uuid [@alert "-legacy"] (Raw) (struct type t = Raw.t let of_binable raw = if Raw.validate_binio_deserialization then Validated.create_exn raw else raw ;; let to_binable = Fn.id end) end module Add_compare (Raw : sig type t [@@deriving compare] include Raw with type t := t end) (_ : S with type raw := Raw.t) = struct let compare t1 t2 = [%compare: Raw.t] (raw t1) (raw t2) end module Add_hash (Raw : sig type t [@@deriving hash] include Raw with type t := t end) (Validated : S with type raw := Raw.t) = struct let hash_fold_t state t = Raw.hash_fold_t state (Validated.raw t) let hash t = Raw.hash (Validated.raw t) end module Add_typerep (Raw : sig type t [@@deriving typerep] include Raw with type t := t end) (_ : S with type raw := Raw.t) = struct type t = Raw.t [@@deriving typerep] end module Make_binable (Raw : Raw_bin_io) = struct module T0 = Make (Raw) include T0 include Add_bin_io (Raw) (T0) end module Make_bin_io_compare_hash_sexp (Raw : sig type t [@@deriving compare, hash] include Raw_bin_io with type t := t end) = struct module T = Make_binable (Raw) include T include Add_compare (Raw) (T) include ( Add_hash (Raw) (T) : sig type t [@@deriving hash] end with type t := t) end
null
https://raw.githubusercontent.com/janestreet/core/4b6635d206f7adcfac8324820d246299d6f572fe/core/src/validated.ml
ocaml
open! Import open Std_internal open Validated_intf module type Raw = Raw type ('raw, 'witness) t = 'raw module type S = S with type ('a, 'b) validated := ('a, 'b) t module type S_allowing_substitution = S_allowing_substitution with type ('a, 'b) validated := ('a, 'b) t module type S_bin_io = S_bin_io with type ('a, 'b) validated := ('a, 'b) t module type S_bin_io_compare_hash_sexp = S_bin_io_compare_hash_sexp with type ('a, 'b) validated := ('a, 'b) t let raw t = t module Make (Raw : Raw) = struct type witness type t = Raw.t [@@deriving sexp_of] let validation_failed t error = Error.create "validation failed" (t, error, Raw.here) [%sexp_of: Raw.t * Error.t * Source_code_position.t] ;; let create_exn t = match Validate.result (Raw.validate t) with | Ok () -> t | Error error -> Error.raise (validation_failed t error) ;; let create t = match Validate.result (Raw.validate t) with | Ok () -> Ok t | Error error -> Error (validation_failed t error) ;; let t_of_sexp sexp = create_exn (Raw.t_of_sexp sexp) let raw t = t let create_stable_witness raw_stable_witness = Stable_witness.of_serializable raw_stable_witness create_exn raw ;; let type_equal = Type_equal.T end module Add_bin_io (Raw : sig type t [@@deriving bin_io] include Raw_bin_io with type t := t end) (Validated : S with type raw := Raw.t) = struct include Binable.Of_binable_without_uuid [@alert "-legacy"] (Raw) (struct type t = Raw.t let of_binable raw = if Raw.validate_binio_deserialization then Validated.create_exn raw else raw ;; let to_binable = Fn.id end) end module Add_compare (Raw : sig type t [@@deriving compare] include Raw with type t := t end) (_ : S with type raw := Raw.t) = struct let compare t1 t2 = [%compare: Raw.t] (raw t1) (raw t2) end module Add_hash (Raw : sig type t [@@deriving hash] include Raw with type t := t end) (Validated : S with type raw := Raw.t) = struct let hash_fold_t state t = Raw.hash_fold_t state (Validated.raw t) let hash t = Raw.hash (Validated.raw t) end module Add_typerep (Raw : sig type t [@@deriving typerep] include Raw with type t := t end) (_ : S with type raw := Raw.t) = struct type t = Raw.t [@@deriving typerep] end module Make_binable (Raw : Raw_bin_io) = struct module T0 = Make (Raw) include T0 include Add_bin_io (Raw) (T0) end module Make_bin_io_compare_hash_sexp (Raw : sig type t [@@deriving compare, hash] include Raw_bin_io with type t := t end) = struct module T = Make_binable (Raw) include T include Add_compare (Raw) (T) include ( Add_hash (Raw) (T) : sig type t [@@deriving hash] end with type t := t) end
78b2d9fc9a3105352605e216893d08a451be70dd476aa9f44eee5eb9ebfe2a95
REPROSEC/dolev-yao-star
Vale_AES_OptPublic.ml
open Prims let (shift_gf128_key_1 : Vale_Math_Poly2_s.poly -> Vale_Math_Poly2_s.poly) = fun h -> Vale_AES_GF128.shift_key_1 (Prims.of_int (128)) Vale_AES_GF128_s.gf128_modulus_low_terms h let rec (g_power : Vale_Math_Poly2_s.poly -> Prims.nat -> Vale_Math_Poly2_s.poly) = fun a -> fun n -> if n = Prims.int_zero then Vale_Math_Poly2_s.zero else if n = Prims.int_one then a else Vale_AES_GF128.op_Star_Tilde a (g_power a (n - Prims.int_one)) let (gf128_power : Vale_Math_Poly2_s.poly -> Prims.nat -> Vale_Math_Poly2_s.poly) = fun h -> fun n -> shift_gf128_key_1 (g_power h n) type ('hkeys, 'huBE) hkeys_reqs_pub = unit let (get_hkeys_reqs : Vale_Def_Types_s.quad32 -> (Vale_Def_Types_s.quad32, unit) FStar_Seq_Properties.lseq) = fun h_BE -> let h = Vale_Math_Poly2_Bits_s.of_quad32 (Vale_Def_Types_s.reverse_bytes_quad32 (Vale_Def_Types_s.reverse_bytes_quad32 h_BE)) in let l = [Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h Prims.int_one); Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (2))); h_BE; Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (3))); Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (4))); { Vale_Def_Words_s.lo0 = Prims.int_zero; Vale_Def_Words_s.lo1 = Prims.int_zero; Vale_Def_Words_s.hi2 = Prims.int_zero; Vale_Def_Words_s.hi3 = Prims.int_zero }; Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (5))); Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (6)))] in let s = FStar_Seq_Properties.seq_of_list l in s
null
https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Vale_AES_OptPublic.ml
ocaml
open Prims let (shift_gf128_key_1 : Vale_Math_Poly2_s.poly -> Vale_Math_Poly2_s.poly) = fun h -> Vale_AES_GF128.shift_key_1 (Prims.of_int (128)) Vale_AES_GF128_s.gf128_modulus_low_terms h let rec (g_power : Vale_Math_Poly2_s.poly -> Prims.nat -> Vale_Math_Poly2_s.poly) = fun a -> fun n -> if n = Prims.int_zero then Vale_Math_Poly2_s.zero else if n = Prims.int_one then a else Vale_AES_GF128.op_Star_Tilde a (g_power a (n - Prims.int_one)) let (gf128_power : Vale_Math_Poly2_s.poly -> Prims.nat -> Vale_Math_Poly2_s.poly) = fun h -> fun n -> shift_gf128_key_1 (g_power h n) type ('hkeys, 'huBE) hkeys_reqs_pub = unit let (get_hkeys_reqs : Vale_Def_Types_s.quad32 -> (Vale_Def_Types_s.quad32, unit) FStar_Seq_Properties.lseq) = fun h_BE -> let h = Vale_Math_Poly2_Bits_s.of_quad32 (Vale_Def_Types_s.reverse_bytes_quad32 (Vale_Def_Types_s.reverse_bytes_quad32 h_BE)) in let l = [Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h Prims.int_one); Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (2))); h_BE; Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (3))); Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (4))); { Vale_Def_Words_s.lo0 = Prims.int_zero; Vale_Def_Words_s.lo1 = Prims.int_zero; Vale_Def_Words_s.hi2 = Prims.int_zero; Vale_Def_Words_s.hi3 = Prims.int_zero }; Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (5))); Vale_Math_Poly2_Bits_s.to_quad32 (gf128_power h (Prims.of_int (6)))] in let s = FStar_Seq_Properties.seq_of_list l in s
7f397db97d33b67f837bfc33c58804a4751fe43891fda5106821b0bcad157c2c
janestreet/merlin-jst
linear_format.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt , Jane Street Europe (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) Copyright 2019 Jane Street Group LLC (* *) (* 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. *) (* *) (**************************************************************************) (* Format of .cmir-linear files *) Compiler can optionally save Linear representation of a compilation unit , along with other information required to emit assembly . along with other information required to emit assembly. *) type linear_item_info = | Func of Linear.fundecl | Data of Cmm.data_item list type linear_unit_info = { mutable unit : Compilation_unit.t; mutable items : linear_item_info list; } Marshal and unmarshal a compilation unit in Linear format . It includes saving and restoring global state required for Emit , that currently consists of Cmm.label_counter . It includes saving and restoring global state required for Emit, that currently consists of Cmm.label_counter. *) val save : string -> linear_unit_info -> unit val restore : string -> linear_unit_info * Digest.t
null
https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/upstream/ocaml_flambda/file_formats/linear_format.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. ************************************************************************ Format of .cmir-linear files
, projet Cristal , INRIA Rocquencourt , Jane Street Europe Copyright 1996 Institut National de Recherche en Informatique et Copyright 2019 Jane Street Group LLC the GNU Lesser General Public License version 2.1 , with the Compiler can optionally save Linear representation of a compilation unit , along with other information required to emit assembly . along with other information required to emit assembly. *) type linear_item_info = | Func of Linear.fundecl | Data of Cmm.data_item list type linear_unit_info = { mutable unit : Compilation_unit.t; mutable items : linear_item_info list; } Marshal and unmarshal a compilation unit in Linear format . It includes saving and restoring global state required for Emit , that currently consists of Cmm.label_counter . It includes saving and restoring global state required for Emit, that currently consists of Cmm.label_counter. *) val save : string -> linear_unit_info -> unit val restore : string -> linear_unit_info * Digest.t
37adb8615146e9b4254a92d3894993347c0eb261438e2eb23ceb11861686813a
gvolpe/haskell-book-exercises
arith4.hs
module Arith4 where -- id :: a -> a -- id x = x roundTrip :: (Show a, Read a) => a -> a roundTrip = read . show roundTripAlt :: (Show a, Read b) => a -> b roundTripAlt = read . show main = do roundTrip 4 print (id 4)
null
https://raw.githubusercontent.com/gvolpe/haskell-book-exercises/5c1b9d8dc729ee5a90c8709b9c889cbacb30a2cb/chapter7/arith4.hs
haskell
id :: a -> a id x = x
module Arith4 where roundTrip :: (Show a, Read a) => a -> a roundTrip = read . show roundTripAlt :: (Show a, Read b) => a -> b roundTripAlt = read . show main = do roundTrip 4 print (id 4)
ae9874e7170f96fc2013b2a94921e2372ef2dc94fc11274a805089cabd46c31d
repl-acement/repl-acement
def.cljs
(ns replacement.forms.events.def "A `def` form creates a global variable and can have an expression to set the initial value. This namespace is concerned with breaking the def forms down using `spec/conform` and putting them back together with `unform`. Editing by a human or a function may happen in between providing that it remains `unform`-able. This is relaxed for humans but not for functions. It is organized to match the life-cycle: ✓ event to set the whole view of a specific form-id ✓ --> fn to write the parts CMs to set the parts view of the whole ✓ event to transact changes (keystrokes) on the whole form ✓ --> fn to ripple out change to appropriate parts ✓ events to transact changes (keystrokes) on any of the form parts ✓ --> fn to reflect back the part change to whole" (:require [cljs.tools.reader.edn :as rdr] [clojure.core.async] [cljs.spec.alpha :as s] [re-frame.core :as re-frame :refer [reg-event-db reg-event-fx reg-fx]] [replacement.forms.events.common :as common] [replacement.protocol.data :as data-specs] [replacement.ui.helpers :refer [js->cljs]] [replacement.structure.wiring :as wiring] [zprint.core :refer [zprint-file-str]])) (defn extract-tx-text [^js tx] (->> (.-newDoc tx) (.toJSON) js->cljs (apply str))) (defn extract-cm-text [^js cm] (->> (-> cm .-state .-doc) (.toJSON) js->cljs (apply str))) (defn- update-cm ([cm tx] (update-cm cm tx nil)) ([cm tx event-args] (.update cm #js [tx]) (when event-args (re-frame/dispatch event-args)))) (defn- replacement-tx [cm text] (let [cm-state (-> cm .-state) doc-length (-> cm-state .-doc .-length)] (.update cm-state (clj->js {:changes {:from 0 :to doc-length :insert text}})))) (reg-fx ::fn-part-update (fn [[cm tx changed?]] (if changed? (update-cm cm tx [::set-part-in-whole]) (update-cm cm tx)))) (reg-event-fx ::part-edit (fn [{:keys [db]} [_ part-cm-name tx]] (let [cm (get-in db [part-cm-name :cm]) changed? (js->cljs (.-docChanged tx))] {:db db ::fn-part-update [cm tx changed?]}))) (reg-fx ::whole-edit (fn [[cm tx changed?]] (if changed? (update-cm cm tx [::transact-whole-form (extract-tx-text tx)]) (update-cm cm tx)))) (reg-event-fx ::def-whole-form-tx (fn [{:keys [db]} [_ cm-name tx]] (let [cm (get-in db [cm-name :cm]) changed? (js->cljs (.-docChanged tx))] {:db db ::whole-edit [cm tx changed?]}))) (reg-event-db ::set-cm+name (fn [db [_ cm comp-name]] (assoc db comp-name {:cm cm :name comp-name}))) (reg-fx ::update-cms (fn [changes] (doall (map (fn [{:keys [cm tx]}] (update-cm cm tx)) changes)))) (def parts [:def.name :def.docstring :def.init]) (def part->props-map (apply merge (map #(hash-map %1 %2) [:var-name :docstring :init-expr] parts))) (defn- def-data->properties [def-data] (reduce-kv (fn [data k v] (-> data (dissoc k) (assoc v (data k)))) def-data part->props-map)) (defn update-cm-states [db def-data cms cm-key] (if-let [cm (get-in db [cm-key :cm])] (let [def-property-name (wiring/cm-name->comp-name cm-key) new-text (pr-str (get def-data def-property-name)) tx (replacement-tx cm new-text)] (conj cms {:cm cm :tx tx})) cms)) (reg-event-fx ::fixed-items-update-cms (fn [{:keys [db]} [_]] (let [cm-keys (map wiring/comp-name->cm-name parts) def-data (def-data->properties db) cms-with-changes (reduce (partial update-cm-states db def-data) [] cm-keys)] {:db db ::update-cms cms-with-changes}))) (defn- text->spec-data [text] (let [data (rdr/read-string text) conformed (s/conform ::data-specs/def-form data) explain-data (and (s/invalid? conformed) (s/explain-data ::data-specs/def-form data)) unformed (or (s/invalid? conformed) (s/unform ::data-specs/def-form conformed))] {:def.text (-> unformed pr-str common/fix-width-format) :def.conformed conformed :def.explain-data explain-data :def.unformed unformed})) (defn conformed->spec-data [conformed] (let [unformed (when-not (s/invalid? conformed) (s/unform ::data-specs/def-form conformed))] {:def.text (-> unformed pr-str common/fix-width-format) :def.conformed conformed :def.explain-data (when (s/invalid? conformed) (s/explain-data ::data-specs/def-form conformed)) :def.unformed unformed})) (defn conformed-form->spec-data [{:keys [conformed]}] (let [unformed (when-not (s/invalid? conformed) (s/unform ::data-specs/form conformed))] {:text (-> unformed pr-str common/fix-width-format) :conformed conformed :explain-data (when (s/invalid? conformed) (s/explain-data ::data-specs/form conformed)) :unformed unformed})) (defn get-var-data [current-ns var-id] (let [form (get-in current-ns [:forms var-id])] {:def-data (conformed-form->spec-data form) :def-name (::data-specs/var-name form)})) (defn- cm-keys->text [db cm-keys] (->> (reduce (fn [text k] (->> (get-in db [k :cm]) (extract-cm-text) (conj text))) [] cm-keys) (interpose " ") (apply str))) (defn- common-parts-text [db] (->> (map wiring/comp-name->cm-name parts) (cm-keys->text db))) (reg-fx ::whole-update (fn [[cm whole-text]] (->> (zprint-file-str whole-text ::whole-update) (replacement-tx cm) (update-cm cm)))) ;; TODO: this should be from def.text that is built from unform ;; and such a change should be signalled per active CM ;; in short, this function is not needed (defn- whole-form-updated "Scan over all the active code mirrors that can provide updates and create the new form to reflect any updates" [db] (let [fixed-parts (common-parts-text db) form-text (apply str fixed-parts)] (str "(def " form-text ")"))) (reg-event-fx ::set-part-in-whole (fn [{:keys [db]} [_]] (let [cm (get-in db [:def.form.cm :cm]) whole-text (whole-form-updated db) updates (text->spec-data whole-text)] {:db (merge db updates) ::whole-update [cm whole-text]}))) (reg-fx ::parts-update (fn [] (re-frame/dispatch [::fixed-items-update-cms]))) (reg-event-fx ::transact-whole-form (fn [{:keys [db]} [_ whole-form-text]] (let [updates (text->spec-data whole-form-text)] {:db (merge db updates) ::parts-update updates}))) (reg-fx ::view-update (fn [[cm whole-text]] (let [tx (->> (zprint-file-str whole-text ::view-update) (replacement-tx cm))] (update-cm cm tx) (re-frame/dispatch [::fixed-items-update-cms])))) (defn parts-update! [{:keys [arity-data] :as db} source-cm-key] ;(fixed-items-update-cms! db source-cm-key) ( arity - update - cms ! db source - cm - key ( first arity - data ) ) ( attrs - update - cms ! db source - cm - key ) ) #_(reg-event-db ::set-form (fn [db [_ var-id]] (when-let [cm (get-in db [:defn.form.cm :cm])] (let [{:keys [ref-conformed ref-name]} (db var-id) visibility {:visible-form-id var-id :the-defn-form ref-name} db' (merge db visibility (conformed->spec-data ref-conformed))] (some->> db' :defn.text (common/format-tx cm) (common/update-cm! cm)) (tap> [::set-form :var-data ref-name]) (when (:defn.conformed db') (parts-update! db' :defn.form.cm)) db')))) (reg-event-db ::set-form (fn [db [_ var-id]] (when-let [cm (get-in db [:def.form.cm :cm])] (let [var-data (get-var-data (:current-ns db) var-id) visibility {:visible-form-id var-id} db' (merge db var-data visibility)] (some->> db' :def.text (common/format-tx cm) (common/update-cm! cm)) (tap> [::set-form :var-data var-data]) (when (:def.conformed db') (parts-update! db' :def.form.cm)) db')))) (reg-event-db ::form-tx (fn [db [_ cm-name tx]] ;; First update the transacting code-mirror (-> (get-in db [cm-name :cm]) (common/update-cm! tx)) (let [text (common/extract-tx-text tx) db' (merge db (text->spec-data text))] (when (:def.conformed db') (parts-update! db' cm-name)) db')))
null
https://raw.githubusercontent.com/repl-acement/repl-acement/2a1c5762ebe6225cd9c53e4ce0413046495ce0d8/repl-ui/replacement/forms/events/def.cljs
clojure
TODO: this should be from def.text that is built from unform and such a change should be signalled per active CM in short, this function is not needed (fixed-items-update-cms! db source-cm-key) First update the transacting code-mirror
(ns replacement.forms.events.def "A `def` form creates a global variable and can have an expression to set the initial value. This namespace is concerned with breaking the def forms down using `spec/conform` and putting them back together with `unform`. Editing by a human or a function may happen in between providing that it remains `unform`-able. This is relaxed for humans but not for functions. It is organized to match the life-cycle: ✓ event to set the whole view of a specific form-id ✓ --> fn to write the parts CMs to set the parts view of the whole ✓ event to transact changes (keystrokes) on the whole form ✓ --> fn to ripple out change to appropriate parts ✓ events to transact changes (keystrokes) on any of the form parts ✓ --> fn to reflect back the part change to whole" (:require [cljs.tools.reader.edn :as rdr] [clojure.core.async] [cljs.spec.alpha :as s] [re-frame.core :as re-frame :refer [reg-event-db reg-event-fx reg-fx]] [replacement.forms.events.common :as common] [replacement.protocol.data :as data-specs] [replacement.ui.helpers :refer [js->cljs]] [replacement.structure.wiring :as wiring] [zprint.core :refer [zprint-file-str]])) (defn extract-tx-text [^js tx] (->> (.-newDoc tx) (.toJSON) js->cljs (apply str))) (defn extract-cm-text [^js cm] (->> (-> cm .-state .-doc) (.toJSON) js->cljs (apply str))) (defn- update-cm ([cm tx] (update-cm cm tx nil)) ([cm tx event-args] (.update cm #js [tx]) (when event-args (re-frame/dispatch event-args)))) (defn- replacement-tx [cm text] (let [cm-state (-> cm .-state) doc-length (-> cm-state .-doc .-length)] (.update cm-state (clj->js {:changes {:from 0 :to doc-length :insert text}})))) (reg-fx ::fn-part-update (fn [[cm tx changed?]] (if changed? (update-cm cm tx [::set-part-in-whole]) (update-cm cm tx)))) (reg-event-fx ::part-edit (fn [{:keys [db]} [_ part-cm-name tx]] (let [cm (get-in db [part-cm-name :cm]) changed? (js->cljs (.-docChanged tx))] {:db db ::fn-part-update [cm tx changed?]}))) (reg-fx ::whole-edit (fn [[cm tx changed?]] (if changed? (update-cm cm tx [::transact-whole-form (extract-tx-text tx)]) (update-cm cm tx)))) (reg-event-fx ::def-whole-form-tx (fn [{:keys [db]} [_ cm-name tx]] (let [cm (get-in db [cm-name :cm]) changed? (js->cljs (.-docChanged tx))] {:db db ::whole-edit [cm tx changed?]}))) (reg-event-db ::set-cm+name (fn [db [_ cm comp-name]] (assoc db comp-name {:cm cm :name comp-name}))) (reg-fx ::update-cms (fn [changes] (doall (map (fn [{:keys [cm tx]}] (update-cm cm tx)) changes)))) (def parts [:def.name :def.docstring :def.init]) (def part->props-map (apply merge (map #(hash-map %1 %2) [:var-name :docstring :init-expr] parts))) (defn- def-data->properties [def-data] (reduce-kv (fn [data k v] (-> data (dissoc k) (assoc v (data k)))) def-data part->props-map)) (defn update-cm-states [db def-data cms cm-key] (if-let [cm (get-in db [cm-key :cm])] (let [def-property-name (wiring/cm-name->comp-name cm-key) new-text (pr-str (get def-data def-property-name)) tx (replacement-tx cm new-text)] (conj cms {:cm cm :tx tx})) cms)) (reg-event-fx ::fixed-items-update-cms (fn [{:keys [db]} [_]] (let [cm-keys (map wiring/comp-name->cm-name parts) def-data (def-data->properties db) cms-with-changes (reduce (partial update-cm-states db def-data) [] cm-keys)] {:db db ::update-cms cms-with-changes}))) (defn- text->spec-data [text] (let [data (rdr/read-string text) conformed (s/conform ::data-specs/def-form data) explain-data (and (s/invalid? conformed) (s/explain-data ::data-specs/def-form data)) unformed (or (s/invalid? conformed) (s/unform ::data-specs/def-form conformed))] {:def.text (-> unformed pr-str common/fix-width-format) :def.conformed conformed :def.explain-data explain-data :def.unformed unformed})) (defn conformed->spec-data [conformed] (let [unformed (when-not (s/invalid? conformed) (s/unform ::data-specs/def-form conformed))] {:def.text (-> unformed pr-str common/fix-width-format) :def.conformed conformed :def.explain-data (when (s/invalid? conformed) (s/explain-data ::data-specs/def-form conformed)) :def.unformed unformed})) (defn conformed-form->spec-data [{:keys [conformed]}] (let [unformed (when-not (s/invalid? conformed) (s/unform ::data-specs/form conformed))] {:text (-> unformed pr-str common/fix-width-format) :conformed conformed :explain-data (when (s/invalid? conformed) (s/explain-data ::data-specs/form conformed)) :unformed unformed})) (defn get-var-data [current-ns var-id] (let [form (get-in current-ns [:forms var-id])] {:def-data (conformed-form->spec-data form) :def-name (::data-specs/var-name form)})) (defn- cm-keys->text [db cm-keys] (->> (reduce (fn [text k] (->> (get-in db [k :cm]) (extract-cm-text) (conj text))) [] cm-keys) (interpose " ") (apply str))) (defn- common-parts-text [db] (->> (map wiring/comp-name->cm-name parts) (cm-keys->text db))) (reg-fx ::whole-update (fn [[cm whole-text]] (->> (zprint-file-str whole-text ::whole-update) (replacement-tx cm) (update-cm cm)))) (defn- whole-form-updated "Scan over all the active code mirrors that can provide updates and create the new form to reflect any updates" [db] (let [fixed-parts (common-parts-text db) form-text (apply str fixed-parts)] (str "(def " form-text ")"))) (reg-event-fx ::set-part-in-whole (fn [{:keys [db]} [_]] (let [cm (get-in db [:def.form.cm :cm]) whole-text (whole-form-updated db) updates (text->spec-data whole-text)] {:db (merge db updates) ::whole-update [cm whole-text]}))) (reg-fx ::parts-update (fn [] (re-frame/dispatch [::fixed-items-update-cms]))) (reg-event-fx ::transact-whole-form (fn [{:keys [db]} [_ whole-form-text]] (let [updates (text->spec-data whole-form-text)] {:db (merge db updates) ::parts-update updates}))) (reg-fx ::view-update (fn [[cm whole-text]] (let [tx (->> (zprint-file-str whole-text ::view-update) (replacement-tx cm))] (update-cm cm tx) (re-frame/dispatch [::fixed-items-update-cms])))) (defn parts-update! [{:keys [arity-data] :as db} source-cm-key] ( arity - update - cms ! db source - cm - key ( first arity - data ) ) ( attrs - update - cms ! db source - cm - key ) ) #_(reg-event-db ::set-form (fn [db [_ var-id]] (when-let [cm (get-in db [:defn.form.cm :cm])] (let [{:keys [ref-conformed ref-name]} (db var-id) visibility {:visible-form-id var-id :the-defn-form ref-name} db' (merge db visibility (conformed->spec-data ref-conformed))] (some->> db' :defn.text (common/format-tx cm) (common/update-cm! cm)) (tap> [::set-form :var-data ref-name]) (when (:defn.conformed db') (parts-update! db' :defn.form.cm)) db')))) (reg-event-db ::set-form (fn [db [_ var-id]] (when-let [cm (get-in db [:def.form.cm :cm])] (let [var-data (get-var-data (:current-ns db) var-id) visibility {:visible-form-id var-id} db' (merge db var-data visibility)] (some->> db' :def.text (common/format-tx cm) (common/update-cm! cm)) (tap> [::set-form :var-data var-data]) (when (:def.conformed db') (parts-update! db' :def.form.cm)) db')))) (reg-event-db ::form-tx (fn [db [_ cm-name tx]] (-> (get-in db [cm-name :cm]) (common/update-cm! tx)) (let [text (common/extract-tx-text tx) db' (merge db (text->spec-data text))] (when (:def.conformed db') (parts-update! db' cm-name)) db')))
7756b5790900dfcdc048228137d4effadce99528b3b5e80901f47ef44322c379
gstew5/snarkl
Stack.hs
# LANGUAGE RebindableSyntax , # , DataKinds #-} module Stack where import Prelude hiding ( (>>) , (>>=) , (+) , (-) , (*) , (/) , (&&) , return , fromRational , negate ) import Data.Typeable import Compile import SyntaxMonad import Syntax import TExpr import Toplevel import List type TStack a = TList a type Stack a = TExp (TStack a) Rational empty_stack :: Typeable a => Comp (TStack a) empty_stack = nil push_stack :: Typeable a => TExp a Rational -> Stack a -> Comp (TStack a) push_stack p q = cons p q pop_stack :: (Derive a, Zippable a, Typeable a) => Stack a -> Comp (TStack a) pop_stack f = tail_list f top_stack :: (Derive a, Zippable a, Typeable a) => TExp a Rational-> Stack a -> Comp a top_stack def e = head_list def e is_empty_stack :: Typeable a => Stack a -> Comp 'TBool is_empty_stack s = case_list s (return true) (\_ _ -> return false) -Test Examples--- stack1 = do { ; tl <- empty_stack ; tl' <- push_stack 15.0 tl ; push_stack 99.0 tl' } stack2 = do { ; tl <- empty_stack ; tl' <- push_stack 1.0 tl ; tl'' <- push_stack 12.0 tl' ; push_stack 89.0 tl'' } --top_stack on empty stack test_top1 = do { ; s1 <- stack1 ; s2 <- pop_stack s1 ; s3 <- pop_stack s2 ; top_stack 1.0 s3 } --top_stack on non-empty stack test_top2 = do { ; s1 <- stack1 ; top_stack 1.0 s1 } --is_empty_stack on an empty stack test_empty_stack1 = do { ; s1 <- stack1 ; s2 <- pop_stack s1 ; s3 <- pop_stack s2 ; is_empty_stack s3 } --is_empty_stack on non-empty stack test_empty_stack2 = do { ; s1 <- stack1 ; is_empty_stack s1 }
null
https://raw.githubusercontent.com/gstew5/snarkl/d6ce72b13e370d2965bb226f28a1135269e7c198/src/examples/Stack.hs
haskell
- top_stack on empty stack top_stack on non-empty stack is_empty_stack on an empty stack is_empty_stack on non-empty stack
# LANGUAGE RebindableSyntax , # , DataKinds #-} module Stack where import Prelude hiding ( (>>) , (>>=) , (+) , (-) , (*) , (/) , (&&) , return , fromRational , negate ) import Data.Typeable import Compile import SyntaxMonad import Syntax import TExpr import Toplevel import List type TStack a = TList a type Stack a = TExp (TStack a) Rational empty_stack :: Typeable a => Comp (TStack a) empty_stack = nil push_stack :: Typeable a => TExp a Rational -> Stack a -> Comp (TStack a) push_stack p q = cons p q pop_stack :: (Derive a, Zippable a, Typeable a) => Stack a -> Comp (TStack a) pop_stack f = tail_list f top_stack :: (Derive a, Zippable a, Typeable a) => TExp a Rational-> Stack a -> Comp a top_stack def e = head_list def e is_empty_stack :: Typeable a => Stack a -> Comp 'TBool is_empty_stack s = case_list s (return true) (\_ _ -> return false) stack1 = do { ; tl <- empty_stack ; tl' <- push_stack 15.0 tl ; push_stack 99.0 tl' } stack2 = do { ; tl <- empty_stack ; tl' <- push_stack 1.0 tl ; tl'' <- push_stack 12.0 tl' ; push_stack 89.0 tl'' } test_top1 = do { ; s1 <- stack1 ; s2 <- pop_stack s1 ; s3 <- pop_stack s2 ; top_stack 1.0 s3 } test_top2 = do { ; s1 <- stack1 ; top_stack 1.0 s1 } test_empty_stack1 = do { ; s1 <- stack1 ; s2 <- pop_stack s1 ; s3 <- pop_stack s2 ; is_empty_stack s3 } test_empty_stack2 = do { ; s1 <- stack1 ; is_empty_stack s1 }
38e8b5a097168458253f8f59982819036e3396d9ed5cc9ec08f266d0be3e466c
esl/ejabberd_tests
metrics_roster_SUITE.erl
%%============================================================================== Copyright 2013 Erlang Solutions Ltd. %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%============================================================================== -module(metrics_roster_SUITE). -compile(export_all). -include_lib("escalus/include/escalus.hrl"). -include_lib("common_test/include/ct.hrl"). -import(metrics_helper, [assert_counter/2, get_counter_value/1]). %%-------------------------------------------------------------------- %% Suite configuration %%-------------------------------------------------------------------- all() -> [{group, roster}, {group, subscriptions} ]. groups() -> [{roster, [sequence], roster_tests()}, {subscriptions, [sequence], subscription_tests()} ]. suite() -> [{required, ejabberd_node} | escalus:suite()]. roster_tests() -> [get_roster, add_contact, roster_push]. %% WARNING: Side-effects & test interference %% subscribe affects subsequent tests %% by sending a directed presence before the roster push in add_sample_contact/2 %% TODO: investigate, fix. subscription_tests() -> [unsubscribe, decline_subscription, subscribe]. %%-------------------------------------------------------------------- Init & teardown %%-------------------------------------------------------------------- init_per_suite(Config) -> MongooseMetrics = [{[data, xmpp, received, xml_stanza_size], changed}, {[data, xmpp, sent, xml_stanza_size], changed}, {fun roster_odbc_precondition/0, [data, odbc, regular], [{recv_oct, '>'}, {send_oct, '>'}]}, {[backends, mod_roster, get_subscription_lists], changed} ], [{mongoose_metrics, MongooseMetrics} | escalus:init_per_suite(Config)]. end_per_suite(Config) -> escalus:end_per_suite(Config). init_per_group(_GroupName, Config) -> escalus:create_users(Config, {by_name, [alice, bob]}). end_per_group(_GroupName, Config) -> escalus:delete_users(Config, {by_name, [alice, bob]}). init_per_testcase(CaseName, Config) -> escalus:init_per_testcase(CaseName, Config). end_per_testcase(add_contact, Config) -> [{_, UserSpec} | _] = escalus_config:get_config(escalus_users, Config), remove_roster(Config, UserSpec), escalus:end_per_testcase(add_contact, Config); end_per_testcase(roster_push, Config) -> [{_, UserSpec} | _] = escalus_config:get_config(escalus_users, Config), remove_roster(Config, UserSpec), escalus:end_per_testcase(roster_push, Config); end_per_testcase(subscribe, Config) -> end_rosters_remove(Config); end_per_testcase(decline_subscription, Config) -> end_rosters_remove(Config); end_per_testcase(unsubscribe, Config) -> end_rosters_remove(Config); end_per_testcase(CaseName, Config) -> escalus:end_per_testcase(CaseName, Config). end_rosters_remove(Config) -> [{_, UserSpec1}, {_, UserSpec2} | _] = escalus_config:get_config(escalus_users, Config), remove_roster(Config, UserSpec1), remove_roster(Config, UserSpec2), escalus:end_per_testcase(subscription, Config). %%-------------------------------------------------------------------- %% Tests %%-------------------------------------------------------------------- get_roster(ConfigIn) -> Metrics = [{['_', modRosterGets], 1}, {[backends, mod_roster, get_roster], changed} ], Config = mongoose_metrics(ConfigIn, Metrics), escalus:story(Config, [1, 1], fun(Alice,_Bob) -> escalus_client:send(Alice, escalus_stanza:roster_get()), escalus_client:wait_for_stanza(Alice) end). add_contact(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modRosterSets], 1}]), escalus:story(Config, [1, 1], fun(Alice, Bob) -> %% add contact escalus_client:send(Alice, escalus_stanza:roster_add_contact(Bob, [<<"friends">>], <<"Bobby">>)), Received = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(Received)), escalus_client:wait_for_stanza(Alice) end). roster_push(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modRosterSets], 1}, {['_', modRosterPush], 2}]), escalus:story(Config, [2, 1], fun(Alice1, Alice2, Bob) -> %% add contact escalus_client:send(Alice1, escalus_stanza:roster_add_contact(Bob, [<<"friends">>], <<"Bobby">>)), Received = escalus_client:wait_for_stanza(Alice1), escalus_client:send(Alice1, escalus_stanza:iq_result(Received)), escalus_client:wait_for_stanza(Alice1), Received2 = escalus_client:wait_for_stanza(Alice2), escalus_client:send(Alice2, escalus_stanza:iq_result(Received2)) end). subscribe(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modPresenceSubscriptions], 1}]), escalus:story(Config, [1, 1], fun(Alice,Bob) -> %% add contact add_sample_contact(Alice, Bob), %% subscribe escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"subscribe">>)), PushReq = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReq)), receives subscription reqest escalus_client:wait_for_stanza(Bob), adds new contact to his roster escalus_client:send(Bob, escalus_stanza:roster_add_contact(Alice, [<<"enemies">>], <<"Alice">>)), PushReqB = escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:iq_result(PushReqB)), escalus_client:wait_for_stanza(Bob), sends subscribed presence escalus_client:send(Bob, escalus_stanza:presence_direct(alice, <<"subscribed">>)), receives subscribed escalus_client:wait_for_stanzas(Alice, 3), receives roster push escalus_client:wait_for_stanza(Bob) end). decline_subscription(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modPresenceUnsubscriptions], 1}]), escalus:story(Config, [1, 1], fun(Alice,Bob) -> %% add contact add_sample_contact(Alice, Bob), %% subscribe escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"subscribe">>)), PushReq = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReq)), receives subscription reqest escalus_client:wait_for_stanza(Bob), refuses subscription escalus_client:send(Bob, escalus_stanza:presence_direct(alice, <<"unsubscribed">>)), receives subscribed escalus_client:wait_for_stanzas(Alice, 2) end). unsubscribe(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modPresenceUnsubscriptions], 1}]), escalus:story(Config, [1, 1], fun(Alice,Bob) -> %% add contact add_sample_contact(Alice, Bob), %% subscribe escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"subscribe">>)), PushReq = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReq)), receives subscription reqest escalus_client:wait_for_stanza(Bob), adds new contact to his roster escalus_client:send(Bob, escalus_stanza:roster_add_contact(Alice, [<<"enemies">>], <<"Alice">>)), PushReqB = escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:iq_result(PushReqB)), escalus_client:wait_for_stanza(Bob), sends subscribed presence escalus_client:send(Bob, escalus_stanza:presence_direct(alice, <<"subscribed">>)), receives subscribed escalus_client:wait_for_stanzas(Alice, 2), escalus_client:wait_for_stanza(Alice), receives roster push PushReqB1 = escalus_client:wait_for_stanza(Bob), escalus_assert:is_roster_set(PushReqB1), sends unsubscribe escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"unsubscribe">>)), PushReqA2 = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReqA2)), receives unsubscribe escalus_client:wait_for_stanzas(Bob, 2) end). %%----------------------------------------------------------------- %% Helpers %%----------------------------------------------------------------- add_sample_contact(Alice, Bob) -> add_sample_contact(Alice, Bob, [<<"friends">>], <<"generic :p name">>). add_sample_contact(Alice, Bob, Groups, Name) -> escalus_client:send(Alice, escalus_stanza:roster_add_contact(Bob, Groups, Name)), RosterPush = escalus_client:wait_for_stanza(Alice), escalus:assert(is_roster_set, RosterPush), escalus_client:send(Alice, escalus_stanza:iq_result(RosterPush)), escalus_client:wait_for_stanza(Alice). remove_roster(Config, UserSpec) -> [Username, Server, _Pass] = escalus_users:get_usp(Config, UserSpec), escalus_ejabberd:rpc(mod_roster_odbc, remove_user, [Username, Server]), escalus_ejabberd:rpc(mod_roster, remove_user, [Username, Server]). mongoose_metrics(ConfigIn, Metrics) -> Predefined = proplists:get_value(mongoose_metrics, ConfigIn, []), MongooseMetrics = Predefined ++ Metrics, [{mongoose_metrics, MongooseMetrics} | ConfigIn]. roster_odbc_precondition() -> mod_roster_odbc == escalus_ejabberd:rpc(mod_roster_backend, backend, []).
null
https://raw.githubusercontent.com/esl/ejabberd_tests/913fb0a5a8c1ab753eb35c1e1b491e8572633b54/tests/metrics_roster_SUITE.erl
erlang
============================================================================== you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================== -------------------------------------------------------------------- Suite configuration -------------------------------------------------------------------- WARNING: Side-effects & test interference subscribe affects subsequent tests by sending a directed presence before the roster push TODO: investigate, fix. -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Tests -------------------------------------------------------------------- add contact add contact add contact subscribe add contact subscribe add contact subscribe ----------------------------------------------------------------- Helpers -----------------------------------------------------------------
Copyright 2013 Erlang Solutions Ltd. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(metrics_roster_SUITE). -compile(export_all). -include_lib("escalus/include/escalus.hrl"). -include_lib("common_test/include/ct.hrl"). -import(metrics_helper, [assert_counter/2, get_counter_value/1]). all() -> [{group, roster}, {group, subscriptions} ]. groups() -> [{roster, [sequence], roster_tests()}, {subscriptions, [sequence], subscription_tests()} ]. suite() -> [{required, ejabberd_node} | escalus:suite()]. roster_tests() -> [get_roster, add_contact, roster_push]. in add_sample_contact/2 subscription_tests() -> [unsubscribe, decline_subscription, subscribe]. Init & teardown init_per_suite(Config) -> MongooseMetrics = [{[data, xmpp, received, xml_stanza_size], changed}, {[data, xmpp, sent, xml_stanza_size], changed}, {fun roster_odbc_precondition/0, [data, odbc, regular], [{recv_oct, '>'}, {send_oct, '>'}]}, {[backends, mod_roster, get_subscription_lists], changed} ], [{mongoose_metrics, MongooseMetrics} | escalus:init_per_suite(Config)]. end_per_suite(Config) -> escalus:end_per_suite(Config). init_per_group(_GroupName, Config) -> escalus:create_users(Config, {by_name, [alice, bob]}). end_per_group(_GroupName, Config) -> escalus:delete_users(Config, {by_name, [alice, bob]}). init_per_testcase(CaseName, Config) -> escalus:init_per_testcase(CaseName, Config). end_per_testcase(add_contact, Config) -> [{_, UserSpec} | _] = escalus_config:get_config(escalus_users, Config), remove_roster(Config, UserSpec), escalus:end_per_testcase(add_contact, Config); end_per_testcase(roster_push, Config) -> [{_, UserSpec} | _] = escalus_config:get_config(escalus_users, Config), remove_roster(Config, UserSpec), escalus:end_per_testcase(roster_push, Config); end_per_testcase(subscribe, Config) -> end_rosters_remove(Config); end_per_testcase(decline_subscription, Config) -> end_rosters_remove(Config); end_per_testcase(unsubscribe, Config) -> end_rosters_remove(Config); end_per_testcase(CaseName, Config) -> escalus:end_per_testcase(CaseName, Config). end_rosters_remove(Config) -> [{_, UserSpec1}, {_, UserSpec2} | _] = escalus_config:get_config(escalus_users, Config), remove_roster(Config, UserSpec1), remove_roster(Config, UserSpec2), escalus:end_per_testcase(subscription, Config). get_roster(ConfigIn) -> Metrics = [{['_', modRosterGets], 1}, {[backends, mod_roster, get_roster], changed} ], Config = mongoose_metrics(ConfigIn, Metrics), escalus:story(Config, [1, 1], fun(Alice,_Bob) -> escalus_client:send(Alice, escalus_stanza:roster_get()), escalus_client:wait_for_stanza(Alice) end). add_contact(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modRosterSets], 1}]), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:send(Alice, escalus_stanza:roster_add_contact(Bob, [<<"friends">>], <<"Bobby">>)), Received = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(Received)), escalus_client:wait_for_stanza(Alice) end). roster_push(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modRosterSets], 1}, {['_', modRosterPush], 2}]), escalus:story(Config, [2, 1], fun(Alice1, Alice2, Bob) -> escalus_client:send(Alice1, escalus_stanza:roster_add_contact(Bob, [<<"friends">>], <<"Bobby">>)), Received = escalus_client:wait_for_stanza(Alice1), escalus_client:send(Alice1, escalus_stanza:iq_result(Received)), escalus_client:wait_for_stanza(Alice1), Received2 = escalus_client:wait_for_stanza(Alice2), escalus_client:send(Alice2, escalus_stanza:iq_result(Received2)) end). subscribe(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modPresenceSubscriptions], 1}]), escalus:story(Config, [1, 1], fun(Alice,Bob) -> add_sample_contact(Alice, Bob), escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"subscribe">>)), PushReq = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReq)), receives subscription reqest escalus_client:wait_for_stanza(Bob), adds new contact to his roster escalus_client:send(Bob, escalus_stanza:roster_add_contact(Alice, [<<"enemies">>], <<"Alice">>)), PushReqB = escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:iq_result(PushReqB)), escalus_client:wait_for_stanza(Bob), sends subscribed presence escalus_client:send(Bob, escalus_stanza:presence_direct(alice, <<"subscribed">>)), receives subscribed escalus_client:wait_for_stanzas(Alice, 3), receives roster push escalus_client:wait_for_stanza(Bob) end). decline_subscription(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modPresenceUnsubscriptions], 1}]), escalus:story(Config, [1, 1], fun(Alice,Bob) -> add_sample_contact(Alice, Bob), escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"subscribe">>)), PushReq = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReq)), receives subscription reqest escalus_client:wait_for_stanza(Bob), refuses subscription escalus_client:send(Bob, escalus_stanza:presence_direct(alice, <<"unsubscribed">>)), receives subscribed escalus_client:wait_for_stanzas(Alice, 2) end). unsubscribe(ConfigIn) -> Config = mongoose_metrics(ConfigIn, [{['_', modPresenceUnsubscriptions], 1}]), escalus:story(Config, [1, 1], fun(Alice,Bob) -> add_sample_contact(Alice, Bob), escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"subscribe">>)), PushReq = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReq)), receives subscription reqest escalus_client:wait_for_stanza(Bob), adds new contact to his roster escalus_client:send(Bob, escalus_stanza:roster_add_contact(Alice, [<<"enemies">>], <<"Alice">>)), PushReqB = escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:iq_result(PushReqB)), escalus_client:wait_for_stanza(Bob), sends subscribed presence escalus_client:send(Bob, escalus_stanza:presence_direct(alice, <<"subscribed">>)), receives subscribed escalus_client:wait_for_stanzas(Alice, 2), escalus_client:wait_for_stanza(Alice), receives roster push PushReqB1 = escalus_client:wait_for_stanza(Bob), escalus_assert:is_roster_set(PushReqB1), sends unsubscribe escalus_client:send(Alice, escalus_stanza:presence_direct(bob, <<"unsubscribe">>)), PushReqA2 = escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:iq_result(PushReqA2)), receives unsubscribe escalus_client:wait_for_stanzas(Bob, 2) end). add_sample_contact(Alice, Bob) -> add_sample_contact(Alice, Bob, [<<"friends">>], <<"generic :p name">>). add_sample_contact(Alice, Bob, Groups, Name) -> escalus_client:send(Alice, escalus_stanza:roster_add_contact(Bob, Groups, Name)), RosterPush = escalus_client:wait_for_stanza(Alice), escalus:assert(is_roster_set, RosterPush), escalus_client:send(Alice, escalus_stanza:iq_result(RosterPush)), escalus_client:wait_for_stanza(Alice). remove_roster(Config, UserSpec) -> [Username, Server, _Pass] = escalus_users:get_usp(Config, UserSpec), escalus_ejabberd:rpc(mod_roster_odbc, remove_user, [Username, Server]), escalus_ejabberd:rpc(mod_roster, remove_user, [Username, Server]). mongoose_metrics(ConfigIn, Metrics) -> Predefined = proplists:get_value(mongoose_metrics, ConfigIn, []), MongooseMetrics = Predefined ++ Metrics, [{mongoose_metrics, MongooseMetrics} | ConfigIn]. roster_odbc_precondition() -> mod_roster_odbc == escalus_ejabberd:rpc(mod_roster_backend, backend, []).
99d2a3b429291baabb889bb0c316e21612ccb605deb0f6b383df6f0e5a7bb4fa
rabbitmq/rabbitmq-erlang-client
uri_parser.erl
This file is a copy of http_uri.erl from the R13B-1 Erlang / OTP %% distribution with several modifications. All modifications are Copyright ( c ) 2009 - 2020 VMware , Inc. or its affiliates . ` ` The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved via the world wide web at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% The Initial Developer of the Original Code is Ericsson Utvecklings AB . Portions created by Ericsson are Copyright 1999 , %% AB. All Rights Reserved.'' %% See -module(uri_parser). -export([parse/2]). %%%========================================================================= %%% API %%%========================================================================= Returns a key list of elements extracted from the URI . Note that %% only 'scheme' is guaranteed to exist. Key-Value pairs from the %% Defaults list will be used absence of a non-empty value extracted from the URI . The values extracted are strings , except for ' port ' %% which is an integer, 'userinfo' which is a list of strings (split %% on $:), and 'query' which is a list of strings where no $= char %% found, or a {key,value} pair where a $= char is found (initial split on $ & and subsequent optional split on $ =) . Possible keys %% are: 'scheme', 'userinfo', 'host', 'port', 'path', 'query', %% 'fragment'. -spec parse(AbsURI, Defaults :: list()) -> [{atom(), string()}] | {error, no_scheme | {malformed_uri, AbsURI, any()}} when AbsURI :: string() | binary(). parse(AbsURI, Defaults) -> AbsUriString = rabbit_data_coercion:to_list(AbsURI), case parse_scheme(AbsUriString) of {error, Reason} -> {error, Reason}; {Scheme, Rest} -> case (catch parse_uri_rest(Rest, true)) of [_|_] = List -> merge_keylists([{scheme, Scheme} | List], Defaults); E -> {error, {malformed_uri, AbsURI, E}} end end. %%%======================================================================== Internal functions %%%======================================================================== parse_scheme(AbsURI) -> split_uri(AbsURI, ":", {error, no_scheme}). parse_uri_rest("//" ++ URIPart, true) -> %% we have an authority {Authority, PathQueryFrag} = split_uri(URIPart, "/|\\?|#", {URIPart, ""}, 1, 0), AuthorityParts = parse_authority(Authority), parse_uri_rest(PathQueryFrag, false) ++ AuthorityParts; parse_uri_rest(PathQueryFrag, _Bool) -> %% no authority, just a path and maybe query {PathQuery, Frag} = split_uri(PathQueryFrag, "#", {PathQueryFrag, ""}), {Path, QueryString} = split_uri(PathQuery, "\\?", {PathQuery, ""}), QueryPropList = split_query(QueryString), [{path, Path}, {'query', QueryPropList}, {fragment, Frag}]. parse_authority(Authority) -> {UserInfo, HostPort} = split_uri(Authority, "@", {"", Authority}), UserInfoSplit = case re:split(UserInfo, ":", [{return, list}]) of [""] -> []; UIS -> UIS end, [{userinfo, UserInfoSplit} | parse_host_port(HostPort)]. parse_host_port("[" ++ HostPort) -> %ipv6 {Host, ColonPort} = split_uri(HostPort, "\\]", {HostPort, ""}), [{host, Host} | case split_uri(ColonPort, ":", not_found, 0, 1) of not_found -> case ColonPort of [] -> []; _ -> throw({invalid_port, ColonPort}) end; {_, Port} -> [{port, list_to_integer(Port)}] end]; parse_host_port(HostPort) -> {Host, Port} = split_uri(HostPort, ":", {HostPort, not_found}), [{host, Host} | case Port of not_found -> []; _ -> [{port, list_to_integer(Port)}] end]. split_query(Query) -> case re:split(Query, "&", [{return, list}]) of [""] -> []; QParams -> [split_uri(Param, "=", Param) || Param <- QParams] end. split_uri(UriPart, SplitChar, NoMatchResult) -> split_uri(UriPart, SplitChar, NoMatchResult, 1, 1). split_uri(UriPart, SplitChar, NoMatchResult, SkipLeft, SkipRight) -> case re:run(UriPart, SplitChar) of {match, [{Match, _}]} -> {string:substr(UriPart, 1, Match + 1 - SkipLeft), string:substr(UriPart, Match + 1 + SkipRight, length(UriPart))}; nomatch -> NoMatchResult end. merge_keylists(A, B) -> {AEmpty, ANonEmpty} = lists:partition(fun ({_Key, V}) -> V =:= [] end, A), [AEmptyS, ANonEmptyS, BS] = [lists:ukeysort(1, X) || X <- [AEmpty, ANonEmpty, B]], lists:ukeymerge(1, lists:ukeymerge(1, ANonEmptyS, BS), AEmptyS).
null
https://raw.githubusercontent.com/rabbitmq/rabbitmq-erlang-client/2022e01c515d93ed1883e9e9e987be2e58fe15c9/src/uri_parser.erl
erlang
distribution with several modifications. compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved via the world wide web at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. AB. All Rights Reserved.'' See ========================================================================= API ========================================================================= only 'scheme' is guaranteed to exist. Key-Value pairs from the Defaults list will be used absence of a non-empty value extracted which is an integer, 'userinfo' which is a list of strings (split on $:), and 'query' which is a list of strings where no $= char found, or a {key,value} pair where a $= char is found (initial are: 'scheme', 'userinfo', 'host', 'port', 'path', 'query', 'fragment'. ======================================================================== ======================================================================== we have an authority no authority, just a path and maybe query ipv6
This file is a copy of http_uri.erl from the R13B-1 Erlang / OTP All modifications are Copyright ( c ) 2009 - 2020 VMware , Inc. or its affiliates . ` ` The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " The Initial Developer of the Original Code is Ericsson Utvecklings AB . Portions created by Ericsson are Copyright 1999 , -module(uri_parser). -export([parse/2]). Returns a key list of elements extracted from the URI . Note that from the URI . The values extracted are strings , except for ' port ' split on $ & and subsequent optional split on $ =) . Possible keys -spec parse(AbsURI, Defaults :: list()) -> [{atom(), string()}] | {error, no_scheme | {malformed_uri, AbsURI, any()}} when AbsURI :: string() | binary(). parse(AbsURI, Defaults) -> AbsUriString = rabbit_data_coercion:to_list(AbsURI), case parse_scheme(AbsUriString) of {error, Reason} -> {error, Reason}; {Scheme, Rest} -> case (catch parse_uri_rest(Rest, true)) of [_|_] = List -> merge_keylists([{scheme, Scheme} | List], Defaults); E -> {error, {malformed_uri, AbsURI, E}} end end. Internal functions parse_scheme(AbsURI) -> split_uri(AbsURI, ":", {error, no_scheme}). parse_uri_rest("//" ++ URIPart, true) -> {Authority, PathQueryFrag} = split_uri(URIPart, "/|\\?|#", {URIPart, ""}, 1, 0), AuthorityParts = parse_authority(Authority), parse_uri_rest(PathQueryFrag, false) ++ AuthorityParts; parse_uri_rest(PathQueryFrag, _Bool) -> {PathQuery, Frag} = split_uri(PathQueryFrag, "#", {PathQueryFrag, ""}), {Path, QueryString} = split_uri(PathQuery, "\\?", {PathQuery, ""}), QueryPropList = split_query(QueryString), [{path, Path}, {'query', QueryPropList}, {fragment, Frag}]. parse_authority(Authority) -> {UserInfo, HostPort} = split_uri(Authority, "@", {"", Authority}), UserInfoSplit = case re:split(UserInfo, ":", [{return, list}]) of [""] -> []; UIS -> UIS end, [{userinfo, UserInfoSplit} | parse_host_port(HostPort)]. {Host, ColonPort} = split_uri(HostPort, "\\]", {HostPort, ""}), [{host, Host} | case split_uri(ColonPort, ":", not_found, 0, 1) of not_found -> case ColonPort of [] -> []; _ -> throw({invalid_port, ColonPort}) end; {_, Port} -> [{port, list_to_integer(Port)}] end]; parse_host_port(HostPort) -> {Host, Port} = split_uri(HostPort, ":", {HostPort, not_found}), [{host, Host} | case Port of not_found -> []; _ -> [{port, list_to_integer(Port)}] end]. split_query(Query) -> case re:split(Query, "&", [{return, list}]) of [""] -> []; QParams -> [split_uri(Param, "=", Param) || Param <- QParams] end. split_uri(UriPart, SplitChar, NoMatchResult) -> split_uri(UriPart, SplitChar, NoMatchResult, 1, 1). split_uri(UriPart, SplitChar, NoMatchResult, SkipLeft, SkipRight) -> case re:run(UriPart, SplitChar) of {match, [{Match, _}]} -> {string:substr(UriPart, 1, Match + 1 - SkipLeft), string:substr(UriPart, Match + 1 + SkipRight, length(UriPart))}; nomatch -> NoMatchResult end. merge_keylists(A, B) -> {AEmpty, ANonEmpty} = lists:partition(fun ({_Key, V}) -> V =:= [] end, A), [AEmptyS, ANonEmptyS, BS] = [lists:ukeysort(1, X) || X <- [AEmpty, ANonEmpty, B]], lists:ukeymerge(1, lists:ukeymerge(1, ANonEmptyS, BS), AEmptyS).
f00f38fa60c4e34fde1408e8a83f89e2d5e8595bda314ee14563338c4e18f806
arcfide/chez-srfi
vectors-impl.scm
SRFI 43 : Vector library -*- Scheme -*- ;;; $ Id$ ;;; wrote this code ; he places it in the public domain . [ wdc ] made some corrections , also in the public domain . modified this code for SRFI 133 ; his changes are also in ;;; the public domain. However, in jurisdictions where it is not possible ;;; to dedicate something to the public domain, the entire implementation is made available under the same license as SRFI 133 . ;;; -------------------- ;;; Exported procedure index ;;; ;;; * Constructors ;;; vector-unfold vector-unfold-right ;;; vector-copy vector-reverse-copy ;;; vector-append vector-concatenate ;;; vector-append-subvectors ;;; ;;; * Predicates ;;; vector-empty? ;;; vector= ;;; ;;; * Iteration ;;; vector-fold vector-fold-right ;;; vector-map vector-map! ;;; vector-for-each ;;; vector-count vector-cumulate ;;; ;;; * Searching ;;; vector-index vector-skip ;;; vector-index-right vector-skip-right ;;; vector-binary-search ;;; vector-any vector-every ;;; vector-partition ;;; ;;; * Mutators ;;; vector-swap! ;;; vector-fill! ;;; vector-reverse! ;;; vector-copy! vector-reverse-copy! ;;; vector-reverse! ;;; vector-unfold! vector-unfold-right! ;;; ;;; * Conversion ;;; vector->list reverse-vector->list ;;; list->vector reverse-list->vector ;;; vector->string string->vector ;;; -------------------- ;;; Commentary on efficiency of the code ;;; This code is somewhat tuned for efficiency. There are several ;;; internal routines that can be optimized greatly to greatly improve ;;; the performance of much of the library. These internal procedures ;;; are already carefully tuned for performance, and lambda-lifted by ;;; hand. Some other routines are lambda-lifted by hand, but only the loops are lambda - lifted , and only if some routine has two possible ;;; loops -- a fast path and an n-ary case --, whereas _all_ of the ;;; internal routines' loops are lambda-lifted so as to never cons a closure in their body ( VECTOR - PARSE - START+END does n't have a loop ) , ;;; even in Scheme systems that perform no loop optimization (which is ;;; most of them, unfortunately). ;;; ;;; Fast paths are provided for common cases in most of the loops in ;;; this library. ;;; ;;; All calls to primitive vector operations are protected by a prior ;;; type check; they can be safely converted to use unsafe equivalents ;;; of the operations, if available. Ideally, the compiler should be able to determine this , but the state of Scheme compilers today is ;;; not a happy one. ;;; ;;; Efficiency of the actual algorithms is a rather mundane point to ;;; mention; vector operations are rarely beyond being straightforward. ;;; -------------------- Utilities ;;; SRFI 8, too trivial to put in the dependencies list. (define-syntax receive (syntax-rules () ((receive ?formals ?producer ?body1 ?body2 ...) (call-with-values (lambda () ?producer) (lambda ?formals ?body1 ?body2 ...))))) Not the best LET*-OPTIONALS , but not the worst , either . ;;; if it's available to you. (define-syntax let*-optionals (syntax-rules () ((let*-optionals (?x ...) ((?var ?default) ...) ?body1 ?body2 ...) (let ((args (?x ...))) (let*-optionals args ((?var ?default) ...) ?body1 ?body2 ...))) ((let*-optionals ?args ((?var ?default) ...) ?body1 ?body2 ...) (let*-optionals:aux ?args ?args ((?var ?default) ...) ?body1 ?body2 ...)))) (define-syntax let*-optionals:aux (syntax-rules () ((aux ?orig-args-var ?args-var () ?body1 ?body2 ...) (if (null? ?args-var) (let () ?body1 ?body2 ...) (error "too many arguments" (length ?orig-args-var) ?orig-args-var))) ((aux ?orig-args-var ?args-var ((?var ?default) ?more ...) ?body1 ?body2 ...) (if (null? ?args-var) (let* ((?var ?default) ?more ...) ?body1 ?body2 ...) (let ((?var (car ?args-var)) (new-args (cdr ?args-var))) (let*-optionals:aux ?orig-args-var new-args (?more ...) ?body1 ?body2 ...)))))) (define (nonneg-int? x) (and (integer? x) (not (negative? x)))) (define (between? x y z) (and (< x y) (<= y z))) (define (unspecified-value) (if #f #f)) ;++ This should be implemented more efficiently. It shouldn't cons a ;++ closure, and the cons cells used in the loops when using this could ;++ be reused. (define (vectors-ref vectors i) (map (lambda (v) (vector-ref v i)) vectors)) ;;; -------------------- ;;; Error checking ;;; Error signalling (not checking) is done in a way that tries to be ;;; as helpful to the person who gets the debugging prompt as possible. ;;; That said, error _checking_ tries to be as unredundant as possible. ;;; I don't use any sort of general condition mechanism; I use simply SRFI 23 's ERROR , even in cases where it might be better to use such ;;; a general condition mechanism. Fix that when porting this to a ;;; Scheme implementation that has its own condition system. ;;; In argument checks, upon receiving an invalid argument, the checker ;;; procedure recursively calls itself, but in one of the arguments to ;;; itself is a call to ERROR; this mechanism is used in the hopes that ;;; the user may be thrown into a debugger prompt, proceed with another ;;; value, and let it be checked again. ;;; Type checking is pretty basic, but easily factored out and replaced ;;; with whatever your implementation's preferred type checking method ;;; is. I doubt there will be many other methods of index checking, ;;; though the index checkers might be better implemented natively. ;;; (CHECK-TYPE <type-predicate?> <value> <callee>) -> value ;;; Ensure that VALUE satisfies TYPE-PREDICATE?; if not, signal an error stating that VALUE did not satisfy TYPE - PREDICATE ? , showing that this happened while calling . Return VALUE if no ;;; error was signalled. (define (check-type pred? value callee) (if (pred? value) value Recur : when ( or if ) the user gets a debugger prompt , he can ;; proceed where the call to ERROR was with the correct value. (check-type pred? (error "erroneous value" (list pred? value) `(while calling ,callee)) callee))) ;;; (CHECK-INDEX <vector> <index> <callee>) -> index Ensure that INDEX is a valid index into VECTOR ; if not , signal an ;;; error stating that it is not and that this happened in a call to . Return INDEX when it is valid . ( Note that this does NOT check that VECTOR is indeed a vector . ) (define (check-index vec index callee) (let ((index (check-type integer? index callee))) (cond ((< index 0) (check-index vec (error "vector index too low" index `(into vector ,vec) `(while calling ,callee)) callee)) ((>= index (vector-length vec)) (check-index vec (error "vector index too high" index `(into vector ,vec) `(while calling ,callee)) callee)) (else index)))) ;;; (CHECK-INDICES <vector> ;;; <start> <start-name> ;;; <end> <end-name> ;;; <caller>) -> [start end] Ensure that START and END are valid bounds of a range within VECTOR ; if not , signal an error stating that they are not , with ;;; the message being informative about what the argument names were called -- by using START - NAME & END - NAME -- , and that it occurred while calling . Also ensure that VEC is in fact a vector . ;;; Returns no useful value. (define (check-indices vec start start-name end end-name callee) (let ((lose (lambda things (apply error "vector range out of bounds" (append things `(vector was ,vec) `(,start-name was ,start) `(,end-name was ,end) `(while calling ,callee))))) (start (check-type integer? start callee)) (end (check-type integer? end callee))) (cond ((> start end) ;; I'm not sure how well this will work. The intent is that ;; the programmer tells the debugger to proceed with both a new START & a new END by returning multiple values ;; somewhere. (receive (new-start new-end) (lose `(,end-name < ,start-name)) (check-indices vec new-start start-name new-end end-name callee))) ((< start 0) (check-indices vec (lose `(,start-name < 0)) start-name end end-name callee)) ((>= start (vector-length vec)) (check-indices vec (lose `(,start-name > len) `(len was ,(vector-length vec))) start-name end end-name callee)) ((> end (vector-length vec)) (check-indices vec start start-name (lose `(,end-name > len) `(len was ,(vector-length vec))) end-name callee)) (else (values start end))))) ;;; -------------------- ;;; Internal routines ;;; These should all be integrated, native, or otherwise optimized -- ;;; they're used a _lot_ --. All of the loops and LETs inside loops ;;; are lambda-lifted by hand, just so as not to cons closures in the ;;; loops. (If your compiler can do better than that if they're not ;;; lambda-lifted, then lambda-drop (?) them.) ( VECTOR - PARSE - START+END < vector > < arguments > ;;; <start-name> <end-name> ;;; <callee>) ;;; -> [start end] Return two values , composing a valid range within VECTOR , as extracted from ARGUMENTS or defaulted from VECTOR -- 0 for START and the length of VECTOR for END -- ; START - NAME and END - NAME are ;;; purely for error checking. (define (vector-parse-start+end vec args start-name end-name callee) (let ((len (vector-length vec))) (cond ((null? args) (values 0 len)) ((null? (cdr args)) (check-indices vec (car args) start-name len end-name callee)) ((null? (cddr args)) (check-indices vec (car args) start-name (cadr args) end-name callee)) (else (error "too many arguments" `(extra args were ,(cddr args)) `(while calling ,callee)))))) (define-syntax let-vector-start+end (syntax-rules () ((let-vector-start+end ?callee ?vec ?args (?start ?end) ?body1 ?body2 ...) (let ((?vec (check-type vector? ?vec ?callee))) (receive (?start ?end) (vector-parse-start+end ?vec ?args '?start '?end ?callee) ?body1 ?body2 ...))))) ;;; (%SMALLEST-LENGTH <vector-list> <default-length> <callee>) ;;; -> exact, nonnegative integer Compute the smallest length of VECTOR - LIST . DEFAULT - LENGTH is the length that is returned if VECTOR - LIST is empty . Common use ;;; of this is in n-ary vector routines: ;;; (define (f vec . vectors) ( let ( ( vec ( check - type vector ? f ) ) ) ;;; ...(%smallest-length vectors (vector-length vec) f)...)) ;;; %SMALLEST-LENGTH takes care of the type checking -- which is what the CALLEE argument is for -- ; thus , the design is tuned for ;;; avoiding redundant type checks. (define %smallest-length (letrec ((loop (lambda (vector-list length callee) (if (null? vector-list) length (loop (cdr vector-list) (min (vector-length (check-type vector? (car vector-list) callee)) length) callee))))) loop)) ( % VECTOR - COPY ! < target > < tstart > < source > < sstart > < send > ) Copy elements at locations SSTART to SEND from SOURCE to TARGET , starting at TSTART in TARGET . ;;; ;;; Optimize this! Probably with some combination of: ;;; - Force it to be integrated. ;;; - Let it use unsafe vector element dereferencing routines: bounds ;;; checking already happens outside of it. (Or use a compiler that figures this out , but PhD thesis seems to ;;; have been largely ignored in actual implementations...) ;;; - Implement it natively as a VM primitive: the VM can undoubtedly ;;; perform much faster than it can make Scheme perform, even with ;;; bounds checking. ;;; - Implement it in assembly: you _want_ the fine control that ;;; assembly can give you for this. ;;; I already lambda-lift it by hand, but you should be able to make it ;;; even better than that. (define %vector-copy! (letrec ((loop/l->r (lambda (target source send i j) (cond ((< i send) (vector-set! target j (vector-ref source i)) (loop/l->r target source send (+ i 1) (+ j 1)))))) (loop/r->l (lambda (target source sstart i j) (cond ((>= i sstart) (vector-set! target j (vector-ref source i)) (loop/r->l target source sstart (- i 1) (- j 1))))))) (lambda (target tstart source sstart send) (if (> sstart tstart) ; Make sure we don't copy over ; ourselves. (loop/l->r target source send sstart tstart) (loop/r->l target source sstart (- send 1) (+ -1 tstart send (- sstart))))))) ;;; (%VECTOR-REVERSE-COPY! <target> <tstart> <source> <sstart> <send>) Copy elements from SSTART to SEND from SOURCE to TARGET , in the ;;; reverse order. (define %vector-reverse-copy! (letrec ((loop (lambda (target source sstart i j) (cond ((>= i sstart) (vector-set! target j (vector-ref source i)) (loop target source sstart (- i 1) (+ j 1))))))) (lambda (target tstart source sstart send) (loop target source sstart (- send 1) tstart)))) ;;; (%VECTOR-REVERSE! <vector>) (define %vector-reverse! (letrec ((loop (lambda (vec i j) (cond ((<= i j) (let ((v (vector-ref vec i))) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j v) (loop vec (+ i 1) (- j 1)))))))) (lambda (vec start end) (loop vec start (- end 1))))) ( % VECTOR - FOLD1 < kons > < knil > < vector > ) - > knil ' ;;; (KONS <index> <knil> <elt>) -> knil' (define %vector-fold1 (letrec ((loop (lambda (kons knil len vec i) (if (= i len) knil (loop kons (kons knil (vector-ref vec i)) len vec (+ i 1)))))) (lambda (kons knil len vec) (loop kons knil len vec 0)))) ( % VECTOR - FOLD2 + < kons > < knil > < vector > ... ) - > knil ' ;;; (KONS <index> <knil> <elt> ...) -> knil' (define %vector-fold2+ (letrec ((loop (lambda (kons knil len vectors i) (if (= i len) knil (loop kons (apply kons knil (vectors-ref vectors i)) len vectors (+ i 1)))))) (lambda (kons knil len vectors) (loop kons knil len vectors 0)))) ( % VECTOR - MAP ! < f > < target > < length > < vector > ) - > target ;;; (F <index> <elt>) -> elt' (define %vector-map1! (letrec ((loop (lambda (f target vec i) (if (zero? i) target (let ((j (- i 1))) (vector-set! target j (f (vector-ref vec j))) (loop f target vec j)))))) (lambda (f target vec len) (loop f target vec len)))) ( % VECTOR - MAP2 + ! < f > < target > < vectors > < len > ) - > target ;;; (F <index> <elt> ...) -> elt' (define %vector-map2+! (letrec ((loop (lambda (f target vectors i) (if (zero? i) target (let ((j (- i 1))) (vector-set! target j (apply f (vectors-ref vectors j))) (loop f target vectors j)))))) (lambda (f target vectors len) (loop f target vectors len)))) ;;;;;;;;;;;;;;;;;;;;;;;; ***** vector-lib ***** ;;;;;;;;;;;;;;;;;;;;;;; ;;; -------------------- ;;; Constructors ( VECTOR - UNFOLD < f > < length > < initial - seed > ... ) - > vector ;;; (F <index> <seed> ...) -> [elt seed' ...] ;;; The fundamental vector constructor. Creates a vector whose ;;; length is LENGTH and iterates across each index K between 0 and ;;; LENGTH, applying F at each iteration to the current index and the current seeds to receive N+1 values : first , the element to put in ;;; the Kth slot and then N new seeds for the next iteration. (define (vector-unfold f length . initial-seeds) (define vec (make-vector length)) (apply vector-unfold! f vec 0 length initial-seeds) vec) ( VECTOR - UNFOLD ! < > < start > < end > < f > < initial - seed > ... ) - > vector ;;; (F <index> <seed> ...) -> [elt seed' ...] ;;; Like VECTOR-UNFOLD, but unfolds onto an existing vector starting ;;; at <start> up to but not including <end>. (define vector-unfold! Special zero - seed case . (lambda (f vec i len) (cond ((< i len) (vector-set! vec i (f i)) (tabulate! f vec (+ i 1) len))))) Fast path for one seed . (lambda (f vec i len seed) (if (< i len) (receive (elt new-seed) (f i seed) (vector-set! vec i elt) (unfold1! f vec (+ i 1) len new-seed))))) (unfold2+! ; Slower variant for N seeds. (lambda (f vec i len seeds) (if (< i len) (receive (elt . new-seeds) (apply f i seeds) (vector-set! vec i elt) (unfold2+! f vec (+ i 1) len new-seeds)))))) (lambda (f vec start end . initial-seeds) (let ((f (check-type procedure? f vector-unfold!)) (start (check-type nonneg-int? start vector-unfold!)) (end (check-type nonneg-int? end vector-unfold!))) (let () (cond ((null? initial-seeds) (tabulate! f vec start end)) ((null? (cdr initial-seeds)) (unfold1! f vec start end (car initial-seeds))) (else (unfold2+! f vec start end initial-seeds)))))))) ( VECTOR - UNFOLD - RIGHT < f > < length > < initial - seed > ... ) - > vector ;;; (F <seed> ...) -> [seed' ...] ;;; Like VECTOR-UNFOLD, but it generates elements from LENGTH to 0 ;;; (still exclusive with LENGTH and inclusive with 0), not 0 to LENGTH as with VECTOR - UNFOLD . (define (vector-unfold-right f len . initial-seeds) (define vec (make-vector len)) (apply vector-unfold-right! f vec 0 len initial-seeds) vec) ( VECTOR - UNFOLD - RIGHT ! > < start > < end > < f > < initial - seed > ... ) - > vector ;;; Like VECTOR-UNFOLD-RIGHT, but unfolds onto an existing vector. (define (vector-unfold-right! f vec start end . initial-seeds) (letrec ((tabulate! (lambda (f vec i) (cond ((>= i start) (vector-set! vec i (f i)) (tabulate! f vec (- i 1)))))) (unfold1! (lambda (f vec i seed) (if (>= i start) (receive (elt new-seed) (f i seed) (vector-set! vec i elt) (unfold1! f vec (- i 1) new-seed))))) (unfold2+! (lambda (f vec i seeds) (if (>= i start) (receive (elt . new-seeds) (apply f i seeds) (vector-set! vec i elt) (unfold2+! f vec (- i 1) new-seeds)))))) (let ((f (check-type procedure? f vector-unfold-right!)) (start (check-type nonneg-int? start vector-unfold-right!)) (end (check-type nonneg-int? end vector-unfold-right!))) (let ((i (- end 1))) (cond ((null? initial-seeds) (tabulate! f vec i)) ((null? (cdr initial-seeds)) (unfold1! f vec i (car initial-seeds))) (else (unfold2+! f vec i initial-seeds))))))) ( VECTOR - COPY < vector > [ < start > < end > < fill > ] ) - > vector ;;; Create a newly allocated vector containing the elements from the range [ START , END ) in VECTOR . START defaults to 0 ; END defaults to the length of VECTOR . END may be greater than the length of VECTOR , in which case the vector is enlarged ; if FILL is passed , ;;; the new locations from which there is no respective element in VECTOR are filled with FILL . (define (vector-copy vec . args) (let ((vec (check-type vector? vec vector-copy))) We ca n't use LET - VECTOR - START+END , because we have one more ;; argument, and we want finer control, too. ;; Olin 's implementation of LET*-OPTIONALS would prove useful here : ;; the built-in argument-checks-as-you-go-along produces almost _ exactly _ the same code as VECTOR - COPY : PARSE - ARGS . (receive (start end fill) (vector-copy:parse-args vec args) (let ((new-vector (make-vector (- end start) fill))) (%vector-copy! new-vector 0 vec start (if (> end (vector-length vec)) (vector-length vec) end)) new-vector)))) ;;; Auxiliary for VECTOR-COPY. ;;; [wdc] Corrected to allow 0 <= start <= (vector-length vec). (define (vector-copy:parse-args vec args) (define (parse-args start end n fill) (let ((start (check-type nonneg-int? start vector-copy)) (end (check-type nonneg-int? end vector-copy))) (cond ((and (<= 0 start end) (<= start n)) (values start end fill)) (else (error "illegal arguments" `(while calling ,vector-copy) `(start was ,start) `(end was ,end) `(vector was ,vec)))))) (let ((n (vector-length vec))) (cond ((null? args) (parse-args 0 n n (unspecified-value))) ((null? (cdr args)) (parse-args (car args) n n (unspecified-value))) ((null? (cddr args)) (parse-args (car args) (cadr args) n (unspecified-value))) ((null? (cdddr args)) (parse-args (car args) (cadr args) n (caddr args))) (else (error "too many arguments" vector-copy (cdddr args)))))) ;;; (VECTOR-REVERSE-COPY <vector> [<start> <end>]) -> vector ;;; Create a newly allocated vector whose elements are the reversed sequence of elements between START and END in VECTOR . START 's default is 0 ; END 's default is the length of VECTOR . (define (vector-reverse-copy vec . maybe-start+end) (let-vector-start+end vector-reverse-copy vec maybe-start+end (start end) (let ((new (make-vector (- end start)))) (%vector-reverse-copy! new 0 vec start end) new))) ( VECTOR - APPEND < vector > ... ) - > vector ;;; Append VECTOR ... into a newly allocated vector and return that ;;; new vector. (define (vector-append . vectors) (vector-concatenate:aux vectors vector-append)) ;;; (VECTOR-CONCATENATE <vector-list>) -> vector the vectors in VECTOR - LIST . This is equivalent to ( apply vector - append VECTOR - LIST ) but VECTOR - APPEND tends to be implemented in terms of ;;; VECTOR-CONCATENATE, and some Schemes bork when the list to apply ;;; a function to is too long. ;;; ;;; Actually, they're both implemented in terms of an internal routine. (define (vector-concatenate vector-list) (vector-concatenate:aux vector-list vector-concatenate)) Auxiliary for VECTOR - APPEND and VECTOR - CONCATENATE (define vector-concatenate:aux (letrec ((compute-length (lambda (vectors len callee) (if (null? vectors) len (let ((vec (check-type vector? (car vectors) callee))) (compute-length (cdr vectors) (+ (vector-length vec) len) callee))))) (concatenate! (lambda (vectors target to) (if (null? vectors) target (let* ((vec1 (car vectors)) (len (vector-length vec1))) (%vector-copy! target to vec1 0 len) (concatenate! (cdr vectors) target (+ to len))))))) (lambda (vectors callee) (cond ((null? vectors) ;+++ (make-vector 0)) ((null? (cdr vectors)) ;+++ Blech , we still have to allocate a new one . (let* ((vec (check-type vector? (car vectors) callee)) (len (vector-length vec)) (new (make-vector len))) (%vector-copy! new 0 vec 0 len) new)) (else (let ((new-vector (make-vector (compute-length vectors 0 callee)))) (concatenate! vectors new-vector 0) new-vector)))))) ( VECTOR - APPEND - SUBVECTORS < arg > ... ) - > vector Like VECTOR - APPEND but appends subvectors specified by ;;; <vector> <start> <end> argument triples. (define (vector-append-subvectors . args) GATHER - ARGS returns three values : vectors , starts , ends (define (gather-args args) (let loop ((args args) (vecs '()) (starts '()) (ends '())) (if (null? args) (values (reverse vecs) (reverse starts) (reverse ends)) (loop (cdddr args) (cons (car args) vecs) (cons (cadr args) starts) (cons (caddr args) ends))))) ;; TOTAL-LENGTH computes the length of all subvectors (define (total-length starts ends) (let loop ((count 0) (starts starts) (ends ends)) (if (null? starts) count (let ((start (car starts)) (end (car ends))) (loop (+ count (- end start)) (cdr starts) (cdr ends)))))) ;; COPY-EACH! copies each subvector into a result vector (define (copy-each! result vecs starts ends) (let loop ((at 0) (vecs vecs) (starts starts) (ends ends)) (if (null? vecs) result (let ((vec (car vecs)) (start (car starts)) (end (car ends))) (%vector-copy! result at vec start end) (loop (+ at (- end start)) (cdr vecs) (cdr starts) (cdr ends)))))) put them all together , they spell VECTOR - APPEND - SUBVECTORS (receive (vecs starts ends) (gather-args args) (define result (make-vector (total-length starts ends))) (copy-each! result vecs starts ends))) ;;; -------------------- ;;; Predicates ( VECTOR - EMPTY ? < vector > ) - > boolean Return # T if VECTOR has zero elements in it , i.e. VECTOR 's length ;;; is 0, and #F if not. (define (vector-empty? vec) (let ((vec (check-type vector? vec vector-empty?))) (zero? (vector-length vec)))) ( VECTOR= < ? > < vector > ... ) - > boolean ( ? < value > < value > ) - > boolean ;;; Determine vector equality generalized across element comparators. ;;; Vectors A and B are equal iff their lengths are the same and for each respective elements E_a and E_b ( element= ? E_a E_b ) returns a true value . ELT= ? is always applied to two arguments . Element comparison must be consistent wtih EQ ? ; that is , if ( eq ? E_a E_b ) ;;; results in a true value, then (ELEMENT=? E_a E_b) must result in a ;;; true value. This may be exploited to avoid multiple unnecessary ;;; element comparisons. (This implementation does, but does not deal ;;; with the situation that ELEMENT=? is EQ? to avoid more unnecessary ;;; comparisons, but I believe this optimization is probably fairly ;;; insignificant.) ;;; If the number of vector arguments is zero or one , then # T is ;;; automatically returned. If there are N vector arguments, VECTOR_1 VECTOR_2 ... VECTOR_N , then VECTOR_1 & VECTOR_2 are compared ; if they are equal , the vectors VECTOR_2 ... VECTOR_N ;;; are compared. The precise order in which ELT=? is applied is not ;;; specified. (define (vector= elt=? . vectors) (let ((elt=? (check-type procedure? elt=? vector=))) (cond ((null? vectors) #t) ((null? (cdr vectors)) (check-type vector? (car vectors) vector=) #t) (else (let loop ((vecs vectors)) (let ((vec1 (check-type vector? (car vecs) vector=)) (vec2+ (cdr vecs))) (or (null? vec2+) (and (binary-vector= elt=? vec1 (car vec2+)) (loop vec2+))))))))) (define (binary-vector= elt=? vector-a vector-b) (or (eq? vector-a vector-b) ;+++ (let ((length-a (vector-length vector-a)) (length-b (vector-length vector-b))) (letrec ((loop (lambda (i) (or (= i length-a) (and (< i length-b) (test (vector-ref vector-a i) (vector-ref vector-b i) i))))) (test (lambda (elt-a elt-b i) (and (or (eq? elt-a elt-b) ;+++ (elt=? elt-a elt-b)) (loop (+ i 1)))))) (and (= length-a length-b) (loop 0)))))) ;;; -------------------- ;;; Selectors ;;; -------------------- ;;; Iteration ( VECTOR - FOLD < kons > < initial - knil > < vector > ... ) - > ( KONS < knil > < elt > ... ) - > knil ' ; N vectors - > N+1 args ;;; The fundamental vector iterator. KONS is iterated over each ;;; index in all of the vectors in parallel, stopping at the end of ;;; the shortest; KONS is applied to an argument list of (list I ;;; STATE (vector-ref VEC I) ...), where STATE is the current state value -- the state value begins with KNIL and becomes whatever ;;; KONS returned at the respective iteration --, and I is the ;;; current index in the iteration. The iteration is strictly left- ;;; to-right. ;;; (vector-fold KONS KNIL (vector E_1 E_2 ... E_N)) ;;; <=> ;;; (KONS (... (KONS (KONS KNIL E_1) E_2) ... E_N-1) E_N) (define (vector-fold kons knil vec . vectors) (let ((kons (check-type procedure? kons vector-fold)) (vec (check-type vector? vec vector-fold))) (if (null? vectors) (%vector-fold1 kons knil (vector-length vec) vec) (%vector-fold2+ kons knil (%smallest-length vectors (vector-length vec) vector-fold) (cons vec vectors))))) ( VECTOR - FOLD - RIGHT < kons > < initial - knil > < vector > ... ) - > ( KONS < knil > < elt > ... ) - > knil ' ; N vectors = > N+1 args The fundamental vector recursor . Iterates in parallel across VECTOR ... right to left , applying KONS to the elements and the ;;; current state value; the state value becomes what KONS returns at each next iteration . KNIL is the initial state value . ;;; (vector-fold-right KONS KNIL (vector E_1 E_2 ... E_N)) ;;; <=> ;;; (KONS (... (KONS (KONS KNIL E_N) E_N-1) ... E_2) E_1) ;;; ;;; Not implemented in terms of a more primitive operations that might called % VECTOR - FOLD - RIGHT due to the fact that it would n't be very ;;; useful elsewhere. (define vector-fold-right (letrec ((loop1 (lambda (kons knil vec i) (if (negative? i) knil (loop1 kons (kons knil (vector-ref vec i)) vec (- i 1))))) (loop2+ (lambda (kons knil vectors i) (if (negative? i) knil (loop2+ kons (apply kons knil (vectors-ref vectors i)) vectors (- i 1)))))) (lambda (kons knil vec . vectors) (let ((kons (check-type procedure? kons vector-fold-right)) (vec (check-type vector? vec vector-fold-right))) (if (null? vectors) (loop1 kons knil vec (- (vector-length vec) 1)) (loop2+ kons knil (cons vec vectors) (- (%smallest-length vectors (vector-length vec) vector-fold-right) 1))))))) ( VECTOR - MAP < f > < vector > ... ) - > vector ;;; (F <elt> ...) -> value ; N vectors -> N args ;;; Constructs a new vector of the shortest length of the vector ;;; arguments. Each element at index I of the new vector is mapped ;;; from the old vectors by (F I (vector-ref VECTOR I) ...). The ;;; dynamic order of application of F is unspecified. ;;; provided by (rnrs base) #;(define (vector-map f vec . vectors) (let ((f (check-type procedure? f vector-map)) (vec (check-type vector? vec vector-map))) (if (null? vectors) (let ((len (vector-length vec))) (%vector-map1! f (make-vector len) vec len)) (let ((len (%smallest-length vectors (vector-length vec) vector-map))) (%vector-map2+! f (make-vector len) (cons vec vectors) len))))) ( VECTOR - MAP ! < f > < vector > ... ) - > unspecified ;;; (F <elt> ...) -> element' ; N vectors -> N args ;;; Similar to VECTOR-MAP, but rather than mapping the new elements ;;; into a new vector, the new mapped elements are destructively inserted into the first vector . Again , the dynamic order of ;;; application of F is unspecified, so it is dangerous for F to manipulate the first VECTOR . (define (vector-map! f vec . vectors) (let ((f (check-type procedure? f vector-map!)) (vec (check-type vector? vec vector-map!))) (if (null? vectors) (%vector-map1! f vec vec (vector-length vec)) (%vector-map2+! f vec (cons vec vectors) (%smallest-length vectors (vector-length vec) vector-map!))) (unspecified-value))) ;;; (VECTOR-FOR-EACH <f> <vector> ...) -> unspecified ;;; (F <elt> ...) ; N vectors -> N args ;;; Simple vector iterator: applies F to each index in the range [0, ;;; LENGTH), where LENGTH is the length of the smallest vector ;;; argument passed, and the respective element at that index. In contrast with VECTOR - MAP , F is reliably applied to each subsequent elements , starting at index 0 from left to right , in ;;; the vectors. ;;; provided by (rnrs base) #;(define vector-for-each (letrec ((for-each1 (lambda (f vec i len) (cond ((< i len) (f (vector-ref vec i)) (for-each1 f vec (+ i 1) len))))) (for-each2+ (lambda (f vecs i len) (cond ((< i len) (apply f (vectors-ref vecs i)) (for-each2+ f vecs (+ i 1) len)))))) (lambda (f vec . vectors) (let ((f (check-type procedure? f vector-for-each)) (vec (check-type vector? vec vector-for-each))) (if (null? vectors) (for-each1 f vec 0 (vector-length vec)) (for-each2+ f (cons vec vectors) 0 (%smallest-length vectors (vector-length vec) vector-for-each))))))) ( VECTOR - COUNT < predicate ? > < vector > ... ) ;;; -> exact, nonnegative integer ;;; (PREDICATE? <value> ...) ; N vectors -> N args PREDICATE ? is applied element - wise to the elements of VECTOR ... , ;;; and a count is tallied of the number of elements for which a ;;; true value is produced by PREDICATE?. This count is returned. (define (vector-count pred? vec . vectors) (let ((pred? (check-type procedure? pred? vector-count)) (vec (check-type vector? vec vector-count))) (if (null? vectors) (%vector-fold1 (lambda (count elt) (if (pred? elt) (+ count 1) count)) 0 (vector-length vec) vec) (%vector-fold2+ (lambda (count . elts) (if (apply pred? elts) (+ count 1) count)) 0 (%smallest-length vectors (vector-length vec) vector-count) (cons vec vectors))))) ( VECTOR - CUMULATE < f > < vector > < knil > ) ;;; -> vector ;;; Returns a <new>ly allocated vector <new> with the same length as > . Each element < i > of < new > is set to the result of invoking < f > on < new>[i-1 ] and < vec>[i ] , except that for the first call on < f > , the first ;;; argument is <knil>. The <new> vector is returned. (define (vector-cumulate f vec knil) (let* ((len (vector-length vec)) (result (make-vector len))) (let loop ((i 0) (left knil)) (if (= i len) result (let* ((right (vector-ref vec i)) (r (f left right))) (vector-set! result i r) (loop (+ i 1) r)))))) ;;; -------------------- ;;; Searching ( VECTOR - INDEX < predicate ? > < vector > ... ) ;;; -> exact, nonnegative integer or #F ;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args Search left - to - right across VECTOR ... in parallel , returning the index of the first set of values VALUE ... such that ( PREDICATE ? ;;; VALUE ...) returns a true value; if no such set of elements is reached , return # F. (define (vector-index pred? vec . vectors) (vector-index/skip pred? vec vectors vector-index)) ;;; (VECTOR-SKIP <predicate?> <vector> ...) ;;; -> exact, nonnegative integer or #F ;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args ( vector - index ( lambda elts ( not ( apply PREDICATE ? ) ) ) VECTOR ... ) Like VECTOR - INDEX , but find the index of the first set of values ;;; that do _not_ satisfy PREDICATE?. (define (vector-skip pred? vec . vectors) (vector-index/skip (lambda elts (not (apply pred? elts))) vec vectors vector-skip)) ;;; Auxiliary for VECTOR-INDEX & VECTOR-SKIP (define vector-index/skip (letrec ((loop1 (lambda (pred? vec len i) (cond ((= i len) #f) ((pred? (vector-ref vec i)) i) (else (loop1 pred? vec len (+ i 1)))))) (loop2+ (lambda (pred? vectors len i) (cond ((= i len) #f) ((apply pred? (vectors-ref vectors i)) i) (else (loop2+ pred? vectors len (+ i 1))))))) (lambda (pred? vec vectors callee) (let ((pred? (check-type procedure? pred? callee)) (vec (check-type vector? vec callee))) (if (null? vectors) (loop1 pred? vec (vector-length vec) 0) (loop2+ pred? (cons vec vectors) (%smallest-length vectors (vector-length vec) callee) 0)))))) ( VECTOR - INDEX - RIGHT < predicate ? > < vector > ... ) ;;; -> exact, nonnegative integer or #F ;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args Right - to - left variant of VECTOR - INDEX . (define (vector-index-right pred? vec . vectors) (vector-index/skip-right pred? vec vectors vector-index-right)) ( VECTOR - SKIP - RIGHT < predicate ? > < vector > ... ) ;;; -> exact, nonnegative integer or #F ;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args Right - to - left variant of VECTOR - SKIP . (define (vector-skip-right pred? vec . vectors) (vector-index/skip-right (lambda elts (not (apply pred? elts))) vec vectors vector-index-right)) (define vector-index/skip-right (letrec ((loop1 (lambda (pred? vec i) (cond ((negative? i) #f) ((pred? (vector-ref vec i)) i) (else (loop1 pred? vec (- i 1)))))) (loop2+ (lambda (pred? vectors i) (cond ((negative? i) #f) ((apply pred? (vectors-ref vectors i)) i) (else (loop2+ pred? vectors (- i 1))))))) (lambda (pred? vec vectors callee) (let ((pred? (check-type procedure? pred? callee)) (vec (check-type vector? vec callee))) (if (null? vectors) (loop1 pred? vec (- (vector-length vec) 1)) (loop2+ pred? (cons vec vectors) (- (%smallest-length vectors (vector-length vec) callee) 1))))))) ;;; (VECTOR-BINARY-SEARCH <vector> <value> <cmp> [<start> <end>]) ;;; -> exact, nonnegative integer or #F ( CMP < value1 > < value2 > ) - > integer ;;; positive -> VALUE1 > VALUE2 zero - > VALUE1 = VALUE2 ;;; negative -> VALUE1 < VALUE2 Perform a binary search through VECTOR for VALUE , comparing each element to VALUE with CMP . (define (vector-binary-search vec value cmp . maybe-start+end) (let ((cmp (check-type procedure? cmp vector-binary-search))) (let-vector-start+end vector-binary-search vec maybe-start+end (start end) (let loop ((start start) (end end) (j #f)) (let ((i (div (+ start end) 2))) (if (or (= start end) (and j (= i j))) #f (let ((comparison (check-type integer? (cmp (vector-ref vec i) value) `(,cmp for ,vector-binary-search)))) (cond ((zero? comparison) i) ((positive? comparison) (loop start i i)) (else (loop i end i)))))))))) ( VECTOR - ANY < pred ? > < vector > ... ) - > value Apply PRED ? to each parallel element in each VECTOR ... ; if PRED ? ;;; should ever return a true value, immediately stop and return that value ; otherwise , when the shortest vector runs out , return # F. ;;; The iteration and order of application of PRED? across elements ;;; is of the vectors is strictly left-to-right. (define vector-any (letrec ((loop1 (lambda (pred? vec i len len-1) (and (not (= i len)) (if (= i len-1) (pred? (vector-ref vec i)) (or (pred? (vector-ref vec i)) (loop1 pred? vec (+ i 1) len len-1)))))) (loop2+ (lambda (pred? vectors i len len-1) (and (not (= i len)) (if (= i len-1) (apply pred? (vectors-ref vectors i)) (or (apply pred? (vectors-ref vectors i)) (loop2+ pred? vectors (+ i 1) len len-1))))))) (lambda (pred? vec . vectors) (let ((pred? (check-type procedure? pred? vector-any)) (vec (check-type vector? vec vector-any))) (if (null? vectors) (let ((len (vector-length vec))) (loop1 pred? vec 0 len (- len 1))) (let ((len (%smallest-length vectors (vector-length vec) vector-any))) (loop2+ pred? (cons vec vectors) 0 len (- len 1)))))))) ( VECTOR - EVERY < pred ? > < vector > ... ) - > value Apply PRED ? to each parallel value in each VECTOR ... ; if PRED ? should ever return # F , immediately stop and return # F ; otherwise , ;;; if PRED? should return a true value for each element, stopping at ;;; the end of the shortest vector, return the last value that PRED? ;;; returned. In the case that there is an empty vector, return #T. ;;; The iteration and order of application of PRED? across elements ;;; is of the vectors is strictly left-to-right. (define vector-every (letrec ((loop1 (lambda (pred? vec i len len-1) (or (= i len) (if (= i len-1) (pred? (vector-ref vec i)) (and (pred? (vector-ref vec i)) (loop1 pred? vec (+ i 1) len len-1)))))) (loop2+ (lambda (pred? vectors i len len-1) (or (= i len) (if (= i len-1) (apply pred? (vectors-ref vectors i)) (and (apply pred? (vectors-ref vectors i)) (loop2+ pred? vectors (+ i 1) len len-1))))))) (lambda (pred? vec . vectors) (let ((pred? (check-type procedure? pred? vector-every)) (vec (check-type vector? vec vector-every))) (if (null? vectors) (let ((len (vector-length vec))) (loop1 pred? vec 0 len (- len 1))) (let ((len (%smallest-length vectors (vector-length vec) vector-every))) (loop2+ pred? (cons vec vectors) 0 len (- len 1)))))))) ( VECTOR - PARTITION < pred ? > < vector > ) - > vector ;;; A vector the same size as <vec> is newly allocated and filled with all the elements of > that satisfy < pred ? > in their original ;;; order followed by all the elements that do not satisfy <pred?>, ;;; also in their original order. Two values are returned , the newly allocated vector and the index ;;; of the leftmost element that does not satisfy <pred?>. (define (vector-partition pred? vec) (let* ((len (vector-length vec)) (cnt (vector-count pred? vec)) (result (make-vector len))) (let loop ((i 0) (yes 0) (no cnt)) (if (= i len) (values result cnt) (let ((elem (vector-ref vec i))) (if (pred? elem) (begin (vector-set! result yes elem) (loop (+ i 1) (+ yes 1) no)) (begin (vector-set! result no elem) (loop (+ i 1) yes (+ no 1))))))))) ;;; -------------------- ;;; Mutators ( VECTOR - SWAP ! < vector > < index1 > < > ) - > unspecified Swap the values in the locations at and INDEX2 . (define (vector-swap! vec i j) (let ((vec (check-type vector? vec vector-swap!))) (let ((i (check-index vec i vector-swap!)) (j (check-index vec j vector-swap!))) (let ((x (vector-ref vec i))) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j x))))) ;;; helper for case-lambda-based versions (define $check-types (case-lambda [(who v start) (check-type vector? v who) (check-indices v start 'start (vector-length v) 'end who)] [(who v start end) (check-type vector? v who) (check-indices v start 'start end 'end who)])) ( VECTOR - FILL ! < vector > < value > [ < start > < end > ] ) - > unspecified [ R5RS+ ] Fill the locations in VECTOR between START , whose default is 0 , and END , whose default is the length of VECTOR , with VALUE . ;;; ;;; This one can probably be made really fast natively. (define vector-fill! (let () (define $vector-fill! (lambda (vec value start end) (do ((i start (+ i 1))) ((= i end)) (vector-set! vec i value)))) (case-lambda [(vec value) (rnrs:vector-fill! vec value)] [(vec value start) ($check-types 'vector-fill! vec start) ($vector-fill! vec value start (vector-length vec))] [(vec value start end) ($check-types 'vector-fill! vec start end) ($vector-fill! vec value start end)]))) ;;; (VECTOR-COPY! <target> <tstart> <source> [<sstart> <send>]) ;;; -> unspecified Copy the values in the locations in [ SSTART , SEND ) from SOURCE to to , starting at TSTART in TARGET . ;;; [wdc] Corrected to allow 0 <= sstart <= send <= (vector-length source). (define (vector-copy! target tstart source . maybe-sstart+send) (define (doit! sstart send source-length) (let ((tstart (check-type nonneg-int? tstart vector-copy!)) (sstart (check-type nonneg-int? sstart vector-copy!)) (send (check-type nonneg-int? send vector-copy!))) (cond ((and (<= 0 sstart send source-length) (<= (+ tstart (- send sstart)) (vector-length target))) (%vector-copy! target tstart source sstart send)) (else (error "illegal arguments" `(while calling ,vector-copy!) `(target was ,target) `(target-length was ,(vector-length target)) `(tstart was ,tstart) `(source was ,source) `(source-length was ,source-length) `(sstart was ,sstart) `(send was ,send)))))) (let ((n (vector-length source))) (cond ((null? maybe-sstart+send) (doit! 0 n n)) ((null? (cdr maybe-sstart+send)) (doit! (car maybe-sstart+send) n n)) ((null? (cddr maybe-sstart+send)) (doit! (car maybe-sstart+send) (cadr maybe-sstart+send) n)) (else (error "too many arguments" vector-copy! (cddr maybe-sstart+send)))))) ;;; (VECTOR-REVERSE-COPY! <target> <tstart> <source> [<sstart> <send>]) ;;; [wdc] Corrected to allow 0 <= sstart <= send <= (vector-length source). (define (vector-reverse-copy! target tstart source . maybe-sstart+send) (define (doit! sstart send source-length) (let ((tstart (check-type nonneg-int? tstart vector-reverse-copy!)) (sstart (check-type nonneg-int? sstart vector-reverse-copy!)) (send (check-type nonneg-int? send vector-reverse-copy!))) (cond ((and (eq? target source) (or (between? sstart tstart send) (between? tstart sstart (+ tstart (- send sstart))))) (error "vector range for self-copying overlaps" vector-reverse-copy! `(vector was ,target) `(tstart was ,tstart) `(sstart was ,sstart) `(send was ,send))) ((and (<= 0 sstart send source-length) (<= (+ tstart (- send sstart)) (vector-length target))) (%vector-reverse-copy! target tstart source sstart send)) (else (error "illegal arguments" `(while calling ,vector-reverse-copy!) `(target was ,target) `(target-length was ,(vector-length target)) `(tstart was ,tstart) `(source was ,source) `(source-length was ,source-length) `(sstart was ,sstart) `(send was ,send)))))) (let ((n (vector-length source))) (cond ((null? maybe-sstart+send) (doit! 0 n n)) ((null? (cdr maybe-sstart+send)) (doit! (car maybe-sstart+send) n n)) ((null? (cddr maybe-sstart+send)) (doit! (car maybe-sstart+send) (cadr maybe-sstart+send) n)) (else (error "too many arguments" vector-reverse-copy! (cddr maybe-sstart+send)))))) ( VECTOR - REVERSE ! < vector > [ < start > < end > ] ) - > unspecified reverse the contents of the sequence of locations in VECTOR between START , whose default is 0 , and END , whose default is the length of VECTOR . (define (vector-reverse! vec . start+end) (let-vector-start+end vector-reverse! vec start+end (start end) (%vector-reverse! vec start end))) ;;; -------------------- ;;; Conversion ;;; (VECTOR->LIST <vector> [<start> <end>]) -> list ;;; [R5RS+] Produce a list containing the elements in the locations between START , whose default is 0 , and END , whose default is the length of VECTOR , from VECTOR . (define vector->list (let () (define ($vector->list vec start end) (do ((i (- end 1) (- i 1)) (result '() (cons (vector-ref vec i) result))) ((< i start) result))) (case-lambda [(vec) (rnrs:vector->list vec)] [(vec start) ($check-types 'vector->list vec start) ($vector->list vec start (vector-length vec))] [(vec start end) ($check-types 'vector->list vec start end) ($vector->list vec start (vector-length vec))]))) ;;; (REVERSE-VECTOR->LIST <vector> [<start> <end>]) -> list ;;; Produce a list containing the elements in the locations between START , whose default is 0 , and END , whose default is the length of VECTOR , from VECTOR , in reverse order . (define (reverse-vector->list vec . maybe-start+end) (let-vector-start+end reverse-vector->list vec maybe-start+end (start end) (do ((i start (+ i 1)) (result '() (cons (vector-ref vec i) result))) ((= i end) result)))) ;;; (LIST->VECTOR <list> [<start> <end>]) -> vector ;;; [R5RS+] Produce a vector containing the elements in LIST, which must be a proper list , between START , whose default is 0 , & END , ;;; whose default is the length of LIST. It is suggested that if the length of LIST is known in advance , the START and END arguments ;;; be passed, so that LIST->VECTOR need not call LENGTH to determine ;;; the length. ;;; ;;; This implementation diverges on circular lists, unless LENGTH fails ;;; and causes - to fail as well. Given a LENGTH* that computes the ;;; length of a list's cycle, this wouldn't diverge, and would work ;;; great for circular lists. (define list->vector (case-lambda [(lst) (rnrs:list->vector lst)] [(lst start) (check-type nonneg-int? start list->vector) (rnrs:list->vector (list-tail lst start))] [(lst start end) (check-type nonneg-int? start list->vector) (check-type nonneg-int? end list->vector) NB : should be fx < ? (unless (<= start end) (error 'list->vector "start is greater than end" start end)) (let ([len (- end start)]) (let ([v (make-vector len)]) (let loop ([i 0] [ls (list-tail lst start)]) (unless (= i len) (unless (pair? ls) (if (null? ls) (error 'list->vector "list too short" lst start end) (error 'list->vector "improper list" lst))) (vector-set! v i (car ls)) (loop (fx+ i 1) (cdr ls)))) v))])) ;;; (REVERSE-LIST->VECTOR <list> [<start> <end>]) -> vector ;;; Produce a vector containing the elements in LIST, which must be a proper list , between START , whose default is 0 , and END , whose ;;; default is the length of LIST, in reverse order. It is suggested that if the length of LIST is known in advance , the START and END ;;; arguments be passed, so that REVERSE-LIST->VECTOR need not call ;;; LENGTH to determine the the length. ;;; ;;; This also diverges on circular lists unless, again, LENGTH returns ;;; something that makes - bork. (define (reverse-list->vector lst . maybe-start+end) (let*-optionals maybe-start+end ((start 0) (end (length lst))) ; Ugh -- LENGTH (let ((start (check-type nonneg-int? start reverse-list->vector)) (end (check-type nonneg-int? end reverse-list->vector))) ((lambda (f) (vector-unfold-right f (- end start) (list-tail lst start))) (lambda (index l) (cond ((null? l) (error "list too short" `(list was ,lst) `(attempted end was ,end) `(while calling ,reverse-list->vector))) ((pair? l) (values (car l) (cdr l))) (else (error "erroneous value" (list list? lst) `(while calling ,reverse-list->vector))))))))) ;;; (VECTOR->STRING <vector> [<start> <end>]) -> string ;;; Produce a string containing the elements in the locations between START , whose default is 0 , and END , whose default is the length of VECTOR , from VECTOR . (define (vector->string vec . maybe-start+end) (let* ((len (vector-length vec)) (start (if (null? maybe-start+end) 0 (car maybe-start+end))) (end (if (null? maybe-start+end) len (if (null? (cdr maybe-start+end)) len (cadr maybe-start+end)))) (size (- end start))) (define result (make-string size)) (let loop ((at 0) (i start)) (if (= i end) result (begin (string-set! result at (vector-ref vec i)) (loop (+ at 1) (+ i 1))))))) ;;; (STRING->VECTOR <string> [<start> <end>]) -> vector ;;; Produce a vector containing the elements in STRING between START , whose default is 0 , & END , ;;; whose default is the length of STRING, from STRING. (define (string->vector str . maybe-start+end) (let* ((len (string-length str)) (start (if (null? maybe-start+end) 0 (car maybe-start+end))) (end (if (null? maybe-start+end) len (if (null? (cdr maybe-start+end)) len (cadr maybe-start+end)))) (size (- end start))) (define result (make-vector size)) (let loop ((at 0) (i start)) (if (= i end) result (begin (vector-set! result at (string-ref str i)) (loop (+ at 1) (+ i 1)))))))
null
https://raw.githubusercontent.com/arcfide/chez-srfi/96fb553b6ba0834747d5ccfc08c181aa8fd5f612/%253a133/vectors-impl.scm
scheme
he places it in the public domain . his changes are also in the public domain. However, in jurisdictions where it is not possible to dedicate something to the public domain, the entire implementation -------------------- Exported procedure index * Constructors vector-unfold vector-unfold-right vector-copy vector-reverse-copy vector-append vector-concatenate vector-append-subvectors * Predicates vector-empty? vector= * Iteration vector-fold vector-fold-right vector-map vector-map! vector-for-each vector-count vector-cumulate * Searching vector-index vector-skip vector-index-right vector-skip-right vector-binary-search vector-any vector-every vector-partition * Mutators vector-swap! vector-fill! vector-reverse! vector-copy! vector-reverse-copy! vector-reverse! vector-unfold! vector-unfold-right! * Conversion vector->list reverse-vector->list list->vector reverse-list->vector vector->string string->vector -------------------- Commentary on efficiency of the code This code is somewhat tuned for efficiency. There are several internal routines that can be optimized greatly to greatly improve the performance of much of the library. These internal procedures are already carefully tuned for performance, and lambda-lifted by hand. Some other routines are lambda-lifted by hand, but only the loops -- a fast path and an n-ary case --, whereas _all_ of the internal routines' loops are lambda-lifted so as to never cons a even in Scheme systems that perform no loop optimization (which is most of them, unfortunately). Fast paths are provided for common cases in most of the loops in this library. All calls to primitive vector operations are protected by a prior type check; they can be safely converted to use unsafe equivalents of the operations, if available. Ideally, the compiler should be not a happy one. Efficiency of the actual algorithms is a rather mundane point to mention; vector operations are rarely beyond being straightforward. -------------------- SRFI 8, too trivial to put in the dependencies list. if it's available to you. ++ This should be implemented more efficiently. It shouldn't cons a ++ closure, and the cons cells used in the loops when using this could ++ be reused. -------------------- Error checking Error signalling (not checking) is done in a way that tries to be as helpful to the person who gets the debugging prompt as possible. That said, error _checking_ tries to be as unredundant as possible. I don't use any sort of general condition mechanism; I use simply a general condition mechanism. Fix that when porting this to a Scheme implementation that has its own condition system. In argument checks, upon receiving an invalid argument, the checker procedure recursively calls itself, but in one of the arguments to itself is a call to ERROR; this mechanism is used in the hopes that the user may be thrown into a debugger prompt, proceed with another value, and let it be checked again. Type checking is pretty basic, but easily factored out and replaced with whatever your implementation's preferred type checking method is. I doubt there will be many other methods of index checking, though the index checkers might be better implemented natively. (CHECK-TYPE <type-predicate?> <value> <callee>) -> value Ensure that VALUE satisfies TYPE-PREDICATE?; if not, signal an error was signalled. proceed where the call to ERROR was with the correct value. (CHECK-INDEX <vector> <index> <callee>) -> index if not , signal an error stating that it is not and that this happened in a call to (CHECK-INDICES <vector> <start> <start-name> <end> <end-name> <caller>) -> [start end] if not , signal an error stating that they are not , with the message being informative about what the argument names were Returns no useful value. I'm not sure how well this will work. The intent is that the programmer tells the debugger to proceed with both a somewhere. -------------------- Internal routines These should all be integrated, native, or otherwise optimized -- they're used a _lot_ --. All of the loops and LETs inside loops are lambda-lifted by hand, just so as not to cons closures in the loops. (If your compiler can do better than that if they're not lambda-lifted, then lambda-drop (?) them.) <start-name> <end-name> <callee>) -> [start end] START - NAME and END - NAME are purely for error checking. (%SMALLEST-LENGTH <vector-list> <default-length> <callee>) -> exact, nonnegative integer of this is in n-ary vector routines: (define (f vec . vectors) ...(%smallest-length vectors (vector-length vec) f)...)) %SMALLEST-LENGTH takes care of the type checking -- which is what thus , the design is tuned for avoiding redundant type checks. Optimize this! Probably with some combination of: - Force it to be integrated. - Let it use unsafe vector element dereferencing routines: bounds checking already happens outside of it. (Or use a compiler have been largely ignored in actual implementations...) - Implement it natively as a VM primitive: the VM can undoubtedly perform much faster than it can make Scheme perform, even with bounds checking. - Implement it in assembly: you _want_ the fine control that assembly can give you for this. I already lambda-lift it by hand, but you should be able to make it even better than that. Make sure we don't copy over ourselves. (%VECTOR-REVERSE-COPY! <target> <tstart> <source> <sstart> <send>) reverse order. (%VECTOR-REVERSE! <vector>) (KONS <index> <knil> <elt>) -> knil' (KONS <index> <knil> <elt> ...) -> knil' (F <index> <elt>) -> elt' (F <index> <elt> ...) -> elt' ***** vector-lib ***** ;;;;;;;;;;;;;;;;;;;;;;; -------------------- Constructors (F <index> <seed> ...) -> [elt seed' ...] The fundamental vector constructor. Creates a vector whose length is LENGTH and iterates across each index K between 0 and LENGTH, applying F at each iteration to the current index and the the Kth slot and then N new seeds for the next iteration. (F <index> <seed> ...) -> [elt seed' ...] Like VECTOR-UNFOLD, but unfolds onto an existing vector starting at <start> up to but not including <end>. Slower variant for N seeds. (F <seed> ...) -> [seed' ...] Like VECTOR-UNFOLD, but it generates elements from LENGTH to 0 (still exclusive with LENGTH and inclusive with 0), not 0 to Like VECTOR-UNFOLD-RIGHT, but unfolds onto an existing vector. Create a newly allocated vector containing the elements from the END defaults if FILL is passed , the new locations from which there is no respective element in argument, and we want finer control, too. the built-in argument-checks-as-you-go-along produces almost Auxiliary for VECTOR-COPY. [wdc] Corrected to allow 0 <= start <= (vector-length vec). (VECTOR-REVERSE-COPY <vector> [<start> <end>]) -> vector Create a newly allocated vector whose elements are the reversed END 's default is the length of VECTOR . Append VECTOR ... into a newly allocated vector and return that new vector. (VECTOR-CONCATENATE <vector-list>) -> vector VECTOR-CONCATENATE, and some Schemes bork when the list to apply a function to is too long. Actually, they're both implemented in terms of an internal routine. +++ +++ <vector> <start> <end> argument triples. TOTAL-LENGTH computes the length of all subvectors COPY-EACH! copies each subvector into a result vector -------------------- Predicates is 0, and #F if not. Determine vector equality generalized across element comparators. Vectors A and B are equal iff their lengths are the same and for that is , if ( eq ? E_a E_b ) results in a true value, then (ELEMENT=? E_a E_b) must result in a true value. This may be exploited to avoid multiple unnecessary element comparisons. (This implementation does, but does not deal with the situation that ELEMENT=? is EQ? to avoid more unnecessary comparisons, but I believe this optimization is probably fairly insignificant.) automatically returned. If there are N vector arguments, if they are equal , the vectors VECTOR_2 ... VECTOR_N are compared. The precise order in which ELT=? is applied is not specified. +++ +++ -------------------- Selectors -------------------- Iteration N vectors - > N+1 args The fundamental vector iterator. KONS is iterated over each index in all of the vectors in parallel, stopping at the end of the shortest; KONS is applied to an argument list of (list I STATE (vector-ref VEC I) ...), where STATE is the current state KONS returned at the respective iteration --, and I is the current index in the iteration. The iteration is strictly left- to-right. (vector-fold KONS KNIL (vector E_1 E_2 ... E_N)) <=> (KONS (... (KONS (KONS KNIL E_1) E_2) ... E_N-1) E_N) N vectors = > N+1 args current state value; the state value becomes what KONS returns (vector-fold-right KONS KNIL (vector E_1 E_2 ... E_N)) <=> (KONS (... (KONS (KONS KNIL E_N) E_N-1) ... E_2) E_1) Not implemented in terms of a more primitive operations that might useful elsewhere. (F <elt> ...) -> value ; N vectors -> N args Constructs a new vector of the shortest length of the vector arguments. Each element at index I of the new vector is mapped from the old vectors by (F I (vector-ref VECTOR I) ...). The dynamic order of application of F is unspecified. provided by (rnrs base) (define (vector-map f vec . vectors) (F <elt> ...) -> element' ; N vectors -> N args Similar to VECTOR-MAP, but rather than mapping the new elements into a new vector, the new mapped elements are destructively application of F is unspecified, so it is dangerous for F to (VECTOR-FOR-EACH <f> <vector> ...) -> unspecified (F <elt> ...) ; N vectors -> N args Simple vector iterator: applies F to each index in the range [0, LENGTH), where LENGTH is the length of the smallest vector argument passed, and the respective element at that index. In the vectors. provided by (rnrs base) (define vector-for-each -> exact, nonnegative integer (PREDICATE? <value> ...) ; N vectors -> N args and a count is tallied of the number of elements for which a true value is produced by PREDICATE?. This count is returned. -> vector Returns a <new>ly allocated vector <new> with the same length as argument is <knil>. The <new> vector is returned. -------------------- Searching -> exact, nonnegative integer or #F (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args VALUE ...) returns a true value; if no such set of elements is (VECTOR-SKIP <predicate?> <vector> ...) -> exact, nonnegative integer or #F (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args that do _not_ satisfy PREDICATE?. Auxiliary for VECTOR-INDEX & VECTOR-SKIP -> exact, nonnegative integer or #F (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args -> exact, nonnegative integer or #F (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args (VECTOR-BINARY-SEARCH <vector> <value> <cmp> [<start> <end>]) -> exact, nonnegative integer or #F positive -> VALUE1 > VALUE2 negative -> VALUE1 < VALUE2 if PRED ? should ever return a true value, immediately stop and return that otherwise , when the shortest vector runs out , return # F. The iteration and order of application of PRED? across elements is of the vectors is strictly left-to-right. if PRED ? otherwise , if PRED? should return a true value for each element, stopping at the end of the shortest vector, return the last value that PRED? returned. In the case that there is an empty vector, return #T. The iteration and order of application of PRED? across elements is of the vectors is strictly left-to-right. A vector the same size as <vec> is newly allocated and filled with order followed by all the elements that do not satisfy <pred?>, also in their original order. of the leftmost element that does not satisfy <pred?>. -------------------- Mutators helper for case-lambda-based versions This one can probably be made really fast natively. (VECTOR-COPY! <target> <tstart> <source> [<sstart> <send>]) -> unspecified [wdc] Corrected to allow 0 <= sstart <= send <= (vector-length source). (VECTOR-REVERSE-COPY! <target> <tstart> <source> [<sstart> <send>]) [wdc] Corrected to allow 0 <= sstart <= send <= (vector-length source). -------------------- Conversion (VECTOR->LIST <vector> [<start> <end>]) -> list [R5RS+] Produce a list containing the elements in the locations (REVERSE-VECTOR->LIST <vector> [<start> <end>]) -> list Produce a list containing the elements in the locations between (LIST->VECTOR <list> [<start> <end>]) -> vector [R5RS+] Produce a vector containing the elements in LIST, which whose default is the length of LIST. It is suggested that if the be passed, so that LIST->VECTOR need not call LENGTH to determine the length. This implementation diverges on circular lists, unless LENGTH fails and causes - to fail as well. Given a LENGTH* that computes the length of a list's cycle, this wouldn't diverge, and would work great for circular lists. (REVERSE-LIST->VECTOR <list> [<start> <end>]) -> vector Produce a vector containing the elements in LIST, which must be a default is the length of LIST, in reverse order. It is suggested arguments be passed, so that REVERSE-LIST->VECTOR need not call LENGTH to determine the the length. This also diverges on circular lists unless, again, LENGTH returns something that makes - bork. Ugh -- LENGTH (VECTOR->STRING <vector> [<start> <end>]) -> string Produce a string containing the elements in the locations (STRING->VECTOR <string> [<start> <end>]) -> vector Produce a vector containing the elements in STRING whose default is the length of STRING, from STRING.
SRFI 43 : Vector library -*- Scheme -*- $ Id$ [ wdc ] made some corrections , also in the public domain . is made available under the same license as SRFI 133 . loops are lambda - lifted , and only if some routine has two possible closure in their body ( VECTOR - PARSE - START+END does n't have a loop ) , able to determine this , but the state of Scheme compilers today is Utilities (define-syntax receive (syntax-rules () ((receive ?formals ?producer ?body1 ?body2 ...) (call-with-values (lambda () ?producer) (lambda ?formals ?body1 ?body2 ...))))) Not the best LET*-OPTIONALS , but not the worst , either . (define-syntax let*-optionals (syntax-rules () ((let*-optionals (?x ...) ((?var ?default) ...) ?body1 ?body2 ...) (let ((args (?x ...))) (let*-optionals args ((?var ?default) ...) ?body1 ?body2 ...))) ((let*-optionals ?args ((?var ?default) ...) ?body1 ?body2 ...) (let*-optionals:aux ?args ?args ((?var ?default) ...) ?body1 ?body2 ...)))) (define-syntax let*-optionals:aux (syntax-rules () ((aux ?orig-args-var ?args-var () ?body1 ?body2 ...) (if (null? ?args-var) (let () ?body1 ?body2 ...) (error "too many arguments" (length ?orig-args-var) ?orig-args-var))) ((aux ?orig-args-var ?args-var ((?var ?default) ?more ...) ?body1 ?body2 ...) (if (null? ?args-var) (let* ((?var ?default) ?more ...) ?body1 ?body2 ...) (let ((?var (car ?args-var)) (new-args (cdr ?args-var))) (let*-optionals:aux ?orig-args-var new-args (?more ...) ?body1 ?body2 ...)))))) (define (nonneg-int? x) (and (integer? x) (not (negative? x)))) (define (between? x y z) (and (< x y) (<= y z))) (define (unspecified-value) (if #f #f)) (define (vectors-ref vectors i) (map (lambda (v) (vector-ref v i)) vectors)) SRFI 23 's ERROR , even in cases where it might be better to use such error stating that VALUE did not satisfy TYPE - PREDICATE ? , showing that this happened while calling . Return VALUE if no (define (check-type pred? value callee) (if (pred? value) value Recur : when ( or if ) the user gets a debugger prompt , he can (check-type pred? (error "erroneous value" (list pred? value) `(while calling ,callee)) callee))) . Return INDEX when it is valid . ( Note that this does NOT check that VECTOR is indeed a vector . ) (define (check-index vec index callee) (let ((index (check-type integer? index callee))) (cond ((< index 0) (check-index vec (error "vector index too low" index `(into vector ,vec) `(while calling ,callee)) callee)) ((>= index (vector-length vec)) (check-index vec (error "vector index too high" index `(into vector ,vec) `(while calling ,callee)) callee)) (else index)))) Ensure that START and END are valid bounds of a range within called -- by using START - NAME & END - NAME -- , and that it occurred while calling . Also ensure that VEC is in fact a vector . (define (check-indices vec start start-name end end-name callee) (let ((lose (lambda things (apply error "vector range out of bounds" (append things `(vector was ,vec) `(,start-name was ,start) `(,end-name was ,end) `(while calling ,callee))))) (start (check-type integer? start callee)) (end (check-type integer? end callee))) (cond ((> start end) new START & a new END by returning multiple values (receive (new-start new-end) (lose `(,end-name < ,start-name)) (check-indices vec new-start start-name new-end end-name callee))) ((< start 0) (check-indices vec (lose `(,start-name < 0)) start-name end end-name callee)) ((>= start (vector-length vec)) (check-indices vec (lose `(,start-name > len) `(len was ,(vector-length vec))) start-name end end-name callee)) ((> end (vector-length vec)) (check-indices vec start start-name (lose `(,end-name > len) `(len was ,(vector-length vec))) end-name callee)) (else (values start end))))) ( VECTOR - PARSE - START+END < vector > < arguments > Return two values , composing a valid range within VECTOR , as extracted from ARGUMENTS or defaulted from VECTOR -- 0 for START (define (vector-parse-start+end vec args start-name end-name callee) (let ((len (vector-length vec))) (cond ((null? args) (values 0 len)) ((null? (cdr args)) (check-indices vec (car args) start-name len end-name callee)) ((null? (cddr args)) (check-indices vec (car args) start-name (cadr args) end-name callee)) (else (error "too many arguments" `(extra args were ,(cddr args)) `(while calling ,callee)))))) (define-syntax let-vector-start+end (syntax-rules () ((let-vector-start+end ?callee ?vec ?args (?start ?end) ?body1 ?body2 ...) (let ((?vec (check-type vector? ?vec ?callee))) (receive (?start ?end) (vector-parse-start+end ?vec ?args '?start '?end ?callee) ?body1 ?body2 ...))))) Compute the smallest length of VECTOR - LIST . DEFAULT - LENGTH is the length that is returned if VECTOR - LIST is empty . Common use ( let ( ( vec ( check - type vector ? f ) ) ) (define %smallest-length (letrec ((loop (lambda (vector-list length callee) (if (null? vector-list) length (loop (cdr vector-list) (min (vector-length (check-type vector? (car vector-list) callee)) length) callee))))) loop)) ( % VECTOR - COPY ! < target > < tstart > < source > < sstart > < send > ) Copy elements at locations SSTART to SEND from SOURCE to TARGET , starting at TSTART in TARGET . that figures this out , but PhD thesis seems to (define %vector-copy! (letrec ((loop/l->r (lambda (target source send i j) (cond ((< i send) (vector-set! target j (vector-ref source i)) (loop/l->r target source send (+ i 1) (+ j 1)))))) (loop/r->l (lambda (target source sstart i j) (cond ((>= i sstart) (vector-set! target j (vector-ref source i)) (loop/r->l target source sstart (- i 1) (- j 1))))))) (lambda (target tstart source sstart send) (loop/l->r target source send sstart tstart) (loop/r->l target source sstart (- send 1) (+ -1 tstart send (- sstart))))))) Copy elements from SSTART to SEND from SOURCE to TARGET , in the (define %vector-reverse-copy! (letrec ((loop (lambda (target source sstart i j) (cond ((>= i sstart) (vector-set! target j (vector-ref source i)) (loop target source sstart (- i 1) (+ j 1))))))) (lambda (target tstart source sstart send) (loop target source sstart (- send 1) tstart)))) (define %vector-reverse! (letrec ((loop (lambda (vec i j) (cond ((<= i j) (let ((v (vector-ref vec i))) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j v) (loop vec (+ i 1) (- j 1)))))))) (lambda (vec start end) (loop vec start (- end 1))))) ( % VECTOR - FOLD1 < kons > < knil > < vector > ) - > knil ' (define %vector-fold1 (letrec ((loop (lambda (kons knil len vec i) (if (= i len) knil (loop kons (kons knil (vector-ref vec i)) len vec (+ i 1)))))) (lambda (kons knil len vec) (loop kons knil len vec 0)))) ( % VECTOR - FOLD2 + < kons > < knil > < vector > ... ) - > knil ' (define %vector-fold2+ (letrec ((loop (lambda (kons knil len vectors i) (if (= i len) knil (loop kons (apply kons knil (vectors-ref vectors i)) len vectors (+ i 1)))))) (lambda (kons knil len vectors) (loop kons knil len vectors 0)))) ( % VECTOR - MAP ! < f > < target > < length > < vector > ) - > target (define %vector-map1! (letrec ((loop (lambda (f target vec i) (if (zero? i) target (let ((j (- i 1))) (vector-set! target j (f (vector-ref vec j))) (loop f target vec j)))))) (lambda (f target vec len) (loop f target vec len)))) ( % VECTOR - MAP2 + ! < f > < target > < vectors > < len > ) - > target (define %vector-map2+! (letrec ((loop (lambda (f target vectors i) (if (zero? i) target (let ((j (- i 1))) (vector-set! target j (apply f (vectors-ref vectors j))) (loop f target vectors j)))))) (lambda (f target vectors len) (loop f target vectors len)))) ( VECTOR - UNFOLD < f > < length > < initial - seed > ... ) - > vector current seeds to receive N+1 values : first , the element to put in (define (vector-unfold f length . initial-seeds) (define vec (make-vector length)) (apply vector-unfold! f vec 0 length initial-seeds) vec) ( VECTOR - UNFOLD ! < > < start > < end > < f > < initial - seed > ... ) - > vector (define vector-unfold! Special zero - seed case . (lambda (f vec i len) (cond ((< i len) (vector-set! vec i (f i)) (tabulate! f vec (+ i 1) len))))) Fast path for one seed . (lambda (f vec i len seed) (if (< i len) (receive (elt new-seed) (f i seed) (vector-set! vec i elt) (unfold1! f vec (+ i 1) len new-seed))))) (lambda (f vec i len seeds) (if (< i len) (receive (elt . new-seeds) (apply f i seeds) (vector-set! vec i elt) (unfold2+! f vec (+ i 1) len new-seeds)))))) (lambda (f vec start end . initial-seeds) (let ((f (check-type procedure? f vector-unfold!)) (start (check-type nonneg-int? start vector-unfold!)) (end (check-type nonneg-int? end vector-unfold!))) (let () (cond ((null? initial-seeds) (tabulate! f vec start end)) ((null? (cdr initial-seeds)) (unfold1! f vec start end (car initial-seeds))) (else (unfold2+! f vec start end initial-seeds)))))))) ( VECTOR - UNFOLD - RIGHT < f > < length > < initial - seed > ... ) - > vector LENGTH as with VECTOR - UNFOLD . (define (vector-unfold-right f len . initial-seeds) (define vec (make-vector len)) (apply vector-unfold-right! f vec 0 len initial-seeds) vec) ( VECTOR - UNFOLD - RIGHT ! > < start > < end > < f > < initial - seed > ... ) - > vector (define (vector-unfold-right! f vec start end . initial-seeds) (letrec ((tabulate! (lambda (f vec i) (cond ((>= i start) (vector-set! vec i (f i)) (tabulate! f vec (- i 1)))))) (unfold1! (lambda (f vec i seed) (if (>= i start) (receive (elt new-seed) (f i seed) (vector-set! vec i elt) (unfold1! f vec (- i 1) new-seed))))) (unfold2+! (lambda (f vec i seeds) (if (>= i start) (receive (elt . new-seeds) (apply f i seeds) (vector-set! vec i elt) (unfold2+! f vec (- i 1) new-seeds)))))) (let ((f (check-type procedure? f vector-unfold-right!)) (start (check-type nonneg-int? start vector-unfold-right!)) (end (check-type nonneg-int? end vector-unfold-right!))) (let ((i (- end 1))) (cond ((null? initial-seeds) (tabulate! f vec i)) ((null? (cdr initial-seeds)) (unfold1! f vec i (car initial-seeds))) (else (unfold2+! f vec i initial-seeds))))))) ( VECTOR - COPY < vector > [ < start > < end > < fill > ] ) - > vector to the length of VECTOR . END may be greater than the length of VECTOR are filled with FILL . (define (vector-copy vec . args) (let ((vec (check-type vector? vec vector-copy))) We ca n't use LET - VECTOR - START+END , because we have one more Olin 's implementation of LET*-OPTIONALS would prove useful here : _ exactly _ the same code as VECTOR - COPY : PARSE - ARGS . (receive (start end fill) (vector-copy:parse-args vec args) (let ((new-vector (make-vector (- end start) fill))) (%vector-copy! new-vector 0 vec start (if (> end (vector-length vec)) (vector-length vec) end)) new-vector)))) (define (vector-copy:parse-args vec args) (define (parse-args start end n fill) (let ((start (check-type nonneg-int? start vector-copy)) (end (check-type nonneg-int? end vector-copy))) (cond ((and (<= 0 start end) (<= start n)) (values start end fill)) (else (error "illegal arguments" `(while calling ,vector-copy) `(start was ,start) `(end was ,end) `(vector was ,vec)))))) (let ((n (vector-length vec))) (cond ((null? args) (parse-args 0 n n (unspecified-value))) ((null? (cdr args)) (parse-args (car args) n n (unspecified-value))) ((null? (cddr args)) (parse-args (car args) (cadr args) n (unspecified-value))) ((null? (cdddr args)) (parse-args (car args) (cadr args) n (caddr args))) (else (error "too many arguments" vector-copy (cdddr args)))))) sequence of elements between START and END in VECTOR . START 's (define (vector-reverse-copy vec . maybe-start+end) (let-vector-start+end vector-reverse-copy vec maybe-start+end (start end) (let ((new (make-vector (- end start)))) (%vector-reverse-copy! new 0 vec start end) new))) ( VECTOR - APPEND < vector > ... ) - > vector (define (vector-append . vectors) (vector-concatenate:aux vectors vector-append)) the vectors in VECTOR - LIST . This is equivalent to ( apply vector - append VECTOR - LIST ) but VECTOR - APPEND tends to be implemented in terms of (define (vector-concatenate vector-list) (vector-concatenate:aux vector-list vector-concatenate)) Auxiliary for VECTOR - APPEND and VECTOR - CONCATENATE (define vector-concatenate:aux (letrec ((compute-length (lambda (vectors len callee) (if (null? vectors) len (let ((vec (check-type vector? (car vectors) callee))) (compute-length (cdr vectors) (+ (vector-length vec) len) callee))))) (concatenate! (lambda (vectors target to) (if (null? vectors) target (let* ((vec1 (car vectors)) (len (vector-length vec1))) (%vector-copy! target to vec1 0 len) (concatenate! (cdr vectors) target (+ to len))))))) (lambda (vectors callee) (make-vector 0)) Blech , we still have to allocate a new one . (let* ((vec (check-type vector? (car vectors) callee)) (len (vector-length vec)) (new (make-vector len))) (%vector-copy! new 0 vec 0 len) new)) (else (let ((new-vector (make-vector (compute-length vectors 0 callee)))) (concatenate! vectors new-vector 0) new-vector)))))) ( VECTOR - APPEND - SUBVECTORS < arg > ... ) - > vector Like VECTOR - APPEND but appends subvectors specified by (define (vector-append-subvectors . args) GATHER - ARGS returns three values : vectors , starts , ends (define (gather-args args) (let loop ((args args) (vecs '()) (starts '()) (ends '())) (if (null? args) (values (reverse vecs) (reverse starts) (reverse ends)) (loop (cdddr args) (cons (car args) vecs) (cons (cadr args) starts) (cons (caddr args) ends))))) (define (total-length starts ends) (let loop ((count 0) (starts starts) (ends ends)) (if (null? starts) count (let ((start (car starts)) (end (car ends))) (loop (+ count (- end start)) (cdr starts) (cdr ends)))))) (define (copy-each! result vecs starts ends) (let loop ((at 0) (vecs vecs) (starts starts) (ends ends)) (if (null? vecs) result (let ((vec (car vecs)) (start (car starts)) (end (car ends))) (%vector-copy! result at vec start end) (loop (+ at (- end start)) (cdr vecs) (cdr starts) (cdr ends)))))) put them all together , they spell VECTOR - APPEND - SUBVECTORS (receive (vecs starts ends) (gather-args args) (define result (make-vector (total-length starts ends))) (copy-each! result vecs starts ends))) ( VECTOR - EMPTY ? < vector > ) - > boolean Return # T if VECTOR has zero elements in it , i.e. VECTOR 's length (define (vector-empty? vec) (let ((vec (check-type vector? vec vector-empty?))) (zero? (vector-length vec)))) ( VECTOR= < ? > < vector > ... ) - > boolean ( ? < value > < value > ) - > boolean each respective elements E_a and E_b ( element= ? E_a E_b ) returns a true value . ELT= ? is always applied to two arguments . Element If the number of vector arguments is zero or one , then # T is VECTOR_1 VECTOR_2 ... VECTOR_N , then VECTOR_1 & VECTOR_2 are (define (vector= elt=? . vectors) (let ((elt=? (check-type procedure? elt=? vector=))) (cond ((null? vectors) #t) ((null? (cdr vectors)) (check-type vector? (car vectors) vector=) #t) (else (let loop ((vecs vectors)) (let ((vec1 (check-type vector? (car vecs) vector=)) (vec2+ (cdr vecs))) (or (null? vec2+) (and (binary-vector= elt=? vec1 (car vec2+)) (loop vec2+))))))))) (define (binary-vector= elt=? vector-a vector-b) (let ((length-a (vector-length vector-a)) (length-b (vector-length vector-b))) (letrec ((loop (lambda (i) (or (= i length-a) (and (< i length-b) (test (vector-ref vector-a i) (vector-ref vector-b i) i))))) (test (lambda (elt-a elt-b i) (elt=? elt-a elt-b)) (loop (+ i 1)))))) (and (= length-a length-b) (loop 0)))))) ( VECTOR - FOLD < kons > < initial - knil > < vector > ... ) - > value -- the state value begins with KNIL and becomes whatever (define (vector-fold kons knil vec . vectors) (let ((kons (check-type procedure? kons vector-fold)) (vec (check-type vector? vec vector-fold))) (if (null? vectors) (%vector-fold1 kons knil (vector-length vec) vec) (%vector-fold2+ kons knil (%smallest-length vectors (vector-length vec) vector-fold) (cons vec vectors))))) ( VECTOR - FOLD - RIGHT < kons > < initial - knil > < vector > ... ) - > The fundamental vector recursor . Iterates in parallel across VECTOR ... right to left , applying KONS to the elements and the at each next iteration . KNIL is the initial state value . called % VECTOR - FOLD - RIGHT due to the fact that it would n't be very (define vector-fold-right (letrec ((loop1 (lambda (kons knil vec i) (if (negative? i) knil (loop1 kons (kons knil (vector-ref vec i)) vec (- i 1))))) (loop2+ (lambda (kons knil vectors i) (if (negative? i) knil (loop2+ kons (apply kons knil (vectors-ref vectors i)) vectors (- i 1)))))) (lambda (kons knil vec . vectors) (let ((kons (check-type procedure? kons vector-fold-right)) (vec (check-type vector? vec vector-fold-right))) (if (null? vectors) (loop1 kons knil vec (- (vector-length vec) 1)) (loop2+ kons knil (cons vec vectors) (- (%smallest-length vectors (vector-length vec) vector-fold-right) 1))))))) ( VECTOR - MAP < f > < vector > ... ) - > vector (let ((f (check-type procedure? f vector-map)) (vec (check-type vector? vec vector-map))) (if (null? vectors) (let ((len (vector-length vec))) (%vector-map1! f (make-vector len) vec len)) (let ((len (%smallest-length vectors (vector-length vec) vector-map))) (%vector-map2+! f (make-vector len) (cons vec vectors) len))))) ( VECTOR - MAP ! < f > < vector > ... ) - > unspecified inserted into the first vector . Again , the dynamic order of manipulate the first VECTOR . (define (vector-map! f vec . vectors) (let ((f (check-type procedure? f vector-map!)) (vec (check-type vector? vec vector-map!))) (if (null? vectors) (%vector-map1! f vec vec (vector-length vec)) (%vector-map2+! f vec (cons vec vectors) (%smallest-length vectors (vector-length vec) vector-map!))) (unspecified-value))) contrast with VECTOR - MAP , F is reliably applied to each subsequent elements , starting at index 0 from left to right , in (letrec ((for-each1 (lambda (f vec i len) (cond ((< i len) (f (vector-ref vec i)) (for-each1 f vec (+ i 1) len))))) (for-each2+ (lambda (f vecs i len) (cond ((< i len) (apply f (vectors-ref vecs i)) (for-each2+ f vecs (+ i 1) len)))))) (lambda (f vec . vectors) (let ((f (check-type procedure? f vector-for-each)) (vec (check-type vector? vec vector-for-each))) (if (null? vectors) (for-each1 f vec 0 (vector-length vec)) (for-each2+ f (cons vec vectors) 0 (%smallest-length vectors (vector-length vec) vector-for-each))))))) ( VECTOR - COUNT < predicate ? > < vector > ... ) PREDICATE ? is applied element - wise to the elements of VECTOR ... , (define (vector-count pred? vec . vectors) (let ((pred? (check-type procedure? pred? vector-count)) (vec (check-type vector? vec vector-count))) (if (null? vectors) (%vector-fold1 (lambda (count elt) (if (pred? elt) (+ count 1) count)) 0 (vector-length vec) vec) (%vector-fold2+ (lambda (count . elts) (if (apply pred? elts) (+ count 1) count)) 0 (%smallest-length vectors (vector-length vec) vector-count) (cons vec vectors))))) ( VECTOR - CUMULATE < f > < vector > < knil > ) > . Each element < i > of < new > is set to the result of invoking < f > on < new>[i-1 ] and < vec>[i ] , except that for the first call on < f > , the first (define (vector-cumulate f vec knil) (let* ((len (vector-length vec)) (result (make-vector len))) (let loop ((i 0) (left knil)) (if (= i len) result (let* ((right (vector-ref vec i)) (r (f left right))) (vector-set! result i r) (loop (+ i 1) r)))))) ( VECTOR - INDEX < predicate ? > < vector > ... ) Search left - to - right across VECTOR ... in parallel , returning the index of the first set of values VALUE ... such that ( PREDICATE ? reached , return # F. (define (vector-index pred? vec . vectors) (vector-index/skip pred? vec vectors vector-index)) ( vector - index ( lambda elts ( not ( apply PREDICATE ? ) ) ) VECTOR ... ) Like VECTOR - INDEX , but find the index of the first set of values (define (vector-skip pred? vec . vectors) (vector-index/skip (lambda elts (not (apply pred? elts))) vec vectors vector-skip)) (define vector-index/skip (letrec ((loop1 (lambda (pred? vec len i) (cond ((= i len) #f) ((pred? (vector-ref vec i)) i) (else (loop1 pred? vec len (+ i 1)))))) (loop2+ (lambda (pred? vectors len i) (cond ((= i len) #f) ((apply pred? (vectors-ref vectors i)) i) (else (loop2+ pred? vectors len (+ i 1))))))) (lambda (pred? vec vectors callee) (let ((pred? (check-type procedure? pred? callee)) (vec (check-type vector? vec callee))) (if (null? vectors) (loop1 pred? vec (vector-length vec) 0) (loop2+ pred? (cons vec vectors) (%smallest-length vectors (vector-length vec) callee) 0)))))) ( VECTOR - INDEX - RIGHT < predicate ? > < vector > ... ) Right - to - left variant of VECTOR - INDEX . (define (vector-index-right pred? vec . vectors) (vector-index/skip-right pred? vec vectors vector-index-right)) ( VECTOR - SKIP - RIGHT < predicate ? > < vector > ... ) Right - to - left variant of VECTOR - SKIP . (define (vector-skip-right pred? vec . vectors) (vector-index/skip-right (lambda elts (not (apply pred? elts))) vec vectors vector-index-right)) (define vector-index/skip-right (letrec ((loop1 (lambda (pred? vec i) (cond ((negative? i) #f) ((pred? (vector-ref vec i)) i) (else (loop1 pred? vec (- i 1)))))) (loop2+ (lambda (pred? vectors i) (cond ((negative? i) #f) ((apply pred? (vectors-ref vectors i)) i) (else (loop2+ pred? vectors (- i 1))))))) (lambda (pred? vec vectors callee) (let ((pred? (check-type procedure? pred? callee)) (vec (check-type vector? vec callee))) (if (null? vectors) (loop1 pred? vec (- (vector-length vec) 1)) (loop2+ pred? (cons vec vectors) (- (%smallest-length vectors (vector-length vec) callee) 1))))))) ( CMP < value1 > < value2 > ) - > integer zero - > VALUE1 = VALUE2 Perform a binary search through VECTOR for VALUE , comparing each element to VALUE with CMP . (define (vector-binary-search vec value cmp . maybe-start+end) (let ((cmp (check-type procedure? cmp vector-binary-search))) (let-vector-start+end vector-binary-search vec maybe-start+end (start end) (let loop ((start start) (end end) (j #f)) (let ((i (div (+ start end) 2))) (if (or (= start end) (and j (= i j))) #f (let ((comparison (check-type integer? (cmp (vector-ref vec i) value) `(,cmp for ,vector-binary-search)))) (cond ((zero? comparison) i) ((positive? comparison) (loop start i i)) (else (loop i end i)))))))))) ( VECTOR - ANY < pred ? > < vector > ... ) - > value (define vector-any (letrec ((loop1 (lambda (pred? vec i len len-1) (and (not (= i len)) (if (= i len-1) (pred? (vector-ref vec i)) (or (pred? (vector-ref vec i)) (loop1 pred? vec (+ i 1) len len-1)))))) (loop2+ (lambda (pred? vectors i len len-1) (and (not (= i len)) (if (= i len-1) (apply pred? (vectors-ref vectors i)) (or (apply pred? (vectors-ref vectors i)) (loop2+ pred? vectors (+ i 1) len len-1))))))) (lambda (pred? vec . vectors) (let ((pred? (check-type procedure? pred? vector-any)) (vec (check-type vector? vec vector-any))) (if (null? vectors) (let ((len (vector-length vec))) (loop1 pred? vec 0 len (- len 1))) (let ((len (%smallest-length vectors (vector-length vec) vector-any))) (loop2+ pred? (cons vec vectors) 0 len (- len 1)))))))) ( VECTOR - EVERY < pred ? > < vector > ... ) - > value (define vector-every (letrec ((loop1 (lambda (pred? vec i len len-1) (or (= i len) (if (= i len-1) (pred? (vector-ref vec i)) (and (pred? (vector-ref vec i)) (loop1 pred? vec (+ i 1) len len-1)))))) (loop2+ (lambda (pred? vectors i len len-1) (or (= i len) (if (= i len-1) (apply pred? (vectors-ref vectors i)) (and (apply pred? (vectors-ref vectors i)) (loop2+ pred? vectors (+ i 1) len len-1))))))) (lambda (pred? vec . vectors) (let ((pred? (check-type procedure? pred? vector-every)) (vec (check-type vector? vec vector-every))) (if (null? vectors) (let ((len (vector-length vec))) (loop1 pred? vec 0 len (- len 1))) (let ((len (%smallest-length vectors (vector-length vec) vector-every))) (loop2+ pred? (cons vec vectors) 0 len (- len 1)))))))) ( VECTOR - PARTITION < pred ? > < vector > ) - > vector all the elements of > that satisfy < pred ? > in their original Two values are returned , the newly allocated vector and the index (define (vector-partition pred? vec) (let* ((len (vector-length vec)) (cnt (vector-count pred? vec)) (result (make-vector len))) (let loop ((i 0) (yes 0) (no cnt)) (if (= i len) (values result cnt) (let ((elem (vector-ref vec i))) (if (pred? elem) (begin (vector-set! result yes elem) (loop (+ i 1) (+ yes 1) no)) (begin (vector-set! result no elem) (loop (+ i 1) yes (+ no 1))))))))) ( VECTOR - SWAP ! < vector > < index1 > < > ) - > unspecified Swap the values in the locations at and INDEX2 . (define (vector-swap! vec i j) (let ((vec (check-type vector? vec vector-swap!))) (let ((i (check-index vec i vector-swap!)) (j (check-index vec j vector-swap!))) (let ((x (vector-ref vec i))) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j x))))) (define $check-types (case-lambda [(who v start) (check-type vector? v who) (check-indices v start 'start (vector-length v) 'end who)] [(who v start end) (check-type vector? v who) (check-indices v start 'start end 'end who)])) ( VECTOR - FILL ! < vector > < value > [ < start > < end > ] ) - > unspecified [ R5RS+ ] Fill the locations in VECTOR between START , whose default is 0 , and END , whose default is the length of VECTOR , with VALUE . (define vector-fill! (let () (define $vector-fill! (lambda (vec value start end) (do ((i start (+ i 1))) ((= i end)) (vector-set! vec i value)))) (case-lambda [(vec value) (rnrs:vector-fill! vec value)] [(vec value start) ($check-types 'vector-fill! vec start) ($vector-fill! vec value start (vector-length vec))] [(vec value start end) ($check-types 'vector-fill! vec start end) ($vector-fill! vec value start end)]))) Copy the values in the locations in [ SSTART , SEND ) from SOURCE to to , starting at TSTART in TARGET . (define (vector-copy! target tstart source . maybe-sstart+send) (define (doit! sstart send source-length) (let ((tstart (check-type nonneg-int? tstart vector-copy!)) (sstart (check-type nonneg-int? sstart vector-copy!)) (send (check-type nonneg-int? send vector-copy!))) (cond ((and (<= 0 sstart send source-length) (<= (+ tstart (- send sstart)) (vector-length target))) (%vector-copy! target tstart source sstart send)) (else (error "illegal arguments" `(while calling ,vector-copy!) `(target was ,target) `(target-length was ,(vector-length target)) `(tstart was ,tstart) `(source was ,source) `(source-length was ,source-length) `(sstart was ,sstart) `(send was ,send)))))) (let ((n (vector-length source))) (cond ((null? maybe-sstart+send) (doit! 0 n n)) ((null? (cdr maybe-sstart+send)) (doit! (car maybe-sstart+send) n n)) ((null? (cddr maybe-sstart+send)) (doit! (car maybe-sstart+send) (cadr maybe-sstart+send) n)) (else (error "too many arguments" vector-copy! (cddr maybe-sstart+send)))))) (define (vector-reverse-copy! target tstart source . maybe-sstart+send) (define (doit! sstart send source-length) (let ((tstart (check-type nonneg-int? tstart vector-reverse-copy!)) (sstart (check-type nonneg-int? sstart vector-reverse-copy!)) (send (check-type nonneg-int? send vector-reverse-copy!))) (cond ((and (eq? target source) (or (between? sstart tstart send) (between? tstart sstart (+ tstart (- send sstart))))) (error "vector range for self-copying overlaps" vector-reverse-copy! `(vector was ,target) `(tstart was ,tstart) `(sstart was ,sstart) `(send was ,send))) ((and (<= 0 sstart send source-length) (<= (+ tstart (- send sstart)) (vector-length target))) (%vector-reverse-copy! target tstart source sstart send)) (else (error "illegal arguments" `(while calling ,vector-reverse-copy!) `(target was ,target) `(target-length was ,(vector-length target)) `(tstart was ,tstart) `(source was ,source) `(source-length was ,source-length) `(sstart was ,sstart) `(send was ,send)))))) (let ((n (vector-length source))) (cond ((null? maybe-sstart+send) (doit! 0 n n)) ((null? (cdr maybe-sstart+send)) (doit! (car maybe-sstart+send) n n)) ((null? (cddr maybe-sstart+send)) (doit! (car maybe-sstart+send) (cadr maybe-sstart+send) n)) (else (error "too many arguments" vector-reverse-copy! (cddr maybe-sstart+send)))))) ( VECTOR - REVERSE ! < vector > [ < start > < end > ] ) - > unspecified reverse the contents of the sequence of locations in VECTOR between START , whose default is 0 , and END , whose default is the length of VECTOR . (define (vector-reverse! vec . start+end) (let-vector-start+end vector-reverse! vec start+end (start end) (%vector-reverse! vec start end))) between START , whose default is 0 , and END , whose default is the length of VECTOR , from VECTOR . (define vector->list (let () (define ($vector->list vec start end) (do ((i (- end 1) (- i 1)) (result '() (cons (vector-ref vec i) result))) ((< i start) result))) (case-lambda [(vec) (rnrs:vector->list vec)] [(vec start) ($check-types 'vector->list vec start) ($vector->list vec start (vector-length vec))] [(vec start end) ($check-types 'vector->list vec start end) ($vector->list vec start (vector-length vec))]))) START , whose default is 0 , and END , whose default is the length of VECTOR , from VECTOR , in reverse order . (define (reverse-vector->list vec . maybe-start+end) (let-vector-start+end reverse-vector->list vec maybe-start+end (start end) (do ((i start (+ i 1)) (result '() (cons (vector-ref vec i) result))) ((= i end) result)))) must be a proper list , between START , whose default is 0 , & END , length of LIST is known in advance , the START and END arguments (define list->vector (case-lambda [(lst) (rnrs:list->vector lst)] [(lst start) (check-type nonneg-int? start list->vector) (rnrs:list->vector (list-tail lst start))] [(lst start end) (check-type nonneg-int? start list->vector) (check-type nonneg-int? end list->vector) NB : should be fx < ? (unless (<= start end) (error 'list->vector "start is greater than end" start end)) (let ([len (- end start)]) (let ([v (make-vector len)]) (let loop ([i 0] [ls (list-tail lst start)]) (unless (= i len) (unless (pair? ls) (if (null? ls) (error 'list->vector "list too short" lst start end) (error 'list->vector "improper list" lst))) (vector-set! v i (car ls)) (loop (fx+ i 1) (cdr ls)))) v))])) proper list , between START , whose default is 0 , and END , whose that if the length of LIST is known in advance , the START and END (define (reverse-list->vector lst . maybe-start+end) (let*-optionals maybe-start+end ((start 0) (let ((start (check-type nonneg-int? start reverse-list->vector)) (end (check-type nonneg-int? end reverse-list->vector))) ((lambda (f) (vector-unfold-right f (- end start) (list-tail lst start))) (lambda (index l) (cond ((null? l) (error "list too short" `(list was ,lst) `(attempted end was ,end) `(while calling ,reverse-list->vector))) ((pair? l) (values (car l) (cdr l))) (else (error "erroneous value" (list list? lst) `(while calling ,reverse-list->vector))))))))) between START , whose default is 0 , and END , whose default is the length of VECTOR , from VECTOR . (define (vector->string vec . maybe-start+end) (let* ((len (vector-length vec)) (start (if (null? maybe-start+end) 0 (car maybe-start+end))) (end (if (null? maybe-start+end) len (if (null? (cdr maybe-start+end)) len (cadr maybe-start+end)))) (size (- end start))) (define result (make-string size)) (let loop ((at 0) (i start)) (if (= i end) result (begin (string-set! result at (vector-ref vec i)) (loop (+ at 1) (+ i 1))))))) between START , whose default is 0 , & END , (define (string->vector str . maybe-start+end) (let* ((len (string-length str)) (start (if (null? maybe-start+end) 0 (car maybe-start+end))) (end (if (null? maybe-start+end) len (if (null? (cdr maybe-start+end)) len (cadr maybe-start+end)))) (size (- end start))) (define result (make-vector size)) (let loop ((at 0) (i start)) (if (= i end) result (begin (vector-set! result at (string-ref str i)) (loop (+ at 1) (+ i 1)))))))
70619af80bd8bb93623503bdc93e9e951678b7ce90c8443e9f8660600045b192
GlideAngle/flare-timing
FsEffortOptions.hs
module FsEffortOptions (description) where import Text.RawString.QQ (r) import Flight.Cmd.Options (Description(..)) description :: Description description = Description [r| Extracts the distance difficulty chunking from a competition. |]
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/flare-timing/prod-apps/fs-effort/FsEffortOptions.hs
haskell
module FsEffortOptions (description) where import Text.RawString.QQ (r) import Flight.Cmd.Options (Description(..)) description :: Description description = Description [r| Extracts the distance difficulty chunking from a competition. |]
e137692bb1d80268a5d6c09749b793979d9b2b9083b73d46f4825d560d9a7702
bnoordhuis/chicken-core
compiler-tests-3.scm
;;; compiler-tests-3.scm - tests for unboxing ;;; unboxing introduced binding in test-position of conditional MBROT -- Generation of set fractal . (define (count r i step x y) (let ((max-count 64) (radius^2 16.0)) (let ((cr (fp+ r (fp* (exact->inexact x) step))) (ci (fp+ i (fp* (exact->inexact y) step)))) (let loop ((zr cr) (zi ci) (c 0)) (if (= c max-count) c (let ((zr^2 (fp* zr zr)) (zi^2 (fp* zi zi))) (if (fp> (fp+ zr^2 zi^2) radius^2) c (let ((new-zr (fp+ (fp- zr^2 zi^2) cr)) (new-zi (fp+ (fp* 2.0 (fp* zr zi)) ci))) (loop new-zr new-zi (+ c 1)))))))))) (define (mbrot matrix r i step n) (let loop1 ((y (- n 1))) (if (>= y 0) (let loop2 ((x (- n 1))) (if (>= x 0) (begin (vector-set! (vector-ref matrix x) y (count r i step x y)) (loop2 (- x 1))) (loop1 (- y 1))))))) (define (test n) (let ((matrix (make-vector n))) (let loop ((i (- n 1))) (if (>= i 0) (begin (vector-set! matrix i (make-vector n)) (loop (- i 1))))) (mbrot matrix -1.0 -0.5 0.005 n) (vector-ref (vector-ref matrix 0) 0))) (define (main . args) (let ((r (test 75))) (unless (equal? r 5) (error "incorrect result: " r))))
null
https://raw.githubusercontent.com/bnoordhuis/chicken-core/56d30e3be095b6abe1bddcfe10505fa726a43bb5/tests/compiler-tests-3.scm
scheme
compiler-tests-3.scm - tests for unboxing unboxing introduced binding in test-position of conditional
MBROT -- Generation of set fractal . (define (count r i step x y) (let ((max-count 64) (radius^2 16.0)) (let ((cr (fp+ r (fp* (exact->inexact x) step))) (ci (fp+ i (fp* (exact->inexact y) step)))) (let loop ((zr cr) (zi ci) (c 0)) (if (= c max-count) c (let ((zr^2 (fp* zr zr)) (zi^2 (fp* zi zi))) (if (fp> (fp+ zr^2 zi^2) radius^2) c (let ((new-zr (fp+ (fp- zr^2 zi^2) cr)) (new-zi (fp+ (fp* 2.0 (fp* zr zi)) ci))) (loop new-zr new-zi (+ c 1)))))))))) (define (mbrot matrix r i step n) (let loop1 ((y (- n 1))) (if (>= y 0) (let loop2 ((x (- n 1))) (if (>= x 0) (begin (vector-set! (vector-ref matrix x) y (count r i step x y)) (loop2 (- x 1))) (loop1 (- y 1))))))) (define (test n) (let ((matrix (make-vector n))) (let loop ((i (- n 1))) (if (>= i 0) (begin (vector-set! matrix i (make-vector n)) (loop (- i 1))))) (mbrot matrix -1.0 -0.5 0.005 n) (vector-ref (vector-ref matrix 0) 0))) (define (main . args) (let ((r (test 75))) (unless (equal? r 5) (error "incorrect result: " r))))
37712144145991e6d025e2ea8a2d80912d1b83913607b53f43fb09f3e62c64be
pixlsus/registry.gimp.org_static
SPMdeframe.scm
; ------------------------------------------------------------------------------ Find & remove white framing from Stereophotomaker images ; ( c ) 2008 Stenschke < > ; All rights reserved ; ; This script is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ; (at your option) any later version. ; The GNU General Public License can be found at ; . ; ; ; Changelog: (add new entries on top) V1.1 ( 2008 - 26 - 08 ) Changed script registration from Gimp 's toolbox window to a new sub menu " Script - Fu " inside the image window V1.0 ( 2008 - 18 - 08 ) Tested and working with Gimp 2.4.5 ; ------------------------------------------------------------------------------ (define (script-fu-SPMdeframe img drawable) (let* ; @note: Scope of the following variables ends with mathching brace to the one before "let*" ( (width (car (gimp-drawable-width drawable))) ;image width (height (car (gimp-drawable-height drawable))) ;image height (oldFg (car (gimp-palette-get-foreground) ) ) ;foreground color before this script (oldBg (car (gimp-palette-get-background) ) ) (x 0) ;set up test point x (y 0) ;set up test point y (test 255) ;result of colorpicked pixel (test_red 0) ;RGB components and sum (test_blue 0) (test_green 0) (sum_rgb 0) (notFound TRUE) ;found border's end? (isBlack TRUE) ;scanned pixel is black? ) ; ------------------------------------------------------------ (gimp-context-set-default-colors) ;set to b/w ; -------------------------------------------------------------- find & remove topmost border: init y (set! x 40) ;init x (set! notFound TRUE) (while (and(< y 50) notFound) ;scanning will go top to bottom, while not found (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) (set! test_red (car (car test))) ;red (set! test_blue (cadr (car test))) ;blue (set! test_green (caddr (car test))) ;green (set! sum_rgb (+ test_red test_blue test_green) ) ;calc sum of r+b+g (set! notFound (> sum_rgb 0) ) ;is black? => frame end found (set! y (+ y 1)) ;increment y @note : incrementation goes one px too far , that s ok because it 'll comprehend the rounded corners (gimp-rect-select img 0 0 width y REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black ;topmost border found & removed. ; -------------------------------------------------------------- cut equally at the bottom: (gimp-rect-select img 0 (- height y) width y REPLACE FALSE 0) ;select area ;@note: gimp-rect-select does only select from left->right, top->bottom! (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black ;bottom border removed. ; -------------------------------------------------------------- find & remove left border: init y (set! x 1) ;init x (set! notFound TRUE) (while (and(< x 50) notFound) ;scanning will go top to bottom, while not found (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) (set! test_red (car (car test))) ;red (set! test_blue (cadr (car test))) ;blue (set! test_green (caddr (car test))) ;green (set! sum_rgb (+ test_red test_blue test_green) ) ;calc sum of r+b+g (set! notFound (> sum_rgb 0) ) ;is black? => frame end found (set! x (+ x 1)) ;increment x @note : incrementation goes one px too far , that s ok because it 'll comprehend the rounded corners (gimp-rect-select img 0 0 x height REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black ;left border found & removed. ; -------------------------------------------------------------- cut equally at the right border: (gimp-rect-select img (- width x) 0 x height REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black ;right border removed. ; -------------------------------------------------------------- remove vertical middle line: (gimp-rect-select img (- (/ width 2) 28) 0 56 height REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black vertical middle line removed . ; -------------------------------------------------------------- find & remove white line at images top border: (define ( removeOnePxFromTopOfImages ) init y (set! x 100) ;init x (set! isBlack TRUE) (while (and(< y 50) isBlack) ;scanning will go top to bottom, while not found (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ;params: image, drawable, x, y, Use the composite image, not the drawable, ; average the color of all the pixels in a specified radius (TRUE or FALSE), radius (set! test_red (car (car test))) ;red (set! test_blue (cadr (car test))) ;blue (set! test_green (caddr (car test))) ;green (set! sum_rgb (+ test_red test_blue test_green) ) ;calc sum of r+b+g (set! isBlack (< sum_rgb 5) ) ;is black? => white line not found yet (set! y (+ y 1)) ;increment y ) (set! y (+ y 1)) ;increment y (gimp-rect-select img 0 0 width y REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black 1 pixel white line at top of images found & removed . ) (removeOnePxFromTopOfImages) (removeOnePxFromTopOfImages) (removeOnePxFromTopOfImages) (removeOnePxFromTopOfImages) ; -------------------------------------------------------------- find & remove white line at images bottom border: (define ( removeOnePxFromBottomOfImages ) init y (set! x 100) ;init x (set! isBlack TRUE) (while (and(> y (- height 50)) isBlack) ;scanning will go top to bottom, while not found (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ;params: image, drawable, x, y, Use the composite image, not the drawable, ; average the color of all the pixels in a specified radius (TRUE or FALSE), radius (set! test_red (car (car test))) ;red (set! test_blue (cadr (car test))) ;blue (set! test_green (caddr (car test))) ;green (set! sum_rgb (+ test_red test_blue test_green) ) ;calc sum of r+b+g (set! isBlack (< sum_rgb 5) ) ;is black? => white line not found yet (set! y (- y 1)) ;increment y ) (gimp-rect-select img 0 y width (- height y) REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black 1 pixel white line at bottom of images found & removed . ) (removeOnePxFromBottomOfImages) (removeOnePxFromBottomOfImages) (removeOnePxFromBottomOfImages) (removeOnePxFromBottomOfImages) ; -------------------------------------------------------------- find & remove white line at left border: (define ( removeOnePxFromLeftOfImage ) init y (set! y 100) ;init x (set! isBlack TRUE) (while (and(< x 50) isBlack) ;scanning will go top to bottom, while not found (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ;params: image, drawable, x, y, Use the composite image, not the drawable, ; average the color of all the pixels in a specified radius (TRUE or FALSE), radius (set! test_red (car (car test))) ;red (set! test_blue (cadr (car test))) ;blue (set! test_green (caddr (car test))) ;green (set! sum_rgb (+ test_red test_blue test_green) ) ;calc sum of r+b+g (set! isBlack (< sum_rgb 5) ) ;is black? => white line not found yet (set! x (+ x 1)) ;increment x ) (set! x (+ x 1)) ;increment x (gimp-rect-select img 0 0 x height REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black 1 pixel white line at left of left image found & removed . ) (removeOnePxFromLeftOfImage) (removeOnePxFromLeftOfImage) (removeOnePxFromLeftOfImage) (removeOnePxFromLeftOfImage) ; -------------------------------------------------------------- find & remove white line at right border: (define ( removeOnePxFromRightOfImage ) init y (set! y 100) ;init x (set! isBlack TRUE) (while (and(> x (- width 50)) isBlack) ;scanning will go top to bottom, while not found (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ;params: image, drawable, x, y, Use the composite image, not the drawable, ; average the color of all the pixels in a specified radius (TRUE or FALSE), radius (set! test_red (car (car test))) ;red (set! test_blue (cadr (car test))) ;blue (set! test_green (caddr (car test))) ;green (set! sum_rgb (+ test_red test_blue test_green) ) ;calc sum of r+b+g (set! isBlack (< sum_rgb 5) ) ;is black? => white line not found yet (set! x (- x 1)) ;increment x ) (gimp-rect-select img x 0 (- width x) height REPLACE FALSE 0) ;select area (gimp-edit-fill drawable FOREGROUND-FILL) ;fill rect with black 1 pixel white line at right of right image found & removed . ) (removeOnePxFromRightOfImage) (removeOnePxFromRightOfImage) (removeOnePxFromRightOfImage) (removeOnePxFromRightOfImage) ; -------------------------------------------------------------- done. cleanup: (gimp-palette-set-background oldBg) ;restore old fg/bg colors (gimp-palette-set-foreground oldFg) ) (gimp-displays-flush) ;flush output ) ; ---------------------------------------------------------------------- register (into image/Script-Fu menu): (script-fu-register "script-fu-SPMdeframe" _"<Image>/Script-Fu/Stereo imaging/Remove stereophotomaker borders" "Find & remove white framing from Stereophotomaker images (image pairs)" "Kay Stenschke <>" "Kay Stenschke" "2008-18-08" "RGB*, GRAY*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 ) ; ----------------------------------------------------------------------
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/SPMdeframe.scm
scheme
------------------------------------------------------------------------------ All rights reserved This script is free software; you can redistribute it and/or modify either version 3 of the License , or (at your option) any later version. . Changelog: (add new entries on top) ------------------------------------------------------------------------------ @note: Scope of the following variables ends with mathching brace to the one before "let*" image width image height foreground color before this script set up test point x set up test point y result of colorpicked pixel RGB components and sum found border's end? scanned pixel is black? ------------------------------------------------------------ set to b/w -------------------------------------------------------------- find & remove topmost border: init x scanning will go top to bottom, while not found red blue green calc sum of r+b+g is black? => frame end found increment y select area fill rect with black topmost border found & removed. -------------------------------------------------------------- cut equally at the bottom: select area @note: gimp-rect-select does only select from left->right, top->bottom! fill rect with black bottom border removed. -------------------------------------------------------------- find & remove left border: init x scanning will go top to bottom, while not found red blue green calc sum of r+b+g is black? => frame end found increment x select area fill rect with black left border found & removed. -------------------------------------------------------------- cut equally at the right border: select area fill rect with black right border removed. -------------------------------------------------------------- remove vertical middle line: select area fill rect with black -------------------------------------------------------------- find & remove white line at images top border: init x scanning will go top to bottom, while not found params: image, drawable, x, y, Use the composite image, not the drawable, average the color of all the pixels in a specified radius (TRUE or FALSE), radius red blue green calc sum of r+b+g is black? => white line not found yet increment y increment y select area fill rect with black -------------------------------------------------------------- find & remove white line at images bottom border: init x scanning will go top to bottom, while not found params: image, drawable, x, y, Use the composite image, not the drawable, average the color of all the pixels in a specified radius (TRUE or FALSE), radius red blue green calc sum of r+b+g is black? => white line not found yet increment y select area fill rect with black -------------------------------------------------------------- find & remove white line at left border: init x scanning will go top to bottom, while not found params: image, drawable, x, y, Use the composite image, not the drawable, average the color of all the pixels in a specified radius (TRUE or FALSE), radius red blue green calc sum of r+b+g is black? => white line not found yet increment x increment x select area fill rect with black -------------------------------------------------------------- find & remove white line at right border: init x scanning will go top to bottom, while not found params: image, drawable, x, y, Use the composite image, not the drawable, average the color of all the pixels in a specified radius (TRUE or FALSE), radius red blue green calc sum of r+b+g is black? => white line not found yet increment x select area fill rect with black -------------------------------------------------------------- done. cleanup: restore old fg/bg colors flush output ---------------------------------------------------------------------- register (into image/Script-Fu menu): ----------------------------------------------------------------------
Find & remove white framing from Stereophotomaker images ( c ) 2008 Stenschke < > it under the terms of the GNU General Public License as published by The GNU General Public License can be found at V1.1 ( 2008 - 26 - 08 ) Changed script registration from Gimp 's toolbox window to a new sub menu " Script - Fu " inside the image window V1.0 ( 2008 - 18 - 08 ) Tested and working with Gimp 2.4.5 (define (script-fu-SPMdeframe img drawable) (oldBg (car (gimp-palette-get-background) ) ) (test_blue 0) (test_green 0) (sum_rgb 0) init y (set! notFound TRUE) (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) @note : incrementation goes one px too far , that s ok because it 'll comprehend the rounded corners init y (set! notFound TRUE) (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) @note : incrementation goes one px too far , that s ok because it 'll comprehend the rounded corners vertical middle line removed . (define ( removeOnePxFromTopOfImages ) init y (set! isBlack TRUE) (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ) 1 pixel white line at top of images found & removed . ) (removeOnePxFromTopOfImages) (removeOnePxFromTopOfImages) (removeOnePxFromTopOfImages) (removeOnePxFromTopOfImages) (define ( removeOnePxFromBottomOfImages ) init y (set! isBlack TRUE) (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ) 1 pixel white line at bottom of images found & removed . ) (removeOnePxFromBottomOfImages) (removeOnePxFromBottomOfImages) (removeOnePxFromBottomOfImages) (removeOnePxFromBottomOfImages) (define ( removeOnePxFromLeftOfImage ) init y (set! isBlack TRUE) (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ) 1 pixel white line at left of left image found & removed . ) (removeOnePxFromLeftOfImage) (removeOnePxFromLeftOfImage) (removeOnePxFromLeftOfImage) (removeOnePxFromLeftOfImage) (define ( removeOnePxFromRightOfImage ) init y (set! isBlack TRUE) (set! test (gimp-image-pick-color img drawable x y TRUE TRUE 1)) ) 1 pixel white line at right of right image found & removed . ) (removeOnePxFromRightOfImage) (removeOnePxFromRightOfImage) (removeOnePxFromRightOfImage) (removeOnePxFromRightOfImage) (gimp-palette-set-foreground oldFg) ) (script-fu-register "script-fu-SPMdeframe" _"<Image>/Script-Fu/Stereo imaging/Remove stereophotomaker borders" "Find & remove white framing from Stereophotomaker images (image pairs)" "Kay Stenschke <>" "Kay Stenschke" "2008-18-08" "RGB*, GRAY*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0
b04801e54c59bd294442570bf84ab6feedf76766b519d3e6959f3a98d75a9395
cyga/real-world-haskell
num.orig.hs
-- file: ch13/num.hs import Data.List -------------------------------------------------- -- Symbolic/units manipulation -------------------------------------------------- -- The "operators" that we're going to support data Op = Plus | Minus | Mul | Div | Pow deriving (Eq, Show) The core symbolic manipulation type . It can be a simple number , a symbol , a binary arithmetic operation ( such as + ) , or a unary arithmetic operation ( such as cos ) Notice the types of BinaryArith and UnaryArith : it 's a recursive type . So , we could represent a ( + ) over two SymbolicManips . a symbol, a binary arithmetic operation (such as +), or a unary arithmetic operation (such as cos) Notice the types of BinaryArith and UnaryArith: it's a recursive type. So, we could represent a (+) over two SymbolicManips. -} data SymbolicManip a = Simple number , such as 5 | Symbol String -- A symbol, such as x | BinaryArith Op (SymbolicManip a) (SymbolicManip a) | UnaryArith String (SymbolicManip a) deriving (Eq) -- file: ch13/num.hs SymbolicManip will be an instance of . Define how the operations are handled over a SymbolicManip . This will implement things like ( + ) for SymbolicManip . operations are handled over a SymbolicManip. This will implement things like (+) for SymbolicManip. -} instance Num a => Num (SymbolicManip a) where a + b = BinaryArith Plus a b a - b = BinaryArith Minus a b a * b = BinaryArith Mul a b negate a = BinaryArith Mul (Number (-1)) a abs a = UnaryArith "abs" a signum _ = error "signum is unimplemented" fromInteger i = Number (fromInteger i) -- file: ch13/num.hs {- Make SymbolicManip an instance of Fractional -} instance (Fractional a) => Fractional (SymbolicManip a) where a / b = BinaryArith Div a b recip a = BinaryArith Div (Number 1) a fromRational r = Number (fromRational r) {- Make SymbolicManip an instance of Floating -} instance (Floating a) => Floating (SymbolicManip a) where pi = Symbol "pi" exp a = UnaryArith "exp" a log a = UnaryArith "log" a sqrt a = UnaryArith "sqrt" a a ** b = BinaryArith Pow a b sin a = UnaryArith "sin" a cos a = UnaryArith "cos" a tan a = UnaryArith "tan" a asin a = UnaryArith "asin" a acos a = UnaryArith "acos" a atan a = UnaryArith "atan" a sinh a = UnaryArith "sinh" a cosh a = UnaryArith "cosh" a tanh a = UnaryArith "tanh" a asinh a = UnaryArith "asinh" a acosh a = UnaryArith "acosh" a atanh a = UnaryArith "atanh" a -- file: ch13/num.hs {- Show a SymbolicManip as a String, using conventional algebraic notation -} prettyShow :: (Show a, Num a) => SymbolicManip a -> String -- Show a number or symbol as a bare number or serial prettyShow (Number x) = show x prettyShow (Symbol x) = x prettyShow (BinaryArith op a b) = let pa = simpleParen a pb = simpleParen b pop = op2str op in pa ++ pop ++ pb prettyShow (UnaryArith opstr a) = opstr ++ "(" ++ show a ++ ")" op2str :: Op -> String op2str Plus = "+" op2str Minus = "-" op2str Mul = "*" op2str Div = "/" op2str Pow = "**" Add parenthesis where needed . This function is fairly conservative and will add parenthesis when not needed in some cases . will have already figured out precedence for us while building up the SymbolicManip . and will add parenthesis when not needed in some cases. Haskell will have already figured out precedence for us while building up the SymbolicManip. -} simpleParen :: (Show a, Num a) => SymbolicManip a -> String simpleParen (Number x) = prettyShow (Number x) simpleParen (Symbol x) = prettyShow (Symbol x) simpleParen x@(BinaryArith _ _ _) = "(" ++ prettyShow x ++ ")" simpleParen x@(UnaryArith _ _) = prettyShow x {- Showing a SymbolicManip calls the prettyShow function on it -} instance (Show a, Num a) => Show (SymbolicManip a) where show a = prettyShow a -- file: ch13/num.hs Show a SymbolicManip using RPN . HP calculator users may find this familiar . find this familiar. -} rpnShow :: (Show a, Num a) => SymbolicManip a -> String rpnShow i = let toList (Number x) = [show x] toList (Symbol x) = [x] toList (BinaryArith op a b) = toList a ++ toList b ++ [op2str op] toList (UnaryArith op a) = toList a ++ [op] join :: [a] -> [[a]] -> [a] join delim l = concat (intersperse delim l) in join " " (toList i) -- file: ch13/num.hs {- Perform some basic algebraic simplifications on a SymbolicManip. -} simplify :: (Num a) => SymbolicManip a -> SymbolicManip a simplify (BinaryArith op ia ib) = let sa = simplify ia sb = simplify ib in case (op, sa, sb) of (Mul, Number 1, b) -> b (Mul, a, Number 1) -> a (Mul, Number 0, b) -> Number 0 (Mul, a, Number 0) -> Number 0 (Div, a, Number 1) -> a (Plus, a, Number 0) -> a (Plus, Number 0, b) -> b (Minus, a, Number 0) -> a _ -> BinaryArith op sa sb simplify (UnaryArith op a) = UnaryArith op (simplify a) simplify x = x -- file: ch13/num.hs {- New data type: Units. A Units type contains a number and a SymbolicManip, which represents the units of measure. A simple label would be something like (Symbol "m") -} data Num a => Units a = Units a (SymbolicManip a) deriving (Eq) -- file: ch13/num.hs Implement Units for . We do n't know how to convert between arbitrary units , so we generate an error if we try to add numbers with different units . For multiplication , generate the appropriate new units . arbitrary units, so we generate an error if we try to add numbers with different units. For multiplication, generate the appropriate new units. -} instance (Num a) => Num (Units a) where (Units xa ua) + (Units xb ub) | ua == ub = Units (xa + xb) ua | otherwise = error "Mis-matched units in add or subtract" (Units xa ua) - (Units xb ub) = (Units xa ua) + (Units (xb * (-1)) ub) (Units xa ua) * (Units xb ub) = Units (xa * xb) (ua * ub) negate (Units xa ua) = Units (negate xa) ua abs (Units xa ua) = Units (abs xa) ua signum (Units xa _) = Units (signum xa) (Number 1) fromInteger i = Units (fromInteger i) (Number 1) -- file: ch13/num.hs {- Make Units an instance of Fractional -} instance (Fractional a) => Fractional (Units a) where (Units xa ua) / (Units xb ub) = Units (xa / xb) (ua / ub) recip a = 1 / a fromRational r = Units (fromRational r) (Number 1) Floating implementation for Units . Use some intelligence for angle calculations : support deg and Use some intelligence for angle calculations: support deg and rad -} instance (Floating a) => Floating (Units a) where pi = (Units pi (Number 1)) exp _ = error "exp not yet implemented in Units" log _ = error "log not yet implemented in Units" (Units xa ua) ** (Units xb ub) | ub == Number 1 = Units (xa ** xb) (ua ** Number xb) | otherwise = error "units for RHS of ** not supported" sqrt (Units xa ua) = Units (sqrt xa) (sqrt ua) sin (Units xa ua) | ua == Symbol "rad" = Units (sin xa) (Number 1) | ua == Symbol "deg" = Units (sin (deg2rad xa)) (Number 1) | otherwise = error "Units for sin must be deg or rad" cos (Units xa ua) | ua == Symbol "rad" = Units (cos xa) (Number 1) | ua == Symbol "deg" = Units (cos (deg2rad xa)) (Number 1) | otherwise = error "Units for cos must be deg or rad" tan (Units xa ua) | ua == Symbol "rad" = Units (tan xa) (Number 1) | ua == Symbol "deg" = Units (tan (deg2rad xa)) (Number 1) | otherwise = error "Units for tan must be deg or rad" asin (Units xa ua) | ua == Number 1 = Units (rad2deg $ asin xa) (Symbol "deg") | otherwise = error "Units for asin must be empty" acos (Units xa ua) | ua == Number 1 = Units (rad2deg $ acos xa) (Symbol "deg") | otherwise = error "Units for acos must be empty" atan (Units xa ua) | ua == Number 1 = Units (rad2deg $ atan xa) (Symbol "deg") | otherwise = error "Units for atan must be empty" sinh = error "sinh not yet implemented in Units" cosh = error "cosh not yet implemented in Units" tanh = error "tanh not yet implemented in Units" asinh = error "asinh not yet implemented in Units" acosh = error "acosh not yet implemented in Units" atanh = error "atanh not yet implemented in Units" -- file: ch13/num.hs {- A simple function that takes a number and a String and returns an appropriate Units type to represent the number and its unit of measure -} units :: (Num z) => z -> String -> Units z units a b = Units a (Symbol b) {- Extract the number only out of a Units type -} dropUnits :: (Num z) => Units z -> z dropUnits (Units x _) = x {- Utilities for the Unit implementation -} deg2rad x = 2 * pi * x / 360 rad2deg x = 360 * x / (2 * pi) -- file: ch13/num.hs {- Showing units: we show the numeric component, an underscore, then the prettyShow version of the simplified units -} instance (Show a, Num a) => Show (Units a) where show (Units xa ua) = show xa ++ "_" ++ prettyShow (simplify ua) -- file: ch13/num.hs test :: (Num a) => a test = 2 * 5 + 3
null
https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch13/num.orig.hs
haskell
file: ch13/num.hs ------------------------------------------------ Symbolic/units manipulation ------------------------------------------------ The "operators" that we're going to support A symbol, such as x file: ch13/num.hs file: ch13/num.hs Make SymbolicManip an instance of Fractional Make SymbolicManip an instance of Floating file: ch13/num.hs Show a SymbolicManip as a String, using conventional algebraic notation Show a number or symbol as a bare number or serial Showing a SymbolicManip calls the prettyShow function on it file: ch13/num.hs file: ch13/num.hs Perform some basic algebraic simplifications on a SymbolicManip. file: ch13/num.hs New data type: Units. A Units type contains a number and a SymbolicManip, which represents the units of measure. A simple label would be something like (Symbol "m") file: ch13/num.hs file: ch13/num.hs Make Units an instance of Fractional file: ch13/num.hs A simple function that takes a number and a String and returns an appropriate Units type to represent the number and its unit of measure Extract the number only out of a Units type Utilities for the Unit implementation file: ch13/num.hs Showing units: we show the numeric component, an underscore, then the prettyShow version of the simplified units file: ch13/num.hs
import Data.List data Op = Plus | Minus | Mul | Div | Pow deriving (Eq, Show) The core symbolic manipulation type . It can be a simple number , a symbol , a binary arithmetic operation ( such as + ) , or a unary arithmetic operation ( such as cos ) Notice the types of BinaryArith and UnaryArith : it 's a recursive type . So , we could represent a ( + ) over two SymbolicManips . a symbol, a binary arithmetic operation (such as +), or a unary arithmetic operation (such as cos) Notice the types of BinaryArith and UnaryArith: it's a recursive type. So, we could represent a (+) over two SymbolicManips. -} data SymbolicManip a = Simple number , such as 5 | BinaryArith Op (SymbolicManip a) (SymbolicManip a) | UnaryArith String (SymbolicManip a) deriving (Eq) SymbolicManip will be an instance of . Define how the operations are handled over a SymbolicManip . This will implement things like ( + ) for SymbolicManip . operations are handled over a SymbolicManip. This will implement things like (+) for SymbolicManip. -} instance Num a => Num (SymbolicManip a) where a + b = BinaryArith Plus a b a - b = BinaryArith Minus a b a * b = BinaryArith Mul a b negate a = BinaryArith Mul (Number (-1)) a abs a = UnaryArith "abs" a signum _ = error "signum is unimplemented" fromInteger i = Number (fromInteger i) instance (Fractional a) => Fractional (SymbolicManip a) where a / b = BinaryArith Div a b recip a = BinaryArith Div (Number 1) a fromRational r = Number (fromRational r) instance (Floating a) => Floating (SymbolicManip a) where pi = Symbol "pi" exp a = UnaryArith "exp" a log a = UnaryArith "log" a sqrt a = UnaryArith "sqrt" a a ** b = BinaryArith Pow a b sin a = UnaryArith "sin" a cos a = UnaryArith "cos" a tan a = UnaryArith "tan" a asin a = UnaryArith "asin" a acos a = UnaryArith "acos" a atan a = UnaryArith "atan" a sinh a = UnaryArith "sinh" a cosh a = UnaryArith "cosh" a tanh a = UnaryArith "tanh" a asinh a = UnaryArith "asinh" a acosh a = UnaryArith "acosh" a atanh a = UnaryArith "atanh" a prettyShow :: (Show a, Num a) => SymbolicManip a -> String prettyShow (Number x) = show x prettyShow (Symbol x) = x prettyShow (BinaryArith op a b) = let pa = simpleParen a pb = simpleParen b pop = op2str op in pa ++ pop ++ pb prettyShow (UnaryArith opstr a) = opstr ++ "(" ++ show a ++ ")" op2str :: Op -> String op2str Plus = "+" op2str Minus = "-" op2str Mul = "*" op2str Div = "/" op2str Pow = "**" Add parenthesis where needed . This function is fairly conservative and will add parenthesis when not needed in some cases . will have already figured out precedence for us while building up the SymbolicManip . and will add parenthesis when not needed in some cases. Haskell will have already figured out precedence for us while building up the SymbolicManip. -} simpleParen :: (Show a, Num a) => SymbolicManip a -> String simpleParen (Number x) = prettyShow (Number x) simpleParen (Symbol x) = prettyShow (Symbol x) simpleParen x@(BinaryArith _ _ _) = "(" ++ prettyShow x ++ ")" simpleParen x@(UnaryArith _ _) = prettyShow x instance (Show a, Num a) => Show (SymbolicManip a) where show a = prettyShow a Show a SymbolicManip using RPN . HP calculator users may find this familiar . find this familiar. -} rpnShow :: (Show a, Num a) => SymbolicManip a -> String rpnShow i = let toList (Number x) = [show x] toList (Symbol x) = [x] toList (BinaryArith op a b) = toList a ++ toList b ++ [op2str op] toList (UnaryArith op a) = toList a ++ [op] join :: [a] -> [[a]] -> [a] join delim l = concat (intersperse delim l) in join " " (toList i) simplify :: (Num a) => SymbolicManip a -> SymbolicManip a simplify (BinaryArith op ia ib) = let sa = simplify ia sb = simplify ib in case (op, sa, sb) of (Mul, Number 1, b) -> b (Mul, a, Number 1) -> a (Mul, Number 0, b) -> Number 0 (Mul, a, Number 0) -> Number 0 (Div, a, Number 1) -> a (Plus, a, Number 0) -> a (Plus, Number 0, b) -> b (Minus, a, Number 0) -> a _ -> BinaryArith op sa sb simplify (UnaryArith op a) = UnaryArith op (simplify a) simplify x = x data Num a => Units a = Units a (SymbolicManip a) deriving (Eq) Implement Units for . We do n't know how to convert between arbitrary units , so we generate an error if we try to add numbers with different units . For multiplication , generate the appropriate new units . arbitrary units, so we generate an error if we try to add numbers with different units. For multiplication, generate the appropriate new units. -} instance (Num a) => Num (Units a) where (Units xa ua) + (Units xb ub) | ua == ub = Units (xa + xb) ua | otherwise = error "Mis-matched units in add or subtract" (Units xa ua) - (Units xb ub) = (Units xa ua) + (Units (xb * (-1)) ub) (Units xa ua) * (Units xb ub) = Units (xa * xb) (ua * ub) negate (Units xa ua) = Units (negate xa) ua abs (Units xa ua) = Units (abs xa) ua signum (Units xa _) = Units (signum xa) (Number 1) fromInteger i = Units (fromInteger i) (Number 1) instance (Fractional a) => Fractional (Units a) where (Units xa ua) / (Units xb ub) = Units (xa / xb) (ua / ub) recip a = 1 / a fromRational r = Units (fromRational r) (Number 1) Floating implementation for Units . Use some intelligence for angle calculations : support deg and Use some intelligence for angle calculations: support deg and rad -} instance (Floating a) => Floating (Units a) where pi = (Units pi (Number 1)) exp _ = error "exp not yet implemented in Units" log _ = error "log not yet implemented in Units" (Units xa ua) ** (Units xb ub) | ub == Number 1 = Units (xa ** xb) (ua ** Number xb) | otherwise = error "units for RHS of ** not supported" sqrt (Units xa ua) = Units (sqrt xa) (sqrt ua) sin (Units xa ua) | ua == Symbol "rad" = Units (sin xa) (Number 1) | ua == Symbol "deg" = Units (sin (deg2rad xa)) (Number 1) | otherwise = error "Units for sin must be deg or rad" cos (Units xa ua) | ua == Symbol "rad" = Units (cos xa) (Number 1) | ua == Symbol "deg" = Units (cos (deg2rad xa)) (Number 1) | otherwise = error "Units for cos must be deg or rad" tan (Units xa ua) | ua == Symbol "rad" = Units (tan xa) (Number 1) | ua == Symbol "deg" = Units (tan (deg2rad xa)) (Number 1) | otherwise = error "Units for tan must be deg or rad" asin (Units xa ua) | ua == Number 1 = Units (rad2deg $ asin xa) (Symbol "deg") | otherwise = error "Units for asin must be empty" acos (Units xa ua) | ua == Number 1 = Units (rad2deg $ acos xa) (Symbol "deg") | otherwise = error "Units for acos must be empty" atan (Units xa ua) | ua == Number 1 = Units (rad2deg $ atan xa) (Symbol "deg") | otherwise = error "Units for atan must be empty" sinh = error "sinh not yet implemented in Units" cosh = error "cosh not yet implemented in Units" tanh = error "tanh not yet implemented in Units" asinh = error "asinh not yet implemented in Units" acosh = error "acosh not yet implemented in Units" atanh = error "atanh not yet implemented in Units" units :: (Num z) => z -> String -> Units z units a b = Units a (Symbol b) dropUnits :: (Num z) => Units z -> z dropUnits (Units x _) = x deg2rad x = 2 * pi * x / 360 rad2deg x = 360 * x / (2 * pi) instance (Show a, Num a) => Show (Units a) where show (Units xa ua) = show xa ++ "_" ++ prettyShow (simplify ua) test :: (Num a) => a test = 2 * 5 + 3
6c018c0127c1e51210c4249c2992b247ce67e28e621c750a53596c48e809eaab
manuel-serrano/bigloo
rss.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / bigloo / api / web / src / Llib / rss.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Tue May 17 08:12:41 2005 * / * Last change : Fri Sep 7 11:11:31 2018 ( serrano ) * / * Copyright : 2005 - 18 * / ;* ------------------------------------------------------------- */ ;* RSS parsing */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __web_rss (import __web_xml __web_html __web_date) (export (cdata-decode ::obj) (rss-1.0-parse ::pair-nil ::pair-nil ::procedure ::procedure ::procedure #!key (prefix #f)) (rss-2.0-parse ::pair-nil ::pair-nil ::procedure ::procedure ::procedure #!key (prefix #f)) (rss-parse version ::pair-nil ::pair-nil prefix ::procedure ::procedure ::procedure))) ;*---------------------------------------------------------------------*/ ;* push! ... */ ;*---------------------------------------------------------------------*/ (define-macro (push! list e) `(set! ,list (cons ,e ,list))) ;*---------------------------------------------------------------------*/ ;* pop! ... */ ;*---------------------------------------------------------------------*/ (define-macro (pop! list) `(let ((kar (car ,list))) (set! ,list (cdr ,list)) kar)) ;*---------------------------------------------------------------------*/ * cdata - decode ... * / ;*---------------------------------------------------------------------*/ (define (cdata-decode o) (cond ((string? o) (html-string-decode o)) ((pair? o) (if (eq? (car o) 'cdata) (html-string-decode (cdr o)) (map cdata-decode o))) (else o))) ;*---------------------------------------------------------------------*/ ;* rss-1.0-parse ... */ ;*---------------------------------------------------------------------*/ (define (rss-1.0-parse xml-tree xml-ns make-rss make-channel make-item #!key (prefix #f)) (rss-parse 1.0 xml-tree xml-ns prefix make-rss make-channel make-item)) ;*---------------------------------------------------------------------*/ ;* rss-2.0-parse ... */ ;*---------------------------------------------------------------------*/ (define (rss-2.0-parse xml-tree xml-ns make-rss make-channel make-item #!key (prefix #f)) (rss-parse 2.0 xml-tree xml-ns prefix make-rss make-channel make-item)) ;*---------------------------------------------------------------------*/ ;* rss-parse ... */ ;*---------------------------------------------------------------------*/ (define (rss-parse version tree namespaces prefix make-rss make-channel make-item) (let ((v1.0 #f) (v2.0 #t)) (when (=fl version 1.0) (set! v1.0 #t) (set! v2.0 #f)) (define (drop-prefix e::symbol) (if prefix (let ((s (symbol->string e)) (l (string-length prefix))) (if (substring=? s prefix l) (string->symbol (substring s (+fx l 1) (string-length s))) e)) e)) (define (decode-image img) (append-map (lambda (prop) (if (pair? prop) (filter-map (match-lambda ((?key () (?val)) (cons key val)) (else #f)) prop) '())) img)) (define (flatten l) (append-map (lambda (l) (if (pair? l) (filter pair? l) '())) l)) (define (channel attr body) (let ((title #f) (desc #f) (links '()) (cat '()) (rights #f) (modified #f) (items '()) (rest '())) ;; sub-elements (for-each (lambda (e) (when (pair? e) (match-case e (((or title dc:ditle) ?- ?t . ?-) (set! title (cdata-decode t))) (((or description dc:description) ?- ?t . ?-) (set! desc (cdata-decode t))) ((link () (?href) . ?-) (push! links `(alternate (href . ,(cdata-decode href)) (title . ,title) (type . ,#f)))) ((link (??- (href . ?href) ??-) . ?-) (push! links `(alternate (href . ,(cdata-decode href)) (title . ,title) (type . ,#f)))) (((or category dc:subject) ?- ?cat . ?-) (push! cat (cdata-decode cat))) (((or copyright dc:rights) ?- ?r . ?-) (unless rights (set! rights (cdata-decode r)))) (((or lastBuildDate pubDate) ?- (?d) . ?-) (let* ((d0 (cdata-decode d)) (d (date->w3c-datetime (rfc2822-date->date d0)))) (when (or (not modified) (>fx (string-compare3 modified d) 0)) (set! modified d)))) ((dc:date ?- (?dt . ?-) . ?-) (let ((d dt)) (when (or (not modified) (>fx (string-compare3 modified d) 0)) (set! modified d)))) ((item ?a ?b . ?-) ;; Only for RSS 2.0 (push! items (item a b))) ((image . ?img) (set! rest (cons* :image (decode-image img) rest))) ((language . ?lang) (set! rest (cons* language: (car (apply append lang)) rest))) (else (set! rest (cons* (symbol->keyword (car e)) (apply append (cddr e)) rest)))))) body) ;; attributes are read last so the title is already known (for-each (lambda (e) (when (pair? e) (case (car e) ((rdf:about) (when v1.0 (push! links `(self (href ,(cdata-decode (cdr e))) (title ,(or title (cdata-decode (cdr e)))) (type ,"application/rss+xml"))))) (else #f)))) attr) (let ((chan (apply make-channel :title title :links links :categories cat :date modified :rights rights :subtitle desc rest))) ;; RSS 1.0 specification : ;; <item> elements are not children of <channel> But they are in RSS 2.0 (if (null? items) (if v1.0 chan (error 'rss-2.0-parse "No items in channel element" items)) (if (not v1.0) (make-rss chan (reverse! items)) (error 'rss-1.0-parse "items in channel element" items)))))) (define (rss-enclosure attr title) (let ((href #f) (type #f) (length #f)) (for-each (lambda (e) (when (pair? e) (case (car e) ((url) (set! href (cdata-decode (cdr e)))) ((type) (set! type (cdata-decode (cdr e)))) ((length) (set! length (cdata-decode (cdr e))))))) attr) `(enclosure (href . ,href) (type . ,type) (length . ,length) (title . ,title)))) (define (item attr body) (let ((title #f) (authors '()) (cat '()) ( ( type ( href . ) ( title . text ) ( type . mime ) ) ... ) (summary #f) (content #f) (date #f) (source #f) ;; pair: (title . uri) (rights #f) (rest '())) ;; Sub-elements (for-each (lambda (e) (when (pair? e) (case (car e) ((title dc:title) (unless title (set! title (cdata-decode (caddr e))))) ((author dc:creator) (push! authors (cdata-decode (caddr e)))) ((category dc:subject) (push! cat (cdata-decode (caddr e)))) ((link) (when (pair? (caddr e)) (push! links `(alternate (href . ,(cdata-decode (caaddr e))) (title . ,title) (type . ,#f))))) ((enclosure) (let ((lnk (rss-enclosure (cadr e) title))) (push! links lnk))) ((description dc:description) (set! summary (cdata-decode (caddr e)))) ((content content:encoded) (set! content (cdata-decode (caddr e)))) ((pubDate) (match-case e ((?- ?- (?dt)) (let ((pd (date->w3c-datetime (rfc2822-date->date (cdata-decode dt))))) (when (or (not date) (> (string-compare3 date pd) 0)) (set! date pd)))))) ((dc:date) (let ((d (cdata-decode (caaddr e)))) (when (or (not date) (>fx (string-compare3 date d) 0)) (set! date d)))) ((source) (let ((uri (assoc 'url (cadr e)))) (when uri (set! source (cons (cdata-decode (caddr e)) (car uri)))))) ((dc:rights copyright) (set! rights (cdata-decode (caddr e)))) ((media:content) (set! rest (cons* content: (flatten (cdr e)) rest))) (else (set! rest (cons* (symbol->keyword (car e)) (apply append (cddr e)) rest)))))) body) (apply make-item :title title :links links :categories cat :date date :rights rights :summary summary :content content :authors authors :source source rest))) (define (rss-elements body) (let ((chan #f) (items '())) (for-each (lambda (e) (match-case e ((channel ?v1 ?v2) (set! chan (channel v1 v2))) ((item ?v1 ?v2) (push! items (item v1 v2))))) body) (if (pair? items) (if v1.0 (make-rss chan (reverse! items)) (error 'rss-2.0-parse "found items outside channel elements" items)) (if (not v1.0) chan (error 'rss-1.0-parse "no item found for channel" chan))))) ;; A recoder... (filter-map (lambda (e) (when (pair? e) (case (drop-prefix (car e)) ((rss RSS) (rss-elements (caddr e))) ((xml-decl instruction) #f) (else (let ((rdf (assoc 'rdf-1999 namespaces))) (when (and rdf (string-ci=? (symbol->string (car e)) (format "~a:rdf" (cdr rdf)))) (rss-elements (caddr e)))))))) tree)))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/api/web/src/Llib/rss.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * RSS parsing */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * push! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * pop! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * rss-1.0-parse ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * rss-2.0-parse ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * rss-parse ... */ *---------------------------------------------------------------------*/ sub-elements Only for RSS 2.0 attributes are read last so the title is already known RSS 1.0 specification : <item> elements are not children of <channel> pair: (title . uri) Sub-elements A recoder...
* serrano / prgm / project / bigloo / bigloo / api / web / src / Llib / rss.scm * / * Author : * / * Creation : Tue May 17 08:12:41 2005 * / * Last change : Fri Sep 7 11:11:31 2018 ( serrano ) * / * Copyright : 2005 - 18 * / (module __web_rss (import __web_xml __web_html __web_date) (export (cdata-decode ::obj) (rss-1.0-parse ::pair-nil ::pair-nil ::procedure ::procedure ::procedure #!key (prefix #f)) (rss-2.0-parse ::pair-nil ::pair-nil ::procedure ::procedure ::procedure #!key (prefix #f)) (rss-parse version ::pair-nil ::pair-nil prefix ::procedure ::procedure ::procedure))) (define-macro (push! list e) `(set! ,list (cons ,e ,list))) (define-macro (pop! list) `(let ((kar (car ,list))) (set! ,list (cdr ,list)) kar)) * cdata - decode ... * / (define (cdata-decode o) (cond ((string? o) (html-string-decode o)) ((pair? o) (if (eq? (car o) 'cdata) (html-string-decode (cdr o)) (map cdata-decode o))) (else o))) (define (rss-1.0-parse xml-tree xml-ns make-rss make-channel make-item #!key (prefix #f)) (rss-parse 1.0 xml-tree xml-ns prefix make-rss make-channel make-item)) (define (rss-2.0-parse xml-tree xml-ns make-rss make-channel make-item #!key (prefix #f)) (rss-parse 2.0 xml-tree xml-ns prefix make-rss make-channel make-item)) (define (rss-parse version tree namespaces prefix make-rss make-channel make-item) (let ((v1.0 #f) (v2.0 #t)) (when (=fl version 1.0) (set! v1.0 #t) (set! v2.0 #f)) (define (drop-prefix e::symbol) (if prefix (let ((s (symbol->string e)) (l (string-length prefix))) (if (substring=? s prefix l) (string->symbol (substring s (+fx l 1) (string-length s))) e)) e)) (define (decode-image img) (append-map (lambda (prop) (if (pair? prop) (filter-map (match-lambda ((?key () (?val)) (cons key val)) (else #f)) prop) '())) img)) (define (flatten l) (append-map (lambda (l) (if (pair? l) (filter pair? l) '())) l)) (define (channel attr body) (let ((title #f) (desc #f) (links '()) (cat '()) (rights #f) (modified #f) (items '()) (rest '())) (for-each (lambda (e) (when (pair? e) (match-case e (((or title dc:ditle) ?- ?t . ?-) (set! title (cdata-decode t))) (((or description dc:description) ?- ?t . ?-) (set! desc (cdata-decode t))) ((link () (?href) . ?-) (push! links `(alternate (href . ,(cdata-decode href)) (title . ,title) (type . ,#f)))) ((link (??- (href . ?href) ??-) . ?-) (push! links `(alternate (href . ,(cdata-decode href)) (title . ,title) (type . ,#f)))) (((or category dc:subject) ?- ?cat . ?-) (push! cat (cdata-decode cat))) (((or copyright dc:rights) ?- ?r . ?-) (unless rights (set! rights (cdata-decode r)))) (((or lastBuildDate pubDate) ?- (?d) . ?-) (let* ((d0 (cdata-decode d)) (d (date->w3c-datetime (rfc2822-date->date d0)))) (when (or (not modified) (>fx (string-compare3 modified d) 0)) (set! modified d)))) ((dc:date ?- (?dt . ?-) . ?-) (let ((d dt)) (when (or (not modified) (>fx (string-compare3 modified d) 0)) (set! modified d)))) ((item ?a ?b . ?-) (push! items (item a b))) ((image . ?img) (set! rest (cons* :image (decode-image img) rest))) ((language . ?lang) (set! rest (cons* language: (car (apply append lang)) rest))) (else (set! rest (cons* (symbol->keyword (car e)) (apply append (cddr e)) rest)))))) body) (for-each (lambda (e) (when (pair? e) (case (car e) ((rdf:about) (when v1.0 (push! links `(self (href ,(cdata-decode (cdr e))) (title ,(or title (cdata-decode (cdr e)))) (type ,"application/rss+xml"))))) (else #f)))) attr) (let ((chan (apply make-channel :title title :links links :categories cat :date modified :rights rights :subtitle desc rest))) But they are in RSS 2.0 (if (null? items) (if v1.0 chan (error 'rss-2.0-parse "No items in channel element" items)) (if (not v1.0) (make-rss chan (reverse! items)) (error 'rss-1.0-parse "items in channel element" items)))))) (define (rss-enclosure attr title) (let ((href #f) (type #f) (length #f)) (for-each (lambda (e) (when (pair? e) (case (car e) ((url) (set! href (cdata-decode (cdr e)))) ((type) (set! type (cdata-decode (cdr e)))) ((length) (set! length (cdata-decode (cdr e))))))) attr) `(enclosure (href . ,href) (type . ,type) (length . ,length) (title . ,title)))) (define (item attr body) (let ((title #f) (authors '()) (cat '()) ( ( type ( href . ) ( title . text ) ( type . mime ) ) ... ) (summary #f) (content #f) (date #f) (rights #f) (rest '())) (for-each (lambda (e) (when (pair? e) (case (car e) ((title dc:title) (unless title (set! title (cdata-decode (caddr e))))) ((author dc:creator) (push! authors (cdata-decode (caddr e)))) ((category dc:subject) (push! cat (cdata-decode (caddr e)))) ((link) (when (pair? (caddr e)) (push! links `(alternate (href . ,(cdata-decode (caaddr e))) (title . ,title) (type . ,#f))))) ((enclosure) (let ((lnk (rss-enclosure (cadr e) title))) (push! links lnk))) ((description dc:description) (set! summary (cdata-decode (caddr e)))) ((content content:encoded) (set! content (cdata-decode (caddr e)))) ((pubDate) (match-case e ((?- ?- (?dt)) (let ((pd (date->w3c-datetime (rfc2822-date->date (cdata-decode dt))))) (when (or (not date) (> (string-compare3 date pd) 0)) (set! date pd)))))) ((dc:date) (let ((d (cdata-decode (caaddr e)))) (when (or (not date) (>fx (string-compare3 date d) 0)) (set! date d)))) ((source) (let ((uri (assoc 'url (cadr e)))) (when uri (set! source (cons (cdata-decode (caddr e)) (car uri)))))) ((dc:rights copyright) (set! rights (cdata-decode (caddr e)))) ((media:content) (set! rest (cons* content: (flatten (cdr e)) rest))) (else (set! rest (cons* (symbol->keyword (car e)) (apply append (cddr e)) rest)))))) body) (apply make-item :title title :links links :categories cat :date date :rights rights :summary summary :content content :authors authors :source source rest))) (define (rss-elements body) (let ((chan #f) (items '())) (for-each (lambda (e) (match-case e ((channel ?v1 ?v2) (set! chan (channel v1 v2))) ((item ?v1 ?v2) (push! items (item v1 v2))))) body) (if (pair? items) (if v1.0 (make-rss chan (reverse! items)) (error 'rss-2.0-parse "found items outside channel elements" items)) (if (not v1.0) chan (error 'rss-1.0-parse "no item found for channel" chan))))) (filter-map (lambda (e) (when (pair? e) (case (drop-prefix (car e)) ((rss RSS) (rss-elements (caddr e))) ((xml-decl instruction) #f) (else (let ((rdf (assoc 'rdf-1999 namespaces))) (when (and rdf (string-ci=? (symbol->string (car e)) (format "~a:rdf" (cdr rdf)))) (rss-elements (caddr e)))))))) tree)))
12e46d31cd9ca4948bc1b9d09e650e5bf52d6992c2b15a7b3f1a6f17f38e2d26
riemann/riemann
nagios_test.clj
(ns riemann.nagios-test (:require [riemann.logging :as logging] [riemann.nagios :refer :all] [cljr-nsca.core :refer :all] [clojure.test :refer :all])) (logging/init) (def test-event {:host "host01" :service "test_service" :state "ok" :description "Quick brown fox"}) (def expected (let [e test-event] (nagios-message (:host e) (:state e) (:service e) (:description e)))) (deftest test-event-to-nagios (testing "Transform event to Nagios message" (is (= expected (event->nagios test-event)))) (testing "Malformed events are rejected" (is (thrown? IllegalArgumentException (event->nagios (dissoc test-event :host)))))) (deftest test-stream (testing "Events get transformed and are sent" (let [message (atom nil)] (with-redefs [cljr-nsca.core/send-message (fn [_ msg] (reset! message msg))] ((nagios {}) test-event)) (is (= expected @message)))))
null
https://raw.githubusercontent.com/riemann/riemann/1649687c0bd913c378701ee0b964a9863bde7c7c/test/riemann/nagios_test.clj
clojure
(ns riemann.nagios-test (:require [riemann.logging :as logging] [riemann.nagios :refer :all] [cljr-nsca.core :refer :all] [clojure.test :refer :all])) (logging/init) (def test-event {:host "host01" :service "test_service" :state "ok" :description "Quick brown fox"}) (def expected (let [e test-event] (nagios-message (:host e) (:state e) (:service e) (:description e)))) (deftest test-event-to-nagios (testing "Transform event to Nagios message" (is (= expected (event->nagios test-event)))) (testing "Malformed events are rejected" (is (thrown? IllegalArgumentException (event->nagios (dissoc test-event :host)))))) (deftest test-stream (testing "Events get transformed and are sent" (let [message (atom nil)] (with-redefs [cljr-nsca.core/send-message (fn [_ msg] (reset! message msg))] ((nagios {}) test-event)) (is (= expected @message)))))
38252e9574812e4ac402d7b33315161971ccd1ef9f4932beafd54bc6af5ec29f
UnkindPartition/monad-classes
State.hs
module Control.Monad.Classes.State where import qualified Control.Monad.Trans.State.Lazy as SL import qualified Control.Monad.Trans.State.Strict as SS import Control.Monad.Trans.Class import GHC.Prim (Proxy#, proxy#) import Control.Monad.Classes.Core import Control.Monad.Classes.Effects type instance CanDo (SS.StateT s m) eff = StateCanDo s eff type instance CanDo (SL.StateT s m) eff = StateCanDo s eff type family StateCanDo s eff where StateCanDo s (EffState s) = 'True StateCanDo s (EffReader s) = 'True StateCanDo s (EffLocal s) = 'True StateCanDo s (EffWriter s) = 'True StateCanDo s eff = 'False class Monad m => MonadStateN (n :: Nat) s m where stateN :: Proxy# n -> ((s -> (a, s)) -> m a) instance Monad m => MonadStateN 'Zero s (SL.StateT s m) where stateN _ = SL.state instance Monad m => MonadStateN 'Zero s (SS.StateT s m) where stateN _ = SS.state instance (Monad (t m), MonadTrans t, MonadStateN n s m, Monad m) => MonadStateN ('Suc n) s (t m) where stateN _ = lift . stateN (proxy# :: Proxy# n) -- | The @'MonadState' s m@ constraint asserts that @m@ is a monad stack -- that supports state operations on type @s@ type MonadState s m = MonadStateN (Find (EffState s) m) s m -- | Construct a state monad computation from a function state :: forall s m a. (MonadState s m) => (s -> (a, s)) -> m a state = stateN (proxy# :: Proxy# (Find (EffState s) m)) -- | @'put' s@ sets the state within the monad to @s@ put :: MonadState s m => s -> m () put s = state $ \_ -> ((), s) -- | Fetch the current value of the state within the monad get :: MonadState a m => m a get = state $ \s -> (s, s) -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a gets f = do s <- get return (f s) -- | Maps an old state to a new state inside a state monad layer modify :: MonadState s m => (s -> s) -> m () modify f = state (\s -> ((), f s)) -- | A variant of 'modify' in which the computation is strict in the -- new state modify' :: MonadState s m => (s -> s) -> m () modify' f = state (\s -> let s' = f s in s' `seq` ((), s')) runStateLazy :: s -> SL.StateT s m a -> m (a, s) runStateLazy = flip SL.runStateT runStateStrict :: s -> SS.StateT s m a -> m (a, s) runStateStrict = flip SS.runStateT evalStateLazy :: Monad m => s -> SL.StateT s m a -> m a evalStateLazy = flip SL.evalStateT evalStateStrict :: Monad m => s -> SS.StateT s m a -> m a evalStateStrict = flip SS.evalStateT execStateLazy :: Monad m => s -> SL.StateT s m a -> m s execStateLazy = flip SL.execStateT execStateStrict :: Monad m => s -> SS.StateT s m a -> m s execStateStrict = flip SS.execStateT
null
https://raw.githubusercontent.com/UnkindPartition/monad-classes/19e41e250615ad1121a958baed6c3081b0efb11b/Control/Monad/Classes/State.hs
haskell
| The @'MonadState' s m@ constraint asserts that @m@ is a monad stack that supports state operations on type @s@ | Construct a state monad computation from a function | @'put' s@ sets the state within the monad to @s@ | Fetch the current value of the state within the monad | Gets specific component of the state, using a projection function supplied. | Maps an old state to a new state inside a state monad layer | A variant of 'modify' in which the computation is strict in the new state
module Control.Monad.Classes.State where import qualified Control.Monad.Trans.State.Lazy as SL import qualified Control.Monad.Trans.State.Strict as SS import Control.Monad.Trans.Class import GHC.Prim (Proxy#, proxy#) import Control.Monad.Classes.Core import Control.Monad.Classes.Effects type instance CanDo (SS.StateT s m) eff = StateCanDo s eff type instance CanDo (SL.StateT s m) eff = StateCanDo s eff type family StateCanDo s eff where StateCanDo s (EffState s) = 'True StateCanDo s (EffReader s) = 'True StateCanDo s (EffLocal s) = 'True StateCanDo s (EffWriter s) = 'True StateCanDo s eff = 'False class Monad m => MonadStateN (n :: Nat) s m where stateN :: Proxy# n -> ((s -> (a, s)) -> m a) instance Monad m => MonadStateN 'Zero s (SL.StateT s m) where stateN _ = SL.state instance Monad m => MonadStateN 'Zero s (SS.StateT s m) where stateN _ = SS.state instance (Monad (t m), MonadTrans t, MonadStateN n s m, Monad m) => MonadStateN ('Suc n) s (t m) where stateN _ = lift . stateN (proxy# :: Proxy# n) type MonadState s m = MonadStateN (Find (EffState s) m) s m state :: forall s m a. (MonadState s m) => (s -> (a, s)) -> m a state = stateN (proxy# :: Proxy# (Find (EffState s) m)) put :: MonadState s m => s -> m () put s = state $ \_ -> ((), s) get :: MonadState a m => m a get = state $ \s -> (s, s) gets :: MonadState s m => (s -> a) -> m a gets f = do s <- get return (f s) modify :: MonadState s m => (s -> s) -> m () modify f = state (\s -> ((), f s)) modify' :: MonadState s m => (s -> s) -> m () modify' f = state (\s -> let s' = f s in s' `seq` ((), s')) runStateLazy :: s -> SL.StateT s m a -> m (a, s) runStateLazy = flip SL.runStateT runStateStrict :: s -> SS.StateT s m a -> m (a, s) runStateStrict = flip SS.runStateT evalStateLazy :: Monad m => s -> SL.StateT s m a -> m a evalStateLazy = flip SL.evalStateT evalStateStrict :: Monad m => s -> SS.StateT s m a -> m a evalStateStrict = flip SS.evalStateT execStateLazy :: Monad m => s -> SL.StateT s m a -> m s execStateLazy = flip SL.execStateT execStateStrict :: Monad m => s -> SS.StateT s m a -> m s execStateStrict = flip SS.execStateT
f9d3148efcea89a6293376d4fd6d121c631fec09a0a7bd44343c197ccd274345
anurudhp/CPHaskell
c.hs
# LANGUAGE ParallelListComp # import Control.Arrow ((>>>)) import Data.List (delete) main :: IO () main = interact $ lines >>> map (words >>> map read) >>> solve >>> show solve :: [[Int]] -> Int solve ([n, k]:ts) = length . filter (== k) . map time $ perms where perms = map (\p -> 0 : p ++ [0]) $ permute [1 .. n - 1] time p = sum [ts !! i !! j | i <- p | j <- tail p] permute :: [Int] -> [[Int]] permute [] = [[]] permute [x] = [[x]] permute xs = concatMap (\x -> (x :) <$> permute (delete x xs)) xs
null
https://raw.githubusercontent.com/anurudhp/CPHaskell/01ae8dde6aab4f6ddfebd122ded0b42779dd16f1/contests/atcoder/abc183/c.hs
haskell
# LANGUAGE ParallelListComp # import Control.Arrow ((>>>)) import Data.List (delete) main :: IO () main = interact $ lines >>> map (words >>> map read) >>> solve >>> show solve :: [[Int]] -> Int solve ([n, k]:ts) = length . filter (== k) . map time $ perms where perms = map (\p -> 0 : p ++ [0]) $ permute [1 .. n - 1] time p = sum [ts !! i !! j | i <- p | j <- tail p] permute :: [Int] -> [[Int]] permute [] = [[]] permute [x] = [[x]] permute xs = concatMap (\x -> (x :) <$> permute (delete x xs)) xs
a5f4179b4cc3fe86be42c6ef0fecf6958d474a191c73fbb147654daa7b0a3c51
tamarin-prover/tamarin-prover
Label.hs
# LANGUAGE TypeOperators # -- | Copyright : ( c ) 2011 -- License : GPL v3 (see LICENSE) -- Maintainer : < > Portability : GHC only -- Extensions to the first - class labels ( fclabels ) package . module Extension.Data.Label ( nthL , fstL , sndL , module Data.Label -- * Labels and applicative functors , modA -- * Labels and Monads , askM , setM , getM , modM , (=:) ) where import Data.Label import Data.Label.Monadic ( (=:) ) import qualified Data.Label.Monadic as LM import Control.Arrow (first, second) import Control . Applicative ( Applicative , ( < $ > ) , ( < * > ) , pure ) import Control.Monad.State (MonadState) import Control.Monad.Reader (MonadReader) | Lens for the first element of a tuple . fstL :: ((a, b) :-> a) fstL = lens fst first | Lens for the second element of a tuple . sndL :: ((a, b) :-> b) sndL = lens snd second -- | Lens for the nth element of the list. nthL :: Int -> ([a] :-> a) nthL i = lens (!! i) updateAt where updateAt f xs | 0 <= i && i < length xs = case splitAt i xs of (prefix, x:suffix) -> prefix ++ (f x:suffix) _ -> error "nthL: impossible" | otherwise = error $ "nthL: index " ++ show i ++ " out of range" -- | Effectful modification of a labeled value. modA :: Applicative f => (a :-> b) -> (b -> f b) -> a -> f a modA l f a = set l <$> f (get l a) <*> pure a -- | Get part of the state from a reader. askM :: MonadReader r m => (r :-> a) -> m a askM = LM.asks -- | Set some part of the state. setM :: MonadState s m => (s :-> a) -> a -> m () setM = LM.puts -- | Get some part of the state. getM :: MonadState s m => (s :-> a) -> m a getM = LM.gets -- | Modify some part of the state. modM :: MonadState s m => (s :-> a) -> (a -> a) -> m () modM = LM.modify
null
https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/c78c7afd3b93b52dd4d2884952ec0fc273832a0d/lib/utils/src/Extension/Data/Label.hs
haskell
| License : GPL v3 (see LICENSE) * Labels and applicative functors * Labels and Monads | Lens for the nth element of the list. | Effectful modification of a labeled value. | Get part of the state from a reader. | Set some part of the state. | Get some part of the state. | Modify some part of the state.
# LANGUAGE TypeOperators # Copyright : ( c ) 2011 Maintainer : < > Portability : GHC only Extensions to the first - class labels ( fclabels ) package . module Extension.Data.Label ( nthL , fstL , sndL , module Data.Label , modA , askM , setM , getM , modM , (=:) ) where import Data.Label import Data.Label.Monadic ( (=:) ) import qualified Data.Label.Monadic as LM import Control.Arrow (first, second) import Control . Applicative ( Applicative , ( < $ > ) , ( < * > ) , pure ) import Control.Monad.State (MonadState) import Control.Monad.Reader (MonadReader) | Lens for the first element of a tuple . fstL :: ((a, b) :-> a) fstL = lens fst first | Lens for the second element of a tuple . sndL :: ((a, b) :-> b) sndL = lens snd second nthL :: Int -> ([a] :-> a) nthL i = lens (!! i) updateAt where updateAt f xs | 0 <= i && i < length xs = case splitAt i xs of (prefix, x:suffix) -> prefix ++ (f x:suffix) _ -> error "nthL: impossible" | otherwise = error $ "nthL: index " ++ show i ++ " out of range" modA :: Applicative f => (a :-> b) -> (b -> f b) -> a -> f a modA l f a = set l <$> f (get l a) <*> pure a askM :: MonadReader r m => (r :-> a) -> m a askM = LM.asks setM :: MonadState s m => (s :-> a) -> a -> m () setM = LM.puts getM :: MonadState s m => (s :-> a) -> m a getM = LM.gets modM :: MonadState s m => (s :-> a) -> (a -> a) -> m () modM = LM.modify
53e1c5d4f5f9ef17baf6ac595cc42821e50dc50198f8bbcdde12b2b144c5cc8d
spartango/CS153
fishcomb_test.ml
open Test_framework open Lcombinators.GenericParsing open Comblexer open Ast open Combparser open Lcombinators.CharParsing open Explode open Eval open Pretty_print Tests for the Parser let test_token_equal = (mk_expect_test (fun () -> let input_tokens = [ (Comblexer.Return, 0);] in ((token_equal Comblexer.Return) input_tokens) ) (singleton ((Comblexer.Return, 0), [])) ("Token Equality Test") ) ;; let test_int_alone = Test( "Standalone Int Test", (fun () -> let input_tokens = [ (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Int(1), 0), []), _) -> true | _ -> false )) ;; let test_var_alone = Test( "Standalone Var Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Var("x"), 0), []), _) -> true | _ -> false )) ;; let test_paren_alone = Test( "Parens Simple Test", (fun () -> let input_tokens = [ (LParen, 0); (Comblexer.Id("x"), 0); (RParen, 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Var("x"), 0), []), _) -> true | _ -> false )) ;; let test_negative_int = Test( "Negative Int Test", (fun () -> let input_tokens = [ (Comblexer.Minus, 0); (Comblexer.Int(1), 0); ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Int(-1), 0), []), _) -> true | _ -> false )) ;; let test_int_simple_op = Test( "Int 1 + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Int(1), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Int(1), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false ) ) ;; let test_var_simple_op = Test( "Var x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_var_var_simple_op = Test( "Var x + x Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Id("x"), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Var("x"), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_var_neg_simple_op = Test( "Var x - 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Minus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Minus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_var_and_op = Test( "Var x && 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.And, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.And( (Ast.Var("x"), 0), (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; run_test_set [ test_token_equal; test_int_alone; test_negative_int; test_var_alone; test_paren_alone; test_int_simple_op; test_var_simple_op; test_var_var_simple_op; test_var_neg_simple_op; test_var_and_op; ] "Parser Building Blocks" ;; let test_simple_var_expr = Test( "Expr x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_simple_int_expr = Test( "Expr 1 + x Test", (fun () -> let input_tokens = [ (Comblexer.Int(1), 0); (Comblexer.Plus, 0); (Comblexer.Id("x"), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Int(1), 0), Ast.Plus, (Ast.Var("x"), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_paren_var_expr = Test( "Expr (x + 1) Test", (fun () -> let input_tokens = [ (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0) ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_rgroup_expr = Test( "Expr 2 + (x + 1) Test", (fun () -> let input_tokens = [ (Comblexer.Int(2), 0); (Comblexer.Plus, 0); (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0) ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Int(2), 0), Ast.Plus, ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))), 0) )), 0), []) , _ ) -> true | _ -> false )) ;; let test_not_var_expr = Test( "Expr !(x + 1) Test", (fun () -> let input_tokens = [ (Comblexer.Not, 0); (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0) ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ((Ast.Not( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0), []) , _ ) -> true | _ -> false )) ;; let test_lgroup_expr = Test( "Expr (x + 1) + 2 Test", (fun () -> let input_tokens = [ (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0); (Comblexer.Plus, 0); (Comblexer.Int(2), 0); ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))), 0), Ast.Plus, (Ast.Int(2), 0) )), 0), []) , _ ) -> true | _ -> false )) ;; run_test_set [ test_simple_var_expr; test_simple_int_expr; test_paren_var_expr; test_rgroup_expr; test_lgroup_expr; test_not_var_expr; ] "Expression Parsing" ;; (* Statement Parsing Tests *) let test_s_expr = Test( "Statement x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); ] in let parsed = (parse_statement input_tokens) in match parsed with | Cons( ( (Ast.Exp( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0), []) , _ ) -> true | _ -> false )) ;; let test_return = Test( "Statement return x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Return, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); ] in let parsed = (parse_statement input_tokens) in match parsed with | Cons( ( (Ast.Return( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0), []) , _ ) -> true | _ -> false )) ;; let test_seq = Test( "Statement { x + 1; y + 1; } Test", (fun () -> let input_tokens = [ (Comblexer.LCurly, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.Semi, 0); (Comblexer.Id("y"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RCurly, 0); ] in let parsed = (parse_statement input_tokens) in match parsed with | Cons( ( (Ast.Seq( (Ast.Seq( _ , (Ast.Exp(((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0)), 0), (Ast.Exp(((Ast.Binop( (Ast.Var("y"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0) ) , 0) , []) , _ ) -> true | _ -> false )) ;; let test_while = Test( "Simple While loop Test", (fun () -> let input_tokens = [ (Comblexer.While, 0); (Comblexer.LParen, 0); (Comblexer.Int(0), 0); (Comblexer.RParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Semi, 0); ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.While( (Ast.Int(0), 0), (Ast.Exp( (Ast.Var("x"), 0)), 0) ), 0), []), _) -> true | _ -> false )) ;; let test_if = Test( "Simple If statement Test", (fun () -> let input_tokens = [ (Comblexer.If, 0); (Comblexer.LParen, 0); (Comblexer.Int(0), 0); (Comblexer.RParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Semi, 0); ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.If( (Ast.Int(0), 0), (Ast.Exp( (Ast.Var("x"), 0)), 0), _ ), 0), []), _) -> true | _ -> false )) ;; let test_if_else = Test( "If else statement Test", (fun () -> let input_tokens = [ (Comblexer.If, 0); (Comblexer.LParen, 0); (Comblexer.Int(0), 0); (Comblexer.RParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Semi, 0); (Comblexer.Else, 0); (Comblexer.Id("y"), 0); (Comblexer.Semi, 0); ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.If( (Ast.Int(0), 0), (Ast.Exp( (Ast.Var("x"), 0)), 0), (Ast.Exp( (Ast.Var("y"), 0)), 0) ), 0), []), _) -> true | _ -> false )) ;; let test_for = Test( "For loop Test", (fun () -> let input_tokens = [ (Comblexer.For, 0); (Comblexer.LParen, 0); (Comblexer.Id("i"), 0); (Comblexer.Assign, 0); (Comblexer.Int(0), 0); (Comblexer.Semi, 0); (Comblexer.Id("i"), 0); (Comblexer.Eq, 0); (Comblexer.Int(1), 0); (Comblexer.Semi, 0); (Comblexer.Id("i"), 0); (Comblexer.Assign, 0); (Comblexer.Id("i"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0); (Comblexer.Id("i"), 0); (Comblexer.Semi, 0) ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.For( (Ast.Assign( "i", (Ast.Int(0), 0)), 0), (Ast.Binop( (Ast.Var("i"), 0), Ast.Eq, (Ast.Int(1), 0)), 0), (Ast.Assign( "i", (Ast.Binop( (Ast.Var("i"), 0), Ast.Plus, (Ast.Int(1), 0)), 0)), 0), (Ast.Exp( (Ast.Var("i"), 0)), 0)), 0), []), _) -> true; | _ -> false )) ;; run_test_set [ test_s_expr; test_return; test_seq; test_while; test_if; test_if_else; test_for; ] "Statement Parsing" ;; let mk_parse_test (file: string) = let label = "Lexing & Parsing " ^ file in Verbose_Test(label, (fun()-> try let ic = (open_in file) in let file_contents = (read_file ic "") in let _ = print_string ( ( format_string " [ RUNNING ] " Bright Cyan ) ^ ( String.escaped file_contents ) ^ " \n " ) in ((format_string "[ RUNNING ] " Bright Cyan) ^ (String.escaped file_contents) ^ "\n") in *) let rslt = eval (parse (tokenize ( explode file_contents ))) in (true, "Parsed with answer " ^ string_of_int rslt) with LexError -> (false, ( format_string "Lexer Failed" Bright Red)) | IntInvalidSyntax -> (false, ( format_string "Int Parser Failed" Bright Red)) | VarInvalidSyntax -> (false, ( format_string "Var Parser Failed" Bright Red)) | ParenInvalidSyntax -> (false, ( format_string "Paren Parser Failed" Bright Red)) | NoParses -> (false, (format_string "No parses" Bright Red)) )) let file_list = [ "test/01cexpr_01add.fish"; "test/01cexpr_02sub.fish"; "test/01cexpr_03mul.fish"; "test/01cexpr_04div.fish"; "test/01cexpr_05eq.fish"; "test/01cexpr_06neq.fish"; "test/01cexpr_07gt.fish"; "test/01cexpr_08gte.fish"; "test/01cexpr_09lt.fish"; "test/01cexpr_10lte.fish"; "test/01cexpr_11uminus.fish"; "test/01cexpr_12not.fish"; "test/01cexpr_13and.fish"; "test/01cexpr_14or.fish"; "test/01cexpr_15bigcon.fish"; "test/01cexpr_16bigcon.fish"; "test/02vexpr_01add.fish"; "test/02vexpr_02sub.fish"; "test/02vexpr_03mul.fish"; "test/02vexpr_04div.fish"; "test/02vexpr_05eq.fish"; "test/02vexpr_06neq.fish"; "test/02vexpr_07gt.fish"; "test/02vexpr_08gte.fish"; "test/02vexpr_09lt.fish"; "test/02vexpr_10lte.fish"; "test/02vexpr_11uminus.fish"; "test/02vexpr_12not.fish"; "test/02vexpr_13and.fish"; "test/02vexpr_14or.fish"; "test/02vexpr_15assignval.fish"; "test/03stmt_01if.fish"; "test/03stmt_02if.fish"; "test/03stmt_03while.fish"; "test/03stmt_04for.fish"; "test/03stmt_05if.fish"; "test/03stmt_06for.fish"; "test/04opt_01cfoldif.fish"; "test/04opt_02cfoldif.fish"; "test/09all_01adder.fish"; "test/09all_02fibo.fish"; ] ;; run_test_set (List.map mk_parse_test file_list) "Parse Test Files";; let lex_test_inputs = [ ( " foo " , [ ( I d " foo " ) ] ) ; ( " foo = baz " , [ ( I d " foo " ) ; Comblexer . Assign ; ( I d " baz " ) ] ) ; ( " 5 " , [ ( Comblexer . Int 5 ) ] ) ; ( " 5 + 9 " , [ ( Comblexer . Int 5);Plus;(Int 9 ) ] ) ; ( " + " , [ Plus ] ) ; ( " + foo " , [ Plus ; ( I d " foo " ) ] ) ; ( " = " , [ Assign ] ) ; ( " = foo " , [ Assign ; ( I d " foo " ) ] ) ; ( " - " , [ Minus ] ) ; ( " -foo+foo " , [ Minus ; ( I d " foo " ) ; Plus ; ( I d " foo " ) ] ) ; ( " * " , [ Times ] ) ; ( " * 5 = foo " , [ Times ; ( Int 5 ) ; Assign ; ( I d " foo " ) ] ) ; ( " / " , [ Div ] ) ; ( " /feed = foo " , [ Div ; ( I d " feed " ) ; Assign ; ( I d " foo " ) ] ) ; ( " ! = " , [ Neq ] ) ; ( " ! = foo " , [ Neq ; ( I d " foo " ) ] ) ; ( " > = " , [ Gte ] ) ; ( " > = 55 " , [ ; ( Int 55 ) ] ) ; ( " > " , [ Gt ] ) ; ( " > foo+5 " , [ " foo");Plus;(Int 5 ) ] ) ; ( " < = " , [ Lte ] ) ; ( " < = foo " , [ " foo " ) ] ) ; ( " = = " , [ Eq ] ) ; ( " = = foo " , [ Eq;(Id " foo " ) ] ) ; ( " ! " , [ Not ] ) ; ( " ! 0 " , [ Not;(Int 0 ) ] ) ; ( " || " , [ Or ] ) ; ( " ||5>=0 " , [ Or;(Int 5);Gte;(Int 0 ) ] ) ; ( " & & " , [ And ] ) ; ( " & & 6<=34 " , [ And;(Int 6);Lte;(Int 34 ) ] ) ; ( " ( " , [ LParen ] ) ; ( " ( 8) " , [ LParen;(Int 8);RParen ] ) ; ( " ) " , [ RParen ] ) ; ( " ) =( & & " , [ RParen;Assign;LParen;And ] ) ; ( " { " , [ LCurly ] ) ; ( " } " , [ RCurly ] ) ; ( " for{i=4;i<=6;i = i+1 } " , [ For;LCurly;(Id " i");Assign;(Int 4);Semi;(Id " i");Lte ; ( Int 6);Semi;(Id " i");Assign;(Id " i");Plus;(Int 1 ) ; RCurly ] ) ; ( " if(i==5){k=2;}else{k=1 ; } " , [ If;LParen;(Id " i");Eq;(Int 5);RParen;LCurly ; ( I d " k");Assign;(Int 2);Semi;RCurly;Else;LCurly ; ( I d " k");Assign;(Int 1);Semi;RCurly ] ) ; ( " while(i>=0){k = k-1;i = i-2 ; } " , [ " i");Gte;(Int 0);RParen;LCurly ; ( I d " k");Assign;(Id " k");Minus;(Int 1);Semi ; ( I d " i");Assign;(Id " i");Minus;(Int 2);Semi ; RCurly ] ) ; ( " forever " , [ ( I d " forever " ) ] ) ; ( " " , [ ( I d " " ) ] ) ; ( " elsey " , [ ( I d " elsey " ) ] ) ; ( " whiley " , [ ( I d " " ) ] ) ; ( " + /*I am a comment*/5 " , [ Plus;(Int 5 ) ] ) ; ] let mk_lex_combinator_test ( p : ( char , rtoken ) parser ) ( expected_token : rtoken ) ( label : string ) = let tkn_match ( t1 : ) ( t2 : ) : match ( t1 , t2 ) with | ( ( I d _ ) , ( I d _ ) ) - > true | ( ( Int _ ) , ( Int _ ) ) - > true | ( _ , _ ) - > ( t1 = t2 ) in let test_map ( errors : string ) ( case : string * rtoken list ) : string = let(code_string , tkns ) = case in let cs = explode code_string in let head_token = ( List.hd tkns ) in match ( p cs ) with | Cons((tkn , _ ) , _ ) - > if ( ( tkn_match head_token expected_token ) & & ( tkn = head_token ) ) || ( not(tkn_match head_token expected_token ) & & ( tkn < > head_token ) ) then errors else errors ^ " \n\tExpected : " ^ ( tkn2str(head_token ) ) ^ " : " ^ ( ) ) | Nil - > if ( tkn_match head_token expected_token ) then errors ^ " \n\tReturned no token but expected : " ^ ( tkn2str(head_token ) ) else errors in let result = List.fold_left test_map " " lex_test_inputs in if ( result < > " " ) then Verbose_Test(label , ( fun ( ) - > ( false , " Lexing error : " ^ result ) ) ) else Verbose_Test(label , ( fun ( ) - > ( true , " Lexed expected tokens " ) ) ) ( * This test maker setup does not work for testing the individual Gt , Lt , Not , , and keyword combinators , due to longest match rule . However , complete_combinator tests should validate them . let lex_test_inputs = [ ("foo", [(Id "foo")]); ("foo=baz", [(Id "foo"); Comblexer.Assign; (Id "baz")]); ("5", [(Comblexer.Int 5)]); ("5+9", [(Comblexer.Int 5);Plus;(Int 9)]); ("+", [Plus]); ("+foo", [Plus; (Id "foo")]); ("=", [Assign]); ("=foo", [Assign; (Id "foo")]); ("-", [Minus]); ("-foo+foo", [Minus; (Id "foo"); Plus; (Id "foo")]); ("*", [Times]); ("*5=foo", [Times; (Int 5); Assign; (Id "foo")]); ("/", [Div]); ("/feed=foo", [Div; (Id "feed"); Assign; (Id "foo")]); ("!=", [Neq]); ("!=foo", [Neq; (Id "foo")]); (">=", [Gte]); (">=55", [Gte; (Int 55)]); (">", [Gt]); (">foo+5", [Gt;(Id "foo");Plus;(Int 5)]); ("<=", [Lte]); ("<=foo", [Lte;(Id "foo")]); ("==", [Eq]); ("==foo", [Eq;(Id "foo")]); ("!", [Not]); ("!0", [Not;(Int 0)]); ("||", [Or]); ("||5>=0", [Or;(Int 5);Gte;(Int 0)]); ("&&", [And]); ("&&6<=34", [And;(Int 6);Lte;(Int 34)]); ("(", [LParen]); ("(8)", [LParen;(Int 8);RParen]); (")", [RParen]); (")=(&&", [RParen;Assign;LParen;And]); ("{", [LCurly]); ("}", [RCurly]); ("for{i=4;i<=6;i=i+1}", [For;LCurly;(Id "i");Assign;(Int 4);Semi;(Id "i");Lte; (Int 6);Semi;(Id "i");Assign;(Id "i");Plus;(Int 1); RCurly]); ("if(i==5){k=2;}else{k=1;}", [If;LParen;(Id "i");Eq;(Int 5);RParen;LCurly; (Id "k");Assign;(Int 2);Semi;RCurly;Else;LCurly; (Id "k");Assign;(Int 1);Semi;RCurly]); ("while(i>=0){k=k-1;i=i-2;}", [While;LParen;(Id "i");Gte;(Int 0);RParen;LCurly; (Id "k");Assign;(Id "k");Minus;(Int 1);Semi; (Id "i");Assign;(Id "i");Minus;(Int 2);Semi; RCurly]); ("forever", [(Id "forever")]); ("if_i_am", [(Id "if_i_am")]); ("elsey", [(Id "elsey")]); ("whiley", [(Id "whiley")]); ("+/*I am a comment*/5", [Plus;(Int 5)]); ] let mk_lex_combinator_test (p: (char, rtoken) parser) (expected_token: rtoken) (label: string) = let tkn_match (t1: rtoken) (t2: rtoken) : bool = match (t1, t2) with | ((Id _), (Id _)) -> true | ((Int _), (Int _)) -> true | (_,_) -> (t1 = t2) in let test_map (errors: string) (case: string * rtoken list) : string = let(code_string, tkns) = case in let cs = explode code_string in let head_token = (List.hd tkns) in match (p cs) with | Cons((tkn,_),_) -> if ((tkn_match head_token expected_token) && (tkn = head_token)) || (not(tkn_match head_token expected_token) && (tkn <> head_token)) then errors else errors ^ "\n\tExpected: " ^ (tkn2str(head_token)) ^ " Lexed: " ^ (tkn2str(tkn)) | Nil -> if (tkn_match head_token expected_token) then errors ^ "\n\tReturned no token but expected: " ^ (tkn2str(head_token)) else errors in let result = List.fold_left test_map "" lex_test_inputs in if (result <> "") then Verbose_Test(label, (fun () -> (false, "Lexing error:" ^ result))) else Verbose_Test(label, (fun () -> (true, "Lexed expected tokens"))) (* This test maker setup does not work for testing the individual Gt, Lt, Not, Eq, and keyword combinators, due to longest match rule. However, complete_combinator tests should validate them. *) let test_int_combinator = (mk_lex_combinator_test int_combinator (Int 5) "Combinator for Int");; let test_plus_combinator = (mk_lex_combinator_test plus_combinator (Plus) "Combinator for Plus");; let test_minus_combinator = (mk_lex_combinator_test minus_combinator (Minus) "Minus Combinator");; let test_times_combinator = (mk_lex_combinator_test times_combinator (Times) "Times Combinator");; let test_div_combinator = (mk_lex_combinator_test div_combinator (Div) "Div Combinator");; let test_neq_combinator = (mk_lex_combinator_test neq_combinator (Neq) "Neq Combinator");; let test_gte_combinator = (mk_lex_combinator_test gte_combinator (Gte) "Gte Combinator");; let test_lte_combinator = (mk_lex_combinator_test lte_combinator (Lte) "Lte Combinator");; let test_eq_combinator = (mk_lex_combinator_test eq_combinator (Eq) "Combinator for Eq");; let test_or_combinator = (mk_lex_combinator_test or_combinator (Or) "Or Combinator");; let test_and_combinator = (mk_lex_combinator_test and_combinator (And) "And combinator");; let test_not_combinator = (mk_lex_combinator_test not_combinator (Not) "Not combinator");; let test_lparen_combinator = (mk_lex_combinator_test lparen_combinator (LParen) "LParen combinator");; let test_rparen_combinator = (mk_lex_combinator_test rparen_combinator (RParen) "RParen combinator");; let test_lcurly_combinator = (mk_lex_combinator_test lcurly_combinator (LCurly) "LCurly combinator");; let test_rcurly_combinator = (mk_lex_combinator_test rcurly_combinator (RCurly) "RCurly combinator");; let test_complete_combinator = let label = "Complete combinator" in let test_case (errors: string) (case: string * token list) : string = let (code_string,tkns) = case in let cs = explode code_string in let head_token = List.hd tkns in match complete_combinator cs with | Cons((tkn,_),_) -> if (tkn = head_token) then errors else errors ^ "\nExpected: " ^ (tkn2str(head_token)) ^ "\nLexed: " ^ (tkn2str(tkn)) | Nil -> errors ^ "\nReturned no token but expected: " ^ (tkn2str(head_token)) in let result = List.fold_left test_case "" lex_test_inputs in if (result <> "") then Verbose_Test(label, (fun () -> (false, result))) else Verbose_Test(label, (fun () -> (true, "Lexed expected tokens")));; let test_tokenizer_snippets = let label = "Tokenize Fish snippets" in let tkn_list2str (ts: token list) = List.fold_left (fun s t -> s ^ " " ^ (tkn2str t)) "" ts in let test_case (errors: string) (case: string * token list) : string = let (code_string, tkns) = case in let cs = explode code_string in let lex = tokenize cs in if lex = tkns then errors else errors ^ "\nExpected:" ^ (tkn_list2str tkns) ^ "\nLexed: " ^ (tkn_list2str lex) in Verbose_Test(label, (fun () -> let result = List.fold_left test_case "" lex_test_inputs in ((result = ""), ( if result = "" then "Lexed expected tokens" else "Lexed tokens did not match expected:" ^ result ^ "\n"))));; run_test_set [test_int_combinator; test_plus_combinator; test_eq_combinator; test_minus_combinator; test_times_combinator; test_div_combinator; test_neq_combinator; test_gte_combinator; test_lte_combinator; test_or_combinator; test_and_combinator; test_not_combinator; test_lparen_combinator; test_rparen_combinator; test_lcurly_combinator; test_rcurly_combinator; test_complete_combinator;] "Token Combinator Tests";; run_test_set [test_tokenizer_snippets] "Tokenizer Tests";; *)
null
https://raw.githubusercontent.com/spartango/CS153/16faf133889f1b287cb95c1ea1245d76c1d8db49/ps1/fishcomb_test.ml
ocaml
Statement Parsing Tests This test maker setup does not work for testing the individual Gt, Lt, Not, Eq, and keyword combinators, due to longest match rule. However, complete_combinator tests should validate them.
open Test_framework open Lcombinators.GenericParsing open Comblexer open Ast open Combparser open Lcombinators.CharParsing open Explode open Eval open Pretty_print Tests for the Parser let test_token_equal = (mk_expect_test (fun () -> let input_tokens = [ (Comblexer.Return, 0);] in ((token_equal Comblexer.Return) input_tokens) ) (singleton ((Comblexer.Return, 0), [])) ("Token Equality Test") ) ;; let test_int_alone = Test( "Standalone Int Test", (fun () -> let input_tokens = [ (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Int(1), 0), []), _) -> true | _ -> false )) ;; let test_var_alone = Test( "Standalone Var Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Var("x"), 0), []), _) -> true | _ -> false )) ;; let test_paren_alone = Test( "Parens Simple Test", (fun () -> let input_tokens = [ (LParen, 0); (Comblexer.Id("x"), 0); (RParen, 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Var("x"), 0), []), _) -> true | _ -> false )) ;; let test_negative_int = Test( "Negative Int Test", (fun () -> let input_tokens = [ (Comblexer.Minus, 0); (Comblexer.Int(1), 0); ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons(((Ast.Int(-1), 0), []), _) -> true | _ -> false )) ;; let test_int_simple_op = Test( "Int 1 + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Int(1), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Int(1), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false ) ) ;; let test_var_simple_op = Test( "Var x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_var_var_simple_op = Test( "Var x + x Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Id("x"), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Var("x"), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_var_neg_simple_op = Test( "Var x - 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Minus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Minus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_var_and_op = Test( "Var x && 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.And, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.And( (Ast.Var("x"), 0), (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; run_test_set [ test_token_equal; test_int_alone; test_negative_int; test_var_alone; test_paren_alone; test_int_simple_op; test_var_simple_op; test_var_var_simple_op; test_var_neg_simple_op; test_var_and_op; ] "Parser Building Blocks" ;; let test_simple_var_expr = Test( "Expr x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_simple_int_expr = Test( "Expr 1 + x Test", (fun () -> let input_tokens = [ (Comblexer.Int(1), 0); (Comblexer.Plus, 0); (Comblexer.Id("x"), 0);] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Int(1), 0), Ast.Plus, (Ast.Var("x"), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_paren_var_expr = Test( "Expr (x + 1) Test", (fun () -> let input_tokens = [ (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0) ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0), []) , _ ) -> true | _ -> false )) ;; let test_rgroup_expr = Test( "Expr 2 + (x + 1) Test", (fun () -> let input_tokens = [ (Comblexer.Int(2), 0); (Comblexer.Plus, 0); (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0) ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( (Ast.Int(2), 0), Ast.Plus, ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))), 0) )), 0), []) , _ ) -> true | _ -> false )) ;; let test_not_var_expr = Test( "Expr !(x + 1) Test", (fun () -> let input_tokens = [ (Comblexer.Not, 0); (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0) ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ((Ast.Not( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0), []) , _ ) -> true | _ -> false )) ;; let test_lgroup_expr = Test( "Expr (x + 1) + 2 Test", (fun () -> let input_tokens = [ (Comblexer.LParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0); (Comblexer.Plus, 0); (Comblexer.Int(2), 0); ] in let parsed = (parse_expression input_tokens) in match parsed with | Cons( ( ((Ast.Binop( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))), 0), Ast.Plus, (Ast.Int(2), 0) )), 0), []) , _ ) -> true | _ -> false )) ;; run_test_set [ test_simple_var_expr; test_simple_int_expr; test_paren_var_expr; test_rgroup_expr; test_lgroup_expr; test_not_var_expr; ] "Expression Parsing" ;; let test_s_expr = Test( "Statement x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); ] in let parsed = (parse_statement input_tokens) in match parsed with | Cons( ( (Ast.Exp( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0), []) , _ ) -> true | _ -> false )) ;; let test_return = Test( "Statement return x + 1 Test", (fun () -> let input_tokens = [ (Comblexer.Return, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); ] in let parsed = (parse_statement input_tokens) in match parsed with | Cons( ( (Ast.Return( ((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0), []) , _ ) -> true | _ -> false )) ;; let test_seq = Test( "Statement { x + 1; y + 1; } Test", (fun () -> let input_tokens = [ (Comblexer.LCurly, 0); (Comblexer.Id("x"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.Semi, 0); (Comblexer.Id("y"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RCurly, 0); ] in let parsed = (parse_statement input_tokens) in match parsed with | Cons( ( (Ast.Seq( (Ast.Seq( _ , (Ast.Exp(((Ast.Binop( (Ast.Var("x"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0)), 0), (Ast.Exp(((Ast.Binop( (Ast.Var("y"), 0), Ast.Plus, (Ast.Int(1), 0))) , 0)), 0) ) , 0) , []) , _ ) -> true | _ -> false )) ;; let test_while = Test( "Simple While loop Test", (fun () -> let input_tokens = [ (Comblexer.While, 0); (Comblexer.LParen, 0); (Comblexer.Int(0), 0); (Comblexer.RParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Semi, 0); ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.While( (Ast.Int(0), 0), (Ast.Exp( (Ast.Var("x"), 0)), 0) ), 0), []), _) -> true | _ -> false )) ;; let test_if = Test( "Simple If statement Test", (fun () -> let input_tokens = [ (Comblexer.If, 0); (Comblexer.LParen, 0); (Comblexer.Int(0), 0); (Comblexer.RParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Semi, 0); ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.If( (Ast.Int(0), 0), (Ast.Exp( (Ast.Var("x"), 0)), 0), _ ), 0), []), _) -> true | _ -> false )) ;; let test_if_else = Test( "If else statement Test", (fun () -> let input_tokens = [ (Comblexer.If, 0); (Comblexer.LParen, 0); (Comblexer.Int(0), 0); (Comblexer.RParen, 0); (Comblexer.Id("x"), 0); (Comblexer.Semi, 0); (Comblexer.Else, 0); (Comblexer.Id("y"), 0); (Comblexer.Semi, 0); ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.If( (Ast.Int(0), 0), (Ast.Exp( (Ast.Var("x"), 0)), 0), (Ast.Exp( (Ast.Var("y"), 0)), 0) ), 0), []), _) -> true | _ -> false )) ;; let test_for = Test( "For loop Test", (fun () -> let input_tokens = [ (Comblexer.For, 0); (Comblexer.LParen, 0); (Comblexer.Id("i"), 0); (Comblexer.Assign, 0); (Comblexer.Int(0), 0); (Comblexer.Semi, 0); (Comblexer.Id("i"), 0); (Comblexer.Eq, 0); (Comblexer.Int(1), 0); (Comblexer.Semi, 0); (Comblexer.Id("i"), 0); (Comblexer.Assign, 0); (Comblexer.Id("i"), 0); (Comblexer.Plus, 0); (Comblexer.Int(1), 0); (Comblexer.RParen, 0); (Comblexer.Id("i"), 0); (Comblexer.Semi, 0) ] in let parsed = parse_statement input_tokens in match parsed with | Cons( ( (Ast.For( (Ast.Assign( "i", (Ast.Int(0), 0)), 0), (Ast.Binop( (Ast.Var("i"), 0), Ast.Eq, (Ast.Int(1), 0)), 0), (Ast.Assign( "i", (Ast.Binop( (Ast.Var("i"), 0), Ast.Plus, (Ast.Int(1), 0)), 0)), 0), (Ast.Exp( (Ast.Var("i"), 0)), 0)), 0), []), _) -> true; | _ -> false )) ;; run_test_set [ test_s_expr; test_return; test_seq; test_while; test_if; test_if_else; test_for; ] "Statement Parsing" ;; let mk_parse_test (file: string) = let label = "Lexing & Parsing " ^ file in Verbose_Test(label, (fun()-> try let ic = (open_in file) in let file_contents = (read_file ic "") in let _ = print_string ( ( format_string " [ RUNNING ] " Bright Cyan ) ^ ( String.escaped file_contents ) ^ " \n " ) in ((format_string "[ RUNNING ] " Bright Cyan) ^ (String.escaped file_contents) ^ "\n") in *) let rslt = eval (parse (tokenize ( explode file_contents ))) in (true, "Parsed with answer " ^ string_of_int rslt) with LexError -> (false, ( format_string "Lexer Failed" Bright Red)) | IntInvalidSyntax -> (false, ( format_string "Int Parser Failed" Bright Red)) | VarInvalidSyntax -> (false, ( format_string "Var Parser Failed" Bright Red)) | ParenInvalidSyntax -> (false, ( format_string "Paren Parser Failed" Bright Red)) | NoParses -> (false, (format_string "No parses" Bright Red)) )) let file_list = [ "test/01cexpr_01add.fish"; "test/01cexpr_02sub.fish"; "test/01cexpr_03mul.fish"; "test/01cexpr_04div.fish"; "test/01cexpr_05eq.fish"; "test/01cexpr_06neq.fish"; "test/01cexpr_07gt.fish"; "test/01cexpr_08gte.fish"; "test/01cexpr_09lt.fish"; "test/01cexpr_10lte.fish"; "test/01cexpr_11uminus.fish"; "test/01cexpr_12not.fish"; "test/01cexpr_13and.fish"; "test/01cexpr_14or.fish"; "test/01cexpr_15bigcon.fish"; "test/01cexpr_16bigcon.fish"; "test/02vexpr_01add.fish"; "test/02vexpr_02sub.fish"; "test/02vexpr_03mul.fish"; "test/02vexpr_04div.fish"; "test/02vexpr_05eq.fish"; "test/02vexpr_06neq.fish"; "test/02vexpr_07gt.fish"; "test/02vexpr_08gte.fish"; "test/02vexpr_09lt.fish"; "test/02vexpr_10lte.fish"; "test/02vexpr_11uminus.fish"; "test/02vexpr_12not.fish"; "test/02vexpr_13and.fish"; "test/02vexpr_14or.fish"; "test/02vexpr_15assignval.fish"; "test/03stmt_01if.fish"; "test/03stmt_02if.fish"; "test/03stmt_03while.fish"; "test/03stmt_04for.fish"; "test/03stmt_05if.fish"; "test/03stmt_06for.fish"; "test/04opt_01cfoldif.fish"; "test/04opt_02cfoldif.fish"; "test/09all_01adder.fish"; "test/09all_02fibo.fish"; ] ;; run_test_set (List.map mk_parse_test file_list) "Parse Test Files";; let lex_test_inputs = [ ( " foo " , [ ( I d " foo " ) ] ) ; ( " foo = baz " , [ ( I d " foo " ) ; Comblexer . Assign ; ( I d " baz " ) ] ) ; ( " 5 " , [ ( Comblexer . Int 5 ) ] ) ; ( " 5 + 9 " , [ ( Comblexer . Int 5);Plus;(Int 9 ) ] ) ; ( " + " , [ Plus ] ) ; ( " + foo " , [ Plus ; ( I d " foo " ) ] ) ; ( " = " , [ Assign ] ) ; ( " = foo " , [ Assign ; ( I d " foo " ) ] ) ; ( " - " , [ Minus ] ) ; ( " -foo+foo " , [ Minus ; ( I d " foo " ) ; Plus ; ( I d " foo " ) ] ) ; ( " * " , [ Times ] ) ; ( " * 5 = foo " , [ Times ; ( Int 5 ) ; Assign ; ( I d " foo " ) ] ) ; ( " / " , [ Div ] ) ; ( " /feed = foo " , [ Div ; ( I d " feed " ) ; Assign ; ( I d " foo " ) ] ) ; ( " ! = " , [ Neq ] ) ; ( " ! = foo " , [ Neq ; ( I d " foo " ) ] ) ; ( " > = " , [ Gte ] ) ; ( " > = 55 " , [ ; ( Int 55 ) ] ) ; ( " > " , [ Gt ] ) ; ( " > foo+5 " , [ " foo");Plus;(Int 5 ) ] ) ; ( " < = " , [ Lte ] ) ; ( " < = foo " , [ " foo " ) ] ) ; ( " = = " , [ Eq ] ) ; ( " = = foo " , [ Eq;(Id " foo " ) ] ) ; ( " ! " , [ Not ] ) ; ( " ! 0 " , [ Not;(Int 0 ) ] ) ; ( " || " , [ Or ] ) ; ( " ||5>=0 " , [ Or;(Int 5);Gte;(Int 0 ) ] ) ; ( " & & " , [ And ] ) ; ( " & & 6<=34 " , [ And;(Int 6);Lte;(Int 34 ) ] ) ; ( " ( " , [ LParen ] ) ; ( " ( 8) " , [ LParen;(Int 8);RParen ] ) ; ( " ) " , [ RParen ] ) ; ( " ) =( & & " , [ RParen;Assign;LParen;And ] ) ; ( " { " , [ LCurly ] ) ; ( " } " , [ RCurly ] ) ; ( " for{i=4;i<=6;i = i+1 } " , [ For;LCurly;(Id " i");Assign;(Int 4);Semi;(Id " i");Lte ; ( Int 6);Semi;(Id " i");Assign;(Id " i");Plus;(Int 1 ) ; RCurly ] ) ; ( " if(i==5){k=2;}else{k=1 ; } " , [ If;LParen;(Id " i");Eq;(Int 5);RParen;LCurly ; ( I d " k");Assign;(Int 2);Semi;RCurly;Else;LCurly ; ( I d " k");Assign;(Int 1);Semi;RCurly ] ) ; ( " while(i>=0){k = k-1;i = i-2 ; } " , [ " i");Gte;(Int 0);RParen;LCurly ; ( I d " k");Assign;(Id " k");Minus;(Int 1);Semi ; ( I d " i");Assign;(Id " i");Minus;(Int 2);Semi ; RCurly ] ) ; ( " forever " , [ ( I d " forever " ) ] ) ; ( " " , [ ( I d " " ) ] ) ; ( " elsey " , [ ( I d " elsey " ) ] ) ; ( " whiley " , [ ( I d " " ) ] ) ; ( " + /*I am a comment*/5 " , [ Plus;(Int 5 ) ] ) ; ] let mk_lex_combinator_test ( p : ( char , rtoken ) parser ) ( expected_token : rtoken ) ( label : string ) = let tkn_match ( t1 : ) ( t2 : ) : match ( t1 , t2 ) with | ( ( I d _ ) , ( I d _ ) ) - > true | ( ( Int _ ) , ( Int _ ) ) - > true | ( _ , _ ) - > ( t1 = t2 ) in let test_map ( errors : string ) ( case : string * rtoken list ) : string = let(code_string , tkns ) = case in let cs = explode code_string in let head_token = ( List.hd tkns ) in match ( p cs ) with | Cons((tkn , _ ) , _ ) - > if ( ( tkn_match head_token expected_token ) & & ( tkn = head_token ) ) || ( not(tkn_match head_token expected_token ) & & ( tkn < > head_token ) ) then errors else errors ^ " \n\tExpected : " ^ ( tkn2str(head_token ) ) ^ " : " ^ ( ) ) | Nil - > if ( tkn_match head_token expected_token ) then errors ^ " \n\tReturned no token but expected : " ^ ( tkn2str(head_token ) ) else errors in let result = List.fold_left test_map " " lex_test_inputs in if ( result < > " " ) then Verbose_Test(label , ( fun ( ) - > ( false , " Lexing error : " ^ result ) ) ) else Verbose_Test(label , ( fun ( ) - > ( true , " Lexed expected tokens " ) ) ) ( * This test maker setup does not work for testing the individual Gt , Lt , Not , , and keyword combinators , due to longest match rule . However , complete_combinator tests should validate them . let lex_test_inputs = [ ("foo", [(Id "foo")]); ("foo=baz", [(Id "foo"); Comblexer.Assign; (Id "baz")]); ("5", [(Comblexer.Int 5)]); ("5+9", [(Comblexer.Int 5);Plus;(Int 9)]); ("+", [Plus]); ("+foo", [Plus; (Id "foo")]); ("=", [Assign]); ("=foo", [Assign; (Id "foo")]); ("-", [Minus]); ("-foo+foo", [Minus; (Id "foo"); Plus; (Id "foo")]); ("*", [Times]); ("*5=foo", [Times; (Int 5); Assign; (Id "foo")]); ("/", [Div]); ("/feed=foo", [Div; (Id "feed"); Assign; (Id "foo")]); ("!=", [Neq]); ("!=foo", [Neq; (Id "foo")]); (">=", [Gte]); (">=55", [Gte; (Int 55)]); (">", [Gt]); (">foo+5", [Gt;(Id "foo");Plus;(Int 5)]); ("<=", [Lte]); ("<=foo", [Lte;(Id "foo")]); ("==", [Eq]); ("==foo", [Eq;(Id "foo")]); ("!", [Not]); ("!0", [Not;(Int 0)]); ("||", [Or]); ("||5>=0", [Or;(Int 5);Gte;(Int 0)]); ("&&", [And]); ("&&6<=34", [And;(Int 6);Lte;(Int 34)]); ("(", [LParen]); ("(8)", [LParen;(Int 8);RParen]); (")", [RParen]); (")=(&&", [RParen;Assign;LParen;And]); ("{", [LCurly]); ("}", [RCurly]); ("for{i=4;i<=6;i=i+1}", [For;LCurly;(Id "i");Assign;(Int 4);Semi;(Id "i");Lte; (Int 6);Semi;(Id "i");Assign;(Id "i");Plus;(Int 1); RCurly]); ("if(i==5){k=2;}else{k=1;}", [If;LParen;(Id "i");Eq;(Int 5);RParen;LCurly; (Id "k");Assign;(Int 2);Semi;RCurly;Else;LCurly; (Id "k");Assign;(Int 1);Semi;RCurly]); ("while(i>=0){k=k-1;i=i-2;}", [While;LParen;(Id "i");Gte;(Int 0);RParen;LCurly; (Id "k");Assign;(Id "k");Minus;(Int 1);Semi; (Id "i");Assign;(Id "i");Minus;(Int 2);Semi; RCurly]); ("forever", [(Id "forever")]); ("if_i_am", [(Id "if_i_am")]); ("elsey", [(Id "elsey")]); ("whiley", [(Id "whiley")]); ("+/*I am a comment*/5", [Plus;(Int 5)]); ] let mk_lex_combinator_test (p: (char, rtoken) parser) (expected_token: rtoken) (label: string) = let tkn_match (t1: rtoken) (t2: rtoken) : bool = match (t1, t2) with | ((Id _), (Id _)) -> true | ((Int _), (Int _)) -> true | (_,_) -> (t1 = t2) in let test_map (errors: string) (case: string * rtoken list) : string = let(code_string, tkns) = case in let cs = explode code_string in let head_token = (List.hd tkns) in match (p cs) with | Cons((tkn,_),_) -> if ((tkn_match head_token expected_token) && (tkn = head_token)) || (not(tkn_match head_token expected_token) && (tkn <> head_token)) then errors else errors ^ "\n\tExpected: " ^ (tkn2str(head_token)) ^ " Lexed: " ^ (tkn2str(tkn)) | Nil -> if (tkn_match head_token expected_token) then errors ^ "\n\tReturned no token but expected: " ^ (tkn2str(head_token)) else errors in let result = List.fold_left test_map "" lex_test_inputs in if (result <> "") then Verbose_Test(label, (fun () -> (false, "Lexing error:" ^ result))) else Verbose_Test(label, (fun () -> (true, "Lexed expected tokens"))) let test_int_combinator = (mk_lex_combinator_test int_combinator (Int 5) "Combinator for Int");; let test_plus_combinator = (mk_lex_combinator_test plus_combinator (Plus) "Combinator for Plus");; let test_minus_combinator = (mk_lex_combinator_test minus_combinator (Minus) "Minus Combinator");; let test_times_combinator = (mk_lex_combinator_test times_combinator (Times) "Times Combinator");; let test_div_combinator = (mk_lex_combinator_test div_combinator (Div) "Div Combinator");; let test_neq_combinator = (mk_lex_combinator_test neq_combinator (Neq) "Neq Combinator");; let test_gte_combinator = (mk_lex_combinator_test gte_combinator (Gte) "Gte Combinator");; let test_lte_combinator = (mk_lex_combinator_test lte_combinator (Lte) "Lte Combinator");; let test_eq_combinator = (mk_lex_combinator_test eq_combinator (Eq) "Combinator for Eq");; let test_or_combinator = (mk_lex_combinator_test or_combinator (Or) "Or Combinator");; let test_and_combinator = (mk_lex_combinator_test and_combinator (And) "And combinator");; let test_not_combinator = (mk_lex_combinator_test not_combinator (Not) "Not combinator");; let test_lparen_combinator = (mk_lex_combinator_test lparen_combinator (LParen) "LParen combinator");; let test_rparen_combinator = (mk_lex_combinator_test rparen_combinator (RParen) "RParen combinator");; let test_lcurly_combinator = (mk_lex_combinator_test lcurly_combinator (LCurly) "LCurly combinator");; let test_rcurly_combinator = (mk_lex_combinator_test rcurly_combinator (RCurly) "RCurly combinator");; let test_complete_combinator = let label = "Complete combinator" in let test_case (errors: string) (case: string * token list) : string = let (code_string,tkns) = case in let cs = explode code_string in let head_token = List.hd tkns in match complete_combinator cs with | Cons((tkn,_),_) -> if (tkn = head_token) then errors else errors ^ "\nExpected: " ^ (tkn2str(head_token)) ^ "\nLexed: " ^ (tkn2str(tkn)) | Nil -> errors ^ "\nReturned no token but expected: " ^ (tkn2str(head_token)) in let result = List.fold_left test_case "" lex_test_inputs in if (result <> "") then Verbose_Test(label, (fun () -> (false, result))) else Verbose_Test(label, (fun () -> (true, "Lexed expected tokens")));; let test_tokenizer_snippets = let label = "Tokenize Fish snippets" in let tkn_list2str (ts: token list) = List.fold_left (fun s t -> s ^ " " ^ (tkn2str t)) "" ts in let test_case (errors: string) (case: string * token list) : string = let (code_string, tkns) = case in let cs = explode code_string in let lex = tokenize cs in if lex = tkns then errors else errors ^ "\nExpected:" ^ (tkn_list2str tkns) ^ "\nLexed: " ^ (tkn_list2str lex) in Verbose_Test(label, (fun () -> let result = List.fold_left test_case "" lex_test_inputs in ((result = ""), ( if result = "" then "Lexed expected tokens" else "Lexed tokens did not match expected:" ^ result ^ "\n"))));; run_test_set [test_int_combinator; test_plus_combinator; test_eq_combinator; test_minus_combinator; test_times_combinator; test_div_combinator; test_neq_combinator; test_gte_combinator; test_lte_combinator; test_or_combinator; test_and_combinator; test_not_combinator; test_lparen_combinator; test_rparen_combinator; test_lcurly_combinator; test_rcurly_combinator; test_complete_combinator;] "Token Combinator Tests";; run_test_set [test_tokenizer_snippets] "Tokenizer Tests";; *)
3f01c4efaaadab58e14a1ea7a4934e2865306114b76b0f25645e8b9125e86ea7
coco-team/lustrec
horn_backend.ml
(********************************************************************) (* *) The LustreC compiler toolset / The LustreC Development Team Copyright 2012 - -- ONERA - CNRS - INPT (* *) (* LustreC is free software, distributed WITHOUT ANY WARRANTY *) (* under the terms of the GNU Lesser General Public License *) version 2.1 . (* *) (********************************************************************) The compilation presented here was first defined in Garoche , Gurfinkel , Kahsai , HCSV'14 . This is a modified version that handles reset and automaton Kahsai, HCSV'14. This is a modified version that handles reset and automaton *) open Format open Lustre_types open Corelang open Machine_code_types open Horn_backend_common open Horn_backend_printers open Horn_backend_collecting_sem TODO : - gerer les traces . l'instant dans le calcul des memoires sur les arrows - gerer le reset --- DONE - reconstruire les rechable states DONE - reintroduire le cex / traces ... DONE - traiter les types enum et les branchements sur ces types enum ( en particulier les traitements des resets qui ont lieu dans certaines branches et pas dans d'autres ) TODO: - gerer les traces. Ca merde pour l'instant dans le calcul des memoires sur les arrows - gerer le reset --- DONE - reconstruire les rechable states DONE - reintroduire le cex/traces ... DONE - traiter les types enum et les branchements sur ces types enum (en particulier les traitements des resets qui ont lieu dans certaines branches et pas dans d'autres ) *) let main_print machines fmt = if !Options.main_node <> "" then begin let node = !Options.main_node in let machine = get_machine machines node in if !Options.horn_cex then( cex_computation machines fmt node machine; get_cex machines fmt node machine) else ( collecting_semantics machines fmt node machine; check_prop machines fmt node machine; ) end let load_file f = let ic = open_in f in let n = in_channel_length ic in let s = Bytes.create n in really_input ic s 0 n; close_in ic; Bytes.to_string s let print_type_definitions fmt = let cpt_type = ref 0 in Hashtbl.iter (fun typ decl -> match typ with | Tydec_const var -> (match decl.top_decl_desc with | TypeDef tdef -> ( match tdef.tydef_desc with | Tydec_enum tl -> incr cpt_type; fprintf fmt "(declare-datatypes () ((%s %a)));@.@." var (Utils.fprintf_list ~sep:" " pp_print_string) tl | _ -> assert false ) | _ -> assert false ) | _ -> ()) type_table let print_dep fmt prog = Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 2>.. extracting Horn libraries@,"); fprintf fmt "; Statically linked libraries@,"; let dependencies = Corelang.get_dependencies prog in List.iter (fun dep -> let (local, s) = Corelang.dependency_of_top dep in let basename = (Options_management.name_dependency (local, s)) ^ ".smt2" in Log.report ~level:1 (fun fmt -> Format.fprintf fmt "@[<v 0> Horn Library %s@," basename); let horn = load_file basename in fprintf fmt "@.%s@." (horn); ) dependencies let check_sfunction mannot = (*Check if its an sfunction*) match mannot with [] -> false | [x] -> begin match x.annots with [] -> false |[(key,va)] -> begin match key with [] -> false | [x] -> x == "c_code" || x =="matlab" | _ -> false end |(_,_)::_ -> false end | _::_ -> false let preprocess machines = List.fold_right (fun m res -> if List.mem m.mname.node_id registered_keywords then { m with mname = { m.mname with node_id = protect_kwd m.mname.node_id }}::res else m :: res ) machines [] let translate fmt basename prog machines= let machines = preprocess machines in (* We print typedef *) print_dep fmt prog; (*print static library e.g. math*) print_type_definitions fmt; (*List.iter (print_machine machines fmt) (List.rev machines);*) List.iter(fun m -> let is_sfunction = check_sfunction m.mannot in if is_sfunction then( Log.report ~level:1 (fun fmt -> fprintf fmt ".. detected sfunction: %s@," m.mname.node_id); print_sfunction machines fmt m ) else ( print_machine machines fmt m) ) (List.rev machines); main_print machines fmt (* Local Variables: *) (* compile-command:"make -C ../.." *) (* End: *)
null
https://raw.githubusercontent.com/coco-team/lustrec/b21f9820df97e661633cd4418fdab68a6c6ca67d/src/backends/Horn/horn_backend.ml
ocaml
****************************************************************** LustreC is free software, distributed WITHOUT ANY WARRANTY under the terms of the GNU Lesser General Public License ****************************************************************** Check if its an sfunction We print typedef print static library e.g. math List.iter (print_machine machines fmt) (List.rev machines); Local Variables: compile-command:"make -C ../.." End:
The LustreC compiler toolset / The LustreC Development Team Copyright 2012 - -- ONERA - CNRS - INPT version 2.1 . The compilation presented here was first defined in Garoche , Gurfinkel , Kahsai , HCSV'14 . This is a modified version that handles reset and automaton Kahsai, HCSV'14. This is a modified version that handles reset and automaton *) open Format open Lustre_types open Corelang open Machine_code_types open Horn_backend_common open Horn_backend_printers open Horn_backend_collecting_sem TODO : - gerer les traces . l'instant dans le calcul des memoires sur les arrows - gerer le reset --- DONE - reconstruire les rechable states DONE - reintroduire le cex / traces ... DONE - traiter les types enum et les branchements sur ces types enum ( en particulier les traitements des resets qui ont lieu dans certaines branches et pas dans d'autres ) TODO: - gerer les traces. Ca merde pour l'instant dans le calcul des memoires sur les arrows - gerer le reset --- DONE - reconstruire les rechable states DONE - reintroduire le cex/traces ... DONE - traiter les types enum et les branchements sur ces types enum (en particulier les traitements des resets qui ont lieu dans certaines branches et pas dans d'autres ) *) let main_print machines fmt = if !Options.main_node <> "" then begin let node = !Options.main_node in let machine = get_machine machines node in if !Options.horn_cex then( cex_computation machines fmt node machine; get_cex machines fmt node machine) else ( collecting_semantics machines fmt node machine; check_prop machines fmt node machine; ) end let load_file f = let ic = open_in f in let n = in_channel_length ic in let s = Bytes.create n in really_input ic s 0 n; close_in ic; Bytes.to_string s let print_type_definitions fmt = let cpt_type = ref 0 in Hashtbl.iter (fun typ decl -> match typ with | Tydec_const var -> (match decl.top_decl_desc with | TypeDef tdef -> ( match tdef.tydef_desc with | Tydec_enum tl -> incr cpt_type; fprintf fmt "(declare-datatypes () ((%s %a)));@.@." var (Utils.fprintf_list ~sep:" " pp_print_string) tl | _ -> assert false ) | _ -> assert false ) | _ -> ()) type_table let print_dep fmt prog = Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 2>.. extracting Horn libraries@,"); fprintf fmt "; Statically linked libraries@,"; let dependencies = Corelang.get_dependencies prog in List.iter (fun dep -> let (local, s) = Corelang.dependency_of_top dep in let basename = (Options_management.name_dependency (local, s)) ^ ".smt2" in Log.report ~level:1 (fun fmt -> Format.fprintf fmt "@[<v 0> Horn Library %s@," basename); let horn = load_file basename in fprintf fmt "@.%s@." (horn); ) dependencies let check_sfunction mannot = match mannot with [] -> false | [x] -> begin match x.annots with [] -> false |[(key,va)] -> begin match key with [] -> false | [x] -> x == "c_code" || x =="matlab" | _ -> false end |(_,_)::_ -> false end | _::_ -> false let preprocess machines = List.fold_right (fun m res -> if List.mem m.mname.node_id registered_keywords then { m with mname = { m.mname with node_id = protect_kwd m.mname.node_id }}::res else m :: res ) machines [] let translate fmt basename prog machines= let machines = preprocess machines in print_type_definitions fmt; List.iter(fun m -> let is_sfunction = check_sfunction m.mannot in if is_sfunction then( Log.report ~level:1 (fun fmt -> fprintf fmt ".. detected sfunction: %s@," m.mname.node_id); print_sfunction machines fmt m ) else ( print_machine machines fmt m) ) (List.rev machines); main_print machines fmt
e4de20cf4199cff438d326d6a912a1efb0c6321629ed2104a063f6b1c5cdbcd1
GaloisInc/halfs
Types.hs
This module contains types and instances common to most of Halfs # LANGUAGE GeneralizedNewtypeDeriving # module Halfs.Types where import Control.Applicative import Control.Monad import Data.Bits import qualified Data.Map as M import Data.List (sort) import Data.Serialize import Data.Word import Halfs.Protection -------------------------------------------------------------------------------- Common Types newtype Ref a = Ref Word64 deriving (Eq, Ord, Num, Show, Integral, Enum, Real) instance Serialize (Ref a) where put (Ref x) = putWord64be x get = Ref `fmap` getWord64be We store / Ext references as simple Word64s , newtype'd in case -- we either decide to do something more fancy or just to make the types -- a bit more clear. -- -- At this point, we assume a reference is equal to its block address, -- and we fix references as Word64s. Note that if you change the -- underlying field size of an InodeRef/ExtRef, you *really* (!) need -- to change 'refSize', below. -- newtype InodeRef = IR { unIR :: Word64 } deriving (Eq, Ord, Num, Show, Integral, Enum, Real) newtype ExtRef = ER { unER :: Word64 } deriving (Eq, Show) instance Serialize InodeRef where put (IR x) = putWord64be x get = IR `fmap` getWord64be instance Serialize ExtRef where put (ER x) = putWord64be x get = ER `fmap` getWord64be | The size of an / Ext reference in bytes refSize :: Word64 refSize = 8 -- | A simple locked resource reference data LockedRscRef l r rsc = LockedRscRef { lrLock :: l , lrRsc :: r rsc } -------------------------------------------------------------------------------- Common Directory and File Types -- File names are arbitrary-length, null-terminated strings. Valid file names are guaranteed to not include null or the System . FilePath.pathSeparator -- character. -- Current directory and parent directory relative path names dotPath, dotdotPath :: FilePath dotPath = "." dotdotPath = ".." -- | DF_WrongFileType implies the filesystem element with the search key -- was found but was not of the correct type. data DirFindRslt a = DF_NotFound | DF_WrongFileType FileType | DF_Found (a, FileType) data DirectoryEntry = DirEnt { deName :: String , deInode :: InodeRef , deUser :: UserID , deGroup :: GroupID , deMode :: FileMode , deType :: FileType } deriving (Show, Eq) data DirHandle r l = DirHandle { dhInode :: r (Maybe InodeRef) , dhContents :: r (M.Map FilePath DirectoryEntry) , dhState :: r DirectoryState , dhLock :: l } data FileHandle r l = FH { fhReadable :: Bool , fhWritable :: Bool , _fhFlags :: FileOpenFlags Maybe to denote FileHandle invalidation , fhLock :: l -- Ensures sequential access to the INR } data AccessRight = Read | Write | Execute deriving (Show, Eq, Ord) Isomorphic to System . . IO.OpenMode , but present here to avoid explicit dependency on the module(s ) . data FileOpenMode = ReadOnly | WriteOnly | ReadWrite deriving (Eq, Show) Similar to System . . IO.OpenFileFlags , but present here to avoid explicit dependency on the module(s ) . data FileOpenFlags = FileOpenFlags { append :: Bool -- append on each write , nonBlock :: Bool -- do not block on open or for data to become avail Always False from HFuse 0.2.2 ! , explicit : : Bool -- atomically obtain an exclusive lock , truncate : : Bool -- truncate size to 0 , explicit :: Bool -- atomically obtain an exclusive lock , truncate :: Bool -- truncate size to 0 -} Not yet supported by halfs , noctty : : isomorphic to System . . IO.OpenMode } deriving (Show) data DirectoryState = Clean | OnlyAdded | OnlyDeleted | VeryDirty deriving (Show, Eq) data FileMode = FileMode { fmOwnerPerms :: [AccessRight] , fmGroupPerms :: [AccessRight] , fmUserPerms :: [AccessRight] } deriving (Show) data FileType = RegularFile | Directory | Symlink | AnyFileType deriving (Show, Eq) data FileStat t = FileStat { fsInode :: InodeRef , fsType :: FileType , fsMode :: FileMode , fsNumLinks :: Word64 -- ^ Number of hardlinks to the file , fsUID :: UserID , fsGID :: GroupID , fsSize :: Word64 -- ^ File size, in bytes , fsNumBlocks :: Word64 -- ^ Number of blocks allocated , fsAccessTime :: t -- ^ Time of last access , fsModifyTime :: t -- ^ Time of last data modification , fsChangeTime :: t -- ^ Time of last status (inode) change } deriving Show -------------------------------------------------------------------------------- -- Misc Instances instance Serialize DirectoryEntry where put de = do put $ deName de put $ deInode de put $ deUser de put $ deGroup de put $ deMode de put $ deType de get = DirEnt <$> get <*> get <*> get <*> get <*> get <*> get instance Serialize FileType where put RegularFile = putWord8 0x0 put Directory = putWord8 0x1 put Symlink = putWord8 0x2 put _ = fail "Invalid FileType during serialize" -- get = getWord8 >>= \x -> case x of 0x0 -> return RegularFile 0x1 -> return Directory 0x2 -> return Symlink _ -> fail "Invalid FileType during deserialize" instance Serialize FileMode where put FileMode{ fmOwnerPerms = op, fmGroupPerms = gp, fmUserPerms = up } = do when (any (>3) $ map length [op, gp, up]) $ fail "Fixed-length check failed in FileMode serialization" putWord8 $ perms op putWord8 $ perms gp putWord8 $ perms up where perms ps = foldr (.|.) 0x0 $ flip map ps $ \x -> -- toBit case x of Read -> 4 ; Write -> 2; Execute -> 1 -- get = FileMode <$> gp <*> gp <*> gp where gp = fromBits `fmap` getWord8 fromBits x = let x0 = if testBit x 0 then [Execute] else [] x1 = if testBit x 1 then Write:x0 else x0 x2 = if testBit x 2 then Read:x1 else x1 in x2 instance Eq FileMode where fm1 == fm2 = sort (fmOwnerPerms fm1) == sort (fmOwnerPerms fm2) && sort (fmGroupPerms fm1) == sort (fmGroupPerms fm2) && sort (fmUserPerms fm1) == sort (fmUserPerms fm2) instance Functor DirFindRslt where fmap _ DF_NotFound = DF_NotFound fmap _ (DF_WrongFileType ft) = DF_WrongFileType ft fmap f (DF_Found (r, a)) = DF_Found (f r, a)
null
https://raw.githubusercontent.com/GaloisInc/halfs/2eb16fb3744e6221ee706b6bd290681a08c18048/Halfs/Types.hs
haskell
------------------------------------------------------------------------------ we either decide to do something more fancy or just to make the types a bit more clear. At this point, we assume a reference is equal to its block address, and we fix references as Word64s. Note that if you change the underlying field size of an InodeRef/ExtRef, you *really* (!) need to change 'refSize', below. | A simple locked resource reference ------------------------------------------------------------------------------ File names are arbitrary-length, null-terminated strings. Valid file names character. Current directory and parent directory relative path names | DF_WrongFileType implies the filesystem element with the search key was found but was not of the correct type. Ensures sequential access to the INR append on each write do not block on open or for data to become avail atomically obtain an exclusive lock truncate size to 0 atomically obtain an exclusive lock truncate size to 0 ^ Number of hardlinks to the file ^ File size, in bytes ^ Number of blocks allocated ^ Time of last access ^ Time of last data modification ^ Time of last status (inode) change ------------------------------------------------------------------------------ Misc Instances toBit
This module contains types and instances common to most of Halfs # LANGUAGE GeneralizedNewtypeDeriving # module Halfs.Types where import Control.Applicative import Control.Monad import Data.Bits import qualified Data.Map as M import Data.List (sort) import Data.Serialize import Data.Word import Halfs.Protection Common Types newtype Ref a = Ref Word64 deriving (Eq, Ord, Num, Show, Integral, Enum, Real) instance Serialize (Ref a) where put (Ref x) = putWord64be x get = Ref `fmap` getWord64be We store / Ext references as simple Word64s , newtype'd in case newtype InodeRef = IR { unIR :: Word64 } deriving (Eq, Ord, Num, Show, Integral, Enum, Real) newtype ExtRef = ER { unER :: Word64 } deriving (Eq, Show) instance Serialize InodeRef where put (IR x) = putWord64be x get = IR `fmap` getWord64be instance Serialize ExtRef where put (ER x) = putWord64be x get = ER `fmap` getWord64be | The size of an / Ext reference in bytes refSize :: Word64 refSize = 8 data LockedRscRef l r rsc = LockedRscRef { lrLock :: l , lrRsc :: r rsc } Common Directory and File Types are guaranteed to not include null or the System . FilePath.pathSeparator dotPath, dotdotPath :: FilePath dotPath = "." dotdotPath = ".." data DirFindRslt a = DF_NotFound | DF_WrongFileType FileType | DF_Found (a, FileType) data DirectoryEntry = DirEnt { deName :: String , deInode :: InodeRef , deUser :: UserID , deGroup :: GroupID , deMode :: FileMode , deType :: FileType } deriving (Show, Eq) data DirHandle r l = DirHandle { dhInode :: r (Maybe InodeRef) , dhContents :: r (M.Map FilePath DirectoryEntry) , dhState :: r DirectoryState , dhLock :: l } data FileHandle r l = FH { fhReadable :: Bool , fhWritable :: Bool , _fhFlags :: FileOpenFlags Maybe to denote FileHandle invalidation } data AccessRight = Read | Write | Execute deriving (Show, Eq, Ord) Isomorphic to System . . IO.OpenMode , but present here to avoid explicit dependency on the module(s ) . data FileOpenMode = ReadOnly | WriteOnly | ReadWrite deriving (Eq, Show) Similar to System . . IO.OpenFileFlags , but present here to avoid explicit dependency on the module(s ) . data FileOpenFlags = FileOpenFlags Always False from HFuse 0.2.2 ! -} Not yet supported by halfs , noctty : : isomorphic to System . . IO.OpenMode } deriving (Show) data DirectoryState = Clean | OnlyAdded | OnlyDeleted | VeryDirty deriving (Show, Eq) data FileMode = FileMode { fmOwnerPerms :: [AccessRight] , fmGroupPerms :: [AccessRight] , fmUserPerms :: [AccessRight] } deriving (Show) data FileType = RegularFile | Directory | Symlink | AnyFileType deriving (Show, Eq) data FileStat t = FileStat { fsInode :: InodeRef , fsType :: FileType , fsMode :: FileMode , fsUID :: UserID , fsGID :: GroupID } deriving Show instance Serialize DirectoryEntry where put de = do put $ deName de put $ deInode de put $ deUser de put $ deGroup de put $ deMode de put $ deType de get = DirEnt <$> get <*> get <*> get <*> get <*> get <*> get instance Serialize FileType where put RegularFile = putWord8 0x0 put Directory = putWord8 0x1 put Symlink = putWord8 0x2 put _ = fail "Invalid FileType during serialize" get = getWord8 >>= \x -> case x of 0x0 -> return RegularFile 0x1 -> return Directory 0x2 -> return Symlink _ -> fail "Invalid FileType during deserialize" instance Serialize FileMode where put FileMode{ fmOwnerPerms = op, fmGroupPerms = gp, fmUserPerms = up } = do when (any (>3) $ map length [op, gp, up]) $ fail "Fixed-length check failed in FileMode serialization" putWord8 $ perms op putWord8 $ perms gp putWord8 $ perms up where case x of Read -> 4 ; Write -> 2; Execute -> 1 get = FileMode <$> gp <*> gp <*> gp where gp = fromBits `fmap` getWord8 fromBits x = let x0 = if testBit x 0 then [Execute] else [] x1 = if testBit x 1 then Write:x0 else x0 x2 = if testBit x 2 then Read:x1 else x1 in x2 instance Eq FileMode where fm1 == fm2 = sort (fmOwnerPerms fm1) == sort (fmOwnerPerms fm2) && sort (fmGroupPerms fm1) == sort (fmGroupPerms fm2) && sort (fmUserPerms fm1) == sort (fmUserPerms fm2) instance Functor DirFindRslt where fmap _ DF_NotFound = DF_NotFound fmap _ (DF_WrongFileType ft) = DF_WrongFileType ft fmap f (DF_Found (r, a)) = DF_Found (f r, a)
58bec9e31166e6fd705f34fe24a9f8eb1aeec973cde6474beb36fd109376a149
marcoheisig/Petalisp
class-diagram.lisp
© 2016 - 2023 - license : GNU AGPLv3 -*- coding : utf-8 -*- (in-package #:petalisp.graphviz) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Classes (defclass class-diagram (any-graph) ()) (defclass direct-subclass-edge (any-edge) ()) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Connectivity (defmethod graphviz-potential-edges append ((graph class-diagram) (class class)) (list (make-instance 'direct-subclass-edge))) (defmethod graphviz-incoming-edge-origins ((graph class-diagram) (edge direct-subclass-edge) (class class)) (closer-mop:class-direct-subclasses class)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Graph Appearance (defmethod graphviz-graph-attributes ((graph class-diagram)) `(:rankdir "BT")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Node Appearance (defmethod cl-dot:graph-object-node ((graph class-diagram) (class class)) (make-instance 'cl-dot:node :attributes `(:shape :record :style :filled :fillcolor "gray95" :label (:html () (:table ((:border "0") (:cellborder "0") (:cellspacing "0")) (:tr () (:td ((:colspan "2") (:align "center")) (:b () ,(stringify (class-name class))))) ,@(loop for slot in (closer-mop:class-direct-slots class) collect `(:tr () (:td ((:align "left")) ,(format nil "~A :" (closer-mop:slot-definition-name slot))) (:td ((:align "left")) ,(stringify (closer-mop:slot-definition-type slot)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Edge Appearance (defmethod graphviz-edge-attributes ((graph class-diagram) (edge direct-subclass-edge) (from class) (to class) edge-number) `(:arrowhead :onormal :style :dashed))
null
https://raw.githubusercontent.com/marcoheisig/Petalisp/a1c85cf71da445ef9c7913cd9ddb5149373211a7/code/graphviz/class-diagram.lisp
lisp
Classes Connectivity Graph Appearance Node Appearance Edge Appearance
© 2016 - 2023 - license : GNU AGPLv3 -*- coding : utf-8 -*- (in-package #:petalisp.graphviz) (defclass class-diagram (any-graph) ()) (defclass direct-subclass-edge (any-edge) ()) (defmethod graphviz-potential-edges append ((graph class-diagram) (class class)) (list (make-instance 'direct-subclass-edge))) (defmethod graphviz-incoming-edge-origins ((graph class-diagram) (edge direct-subclass-edge) (class class)) (closer-mop:class-direct-subclasses class)) (defmethod graphviz-graph-attributes ((graph class-diagram)) `(:rankdir "BT")) (defmethod cl-dot:graph-object-node ((graph class-diagram) (class class)) (make-instance 'cl-dot:node :attributes `(:shape :record :style :filled :fillcolor "gray95" :label (:html () (:table ((:border "0") (:cellborder "0") (:cellspacing "0")) (:tr () (:td ((:colspan "2") (:align "center")) (:b () ,(stringify (class-name class))))) ,@(loop for slot in (closer-mop:class-direct-slots class) collect `(:tr () (:td ((:align "left")) ,(format nil "~A :" (closer-mop:slot-definition-name slot))) (:td ((:align "left")) ,(stringify (closer-mop:slot-definition-type slot)))))))))) (defmethod graphviz-edge-attributes ((graph class-diagram) (edge direct-subclass-edge) (from class) (to class) edge-number) `(:arrowhead :onormal :style :dashed))
e37826702e909190665e3aaad8fa7af5969c450a49482609374815dc11cc2767
Helium4Haskell/helium
UnifierList.hs
test x = [x, "hello", 13, x]
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeerrors/Heuristics/UnifierList.hs
haskell
test x = [x, "hello", 13, x]
2a9230cde447081d278ea8293b6449c618e5f90c65daeb29107956e5303d91ed
SimulaVR/godot-haskell
VisualShaderNodeScalarInterp.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.VisualShaderNodeScalarInterp () where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.VisualShaderNode()
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/VisualShaderNodeScalarInterp.hs
haskell
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.VisualShaderNodeScalarInterp () where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.VisualShaderNode()
b0ec0cb19bb438ab9a7398cafe97b41be2871e191c7601ded3627d9a02654393
ruliana/racket-examples
hate-define-use.rkt
#lang s-exp "hate-define.rkt" ( define x ( λ ( y ) ( add1 y ) ) ) ( def x ( λ ( y ) ( add1 y ) ) )
null
https://raw.githubusercontent.com/ruliana/racket-examples/688293c86132f3b5c924360d53238ca352d4cf5b/module-basic/hate-define-use.rkt
racket
#lang s-exp "hate-define.rkt" ( define x ( λ ( y ) ( add1 y ) ) ) ( def x ( λ ( y ) ( add1 y ) ) )
2a7d2b5897134eeb7aec3de745867feb0349a15c924ff8eed7601f6cb3a8024f
swarmpit/swarmpit
inbound.clj
(ns swarmpit.docker.hub.mapper.inbound) (defn ->repository [repository] (into {:name (:repo_name repository) :description (:short_description repository) :private false :stars (:star_count repository) :pulls (:pull_count repository) :official (:is_official repository)})) (defn ->repositories [repositories query page] (let [results (->> (:results repositories) (map #(->repository %)) (map #(assoc % :id (hash (:name %)))) (into []))] {:query query :page page :limit 20 :total (:count repositories) :results results})) (defn ->user-repository [repository] (into {:name (str (:namespace repository) "/" (:name repository)) :description (:description repository) :private (:is_private repository) :stars (:star_count repository) :pulls (:pull_count repository) :official (:is_official repository)})) (defn ->user-repositories [repositories] (->> repositories (map #(->user-repository %)) (map #(assoc % :id (hash (:name %)))) (into [])))
null
https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/clj/swarmpit/docker/hub/mapper/inbound.clj
clojure
(ns swarmpit.docker.hub.mapper.inbound) (defn ->repository [repository] (into {:name (:repo_name repository) :description (:short_description repository) :private false :stars (:star_count repository) :pulls (:pull_count repository) :official (:is_official repository)})) (defn ->repositories [repositories query page] (let [results (->> (:results repositories) (map #(->repository %)) (map #(assoc % :id (hash (:name %)))) (into []))] {:query query :page page :limit 20 :total (:count repositories) :results results})) (defn ->user-repository [repository] (into {:name (str (:namespace repository) "/" (:name repository)) :description (:description repository) :private (:is_private repository) :stars (:star_count repository) :pulls (:pull_count repository) :official (:is_official repository)})) (defn ->user-repositories [repositories] (->> repositories (map #(->user-repository %)) (map #(assoc % :id (hash (:name %)))) (into [])))
f1599bc1878d7c8e3219b94a65da315b7827908964802b27474ff39665b6c4b7
Smart-Sql/smart-sql
my_alter_table.clj
(ns org.gridgain.plus.ddl.my-alter-table (:require [org.gridgain.plus.dml.select-lexical :as my-lexical] [org.gridgain.plus.dml.my-select-plus :as my-select] [org.gridgain.plus.dml.my-insert :as my-insert] [org.gridgain.plus.dml.my-update :as my-update] [org.gridgain.plus.init.plus-init-sql :as plus-init-sql] [org.gridgain.plus.ddl.my-create-table :as my-create-table] [clojure.core.reducers :as r] [clojure.string :as str]) (:import (org.apache.ignite Ignite IgniteCache) (org.apache.ignite.internal IgnitionEx) (com.google.common.base Strings) (org.tools MyConvertUtil) (cn.plus.model MyNoSqlCache MyCacheEx MyKeyValue MyLogCache SqlType MyLog) (org.gridgain.dml.util MyCacheExUtil) (cn.plus.model.ddl MySchemaTable MyTableItemPK) (org.apache.ignite.cache.query FieldsQueryCursor SqlFieldsQuery) (org.apache.ignite.binary BinaryObjectBuilder BinaryObject) (org.gridgain.ddl MyDdlUtilEx MyDdlUtil) (java.util ArrayList Date Iterator) (java.sql Timestamp) (java.math BigDecimal)) (:gen-class ; 生成 class 的类名 :name org.gridgain.plus.dml.MyAlterTable 是否生成 class 的 main 方法 :main false 生成 java 静态的方法 : methods [ ^:static [ getPlusInsert [ org.apache.ignite . Ignite Long String ] clojure.lang . ] ] )) ; 获取要添加或删除的 item 定义 (defn get_items_line [items_line] (if (and (= (first items_line) \() (= (last items_line) \))) (str/trim (subs items_line 1 (- (count items_line) 1))) (str/trim items_line) )) (defn get_items_obj [items_line] (my-create-table/items_obj (my-create-table/get_items (my-lexical/to-back (get_items_line items_line))))) (defn get_obj ([items] (get_obj items (ArrayList.) (StringBuilder.))) ([[f & r] ^ArrayList lst ^StringBuilder sb] (if (some? f) (when-let [{table_item :table_item code_line :code} (my-create-table/to_item f)] (do (.add lst table_item) (.append sb (.concat (.trim (.toString code_line)) ",")) (recur r lst sb) )) (let [code (str/trim (.toString sb))] {:lst_table_item (my-create-table/table_items lst) :code_line (str/trim (subs code 0 (- (count code) 1)))}) ))) (defn add_or_drop [^String line] (cond (not (nil? (re-find #"^(?i)DROP\s+COLUMN\s+IF\s+EXISTS\s*" line))) {:line (str/lower-case line) :is_drop true :is_add false :is_exists true :is_no_exists false} (not (nil? (re-find #"^(?i)ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s*" line))) {:line (str/lower-case line) :is_drop false :is_add true :is_exists false :is_no_exists true} (not (nil? (re-find #"^(?i)DROP\s+COLUMN\s*" line))) {:line (str/lower-case line) :is_drop true :is_add false :is_exists false :is_no_exists false} (not (nil? (re-find #"^(?i)ADD\s+COLUMN\s*" line))) {:line (str/lower-case line) :is_drop false :is_add true :is_exists false :is_no_exists false} :else (throw (Exception. (format "修改表的语句错误!位置:%s" line))) )) ; 获取 alter obj (defn get_table_alter_obj [^String sql] (let [alter_table (re-find #"^(?i)ALTER\s+TABLE\s+IF\s+EXISTS\s+|^(?i)ALTER\s+TABLE\s+" sql) last_line (str/replace sql #"^(?i)ALTER\s+TABLE\s+IF\s+EXISTS\s+|^(?i)ALTER\s+TABLE\s+" "")] (if (some? alter_table) (let [table_name (str/trim (re-find #"^(?i)\w+\s*\.\s*\w+\s+|^(?i)\w+\s+" last_line)) last_line_1 (str/replace last_line #"^(?i)\w+\s*\.\s*\w+\s+|^(?i)\w+\s+" "")] (if (some? table_name) (let [add_or_drop_line (re-find #"^(?i)ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+|^(?i)DROP\s+COLUMN\s+|^(?i)ADD\s+|^(?i)DROP\s+" last_line_1) colums_line (str/replace last_line_1 #"^(?i)ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+|^(?i)DROP\s+COLUMN\s+|^(?i)ADD\s+|^(?i)DROP\s+" "")] ;(println (get_items_obj colums_line)) (assoc (my-lexical/get-schema table_name) :alter_table alter_table :add_or_drop (add_or_drop add_or_drop_line) :colums (get_obj (get_items_obj colums_line))) ) (throw (Exception. (format "修改表的语句错误!位置:%s" table_name))))) (throw (Exception. "修改表的语句错误!"))))) (declare get-table-id get-add-table-item get-drop-table-item re-obj) (defn get-table-id [^Ignite ignite ^String schema_name ^String table_name] (if (my-lexical/is-eq? "public" schema_name) (first (first (.getAll (.query (.cache ignite "my_meta_tables") (.setArgs (SqlFieldsQuery. "select m.id from my_meta_tables as m where m.data_set_id = 0 and m.table_name = ?") (to-array [(str/lower-case table_name)])))))) (first (first (.getAll (.query (.cache ignite "my_meta_tables") (.setArgs (SqlFieldsQuery. "select m.id from my_meta_tables as m, my_dataset as d where m.data_set_id = d.id and d.schema_name = ? and m.table_name = ?") (to-array [(str/lower-case schema_name) (str/lower-case table_name)]))))))) ) (defn get-add-table-item [^Ignite ignite ^Long table_id lst_table_item] (loop [[f & r] lst_table_item lst-rs (ArrayList.)] (if (some? f) (if-not (nil? (first (first (.getAll (.query (.cache ignite "table_item") (.setArgs (SqlFieldsQuery. "select id from MY_META.table_item where table_id = ? and column_name = ?") (to-array [table_id (str/lower-case (.getColumn_name f))]))))))) (let [table-item-id (.incrementAndGet (.atomicSequence ignite "table_item" 0 true))] (let [my-key (MyTableItemPK. table-item-id table_id) my-value (doto f (.setId table-item-id) (.setTable_id table_id))] (if-not (Strings/isNullOrEmpty (.getMyLogCls (.configuration ignite))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key my-value (SqlType/INSERT) (MyLogCache. "table_index" "MY_META" "table_index" my-key my-value (SqlType/INSERT)))))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key my-value (SqlType/INSERT) nil))))) ) ) (recur r lst-rs)) lst-rs))) (defn get-drop-table-item [^Ignite ignite ^Long table_id lst_table_item] (loop [[f & r] lst_table_item lst-rs (ArrayList.)] (if (some? f) (if-let [table-item-id (first (first (.getAll (.query (.cache ignite "table_item") (.setArgs (SqlFieldsQuery. "select id from MY_META.table_item where table_id = ? and column_name = ?") (to-array [table_id (str/lower-case (.getColumn_name f))]))))))] (let [my-key (MyTableItemPK. table-item-id table_id)] (if-not (Strings/isNullOrEmpty (.getMyLogCls (.configuration ignite))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key nil (SqlType/DELETE) (MyLogCache. "table_index" "MY_META" "table_index" my-key nil (SqlType/DELETE)))))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key nil (SqlType/DELETE) nil))))) ) (throw (Exception. (format "要删除的列 %s 不存在!" (.getColumn_name f))))) lst-rs))) (defn re-obj [^String schema_name ^String sql_line] (if-let [m (get_table_alter_obj sql_line)] (cond (and (= (-> m :schema_name) "") (not (= schema_name ""))) (assoc m :schema_name schema_name) (or (and (not (= (-> m :schema_name) "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= (-> m :schema_name) "")) (my-lexical/is-eq? (-> m :schema_name) schema_name))) m :else (throw (Exception. "没有修改表的权限!")) ))) (defn get-date-items [data] (loop [[f & r] data lst #{}] (if (some? f) (recur r (conj lst (str/lower-case (-> f :column_name)))) lst))) (defn repace-ast [^Ignite ignite ^String schema_name ^String table_name lst_table_item is-add] (let [vs (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name)) {pk :pk data :data} (my-create-table/get_pk_data lst_table_item)] (if (> (count pk) 0) (throw (Exception. "不能修改主键!")) (if (true? is-add) (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) (assoc vs :data (concat (-> vs :data) data)) (SqlType/UPDATE)) (loop [[f & r] data items (get-date-items data) lst []] (if (some? f) (if (contains? items (str/lower-case (-> f :column_name))) (recur r items lst) (recur r items (conj lst f))) (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) (assoc vs :data lst) (SqlType/UPDATE)))) )) )) (defn alter-table-obj [^Ignite ignite ^String schema_name ^String sql_line] (let [{alter_table :alter_table schema_name :schema_name my-table_name :table_name {line :line is_drop :is_drop is_add :is_add} :add_or_drop {lst_table_item :lst_table_item code_line :code_line} :colums} (re-obj schema_name sql_line)] (let [table_name (str/lower-case my-table_name)] (if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name)) (if-let [table_id (get-table-id ignite schema_name table_name)] (cond (and (true? is_drop) (false? is_add)) {:sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :lst_cachex (get-drop-table-item ignite table_id lst_table_item) :nosql (repace-ast ignite schema_name table_name lst_table_item true)} (and (false? is_drop) (true? is_add)) {:sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :lst_cachex (get-add-table-item ignite table_id lst_table_item) :nosql (repace-ast ignite schema_name table_name lst_table_item false)} :else (throw (Exception. "修改表的语句有错误!"))) (throw (Exception. "要修改的表不存在!"))) (throw (Exception. "MY_META 数据集中的表不能被修改!")))) )) ; 执行实时数据集中的 ddl (defn run_ddl_real_time [^Ignite ignite ^String sql_line group_id] (let [{sql :sql lst_cachex :lst_cachex nosql :nosql} (alter-table-obj ignite (second group_id) sql_line)] (if-not (nil? lst_cachex) (MyDdlUtil/runDdl ignite {:sql (doto (ArrayList.) (.add sql)) :un_sql nil :lst_cachex lst_cachex :nosql nosql} sql_line) (throw (Exception. "修改表的语句有错误!"))) ) ) ; 1、如果要修改的是实时数据集,则修改实时数据集的时候要同步修改在其它数据集中的表 ; 2、判断要修改的表是否是实时数据集映射到,批处理数据集中的,如果是就不能修改,如果不是就可以修改 ; 执行 alter table group_id : ^Long group_id ^String schema_name group_type ^Long dataset_id ( defn alter_table [ ^Ignite ignite group_id ^String sql_line ] ; (let [sql_code (str/lower-case sql_line)] ( if (= ( first group_id ) 0 ) ; (run_ddl_real_time ignite sql_line group_id) ( if ( contains ? # { " ALL " " DDL " } ( str / upper - case ( nth group_id 2 ) ) ) ; (run_ddl_real_time ignite sql_code group_id) ( throw ( Exception . " DDL 语句的权限 ! " ) ) ) ) ) ) ( defn repace - ast - add [ ignite schema_name table_name data ] ; (if-let [ast (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name))] ; (assoc ast :data (concat (-> ast :data) data)) ; )) (defn repace-ast-add [ignite schema_name table_name data] (if-let [ast (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name))] ;(assoc ast :data (concat (-> ast :data) data)) (assoc ast :data (merge (-> ast :data) data)) )) (defn is-contains [item data] (loop [[f & r] data] (if (some? f) (if (my-lexical/is-eq? (-> f :column_name) (-> item :column_name)) true (recur r)) false))) (defn repace-ast-del [ignite schema_name table_name data] (if-let [ast (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name))] (loop [[f & r] (keys data) my-data (-> ast :data)] (if (some? f) (if (contains? my-data f) (recur r (dissoc my-data f)) (recur r my-data)) (assoc ast :data my-data))))) (defn alter-table-obj [^Ignite ignite ^String schema_name ^String sql_line] (let [{alter_table :alter_table schema_name :schema_name my-table_name :table_name {line :line is_drop :is_drop is_add :is_add is_exists :is_exists is_no_exists :is_no_exists} :add_or_drop {lst_table_item :lst_table_item code_line :code_line} :colums} (re-obj schema_name sql_line)] (let [table_name (str/lower-case my-table_name)] (if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name)) (cond (and (true? is_drop) (false? is_add)) {:schema_name schema_name :table_name table_name :sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :pk-data (repace-ast-del ignite schema_name table_name (-> (my-create-table/get_pk_data lst_table_item) :data))} (and (false? is_drop) (true? is_add)) (if (true? is_no_exists) {:schema_name schema_name :table_name table_name :sql (format "%s %s.%s %s %s" alter_table schema_name table_name line code_line) :pk-data (repace-ast-add ignite schema_name table_name (-> (my-create-table/get_pk_data lst_table_item) :data))} {:schema_name schema_name :table_name table_name :sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :pk-data (repace-ast-add ignite schema_name table_name (-> (my-create-table/get_pk_data lst_table_item) :data))}) :else (throw (Exception. "修改表的语句有错误!"))) (throw (Exception. "MY_META 数据集中的原始表不能被修改!")))) )) (defn alter_table [^Ignite ignite group_id ^String sql_line] (let [sql_code (str/lower-case sql_line)] (if (= (first group_id) 0) (MyDdlUtilEx/updateCache ignite (alter-table-obj ignite (second group_id) sql_code)) (if (contains? #{"ALL" "DDL"} (str/upper-case (nth group_id 2))) (MyDdlUtilEx/updateCache ignite (alter-table-obj ignite (second group_id) sql_code)) (throw (Exception. "该用户组没有执行 DDL 语句的权限!"))))))
null
https://raw.githubusercontent.com/Smart-Sql/smart-sql/d2f237f935472942a143816925221cdcf8246aff/src/main/clojure/org/gridgain/plus/ddl/my_alter_table.clj
clojure
生成 class 的类名 获取要添加或删除的 item 定义 获取 alter obj (println (get_items_obj colums_line)) 执行实时数据集中的 ddl 1、如果要修改的是实时数据集,则修改实时数据集的时候要同步修改在其它数据集中的表 2、判断要修改的表是否是实时数据集映射到,批处理数据集中的,如果是就不能修改,如果不是就可以修改 执行 alter table (let [sql_code (str/lower-case sql_line)] (run_ddl_real_time ignite sql_line group_id) (run_ddl_real_time ignite sql_code group_id) (if-let [ast (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name))] (assoc ast :data (concat (-> ast :data) data)) )) (assoc ast :data (concat (-> ast :data) data))
(ns org.gridgain.plus.ddl.my-alter-table (:require [org.gridgain.plus.dml.select-lexical :as my-lexical] [org.gridgain.plus.dml.my-select-plus :as my-select] [org.gridgain.plus.dml.my-insert :as my-insert] [org.gridgain.plus.dml.my-update :as my-update] [org.gridgain.plus.init.plus-init-sql :as plus-init-sql] [org.gridgain.plus.ddl.my-create-table :as my-create-table] [clojure.core.reducers :as r] [clojure.string :as str]) (:import (org.apache.ignite Ignite IgniteCache) (org.apache.ignite.internal IgnitionEx) (com.google.common.base Strings) (org.tools MyConvertUtil) (cn.plus.model MyNoSqlCache MyCacheEx MyKeyValue MyLogCache SqlType MyLog) (org.gridgain.dml.util MyCacheExUtil) (cn.plus.model.ddl MySchemaTable MyTableItemPK) (org.apache.ignite.cache.query FieldsQueryCursor SqlFieldsQuery) (org.apache.ignite.binary BinaryObjectBuilder BinaryObject) (org.gridgain.ddl MyDdlUtilEx MyDdlUtil) (java.util ArrayList Date Iterator) (java.sql Timestamp) (java.math BigDecimal)) (:gen-class :name org.gridgain.plus.dml.MyAlterTable 是否生成 class 的 main 方法 :main false 生成 java 静态的方法 : methods [ ^:static [ getPlusInsert [ org.apache.ignite . Ignite Long String ] clojure.lang . ] ] )) (defn get_items_line [items_line] (if (and (= (first items_line) \() (= (last items_line) \))) (str/trim (subs items_line 1 (- (count items_line) 1))) (str/trim items_line) )) (defn get_items_obj [items_line] (my-create-table/items_obj (my-create-table/get_items (my-lexical/to-back (get_items_line items_line))))) (defn get_obj ([items] (get_obj items (ArrayList.) (StringBuilder.))) ([[f & r] ^ArrayList lst ^StringBuilder sb] (if (some? f) (when-let [{table_item :table_item code_line :code} (my-create-table/to_item f)] (do (.add lst table_item) (.append sb (.concat (.trim (.toString code_line)) ",")) (recur r lst sb) )) (let [code (str/trim (.toString sb))] {:lst_table_item (my-create-table/table_items lst) :code_line (str/trim (subs code 0 (- (count code) 1)))}) ))) (defn add_or_drop [^String line] (cond (not (nil? (re-find #"^(?i)DROP\s+COLUMN\s+IF\s+EXISTS\s*" line))) {:line (str/lower-case line) :is_drop true :is_add false :is_exists true :is_no_exists false} (not (nil? (re-find #"^(?i)ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s*" line))) {:line (str/lower-case line) :is_drop false :is_add true :is_exists false :is_no_exists true} (not (nil? (re-find #"^(?i)DROP\s+COLUMN\s*" line))) {:line (str/lower-case line) :is_drop true :is_add false :is_exists false :is_no_exists false} (not (nil? (re-find #"^(?i)ADD\s+COLUMN\s*" line))) {:line (str/lower-case line) :is_drop false :is_add true :is_exists false :is_no_exists false} :else (throw (Exception. (format "修改表的语句错误!位置:%s" line))) )) (defn get_table_alter_obj [^String sql] (let [alter_table (re-find #"^(?i)ALTER\s+TABLE\s+IF\s+EXISTS\s+|^(?i)ALTER\s+TABLE\s+" sql) last_line (str/replace sql #"^(?i)ALTER\s+TABLE\s+IF\s+EXISTS\s+|^(?i)ALTER\s+TABLE\s+" "")] (if (some? alter_table) (let [table_name (str/trim (re-find #"^(?i)\w+\s*\.\s*\w+\s+|^(?i)\w+\s+" last_line)) last_line_1 (str/replace last_line #"^(?i)\w+\s*\.\s*\w+\s+|^(?i)\w+\s+" "")] (if (some? table_name) (let [add_or_drop_line (re-find #"^(?i)ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+|^(?i)DROP\s+COLUMN\s+|^(?i)ADD\s+|^(?i)DROP\s+" last_line_1) colums_line (str/replace last_line_1 #"^(?i)ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)DROP\s+COLUMN\s+IF\s+EXISTS\s+|^(?i)ADD\s+COLUMN\s+|^(?i)DROP\s+COLUMN\s+|^(?i)ADD\s+|^(?i)DROP\s+" "")] (assoc (my-lexical/get-schema table_name) :alter_table alter_table :add_or_drop (add_or_drop add_or_drop_line) :colums (get_obj (get_items_obj colums_line))) ) (throw (Exception. (format "修改表的语句错误!位置:%s" table_name))))) (throw (Exception. "修改表的语句错误!"))))) (declare get-table-id get-add-table-item get-drop-table-item re-obj) (defn get-table-id [^Ignite ignite ^String schema_name ^String table_name] (if (my-lexical/is-eq? "public" schema_name) (first (first (.getAll (.query (.cache ignite "my_meta_tables") (.setArgs (SqlFieldsQuery. "select m.id from my_meta_tables as m where m.data_set_id = 0 and m.table_name = ?") (to-array [(str/lower-case table_name)])))))) (first (first (.getAll (.query (.cache ignite "my_meta_tables") (.setArgs (SqlFieldsQuery. "select m.id from my_meta_tables as m, my_dataset as d where m.data_set_id = d.id and d.schema_name = ? and m.table_name = ?") (to-array [(str/lower-case schema_name) (str/lower-case table_name)]))))))) ) (defn get-add-table-item [^Ignite ignite ^Long table_id lst_table_item] (loop [[f & r] lst_table_item lst-rs (ArrayList.)] (if (some? f) (if-not (nil? (first (first (.getAll (.query (.cache ignite "table_item") (.setArgs (SqlFieldsQuery. "select id from MY_META.table_item where table_id = ? and column_name = ?") (to-array [table_id (str/lower-case (.getColumn_name f))]))))))) (let [table-item-id (.incrementAndGet (.atomicSequence ignite "table_item" 0 true))] (let [my-key (MyTableItemPK. table-item-id table_id) my-value (doto f (.setId table-item-id) (.setTable_id table_id))] (if-not (Strings/isNullOrEmpty (.getMyLogCls (.configuration ignite))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key my-value (SqlType/INSERT) (MyLogCache. "table_index" "MY_META" "table_index" my-key my-value (SqlType/INSERT)))))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key my-value (SqlType/INSERT) nil))))) ) ) (recur r lst-rs)) lst-rs))) (defn get-drop-table-item [^Ignite ignite ^Long table_id lst_table_item] (loop [[f & r] lst_table_item lst-rs (ArrayList.)] (if (some? f) (if-let [table-item-id (first (first (.getAll (.query (.cache ignite "table_item") (.setArgs (SqlFieldsQuery. "select id from MY_META.table_item where table_id = ? and column_name = ?") (to-array [table_id (str/lower-case (.getColumn_name f))]))))))] (let [my-key (MyTableItemPK. table-item-id table_id)] (if-not (Strings/isNullOrEmpty (.getMyLogCls (.configuration ignite))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key nil (SqlType/DELETE) (MyLogCache. "table_index" "MY_META" "table_index" my-key nil (SqlType/DELETE)))))) (recur r (doto lst-rs (.add (MyCacheEx. (.cache ignite "table_index") my-key nil (SqlType/DELETE) nil))))) ) (throw (Exception. (format "要删除的列 %s 不存在!" (.getColumn_name f))))) lst-rs))) (defn re-obj [^String schema_name ^String sql_line] (if-let [m (get_table_alter_obj sql_line)] (cond (and (= (-> m :schema_name) "") (not (= schema_name ""))) (assoc m :schema_name schema_name) (or (and (not (= (-> m :schema_name) "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= (-> m :schema_name) "")) (my-lexical/is-eq? (-> m :schema_name) schema_name))) m :else (throw (Exception. "没有修改表的权限!")) ))) (defn get-date-items [data] (loop [[f & r] data lst #{}] (if (some? f) (recur r (conj lst (str/lower-case (-> f :column_name)))) lst))) (defn repace-ast [^Ignite ignite ^String schema_name ^String table_name lst_table_item is-add] (let [vs (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name)) {pk :pk data :data} (my-create-table/get_pk_data lst_table_item)] (if (> (count pk) 0) (throw (Exception. "不能修改主键!")) (if (true? is-add) (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) (assoc vs :data (concat (-> vs :data) data)) (SqlType/UPDATE)) (loop [[f & r] data items (get-date-items data) lst []] (if (some? f) (if (contains? items (str/lower-case (-> f :column_name))) (recur r items lst) (recur r items (conj lst f))) (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) (assoc vs :data lst) (SqlType/UPDATE)))) )) )) (defn alter-table-obj [^Ignite ignite ^String schema_name ^String sql_line] (let [{alter_table :alter_table schema_name :schema_name my-table_name :table_name {line :line is_drop :is_drop is_add :is_add} :add_or_drop {lst_table_item :lst_table_item code_line :code_line} :colums} (re-obj schema_name sql_line)] (let [table_name (str/lower-case my-table_name)] (if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name)) (if-let [table_id (get-table-id ignite schema_name table_name)] (cond (and (true? is_drop) (false? is_add)) {:sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :lst_cachex (get-drop-table-item ignite table_id lst_table_item) :nosql (repace-ast ignite schema_name table_name lst_table_item true)} (and (false? is_drop) (true? is_add)) {:sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :lst_cachex (get-add-table-item ignite table_id lst_table_item) :nosql (repace-ast ignite schema_name table_name lst_table_item false)} :else (throw (Exception. "修改表的语句有错误!"))) (throw (Exception. "要修改的表不存在!"))) (throw (Exception. "MY_META 数据集中的表不能被修改!")))) )) (defn run_ddl_real_time [^Ignite ignite ^String sql_line group_id] (let [{sql :sql lst_cachex :lst_cachex nosql :nosql} (alter-table-obj ignite (second group_id) sql_line)] (if-not (nil? lst_cachex) (MyDdlUtil/runDdl ignite {:sql (doto (ArrayList.) (.add sql)) :un_sql nil :lst_cachex lst_cachex :nosql nosql} sql_line) (throw (Exception. "修改表的语句有错误!"))) ) ) group_id : ^Long group_id ^String schema_name group_type ^Long dataset_id ( defn alter_table [ ^Ignite ignite group_id ^String sql_line ] ( if (= ( first group_id ) 0 ) ( if ( contains ? # { " ALL " " DDL " } ( str / upper - case ( nth group_id 2 ) ) ) ( throw ( Exception . " DDL 语句的权限 ! " ) ) ) ) ) ) ( defn repace - ast - add [ ignite schema_name table_name data ] (defn repace-ast-add [ignite schema_name table_name data] (if-let [ast (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name))] (assoc ast :data (merge (-> ast :data) data)) )) (defn is-contains [item data] (loop [[f & r] data] (if (some? f) (if (my-lexical/is-eq? (-> f :column_name) (-> item :column_name)) true (recur r)) false))) (defn repace-ast-del [ignite schema_name table_name data] (if-let [ast (.get (.cache ignite "table_ast") (MySchemaTable. schema_name table_name))] (loop [[f & r] (keys data) my-data (-> ast :data)] (if (some? f) (if (contains? my-data f) (recur r (dissoc my-data f)) (recur r my-data)) (assoc ast :data my-data))))) (defn alter-table-obj [^Ignite ignite ^String schema_name ^String sql_line] (let [{alter_table :alter_table schema_name :schema_name my-table_name :table_name {line :line is_drop :is_drop is_add :is_add is_exists :is_exists is_no_exists :is_no_exists} :add_or_drop {lst_table_item :lst_table_item code_line :code_line} :colums} (re-obj schema_name sql_line)] (let [table_name (str/lower-case my-table_name)] (if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name)) (cond (and (true? is_drop) (false? is_add)) {:schema_name schema_name :table_name table_name :sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :pk-data (repace-ast-del ignite schema_name table_name (-> (my-create-table/get_pk_data lst_table_item) :data))} (and (false? is_drop) (true? is_add)) (if (true? is_no_exists) {:schema_name schema_name :table_name table_name :sql (format "%s %s.%s %s %s" alter_table schema_name table_name line code_line) :pk-data (repace-ast-add ignite schema_name table_name (-> (my-create-table/get_pk_data lst_table_item) :data))} {:schema_name schema_name :table_name table_name :sql (format "%s %s.%s %s (%s)" alter_table schema_name table_name line code_line) :pk-data (repace-ast-add ignite schema_name table_name (-> (my-create-table/get_pk_data lst_table_item) :data))}) :else (throw (Exception. "修改表的语句有错误!"))) (throw (Exception. "MY_META 数据集中的原始表不能被修改!")))) )) (defn alter_table [^Ignite ignite group_id ^String sql_line] (let [sql_code (str/lower-case sql_line)] (if (= (first group_id) 0) (MyDdlUtilEx/updateCache ignite (alter-table-obj ignite (second group_id) sql_code)) (if (contains? #{"ALL" "DDL"} (str/upper-case (nth group_id 2))) (MyDdlUtilEx/updateCache ignite (alter-table-obj ignite (second group_id) sql_code)) (throw (Exception. "该用户组没有执行 DDL 语句的权限!"))))))
930c8e7bc474dc71529eea116587b291c1f83fa10b49b42a084d5c81f5013ad5
sgbj/MaximaSharp
csimp2.lisp
-*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The data in this file contains enhancments. ;;;;; ;;; ;;;;; Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ; ;;; All rights reserved ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ( c ) Copyright 1982 Massachusetts Institute of Technology ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) (macsyma-module csimp2) (load-macsyma-macros rzmac) (declare-top (special var %p%i varlist plogabs half%pi nn* dn* $factlim $beta_expand)) (defmvar $gammalim 10000 "Controls simplification of gamma for rational number arguments.") (defvar $gamma_expand nil "Expand gamma(z+n) for n an integer when T.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Implementation of the function (defmfun simpplog (x vestigial z) (declare (ignore vestigial)) (prog (varlist dd check y) (oneargcheck x) (setq check x) (setq x (simpcheck (cadr x) z)) (cond ((equal 0 x) (merror (intl:gettext "plog: plog(0) is undefined."))) This is used in DEFINT . 1/19/81 . -JIM (return (eqtest (list '(%plog) x) check)))) (newvar x) (cond ((and (member '$%i varlist) (not (some #'(lambda (v) (and (atom v) (not (eq v '$%i)))) varlist))) (setq dd (trisplit x)) (cond ((setq z (patan (car dd) (cdr dd))) (return (add2* (simpln (list '(%log) (simpexpt (list '(mexpt) ($expand (list '(mplus) (list '(mexpt) (car dd) 2) (list '(mexpt) (cdr dd) 2))) '((rat) 1 2)) 1 nil)) 1 t) (list '(mtimes) z '$%i)))))) ((and (free x '$%i) (eq ($sign x) '$pnz)) (return (eqtest (list '(%plog) x) check))) ((and (equal ($imagpart x) 0) (setq y ($asksign x))) (cond ((eq y '$pos) (return (simpln (list '(%log) x) 1 t))) ((and plogabs (eq y '$neg)) (return (simpln (list '(%log) (list '(mtimes) -1 x)) 1 nil))) ((eq y '$neg) (return (add2 %p%i (simpln (list '(%log) (list '(mtimes) -1 x)) 1 nil)))) (t (merror (intl:gettext "plog: plog(0) is undefined."))))) ((and (equal ($imagpart (setq z (div* x '$%i))) 0) (setq y ($asksign z))) (cond ((equal y '$zero) (merror (intl:gettext "plog: plog(0) is undefined."))) (t (cond ((eq y '$pos) (setq y 1)) ((eq y '$neg) (setq y -1))) (return (add2* (simpln (list '(%log) (list '(mtimes) y z)) 1 nil) (list '(mtimes) y '((rat) 1 2) '$%i '$%pi))))))) (return (eqtest (list '(%plog) x) check)))) (defun patan (r i) (let (($numer $numer)) (prog (a b var) (setq i (simplifya i nil) r (simplifya r nil)) (cond ((zerop1 r) (if (floatp i) (setq $numer t)) (setq i ($asksign i)) (cond ((equal i '$pos) (return (simplify half%pi))) ((equal i '$neg) (return (mul2 -1 (simplify half%pi)))) (t (merror (intl:gettext "plog: encountered atan(0/0)."))))) ((zerop1 i) (cond ((floatp r) (setq $numer t))) (setq r ($asksign r)) (cond ((equal r '$pos) (return 0)) ((equal r '$neg) (return (simplify '$%pi))) (t (merror (intl:gettext "plog: encountered atan(0/0)."))))) ((and (among '%cos r) (among '%sin i)) (setq var 'xz) (numden (div* r i)) (cond ((and (eq (caar nn*) '%cos) (eq (caar dn*) '%sin)) (return (cadr nn*)))))) (setq a ($sign r) b ($sign i)) (cond ((eq a '$pos) (setq a 1)) ((eq a '$neg) (setq a -1)) ((eq a '$zero) (setq a 0))) (cond ((eq b '$pos) (setq b 1)) ((eq b '$neg) (setq b -1)) ((eq a '$zero) (setq b 0))) (cond ((equal i 0) (return (if (equal a 1) 0 (simplify '$%pi)))) ((equal r 0) (return (cond ((equal b 1) (simplify half%pi)) (t (mul2 '((rat simp) -1 2) (simplify '$%pi))))))) (setq r (simptimes (list '(mtimes) a b (div* i r)) 1 nil)) (return (cond ((onep1 r) (archk a b (list '(mtimes) '((rat) 1 4) '$%pi))) ((alike1 r '((mexpt) 3 ((rat) 1 2))) (archk a b (list '(mtimes) '((rat) 1 3) '$%pi))) ((alike1 r '((mexpt) 3 ((rat) -1 2))) (archk a b (list '(mtimes) '((rat) 1 6) '$%pi)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Implementation of the Binomial coefficient Verb function for the Binomial coefficient (defun $binomial (x y) (simplify (list '(%binomial) x y))) ;; Binomial has Mirror symmetry (defprop %binomial t commutes-with-conjugate) (defun simpbinocoef (x vestigial z) (declare (ignore vestigial)) (twoargcheck x) (let ((u (simpcheck (cadr x) z)) (v (simpcheck (caddr x) z)) (y)) (cond ((integerp v) (cond ((minusp v) (if (and (integerp u) (minusp u) (< v u)) (bincomp u (- u v)) 0)) ((or (zerop v) (equal u v)) 1) ((and (integerp u) (not (minusp u))) (bincomp u (min v (- u v)))) (t (bincomp u v)))) ((integerp (setq y (sub u v))) (cond ((zerop1 y) ;; u and v are equal, simplify not if argument can be negative (if (member ($csign u) '($pnz $pn $neg $nz)) (eqtest (list '(%binomial) u v) x) (bincomp u y))) (t (bincomp u y)))) ((complex-float-numerical-eval-p u v) Numercial evaluation for real and complex floating point numbers . (let (($numer t) ($float t)) ($rectform ($float ($makegamma (list '(%binomial) ($float u) ($float v))))))) ((complex-bigfloat-numerical-eval-p u v) ;; Numerical evaluation for real and complex bigfloat numbers. ($rectform ($bfloat ($makegamma (list '(%binomial) ($bfloat u) ($bfloat v)))))) (t (eqtest (list '(%binomial) u v) x))))) (defun bincomp (u v) (cond ((minusp v) 0) ((zerop v) 1) ((mnump u) (binocomp u v)) (t (muln (bincomp1 u v) nil)))) (defun bincomp1 (u v) (if (equal v 1) (ncons u) (list* u (list '(mexpt) v -1) (bincomp1 (add2 -1 u) (1- v))))) (defmfun binocomp (u v) (prog (ans) (setq ans 1) loop (if (zerop v) (return ans)) (setq ans (timesk (timesk u ans) (simplify (list '(rat) 1 v)))) (setq u (addk -1 u) v (1- v)) (go loop))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Implementation of the Beta function (declare-top (special $numer $gammalim)) (defmvar $beta_args_sum_to_integer nil) ;;; The Beta function has mirror symmetry (defprop $beta t commutes-with-conjugate) (defmfun simpbeta (x vestigial z &aux check) (declare (ignore vestigial)) (twoargcheck x) (setq check x) (let ((u (simpcheck (cadr x) z)) (v (simpcheck (caddr x) z))) (cond ((or (zerop1 u) (zerop1 v)) (if errorsw (throw 'errorsw t) (merror (intl:gettext "beta: expected nonzero arguments; found ~M, ~M") u v))) ;; Check for numerical evaluation in float precision ((complex-float-numerical-eval-p u v) (cond ;; We use gamma(u)*gamma(v)/gamma(u+v) for numerical evaluation. ;; Therefore u, v or u+v can not be a negative integer or a ;; floating point representation of a negative integer. ((and (or (not (numberp u)) (> u 0) (not (= (nth-value 1 (truncate u)) 0))) (and (or (not (numberp v)) (> v 0) (not (= (nth-value 1 (truncate v)) 0))) (and (or (not (numberp (add u v))) (> (add v u) 0) (not (= (nth-value 1 ($truncate (add u v))) 0)))))) ($rectform (power ($float '$%e) (add ($log_gamma ($float u)) ($log_gamma ($float v)) (mul -1 ($log_gamma ($float (add u v)))))))) ((or (and (numberp u) (> u 0) (= (nth-value 1 (truncate u)) 0) (not (and (mnump v) (eq ($sign (sub ($truncate v) v)) '$zero) (eq ($sign v) '$neg) (eq ($sign (add u v)) '$pos))) (setq u (truncate u))) (and (numberp v) (> v 0) (= (nth-value 1 (truncate u)) 0) (not (and (mnump u) (eq ($sign (sub ($truncate u) u)) '$zero) (eq ($sign u) '$neg) (eq ($sign (add u v)) '$pos))) (setq v (truncate v)))) One value is representing a negative integer , the other a ;; positive integer and the sum is negative. Expand. ($rectform ($float (beta-expand-integer u v)))) (t (eqtest (list '($beta) u v) check)))) Check for numerical evaluation in bigfloat precision ((complex-bigfloat-numerical-eval-p u v) (let (($ratprint nil)) (cond ((and (or (not (mnump u)) (eq ($sign u) '$pos) (not (eq ($sign (sub ($truncate u) u)) '$zero))) (or (not (mnump v)) (eq ($sign v) '$pos) (not (eq ($sign (sub ($truncate v) v)) '$zero))) (or (not (mnump (add u v))) (eq ($sign (add u v)) '$pos) (not (eq ($sign (sub ($truncate (add u v)) (add u v))) '$zero)))) ($rectform (power ($bfloat'$%e) (add ($log_gamma ($bfloat u)) ($log_gamma ($bfloat v)) (mul -1 ($log_gamma ($bfloat (add u v)))))))) ((or (and (mnump u) (eq ($sign u) '$pos) (eq ($sign (sub ($truncate u) u)) '$zero) (not (and (mnump v) (eq ($sign (sub ($truncate v) v)) '$zero) (eq ($sign v) '$neg) (eq ($sign (add u v)) '$pos))) (setq u ($truncate u))) (and (mnump v) (eq ($sign v) '$pos) (eq ($sign (sub ($truncate v) v)) '$zero) (not (and (mnump u) (eq ($sign (sub ($truncate u) u)) '$zero) (eq ($sign u) '$neg) (eq ($sign (add u v)) '$pos))) (setq v ($truncate v)))) ($rectform ($bfloat (beta-expand-integer u v)))) (t (eqtest (list '($beta) u v) check))))) ((or (and (and (integerp u) (plusp u)) (not (and (mnump v) (eq ($sign (sub ($truncate v) v)) '$zero) (eq ($sign v) '$neg) (eq ($sign (add u v)) '$pos)))) (and (and (integerp v) (plusp v)) (not (and (mnump u) (eq ($sign (sub ($truncate u) u)) '$zero) (eq ($sign u) '$neg) (eq ($sign (add u v)) '$pos))))) ;; Expand for a positive integer. But not if the other argument is ;; a negative integer and the sum of the integers is not negative. (beta-expand-integer u v)) ;;; At this point both integers are negative. This code does not work for ;;; negative integers. The factorial function is not defined. ( ( and ( integerp u ) ( integerp v ) ) ; (mul2* (div* (list '(mfactorial) (1- u)) ; (list '(mfactorial) (+ u v -1))) ; (list '(mfactorial) (1- v)))) ((or (and (ratnump u) (ratnump v) (integerp (setq x (addk u v)))) (and $beta_args_sum_to_integer (integerp (setq x (expand1 (add2 u v) 1 1))))) (let ((w (if (symbolp v) v u))) (div* (mul2* '$%pi (list '(%binomial) (add2 (1- x) (neg w)) (1- x))) `((%sin) ((mtimes) ,w $%pi))))) ((and $beta_expand (mplusp u) (integerp (cadr u))) ;; Expand beta(a+n,b) where n is an integer. (let ((n (cadr u)) (u (simplify (cons '(mplus) (cddr u))))) (beta-expand-add-integer n u v))) ((and $beta_expand (mplusp v) (integerp (cadr v))) ;; Expand beta(a,b+n) where n is an integer. (let ((n (cadr v)) (v (simplify (cons '(mplus) (cddr v))))) (beta-expand-add-integer n v u))) (t (eqtest (list '($beta) u v) check))))) (defun beta-expand-integer (u v) One of the arguments is a positive integer . Do an expansion . BUT for a negative integer as second argument the expansion is only ;; possible when the sum of the integers is negative too. ;; This routine expects that the calling routine has checked this. (let ((x (add u v))) (power (mul (sub x 1) (simplify (list '(%binomial) (sub x 2) (sub (if (and (integerp u) (plusp u)) u v) 1)))) -1))) (defun beta-expand-add-integer (n u v) (if (plusp n) (mul (simplify (list '($pochhammer) u n)) (power (simplify (list '($pochhammer) (add u v) n)) -1) (simplify (list '($beta) u v))) (mul (simplify (list '($pochhammer) (add u v n) (- n))) (power (simplify (list '($pochhammer) (add u n) (- n))) -1) (simplify (list '($beta) u v))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Implementation of the Gamma function (defmfun simpgamma (x vestigial z) (declare (ignore vestigial)) (oneargcheck x) (let ((j (simpcheck (cadr x) z))) (cond ((and (floatp j) (or (zerop j) (and (< j 0) (zerop (nth-value 1 (truncate j)))))) (merror (intl:gettext "gamma: gamma(~:M) is undefined.") j)) ((float-numerical-eval-p j) (gammafloat ($float j))) ((and ($bfloatp j) (or (zerop1 j) (and (eq ($sign j) '$neg) (zerop1 (sub j ($truncate j)))))) (merror (intl:gettext "gamma: gamma(~:M) is undefined.") j)) ((bigfloat-numerical-eval-p j) Adding 4 digits in the call to bffac . For $ fpprec up to about 256 and an argument up to about 500.0 the accuracy of the result is ;; better than 10^(-$fpprec). (let ((result (mfuncall '$bffac (m+ ($bfloat j) -1) (+ $fpprec 4)))) ;; bigfloatp will round the result to the correct fpprec (bigfloatp result))) ((complex-float-numerical-eval-p j) (complexify (gamma-lanczos (complex ($float ($realpart j)) ($float ($imagpart j)))))) ((complex-bigfloat-numerical-eval-p j) Adding 4 digits in the call to . See comment above . (let ((result (mfuncall '$cbffac (add -1 ($bfloat ($realpart j)) (mul '$%i ($bfloat ($imagpart j)))) (+ $fpprec 4)))) (add (bigfloatp ($realpart result)) (mul '$%i (bigfloatp ($imagpart result)))))) ((taylorize (mop x) (cadr x))) ((eq j '$inf) '$inf) ; Simplify to $inf to be more consistent. ((and $gamma_expand (mplusp j) (integerp (cadr j))) ;; Expand gamma(z+n) for n an integer. (let ((n (cadr j)) (z (simplify (cons '(mplus) (cddr j))))) (cond ((> n 0) (mul (simplify (list '($pochhammer) z n)) (simplify (list '(%gamma) z)))) ((< n 0) (setq n (- n)) (div (mul (power -1 n) (simplify (list '(%gamma) z))) ;; We factor to get the order (z-1)*(z-2)*... ;; and not (1-z)*(2-z)*... ($factor (simplify (list '($pochhammer) (sub 1 z) n)))))))) ((integerp j) (cond ((> j 0) (cond ((<= j $factlim) Positive integer less than $ factlim . Evaluate . (simplify (list '(mfactorial) (1- j)))) ;; Positive integer greater $factlim. Noun form. (t (eqtest (list '(%gamma) j) x)))) Negative integer . Throw a Maxima error . (errorsw (throw 'errorsw t)) (t (merror (intl:gettext "gamma: gamma(~:M) is undefined.") j)))) ((alike1 j '((rat) 1 2)) (list '(mexpt simp) '$%pi j)) ((and (mnump j) (ratgreaterp $gammalim (simplify (list '(mabs) j))) (or (ratgreaterp j 1) (ratgreaterp 0 j))) Expand for rational numbers less than $ gammalim . (gammared j)) (t (eqtest (list '(%gamma) j) x))))) numerical evaluation for 0 < y < 1 (prog (sum coefs) (setq coefs (list 0.035868343 -0.193527817 0.48219939 -0.75670407 0.91820685 -0.89705693 0.98820588 -0.57719165)) (unless (atom y) (setq y (fpcofrat y))) (setq sum (car coefs) coefs (cdr coefs)) loop (setq sum (+ (* sum y) (car coefs))) (when (setq coefs (cdr coefs)) (go loop)) (return (+ (/ y) sum)))) (defun gammared (a) ;A is assumed to (prog (m q n) ;be '((RAT) M N) (cond ((floatp a) (return (gammafloat a)))) (setq m (cadr a) ;Numerator n (caddr a) ;denominator q (abs (truncate m n))) ;integer part (cond ((minusp m) (setq q (1+ q) m (+ m (* n q))) (return (simptimes (list '(mtimes) (list '(mexpt) n q) (simpgamma (list '(%gamma) (list '(rat) m n)) 1 nil) (list '(mexpt) (gammac m n q) -1)) 1 nil)))) (return (m* (gammac m n q) (simpgamma (list '(%gamma) (list '(rat) (rem m n) n)) 1 nil) (m^ n (- q)))))) (defun gammac (m n q) (do ((ans 1)) ((< q 1) ans) (setq q (1- q) m (- m n) ans (* m ans)))) This implementation is based on Lanczos convergent formula for the gamma function for ) > 0 . We can use the reflection formula ;; ;; -z*Gamma(z)*Gamma(-z) = pi/sin(pi*z) ;; to handle the case of ) < = 0 . ;; See /~gabdo/gamma.m for some matlab code to ;; compute this and /~gabdo/gamma.txt for a nice discussion of Lanczos method and an improvement of Lanczos method . ;; ;; The document says this should give about 15 digits of accuracy for double - precision IEEE floats . The document also indicates how to ;; compute a new set of coefficients if you need more range or ;; accuracy. (defun gamma-lanczos (z) (declare (type (complex flonum) z) (optimize (safety 3))) (let ((c (make-array 15 :element-type 'flonum :initial-contents '(0.99999999999999709182 57.156235665862923517 -59.597960355475491248 14.136097974741747174 -0.49191381609762019978 .33994649984811888699e-4 .46523628927048575665e-4 -.98374475304879564677e-4 .15808870322491248884e-3 -.21026444172410488319e-3 .21743961811521264320e-3 -.16431810653676389022e-3 .84418223983852743293e-4 -.26190838401581408670e-4 .36899182659531622704e-5)))) (declare (type (simple-array flonum (15)) c)) (if (minusp (realpart z)) ;; Use the reflection formula ;; -z*Gamma(z)*Gamma(-z) = pi/sin(pi*z) ;; or ;; Gamma(z) = pi/z/sin(pi*z)/Gamma(-z) ;; ;; If z is a negative integer, Gamma(z) is infinity. Should we test for this ? Throw an error ? ;; The test must be done by the calling routine. (/ (float pi) (* (- z) (sin (* (float pi) z)) (gamma-lanczos (- z)))) (let* ((z (- z 1)) (zh (+ z 1/2)) (zgh (+ zh 607/128)) (ss (do ((sum 0.0) (pp (1- (length c)) (1- pp))) ((< pp 1) sum) (incf sum (/ (aref c pp) (+ z pp)))))) (let ((result ;; We check for an overflow. The last positive value in double - float precicsion for which Maxima can calculate gamma is ~171.6243 ( CLISP 2.46 and GCL 2.6.8 ) (ignore-errors (let ((zp (expt zgh (/ zh 2)))) (* (sqrt (float (* 2 pi))) (+ ss (aref c 0)) (* (/ zp (exp zgh)) zp)))))) (cond ((null result) ;; No result. Overflow. (merror (intl:gettext "gamma: overflow in GAMMA-LANCZOS."))) ((or (float-nan-p (realpart result)) (float-inf-p (realpart result))) ;; Result, but beyond extreme values. Overflow. (merror (intl:gettext "gamma: overflow in GAMMA-LANCZOS."))) (t result))))))) (defun gammafloat (a) (let ((a (float a))) (cond ((minusp a) (/ (float (- pi)) (* a (sin (* (float pi) a))) (gammafloat (- a)))) ((< a 10) (slatec::dgamma a)) (t (let ((result (let ((c (* (sqrt (* 2 (float pi))) (exp (slatec::d9lgmc a))))) (let ((v (expt a (- (* .5e0 a) 0.25e0)))) (* v (/ v (exp a)) c))))) (if (or (float-nan-p result) (float-inf-p result)) (merror (intl:gettext "gamma: overflow in GAMMAFLOAT.")) result)))))) (declare-top (special $numer $trigsign)) (defmfun $zeromatrix (m n) ($ematrix m n 0 1 1)) (defmfun $ematrix (m n var i j) (prog (ans row) (cond ((equal m 0) (return (ncons '($matrix simp)))) ((and (equal n 0) (fixnump m) (> m 0)) (return (cons '($matrix simp) (list-of-mlists m)))) ((not (and (fixnump m) (fixnump n) (fixnump i) (fixnump j) (> m 0) (> n 0) (> i 0) (> j 0))) (merror (intl:gettext "ematrix: arguments must be positive integers; found ~M") (list '(mlist simp) m n i j) ))) loop (cond ((= m i) (setq row (onen j n var 0)) (go on)) ((zerop m) (return (cons '($matrix) (mxc ans))))) (setq row nil) (do ((n n (1- n))) ((zerop n)) (setq row (cons 0 row))) on (setq ans (cons row ans) m (1- m)) (go loop))) (defun list-of-mlists (n) (do ((n n (1- n)) (l nil (cons (ncons '(mlist simp)) l))) ((= n 0) l))) (declare-top (special $ratmx)) (defmfun $coefmatrix (eql varl) (coefmatrix eql varl nil)) (defmfun $augcoefmatrix (eql varl) (coefmatrix eql varl t)) (defun coefmatrix (eql varl ind) (prog (ans row a b elem) (if (not ($listp eql)) (improper-arg-err eql '$coefmatrix)) (if (not ($listp varl)) (improper-arg-err varl '$coefmatrix)) (dolist (v (cdr varl)) (if (and (not (atom v)) (member (caar v) '(mplus mtimes) :test #'eq)) (merror (intl:gettext "coefmatrix: variables cannot be '+' or '*' expressions; found ~M") v))) (setq eql (nreverse (mapcar #'meqhk (cdr eql))) varl (reverse (cdr varl))) loop1(if (null eql) (return (cons '($matrix) (mxc ans)))) (setq a (car eql) eql (cdr eql) row nil) (if ind (setq row (cons (const1 a varl) row))) (setq b varl) loop2(setq elem (ratcoef a (car b))) (setq row (cons (if $ratmx elem (ratdisrep elem)) row)) (if (setq b (cdr b)) (go loop2)) (setq ans (cons row ans)) (go loop1))) (defun const1 (e varl) (dolist (v varl) (setq e (maxima-substitute 0 v e))) e) (defmfun $entermatrix (rows columns) (prog (row column vector matrix sym symvector) (cond ((or (not (fixnump rows)) (not (fixnump columns))) (merror (intl:gettext "entermatrix: arguments must be integers; found ~M, ~M") rows columns))) (setq row 0) (unless (= rows columns) (setq sym nil) (go oloop)) quest (format t "~%Is the matrix 1. Diagonal 2. Symmetric 3. Antisymmetric 4. General~%") (setq sym (retrieve "Answer 1, 2, 3 or 4 : " nil)) (unless (member sym '(1 2 3 4)) (go quest)) oloop (cond ((> (incf row) rows) (format t "~%Matrix entered.~%") (return (cons '($matrix) (mxc matrix))))) (cond ((equal sym 1) (setq column row) (let ((prompt (format nil "Row ~a Column ~a: " row column))) (setq matrix (nconc matrix (ncons (onen row columns (meval (retrieve prompt nil)) 0))))) (go oloop)) ((equal sym 2) (setq column (1- row)) (cond ((equal row 1) (go iloop))) (setq symvector (cons (nthcdr column vector) symvector) vector (nreverse (mapcar 'car symvector)) symvector (mapcar 'cdr symvector)) (go iloop)) ((equal sym 3) (setq column row) (cond ((equal row 1) (setq vector (ncons 0)) (go iloop))) (setq symvector (cons (mapcar #'neg (nthcdr (1- column) vector)) symvector) vector (nreconc (mapcar 'car symvector) (ncons 0)) symvector (mapcar 'cdr symvector)) (go iloop))) (setq column 0 vector nil) iloop (cond ((> (incf column) columns) (setq matrix (nconc matrix (ncons vector))) (go oloop))) (let ((prompt (format nil "Row ~a Column ~a: " row column))) (setq vector (nconc vector (ncons (meval (retrieve prompt nil)))))) (go iloop))) (declare-top (special sn* sd* rsn*)) (defmfun $xthru (e) (cond ((atom e) e) ((mtimesp e) (muln (mapcar '$xthru (cdr e)) nil)) ((mplusp e) (simplify (comdenom (mapcar '$xthru (cdr e)) t))) ((mexptp e) (power ($xthru (cadr e)) (caddr e))) ((member (caar e) '(mequal mlist $matrix) :test #'eq) (cons (car e) (mapcar '$xthru (cdr e)))) (t e))) (defun comdenom (l ind) (prog (n d) (prodnumden (car l)) (setq n (m*l sn*) sn* nil) (setq d (m*l sd*) sd* nil) loop (setq l (cdr l)) (cond ((null l) (return (cond (ind (div* (cond (rsn* ($ratsimp n)) (t n)) d)) (t (list n d)))))) (prodnumden (car l)) (setq d (comdenom1 n d (m*l sn*) (m*l sd*))) (setq n (car d)) (setq d (cadr d)) (go loop))) (defun prodnumden (e) (cond ((atom e) (prodnd (list e))) ((eq (caar e) 'mtimes) (prodnd (cdr e))) (t (prodnd (list e))))) (defun prodnd (l) (prog (e) (setq l (reverse l)) (setq sn* nil sd* nil) loop (cond ((null l) (return nil))) (setq e (car l)) (cond ((atom e) (setq sn* (cons e sn*))) ((ratnump e) (cond ((not (equal 1 (cadr e))) (setq sn* (cons (cadr e) sn*)))) (setq sd* (cons (caddr e) sd*))) ((and (eq (caar e) 'mexpt) (mnegp (caddr e))) (setq sd* (cons (power (cadr e) (timesk -1 (caddr e))) sd*))) (t (setq sn* (cons e sn*)))) (setq l (cdr l)) (go loop))) (defun comdenom1 (a b c d) (prog (b1 c1) (prodnumden (div* b d)) (setq b1 (m*l sn*) sn* nil) (setq c1 (m*l sd*) sd* nil) (return (list (add2 (m* a c1) (m* c b1)) (mul2 d b1))))) (declare-top (special $globalsolve $backsubst $dispflag $linsolve_params $%rnum_list ax *linelabel* $linechar $linenum *mosesflag)) (defun xrutout (ax n m varl ind) (let (($linsolve_params (and $backsubst $linsolve_params))) (prog (ix imin ans zz m-1 sol tim chk zzz) (setq ax (get-array-pointer ax) tim 0) (if $linsolve_params (setq $%rnum_list (list '(mlist)))) (setq imin (min (setq m-1 (1- m)) n)) (setq ix (max imin (length varl))) loop (if (zerop ix) (if ind (go out) (return (cons '(mlist) zz)))) (when (or (> ix imin) (equal (car (aref ax ix ix)) 0)) (setf (aref ax 0 ix) (rform (if $linsolve_params (make-param) (ith varl ix)))) (if $linsolve_params (go saval) (go next))) (setq ans (aref ax ix m)) (setf (aref ax ix m) nil) (do ((j (1+ ix) (1+ j))) ((> j m-1)) (setq ans (ratdif ans (rattimes (aref ax ix j) (aref ax 0 j) t))) (setf (aref ax ix j) nil)) (setf (aref ax 0 ix) (ratquotient ans (aref ax ix ix))) (setf (aref ax ix ix) nil) (setq ans nil) saval (push (cond (*mosesflag (aref ax 0 ix)) (t (list (if $globalsolve '(msetq) '(mequal)) (ith varl ix) (simplify (rdis (aref ax 0 ix)))))) zz) (if (not $backsubst) (setf (aref ax 0 ix) (rform (ith varl ix)))) (and $globalsolve (meval (car zz))) next (decf ix) (go loop) out (cond ($dispflag (mtell (intl:gettext "Solution:~%")))) (setq sol (list '(mlist)) chk (checklabel $linechar)) (do ((ll zz (cdr ll))) ((null ll)) (setq zzz (car ll)) (setq zzz (list '(mlabel) (progn (if chk (setq chk nil) (incf $linenum)) (let (($nolabels nil)) (makelabel $linechar)) *linelabel*) (set *linelabel* zzz))) (nconc sol (ncons *linelabel*)) (cond ($dispflag (setq tim (get-internal-run-time)) (mtell-open "~%~M" zzz) (timeorg tim)) (t (putprop *linelabel* t 'nodisp)))) (return sol))))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/csimp2.lisp
lisp
Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; The data in this file contains enhancments. ;;;;; ;;;;; ; ; ; ; All rights reserved ;;;;; ; ; Implementation of the Binomial coefficient Binomial has Mirror symmetry u and v are equal, simplify not if argument can be negative Numerical evaluation for real and complex bigfloat numbers. Implementation of the Beta function The Beta function has mirror symmetry Check for numerical evaluation in float precision We use gamma(u)*gamma(v)/gamma(u+v) for numerical evaluation. Therefore u, v or u+v can not be a negative integer or a floating point representation of a negative integer. positive integer and the sum is negative. Expand. Expand for a positive integer. But not if the other argument is a negative integer and the sum of the integers is not negative. At this point both integers are negative. This code does not work for negative integers. The factorial function is not defined. (mul2* (div* (list '(mfactorial) (1- u)) (list '(mfactorial) (+ u v -1))) (list '(mfactorial) (1- v)))) Expand beta(a+n,b) where n is an integer. Expand beta(a,b+n) where n is an integer. possible when the sum of the integers is negative too. This routine expects that the calling routine has checked this. better than 10^(-$fpprec). bigfloatp will round the result to the correct fpprec Simplify to $inf to be more consistent. Expand gamma(z+n) for n an integer. We factor to get the order (z-1)*(z-2)*... and not (1-z)*(2-z)*... Positive integer greater $factlim. Noun form. A is assumed to be '((RAT) M N) Numerator denominator integer part -z*Gamma(z)*Gamma(-z) = pi/sin(pi*z) compute this and /~gabdo/gamma.txt for a nice compute a new set of coefficients if you need more range or accuracy. Use the reflection formula -z*Gamma(z)*Gamma(-z) = pi/sin(pi*z) or Gamma(z) = pi/z/sin(pi*z)/Gamma(-z) If z is a negative integer, Gamma(z) is infinity. Should The test must be done by the calling routine. We check for an overflow. The last positive value in No result. Overflow. Result, but beyond extreme values. Overflow.
(in-package :maxima) (macsyma-module csimp2) (load-macsyma-macros rzmac) (declare-top (special var %p%i varlist plogabs half%pi nn* dn* $factlim $beta_expand)) (defmvar $gammalim 10000 "Controls simplification of gamma for rational number arguments.") (defvar $gamma_expand nil "Expand gamma(z+n) for n an integer when T.") Implementation of the function (defmfun simpplog (x vestigial z) (declare (ignore vestigial)) (prog (varlist dd check y) (oneargcheck x) (setq check x) (setq x (simpcheck (cadr x) z)) (cond ((equal 0 x) (merror (intl:gettext "plog: plog(0) is undefined."))) This is used in DEFINT . 1/19/81 . -JIM (return (eqtest (list '(%plog) x) check)))) (newvar x) (cond ((and (member '$%i varlist) (not (some #'(lambda (v) (and (atom v) (not (eq v '$%i)))) varlist))) (setq dd (trisplit x)) (cond ((setq z (patan (car dd) (cdr dd))) (return (add2* (simpln (list '(%log) (simpexpt (list '(mexpt) ($expand (list '(mplus) (list '(mexpt) (car dd) 2) (list '(mexpt) (cdr dd) 2))) '((rat) 1 2)) 1 nil)) 1 t) (list '(mtimes) z '$%i)))))) ((and (free x '$%i) (eq ($sign x) '$pnz)) (return (eqtest (list '(%plog) x) check))) ((and (equal ($imagpart x) 0) (setq y ($asksign x))) (cond ((eq y '$pos) (return (simpln (list '(%log) x) 1 t))) ((and plogabs (eq y '$neg)) (return (simpln (list '(%log) (list '(mtimes) -1 x)) 1 nil))) ((eq y '$neg) (return (add2 %p%i (simpln (list '(%log) (list '(mtimes) -1 x)) 1 nil)))) (t (merror (intl:gettext "plog: plog(0) is undefined."))))) ((and (equal ($imagpart (setq z (div* x '$%i))) 0) (setq y ($asksign z))) (cond ((equal y '$zero) (merror (intl:gettext "plog: plog(0) is undefined."))) (t (cond ((eq y '$pos) (setq y 1)) ((eq y '$neg) (setq y -1))) (return (add2* (simpln (list '(%log) (list '(mtimes) y z)) 1 nil) (list '(mtimes) y '((rat) 1 2) '$%i '$%pi))))))) (return (eqtest (list '(%plog) x) check)))) (defun patan (r i) (let (($numer $numer)) (prog (a b var) (setq i (simplifya i nil) r (simplifya r nil)) (cond ((zerop1 r) (if (floatp i) (setq $numer t)) (setq i ($asksign i)) (cond ((equal i '$pos) (return (simplify half%pi))) ((equal i '$neg) (return (mul2 -1 (simplify half%pi)))) (t (merror (intl:gettext "plog: encountered atan(0/0)."))))) ((zerop1 i) (cond ((floatp r) (setq $numer t))) (setq r ($asksign r)) (cond ((equal r '$pos) (return 0)) ((equal r '$neg) (return (simplify '$%pi))) (t (merror (intl:gettext "plog: encountered atan(0/0)."))))) ((and (among '%cos r) (among '%sin i)) (setq var 'xz) (numden (div* r i)) (cond ((and (eq (caar nn*) '%cos) (eq (caar dn*) '%sin)) (return (cadr nn*)))))) (setq a ($sign r) b ($sign i)) (cond ((eq a '$pos) (setq a 1)) ((eq a '$neg) (setq a -1)) ((eq a '$zero) (setq a 0))) (cond ((eq b '$pos) (setq b 1)) ((eq b '$neg) (setq b -1)) ((eq a '$zero) (setq b 0))) (cond ((equal i 0) (return (if (equal a 1) 0 (simplify '$%pi)))) ((equal r 0) (return (cond ((equal b 1) (simplify half%pi)) (t (mul2 '((rat simp) -1 2) (simplify '$%pi))))))) (setq r (simptimes (list '(mtimes) a b (div* i r)) 1 nil)) (return (cond ((onep1 r) (archk a b (list '(mtimes) '((rat) 1 4) '$%pi))) ((alike1 r '((mexpt) 3 ((rat) 1 2))) (archk a b (list '(mtimes) '((rat) 1 3) '$%pi))) ((alike1 r '((mexpt) 3 ((rat) -1 2))) (archk a b (list '(mtimes) '((rat) 1 6) '$%pi)))))))) Verb function for the Binomial coefficient (defun $binomial (x y) (simplify (list '(%binomial) x y))) (defprop %binomial t commutes-with-conjugate) (defun simpbinocoef (x vestigial z) (declare (ignore vestigial)) (twoargcheck x) (let ((u (simpcheck (cadr x) z)) (v (simpcheck (caddr x) z)) (y)) (cond ((integerp v) (cond ((minusp v) (if (and (integerp u) (minusp u) (< v u)) (bincomp u (- u v)) 0)) ((or (zerop v) (equal u v)) 1) ((and (integerp u) (not (minusp u))) (bincomp u (min v (- u v)))) (t (bincomp u v)))) ((integerp (setq y (sub u v))) (cond ((zerop1 y) (if (member ($csign u) '($pnz $pn $neg $nz)) (eqtest (list '(%binomial) u v) x) (bincomp u y))) (t (bincomp u y)))) ((complex-float-numerical-eval-p u v) Numercial evaluation for real and complex floating point numbers . (let (($numer t) ($float t)) ($rectform ($float ($makegamma (list '(%binomial) ($float u) ($float v))))))) ((complex-bigfloat-numerical-eval-p u v) ($rectform ($bfloat ($makegamma (list '(%binomial) ($bfloat u) ($bfloat v)))))) (t (eqtest (list '(%binomial) u v) x))))) (defun bincomp (u v) (cond ((minusp v) 0) ((zerop v) 1) ((mnump u) (binocomp u v)) (t (muln (bincomp1 u v) nil)))) (defun bincomp1 (u v) (if (equal v 1) (ncons u) (list* u (list '(mexpt) v -1) (bincomp1 (add2 -1 u) (1- v))))) (defmfun binocomp (u v) (prog (ans) (setq ans 1) loop (if (zerop v) (return ans)) (setq ans (timesk (timesk u ans) (simplify (list '(rat) 1 v)))) (setq u (addk -1 u) v (1- v)) (go loop))) (declare-top (special $numer $gammalim)) (defmvar $beta_args_sum_to_integer nil) (defprop $beta t commutes-with-conjugate) (defmfun simpbeta (x vestigial z &aux check) (declare (ignore vestigial)) (twoargcheck x) (setq check x) (let ((u (simpcheck (cadr x) z)) (v (simpcheck (caddr x) z))) (cond ((or (zerop1 u) (zerop1 v)) (if errorsw (throw 'errorsw t) (merror (intl:gettext "beta: expected nonzero arguments; found ~M, ~M") u v))) ((complex-float-numerical-eval-p u v) (cond ((and (or (not (numberp u)) (> u 0) (not (= (nth-value 1 (truncate u)) 0))) (and (or (not (numberp v)) (> v 0) (not (= (nth-value 1 (truncate v)) 0))) (and (or (not (numberp (add u v))) (> (add v u) 0) (not (= (nth-value 1 ($truncate (add u v))) 0)))))) ($rectform (power ($float '$%e) (add ($log_gamma ($float u)) ($log_gamma ($float v)) (mul -1 ($log_gamma ($float (add u v)))))))) ((or (and (numberp u) (> u 0) (= (nth-value 1 (truncate u)) 0) (not (and (mnump v) (eq ($sign (sub ($truncate v) v)) '$zero) (eq ($sign v) '$neg) (eq ($sign (add u v)) '$pos))) (setq u (truncate u))) (and (numberp v) (> v 0) (= (nth-value 1 (truncate u)) 0) (not (and (mnump u) (eq ($sign (sub ($truncate u) u)) '$zero) (eq ($sign u) '$neg) (eq ($sign (add u v)) '$pos))) (setq v (truncate v)))) One value is representing a negative integer , the other a ($rectform ($float (beta-expand-integer u v)))) (t (eqtest (list '($beta) u v) check)))) Check for numerical evaluation in bigfloat precision ((complex-bigfloat-numerical-eval-p u v) (let (($ratprint nil)) (cond ((and (or (not (mnump u)) (eq ($sign u) '$pos) (not (eq ($sign (sub ($truncate u) u)) '$zero))) (or (not (mnump v)) (eq ($sign v) '$pos) (not (eq ($sign (sub ($truncate v) v)) '$zero))) (or (not (mnump (add u v))) (eq ($sign (add u v)) '$pos) (not (eq ($sign (sub ($truncate (add u v)) (add u v))) '$zero)))) ($rectform (power ($bfloat'$%e) (add ($log_gamma ($bfloat u)) ($log_gamma ($bfloat v)) (mul -1 ($log_gamma ($bfloat (add u v)))))))) ((or (and (mnump u) (eq ($sign u) '$pos) (eq ($sign (sub ($truncate u) u)) '$zero) (not (and (mnump v) (eq ($sign (sub ($truncate v) v)) '$zero) (eq ($sign v) '$neg) (eq ($sign (add u v)) '$pos))) (setq u ($truncate u))) (and (mnump v) (eq ($sign v) '$pos) (eq ($sign (sub ($truncate v) v)) '$zero) (not (and (mnump u) (eq ($sign (sub ($truncate u) u)) '$zero) (eq ($sign u) '$neg) (eq ($sign (add u v)) '$pos))) (setq v ($truncate v)))) ($rectform ($bfloat (beta-expand-integer u v)))) (t (eqtest (list '($beta) u v) check))))) ((or (and (and (integerp u) (plusp u)) (not (and (mnump v) (eq ($sign (sub ($truncate v) v)) '$zero) (eq ($sign v) '$neg) (eq ($sign (add u v)) '$pos)))) (and (and (integerp v) (plusp v)) (not (and (mnump u) (eq ($sign (sub ($truncate u) u)) '$zero) (eq ($sign u) '$neg) (eq ($sign (add u v)) '$pos))))) (beta-expand-integer u v)) ( ( and ( integerp u ) ( integerp v ) ) ((or (and (ratnump u) (ratnump v) (integerp (setq x (addk u v)))) (and $beta_args_sum_to_integer (integerp (setq x (expand1 (add2 u v) 1 1))))) (let ((w (if (symbolp v) v u))) (div* (mul2* '$%pi (list '(%binomial) (add2 (1- x) (neg w)) (1- x))) `((%sin) ((mtimes) ,w $%pi))))) ((and $beta_expand (mplusp u) (integerp (cadr u))) (let ((n (cadr u)) (u (simplify (cons '(mplus) (cddr u))))) (beta-expand-add-integer n u v))) ((and $beta_expand (mplusp v) (integerp (cadr v))) (let ((n (cadr v)) (v (simplify (cons '(mplus) (cddr v))))) (beta-expand-add-integer n v u))) (t (eqtest (list '($beta) u v) check))))) (defun beta-expand-integer (u v) One of the arguments is a positive integer . Do an expansion . BUT for a negative integer as second argument the expansion is only (let ((x (add u v))) (power (mul (sub x 1) (simplify (list '(%binomial) (sub x 2) (sub (if (and (integerp u) (plusp u)) u v) 1)))) -1))) (defun beta-expand-add-integer (n u v) (if (plusp n) (mul (simplify (list '($pochhammer) u n)) (power (simplify (list '($pochhammer) (add u v) n)) -1) (simplify (list '($beta) u v))) (mul (simplify (list '($pochhammer) (add u v n) (- n))) (power (simplify (list '($pochhammer) (add u n) (- n))) -1) (simplify (list '($beta) u v))))) Implementation of the Gamma function (defmfun simpgamma (x vestigial z) (declare (ignore vestigial)) (oneargcheck x) (let ((j (simpcheck (cadr x) z))) (cond ((and (floatp j) (or (zerop j) (and (< j 0) (zerop (nth-value 1 (truncate j)))))) (merror (intl:gettext "gamma: gamma(~:M) is undefined.") j)) ((float-numerical-eval-p j) (gammafloat ($float j))) ((and ($bfloatp j) (or (zerop1 j) (and (eq ($sign j) '$neg) (zerop1 (sub j ($truncate j)))))) (merror (intl:gettext "gamma: gamma(~:M) is undefined.") j)) ((bigfloat-numerical-eval-p j) Adding 4 digits in the call to bffac . For $ fpprec up to about 256 and an argument up to about 500.0 the accuracy of the result is (let ((result (mfuncall '$bffac (m+ ($bfloat j) -1) (+ $fpprec 4)))) (bigfloatp result))) ((complex-float-numerical-eval-p j) (complexify (gamma-lanczos (complex ($float ($realpart j)) ($float ($imagpart j)))))) ((complex-bigfloat-numerical-eval-p j) Adding 4 digits in the call to . See comment above . (let ((result (mfuncall '$cbffac (add -1 ($bfloat ($realpart j)) (mul '$%i ($bfloat ($imagpart j)))) (+ $fpprec 4)))) (add (bigfloatp ($realpart result)) (mul '$%i (bigfloatp ($imagpart result)))))) ((taylorize (mop x) (cadr x))) ((and $gamma_expand (mplusp j) (integerp (cadr j))) (let ((n (cadr j)) (z (simplify (cons '(mplus) (cddr j))))) (cond ((> n 0) (mul (simplify (list '($pochhammer) z n)) (simplify (list '(%gamma) z)))) ((< n 0) (setq n (- n)) (div (mul (power -1 n) (simplify (list '(%gamma) z))) ($factor (simplify (list '($pochhammer) (sub 1 z) n)))))))) ((integerp j) (cond ((> j 0) (cond ((<= j $factlim) Positive integer less than $ factlim . Evaluate . (simplify (list '(mfactorial) (1- j)))) (t (eqtest (list '(%gamma) j) x)))) Negative integer . Throw a Maxima error . (errorsw (throw 'errorsw t)) (t (merror (intl:gettext "gamma: gamma(~:M) is undefined.") j)))) ((alike1 j '((rat) 1 2)) (list '(mexpt simp) '$%pi j)) ((and (mnump j) (ratgreaterp $gammalim (simplify (list '(mabs) j))) (or (ratgreaterp j 1) (ratgreaterp 0 j))) Expand for rational numbers less than $ gammalim . (gammared j)) (t (eqtest (list '(%gamma) j) x))))) numerical evaluation for 0 < y < 1 (prog (sum coefs) (setq coefs (list 0.035868343 -0.193527817 0.48219939 -0.75670407 0.91820685 -0.89705693 0.98820588 -0.57719165)) (unless (atom y) (setq y (fpcofrat y))) (setq sum (car coefs) coefs (cdr coefs)) loop (setq sum (+ (* sum y) (car coefs))) (when (setq coefs (cdr coefs)) (go loop)) (return (+ (/ y) sum)))) (cond ((floatp a) (return (gammafloat a)))) (cond ((minusp m) (setq q (1+ q) m (+ m (* n q))) (return (simptimes (list '(mtimes) (list '(mexpt) n q) (simpgamma (list '(%gamma) (list '(rat) m n)) 1 nil) (list '(mexpt) (gammac m n q) -1)) 1 nil)))) (return (m* (gammac m n q) (simpgamma (list '(%gamma) (list '(rat) (rem m n) n)) 1 nil) (m^ n (- q)))))) (defun gammac (m n q) (do ((ans 1)) ((< q 1) ans) (setq q (1- q) m (- m n) ans (* m ans)))) This implementation is based on Lanczos convergent formula for the gamma function for ) > 0 . We can use the reflection formula to handle the case of ) < = 0 . See /~gabdo/gamma.m for some matlab code to discussion of Lanczos method and an improvement of Lanczos method . The document says this should give about 15 digits of accuracy for double - precision IEEE floats . The document also indicates how to (defun gamma-lanczos (z) (declare (type (complex flonum) z) (optimize (safety 3))) (let ((c (make-array 15 :element-type 'flonum :initial-contents '(0.99999999999999709182 57.156235665862923517 -59.597960355475491248 14.136097974741747174 -0.49191381609762019978 .33994649984811888699e-4 .46523628927048575665e-4 -.98374475304879564677e-4 .15808870322491248884e-3 -.21026444172410488319e-3 .21743961811521264320e-3 -.16431810653676389022e-3 .84418223983852743293e-4 -.26190838401581408670e-4 .36899182659531622704e-5)))) (declare (type (simple-array flonum (15)) c)) (if (minusp (realpart z)) we test for this ? Throw an error ? (/ (float pi) (* (- z) (sin (* (float pi) z)) (gamma-lanczos (- z)))) (let* ((z (- z 1)) (zh (+ z 1/2)) (zgh (+ zh 607/128)) (ss (do ((sum 0.0) (pp (1- (length c)) (1- pp))) ((< pp 1) sum) (incf sum (/ (aref c pp) (+ z pp)))))) (let ((result double - float precicsion for which Maxima can calculate gamma is ~171.6243 ( CLISP 2.46 and GCL 2.6.8 ) (ignore-errors (let ((zp (expt zgh (/ zh 2)))) (* (sqrt (float (* 2 pi))) (+ ss (aref c 0)) (* (/ zp (exp zgh)) zp)))))) (cond ((null result) (merror (intl:gettext "gamma: overflow in GAMMA-LANCZOS."))) ((or (float-nan-p (realpart result)) (float-inf-p (realpart result))) (merror (intl:gettext "gamma: overflow in GAMMA-LANCZOS."))) (t result))))))) (defun gammafloat (a) (let ((a (float a))) (cond ((minusp a) (/ (float (- pi)) (* a (sin (* (float pi) a))) (gammafloat (- a)))) ((< a 10) (slatec::dgamma a)) (t (let ((result (let ((c (* (sqrt (* 2 (float pi))) (exp (slatec::d9lgmc a))))) (let ((v (expt a (- (* .5e0 a) 0.25e0)))) (* v (/ v (exp a)) c))))) (if (or (float-nan-p result) (float-inf-p result)) (merror (intl:gettext "gamma: overflow in GAMMAFLOAT.")) result)))))) (declare-top (special $numer $trigsign)) (defmfun $zeromatrix (m n) ($ematrix m n 0 1 1)) (defmfun $ematrix (m n var i j) (prog (ans row) (cond ((equal m 0) (return (ncons '($matrix simp)))) ((and (equal n 0) (fixnump m) (> m 0)) (return (cons '($matrix simp) (list-of-mlists m)))) ((not (and (fixnump m) (fixnump n) (fixnump i) (fixnump j) (> m 0) (> n 0) (> i 0) (> j 0))) (merror (intl:gettext "ematrix: arguments must be positive integers; found ~M") (list '(mlist simp) m n i j) ))) loop (cond ((= m i) (setq row (onen j n var 0)) (go on)) ((zerop m) (return (cons '($matrix) (mxc ans))))) (setq row nil) (do ((n n (1- n))) ((zerop n)) (setq row (cons 0 row))) on (setq ans (cons row ans) m (1- m)) (go loop))) (defun list-of-mlists (n) (do ((n n (1- n)) (l nil (cons (ncons '(mlist simp)) l))) ((= n 0) l))) (declare-top (special $ratmx)) (defmfun $coefmatrix (eql varl) (coefmatrix eql varl nil)) (defmfun $augcoefmatrix (eql varl) (coefmatrix eql varl t)) (defun coefmatrix (eql varl ind) (prog (ans row a b elem) (if (not ($listp eql)) (improper-arg-err eql '$coefmatrix)) (if (not ($listp varl)) (improper-arg-err varl '$coefmatrix)) (dolist (v (cdr varl)) (if (and (not (atom v)) (member (caar v) '(mplus mtimes) :test #'eq)) (merror (intl:gettext "coefmatrix: variables cannot be '+' or '*' expressions; found ~M") v))) (setq eql (nreverse (mapcar #'meqhk (cdr eql))) varl (reverse (cdr varl))) loop1(if (null eql) (return (cons '($matrix) (mxc ans)))) (setq a (car eql) eql (cdr eql) row nil) (if ind (setq row (cons (const1 a varl) row))) (setq b varl) loop2(setq elem (ratcoef a (car b))) (setq row (cons (if $ratmx elem (ratdisrep elem)) row)) (if (setq b (cdr b)) (go loop2)) (setq ans (cons row ans)) (go loop1))) (defun const1 (e varl) (dolist (v varl) (setq e (maxima-substitute 0 v e))) e) (defmfun $entermatrix (rows columns) (prog (row column vector matrix sym symvector) (cond ((or (not (fixnump rows)) (not (fixnump columns))) (merror (intl:gettext "entermatrix: arguments must be integers; found ~M, ~M") rows columns))) (setq row 0) (unless (= rows columns) (setq sym nil) (go oloop)) quest (format t "~%Is the matrix 1. Diagonal 2. Symmetric 3. Antisymmetric 4. General~%") (setq sym (retrieve "Answer 1, 2, 3 or 4 : " nil)) (unless (member sym '(1 2 3 4)) (go quest)) oloop (cond ((> (incf row) rows) (format t "~%Matrix entered.~%") (return (cons '($matrix) (mxc matrix))))) (cond ((equal sym 1) (setq column row) (let ((prompt (format nil "Row ~a Column ~a: " row column))) (setq matrix (nconc matrix (ncons (onen row columns (meval (retrieve prompt nil)) 0))))) (go oloop)) ((equal sym 2) (setq column (1- row)) (cond ((equal row 1) (go iloop))) (setq symvector (cons (nthcdr column vector) symvector) vector (nreverse (mapcar 'car symvector)) symvector (mapcar 'cdr symvector)) (go iloop)) ((equal sym 3) (setq column row) (cond ((equal row 1) (setq vector (ncons 0)) (go iloop))) (setq symvector (cons (mapcar #'neg (nthcdr (1- column) vector)) symvector) vector (nreconc (mapcar 'car symvector) (ncons 0)) symvector (mapcar 'cdr symvector)) (go iloop))) (setq column 0 vector nil) iloop (cond ((> (incf column) columns) (setq matrix (nconc matrix (ncons vector))) (go oloop))) (let ((prompt (format nil "Row ~a Column ~a: " row column))) (setq vector (nconc vector (ncons (meval (retrieve prompt nil)))))) (go iloop))) (declare-top (special sn* sd* rsn*)) (defmfun $xthru (e) (cond ((atom e) e) ((mtimesp e) (muln (mapcar '$xthru (cdr e)) nil)) ((mplusp e) (simplify (comdenom (mapcar '$xthru (cdr e)) t))) ((mexptp e) (power ($xthru (cadr e)) (caddr e))) ((member (caar e) '(mequal mlist $matrix) :test #'eq) (cons (car e) (mapcar '$xthru (cdr e)))) (t e))) (defun comdenom (l ind) (prog (n d) (prodnumden (car l)) (setq n (m*l sn*) sn* nil) (setq d (m*l sd*) sd* nil) loop (setq l (cdr l)) (cond ((null l) (return (cond (ind (div* (cond (rsn* ($ratsimp n)) (t n)) d)) (t (list n d)))))) (prodnumden (car l)) (setq d (comdenom1 n d (m*l sn*) (m*l sd*))) (setq n (car d)) (setq d (cadr d)) (go loop))) (defun prodnumden (e) (cond ((atom e) (prodnd (list e))) ((eq (caar e) 'mtimes) (prodnd (cdr e))) (t (prodnd (list e))))) (defun prodnd (l) (prog (e) (setq l (reverse l)) (setq sn* nil sd* nil) loop (cond ((null l) (return nil))) (setq e (car l)) (cond ((atom e) (setq sn* (cons e sn*))) ((ratnump e) (cond ((not (equal 1 (cadr e))) (setq sn* (cons (cadr e) sn*)))) (setq sd* (cons (caddr e) sd*))) ((and (eq (caar e) 'mexpt) (mnegp (caddr e))) (setq sd* (cons (power (cadr e) (timesk -1 (caddr e))) sd*))) (t (setq sn* (cons e sn*)))) (setq l (cdr l)) (go loop))) (defun comdenom1 (a b c d) (prog (b1 c1) (prodnumden (div* b d)) (setq b1 (m*l sn*) sn* nil) (setq c1 (m*l sd*) sd* nil) (return (list (add2 (m* a c1) (m* c b1)) (mul2 d b1))))) (declare-top (special $globalsolve $backsubst $dispflag $linsolve_params $%rnum_list ax *linelabel* $linechar $linenum *mosesflag)) (defun xrutout (ax n m varl ind) (let (($linsolve_params (and $backsubst $linsolve_params))) (prog (ix imin ans zz m-1 sol tim chk zzz) (setq ax (get-array-pointer ax) tim 0) (if $linsolve_params (setq $%rnum_list (list '(mlist)))) (setq imin (min (setq m-1 (1- m)) n)) (setq ix (max imin (length varl))) loop (if (zerop ix) (if ind (go out) (return (cons '(mlist) zz)))) (when (or (> ix imin) (equal (car (aref ax ix ix)) 0)) (setf (aref ax 0 ix) (rform (if $linsolve_params (make-param) (ith varl ix)))) (if $linsolve_params (go saval) (go next))) (setq ans (aref ax ix m)) (setf (aref ax ix m) nil) (do ((j (1+ ix) (1+ j))) ((> j m-1)) (setq ans (ratdif ans (rattimes (aref ax ix j) (aref ax 0 j) t))) (setf (aref ax ix j) nil)) (setf (aref ax 0 ix) (ratquotient ans (aref ax ix ix))) (setf (aref ax ix ix) nil) (setq ans nil) saval (push (cond (*mosesflag (aref ax 0 ix)) (t (list (if $globalsolve '(msetq) '(mequal)) (ith varl ix) (simplify (rdis (aref ax 0 ix)))))) zz) (if (not $backsubst) (setf (aref ax 0 ix) (rform (ith varl ix)))) (and $globalsolve (meval (car zz))) next (decf ix) (go loop) out (cond ($dispflag (mtell (intl:gettext "Solution:~%")))) (setq sol (list '(mlist)) chk (checklabel $linechar)) (do ((ll zz (cdr ll))) ((null ll)) (setq zzz (car ll)) (setq zzz (list '(mlabel) (progn (if chk (setq chk nil) (incf $linenum)) (let (($nolabels nil)) (makelabel $linechar)) *linelabel*) (set *linelabel* zzz))) (nconc sol (ncons *linelabel*)) (cond ($dispflag (setq tim (get-internal-run-time)) (mtell-open "~%~M" zzz) (timeorg tim)) (t (putprop *linelabel* t 'nodisp)))) (return sol))))
2aa73b8c5876f78cda940a4c385e3f09b6e221e908ae743ca74c6a8ade88dcd1
ericcervin/getting-started-with-sketching
pg025a.rkt
#lang sketching (define (setup) (size 480 120) (smoothing 'smoothed) (background 0) (no-loop) ) (define (draw) (fill 204) (ellipse 132 82 200 200) (fill 153) (ellipse 228 -16 200 200) (fill 102) (ellipse 268 118 200 200) )
null
https://raw.githubusercontent.com/ericcervin/getting-started-with-sketching/e7c15b2ac942a929297ac59db92dcd123421e7b7/pg025a.rkt
racket
#lang sketching (define (setup) (size 480 120) (smoothing 'smoothed) (background 0) (no-loop) ) (define (draw) (fill 204) (ellipse 132 82 200 200) (fill 153) (ellipse 228 -16 200 200) (fill 102) (ellipse 268 118 200 200) )