_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
37acad232c6b2dbd40cd8843c1a1394afb45610c6dbbeb1b17012a42bee4fab6
lisp-korea/sicp
ch4-mceval.scm
METACIRCULAR EVALUATOR FROM CHAPTER 4 ( SECTIONS 4.1.1 - 4.1.4 ) of ;;;; STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS ;;;;Matches code in ch4.scm ;;;;This file can be loaded into Scheme as a whole. ;;;;Then you can initialize and start the evaluator by evaluating the two commented - out lines at the end of the file ( setting up the ;;;; global environment and starting the driver loop). ;;;;**WARNING: Don't load this file twice (or you'll lose the primitives ;;;; interface, due to renamings of apply). from section 4.1.4 -- must precede def of metacircular apply (define apply-in-underlying-scheme apply) SECTION 4.1.1 (define (mceval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (mceval (cond->if exp) env)) ((application? exp) (mcapply (mceval (operator exp) env) (list-of-values (operands exp) env))) (else (error "Unknown expression type -- EVAL" exp)))) (define (mcapply procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure)))) (define (list-of-values exps env) (if (no-operands? exps) '() (cons (mceval (first-operand exps) env) (list-of-values (rest-operands exps) env)))) (define (eval-if exp env) (if (true? (mceval (if-predicate exp) env)) (mceval (if-consequent exp) env) (mceval (if-alternative exp) env))) (define (eval-sequence exps env) (cond ((last-exp? exps) (mceval (first-exp exps) env)) (else (mceval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (define (eval-assignment exp env) (set-variable-value! (assignment-variable exp) (mceval (assignment-value exp) env) env) 'ok) (define (eval-definition exp env) (define-variable! (definition-variable exp) (mceval (definition-value exp) env) env) 'ok) SECTION 4.1.2 (define (self-evaluating? exp) (cond ((number? exp) #t) ((string? exp) #t) (else #f))) (define (quoted? exp) (tagged-list? exp 'quote)) (define (text-of-quotation exp) (cadr exp)) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) #f)) (define (variable? exp) (symbol? exp)) (define (assignment? exp) (tagged-list? exp 'set!)) (define (assignment-variable exp) (cadr exp)) (define (assignment-value exp) (caddr exp)) (define (definition? exp) (tagged-list? exp 'define)) (define (definition-variable exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp))) (define (definition-value exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) (define (lambda? exp) (tagged-list? exp 'lambda)) (define (lambda-parameters exp) (cadr exp)) (define (lambda-body exp) (cddr exp)) (define (make-lambda parameters body) (cons 'lambda (cons parameters body))) (define (if? exp) (tagged-list? exp 'if)) (define (if-predicate exp) (cadr exp)) (define (if-consequent exp) (caddr exp)) (define (if-alternative exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false)) (define (make-if predicate consequent alternative) (list 'if predicate consequent alternative)) (define (begin? exp) (tagged-list? exp 'begin)) (define (begin-actions exp) (cdr exp)) (define (last-exp? seq) (null? (cdr seq))) (define (first-exp seq) (car seq)) (define (rest-exps seq) (cdr seq)) (define (sequence->exp seq) (cond ((null? seq) seq) ((last-exp? seq) (first-exp seq)) (else (make-begin seq)))) (define (make-begin seq) (cons 'begin seq)) (define (application? exp) (pair? exp)) (define (operator exp) (car exp)) (define (operands exp) (cdr exp)) (define (no-operands? ops) (null? ops)) (define (first-operand ops) (car ops)) (define (rest-operands ops) (cdr ops)) (define (cond? exp) (tagged-list? exp 'cond)) (define (cond-clauses exp) (cdr exp)) (define (cond-else-clause? clause) (eq? (cond-predicate clause) 'else)) (define (cond-predicate clause) (car clause)) (define (cond-actions clause) (cdr clause)) (define (cond->if exp) (expand-clauses (cond-clauses exp))) (define (expand-clauses clauses) (if (null? clauses) 'false ; no else clause (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF" clauses)) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest)))))) ;;;SECTION 4.1.3 (define (true? x) (not (eq? x #f))) (define (false? x) (eq? x #f)) (define (make-procedure parameters body env) (list 'procedure parameters body env)) (define (compound-procedure? p) (tagged-list? p 'procedure)) (define (procedure-parameters p) (cadr p)) (define (procedure-body p) (caddr p)) (define (procedure-environment p) (cadddr p)) (define (enclosing-environment env) (cdr env)) (define (first-frame env) (car env)) (define the-empty-environment '()) (define (make-frame variables values) (cons variables values)) (define (frame-variables frame) (car frame)) (define (frame-values frame) (cdr frame)) (define (add-binding-to-frame! var val frame) (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame)))) (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals)))) (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (car vals)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (set-variable-value! var val env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable -- SET!" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan vars vals) (cond ((null? vars) (add-binding-to-frame! var val frame)) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (scan (frame-variables frame) (frame-values frame)))) SECTION 4.1.4 (define (setup-environment) (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true #t initial-env) (define-variable! 'false #f initial-env) initial-env)) ;[do later] (define the-global-environment (setup-environment)) (define (primitive-procedure? proc) (tagged-list? proc 'primitive)) (define (primitive-implementation proc) (cadr proc)) (define primitive-procedures (list (list 'car car) (list 'cdr cdr) (list 'cons cons) (list 'null? null?) ;; more primitives )) (define (primitive-procedure-names) (map car primitive-procedures)) (define (primitive-procedure-objects) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures)) ;[moved to start of file] (define apply-in-underlying-scheme apply) (define (apply-primitive-procedure proc args) (apply-in-underlying-scheme (primitive-implementation proc) args)) (define input-prompt ";;; M-Mceval input:") (define output-prompt ";;; M-Mceval value:") (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (mceval input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (define (prompt-for-input string) (newline) (newline) (display string) (newline)) (define (announce-output string) (newline) (display string) (newline)) (define (user-print object) (if (compound-procedure? object) (display (list 'compound-procedure (procedure-parameters object) (procedure-body object) '<procedure-env>)) (display object))) ;;;Following are commented out so as not to be evaluated when ;;; the file is loaded. ;;(define the-global-environment (setup-environment)) ;;(driver-loop) 'METACIRCULAR-EVALUATOR-LOADED
null
https://raw.githubusercontent.com/lisp-korea/sicp/4cdc1b1d858c6da7c9f4ec925ff4a724f36041cc/ch04/4.3/ch4-mceval.scm
scheme
STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS Matches code in ch4.scm This file can be loaded into Scheme as a whole. Then you can initialize and start the evaluator by evaluating global environment and starting the driver loop). **WARNING: Don't load this file twice (or you'll lose the primitives interface, due to renamings of apply). no else clause SECTION 4.1.3 [do later] (define the-global-environment (setup-environment)) more primitives [moved to start of file] (define apply-in-underlying-scheme apply) Following are commented out so as not to be evaluated when the file is loaded. (define the-global-environment (setup-environment)) (driver-loop)
METACIRCULAR EVALUATOR FROM CHAPTER 4 ( SECTIONS 4.1.1 - 4.1.4 ) of the two commented - out lines at the end of the file ( setting up the from section 4.1.4 -- must precede def of metacircular apply (define apply-in-underlying-scheme apply) SECTION 4.1.1 (define (mceval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (mceval (cond->if exp) env)) ((application? exp) (mcapply (mceval (operator exp) env) (list-of-values (operands exp) env))) (else (error "Unknown expression type -- EVAL" exp)))) (define (mcapply procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure)))) (define (list-of-values exps env) (if (no-operands? exps) '() (cons (mceval (first-operand exps) env) (list-of-values (rest-operands exps) env)))) (define (eval-if exp env) (if (true? (mceval (if-predicate exp) env)) (mceval (if-consequent exp) env) (mceval (if-alternative exp) env))) (define (eval-sequence exps env) (cond ((last-exp? exps) (mceval (first-exp exps) env)) (else (mceval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (define (eval-assignment exp env) (set-variable-value! (assignment-variable exp) (mceval (assignment-value exp) env) env) 'ok) (define (eval-definition exp env) (define-variable! (definition-variable exp) (mceval (definition-value exp) env) env) 'ok) SECTION 4.1.2 (define (self-evaluating? exp) (cond ((number? exp) #t) ((string? exp) #t) (else #f))) (define (quoted? exp) (tagged-list? exp 'quote)) (define (text-of-quotation exp) (cadr exp)) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) #f)) (define (variable? exp) (symbol? exp)) (define (assignment? exp) (tagged-list? exp 'set!)) (define (assignment-variable exp) (cadr exp)) (define (assignment-value exp) (caddr exp)) (define (definition? exp) (tagged-list? exp 'define)) (define (definition-variable exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp))) (define (definition-value exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) (define (lambda? exp) (tagged-list? exp 'lambda)) (define (lambda-parameters exp) (cadr exp)) (define (lambda-body exp) (cddr exp)) (define (make-lambda parameters body) (cons 'lambda (cons parameters body))) (define (if? exp) (tagged-list? exp 'if)) (define (if-predicate exp) (cadr exp)) (define (if-consequent exp) (caddr exp)) (define (if-alternative exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false)) (define (make-if predicate consequent alternative) (list 'if predicate consequent alternative)) (define (begin? exp) (tagged-list? exp 'begin)) (define (begin-actions exp) (cdr exp)) (define (last-exp? seq) (null? (cdr seq))) (define (first-exp seq) (car seq)) (define (rest-exps seq) (cdr seq)) (define (sequence->exp seq) (cond ((null? seq) seq) ((last-exp? seq) (first-exp seq)) (else (make-begin seq)))) (define (make-begin seq) (cons 'begin seq)) (define (application? exp) (pair? exp)) (define (operator exp) (car exp)) (define (operands exp) (cdr exp)) (define (no-operands? ops) (null? ops)) (define (first-operand ops) (car ops)) (define (rest-operands ops) (cdr ops)) (define (cond? exp) (tagged-list? exp 'cond)) (define (cond-clauses exp) (cdr exp)) (define (cond-else-clause? clause) (eq? (cond-predicate clause) 'else)) (define (cond-predicate clause) (car clause)) (define (cond-actions clause) (cdr clause)) (define (cond->if exp) (expand-clauses (cond-clauses exp))) (define (expand-clauses clauses) (if (null? clauses) (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF" clauses)) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest)))))) (define (true? x) (not (eq? x #f))) (define (false? x) (eq? x #f)) (define (make-procedure parameters body env) (list 'procedure parameters body env)) (define (compound-procedure? p) (tagged-list? p 'procedure)) (define (procedure-parameters p) (cadr p)) (define (procedure-body p) (caddr p)) (define (procedure-environment p) (cadddr p)) (define (enclosing-environment env) (cdr env)) (define (first-frame env) (car env)) (define the-empty-environment '()) (define (make-frame variables values) (cons variables values)) (define (frame-variables frame) (car frame)) (define (frame-values frame) (cdr frame)) (define (add-binding-to-frame! var val frame) (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame)))) (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals)))) (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (car vals)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (set-variable-value! var val env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable -- SET!" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan vars vals) (cond ((null? vars) (add-binding-to-frame! var val frame)) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (scan (frame-variables frame) (frame-values frame)))) SECTION 4.1.4 (define (setup-environment) (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true #t initial-env) (define-variable! 'false #f initial-env) initial-env)) (define (primitive-procedure? proc) (tagged-list? proc 'primitive)) (define (primitive-implementation proc) (cadr proc)) (define primitive-procedures (list (list 'car car) (list 'cdr cdr) (list 'cons cons) (list 'null? null?) )) (define (primitive-procedure-names) (map car primitive-procedures)) (define (primitive-procedure-objects) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures)) (define (apply-primitive-procedure proc args) (apply-in-underlying-scheme (primitive-implementation proc) args)) (define input-prompt ";;; M-Mceval input:") (define output-prompt ";;; M-Mceval value:") (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (mceval input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (define (prompt-for-input string) (newline) (newline) (display string) (newline)) (define (announce-output string) (newline) (display string) (newline)) (define (user-print object) (if (compound-procedure? object) (display (list 'compound-procedure (procedure-parameters object) (procedure-body object) '<procedure-env>)) (display object))) 'METACIRCULAR-EVALUATOR-LOADED
f4113210b2d6a666a2b5ec3b4d4a7790b80d3873e5fcf3e101257adb6bf44b73
xapi-project/message-switch
apis.ml
let apis = [ Plugin.interfaces ; Control.interfaces ; Data.interfaces ; Task.interfaces ]
null
https://raw.githubusercontent.com/xapi-project/message-switch/bd10e096c56f149d6cb0831a520a84843ebca300/xapi-storage/generator/lib/apis.ml
ocaml
let apis = [ Plugin.interfaces ; Control.interfaces ; Data.interfaces ; Task.interfaces ]
b2557780d7c9e6a6a1d2eda36bd23972c01de1088abc181c877cda7563d0b089
AeroNotix/lispkit
settings.lisp
(in-package :lispkit) (defparameter *cookie-path-dir* (merge-pathnames #P"lispkit/" (get-xdg-config-dir))) (defparameter *cookie-type* :webkit-cookie-persistent-storage-text) (defparameter *cookie-accept-policy* :webkit-cookie-policy-accept-always) (defun ensure-cookies-folder-exists (path) "Ensures that the cookies folder exists." (handler-case (ensure-directories-exist path) (file-error () (format *error-output* "Unable to ensure that the cookies folder ~s exists." path))))
null
https://raw.githubusercontent.com/AeroNotix/lispkit/2482dbeabc79667407dabe7765dfbffc16584b08/settings.lisp
lisp
(in-package :lispkit) (defparameter *cookie-path-dir* (merge-pathnames #P"lispkit/" (get-xdg-config-dir))) (defparameter *cookie-type* :webkit-cookie-persistent-storage-text) (defparameter *cookie-accept-policy* :webkit-cookie-policy-accept-always) (defun ensure-cookies-folder-exists (path) "Ensures that the cookies folder exists." (handler-case (ensure-directories-exist path) (file-error () (format *error-output* "Unable to ensure that the cookies folder ~s exists." path))))
03b208f8971196f1ecc176cb6a024d21e3a8596ae82ce32a15f488cb0fa9dc74
appleby/Lisp-In-Small-Pieces
chap8f.scm
$ I d : chap8f.scm , v 4.1 2006/11/24 18:40:55 queinnec Exp $ ;;;(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) ;;; This file is derived from the files that accompany the book: LISP Implantation Semantique Programmation ( InterEditions , France ) or Lisp In Small Pieces ( Cambridge University Press ) . By Christian Queinnec < > ;;; The original sources can be downloaded from the author's website at ;;; -systeme.lip6.fr/Christian.Queinnec/WWW/LiSP.html ;;; This file may have been altered from the original in order to work with ;;; modern schemes. The latest copy of these altered sources can be found at ;;; -In-Small-Pieces ;;; If you want to report a bug in this program, open a GitHub Issue at the ;;; repo mentioned above. ;;; Check the README file before using this file. ;;;(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) ;;; eval as a function in the bytecode compiler (definitial eval (let* ((arity 1) (arity+1 (+ arity 1)) ) (make-primitive (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (let ((v (activation-frame-argument *val* 0))) (if (program? v) (compile-and-run v r.init #t) (signal-exception #t (list "Illegal program" v)) ) ) (signal-exception #t (list "Incorrect arity" 'eval) ) ) ) ) ) ) ;;; same as in chap8d.scm (define (compile-and-run v r tail?) (set! g.current '()) (for-each g.current-extend! sg.current.names) (set! *quotations* (vector->list *constants*)) (set! *dynamic-variables* *dynamic-variables*) (let ((code (apply vector (append (meaning v r #f) (RETURN))))) (set! sg.current.names (map car (reverse g.current))) (let ((v (make-vector (length sg.current.names) undefined-value))) (_vector-copy! sg.current v 0 (vector-length sg.current)) (set! sg.current v) ) (set! *constants* (apply vector *quotations*)) (set! *dynamic-variables* *dynamic-variables*) (unless tail? (stack-push *pc*)) (set! *pc* (install-code! code)) ) ) ;;; end of chap8f.scm
null
https://raw.githubusercontent.com/appleby/Lisp-In-Small-Pieces/af4139232bb7170f32470774a92d647e83254721/src/chap8f.scm
scheme
(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) This file is derived from the files that accompany the book: The original sources can be downloaded from the author's website at -systeme.lip6.fr/Christian.Queinnec/WWW/LiSP.html This file may have been altered from the original in order to work with modern schemes. The latest copy of these altered sources can be found at -In-Small-Pieces If you want to report a bug in this program, open a GitHub Issue at the repo mentioned above. Check the README file before using this file. (((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) eval as a function in the bytecode compiler same as in chap8d.scm end of chap8f.scm
$ I d : chap8f.scm , v 4.1 2006/11/24 18:40:55 queinnec Exp $ LISP Implantation Semantique Programmation ( InterEditions , France ) or Lisp In Small Pieces ( Cambridge University Press ) . By Christian Queinnec < > (definitial eval (let* ((arity 1) (arity+1 (+ arity 1)) ) (make-primitive (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (let ((v (activation-frame-argument *val* 0))) (if (program? v) (compile-and-run v r.init #t) (signal-exception #t (list "Illegal program" v)) ) ) (signal-exception #t (list "Incorrect arity" 'eval) ) ) ) ) ) ) (define (compile-and-run v r tail?) (set! g.current '()) (for-each g.current-extend! sg.current.names) (set! *quotations* (vector->list *constants*)) (set! *dynamic-variables* *dynamic-variables*) (let ((code (apply vector (append (meaning v r #f) (RETURN))))) (set! sg.current.names (map car (reverse g.current))) (let ((v (make-vector (length sg.current.names) undefined-value))) (_vector-copy! sg.current v 0 (vector-length sg.current)) (set! sg.current v) ) (set! *constants* (apply vector *quotations*)) (set! *dynamic-variables* *dynamic-variables*) (unless tail? (stack-push *pc*)) (set! *pc* (install-code! code)) ) )
0abeea63a6fabfc8ffda312a6d32c9e96b012f075ef32da1d18a86869b1c8ce6
fantasytree/fancy_game_server
sup_boot.erl
%%---------------------------------------------------- %% 游戏区监控树 %%---------------------------------------------------- -module(sup_boot). -behaviour(supervisor). -export([start_link/1, init/1]). start_link(NodeType) -> supervisor:start_link({local, ?MODULE}, ?MODULE, [NodeType]). init([NodeType]) -> {ok, { {one_for_one, 50, 1} ,[ {env, {env, start_link, ["env.cfg"]}, transient, 10000, worker, [env]} ,{sys_code, {sys_code, start_link, []}, transient, 10000, worker, [sys_code]} ,{sys_rand, {sys_rand, start_link, []}, transient, 10000, worker, [sys_rand]} ,{sys_boot, {sys_boot, start_link, [NodeType]}, transient, 10000, worker, [sys_boot]} ] } }.
null
https://raw.githubusercontent.com/fantasytree/fancy_game_server/4ca93486fc0d5b6630170e79b48fb31e9c6e2358/src/sys/sup_boot.erl
erlang
---------------------------------------------------- 游戏区监控树 ----------------------------------------------------
-module(sup_boot). -behaviour(supervisor). -export([start_link/1, init/1]). start_link(NodeType) -> supervisor:start_link({local, ?MODULE}, ?MODULE, [NodeType]). init([NodeType]) -> {ok, { {one_for_one, 50, 1} ,[ {env, {env, start_link, ["env.cfg"]}, transient, 10000, worker, [env]} ,{sys_code, {sys_code, start_link, []}, transient, 10000, worker, [sys_code]} ,{sys_rand, {sys_rand, start_link, []}, transient, 10000, worker, [sys_rand]} ,{sys_boot, {sys_boot, start_link, [NodeType]}, transient, 10000, worker, [sys_boot]} ] } }.
45a95cf174209969ee54efc560320338504cd74762377ce3b8ed225ae074bb8e
processone/ejabberd
mod_delegation_opt.erl
%% Generated automatically %% DO NOT EDIT: run `make options` instead -module(mod_delegation_opt). -export([namespaces/1]). -spec namespaces(gen_mod:opts() | global | binary()) -> [{binary(),[binary()],acl:acl()}]. namespaces(Opts) when is_map(Opts) -> gen_mod:get_opt(namespaces, Opts); namespaces(Host) -> gen_mod:get_module_opt(Host, mod_delegation, namespaces).
null
https://raw.githubusercontent.com/processone/ejabberd/b860a25c82515ba51b044e13ea4e040e3b9bbc41/src/mod_delegation_opt.erl
erlang
Generated automatically DO NOT EDIT: run `make options` instead
-module(mod_delegation_opt). -export([namespaces/1]). -spec namespaces(gen_mod:opts() | global | binary()) -> [{binary(),[binary()],acl:acl()}]. namespaces(Opts) when is_map(Opts) -> gen_mod:get_opt(namespaces, Opts); namespaces(Host) -> gen_mod:get_module_opt(Host, mod_delegation, namespaces).
e37516b08e85b29a664c0bb80ea5f8988849836fa4078eb11dce3d9381c5566a
dundalek/closh
history_test.cljc
(ns closh.history-test (:require [clojure.test :refer [deftest is testing]] [closh.test-util.util :refer [with-tempfile] #?@(:cljs [:refer-macros [with-async]])] [closh.zero.macros #?(:clj :refer :cljs :refer-macros) [chain->]] #?(:cljs [closh.zero.service.history-common :refer [check-history-line]]) #?(:cljs [util]) #?(:cljs [closh.zero.service.history :as history] :clj [closh.zero.frontend.jline-history :as jhistory]))) #?(:clj (do (defn iter->seq [iter] (loop [coll []] (if (.hasPrevious iter) (recur (conj coll (.previous iter))) coll))) (defn history->seq [h] (->> (iter->seq (.iterator h (.index h))) (map #(.line %)) (into []))))) #?(:cljs (do (def add-history-promise (util/promisify history/add-history)) (def search-history-prev (util/promisify history/search-history-prev)) (def search-history-next (util/promisify history/search-history-next)) (defn history->seq ([h] (history->seq h "" nil :prefix [])) ([h query history-state search-mode coll] (.then (search-history-prev h query history-state search-mode) (fn [data] (if-let [[line history-state] data] (history->seq h query history-state search-mode (conj coll line)) coll))))))) (defn create-history [db-file] #?(:clj (jhistory/sqlite-history db-file) :cljs (history/init-database db-file))) (defn add-history [h command] #?(:clj (.add h command) :cljs (if-let [command (check-history-line command)] (add-history-promise h command "") (js/Promise.resolve)))) (defn assert-history [expected h] #?(:clj (is (= expected (history->seq h))) :cljs (.then (history->seq h) (fn [result] (is (= expected result)))))) #?(:clj (defmacro with-async [form] form)) (deftest history-multi-sessions (testing "First get history from current session, then from other sessions" (with-tempfile (fn [db-file] (let [s1 (create-history db-file) s2 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s2 "b")) (fn [_] (add-history s1 "c")) #?(:clj (fn [_] (.moveToEnd s2))) (fn [_] (assert-history ["c" "a" "b"] s1)) (fn [_] (assert-history ["b" "c" "a"] s2))))))))) (deftest history-leading-whitespace (testing "Do do not add when line is starting with whitespace" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s1 " b")) (fn [_] (assert-history ["a"] s1))))))))) (deftest history-dont-add-empty (testing "Do do not add empty lines" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s1 " ")) (fn [_] (add-history s1 "")) (fn [_] (assert-history ["a"] s1))))))))) (deftest history-trim-whitespace (testing "Trim whitespace" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a b \n") (fn [_] (assert-history ["a b"] s1))))))))) (deftest history-no-duplicates (testing "No duplicates are returned" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s1 "b")) (fn [_] (add-history s1 "a")) (fn [_] (assert-history ["a" "b"] s1)))))))))
null
https://raw.githubusercontent.com/dundalek/closh/b1a7fd310b6511048fbacb8e496f574c8ccfa291/test/closh/history_test.cljc
clojure
(ns closh.history-test (:require [clojure.test :refer [deftest is testing]] [closh.test-util.util :refer [with-tempfile] #?@(:cljs [:refer-macros [with-async]])] [closh.zero.macros #?(:clj :refer :cljs :refer-macros) [chain->]] #?(:cljs [closh.zero.service.history-common :refer [check-history-line]]) #?(:cljs [util]) #?(:cljs [closh.zero.service.history :as history] :clj [closh.zero.frontend.jline-history :as jhistory]))) #?(:clj (do (defn iter->seq [iter] (loop [coll []] (if (.hasPrevious iter) (recur (conj coll (.previous iter))) coll))) (defn history->seq [h] (->> (iter->seq (.iterator h (.index h))) (map #(.line %)) (into []))))) #?(:cljs (do (def add-history-promise (util/promisify history/add-history)) (def search-history-prev (util/promisify history/search-history-prev)) (def search-history-next (util/promisify history/search-history-next)) (defn history->seq ([h] (history->seq h "" nil :prefix [])) ([h query history-state search-mode coll] (.then (search-history-prev h query history-state search-mode) (fn [data] (if-let [[line history-state] data] (history->seq h query history-state search-mode (conj coll line)) coll))))))) (defn create-history [db-file] #?(:clj (jhistory/sqlite-history db-file) :cljs (history/init-database db-file))) (defn add-history [h command] #?(:clj (.add h command) :cljs (if-let [command (check-history-line command)] (add-history-promise h command "") (js/Promise.resolve)))) (defn assert-history [expected h] #?(:clj (is (= expected (history->seq h))) :cljs (.then (history->seq h) (fn [result] (is (= expected result)))))) #?(:clj (defmacro with-async [form] form)) (deftest history-multi-sessions (testing "First get history from current session, then from other sessions" (with-tempfile (fn [db-file] (let [s1 (create-history db-file) s2 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s2 "b")) (fn [_] (add-history s1 "c")) #?(:clj (fn [_] (.moveToEnd s2))) (fn [_] (assert-history ["c" "a" "b"] s1)) (fn [_] (assert-history ["b" "c" "a"] s2))))))))) (deftest history-leading-whitespace (testing "Do do not add when line is starting with whitespace" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s1 " b")) (fn [_] (assert-history ["a"] s1))))))))) (deftest history-dont-add-empty (testing "Do do not add empty lines" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s1 " ")) (fn [_] (add-history s1 "")) (fn [_] (assert-history ["a"] s1))))))))) (deftest history-trim-whitespace (testing "Trim whitespace" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a b \n") (fn [_] (assert-history ["a b"] s1))))))))) (deftest history-no-duplicates (testing "No duplicates are returned" (with-tempfile (fn [db-file] (let [s1 (create-history db-file)] (with-async (chain-> (add-history s1 "a") (fn [_] (add-history s1 "b")) (fn [_] (add-history s1 "a")) (fn [_] (assert-history ["a" "b"] s1)))))))))
1e9551f1243b8594ea2318c7bfac1607d4b6336a9e12814e9ede6f2584f51cd2
ashinkarov/heh
parser.ml
* Copyright ( c ) 2017 - 2018 , < > * * Permission to use , copy , modify , and/or distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , * INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE * OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2017-2018, Artem Shinkarov <> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. *) module Tok = struct type t = { loc: Loc.t; tok: Lexer.token; } let mk loc tok = {loc; tok} let to_str tok = Lexer.tok_to_str tok.tok let get_tok tok = tok.tok let get_loc tok = tok.loc let eq tok lextok = tok.tok = lextok end let opt_get = function | Some x -> x | None -> raise (Invalid_argument "opt_get") open Lexer open Printf open Ordinals open Ast (* This is a helper type to allow for short generators of form: _(iv): expr as opposed to regular generators lb_expr <= iv < ub_expr *) type gen_opt = | FullGen of expr * string * expr | DefGen of string let mk_full_gen shp x = let { loc = shp_loc } = shp in let mul_shp_zero = mk_elambda "__x" (mk_eimap (mk_eunary OpShape (mk_evar "__x")) (mk_earray []) [( (* generator: [0] <= iv |__x| *) (mk_earray [mk_enum zero], "__iv", mk_eunary OpShape (mk_evar "__x")), (* body: 0 * __x.iv *) mk_ebinop OpMult (mk_enum zero) (mk_esel (mk_evar "__x") (mk_evar "__iv")))]) ~loc:shp_loc in (mk_eapply mul_shp_zero shp, x, shp) let op_prec tok = match tok with (* = and <> have the least priority *) | EQ -> 1 | NE -> 1 (* comparisons <, <=, >, >= *) | LT -> 2 | LE -> 2 | GT -> 2 | GE -> 2 (* addition/subtraction: +, - *) | PLUS -> 3 | MINUS -> 3 (* multiplication/division/modulo: *, /, % *) | MULT -> 4 | DIV -> 4 | MOD -> 4 (* any other possibly user-defined operations *) | _ -> 5 Stack to keep tokens that we have peeked at but not consumed yet . but not consumed yet. *) let tok_stack = ref [] State of the parser that indicates whether ` | ' can start an expression . This is useful when disambiguating nested expression within |e| . start an expression. This is useful when disambiguating nested expression within |e|. *) let bar_starts_expr = ref true let parse_err_loc loc msg = raise (ImapFailure (sprintf "%s: error: %s" (Loc.to_str loc) msg)) let get_loc lexbuf = (* XXX we can grab the end of the token as well, in case we want to. *) let open Lexing in let loc_s = lexeme_start_p lexbuf in let l = Loc.mk loc_s.pos_fname loc_s.pos_lnum (loc_s.pos_cnum - loc_s.pos_bol + 1) in l (* Puts the token back on the to of the stack. *) let unget_tok tok = printf " unget - tok ` % s'\n " @@ ; tok_stack := tok :: !tok_stack let get_token lexbuf = match !tok_stack with | [] -> let t = Lexer.token lexbuf in let l = get_loc lexbuf in (* print_sloc l; *) (* printf "get-token returns `%s'\n" @@ tok_to_str t; *) Tok.mk l t | h::t -> tok_stack := t; (*printf "get-token returns `%s'\n" @@ tok_to_str h;*) h let peek_token lexbuf = let t = get_token lexbuf in unget_tok t; (*printf "peek-tok returns `%s'\n" @@ tok_to_str t;*) t let peek_loc lexbuf = Tok.get_loc (peek_token lexbuf) FIXME add ' msg ' parameter to alter the error message . let expect_id lexbuf = let t = get_token lexbuf in match Tok.get_tok t with | ID (x) -> t | _ -> parse_err_loc (Tok.get_loc t) @@ sprintf "expected identifier, found `%s' instead" (Tok.to_str t) FIXME add ' msg ' parameter to alter the error message . let expect_tok lexbuf t_exp = let t = get_token lexbuf in if Tok.get_tok t <> t_exp then parse_err_loc (Tok.get_loc t) @@ sprintf "expected token `%s', found `%s' instead" (Lexer.tok_to_str t_exp) (Tok.to_str t); t (* Parse NON-EMPTY comma separated list of elements that can be parsed by `parse_fun' function. *) let rec parse_generic_list ?(msg="expression expected") lexbuf parse_fun = let e = parse_fun lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) msg; let t = peek_token lexbuf in if Tok.get_tok t = COMMA then let _ = get_token lexbuf in let l = parse_generic_list ~msg:msg lexbuf parse_fun in e :: l else [e] let rec parse_primary lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in match Tok.get_tok t with | TRUE -> Some (mk_etrue () ~loc:l) | FALSE -> Some (mk_efalse () ~loc:l) | ID x -> Some (mk_evar x ~loc:l) | INT n -> Some (mk_enum (int_to_ord n) ~loc:l) | OMEGA -> Some (mk_enum (omega) ~loc:l) | BAR -> if !bar_starts_expr then begin bar_starts_expr := false; let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "expression expected after |"; let t = peek_token lexbuf in if Tok.get_tok t <> BAR then parse_err_loc (Tok.get_loc t) (sprintf "missing closing `|' to match the one at location %s" (Loc.to_str l)); let _ = get_token lexbuf in bar_starts_expr := true; Some (mk_eunary OpShape (opt_get e) ~loc:l) end else begin unget_tok t; None end | LSQUARE -> let bar_state = !bar_starts_expr in bar_starts_expr := true; let lst = if Tok.get_tok (peek_token lexbuf) = RSQUARE then [] else parse_generic_list lexbuf parse_expr ~msg:"array element definition is missing" in let _ = expect_tok lexbuf RSQUARE in bar_starts_expr := bar_state; Some (mk_earray (List.map opt_get lst) ~loc:l) | LPAREN -> let bar_state = !bar_starts_expr in bar_starts_expr := true; let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "empty expression found"; let _ = expect_tok lexbuf RPAREN in bar_starts_expr := bar_state; e | LAMBDA -> unget_tok t; parse_lambda lexbuf | IF -> unget_tok t; parse_cond lexbuf | LETREC -> unget_tok t; parse_letrec lexbuf | IMAP -> unget_tok t; parse_imap lexbuf | _ -> unget_tok t; None and parse_postfix lexbuf = let e = ref @@ parse_primary lexbuf in while !e <> None && Tok.get_tok (peek_token lexbuf) = DOT do let _ = get_token lexbuf in let e1 = parse_primary lexbuf in if e1 = None then parse_err_loc (peek_loc lexbuf) "expected index specification in selection"; e := Some (mk_esel (opt_get !e) (opt_get e1)) done; !e and parse_unary lexbuf = let t = peek_token lexbuf in let l = Tok.get_loc t in match Tok.get_tok t with | ISLIM -> let _ = get_token lexbuf in let e = parse_unary lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "expected expression after `islim' operator"; Some (mk_eunary OpIsLim (opt_get e) ~loc:l) | _ -> parse_postfix lexbuf and parse_app ?(e1=None) lexbuf = match e1, parse_unary lexbuf with | None, Some e2 -> parse_app lexbuf ~e1:(Some e2) | Some e1, Some e2 -> parse_app lexbuf ~e1:(Some (mk_eapply e1 e2)) | _, None -> e1 and parse_binop ?(no_relop=false) lexbuf = let rec resolve_stack s prec = let e1, op1, p1 = Stack.pop s in if prec <= p1 then begin let e2, op2, p2 = Stack.pop s in let e = mk_ebinop (op_to_binop op1) (opt_get e2) (opt_get e1) in Stack.push (Some (e), op2, p2) s; resolve_stack s prec end else begin Stack.push (e1, op1, p1) s end in let e1 = parse_app lexbuf in if e1 = None then e1 else let s = Stack.create () in First expression goes with no priority , priority = -1 . FIXME we also use EOF as bogus operation , we can make this field of type token option to make it cleaner . FIXME we also use EOF as bogus operation, we can make this field of type token option to make it cleaner. *) Stack.push (e1, EOF, -1) s; while is_op ~no_relop:no_relop (Tok.get_tok @@ peek_token lexbuf) do let t = get_token lexbuf in (* resolve priority stack. *) resolve_stack s (op_prec @@ Tok.get_tok t); let e2 = parse_app lexbuf in if e2 = None then parse_err_loc (peek_loc lexbuf) @@ sprintf "expression expected after %s" (Tok.to_str t); Stack.push (e2, Tok.get_tok t, (op_prec @@ Tok.get_tok t)) s; done; resolve_stack s 0; let e, op, prec = Stack.pop s in e and parse_expr lexbuf = parse_binop lexbuf and parse_lambda lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (LAMBDA = Tok.get_tok t); let t = expect_id lexbuf in let _ = expect_tok lexbuf DOT in let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "expression expected after `.'"; Some (mk_elambda (Tok.to_str t) (opt_get e) ~loc:l) and parse_cond lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (IF = Tok.get_tok t); let bar_state = !bar_starts_expr in bar_starts_expr := true; let e1 = parse_expr lexbuf in if e1 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `if'"; let _ = expect_tok lexbuf THEN in let e2 = parse_expr lexbuf in if e2 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `then'"; let _ = expect_tok lexbuf ELSE in bar_starts_expr := bar_state; let e3 = parse_expr lexbuf in if e3 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `else'"; Some (mk_econd (opt_get e1) (opt_get e2) (opt_get e3) ~loc:l) and parse_letrec lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (LETREC = Tok.get_tok t); let t = expect_id lexbuf in let _ = expect_tok lexbuf EQ in let bar_state = !bar_starts_expr in bar_starts_expr := true; let e1 = parse_expr lexbuf in bar_starts_expr := bar_state; if e1 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `=' and before `in'"; let _ = expect_tok lexbuf IN in let e2 = parse_expr lexbuf in if e2 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `in'"; Some (mk_eletrec (Tok.to_str t) (opt_get e1) (opt_get e2) ~loc:l) and parse_imap lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (IMAP = Tok.get_tok t); let bar_state = !bar_starts_expr in bar_starts_expr := (Tok.get_tok @@ peek_token lexbuf) = BAR; let sh1 = parse_expr lexbuf in if sh1 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `imap'"; let sh2 = if BAR = Tok.get_tok @@ peek_token lexbuf then begin bar_starts_expr := true; let _ = get_token lexbuf in let sh2 = parse_expr lexbuf in if sh2 = None then parse_err_loc (peek_loc lexbuf) "cell shape specification expected"; sh2 end else Some (mk_earray []) in let _ = expect_tok lexbuf LBRACE in bar_starts_expr := bar_state; let lst = parse_generic_list lexbuf parse_gen ~msg:"generator expected" in let gl = List.map (fun x -> match x with | Some (FullGen (lb, x, ub), e) -> ((lb, x, ub), e) | Some (DefGen (x), e) -> (* construct gen (out_shp * 0) <= x < out_shp *) (mk_full_gen (opt_get sh1) x, e) | _ -> raise (ImapFailure "error in parser function `parse_gen'")) lst in Some (mk_eimap (opt_get sh1) (opt_get sh2) gl ~loc:l) and parse_gen lexbuf = let t = peek_token lexbuf in let gen = if Tok.get_tok t = UNDERSCORE then let _ = get_token lexbuf in let _ = expect_tok lexbuf LPAREN in let iv = expect_id lexbuf in let _ = expect_tok lexbuf RPAREN in DefGen (Tok.to_str iv) else let lb = parse_binop ~no_relop:true lexbuf in if lb = None then parse_err_loc (peek_loc lexbuf) "lower bound expression expected"; let _ = expect_tok lexbuf LE in let iv = expect_id lexbuf in let _ = expect_tok lexbuf LT in let ub = parse_binop lexbuf in if ub = None then parse_err_loc (peek_loc lexbuf) "upper bound expression expected"; FullGen ((opt_get lb), (Tok.to_str iv), (opt_get ub)) in let _ = expect_tok lexbuf COLON in let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "generator body expected"; Some (gen, opt_get e) let prog lexbuf = tok_stack := []; bar_starts_expr := true; match parse_expr lexbuf with | Some (e) -> e | None -> raise (ImapFailure (sprintf "failed to parse `%s' (parser rerutned None)" !Globals.fname))
null
https://raw.githubusercontent.com/ashinkarov/heh/42866803b2ffacdc42b8f06203bf4e5bd18e03b0/parser.ml
ocaml
This is a helper type to allow for short generators of form: _(iv): expr as opposed to regular generators lb_expr <= iv < ub_expr generator: [0] <= iv |__x| body: 0 * __x.iv = and <> have the least priority comparisons <, <=, >, >= addition/subtraction: +, - multiplication/division/modulo: *, /, % any other possibly user-defined operations XXX we can grab the end of the token as well, in case we want to. Puts the token back on the to of the stack. print_sloc l; printf "get-token returns `%s'\n" @@ tok_to_str t; printf "get-token returns `%s'\n" @@ tok_to_str h; printf "peek-tok returns `%s'\n" @@ tok_to_str t; Parse NON-EMPTY comma separated list of elements that can be parsed by `parse_fun' function. resolve priority stack. construct gen (out_shp * 0) <= x < out_shp
* Copyright ( c ) 2017 - 2018 , < > * * Permission to use , copy , modify , and/or distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , * INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE * OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2017-2018, Artem Shinkarov <> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. *) module Tok = struct type t = { loc: Loc.t; tok: Lexer.token; } let mk loc tok = {loc; tok} let to_str tok = Lexer.tok_to_str tok.tok let get_tok tok = tok.tok let get_loc tok = tok.loc let eq tok lextok = tok.tok = lextok end let opt_get = function | Some x -> x | None -> raise (Invalid_argument "opt_get") open Lexer open Printf open Ordinals open Ast type gen_opt = | FullGen of expr * string * expr | DefGen of string let mk_full_gen shp x = let { loc = shp_loc } = shp in let mul_shp_zero = mk_elambda "__x" (mk_eimap (mk_eunary OpShape (mk_evar "__x")) (mk_earray []) [( (mk_earray [mk_enum zero], "__iv", mk_eunary OpShape (mk_evar "__x")), mk_ebinop OpMult (mk_enum zero) (mk_esel (mk_evar "__x") (mk_evar "__iv")))]) ~loc:shp_loc in (mk_eapply mul_shp_zero shp, x, shp) let op_prec tok = match tok with | EQ -> 1 | NE -> 1 | LT -> 2 | LE -> 2 | GT -> 2 | GE -> 2 | PLUS -> 3 | MINUS -> 3 | MULT -> 4 | DIV -> 4 | MOD -> 4 | _ -> 5 Stack to keep tokens that we have peeked at but not consumed yet . but not consumed yet. *) let tok_stack = ref [] State of the parser that indicates whether ` | ' can start an expression . This is useful when disambiguating nested expression within |e| . start an expression. This is useful when disambiguating nested expression within |e|. *) let bar_starts_expr = ref true let parse_err_loc loc msg = raise (ImapFailure (sprintf "%s: error: %s" (Loc.to_str loc) msg)) let get_loc lexbuf = let open Lexing in let loc_s = lexeme_start_p lexbuf in let l = Loc.mk loc_s.pos_fname loc_s.pos_lnum (loc_s.pos_cnum - loc_s.pos_bol + 1) in l let unget_tok tok = printf " unget - tok ` % s'\n " @@ ; tok_stack := tok :: !tok_stack let get_token lexbuf = match !tok_stack with | [] -> let t = Lexer.token lexbuf in let l = get_loc lexbuf in Tok.mk l t | h::t -> tok_stack := t; h let peek_token lexbuf = let t = get_token lexbuf in unget_tok t; t let peek_loc lexbuf = Tok.get_loc (peek_token lexbuf) FIXME add ' msg ' parameter to alter the error message . let expect_id lexbuf = let t = get_token lexbuf in match Tok.get_tok t with | ID (x) -> t | _ -> parse_err_loc (Tok.get_loc t) @@ sprintf "expected identifier, found `%s' instead" (Tok.to_str t) FIXME add ' msg ' parameter to alter the error message . let expect_tok lexbuf t_exp = let t = get_token lexbuf in if Tok.get_tok t <> t_exp then parse_err_loc (Tok.get_loc t) @@ sprintf "expected token `%s', found `%s' instead" (Lexer.tok_to_str t_exp) (Tok.to_str t); t let rec parse_generic_list ?(msg="expression expected") lexbuf parse_fun = let e = parse_fun lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) msg; let t = peek_token lexbuf in if Tok.get_tok t = COMMA then let _ = get_token lexbuf in let l = parse_generic_list ~msg:msg lexbuf parse_fun in e :: l else [e] let rec parse_primary lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in match Tok.get_tok t with | TRUE -> Some (mk_etrue () ~loc:l) | FALSE -> Some (mk_efalse () ~loc:l) | ID x -> Some (mk_evar x ~loc:l) | INT n -> Some (mk_enum (int_to_ord n) ~loc:l) | OMEGA -> Some (mk_enum (omega) ~loc:l) | BAR -> if !bar_starts_expr then begin bar_starts_expr := false; let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "expression expected after |"; let t = peek_token lexbuf in if Tok.get_tok t <> BAR then parse_err_loc (Tok.get_loc t) (sprintf "missing closing `|' to match the one at location %s" (Loc.to_str l)); let _ = get_token lexbuf in bar_starts_expr := true; Some (mk_eunary OpShape (opt_get e) ~loc:l) end else begin unget_tok t; None end | LSQUARE -> let bar_state = !bar_starts_expr in bar_starts_expr := true; let lst = if Tok.get_tok (peek_token lexbuf) = RSQUARE then [] else parse_generic_list lexbuf parse_expr ~msg:"array element definition is missing" in let _ = expect_tok lexbuf RSQUARE in bar_starts_expr := bar_state; Some (mk_earray (List.map opt_get lst) ~loc:l) | LPAREN -> let bar_state = !bar_starts_expr in bar_starts_expr := true; let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "empty expression found"; let _ = expect_tok lexbuf RPAREN in bar_starts_expr := bar_state; e | LAMBDA -> unget_tok t; parse_lambda lexbuf | IF -> unget_tok t; parse_cond lexbuf | LETREC -> unget_tok t; parse_letrec lexbuf | IMAP -> unget_tok t; parse_imap lexbuf | _ -> unget_tok t; None and parse_postfix lexbuf = let e = ref @@ parse_primary lexbuf in while !e <> None && Tok.get_tok (peek_token lexbuf) = DOT do let _ = get_token lexbuf in let e1 = parse_primary lexbuf in if e1 = None then parse_err_loc (peek_loc lexbuf) "expected index specification in selection"; e := Some (mk_esel (opt_get !e) (opt_get e1)) done; !e and parse_unary lexbuf = let t = peek_token lexbuf in let l = Tok.get_loc t in match Tok.get_tok t with | ISLIM -> let _ = get_token lexbuf in let e = parse_unary lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "expected expression after `islim' operator"; Some (mk_eunary OpIsLim (opt_get e) ~loc:l) | _ -> parse_postfix lexbuf and parse_app ?(e1=None) lexbuf = match e1, parse_unary lexbuf with | None, Some e2 -> parse_app lexbuf ~e1:(Some e2) | Some e1, Some e2 -> parse_app lexbuf ~e1:(Some (mk_eapply e1 e2)) | _, None -> e1 and parse_binop ?(no_relop=false) lexbuf = let rec resolve_stack s prec = let e1, op1, p1 = Stack.pop s in if prec <= p1 then begin let e2, op2, p2 = Stack.pop s in let e = mk_ebinop (op_to_binop op1) (opt_get e2) (opt_get e1) in Stack.push (Some (e), op2, p2) s; resolve_stack s prec end else begin Stack.push (e1, op1, p1) s end in let e1 = parse_app lexbuf in if e1 = None then e1 else let s = Stack.create () in First expression goes with no priority , priority = -1 . FIXME we also use EOF as bogus operation , we can make this field of type token option to make it cleaner . FIXME we also use EOF as bogus operation, we can make this field of type token option to make it cleaner. *) Stack.push (e1, EOF, -1) s; while is_op ~no_relop:no_relop (Tok.get_tok @@ peek_token lexbuf) do let t = get_token lexbuf in resolve_stack s (op_prec @@ Tok.get_tok t); let e2 = parse_app lexbuf in if e2 = None then parse_err_loc (peek_loc lexbuf) @@ sprintf "expression expected after %s" (Tok.to_str t); Stack.push (e2, Tok.get_tok t, (op_prec @@ Tok.get_tok t)) s; done; resolve_stack s 0; let e, op, prec = Stack.pop s in e and parse_expr lexbuf = parse_binop lexbuf and parse_lambda lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (LAMBDA = Tok.get_tok t); let t = expect_id lexbuf in let _ = expect_tok lexbuf DOT in let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "expression expected after `.'"; Some (mk_elambda (Tok.to_str t) (opt_get e) ~loc:l) and parse_cond lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (IF = Tok.get_tok t); let bar_state = !bar_starts_expr in bar_starts_expr := true; let e1 = parse_expr lexbuf in if e1 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `if'"; let _ = expect_tok lexbuf THEN in let e2 = parse_expr lexbuf in if e2 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `then'"; let _ = expect_tok lexbuf ELSE in bar_starts_expr := bar_state; let e3 = parse_expr lexbuf in if e3 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `else'"; Some (mk_econd (opt_get e1) (opt_get e2) (opt_get e3) ~loc:l) and parse_letrec lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (LETREC = Tok.get_tok t); let t = expect_id lexbuf in let _ = expect_tok lexbuf EQ in let bar_state = !bar_starts_expr in bar_starts_expr := true; let e1 = parse_expr lexbuf in bar_starts_expr := bar_state; if e1 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `=' and before `in'"; let _ = expect_tok lexbuf IN in let e2 = parse_expr lexbuf in if e2 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `in'"; Some (mk_eletrec (Tok.to_str t) (opt_get e1) (opt_get e2) ~loc:l) and parse_imap lexbuf = let t = get_token lexbuf in let l = Tok.get_loc t in assert (IMAP = Tok.get_tok t); let bar_state = !bar_starts_expr in bar_starts_expr := (Tok.get_tok @@ peek_token lexbuf) = BAR; let sh1 = parse_expr lexbuf in if sh1 = None then parse_err_loc (peek_loc lexbuf) "expression expected after `imap'"; let sh2 = if BAR = Tok.get_tok @@ peek_token lexbuf then begin bar_starts_expr := true; let _ = get_token lexbuf in let sh2 = parse_expr lexbuf in if sh2 = None then parse_err_loc (peek_loc lexbuf) "cell shape specification expected"; sh2 end else Some (mk_earray []) in let _ = expect_tok lexbuf LBRACE in bar_starts_expr := bar_state; let lst = parse_generic_list lexbuf parse_gen ~msg:"generator expected" in let gl = List.map (fun x -> match x with | Some (FullGen (lb, x, ub), e) -> ((lb, x, ub), e) | Some (DefGen (x), e) -> (mk_full_gen (opt_get sh1) x, e) | _ -> raise (ImapFailure "error in parser function `parse_gen'")) lst in Some (mk_eimap (opt_get sh1) (opt_get sh2) gl ~loc:l) and parse_gen lexbuf = let t = peek_token lexbuf in let gen = if Tok.get_tok t = UNDERSCORE then let _ = get_token lexbuf in let _ = expect_tok lexbuf LPAREN in let iv = expect_id lexbuf in let _ = expect_tok lexbuf RPAREN in DefGen (Tok.to_str iv) else let lb = parse_binop ~no_relop:true lexbuf in if lb = None then parse_err_loc (peek_loc lexbuf) "lower bound expression expected"; let _ = expect_tok lexbuf LE in let iv = expect_id lexbuf in let _ = expect_tok lexbuf LT in let ub = parse_binop lexbuf in if ub = None then parse_err_loc (peek_loc lexbuf) "upper bound expression expected"; FullGen ((opt_get lb), (Tok.to_str iv), (opt_get ub)) in let _ = expect_tok lexbuf COLON in let e = parse_expr lexbuf in if e = None then parse_err_loc (peek_loc lexbuf) "generator body expected"; Some (gen, opt_get e) let prog lexbuf = tok_stack := []; bar_starts_expr := true; match parse_expr lexbuf with | Some (e) -> e | None -> raise (ImapFailure (sprintf "failed to parse `%s' (parser rerutned None)" !Globals.fname))
d3e974141d59b54f39dae3e3b3f595c0420aaa00fe384eabab473b65ee05bcff
cojna/iota
UtilsSpec.hs
# LANGUAGE ViewPatterns # module Math.UtilsSpec where import Data.Bits import Math.Utils import Test.Prelude main :: IO () main = hspec spec spec :: Spec spec = do describe "floorSqrt" $ do prop "floor (sqrt x)" prop_floorSqrt describe "floorLog2" $ do it "floorLog2 0 = -1023" $ do floorLog2 0 `shouldBe` (-1023) it "floorLog2 1 = 0" $ do floorLog2 1 `shouldBe` 0 it "floorLog2 2 = 1" $ do floorLog2 2 `shouldBe` 1 it "floorLog2 3 = 1" $ do floorLog2 3 `shouldBe` 1 it "floorLog2 1023 = 9" $ do floorLog2 1023 `shouldBe` 9 it "floorLog2 1024 = 10" $ do floorLog2 1024 `shouldBe` 10 it "floorLog2 1025 = 10" $ do floorLog2 1025 `shouldBe` 10 prop "2 ^ n <= floorLog2 n < 2 ^ (n + 1)" prop_floorLog2 prop_floorSqrt :: NonNegative Int -> Bool prop_floorSqrt (getNonNegative -> n) = res * res <= n && (res + 1) * (res + 1) > n where res = floorSqrt n prop_floorLog2 :: Positive Int -> Bool prop_floorLog2 (getPositive -> n) = shiftL 1 res <= n && n < shiftL 1 (res + 1) where res = floorLog2 n
null
https://raw.githubusercontent.com/cojna/iota/6d2ad5b71b1b50bca9136d6ed84f80a0b7713d7c/test/Math/UtilsSpec.hs
haskell
# LANGUAGE ViewPatterns # module Math.UtilsSpec where import Data.Bits import Math.Utils import Test.Prelude main :: IO () main = hspec spec spec :: Spec spec = do describe "floorSqrt" $ do prop "floor (sqrt x)" prop_floorSqrt describe "floorLog2" $ do it "floorLog2 0 = -1023" $ do floorLog2 0 `shouldBe` (-1023) it "floorLog2 1 = 0" $ do floorLog2 1 `shouldBe` 0 it "floorLog2 2 = 1" $ do floorLog2 2 `shouldBe` 1 it "floorLog2 3 = 1" $ do floorLog2 3 `shouldBe` 1 it "floorLog2 1023 = 9" $ do floorLog2 1023 `shouldBe` 9 it "floorLog2 1024 = 10" $ do floorLog2 1024 `shouldBe` 10 it "floorLog2 1025 = 10" $ do floorLog2 1025 `shouldBe` 10 prop "2 ^ n <= floorLog2 n < 2 ^ (n + 1)" prop_floorLog2 prop_floorSqrt :: NonNegative Int -> Bool prop_floorSqrt (getNonNegative -> n) = res * res <= n && (res + 1) * (res + 1) > n where res = floorSqrt n prop_floorLog2 :: Positive Int -> Bool prop_floorLog2 (getPositive -> n) = shiftL 1 res <= n && n < shiftL 1 (res + 1) where res = floorLog2 n
3a0909a211c0a85200fae6b6bb366c08ad85d9c6170c6a34202124ca52754131
Frama-C/Frama-C-snapshot
source_viewer.ml
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 , version 2.1 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (* Build a read only text view for C source code. *) let set_language_to_C (buffer:GSourceView.source_buffer) = let original_source_language_manager = GSourceView.source_language_manager ~default:true in let original_lang = original_source_language_manager#guess_language ~content_type:"text/x-csrc" () in begin match original_lang with | Some _ -> buffer#set_language original_lang | None -> Gui_parameters.warning "Mime type 'text/x-csrc' not found" end; buffer#set_highlight_syntax true let make ?name ~packing () = let d = GWindow.font_selection_dialog ~title:"tutu " ~show : true ( ) in d#selection#set_preview_text ( Format.sprintf " % s % s % s % s " Utf8_logic.forall Utf8_logic.exists Utf8_logic.eq Utf8_logic.neq ) ; d#selection#set_preview_text (Format.sprintf "%s %s %s %s" Utf8_logic.forall Utf8_logic.exists Utf8_logic.eq Utf8_logic.neq) ; *) let original_source_window = GSourceView.source_view ~show_line_numbers:true ~editable:false ~packing () in (* let pixbuf = original_source_window#misc#render_icon ~size:`MENU `DIALOG_WARNING in original_source_window#set_marker_pixbuf "warning" pixbuf; *) original_source_window#misc#modify_font_by_name "Monospace"; original_source_window#misc#set_name (Extlib.opt_conv "source" name); let original_source_buffer = original_source_window#source_buffer in set_language_to_C original_source_buffer; (* ignore (original_source_buffer#create_marker ~typ:"warning" original_source_buffer#start_iter ) ;*) begin try original_source_window#set_highlight_current_line true with Not_found -> () (* very old gtksourceview do not have this property. *) end; original_source_window let buffer () = let original_source_buffer = GSourceView.source_buffer () in set_language_to_C original_source_buffer; original_source_buffer
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/gui/source_viewer.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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. ************************************************************************ Build a read only text view for C source code. let pixbuf = original_source_window#misc#render_icon ~size:`MENU `DIALOG_WARNING in original_source_window#set_marker_pixbuf "warning" pixbuf; ignore (original_source_buffer#create_marker ~typ:"warning" original_source_buffer#start_iter ) ; very old gtksourceview do not have this property.
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . let set_language_to_C (buffer:GSourceView.source_buffer) = let original_source_language_manager = GSourceView.source_language_manager ~default:true in let original_lang = original_source_language_manager#guess_language ~content_type:"text/x-csrc" () in begin match original_lang with | Some _ -> buffer#set_language original_lang | None -> Gui_parameters.warning "Mime type 'text/x-csrc' not found" end; buffer#set_highlight_syntax true let make ?name ~packing () = let d = GWindow.font_selection_dialog ~title:"tutu " ~show : true ( ) in d#selection#set_preview_text ( Format.sprintf " % s % s % s % s " Utf8_logic.forall Utf8_logic.exists Utf8_logic.eq Utf8_logic.neq ) ; d#selection#set_preview_text (Format.sprintf "%s %s %s %s" Utf8_logic.forall Utf8_logic.exists Utf8_logic.eq Utf8_logic.neq) ; *) let original_source_window = GSourceView.source_view ~show_line_numbers:true ~editable:false ~packing () in original_source_window#misc#modify_font_by_name "Monospace"; original_source_window#misc#set_name (Extlib.opt_conv "source" name); let original_source_buffer = original_source_window#source_buffer in set_language_to_C original_source_buffer; begin try original_source_window#set_highlight_current_line true with Not_found -> () end; original_source_window let buffer () = let original_source_buffer = GSourceView.source_buffer () in set_language_to_C original_source_buffer; original_source_buffer
3d52e3cdd706a37175e7e2f239be081623467759aa634c66f81776d4a48ee0f3
startalkIM/ejabberd
mod_blocking_mnesia.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2016 , %%% @doc %%% %%% @end Created : 14 Apr 2016 by < > %%%------------------------------------------------------------------- -module(mod_blocking_mnesia). -behaviour(mod_blocking). %% API -export([process_blocklist_block/3, unblock_by_filter/3, process_blocklist_get/2]). -include("jlib.hrl"). -include("mod_privacy.hrl"). %%%=================================================================== %%% API %%%=================================================================== process_blocklist_block(LUser, LServer, Filter) -> F = fun () -> case mnesia:wread({privacy, {LUser, LServer}}) of [] -> P = #privacy{us = {LUser, LServer}}, NewDefault = <<"Blocked contacts">>, NewLists1 = [], List = []; [#privacy{default = Default, lists = Lists} = P] -> case lists:keysearch(Default, 1, Lists) of {value, {_, List}} -> NewDefault = Default, NewLists1 = lists:keydelete(Default, 1, Lists); false -> NewDefault = <<"Blocked contacts">>, NewLists1 = Lists, List = [] end end, NewList = Filter(List), NewLists = [{NewDefault, NewList} | NewLists1], mnesia:write(P#privacy{default = NewDefault, lists = NewLists}), {ok, NewDefault, NewList} end, mnesia:transaction(F). unblock_by_filter(LUser, LServer, Filter) -> F = fun () -> case mnesia:read({privacy, {LUser, LServer}}) of [] -> %% No lists, nothing to unblock ok; [#privacy{default = Default, lists = Lists} = P] -> case lists:keysearch(Default, 1, Lists) of {value, {_, List}} -> NewList = Filter(List), NewLists1 = lists:keydelete(Default, 1, Lists), NewLists = [{Default, NewList} | NewLists1], mnesia:write(P#privacy{lists = NewLists}), {ok, Default, NewList}; false -> %% No default list, nothing to unblock ok end end end, mnesia:transaction(F). process_blocklist_get(LUser, LServer) -> case catch mnesia:dirty_read(privacy, {LUser, LServer}) of {'EXIT', _Reason} -> error; [] -> []; [#privacy{default = Default, lists = Lists}] -> case lists:keysearch(Default, 1, Lists) of {value, {_, List}} -> List; _ -> [] end end. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/src/mod_blocking_mnesia.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API =================================================================== API =================================================================== No lists, nothing to unblock No default list, nothing to unblock =================================================================== ===================================================================
@author < > ( C ) 2016 , Created : 14 Apr 2016 by < > -module(mod_blocking_mnesia). -behaviour(mod_blocking). -export([process_blocklist_block/3, unblock_by_filter/3, process_blocklist_get/2]). -include("jlib.hrl"). -include("mod_privacy.hrl"). process_blocklist_block(LUser, LServer, Filter) -> F = fun () -> case mnesia:wread({privacy, {LUser, LServer}}) of [] -> P = #privacy{us = {LUser, LServer}}, NewDefault = <<"Blocked contacts">>, NewLists1 = [], List = []; [#privacy{default = Default, lists = Lists} = P] -> case lists:keysearch(Default, 1, Lists) of {value, {_, List}} -> NewDefault = Default, NewLists1 = lists:keydelete(Default, 1, Lists); false -> NewDefault = <<"Blocked contacts">>, NewLists1 = Lists, List = [] end end, NewList = Filter(List), NewLists = [{NewDefault, NewList} | NewLists1], mnesia:write(P#privacy{default = NewDefault, lists = NewLists}), {ok, NewDefault, NewList} end, mnesia:transaction(F). unblock_by_filter(LUser, LServer, Filter) -> F = fun () -> case mnesia:read({privacy, {LUser, LServer}}) of [] -> ok; [#privacy{default = Default, lists = Lists} = P] -> case lists:keysearch(Default, 1, Lists) of {value, {_, List}} -> NewList = Filter(List), NewLists1 = lists:keydelete(Default, 1, Lists), NewLists = [{Default, NewList} | NewLists1], mnesia:write(P#privacy{lists = NewLists}), {ok, Default, NewList}; false -> ok end end end, mnesia:transaction(F). process_blocklist_get(LUser, LServer) -> case catch mnesia:dirty_read(privacy, {LUser, LServer}) of {'EXIT', _Reason} -> error; [] -> []; [#privacy{default = Default, lists = Lists}] -> case lists:keysearch(Default, 1, Lists) of {value, {_, List}} -> List; _ -> [] end end. Internal functions
349f606b21a91ccaf68beeff4134c081a4a8e13de19590c0243b05f8d3835a20
andrejbauer/marshall
interval.ml
(* \section{Interval arithmetic (module [Interval])} *) An interval is a pair [ ( l , u ) ] of [ Dyadic ] numbers . There is no restriction that [ l ] should be smaller than [ u ] , i.e. , the library also works with back - to - front intervals . It uses multiplication for back - to - front intervals . Infinity and negative infinity are allowed as endpoints . restriction that [l] should be smaller than [u], i.e., the library also works with back-to-front intervals. It uses Kaucher multiplication for back-to-front intervals. Infinity and negative infinity are allowed as endpoints. *) An interval is represented as a pair of lazy [ Mfpr.t ] values . This is so because often we only need to evaluate one of the endpoints . so because often we only need to evaluate one of the endpoints. *) open Lazy module Make = functor (D : Dyadic.DYADIC) -> struct (* An interval is a record with fields [lower] and [upper]. *) type t = { lower : D.t Lazy.t; upper : D.t Lazy.t } (* \subsection{Basic mainpulation} *) [ make l u ] constructs an interal from two . let make l u = { lower = Lazy.from_val l; upper = Lazy.from_val u } (* [lower i] computes the lower endpoint. *) let lower i = force_val i.lower (* [upper i] computes the upper endpoint. *) let upper i = force_val i.upper (* [flip i] exchanges the lower and upper endpoints. *) let flip i = { lower = i.upper; upper = i.lower } (* Compute the width of the interval *) let width ~prec ~round i = D.sub ~prec ~round (upper i) (lower i) let of_dyadic q = make q q let bottom = make D.negative_infinity D.positive_infinity let top = make D.positive_infinity D.negative_infinity (* \subsection{Testing for infinite endpoints and back-to-front.} *) (* [forward i] returns [true] if [i] is a front-to-back interval *) let forward i = D.leq (lower i) (upper i) (* [backward i] returns [true] if [i] is a back-to-front interval *) let backward i = D.gt (lower i) (upper i) (* [proper i] returns [true] of [i] is a front-to-back interval with finite endpoints. *) let proper i = forward i && D.is_number (lower i) && D.is_number (upper i) (* \subsection{String conversion} *) let to_string i = "[" ^ D.to_string (lower i) ^ ", " ^ D.to_string (upper i) ^ "]" let to_string_number i = let a = lower i in let b = upper i in if D.is_number a && D.is_number b then let c = D.average a b in let r = D.sub ~prec:2 ~round:D.up b a in D.to_string c ^ " +- " ^ D.to_string r else to_string i (* \subsection{Arithmetic} *) Results are computed to precision [ prec ] and rounded according to [ round ] . If [ round ] is [ Dyadic.down ] then the result approximates the true value from below . If [ round ] is [ Dyadic.up ] then the true value is approximated from above . It is perhaps more customary to always approximate the true value from below , but we need the other approximant in [ Eval.upper ] . [round]. If [round] is [Dyadic.down] then the result approximates the true value from below. If [round] is [Dyadic.up] then the true value is approximated from above. It is perhaps more customary to always approximate the true value from below, but we need the other approximant in [Eval.upper]. *) let add ~prec ~round i j = let dnuor = D.anti round in { lower = lazy (D.add ~prec ~round (lower i) (lower j)) ; upper = lazy (D.add ~prec ~round:dnuor (upper i) (upper j)) } let sub ~prec ~round i j = let dnuor = D.anti round in { lower = lazy (D.sub ~prec ~round (lower i) (upper j)) ; upper = lazy (D.sub ~prec ~round:dnuor (upper i) (lower j)) } let neg ~prec ~round i = let dnuor = D.anti round in { lower = lazy (D.neg ~prec ~round (upper i)) ; upper = lazy (D.neg ~prec ~round:dnuor (lower i)) } Kaucher multiplication of intervals is given by the following table . \begin{center } \begin{tabular}{|c|c|c|c|c| } \hline $ [ a , b ] \times [ c , d]$ & $ a , b \leq 0 $ & $ a \leq 0 \leq b$ & $ b \leq 0 \leq a$ & $ 0 \leq a , b$ \\ \hline $ 0 \leq c , d$ & $ [ ad , bc]$ & $ [ ad , bd]$ & $ [ ac , bc]$ & $ [ ac , bd]$ \\ \hline $ d \leq 0 \leq c$ & $ [ bd , bc]$ & $ [ 0,0]$ & $ [ q , p]$ & $ [ ac , ad]$ \\ \hline $ c \leq 0 \leq d$ & $ [ ad , ac]$ & $ [ p , q]$ & $ [ 0,0]$ & $ [ bc , bd]$ \\ \hline $ c , d \leq 0 $ & $ [ bd , ac]$ & $ [ bc , ac]$ & $ [ bd , ad]$ & $ [ bc , \\ \hline \end{tabular } \end{center } Where $ p = \min(ad , bc ) \leq 0 $ and $ q = \max(ac , bd ) \geq 0$. \begin{center} \begin{tabular}{|c|c|c|c|c|} \hline $[a,b] \times [c,d]$ & $a, b \leq 0$ & $a \leq 0 \leq b$ & $b \leq 0 \leq a$ & $0 \leq a,b$ \\ \hline $ 0 \leq c, d$ & $[ad,bc]$ & $[ad,bd]$ & $[ac,bc]$ & $[ac,bd]$ \\ \hline $ d \leq 0 \leq c$ & $[bd,bc]$ & $[0,0]$ & $[q,p]$ & $[ac,ad]$ \\ \hline $ c \leq 0 \leq d$ & $[ad,ac]$ & $[p,q]$ & $[0,0]$ & $[bc,bd]$ \\ \hline $ c, d \leq 0$ & $[bd,ac]$ & $[bc,ac]$ & $[bd,ad]$ & $[bc,ad]$ \\ \hline \end{tabular} \end{center} Where $p = \min(ad,bc) \leq 0$ and $q = \max(ac,bd) \geq 0$. *) let mul ~prec ~round i j = let negative = D.negative in { lower = lazy ( let lmul = D.mul ~prec ~round in let a = lower i in let b = upper i in let c = lower j in let d = upper j in if negative a then if negative b then if negative d then lmul b d else lmul a d else (* positive [b] *) if negative c then if negative d then lmul b c else D.min (lmul a d) (lmul b c) else (* positive [c] *) if negative d then D.zero else lmul a d else (* positive [a] *) if negative b then if negative c then if negative d then lmul b d else D.zero else (* positive [c] *) if negative d then D.max (lmul a c) (lmul b d) else lmul a c else (* positive [b] *) if negative c then lmul b c else lmul a c) ; upper = lazy ( let umul = D.mul ~prec ~round:(D.anti round) in let a = lower i in let b = upper i in let c = lower j in let d = upper j in if negative a then if negative b then if negative c then umul a c else umul b c else (* positive [b] *) if negative c then if negative d then umul a c else D.max (umul a c) (umul b d) else (* positive [c] *) if negative d then D.zero else umul b d else (* positive [a] *) if negative b then if negative c then if negative d then umul a d else D.zero else (* positive [c] *) if negative d then D.min (umul a d) (umul b c) else umul b c else (* positive [b] *) if negative d then umul a d else umul b d) } (* Power by non-negative exponent. *) let pow ~prec ~round i k = let dnuor = D.anti round in if k mod 2 = 1 then { lower = lazy (D.pow ~prec ~round:round (lower i) k) ; upper = lazy (D.pow ~prec ~round:dnuor (upper i) k) } else let a = lower i in let b = upper i in { lower = lazy ( let lpow = D.pow ~prec ~round in if D.negative a then if D.negative b then lpow b k else (* non-negative [b] *) D.zero else (* non-negative [a] *) if D.negative b then D.max (lpow a k) (lpow b k) else (* non-negative [b] *) lpow a k ) ; upper = lazy ( let upow = D.pow ~prec ~round:dnuor in if D.negative a then if D.negative b then upow a k else (* non-negative [b] *) D.max (upow a k) (upow b k) else (* non-negative [a] *) if D.negative b then D.zero else (* non-negative [b] *) upow b k ) } let inv ~prec ~round i = let a = lower i in let b = upper i in { lower = lazy ( let linv = D.inv ~prec ~round in match D.sgn a, D.sgn b with | `negative, `negative -> linv b | `zero, `negative -> linv b | `positive, `negative -> D.positive_infinity | `negative, `zero -> D.negative_infinity | `zero, `zero -> D.negative_infinity | `positive, `zero -> D.positive_infinity | `negative, `positive -> D.negative_infinity | `zero, `positive -> D.negative_infinity | `positive, `positive -> linv b ) ; upper = lazy ( let uinv = D.inv ~prec ~round:(D.anti round) in match D.sgn a, D.sgn b with | `negative, `negative -> uinv a | `zero, `negative -> D.negative_infinity | `positive, `negative -> D.negative_infinity | `negative, `zero -> D.positive_infinity | `zero, `zero -> D.positive_infinity | `positive, `zero -> uinv a | `negative, `positive -> D.positive_infinity | `zero, `positive -> D.positive_infinity | `positive, `positive -> uinv a ) } let div ~prec ~round i j = mul ~prec ~round i (inv ~prec ~round j) let exp ~prec ~round i = let dnuor = D.anti round in { lower = lazy ( D.exp prec round ( lower i ) ) ; upper = lazy ( D.exp prec dnuor ( upper i ) ) } let dnuor = D.anti round in { lower = lazy (D.exp prec round (lower i)) ; upper = lazy (D.exp prec dnuor (upper i)) }*) (* \subsection{Interval splitting} *) (* [midpoint prec i] computes the midpoint of an interval [i]. It guarantees that the point is actually inside the interval (which means that it will use precision higher than [prec] if necessary. It works correctly for infinite and back-to-front intervals. For infinite intervals it goes closer to infinity as [prec] increases. *) let midpoint ~prec k i = let a = lower i in let b = upper i in match D.classify a, D.classify b with | `number, `number -> D.average a b | `negative_infinity, `positive_infinity | `positive_infinity, `negative_infinity -> D.zero | `negative_infinity, `number -> if D.leq b D.negative_one then D.shift ~prec ~round:D.down b k else D.negative_one | `positive_infinity, `number -> if D.geq b D.one then D.shift ~prec ~round:D.up b k else D.one | `number, `positive_infinity -> if D.geq a D.one then D.shift ~prec ~round:D.up a k else D.one | `number, `negative_infinity -> if D.leq a D.negative_one then D.shift ~prec ~round:D.down a k else D.negative_one | _ -> raise (Invalid_argument ("Interval.midpoint: " ^ to_string i)) Split an interval into two smaller ones . let split ~prec k i = let m = lazy (midpoint ~prec k i) in ({ lower = i.lower; upper = m }, { lower = m; upper = i.upper }) [ thirds prec i ] computes points $ m_1 $ and $ m_2 $ which divide [ i ] into three roughly equal parts . If [ i ] is infinite it does a reasonable thing . into three roughly equal parts. If [i] is infinite it does a reasonable thing. *) let thirds ~prec k i = let i1, i2 = split ~prec k i in midpoint ~prec k i1, midpoint ~prec k i2 end;;
null
https://raw.githubusercontent.com/andrejbauer/marshall/1e630b34b7ae880835aca31fd2b3eda562348b2e/src/interval.ml
ocaml
\section{Interval arithmetic (module [Interval])} An interval is a record with fields [lower] and [upper]. \subsection{Basic mainpulation} [lower i] computes the lower endpoint. [upper i] computes the upper endpoint. [flip i] exchanges the lower and upper endpoints. Compute the width of the interval \subsection{Testing for infinite endpoints and back-to-front.} [forward i] returns [true] if [i] is a front-to-back interval [backward i] returns [true] if [i] is a back-to-front interval [proper i] returns [true] of [i] is a front-to-back interval with finite endpoints. \subsection{String conversion} \subsection{Arithmetic} positive [b] positive [c] positive [a] positive [c] positive [b] positive [b] positive [c] positive [a] positive [c] positive [b] Power by non-negative exponent. non-negative [b] non-negative [a] non-negative [b] non-negative [b] non-negative [a] non-negative [b] \subsection{Interval splitting} [midpoint prec i] computes the midpoint of an interval [i]. It guarantees that the point is actually inside the interval (which means that it will use precision higher than [prec] if necessary. It works correctly for infinite and back-to-front intervals. For infinite intervals it goes closer to infinity as [prec] increases.
An interval is a pair [ ( l , u ) ] of [ Dyadic ] numbers . There is no restriction that [ l ] should be smaller than [ u ] , i.e. , the library also works with back - to - front intervals . It uses multiplication for back - to - front intervals . Infinity and negative infinity are allowed as endpoints . restriction that [l] should be smaller than [u], i.e., the library also works with back-to-front intervals. It uses Kaucher multiplication for back-to-front intervals. Infinity and negative infinity are allowed as endpoints. *) An interval is represented as a pair of lazy [ Mfpr.t ] values . This is so because often we only need to evaluate one of the endpoints . so because often we only need to evaluate one of the endpoints. *) open Lazy module Make = functor (D : Dyadic.DYADIC) -> struct type t = { lower : D.t Lazy.t; upper : D.t Lazy.t } [ make l u ] constructs an interal from two . let make l u = { lower = Lazy.from_val l; upper = Lazy.from_val u } let lower i = force_val i.lower let upper i = force_val i.upper let flip i = { lower = i.upper; upper = i.lower } let width ~prec ~round i = D.sub ~prec ~round (upper i) (lower i) let of_dyadic q = make q q let bottom = make D.negative_infinity D.positive_infinity let top = make D.positive_infinity D.negative_infinity let forward i = D.leq (lower i) (upper i) let backward i = D.gt (lower i) (upper i) let proper i = forward i && D.is_number (lower i) && D.is_number (upper i) let to_string i = "[" ^ D.to_string (lower i) ^ ", " ^ D.to_string (upper i) ^ "]" let to_string_number i = let a = lower i in let b = upper i in if D.is_number a && D.is_number b then let c = D.average a b in let r = D.sub ~prec:2 ~round:D.up b a in D.to_string c ^ " +- " ^ D.to_string r else to_string i Results are computed to precision [ prec ] and rounded according to [ round ] . If [ round ] is [ Dyadic.down ] then the result approximates the true value from below . If [ round ] is [ Dyadic.up ] then the true value is approximated from above . It is perhaps more customary to always approximate the true value from below , but we need the other approximant in [ Eval.upper ] . [round]. If [round] is [Dyadic.down] then the result approximates the true value from below. If [round] is [Dyadic.up] then the true value is approximated from above. It is perhaps more customary to always approximate the true value from below, but we need the other approximant in [Eval.upper]. *) let add ~prec ~round i j = let dnuor = D.anti round in { lower = lazy (D.add ~prec ~round (lower i) (lower j)) ; upper = lazy (D.add ~prec ~round:dnuor (upper i) (upper j)) } let sub ~prec ~round i j = let dnuor = D.anti round in { lower = lazy (D.sub ~prec ~round (lower i) (upper j)) ; upper = lazy (D.sub ~prec ~round:dnuor (upper i) (lower j)) } let neg ~prec ~round i = let dnuor = D.anti round in { lower = lazy (D.neg ~prec ~round (upper i)) ; upper = lazy (D.neg ~prec ~round:dnuor (lower i)) } Kaucher multiplication of intervals is given by the following table . \begin{center } \begin{tabular}{|c|c|c|c|c| } \hline $ [ a , b ] \times [ c , d]$ & $ a , b \leq 0 $ & $ a \leq 0 \leq b$ & $ b \leq 0 \leq a$ & $ 0 \leq a , b$ \\ \hline $ 0 \leq c , d$ & $ [ ad , bc]$ & $ [ ad , bd]$ & $ [ ac , bc]$ & $ [ ac , bd]$ \\ \hline $ d \leq 0 \leq c$ & $ [ bd , bc]$ & $ [ 0,0]$ & $ [ q , p]$ & $ [ ac , ad]$ \\ \hline $ c \leq 0 \leq d$ & $ [ ad , ac]$ & $ [ p , q]$ & $ [ 0,0]$ & $ [ bc , bd]$ \\ \hline $ c , d \leq 0 $ & $ [ bd , ac]$ & $ [ bc , ac]$ & $ [ bd , ad]$ & $ [ bc , \\ \hline \end{tabular } \end{center } Where $ p = \min(ad , bc ) \leq 0 $ and $ q = \max(ac , bd ) \geq 0$. \begin{center} \begin{tabular}{|c|c|c|c|c|} \hline $[a,b] \times [c,d]$ & $a, b \leq 0$ & $a \leq 0 \leq b$ & $b \leq 0 \leq a$ & $0 \leq a,b$ \\ \hline $ 0 \leq c, d$ & $[ad,bc]$ & $[ad,bd]$ & $[ac,bc]$ & $[ac,bd]$ \\ \hline $ d \leq 0 \leq c$ & $[bd,bc]$ & $[0,0]$ & $[q,p]$ & $[ac,ad]$ \\ \hline $ c \leq 0 \leq d$ & $[ad,ac]$ & $[p,q]$ & $[0,0]$ & $[bc,bd]$ \\ \hline $ c, d \leq 0$ & $[bd,ac]$ & $[bc,ac]$ & $[bd,ad]$ & $[bc,ad]$ \\ \hline \end{tabular} \end{center} Where $p = \min(ad,bc) \leq 0$ and $q = \max(ac,bd) \geq 0$. *) let mul ~prec ~round i j = let negative = D.negative in { lower = lazy ( let lmul = D.mul ~prec ~round in let a = lower i in let b = upper i in let c = lower j in let d = upper j in if negative a then if negative b then if negative d then lmul b d else lmul a d if negative c then if negative d then lmul b c else D.min (lmul a d) (lmul b c) if negative d then D.zero else lmul a d if negative b then if negative c then if negative d then lmul b d else D.zero if negative d then D.max (lmul a c) (lmul b d) else lmul a c if negative c then lmul b c else lmul a c) ; upper = lazy ( let umul = D.mul ~prec ~round:(D.anti round) in let a = lower i in let b = upper i in let c = lower j in let d = upper j in if negative a then if negative b then if negative c then umul a c else umul b c if negative c then if negative d then umul a c else D.max (umul a c) (umul b d) if negative d then D.zero else umul b d if negative b then if negative c then if negative d then umul a d else D.zero if negative d then D.min (umul a d) (umul b c) else umul b c if negative d then umul a d else umul b d) } let pow ~prec ~round i k = let dnuor = D.anti round in if k mod 2 = 1 then { lower = lazy (D.pow ~prec ~round:round (lower i) k) ; upper = lazy (D.pow ~prec ~round:dnuor (upper i) k) } else let a = lower i in let b = upper i in { lower = lazy ( let lpow = D.pow ~prec ~round in if D.negative a then if D.negative b then lpow b k D.zero if D.negative b then D.max (lpow a k) (lpow b k) lpow a k ) ; upper = lazy ( let upow = D.pow ~prec ~round:dnuor in if D.negative a then if D.negative b then upow a k D.max (upow a k) (upow b k) if D.negative b then D.zero upow b k ) } let inv ~prec ~round i = let a = lower i in let b = upper i in { lower = lazy ( let linv = D.inv ~prec ~round in match D.sgn a, D.sgn b with | `negative, `negative -> linv b | `zero, `negative -> linv b | `positive, `negative -> D.positive_infinity | `negative, `zero -> D.negative_infinity | `zero, `zero -> D.negative_infinity | `positive, `zero -> D.positive_infinity | `negative, `positive -> D.negative_infinity | `zero, `positive -> D.negative_infinity | `positive, `positive -> linv b ) ; upper = lazy ( let uinv = D.inv ~prec ~round:(D.anti round) in match D.sgn a, D.sgn b with | `negative, `negative -> uinv a | `zero, `negative -> D.negative_infinity | `positive, `negative -> D.negative_infinity | `negative, `zero -> D.positive_infinity | `zero, `zero -> D.positive_infinity | `positive, `zero -> uinv a | `negative, `positive -> D.positive_infinity | `zero, `positive -> D.positive_infinity | `positive, `positive -> uinv a ) } let div ~prec ~round i j = mul ~prec ~round i (inv ~prec ~round j) let exp ~prec ~round i = let dnuor = D.anti round in { lower = lazy ( D.exp prec round ( lower i ) ) ; upper = lazy ( D.exp prec dnuor ( upper i ) ) } let dnuor = D.anti round in { lower = lazy (D.exp prec round (lower i)) ; upper = lazy (D.exp prec dnuor (upper i)) }*) let midpoint ~prec k i = let a = lower i in let b = upper i in match D.classify a, D.classify b with | `number, `number -> D.average a b | `negative_infinity, `positive_infinity | `positive_infinity, `negative_infinity -> D.zero | `negative_infinity, `number -> if D.leq b D.negative_one then D.shift ~prec ~round:D.down b k else D.negative_one | `positive_infinity, `number -> if D.geq b D.one then D.shift ~prec ~round:D.up b k else D.one | `number, `positive_infinity -> if D.geq a D.one then D.shift ~prec ~round:D.up a k else D.one | `number, `negative_infinity -> if D.leq a D.negative_one then D.shift ~prec ~round:D.down a k else D.negative_one | _ -> raise (Invalid_argument ("Interval.midpoint: " ^ to_string i)) Split an interval into two smaller ones . let split ~prec k i = let m = lazy (midpoint ~prec k i) in ({ lower = i.lower; upper = m }, { lower = m; upper = i.upper }) [ thirds prec i ] computes points $ m_1 $ and $ m_2 $ which divide [ i ] into three roughly equal parts . If [ i ] is infinite it does a reasonable thing . into three roughly equal parts. If [i] is infinite it does a reasonable thing. *) let thirds ~prec k i = let i1, i2 = split ~prec k i in midpoint ~prec k i1, midpoint ~prec k i2 end;;
135f13bda89e53cf3622d437abb8950c7698178f047c79dd26f21b88995e4224
cxphoe/SICP-solutions
3.3.rkt
(define (make-account balance password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount))) (define (dispatch pw m) (if (eq? pw password) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m))) (lambda (x) "Incorrect password"))) dispatch) (define acc (make-account 100 'secret-password)) ((acc 'secret-password 'withdraw) 40) ((acc 'some-other-password 'deposit) 50)
null
https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%203-Modeling%20with%20Mutable%20Data/1.Assignment%20and%20Local%20state/3.3.rkt
racket
(define (make-account balance password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount))) (define (dispatch pw m) (if (eq? pw password) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m))) (lambda (x) "Incorrect password"))) dispatch) (define acc (make-account 100 'secret-password)) ((acc 'secret-password 'withdraw) 40) ((acc 'some-other-password 'deposit) 50)
eef55cb3137549af6b5c9f010c6cd33842051261118aff94c243dea9e4a8e1d0
naoto-ogawa/h-xproto-mysql
Example03.hs
{-# LANGUAGE ScopedTypeVariables, TemplateHaskell #-} # LANGUAGE TypeInType , TypeFamilies , KindSignatures , DataKinds , TypeOperators , GADTs , TypeSynonymInstances , FlexibleInstances # module Example.Example03 where import Language.Haskell.TH import Language.Haskell.TH.Syntax import Control.Exception.Safe (Exception, MonadThrow, SomeException, throwM, bracket, catch) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Int as I import Data.Kind import qualified Data.Sequence as Seq import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Word as W import qualified Com.Mysql.Cj.Mysqlx.Protobuf.ColumnMetaData as PCMD -- my library import DataBase.MySQLX.Exception import DataBase.MySQLX.Model as XM import DataBase.MySQLX.NodeSession import DataBase.MySQLX.Statement import DataBase.MySQLX.TH import DataBase.MySQLX.Util import DataBase.MySQLX.Util import Example.Example03_data -- Select interface from a row to a record object by . -- example03_1 :: IO () example03_1 = do putStrLn "start example03_1" node <- openNodeSession $ defaultNodeSesssionInfo {database = "world_x", user = "root", password="root"} debug $ "node=" ++ (show node) select1 node closeNodeSession node putStrLn "end example03_1" select1 :: NodeSession -> IO () select1 node = do print "start select 1 ---------- " ret@(x:xs) <- executeRawSql "select * from city limit 2" node print ( $(retrieveRow ''MyRecord) x ) print "end select 1 ---------- "
null
https://raw.githubusercontent.com/naoto-ogawa/h-xproto-mysql/1eacd6486c99b849016bf088788cb8d8b166f964/src/Example/Example03.hs
haskell
# LANGUAGE ScopedTypeVariables, TemplateHaskell # my library
# LANGUAGE TypeInType , TypeFamilies , KindSignatures , DataKinds , TypeOperators , GADTs , TypeSynonymInstances , FlexibleInstances # module Example.Example03 where import Language.Haskell.TH import Language.Haskell.TH.Syntax import Control.Exception.Safe (Exception, MonadThrow, SomeException, throwM, bracket, catch) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Int as I import Data.Kind import qualified Data.Sequence as Seq import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Word as W import qualified Com.Mysql.Cj.Mysqlx.Protobuf.ColumnMetaData as PCMD import DataBase.MySQLX.Exception import DataBase.MySQLX.Model as XM import DataBase.MySQLX.NodeSession import DataBase.MySQLX.Statement import DataBase.MySQLX.TH import DataBase.MySQLX.Util import DataBase.MySQLX.Util import Example.Example03_data Select interface from a row to a record object by . example03_1 :: IO () example03_1 = do putStrLn "start example03_1" node <- openNodeSession $ defaultNodeSesssionInfo {database = "world_x", user = "root", password="root"} debug $ "node=" ++ (show node) select1 node closeNodeSession node putStrLn "end example03_1" select1 :: NodeSession -> IO () select1 node = do print "start select 1 ---------- " ret@(x:xs) <- executeRawSql "select * from city limit 2" node print ( $(retrieveRow ''MyRecord) x ) print "end select 1 ---------- "
67fa8542921d8140512974676303f36aa114b6046dd89b0617bbe44d0ca06862
Simre1/hero
Component.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DefaultSignatures # # LANGUAGE FunctionalDependencies # # LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # module Hero.Component.Component where import Data.Kind import Hero.Entity (Entity, MaxEntities) import Type.Reflection (Typeable) | ' ' is unique to a component within the context of a World . Do not use the same ' ' with different worlds . newtype ComponentId = ComponentId {unwrapComponentId :: Int} deriving (Show, Eq, Ord) | A component is a datatype usually containing raw data . -- For example `data Position = Position Float Float` class (ComponentStore component (Store component), Typeable component) => Component component where -- | The datastructure used to store the component (for example BoxedSparseSet) type Store component :: Type -> Type -- | Store which do not require systems to run can be automatically created (the sparse sets can be set up automatically!). Then, you do not have to -- set them up yourself and the defualt 'createStoreAutomatically' is enough. createStoreAutomatically :: Maybe (MaxEntities -> IO (Store' component)) default createStoreAutomatically :: AutomaticStoreCreation component (Store component) => Maybe (MaxEntities -> IO (Store' component)) createStoreAutomatically = createStoreAutomatically' @component @(Store component) type Store' component = Store component component -- | Contains methods that every store must have. class ComponentStore component store where componentEntityDelete :: store component -> Entity -> IO () | Stores which do not any systems to run should implement AutomaticStoreCreation so -- they can be set up automatically. class AutomaticStoreCreation component store where createStoreAutomatically' :: Maybe (MaxEntities -> IO (Store' component)) instance {-# OVERLAPPABLE #-} AutomaticStoreCreation component store where createStoreAutomatically' = Nothing
null
https://raw.githubusercontent.com/Simre1/hero/61e18ad87e93b349c0bc453c405bfa76feda62bc/src/Hero/Component/Component.hs
haskell
For example `data Position = Position Float Float` | The datastructure used to store the component (for example BoxedSparseSet) | Store which do not require systems to run can be automatically created (the sparse sets can be set up automatically!). Then, you do not have to set them up yourself and the defualt 'createStoreAutomatically' is enough. | Contains methods that every store must have. they can be set up automatically. # OVERLAPPABLE #
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DefaultSignatures # # LANGUAGE FunctionalDependencies # # LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # module Hero.Component.Component where import Data.Kind import Hero.Entity (Entity, MaxEntities) import Type.Reflection (Typeable) | ' ' is unique to a component within the context of a World . Do not use the same ' ' with different worlds . newtype ComponentId = ComponentId {unwrapComponentId :: Int} deriving (Show, Eq, Ord) | A component is a datatype usually containing raw data . class (ComponentStore component (Store component), Typeable component) => Component component where type Store component :: Type -> Type createStoreAutomatically :: Maybe (MaxEntities -> IO (Store' component)) default createStoreAutomatically :: AutomaticStoreCreation component (Store component) => Maybe (MaxEntities -> IO (Store' component)) createStoreAutomatically = createStoreAutomatically' @component @(Store component) type Store' component = Store component component class ComponentStore component store where componentEntityDelete :: store component -> Entity -> IO () | Stores which do not any systems to run should implement AutomaticStoreCreation so class AutomaticStoreCreation component store where createStoreAutomatically' :: Maybe (MaxEntities -> IO (Store' component)) createStoreAutomatically' = Nothing
9fc63e45dbdd6390a3cc9cbc2555c447101e8e01fb0b804f5152adbef102858d
kawasima/darzana
template.clj
(ns darzana.template (:require [integrant.core :as ig])) (defprotocol TemplateEngine (render-html [this ctx template-name])) (defmethod ig/init-key :darzana/template [_ spec] )
null
https://raw.githubusercontent.com/kawasima/darzana/4b37c8556f74219b707d23cb2d6dce70509a0c1b/src/darzana/template.clj
clojure
(ns darzana.template (:require [integrant.core :as ig])) (defprotocol TemplateEngine (render-html [this ctx template-name])) (defmethod ig/init-key :darzana/template [_ spec] )
a0996bb33d26c2285510980478575170d3e3eb54c6119427236834872f5210ac
ds-wizard/engine-backend
LocaleBundleService.hs
module Registry.Service.Locale.Bundle.LocaleBundleService where import Control.Monad.Except (throwError) import qualified Data.ByteString.Lazy.Char8 as BSL import qualified Data.UUID as U import Registry.Api.Resource.Locale.LocaleDTO import Registry.Model.Context.AppContext import Registry.S3.Locale.LocaleS3 import Registry.Service.Audit.AuditService import Registry.Service.Locale.Bundle.LocaleBundleAcl import Registry.Service.Locale.LocaleMapper import Shared.Database.DAO.Locale.LocaleDAO import Shared.Model.Locale.Locale import Shared.Service.Locale.Bundle.LocaleBundleMapper exportBundle :: String -> AppContextM BSL.ByteString exportBundle lclId = do _ <- auditGetLocaleBundle lclId locale <- findLocaleById lclId content <- retrieveLocale locale.lId return $ toLocaleArchive locale content importBundle :: BSL.ByteString -> AppContextM LocaleDTO importBundle contentS = do checkWritePermission case fromLocaleArchive contentS of Right (bundle, content) -> do let locale = fromLocaleBundle bundle U.nil putLocale locale.lId content insertLocale locale return . toDTO [] $ locale Left error -> throwError error
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/090f4f3460e8df128e88e2c3ce266b165e4a0a50/engine-registry/src/Registry/Service/Locale/Bundle/LocaleBundleService.hs
haskell
module Registry.Service.Locale.Bundle.LocaleBundleService where import Control.Monad.Except (throwError) import qualified Data.ByteString.Lazy.Char8 as BSL import qualified Data.UUID as U import Registry.Api.Resource.Locale.LocaleDTO import Registry.Model.Context.AppContext import Registry.S3.Locale.LocaleS3 import Registry.Service.Audit.AuditService import Registry.Service.Locale.Bundle.LocaleBundleAcl import Registry.Service.Locale.LocaleMapper import Shared.Database.DAO.Locale.LocaleDAO import Shared.Model.Locale.Locale import Shared.Service.Locale.Bundle.LocaleBundleMapper exportBundle :: String -> AppContextM BSL.ByteString exportBundle lclId = do _ <- auditGetLocaleBundle lclId locale <- findLocaleById lclId content <- retrieveLocale locale.lId return $ toLocaleArchive locale content importBundle :: BSL.ByteString -> AppContextM LocaleDTO importBundle contentS = do checkWritePermission case fromLocaleArchive contentS of Right (bundle, content) -> do let locale = fromLocaleBundle bundle U.nil putLocale locale.lId content insertLocale locale return . toDTO [] $ locale Left error -> throwError error
7df978866bad627c9800c8add5918a68de12d6e20e44b673f73cfe0f78d14e44
xvw/muhokama
db_migrate.ml
open Lib_common module Migration_context = Lib_migration.Context module Db = Lib_db let reset migrations_path = let promise = let open Lwt_util in let*? env = Env.init () in let*? pool = Db.connect env in Lib_db.use pool @@ Lib_migration.Migrate.reset migrations_path in Termination.handle promise ;; let migrate migrations_path target = let promise = let open Lwt_util in let*? env = Env.init () in let*? pool = Db.connect env in Lib_db.use pool @@ Lib_migration.Migrate.run migrations_path target in Termination.handle promise ;; let action_migrate = let open Cmdliner in let doc = "Migrations are used to modify your database schema over time" in let exits = Termination.exits in let info = Cmd.info "db.migrate" ~doc ~exits in Cmd.v info Term.(const migrate $ Param.migrations_path_term $ Param.migrate_to_term) ;; let action_reset = let open Cmdliner in let doc = "Reset the migration state (same of [migrate --to 0])" in let exits = Termination.exits in let info = Cmd.info "db.migrate.reset" ~doc ~exits in Cmd.v info Term.(const reset $ Param.migrations_path_term) ;;
null
https://raw.githubusercontent.com/xvw/muhokama/d628d05e2fc5af3fbf86d2177458336b647ece08/bin/db_migrate.ml
ocaml
open Lib_common module Migration_context = Lib_migration.Context module Db = Lib_db let reset migrations_path = let promise = let open Lwt_util in let*? env = Env.init () in let*? pool = Db.connect env in Lib_db.use pool @@ Lib_migration.Migrate.reset migrations_path in Termination.handle promise ;; let migrate migrations_path target = let promise = let open Lwt_util in let*? env = Env.init () in let*? pool = Db.connect env in Lib_db.use pool @@ Lib_migration.Migrate.run migrations_path target in Termination.handle promise ;; let action_migrate = let open Cmdliner in let doc = "Migrations are used to modify your database schema over time" in let exits = Termination.exits in let info = Cmd.info "db.migrate" ~doc ~exits in Cmd.v info Term.(const migrate $ Param.migrations_path_term $ Param.migrate_to_term) ;; let action_reset = let open Cmdliner in let doc = "Reset the migration state (same of [migrate --to 0])" in let exits = Termination.exits in let info = Cmd.info "db.migrate.reset" ~doc ~exits in Cmd.v info Term.(const reset $ Param.migrations_path_term) ;;
7bc1c79db0b496938829495a4c4b81aef90b3af129c7a3420f395a0fd4d4ce0e
phoe/damn-fast-priority-queue
src.lisp
;;;; damn-fast-priority-queue.lisp (defpackage #:damn-fast-priority-queue (:use #:cl) (:shadow #:map) (:local-nicknames (#:a #:alexandria)) (:export #:queue #:make-queue #:copy-queue #:enqueue #:dequeue #:peek #:size #:trim #:map #:do-queue #:queue-size-limit-reached #:queue-size-limit-reached-queue #:queue-size-limit-reached-object)) (in-package #:damn-fast-priority-queue) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Read-time variables (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *optimize-qualities* #+real-damn-fast-priority-queue ;; Good luck. `(optimize (speed 3) (debug 0) (safety 0) (space 0) (compilation-speed 0)) #-real-damn-fast-priority-queue `(optimize (speed 3)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Type definitions (deftype data-type () 't) (deftype data-vector-type () '(simple-array data-type (*))) (deftype prio-type () '(unsigned-byte 32)) (deftype prio-vector-type () '(simple-array prio-type (*))) (deftype extension-factor-type () '(integer 2 256)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Structure definition (declaim (inline %make %data-vector %prio-vector %size %extension-factor)) (defstruct (queue (:conc-name #:%) (:constructor %make) (:predicate nil) (:copier nil)) (data-vector (make-array 256 :element-type 'data-type) :type data-vector-type) (prio-vector (make-array 256 :element-type 'prio-type) :type prio-vector-type) (size 0 :type a:array-length) (extension-factor 2 :type extension-factor-type) (extend-queue-p t :type boolean)) (declaim (inline make-queue copy-queue)) (declaim (ftype (function (&optional a:array-index extension-factor-type boolean) (values queue &optional)) make-queue)) (defun make-queue (&optional (initial-storage-size 256) (extension-factor 2) (extend-queue-p t)) (declare (type extension-factor-type extension-factor)) (declare #.*optimize-qualities*) (%make :extension-factor extension-factor :data-vector (make-array initial-storage-size :element-type 'data-type) :prio-vector (make-array initial-storage-size :element-type 'prio-type) :extend-queue-p extend-queue-p)) (defmethod print-object ((object queue) stream) (print-unreadable-object (object stream :type t :identity t) (format stream "(~D)" (%size object)))) (declaim (ftype (function (queue) (values queue &optional)) copy-queue)) (defun copy-queue (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (%make :extension-factor (%extension-factor queue) :size (%size queue) :extend-queue-p (%extend-queue-p queue) :data-vector (copy-seq (%data-vector queue)) :prio-vector (copy-seq (%prio-vector queue)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Enqueueing (declaim (inline heapify-upwards enqueue)) (declaim (ftype (function (data-vector-type prio-vector-type a:array-length) (values null &optional)) heapify-upwards)) (defun heapify-upwards (data-vector prio-vector index) (declare (type data-vector-type data-vector)) (declare (type prio-vector-type prio-vector)) (declare (type a:array-length index)) (declare #.*optimize-qualities*) (do ((child-index index parent-index) (parent-index (ash (1- index) -1) (ash (1- parent-index) -1))) ((= child-index 0)) (let ((child-priority (aref prio-vector child-index)) (parent-priority (aref prio-vector parent-index))) (cond ((< child-priority parent-priority) (rotatef (aref prio-vector parent-index) (aref prio-vector child-index)) (rotatef (aref data-vector parent-index) (aref data-vector child-index))) (t (return)))))) (declaim (ftype (function (queue t prio-type) (values null &optional)) enqueue)) (defun enqueue (queue object priority) (declare (type queue queue)) (declare (type prio-type priority)) (declare #.*optimize-qualities*) (symbol-macrolet ((data-vector (%data-vector queue)) (prio-vector (%prio-vector queue))) (let ((size (%size queue)) (extension-factor (%extension-factor queue)) (length (array-total-size data-vector))) (when (>= size length) (unless (%extend-queue-p queue) (error 'queue-size-limit-reached :queue queue :element object)) (let ((new-length (max 1 (mod (* length extension-factor) (ash 1 64))))) (declare (type a:array-length new-length)) (when (<= new-length length) (error "Integer overflow while resizing array: new-length ~D is ~ smaller than old length ~D" new-length length)) (setf data-vector (adjust-array data-vector new-length) prio-vector (adjust-array prio-vector new-length)))) (setf (aref data-vector size) object (aref prio-vector size) priority) (heapify-upwards data-vector prio-vector (%size queue)) (incf (%size queue)) nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Dequeueing (declaim (inline heapify-downwards dequeue)) (declaim (ftype (function (data-vector-type prio-vector-type a:array-index) (values null &optional)) heapify-downwards)) (defun heapify-downwards (data-vector prio-vector size) (declare (type data-vector-type data-vector)) (declare (type prio-vector-type prio-vector)) (declare #.*optimize-qualities*) (let ((parent-index 0)) (loop (let* ((left-index (+ (* parent-index 2) 1)) (left-index-validp (< left-index size)) (right-index (+ (* parent-index 2) 2)) (right-index-validp (< right-index size))) (flet ((swap-left () (rotatef (aref prio-vector parent-index) (aref prio-vector left-index)) (rotatef (aref data-vector parent-index) (aref data-vector left-index)) (setf parent-index left-index)) (swap-right () (rotatef (aref prio-vector parent-index) (aref prio-vector right-index)) (rotatef (aref data-vector parent-index) (aref data-vector right-index)) (setf parent-index right-index))) (declare (inline swap-left swap-right)) (when (and (not left-index-validp) (not right-index-validp)) (return)) (when (and left-index-validp (< (aref prio-vector parent-index) (aref prio-vector left-index)) (or (not right-index-validp) (< (aref prio-vector parent-index) (aref prio-vector right-index)))) (return)) (if (and right-index-validp (<= (aref prio-vector right-index) (aref prio-vector left-index))) (swap-right) (swap-left))))))) (declaim (ftype (function (queue) (values t boolean &optional)) dequeue)) (defun dequeue (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (if (= 0 (%size queue)) (values nil nil) (let ((data-vector (%data-vector queue)) (prio-vector (%prio-vector queue))) (multiple-value-prog1 (values (aref data-vector 0) t) (decf (%size queue)) (let ((old-data (aref data-vector (%size queue))) (old-prio (aref prio-vector (%size queue)))) (setf (aref data-vector 0) old-data (aref prio-vector 0) old-prio)) (heapify-downwards data-vector prio-vector (%size queue)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Introspection and maintenance (declaim (inline peek size trim map)) (declaim (ftype (function (queue) (values t boolean &optional)) peek)) (defun peek (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (if (= 0 (%size queue)) (values nil nil) (values (aref (%data-vector queue) 0) t))) (declaim (ftype (function (queue) (values a:array-length &optional)) size)) (defun size (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (%size queue)) (declaim (ftype (function (queue) (values null &optional)) trim)) (defun trim (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (let ((size (%size queue))) (setf (%data-vector queue) (adjust-array (%data-vector queue) size) (%prio-vector queue) (adjust-array (%prio-vector queue) size)) nil)) (declaim (ftype (function (queue (function (t) t)) (values null &optional)) map)) (defun map (queue function) (dotimes (i (%size queue)) (funcall function (aref (%data-vector queue) i)))) (defmacro do-queue ((object queue &optional result) &body body) (multiple-value-bind (forms declarations) (a:parse-body body) (a:with-gensyms (i) (a:once-only (queue) `(dotimes (,i (%size ,queue) ,result) (let ((,object (aref (%data-vector ,queue) ,i))) ,@declarations (tagbody ,@forms))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Conditions (defun report-queue-size-limit-reached (condition stream) (let ((queue (queue-size-limit-reached-queue condition)) (element (queue-size-limit-reached-object condition))) (format stream "Size limit (~D) reached for non-extensible ~ queue ~S while trying to enqueue element ~S onto it." (length (%data-vector queue)) queue element))) (define-condition queue-size-limit-reached (error) ((%queue :reader queue-size-limit-reached-queue :initarg :queue) (%object :reader queue-size-limit-reached-object :initarg :element)) (:default-initargs :queue (a:required-argument :queue) :object (a:required-argument :object)) (:report report-queue-size-limit-reached))
null
https://raw.githubusercontent.com/phoe/damn-fast-priority-queue/9b436de2c1dd296180c10e57e96227e5b4193ff1/damn-fast-priority-queue/src.lisp
lisp
damn-fast-priority-queue.lisp Read-time variables Good luck. Type definitions Structure definition Enqueueing Introspection and maintenance Conditions
(defpackage #:damn-fast-priority-queue (:use #:cl) (:shadow #:map) (:local-nicknames (#:a #:alexandria)) (:export #:queue #:make-queue #:copy-queue #:enqueue #:dequeue #:peek #:size #:trim #:map #:do-queue #:queue-size-limit-reached #:queue-size-limit-reached-queue #:queue-size-limit-reached-object)) (in-package #:damn-fast-priority-queue) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *optimize-qualities* #+real-damn-fast-priority-queue `(optimize (speed 3) (debug 0) (safety 0) (space 0) (compilation-speed 0)) #-real-damn-fast-priority-queue `(optimize (speed 3)))) (deftype data-type () 't) (deftype data-vector-type () '(simple-array data-type (*))) (deftype prio-type () '(unsigned-byte 32)) (deftype prio-vector-type () '(simple-array prio-type (*))) (deftype extension-factor-type () '(integer 2 256)) (declaim (inline %make %data-vector %prio-vector %size %extension-factor)) (defstruct (queue (:conc-name #:%) (:constructor %make) (:predicate nil) (:copier nil)) (data-vector (make-array 256 :element-type 'data-type) :type data-vector-type) (prio-vector (make-array 256 :element-type 'prio-type) :type prio-vector-type) (size 0 :type a:array-length) (extension-factor 2 :type extension-factor-type) (extend-queue-p t :type boolean)) (declaim (inline make-queue copy-queue)) (declaim (ftype (function (&optional a:array-index extension-factor-type boolean) (values queue &optional)) make-queue)) (defun make-queue (&optional (initial-storage-size 256) (extension-factor 2) (extend-queue-p t)) (declare (type extension-factor-type extension-factor)) (declare #.*optimize-qualities*) (%make :extension-factor extension-factor :data-vector (make-array initial-storage-size :element-type 'data-type) :prio-vector (make-array initial-storage-size :element-type 'prio-type) :extend-queue-p extend-queue-p)) (defmethod print-object ((object queue) stream) (print-unreadable-object (object stream :type t :identity t) (format stream "(~D)" (%size object)))) (declaim (ftype (function (queue) (values queue &optional)) copy-queue)) (defun copy-queue (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (%make :extension-factor (%extension-factor queue) :size (%size queue) :extend-queue-p (%extend-queue-p queue) :data-vector (copy-seq (%data-vector queue)) :prio-vector (copy-seq (%prio-vector queue)))) (declaim (inline heapify-upwards enqueue)) (declaim (ftype (function (data-vector-type prio-vector-type a:array-length) (values null &optional)) heapify-upwards)) (defun heapify-upwards (data-vector prio-vector index) (declare (type data-vector-type data-vector)) (declare (type prio-vector-type prio-vector)) (declare (type a:array-length index)) (declare #.*optimize-qualities*) (do ((child-index index parent-index) (parent-index (ash (1- index) -1) (ash (1- parent-index) -1))) ((= child-index 0)) (let ((child-priority (aref prio-vector child-index)) (parent-priority (aref prio-vector parent-index))) (cond ((< child-priority parent-priority) (rotatef (aref prio-vector parent-index) (aref prio-vector child-index)) (rotatef (aref data-vector parent-index) (aref data-vector child-index))) (t (return)))))) (declaim (ftype (function (queue t prio-type) (values null &optional)) enqueue)) (defun enqueue (queue object priority) (declare (type queue queue)) (declare (type prio-type priority)) (declare #.*optimize-qualities*) (symbol-macrolet ((data-vector (%data-vector queue)) (prio-vector (%prio-vector queue))) (let ((size (%size queue)) (extension-factor (%extension-factor queue)) (length (array-total-size data-vector))) (when (>= size length) (unless (%extend-queue-p queue) (error 'queue-size-limit-reached :queue queue :element object)) (let ((new-length (max 1 (mod (* length extension-factor) (ash 1 64))))) (declare (type a:array-length new-length)) (when (<= new-length length) (error "Integer overflow while resizing array: new-length ~D is ~ smaller than old length ~D" new-length length)) (setf data-vector (adjust-array data-vector new-length) prio-vector (adjust-array prio-vector new-length)))) (setf (aref data-vector size) object (aref prio-vector size) priority) (heapify-upwards data-vector prio-vector (%size queue)) (incf (%size queue)) nil))) Dequeueing (declaim (inline heapify-downwards dequeue)) (declaim (ftype (function (data-vector-type prio-vector-type a:array-index) (values null &optional)) heapify-downwards)) (defun heapify-downwards (data-vector prio-vector size) (declare (type data-vector-type data-vector)) (declare (type prio-vector-type prio-vector)) (declare #.*optimize-qualities*) (let ((parent-index 0)) (loop (let* ((left-index (+ (* parent-index 2) 1)) (left-index-validp (< left-index size)) (right-index (+ (* parent-index 2) 2)) (right-index-validp (< right-index size))) (flet ((swap-left () (rotatef (aref prio-vector parent-index) (aref prio-vector left-index)) (rotatef (aref data-vector parent-index) (aref data-vector left-index)) (setf parent-index left-index)) (swap-right () (rotatef (aref prio-vector parent-index) (aref prio-vector right-index)) (rotatef (aref data-vector parent-index) (aref data-vector right-index)) (setf parent-index right-index))) (declare (inline swap-left swap-right)) (when (and (not left-index-validp) (not right-index-validp)) (return)) (when (and left-index-validp (< (aref prio-vector parent-index) (aref prio-vector left-index)) (or (not right-index-validp) (< (aref prio-vector parent-index) (aref prio-vector right-index)))) (return)) (if (and right-index-validp (<= (aref prio-vector right-index) (aref prio-vector left-index))) (swap-right) (swap-left))))))) (declaim (ftype (function (queue) (values t boolean &optional)) dequeue)) (defun dequeue (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (if (= 0 (%size queue)) (values nil nil) (let ((data-vector (%data-vector queue)) (prio-vector (%prio-vector queue))) (multiple-value-prog1 (values (aref data-vector 0) t) (decf (%size queue)) (let ((old-data (aref data-vector (%size queue))) (old-prio (aref prio-vector (%size queue)))) (setf (aref data-vector 0) old-data (aref prio-vector 0) old-prio)) (heapify-downwards data-vector prio-vector (%size queue)))))) (declaim (inline peek size trim map)) (declaim (ftype (function (queue) (values t boolean &optional)) peek)) (defun peek (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (if (= 0 (%size queue)) (values nil nil) (values (aref (%data-vector queue) 0) t))) (declaim (ftype (function (queue) (values a:array-length &optional)) size)) (defun size (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (%size queue)) (declaim (ftype (function (queue) (values null &optional)) trim)) (defun trim (queue) (declare (type queue queue)) (declare #.*optimize-qualities*) (let ((size (%size queue))) (setf (%data-vector queue) (adjust-array (%data-vector queue) size) (%prio-vector queue) (adjust-array (%prio-vector queue) size)) nil)) (declaim (ftype (function (queue (function (t) t)) (values null &optional)) map)) (defun map (queue function) (dotimes (i (%size queue)) (funcall function (aref (%data-vector queue) i)))) (defmacro do-queue ((object queue &optional result) &body body) (multiple-value-bind (forms declarations) (a:parse-body body) (a:with-gensyms (i) (a:once-only (queue) `(dotimes (,i (%size ,queue) ,result) (let ((,object (aref (%data-vector ,queue) ,i))) ,@declarations (tagbody ,@forms))))))) (defun report-queue-size-limit-reached (condition stream) (let ((queue (queue-size-limit-reached-queue condition)) (element (queue-size-limit-reached-object condition))) (format stream "Size limit (~D) reached for non-extensible ~ queue ~S while trying to enqueue element ~S onto it." (length (%data-vector queue)) queue element))) (define-condition queue-size-limit-reached (error) ((%queue :reader queue-size-limit-reached-queue :initarg :queue) (%object :reader queue-size-limit-reached-object :initarg :element)) (:default-initargs :queue (a:required-argument :queue) :object (a:required-argument :object)) (:report report-queue-size-limit-reached))
ed704c8723640440b774c9334cc49314cd1ff3849bac8bfbbd4eb7e47ca28e4d
haskell/haskell-language-server
AutoTypeLevel.expected.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE GADTs # # LANGUAGE KindSignatures # {-# LANGUAGE TypeOperators #-} import Data.Kind data Nat = Z | S Nat data HList (ls :: [Type]) where HNil :: HList '[] HCons :: t -> HList ts -> HList (t ': ts) data ElemAt (n :: Nat) t (ts :: [Type]) where AtZ :: ElemAt 'Z t (t ': ts) AtS :: ElemAt k t ts -> ElemAt ('S k) t (u ': ts) lookMeUp :: ElemAt i ty tys -> HList tys -> ty lookMeUp AtZ (HCons t _) = t lookMeUp (AtS ea') (HCons _ hl') = lookMeUp ea' hl'
null
https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/AutoTypeLevel.expected.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE TypeOperators #
# LANGUAGE GADTs # # LANGUAGE KindSignatures # import Data.Kind data Nat = Z | S Nat data HList (ls :: [Type]) where HNil :: HList '[] HCons :: t -> HList ts -> HList (t ': ts) data ElemAt (n :: Nat) t (ts :: [Type]) where AtZ :: ElemAt 'Z t (t ': ts) AtS :: ElemAt k t ts -> ElemAt ('S k) t (u ': ts) lookMeUp :: ElemAt i ty tys -> HList tys -> ty lookMeUp AtZ (HCons t _) = t lookMeUp (AtS ea') (HCons _ hl') = lookMeUp ea' hl'
b49c2bb68790076ddd9ed1194e3486ea295a75a936b1ea1de4a7aa1adcd077d2
OCADml/OCADml
offset.mli
val offset : ?fn:int -> ?fs:float -> ?fa:float -> ?closed:bool -> ?check_valid:[ `Quality of int | `No ] -> ?mode:[< `Chamfer | `Delta | `Radius > `Delta ] -> float -> V2.t list -> V2.t list val offset_with_faces : ?fn:int -> ?fs:float -> ?fa:float -> ?closed:bool -> ?check_valid:[ `Quality of int | `No ] -> ?flip_faces:bool -> ?start_idx:int -> ?mode:[< `Chamfer | `Delta | `Radius > `Delta ] -> float -> V2.t list -> int * V2.t list * int list list
null
https://raw.githubusercontent.com/OCADml/OCADml/ceed2bfce640667580f7286b46864a69cdc1d4d7/lib/offset.mli
ocaml
val offset : ?fn:int -> ?fs:float -> ?fa:float -> ?closed:bool -> ?check_valid:[ `Quality of int | `No ] -> ?mode:[< `Chamfer | `Delta | `Radius > `Delta ] -> float -> V2.t list -> V2.t list val offset_with_faces : ?fn:int -> ?fs:float -> ?fa:float -> ?closed:bool -> ?check_valid:[ `Quality of int | `No ] -> ?flip_faces:bool -> ?start_idx:int -> ?mode:[< `Chamfer | `Delta | `Radius > `Delta ] -> float -> V2.t list -> int * V2.t list * int list list
c4c453782dde5b58df70e1224d86d23bf249a645e8943ffa95f015279b33720c
casperschipper/ocaml-cisp
cisp8.ml
open Cisp open Seq (* open Format *) let sec s = !Process.sample_rate *. s let msec = map sec let place = (seq [0.0;4.0 |> sec]) +.~ (rvf (st 0.0) (st 3.0)) let dura = (ch [|0.1;0.5;1.0;2.0;1.5;0.75;4.0;8.0|]) let myLineTest () = tline dura place let sum lst = List.fold_right (fun x acc -> x +.~ acc) lst (st 0.0) let singleton a = [a] let () = let buffer = Array.make (sec 5.0 |> Int.of_float) 0.0 in let input = Process.inputSeq 0 in let input_2 = Process.inputSeq 1 *.~ (st 0.5) |> map (clip (-1.0) 1.0) in let input_osc = input +.~ input_2 in let hpf = bhpf_static 100.0 0.9 input_osc in let writer = write buffer (countTill <| cap buffer) hpf in let myReader () = indexCub buffer (myLineTest ()) in let timefied = effectSync masterClock (myReader ()) in let joined = effectSync writer timefied in Jack.playSeqs 2 Process.sample_rate [joined +.~ mkLots 4 myReader;mkLots 5 myReader]
null
https://raw.githubusercontent.com/casperschipper/ocaml-cisp/571ffb8e508c5427d01e407ba5e91ff2a4604f40/examples/cisp_backup/beforeDecoherence/cisp8.ml
ocaml
open Format
open Cisp open Seq let sec s = !Process.sample_rate *. s let msec = map sec let place = (seq [0.0;4.0 |> sec]) +.~ (rvf (st 0.0) (st 3.0)) let dura = (ch [|0.1;0.5;1.0;2.0;1.5;0.75;4.0;8.0|]) let myLineTest () = tline dura place let sum lst = List.fold_right (fun x acc -> x +.~ acc) lst (st 0.0) let singleton a = [a] let () = let buffer = Array.make (sec 5.0 |> Int.of_float) 0.0 in let input = Process.inputSeq 0 in let input_2 = Process.inputSeq 1 *.~ (st 0.5) |> map (clip (-1.0) 1.0) in let input_osc = input +.~ input_2 in let hpf = bhpf_static 100.0 0.9 input_osc in let writer = write buffer (countTill <| cap buffer) hpf in let myReader () = indexCub buffer (myLineTest ()) in let timefied = effectSync masterClock (myReader ()) in let joined = effectSync writer timefied in Jack.playSeqs 2 Process.sample_rate [joined +.~ mkLots 4 myReader;mkLots 5 myReader]
75ebf1d1183d859c784d0ccccd40f941acdde7886828a4b874e896a075d804ed
intermine/bluegenes
events.cljs
(ns bluegenes.pages.templates.events (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [re-frame.core :refer [reg-event-db reg-event-fx reg-fx dispatch subscribe]] [re-frame.events] [oops.core :refer [oset!]] [goog.dom :as gdom] [cljs.core.async :refer [put! chan <! >! timeout close!]] [imcljs.fetch :as fetch] [imcljs.save :as save] [bluegenes.route :as route] [bluegenes.components.ui.constraint :as constraint] [bluegenes.pages.templates.helpers :refer [prepare-template-query template-matches?]] [bluegenes.utils :refer [template->xml]])) (defn template-matches-filters? [db template-id] (let [{:keys [selected-template-category text-filter authorized-filter]} (get-in db [:components :template-chooser]) template (get-in db [:assets :templates (:current-mine db) template-id])] (template-matches? {:category selected-template-category :text text-filter :authorized authorized-filter} template))) ;; This effect handler is used from routes and has different behaviour ;; depending on if it's called from a different panel, or the template panel. (reg-event-fx :template-chooser/open-template (fn [{db :db} [_ id]] (if (= :templates-panel (:active-panel db)) {:dispatch [:template-chooser/choose-template id]} {:dispatch-n [[:set-active-panel :templates-panel nil flush - dom makes the event wait for the page to update first . ;; This is because we'll be scrolling to the template, so the element needs to be present first . ^:flush-dom [:template-chooser/choose-template id {:scroll? true}]]]}))) (reg-event-fx :template-chooser/choose-template (fn [{db :db} [_ id {:keys [scroll?] :as _opts}]] (let [matches-filters? (template-matches-filters? db id) current-mine (:current-mine db) query (get-in db [:assets :templates current-mine id])] (cond (and matches-filters? (not-empty query)) (merge {:db (update-in db [:components :template-chooser] assoc :selected-template query :selected-template-name id :selected-template-service (get-in db [:mines current-mine :service]) :count nil :results-preview nil) :dispatch-n [[:template-chooser/run-count] [:template-chooser/fetch-preview]]} (when scroll? {:scroll-to-template {:id (name id)}})) ;; Clear filters by using assoc-in instead of update-in assoc. (not-empty query) {:db (assoc-in db [:components :template-chooser] {:selected-template query :selected-template-name id :selected-template-service (get-in db [:mines current-mine :service]) :count nil :results-preview nil}) :dispatch-n [[:template-chooser/run-count] [:template-chooser/fetch-preview]] ;; Will always scroll as this clause means the user cannot see the ;; template and likely chose it using the browser's back/forward. :scroll-to-template {:id (name id) :delay 100}} ;; Template can't be found. :else {:dispatch-n [[::route/navigate ::route/templates] [:messages/add {:markup [:span "The template " [:em (name id)] " does not exist. It's possible the ID has changed. Use the text filter above to find a template with a similar name."] :style "warning" :timeout 0}]]})))) (reg-event-db :template-chooser/deselect-template (fn [db [_]] (update-in db [:components :template-chooser] select-keys [:selected-template-category :text-filter :authorized-filter]))) ;; Above keeps filters, while the below clears them. (reg-event-db :template-chooser/clear-template (fn [db [_]] (update db :components dissoc :template-chooser))) (reg-event-db :template-chooser/set-category-filter (fn [db [_ id]] (assoc-in db [:components :template-chooser :selected-template-category] id))) (reg-event-db :template-chooser/set-text-filter (fn [db [_ text]] (assoc-in db [:components :template-chooser :text-filter] text))) (reg-event-db :template-chooser/toggle-authorized-filter (fn [db [_]] (update-in db [:components :template-chooser :authorized-filter] not))) ;; We don't want to make the text filter a controlled input as we want to be able to debounce its event . Leading to this lesser evil of DOM manipulation . (reg-fx ::clear-text-filter (fn [_] (oset! (gdom/getElement "template-text-filter") :value ""))) (reg-event-fx :template-chooser/clear-text-filter (fn [{db :db} [_]] {:db (assoc-in db [:components :template-chooser :text-filter] "") ::clear-text-filter {}})) (reg-event-fx :templates/send-off-query (fn [{db :db} [_]] {:db db :dispatch [:results/history+ {:source (:current-mine db) :type :query :intent :template :value (prepare-template-query (get-in db [:components :template-chooser :selected-template]))}]})) (reg-event-db :templates/reset-template (fn [db [_]] (let [current-mine (:current-mine db) id (get-in db [:components :template-chooser :selected-template-name])] (assoc-in db [:components :template-chooser :selected-template] (get-in db [:assets :templates current-mine id]))))) (reg-event-fx :templates/edit-query (fn [{db :db} [_]] {:db db :dispatch-n [[::route/navigate ::route/querybuilder] [:qb/load-query (prepare-template-query (get-in db [:components :template-chooser :selected-template]))]]})) (reg-event-fx :templates/edit-template (fn [{db :db} [_]] {:db db :dispatch-n [[::route/navigate ::route/querybuilder] [:qb/load-template (get-in db [:components :template-chooser :selected-template])]]})) (reg-event-fx :template-chooser/replace-constraint (fn [{db :db} [_ index {new-op :op :as new-constraint}]] (let [constraint-location [:components :template-chooser :selected-template :where index] {old-op :op :as old-constraint} (get-in db constraint-location)] {:db (-> db (assoc-in constraint-location (constraint/clear-constraint-value old-constraint new-constraint)) (cond-> (not= old-op new-op) (assoc-in [:components :template-chooser :results-preview] nil)))}))) (reg-event-fx :template-chooser/update-preview (fn [{db :db} [_ _index new-constraint]] (if (constraint/satisfied-constraint? new-constraint) {:dispatch-n [[:template-chooser/run-count] [:template-chooser/fetch-preview]]} {:db (assoc-in db [:components :template-chooser :results-preview] nil)}))) (reg-event-db :template-chooser/update-count (fn [db [_ c]] (update-in db [:components :template-chooser] assoc :count c :counting? false))) (reg-event-db :template-chooser/store-results-preview (fn [db [_ results]] (update-in db [:components :template-chooser] assoc :results-preview results :fetching-preview? false))) (reg-fx :template-chooser/pipe-preview (fn [preview-chan] (go (dispatch [:template-chooser/store-results-preview (<! preview-chan)])))) (reg-event-fx :template-chooser/fetch-preview (fn [{db :db}] (let [query (prepare-template-query (get-in db [:components :template-chooser :selected-template])) service (get-in db [:mines (:current-mine db) :service]) count-chan (fetch/table-rows service query {:size 5}) query-changed? (not= query (get-in db [:components :template-chooser :previously-ran])) new-db (update-in db [:components :template-chooser] assoc :preview-chan count-chan :previously-ran query)] (cond-> {:db new-db} query-changed? (-> (update-in [:db :components :template-chooser] assoc :fetching-preview? true :preview-error nil) (assoc :im-chan {:chan count-chan :on-success [:template-chooser/store-results-preview] :on-failure [:template-chooser/fetch-preview-failure]})))))) (reg-event-db :template-chooser/fetch-preview-failure (fn [db [_ res]] (update-in db [:components :template-chooser] assoc :fetching-preview? false :preview-error (or (get-in res [:body :error]) "Error occurred when running template.")))) (reg-fx :template-chooser/pipe-count (fn [count-chan] (go (dispatch [:template-chooser/update-count (<! count-chan)])))) (reg-event-fx :template-chooser/run-count (fn [{db :db}] (let [query (prepare-template-query (get-in db [:components :template-chooser :selected-template])) service (get-in db [:mines (:current-mine db) :service]) count-chan (fetch/row-count service query) new-db (update-in db [:components :template-chooser] assoc :count-chan count-chan :counting? true)] {:db new-db :template-chooser/pipe-count count-chan}))) (reg-event-fx :templates/delete-template (fn [{db :db} [_]] (let [service (get-in db [:mines (:current-mine db) :service]) template-name (name (get-in db [:components :template-chooser :selected-template-name])) template-details (get-in db [:components :template-chooser :selected-template])] {:im-chan {:chan (save/delete-template service template-name) :on-success [:templates/delete-template-success template-name template-details] :on-failure [:templates/delete-template-failure template-name template-details]}}))) (reg-event-fx :templates/delete-template-success (fn [{db :db} [_ template-name template-details _res]] {:db (update-in db [:assets :templates (:current-mine db)] dissoc (keyword template-name)) :dispatch-n [[::route/navigate ::route/templates] [:messages/add {:markup (fn [id] [:span "The template " [:em template-name] " has been deleted. " [:a {:role "button" :on-click #(dispatch [:templates/undo-delete-template template-name template-details id])} "Click here"] " to undo this action and restore the template."]) :style "info" :timeout 10000}]]})) (reg-event-fx :templates/undo-delete-template (fn [{db :db} [_ template-name template-details message-id]] (let [service (get-in db [:mines (:current-mine db) :service]) model (:model service) ;; We're passing template-details as the query here. It's fine as it contains the expected query keys , and imcljs.query/->xml will only ;; use the query-related keys, ignoring the rest. template-query (template->xml model template-details template-details)] {:im-chan {:chan (save/template service template-query) :on-success [:templates/undo-delete-template-success template-name] :on-failure [:qb/save-template-failure template-name]} :dispatch [:messages/remove message-id]}))) (reg-event-fx :templates/undo-delete-template-success (fn [{db :db} [_ template-name _res]] {:dispatch [:assets/fetch-templates [::route/navigate ::route/template {:template template-name}]]})) (reg-event-fx :templates/delete-template-failure (fn [{db :db} [_ template-name _template-details res]] {:dispatch [:messages/add {:markup [:span (str "Failed to delete template '" template-name "'. " (or (get-in res [:body :error]) "Please check your connection and try again."))] :style "warning"}]}))
null
https://raw.githubusercontent.com/intermine/bluegenes/13b43c3ca0cec7b1596a51d4254a519266a28d6e/src/cljs/bluegenes/pages/templates/events.cljs
clojure
This effect handler is used from routes and has different behaviour depending on if it's called from a different panel, or the template panel. This is because we'll be scrolling to the template, so the Clear filters by using assoc-in instead of update-in assoc. Will always scroll as this clause means the user cannot see the template and likely chose it using the browser's back/forward. Template can't be found. Above keeps filters, while the below clears them. We don't want to make the text filter a controlled input as we want to be We're passing template-details as the query here. It's fine as it use the query-related keys, ignoring the rest.
(ns bluegenes.pages.templates.events (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [re-frame.core :refer [reg-event-db reg-event-fx reg-fx dispatch subscribe]] [re-frame.events] [oops.core :refer [oset!]] [goog.dom :as gdom] [cljs.core.async :refer [put! chan <! >! timeout close!]] [imcljs.fetch :as fetch] [imcljs.save :as save] [bluegenes.route :as route] [bluegenes.components.ui.constraint :as constraint] [bluegenes.pages.templates.helpers :refer [prepare-template-query template-matches?]] [bluegenes.utils :refer [template->xml]])) (defn template-matches-filters? [db template-id] (let [{:keys [selected-template-category text-filter authorized-filter]} (get-in db [:components :template-chooser]) template (get-in db [:assets :templates (:current-mine db) template-id])] (template-matches? {:category selected-template-category :text text-filter :authorized authorized-filter} template))) (reg-event-fx :template-chooser/open-template (fn [{db :db} [_ id]] (if (= :templates-panel (:active-panel db)) {:dispatch [:template-chooser/choose-template id]} {:dispatch-n [[:set-active-panel :templates-panel nil flush - dom makes the event wait for the page to update first . element needs to be present first . ^:flush-dom [:template-chooser/choose-template id {:scroll? true}]]]}))) (reg-event-fx :template-chooser/choose-template (fn [{db :db} [_ id {:keys [scroll?] :as _opts}]] (let [matches-filters? (template-matches-filters? db id) current-mine (:current-mine db) query (get-in db [:assets :templates current-mine id])] (cond (and matches-filters? (not-empty query)) (merge {:db (update-in db [:components :template-chooser] assoc :selected-template query :selected-template-name id :selected-template-service (get-in db [:mines current-mine :service]) :count nil :results-preview nil) :dispatch-n [[:template-chooser/run-count] [:template-chooser/fetch-preview]]} (when scroll? {:scroll-to-template {:id (name id)}})) (not-empty query) {:db (assoc-in db [:components :template-chooser] {:selected-template query :selected-template-name id :selected-template-service (get-in db [:mines current-mine :service]) :count nil :results-preview nil}) :dispatch-n [[:template-chooser/run-count] [:template-chooser/fetch-preview]] :scroll-to-template {:id (name id) :delay 100}} :else {:dispatch-n [[::route/navigate ::route/templates] [:messages/add {:markup [:span "The template " [:em (name id)] " does not exist. It's possible the ID has changed. Use the text filter above to find a template with a similar name."] :style "warning" :timeout 0}]]})))) (reg-event-db :template-chooser/deselect-template (fn [db [_]] (update-in db [:components :template-chooser] select-keys [:selected-template-category :text-filter :authorized-filter]))) (reg-event-db :template-chooser/clear-template (fn [db [_]] (update db :components dissoc :template-chooser))) (reg-event-db :template-chooser/set-category-filter (fn [db [_ id]] (assoc-in db [:components :template-chooser :selected-template-category] id))) (reg-event-db :template-chooser/set-text-filter (fn [db [_ text]] (assoc-in db [:components :template-chooser :text-filter] text))) (reg-event-db :template-chooser/toggle-authorized-filter (fn [db [_]] (update-in db [:components :template-chooser :authorized-filter] not))) able to debounce its event . Leading to this lesser evil of DOM manipulation . (reg-fx ::clear-text-filter (fn [_] (oset! (gdom/getElement "template-text-filter") :value ""))) (reg-event-fx :template-chooser/clear-text-filter (fn [{db :db} [_]] {:db (assoc-in db [:components :template-chooser :text-filter] "") ::clear-text-filter {}})) (reg-event-fx :templates/send-off-query (fn [{db :db} [_]] {:db db :dispatch [:results/history+ {:source (:current-mine db) :type :query :intent :template :value (prepare-template-query (get-in db [:components :template-chooser :selected-template]))}]})) (reg-event-db :templates/reset-template (fn [db [_]] (let [current-mine (:current-mine db) id (get-in db [:components :template-chooser :selected-template-name])] (assoc-in db [:components :template-chooser :selected-template] (get-in db [:assets :templates current-mine id]))))) (reg-event-fx :templates/edit-query (fn [{db :db} [_]] {:db db :dispatch-n [[::route/navigate ::route/querybuilder] [:qb/load-query (prepare-template-query (get-in db [:components :template-chooser :selected-template]))]]})) (reg-event-fx :templates/edit-template (fn [{db :db} [_]] {:db db :dispatch-n [[::route/navigate ::route/querybuilder] [:qb/load-template (get-in db [:components :template-chooser :selected-template])]]})) (reg-event-fx :template-chooser/replace-constraint (fn [{db :db} [_ index {new-op :op :as new-constraint}]] (let [constraint-location [:components :template-chooser :selected-template :where index] {old-op :op :as old-constraint} (get-in db constraint-location)] {:db (-> db (assoc-in constraint-location (constraint/clear-constraint-value old-constraint new-constraint)) (cond-> (not= old-op new-op) (assoc-in [:components :template-chooser :results-preview] nil)))}))) (reg-event-fx :template-chooser/update-preview (fn [{db :db} [_ _index new-constraint]] (if (constraint/satisfied-constraint? new-constraint) {:dispatch-n [[:template-chooser/run-count] [:template-chooser/fetch-preview]]} {:db (assoc-in db [:components :template-chooser :results-preview] nil)}))) (reg-event-db :template-chooser/update-count (fn [db [_ c]] (update-in db [:components :template-chooser] assoc :count c :counting? false))) (reg-event-db :template-chooser/store-results-preview (fn [db [_ results]] (update-in db [:components :template-chooser] assoc :results-preview results :fetching-preview? false))) (reg-fx :template-chooser/pipe-preview (fn [preview-chan] (go (dispatch [:template-chooser/store-results-preview (<! preview-chan)])))) (reg-event-fx :template-chooser/fetch-preview (fn [{db :db}] (let [query (prepare-template-query (get-in db [:components :template-chooser :selected-template])) service (get-in db [:mines (:current-mine db) :service]) count-chan (fetch/table-rows service query {:size 5}) query-changed? (not= query (get-in db [:components :template-chooser :previously-ran])) new-db (update-in db [:components :template-chooser] assoc :preview-chan count-chan :previously-ran query)] (cond-> {:db new-db} query-changed? (-> (update-in [:db :components :template-chooser] assoc :fetching-preview? true :preview-error nil) (assoc :im-chan {:chan count-chan :on-success [:template-chooser/store-results-preview] :on-failure [:template-chooser/fetch-preview-failure]})))))) (reg-event-db :template-chooser/fetch-preview-failure (fn [db [_ res]] (update-in db [:components :template-chooser] assoc :fetching-preview? false :preview-error (or (get-in res [:body :error]) "Error occurred when running template.")))) (reg-fx :template-chooser/pipe-count (fn [count-chan] (go (dispatch [:template-chooser/update-count (<! count-chan)])))) (reg-event-fx :template-chooser/run-count (fn [{db :db}] (let [query (prepare-template-query (get-in db [:components :template-chooser :selected-template])) service (get-in db [:mines (:current-mine db) :service]) count-chan (fetch/row-count service query) new-db (update-in db [:components :template-chooser] assoc :count-chan count-chan :counting? true)] {:db new-db :template-chooser/pipe-count count-chan}))) (reg-event-fx :templates/delete-template (fn [{db :db} [_]] (let [service (get-in db [:mines (:current-mine db) :service]) template-name (name (get-in db [:components :template-chooser :selected-template-name])) template-details (get-in db [:components :template-chooser :selected-template])] {:im-chan {:chan (save/delete-template service template-name) :on-success [:templates/delete-template-success template-name template-details] :on-failure [:templates/delete-template-failure template-name template-details]}}))) (reg-event-fx :templates/delete-template-success (fn [{db :db} [_ template-name template-details _res]] {:db (update-in db [:assets :templates (:current-mine db)] dissoc (keyword template-name)) :dispatch-n [[::route/navigate ::route/templates] [:messages/add {:markup (fn [id] [:span "The template " [:em template-name] " has been deleted. " [:a {:role "button" :on-click #(dispatch [:templates/undo-delete-template template-name template-details id])} "Click here"] " to undo this action and restore the template."]) :style "info" :timeout 10000}]]})) (reg-event-fx :templates/undo-delete-template (fn [{db :db} [_ template-name template-details message-id]] (let [service (get-in db [:mines (:current-mine db) :service]) model (:model service) contains the expected query keys , and imcljs.query/->xml will only template-query (template->xml model template-details template-details)] {:im-chan {:chan (save/template service template-query) :on-success [:templates/undo-delete-template-success template-name] :on-failure [:qb/save-template-failure template-name]} :dispatch [:messages/remove message-id]}))) (reg-event-fx :templates/undo-delete-template-success (fn [{db :db} [_ template-name _res]] {:dispatch [:assets/fetch-templates [::route/navigate ::route/template {:template template-name}]]})) (reg-event-fx :templates/delete-template-failure (fn [{db :db} [_ template-name _template-details res]] {:dispatch [:messages/add {:markup [:span (str "Failed to delete template '" template-name "'. " (or (get-in res [:body :error]) "Please check your connection and try again."))] :style "warning"}]}))
7ed35076c6d5d84d49ca06f7e62a8534cbc6fcb6f8dd8d2ec04ee8524cc5eaa7
Bogdanp/racket-kafka
help.rkt
#lang racket/base (require racket/port) (provide null8 null16 null32 ref opt with-output-bytes) (define null8 #"\xFF") (define null16 #"\xFF\xFF") (define null32 #"\xFF\xFF\xFF\xFF") (define ref (case-lambda [(id v) (define p (assq id v)) (unless p (error 'ref "key not found: ~s~n have: ~e" id (map car v))) (cdr p)] [(id . args) (ref id (apply ref args))])) (define opt (case-lambda [(id v) (define p (assq id v)) (and p (cdr p))] [(id . args) (opt id (apply ref args))])) (define-syntax-rule (with-output-bytes e0 e ...) (with-output-to-bytes (lambda () e0 e ...)))
null
https://raw.githubusercontent.com/Bogdanp/racket-kafka/39a25759a312b535666cb7f247b6ac00cb76e4b8/kafka-lib/private/help.rkt
racket
#lang racket/base (require racket/port) (provide null8 null16 null32 ref opt with-output-bytes) (define null8 #"\xFF") (define null16 #"\xFF\xFF") (define null32 #"\xFF\xFF\xFF\xFF") (define ref (case-lambda [(id v) (define p (assq id v)) (unless p (error 'ref "key not found: ~s~n have: ~e" id (map car v))) (cdr p)] [(id . args) (ref id (apply ref args))])) (define opt (case-lambda [(id v) (define p (assq id v)) (and p (cdr p))] [(id . args) (opt id (apply ref args))])) (define-syntax-rule (with-output-bytes e0 e ...) (with-output-to-bytes (lambda () e0 e ...)))
cbbc1e42375edd3effd5c720466327f2617a5107fe3b251a38cecb518b505b20
dparis/gen-phzr
net.cljs
(ns phzr.net (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser])) (defn ->Net "Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. Parameters: * game (Phaser.Game) - A reference to the currently running game." ([game] (js/Phaser.Net. (clj->phaser game)))) (defn check-domain-name "Compares the given domain name against the hostname of the browser containing the game. If the domain name is found it returns true. You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. Do not include 'http://' at the start. Parameters: * net (Phaser.Net) - Targeted instance for method * domain (string) - No description Returns: boolean - true if the given domain fragment can be found in the window.location.hostname" ([net domain] (phaser->clj (.checkDomainName net (clj->phaser domain))))) (defn decode-uri "Returns the Query String as an object. If you specify a parameter it will return just the value of that parameter, should it exist. Parameters: * net (Phaser.Net) - Targeted instance for method * value (string) - The URI component to be decoded. Returns: string - The decoded value." ([net value] (phaser->clj (.decodeURI net (clj->phaser value))))) (defn get-host-name "Returns the hostname given by the browser. Returns: string - " ([net] (phaser->clj (.getHostName net)))) (defn get-query-string "Returns the Query String as an object. If you specify a parameter it will return just the value of that parameter, should it exist. Parameters: * net (Phaser.Net) - Targeted instance for method * parameter (string) {optional} - If specified this will return just the value for that key. Returns: [string | object] - An object containing the key value pairs found in the query string or just the value if a parameter was given." ([net] (phaser->clj (.getQueryString net))) ([net parameter] (phaser->clj (.getQueryString net (clj->phaser parameter))))) (defn update-query-string "Updates a value on the Query String and returns it in full. If the value doesn't already exist it is set. If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. Optionally you can redirect to the new url, or just return it as a string. Parameters: * net (Phaser.Net) - Targeted instance for method * key (string) - The querystring key to update. * value (string) - The new value to be set. If it already exists it will be replaced. * redirect (boolean) - If true the browser will issue a redirect to the url with the new querystring. * url (string) - The URL to modify. If none is given it uses window.location.href. Returns: string - If redirect is false then the modified url and query string is returned." ([net key value redirect url] (phaser->clj (.updateQueryString net (clj->phaser key) (clj->phaser value) (clj->phaser redirect) (clj->phaser url)))))
null
https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/net.cljs
clojure
(ns phzr.net (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser])) (defn ->Net "Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. Parameters: * game (Phaser.Game) - A reference to the currently running game." ([game] (js/Phaser.Net. (clj->phaser game)))) (defn check-domain-name "Compares the given domain name against the hostname of the browser containing the game. If the domain name is found it returns true. You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. Do not include 'http://' at the start. Parameters: * net (Phaser.Net) - Targeted instance for method * domain (string) - No description Returns: boolean - true if the given domain fragment can be found in the window.location.hostname" ([net domain] (phaser->clj (.checkDomainName net (clj->phaser domain))))) (defn decode-uri "Returns the Query String as an object. If you specify a parameter it will return just the value of that parameter, should it exist. Parameters: * net (Phaser.Net) - Targeted instance for method * value (string) - The URI component to be decoded. Returns: string - The decoded value." ([net value] (phaser->clj (.decodeURI net (clj->phaser value))))) (defn get-host-name "Returns the hostname given by the browser. Returns: string - " ([net] (phaser->clj (.getHostName net)))) (defn get-query-string "Returns the Query String as an object. If you specify a parameter it will return just the value of that parameter, should it exist. Parameters: * net (Phaser.Net) - Targeted instance for method * parameter (string) {optional} - If specified this will return just the value for that key. Returns: [string | object] - An object containing the key value pairs found in the query string or just the value if a parameter was given." ([net] (phaser->clj (.getQueryString net))) ([net parameter] (phaser->clj (.getQueryString net (clj->phaser parameter))))) (defn update-query-string "Updates a value on the Query String and returns it in full. If the value doesn't already exist it is set. If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. Optionally you can redirect to the new url, or just return it as a string. Parameters: * net (Phaser.Net) - Targeted instance for method * key (string) - The querystring key to update. * value (string) - The new value to be set. If it already exists it will be replaced. * redirect (boolean) - If true the browser will issue a redirect to the url with the new querystring. * url (string) - The URL to modify. If none is given it uses window.location.href. Returns: string - If redirect is false then the modified url and query string is returned." ([net key value redirect url] (phaser->clj (.updateQueryString net (clj->phaser key) (clj->phaser value) (clj->phaser redirect) (clj->phaser url)))))
182d27ab41254e5256d8240b5fc95e30ffc925827244152d061dd34d4e559ae2
didierverna/clon
termio.lisp
;;; termio.lisp --- Clon termio setup Copyright ( C ) 2015 , 2021 Author : < > This file is part of . ;; Permission to use, copy, modify, and distribute this software for any ;; purpose with or without fee is hereby granted, provided that the above ;; copyright notice and this permission notice appear in all copies. THIS SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ;; WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF ;; MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ;; ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF ;; OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ;;; Commentary: Contents management by FCM version 0.1 . ;;; Code: (in-package :net.didierverna.clon.setup) (in-readtable :net.didierverna.clon) (defun restrict-because (reason) "Put Clon in restricted mode because of REASON." (format *error-output* "~ ******************************************************************* * WARNING: ~A.~66T* * Clon will be loaded without support for terminal autodetection. * * See sections 2 and A.1 of the user manual for more information. * *******************************************************************" reason) (configure :restricted t)) (defun setup-termio () "Autodetect termio support. Update Clon configuration and *FEATURES* accordingly." (unless (configuration :restricted) #+sbcl (handler-case (asdf:load-system :sb-grovel) (error () (restrict-because "unable to load SB-GROVEL"))) #+clisp (cond ((member :ffi *features*) (handler-case (asdf:load-system :cffi-grovel) (error () (restrict-because "unable to load CFFI-GROVEL")))) (t (restrict-because "CLISP is compiled without FFI support"))) #+(or allegro lispworks) (handler-case (asdf:load-system :cffi-grovel) (error () (restrict-because "unable to load CFFI-GROVEL"))) #+abcl (restrict-because "ABCL is in use")) (if (configuration :restricted) (setq *features* (delete :net.didierverna.clon.termio *features*)) (pushnew :net.didierverna.clon.termio *features*))) ;;; termio.lisp ends here
null
https://raw.githubusercontent.com/didierverna/clon/98e95c0635ec80517711d5e5c2ad43884cbb275f/setup/src/termio.lisp
lisp
termio.lisp --- Clon termio setup Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Commentary: Code: termio.lisp ends here
Copyright ( C ) 2015 , 2021 Author : < > This file is part of . THIS SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN Contents management by FCM version 0.1 . (in-package :net.didierverna.clon.setup) (in-readtable :net.didierverna.clon) (defun restrict-because (reason) "Put Clon in restricted mode because of REASON." (format *error-output* "~ ******************************************************************* * WARNING: ~A.~66T* * Clon will be loaded without support for terminal autodetection. * * See sections 2 and A.1 of the user manual for more information. * *******************************************************************" reason) (configure :restricted t)) (defun setup-termio () "Autodetect termio support. Update Clon configuration and *FEATURES* accordingly." (unless (configuration :restricted) #+sbcl (handler-case (asdf:load-system :sb-grovel) (error () (restrict-because "unable to load SB-GROVEL"))) #+clisp (cond ((member :ffi *features*) (handler-case (asdf:load-system :cffi-grovel) (error () (restrict-because "unable to load CFFI-GROVEL")))) (t (restrict-because "CLISP is compiled without FFI support"))) #+(or allegro lispworks) (handler-case (asdf:load-system :cffi-grovel) (error () (restrict-because "unable to load CFFI-GROVEL"))) #+abcl (restrict-because "ABCL is in use")) (if (configuration :restricted) (setq *features* (delete :net.didierverna.clon.termio *features*)) (pushnew :net.didierverna.clon.termio *features*)))
64a9f9b5829d7a87f67cac20965e277c893746919e7a72065687262baf35078d
cyga/real-world-haskell
LineCount.hs
file : ch24 / LineCount.hs module Main where import Control.Monad (forM_) import Data.Int (Int64) import qualified Data.ByteString.Lazy.Char8 as LB import System.Environment (getArgs) import LineChunks (chunkedReadWith) import MapReduce (mapReduce, rnf) lineCount :: [LB.ByteString] -> Int64 lineCount = mapReduce rnf (LB.count '\n') rnf sum main :: IO () main = do args <- getArgs forM_ args $ \path -> do numLines <- chunkedReadWith lineCount path putStrLn $ path ++ ": " ++ show numLines
null
https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch24/LineCount.hs
haskell
file : ch24 / LineCount.hs module Main where import Control.Monad (forM_) import Data.Int (Int64) import qualified Data.ByteString.Lazy.Char8 as LB import System.Environment (getArgs) import LineChunks (chunkedReadWith) import MapReduce (mapReduce, rnf) lineCount :: [LB.ByteString] -> Int64 lineCount = mapReduce rnf (LB.count '\n') rnf sum main :: IO () main = do args <- getArgs forM_ args $ \path -> do numLines <- chunkedReadWith lineCount path putStrLn $ path ++ ": " ++ show numLines
5f3461af41cb717fc63f965cdbb9b411103799eeaffb8958b9b03d931aa139e1
michalkonecny/aern2
Variables.hs
module ERC.Variables where import Prelude import Control.Monad.ST.Trans import ERC.Monad type Var s = STRef s (?) :: Var s t -> ERC s t (?) = readSTRef assign :: Var s t -> ERC s t -> ERC s () assign v valERC = do val <- valERC ifInvalidUseDummy () $ writeSTRef v val (.=) :: Var s t -> ERC s t -> ERC s () (.=) = assign infixl 1 .=
null
https://raw.githubusercontent.com/michalkonecny/aern2/1c8f12dfcb287bd8e3353802a94865d7c2c121ec/aern2-erc/src/ERC/Variables.hs
haskell
module ERC.Variables where import Prelude import Control.Monad.ST.Trans import ERC.Monad type Var s = STRef s (?) :: Var s t -> ERC s t (?) = readSTRef assign :: Var s t -> ERC s t -> ERC s () assign v valERC = do val <- valERC ifInvalidUseDummy () $ writeSTRef v val (.=) :: Var s t -> ERC s t -> ERC s () (.=) = assign infixl 1 .=
96cedca53c2ac92f4d3e879f301320a56438250f02c6459ee9fb557969662be0
janestreet/universe
ppx_sexp_value.ml
open Base open Ppxlib open Ast_builder.Default let omit_nil = Attribute.declare "sexp_value.sexp.omit_nil" Attribute.Context.core_type Ast_pattern.(pstr nil) () let option = Attribute.declare "sexp_value.sexp.option" Attribute.Context.core_type Ast_pattern.(pstr nil) () let sexp_atom ~loc x = [%expr Ppx_sexp_conv_lib.Sexp.Atom [%e x]] let sexp_list ~loc x = [%expr Ppx_sexp_conv_lib.Sexp.List [%e x]] let rec list_and_tail_of_ast_list rev_el e = match e.pexp_desc with | Pexp_construct ({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple [hd; tl]; _ }) -> list_and_tail_of_ast_list (hd :: rev_el) tl | Pexp_construct ({ txt = Lident "[]"; _ }, None) -> List.rev rev_el, None | _ -> List.rev rev_el, Some e ;; let sexp_of_constant ~loc const = let f typ = eapply ~loc (evar ~loc ("Ppx_sexp_conv_lib.Conv.sexp_of_" ^ typ)) [pexp_constant ~loc const] in match const with | Pconst_integer _ -> f "int" | Pconst_char _ -> f "char" | Pconst_string _ -> f "string" | Pconst_float _ -> f "float" ;; type omittable_sexp = | Present of expression | Optional of (Location.t * string) * expression * (expression -> expression) In [ Optional ( _ , e , k ) ] , [ e ] is an ast whose values have type [ ' a option ] , and [ k ] is a function from ast of type [ ' a ] to ast of type [ Sexp.t ] . The None case should not be displayed , and the [ a ] in the Some case should be displayed by calling [ k ] on it . a function from ast of type ['a] to ast of type [Sexp.t]. The None case should not be displayed, and the [a] in the Some case should be displayed by calling [k] on it. *) | Omit_nil of Location.t * expression * (expression -> expression) In [ ( _ , e , k ) ] , [ e ] is an ast of type [ Sexp.t ] , and [ k ] if a function ast of type [ Sexp.t ] and returns an other [ Sexp.t ] . When [ e ] is [ List [ ] ] , it should be not displayed . Otherwise [ e ] should be displayed by calling [ k ] on it . ast of type [Sexp.t] and returns an other [Sexp.t]. When [e] is [List []], it should be not displayed. Otherwise [e] should be displayed by calling [k] on it. *) let wrap_sexp_if_present omittable_sexp ~f = match omittable_sexp with | Optional (loc, e, k) -> Optional (loc, e, (fun e -> f (k e))) | Present e -> Present (f e) | Omit_nil (loc, e, k) -> Omit_nil (loc, e, (fun e -> f (k e))) let sexp_of_constraint ~loc expr ctyp = match ctyp with | [%type: [%t? ty] sexp_option] -> let sexp_of = Ppx_sexp_conv_expander.Sexp_of.core_type ty in Optional ((loc, "sexp_option"), expr, fun expr -> eapply ~loc sexp_of [expr]) | [%type: [%t? ty] option] when Option.is_some (Attribute.get option ctyp) -> let sexp_of = Ppx_sexp_conv_expander.Sexp_of.core_type ty in Optional ((loc, "[@sexp.optional]"), expr, fun expr -> eapply ~loc sexp_of [expr]) | _ -> let expr = let sexp_of = Ppx_sexp_conv_expander.Sexp_of.core_type ctyp in eapply ~loc sexp_of [expr] in match Attribute.get omit_nil ctyp with | Some () -> Omit_nil (loc, expr, Fn.id) | None -> Present expr ;; let rec sexp_of_expr expr = match omittable_sexp_of_expr expr with | Present v -> v | Optional ((loc, s), _, _) -> Location.raise_errorf ~loc "ppx_sexp_value: cannot handle %s in this context" s | Omit_nil (loc, _, _) -> Location.raise_errorf ~loc "ppx_sexp_value: cannot handle [@omit_nil] in this context" and omittable_sexp_of_expr expr = let loc = { expr.pexp_loc with loc_ghost = true } in wrap_sexp_if_present ~f:(fun new_expr -> { new_expr with pexp_attributes = expr.pexp_attributes }) (match expr.pexp_desc with | Pexp_ifthenelse (e1, e2, e3) -> Present { expr with pexp_desc = Pexp_ifthenelse (e1, sexp_of_expr e2, match e3 with | None -> None | Some e -> Some (sexp_of_expr e)) } | Pexp_constraint (expr, ctyp) -> sexp_of_constraint ~loc expr ctyp | Pexp_construct ({ txt = Lident "[]"; _ }, None) | Pexp_construct ({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple [_; _]; _ }) -> let el, tl = list_and_tail_of_ast_list [] expr in let el = List.map el ~f:omittable_sexp_of_expr in let tl = match tl with | None -> [%expr [] ] | Some e -> [%expr match [%e sexp_of_expr e] with | Ppx_sexp_conv_lib.Sexp.List l -> l | Ppx_sexp_conv_lib.Sexp.Atom _ as sexp -> [sexp] ] in Present (sexp_of_omittable_sexp_list loc el ~tl) | Pexp_constant const -> Present (sexp_of_constant ~loc const) | Pexp_extension ({ txt = "here"; _ }, PStr []) -> Present (sexp_atom ~loc (Ppx_here_expander.lift_position_as_string ~loc)) | Pexp_construct ({ txt = Lident "()"; _ }, None) -> Present (sexp_list ~loc (elist ~loc [])) | Pexp_construct ({ txt = Lident constr; _ }, None) | Pexp_variant ( constr , None) -> Present (sexp_atom ~loc (estring ~loc constr)) | Pexp_construct ({ txt = Lident constr; _ }, Some arg) | Pexp_variant ( constr , Some arg) -> let k hole = sexp_list ~loc (elist ~loc [ sexp_atom ~loc (estring ~loc constr) ; hole ]) in wrap_sexp_if_present (omittable_sexp_of_expr arg) ~f:k | Pexp_tuple el -> let el = List.map el ~f:omittable_sexp_of_expr in Present (sexp_of_omittable_sexp_list loc el ~tl:(elist ~loc [])) | Pexp_record (fields, None) -> Present (sexp_of_record ~loc fields) | Pexp_apply ({ pexp_desc = Pexp_ident { txt = Lident "~~"; _ }; _}, [ (Nolabel, { pexp_desc = Pexp_constraint (expr, ctyp); _ }) ]) -> let expr_str = Pprintast.string_of_expression expr in let k hole = sexp_list ~loc (elist ~loc [ sexp_atom ~loc (estring ~loc expr_str) ; hole ]) in wrap_sexp_if_present (sexp_of_constraint ~loc expr ctyp) ~f:k | _ -> Location.raise_errorf ~loc "ppx_sexp_value: don't know how to handle this construct" ) and sexp_of_omittable_sexp_list loc el ~tl = let l = List.fold_left (List.rev el) ~init:tl ~f:(fun acc e -> match e with | Present e -> [%expr [%e e] :: [%e acc] ] | Optional (_, v_opt, k) -> (* We match simultaneously on the head and tail in the generated code to avoid changing their respective typing environments. *) [%expr match [%e v_opt], [%e acc ] with | None, tl -> tl | Some v, tl -> [%e k [%expr v]] :: tl ] | Omit_nil (_, e, k) -> [%expr match [%e e], [%e acc] with | Ppx_sexp_conv_lib.Sexp.List [], tl -> tl | v, tl -> [%e k [%expr v]] :: tl ] ) in sexp_list ~loc l and sexp_of_record ~loc fields = sexp_of_omittable_sexp_list loc ~tl:(elist ~loc []) (List.map fields ~f:(fun (id, e) -> let e = match e.pexp_desc with | Pexp_constraint (e', c) when Location.compare_pos id.loc.loc_start e.pexp_loc.loc_start = 0 && Location.compare e.pexp_loc e'.pexp_loc = 0 -> (* { foo : int } *) { e with pexp_desc = Pexp_constraint ({ e' with pexp_loc = id.loc}, c) } | _ -> e in let loc = { id.loc with loc_end = e.pexp_loc.loc_end; loc_ghost = true } in let name = String.concat ~sep:"." (Longident.flatten_exn id.txt) in let k hole = sexp_list ~loc (elist ~loc [ sexp_atom ~loc (estring ~loc:{ id.loc with loc_ghost = true } name) ; hole ]) in wrap_sexp_if_present (omittable_sexp_of_expr e) ~f:k)) ;; let () = Driver.register_transformation "sexp_value" ~extensions:[ Extension.declare "sexp" Extension.Context.expression Ast_pattern.(pstr (pstr_eval __ nil ^:: nil)) (fun ~loc:_ ~path:_ e -> sexp_of_expr e) ] ;;
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/ppx_sexp_value/src/ppx_sexp_value.ml
ocaml
We match simultaneously on the head and tail in the generated code to avoid changing their respective typing environments. { foo : int }
open Base open Ppxlib open Ast_builder.Default let omit_nil = Attribute.declare "sexp_value.sexp.omit_nil" Attribute.Context.core_type Ast_pattern.(pstr nil) () let option = Attribute.declare "sexp_value.sexp.option" Attribute.Context.core_type Ast_pattern.(pstr nil) () let sexp_atom ~loc x = [%expr Ppx_sexp_conv_lib.Sexp.Atom [%e x]] let sexp_list ~loc x = [%expr Ppx_sexp_conv_lib.Sexp.List [%e x]] let rec list_and_tail_of_ast_list rev_el e = match e.pexp_desc with | Pexp_construct ({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple [hd; tl]; _ }) -> list_and_tail_of_ast_list (hd :: rev_el) tl | Pexp_construct ({ txt = Lident "[]"; _ }, None) -> List.rev rev_el, None | _ -> List.rev rev_el, Some e ;; let sexp_of_constant ~loc const = let f typ = eapply ~loc (evar ~loc ("Ppx_sexp_conv_lib.Conv.sexp_of_" ^ typ)) [pexp_constant ~loc const] in match const with | Pconst_integer _ -> f "int" | Pconst_char _ -> f "char" | Pconst_string _ -> f "string" | Pconst_float _ -> f "float" ;; type omittable_sexp = | Present of expression | Optional of (Location.t * string) * expression * (expression -> expression) In [ Optional ( _ , e , k ) ] , [ e ] is an ast whose values have type [ ' a option ] , and [ k ] is a function from ast of type [ ' a ] to ast of type [ Sexp.t ] . The None case should not be displayed , and the [ a ] in the Some case should be displayed by calling [ k ] on it . a function from ast of type ['a] to ast of type [Sexp.t]. The None case should not be displayed, and the [a] in the Some case should be displayed by calling [k] on it. *) | Omit_nil of Location.t * expression * (expression -> expression) In [ ( _ , e , k ) ] , [ e ] is an ast of type [ Sexp.t ] , and [ k ] if a function ast of type [ Sexp.t ] and returns an other [ Sexp.t ] . When [ e ] is [ List [ ] ] , it should be not displayed . Otherwise [ e ] should be displayed by calling [ k ] on it . ast of type [Sexp.t] and returns an other [Sexp.t]. When [e] is [List []], it should be not displayed. Otherwise [e] should be displayed by calling [k] on it. *) let wrap_sexp_if_present omittable_sexp ~f = match omittable_sexp with | Optional (loc, e, k) -> Optional (loc, e, (fun e -> f (k e))) | Present e -> Present (f e) | Omit_nil (loc, e, k) -> Omit_nil (loc, e, (fun e -> f (k e))) let sexp_of_constraint ~loc expr ctyp = match ctyp with | [%type: [%t? ty] sexp_option] -> let sexp_of = Ppx_sexp_conv_expander.Sexp_of.core_type ty in Optional ((loc, "sexp_option"), expr, fun expr -> eapply ~loc sexp_of [expr]) | [%type: [%t? ty] option] when Option.is_some (Attribute.get option ctyp) -> let sexp_of = Ppx_sexp_conv_expander.Sexp_of.core_type ty in Optional ((loc, "[@sexp.optional]"), expr, fun expr -> eapply ~loc sexp_of [expr]) | _ -> let expr = let sexp_of = Ppx_sexp_conv_expander.Sexp_of.core_type ctyp in eapply ~loc sexp_of [expr] in match Attribute.get omit_nil ctyp with | Some () -> Omit_nil (loc, expr, Fn.id) | None -> Present expr ;; let rec sexp_of_expr expr = match omittable_sexp_of_expr expr with | Present v -> v | Optional ((loc, s), _, _) -> Location.raise_errorf ~loc "ppx_sexp_value: cannot handle %s in this context" s | Omit_nil (loc, _, _) -> Location.raise_errorf ~loc "ppx_sexp_value: cannot handle [@omit_nil] in this context" and omittable_sexp_of_expr expr = let loc = { expr.pexp_loc with loc_ghost = true } in wrap_sexp_if_present ~f:(fun new_expr -> { new_expr with pexp_attributes = expr.pexp_attributes }) (match expr.pexp_desc with | Pexp_ifthenelse (e1, e2, e3) -> Present { expr with pexp_desc = Pexp_ifthenelse (e1, sexp_of_expr e2, match e3 with | None -> None | Some e -> Some (sexp_of_expr e)) } | Pexp_constraint (expr, ctyp) -> sexp_of_constraint ~loc expr ctyp | Pexp_construct ({ txt = Lident "[]"; _ }, None) | Pexp_construct ({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple [_; _]; _ }) -> let el, tl = list_and_tail_of_ast_list [] expr in let el = List.map el ~f:omittable_sexp_of_expr in let tl = match tl with | None -> [%expr [] ] | Some e -> [%expr match [%e sexp_of_expr e] with | Ppx_sexp_conv_lib.Sexp.List l -> l | Ppx_sexp_conv_lib.Sexp.Atom _ as sexp -> [sexp] ] in Present (sexp_of_omittable_sexp_list loc el ~tl) | Pexp_constant const -> Present (sexp_of_constant ~loc const) | Pexp_extension ({ txt = "here"; _ }, PStr []) -> Present (sexp_atom ~loc (Ppx_here_expander.lift_position_as_string ~loc)) | Pexp_construct ({ txt = Lident "()"; _ }, None) -> Present (sexp_list ~loc (elist ~loc [])) | Pexp_construct ({ txt = Lident constr; _ }, None) | Pexp_variant ( constr , None) -> Present (sexp_atom ~loc (estring ~loc constr)) | Pexp_construct ({ txt = Lident constr; _ }, Some arg) | Pexp_variant ( constr , Some arg) -> let k hole = sexp_list ~loc (elist ~loc [ sexp_atom ~loc (estring ~loc constr) ; hole ]) in wrap_sexp_if_present (omittable_sexp_of_expr arg) ~f:k | Pexp_tuple el -> let el = List.map el ~f:omittable_sexp_of_expr in Present (sexp_of_omittable_sexp_list loc el ~tl:(elist ~loc [])) | Pexp_record (fields, None) -> Present (sexp_of_record ~loc fields) | Pexp_apply ({ pexp_desc = Pexp_ident { txt = Lident "~~"; _ }; _}, [ (Nolabel, { pexp_desc = Pexp_constraint (expr, ctyp); _ }) ]) -> let expr_str = Pprintast.string_of_expression expr in let k hole = sexp_list ~loc (elist ~loc [ sexp_atom ~loc (estring ~loc expr_str) ; hole ]) in wrap_sexp_if_present (sexp_of_constraint ~loc expr ctyp) ~f:k | _ -> Location.raise_errorf ~loc "ppx_sexp_value: don't know how to handle this construct" ) and sexp_of_omittable_sexp_list loc el ~tl = let l = List.fold_left (List.rev el) ~init:tl ~f:(fun acc e -> match e with | Present e -> [%expr [%e e] :: [%e acc] ] | Optional (_, v_opt, k) -> [%expr match [%e v_opt], [%e acc ] with | None, tl -> tl | Some v, tl -> [%e k [%expr v]] :: tl ] | Omit_nil (_, e, k) -> [%expr match [%e e], [%e acc] with | Ppx_sexp_conv_lib.Sexp.List [], tl -> tl | v, tl -> [%e k [%expr v]] :: tl ] ) in sexp_list ~loc l and sexp_of_record ~loc fields = sexp_of_omittable_sexp_list loc ~tl:(elist ~loc []) (List.map fields ~f:(fun (id, e) -> let e = match e.pexp_desc with | Pexp_constraint (e', c) when Location.compare_pos id.loc.loc_start e.pexp_loc.loc_start = 0 && Location.compare e.pexp_loc e'.pexp_loc = 0 -> { e with pexp_desc = Pexp_constraint ({ e' with pexp_loc = id.loc}, c) } | _ -> e in let loc = { id.loc with loc_end = e.pexp_loc.loc_end; loc_ghost = true } in let name = String.concat ~sep:"." (Longident.flatten_exn id.txt) in let k hole = sexp_list ~loc (elist ~loc [ sexp_atom ~loc (estring ~loc:{ id.loc with loc_ghost = true } name) ; hole ]) in wrap_sexp_if_present (omittable_sexp_of_expr e) ~f:k)) ;; let () = Driver.register_transformation "sexp_value" ~extensions:[ Extension.declare "sexp" Extension.Context.expression Ast_pattern.(pstr (pstr_eval __ nil ^:: nil)) (fun ~loc:_ ~path:_ e -> sexp_of_expr e) ] ;;
162a906530265ff6afdf20cd28d7d65809f774e0b2e81107ef0c2c0ad3562d1c
cxphoe/SICP-solutions
2.66.rkt
(define (lookup given-key set-of-records) (if (null? set-of-records) false (let ((set-entry (entry set-of-records))) (cond ((= given-key (key set-entry)) set-entry) ((< given-key (key set-entry)) (lookup given-key (left-branch set-of-records))) ((> given-key (key set-entry)) (lookup given-key (right-branch set-of-records))) (else (error "wrong key type" given-key))))))
null
https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%202-Building%20Abstractions%20with%20Data/3.Symbolic%20Data/2.66.rkt
racket
(define (lookup given-key set-of-records) (if (null? set-of-records) false (let ((set-entry (entry set-of-records))) (cond ((= given-key (key set-entry)) set-entry) ((< given-key (key set-entry)) (lookup given-key (left-branch set-of-records))) ((> given-key (key set-entry)) (lookup given-key (right-branch set-of-records))) (else (error "wrong key type" given-key))))))
366817b77e1797127249e4ecd8824df3a6d2465c58e9d017ec0b03a5aae730a6
yapsterapp/er-cassandra
unique_key_test.clj
(ns er-cassandra.model.alia.unique-key-test (:require [er-cassandra.model.util.test :as tu :refer [fetch-record]] [clojure.test :as test :refer [deftest is are testing use-fixtures]] [schema.test :as st] [clj-uuid :as uuid] [er-cassandra.record :as r] [er-cassandra.model.util.timestamp :as ts] [er-cassandra.model.types :as t] [er-cassandra.model.alia.unique-key :as uk] [er-cassandra.model.model-session :as ms] [er-cassandra.session :as session] [qbits.hayt :as h] [prpr.promise :as pr] [taoensso.timbre :refer [warn]])) (use-fixtures :once st/validate-schemas) (use-fixtures :each (tu/with-model-session-fixture)) (defn create-singular-unique-key-entity [] (tu/create-table :singular_unique_key_test "(id timeuuid primary key, nick text)") (tu/create-table :singular_unique_key_test_by_nick "(nick text primary key, id timeuuid)") (t/create-entity {:primary-table {:name :singular_unique_key_test :key [:id]} :unique-key-tables [{:name :singular_unique_key_test_by_nick :key [:nick]}]})) (defn create-singular-unique-key-entity-with-additional-cols [] (tu/create-table :singular_unique_key_with_cols_test "(id timeuuid primary key, nick text, stuff text)") (tu/create-table :singular_unique_key_with_cols_test_by_nick "(nick text primary key, stuff text, id timeuuid)") (t/create-entity {:primary-table {:name :singular_unique_key_with_cols_test :key [:id]} :unique-key-tables [{:name :singular_unique_key_with_cols_test_by_nick :key [:nick] :with-columns [:stuff]}]})) (defn create-set-unique-key-entity [] (tu/create-table :set_unique_key_test "(id timeuuid primary key, nick set<text>)") (tu/create-table :set_unique_key_test_by_nick "(nick text primary key, id timeuuid)") (t/create-entity {:primary-table {:name :set_unique_key_test :key [:id]} :unique-key-tables [{:name :set_unique_key_test_by_nick :key [:nick] :collections {:nick :set}}]})) (defn create-mixed-unique-key-entity [] (tu/create-table :mixed_unique_key_test "(org_id timeuuid, id timeuuid, nick text, email set<text>, phone list<text>, stuff text, primary key (org_id, id))") (tu/create-table :mixed_unique_key_test_by_nick "(nick text, org_id timeuuid, id timeuuid, primary key (org_id, nick))") (tu/create-table :mixed_unique_key_test_by_email "(email text primary key, org_id timeuuid, id timeuuid)") (tu/create-table :mixed_unique_key_test_by_phone "(phone text primary key, org_id timeuuid, id timeuuid)") (t/create-entity {:primary-table {:name :mixed_unique_key_test :key [:org_id :id]} :unique-key-tables [{:name :mixed_unique_key_test_by_nick :key [:org_id :nick]} {:name :mixed_unique_key_test_by_email :key [:email] :collections {:email :set}} {:name :mixed_unique_key_test_by_phone :key [:phone] :collections {:phone :list}}]})) (deftest applied?-test (is (= true (boolean (uk/applied? {(keyword "[applied]") true})))) (is (= false (boolean (uk/applied? {}))))) (deftest applied-or-owned?-test (let [e (t/create-entity {:primary-table {:name :foos :key [:id]}}) oid (uuid/v1)] (is (= true (boolean (uk/applied-or-owned? e [oid] {(keyword "[applied]") true})))) (is (= true (boolean (uk/applied-or-owned? e [oid] {(keyword "[applied]") false :id oid})))) (is (= false (boolean (uk/applied-or-owned? e [oid] {(keyword "[applied]") false :id (uuid/v1)})))))) (deftest acquire-unique-key-test (let [_ (tu/create-table :unique_key_test "(id timeuuid primary key, nick text)") _ (tu/create-table :unique_key_test_by_nick "(nick text primary key, id timeuuid)") m (t/create-entity {:primary-table {:name :unique_key_test :key [:id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:nick]}]}) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :unique_key_test {:id ida :nick "foo"})] (testing "acquire an uncontended unique-key" (let [[status report reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} report)) (is (= :key/inserted reason)))) (testing "acquiring an already owned unique-key" (let [[status key-desc reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/owned reason)))) (testing "acquiring a stale ref" (let [;; remove the owning record so the ref is stale _ (tu/delete-record :unique_key_test :id ida) _ (tu/insert-record :unique_key_test {:id idb :nick "foo"}) [status key-desc reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [idb] {:id idb :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/updated reason)))) (testing "failing to acquire" (let [[status key-desc reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :fail status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)))))) (deftest update-unique-key-test (let [_ (tu/create-table :update_unique_key_test "(id timeuuid primary key, nick text, foo text)") _ (tu/create-table :update_unique_key_test_by_nick "(nick text primary key, id timeuuid, foo text)") m (t/create-entity {:primary-table {:name :update_unique_key_test :key [:id]} :unique-key-tables [{:name :update_unique_key_test_by_nick :key [:nick] :with-columns [:foo]}]}) [ida idb] [(uuid/v1) (uuid/v1)] initial-record {:id ida :nick "foo" :foo "foofoo"} _ (tu/insert-record :update_unique_key_test initial-record) _ (tu/insert-record :update_unique_key_test_by_nick initial-record)] (testing "noop on an already owned unique key" (let [[status key-desc reason] @(uk/update-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] initial-record initial-record (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/nochange reason)))) (testing "updating an already owned unique key" (let [[status key-desc reason] @(uk/update-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] initial-record {:id ida :nick "foo" :foo "bar"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/updated reason)))) (testing "failing to update" (let [[status key-desc reason] @(uk/update-unique-key tu/*model-session* m (-> m :unique-key-tables first) [idb] {:id idb :nick "foo" :foo "foo"} {:id idb :nick "foo" :foo "bar"} (ts/default-timestamp-opt))] (is (= :fail status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)))))) (deftest release-unique-key-test (let [_ (tu/create-table :unique_key_test "(id timeuuid primary key, nick text)") _ (tu/create-table :unique_key_test_by_nick "(nick text primary key, id timeuuid)") m (t/create-entity {:primary-table {:name :unique_key_test :key [:id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:nick]}]}) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :unique_key_test {:id ida :nick "foo"}) _ (tu/insert-record :unique_key_test_by_nick {:nick "foo" :id ida})] (testing "release an owned key" (let [[status key-desc reason] @(uk/release-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] ["foo"] (ts/default-timestamp-opt)) _ (Thread/sleep 1000) dr (fetch-record :unique_key_test_by_nick :nick "foo")] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :deleted reason)) (is (= nil dr)))) (testing "releasing a non-existing key" (let [[status key-desc reason] @(uk/release-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] ["foo"] (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :stale reason)))) (testing "attempting to release someone else's key" first give the key back to _ (tu/insert-record :unique_key_test_by_nick {:nick "foo" :id ida}) [status key-desc reason] @(uk/release-unique-key tu/*model-session* m (-> m :unique-key-tables first) [idb] ["foo"] (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :stale reason)))))) (deftest change-unique-keys-release-test (testing "singular unique key" (let [sm (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :singular_unique_key_test {:id ida :nick "foo"}) _ (tu/insert-record :singular_unique_key_test_by_nick {:nick "foo" :id ida})] (testing "release singular stale unique key" (let [{[[status key-desc reason]] :release-key-responses} @(uk/change-unique-keys tu/*model-session* sm {:id ida :nick "foo"} {:id ida :nick nil} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :deleted reason)))))) (testing "release values from set unique key" (let [cm (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :set_unique_key_test {:id ida :nick #{"foo" "bar" "baz"}}) _ (tu/insert-record :set_unique_key_test_by_nick {:nick "foo" :id ida}) _ (tu/insert-record :set_unique_key_test_by_nick {:nick "bar" :id ida})] (testing "release set stale unique key values" (let [{release-key-responses :release-key-responses} @(uk/change-unique-keys tu/*model-session* cm {:id ida :nick #{"foo" "bar" "baz"}} {:id ida :nick #{"foo"}} (ts/default-timestamp-opt))] (is (= #{[:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["bar"]} :deleted] [:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["baz"]} :stale]} (set release-key-responses)))))))) (deftest change-unique-keys-acquire-test (testing "acquire singular unique key" (let [sm (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :singular_unique_key_test {:id ida :nick "foo"})] (testing "acquire a singular unique key" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/inserted reason)))) (testing "failing to acquire a singular unique key" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id idb :nick "foo"} (ts/default-timestamp-opt))] (is (= :fail status)) (is (= {:uber-key [:id] :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)))))) (testing "acquire values in set unique key" (let [cm (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :set_unique_key_test {:id ida :nick #{"foo" "bar"}}) _ (tu/insert-record :set_unique_key_test_by_nick {:nick "foo" :id ida})] (testing "acquire values from a set of unique keys" (let [{acquire-key-responses :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* cm nil {:id ida :nick #{"foo" "bar"}} (ts/default-timestamp-opt))] (is (= #{[:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/owned] [:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["bar"]} :key/inserted]} (set acquire-key-responses)))))))) (deftest change-unique-keys-with-additional-cols-test (testing "acquire singular unique key with additional cols" (let [sm (create-singular-unique-key-entity-with-additional-cols) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :singular_unique_key_with_cols_test {:id ida :nick "foo" :stuff "blah"})] (testing "acquire a singular unique key with additional cols" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id ida :nick "foo" :stuff "bloop"} (ts/default-timestamp-opt)) r (tu/fetch-record :singular_unique_key_with_cols_test_by_nick :nick "foo")] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/inserted reason)) (is (= r {:id ida :nick "foo" :stuff "bloop"})))) (testing "update a singular unique key with additional cols" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id ida :nick "foo" :stuff "moop"} (ts/default-timestamp-opt)) r (tu/fetch-record :singular_unique_key_with_cols_test_by_nick :nick "foo")] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/owned reason)) (is (= r {:id ida :nick "foo" :stuff "moop"})))) (testing "failing to acquire a singular unique key with additional cols" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id idb :nick "foo" :stuff "blargh"} (ts/default-timestamp-opt)) r (tu/fetch-record :singular_unique_key_with_cols_test_by_nick :nick "foo")] (is (= :fail status)) (is (= {:uber-key [:id] :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)) (is (= r {:id ida :nick "foo" :stuff "moop"}))))))) (deftest update-with-acquire-responses-test (testing "removing singular unacquired value" (let [sm (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] r (uk/update-with-acquire-responses (-> sm :unique-key-tables first) [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]] {:id ida :nick "foo"})] (is (= {:id ida :nick nil} r)))) (testing "removing unacquired collection values" (let [cm (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] r (uk/update-with-acquire-responses (-> cm :unique-key-tables first) [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]] {:id ida :nick #{"foo" "bar"}})] (is (= {:id ida :nick #{"bar"}} r))))) (deftest describe-acquire-failures-test (testing "describe singular acquisition failure" (let [m (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)]] (is (= [[:key/notunique {:tag :key/notunique, :message ":nick is not unique: foo", :type :key, :primary-table :singular_unique_key_test, :uber-key-value [ida], :key [:nick], :key-value ["foo"]}]] (uk/describe-acquire-failures m {:id ida :nick "foo"} [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]]))))) (testing "describe set value acquisition failure" (let [m (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)]] (is (= [[:key/notunique {:tag :key/notunique, :message ":nick is not unique: foo", :type :key, :primary-table :set_unique_key_test, :uber-key-value [ida], :key [:nick], :key-value ["foo"]}] [:key/notunique {:tag :key/notunique, :message ":nick is not unique: bar", :type :key, :primary-table :set_unique_key_test, :uber-key-value [ida], :key [:nick], :key-value ["bar"]}]] (uk/describe-acquire-failures m {:id ida :nick #{"foo" "bar" "baz"}} [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique] [:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["bar"]} :key/notunique]])))))) (deftest responses-for-key-test (let [ida (uuid/v1)] (is (= [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]] (uk/responses-for-key [:nick] [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique] [:fail {:uber-key [:id] :uber-key-value [ida] :key [:blah] :key-value ["bar"]} :key/notunique]]))))) (deftest update-record-by-key-response-test (testing "updating record according to acquire responses" (let [m (t/create-entity {:primary-table {:name :unique_key_test :key [:id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:nick]} {:name :unique_key_test_by_email :key [:email] :collections {:email :set}}]}) ida (uuid/v1)] (is (= {:id ida :nick nil :email #{""}} (uk/update-record-by-key-responses m nil {:id ida :nick "foo" :email #{"" ""}} [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique] [:fail {:uber-key [:id] :uber-key-value [ida] :key [:email] :key-value [""]} :key/notunique]])))))) (deftest without-unique-keys-test (let [m (t/create-entity {:primary-table {:name :unique_key_test :key [:org_id :id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:org_id :nick]} {:name :unique_key_test_by_email :key [:org_id :email] :collections {:email :set}}]}) [org-id ida] [(uuid/v1) (uuid/v1)]] (is (= {:org_id org-id :id ida} (uk/without-unique-keys m {:org_id org-id :id ida :nick "foo" :email #{"" ""}}))))) (deftest upsert-primary-record-without-unique-keys-test (let [_ (tu/create-table :upsert_primary_without_unique_keys_test "(id timeuuid primary key, nick text, a text, b text)") m (t/create-entity {:primary-table {:name :upsert_primary_without_unique_keys_test :key [:id]} :unique-key-tables [{:name :upsert_primary_without_unique_keys_test_by_nick :key [:nick]}]})] (testing "simple insert" (session/reset-spy-log tu/*model-session*) (ms/-reset-model-spy-log tu/*model-session*) (let [id (uuid/v1) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt))] (is (= {:id id :a "ana" :b "anb"} r)) ;; check something actually happened (is (= :upsert_primary_without_unique_keys_test (-> (session/spy-log tu/*model-session*) first :insert))) (is (= [] (ms/-model-spy-log tu/*model-session*))))) (testing "does nothing if old-record is identical to record" (session/reset-spy-log tu/*model-session*) (ms/-reset-model-spy-log tu/*model-session*) (let [id (uuid/v1) record {:id id :nick "foo" :a "ana" :b "anb"} r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m record record (ts/default-timestamp-opt))] (is (= {:id id :a "ana" :b "anb"} r)) ;; check nothing happened (is (= [] (session/spy-log tu/*model-session*))) (is (= [] (ms/-model-spy-log tu/*model-session*))))) (testing "simple insert with a timestamp & ttl" (let [id (uuid/v1) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} {:using {:ttl 10 :timestamp 1000}}) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl) (h/as (h/cql-fn :writetime :a) :a_writetime)]})] (is (= {:id id :a "ana" :b "anb"} r)) (is (= {:id id :nick nil :a "ana" :b "anb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)) (is (some? (:a_writetime fr))) (is (> (:a_writetime fr) 5)))) (testing "update existing record" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "blah" :a "olda" :b "oldb"}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "newa"} (ts/default-timestamp-opt)) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id])] (is (= {:id id :a "newa"} r)) (is (= {:id id :a "newa" :b "oldb" :nick "blah"} fr)))) (testing "update existing record with a timestamp & ttl" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "blah" :a "olda" :b "oldb"} {:using {:ttl 10 :timestamp 1000}}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "newa"} {:using {:ttl 10 :timestamp 1001}}) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl) (h/as (h/cql-fn :writetime :a) :a_writetime)]})] (is (= {:id id :a "newa"} r)) (is (= {:id id :nick "blah" :a "newa" :b "oldb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)) (is (some? (:a_writetime fr))) (is (> (:a_writetime fr) 5)))) (testing "with if-not-exists" (let [[id id-b] [(uuid/v1) (uuid/v1)]] (testing "if it doesn't already exist" (let [r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt {:if-not-exists true}))] (is (= {:id id :a "ana" :b "anb"} r)))) (testing "with a TTL" (let [r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id-b :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt {:if-not-exists true :using {:ttl 10}})) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id-b] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl)]})] (is (= {:id id-b :a "ana" :b "anb"} r)) (is (= {:id id-b :nick nil :a "ana" :b "anb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)))) (testing "if it does already exist" (let [r @(pr/catch-error (uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt {:if-not-exists true})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error, :message "couldn't upsert primary record" :primary-table :upsert_primary_without_unique_keys_test :uber-key-value [id] :record {:id id :nick "foo" :a "ana" :b "anb"} :if-not-exists true :only-if nil}] r)))))) (testing "with only-if" (testing "if it already exists" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "bloogh" :a "olda" :b "oldb"}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "bloogh" :a "newa" :b "newb"} (ts/default-timestamp-opt {:only-if [[:= :nick "bloogh"]]}))] (is (= {:id id :a "newa" :b "newb"} r)))) (testing "if it already exists with a TTL" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "bloogh" :a "olda" :b "oldb"}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "bloogh" :a "newa" :b "newb"} (ts/default-timestamp-opt {:only-if [[:= :nick "bloogh"]] :using {:ttl 10}})) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl)]})] (is (= {:id id :a "newa" :b "newb"} r)) (is (= {:id id :nick "bloogh" :a "newa" :b "newb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)))) (testing "if it doesn't already exist" (let [id (uuid/v1) r @(pr/catch-error (uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foogle" :a "newa" :b "newb"} (ts/default-timestamp-opt {:only-if [[:= :nick "blah"]]})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error :message "couldn't upsert primary record" :primary-table :upsert_primary_without_unique_keys_test :uber-key-value [id] :record {:id id :nick "foogle" :a "newa" :b "newb"} :if-not-exists nil :only-if [[:= :nick "blah"]]}] r))))))) (deftest update-unique-keys-after-primary-upsert-test (testing "with mixed unique keys" (let [m (create-mixed-unique-key-entity) [org-id ida idb] [(uuid/v1) (uuid/v1) (uuid/v1)]] (testing "acquire some keys" (let [_ (tu/insert-record :mixed_unique_key_test {:org_id org-id :id ida :stuff "blah"}) updated-a {:org_id org-id :id ida :stuff "blah" :nick "foo" :email #{""} :phone ["123456"]} [record acquire-failures] @(uk/update-unique-keys-after-primary-upsert tu/*model-session* m {:org_id org-id :id ida} (assoc updated-a :stuff "wrong stuff") (ts/default-timestamp-opt))] ;; only unique key cols should get written (is (= (dissoc updated-a :stuff) (dissoc record :stuff))) (is (empty? acquire-failures)) (is (= updated-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]))) (is (= {:org_id org-id :id ida :nick "foo"} (fetch-record :mixed_unique_key_test_by_nick [:org_id :nick] [org-id "foo"]))) (is (= {:email "" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:phone "123456" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_phone :phone "123456"))))) (testing "mixed acquire / failure" (let [_ (tu/insert-record :mixed_unique_key_test {:org_id org-id :id idb :stuff "boo"}) [record acquire-failures] @(uk/update-unique-keys-after-primary-upsert tu/*model-session* m {:org_id org-id :id idb} {:org_id org-id :id idb :stuff "wrong stuff" ;; should not get written :nick "foo" :email #{"" "" ""} :phone ["123456" "09876" "777777"]} (ts/default-timestamp-opt)) updated-b {:org_id org-id :id idb :stuff "boo" :nick nil :email #{"" ""} :phone ["09876" "777777"]}] (is (= (dissoc updated-b :stuff) (dissoc record :stuff))) (is (= #{[:key/notunique {:tag :key/notunique, :message ":phone is not unique: 123456", :type :key, :primary-table :mixed_unique_key_test, :uber-key-value [org-id idb], :key [:phone], :key-value ["123456"]}] [:key/notunique {:tag :key/notunique, :message ":nick is not unique: foo", :type :key, :primary-table :mixed_unique_key_test, :uber-key-value [org-id idb], :key [:org_id :nick], :key-value [org-id "foo"]}] [:key/notunique {:tag :key/notunique, :message ":email is not unique: ", :type :key, :primary-table :mixed_unique_key_test, :uber-key-value [org-id idb], :key [:email], :key-value [""]}]} (set acquire-failures))) (let [fetched-b (fetch-record :mixed_unique_key_test [:org_id :id] [org-id idb])] (is (= (update updated-b :phone sort) (update fetched-b :phone sort)))) ida keys remain with (is (= {:nick "foo" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_nick [:org_id :nick] [org-id "foo"]))) (is (= {:phone "123456" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_phone :phone "123456"))) (is (= {:email "" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_email :email ""))) ;; idb gets the new keys (is (= {:phone "09876" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "09876"))) (is (= {:phone "777777" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "777777"))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email ""))))) (testing "updates and removals" (let [updated-b {:org_id org-id :id idb :stuff "boo" :nick "bar" :email #{"" ""} :phone ["777777" "111111"]} old-r (fetch-record :mixed_unique_key_test [:org_id :id] [org-id idb]) [record acquire-failures] @(uk/update-unique-keys-after-primary-upsert tu/*model-session* m old-r (assoc updated-b :stuff "more wrong stuff") (ts/default-timestamp-opt))] ;; only unique key cols should get written (is (= (dissoc updated-b :stuff) (dissoc record :stuff))) (is (empty? acquire-failures)) (is (= updated-b (fetch-record :mixed_unique_key_test [:org_id :id] [org-id idb]))) ;; stale keys (is (= nil (fetch-record :mixed_unique_key_test_by_phone :phone "09876"))) (is (= nil (fetch-record :mixed_unique_key_test_by_email :email ""))) ;; preserved and new keys (is (= {:phone "777777" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "777777"))) (is (= {:phone "111111" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "111111"))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email "")))))))) (deftest upsert-primary-record-and-update-unique-keys-test (let [m (create-mixed-unique-key-entity) [org-id ida idb] [(uuid/v1) (uuid/v1) (uuid/v1)]] (testing "success" (let [updated-a {:org_id org-id :id ida :stuff "stuff" :nick "foo" :email #{""} :phone ["123456"]} [record acquire-failures] @(uk/upsert-primary-record-and-update-unique-keys tu/*model-session* m nil updated-a (ts/default-timestamp-opt))] (is (= updated-a record)) (is (empty? acquire-failures)) (is (= updated-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]))))) (testing "if-not-exists failure" (let [old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]) updated-a {:org_id org-id :id ida :stuff "blah" :nick "foofoo" :email #{""} :phone ["12345654321"]} r @(pr/catch-error (uk/upsert-primary-record-and-update-unique-keys tu/*model-session* m nil updated-a (ts/default-timestamp-opt {:if-not-exists true})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error :message "couldn't upsert primary record" :primary-table :mixed_unique_key_test :uber-key-value [org-id ida] :record updated-a :if-not-exists true :only-if nil}] r)) (is (= old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]))))) (testing "only-if failure" (let [old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]) updated-a {:org_id org-id :id ida :stuff "wha" :nick "foofoo" :email #{""} :phone ["12345654321"]} r @(pr/catch-error (uk/upsert-primary-record-and-update-unique-keys tu/*model-session* m nil updated-a (ts/default-timestamp-opt {:only-if [[:= :nick "bar"]]})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error :message "couldn't upsert primary record" :primary-table :mixed_unique_key_test :uber-key-value [org-id ida] :record updated-a :if-not-exists nil :only-if [[:= :nick "bar"]]}] r)) (is (= old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida])))))))
null
https://raw.githubusercontent.com/yapsterapp/er-cassandra/1d059f47bdf8654c7a4dd6f0759f1a114fdeba81/test/er_cassandra/model/alia/unique_key_test.clj
clojure
remove the owning record so the ref is stale check something actually happened check nothing happened only unique key cols should get written should not get written idb gets the new keys only unique key cols should get written stale keys preserved and new keys
(ns er-cassandra.model.alia.unique-key-test (:require [er-cassandra.model.util.test :as tu :refer [fetch-record]] [clojure.test :as test :refer [deftest is are testing use-fixtures]] [schema.test :as st] [clj-uuid :as uuid] [er-cassandra.record :as r] [er-cassandra.model.util.timestamp :as ts] [er-cassandra.model.types :as t] [er-cassandra.model.alia.unique-key :as uk] [er-cassandra.model.model-session :as ms] [er-cassandra.session :as session] [qbits.hayt :as h] [prpr.promise :as pr] [taoensso.timbre :refer [warn]])) (use-fixtures :once st/validate-schemas) (use-fixtures :each (tu/with-model-session-fixture)) (defn create-singular-unique-key-entity [] (tu/create-table :singular_unique_key_test "(id timeuuid primary key, nick text)") (tu/create-table :singular_unique_key_test_by_nick "(nick text primary key, id timeuuid)") (t/create-entity {:primary-table {:name :singular_unique_key_test :key [:id]} :unique-key-tables [{:name :singular_unique_key_test_by_nick :key [:nick]}]})) (defn create-singular-unique-key-entity-with-additional-cols [] (tu/create-table :singular_unique_key_with_cols_test "(id timeuuid primary key, nick text, stuff text)") (tu/create-table :singular_unique_key_with_cols_test_by_nick "(nick text primary key, stuff text, id timeuuid)") (t/create-entity {:primary-table {:name :singular_unique_key_with_cols_test :key [:id]} :unique-key-tables [{:name :singular_unique_key_with_cols_test_by_nick :key [:nick] :with-columns [:stuff]}]})) (defn create-set-unique-key-entity [] (tu/create-table :set_unique_key_test "(id timeuuid primary key, nick set<text>)") (tu/create-table :set_unique_key_test_by_nick "(nick text primary key, id timeuuid)") (t/create-entity {:primary-table {:name :set_unique_key_test :key [:id]} :unique-key-tables [{:name :set_unique_key_test_by_nick :key [:nick] :collections {:nick :set}}]})) (defn create-mixed-unique-key-entity [] (tu/create-table :mixed_unique_key_test "(org_id timeuuid, id timeuuid, nick text, email set<text>, phone list<text>, stuff text, primary key (org_id, id))") (tu/create-table :mixed_unique_key_test_by_nick "(nick text, org_id timeuuid, id timeuuid, primary key (org_id, nick))") (tu/create-table :mixed_unique_key_test_by_email "(email text primary key, org_id timeuuid, id timeuuid)") (tu/create-table :mixed_unique_key_test_by_phone "(phone text primary key, org_id timeuuid, id timeuuid)") (t/create-entity {:primary-table {:name :mixed_unique_key_test :key [:org_id :id]} :unique-key-tables [{:name :mixed_unique_key_test_by_nick :key [:org_id :nick]} {:name :mixed_unique_key_test_by_email :key [:email] :collections {:email :set}} {:name :mixed_unique_key_test_by_phone :key [:phone] :collections {:phone :list}}]})) (deftest applied?-test (is (= true (boolean (uk/applied? {(keyword "[applied]") true})))) (is (= false (boolean (uk/applied? {}))))) (deftest applied-or-owned?-test (let [e (t/create-entity {:primary-table {:name :foos :key [:id]}}) oid (uuid/v1)] (is (= true (boolean (uk/applied-or-owned? e [oid] {(keyword "[applied]") true})))) (is (= true (boolean (uk/applied-or-owned? e [oid] {(keyword "[applied]") false :id oid})))) (is (= false (boolean (uk/applied-or-owned? e [oid] {(keyword "[applied]") false :id (uuid/v1)})))))) (deftest acquire-unique-key-test (let [_ (tu/create-table :unique_key_test "(id timeuuid primary key, nick text)") _ (tu/create-table :unique_key_test_by_nick "(nick text primary key, id timeuuid)") m (t/create-entity {:primary-table {:name :unique_key_test :key [:id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:nick]}]}) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :unique_key_test {:id ida :nick "foo"})] (testing "acquire an uncontended unique-key" (let [[status report reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} report)) (is (= :key/inserted reason)))) (testing "acquiring an already owned unique-key" (let [[status key-desc reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/owned reason)))) (testing "acquiring a stale ref" _ (tu/delete-record :unique_key_test :id ida) _ (tu/insert-record :unique_key_test {:id idb :nick "foo"}) [status key-desc reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [idb] {:id idb :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/updated reason)))) (testing "failing to acquire" (let [[status key-desc reason] @(uk/acquire-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :fail status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)))))) (deftest update-unique-key-test (let [_ (tu/create-table :update_unique_key_test "(id timeuuid primary key, nick text, foo text)") _ (tu/create-table :update_unique_key_test_by_nick "(nick text primary key, id timeuuid, foo text)") m (t/create-entity {:primary-table {:name :update_unique_key_test :key [:id]} :unique-key-tables [{:name :update_unique_key_test_by_nick :key [:nick] :with-columns [:foo]}]}) [ida idb] [(uuid/v1) (uuid/v1)] initial-record {:id ida :nick "foo" :foo "foofoo"} _ (tu/insert-record :update_unique_key_test initial-record) _ (tu/insert-record :update_unique_key_test_by_nick initial-record)] (testing "noop on an already owned unique key" (let [[status key-desc reason] @(uk/update-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] initial-record initial-record (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/nochange reason)))) (testing "updating an already owned unique key" (let [[status key-desc reason] @(uk/update-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] initial-record {:id ida :nick "foo" :foo "bar"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/updated reason)))) (testing "failing to update" (let [[status key-desc reason] @(uk/update-unique-key tu/*model-session* m (-> m :unique-key-tables first) [idb] {:id idb :nick "foo" :foo "foo"} {:id idb :nick "foo" :foo "bar"} (ts/default-timestamp-opt))] (is (= :fail status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)))))) (deftest release-unique-key-test (let [_ (tu/create-table :unique_key_test "(id timeuuid primary key, nick text)") _ (tu/create-table :unique_key_test_by_nick "(nick text primary key, id timeuuid)") m (t/create-entity {:primary-table {:name :unique_key_test :key [:id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:nick]}]}) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :unique_key_test {:id ida :nick "foo"}) _ (tu/insert-record :unique_key_test_by_nick {:nick "foo" :id ida})] (testing "release an owned key" (let [[status key-desc reason] @(uk/release-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] ["foo"] (ts/default-timestamp-opt)) _ (Thread/sleep 1000) dr (fetch-record :unique_key_test_by_nick :nick "foo")] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :deleted reason)) (is (= nil dr)))) (testing "releasing a non-existing key" (let [[status key-desc reason] @(uk/release-unique-key tu/*model-session* m (-> m :unique-key-tables first) [ida] ["foo"] (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :stale reason)))) (testing "attempting to release someone else's key" first give the key back to _ (tu/insert-record :unique_key_test_by_nick {:nick "foo" :id ida}) [status key-desc reason] @(uk/release-unique-key tu/*model-session* m (-> m :unique-key-tables first) [idb] ["foo"] (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key (t/uber-key m) :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :stale reason)))))) (deftest change-unique-keys-release-test (testing "singular unique key" (let [sm (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :singular_unique_key_test {:id ida :nick "foo"}) _ (tu/insert-record :singular_unique_key_test_by_nick {:nick "foo" :id ida})] (testing "release singular stale unique key" (let [{[[status key-desc reason]] :release-key-responses} @(uk/change-unique-keys tu/*model-session* sm {:id ida :nick "foo"} {:id ida :nick nil} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :deleted reason)))))) (testing "release values from set unique key" (let [cm (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :set_unique_key_test {:id ida :nick #{"foo" "bar" "baz"}}) _ (tu/insert-record :set_unique_key_test_by_nick {:nick "foo" :id ida}) _ (tu/insert-record :set_unique_key_test_by_nick {:nick "bar" :id ida})] (testing "release set stale unique key values" (let [{release-key-responses :release-key-responses} @(uk/change-unique-keys tu/*model-session* cm {:id ida :nick #{"foo" "bar" "baz"}} {:id ida :nick #{"foo"}} (ts/default-timestamp-opt))] (is (= #{[:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["bar"]} :deleted] [:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["baz"]} :stale]} (set release-key-responses)))))))) (deftest change-unique-keys-acquire-test (testing "acquire singular unique key" (let [sm (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :singular_unique_key_test {:id ida :nick "foo"})] (testing "acquire a singular unique key" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id ida :nick "foo"} (ts/default-timestamp-opt))] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/inserted reason)))) (testing "failing to acquire a singular unique key" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id idb :nick "foo"} (ts/default-timestamp-opt))] (is (= :fail status)) (is (= {:uber-key [:id] :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)))))) (testing "acquire values in set unique key" (let [cm (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :set_unique_key_test {:id ida :nick #{"foo" "bar"}}) _ (tu/insert-record :set_unique_key_test_by_nick {:nick "foo" :id ida})] (testing "acquire values from a set of unique keys" (let [{acquire-key-responses :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* cm nil {:id ida :nick #{"foo" "bar"}} (ts/default-timestamp-opt))] (is (= #{[:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/owned] [:ok {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["bar"]} :key/inserted]} (set acquire-key-responses)))))))) (deftest change-unique-keys-with-additional-cols-test (testing "acquire singular unique key with additional cols" (let [sm (create-singular-unique-key-entity-with-additional-cols) [ida idb] [(uuid/v1) (uuid/v1)] _ (tu/insert-record :singular_unique_key_with_cols_test {:id ida :nick "foo" :stuff "blah"})] (testing "acquire a singular unique key with additional cols" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id ida :nick "foo" :stuff "bloop"} (ts/default-timestamp-opt)) r (tu/fetch-record :singular_unique_key_with_cols_test_by_nick :nick "foo")] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/inserted reason)) (is (= r {:id ida :nick "foo" :stuff "bloop"})))) (testing "update a singular unique key with additional cols" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id ida :nick "foo" :stuff "moop"} (ts/default-timestamp-opt)) r (tu/fetch-record :singular_unique_key_with_cols_test_by_nick :nick "foo")] (is (= :ok status)) (is (= {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/owned reason)) (is (= r {:id ida :nick "foo" :stuff "moop"})))) (testing "failing to acquire a singular unique key with additional cols" (let [{[[status key-desc reason]] :acquire-key-responses} @(uk/change-unique-keys tu/*model-session* sm nil {:id idb :nick "foo" :stuff "blargh"} (ts/default-timestamp-opt)) r (tu/fetch-record :singular_unique_key_with_cols_test_by_nick :nick "foo")] (is (= :fail status)) (is (= {:uber-key [:id] :uber-key-value [idb] :key [:nick] :key-value ["foo"]} key-desc)) (is (= :key/notunique reason)) (is (= r {:id ida :nick "foo" :stuff "moop"}))))))) (deftest update-with-acquire-responses-test (testing "removing singular unacquired value" (let [sm (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] r (uk/update-with-acquire-responses (-> sm :unique-key-tables first) [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]] {:id ida :nick "foo"})] (is (= {:id ida :nick nil} r)))) (testing "removing unacquired collection values" (let [cm (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)] r (uk/update-with-acquire-responses (-> cm :unique-key-tables first) [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]] {:id ida :nick #{"foo" "bar"}})] (is (= {:id ida :nick #{"bar"}} r))))) (deftest describe-acquire-failures-test (testing "describe singular acquisition failure" (let [m (create-singular-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)]] (is (= [[:key/notunique {:tag :key/notunique, :message ":nick is not unique: foo", :type :key, :primary-table :singular_unique_key_test, :uber-key-value [ida], :key [:nick], :key-value ["foo"]}]] (uk/describe-acquire-failures m {:id ida :nick "foo"} [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]]))))) (testing "describe set value acquisition failure" (let [m (create-set-unique-key-entity) [ida idb] [(uuid/v1) (uuid/v1)]] (is (= [[:key/notunique {:tag :key/notunique, :message ":nick is not unique: foo", :type :key, :primary-table :set_unique_key_test, :uber-key-value [ida], :key [:nick], :key-value ["foo"]}] [:key/notunique {:tag :key/notunique, :message ":nick is not unique: bar", :type :key, :primary-table :set_unique_key_test, :uber-key-value [ida], :key [:nick], :key-value ["bar"]}]] (uk/describe-acquire-failures m {:id ida :nick #{"foo" "bar" "baz"}} [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique] [:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["bar"]} :key/notunique]])))))) (deftest responses-for-key-test (let [ida (uuid/v1)] (is (= [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique]] (uk/responses-for-key [:nick] [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique] [:fail {:uber-key [:id] :uber-key-value [ida] :key [:blah] :key-value ["bar"]} :key/notunique]]))))) (deftest update-record-by-key-response-test (testing "updating record according to acquire responses" (let [m (t/create-entity {:primary-table {:name :unique_key_test :key [:id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:nick]} {:name :unique_key_test_by_email :key [:email] :collections {:email :set}}]}) ida (uuid/v1)] (is (= {:id ida :nick nil :email #{""}} (uk/update-record-by-key-responses m nil {:id ida :nick "foo" :email #{"" ""}} [[:fail {:uber-key [:id] :uber-key-value [ida] :key [:nick] :key-value ["foo"]} :key/notunique] [:fail {:uber-key [:id] :uber-key-value [ida] :key [:email] :key-value [""]} :key/notunique]])))))) (deftest without-unique-keys-test (let [m (t/create-entity {:primary-table {:name :unique_key_test :key [:org_id :id]} :unique-key-tables [{:name :unique_key_test_by_nick :key [:org_id :nick]} {:name :unique_key_test_by_email :key [:org_id :email] :collections {:email :set}}]}) [org-id ida] [(uuid/v1) (uuid/v1)]] (is (= {:org_id org-id :id ida} (uk/without-unique-keys m {:org_id org-id :id ida :nick "foo" :email #{"" ""}}))))) (deftest upsert-primary-record-without-unique-keys-test (let [_ (tu/create-table :upsert_primary_without_unique_keys_test "(id timeuuid primary key, nick text, a text, b text)") m (t/create-entity {:primary-table {:name :upsert_primary_without_unique_keys_test :key [:id]} :unique-key-tables [{:name :upsert_primary_without_unique_keys_test_by_nick :key [:nick]}]})] (testing "simple insert" (session/reset-spy-log tu/*model-session*) (ms/-reset-model-spy-log tu/*model-session*) (let [id (uuid/v1) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt))] (is (= {:id id :a "ana" :b "anb"} r)) (is (= :upsert_primary_without_unique_keys_test (-> (session/spy-log tu/*model-session*) first :insert))) (is (= [] (ms/-model-spy-log tu/*model-session*))))) (testing "does nothing if old-record is identical to record" (session/reset-spy-log tu/*model-session*) (ms/-reset-model-spy-log tu/*model-session*) (let [id (uuid/v1) record {:id id :nick "foo" :a "ana" :b "anb"} r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m record record (ts/default-timestamp-opt))] (is (= {:id id :a "ana" :b "anb"} r)) (is (= [] (session/spy-log tu/*model-session*))) (is (= [] (ms/-model-spy-log tu/*model-session*))))) (testing "simple insert with a timestamp & ttl" (let [id (uuid/v1) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} {:using {:ttl 10 :timestamp 1000}}) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl) (h/as (h/cql-fn :writetime :a) :a_writetime)]})] (is (= {:id id :a "ana" :b "anb"} r)) (is (= {:id id :nick nil :a "ana" :b "anb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)) (is (some? (:a_writetime fr))) (is (> (:a_writetime fr) 5)))) (testing "update existing record" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "blah" :a "olda" :b "oldb"}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "newa"} (ts/default-timestamp-opt)) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id])] (is (= {:id id :a "newa"} r)) (is (= {:id id :a "newa" :b "oldb" :nick "blah"} fr)))) (testing "update existing record with a timestamp & ttl" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "blah" :a "olda" :b "oldb"} {:using {:ttl 10 :timestamp 1000}}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "newa"} {:using {:ttl 10 :timestamp 1001}}) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl) (h/as (h/cql-fn :writetime :a) :a_writetime)]})] (is (= {:id id :a "newa"} r)) (is (= {:id id :nick "blah" :a "newa" :b "oldb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)) (is (some? (:a_writetime fr))) (is (> (:a_writetime fr) 5)))) (testing "with if-not-exists" (let [[id id-b] [(uuid/v1) (uuid/v1)]] (testing "if it doesn't already exist" (let [r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt {:if-not-exists true}))] (is (= {:id id :a "ana" :b "anb"} r)))) (testing "with a TTL" (let [r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id-b :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt {:if-not-exists true :using {:ttl 10}})) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id-b] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl)]})] (is (= {:id id-b :a "ana" :b "anb"} r)) (is (= {:id id-b :nick nil :a "ana" :b "anb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)))) (testing "if it does already exist" (let [r @(pr/catch-error (uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foo" :a "ana" :b "anb"} (ts/default-timestamp-opt {:if-not-exists true})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error, :message "couldn't upsert primary record" :primary-table :upsert_primary_without_unique_keys_test :uber-key-value [id] :record {:id id :nick "foo" :a "ana" :b "anb"} :if-not-exists true :only-if nil}] r)))))) (testing "with only-if" (testing "if it already exists" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "bloogh" :a "olda" :b "oldb"}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "bloogh" :a "newa" :b "newb"} (ts/default-timestamp-opt {:only-if [[:= :nick "bloogh"]]}))] (is (= {:id id :a "newa" :b "newb"} r)))) (testing "if it already exists with a TTL" (let [id (uuid/v1) _ (tu/insert-record :upsert_primary_without_unique_keys_test {:id id :nick "bloogh" :a "olda" :b "oldb"}) r @(uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "bloogh" :a "newa" :b "newb"} (ts/default-timestamp-opt {:only-if [[:= :nick "bloogh"]] :using {:ttl 10}})) fr @(r/select-one tu/*model-session* :upsert_primary_without_unique_keys_test [:id] [id] {:columns [:id :nick :a :b (h/as (h/cql-fn :ttl :a) :a_ttl)]})] (is (= {:id id :a "newa" :b "newb"} r)) (is (= {:id id :nick "bloogh" :a "newa" :b "newb"} (select-keys fr [:id :nick :a :b]))) (is (some? (:a_ttl fr))) (is (> (:a_ttl fr) 5)))) (testing "if it doesn't already exist" (let [id (uuid/v1) r @(pr/catch-error (uk/upsert-primary-record-without-unique-keys tu/*model-session* m nil {:id id :nick "foogle" :a "newa" :b "newb"} (ts/default-timestamp-opt {:only-if [[:= :nick "blah"]]})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error :message "couldn't upsert primary record" :primary-table :upsert_primary_without_unique_keys_test :uber-key-value [id] :record {:id id :nick "foogle" :a "newa" :b "newb"} :if-not-exists nil :only-if [[:= :nick "blah"]]}] r))))))) (deftest update-unique-keys-after-primary-upsert-test (testing "with mixed unique keys" (let [m (create-mixed-unique-key-entity) [org-id ida idb] [(uuid/v1) (uuid/v1) (uuid/v1)]] (testing "acquire some keys" (let [_ (tu/insert-record :mixed_unique_key_test {:org_id org-id :id ida :stuff "blah"}) updated-a {:org_id org-id :id ida :stuff "blah" :nick "foo" :email #{""} :phone ["123456"]} [record acquire-failures] @(uk/update-unique-keys-after-primary-upsert tu/*model-session* m {:org_id org-id :id ida} (assoc updated-a :stuff "wrong stuff") (ts/default-timestamp-opt))] (is (= (dissoc updated-a :stuff) (dissoc record :stuff))) (is (empty? acquire-failures)) (is (= updated-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]))) (is (= {:org_id org-id :id ida :nick "foo"} (fetch-record :mixed_unique_key_test_by_nick [:org_id :nick] [org-id "foo"]))) (is (= {:email "" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:phone "123456" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_phone :phone "123456"))))) (testing "mixed acquire / failure" (let [_ (tu/insert-record :mixed_unique_key_test {:org_id org-id :id idb :stuff "boo"}) [record acquire-failures] @(uk/update-unique-keys-after-primary-upsert tu/*model-session* m {:org_id org-id :id idb} {:org_id org-id :id idb :nick "foo" :email #{"" "" ""} :phone ["123456" "09876" "777777"]} (ts/default-timestamp-opt)) updated-b {:org_id org-id :id idb :stuff "boo" :nick nil :email #{"" ""} :phone ["09876" "777777"]}] (is (= (dissoc updated-b :stuff) (dissoc record :stuff))) (is (= #{[:key/notunique {:tag :key/notunique, :message ":phone is not unique: 123456", :type :key, :primary-table :mixed_unique_key_test, :uber-key-value [org-id idb], :key [:phone], :key-value ["123456"]}] [:key/notunique {:tag :key/notunique, :message ":nick is not unique: foo", :type :key, :primary-table :mixed_unique_key_test, :uber-key-value [org-id idb], :key [:org_id :nick], :key-value [org-id "foo"]}] [:key/notunique {:tag :key/notunique, :message ":email is not unique: ", :type :key, :primary-table :mixed_unique_key_test, :uber-key-value [org-id idb], :key [:email], :key-value [""]}]} (set acquire-failures))) (let [fetched-b (fetch-record :mixed_unique_key_test [:org_id :id] [org-id idb])] (is (= (update updated-b :phone sort) (update fetched-b :phone sort)))) ida keys remain with (is (= {:nick "foo" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_nick [:org_id :nick] [org-id "foo"]))) (is (= {:phone "123456" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_phone :phone "123456"))) (is (= {:email "" :org_id org-id :id ida} (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:phone "09876" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "09876"))) (is (= {:phone "777777" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "777777"))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email ""))))) (testing "updates and removals" (let [updated-b {:org_id org-id :id idb :stuff "boo" :nick "bar" :email #{"" ""} :phone ["777777" "111111"]} old-r (fetch-record :mixed_unique_key_test [:org_id :id] [org-id idb]) [record acquire-failures] @(uk/update-unique-keys-after-primary-upsert tu/*model-session* m old-r (assoc updated-b :stuff "more wrong stuff") (ts/default-timestamp-opt))] (is (= (dissoc updated-b :stuff) (dissoc record :stuff))) (is (empty? acquire-failures)) (is (= updated-b (fetch-record :mixed_unique_key_test [:org_id :id] [org-id idb]))) (is (= nil (fetch-record :mixed_unique_key_test_by_phone :phone "09876"))) (is (= nil (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:phone "777777" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "777777"))) (is (= {:phone "111111" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_phone :phone "111111"))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email ""))) (is (= {:email "" :org_id org-id :id idb} (fetch-record :mixed_unique_key_test_by_email :email "")))))))) (deftest upsert-primary-record-and-update-unique-keys-test (let [m (create-mixed-unique-key-entity) [org-id ida idb] [(uuid/v1) (uuid/v1) (uuid/v1)]] (testing "success" (let [updated-a {:org_id org-id :id ida :stuff "stuff" :nick "foo" :email #{""} :phone ["123456"]} [record acquire-failures] @(uk/upsert-primary-record-and-update-unique-keys tu/*model-session* m nil updated-a (ts/default-timestamp-opt))] (is (= updated-a record)) (is (empty? acquire-failures)) (is (= updated-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]))))) (testing "if-not-exists failure" (let [old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]) updated-a {:org_id org-id :id ida :stuff "blah" :nick "foofoo" :email #{""} :phone ["12345654321"]} r @(pr/catch-error (uk/upsert-primary-record-and-update-unique-keys tu/*model-session* m nil updated-a (ts/default-timestamp-opt {:if-not-exists true})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error :message "couldn't upsert primary record" :primary-table :mixed_unique_key_test :uber-key-value [org-id ida] :record updated-a :if-not-exists true :only-if nil}] r)) (is (= old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]))))) (testing "only-if failure" (let [old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida]) updated-a {:org_id org-id :id ida :stuff "wha" :nick "foofoo" :email #{""} :phone ["12345654321"]} r @(pr/catch-error (uk/upsert-primary-record-and-update-unique-keys tu/*model-session* m nil updated-a (ts/default-timestamp-opt {:only-if [[:= :nick "bar"]]})))] (is (= [:upsert/primary-record-upsert-error {:error-tag :upsert/primary-record-upsert-error :message "couldn't upsert primary record" :primary-table :mixed_unique_key_test :uber-key-value [org-id ida] :record updated-a :if-not-exists nil :only-if [[:= :nick "bar"]]}] r)) (is (= old-a (fetch-record :mixed_unique_key_test [:org_id :id] [org-id ida])))))))
538ad5191d77fb6b6c8927a7a1dee9580609ac093d4bd87061f066da22336773
ocaml-obuild/obuild
filetype.ml
open Ext.Filepath type t = FileML | FileMLI | FileH | FileC | FileCMX | FileCMO | FileCMI | FileCMA | FileCMXA | FileCMXS | FileCMT | FileCMTI | FileO | FileA | FileSO | FileEXE | FileOther of string let of_string s = match s with | "ml" -> FileML | "mli" -> FileMLI | "h" -> FileH | "c" -> FileC | "cmx" -> FileCMX | "cmo" -> FileCMO | "cmi" -> FileCMI | "cma" -> FileCMA | "cmxa" -> FileCMXA | "cmxs" -> FileCMXS | "cmt" -> FileCMT | "cmti" -> FileCMTI | "o" -> FileO | "a" -> FileA | "so" -> FileSO | "exe" -> FileEXE | _ -> FileOther s let to_string fty = match fty with | FileML -> "ml" | FileMLI -> "mli" | FileH -> "h" | FileC -> "c" | FileCMX -> "cmx" | FileCMO -> "cmo" | FileCMI -> "cmi" | FileCMA -> "cma" | FileCMXA -> "cmxa" | FileCMXS -> "cmxs" | FileCMT -> "cmt" | FileCMTI -> "cmti" | FileO -> "o" | FileA -> "a" | FileSO -> "so" | FileEXE -> "exe" | FileOther s -> s type id = { fdep_ty : t; fdep_path : filepath } let make_id (ty,p) = { fdep_ty = ty; fdep_path = p } let get_id fdep = (fdep.fdep_ty, fdep.fdep_path) let get_type fdep = fdep.fdep_ty let get_path fdep = fdep.fdep_path let of_filename (name : filename) : t = try let nameUnpack = fn_to_string name in let len = String.length (Filename.chop_extension nameUnpack) in (* +1 to remove the dot *) of_string (String.sub nameUnpack (len+1) (String.length nameUnpack - len - 1)) with Invalid_argument _ -> FileEXE (* best effort, suit our case for unix *) let of_filepath (path : filepath) : t = of_filename (path_basename path) let replace_extension (name:filename) ext = let extStr = to_string ext in try let choppedName = Filename.chop_extension (fn_to_string name) in fn (String.concat "." [ choppedName; extStr ]) with Invalid_argument _ -> fn (fn_to_string name ^ "." ^ extStr) let replace_extension_path path ext = let dir = path_dirname path in dir </> replace_extension (path_basename path) ext
null
https://raw.githubusercontent.com/ocaml-obuild/obuild/28252e8cee836448e85bfbc9e09a44e7674dae39/obuild/filetype.ml
ocaml
+1 to remove the dot best effort, suit our case for unix
open Ext.Filepath type t = FileML | FileMLI | FileH | FileC | FileCMX | FileCMO | FileCMI | FileCMA | FileCMXA | FileCMXS | FileCMT | FileCMTI | FileO | FileA | FileSO | FileEXE | FileOther of string let of_string s = match s with | "ml" -> FileML | "mli" -> FileMLI | "h" -> FileH | "c" -> FileC | "cmx" -> FileCMX | "cmo" -> FileCMO | "cmi" -> FileCMI | "cma" -> FileCMA | "cmxa" -> FileCMXA | "cmxs" -> FileCMXS | "cmt" -> FileCMT | "cmti" -> FileCMTI | "o" -> FileO | "a" -> FileA | "so" -> FileSO | "exe" -> FileEXE | _ -> FileOther s let to_string fty = match fty with | FileML -> "ml" | FileMLI -> "mli" | FileH -> "h" | FileC -> "c" | FileCMX -> "cmx" | FileCMO -> "cmo" | FileCMI -> "cmi" | FileCMA -> "cma" | FileCMXA -> "cmxa" | FileCMXS -> "cmxs" | FileCMT -> "cmt" | FileCMTI -> "cmti" | FileO -> "o" | FileA -> "a" | FileSO -> "so" | FileEXE -> "exe" | FileOther s -> s type id = { fdep_ty : t; fdep_path : filepath } let make_id (ty,p) = { fdep_ty = ty; fdep_path = p } let get_id fdep = (fdep.fdep_ty, fdep.fdep_path) let get_type fdep = fdep.fdep_ty let get_path fdep = fdep.fdep_path let of_filename (name : filename) : t = try let nameUnpack = fn_to_string name in let len = String.length (Filename.chop_extension nameUnpack) in of_string (String.sub nameUnpack (len+1) (String.length nameUnpack - len - 1)) let of_filepath (path : filepath) : t = of_filename (path_basename path) let replace_extension (name:filename) ext = let extStr = to_string ext in try let choppedName = Filename.chop_extension (fn_to_string name) in fn (String.concat "." [ choppedName; extStr ]) with Invalid_argument _ -> fn (fn_to_string name ^ "." ^ extStr) let replace_extension_path path ext = let dir = path_dirname path in dir </> replace_extension (path_basename path) ext
8dbfbc4fc13e77e20a1cf439a893223746898452df3848dea367ae4f5665d24d
amnh/PCG
Converter.hs
----------------------------------------------------------------------------- -- | -- Module : File.Format.Fasta.Converter Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Functions for interpreting and converting parsed abiguous FASTA sequences. -- ----------------------------------------------------------------------------- {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # {-# LANGUAGE TypeFamilies #-} # LANGUAGE UnboxedSums # module File.Format.Fasta.Converter ( FastaSequenceType(..) , fastaStreamConverter ) where import Control.DeepSeq import Data.Alphabet.IUPAC import Data.Bimap (Bimap) import qualified Data.Bimap as BM import Data.Data import Data.List (intercalate) import Data.List.NonEmpty (NonEmpty(..)) import Data.Map hiding (filter, foldr, (!)) import Data.String import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Data.Text.Short (ShortText, toString) import qualified Data.Vector.NonEmpty as VNE import Data.Vector.Unboxed (Vector, (!)) import qualified Data.Vector.Unboxed as V (filter, length, map, null, toList) import Data.Void import File.Format.Fasta.Internal import File.Format.Fasta.Parser import GHC.Generics import Text.Megaparsec (MonadParsec, Parsec) import Text.Megaparsec.Custom (fails) -- | -- Different forms a 'FastaSequence' can be interpreted as. data FastaSequenceType = DNA | RNA | AminoAcid deriving stock (Data, Bounded, Eq, Enum, Generic, Read, Show, Typeable) deriving anyclass (NFData) -- | Define and convert a ' FastaParseResult ' to the expected sequence type {-# INLINEABLE fastaStreamConverter #-} # SPECIALISE fastaStreamConverter : : FastaSequenceType - > FastaParseResult - > Parsec Void T.Text TaxonSequenceMap # # SPECIALISE fastaStreamConverter : : FastaSequenceType - > FastaParseResult - > Parsec Void LT.Text TaxonSequenceMap # # SPECIALISE fastaStreamConverter : : FastaSequenceType - > FastaParseResult - > Parsec Void String TaxonSequenceMap # fastaStreamConverter :: MonadParsec e s m => FastaSequenceType -> FastaParseResult -> m TaxonSequenceMap fastaStreamConverter seqType = fmap (colate seqType) . validateStreamConversion seqType . processedChars seqType -- | Since Bimap 's are bijective , and there are some elements of the range that are -- not surjectively mapped to from the domain ( ie , more than one element on the left side goes to an element on the right side ) , -- this means that we must preprocess these element so that there is a bijective mapping. # INLINE processedChars # processedChars :: FastaSequenceType -> FastaParseResult -> FastaParseResult processedChars seqType = fmap processElement where processElement :: FastaSequence -> FastaSequence processElement (FastaSequence name chars) = FastaSequence name $ replaceSymbol chars replaceSymbol :: Vector Char -> Vector Char replaceSymbol = case seqType of AminoAcid -> replace 'U' 'C' . replace '.' '-' DNA -> replace 'n' '?' . replace '.' '-' RNA -> replace 'n' '?' . replace '.' '-' replace :: Char -> Char -> Vector Char -> Vector Char replace a b = V.map $ \x -> if a == x then b else x -- | Validates that the stream contains a ' FastaParseResult ' of the given ' FastaSequenceType ' . # INLINE validateStreamConversion # # validateStreamConversion : : FastaSequenceType - > FastaParseResult - > Parsec Void T.Text FastaParseResult # # validateStreamConversion : : FastaSequenceType - > FastaParseResult - > Parsec Void LT.Text FastaParseResult # # validateStreamConversion : : FastaSequenceType - > FastaParseResult - > Parsec Void String FastaParseResult # validateStreamConversion :: MonadParsec e s m => FastaSequenceType -> FastaParseResult -> m FastaParseResult validateStreamConversion seqType xs = case filter hasErrors result of [] -> pure xs err -> fails $ errorMessage <$> err where result = containsIncorrectChars <$> xs hasErrors = not . V.null . snd containsIncorrectChars (FastaSequence name chars) = (name, f chars) f = V.filter ((`notElem` s) . pure . pure) where s = keysSet $ BM.toMap bm bm :: Bimap (NonEmpty String) (NonEmpty String) bm = case seqType of AminoAcid -> iupacToAminoAcid DNA -> iupacToDna RNA -> iupacToRna errorMessage (name, badChars) = concat [ "In the sequence for taxon: '" , toString name , "' the following invalid characters were found: " , intercalate ", " $ enquote <$> V.toList badChars ] enquote c = '\'' : c : "'" -- | Interprets and converts an entire ' FastaParseResult according to the given ' FastaSequenceType ' . # INLINE colate # colate :: FastaSequenceType -> FastaParseResult -> TaxonSequenceMap colate seqType = foldr f empty where f (FastaSequence name seq') = insert name (seqCharMapping seqType seq') -- | Interprets and converts an ambiguous sequence according to the given ' FastaSequenceType ' from the ambiguous form to a ' CharacterSequence ' based on IUPAC codes . # INLINE seqCharMapping # seqCharMapping :: FastaSequenceType -> Vector Char -> CharacterSequence seqCharMapping seqType v = transformVector where transformVector = VNE.unfoldr g 0 n = V.length v g :: Int -> (VNE.Vector ShortText, Maybe Int) g !i = let e = force . f seqType $ v ! i in (e, if i >= n then Nothing else Just $ i + 1) f :: FastaSequenceType -> Char -> VNE.Vector ShortText f t c = let ne = [c]:|[] bm = case t of AminoAcid -> iupacToAminoAcid DNA -> iupacToDna RNA -> iupacToRna in force . VNE.fromNonEmpty . fmap fromString $ bm BM.! ne
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/file-parsers/src/File/Format/Fasta/Converter.hs
haskell
--------------------------------------------------------------------------- | Module : File.Format.Fasta.Converter License : BSD-style Maintainer : Stability : provisional Portability : portable Functions for interpreting and converting parsed abiguous FASTA sequences. --------------------------------------------------------------------------- # LANGUAGE BangPatterns # # LANGUAGE DeriveAnyClass # # LANGUAGE DeriveDataTypeable # # LANGUAGE TypeFamilies # | Different forms a 'FastaSequence' can be interpreted as. | # INLINEABLE fastaStreamConverter # | not surjectively mapped to from the domain this means that we must preprocess these element so that there is a bijective mapping. | | |
Copyright : ( c ) 2015 - 2021 Ward Wheeler # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE UnboxedSums # module File.Format.Fasta.Converter ( FastaSequenceType(..) , fastaStreamConverter ) where import Control.DeepSeq import Data.Alphabet.IUPAC import Data.Bimap (Bimap) import qualified Data.Bimap as BM import Data.Data import Data.List (intercalate) import Data.List.NonEmpty (NonEmpty(..)) import Data.Map hiding (filter, foldr, (!)) import Data.String import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Data.Text.Short (ShortText, toString) import qualified Data.Vector.NonEmpty as VNE import Data.Vector.Unboxed (Vector, (!)) import qualified Data.Vector.Unboxed as V (filter, length, map, null, toList) import Data.Void import File.Format.Fasta.Internal import File.Format.Fasta.Parser import GHC.Generics import Text.Megaparsec (MonadParsec, Parsec) import Text.Megaparsec.Custom (fails) data FastaSequenceType = DNA | RNA | AminoAcid deriving stock (Data, Bounded, Eq, Enum, Generic, Read, Show, Typeable) deriving anyclass (NFData) Define and convert a ' FastaParseResult ' to the expected sequence type # SPECIALISE fastaStreamConverter : : FastaSequenceType - > FastaParseResult - > Parsec Void T.Text TaxonSequenceMap # # SPECIALISE fastaStreamConverter : : FastaSequenceType - > FastaParseResult - > Parsec Void LT.Text TaxonSequenceMap # # SPECIALISE fastaStreamConverter : : FastaSequenceType - > FastaParseResult - > Parsec Void String TaxonSequenceMap # fastaStreamConverter :: MonadParsec e s m => FastaSequenceType -> FastaParseResult -> m TaxonSequenceMap fastaStreamConverter seqType = fmap (colate seqType) . validateStreamConversion seqType . processedChars seqType Since Bimap 's are bijective , and there are some elements of the range that are ( ie , more than one element on the left side goes to an element on the right side ) , # INLINE processedChars # processedChars :: FastaSequenceType -> FastaParseResult -> FastaParseResult processedChars seqType = fmap processElement where processElement :: FastaSequence -> FastaSequence processElement (FastaSequence name chars) = FastaSequence name $ replaceSymbol chars replaceSymbol :: Vector Char -> Vector Char replaceSymbol = case seqType of AminoAcid -> replace 'U' 'C' . replace '.' '-' DNA -> replace 'n' '?' . replace '.' '-' RNA -> replace 'n' '?' . replace '.' '-' replace :: Char -> Char -> Vector Char -> Vector Char replace a b = V.map $ \x -> if a == x then b else x Validates that the stream contains a ' FastaParseResult ' of the given ' FastaSequenceType ' . # INLINE validateStreamConversion # # validateStreamConversion : : FastaSequenceType - > FastaParseResult - > Parsec Void T.Text FastaParseResult # # validateStreamConversion : : FastaSequenceType - > FastaParseResult - > Parsec Void LT.Text FastaParseResult # # validateStreamConversion : : FastaSequenceType - > FastaParseResult - > Parsec Void String FastaParseResult # validateStreamConversion :: MonadParsec e s m => FastaSequenceType -> FastaParseResult -> m FastaParseResult validateStreamConversion seqType xs = case filter hasErrors result of [] -> pure xs err -> fails $ errorMessage <$> err where result = containsIncorrectChars <$> xs hasErrors = not . V.null . snd containsIncorrectChars (FastaSequence name chars) = (name, f chars) f = V.filter ((`notElem` s) . pure . pure) where s = keysSet $ BM.toMap bm bm :: Bimap (NonEmpty String) (NonEmpty String) bm = case seqType of AminoAcid -> iupacToAminoAcid DNA -> iupacToDna RNA -> iupacToRna errorMessage (name, badChars) = concat [ "In the sequence for taxon: '" , toString name , "' the following invalid characters were found: " , intercalate ", " $ enquote <$> V.toList badChars ] enquote c = '\'' : c : "'" Interprets and converts an entire ' FastaParseResult according to the given ' FastaSequenceType ' . # INLINE colate # colate :: FastaSequenceType -> FastaParseResult -> TaxonSequenceMap colate seqType = foldr f empty where f (FastaSequence name seq') = insert name (seqCharMapping seqType seq') Interprets and converts an ambiguous sequence according to the given ' FastaSequenceType ' from the ambiguous form to a ' CharacterSequence ' based on IUPAC codes . # INLINE seqCharMapping # seqCharMapping :: FastaSequenceType -> Vector Char -> CharacterSequence seqCharMapping seqType v = transformVector where transformVector = VNE.unfoldr g 0 n = V.length v g :: Int -> (VNE.Vector ShortText, Maybe Int) g !i = let e = force . f seqType $ v ! i in (e, if i >= n then Nothing else Just $ i + 1) f :: FastaSequenceType -> Char -> VNE.Vector ShortText f t c = let ne = [c]:|[] bm = case t of AminoAcid -> iupacToAminoAcid DNA -> iupacToDna RNA -> iupacToRna in force . VNE.fromNonEmpty . fmap fromString $ bm BM.! ne
aee5a7d4e168f3c96eb8fa63f8cca529a44bd512a8a194b0023a73e0a013f3b5
HaskellCNOrg/snaplet-oauth
Splices.hs
{-# LANGUAGE OverloadedStrings #-} module Splices where import Snap.Snaplet.OAuth import Text.Templating.Heist ---------------------------------------------------------------------- -- Splices ---------------------------------------------------------------------- rawResponseSplices :: (Monad m, Show a) => a -> Splice m rawResponseSplices = textSplice . sToText bindRawResponseSplices :: (Monad m, Show a) => a -> HeistState m -> HeistState m bindRawResponseSplices value = bindSplice "rawResponseSplices" (rawResponseSplices value)
null
https://raw.githubusercontent.com/HaskellCNOrg/snaplet-oauth/17318ef528512370b892b6cb91de7c5e6e1d7814/example/src/Splices.hs
haskell
# LANGUAGE OverloadedStrings # -------------------------------------------------------------------- Splices --------------------------------------------------------------------
module Splices where import Snap.Snaplet.OAuth import Text.Templating.Heist rawResponseSplices :: (Monad m, Show a) => a -> Splice m rawResponseSplices = textSplice . sToText bindRawResponseSplices :: (Monad m, Show a) => a -> HeistState m -> HeistState m bindRawResponseSplices value = bindSplice "rawResponseSplices" (rawResponseSplices value)
d29cb9682e57d215fca60b95d2444168c3ad1c51e55518853373a00a3310f81c
melange-re/melange
js_name_of_module_id.ml
Copyright ( C ) 2017 , Authors of ReScript * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let ( ( x : int ) ( y : float ) = assert false let (=) (x : int) (y:float) = assert false *) let ( // ) = Filename.concat let fix_path_for_windows : string -> string = if Ext_sys.is_windows_or_cygwin then Ext_string.replace_backward_slash else fun s -> s let js_file_name ~(path_info : Js_packages_info.path_info) ~case ~suffix (dep_module_id : Lam_module_ident.t) = let module_name = match path_info.module_name with | Some module_name -> module_name | None -> Ident.name dep_module_id.id in Ext_namespace.js_name_of_modulename module_name case suffix (* dependency is runtime module *) let get_runtime_module_path ~package_info ~output_info (dep_module_id : Lam_module_ident.t) = let { Js_packages_info.module_system; suffix } = output_info in let suffix = if !Js_config.bs_legacy then match module_system with | NodeJS -> Ext_js_suffix.Js | Es6 | Es6_global -> Mjs else suffix in let js_file = Ext_namespace.js_name_of_modulename (Ident.name dep_module_id.id) Lowercase suffix in match Js_packages_info.query_package_infos package_info module_system with | Package_not_found -> assert false | Package_script -> Ext_module_system.runtime_package_path ~legacy:!Js_config.bs_legacy module_system js_file | Package_found path_info -> ( match Js_packages_info.Legacy_runtime.is_runtime_package package_info with | true -> (* Runtime files end up in the same directory, `lib/js` or `lib/es6` *) Ext_path.node_rebase_file ~from:path_info.rel_path ~to_:path_info.rel_path js_file | false -> ( match module_system with | NodeJS | Es6 -> Ext_module_system.runtime_package_path ~legacy:!Js_config.bs_legacy module_system js_file Note we did a post - processing when working on Windows | Es6_global -> (* lib/ocaml/xx.cmj -- HACKING: FIXME maybe we can caching relative package path calculation or employ package map *) let dep_path = Literals.lib // Ext_module_system.runtime_dir module_system in Ext_path.rel_normalized_absolute_path ~from: (Js_packages_info.get_output_dir package_info ~package_dir:(Lazy.force Ext_path.package_dir) module_system) (*Invariant: the package path to bs-platform, it is used to calculate relative js path *) (match !Js_config.customize_runtime with | None -> Filename.dirname (Filename.dirname Sys.executable_name) // dep_path // js_file | Some path -> path // dep_path // js_file))) [ output_dir ] is decided by the command line argument let string_of_module_id ~package_info ~output_info (dep_module_id : Lam_module_ident.t) ~(output_dir : string) : string = let { Js_packages_info.module_system; suffix } = output_info in fix_path_for_windows (match dep_module_id.kind with | External { name } -> name (* the literal string for external package *) This may not be enough , 1 . For cross packages , we may need settle down a single js package 2 . We may need es6 path for dead code elimination But frankly , very few JS packages have no dependency , so having plugin may sound not that bad 1. For cross packages, we may need settle down a single js package 2. We may need es6 path for dead code elimination But frankly, very few JS packages have no dependency, so having plugin may sound not that bad *) | Runtime -> get_runtime_module_path ~package_info ~output_info dep_module_id | Ml -> ( let package_path, dep_package_info, case = Lam_compile_env.get_package_path_from_cmj dep_module_id in match ( Js_packages_info.query_package_infos dep_package_info module_system, Js_packages_info.query_package_infos package_info module_system ) with | _, Package_not_found -> (* Impossible to not find the current package. *) assert false | Package_not_found, _ -> Bs_exception.error (Missing_ml_dependency (Ident.name dep_module_id.id)) | Package_script, Package_found _ -> Bs_exception.error (Dependency_script_module_dependent_not (Ident.name dep_module_id.id)) | Package_found path_info, Package_script -> let js_file = js_file_name ~case ~suffix ~path_info dep_module_id in path_info.pkg_rel_path // js_file | Package_found dep_info, Package_found cur_pkg -> ( let js_file = js_file_name ~case ~suffix ~path_info:dep_info dep_module_id in match Js_packages_info.Legacy_runtime.is_runtime_package package_info with | true -> (* If we're compiling the melange runtime, get a runtime module path. *) get_runtime_module_path ~package_info ~output_info dep_module_id | false -> ( match Js_packages_info.same_package_by_name package_info dep_package_info with | true -> (* If this is the same package, we know all imports are relative. *) Ext_path.node_rebase_file ~from:cur_pkg.rel_path ~to_:dep_info.rel_path js_file | false -> ( if (* Importing a dependency: * - are we importing the melange runtime / stdlib? *) Js_packages_info.Legacy_runtime.is_runtime_package dep_package_info then get_runtime_module_path ~package_info ~output_info dep_module_id else (* - Are we importing another package? *) match module_system with | NodeJS | Es6 -> dep_info.pkg_rel_path // js_file Note we did a post - processing when working on Windows | Es6_global -> Ext_path.rel_normalized_absolute_path ~from: (Js_packages_info.get_output_dir package_info ~package_dir:(Lazy.force Ext_path.package_dir) module_system) (package_path // dep_info.rel_path // js_file)))) | Package_script, Package_script -> ( let js_file = Ext_namespace.js_name_of_modulename (Ident.name dep_module_id.id) case Js in match Config_util.find_opt js_file with | Some file -> let basename = Filename.basename file in let dirname = Filename.dirname file in Ext_path.node_rebase_file ~from:(Ext_path.absolute_cwd_path output_dir) ~to_:(Ext_path.absolute_cwd_path dirname) basename | None -> Bs_exception.error (Js_not_found js_file)))) ;; (* Override it in browser *) #ifdef BS_BROWSER let string_of_module_id_in_browser (x : Lam_module_ident.t) = match x.kind with | External { name } -> name | Runtime | Ml -> "./stdlib/" ^ Ext_string.uncapitalize_ascii x.id.name ^ ".js" let string_of_module_id ~package_info:_ ~output_info:_ (id : Lam_module_ident.t) ~output_dir:(_ : string) : string = string_of_module_id_in_browser id ;; #endif
null
https://raw.githubusercontent.com/melange-re/melange/47a2971b65d5abf996457bdcc9fc483bdb9551e6/jscomp/core/js_name_of_module_id.ml
ocaml
dependency is runtime module Runtime files end up in the same directory, `lib/js` or `lib/es6` lib/ocaml/xx.cmj -- HACKING: FIXME maybe we can caching relative package path calculation or employ package map Invariant: the package path to bs-platform, it is used to calculate relative js path the literal string for external package Impossible to not find the current package. If we're compiling the melange runtime, get a runtime module path. If this is the same package, we know all imports are relative. Importing a dependency: * - are we importing the melange runtime / stdlib? - Are we importing another package? Override it in browser
Copyright ( C ) 2017 , Authors of ReScript * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let ( ( x : int ) ( y : float ) = assert false let (=) (x : int) (y:float) = assert false *) let ( // ) = Filename.concat let fix_path_for_windows : string -> string = if Ext_sys.is_windows_or_cygwin then Ext_string.replace_backward_slash else fun s -> s let js_file_name ~(path_info : Js_packages_info.path_info) ~case ~suffix (dep_module_id : Lam_module_ident.t) = let module_name = match path_info.module_name with | Some module_name -> module_name | None -> Ident.name dep_module_id.id in Ext_namespace.js_name_of_modulename module_name case suffix let get_runtime_module_path ~package_info ~output_info (dep_module_id : Lam_module_ident.t) = let { Js_packages_info.module_system; suffix } = output_info in let suffix = if !Js_config.bs_legacy then match module_system with | NodeJS -> Ext_js_suffix.Js | Es6 | Es6_global -> Mjs else suffix in let js_file = Ext_namespace.js_name_of_modulename (Ident.name dep_module_id.id) Lowercase suffix in match Js_packages_info.query_package_infos package_info module_system with | Package_not_found -> assert false | Package_script -> Ext_module_system.runtime_package_path ~legacy:!Js_config.bs_legacy module_system js_file | Package_found path_info -> ( match Js_packages_info.Legacy_runtime.is_runtime_package package_info with | true -> Ext_path.node_rebase_file ~from:path_info.rel_path ~to_:path_info.rel_path js_file | false -> ( match module_system with | NodeJS | Es6 -> Ext_module_system.runtime_package_path ~legacy:!Js_config.bs_legacy module_system js_file Note we did a post - processing when working on Windows | Es6_global -> let dep_path = Literals.lib // Ext_module_system.runtime_dir module_system in Ext_path.rel_normalized_absolute_path ~from: (Js_packages_info.get_output_dir package_info ~package_dir:(Lazy.force Ext_path.package_dir) module_system) (match !Js_config.customize_runtime with | None -> Filename.dirname (Filename.dirname Sys.executable_name) // dep_path // js_file | Some path -> path // dep_path // js_file))) [ output_dir ] is decided by the command line argument let string_of_module_id ~package_info ~output_info (dep_module_id : Lam_module_ident.t) ~(output_dir : string) : string = let { Js_packages_info.module_system; suffix } = output_info in fix_path_for_windows (match dep_module_id.kind with This may not be enough , 1 . For cross packages , we may need settle down a single js package 2 . We may need es6 path for dead code elimination But frankly , very few JS packages have no dependency , so having plugin may sound not that bad 1. For cross packages, we may need settle down a single js package 2. We may need es6 path for dead code elimination But frankly, very few JS packages have no dependency, so having plugin may sound not that bad *) | Runtime -> get_runtime_module_path ~package_info ~output_info dep_module_id | Ml -> ( let package_path, dep_package_info, case = Lam_compile_env.get_package_path_from_cmj dep_module_id in match ( Js_packages_info.query_package_infos dep_package_info module_system, Js_packages_info.query_package_infos package_info module_system ) with | _, Package_not_found -> assert false | Package_not_found, _ -> Bs_exception.error (Missing_ml_dependency (Ident.name dep_module_id.id)) | Package_script, Package_found _ -> Bs_exception.error (Dependency_script_module_dependent_not (Ident.name dep_module_id.id)) | Package_found path_info, Package_script -> let js_file = js_file_name ~case ~suffix ~path_info dep_module_id in path_info.pkg_rel_path // js_file | Package_found dep_info, Package_found cur_pkg -> ( let js_file = js_file_name ~case ~suffix ~path_info:dep_info dep_module_id in match Js_packages_info.Legacy_runtime.is_runtime_package package_info with | true -> get_runtime_module_path ~package_info ~output_info dep_module_id | false -> ( match Js_packages_info.same_package_by_name package_info dep_package_info with | true -> Ext_path.node_rebase_file ~from:cur_pkg.rel_path ~to_:dep_info.rel_path js_file | false -> ( if Js_packages_info.Legacy_runtime.is_runtime_package dep_package_info then get_runtime_module_path ~package_info ~output_info dep_module_id else match module_system with | NodeJS | Es6 -> dep_info.pkg_rel_path // js_file Note we did a post - processing when working on Windows | Es6_global -> Ext_path.rel_normalized_absolute_path ~from: (Js_packages_info.get_output_dir package_info ~package_dir:(Lazy.force Ext_path.package_dir) module_system) (package_path // dep_info.rel_path // js_file)))) | Package_script, Package_script -> ( let js_file = Ext_namespace.js_name_of_modulename (Ident.name dep_module_id.id) case Js in match Config_util.find_opt js_file with | Some file -> let basename = Filename.basename file in let dirname = Filename.dirname file in Ext_path.node_rebase_file ~from:(Ext_path.absolute_cwd_path output_dir) ~to_:(Ext_path.absolute_cwd_path dirname) basename | None -> Bs_exception.error (Js_not_found js_file)))) ;; #ifdef BS_BROWSER let string_of_module_id_in_browser (x : Lam_module_ident.t) = match x.kind with | External { name } -> name | Runtime | Ml -> "./stdlib/" ^ Ext_string.uncapitalize_ascii x.id.name ^ ".js" let string_of_module_id ~package_info:_ ~output_info:_ (id : Lam_module_ident.t) ~output_dir:(_ : string) : string = string_of_module_id_in_browser id ;; #endif
d5ba2fda89e01a3edfa8fe0d91f9e7a005a1a884a39b917979dcd9015e023099
input-output-hk/cardano-ledger
Internal.hs
{-# OPTIONS_HADDOCK hide, not-home #-} -- | Provide Tools for debugging -- Feel free to add new things as they are developed. module Cardano.Ledger.Shelley.Internal ( trace, totalAdaPotsES, compareAdaPots, producedTxBody, consumedTxBody, showCred, showIR, showKeyHash, showListy, showMap, showWithdrawal, showSafeHash, synopsisCert, synopsisCoinMap, trim, showTxCerts, ) where import Cardano.Ledger.Shelley.AdaPots ( AdaPots (..), consumedTxBody, producedTxBody, totalAdaPotsES, ) import Cardano.Ledger.Shelley.Rules.Reports ( showCred, showIR, showKeyHash, showListy, showMap, showSafeHash, showTxCerts, showWithdrawal, synopsisCert, synopsisCoinMap, trim, ) import Cardano.Ledger.Val ((<->)) import Debug.Trace (trace) -- ============================================== Compare two AdaPots , item by item pad :: Int -> String -> String pad n x = x ++ replicate (n - length x) ' ' compareAdaPots :: String -> AdaPots -> String -> AdaPots -> String compareAdaPots xlabel x ylabel y = unlines [ pad n "field" ++ pad n xlabel ++ pad n ylabel ++ pad n "difference" , oneline "treasuryAdaPot" treasuryAdaPot , oneline "reservesAdaPot" reservesAdaPot , oneline "rewardsAdaPot" rewardsAdaPot , oneline "utxoAdaPot" utxoAdaPot , oneline "keyDepositAdaPot" keyDepositAdaPot , oneline "poolDepositAdaPot" poolDepositAdaPot , oneline "depositsAdaPot" depositsAdaPot , oneline "feesAdaPot" feesAdaPot ] where n = 25 oneline name f = pad n name ++ pad n (show (f x)) ++ pad n (show (f y)) ++ pad n (show (f y <-> f x))
null
https://raw.githubusercontent.com/input-output-hk/cardano-ledger/6ac1edddfb207cff0c61481f8918b656021c14de/eras/shelley/impl/src/Cardano/Ledger/Shelley/Internal.hs
haskell
# OPTIONS_HADDOCK hide, not-home # | Provide Tools for debugging Feel free to add new things as they are developed. ==============================================
module Cardano.Ledger.Shelley.Internal ( trace, totalAdaPotsES, compareAdaPots, producedTxBody, consumedTxBody, showCred, showIR, showKeyHash, showListy, showMap, showWithdrawal, showSafeHash, synopsisCert, synopsisCoinMap, trim, showTxCerts, ) where import Cardano.Ledger.Shelley.AdaPots ( AdaPots (..), consumedTxBody, producedTxBody, totalAdaPotsES, ) import Cardano.Ledger.Shelley.Rules.Reports ( showCred, showIR, showKeyHash, showListy, showMap, showSafeHash, showTxCerts, showWithdrawal, synopsisCert, synopsisCoinMap, trim, ) import Cardano.Ledger.Val ((<->)) import Debug.Trace (trace) Compare two AdaPots , item by item pad :: Int -> String -> String pad n x = x ++ replicate (n - length x) ' ' compareAdaPots :: String -> AdaPots -> String -> AdaPots -> String compareAdaPots xlabel x ylabel y = unlines [ pad n "field" ++ pad n xlabel ++ pad n ylabel ++ pad n "difference" , oneline "treasuryAdaPot" treasuryAdaPot , oneline "reservesAdaPot" reservesAdaPot , oneline "rewardsAdaPot" rewardsAdaPot , oneline "utxoAdaPot" utxoAdaPot , oneline "keyDepositAdaPot" keyDepositAdaPot , oneline "poolDepositAdaPot" poolDepositAdaPot , oneline "depositsAdaPot" depositsAdaPot , oneline "feesAdaPot" feesAdaPot ] where n = 25 oneline name f = pad n name ++ pad n (show (f x)) ++ pad n (show (f y)) ++ pad n (show (f y <-> f x))
7f08a45bca950f4e63527ef87646379a3484a6cb42589e71edeb3ff2e6fef7e9
vernemq/vernemq
vmq_metrics_http.erl
Copyright 2018 Erlio GmbH Basel Switzerland ( ) %% 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(vmq_metrics_http). -behaviour(vmq_http_config). -include("vmq_metrics.hrl"). -export([routes/0, is_authorized/2]). -export([ init/2, content_types_provided/2, reply_to_text/2 ]). routes() -> [{"/metrics", ?MODULE, []}]. is_authorized(Req, State) -> AuthMode = vmq_http_config:auth_mode(Req, vmq_metrics_http), case AuthMode of "apikey" -> vmq_auth_apikey:is_authorized(Req, State, "metrics"); "noauth" -> {true, Req, State}; _ -> {error, invalid_authentication_scheme} end. init(Req, Opts) -> {cowboy_rest, Req, Opts}. content_types_provided(Req, State) -> { [ {{<<"text">>, <<"plain">>, '*'}, reply_to_text} ], Req, State }. reply_to_text(Req, State) -> %% Prometheus output Metrics = vmq_metrics:metrics(#{aggregate => false}), Output = prometheus_output(Metrics, {#{}, []}), {Output, Req, State}. prometheus_output( [ { #metric_def{ type = histogram = Type, name = Metric, description = Descr, labels = Labels }, Val } | Metrics ], {EmittedAcc, OutAcc} ) -> BinMetric = atom_to_binary(Metric, utf8), Node = atom_to_binary(node(), utf8), {Count, Sum, Buckets} = Val, CountLine = line(<<BinMetric/binary, "_count">>, Node, Labels, integer_to_binary(Count)), SumLine = line(<<BinMetric/binary, "_sum">>, Node, Labels, integer_to_binary(Sum)), Lines = maps:fold( fun(Bucket, BucketVal, BAcc) -> [ line( <<BinMetric/binary, "_bucket">>, Node, [ {<<"le">>, case Bucket of infinity -> <<"+Inf">>; _ -> integer_to_binary(Bucket) end} | Labels ], integer_to_binary(BucketVal) ) | BAcc ] end, [CountLine, SumLine], Buckets ), case EmittedAcc of #{Metric := _} -> prometheus_output(Metrics, {EmittedAcc, [Lines | OutAcc]}); _ -> HelpLine = [<<"# HELP ">>, BinMetric, <<" ", Descr/binary, "\n">>], TypeLine = [<<"# TYPE ">>, BinMetric, type(Type)], prometheus_output( Metrics, {EmittedAcc#{Metric => true}, [[HelpLine, TypeLine, Lines] | OutAcc]} ) end; prometheus_output( [ {#metric_def{type = Type, name = Metric, description = Descr, labels = Labels}, Val} | Metrics ], {EmittedAcc, OutAcc} ) -> BinMetric = atom_to_binary(Metric, utf8), BinVal = integer_to_binary(Val), Node = atom_to_binary(node(), utf8), Line = line(BinMetric, Node, Labels, BinVal), case EmittedAcc of #{Metric := _} -> prometheus_output(Metrics, {EmittedAcc, [Line | OutAcc]}); _ -> HelpLine = [<<"# HELP ">>, BinMetric, <<" ", Descr/binary, "\n">>], TypeLine = [<<"# TYPE ">>, BinMetric, type(Type)], prometheus_output( Metrics, {EmittedAcc#{Metric => true}, [[HelpLine, TypeLine, Line] | OutAcc]} ) end; prometheus_output([], {_, OutAcc}) -> %% Make sure the metrics with HELP and TYPE annotations are emitted first . lists:reverse(OutAcc). line(BinMetric, Node, Labels, BinVal) -> [ BinMetric, <<"{">>, labels([{<<"node">>, Node} | Labels]), <<"} ">>, BinVal, <<"\n">> ]. labels(Labels) -> lists:join( $,, lists:map( fun({Key, Val}) -> label(Key, Val) end, Labels ) ). label(Key, Val) -> [ensure_bin(Key), <<"=\"">>, ensure_bin(Val), <<"\"">>]. ensure_bin(E) when is_atom(E) -> atom_to_binary(E, utf8); ensure_bin(E) when is_list(E) -> list_to_binary(E); ensure_bin(E) when is_binary(E) -> E. type(gauge) -> <<" gauge\n">>; type(counter) -> <<" counter\n">>; type(histogram) -> <<" histogram\n">>.
null
https://raw.githubusercontent.com/vernemq/vernemq/72b565d20defbc2339d4c2cb8f19daba80357305/apps/vmq_server/src/vmq_metrics_http.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. Prometheus output Make sure the metrics with HELP and TYPE annotations are
Copyright 2018 Erlio GmbH Basel Switzerland ( ) Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(vmq_metrics_http). -behaviour(vmq_http_config). -include("vmq_metrics.hrl"). -export([routes/0, is_authorized/2]). -export([ init/2, content_types_provided/2, reply_to_text/2 ]). routes() -> [{"/metrics", ?MODULE, []}]. is_authorized(Req, State) -> AuthMode = vmq_http_config:auth_mode(Req, vmq_metrics_http), case AuthMode of "apikey" -> vmq_auth_apikey:is_authorized(Req, State, "metrics"); "noauth" -> {true, Req, State}; _ -> {error, invalid_authentication_scheme} end. init(Req, Opts) -> {cowboy_rest, Req, Opts}. content_types_provided(Req, State) -> { [ {{<<"text">>, <<"plain">>, '*'}, reply_to_text} ], Req, State }. reply_to_text(Req, State) -> Metrics = vmq_metrics:metrics(#{aggregate => false}), Output = prometheus_output(Metrics, {#{}, []}), {Output, Req, State}. prometheus_output( [ { #metric_def{ type = histogram = Type, name = Metric, description = Descr, labels = Labels }, Val } | Metrics ], {EmittedAcc, OutAcc} ) -> BinMetric = atom_to_binary(Metric, utf8), Node = atom_to_binary(node(), utf8), {Count, Sum, Buckets} = Val, CountLine = line(<<BinMetric/binary, "_count">>, Node, Labels, integer_to_binary(Count)), SumLine = line(<<BinMetric/binary, "_sum">>, Node, Labels, integer_to_binary(Sum)), Lines = maps:fold( fun(Bucket, BucketVal, BAcc) -> [ line( <<BinMetric/binary, "_bucket">>, Node, [ {<<"le">>, case Bucket of infinity -> <<"+Inf">>; _ -> integer_to_binary(Bucket) end} | Labels ], integer_to_binary(BucketVal) ) | BAcc ] end, [CountLine, SumLine], Buckets ), case EmittedAcc of #{Metric := _} -> prometheus_output(Metrics, {EmittedAcc, [Lines | OutAcc]}); _ -> HelpLine = [<<"# HELP ">>, BinMetric, <<" ", Descr/binary, "\n">>], TypeLine = [<<"# TYPE ">>, BinMetric, type(Type)], prometheus_output( Metrics, {EmittedAcc#{Metric => true}, [[HelpLine, TypeLine, Lines] | OutAcc]} ) end; prometheus_output( [ {#metric_def{type = Type, name = Metric, description = Descr, labels = Labels}, Val} | Metrics ], {EmittedAcc, OutAcc} ) -> BinMetric = atom_to_binary(Metric, utf8), BinVal = integer_to_binary(Val), Node = atom_to_binary(node(), utf8), Line = line(BinMetric, Node, Labels, BinVal), case EmittedAcc of #{Metric := _} -> prometheus_output(Metrics, {EmittedAcc, [Line | OutAcc]}); _ -> HelpLine = [<<"# HELP ">>, BinMetric, <<" ", Descr/binary, "\n">>], TypeLine = [<<"# TYPE ">>, BinMetric, type(Type)], prometheus_output( Metrics, {EmittedAcc#{Metric => true}, [[HelpLine, TypeLine, Line] | OutAcc]} ) end; prometheus_output([], {_, OutAcc}) -> emitted first . lists:reverse(OutAcc). line(BinMetric, Node, Labels, BinVal) -> [ BinMetric, <<"{">>, labels([{<<"node">>, Node} | Labels]), <<"} ">>, BinVal, <<"\n">> ]. labels(Labels) -> lists:join( $,, lists:map( fun({Key, Val}) -> label(Key, Val) end, Labels ) ). label(Key, Val) -> [ensure_bin(Key), <<"=\"">>, ensure_bin(Val), <<"\"">>]. ensure_bin(E) when is_atom(E) -> atom_to_binary(E, utf8); ensure_bin(E) when is_list(E) -> list_to_binary(E); ensure_bin(E) when is_binary(E) -> E. type(gauge) -> <<" gauge\n">>; type(counter) -> <<" counter\n">>; type(histogram) -> <<" histogram\n">>.
41b431020c7ab70b8bd92592c45a5e3465796293f893abea6c4c947f4ec9176b
ocaml-flambda/flambda-backend
inlining_report.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro (* *) Copyright 2020 - -2021 OCamlPro SAS Copyright 2021 - -2021 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. *) (* *) (**************************************************************************) Inlining reports for Flambda2 . * * Given the history of decisions made by the inliner , reconstructing the * implied tree of decisions made by the inliner is feasible . * * Let 's take the following bit of code : * ` ` ` * ( * Module A * * Given the history of decisions made by the inliner, reconstructing the * implied tree of decisions made by the inliner is feasible. * * Let's take the following bit of code: * ``` * (* Module A*) * let foo arg = * let[@inline never] bar arg = .... in * bar x * * let baz_1 x = foo x * let baz_2 x = (foo [@@inlined never]) x * ``` * * Let's assume that simplify inlined the call to [foo] * in [baz_1] and doesn't inline the call to [foo]. * * Then the inliner will have taken the following decisions: * - Mark the function [foo] as inlinable * - Mark the function [foo.bar] as non inlinable * - Mark the function [baz_1] as inlinable * - Inline the call to [baz_1.foo] * - Do not inline the call to [bar] that was created as a * consequence of inlining [foo.baz_1] * - Mark the call to [baz_2.foo] as non inlinable * * All of this can also be represented into the following tree: * Module A * ├─► Declaration of Function [foo] * │ │ Deemed inlinable * │ ├─► Declaration of function [bar] * │ │ │ Deemed as non inlinable * │ └─► Call to [bar] * │ │ Non inlined because the callee was deemed to be non inlinable * └─► Definition of [baz_1] * │ Deemed inlinable * ├─► Call to [foo] * │ │ Inlined * │ ├─► Declaration of function [bar] * │ │ │ Deemed as non inlinable * │ └─► Call to [bar] that was first defined at [foo.bar] * │ │ Non inlined because the callee was deemed to be non inlinable * └─► Call to [foo] * │ Not inlined because of an annotation * * These inlining reports are: * - Recording all decisions made during [simplify] * - Reconstructing the inlining tree from these decisions * - Printing this tree to a human-readable file compatible with org mode *) module IHA = Inlining_history.Absolute module Pass = struct type t = | After_closure_conversion | Before_simplify | After_simplify let print ppf pass = match pass with | After_closure_conversion -> Format.fprintf ppf "afte@r closure@ conversion" | Before_simplify -> Format.fprintf ppf "before@ simplify" | After_simplify -> Format.fprintf ppf "after@ simplify" end module Table : sig Pretty print a table of values . The width of cells containing a float or an int is determined using the width of the string returned by [ string_of_float ] and [ string_of_int ] respectively . The width of cells containing a float or an int is determined using the width of the string returned by [string_of_float] and [string_of_int] respectively. *) type t val create : [< `Float of float | `Int of int | `String of string] list list -> t val print : Format.formatter -> t -> unit end = struct type t = int list * string list list let create cells = let cells_with_size = List.map (fun row -> List.map (fun cell -> let s_cell = match cell with | `Float f -> string_of_float f | `Int d -> string_of_int d | `String s -> s in s_cell, String.length s_cell) row) cells in let sizes = List.fold_left (fun sizes row_sizes -> List.map2 (fun s1 (_, s2) -> if s1 < s2 then s2 else s1) sizes row_sizes) (List.hd cells_with_size |> List.map snd) cells_with_size in let cells = List.map (List.map fst) cells_with_size in sizes, cells let table_line (sizes, _) = let dashes = List.map (fun s -> String.make s '-') sizes in "|-" ^ String.concat "-+-" dashes ^ "-|" let print_row ppf (size, cells) = let rec loop ppf = function | [] -> Format.fprintf ppf "|" | (width, c) :: rest -> Format.fprintf ppf "| %*s %a" width c loop rest in loop ppf (List.combine size cells) let print_table_values ~table_line ppf (size, cells) = let rec loop ppf = function | [] -> Format.fprintf ppf "@[<h>%s@]" table_line | row :: rest -> Format.fprintf ppf "@[<h>%s@]@;@[<h>%a@]@;%a" table_line print_row (size, row) loop rest in loop ppf cells let print ppf t = let table_line = table_line t in Format.fprintf ppf "@[<v>%a@]" (print_table_values ~table_line) t end module Context = struct (* Represents the context under which an inlining decision was taken. *) type t = { args : Inlining_arguments.t; cost_metrics : Cost_metrics.t option; depth : int option; unrolling_depth : int option option; are_rebuilding_terms : Are_rebuilding_terms.t; pass : Pass.t } let create ?depth ?unrolling_depth ?cost_metrics ~are_rebuilding_terms ~args ~pass () = { args; depth; unrolling_depth; cost_metrics; are_rebuilding_terms; pass } let print ppf { args; cost_metrics; depth; unrolling_depth; are_rebuilding_terms; pass = _ } = let print_unrolling_depth ppf = function | None -> () | Some (Some unroll) -> Format.fprintf ppf "@[<h>Unrolling@ depth:@ %d@]@,@," unroll | Some None -> Format.fprintf ppf "@[<h>Unrolling@ depth unknown@]@,@," in let print_args ppf args = let table = [ [ `String "max inlining depth"; `Int (Inlining_arguments.max_inlining_depth args); `String "call cost"; `Float (Inlining_arguments.call_cost args) ]; [ `String "small function size"; `Int (Inlining_arguments.small_function_size args); `String "alloc cost"; `Float (Inlining_arguments.alloc_cost args) ]; [ `String "large function size"; `Int (Inlining_arguments.large_function_size args); `String "branch cost"; `Float (Inlining_arguments.branch_cost args) ]; [ `String "threshold"; `Float (Inlining_arguments.threshold args); `String "indirect call cost"; `Float (Inlining_arguments.indirect_call_cost args) ]; [ `String "prim cost"; `Float (Inlining_arguments.prim_cost args); `String "poly compare cost"; `Float (Inlining_arguments.poly_compare_cost args) ] ] |> Table.create in Format.fprintf ppf "@[<h>Inlining@ arguments:@;@]@,@[<h>%a@]@,@," Table.print table in let print_cost_metrics ppf = function | None -> () | Some c -> let Removed_operations. { call; alloc; prim; branch; direct_call_of_indirect; specialized_poly_compare; requested_inline } = Cost_metrics.removed c in let table = [ [ `String "Call"; `String "Alloc"; `String "Prim"; `String "Branch"; `String "Direct call of indirect"; `String "Specialized poly compare"; `String "Requested inline" ]; [ `Int call; `Int alloc; `Int prim; `Int branch; `Int direct_call_of_indirect; `Int specialized_poly_compare; `Int requested_inline ] ] |> Table.create in Format.fprintf ppf "@[<v>@[<h>Code@ size@ was@ estimated@ to@ be@ %a@]@,\ @,\ @[<h>Benefits@ of@ inlining@ this@ call:@;\ @]@,\ @[<h>%a@]@]@,\ @," Code_size.print (Cost_metrics.size c) Table.print table in let print_depth ppf = function | None -> () | Some c -> Format.fprintf ppf "@[<h>Considered@ at@ inlining@ depth@ of@ %d@]@,@," c in let print_are_rebuilding_terms ppf t = Format.fprintf ppf "@[<h>Considered@ with@ are_rebuilding_terms@ =@ %a@]@,@," Are_rebuilding_terms.print t in print_are_rebuilding_terms ppf are_rebuilding_terms; print_args ppf args; print_cost_metrics ppf cost_metrics; print_depth ppf depth; print_unrolling_depth ppf unrolling_depth end module Decision_with_context = struct type decision = | Call of Call_site_inlining_decision_type.t | Fundecl of Function_decl_inlining_decision_type.t type t = { context : Context.t; decision : decision } let print_decision ppf = function | Call c -> Call_site_inlining_decision_type.report ppf c | Fundecl c -> Function_decl_inlining_decision_type.report ppf c let print ppf { context; decision } = Format.fprintf ppf "@[<v>@[<h>Decision@ taken@ *%a*@]@," Pass.print context.pass; Format.fprintf ppf "@[<v 2>@,"; Format.fprintf ppf "%a@,@[<h>%a@]@," Context.print context print_decision decision; Format.fprintf ppf "@]@]" end type raw_decision = { path : IHA.t; dbg : Debuginfo.t; decision_with_context : Decision_with_context.t option } (* Record all raw decisions inside a list. Decisions are appended as they are recorded. The ordering in which they are recorded doesn't matter. *) let log : raw_decision list ref = ref [] let record_decision_at_call_site_for_known_function ~tracker ~unrolling_depth ~apply ~pass ~callee ~are_rebuilding_terms decision = if Flambda_features.inlining_report () || Flambda_features.inlining_report_bin () then let dbg = Apply_expr.dbg apply in let path = Inlining_history.Tracker.call ~dbg ~callee ~relative:(Apply_expr.relative_history apply) tracker in let state = Apply_expr.inlining_state apply in let context = Context.create ~depth:(Inlining_state.depth state) ~args:(Inlining_state.arguments state) ~unrolling_depth ~are_rebuilding_terms ~pass () in log := { decision_with_context = Some { decision = Call decision; context }; path; dbg } :: !log else () let record_decision_at_call_site_for_unknown_function ~tracker ~apply ~pass:_ () = if Flambda_features.inlining_report () || Flambda_features.inlining_report_bin () then let dbg = Apply_expr.dbg apply in let path = Inlining_history.Tracker.unknown_call ~dbg ~relative:(Apply_expr.relative_history apply) tracker in log := { decision_with_context = None; path; dbg } :: !log else () let record_decision_at_function_definition ~absolute_history ~code_metadata ~pass ~are_rebuilding_terms decision = if Flambda_features.inlining_report () || Flambda_features.inlining_report_bin () then let dbg = Code_metadata.dbg code_metadata in let args = Code_metadata.inlining_arguments code_metadata in let cost_metrics = Code_metadata.cost_metrics code_metadata in let context = Context.create ~args ~cost_metrics ~are_rebuilding_terms ~pass () in log := { decision_with_context = Some { decision = Fundecl decision; context }; path = absolute_history; dbg } :: !log else () module Uid = struct type t = { compilation_unit : Compilation_unit.t; t : string } let create ~compilation_unit path = { compilation_unit; t = IHA.uid_path path } let print_anchor ppf { compilation_unit = _; t } = Format.fprintf ppf " <<%s>>" t let print_link_hum ~compilation_unit ppf { compilation_unit = cu_uid; t } = if Compilation_unit.equal compilation_unit cu_uid then Format.fprintf ppf "[[%s][here]]" t else let external_reports = Format.asprintf "%a.0.inlining.org" Compilation_unit.print_name cu_uid in try let file = Load_path.find_uncap external_reports in Format.fprintf ppf "[[file:%s::%s][in compilation unit %a]]" t file Compilation_unit.print cu_uid with Not_found -> Format.fprintf ppf "in@ compilation@ unit@ %a@ but@ no@ inlining@ reports@ were@ \ generated@ for@ this@ unit." Compilation_unit.print cu_uid end module Inlining_tree = struct module Key = struct type scope = | Module | Class | Unknown let compare_scope a b = match a, b with | Module, Module | Class, Class | Unknown, Unknown -> 0 | Module, (Class | Unknown) | Class, Unknown -> 1 | (Class | Unknown), Module | Unknown, Class -> -1 type element = | Fundecl of string | Scope of scope * string | Call of IHA.t let compare_element a b = match a, b with | Fundecl s1, Fundecl s2 -> String.compare s1 s2 | Call s1, Call s2 -> IHA.compare s1 s2 | Scope (t1, s1), Scope (t2, s2) -> let c = compare_scope t1 t2 in if c <> 0 then c else String.compare s1 s2 | Fundecl _, (Call _ | Scope _) | Call _, Scope _ -> 1 | (Call _ | Scope _), Fundecl _ | Scope _, Call _ -> -1 type t = Debuginfo.t * element let compare (dbg1, e1) (dbg2, e2) = let c = Debuginfo.compare dbg1 dbg2 in if c <> 0 then c else compare_element e1 e2 end module Map = Map.Make (Key) type decision_or_reference = | Decision of Decision_with_context.t | Reference of IHA.t | Unavailable let merge_decision_or_reference old new_ = match old, new_ with | Reference _, ((Decision _ | Unavailable) as d) | ((Decision _ | Unavailable) as d), Reference _ -> d | Unavailable, (Decision _ as d) | (Decision _ as d), Unavailable -> d | Reference _, Reference _ | Decision _, Decision _ | Unavailable, Unavailable -> new_ type item = | Call of { decision : decision_or_reference; tree : t } | Fundecl of { decisions : decisions; body : t } | Scope of t and t = item Map.t and decisions = Decision_with_context.t list let empty = Map.empty let insert_or_update_scope ~scope_type ~name ~apply_to_child t = let key = Debuginfo.none, Key.Scope (scope_type, name) in let m = if not (Map.mem key t) then Map.empty else match Map.find key t with | Scope m -> m | Call _ | Fundecl _ -> assert false in Map.add key (Scope (apply_to_child m)) t let insert_or_update_call ~decision ~dbg ~callee ~(apply_to_child : t -> t) t = let key = dbg, Key.Call callee in Map.update key (function | None -> Some (Call { tree = apply_to_child Map.empty; decision }) | Some (Call t) -> let decision = merge_decision_or_reference t.decision decision in Some (Call { tree = apply_to_child t.tree; decision }) | Some (Scope _ | Fundecl _) -> Misc.fatal_errorf "A key of type call or fundecl should be associated with an item \ of type Call") t let insert_or_update_fundecl ?decision_with_context ~dbg ~name ~(apply_to_child : t -> t) t = let key = dbg, Key.Fundecl name in Map.update key (function | None -> Some (Fundecl { body = apply_to_child Map.empty; decisions = Option.to_list decision_with_context }) | Some (Fundecl t) -> let decisions = match decision_with_context with | Some decision -> decision :: t.decisions | None -> t.decisions in Some (Fundecl { body = apply_to_child t.body; decisions }) | Some (Scope _ | Call _) -> Misc.fatal_errorf "A key of type fundecl should be associated with an item of type \ Fundecl") t (* Insert a decision into an inlining tree [t]. Only decisions rooted in [compilation_unit] are kept. *) let insert ~compilation_unit t (decision : raw_decision) = (* Paths are stored as a linked list, meaning that the innermost atoms of the paths are also the one at the start of it. For example, the path: Empty -> fundecl(foo) -> apply(bar) -> inlined -> apply(baz) Is represented as Apply(baz, Inlined(Apply(bar, Fundecl(foo, Empty)))) As such path can only traversed from top to bottom. However, [insert] will insert a decision in a inlining tree rooted in [t] and inside an inlining [tree] nodes are traversed from bottom to tree. To avoid having to manually reverse the path each call to [insert_or_update_descendant] constructs a [apply_to_child] function that will replay the traversal in reversed order and build the inlining tree [t] where nodes corresponding to [decision] are present. *) let rec insert_or_update_descendant ~apply_to_child path = match (path : IHA.path) with | Empty -> apply_to_child t | Unknown { prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_scope ~scope_type:Unknown ~name:"" ~apply_to_child m) | Module { name; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_scope ~scope_type:Module ~name ~apply_to_child m) | Class { name; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_scope ~scope_type:Class ~name ~apply_to_child m) | Function { dbg; name; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_fundecl ~dbg ~name ~apply_to_child m) | Call { dbg; callee; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_call ~decision:(Reference callee) ~dbg ~callee ~apply_to_child m) | Inline { prev } -> insert_or_update_descendant prev ~apply_to_child in let { path; dbg; decision_with_context } = decision in if Compilation_unit.equal compilation_unit (IHA.compilation_unit path) then let path = IHA.path path in match path with | Unknown _ -> t | Call { callee; prev; _ } -> insert_or_update_descendant ~apply_to_child:(fun m -> let decision = match decision_with_context with | Some decision -> Decision decision | None -> Unavailable in insert_or_update_call ~decision ~dbg ~callee ~apply_to_child:(fun x -> x) m) prev | Function { name; prev; _ } -> insert_or_update_descendant ~apply_to_child: (insert_or_update_fundecl ?decision_with_context ~dbg ~name ~apply_to_child:(fun x -> x)) prev | Module _ | Class _ | Inline _ | Empty -> Misc.fatal_errorf "Only decisions for closures and calls can be recorded." else t let stars ppf n = Format.fprintf ppf "%s" (String.make n '*') let print_title ?uid ?(dbg = Debuginfo.none) ~depth ~label ~f ppf w = let print_uid ppf uid = match uid with None -> () | Some uid -> Uid.print_anchor ppf uid in let print_dbg ppf dbg = if Debuginfo.is_none dbg then () else Format.fprintf ppf "@ at@ %a" Debuginfo.print_compact dbg in Format.fprintf ppf "@[<h>%a@ %s@ %a%a%a@]@,@," stars depth label f w print_dbg dbg print_uid uid let print_decision_with_context ppf decision_with_context = Format.fprintf ppf "@[%a@]@," Decision_with_context.print decision_with_context let print_decisions ppf decisions = match decisions with | [] -> assert false | decisions -> let decisions = List.rev decisions in Format.fprintf ppf "@[<v>"; List.iter (print_decision_with_context ppf) decisions; Format.fprintf ppf "@]" let rebuild_path ~path ~dbg (key : Key.element) = match key with | Scope (Unknown, _) -> IHA.Unknown { prev = path } | Scope (Module, name) -> IHA.Module { name; prev = path } | Scope (Class, name) -> IHA.Class { name; prev = path } | Call callee -> IHA.Call { callee; dbg; prev = path } | Fundecl fundecl -> IHA.Function { name = fundecl; dbg; prev = path } let print_reference ~compilation_unit ppf to_ = let cu ppf () = let defined_in = IHA.compilation_unit to_ in if Compilation_unit.equal defined_in compilation_unit then Format.fprintf ppf "this compilation unit" else Format.fprintf ppf "%a" Compilation_unit.print_name defined_in in Format.fprintf ppf "@[<hov>The@ decision@ to@ inline@ this@ call@ was@ taken@ in@ %a@ at@ \ %a.@]" cu () IHA.print to_ let print_unavailable ppf () = Format.fprintf ppf "@[<hov>Flambda2@ was@ unavailable@ to@ do@ a@ direct@ call@ to@ this@ \ function.@]" let rec print ~compilation_unit ~depth ~path ppf t = Map.iter (fun (dbg, key) (v : item) -> let path = rebuild_path ~path ~dbg key in let uid = Uid.create ~compilation_unit path in match key, v with | Scope (Unknown, _), _ -> print_title ~uid ~depth ~label:"Unknown" ~f:Format.pp_print_text ppf "" | Scope (Module, name), Scope t -> print_title ~uid ~depth ~label:"Module" ~f:Format.pp_print_text ppf name; print ~compilation_unit ppf ~depth:(depth + 1) ~path t | Scope (Class, name), Scope t -> print_title ~uid ~depth ~label:"Class" ~f:Format.pp_print_text ppf name; print ~compilation_unit ppf ~depth:(depth + 1) ~path t | Call callee, Call { decision; tree } -> print_title ppf ?uid:None ~dbg ~depth ~label:"Application of" ~f:IHA.print callee; Format.fprintf ppf "@[<v>"; Format.fprintf ppf "@[<hov>Defined@ %a@]@,@," (Uid.print_link_hum ~compilation_unit) (Uid.create ~compilation_unit (IHA.path callee)); (match decision with | Decision decision_with_context -> Format.fprintf ppf "@[<v>%a@]" print_decision_with_context decision_with_context | Reference path -> print_reference ~compilation_unit ppf path | Unavailable -> print_unavailable ppf ()); Format.fprintf ppf "@]@,@,"; print ppf ~compilation_unit ~depth:(depth + 1) ~path:(IHA.Inline { prev = path }) tree | Fundecl fundecl, Fundecl { decisions; body } -> print_title ppf ~uid ~dbg ~depth ~label:"Definition of" ~f:Format.pp_print_text fundecl; Format.fprintf ppf "@[<v>%a@]@,@," print_decisions decisions; print ppf ~compilation_unit ~depth:(depth + 1) ~path body | Scope _, (Call _ | Fundecl _) | Call _, Scope _ | Fundecl _, Scope _ | Fundecl _, Call _ | Call _, Fundecl _ -> assert false) t let print ~compilation_unit ppf t = print ~compilation_unit ~depth:0 ~path:IHA.Empty ppf t end type metadata = { compilation_unit : Compilation_unit.t } type report = [`Flambda2_1_0_0 of metadata * Inlining_tree.t] let output_then_forget_decisions ~output_prefix = Misc.try_finally ~always:(fun () -> log := []) ~exceptionally:(fun () -> (* CR gbury: Is there a more appropriate function to report a warning (that is not one of the numbered warnings)? *) Format.eprintf "WARNING: inlining report output failed@.") (fun () -> let compilation_unit = Compilation_unit.get_current_exn () in let tree = lazy (List.fold_left (Inlining_tree.insert ~compilation_unit) Inlining_tree.empty (List.rev !log)) in if Flambda_features.inlining_report () then ( let filename = output_prefix ^ ".inlining.org" in let out_channel = open_out filename in let fmt = Format.formatter_of_out_channel out_channel in Format.fprintf fmt "@[<v>%a@]@." (Inlining_tree.print ~compilation_unit) (Lazy.force tree); close_out out_channel); if Flambda_features.inlining_report_bin () then ( let ch = open_out_bin (output_prefix ^ ".inlining") in let metadata = { compilation_unit } in let report : report = `Flambda2_1_0_0 (metadata, Lazy.force tree) in Marshal.to_channel ch report []; close_out ch); Lazy.force tree)
null
https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/f1af4294b2eb49c7938da6d93d68391d2c7cb035/middle_end/flambda2/simplify_shared/inlining_report.ml
ocaml
************************************************************************ OCaml All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Module A Represents the context under which an inlining decision was taken. Record all raw decisions inside a list. Decisions are appended as they are recorded. The ordering in which they are recorded doesn't matter. Insert a decision into an inlining tree [t]. Only decisions rooted in [compilation_unit] are kept. Paths are stored as a linked list, meaning that the innermost atoms of the paths are also the one at the start of it. For example, the path: Empty -> fundecl(foo) -> apply(bar) -> inlined -> apply(baz) Is represented as Apply(baz, Inlined(Apply(bar, Fundecl(foo, Empty)))) As such path can only traversed from top to bottom. However, [insert] will insert a decision in a inlining tree rooted in [t] and inside an inlining [tree] nodes are traversed from bottom to tree. To avoid having to manually reverse the path each call to [insert_or_update_descendant] constructs a [apply_to_child] function that will replay the traversal in reversed order and build the inlining tree [t] where nodes corresponding to [decision] are present. CR gbury: Is there a more appropriate function to report a warning (that is not one of the numbered warnings)?
, OCamlPro Copyright 2020 - -2021 OCamlPro SAS Copyright 2021 - -2021 Jane Street Group LLC the GNU Lesser General Public License version 2.1 , with the Inlining reports for Flambda2 . * * Given the history of decisions made by the inliner , reconstructing the * implied tree of decisions made by the inliner is feasible . * * Let 's take the following bit of code : * ` ` ` * ( * Module A * * Given the history of decisions made by the inliner, reconstructing the * implied tree of decisions made by the inliner is feasible. * * Let's take the following bit of code: * ``` * let foo arg = * let[@inline never] bar arg = .... in * bar x * * let baz_1 x = foo x * let baz_2 x = (foo [@@inlined never]) x * ``` * * Let's assume that simplify inlined the call to [foo] * in [baz_1] and doesn't inline the call to [foo]. * * Then the inliner will have taken the following decisions: * - Mark the function [foo] as inlinable * - Mark the function [foo.bar] as non inlinable * - Mark the function [baz_1] as inlinable * - Inline the call to [baz_1.foo] * - Do not inline the call to [bar] that was created as a * consequence of inlining [foo.baz_1] * - Mark the call to [baz_2.foo] as non inlinable * * All of this can also be represented into the following tree: * Module A * ├─► Declaration of Function [foo] * │ │ Deemed inlinable * │ ├─► Declaration of function [bar] * │ │ │ Deemed as non inlinable * │ └─► Call to [bar] * │ │ Non inlined because the callee was deemed to be non inlinable * └─► Definition of [baz_1] * │ Deemed inlinable * ├─► Call to [foo] * │ │ Inlined * │ ├─► Declaration of function [bar] * │ │ │ Deemed as non inlinable * │ └─► Call to [bar] that was first defined at [foo.bar] * │ │ Non inlined because the callee was deemed to be non inlinable * └─► Call to [foo] * │ Not inlined because of an annotation * * These inlining reports are: * - Recording all decisions made during [simplify] * - Reconstructing the inlining tree from these decisions * - Printing this tree to a human-readable file compatible with org mode *) module IHA = Inlining_history.Absolute module Pass = struct type t = | After_closure_conversion | Before_simplify | After_simplify let print ppf pass = match pass with | After_closure_conversion -> Format.fprintf ppf "afte@r closure@ conversion" | Before_simplify -> Format.fprintf ppf "before@ simplify" | After_simplify -> Format.fprintf ppf "after@ simplify" end module Table : sig Pretty print a table of values . The width of cells containing a float or an int is determined using the width of the string returned by [ string_of_float ] and [ string_of_int ] respectively . The width of cells containing a float or an int is determined using the width of the string returned by [string_of_float] and [string_of_int] respectively. *) type t val create : [< `Float of float | `Int of int | `String of string] list list -> t val print : Format.formatter -> t -> unit end = struct type t = int list * string list list let create cells = let cells_with_size = List.map (fun row -> List.map (fun cell -> let s_cell = match cell with | `Float f -> string_of_float f | `Int d -> string_of_int d | `String s -> s in s_cell, String.length s_cell) row) cells in let sizes = List.fold_left (fun sizes row_sizes -> List.map2 (fun s1 (_, s2) -> if s1 < s2 then s2 else s1) sizes row_sizes) (List.hd cells_with_size |> List.map snd) cells_with_size in let cells = List.map (List.map fst) cells_with_size in sizes, cells let table_line (sizes, _) = let dashes = List.map (fun s -> String.make s '-') sizes in "|-" ^ String.concat "-+-" dashes ^ "-|" let print_row ppf (size, cells) = let rec loop ppf = function | [] -> Format.fprintf ppf "|" | (width, c) :: rest -> Format.fprintf ppf "| %*s %a" width c loop rest in loop ppf (List.combine size cells) let print_table_values ~table_line ppf (size, cells) = let rec loop ppf = function | [] -> Format.fprintf ppf "@[<h>%s@]" table_line | row :: rest -> Format.fprintf ppf "@[<h>%s@]@;@[<h>%a@]@;%a" table_line print_row (size, row) loop rest in loop ppf cells let print ppf t = let table_line = table_line t in Format.fprintf ppf "@[<v>%a@]" (print_table_values ~table_line) t end module Context = struct type t = { args : Inlining_arguments.t; cost_metrics : Cost_metrics.t option; depth : int option; unrolling_depth : int option option; are_rebuilding_terms : Are_rebuilding_terms.t; pass : Pass.t } let create ?depth ?unrolling_depth ?cost_metrics ~are_rebuilding_terms ~args ~pass () = { args; depth; unrolling_depth; cost_metrics; are_rebuilding_terms; pass } let print ppf { args; cost_metrics; depth; unrolling_depth; are_rebuilding_terms; pass = _ } = let print_unrolling_depth ppf = function | None -> () | Some (Some unroll) -> Format.fprintf ppf "@[<h>Unrolling@ depth:@ %d@]@,@," unroll | Some None -> Format.fprintf ppf "@[<h>Unrolling@ depth unknown@]@,@," in let print_args ppf args = let table = [ [ `String "max inlining depth"; `Int (Inlining_arguments.max_inlining_depth args); `String "call cost"; `Float (Inlining_arguments.call_cost args) ]; [ `String "small function size"; `Int (Inlining_arguments.small_function_size args); `String "alloc cost"; `Float (Inlining_arguments.alloc_cost args) ]; [ `String "large function size"; `Int (Inlining_arguments.large_function_size args); `String "branch cost"; `Float (Inlining_arguments.branch_cost args) ]; [ `String "threshold"; `Float (Inlining_arguments.threshold args); `String "indirect call cost"; `Float (Inlining_arguments.indirect_call_cost args) ]; [ `String "prim cost"; `Float (Inlining_arguments.prim_cost args); `String "poly compare cost"; `Float (Inlining_arguments.poly_compare_cost args) ] ] |> Table.create in Format.fprintf ppf "@[<h>Inlining@ arguments:@;@]@,@[<h>%a@]@,@," Table.print table in let print_cost_metrics ppf = function | None -> () | Some c -> let Removed_operations. { call; alloc; prim; branch; direct_call_of_indirect; specialized_poly_compare; requested_inline } = Cost_metrics.removed c in let table = [ [ `String "Call"; `String "Alloc"; `String "Prim"; `String "Branch"; `String "Direct call of indirect"; `String "Specialized poly compare"; `String "Requested inline" ]; [ `Int call; `Int alloc; `Int prim; `Int branch; `Int direct_call_of_indirect; `Int specialized_poly_compare; `Int requested_inline ] ] |> Table.create in Format.fprintf ppf "@[<v>@[<h>Code@ size@ was@ estimated@ to@ be@ %a@]@,\ @,\ @[<h>Benefits@ of@ inlining@ this@ call:@;\ @]@,\ @[<h>%a@]@]@,\ @," Code_size.print (Cost_metrics.size c) Table.print table in let print_depth ppf = function | None -> () | Some c -> Format.fprintf ppf "@[<h>Considered@ at@ inlining@ depth@ of@ %d@]@,@," c in let print_are_rebuilding_terms ppf t = Format.fprintf ppf "@[<h>Considered@ with@ are_rebuilding_terms@ =@ %a@]@,@," Are_rebuilding_terms.print t in print_are_rebuilding_terms ppf are_rebuilding_terms; print_args ppf args; print_cost_metrics ppf cost_metrics; print_depth ppf depth; print_unrolling_depth ppf unrolling_depth end module Decision_with_context = struct type decision = | Call of Call_site_inlining_decision_type.t | Fundecl of Function_decl_inlining_decision_type.t type t = { context : Context.t; decision : decision } let print_decision ppf = function | Call c -> Call_site_inlining_decision_type.report ppf c | Fundecl c -> Function_decl_inlining_decision_type.report ppf c let print ppf { context; decision } = Format.fprintf ppf "@[<v>@[<h>Decision@ taken@ *%a*@]@," Pass.print context.pass; Format.fprintf ppf "@[<v 2>@,"; Format.fprintf ppf "%a@,@[<h>%a@]@," Context.print context print_decision decision; Format.fprintf ppf "@]@]" end type raw_decision = { path : IHA.t; dbg : Debuginfo.t; decision_with_context : Decision_with_context.t option } let log : raw_decision list ref = ref [] let record_decision_at_call_site_for_known_function ~tracker ~unrolling_depth ~apply ~pass ~callee ~are_rebuilding_terms decision = if Flambda_features.inlining_report () || Flambda_features.inlining_report_bin () then let dbg = Apply_expr.dbg apply in let path = Inlining_history.Tracker.call ~dbg ~callee ~relative:(Apply_expr.relative_history apply) tracker in let state = Apply_expr.inlining_state apply in let context = Context.create ~depth:(Inlining_state.depth state) ~args:(Inlining_state.arguments state) ~unrolling_depth ~are_rebuilding_terms ~pass () in log := { decision_with_context = Some { decision = Call decision; context }; path; dbg } :: !log else () let record_decision_at_call_site_for_unknown_function ~tracker ~apply ~pass:_ () = if Flambda_features.inlining_report () || Flambda_features.inlining_report_bin () then let dbg = Apply_expr.dbg apply in let path = Inlining_history.Tracker.unknown_call ~dbg ~relative:(Apply_expr.relative_history apply) tracker in log := { decision_with_context = None; path; dbg } :: !log else () let record_decision_at_function_definition ~absolute_history ~code_metadata ~pass ~are_rebuilding_terms decision = if Flambda_features.inlining_report () || Flambda_features.inlining_report_bin () then let dbg = Code_metadata.dbg code_metadata in let args = Code_metadata.inlining_arguments code_metadata in let cost_metrics = Code_metadata.cost_metrics code_metadata in let context = Context.create ~args ~cost_metrics ~are_rebuilding_terms ~pass () in log := { decision_with_context = Some { decision = Fundecl decision; context }; path = absolute_history; dbg } :: !log else () module Uid = struct type t = { compilation_unit : Compilation_unit.t; t : string } let create ~compilation_unit path = { compilation_unit; t = IHA.uid_path path } let print_anchor ppf { compilation_unit = _; t } = Format.fprintf ppf " <<%s>>" t let print_link_hum ~compilation_unit ppf { compilation_unit = cu_uid; t } = if Compilation_unit.equal compilation_unit cu_uid then Format.fprintf ppf "[[%s][here]]" t else let external_reports = Format.asprintf "%a.0.inlining.org" Compilation_unit.print_name cu_uid in try let file = Load_path.find_uncap external_reports in Format.fprintf ppf "[[file:%s::%s][in compilation unit %a]]" t file Compilation_unit.print cu_uid with Not_found -> Format.fprintf ppf "in@ compilation@ unit@ %a@ but@ no@ inlining@ reports@ were@ \ generated@ for@ this@ unit." Compilation_unit.print cu_uid end module Inlining_tree = struct module Key = struct type scope = | Module | Class | Unknown let compare_scope a b = match a, b with | Module, Module | Class, Class | Unknown, Unknown -> 0 | Module, (Class | Unknown) | Class, Unknown -> 1 | (Class | Unknown), Module | Unknown, Class -> -1 type element = | Fundecl of string | Scope of scope * string | Call of IHA.t let compare_element a b = match a, b with | Fundecl s1, Fundecl s2 -> String.compare s1 s2 | Call s1, Call s2 -> IHA.compare s1 s2 | Scope (t1, s1), Scope (t2, s2) -> let c = compare_scope t1 t2 in if c <> 0 then c else String.compare s1 s2 | Fundecl _, (Call _ | Scope _) | Call _, Scope _ -> 1 | (Call _ | Scope _), Fundecl _ | Scope _, Call _ -> -1 type t = Debuginfo.t * element let compare (dbg1, e1) (dbg2, e2) = let c = Debuginfo.compare dbg1 dbg2 in if c <> 0 then c else compare_element e1 e2 end module Map = Map.Make (Key) type decision_or_reference = | Decision of Decision_with_context.t | Reference of IHA.t | Unavailable let merge_decision_or_reference old new_ = match old, new_ with | Reference _, ((Decision _ | Unavailable) as d) | ((Decision _ | Unavailable) as d), Reference _ -> d | Unavailable, (Decision _ as d) | (Decision _ as d), Unavailable -> d | Reference _, Reference _ | Decision _, Decision _ | Unavailable, Unavailable -> new_ type item = | Call of { decision : decision_or_reference; tree : t } | Fundecl of { decisions : decisions; body : t } | Scope of t and t = item Map.t and decisions = Decision_with_context.t list let empty = Map.empty let insert_or_update_scope ~scope_type ~name ~apply_to_child t = let key = Debuginfo.none, Key.Scope (scope_type, name) in let m = if not (Map.mem key t) then Map.empty else match Map.find key t with | Scope m -> m | Call _ | Fundecl _ -> assert false in Map.add key (Scope (apply_to_child m)) t let insert_or_update_call ~decision ~dbg ~callee ~(apply_to_child : t -> t) t = let key = dbg, Key.Call callee in Map.update key (function | None -> Some (Call { tree = apply_to_child Map.empty; decision }) | Some (Call t) -> let decision = merge_decision_or_reference t.decision decision in Some (Call { tree = apply_to_child t.tree; decision }) | Some (Scope _ | Fundecl _) -> Misc.fatal_errorf "A key of type call or fundecl should be associated with an item \ of type Call") t let insert_or_update_fundecl ?decision_with_context ~dbg ~name ~(apply_to_child : t -> t) t = let key = dbg, Key.Fundecl name in Map.update key (function | None -> Some (Fundecl { body = apply_to_child Map.empty; decisions = Option.to_list decision_with_context }) | Some (Fundecl t) -> let decisions = match decision_with_context with | Some decision -> decision :: t.decisions | None -> t.decisions in Some (Fundecl { body = apply_to_child t.body; decisions }) | Some (Scope _ | Call _) -> Misc.fatal_errorf "A key of type fundecl should be associated with an item of type \ Fundecl") t let insert ~compilation_unit t (decision : raw_decision) = let rec insert_or_update_descendant ~apply_to_child path = match (path : IHA.path) with | Empty -> apply_to_child t | Unknown { prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_scope ~scope_type:Unknown ~name:"" ~apply_to_child m) | Module { name; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_scope ~scope_type:Module ~name ~apply_to_child m) | Class { name; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_scope ~scope_type:Class ~name ~apply_to_child m) | Function { dbg; name; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_fundecl ~dbg ~name ~apply_to_child m) | Call { dbg; callee; prev } -> insert_or_update_descendant prev ~apply_to_child:(fun m -> insert_or_update_call ~decision:(Reference callee) ~dbg ~callee ~apply_to_child m) | Inline { prev } -> insert_or_update_descendant prev ~apply_to_child in let { path; dbg; decision_with_context } = decision in if Compilation_unit.equal compilation_unit (IHA.compilation_unit path) then let path = IHA.path path in match path with | Unknown _ -> t | Call { callee; prev; _ } -> insert_or_update_descendant ~apply_to_child:(fun m -> let decision = match decision_with_context with | Some decision -> Decision decision | None -> Unavailable in insert_or_update_call ~decision ~dbg ~callee ~apply_to_child:(fun x -> x) m) prev | Function { name; prev; _ } -> insert_or_update_descendant ~apply_to_child: (insert_or_update_fundecl ?decision_with_context ~dbg ~name ~apply_to_child:(fun x -> x)) prev | Module _ | Class _ | Inline _ | Empty -> Misc.fatal_errorf "Only decisions for closures and calls can be recorded." else t let stars ppf n = Format.fprintf ppf "%s" (String.make n '*') let print_title ?uid ?(dbg = Debuginfo.none) ~depth ~label ~f ppf w = let print_uid ppf uid = match uid with None -> () | Some uid -> Uid.print_anchor ppf uid in let print_dbg ppf dbg = if Debuginfo.is_none dbg then () else Format.fprintf ppf "@ at@ %a" Debuginfo.print_compact dbg in Format.fprintf ppf "@[<h>%a@ %s@ %a%a%a@]@,@," stars depth label f w print_dbg dbg print_uid uid let print_decision_with_context ppf decision_with_context = Format.fprintf ppf "@[%a@]@," Decision_with_context.print decision_with_context let print_decisions ppf decisions = match decisions with | [] -> assert false | decisions -> let decisions = List.rev decisions in Format.fprintf ppf "@[<v>"; List.iter (print_decision_with_context ppf) decisions; Format.fprintf ppf "@]" let rebuild_path ~path ~dbg (key : Key.element) = match key with | Scope (Unknown, _) -> IHA.Unknown { prev = path } | Scope (Module, name) -> IHA.Module { name; prev = path } | Scope (Class, name) -> IHA.Class { name; prev = path } | Call callee -> IHA.Call { callee; dbg; prev = path } | Fundecl fundecl -> IHA.Function { name = fundecl; dbg; prev = path } let print_reference ~compilation_unit ppf to_ = let cu ppf () = let defined_in = IHA.compilation_unit to_ in if Compilation_unit.equal defined_in compilation_unit then Format.fprintf ppf "this compilation unit" else Format.fprintf ppf "%a" Compilation_unit.print_name defined_in in Format.fprintf ppf "@[<hov>The@ decision@ to@ inline@ this@ call@ was@ taken@ in@ %a@ at@ \ %a.@]" cu () IHA.print to_ let print_unavailable ppf () = Format.fprintf ppf "@[<hov>Flambda2@ was@ unavailable@ to@ do@ a@ direct@ call@ to@ this@ \ function.@]" let rec print ~compilation_unit ~depth ~path ppf t = Map.iter (fun (dbg, key) (v : item) -> let path = rebuild_path ~path ~dbg key in let uid = Uid.create ~compilation_unit path in match key, v with | Scope (Unknown, _), _ -> print_title ~uid ~depth ~label:"Unknown" ~f:Format.pp_print_text ppf "" | Scope (Module, name), Scope t -> print_title ~uid ~depth ~label:"Module" ~f:Format.pp_print_text ppf name; print ~compilation_unit ppf ~depth:(depth + 1) ~path t | Scope (Class, name), Scope t -> print_title ~uid ~depth ~label:"Class" ~f:Format.pp_print_text ppf name; print ~compilation_unit ppf ~depth:(depth + 1) ~path t | Call callee, Call { decision; tree } -> print_title ppf ?uid:None ~dbg ~depth ~label:"Application of" ~f:IHA.print callee; Format.fprintf ppf "@[<v>"; Format.fprintf ppf "@[<hov>Defined@ %a@]@,@," (Uid.print_link_hum ~compilation_unit) (Uid.create ~compilation_unit (IHA.path callee)); (match decision with | Decision decision_with_context -> Format.fprintf ppf "@[<v>%a@]" print_decision_with_context decision_with_context | Reference path -> print_reference ~compilation_unit ppf path | Unavailable -> print_unavailable ppf ()); Format.fprintf ppf "@]@,@,"; print ppf ~compilation_unit ~depth:(depth + 1) ~path:(IHA.Inline { prev = path }) tree | Fundecl fundecl, Fundecl { decisions; body } -> print_title ppf ~uid ~dbg ~depth ~label:"Definition of" ~f:Format.pp_print_text fundecl; Format.fprintf ppf "@[<v>%a@]@,@," print_decisions decisions; print ppf ~compilation_unit ~depth:(depth + 1) ~path body | Scope _, (Call _ | Fundecl _) | Call _, Scope _ | Fundecl _, Scope _ | Fundecl _, Call _ | Call _, Fundecl _ -> assert false) t let print ~compilation_unit ppf t = print ~compilation_unit ~depth:0 ~path:IHA.Empty ppf t end type metadata = { compilation_unit : Compilation_unit.t } type report = [`Flambda2_1_0_0 of metadata * Inlining_tree.t] let output_then_forget_decisions ~output_prefix = Misc.try_finally ~always:(fun () -> log := []) ~exceptionally:(fun () -> Format.eprintf "WARNING: inlining report output failed@.") (fun () -> let compilation_unit = Compilation_unit.get_current_exn () in let tree = lazy (List.fold_left (Inlining_tree.insert ~compilation_unit) Inlining_tree.empty (List.rev !log)) in if Flambda_features.inlining_report () then ( let filename = output_prefix ^ ".inlining.org" in let out_channel = open_out filename in let fmt = Format.formatter_of_out_channel out_channel in Format.fprintf fmt "@[<v>%a@]@." (Inlining_tree.print ~compilation_unit) (Lazy.force tree); close_out out_channel); if Flambda_features.inlining_report_bin () then ( let ch = open_out_bin (output_prefix ^ ".inlining") in let metadata = { compilation_unit } in let report : report = `Flambda2_1_0_0 (metadata, Lazy.force tree) in Marshal.to_channel ch report []; close_out ch); Lazy.force tree)
74af1956f4b2e402d1f0ff62a8f515e26daea8dd4d1b466d39630c2789979749
bufferswap/ViralityEngine
component-mop-defs.lisp
(in-package #:virality) ;; In the component-class we keep annotation values for annotations that are ;; identified by symbol. (defclass annotation-value () ((%serialnum :accessor serialnum :initarg :serialnum) (%name :accessor name :initarg :name) (%state :accessor state ;; :initialized or :forward-reference :initarg :state) (%setter :accessor setter :initarg :setter) (%getter :accessor getter :initarg :getter))) ;; The meta-class for the component class. (defclass component-class (standard-class) (;; Each created annotation gets a serialnumber gotten from here. (%annotation-serialnum :accessor annotation-serialnum :initarg :annotation-serialnum :initform 0) ;; The annotation database for all annotations (%annotations :accessor annotations :initarg :annotations ;; key: symbol, value: component-class/annotation-value :initform (u:dict #'eq)) (%annotations-dirty-p :accessor annotations-dirty-p :initarg :annotations-dirty-p :initform nil) ;; The optimized annotations for easy funcalling. (%annotation-array :accessor annotation-array :initarg :annotation-array :initform #()) ;; A database of which slots on which classes are annotated. ;; key: component-name, value: list of (slot-name (initarg ..) (anno ..)) ;; Note: I'm storing the EFFECTIVE slot data in thie db. This means that ;; all annotation inheritance rules are in effect and we can track ;; annotations across inherited components. (%annotated-slots :accessor annotated-slots :initarg :annotated-slots :initform (u:dict #'eq)))) (defclass annotatable-slot () (;; A list of symbols like: (material transform ... texture) (%annotation :accessor annotation :initarg :annotation :initform nil) ;; An array of indexes that map the symbols, in the same order, to locations ;; in an optimized annotation array in the 'component metaclass slots. (%annotation-indexes :accessor annotation-indexes :initarg :annotation-indexes :initform nil))) NOTE : First we define the direct and effective slot class we desire for the component - class metaclass . Then the point of having two classes , annotated , ;; and not annotated, is to make slot-value-using-class ONLY execute on ;; _actually_ annotated slots. ;; component-class has its own definition of standard-direct slots (defclass component-direct-slot-definition (c2mop:standard-direct-slot-definition) ()) ;; annotated slot definitions for direct slots (defclass component-annotated-direct-slot-definition (component-direct-slot-definition annotatable-slot) ()) ;; component-class has its own definition of standard-effective slots (defclass component-effective-slot-definition (c2mop:standard-effective-slot-definition) ()) ;; annotated slot defitions for effective slots. (defclass component-annotated-effective-slot-definition (component-effective-slot-definition annotatable-slot) ()) ;; NOTE: The MOP chicanery we're doing quires this method to be defined ;; before we can declare a defclass with the component-class metaclass. (defmethod c2mop:validate-superclass ((class component-class) (super standard-class)) t) ;; The venerable COMPONENT class from which all user components are derived. ;; It uses the above machinery to deal with annotable slots. Since this is so intertwined with the MOP stuff defined above , we keep it in the same file . (defclass component (kernel) ((%type :reader component-type :initarg :type) (%actor :accessor actor :initarg :actor :initform nil) (%initializer :accessor initializer :initarg :initializer :initform nil) (%attach/detach-event-queue :accessor attach/detach-event-queue :initarg :attach/detach-event-queue :initform (queues:make-queue :simple-queue))) (:metaclass component-class))
null
https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/src/datatype/component-mop-defs.lisp
lisp
In the component-class we keep annotation values for annotations that are identified by symbol. :initialized or :forward-reference The meta-class for the component class. Each created annotation gets a serialnumber gotten from here. The annotation database for all annotations key: symbol, value: component-class/annotation-value The optimized annotations for easy funcalling. A database of which slots on which classes are annotated. key: component-name, value: list of (slot-name (initarg ..) (anno ..)) Note: I'm storing the EFFECTIVE slot data in thie db. This means that all annotation inheritance rules are in effect and we can track annotations across inherited components. A list of symbols like: (material transform ... texture) An array of indexes that map the symbols, in the same order, to locations in an optimized annotation array in the 'component metaclass slots. and not annotated, is to make slot-value-using-class ONLY execute on _actually_ annotated slots. component-class has its own definition of standard-direct slots annotated slot definitions for direct slots component-class has its own definition of standard-effective slots annotated slot defitions for effective slots. NOTE: The MOP chicanery we're doing quires this method to be defined before we can declare a defclass with the component-class metaclass. The venerable COMPONENT class from which all user components are derived. It uses the above machinery to deal with annotable slots. Since this is so
(in-package #:virality) (defclass annotation-value () ((%serialnum :accessor serialnum :initarg :serialnum) (%name :accessor name :initarg :name) :initarg :state) (%setter :accessor setter :initarg :setter) (%getter :accessor getter :initarg :getter))) (defclass component-class (standard-class) (%annotation-serialnum :accessor annotation-serialnum :initarg :annotation-serialnum :initform 0) (%annotations :accessor annotations :initarg :annotations :initform (u:dict #'eq)) (%annotations-dirty-p :accessor annotations-dirty-p :initarg :annotations-dirty-p :initform nil) (%annotation-array :accessor annotation-array :initarg :annotation-array :initform #()) (%annotated-slots :accessor annotated-slots :initarg :annotated-slots :initform (u:dict #'eq)))) (defclass annotatable-slot () (%annotation :accessor annotation :initarg :annotation :initform nil) (%annotation-indexes :accessor annotation-indexes :initarg :annotation-indexes :initform nil))) NOTE : First we define the direct and effective slot class we desire for the component - class metaclass . Then the point of having two classes , annotated , (defclass component-direct-slot-definition (c2mop:standard-direct-slot-definition) ()) (defclass component-annotated-direct-slot-definition (component-direct-slot-definition annotatable-slot) ()) (defclass component-effective-slot-definition (c2mop:standard-effective-slot-definition) ()) (defclass component-annotated-effective-slot-definition (component-effective-slot-definition annotatable-slot) ()) (defmethod c2mop:validate-superclass ((class component-class) (super standard-class)) t) intertwined with the MOP stuff defined above , we keep it in the same file . (defclass component (kernel) ((%type :reader component-type :initarg :type) (%actor :accessor actor :initarg :actor :initform nil) (%initializer :accessor initializer :initarg :initializer :initform nil) (%attach/detach-event-queue :accessor attach/detach-event-queue :initarg :attach/detach-event-queue :initform (queues:make-queue :simple-queue))) (:metaclass component-class))
0d0b9ec61a39db4c25fe712bf98d6b31fe996a20681d91edd196c4b09d4b20b1
metosin/komponentit
clipboard.cljs
(ns example.clipboard (:require [komponentit.clipboard :as clipboard] [reagent.core :as r] [devcards.core :as dc :include-macros true] [clojure.string :as str] [example.core :as e])) (dc/defcard (str (e/header 'clipboard "Clipboard") (:doc (meta #'clipboard/copy-text)))) (dc/defcard-rg clipboard-example (fn [value _] [:div [:div [:input {:placeholder "paste text here for test"}] [:button {:type "button" :on-click #(clipboard/copy-text "foo")} "Copy \"foo\""]]]) (r/atom nil))
null
https://raw.githubusercontent.com/metosin/komponentit/d962ce1d69ccc3800db0d6b4fc18fc2fd30b494a/example-src/cljs/example/clipboard.cljs
clojure
(ns example.clipboard (:require [komponentit.clipboard :as clipboard] [reagent.core :as r] [devcards.core :as dc :include-macros true] [clojure.string :as str] [example.core :as e])) (dc/defcard (str (e/header 'clipboard "Clipboard") (:doc (meta #'clipboard/copy-text)))) (dc/defcard-rg clipboard-example (fn [value _] [:div [:div [:input {:placeholder "paste text here for test"}] [:button {:type "button" :on-click #(clipboard/copy-text "foo")} "Copy \"foo\""]]]) (r/atom nil))
c5a25da88d6610b68e028ada41c7845f55b14331e345dad0a33a2a70c5fc7285
wangzhe3224/cs3110
print.ml
module type ToString = sig type t val to_string : t -> string end module Print (M: ToString) = struct let print t = print_endline (M.to_string t) end module Int = struct type t = int let to_string = string_of_int end module MyString = struct type t = string let to_string t = t end module StringWithPrint = struct include string type t = string let to_string t = t end module PrintInt = Print(Int) module PrintString = Print(MyString) (* module PrintWith = Print(StringWithPrint) *)
null
https://raw.githubusercontent.com/wangzhe3224/cs3110/33c1b9662ee5ba4bd13d7ec5a116b539bf086605/labs/lab8/print.ml
ocaml
module PrintWith = Print(StringWithPrint)
module type ToString = sig type t val to_string : t -> string end module Print (M: ToString) = struct let print t = print_endline (M.to_string t) end module Int = struct type t = int let to_string = string_of_int end module MyString = struct type t = string let to_string t = t end module StringWithPrint = struct include string type t = string let to_string t = t end module PrintInt = Print(Int) module PrintString = Print(MyString)
19a4e0f29a2e733a0591c1294a8960768cea9768e6250af3a7805f3ac05e9705
g-andrade/deigma
deigma_sup.erl
Copyright ( c ) 2018 - 2022 %% %% 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. @private -module(deigma_sup). -behaviour(supervisor). %% ------------------------------------------------------------------ %% API Function Exports %% ------------------------------------------------------------------ -export( [start_link/0, start_child/1 ]). -ignore_xref( [start_link/0 ]). %% ------------------------------------------------------------------ supervisor Function Exports %% ------------------------------------------------------------------ -export( [init/1 ]). %% ------------------------------------------------------------------ Macro Definitions %% ------------------------------------------------------------------ -define(SERVER, ?MODULE). %% ------------------------------------------------------------------ %% API Function Definitions %% ------------------------------------------------------------------ -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). -spec start_child(list()) -> {ok, pid()}. start_child(Args) -> supervisor:start_child(?SERVER, Args). %% ------------------------------------------------------------------ %% supervisor Function Definitions %% ------------------------------------------------------------------ -spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec(), ...]}}. init([]) -> SupFlags = #{ strategy => simple_one_for_one }, ChildSpecs = [#{ id => deigma, start => {deigma, start_link, []}, restart => temporary, type => supervisor }], {ok, {SupFlags, ChildSpecs}}.
null
https://raw.githubusercontent.com/g-andrade/deigma/85b63171f00a557b7b688b5d6c510baeb5de2a99/src/deigma_sup.erl
erlang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------ API Function Exports ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ API Function Definitions ------------------------------------------------------------------ ------------------------------------------------------------------ supervisor Function Definitions ------------------------------------------------------------------
Copyright ( c ) 2018 - 2022 to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the 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 @private -module(deigma_sup). -behaviour(supervisor). -export( [start_link/0, start_child/1 ]). -ignore_xref( [start_link/0 ]). supervisor Function Exports -export( [init/1 ]). Macro Definitions -define(SERVER, ?MODULE). -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). -spec start_child(list()) -> {ok, pid()}. start_child(Args) -> supervisor:start_child(?SERVER, Args). -spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec(), ...]}}. init([]) -> SupFlags = #{ strategy => simple_one_for_one }, ChildSpecs = [#{ id => deigma, start => {deigma, start_link, []}, restart => temporary, type => supervisor }], {ok, {SupFlags, ChildSpecs}}.
399d1b5d896e81b7f949c1ef56d3b3e7e8aab2ece72a10c57562b45673956d6c
argp/bap
generate_mli.ml
Build a .mli from a .dist file . Files with extension .dist are used to assemble modules into a consistent hierarchy . Essentially , .dist files are .ml files with additional annotations designed to allow generation of the corresponding .mli . Format of a .dist file : { [ ( * Module comment Build a .mli from a .dist file. Files with extension .dist are used to assemble modules into a consistent hierarchy. Essentially, .dist files are .ml files with additional annotations designed to allow generation of the corresponding .mli. Format of a .dist file: {[ (*Module comment*) module Foo = A.Module.Path (*%mli "a/file/path/foo.mli" aka "InnerFoo"*) (*Module comment*) module Bar = Another.Module.Path.Foo (*%mli "another/file/path/foo.mli" submodule "Bar"*) (*Module comment*) module Sna = struct module Toto = Yet.Another.Module.Path (*%mli "a/file/path/foo.mli"*) (*...same grammar...*) end ]} Producing a .ml is trivial, there's nothing to do. Producing a .mli is more complex: - parse the .dist file, keeping comments which don't start with % (gasp) - build the list of substitutions -- here, every occurrence of [InnerFoo] must become [Foo] -- here, every occurrence of [A.Module.Path] must become [Foo] -- here, every occurrence of [Yet.Another.Module.Path] must become [Sna.Toto] - build the list of source .mli - if necessary, generate each source .mli (so this needs to be done from myocamlbuild.ml) - from each %mli directive -- build a temporary file, obtained by ---- extracting only the necessary submodules (remove [module Stuff : sig] and [end (*Stuff*)]) ---- performing all the substitutions in the list -- invoke ocamldep -- parse the result of ocamldep and deduce a list of dependencies for the destination module (here, [Foo], [Bar], [Toto]) - bubble dependencies upwards in the tree of modules (here, [Sna] should inherit all the dependencies of [Toto]) - perform topological sort on dependencies - assuming topological sort has succeeded, generate a .mli where every module alias is replaced by the contents of the corresponding temporary .mli - write down all of this to a file. easy, isn't it? *) open Preprocess_common open Genlex open Camlp4.PreCast open Camlp4.Sig module StringSet = Set.Make(String) * { 6 Finding files } (**The list of include directories. Specified on the command-line*) let include_dirs : string list ref = ref [] * { 6 Calling ocamldep } open Ocamlbuild_pack (** Invoke ocamldep and compute the dependencies of a .mli*) let stringset_of_ocamldep : string -> StringSet.t = fun file -> List.fold_left (fun acc (_, x) -> StringSet.add x acc) StringSet.empty (Ocaml_utils.path_dependencies_of file) * { 6 Utilities } (** Imported from {!IO.Printf} to avoid unsolvable dependencies*) module Printf = struct include Printf let make_list_printer (p:(out_channel -> 'b -> unit)) (start: string) (finish: string) (separate:string) (out:out_channel) (l: 'b list ) = let rec aux out l = match l with | [] -> () | [h] -> p out h | h::t -> fprintf out "%a%s%a" p h separate aux t in fprintf out "%s%a%s" start aux l finish end open Printf * { 6 Dependency sorting } module Dependency = struct type t = (string, StringSet.t) Hashtbl.t let create () = Hashtbl.create 100 let add tbl k dep = try Hashtbl.replace tbl k (StringSet.add dep (Hashtbl.find tbl k)) with Not_found -> Hashtbl.add tbl k (StringSet.singleton dep) let remove tbl (k:string) dep = try let set = StringSet.remove dep (Hashtbl.find tbl k) in if StringSet.is_empty set then Hashtbl.remove tbl k else Hashtbl.replace tbl k set with Not_found -> () let find tbl (k:string) = try Some (Hashtbl.find tbl k) with Not_found -> None let find_all tbl (k:string) = try StringSet.elements (Hashtbl.find tbl k) with Not_found -> [] let print out tbl = Printf.fprintf out "{"; Hashtbl.iter (fun k set -> Printf.fprintf out "%s: {%a}\n" k (Printf.make_list_printer (fun out -> Printf.fprintf out "%s") "{" "}" "; ") (StringSet.elements set)) tbl; Printf.fprintf out "}\n" end module Depsort = struct type t = { direct : Dependency.t (**Direct dependency*); reverse: Dependency.t (**Reverse dependency*); set : StringSet.t ref (**All the nodes*) } let create () = { direct = Dependency.create (); reverse = Dependency.create (); set = ref StringSet.empty } let add_node t node = t.set := StringSet.add node !(t.set) let add_dependency t depending depended = Dependency.add t.direct depending depended; Dependency.add t.reverse depended depending; add_node t depending; add_node t depended let sort t = Printf.eprintf " Sorting % a\n " Dependency.print t.direct ; let rec aux (sorted:string list) (rest: string list) = match rest with | [] -> sorted | _ -> (*Find nodes which haven't been removed and depend on nothing*) match List.fold_left (fun (keep, remove) k -> match Dependency.find t.direct k with | None -> (keep, k::remove) | Some dependencies -> (k::keep, remove) ) ([],[]) rest with | (_, []) -> Printf.eprintf "Cyclic dependencies in %a\n" Dependency.print t.direct; failwith "Cyclic dependencies" | (rest, roots) -> List.iter (fun d -> Printf.eprintf " Dependency % S resolved\n " d ; List.iter (*Dependency [d] has been resolved, remove it.*) (fun x -> Dependency.remove t.direct x d) (Dependency.find_all t.reverse d)) roots; aux (sorted @ roots) rest in aux [] (StringSet.elements !(t.set)) end * { 6 String manipulation } module String = struct include String exception Invalid_string let find str ?(pos=0) ?(end_pos=length str) sub = let sublen = length sub in if sublen = 0 then 0 else let found = ref 0 in try for i = pos to end_pos - sublen do let j = ref 0 in while unsafe_get str (i + !j) = unsafe_get sub !j do incr j; if !j = sublen then begin found := i; raise Exit; end; done; done; raise Invalid_string with Exit -> !found let split str sep = let p = find str sep in let len = length sep in let slen = length str in sub str 0 p, sub str (p + len) (slen - p - len) let nsplit str sep = if str = "" then [] else ( let rec nsplit str sep = try let s1 , s2 = split str sep in s1 :: nsplit s2 sep with Invalid_string -> [str] in nsplit str sep ) type segment = Changed of string | Slice of int * int let global_replace convs str = (* convs = (seek, replace) list *) let repl_one slist (seek,repl) = let rec split_multi acc = function Slice (start_idx, end_idx) -> begin try let i = find str ~pos:start_idx ~end_pos:end_idx seek in split_multi accumulate slice & replacement (Changed repl :: Slice (start_idx,i-1) :: acc) (* split the rest of the slice *) (Slice (i+length seek, end_idx)) with Invalid_string -> Slice (start_idx,end_idx) :: acc end | s -> s :: acc (* don't replace in a replacement *) in List.fold_left split_multi [] slist in let to_str pieces = let len_p = function Changed s -> length s | Slice (a,b) -> b-a + 1 in let len = List.fold_left (fun a p -> a + len_p p) 0 pieces in let out = String.create len in let rec loop pos = function Slice (s, e) :: t -> String.blit str s out pos (e-s+1); loop (pos+e-s+1) t | Changed s :: t -> String.blit s 0 out pos (length s); loop (pos + length s) t | [] -> () in loop 0 pieces; out in to_str (List.fold_left repl_one [Slice (0,length str)] convs) end * { 6 Representation of the .dist file } type path = string list (** The type of a module path*) (**Information regarding where to find the signature for a module.*) type sigsource = { mli : string (**Path towards the .mli file containing the data for this module, e.g. "src/core/extlib/extList.mli"*); inner_path : path (**Module path towards the interesting module, e.g. "List"*) } type comment = string list type substitution = (string * string) (** [(original, replacement)] *) type ('a,'b) sigtree = 'a * (('a, 'b) sigtree_aux) and ('a,'b) sigtree_aux = | Leaf of string * 'b * comment (**A module alias*) | Node of string * ('a, 'b) sigtree list * comment | Other of string (**Some uninterpreted content, such as unattached comments*);; (** Return the annotations on a tree*) let leaves_of (tree: (_, 'b) sigtree) : 'b list = let rec aux acc n = match n with | (_, Other _) -> acc | (_, Node (_, l, _)) -> List.fold_left aux acc l | (_, Leaf (_, x, _)) -> x :: acc in aux [] tree;; (** [extract_relevant_of_string file submodule] returns a string containing the relevant parts of [file]. If [submodule] is [[]], the relevant parts of [file] are the complete contents of [source]. If [submodule] is a module path, the relevant parts of [file] are only the contents of the corresponding path. *) let extract_relevant_of_file (filename: string) (path: path) (subs:substitution list) = let ic = open_in filename in let buf= Buffer.create 1024 in let oc = Format.formatter_of_buffer buf in extract filename ic oc path; let contents = Buffer.contents buf in String.global_replace subs contents;; let parse_annotation stream = let parse_annotation_content stream = let rec aux ?mli ~aka ?path = parser | [< 'Kwd "aka"; 'String s; stream >] -> aux ?mli ~aka:(s::aka) ?path stream | [< 'Kwd "mli"; 'String mli; stream >] -> aux ~mli ~aka ?path stream | [< 'Kwd "submodule"; 'String s; stream >] -> aux ?mli ~aka ~path:s stream | [< >] -> (mli, aka, path) in aux ~aka:[] (make_lexer ["aka"; "mli"; "submodule"] stream) in let rec aux stream = match Stream.next stream with | ((BLANKS _ | NEWLINE), _) -> aux stream | (COMMENT c, _) -> if String.length c >= 1 && String.get c 0 = '%' then Some (parse_annotation_content (Stream.of_string c)) else None | _ -> None in aux stream (** Read and parse the contents of a .dist file and return it without any additional processing*) let read_dist: in_channel -> string -> (unit, sigsource) sigtree * substitution list = fun channel name -> let renamings = ref [] in let rec aux ~recent_comments (*~old_comments*) ~path stream : (_, _) sigtree list = match Stream.next stream with | (COMMENT c, _) -> aux ~recent_comments:(c::recent_comments) ~path (*~old_comments*) stream ~old_comments:(recent_comments @ ) | (KEYWORD "module", _) -> begin skip_blanks stream; let id = parse_uident stream in skip_blanks stream; parse_equal stream; skip_blanks stream; match Stream.peek stream with | Some(KEYWORD "struct", _) -> njunk 1 stream; List.rev ( List.map ( fun x - > Other x ) ) @ [((),Node (id, aux ~recent_comments:[] stream ~path:(path^id^"."), List.rev recent_comments))] | _ -> begin let source_path = parse_path stream in renamings := (string_of_path source_path, id) :: (path, id) :: !renamings; match parse_annotation stream with | Some (Some mli, aka, Some path) -> List.iter (fun x -> renamings := (x, id)::!renamings) aka; let annot = { mli = mli; inner_path = path_of_string path } in ((), Leaf (id, annot, List.rev recent_comments)) :: aux ~recent_comments:[] ~path stream | None -> failwith "Missing annotation" | _ -> failwith "Incomplete annotation" end end | (EOI, _) -> [] | (tok, loc) -> [] in (((), Node ("", aux ~recent_comments:[] ~path:"" (tokens_of_channel name channel), [])), !renamings) (** Go through a tree applying substitutions. For each leaf of the tree - read the [source] - extract the relevant part - apply the substitutions to the relevant part - write the substituted version to a temporary file - replace the leaf content with the temporary file name*) let apply_substitutions: ('a, sigsource) sigtree -> substitution list -> ('a, string) sigtree = fun tree substitutions -> let rec aux = function | (tag, Leaf (name, {mli = mli; inner_path = inner_path}, comment)) -> let contents = extract_relevant_of_file mli inner_path substitutions in let filename = Filename.temp_file "ocamlbuild_distrib" ".mli" in let cout = open_out filename in output_string cout contents; (tag, Leaf (name, filename, comment)) | (tag, Node (name, tree, comment)) -> (tag, Node (name, List.map aux tree, comment)) | (tag, Other o) -> (tag, Other o) in aux tree * Compute dependencies of each node of the tree . For each leaf of the tree - apply ocamldep - parse the result into a list of dependencies For each node , merge the dependencies of subtrees . For each leaf of the tree - apply ocamldep - parse the result into a list of dependencies For each node, merge the dependencies of subtrees. *) let compute_dependencies: (unit, string) sigtree -> (StringSet.t, string) sigtree = fun tree -> let rec aux = function | ((), Other o) -> (StringSet.empty, Other o) | ((), Node (name, children, comment)) -> let (deps, rewritten) = List.fold_left (fun (deps, rewritten) child -> let ((child_deps, _) as child') = aux child in (StringSet.union deps child_deps, child'::rewritten)) (StringSet.empty, []) children in (deps, Node (name, rewritten, comment)) | ((), Leaf (name, file_name, comment))-> (stringset_of_ocamldep file_name, Leaf (name, file_name, comment)) in aux tree (** Sort a list of modules topologically. [sort_modules l rename] sorts the modules of list [l]. Each name is transformed using [rename] before taking dependencies into account ([rename] serves chiefly to add prefixes). *) let sort_modules: ((StringSet.t, _) sigtree list as 'a) -> (string -> string) -> 'a = fun list prefix -> let dependencies = Depsort.create () and modules = Hashtbl.create 16 and others = ref [] in List.iter (function ((depends_on, Leaf (name, _, _)) as node) | ((depends_on, Node (name, _, _)) as node)-> let name' = prefix name in (*Collect dependencies*) Hashtbl.add modules name node; Depsort.add_node dependencies name; StringSet.iter (fun dep -> Depsort.add_dependency dependencies name' dep) depends_on | other -> others := other :: !others) list; List.rev_append !others (List.map (fun name -> Hashtbl.find modules name) (Depsort.sort dependencies)) (**Recursively sort by dependencies each level of the tree. *) let sort_tree : (StringSet.t, string) sigtree -> (StringSet.t, string) sigtree = fun tree -> let rec aux prefix = function | (_, Other _) as o -> o | (set, Node (name, children, comment)) -> First sort each child let prefix' = prefix ^ name ^ "." in let children = List.map (aux prefix') children in let mkprefix = fun s -> prefix' ^ s in (*Then sort between children*) (set, Node (name, sort_modules children mkprefix, comment)) | (_, Leaf _) as l -> l in aux "" tree (**Write down the tree *) let serialize_tree : Format.formatter -> (_, string) sigtree -> unit = fun out -> let serialize_comment out l = List.iter (Format.fprintf out "%s@\n") l in let rec aux = function | (_, Leaf (name, content, comment)) -> Format.fprintf out "%a@\nmodule %s : sig@[<v 5>%s@]@\n" serialize_comment comment name content | (_, Node (name, children, comment)) -> Format.fprintf out "%a@\nmodule %s = struct@[%a@]@\n" serialize_comment comment name (fun _ l -> List.iter aux l) children | (_, Other s) -> Format.fprintf out "%s@\n" s in aux (** Drive the process*) let driver name cin cout = let (tree,substitutions) = read_dist cin name in let deps = compute_dependencies (apply_substitutions tree substitutions) in serialize_tree cout (sort_tree deps) let _ = let out_file = ref "" and in_file = ref "" in Arg.parse [("-I", Arg.String (fun x -> include_dirs := x :: !include_dirs), "Add include directory"); ("-o", Arg.Set_string out_file, "Set output .mli (standard out by default)")] (fun file -> out_file := file) "Generate a .mli file from a .dist"; let cout = match !out_file with | "" -> Format.std_formatter | s -> Format.formatter_of_out_channel (open_out s) and cin = match !in_file with | "" -> stdin | s -> open_in s in driver !in_file cin cout; flush_all ()
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/build/preprocess_mli/generate_mli.ml
ocaml
Module comment %mli "a/file/path/foo.mli" aka "InnerFoo" Module comment %mli "another/file/path/foo.mli" submodule "Bar" Module comment %mli "a/file/path/foo.mli" ...same grammar... Stuff *The list of include directories. Specified on the command-line * Invoke ocamldep and compute the dependencies of a .mli * Imported from {!IO.Printf} to avoid unsolvable dependencies *Direct dependency *Reverse dependency *All the nodes Find nodes which haven't been removed and depend on nothing Dependency [d] has been resolved, remove it. convs = (seek, replace) list split the rest of the slice don't replace in a replacement * The type of a module path *Information regarding where to find the signature for a module. *Path towards the .mli file containing the data for this module, e.g. "src/core/extlib/extList.mli" *Module path towards the interesting module, e.g. "List" * [(original, replacement)] *A module alias *Some uninterpreted content, such as unattached comments * Return the annotations on a tree * [extract_relevant_of_string file submodule] returns a string containing the relevant parts of [file]. If [submodule] is [[]], the relevant parts of [file] are the complete contents of [source]. If [submodule] is a module path, the relevant parts of [file] are only the contents of the corresponding path. * Read and parse the contents of a .dist file and return it without any additional processing ~old_comments ~old_comments * Go through a tree applying substitutions. For each leaf of the tree - read the [source] - extract the relevant part - apply the substitutions to the relevant part - write the substituted version to a temporary file - replace the leaf content with the temporary file name * Sort a list of modules topologically. [sort_modules l rename] sorts the modules of list [l]. Each name is transformed using [rename] before taking dependencies into account ([rename] serves chiefly to add prefixes). Collect dependencies *Recursively sort by dependencies each level of the tree. Then sort between children *Write down the tree * Drive the process
Build a .mli from a .dist file . Files with extension .dist are used to assemble modules into a consistent hierarchy . Essentially , .dist files are .ml files with additional annotations designed to allow generation of the corresponding .mli . Format of a .dist file : { [ ( * Module comment Build a .mli from a .dist file. Files with extension .dist are used to assemble modules into a consistent hierarchy. Essentially, .dist files are .ml files with additional annotations designed to allow generation of the corresponding .mli. Format of a .dist file: {[ module Sna = struct end ]} Producing a .ml is trivial, there's nothing to do. Producing a .mli is more complex: - parse the .dist file, keeping comments which don't start with % (gasp) - build the list of substitutions -- here, every occurrence of [InnerFoo] must become [Foo] -- here, every occurrence of [A.Module.Path] must become [Foo] -- here, every occurrence of [Yet.Another.Module.Path] must become [Sna.Toto] - build the list of source .mli - if necessary, generate each source .mli (so this needs to be done from myocamlbuild.ml) - from each %mli directive -- build a temporary file, obtained by ---- performing all the substitutions in the list -- invoke ocamldep -- parse the result of ocamldep and deduce a list of dependencies for the destination module (here, [Foo], [Bar], [Toto]) - bubble dependencies upwards in the tree of modules (here, [Sna] should inherit all the dependencies of [Toto]) - perform topological sort on dependencies - assuming topological sort has succeeded, generate a .mli where every module alias is replaced by the contents of the corresponding temporary .mli - write down all of this to a file. easy, isn't it? *) open Preprocess_common open Genlex open Camlp4.PreCast open Camlp4.Sig module StringSet = Set.Make(String) * { 6 Finding files } let include_dirs : string list ref = ref [] * { 6 Calling ocamldep } open Ocamlbuild_pack let stringset_of_ocamldep : string -> StringSet.t = fun file -> List.fold_left (fun acc (_, x) -> StringSet.add x acc) StringSet.empty (Ocaml_utils.path_dependencies_of file) * { 6 Utilities } module Printf = struct include Printf let make_list_printer (p:(out_channel -> 'b -> unit)) (start: string) (finish: string) (separate:string) (out:out_channel) (l: 'b list ) = let rec aux out l = match l with | [] -> () | [h] -> p out h | h::t -> fprintf out "%a%s%a" p h separate aux t in fprintf out "%s%a%s" start aux l finish end open Printf * { 6 Dependency sorting } module Dependency = struct type t = (string, StringSet.t) Hashtbl.t let create () = Hashtbl.create 100 let add tbl k dep = try Hashtbl.replace tbl k (StringSet.add dep (Hashtbl.find tbl k)) with Not_found -> Hashtbl.add tbl k (StringSet.singleton dep) let remove tbl (k:string) dep = try let set = StringSet.remove dep (Hashtbl.find tbl k) in if StringSet.is_empty set then Hashtbl.remove tbl k else Hashtbl.replace tbl k set with Not_found -> () let find tbl (k:string) = try Some (Hashtbl.find tbl k) with Not_found -> None let find_all tbl (k:string) = try StringSet.elements (Hashtbl.find tbl k) with Not_found -> [] let print out tbl = Printf.fprintf out "{"; Hashtbl.iter (fun k set -> Printf.fprintf out "%s: {%a}\n" k (Printf.make_list_printer (fun out -> Printf.fprintf out "%s") "{" "}" "; ") (StringSet.elements set)) tbl; Printf.fprintf out "}\n" end module Depsort = struct type t = { } let create () = { direct = Dependency.create (); reverse = Dependency.create (); set = ref StringSet.empty } let add_node t node = t.set := StringSet.add node !(t.set) let add_dependency t depending depended = Dependency.add t.direct depending depended; Dependency.add t.reverse depended depending; add_node t depending; add_node t depended let sort t = Printf.eprintf " Sorting % a\n " Dependency.print t.direct ; let rec aux (sorted:string list) (rest: string list) = match rest with | [] -> sorted | _ -> match List.fold_left (fun (keep, remove) k -> match Dependency.find t.direct k with | None -> (keep, k::remove) | Some dependencies -> (k::keep, remove) ) ([],[]) rest with | (_, []) -> Printf.eprintf "Cyclic dependencies in %a\n" Dependency.print t.direct; failwith "Cyclic dependencies" | (rest, roots) -> List.iter (fun d -> Printf.eprintf " Dependency % S resolved\n " d ; (fun x -> Dependency.remove t.direct x d) (Dependency.find_all t.reverse d)) roots; aux (sorted @ roots) rest in aux [] (StringSet.elements !(t.set)) end * { 6 String manipulation } module String = struct include String exception Invalid_string let find str ?(pos=0) ?(end_pos=length str) sub = let sublen = length sub in if sublen = 0 then 0 else let found = ref 0 in try for i = pos to end_pos - sublen do let j = ref 0 in while unsafe_get str (i + !j) = unsafe_get sub !j do incr j; if !j = sublen then begin found := i; raise Exit; end; done; done; raise Invalid_string with Exit -> !found let split str sep = let p = find str sep in let len = length sep in let slen = length str in sub str 0 p, sub str (p + len) (slen - p - len) let nsplit str sep = if str = "" then [] else ( let rec nsplit str sep = try let s1 , s2 = split str sep in s1 :: nsplit s2 sep with Invalid_string -> [str] in nsplit str sep ) type segment = Changed of string | Slice of int * int let repl_one slist (seek,repl) = let rec split_multi acc = function Slice (start_idx, end_idx) -> begin try let i = find str ~pos:start_idx ~end_pos:end_idx seek in split_multi accumulate slice & replacement (Changed repl :: Slice (start_idx,i-1) :: acc) (Slice (i+length seek, end_idx)) with Invalid_string -> Slice (start_idx,end_idx) :: acc end in List.fold_left split_multi [] slist in let to_str pieces = let len_p = function Changed s -> length s | Slice (a,b) -> b-a + 1 in let len = List.fold_left (fun a p -> a + len_p p) 0 pieces in let out = String.create len in let rec loop pos = function Slice (s, e) :: t -> String.blit str s out pos (e-s+1); loop (pos+e-s+1) t | Changed s :: t -> String.blit s 0 out pos (length s); loop (pos + length s) t | [] -> () in loop 0 pieces; out in to_str (List.fold_left repl_one [Slice (0,length str)] convs) end * { 6 Representation of the .dist file } type path = string list type sigsource = { } type comment = string list type ('a,'b) sigtree = 'a * (('a, 'b) sigtree_aux) and ('a,'b) sigtree_aux = | Node of string * ('a, 'b) sigtree list * comment let leaves_of (tree: (_, 'b) sigtree) : 'b list = let rec aux acc n = match n with | (_, Other _) -> acc | (_, Node (_, l, _)) -> List.fold_left aux acc l | (_, Leaf (_, x, _)) -> x :: acc in aux [] tree;; let extract_relevant_of_file (filename: string) (path: path) (subs:substitution list) = let ic = open_in filename in let buf= Buffer.create 1024 in let oc = Format.formatter_of_buffer buf in extract filename ic oc path; let contents = Buffer.contents buf in String.global_replace subs contents;; let parse_annotation stream = let parse_annotation_content stream = let rec aux ?mli ~aka ?path = parser | [< 'Kwd "aka"; 'String s; stream >] -> aux ?mli ~aka:(s::aka) ?path stream | [< 'Kwd "mli"; 'String mli; stream >] -> aux ~mli ~aka ?path stream | [< 'Kwd "submodule"; 'String s; stream >] -> aux ?mli ~aka ~path:s stream | [< >] -> (mli, aka, path) in aux ~aka:[] (make_lexer ["aka"; "mli"; "submodule"] stream) in let rec aux stream = match Stream.next stream with | ((BLANKS _ | NEWLINE), _) -> aux stream | (COMMENT c, _) -> if String.length c >= 1 && String.get c 0 = '%' then Some (parse_annotation_content (Stream.of_string c)) else None | _ -> None in aux stream let read_dist: in_channel -> string -> (unit, sigsource) sigtree * substitution list = fun channel name -> let renamings = ref [] in match Stream.next stream with ~old_comments:(recent_comments @ ) | (KEYWORD "module", _) -> begin skip_blanks stream; let id = parse_uident stream in skip_blanks stream; parse_equal stream; skip_blanks stream; match Stream.peek stream with | Some(KEYWORD "struct", _) -> njunk 1 stream; List.rev ( List.map ( fun x - > Other x ) ) @ [((),Node (id, aux ~recent_comments:[] stream ~path:(path^id^"."), List.rev recent_comments))] | _ -> begin let source_path = parse_path stream in renamings := (string_of_path source_path, id) :: (path, id) :: !renamings; match parse_annotation stream with | Some (Some mli, aka, Some path) -> List.iter (fun x -> renamings := (x, id)::!renamings) aka; let annot = { mli = mli; inner_path = path_of_string path } in ((), Leaf (id, annot, List.rev recent_comments)) :: aux ~recent_comments:[] ~path stream | None -> failwith "Missing annotation" | _ -> failwith "Incomplete annotation" end end | (EOI, _) -> [] | (tok, loc) -> [] in (((), Node ("", aux ~recent_comments:[] ~path:"" (tokens_of_channel name channel), [])), !renamings) let apply_substitutions: ('a, sigsource) sigtree -> substitution list -> ('a, string) sigtree = fun tree substitutions -> let rec aux = function | (tag, Leaf (name, {mli = mli; inner_path = inner_path}, comment)) -> let contents = extract_relevant_of_file mli inner_path substitutions in let filename = Filename.temp_file "ocamlbuild_distrib" ".mli" in let cout = open_out filename in output_string cout contents; (tag, Leaf (name, filename, comment)) | (tag, Node (name, tree, comment)) -> (tag, Node (name, List.map aux tree, comment)) | (tag, Other o) -> (tag, Other o) in aux tree * Compute dependencies of each node of the tree . For each leaf of the tree - apply ocamldep - parse the result into a list of dependencies For each node , merge the dependencies of subtrees . For each leaf of the tree - apply ocamldep - parse the result into a list of dependencies For each node, merge the dependencies of subtrees. *) let compute_dependencies: (unit, string) sigtree -> (StringSet.t, string) sigtree = fun tree -> let rec aux = function | ((), Other o) -> (StringSet.empty, Other o) | ((), Node (name, children, comment)) -> let (deps, rewritten) = List.fold_left (fun (deps, rewritten) child -> let ((child_deps, _) as child') = aux child in (StringSet.union deps child_deps, child'::rewritten)) (StringSet.empty, []) children in (deps, Node (name, rewritten, comment)) | ((), Leaf (name, file_name, comment))-> (stringset_of_ocamldep file_name, Leaf (name, file_name, comment)) in aux tree let sort_modules: ((StringSet.t, _) sigtree list as 'a) -> (string -> string) -> 'a = fun list prefix -> let dependencies = Depsort.create () and modules = Hashtbl.create 16 and others = ref [] in List.iter (function ((depends_on, Leaf (name, _, _)) as node) | ((depends_on, Node (name, _, _)) as node)-> Hashtbl.add modules name node; Depsort.add_node dependencies name; StringSet.iter (fun dep -> Depsort.add_dependency dependencies name' dep) depends_on | other -> others := other :: !others) list; List.rev_append !others (List.map (fun name -> Hashtbl.find modules name) (Depsort.sort dependencies)) let sort_tree : (StringSet.t, string) sigtree -> (StringSet.t, string) sigtree = fun tree -> let rec aux prefix = function | (_, Other _) as o -> o | (set, Node (name, children, comment)) -> First sort each child let prefix' = prefix ^ name ^ "." in let children = List.map (aux prefix') children in let mkprefix = fun s -> prefix' ^ s in (set, Node (name, sort_modules children mkprefix, comment)) | (_, Leaf _) as l -> l in aux "" tree let serialize_tree : Format.formatter -> (_, string) sigtree -> unit = fun out -> let serialize_comment out l = List.iter (Format.fprintf out "%s@\n") l in let rec aux = function | (_, Leaf (name, content, comment)) -> Format.fprintf out "%a@\nmodule %s : sig@[<v 5>%s@]@\n" serialize_comment comment name content | (_, Node (name, children, comment)) -> Format.fprintf out "%a@\nmodule %s = struct@[%a@]@\n" serialize_comment comment name (fun _ l -> List.iter aux l) children | (_, Other s) -> Format.fprintf out "%s@\n" s in aux let driver name cin cout = let (tree,substitutions) = read_dist cin name in let deps = compute_dependencies (apply_substitutions tree substitutions) in serialize_tree cout (sort_tree deps) let _ = let out_file = ref "" and in_file = ref "" in Arg.parse [("-I", Arg.String (fun x -> include_dirs := x :: !include_dirs), "Add include directory"); ("-o", Arg.Set_string out_file, "Set output .mli (standard out by default)")] (fun file -> out_file := file) "Generate a .mli file from a .dist"; let cout = match !out_file with | "" -> Format.std_formatter | s -> Format.formatter_of_out_channel (open_out s) and cin = match !in_file with | "" -> stdin | s -> open_in s in driver !in_file cin cout; flush_all ()
cde6f652c4c6433dfe8ac7814170f45d7686836f8d2a1e59ef63ec0347e494bd
keithj/cl-genomic
conditions.lisp
;;; Copyright ( c ) 2007 - 2011 . All rights reserved . ;;; ;;; This file is part of cl-genomic. ;;; ;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 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 General Public License for more details. ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see </>. ;;; (in-package :bio-sequence) (define-condition bio-sequence-error (error) () (:documentation "The parent type of all bio-sequence error conditions.")) (define-condition bio-sequence-warning (warning) () (:documentation "The parent type of all bio-sequence warning conditions.")) ;; (define-condition bio-sequence-io-error (io-error ;; bio-sequence-error) ( ( text : initform nil ;; :initarg :text ;; :reader text-of ;; :documentation "Error message text.")) ;; (:report (lambda (condition stream) ;; (format stream "IO error~@[: ~a~]" ;; (text-of condition)))) ;; (:documentation "An error that is raised when performing stream IO ;; on bio-sequences.")) ;; (define-condition bio-sequence-parse-error (general-parse-error ;; bio-sequence-io-error) ( ( text : initform nil ;; :initarg :text ;; :reader text-of ;; :documentation "Error message text.")) ;; (:report (lambda (condition stream) ;; (format stream "IO error~@[: ~a~]" ;; (text-of condition)))) ;; (:documentation "An error that is raised when performing stream IO ;; on bio-sequences.")) (define-condition bio-sequence-op-error (invalid-operation-error bio-sequence-error simple-text-condition) () (:report (lambda (condition stream) (format stream "Invalid bio-sequence operation~@[: ~a~]" (message-of condition)))) (:documentation "An error that is raised when performing operations on bio-sequences.")) (define-condition initiator-codon-error (bio-sequence-op-error) ((codon :initform nil :initarg :codon :reader codon-of :documentation "The invalid codon.") (genetic-code :initform nil :initarg :genetic-code :reader genetic-code-of :documentation "The genetic code used to translate.")) (:report (lambda (condition stream) (format stream "Codon ~a is not an initiator in ~a" (codon-of condition) (genetic-code-of condition)))) (:documentation "An error that is raised when attempting to translate a non-initiator codon as an initiator.")) (define-condition translation-error (bio-sequence-op-error) ((seq :initform nil :initarg :sequence :reader sequence-of :documentation "The translated sequence.") (start :initform nil :initarg :start :reader start-of :documentation "The translation start position.") (end :initform nil :initarg :end :reader end-of :documentation "The translation end position.") (genetic-code :initform nil :initarg :genetic-code :reader genetic-code-of :documentation "The genetic code used to translate.")) (:report (lambda (condition stream) (format stream "Invalid translation of ~a~@[: ~a~]" (sequence-of condition) (message-of condition)))) (:documentation "An error that is raised when attempting an invalid translation of a sequence."))
null
https://raw.githubusercontent.com/keithj/cl-genomic/d160199c2b369df97afd3fded16b1ade507b80dd/src/conditions.lisp
lisp
This file is part of cl-genomic. This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. (define-condition bio-sequence-io-error (io-error bio-sequence-error) :initarg :text :reader text-of :documentation "Error message text.")) (:report (lambda (condition stream) (format stream "IO error~@[: ~a~]" (text-of condition)))) (:documentation "An error that is raised when performing stream IO on bio-sequences.")) (define-condition bio-sequence-parse-error (general-parse-error bio-sequence-io-error) :initarg :text :reader text-of :documentation "Error message text.")) (:report (lambda (condition stream) (format stream "IO error~@[: ~a~]" (text-of condition)))) (:documentation "An error that is raised when performing stream IO on bio-sequences."))
Copyright ( c ) 2007 - 2011 . All rights reserved . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (in-package :bio-sequence) (define-condition bio-sequence-error (error) () (:documentation "The parent type of all bio-sequence error conditions.")) (define-condition bio-sequence-warning (warning) () (:documentation "The parent type of all bio-sequence warning conditions.")) ( ( text : initform nil ( ( text : initform nil (define-condition bio-sequence-op-error (invalid-operation-error bio-sequence-error simple-text-condition) () (:report (lambda (condition stream) (format stream "Invalid bio-sequence operation~@[: ~a~]" (message-of condition)))) (:documentation "An error that is raised when performing operations on bio-sequences.")) (define-condition initiator-codon-error (bio-sequence-op-error) ((codon :initform nil :initarg :codon :reader codon-of :documentation "The invalid codon.") (genetic-code :initform nil :initarg :genetic-code :reader genetic-code-of :documentation "The genetic code used to translate.")) (:report (lambda (condition stream) (format stream "Codon ~a is not an initiator in ~a" (codon-of condition) (genetic-code-of condition)))) (:documentation "An error that is raised when attempting to translate a non-initiator codon as an initiator.")) (define-condition translation-error (bio-sequence-op-error) ((seq :initform nil :initarg :sequence :reader sequence-of :documentation "The translated sequence.") (start :initform nil :initarg :start :reader start-of :documentation "The translation start position.") (end :initform nil :initarg :end :reader end-of :documentation "The translation end position.") (genetic-code :initform nil :initarg :genetic-code :reader genetic-code-of :documentation "The genetic code used to translate.")) (:report (lambda (condition stream) (format stream "Invalid translation of ~a~@[: ~a~]" (sequence-of condition) (message-of condition)))) (:documentation "An error that is raised when attempting an invalid translation of a sequence."))
e507832c82568438a70cec67abf58dda0c67ad1dce980cd1b0f236ae7e06cffc
ejgallego/coq-serapi
sertop_sexp.mli
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * INRIA , CNRS and contributors - Copyright 1999 - 2018 (* <O___,, * (see CREDITS file for the list of authors) *) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) (************************************************************************) (* Coq serialization API/Plugin *) Copyright 2016 - 2018 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 + Written by : (************************************************************************) (* Status: Very Experimental *) (************************************************************************) (************************************************************************) (* Global Protocol Options *) (************************************************************************) type ser_opts = { in_chan : in_channel ; out_chan : out_channel (** Input/Output channels *) ; printer : Sertop_ser.ser_printer (** Printer type *) ; debug : bool (** Enable Coq debug mode *) ; set_impredicative_set: bool (** Enable Coq -impredicative-set option *) * Allow using the proof irrelevant sort ; indices_matter : bool (** Indices of indexes contribute to inductive level *) ; print0 : bool (** End every answer with [\0] *) ; lheader : bool (** Print lenght header (deprecated) *) ; no_init : bool (** Whether to create the initial document *) ; no_prelude : bool (** Whether to load stdlib's prelude *) ; topfile : string option (** Top name is derived from topfile name *) Coq options ; ml_path : string list ; vo_path : Loadpath.vo_path list (** From -R and -Q options usually *) ; async : Sertop_init.async_flags (** Async flags *) } (** Options for the sertop interactive toplevel *) (******************************************************************************) (* Input/Output -- Main Loop *) (******************************************************************************) val ser_loop : ser_opts -> unit * [ ser_loop opts ] main se(xp)r - protocol interactive loop
null
https://raw.githubusercontent.com/ejgallego/coq-serapi/dd9e3fbf7faaf3bf365fa3eff134641055151a9b/sertop/sertop_sexp.mli
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team <O___,, * (see CREDITS file for the list of authors) // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** ********************************************************************** Coq serialization API/Plugin ********************************************************************** Status: Very Experimental ********************************************************************** ********************************************************************** Global Protocol Options ********************************************************************** * Input/Output channels * Printer type * Enable Coq debug mode * Enable Coq -impredicative-set option * Indices of indexes contribute to inductive level * End every answer with [\0] * Print lenght header (deprecated) * Whether to create the initial document * Whether to load stdlib's prelude * Top name is derived from topfile name * From -R and -Q options usually * Async flags * Options for the sertop interactive toplevel **************************************************************************** Input/Output -- Main Loop ****************************************************************************
v * INRIA , CNRS and contributors - Copyright 1999 - 2018 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 Copyright 2016 - 2018 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 + Written by : type ser_opts = { in_chan : in_channel ; printer : Sertop_ser.ser_printer * Allow using the proof irrelevant sort Coq options ; ml_path : string list ; async : Sertop_init.async_flags } val ser_loop : ser_opts -> unit * [ ser_loop opts ] main se(xp)r - protocol interactive loop
29f3a839a438a4d8f461478dd9416388d4ec805c457d666b00d3c43bd78e7a87
OCamlPro/typerex-lint
type_collector.mli
val typ_collector : (string * Parsetree.core_type) list ref -> Ast_mapper.mapper val collect : Parsetree.type_declaration list -> Parsetree.type_declaration list
null
https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/libs/ocplib-sempatch/lib/automaton/generator/type_collector.mli
ocaml
val typ_collector : (string * Parsetree.core_type) list ref -> Ast_mapper.mapper val collect : Parsetree.type_declaration list -> Parsetree.type_declaration list
772ea90799b0f97580786b3615cf0cc57ead3ba5eb4d01f08cd0129fae58e15a
SjVer/Som-Lang
malfunction_compiler.mli
type outfiles = { objfile : string; cmxfile : string; cmifile : string option } val delete_temps : outfiles -> unit val compile_module : filename:string -> Malfunction.moduleexp -> outfiles val link_executable : string -> outfiles -> int
null
https://raw.githubusercontent.com/SjVer/Som-Lang/4d2f62d7f3bfe5929a962bdeddbd94ea75439ad7/somc/lib/malfunction/malfunction_compiler.mli
ocaml
type outfiles = { objfile : string; cmxfile : string; cmifile : string option } val delete_temps : outfiles -> unit val compile_module : filename:string -> Malfunction.moduleexp -> outfiles val link_executable : string -> outfiles -> int
bc444a572578d5697be7297695d8a807882bf2079d4c32e5b904017b4a864d73
pcapriotti/optparse-applicative
Help.hs
module Options.Applicative.Help ( -- | This is an empty module which re-exports -- the help text system for optparse. | Pretty printer . most combinators from Text . PrettyPrint . module Options.Applicative.Help.Pretty, -- | A free monoid over Doc with helpers for -- composing help text components. module Options.Applicative.Help.Chunk, -- | Types required by the help system. module Options.Applicative.Help.Types, -- | Core implementation of the help text -- generator. module Options.Applicative.Help.Core, -- | Edit distance calculations for suggestions module Options.Applicative.Help.Levenshtein ) where import Options.Applicative.Help.Chunk import Options.Applicative.Help.Core import Options.Applicative.Help.Levenshtein import Options.Applicative.Help.Pretty import Options.Applicative.Help.Types
null
https://raw.githubusercontent.com/pcapriotti/optparse-applicative/8edc41994984cbfdfc1ee960e4d4d112cfccbc11/src/Options/Applicative/Help.hs
haskell
| This is an empty module which re-exports the help text system for optparse. | A free monoid over Doc with helpers for composing help text components. | Types required by the help system. | Core implementation of the help text generator. | Edit distance calculations for suggestions
module Options.Applicative.Help ( | Pretty printer . most combinators from Text . PrettyPrint . module Options.Applicative.Help.Pretty, module Options.Applicative.Help.Chunk, module Options.Applicative.Help.Types, module Options.Applicative.Help.Core, module Options.Applicative.Help.Levenshtein ) where import Options.Applicative.Help.Chunk import Options.Applicative.Help.Core import Options.Applicative.Help.Levenshtein import Options.Applicative.Help.Pretty import Options.Applicative.Help.Types
29cd1d10cb27b25f1e0871468786b69b5e37569b552f996fa01d972fa288f845
capnproto/capnp-ocaml
generate.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * capnp - ocaml * * Copyright ( c ) 2013 - 2014 , * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are met : * * 1 . Redistributions of source code must retain the above copyright notice , * this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " * AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR * CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS * INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN * CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * capnp-ocaml * * Copyright (c) 2013-2014, Paul Pelzl * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************) module Uint64 = Stdint.Uint64 module List = Base.List module String = Base.String module Hashtbl = Base.Hashtbl module Out_channel = Stdio.Out_channel module PS = GenCommon.PS module C = Capnp module Context = GenCommon.Context module Mode = GenCommon.Mode let sig_s_header ~context = [ "[@@@ocaml.warning \"-27-32-37-60\"]"; ""; "type ro = Capnp.Message.ro"; "type rw = Capnp.Message.rw"; ""; "module type S = sig"; " module MessageWrapper : Capnp.RPC.S"; " type 'cap message_t = 'cap MessageWrapper.Message.t"; " type 'a reader_t = 'a MessageWrapper.StructStorage.reader_t"; " type 'a builder_t = 'a MessageWrapper.StructStorage.builder_t"; ""; ] @ (List.concat_map context.Context.imports ~f:(fun import -> [ " module " ^ import.Context.schema_name ^ " : " ^ import.Context.module_name ^ ".S with"; " module MessageWrapper = MessageWrapper"; ""; ])) let sig_s_reader_header = [ ""; " module Reader : sig"; " type array_t"; " type builder_array_t"; " type pointer_t = ro MessageWrapper.Slice.t option"; " val of_pointer : pointer_t -> 'a reader_t"; ] let sig_s_divide_reader_builder = [ " end"; ""; " module Builder : sig"; " type array_t = Reader.builder_array_t"; " type reader_array_t = Reader.array_t"; " type pointer_t = rw MessageWrapper.Slice.t"; ] let sig_s_client_header = [ ""; " module Client : sig"; ] let sig_s_divide_client_service = [ " end"; ""; " module Service : sig"; ] let sig_s_service_footer = [ " end"; ] let sig_s_footer = [ " end"; "end"; ""; ] let functor_sig ~context ~rpc = [ "module MakeRPC(MessageWrapper : Capnp.RPC.S) : sig"; " include S with module MessageWrapper = MessageWrapper"; ] @ (List.concat_map context.Context.imports ~f:(fun import -> [ " and module " ^ import.Context.schema_name ^ " = " ^ import.Context.module_name ^ ".MakeRPC(MessageWrapper)"; ])) @ rpc @ [ "end"; ""; "module Make(M : Capnp.MessageSig.S) : module type of MakeRPC(Capnp.RPC.None(M))"; ] let mod_functor_header = [ "module MakeRPC(MessageWrapper : Capnp.RPC.S) = struct"; " type 'a reader_t = 'a MessageWrapper.StructStorage.reader_t"; " type 'a builder_t = 'a MessageWrapper.StructStorage.builder_t"; " module CamlBytes = Bytes"; ] let mod_header ~context = [ " let invalid_msg = Capnp.Message.invalid_msg"; ""; " include Capnp.Runtime.BuilderInc.Make[@inlined](MessageWrapper)"; ""; " type 'cap message_t = 'cap MessageWrapper.Message.t"; ""; ] @ (List.concat_map context.Context.imports ~f:(fun import -> [ " module " ^ import.Context.schema_name ^ " = " ^ import.Context.module_name ^ ".MakeRPC(MessageWrapper)"; ""; ])) let mod_reader_header = [ ""; " module Reader = struct"; " type array_t = ro MessageWrapper.ListStorage.t"; " type builder_array_t = rw MessageWrapper.ListStorage.t"; " type pointer_t = ro MessageWrapper.Slice.t option"; " let of_pointer = RA_.deref_opt_struct_pointer"; ""; ] let mod_divide_reader_builder = [ " end"; ""; " module Builder = struct"; " type array_t = Reader.builder_array_t"; " type reader_array_t = Reader.array_t"; " type pointer_t = rw MessageWrapper.Slice.t"; ""; ] let mod_divide_builder_client = [ " end"; ""; " module Client = struct"; ] let mod_divide_client_service = [ " end"; ""; " module Service = struct"; ] let mod_footer = [ " end"; ] let mod_functor_footer = [ " module MessageWrapper = MessageWrapper"; "end [@@inline]"; ""; "module Make(M:Capnp.MessageSig.S) = MakeRPC[@inlined](Capnp.RPC.None(M)) [@@inline]"; ] let ml_filename filename = let module_name = GenCommon.make_legal_module_name filename in String.uncapitalize (module_name ^ ".ml") let mli_filename filename = let module_name = GenCommon.make_legal_module_name filename in String.uncapitalize (module_name ^ ".mli") let string_of_lines lines = (String.concat ~sep:"\n" lines) ^ "\n" let calculate_positions ~nodes ~requested_file_node = let positions = Hashtbl.Poly.create ~size:(Hashtbl.Poly.length nodes) () in let pos = ref 0 in let rec scan node = let id = PS.Node.id_get node in Hashtbl.Poly.add_exn positions ~key:id ~data:!pos; pos := succ !pos; let children = GenCommon.child_ids_of node |> List.map ~f:(Hashtbl.Poly.find_exn nodes) in List.iter children ~f:scan in scan requested_file_node; positions let compile (request : PS.CodeGeneratorRequest.t) : unit = let nodes_table = Hashtbl.Poly.create () in let nodes = PS.CodeGeneratorRequest.nodes_get request in let () = C.Array.iter nodes ~f:(fun node -> Hashtbl.set nodes_table ~key:(PS.Node.id_get node) ~data:node) in let requested_files = PS.CodeGeneratorRequest.requested_files_get request in C.Array.iter requested_files ~f:(fun requested_file -> let open PS.CodeGeneratorRequest in let requested_file_id = RequestedFile.id_get requested_file in let requested_file_node = Hashtbl.find_exn nodes_table requested_file_id in let requested_filename = RequestedFile.filename_get requested_file in let imports = C.Array.map_list (RequestedFile.imports_get requested_file) ~f:(fun import -> let import_id = RequestedFile.Import.id_get import in let schema_filename = RequestedFile.Import.name_get import in let module_name = GenCommon.make_legal_module_name schema_filename in { Context.id = import_id; Context.schema_name = module_name ^ "_" ^ (Uint64.to_string import_id); Context.module_name = module_name }) in let context_unfiltered = { Context.nodes = nodes_table; Context.imports = imports; Context.positions = calculate_positions ~nodes:nodes_table ~requested_file_node; } in let context = GenCommon.filter_interesting_imports ~context:context_unfiltered requested_file_node in let sig_unique_enums = GenCommon.apply_indent ~indent:" " (GenCommon.collect_unique_enums ~is_sig:true ~context requested_file_node) in let mod_unique_enums = GenCommon.apply_indent ~indent:" " (GenCommon.collect_unique_enums ~is_sig:false ~context requested_file_node) in let sig_s = (sig_s_header ~context) @ sig_unique_enums @ sig_s_reader_header @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Reader ~node_name:requested_filename requested_file_node)) @ sig_s_divide_reader_builder @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Builder ~node_name:requested_filename requested_file_node)) @ sig_s_footer in let sig_file_content = let rpc = sig_s_client_header @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_clients ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node)) @ sig_s_divide_client_service @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_services ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node)) @ sig_s_service_footer in string_of_lines (sig_s @ (functor_sig ~context ~rpc)) in let mod_shared_content = let defaults_context = GenModules.build_defaults_context ~context ~node_name:requested_filename requested_file_node in let reader_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Reader ~node_name:requested_filename requested_file_node) in let builder_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Builder ~node_name:requested_filename requested_file_node) in let builder_defaults = GenCommon.apply_indent ~indent:" " (Defaults.gen_builder_defaults defaults_context) in let reader_defaults = GenCommon.apply_indent ~indent:" " (Defaults.gen_reader_defaults defaults_context) in let client_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_clients ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node) in let service_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_services ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node) in builder_defaults @ (mod_header ~context) @ mod_unique_enums @ reader_defaults @ mod_reader_header @ reader_body @ mod_divide_reader_builder @ builder_body @ mod_divide_builder_client @ client_body @ mod_divide_client_service @ service_body @ mod_footer in let mod_file_content = string_of_lines ( sig_s @ mod_functor_header @ mod_shared_content @ mod_functor_footer) in let () = Out_channel.with_file (mli_filename requested_filename) ~f:(fun chan -> Out_channel.output_string chan sig_file_content) in let () = Out_channel.with_file (ml_filename requested_filename) ~f:(fun chan -> Out_channel.output_string chan mod_file_content) in let () = Printf.printf "%s --> %s %s\n" requested_filename (mli_filename requested_filename) (ml_filename requested_filename) in ())
null
https://raw.githubusercontent.com/capnproto/capnp-ocaml/dda3d811aa7734110d7af051465011f1f823ffb9/src/compiler/generate.ml
ocaml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * capnp - ocaml * * Copyright ( c ) 2013 - 2014 , * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are met : * * 1 . Redistributions of source code must retain the above copyright notice , * this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " * AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR * CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS * INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN * CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * capnp-ocaml * * Copyright (c) 2013-2014, Paul Pelzl * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************) module Uint64 = Stdint.Uint64 module List = Base.List module String = Base.String module Hashtbl = Base.Hashtbl module Out_channel = Stdio.Out_channel module PS = GenCommon.PS module C = Capnp module Context = GenCommon.Context module Mode = GenCommon.Mode let sig_s_header ~context = [ "[@@@ocaml.warning \"-27-32-37-60\"]"; ""; "type ro = Capnp.Message.ro"; "type rw = Capnp.Message.rw"; ""; "module type S = sig"; " module MessageWrapper : Capnp.RPC.S"; " type 'cap message_t = 'cap MessageWrapper.Message.t"; " type 'a reader_t = 'a MessageWrapper.StructStorage.reader_t"; " type 'a builder_t = 'a MessageWrapper.StructStorage.builder_t"; ""; ] @ (List.concat_map context.Context.imports ~f:(fun import -> [ " module " ^ import.Context.schema_name ^ " : " ^ import.Context.module_name ^ ".S with"; " module MessageWrapper = MessageWrapper"; ""; ])) let sig_s_reader_header = [ ""; " module Reader : sig"; " type array_t"; " type builder_array_t"; " type pointer_t = ro MessageWrapper.Slice.t option"; " val of_pointer : pointer_t -> 'a reader_t"; ] let sig_s_divide_reader_builder = [ " end"; ""; " module Builder : sig"; " type array_t = Reader.builder_array_t"; " type reader_array_t = Reader.array_t"; " type pointer_t = rw MessageWrapper.Slice.t"; ] let sig_s_client_header = [ ""; " module Client : sig"; ] let sig_s_divide_client_service = [ " end"; ""; " module Service : sig"; ] let sig_s_service_footer = [ " end"; ] let sig_s_footer = [ " end"; "end"; ""; ] let functor_sig ~context ~rpc = [ "module MakeRPC(MessageWrapper : Capnp.RPC.S) : sig"; " include S with module MessageWrapper = MessageWrapper"; ] @ (List.concat_map context.Context.imports ~f:(fun import -> [ " and module " ^ import.Context.schema_name ^ " = " ^ import.Context.module_name ^ ".MakeRPC(MessageWrapper)"; ])) @ rpc @ [ "end"; ""; "module Make(M : Capnp.MessageSig.S) : module type of MakeRPC(Capnp.RPC.None(M))"; ] let mod_functor_header = [ "module MakeRPC(MessageWrapper : Capnp.RPC.S) = struct"; " type 'a reader_t = 'a MessageWrapper.StructStorage.reader_t"; " type 'a builder_t = 'a MessageWrapper.StructStorage.builder_t"; " module CamlBytes = Bytes"; ] let mod_header ~context = [ " let invalid_msg = Capnp.Message.invalid_msg"; ""; " include Capnp.Runtime.BuilderInc.Make[@inlined](MessageWrapper)"; ""; " type 'cap message_t = 'cap MessageWrapper.Message.t"; ""; ] @ (List.concat_map context.Context.imports ~f:(fun import -> [ " module " ^ import.Context.schema_name ^ " = " ^ import.Context.module_name ^ ".MakeRPC(MessageWrapper)"; ""; ])) let mod_reader_header = [ ""; " module Reader = struct"; " type array_t = ro MessageWrapper.ListStorage.t"; " type builder_array_t = rw MessageWrapper.ListStorage.t"; " type pointer_t = ro MessageWrapper.Slice.t option"; " let of_pointer = RA_.deref_opt_struct_pointer"; ""; ] let mod_divide_reader_builder = [ " end"; ""; " module Builder = struct"; " type array_t = Reader.builder_array_t"; " type reader_array_t = Reader.array_t"; " type pointer_t = rw MessageWrapper.Slice.t"; ""; ] let mod_divide_builder_client = [ " end"; ""; " module Client = struct"; ] let mod_divide_client_service = [ " end"; ""; " module Service = struct"; ] let mod_footer = [ " end"; ] let mod_functor_footer = [ " module MessageWrapper = MessageWrapper"; "end [@@inline]"; ""; "module Make(M:Capnp.MessageSig.S) = MakeRPC[@inlined](Capnp.RPC.None(M)) [@@inline]"; ] let ml_filename filename = let module_name = GenCommon.make_legal_module_name filename in String.uncapitalize (module_name ^ ".ml") let mli_filename filename = let module_name = GenCommon.make_legal_module_name filename in String.uncapitalize (module_name ^ ".mli") let string_of_lines lines = (String.concat ~sep:"\n" lines) ^ "\n" let calculate_positions ~nodes ~requested_file_node = let positions = Hashtbl.Poly.create ~size:(Hashtbl.Poly.length nodes) () in let pos = ref 0 in let rec scan node = let id = PS.Node.id_get node in Hashtbl.Poly.add_exn positions ~key:id ~data:!pos; pos := succ !pos; let children = GenCommon.child_ids_of node |> List.map ~f:(Hashtbl.Poly.find_exn nodes) in List.iter children ~f:scan in scan requested_file_node; positions let compile (request : PS.CodeGeneratorRequest.t) : unit = let nodes_table = Hashtbl.Poly.create () in let nodes = PS.CodeGeneratorRequest.nodes_get request in let () = C.Array.iter nodes ~f:(fun node -> Hashtbl.set nodes_table ~key:(PS.Node.id_get node) ~data:node) in let requested_files = PS.CodeGeneratorRequest.requested_files_get request in C.Array.iter requested_files ~f:(fun requested_file -> let open PS.CodeGeneratorRequest in let requested_file_id = RequestedFile.id_get requested_file in let requested_file_node = Hashtbl.find_exn nodes_table requested_file_id in let requested_filename = RequestedFile.filename_get requested_file in let imports = C.Array.map_list (RequestedFile.imports_get requested_file) ~f:(fun import -> let import_id = RequestedFile.Import.id_get import in let schema_filename = RequestedFile.Import.name_get import in let module_name = GenCommon.make_legal_module_name schema_filename in { Context.id = import_id; Context.schema_name = module_name ^ "_" ^ (Uint64.to_string import_id); Context.module_name = module_name }) in let context_unfiltered = { Context.nodes = nodes_table; Context.imports = imports; Context.positions = calculate_positions ~nodes:nodes_table ~requested_file_node; } in let context = GenCommon.filter_interesting_imports ~context:context_unfiltered requested_file_node in let sig_unique_enums = GenCommon.apply_indent ~indent:" " (GenCommon.collect_unique_enums ~is_sig:true ~context requested_file_node) in let mod_unique_enums = GenCommon.apply_indent ~indent:" " (GenCommon.collect_unique_enums ~is_sig:false ~context requested_file_node) in let sig_s = (sig_s_header ~context) @ sig_unique_enums @ sig_s_reader_header @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Reader ~node_name:requested_filename requested_file_node)) @ sig_s_divide_reader_builder @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Builder ~node_name:requested_filename requested_file_node)) @ sig_s_footer in let sig_file_content = let rpc = sig_s_client_header @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_clients ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node)) @ sig_s_divide_client_service @ (GenCommon.apply_indent ~indent:" " (GenSignatures.generate_services ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node)) @ sig_s_service_footer in string_of_lines (sig_s @ (functor_sig ~context ~rpc)) in let mod_shared_content = let defaults_context = GenModules.build_defaults_context ~context ~node_name:requested_filename requested_file_node in let reader_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Reader ~node_name:requested_filename requested_file_node) in let builder_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_node ~suppress_module_wrapper:true ~context ~scope:[] ~mode:Mode.Builder ~node_name:requested_filename requested_file_node) in let builder_defaults = GenCommon.apply_indent ~indent:" " (Defaults.gen_builder_defaults defaults_context) in let reader_defaults = GenCommon.apply_indent ~indent:" " (Defaults.gen_reader_defaults defaults_context) in let client_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_clients ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node) in let service_body = GenCommon.apply_indent ~indent:" " (GenModules.generate_services ~suppress_module_wrapper:true ~context ~scope:[] ~node_name:requested_filename requested_file_node) in builder_defaults @ (mod_header ~context) @ mod_unique_enums @ reader_defaults @ mod_reader_header @ reader_body @ mod_divide_reader_builder @ builder_body @ mod_divide_builder_client @ client_body @ mod_divide_client_service @ service_body @ mod_footer in let mod_file_content = string_of_lines ( sig_s @ mod_functor_header @ mod_shared_content @ mod_functor_footer) in let () = Out_channel.with_file (mli_filename requested_filename) ~f:(fun chan -> Out_channel.output_string chan sig_file_content) in let () = Out_channel.with_file (ml_filename requested_filename) ~f:(fun chan -> Out_channel.output_string chan mod_file_content) in let () = Printf.printf "%s --> %s %s\n" requested_filename (mli_filename requested_filename) (ml_filename requested_filename) in ())
3ccaa8e141f307056f0ecad02a5db96aaf1099b2a820239a7a0ed6518a482151
facebook/pyre-check
cache.ml
* 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. *) (* Cache: implements caching capabilities for the taint analysis. This is what * powers the `--use-cache` command line option. This is basically implemented * by writing the shared memory into a file and restoring it later. *) open Core open Pyre module TypeEnvironment = Analysis.TypeEnvironment module AstEnvironment = Analysis.AstEnvironment module FetchCallables = Interprocedural.FetchCallables module ClassHierarchyGraph = Interprocedural.ClassHierarchyGraph module OverrideGraph = Interprocedural.OverrideGraph module InitialCallablesSharedMemory = Memory.Serializer (struct type t = FetchCallables.t module Serialized = struct type t = FetchCallables.t let prefix = Prefix.make () let description = "Initial callables to analyze" end let serialize = Fn.id let deserialize = Fn.id end) module OverrideGraphSharedMemory = Memory.Serializer (struct type t = OverrideGraph.whole_program_overrides module Serialized = struct type t = OverrideGraph.whole_program_overrides let prefix = Prefix.make () let description = "Cached override graph" end let serialize = Fn.id let deserialize = Fn.id end) module ClassHierarchyGraphSharedMemory = Memory.Serializer (struct type t = ClassHierarchyGraph.Heap.t module Serialized = struct type t = ClassHierarchyGraph.Heap.t let prefix = Prefix.make () let description = "Class hierarchy graph" end let serialize = Fn.id let deserialize = Fn.id end) type cached = { type_environment: TypeEnvironment.t } type error = | InvalidByCodeChange | LoadError | NotFound | Disabled type t = { cache: (cached, error) Result.t; save_cache: bool; scheduler: Scheduler.t; configuration: Configuration.Analysis.t; } let get_save_directory ~configuration = PyrePath.create_relative ~root:(Configuration.Analysis.log_directory configuration) ~relative:".pysa_cache" let get_shared_memory_save_path ~configuration = PyrePath.append (get_save_directory ~configuration) ~element:"sharedmem" let exception_to_error ~error ~message ~f = try f () with | exception_ -> Log.error "Error %s:\n%s" message (Exn.to_string exception_); Error error let ignore_result (_ : ('a, 'b) result) = () let initialize_shared_memory ~configuration = let path = get_shared_memory_save_path ~configuration in if not (PyrePath.file_exists path) then ( Log.warning "Could not find a cached state."; Error NotFound) else exception_to_error ~error:LoadError ~message:"loading cached state" ~f:(fun () -> Log.info "Loading cached state from `%s`" (PyrePath.absolute (get_save_directory ~configuration)); let _ = Memory.get_heap_handle configuration in Memory.load_shared_memory ~path:(PyrePath.absolute path) ~configuration; Log.info "Cached state successfully loaded."; Ok ()) let load_type_environment ~scheduler ~configuration = let open Result in let controls = Analysis.EnvironmentControls.create configuration in Log.info "Determining if source files have changed since cache was created."; exception_to_error ~error:LoadError ~message:"Loading type environment" ~f:(fun () -> Ok (TypeEnvironment.load controls)) >>= fun type_environment -> let old_module_tracker = TypeEnvironment.ast_environment type_environment |> AstEnvironment.module_tracker in let new_module_tracker = Analysis.ModuleTracker.create controls in let changed_paths = let is_pysa_model path = String.is_suffix ~suffix:".pysa" (PyrePath.get_suffix_path path) in let is_taint_config path = String.is_suffix ~suffix:"taint.config" (PyrePath.absolute path) in Interprocedural.ChangedPaths.compute_locally_changed_paths ~scheduler ~configuration ~old_module_tracker ~new_module_tracker |> List.map ~f:ArtifactPath.raw |> List.filter ~f:(fun path -> not (is_pysa_model path || is_taint_config path)) in match changed_paths with | [] -> Ok type_environment | _ -> Log.warning "Changes to source files detected, ignoring existing cache."; Error InvalidByCodeChange let load ~scheduler ~configuration ~taint_configuration ~enabled = if not enabled then { cache = Error Disabled; save_cache = false; scheduler; configuration } else let open Result in let type_environment = initialize_shared_memory ~configuration >>= fun () -> load_type_environment ~scheduler ~configuration in let cache = match type_environment with | Ok type_environment -> Ok { type_environment } | Error error -> Memory.reset_shared_memory (); Error error in (* Re-write the original taint configuration in shared memory, * in case it was overwritten when loading the cache. *) let (_ : TaintConfiguration.SharedMemory.t) = TaintConfiguration.SharedMemory.from_heap taint_configuration in { cache; save_cache = true; scheduler; configuration } let save_type_environment ~scheduler ~configuration ~environment = exception_to_error ~error:() ~message:"saving type environment to cache" ~f:(fun () -> Memory.SharedMemory.collect `aggressive; let module_tracker = TypeEnvironment.module_tracker environment in Interprocedural.ChangedPaths.save_current_paths ~scheduler ~configuration ~module_tracker; TypeEnvironment.store environment; Log.info "Saved type environment to cache shared memory."; Ok ()) let type_environment { cache; save_cache; scheduler; configuration } f = match cache with | Ok { type_environment } -> type_environment | _ -> let environment = f () in if save_cache then save_type_environment ~scheduler ~configuration ~environment |> ignore_result; environment let load_initial_callables () = exception_to_error ~error:LoadError ~message:"loading initial callables from cache" ~f:(fun () -> Log.info "Loading initial callables from cache..."; let initial_callables = InitialCallablesSharedMemory.load () in Log.info "Loaded initial callables from cache."; Ok initial_callables) let ensure_save_directory_exists ~configuration = let directory = PyrePath.absolute (get_save_directory ~configuration) in try Core_unix.mkdir directory with [ mkdir ] on returns [ EISDIR ] instead of [ EEXIST ] if the directory already exists . | Core_unix.Unix_error ((EEXIST | EISDIR), _, _) -> () | e -> raise e let save_shared_memory ~configuration = exception_to_error ~error:() ~message:"saving cached state to file" ~f:(fun () -> let path = get_shared_memory_save_path ~configuration in Log.info "Saving shared memory state to cache file..."; ensure_save_directory_exists ~configuration; Memory.SharedMemory.collect `aggressive; Memory.save_shared_memory ~path:(PyrePath.absolute path) ~configuration; Log.info "Saved shared memory state to cache file: `%s`" (PyrePath.absolute path); Ok ()) let save { save_cache; configuration; _ } = if save_cache then save_shared_memory ~configuration |> ignore let save_initial_callables ~initial_callables = exception_to_error ~error:() ~message:"saving initial callables to cache" ~f:(fun () -> Memory.SharedMemory.collect `aggressive; InitialCallablesSharedMemory.store initial_callables; Log.info "Saved initial callables to cache shared memory."; Ok ()) let initial_callables { cache; save_cache; _ } f = let initial_callables = match cache with | Ok _ -> load_initial_callables () |> Result.ok | _ -> None in match initial_callables with | Some initial_callables -> initial_callables | None -> let callables = f () in if save_cache then save_initial_callables ~initial_callables:callables |> ignore_result; callables let load_overrides () = exception_to_error ~error:LoadError ~message:"loading overrides from cache" ~f:(fun () -> Log.info "Loading overrides from cache..."; let override_graph = OverrideGraphSharedMemory.load () in Log.info "Loaded overrides from cache."; Ok override_graph) let save_overrides ~overrides = exception_to_error ~error:() ~message:"saving overrides to cache" ~f:(fun () -> OverrideGraphSharedMemory.store overrides; Log.info "Saved overrides to cache shared memory."; Ok ()) let override_graph { cache; save_cache; _ } f = let overrides = match cache with | Ok _ -> load_overrides () |> Result.ok | _ -> None in match overrides with | Some overrides -> overrides | None -> let overrides = f () in if save_cache then save_overrides ~overrides |> ignore_result; overrides let load_class_hierarchy_graph () = exception_to_error ~error:LoadError ~message:"loading class hierarchy graph from cache" ~f:(fun () -> Log.info "Loading class hierarchy graph from cache..."; let class_hierarchy_graph = ClassHierarchyGraphSharedMemory.load () in Log.info "Loaded class hierarchy graph from cache."; Ok class_hierarchy_graph) let save_class_hierarchy_graph ~class_hierarchy_graph = exception_to_error ~error:() ~message:"saving class hierarchy graph to cache" ~f:(fun () -> Memory.SharedMemory.collect `aggressive; ClassHierarchyGraphSharedMemory.store class_hierarchy_graph; Log.info "Saved class hierarchy graph to cache shared memory."; Ok ()) let class_hierarchy_graph { cache; save_cache; _ } f = let class_hierarchy_graph = match cache with | Ok _ -> load_class_hierarchy_graph () |> Result.ok | _ -> None in match class_hierarchy_graph with | Some class_hierarchy_graph -> class_hierarchy_graph | None -> let class_hierarchy_graph = f () in if save_cache then save_class_hierarchy_graph ~class_hierarchy_graph |> ignore_result; class_hierarchy_graph
null
https://raw.githubusercontent.com/facebook/pyre-check/536e4a2c008726d0ce5589eaef681166923b6183/source/interprocedural_analyses/taint/cache.ml
ocaml
Cache: implements caching capabilities for the taint analysis. This is what * powers the `--use-cache` command line option. This is basically implemented * by writing the shared memory into a file and restoring it later. Re-write the original taint configuration in shared memory, * in case it was overwritten when loading the cache.
* 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. *) open Core open Pyre module TypeEnvironment = Analysis.TypeEnvironment module AstEnvironment = Analysis.AstEnvironment module FetchCallables = Interprocedural.FetchCallables module ClassHierarchyGraph = Interprocedural.ClassHierarchyGraph module OverrideGraph = Interprocedural.OverrideGraph module InitialCallablesSharedMemory = Memory.Serializer (struct type t = FetchCallables.t module Serialized = struct type t = FetchCallables.t let prefix = Prefix.make () let description = "Initial callables to analyze" end let serialize = Fn.id let deserialize = Fn.id end) module OverrideGraphSharedMemory = Memory.Serializer (struct type t = OverrideGraph.whole_program_overrides module Serialized = struct type t = OverrideGraph.whole_program_overrides let prefix = Prefix.make () let description = "Cached override graph" end let serialize = Fn.id let deserialize = Fn.id end) module ClassHierarchyGraphSharedMemory = Memory.Serializer (struct type t = ClassHierarchyGraph.Heap.t module Serialized = struct type t = ClassHierarchyGraph.Heap.t let prefix = Prefix.make () let description = "Class hierarchy graph" end let serialize = Fn.id let deserialize = Fn.id end) type cached = { type_environment: TypeEnvironment.t } type error = | InvalidByCodeChange | LoadError | NotFound | Disabled type t = { cache: (cached, error) Result.t; save_cache: bool; scheduler: Scheduler.t; configuration: Configuration.Analysis.t; } let get_save_directory ~configuration = PyrePath.create_relative ~root:(Configuration.Analysis.log_directory configuration) ~relative:".pysa_cache" let get_shared_memory_save_path ~configuration = PyrePath.append (get_save_directory ~configuration) ~element:"sharedmem" let exception_to_error ~error ~message ~f = try f () with | exception_ -> Log.error "Error %s:\n%s" message (Exn.to_string exception_); Error error let ignore_result (_ : ('a, 'b) result) = () let initialize_shared_memory ~configuration = let path = get_shared_memory_save_path ~configuration in if not (PyrePath.file_exists path) then ( Log.warning "Could not find a cached state."; Error NotFound) else exception_to_error ~error:LoadError ~message:"loading cached state" ~f:(fun () -> Log.info "Loading cached state from `%s`" (PyrePath.absolute (get_save_directory ~configuration)); let _ = Memory.get_heap_handle configuration in Memory.load_shared_memory ~path:(PyrePath.absolute path) ~configuration; Log.info "Cached state successfully loaded."; Ok ()) let load_type_environment ~scheduler ~configuration = let open Result in let controls = Analysis.EnvironmentControls.create configuration in Log.info "Determining if source files have changed since cache was created."; exception_to_error ~error:LoadError ~message:"Loading type environment" ~f:(fun () -> Ok (TypeEnvironment.load controls)) >>= fun type_environment -> let old_module_tracker = TypeEnvironment.ast_environment type_environment |> AstEnvironment.module_tracker in let new_module_tracker = Analysis.ModuleTracker.create controls in let changed_paths = let is_pysa_model path = String.is_suffix ~suffix:".pysa" (PyrePath.get_suffix_path path) in let is_taint_config path = String.is_suffix ~suffix:"taint.config" (PyrePath.absolute path) in Interprocedural.ChangedPaths.compute_locally_changed_paths ~scheduler ~configuration ~old_module_tracker ~new_module_tracker |> List.map ~f:ArtifactPath.raw |> List.filter ~f:(fun path -> not (is_pysa_model path || is_taint_config path)) in match changed_paths with | [] -> Ok type_environment | _ -> Log.warning "Changes to source files detected, ignoring existing cache."; Error InvalidByCodeChange let load ~scheduler ~configuration ~taint_configuration ~enabled = if not enabled then { cache = Error Disabled; save_cache = false; scheduler; configuration } else let open Result in let type_environment = initialize_shared_memory ~configuration >>= fun () -> load_type_environment ~scheduler ~configuration in let cache = match type_environment with | Ok type_environment -> Ok { type_environment } | Error error -> Memory.reset_shared_memory (); Error error in let (_ : TaintConfiguration.SharedMemory.t) = TaintConfiguration.SharedMemory.from_heap taint_configuration in { cache; save_cache = true; scheduler; configuration } let save_type_environment ~scheduler ~configuration ~environment = exception_to_error ~error:() ~message:"saving type environment to cache" ~f:(fun () -> Memory.SharedMemory.collect `aggressive; let module_tracker = TypeEnvironment.module_tracker environment in Interprocedural.ChangedPaths.save_current_paths ~scheduler ~configuration ~module_tracker; TypeEnvironment.store environment; Log.info "Saved type environment to cache shared memory."; Ok ()) let type_environment { cache; save_cache; scheduler; configuration } f = match cache with | Ok { type_environment } -> type_environment | _ -> let environment = f () in if save_cache then save_type_environment ~scheduler ~configuration ~environment |> ignore_result; environment let load_initial_callables () = exception_to_error ~error:LoadError ~message:"loading initial callables from cache" ~f:(fun () -> Log.info "Loading initial callables from cache..."; let initial_callables = InitialCallablesSharedMemory.load () in Log.info "Loaded initial callables from cache."; Ok initial_callables) let ensure_save_directory_exists ~configuration = let directory = PyrePath.absolute (get_save_directory ~configuration) in try Core_unix.mkdir directory with [ mkdir ] on returns [ EISDIR ] instead of [ EEXIST ] if the directory already exists . | Core_unix.Unix_error ((EEXIST | EISDIR), _, _) -> () | e -> raise e let save_shared_memory ~configuration = exception_to_error ~error:() ~message:"saving cached state to file" ~f:(fun () -> let path = get_shared_memory_save_path ~configuration in Log.info "Saving shared memory state to cache file..."; ensure_save_directory_exists ~configuration; Memory.SharedMemory.collect `aggressive; Memory.save_shared_memory ~path:(PyrePath.absolute path) ~configuration; Log.info "Saved shared memory state to cache file: `%s`" (PyrePath.absolute path); Ok ()) let save { save_cache; configuration; _ } = if save_cache then save_shared_memory ~configuration |> ignore let save_initial_callables ~initial_callables = exception_to_error ~error:() ~message:"saving initial callables to cache" ~f:(fun () -> Memory.SharedMemory.collect `aggressive; InitialCallablesSharedMemory.store initial_callables; Log.info "Saved initial callables to cache shared memory."; Ok ()) let initial_callables { cache; save_cache; _ } f = let initial_callables = match cache with | Ok _ -> load_initial_callables () |> Result.ok | _ -> None in match initial_callables with | Some initial_callables -> initial_callables | None -> let callables = f () in if save_cache then save_initial_callables ~initial_callables:callables |> ignore_result; callables let load_overrides () = exception_to_error ~error:LoadError ~message:"loading overrides from cache" ~f:(fun () -> Log.info "Loading overrides from cache..."; let override_graph = OverrideGraphSharedMemory.load () in Log.info "Loaded overrides from cache."; Ok override_graph) let save_overrides ~overrides = exception_to_error ~error:() ~message:"saving overrides to cache" ~f:(fun () -> OverrideGraphSharedMemory.store overrides; Log.info "Saved overrides to cache shared memory."; Ok ()) let override_graph { cache; save_cache; _ } f = let overrides = match cache with | Ok _ -> load_overrides () |> Result.ok | _ -> None in match overrides with | Some overrides -> overrides | None -> let overrides = f () in if save_cache then save_overrides ~overrides |> ignore_result; overrides let load_class_hierarchy_graph () = exception_to_error ~error:LoadError ~message:"loading class hierarchy graph from cache" ~f:(fun () -> Log.info "Loading class hierarchy graph from cache..."; let class_hierarchy_graph = ClassHierarchyGraphSharedMemory.load () in Log.info "Loaded class hierarchy graph from cache."; Ok class_hierarchy_graph) let save_class_hierarchy_graph ~class_hierarchy_graph = exception_to_error ~error:() ~message:"saving class hierarchy graph to cache" ~f:(fun () -> Memory.SharedMemory.collect `aggressive; ClassHierarchyGraphSharedMemory.store class_hierarchy_graph; Log.info "Saved class hierarchy graph to cache shared memory."; Ok ()) let class_hierarchy_graph { cache; save_cache; _ } f = let class_hierarchy_graph = match cache with | Ok _ -> load_class_hierarchy_graph () |> Result.ok | _ -> None in match class_hierarchy_graph with | Some class_hierarchy_graph -> class_hierarchy_graph | None -> let class_hierarchy_graph = f () in if save_cache then save_class_hierarchy_graph ~class_hierarchy_graph |> ignore_result; class_hierarchy_graph
e28681a731c331f7589fbfcbad08e0a3f1805a190f8fb37817cf46b0f6fd9d51
input-output-hk/cardano-wallet
Coin.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingVia # {-# LANGUAGE ExplicitForAll #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # -- | Copyright : © 2018 - 2020 IOHK -- License: Apache-2.0 -- -- This module provides the 'Coin' data type, which represents a quantity of -- lovelace. -- module Cardano.Wallet.Primitive.Types.Coin ( -- * Type Coin (..) -- * Conversions (Safe) , fromIntegralMaybe , fromNatural , fromQuantity , fromWord64 , toInteger , toNatural , toQuantity , toQuantityMaybe , toWord64Maybe -- * Conversions (Unsafe) , unsafeFromIntegral , unsafeToQuantity , unsafeToWord64 -- * Arithmetic operations , add , subtract , difference , distance -- * Partitioning , equipartition , partition , partitionDefault , unsafePartition , coinToQuantity , coinFromQuantity ) where import Prelude hiding ( fromIntegral, subtract, toInteger ) import Cardano.Numeric.Util ( equipartitionNatural, partitionNatural ) import Control.DeepSeq ( NFData (..) ) import Data.Bits ( Bits ) import Data.Hashable ( Hashable ) import Data.IntCast ( IsIntSubType, intCast, intCastMaybe ) import Data.List.NonEmpty ( NonEmpty (..) ) import Data.Maybe ( fromMaybe ) import Data.Quantity ( Quantity (..) ) import Data.Text.Class ( FromText (..), ToText (..) ) import Data.Word ( Word64 ) import Fmt ( Buildable (..), fixedF ) import GHC.Generics ( Generic ) import GHC.Stack ( HasCallStack ) import Numeric.Natural ( Natural ) import Quiet ( Quiet (..) ) import qualified Data.Text as T import qualified Prelude -- | A 'Coin' represents a quantity of lovelace. -- Reminder : 1 ada = 1,000,000 lovelace . -- The ' Coin ' type has ' Semigroup ' and ' Monoid ' instances that correspond -- to ordinary addition and summation. -- newtype Coin = Coin { unCoin :: Natural } deriving stock (Ord, Eq, Generic) deriving (Read, Show) via (Quiet Coin) -- | The 'Semigroup' instance for 'Coin' corresponds to ordinary addition. -- instance Semigroup Coin where Natural does n't have a default Semigroup instance . (<>) = add instance Monoid Coin where mempty = Coin 0 instance ToText Coin where toText (Coin c) = T.pack $ show c instance FromText Coin where fromText = fmap Coin . fromText @Natural instance NFData Coin instance Hashable Coin instance Buildable Coin where build (Coin c) = fixedF @Double 6 (Prelude.fromIntegral c / 1e6) -------------------------------------------------------------------------------- -- Conversions (Safe) -------------------------------------------------------------------------------- -- | Constructs a 'Coin' from an 'Integral' value. -- -- Returns 'Nothing' if the given value is negative. -- fromIntegralMaybe :: (Bits i, Integral i) => i -> Maybe Coin fromIntegralMaybe i = Coin <$> intCastMaybe i -- | Constructs a 'Coin' from a 'Natural' value. -- fromNatural :: Natural -> Coin fromNatural = Coin -- | Constructs a 'Coin' from a 'Quantity'. -- fromQuantity :: (Integral i, IsIntSubType i Natural ~ 'True) => Quantity "lovelace" i -> Coin fromQuantity (Quantity c) = Coin (intCast c) -- | Constructs a 'Coin' from a 'Word64' value. -- fromWord64 :: Word64 -> Coin fromWord64 = Coin . intCast | Converts a ' Coin ' to an ' Integer ' value . -- toInteger :: Coin -> Integer toInteger = intCast . unCoin -- | Converts a 'Coin' to a 'Natural' value. -- toNatural :: Coin -> Natural toNatural = unCoin -- | Converts a 'Coin' to a 'Quantity'. -- toQuantity :: (Integral i, IsIntSubType Natural i ~ 'True) => Coin -> Quantity "lovelace" i toQuantity (Coin c) = Quantity (intCast c) -- | Converts a 'Coin' to a 'Quantity'. -- -- Returns 'Nothing' if the given value does not fit within the bounds of -- the target type. -- toQuantityMaybe :: (Bits i, Integral i) => Coin -> Maybe (Quantity "lovelace" i) toQuantityMaybe (Coin c) = Quantity <$> intCastMaybe c -- | Converts a 'Coin' to a 'Word64' value. -- -- Returns 'Nothing' if the given value does not fit within the bounds of a 64 - bit word . -- toWord64Maybe :: Coin -> Maybe Word64 toWord64Maybe (Coin c) = intCastMaybe c coinToQuantity :: Integral n => Coin -> Quantity "lovelace" n coinToQuantity = Quantity . Prelude.fromIntegral . unCoin coinFromQuantity :: Integral n => Quantity "lovelace" n -> Coin coinFromQuantity = Coin . Prelude.fromIntegral . getQuantity -------------------------------------------------------------------------------- -- Conversions (Unsafe) ------------------------------------------------------------------------------- -- | Constructs a 'Coin' from an 'Integral' value. -- -- Callers of this function must take responsibility for checking that the -- given value is not negative. -- -- Produces a run-time error if the given value is negative. -- unsafeFromIntegral :: HasCallStack => (Bits i, Integral i, Show i) => i -> Coin unsafeFromIntegral i = fromMaybe onError (fromIntegralMaybe i) where onError = error $ unwords [ "Coin.unsafeFromIntegral:" , show i , "is not a natural number." ] -- | Converts a 'Coin' to a 'Quantity'. -- -- Callers of this function must take responsibility for checking that the -- given value will fit within the bounds of the target type. -- -- Produces a run-time error if the given value is out of bounds. -- unsafeToQuantity :: HasCallStack => (Bits i, Integral i) => Coin -> Quantity "lovelace" i unsafeToQuantity c = fromMaybe onError (toQuantityMaybe c) where onError = error $ unwords [ "Coin.unsafeToQuantity:" , show c , "does not fit within the bounds of the target type." ] -- | Converts a 'Coin' to a 'Word64' value. -- -- Callers of this function must take responsibility for checking that the given value will fit within the bounds of a 64 - bit word . -- -- Produces a run-time error if the given value is out of bounds. -- unsafeToWord64 :: HasCallStack => Coin -> Word64 unsafeToWord64 c = fromMaybe onError (toWord64Maybe c) where onError = error $ unwords [ "Coin.unsafeToWord64:" , show c , "does not fit within the bounds of a 64-bit word." ] -------------------------------------------------------------------------------- -- Arithmetic operations -------------------------------------------------------------------------------- | Subtracts the second coin from the first . -- Returns ' Nothing ' if the second coin is strictly greater than the first . -- subtract :: Coin -> Coin -> Maybe Coin subtract (Coin a) (Coin b) | a >= b = Just $ Coin (a - b) | otherwise = Nothing | Calculates the combined value of two coins . -- add :: Coin -> Coin -> Coin add (Coin a) (Coin b) = Coin (a + b) | Subtracts the second coin from the first . -- Returns ' Coin 0 ' if the second coin is strictly greater than the first . -- difference :: Coin -> Coin -> Coin difference a b = fromMaybe (Coin 0) (subtract a b) | Absolute difference between two coin amounts . The result is never negative . distance :: Coin -> Coin -> Coin distance (Coin a) (Coin b) = if a < b then Coin (b - a) else Coin (a - b) -------------------------------------------------------------------------------- -- Partitioning -------------------------------------------------------------------------------- -- | Computes the equipartition of a coin into 'n' smaller coins. -- -- An /equipartition/ of a coin is a /partition/ of that coin into 'n' smaller coins whose values differ by no more than 1 . -- -- The resultant list is sorted in ascending order. -- equipartition :: Coin -- ^ The coin to be partitioned. -> NonEmpty a -- ^ Represents the number of portions in which to partition the coin. -> NonEmpty Coin -- ^ The partitioned coins. equipartition c = fmap fromNatural . equipartitionNatural (toNatural c) -- | Partitions a coin into a number of parts, where the size of each part is -- proportional (modulo rounding) to the size of its corresponding element in -- the given list of weights, and the number of parts is equal to the number -- of weights. -- Returns ' Nothing ' if the sum of weights is equal to zero . -- partition :: Coin -- ^ The coin to be partitioned. -> NonEmpty Coin -- ^ The list of weights. -> Maybe (NonEmpty Coin) -- ^ The partitioned coins. partition c = fmap (fmap fromNatural) . partitionNatural (toNatural c) . fmap toNatural -- | Partitions a coin into a number of parts, where the size of each part is -- proportional (modulo rounding) to the size of its corresponding element in -- the given list of weights, and the number of parts is equal to the number -- of weights. -- -- This function always satisfies the following properties: -- -- prop> fold (partitionDefault c ws) == c prop > length ( partitionDefault c ws ) = = length ws -- If the sum of weights is equal to zero , then this function returns an -- 'equipartition' satisfying the following property: -- -- prop> partitionDefault c ws == equipartition c ws -- partitionDefault :: Coin -- ^ The token quantity to be partitioned. -> NonEmpty Coin -- ^ The list of weights. -> NonEmpty Coin -- ^ The partitioned token quantities. partitionDefault c ws = fromMaybe (equipartition c ws) (partition c ws) -- | Partitions a coin into a number of parts, where the size of each part is -- proportional (modulo rounding) to the size of its corresponding element in -- the given list of weights, and the number of parts is equal to the number -- of weights. -- Throws a run - time error if the sum of weights is equal to zero . -- unsafePartition :: HasCallStack => Coin -- ^ The coin to be partitioned. -> NonEmpty Coin -- ^ The list of weights. -> NonEmpty Coin -- ^ The partitioned coins. unsafePartition = (fromMaybe zeroWeightSumError .) . partition where zeroWeightSumError = error "Coin.unsafePartition: weights must have a non-zero sum."
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet/157a6d5f977f4600373596b7cfa9700138e8e140/lib/primitive/lib/Cardano/Wallet/Primitive/Types/Coin.hs
haskell
# LANGUAGE ExplicitForAll # | License: Apache-2.0 This module provides the 'Coin' data type, which represents a quantity of lovelace. * Type * Conversions (Safe) * Conversions (Unsafe) * Arithmetic operations * Partitioning | A 'Coin' represents a quantity of lovelace. to ordinary addition and summation. | The 'Semigroup' instance for 'Coin' corresponds to ordinary addition. ------------------------------------------------------------------------------ Conversions (Safe) ------------------------------------------------------------------------------ | Constructs a 'Coin' from an 'Integral' value. Returns 'Nothing' if the given value is negative. | Constructs a 'Coin' from a 'Natural' value. | Constructs a 'Coin' from a 'Quantity'. | Constructs a 'Coin' from a 'Word64' value. | Converts a 'Coin' to a 'Natural' value. | Converts a 'Coin' to a 'Quantity'. | Converts a 'Coin' to a 'Quantity'. Returns 'Nothing' if the given value does not fit within the bounds of the target type. | Converts a 'Coin' to a 'Word64' value. Returns 'Nothing' if the given value does not fit within the bounds of a ------------------------------------------------------------------------------ Conversions (Unsafe) ----------------------------------------------------------------------------- | Constructs a 'Coin' from an 'Integral' value. Callers of this function must take responsibility for checking that the given value is not negative. Produces a run-time error if the given value is negative. | Converts a 'Coin' to a 'Quantity'. Callers of this function must take responsibility for checking that the given value will fit within the bounds of the target type. Produces a run-time error if the given value is out of bounds. | Converts a 'Coin' to a 'Word64' value. Callers of this function must take responsibility for checking that the Produces a run-time error if the given value is out of bounds. ------------------------------------------------------------------------------ Arithmetic operations ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Partitioning ------------------------------------------------------------------------------ | Computes the equipartition of a coin into 'n' smaller coins. An /equipartition/ of a coin is a /partition/ of that coin into 'n' smaller The resultant list is sorted in ascending order. ^ The coin to be partitioned. ^ Represents the number of portions in which to partition the coin. ^ The partitioned coins. | Partitions a coin into a number of parts, where the size of each part is proportional (modulo rounding) to the size of its corresponding element in the given list of weights, and the number of parts is equal to the number of weights. ^ The coin to be partitioned. ^ The list of weights. ^ The partitioned coins. | Partitions a coin into a number of parts, where the size of each part is proportional (modulo rounding) to the size of its corresponding element in the given list of weights, and the number of parts is equal to the number of weights. This function always satisfies the following properties: prop> fold (partitionDefault c ws) == c 'equipartition' satisfying the following property: prop> partitionDefault c ws == equipartition c ws ^ The token quantity to be partitioned. ^ The list of weights. ^ The partitioned token quantities. | Partitions a coin into a number of parts, where the size of each part is proportional (modulo rounding) to the size of its corresponding element in the given list of weights, and the number of parts is equal to the number of weights. ^ The coin to be partitioned. ^ The list of weights. ^ The partitioned coins.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingVia # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # Copyright : © 2018 - 2020 IOHK module Cardano.Wallet.Primitive.Types.Coin Coin (..) , fromIntegralMaybe , fromNatural , fromQuantity , fromWord64 , toInteger , toNatural , toQuantity , toQuantityMaybe , toWord64Maybe , unsafeFromIntegral , unsafeToQuantity , unsafeToWord64 , add , subtract , difference , distance , equipartition , partition , partitionDefault , unsafePartition , coinToQuantity , coinFromQuantity ) where import Prelude hiding ( fromIntegral, subtract, toInteger ) import Cardano.Numeric.Util ( equipartitionNatural, partitionNatural ) import Control.DeepSeq ( NFData (..) ) import Data.Bits ( Bits ) import Data.Hashable ( Hashable ) import Data.IntCast ( IsIntSubType, intCast, intCastMaybe ) import Data.List.NonEmpty ( NonEmpty (..) ) import Data.Maybe ( fromMaybe ) import Data.Quantity ( Quantity (..) ) import Data.Text.Class ( FromText (..), ToText (..) ) import Data.Word ( Word64 ) import Fmt ( Buildable (..), fixedF ) import GHC.Generics ( Generic ) import GHC.Stack ( HasCallStack ) import Numeric.Natural ( Natural ) import Quiet ( Quiet (..) ) import qualified Data.Text as T import qualified Prelude Reminder : 1 ada = 1,000,000 lovelace . The ' Coin ' type has ' Semigroup ' and ' Monoid ' instances that correspond newtype Coin = Coin { unCoin :: Natural } deriving stock (Ord, Eq, Generic) deriving (Read, Show) via (Quiet Coin) instance Semigroup Coin where Natural does n't have a default Semigroup instance . (<>) = add instance Monoid Coin where mempty = Coin 0 instance ToText Coin where toText (Coin c) = T.pack $ show c instance FromText Coin where fromText = fmap Coin . fromText @Natural instance NFData Coin instance Hashable Coin instance Buildable Coin where build (Coin c) = fixedF @Double 6 (Prelude.fromIntegral c / 1e6) fromIntegralMaybe :: (Bits i, Integral i) => i -> Maybe Coin fromIntegralMaybe i = Coin <$> intCastMaybe i fromNatural :: Natural -> Coin fromNatural = Coin fromQuantity :: (Integral i, IsIntSubType i Natural ~ 'True) => Quantity "lovelace" i -> Coin fromQuantity (Quantity c) = Coin (intCast c) fromWord64 :: Word64 -> Coin fromWord64 = Coin . intCast | Converts a ' Coin ' to an ' Integer ' value . toInteger :: Coin -> Integer toInteger = intCast . unCoin toNatural :: Coin -> Natural toNatural = unCoin toQuantity :: (Integral i, IsIntSubType Natural i ~ 'True) => Coin -> Quantity "lovelace" i toQuantity (Coin c) = Quantity (intCast c) toQuantityMaybe :: (Bits i, Integral i) => Coin -> Maybe (Quantity "lovelace" i) toQuantityMaybe (Coin c) = Quantity <$> intCastMaybe c 64 - bit word . toWord64Maybe :: Coin -> Maybe Word64 toWord64Maybe (Coin c) = intCastMaybe c coinToQuantity :: Integral n => Coin -> Quantity "lovelace" n coinToQuantity = Quantity . Prelude.fromIntegral . unCoin coinFromQuantity :: Integral n => Quantity "lovelace" n -> Coin coinFromQuantity = Coin . Prelude.fromIntegral . getQuantity unsafeFromIntegral :: HasCallStack => (Bits i, Integral i, Show i) => i -> Coin unsafeFromIntegral i = fromMaybe onError (fromIntegralMaybe i) where onError = error $ unwords [ "Coin.unsafeFromIntegral:" , show i , "is not a natural number." ] unsafeToQuantity :: HasCallStack => (Bits i, Integral i) => Coin -> Quantity "lovelace" i unsafeToQuantity c = fromMaybe onError (toQuantityMaybe c) where onError = error $ unwords [ "Coin.unsafeToQuantity:" , show c , "does not fit within the bounds of the target type." ] given value will fit within the bounds of a 64 - bit word . unsafeToWord64 :: HasCallStack => Coin -> Word64 unsafeToWord64 c = fromMaybe onError (toWord64Maybe c) where onError = error $ unwords [ "Coin.unsafeToWord64:" , show c , "does not fit within the bounds of a 64-bit word." ] | Subtracts the second coin from the first . Returns ' Nothing ' if the second coin is strictly greater than the first . subtract :: Coin -> Coin -> Maybe Coin subtract (Coin a) (Coin b) | a >= b = Just $ Coin (a - b) | otherwise = Nothing | Calculates the combined value of two coins . add :: Coin -> Coin -> Coin add (Coin a) (Coin b) = Coin (a + b) | Subtracts the second coin from the first . Returns ' Coin 0 ' if the second coin is strictly greater than the first . difference :: Coin -> Coin -> Coin difference a b = fromMaybe (Coin 0) (subtract a b) | Absolute difference between two coin amounts . The result is never negative . distance :: Coin -> Coin -> Coin distance (Coin a) (Coin b) = if a < b then Coin (b - a) else Coin (a - b) coins whose values differ by no more than 1 . equipartition :: Coin -> NonEmpty a -> NonEmpty Coin equipartition c = fmap fromNatural . equipartitionNatural (toNatural c) Returns ' Nothing ' if the sum of weights is equal to zero . partition :: Coin -> NonEmpty Coin -> Maybe (NonEmpty Coin) partition c = fmap (fmap fromNatural) . partitionNatural (toNatural c) . fmap toNatural prop > length ( partitionDefault c ws ) = = length ws If the sum of weights is equal to zero , then this function returns an partitionDefault :: Coin -> NonEmpty Coin -> NonEmpty Coin partitionDefault c ws = fromMaybe (equipartition c ws) (partition c ws) Throws a run - time error if the sum of weights is equal to zero . unsafePartition :: HasCallStack => Coin -> NonEmpty Coin -> NonEmpty Coin unsafePartition = (fromMaybe zeroWeightSumError .) . partition where zeroWeightSumError = error "Coin.unsafePartition: weights must have a non-zero sum."
a00644e2739702fc0ed6289ca32dc616875b2811e885cb602fe3edf4a1670450
nickewing/netz
util.clj
(defn- matrix-mult "Multiply two matrices and ensure the result is also a matrix." [a b] (let [result (mmult a b)] (if (matrix? result) result (matrix [result])))) (defn- round-output "Round outputs to nearest integer." [output] (vec (map #(Math/round ^Double %) output))) (defn- sign "Returns +1 if x is positive, -1 if negative, 0 otherwise" [x] (cond (> x 0.0) 1.0 (< x 0.0) -1.0 (= x 0.0) 0.0)) (defn- map-to-vectors "Map given inputs to func and conj each output to the end of accumulating vectors." [func & inputs] (loop [inputs inputs accum nil] (let [input (map first inputs) inputs (map rest inputs) output (apply func input) accum (if accum (map conj accum output) (map vector output))] (if (empty? (first inputs)) accum (recur inputs accum)))))
null
https://raw.githubusercontent.com/nickewing/netz/8103cb947f7fea989f12aec5debed7823950ac06/src/netz/util.clj
clojure
(defn- matrix-mult "Multiply two matrices and ensure the result is also a matrix." [a b] (let [result (mmult a b)] (if (matrix? result) result (matrix [result])))) (defn- round-output "Round outputs to nearest integer." [output] (vec (map #(Math/round ^Double %) output))) (defn- sign "Returns +1 if x is positive, -1 if negative, 0 otherwise" [x] (cond (> x 0.0) 1.0 (< x 0.0) -1.0 (= x 0.0) 0.0)) (defn- map-to-vectors "Map given inputs to func and conj each output to the end of accumulating vectors." [func & inputs] (loop [inputs inputs accum nil] (let [input (map first inputs) inputs (map rest inputs) output (apply func input) accum (if accum (map conj accum output) (map vector output))] (if (empty? (first inputs)) accum (recur inputs accum)))))
32b7fcae2e0436a23462051937ee7d558a90737749cdbd2105880780f3815a48
UU-ComputerScience/uhc
Main.hs
-- There was a lot of discussion about various ways of computing numbers ( whatever they are ) on haskell - cafe in March 2003 Here 's one of the programs . -- It's not a very good test, I suspect, because it manipulates big integers, and so probably spends most of its time in GMP . import Data.Ratio import System.Environment -- powers = [[r^n | r<-[2..]] | n<-1..] -- type signature required for compilers lacking the monomorphism restriction powers :: [[Integer]] powers = [2..] : map (zipWith (*) (head powers)) powers -- powers = [[(-1)^r * r^n | r<-[2..]] | n<-1..] neg_powers = map (zipWith (\n x -> if n then x else -x) (iterate not True)) powers pascal:: [[Integer]] pascal = [1,2,1] : map (\line -> zipWith (+) (line++[0]) (0:line)) pascal bernoulli :: Int -> Rational bernoulli 0 = 1 bernoulli 1 = -(1%2) bernoulli n | odd n = 0 bernoulli n = (-1)%2 + sum [ fromIntegral ((sum $ zipWith (*) powers (tail $ tail combs)) - fromIntegral k) % fromIntegral (k+1) | (k,combs)<- zip [2..n] pascal] where powers = (neg_powers!!(n-1)) main = do [arg] <- getArgs let n = (read arg)::Int putStr $ "Bernoulli of " ++ (show n) ++ " is " putStrLn . filter (\c -> not (c `elem` "( )")) . show . bernoulli $ n
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/benchmark/nofib/imag/bernouilli/Main.hs
haskell
There was a lot of discussion about various ways of computing It's not a very good test, I suspect, because it manipulates big integers, powers = [[r^n | r<-[2..]] | n<-1..] type signature required for compilers lacking the monomorphism restriction powers = [[(-1)^r * r^n | r<-[2..]] | n<-1..]
numbers ( whatever they are ) on haskell - cafe in March 2003 Here 's one of the programs . and so probably spends most of its time in GMP . import Data.Ratio import System.Environment powers :: [[Integer]] powers = [2..] : map (zipWith (*) (head powers)) powers neg_powers = map (zipWith (\n x -> if n then x else -x) (iterate not True)) powers pascal:: [[Integer]] pascal = [1,2,1] : map (\line -> zipWith (+) (line++[0]) (0:line)) pascal bernoulli :: Int -> Rational bernoulli 0 = 1 bernoulli 1 = -(1%2) bernoulli n | odd n = 0 bernoulli n = (-1)%2 + sum [ fromIntegral ((sum $ zipWith (*) powers (tail $ tail combs)) - fromIntegral k) % fromIntegral (k+1) | (k,combs)<- zip [2..n] pascal] where powers = (neg_powers!!(n-1)) main = do [arg] <- getArgs let n = (read arg)::Int putStr $ "Bernoulli of " ++ (show n) ++ " is " putStrLn . filter (\c -> not (c `elem` "( )")) . show . bernoulli $ n
8ce9d733c2278ae8ed7518f4020d4e1031f17c8d80b7d13b0060b5ba99dadbf8
alicemaz/digital_henge
Moon.hs
module Moon () where import GHC.Exts import Data.Tuple.Curry import Control.Lens.Operators import Control.Lens.Tuple import Types import Util basically just generate illumination for every minute of the interval -- for full/new if it crosses the target it reverses direction -- so we just take time at max/min -- for other phases if it crosses, we take the closest to the target -- otherwise there is no phase point in the interval instance CheckEvent Moon where checkEvent y m d = checkPhase ival where jds = (dateToJD y m . (+fromIntegral d) . (/1440)) <$> [0..1439] ival = zip (moonIllum . (+deltaT y) <$> jds) jds note " " mean the time corresponding to min / max i -- actual min/max t are always t0/tN because... that's how time works checkPhase :: (Ord a, Fractional a, RealFrac b) => [(a, b)] -> EventResult Moon checkPhase ival | i0 < 0.25 && 0.25 < iN = Event WaxingCrescent $ f 0.25 | iN < 0.25 && 0.25 < i0 = Event WaningCrescent $ f 0.25 | i0 < 0.75 && 0.75 < iN = Event WaxingGibbous $ f 0.75 | iN < 0.75 && 0.75 < i0 = Event WaningGibbous $ f 0.75 | i0 < 0.50 && 0.50 < iN = Event FirstQuarter $ f 0.50 | iN < 0.50 && 0.50 < i0 = Event ThirdQuarter $ f 0.50 | iMin < i0 && iMin < iN = Event New (jdToTimestring tMin) | iMax > i0 && iMax > iN = Event Full (jdToTimestring tMax) | otherwise = Nil where (i0, _) = head ival (iN, _) = last ival (iMin, tMin) = foldr1 min ival (iMax, tMax) = foldr1 max ival f = findPhaseChange ival findPhaseChange :: (Ord a, Num a, RealFrac b) => [(a, b)] -> a -> String findPhaseChange ival t = head (sortWith (\(i, _) -> abs (i - t)) ival) ^. _2 & jdToTimestring I really wanted this to be constrained by RealFloat or smth -- but monomorphism restriction I guess is screwing me somewhere -- tried changing all "Double" types below and still couldn't unify also our margin of error appears to be about a half hour -- probably because I got lazy with the obliquity calculations moonIllum :: Double -> Double moonIllum jde = moonIllum' a d del a0 d0 r where (a, d, del) = moonPos jde (a0, d0, r) = sunPos jde args order is asc decl dist of moon , asc decl dist of sun moonIllum' :: RealFloat a => a -> a -> a -> a -> a -> a -> a moonIllum' a d del a0 d0 r = (1 + cos' i) / 2 where p = acos' $ sin' d0*sin' d + cos' d0*cos' d*cos' (a0 - a) i = atan2' (r*sin' p) (del - r*cos' p) this is only accurate to a half minute of arc or so -- since it disregards gravitational effects outside sun/earth system -- l' and m same as below -- e' is earth's eccentricity -- c is equation of center resulting in longitude in degrees and distance in au -- converts to apparent right ascension and declination, and distance to km since the sun 's latitude is never more than a second or two of arc , we take it at 0 for simplicity sunPos :: RealFloat a => a -> (a, a, a) sunPos jde = (asc, decl, 149598000*r) where t = (jde - 2451545) / 36525 l' = sunMeanLong t m = solarAnomaly t e' = 0.016708617 - 0.000042037*t - 0.0000001236*t^2 c = (1.914600 - 0.004817*t - 0.000014*t^2)*sin' m + (0.019993 - 0.000101*t)*sin' (2*m) + 0.00029*sin' (3*m) r = 1.000001018*(1 - e'^2) / (1 + e'*cos' (m+c)) o = 125.04 - 1934.136*t l = l' + c - 0.00569 - 0.00478*sin' o e = (obliqNutation t ^. _1) + 0.00256*cos' o (asc, decl) = ascDecl 0 l e -- l' is mean longitude -- d is mean elongation m is 's mean anomoly m ' is 's mean anomoly f is 's mean distance from ascending node and each m must be scaled to take into account eccentricity of earth 's orbit further corrections are made to the sums to account for action of venus and produces geometric latitude and longitude in degrees and distance in km again converted from ecliptic and returned as apparent equitoral asc / decl --moonPos :: RealFloat a => a -> (a, a, a) moonPos :: Double -> (Double, Double, Double) moonPos jde = (asc, decl, dist) where t = (jde - 2451545) / 36525 l' = moonMeanLong t d = 297.8502042 + 445267.1115168*t - 0.00163*t^2 + t^3/545868 - t^4/113065000 m = solarAnomaly t m' = 134.9634114 + 477198.8676313*t + 0.0089970*t^2 + t^3/69699 - t^4/14712000 f = 93.2720993 + 483202.0175273*t - 0.0034029*t^2 -t^3/3526000 + t^4/863310000 a1 = 119.75 + 131.849*t a2 = 53.09 + 479264.290*t a3 = 313.45 + 481266.484*t ls = (uncurryN $ computeTerm sin' t d m m' f) <$> longTermCoeffs l = sum ls + 3958*sin' a1 + 1962*sin' (l' - f) + 318*sin' a2 bs = (uncurryN $ computeTerm sin' t d m m' f) <$> latTermCoeffs b = sum bs - 2235*sin' l' + 382*sin' a3 + 175*sin' (a1 - f) + 175*sin' (a1 + f) + 127*sin' (l' - m') - 115*sin' (l' + m') r = sum $ (uncurryN $ computeTerm cos' t d m m' f) <$> distTermCoeffs lat = b / 1000000 long = l' + l/1000000 dist = 385000.56 + r/1000 (e, dP) = obliqNutation t appLong = simplA' $ long + dP (asc, decl) = ascDecl lat appLong e -- right ascension and declination, function of lat long and true obliquity ascDecl :: RealFloat a => a -> a -> a -> (a, a) ascDecl b l e = (a, d) where a = atan2' (sin' l*cos' e - tan' b*sin' e) (cos' l) d = asin' $ sin' b*cos' e + cos' b*sin' e*sin' l -- true ecliptic obliquity (little epsilon) and nutation in longitude (delta psi) obliqNutation :: Floating a => a -> (a, a) obliqNutation t = (e0 + dE, dP) where u = t/100 e0 = 23.43929 - 0.01300417*u - 1.55*u^2 + 1999.25*u^3 - 51.38*u^4 - 249.67*u^5 - 39.05*u^6 + 7.12*u^7 + 27.87*u^8 + 5.79*u^9 + 2.45*u^10 o = 125.04452 - 1934.136261*t lm = moonMeanLong t ls = sunMeanLong t dE = 0.002555556*cos' o + 0.0001583333*cos' (2*ls) + 0.00002777778*cos' (2*lm) - 0.000025*cos' (2*o) dP = -0.004777778*cos' o - 0.0003666667*sin' (2*ls) - 0.0000638889*sin (2*lm) - 0.00005833333*cos' (2*o) sunMeanLong :: Fractional a => a -> a sunMeanLong t = 280.46645 + 36000.76983*t + 0.0003032*t^2 moonMeanLong :: Fractional a => a -> a moonMeanLong t = 218.3164591 + 481267.88134236*t - 0.0013268*t^2 + t^3/538841 - t^4/65194000 solarAnomaly :: Fractional a => a -> a solarAnomaly t = 357.5291092 + 35999.0502909*t - 0.0001536*t^2 + t^3/24490000 computes a term of the three sums giving 's geometric lat / long and distance computeTerm :: (Fractional a, Eq a) => (a -> a) -> a -> a -> a -> a -> a -> a -> a -> a -> a -> a -> a computeTerm w t d m m' f cd cm cm' cf c | abs cm == 1 = e * s | abs cm == 2 = e^2 * s | otherwise = s where e = 1 - 0.002516*t - 0.0000074*t^2 s = c * w (cd*d + cm*m + cm'*m' + cf*f) longTermCoeffs :: [(Double, Double, Double, Double, Double)] distTermCoeffs :: [(Double, Double, Double, Double, Double)] (longTermCoeffs, distTermCoeffs) = (g longCoeffs, g distCoeffs) where g = foldr f [] . zip longDistTerms f ((w, x, y, z), Just c) acc = (w, x, y, z, c) : acc f (_, Nothing) acc = acc latTermCoeffs :: [(Double, Double, Double, Double, Double)] latTermCoeffs = [ (0, 0, 0, 1, 5128122), (0, 0, 1, 1, 280602), (0, 0, 1, -1, 277693), (2, 0, 0, -1, 173237), (2, 0, -1, 1, 55413), (2, 0, -1, -1, 46271), (2, 0, 0, 1, 32573), (0, 0, 2, 1, 17198), (2, 0, 1, -1, 9266), (0, 0, 2, -1, 8822), (2, -1, 0, -1, 8216), (2, 0, -2, -1, 4324), (2, 0, 1, 1, 4200), (2, 1, 0, -1, -3359), (2, -1, -1, 1, 2463), (2, -1, 0, 1, 2211), (2, -1, -1, -1, 2065), (0, 1, -1, -1, -1870), (4, 0, -1, -1, 1828), (0, 1, 0, 1, -1794), (0, 0, 0, 3, -1749), (0, 1, -1, 1, -1565), (1, 0, 0, 1, -1491), (0, 1, 1, 1, -1475), (0, 1, 1, -1, -1410), (0, 1, 0, -1, -1344), (1, 0, 0, -1, -1335), (0, 0, 3, 1, 1107), (4, 0, 0, -1, 1021), (4, 0, -1, 1, 833), (0, 0, 1, -3, 777), (4, 0, -2, 1, 671), (2, 0, 0, -3, 607), (2, 0, 2, -1, 596), (2, -1, 1, -1, 491), (2, 0, -2, 1, -451), (0, 0, 3, -1, 439), (2, 0, 2, 1, 422), (2, 0, -3, -1, 421), (2, 1, -1, 1, -366), (2, 1, 0, 1, -351), (4, 0, 0, 1, 331), (2, -1, 1, 1, 315), (2, -2, 0, -1, 302), (0, 0, 1, 3, -283), (2, 1, 1, -1, -229), (1, 1, 0, -1, 223), (1, 1, 0, 1, 223), (0, 1, -2, -1, -220), (2, 1, -1, -1, -220), (1, 0, 1, 1, -185), (2, -1, -2, -1, 181), (0, 1, 2, 1, -177), (4, 0, -2, -1, 176), (4, -1, -1, -1, 166), (1, 0, 1, -1, -164), (4, 0, 1, -1, 132), (1, 0, -1, -1, -119), (4, -1, 0, -1, 115), (2, -2, 0, 1, 107) ] longDistTerms :: [(Double, Double, Double, Double)] longDistTerms = [ (0, 0, 1, 0), (2, 0, -1, 0), (2, 0, 0, 0), (0, 0, 2, 0), (0, 1, 0, 0), (0, 0, 0, 2), (2, 0, -2, 0), (2, -1, -1, 0), (2, 0, 1, 0), (2, -1, 0, 0), (0, 1, -1, 0), (1, 0, 0, 0), (0, 1, 1, 0), (2, 0, 0, -2), (0, 0, 1, 2), (0, 0, 1, -2), (4, 0, -1, 0), (0, 0, 3, 0), (4, 0, -2, 0), (2, 1, -1, 0), (2, 1, 0, 0), (1, 0, -1, 0), (1, 1, 0, 0), (2, -1, 1, 0), (2, 0, 2, 0), (4, 0, 0, 0), (2, 0, -3, 0), (0, 1, -2, 0), (2, 0, -1, 2), (2, -1, -2, 0), (1, 0, 1, 0), (2, -2, 0, 0), (0, 1, 2, 0), (0, 2, 0, 0), (2, -2, -1, 0), (2, 0, 1, -2), (2, 0, 0, 2), (4, -1, -1, 0), (0, 0, 2, 2), (3, 0, -1, 0), (2, 1, 1, 0), (4, -1, -2, 0), (0, 2, -1, 0), (2, 2, -1, 0), (2, 1, -2, 0), (2, -1, 0, -2), (4, 0, 1, 0), (0, 0, 4, 0), (4, -1, 0, 0), (1, 0, -2, 0), (2, 1, 0, -2), (0, 0, 2, -2), (1, 1, 1, 0), (3, 0, -2, 0), (4, 0, -3, 0), (2, -1, 2, 0), (0, 2, 1, 0), (1, 1, -1, 0), (2, 0, 3, 0), (2, 0, -1, -2) ] longCoeffs :: [Maybe Double] longCoeffs = Just <$> [ 6288774, 1274027, 658314, 213618, -185116, -114332, 58793, 57066, 53322, 45758, -40923, -34720, -30383, 15327, -12528, 10980, 10675, 10034, 8548, -7888, -6766, -5163, 4987, 4036, 3994, 3861, 3665, -2689, -2602, 2390, -2348, 2236, -2120, -2069, 2048, -1773, -1595, 1215, -1110, -892, -810, 759, -713, -700, 691, 596, 549, 537, 520, -487, -399, -381, 351, -340, 330, 327, -323, 299, 294 ] distCoeffs :: [Maybe Double] distCoeffs = [ Just (-20905355), Just (-3699111), Just (-2955968), Just (-569925), Just 48888, Just (-3149), Just 246158, Just (-152138), Just (-170733), Just (-204586), Just (-129620), Just 108743, Just 104755, Just 10321, Nothing, Just 79661, Just (-34782), Just (-23210), Just (-21636), Just 24208, Just 30824, Just (-8379), Just (-16675), Just (-12831), Just (-10445), Just (-11650), Just 14403, Just (-7003), Nothing, Just 10056, Just 6322, Just (-9884), Just 5751, Nothing, Just (-4950), Just 4130, Nothing, Just (-3958), Nothing, Just 3258, Just 2616, Just (-1897), Just (-2117), Just 2354, Nothing, Nothing, Just (-1423), Just (-1117), Just (-1571), Just (-1739), Nothing, Just (-4421), Nothing, Nothing, Nothing, Nothing, Just 1165, Nothing, Nothing, Just 8752 ]
null
https://raw.githubusercontent.com/alicemaz/digital_henge/0a1c75a5088fc6f256179024b51ebbbf4381c9e4/src/Moon.hs
haskell
for full/new if it crosses the target it reverses direction so we just take time at max/min for other phases if it crosses, we take the closest to the target otherwise there is no phase point in the interval actual min/max t are always t0/tN because... that's how time works but monomorphism restriction I guess is screwing me somewhere tried changing all "Double" types below and still couldn't unify probably because I got lazy with the obliquity calculations since it disregards gravitational effects outside sun/earth system l' and m same as below e' is earth's eccentricity c is equation of center converts to apparent right ascension and declination, and distance to km l' is mean longitude d is mean elongation moonPos :: RealFloat a => a -> (a, a, a) right ascension and declination, function of lat long and true obliquity true ecliptic obliquity (little epsilon) and nutation in longitude (delta psi)
module Moon () where import GHC.Exts import Data.Tuple.Curry import Control.Lens.Operators import Control.Lens.Tuple import Types import Util basically just generate illumination for every minute of the interval instance CheckEvent Moon where checkEvent y m d = checkPhase ival where jds = (dateToJD y m . (+fromIntegral d) . (/1440)) <$> [0..1439] ival = zip (moonIllum . (+deltaT y) <$> jds) jds note " " mean the time corresponding to min / max i checkPhase :: (Ord a, Fractional a, RealFrac b) => [(a, b)] -> EventResult Moon checkPhase ival | i0 < 0.25 && 0.25 < iN = Event WaxingCrescent $ f 0.25 | iN < 0.25 && 0.25 < i0 = Event WaningCrescent $ f 0.25 | i0 < 0.75 && 0.75 < iN = Event WaxingGibbous $ f 0.75 | iN < 0.75 && 0.75 < i0 = Event WaningGibbous $ f 0.75 | i0 < 0.50 && 0.50 < iN = Event FirstQuarter $ f 0.50 | iN < 0.50 && 0.50 < i0 = Event ThirdQuarter $ f 0.50 | iMin < i0 && iMin < iN = Event New (jdToTimestring tMin) | iMax > i0 && iMax > iN = Event Full (jdToTimestring tMax) | otherwise = Nil where (i0, _) = head ival (iN, _) = last ival (iMin, tMin) = foldr1 min ival (iMax, tMax) = foldr1 max ival f = findPhaseChange ival findPhaseChange :: (Ord a, Num a, RealFrac b) => [(a, b)] -> a -> String findPhaseChange ival t = head (sortWith (\(i, _) -> abs (i - t)) ival) ^. _2 & jdToTimestring I really wanted this to be constrained by RealFloat or smth also our margin of error appears to be about a half hour moonIllum :: Double -> Double moonIllum jde = moonIllum' a d del a0 d0 r where (a, d, del) = moonPos jde (a0, d0, r) = sunPos jde args order is asc decl dist of moon , asc decl dist of sun moonIllum' :: RealFloat a => a -> a -> a -> a -> a -> a -> a moonIllum' a d del a0 d0 r = (1 + cos' i) / 2 where p = acos' $ sin' d0*sin' d + cos' d0*cos' d*cos' (a0 - a) i = atan2' (r*sin' p) (del - r*cos' p) this is only accurate to a half minute of arc or so resulting in longitude in degrees and distance in au since the sun 's latitude is never more than a second or two of arc , we take it at 0 for simplicity sunPos :: RealFloat a => a -> (a, a, a) sunPos jde = (asc, decl, 149598000*r) where t = (jde - 2451545) / 36525 l' = sunMeanLong t m = solarAnomaly t e' = 0.016708617 - 0.000042037*t - 0.0000001236*t^2 c = (1.914600 - 0.004817*t - 0.000014*t^2)*sin' m + (0.019993 - 0.000101*t)*sin' (2*m) + 0.00029*sin' (3*m) r = 1.000001018*(1 - e'^2) / (1 + e'*cos' (m+c)) o = 125.04 - 1934.136*t l = l' + c - 0.00569 - 0.00478*sin' o e = (obliqNutation t ^. _1) + 0.00256*cos' o (asc, decl) = ascDecl 0 l e m is 's mean anomoly m ' is 's mean anomoly f is 's mean distance from ascending node and each m must be scaled to take into account eccentricity of earth 's orbit further corrections are made to the sums to account for action of venus and produces geometric latitude and longitude in degrees and distance in km again converted from ecliptic and returned as apparent equitoral asc / decl moonPos :: Double -> (Double, Double, Double) moonPos jde = (asc, decl, dist) where t = (jde - 2451545) / 36525 l' = moonMeanLong t d = 297.8502042 + 445267.1115168*t - 0.00163*t^2 + t^3/545868 - t^4/113065000 m = solarAnomaly t m' = 134.9634114 + 477198.8676313*t + 0.0089970*t^2 + t^3/69699 - t^4/14712000 f = 93.2720993 + 483202.0175273*t - 0.0034029*t^2 -t^3/3526000 + t^4/863310000 a1 = 119.75 + 131.849*t a2 = 53.09 + 479264.290*t a3 = 313.45 + 481266.484*t ls = (uncurryN $ computeTerm sin' t d m m' f) <$> longTermCoeffs l = sum ls + 3958*sin' a1 + 1962*sin' (l' - f) + 318*sin' a2 bs = (uncurryN $ computeTerm sin' t d m m' f) <$> latTermCoeffs b = sum bs - 2235*sin' l' + 382*sin' a3 + 175*sin' (a1 - f) + 175*sin' (a1 + f) + 127*sin' (l' - m') - 115*sin' (l' + m') r = sum $ (uncurryN $ computeTerm cos' t d m m' f) <$> distTermCoeffs lat = b / 1000000 long = l' + l/1000000 dist = 385000.56 + r/1000 (e, dP) = obliqNutation t appLong = simplA' $ long + dP (asc, decl) = ascDecl lat appLong e ascDecl :: RealFloat a => a -> a -> a -> (a, a) ascDecl b l e = (a, d) where a = atan2' (sin' l*cos' e - tan' b*sin' e) (cos' l) d = asin' $ sin' b*cos' e + cos' b*sin' e*sin' l obliqNutation :: Floating a => a -> (a, a) obliqNutation t = (e0 + dE, dP) where u = t/100 e0 = 23.43929 - 0.01300417*u - 1.55*u^2 + 1999.25*u^3 - 51.38*u^4 - 249.67*u^5 - 39.05*u^6 + 7.12*u^7 + 27.87*u^8 + 5.79*u^9 + 2.45*u^10 o = 125.04452 - 1934.136261*t lm = moonMeanLong t ls = sunMeanLong t dE = 0.002555556*cos' o + 0.0001583333*cos' (2*ls) + 0.00002777778*cos' (2*lm) - 0.000025*cos' (2*o) dP = -0.004777778*cos' o - 0.0003666667*sin' (2*ls) - 0.0000638889*sin (2*lm) - 0.00005833333*cos' (2*o) sunMeanLong :: Fractional a => a -> a sunMeanLong t = 280.46645 + 36000.76983*t + 0.0003032*t^2 moonMeanLong :: Fractional a => a -> a moonMeanLong t = 218.3164591 + 481267.88134236*t - 0.0013268*t^2 + t^3/538841 - t^4/65194000 solarAnomaly :: Fractional a => a -> a solarAnomaly t = 357.5291092 + 35999.0502909*t - 0.0001536*t^2 + t^3/24490000 computes a term of the three sums giving 's geometric lat / long and distance computeTerm :: (Fractional a, Eq a) => (a -> a) -> a -> a -> a -> a -> a -> a -> a -> a -> a -> a -> a computeTerm w t d m m' f cd cm cm' cf c | abs cm == 1 = e * s | abs cm == 2 = e^2 * s | otherwise = s where e = 1 - 0.002516*t - 0.0000074*t^2 s = c * w (cd*d + cm*m + cm'*m' + cf*f) longTermCoeffs :: [(Double, Double, Double, Double, Double)] distTermCoeffs :: [(Double, Double, Double, Double, Double)] (longTermCoeffs, distTermCoeffs) = (g longCoeffs, g distCoeffs) where g = foldr f [] . zip longDistTerms f ((w, x, y, z), Just c) acc = (w, x, y, z, c) : acc f (_, Nothing) acc = acc latTermCoeffs :: [(Double, Double, Double, Double, Double)] latTermCoeffs = [ (0, 0, 0, 1, 5128122), (0, 0, 1, 1, 280602), (0, 0, 1, -1, 277693), (2, 0, 0, -1, 173237), (2, 0, -1, 1, 55413), (2, 0, -1, -1, 46271), (2, 0, 0, 1, 32573), (0, 0, 2, 1, 17198), (2, 0, 1, -1, 9266), (0, 0, 2, -1, 8822), (2, -1, 0, -1, 8216), (2, 0, -2, -1, 4324), (2, 0, 1, 1, 4200), (2, 1, 0, -1, -3359), (2, -1, -1, 1, 2463), (2, -1, 0, 1, 2211), (2, -1, -1, -1, 2065), (0, 1, -1, -1, -1870), (4, 0, -1, -1, 1828), (0, 1, 0, 1, -1794), (0, 0, 0, 3, -1749), (0, 1, -1, 1, -1565), (1, 0, 0, 1, -1491), (0, 1, 1, 1, -1475), (0, 1, 1, -1, -1410), (0, 1, 0, -1, -1344), (1, 0, 0, -1, -1335), (0, 0, 3, 1, 1107), (4, 0, 0, -1, 1021), (4, 0, -1, 1, 833), (0, 0, 1, -3, 777), (4, 0, -2, 1, 671), (2, 0, 0, -3, 607), (2, 0, 2, -1, 596), (2, -1, 1, -1, 491), (2, 0, -2, 1, -451), (0, 0, 3, -1, 439), (2, 0, 2, 1, 422), (2, 0, -3, -1, 421), (2, 1, -1, 1, -366), (2, 1, 0, 1, -351), (4, 0, 0, 1, 331), (2, -1, 1, 1, 315), (2, -2, 0, -1, 302), (0, 0, 1, 3, -283), (2, 1, 1, -1, -229), (1, 1, 0, -1, 223), (1, 1, 0, 1, 223), (0, 1, -2, -1, -220), (2, 1, -1, -1, -220), (1, 0, 1, 1, -185), (2, -1, -2, -1, 181), (0, 1, 2, 1, -177), (4, 0, -2, -1, 176), (4, -1, -1, -1, 166), (1, 0, 1, -1, -164), (4, 0, 1, -1, 132), (1, 0, -1, -1, -119), (4, -1, 0, -1, 115), (2, -2, 0, 1, 107) ] longDistTerms :: [(Double, Double, Double, Double)] longDistTerms = [ (0, 0, 1, 0), (2, 0, -1, 0), (2, 0, 0, 0), (0, 0, 2, 0), (0, 1, 0, 0), (0, 0, 0, 2), (2, 0, -2, 0), (2, -1, -1, 0), (2, 0, 1, 0), (2, -1, 0, 0), (0, 1, -1, 0), (1, 0, 0, 0), (0, 1, 1, 0), (2, 0, 0, -2), (0, 0, 1, 2), (0, 0, 1, -2), (4, 0, -1, 0), (0, 0, 3, 0), (4, 0, -2, 0), (2, 1, -1, 0), (2, 1, 0, 0), (1, 0, -1, 0), (1, 1, 0, 0), (2, -1, 1, 0), (2, 0, 2, 0), (4, 0, 0, 0), (2, 0, -3, 0), (0, 1, -2, 0), (2, 0, -1, 2), (2, -1, -2, 0), (1, 0, 1, 0), (2, -2, 0, 0), (0, 1, 2, 0), (0, 2, 0, 0), (2, -2, -1, 0), (2, 0, 1, -2), (2, 0, 0, 2), (4, -1, -1, 0), (0, 0, 2, 2), (3, 0, -1, 0), (2, 1, 1, 0), (4, -1, -2, 0), (0, 2, -1, 0), (2, 2, -1, 0), (2, 1, -2, 0), (2, -1, 0, -2), (4, 0, 1, 0), (0, 0, 4, 0), (4, -1, 0, 0), (1, 0, -2, 0), (2, 1, 0, -2), (0, 0, 2, -2), (1, 1, 1, 0), (3, 0, -2, 0), (4, 0, -3, 0), (2, -1, 2, 0), (0, 2, 1, 0), (1, 1, -1, 0), (2, 0, 3, 0), (2, 0, -1, -2) ] longCoeffs :: [Maybe Double] longCoeffs = Just <$> [ 6288774, 1274027, 658314, 213618, -185116, -114332, 58793, 57066, 53322, 45758, -40923, -34720, -30383, 15327, -12528, 10980, 10675, 10034, 8548, -7888, -6766, -5163, 4987, 4036, 3994, 3861, 3665, -2689, -2602, 2390, -2348, 2236, -2120, -2069, 2048, -1773, -1595, 1215, -1110, -892, -810, 759, -713, -700, 691, 596, 549, 537, 520, -487, -399, -381, 351, -340, 330, 327, -323, 299, 294 ] distCoeffs :: [Maybe Double] distCoeffs = [ Just (-20905355), Just (-3699111), Just (-2955968), Just (-569925), Just 48888, Just (-3149), Just 246158, Just (-152138), Just (-170733), Just (-204586), Just (-129620), Just 108743, Just 104755, Just 10321, Nothing, Just 79661, Just (-34782), Just (-23210), Just (-21636), Just 24208, Just 30824, Just (-8379), Just (-16675), Just (-12831), Just (-10445), Just (-11650), Just 14403, Just (-7003), Nothing, Just 10056, Just 6322, Just (-9884), Just 5751, Nothing, Just (-4950), Just 4130, Nothing, Just (-3958), Nothing, Just 3258, Just 2616, Just (-1897), Just (-2117), Just 2354, Nothing, Nothing, Just (-1423), Just (-1117), Just (-1571), Just (-1739), Nothing, Just (-4421), Nothing, Nothing, Nothing, Nothing, Just 1165, Nothing, Nothing, Just 8752 ]
e61437d856c524545b8881ac1a2a0b696aea7de962bade33f0ba81e374d22baa
thheller/shadow-cljs
chokidar.cljs
(ns shadow.chokidar (:require ["chokidar" :refer (watch)])) (def watcher (watch #js ["src/dev" "src/main" "src/test"] #js {})) (defn watch-callback [event path] (js/console.log event path)) (defn main [& args] (.on watcher "all" watch-callback))
null
https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/src/repl/shadow/chokidar.cljs
clojure
(ns shadow.chokidar (:require ["chokidar" :refer (watch)])) (def watcher (watch #js ["src/dev" "src/main" "src/test"] #js {})) (defn watch-callback [event path] (js/console.log event path)) (defn main [& args] (.on watcher "all" watch-callback))
877f7a0372252cb04c2a6713bf3cd273888c0efc36225e70c0625fd79c3e2587
softwarelanguageslab/maf
phil.scm
Adapted from Savina benchmarks ( " Dining Philosophers benchmarks " , coming from Wikipedia ) (define Rounds (int-top)) (define NumForks (int-top)) (define NumPhilosophers NumForks) (define counter (actor "counter" (n) (add (m) (become counter (+ n m))) (finish () (display n) (terminate)))) (define arbitrator (actor "abritrator" (forks num-exited) (hungry (p id) (let ((left id) (right (modulo (+ id 1) NumForks))) (if (or (vector-ref forks left) (vector-ref forks right)) (send p denied) (begin ;; Modeled as side effects, probably not the best thing to do... but since there is only one arbitrator , that should be fine (vector-set! forks left #t) (vector-set! forks right #t) (send p eat)))) (become arbitrator forks num-exited)) (done (id) (let ((left id) (right (modulo (+ id 1) NumForks))) (vector-set! forks left #f) (vector-set! forks right #f)) (become arbitrator forks num-exited)) (exit () (if (= (+ num-exited 1) NumForks) (terminate) (become arbitrator forks (+ num-exited 1)))))) (define philosopher (actor "philosopher" (id rounds-so-far local-counter) (denied () (send arbitrator-actor hungry a/self id) (become philosopher id rounds-so-far (+ local-counter 1))) (eat () (send counter-actor add local-counter) (send arbitrator-actor done id) (if (< (+ rounds-so-far 1) Rounds) (begin ;; was: (send self start) (send arbitrator-actor hungry a/self id) (become philosopher id (+ rounds-so-far 1) local-counter)) (begin (send arbitrator-actor exit) (terminate)))) (start () (send arbitrator-actor hungry a/self id) (become philosopher id rounds-so-far local-counter)))) (define counter-actor (create counter 0)) (define arbitrator-actor (create arbitrator (make-vector NumForks #f) 0)) (define (create-philosophers i) (if (= i NumPhilosophers) #t (let ((p (create philosopher i 0 0))) (send p start) (create-philosophers (+ i 1))))) (create-philosophers 0)
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/4ad15e2fe3b8ceeb1bb77c1ff2737582675bfb77/test/concurrentScheme/actors/savina/phil.scm
scheme
Modeled as side effects, probably not the best thing to do... was: (send self start)
Adapted from Savina benchmarks ( " Dining Philosophers benchmarks " , coming from Wikipedia ) (define Rounds (int-top)) (define NumForks (int-top)) (define NumPhilosophers NumForks) (define counter (actor "counter" (n) (add (m) (become counter (+ n m))) (finish () (display n) (terminate)))) (define arbitrator (actor "abritrator" (forks num-exited) (hungry (p id) (let ((left id) (right (modulo (+ id 1) NumForks))) (if (or (vector-ref forks left) (vector-ref forks right)) (send p denied) (begin but since there is only one arbitrator , that should be fine (vector-set! forks left #t) (vector-set! forks right #t) (send p eat)))) (become arbitrator forks num-exited)) (done (id) (let ((left id) (right (modulo (+ id 1) NumForks))) (vector-set! forks left #f) (vector-set! forks right #f)) (become arbitrator forks num-exited)) (exit () (if (= (+ num-exited 1) NumForks) (terminate) (become arbitrator forks (+ num-exited 1)))))) (define philosopher (actor "philosopher" (id rounds-so-far local-counter) (denied () (send arbitrator-actor hungry a/self id) (become philosopher id rounds-so-far (+ local-counter 1))) (eat () (send counter-actor add local-counter) (send arbitrator-actor done id) (if (< (+ rounds-so-far 1) Rounds) (begin (send arbitrator-actor hungry a/self id) (become philosopher id (+ rounds-so-far 1) local-counter)) (begin (send arbitrator-actor exit) (terminate)))) (start () (send arbitrator-actor hungry a/self id) (become philosopher id rounds-so-far local-counter)))) (define counter-actor (create counter 0)) (define arbitrator-actor (create arbitrator (make-vector NumForks #f) 0)) (define (create-philosophers i) (if (= i NumPhilosophers) #t (let ((p (create philosopher i 0 0))) (send p start) (create-philosophers (+ i 1))))) (create-philosophers 0)
d0ad98bd648df6f375cb88b7950dc82d8f6a30950d5c1da83a0b139a386d66d8
alex-gutev/generic-cl
equality.lisp
;;;; equality.lisp ;;;; Copyright 2018 - 2021 ;;;; ;;;; 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. ;;;; Unit tests for equality predicates (in-package :generic-cl/test) Test Utilities (defmacro test-nary (name fn &body tests) "Evaluates the forms TESTS once in a LOCALLY block with the n-ary function FN declared INLINE (hinting that compiler-macros should be expanded) and once in a LOCALLY block with FN declared NOTINLINE, thus preventing compiler-macros from being expanded." `(progn (test ,(symbolicate name '- fn '-inline) (locally (declare (inline ,fn)) ,@tests)) (test ,(symbolicate name '- fn '-notinline) (locally (declare (notinline ,fn)) ,@tests)))) ;;; Test Suite Definition (def-suite equality :description "Test equality comparison functions" :in generic-cl) (in-suite equality) Test Equality ( EQUALP ) (test number-equalp "Test EQUALP on numbers" (is-true (equalp 1 1)) (is-true (equalp 2.0 2)) (is-true (equalp 6/3 2)) (is-false (equalp 1 0)) (is-false (equalp 1 'x)) (is-false (equalp 1 #\1))) (test-nary number = (is-true (= 1)) (is-true (= 1 1.0 2/2)) (is-false (= 1 "1" #\1))) (test-nary number /= (is-true "(/= 1)") (is-true (/= 1 "1" #\1)) (is-false (/= 1 1.0 2/2))) (test character-equalp "Test EQUALP on characters" (is-true (equalp #\a #\a)) (is-true (equalp #\0 #\0)) (is-false (equalp #\a #\A)) (is-false (equalp #\a 'a)) (is-false (equalp #\a "a"))) (test-nary character = (is-true (= #\a #\a #\a)) (is-false (= #\a #\A 'a))) (test-nary character /= (is-true (/= #\a 'a "a")) (is-false (/= #\a #\a #\a))) (test list-equalp "Test EQUALP on Lists/CONS cells" (is-true (equalp '(1 2 3) (list 1.0 2 3.0))) (is-true (equalp '(1 a #\x) (list 2/2 'a #\x))) (is-true (equalp '(((1 2) x y) #\z) (list (list (list 1 2) 'x 'y) #\z))) (is-true (equalp '(a b . c) (list* 'a 'b 'c))) (is-false (equalp '(1 2 3) '(1 2 1))) (is-false (equalp '(1 2 3) '(1 2))) (is-false (equalp '(1 2 3) '(1 2 . 3)))) (test vector-equalp "Test EQUALP on Vectors" (is-true (equalp #(1 2 3) (vector 1 2 3))) (is-true (equalp #(1 2 3) (make-array 3 :element-type 'number :adjustable t :fill-pointer t :initial-contents '(1 2 3)))) (is-true (equalp #(1 2 x) (vector 1.0 2 'x))) (is-true (equalp #(#(1 2) 3) (vector (vector 1.0 2.0) 3))) (is-true (equalp #((1 2) 3) (vector '(1.0 2.0) 3))) (is-false (equalp #(1 2 3) #(1 1 1))) (is-false (equalp #(1 2 3) #(1 2 3 4))) (is-false (equalp #(1 2 3) (make-array 0))) (is-false (equalp #(1 2 3) (make-array '(2 2) :initial-contents '((1 2) (3 4))))) (is-false (equalp #(#(1 2)) #(#(2 1))))) (test array-equalp "Test EQUALP on multi-dimensional arrays" (is-true (equalp #2A((1 2 3) (4 5 6)) (make-array '(2 3) :initial-contents '((1 2 3) (4 5 6))))) (is-true (equalp #2A((1 (3 4)) (5 #\c)) (make-array '(2 2) :initial-contents '((1 (3 4)) (5 #\c))))) (is-false (equalp #2A((1 2) (3 4)) #2A((1 1) (3 4)))) (is-false (equalp #2A((1 2) (3 4)) #(1 2 3 4)))) (test string-equalp "Test EQUALP on strings" (is-true (equalp "Hello" "Hello")) (is-true (equalp "World" (string '|World|))) (is-true (equalp "AAA" (make-string 3 :initial-element #\A))) (is-true (equalp "hello" (vector #\h #\e #\l #\l #\o))) (is-false (equalp "hello" "Hello")) (is-false (equalp "hello" '|hello|)) (is-false (equalp "world" "worlds"))) (test pathname-equalp "Test EQUALP on pathnames" ;; This is quite complicated to test properly as there are a lot ;; of possible cases (is-true (equalp (pathname "/usr/local/bin") #p"/usr/local/bin")) (is-false (equalp #p"/usr/local/bin" "/usr/local/bin")) (is-false (equalp #p"/usr/local/bin" #p"/USR/local/bin"))) (test hash-table-equalp "Test EQUALP on hash-tables" (let ((table (make-hash-map))) (setf (get 'x table) 1) (setf (get 'y table) 'z) (setf (get "hello" table) "world") (setf (get '(1 2 3) table) #\z) (is-true (equalp table (alist-hash-map '((x . 1) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-true (equalp table (alist-hash-map '((x . 1) (y . z) ("HELLO" . "world") ((1 2 3) . #\z)) :test #'cl:equalp))) (is-false (equalp table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (equalp table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (equalp table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z) ("x" . "z"))))))) (test object-equalp "Test default EQUALP method" (is-true (equalp 'a 'a)) (is-true (equalp *standard-output* *standard-output*)) (is-false (equalp 'a 'b))) Test Similarity ( LIKEP ) (test number-likep "Test LIKEP on numbers" (is-true (likep 1 1)) (is-true (likep 2.0 2)) (is-true (likep 6/3 2)) (is-false (likep 1 0)) (is-false (likep 1 'x)) (is-false (likep 1 #\1))) (test character-likep "Test LIKEP on characters" (is-true (likep #\a #\a)) (is-true (likep #\0 #\0)) (is-true (likep #\a #\A)) (is-false (likep #\a #\b)) (is-false (likep #\a 'a)) (is-false (likep #\a "a"))) (test list-likep "Test LIKEP on lists / CONS cells" (is-true (likep '(1 2 3) (list 1.0 2 3.0))) (is-true (likep '(1 a #\x) (list 2/2 'a #\x))) (is-true (likep '(((1 2) x y) #\Z) (list (list (list 1 2) 'x 'y) #\z))) (is-true (likep '(a b . c) (list* 'a 'b 'c))) (is-false (likep '(1 2 3) '(1 2 1))) (is-false (likep '(1 2 3) '(1 2))) (is-false (likep '(1 2 3) '(1 2 . 3))) (is-false (likep '(#\a #\b) '(#\x #\y)))) (test vector-likep "Test LIKEP on vectors" (is-true (likep #(1 2 3) (vector 1 2 3))) (is-true (likep #(1 2 3) (make-array 3 :element-type 'number :adjustable t :fill-pointer t :initial-contents '(1 2 3)))) (is-true (likep #(1 2 #\x) (vector 1.0 2 #\X))) (is-true (likep #(#(1 #\a) 3) (vector (vector 1.0 #\A) 3))) (is-true (likep #((1 2) 3) (vector '(1.0 2.0) 3))) (is-false (likep #(1 2 3) #(1 1 1))) (is-false (likep #(1 2 3) #(1 2 3 4))) (is-false (likep #(1 2 3) (make-array 0))) (is-false (likep #(1 2 3) (make-array '(2 2) :initial-contents '((1 2) (3 4))))) (is-false (likep #(#(1 2)) #(#(2 1)))) (is-false (likep #(#\a #\b) #(#\x #\y)))) (test array-likep "Test LIKEP on multi-dimensional arrays" (is-true (likep #2A((1 2 3) (4 5 6)) (make-array '(2 3) :initial-contents '((1 2 3) (4 5 6))))) (is-true (likep #2A((1 (3 4)) (5 #\C)) (make-array '(2 2) :initial-contents '((1 (3 4)) (5 #\c))))) (is-false (likep #2A((1 2) (3 4)) #2A((1 1) (3 4)))) (is-false (likep #2A((1 2) (3 4)) #(1 2 3 4)))) (test string-likep "Test LIKEP on strings" (is-true (likep "Hello" "Hello")) (is-true (likep "World" (string '|World|))) (is-true (likep "AAA" (make-string 3 :initial-element #\A))) (is-true (likep "hello" (vector #\H #\e #\l #\l #\o))) (is-true (likep "hello" "Hello")) (is-false (likep "hello" "hell")) (is-false (likep "hello" '|hello|)) (is-false (likep "world" "worlds"))) (test pathname-likep "Test LIKEP on pathnames" ;; This is quite complicated to test properly as there are a lot ;; of possible cases (is-true (likep (pathname "/usr/local/bin") #p"/usr/local/bin")) (is-false (likep #p"/usr/local/bin" "/usr/local/bin")) (is-false (likep #p"/usr/local/bin" #p"/USR/local/bin"))) (test hash-table-likep "Test LIKEP on hash-tables" (let ((table (make-hash-map))) (setf (get 'x table) 1) (setf (get 'y table) 'z) (setf (get "hello" table) "world") (setf (get '(1 2 3) table) #\z) (is-true (likep table (alist-hash-map '((x . 1) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-true (likep table (alist-hash-map '((x . 1) (y . z) ("HELLO" . "world") ((1 2 3) . #\Z))))) (is-false (likep table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (likep table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (likep table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z) ("x" . "z"))))))) (test object-likep "Test default LIKEP method" (is-true (likep 'a 'a)) (is-true (likep *standard-output* *standard-output*)) (is-false (likep 'a 'b)))
null
https://raw.githubusercontent.com/alex-gutev/generic-cl/a2626e85f400ba6f453ce849899071b722c2b6b5/test/equality.lisp
lisp
equality.lisp Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be 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. Unit tests for equality predicates Test Suite Definition This is quite complicated to test properly as there are a lot of possible cases This is quite complicated to test properly as there are a lot of possible cases
Copyright 2018 - 2021 files ( the " Software " ) , to deal in the Software without copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package :generic-cl/test) Test Utilities (defmacro test-nary (name fn &body tests) "Evaluates the forms TESTS once in a LOCALLY block with the n-ary function FN declared INLINE (hinting that compiler-macros should be expanded) and once in a LOCALLY block with FN declared NOTINLINE, thus preventing compiler-macros from being expanded." `(progn (test ,(symbolicate name '- fn '-inline) (locally (declare (inline ,fn)) ,@tests)) (test ,(symbolicate name '- fn '-notinline) (locally (declare (notinline ,fn)) ,@tests)))) (def-suite equality :description "Test equality comparison functions" :in generic-cl) (in-suite equality) Test Equality ( EQUALP ) (test number-equalp "Test EQUALP on numbers" (is-true (equalp 1 1)) (is-true (equalp 2.0 2)) (is-true (equalp 6/3 2)) (is-false (equalp 1 0)) (is-false (equalp 1 'x)) (is-false (equalp 1 #\1))) (test-nary number = (is-true (= 1)) (is-true (= 1 1.0 2/2)) (is-false (= 1 "1" #\1))) (test-nary number /= (is-true "(/= 1)") (is-true (/= 1 "1" #\1)) (is-false (/= 1 1.0 2/2))) (test character-equalp "Test EQUALP on characters" (is-true (equalp #\a #\a)) (is-true (equalp #\0 #\0)) (is-false (equalp #\a #\A)) (is-false (equalp #\a 'a)) (is-false (equalp #\a "a"))) (test-nary character = (is-true (= #\a #\a #\a)) (is-false (= #\a #\A 'a))) (test-nary character /= (is-true (/= #\a 'a "a")) (is-false (/= #\a #\a #\a))) (test list-equalp "Test EQUALP on Lists/CONS cells" (is-true (equalp '(1 2 3) (list 1.0 2 3.0))) (is-true (equalp '(1 a #\x) (list 2/2 'a #\x))) (is-true (equalp '(((1 2) x y) #\z) (list (list (list 1 2) 'x 'y) #\z))) (is-true (equalp '(a b . c) (list* 'a 'b 'c))) (is-false (equalp '(1 2 3) '(1 2 1))) (is-false (equalp '(1 2 3) '(1 2))) (is-false (equalp '(1 2 3) '(1 2 . 3)))) (test vector-equalp "Test EQUALP on Vectors" (is-true (equalp #(1 2 3) (vector 1 2 3))) (is-true (equalp #(1 2 3) (make-array 3 :element-type 'number :adjustable t :fill-pointer t :initial-contents '(1 2 3)))) (is-true (equalp #(1 2 x) (vector 1.0 2 'x))) (is-true (equalp #(#(1 2) 3) (vector (vector 1.0 2.0) 3))) (is-true (equalp #((1 2) 3) (vector '(1.0 2.0) 3))) (is-false (equalp #(1 2 3) #(1 1 1))) (is-false (equalp #(1 2 3) #(1 2 3 4))) (is-false (equalp #(1 2 3) (make-array 0))) (is-false (equalp #(1 2 3) (make-array '(2 2) :initial-contents '((1 2) (3 4))))) (is-false (equalp #(#(1 2)) #(#(2 1))))) (test array-equalp "Test EQUALP on multi-dimensional arrays" (is-true (equalp #2A((1 2 3) (4 5 6)) (make-array '(2 3) :initial-contents '((1 2 3) (4 5 6))))) (is-true (equalp #2A((1 (3 4)) (5 #\c)) (make-array '(2 2) :initial-contents '((1 (3 4)) (5 #\c))))) (is-false (equalp #2A((1 2) (3 4)) #2A((1 1) (3 4)))) (is-false (equalp #2A((1 2) (3 4)) #(1 2 3 4)))) (test string-equalp "Test EQUALP on strings" (is-true (equalp "Hello" "Hello")) (is-true (equalp "World" (string '|World|))) (is-true (equalp "AAA" (make-string 3 :initial-element #\A))) (is-true (equalp "hello" (vector #\h #\e #\l #\l #\o))) (is-false (equalp "hello" "Hello")) (is-false (equalp "hello" '|hello|)) (is-false (equalp "world" "worlds"))) (test pathname-equalp "Test EQUALP on pathnames" (is-true (equalp (pathname "/usr/local/bin") #p"/usr/local/bin")) (is-false (equalp #p"/usr/local/bin" "/usr/local/bin")) (is-false (equalp #p"/usr/local/bin" #p"/USR/local/bin"))) (test hash-table-equalp "Test EQUALP on hash-tables" (let ((table (make-hash-map))) (setf (get 'x table) 1) (setf (get 'y table) 'z) (setf (get "hello" table) "world") (setf (get '(1 2 3) table) #\z) (is-true (equalp table (alist-hash-map '((x . 1) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-true (equalp table (alist-hash-map '((x . 1) (y . z) ("HELLO" . "world") ((1 2 3) . #\z)) :test #'cl:equalp))) (is-false (equalp table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (equalp table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (equalp table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z) ("x" . "z"))))))) (test object-equalp "Test default EQUALP method" (is-true (equalp 'a 'a)) (is-true (equalp *standard-output* *standard-output*)) (is-false (equalp 'a 'b))) Test Similarity ( LIKEP ) (test number-likep "Test LIKEP on numbers" (is-true (likep 1 1)) (is-true (likep 2.0 2)) (is-true (likep 6/3 2)) (is-false (likep 1 0)) (is-false (likep 1 'x)) (is-false (likep 1 #\1))) (test character-likep "Test LIKEP on characters" (is-true (likep #\a #\a)) (is-true (likep #\0 #\0)) (is-true (likep #\a #\A)) (is-false (likep #\a #\b)) (is-false (likep #\a 'a)) (is-false (likep #\a "a"))) (test list-likep "Test LIKEP on lists / CONS cells" (is-true (likep '(1 2 3) (list 1.0 2 3.0))) (is-true (likep '(1 a #\x) (list 2/2 'a #\x))) (is-true (likep '(((1 2) x y) #\Z) (list (list (list 1 2) 'x 'y) #\z))) (is-true (likep '(a b . c) (list* 'a 'b 'c))) (is-false (likep '(1 2 3) '(1 2 1))) (is-false (likep '(1 2 3) '(1 2))) (is-false (likep '(1 2 3) '(1 2 . 3))) (is-false (likep '(#\a #\b) '(#\x #\y)))) (test vector-likep "Test LIKEP on vectors" (is-true (likep #(1 2 3) (vector 1 2 3))) (is-true (likep #(1 2 3) (make-array 3 :element-type 'number :adjustable t :fill-pointer t :initial-contents '(1 2 3)))) (is-true (likep #(1 2 #\x) (vector 1.0 2 #\X))) (is-true (likep #(#(1 #\a) 3) (vector (vector 1.0 #\A) 3))) (is-true (likep #((1 2) 3) (vector '(1.0 2.0) 3))) (is-false (likep #(1 2 3) #(1 1 1))) (is-false (likep #(1 2 3) #(1 2 3 4))) (is-false (likep #(1 2 3) (make-array 0))) (is-false (likep #(1 2 3) (make-array '(2 2) :initial-contents '((1 2) (3 4))))) (is-false (likep #(#(1 2)) #(#(2 1)))) (is-false (likep #(#\a #\b) #(#\x #\y)))) (test array-likep "Test LIKEP on multi-dimensional arrays" (is-true (likep #2A((1 2 3) (4 5 6)) (make-array '(2 3) :initial-contents '((1 2 3) (4 5 6))))) (is-true (likep #2A((1 (3 4)) (5 #\C)) (make-array '(2 2) :initial-contents '((1 (3 4)) (5 #\c))))) (is-false (likep #2A((1 2) (3 4)) #2A((1 1) (3 4)))) (is-false (likep #2A((1 2) (3 4)) #(1 2 3 4)))) (test string-likep "Test LIKEP on strings" (is-true (likep "Hello" "Hello")) (is-true (likep "World" (string '|World|))) (is-true (likep "AAA" (make-string 3 :initial-element #\A))) (is-true (likep "hello" (vector #\H #\e #\l #\l #\o))) (is-true (likep "hello" "Hello")) (is-false (likep "hello" "hell")) (is-false (likep "hello" '|hello|)) (is-false (likep "world" "worlds"))) (test pathname-likep "Test LIKEP on pathnames" (is-true (likep (pathname "/usr/local/bin") #p"/usr/local/bin")) (is-false (likep #p"/usr/local/bin" "/usr/local/bin")) (is-false (likep #p"/usr/local/bin" #p"/USR/local/bin"))) (test hash-table-likep "Test LIKEP on hash-tables" (let ((table (make-hash-map))) (setf (get 'x table) 1) (setf (get 'y table) 'z) (setf (get "hello" table) "world") (setf (get '(1 2 3) table) #\z) (is-true (likep table (alist-hash-map '((x . 1) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-true (likep table (alist-hash-map '((x . 1) (y . z) ("HELLO" . "world") ((1 2 3) . #\Z))))) (is-false (likep table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (likep table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z))))) (is-false (likep table (alist-hash-map '((x . 2) (y . z) ("hello" . "world") ((1 2 3) . #\z) ("x" . "z"))))))) (test object-likep "Test default LIKEP method" (is-true (likep 'a 'a)) (is-true (likep *standard-output* *standard-output*)) (is-false (likep 'a 'b)))
987c0030c153fd4fe4419f4a0f6862e14f6cd8f4b5d08ca8df5dbec9a127ff84
fogfish/pts
pts_sup.erl
%% Copyright ( c ) 2012 , %% All Rights Reserved. %% %% This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License , version 3.0 as published by the Free Software Foundation ( the " License " ) . %% 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. %% You should have received a copy of the GNU Lesser General Public %% License along with this library; if not, write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA or retrieve online -3.0.html %% -module(pts_sup). -behaviour(supervisor). -author('Dmitry Kolesnikov <>'). -export([ start_link/0, init/1 ]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, { {one_for_one, 2, 60}, [] } }.
null
https://raw.githubusercontent.com/fogfish/pts/f98c594f1e596f81b5e54c9791bf69568327fba2/src/pts_sup.erl
erlang
All Rights Reserved. This library is free software; you can redistribute it and/or modify basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. License along with this library; if not, write to the Free Software
Copyright ( c ) 2012 , it under the terms of the GNU Lesser General Public License , version 3.0 as published by the Free Software Foundation ( the " License " ) . Software distributed under the License is distributed on an " AS IS " You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA or retrieve online -3.0.html -module(pts_sup). -behaviour(supervisor). -author('Dmitry Kolesnikov <>'). -export([ start_link/0, init/1 ]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, { {one_for_one, 2, 60}, [] } }.
f6dedf942964b7e2a4f870b5e49b57a7695efc7c34c6f5dd78a589ddce3fd00d
parapluu/Concuerror
receive_deps.erl
-module(receive_deps). -export([test/0]). -export([scenarios/0]). -concuerror_options_forced([{ignore_error, deadlock}]). scenarios() -> [{test, inf, dpor}]. test() -> P = self(), ets:new(table, [public, named_table]), Fun = fun(X) -> fun() -> P ! X, case X =:= 1 orelse ets:lookup(table, k) =:= [{k,1}] of true -> ets:insert(table, {k,X}); false -> ok end end end, spawn(Fun(1)), spawn(Fun(2)), spawn(Fun(3)), receive A -> receive B when B =/= A -> receive C when C =/= A, C =/= B -> ok end end end, true = ets:lookup(table,k) =/= [{k,3}], receive after infinity -> ok end.
null
https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/advanced_tests/src/receive_deps.erl
erlang
-module(receive_deps). -export([test/0]). -export([scenarios/0]). -concuerror_options_forced([{ignore_error, deadlock}]). scenarios() -> [{test, inf, dpor}]. test() -> P = self(), ets:new(table, [public, named_table]), Fun = fun(X) -> fun() -> P ! X, case X =:= 1 orelse ets:lookup(table, k) =:= [{k,1}] of true -> ets:insert(table, {k,X}); false -> ok end end end, spawn(Fun(1)), spawn(Fun(2)), spawn(Fun(3)), receive A -> receive B when B =/= A -> receive C when C =/= A, C =/= B -> ok end end end, true = ets:lookup(table,k) =/= [{k,3}], receive after infinity -> ok end.
2443feb81bedd45fe7b3703da4c3084f7b2ec69dabf1deec17387ebda0224d1b
haskell-works/hw-kafka-avro
Avro.hs
module Kafka.Avro ( module X , propagateKeySchema , propagateValueSchema ) where import Control.Monad.IO.Class import Data.ByteString.Lazy import Kafka.Avro.Decode as X import Kafka.Avro.Encode as X import Kafka.Avro.SchemaRegistry as X -- | Registers schema that was used for a given payload against the specified subject as a key shema. -- It is possible that a given payload doesn't have schema registered against it, in this case no prapagation happens. propagateKeySchema :: MonadIO m => SchemaRegistry -> Subject -> ByteString -> m (Either SchemaRegistryError (Maybe SchemaId)) propagateKeySchema sr subj = propagateSchema sr (keySubject subj) -- | Registers schema that was used for a given payload against the specified subject as a value schema. -- It is possible that a given payload doesn't have schema registered against it, in this case no prapagation happens. propagateValueSchema :: MonadIO m => SchemaRegistry -> Subject -> ByteString -> m (Either SchemaRegistryError (Maybe SchemaId)) propagateValueSchema sr subj = propagateSchema sr (valueSubject subj) propagateSchema :: MonadIO m => SchemaRegistry -> Subject -> ByteString -> m (Either SchemaRegistryError (Maybe SchemaId)) propagateSchema sr subj bs = case extractSchemaId bs of Nothing -> return $ Right Nothing Just (sid, _) -> do mSchema <- loadSchema sr sid case mSchema of Left (SchemaRegistrySchemaNotFound _) -> return $ Right Nothing Left err -> return $ Left err Right schema -> fmap Just <$> sendSchema sr subj schema
null
https://raw.githubusercontent.com/haskell-works/hw-kafka-avro/12af0eaaae1e0bff227b73864f7305714e458947/src/Kafka/Avro.hs
haskell
| Registers schema that was used for a given payload against the specified subject as a key shema. It is possible that a given payload doesn't have schema registered against it, in this case no prapagation happens. | Registers schema that was used for a given payload against the specified subject as a value schema. It is possible that a given payload doesn't have schema registered against it, in this case no prapagation happens.
module Kafka.Avro ( module X , propagateKeySchema , propagateValueSchema ) where import Control.Monad.IO.Class import Data.ByteString.Lazy import Kafka.Avro.Decode as X import Kafka.Avro.Encode as X import Kafka.Avro.SchemaRegistry as X propagateKeySchema :: MonadIO m => SchemaRegistry -> Subject -> ByteString -> m (Either SchemaRegistryError (Maybe SchemaId)) propagateKeySchema sr subj = propagateSchema sr (keySubject subj) propagateValueSchema :: MonadIO m => SchemaRegistry -> Subject -> ByteString -> m (Either SchemaRegistryError (Maybe SchemaId)) propagateValueSchema sr subj = propagateSchema sr (valueSubject subj) propagateSchema :: MonadIO m => SchemaRegistry -> Subject -> ByteString -> m (Either SchemaRegistryError (Maybe SchemaId)) propagateSchema sr subj bs = case extractSchemaId bs of Nothing -> return $ Right Nothing Just (sid, _) -> do mSchema <- loadSchema sr sid case mSchema of Left (SchemaRegistrySchemaNotFound _) -> return $ Right Nothing Left err -> return $ Left err Right schema -> fmap Just <$> sendSchema sr subj schema
1091c726afeed62b37c03d2fde756a00e8f20a6be3b951141dfa4475972390de
spartango/CS153
compile.ml
(* Compile Cish AST to MIPS AST *) open Mips open Ast open Utility open Word32 exception TODO type result = { code : Mips.inst list; data : Mips.label list } (* generate fresh labels *) let label_counter = ref 0 let new_int() = (label_counter := (!label_counter) + 1; !label_counter) let new_label() = "L" ^ (string_of_int (new_int())) (* Stack Manipulation *) Offset is with respect to the Frame Pointer ( fp ) type virtualStack = { last_offset : int32; contents : int32 StringMap.t} (* Code Gen *) let sanitize_f_name (f : string) : string= if (f <> "main") then "f_"^f else f (* Generates code to push a variable on to the stack *) let add_local_var (v : string) (stack : virtualStack) : virtualStack * inst list = (* Push variable on to stack *) Variable is an aligned 32 bit int let new_contents = StringMap.add v stack.last_offset stack.contents in let new_stack = { last_offset = (Int32.add stack.last_offset (-4l)) ; contents = new_contents } in (* Generate corresponding instructions *) (* Move $sp *) let insts = [ Add(sp, sp, Immed(-4l)); ] in (new_stack, insts) (* Generates code to pop a variable off the stack *) let pop_local_var (v : string) (stack : virtualStack) : virtualStack * inst list = let new_contents = StringMap.remove v stack.contents in let new_stack = { last_offset = (Int32.add stack.last_offset 4l) ; contents = new_contents } in let insts = [ Add(sp, sp, Immed(4l)); ] in (new_stack, insts) (* Provides the offset of a variable relative to the stack ptr *) let find_local_var (v : string) (stack : virtualStack) : int32 = StringMap.find v stack.contents (* Generates code to create a new temporary var *) let rec new_temp (stack : virtualStack) : string * virtualStack * inst list = (* Create a variable, add it *) let name = "T"^ (string_of_int (new_int ())) in let (new_stack, insts) = add_local_var name stack in (name, new_stack, insts) (* Function prologue generation *) let generate_prologue (f_sig : funcsig) (stack : virtualStack) : virtualStack * inst list = let n_args = List.length f_sig.args in let arg_offset = (Int32.mul (-4l) (Int32.of_int n_args)) in Save the old FP and set new FP let insts = [ Sw (fp, sp, arg_offset); Add(fp, sp, Reg(R0)); ] in let rec mark_high_args skipped_num arg_names t_stack t_insts = if skipped_num < 4 then mark_high_args (skipped_num + 1) (List.tl arg_names) t_stack t_insts else match arg_names with | [] -> (t_stack, t_insts) | hd::rest -> let (new_stack, new_insts) = add_local_var hd t_stack in mark_high_args skipped_num rest new_stack (t_insts @ new_insts) in let rec save_low_args touched_num arg_names t_stack t_insts = if touched_num >= 4 then (t_stack, t_insts) else match arg_names with | [] -> (t_stack, t_insts) | hd::rest -> let (new_stack, new_insts) = add_local_var hd t_stack in let new_insts = new_insts @ [ Sw((string2reg ("A"^(string_of_int touched_num))), fp, (find_local_var hd new_stack)); ] in save_low_args (touched_num + 1) rest new_stack (t_insts @ new_insts) in Then the first 4 args (* Save the rest of the arguments a0 - a3 *) let (new_stack, narg_insts) = save_low_args 0 f_sig.args stack [] in (* Mark the stack positions of arguments *) First are n_arg > 3 let (new_stack, arg_insts) = if (arg_offset > -16l) then (new_stack, []) else mark_high_args 0 f_sig.args new_stack [] in let (new_stack, fp_insts) = add_local_var "FP" new_stack in Save saved registers : $ ra , and $ s0-$s7 ( $ 16-$23 ) let (new_stack, ra_insts) = add_local_var "RA" new_stack in let ra_insts = ra_insts @ [ Sw(ra, fp, (find_local_var "RA" new_stack)); ] in let rec save_sregs (num : int) (t_stack : virtualStack) (t_insts : inst list) = if num < 0 then (t_stack, t_insts) else let name = "S"^(string_of_int num) in let (new_stack, s_insts) = add_local_var name t_stack in let new_insts = s_insts @ [ Sw((string2reg name), fp, (find_local_var name new_stack)); ] in save_sregs (num - 1) new_stack (t_insts @ new_insts) in let (new_stack, s_insts) = save_sregs 7 new_stack [] in let new_insts = (insts @ arg_insts @ narg_insts @ fp_insts @ ra_insts @ s_insts) in (new_stack, new_insts) (* Function epilogue generation *) let generate_epilogue (stack : virtualStack) : virtualStack * inst list = Restore saved registers : $ fp , $ ra , and $ s0-$s7 ( $ 16-$23 ) let rec load_sregs (num : int) (t_insts : inst list) = if num < 0 then t_insts else let name = "S"^(string_of_int num) in load_sregs (num - 1) t_insts @ [ Lw((string2reg name), fp, (find_local_var name stack)); ] in let s_insts = load_sregs 7 [] in let ra_fp_insts = [ Lw(ra, fp, (find_local_var "RA" stack)); Lw(fp, fp, (find_local_var "FP" stack)); ] in let jr_insts = [ Jr(R31); ] in let new_insts = s_insts @ ra_fp_insts @ jr_insts in Reset the SP to our FP ( frame pop ) (stack, new_insts) Factors out common code for compiling two nested expressions and * carrying out some instruction . The result of e1 is stored in R3 , * the result of e2 in R2 . in is the instruction to carry out on these * results * carrying out some instruction. The result of e1 is stored in R3, * the result of e2 in R2. in is the instruction to carry out on these * results *) (* Returns assembly code to store var from stack *) let store_var (stack: virtualStack) (v: string) (dest: Mips.reg) : inst = Sw(dest, fp, (find_local_var v stack)) (* Returns assembly code to load var from stack *) let load_var (stack: virtualStack) (v: string) (dest: Mips.reg) : inst = Lw(dest, fp, (find_local_var v stack)) (* Places result in R2 *) let rec compile_exp_r (is: RInstList.rlist) ((e,_): Ast.exp) (stack : virtualStack) : virtualStack * RInstList.rlist = HELPER : Compiles e1 and e2 . Result of e1 goes in R2 , e2 in R3 let dual_op (e1: Ast.exp) (e2: Ast.exp) (instructions: inst list) : virtualStack * RInstList.rlist = let (t, stack1, insts1) = new_temp stack in Compile e2 first so result goes in R3 , getting resulting instructions and stack let (stack2, insts2) = compile_exp_r (is <@ insts1) e2 stack1 in (* Store result of e2; compile e1 *) let (stack3, insts3) = compile_exp_r (insts2 <@ [(store_var stack2 t R2)]) e1 stack2 in (* Load e2 into R3 and execute instruction *) let insts4 = insts3 <@ [(load_var stack3 t R3)] <@ instructions in (* Pop temp var *) let (stack4, pop_inst) = pop_local_var t stack3 in (stack3, insts4 <@ pop_inst) in match e with | Var v -> (stack, is <@ [(load_var stack v R2)]) (* Load from the correct stack offset *) | Int i -> (stack, is <@ [Li(R2, Word32.fromInt i)]) | Binop(e1,op,e2) -> let oper = (match op with | Plus -> Mips.Add(R2, R2, Reg(R3)) | Minus -> Mips.Sub(R2, R2, R3) | Times -> Mips.Mul(R2, R2, R3) | Div -> Mips.Div(R2, R2, R3) | Eq -> Mips.Seq(R2, R2, R3) | Neq -> Mips.Sne(R2, R2, R3) | Lt -> Mips.Slt(R2, R2, Reg(R3)) | Lte -> Mips.Sle(R2, R2, R3) | Gt -> Mips.Sgt(R2, R2, R3) | Gte -> Mips.Sge(R2, R2, R3)) in dual_op e1 e2 [oper] If R2 = 0 , then set R2 = 1 , else R2 = 0 | Not(e) -> let (stack1, insts1) = compile_exp_r is e stack in (stack1, insts1 <@ [Mips.Seq(R2, R2, R0)]) | And(e1, e2) -> dual_op e1 e2 [ If R2 = 0 , then R2 = 0 , else R2 = 1 Mips.Sne(R2, R2, R0); If R3 = 0 , then R3 = 0 , else R3 = 1 Mips.Sne(R3, R3, R0); If R2 = R3 = 1 , then R2 = 1 , else R2 = 0 Mips.And(R2, R2, Reg R3) ] | Or(e1, e2) -> dual_op e1 e2 [ If R2 = 0 , then R2 = 0 , else R2 = 1 Mips.Sne(R2, R2, R0); If R3 = 0 , then R3 = 0 , else R3 = 1 Mips.Sne(R3, R3, R0); If R2 or R3 = 1 , then R2 = 1 , else R2 = 0 Mips.Or(R2, R2, Reg R3) ] (* Assumes variable has already been delcared; if not allows exception to fall through *) | Assign(v, e) -> let (stack1, insts1) = compile_exp_r is e stack in (stack1, insts1 <@ [(store_var stack1 v R2)]) | Call(f, exp_list) -> compile_call (sanitize_f_name f) exp_list stack is and compile_call f exp_list (stack : virtualStack) (prev_insts: RInstList.rlist) : virtualStack * RInstList.rlist = let arg_offset = Int32.of_int ((List.length exp_list) * -4) in (* helper to deal with groups of args *) let rec compile_call_r argno exps t_stack t_insts = (* For each expression *) match exps with | [] -> (t_stack, t_insts <@ [ Jal(f); ]) (* Jump and Link *) | t_exp::rest -> (* Setup Sandbox *) let sandbox_stack = { contents = t_stack.contents; last_offset = (Int32.add t_stack.last_offset arg_offset); } in (* Compile expression *) let (sandbox_stack, new_insts) = compile_exp_r t_insts t_exp sandbox_stack in Exit Sandbox Move result into aX OR If n_arg > 3 then push arg into next frame ( past sp ) let mv_insts = (if argno < 4 then [ Add((string2reg ("A"^(string_of_int argno))), R2, Reg(R0)); ] else [] ) @ [ Sw(R2, sp, (Int32.mul (-4l) (Int32.of_int argno))); ] in compile_call_r (argno + 1) rest t_stack ( new_insts <@ mv_insts ) in compile_call_r 0 exp_list stack prev_insts (* Compiles a statement in reverse order *) let rec compile_stmt_r (is: RInstList.rlist) ((s,pos): Ast.stmt) (stack : virtualStack) : virtualStack * RInstList.rlist = match s with Using directly eliminates redundant reversing the list | Exp e -> compile_exp_r is e stack | Let(t_var, t_exp, t_stmt) -> (* Push a variable on to the stack *) let (stack1, insts1) = add_local_var t_var stack in (* Compile the expression *) let (stack2, insts2) = compile_exp_r (is <@ insts1) t_exp stack1 in (* Store the expression in the var *) let sw_insts = [(store_var stack2 t_var R2)] in (* Compile the statment *) let (stack3, insts3) = compile_stmt_r (insts2 <@ sw_insts) t_stmt stack2 in (* Pop the variable *) let (stack4, pop_insts) = pop_local_var t_var stack3 in (stack4, insts3 <@ pop_insts) | Seq (s1, s2) -> let(stack1, insts1) = compile_stmt_r is s1 stack in compile_stmt_r insts1 s2 stack1 | If(e, then_s, else_s) -> (* Labels *) let else_l = new_label () in let end_l = new_label () in (* Compile expression e*) let (stack1, insts1) = compile_exp_r is e stack in Branch is e1 evaluates to false let branch_inst = [Beq(R2,R0,else_l)] in (* Compile then_s *) let (stack2, insts2) = compile_stmt_r (insts1 <@ branch_inst) then_s stack1 in (* Jump to end, place else label *) let else_inst = [J(end_l); Label(else_l)] in (* Compile else_s *) let (stack3, insts3) = compile_stmt_r (insts2 <@ else_inst) else_s stack2 in (* Append end label *) (stack3, insts3 <@ [Label(end_l)]) | While(e, s) -> (* Labels *) let test_l = new_label () in let top_l = new_label () in (* Jump and top label *) let head_inst = [J(test_l); Label(top_l)] in (* Compile statement *) let (stack1, insts1) = compile_stmt_r (is <@ head_inst) s stack in (* Test label instruction *) let test_inst = [Label(test_l)] in (* Compile expression *) let (stack2, insts2) = compile_exp_r (insts1 <@ test_inst) e stack1 in (* Append branch if expression is false *) (stack2, insts2 <@ [Bne(R2,R0,top_l)]) (* Transform for loops into while loops *) | For(e1, e2, e3, s) -> (* Helper to get position out of statement *) let get_pos s = let (_,p) = s in p in Nastiness due to necesity of having position compile_stmt_r is ((Ast.Seq( (Ast.Exp e1, (get_pos e1)), (While( e2, (Ast.Seq(s, (Ast.Exp e3, (get_pos e3))), get_pos s)), pos))), pos) stack | Return (e) -> compile_exp_r is e stack compiles a Fish statement down to a list of MIPS instructions . * Note that a " Return " is accomplished by placing the resulting * value in R2 and then doing . * Note that a "Return" is accomplished by placing the resulting * value in R2 and then doing a Jr R31. *) let compile_stmt (s : Ast.stmt) (stack : virtualStack) : virtualStack * inst list = let(stack1, insts1) = compile_stmt_r RInstList.empty s stack in (stack1, RInstList.to_list insts1) let compile_function (f : func) : inst list = let Fn(signature) = f in (* Allocate a local "stack" (Map) to simulate the real stack *) let local_stack = { last_offset = 0l; contents = StringMap.empty } in (* Generate a label for the function *) let f_label = Label((sanitize_f_name signature.name)) in (* Generate a prologue for the function *) let (new_stack, prologue_code) = generate_prologue signature local_stack in (* Code gen for the function *) let (new_stack, body_code) = compile_stmt signature.body new_stack in (* Generate an epilogue for the function *) let (new_stack, epilogue_code) = generate_epilogue new_stack in Concate code blocks together ([ f_label; ] @ prologue_code @ body_code @ epilogue_code) let rec compile (p:Ast.program) : result = let rec compile_prog (prog : Ast.program) (compiled : result) = match prog with | [] -> compiled | f::rest -> let new_insts = compile_function f in compile_prog rest { code = compiled.code @ new_insts; data = compiled.data } in compile_prog p { code = []; data = [] } let result2string (res:result) : string = let code = res.code in let data = res.data in let strs = List.map (fun x -> (Mips.inst2string x) ^ "\n") code in let vaR8decl x = x ^ ":\t.word 0\n" in let readfile f = let stream = open_in f in let size = in_channel_length stream in let text = String.create size in let _ = really_input stream text 0 size in let _ = close_in stream in text in let debugcode = readfile "print.asm" in "\t.text\n" ^ "\t.align\t2\n" ^ "\t.globl main\n" ^ (String.concat "" strs) ^ "\n\n" ^ "\t.data\n" ^ "\t.align 0\n"^ (String.concat "" (List.map vaR8decl data)) ^ "\n" ^ debugcode
null
https://raw.githubusercontent.com/spartango/CS153/16faf133889f1b287cb95c1ea1245d76c1d8db49/ps3/compile.ml
ocaml
Compile Cish AST to MIPS AST generate fresh labels Stack Manipulation Code Gen Generates code to push a variable on to the stack Push variable on to stack Generate corresponding instructions Move $sp Generates code to pop a variable off the stack Provides the offset of a variable relative to the stack ptr Generates code to create a new temporary var Create a variable, add it Function prologue generation Save the rest of the arguments a0 - a3 Mark the stack positions of arguments Function epilogue generation Returns assembly code to store var from stack Returns assembly code to load var from stack Places result in R2 Store result of e2; compile e1 Load e2 into R3 and execute instruction Pop temp var Load from the correct stack offset Assumes variable has already been delcared; if not allows exception to fall through helper to deal with groups of args For each expression Jump and Link Setup Sandbox Compile expression Compiles a statement in reverse order Push a variable on to the stack Compile the expression Store the expression in the var Compile the statment Pop the variable Labels Compile expression e Compile then_s Jump to end, place else label Compile else_s Append end label Labels Jump and top label Compile statement Test label instruction Compile expression Append branch if expression is false Transform for loops into while loops Helper to get position out of statement Allocate a local "stack" (Map) to simulate the real stack Generate a label for the function Generate a prologue for the function Code gen for the function Generate an epilogue for the function
open Mips open Ast open Utility open Word32 exception TODO type result = { code : Mips.inst list; data : Mips.label list } let label_counter = ref 0 let new_int() = (label_counter := (!label_counter) + 1; !label_counter) let new_label() = "L" ^ (string_of_int (new_int())) Offset is with respect to the Frame Pointer ( fp ) type virtualStack = { last_offset : int32; contents : int32 StringMap.t} let sanitize_f_name (f : string) : string= if (f <> "main") then "f_"^f else f let add_local_var (v : string) (stack : virtualStack) : virtualStack * inst list = Variable is an aligned 32 bit int let new_contents = StringMap.add v stack.last_offset stack.contents in let new_stack = { last_offset = (Int32.add stack.last_offset (-4l)) ; contents = new_contents } in let insts = [ Add(sp, sp, Immed(-4l)); ] in (new_stack, insts) let pop_local_var (v : string) (stack : virtualStack) : virtualStack * inst list = let new_contents = StringMap.remove v stack.contents in let new_stack = { last_offset = (Int32.add stack.last_offset 4l) ; contents = new_contents } in let insts = [ Add(sp, sp, Immed(4l)); ] in (new_stack, insts) let find_local_var (v : string) (stack : virtualStack) : int32 = StringMap.find v stack.contents let rec new_temp (stack : virtualStack) : string * virtualStack * inst list = let name = "T"^ (string_of_int (new_int ())) in let (new_stack, insts) = add_local_var name stack in (name, new_stack, insts) let generate_prologue (f_sig : funcsig) (stack : virtualStack) : virtualStack * inst list = let n_args = List.length f_sig.args in let arg_offset = (Int32.mul (-4l) (Int32.of_int n_args)) in Save the old FP and set new FP let insts = [ Sw (fp, sp, arg_offset); Add(fp, sp, Reg(R0)); ] in let rec mark_high_args skipped_num arg_names t_stack t_insts = if skipped_num < 4 then mark_high_args (skipped_num + 1) (List.tl arg_names) t_stack t_insts else match arg_names with | [] -> (t_stack, t_insts) | hd::rest -> let (new_stack, new_insts) = add_local_var hd t_stack in mark_high_args skipped_num rest new_stack (t_insts @ new_insts) in let rec save_low_args touched_num arg_names t_stack t_insts = if touched_num >= 4 then (t_stack, t_insts) else match arg_names with | [] -> (t_stack, t_insts) | hd::rest -> let (new_stack, new_insts) = add_local_var hd t_stack in let new_insts = new_insts @ [ Sw((string2reg ("A"^(string_of_int touched_num))), fp, (find_local_var hd new_stack)); ] in save_low_args (touched_num + 1) rest new_stack (t_insts @ new_insts) in Then the first 4 args let (new_stack, narg_insts) = save_low_args 0 f_sig.args stack [] in First are n_arg > 3 let (new_stack, arg_insts) = if (arg_offset > -16l) then (new_stack, []) else mark_high_args 0 f_sig.args new_stack [] in let (new_stack, fp_insts) = add_local_var "FP" new_stack in Save saved registers : $ ra , and $ s0-$s7 ( $ 16-$23 ) let (new_stack, ra_insts) = add_local_var "RA" new_stack in let ra_insts = ra_insts @ [ Sw(ra, fp, (find_local_var "RA" new_stack)); ] in let rec save_sregs (num : int) (t_stack : virtualStack) (t_insts : inst list) = if num < 0 then (t_stack, t_insts) else let name = "S"^(string_of_int num) in let (new_stack, s_insts) = add_local_var name t_stack in let new_insts = s_insts @ [ Sw((string2reg name), fp, (find_local_var name new_stack)); ] in save_sregs (num - 1) new_stack (t_insts @ new_insts) in let (new_stack, s_insts) = save_sregs 7 new_stack [] in let new_insts = (insts @ arg_insts @ narg_insts @ fp_insts @ ra_insts @ s_insts) in (new_stack, new_insts) let generate_epilogue (stack : virtualStack) : virtualStack * inst list = Restore saved registers : $ fp , $ ra , and $ s0-$s7 ( $ 16-$23 ) let rec load_sregs (num : int) (t_insts : inst list) = if num < 0 then t_insts else let name = "S"^(string_of_int num) in load_sregs (num - 1) t_insts @ [ Lw((string2reg name), fp, (find_local_var name stack)); ] in let s_insts = load_sregs 7 [] in let ra_fp_insts = [ Lw(ra, fp, (find_local_var "RA" stack)); Lw(fp, fp, (find_local_var "FP" stack)); ] in let jr_insts = [ Jr(R31); ] in let new_insts = s_insts @ ra_fp_insts @ jr_insts in Reset the SP to our FP ( frame pop ) (stack, new_insts) Factors out common code for compiling two nested expressions and * carrying out some instruction . The result of e1 is stored in R3 , * the result of e2 in R2 . in is the instruction to carry out on these * results * carrying out some instruction. The result of e1 is stored in R3, * the result of e2 in R2. in is the instruction to carry out on these * results *) let store_var (stack: virtualStack) (v: string) (dest: Mips.reg) : inst = Sw(dest, fp, (find_local_var v stack)) let load_var (stack: virtualStack) (v: string) (dest: Mips.reg) : inst = Lw(dest, fp, (find_local_var v stack)) let rec compile_exp_r (is: RInstList.rlist) ((e,_): Ast.exp) (stack : virtualStack) : virtualStack * RInstList.rlist = HELPER : Compiles e1 and e2 . Result of e1 goes in R2 , e2 in R3 let dual_op (e1: Ast.exp) (e2: Ast.exp) (instructions: inst list) : virtualStack * RInstList.rlist = let (t, stack1, insts1) = new_temp stack in Compile e2 first so result goes in R3 , getting resulting instructions and stack let (stack2, insts2) = compile_exp_r (is <@ insts1) e2 stack1 in let (stack3, insts3) = compile_exp_r (insts2 <@ [(store_var stack2 t R2)]) e1 stack2 in let insts4 = insts3 <@ [(load_var stack3 t R3)] <@ instructions in let (stack4, pop_inst) = pop_local_var t stack3 in (stack3, insts4 <@ pop_inst) in match e with | Int i -> (stack, is <@ [Li(R2, Word32.fromInt i)]) | Binop(e1,op,e2) -> let oper = (match op with | Plus -> Mips.Add(R2, R2, Reg(R3)) | Minus -> Mips.Sub(R2, R2, R3) | Times -> Mips.Mul(R2, R2, R3) | Div -> Mips.Div(R2, R2, R3) | Eq -> Mips.Seq(R2, R2, R3) | Neq -> Mips.Sne(R2, R2, R3) | Lt -> Mips.Slt(R2, R2, Reg(R3)) | Lte -> Mips.Sle(R2, R2, R3) | Gt -> Mips.Sgt(R2, R2, R3) | Gte -> Mips.Sge(R2, R2, R3)) in dual_op e1 e2 [oper] If R2 = 0 , then set R2 = 1 , else R2 = 0 | Not(e) -> let (stack1, insts1) = compile_exp_r is e stack in (stack1, insts1 <@ [Mips.Seq(R2, R2, R0)]) | And(e1, e2) -> dual_op e1 e2 [ If R2 = 0 , then R2 = 0 , else R2 = 1 Mips.Sne(R2, R2, R0); If R3 = 0 , then R3 = 0 , else R3 = 1 Mips.Sne(R3, R3, R0); If R2 = R3 = 1 , then R2 = 1 , else R2 = 0 Mips.And(R2, R2, Reg R3) ] | Or(e1, e2) -> dual_op e1 e2 [ If R2 = 0 , then R2 = 0 , else R2 = 1 Mips.Sne(R2, R2, R0); If R3 = 0 , then R3 = 0 , else R3 = 1 Mips.Sne(R3, R3, R0); If R2 or R3 = 1 , then R2 = 1 , else R2 = 0 Mips.Or(R2, R2, Reg R3) ] | Assign(v, e) -> let (stack1, insts1) = compile_exp_r is e stack in (stack1, insts1 <@ [(store_var stack1 v R2)]) | Call(f, exp_list) -> compile_call (sanitize_f_name f) exp_list stack is and compile_call f exp_list (stack : virtualStack) (prev_insts: RInstList.rlist) : virtualStack * RInstList.rlist = let arg_offset = Int32.of_int ((List.length exp_list) * -4) in let rec compile_call_r argno exps t_stack t_insts = match exps with | t_exp::rest -> let sandbox_stack = { contents = t_stack.contents; last_offset = (Int32.add t_stack.last_offset arg_offset); } in let (sandbox_stack, new_insts) = compile_exp_r t_insts t_exp sandbox_stack in Exit Sandbox Move result into aX OR If n_arg > 3 then push arg into next frame ( past sp ) let mv_insts = (if argno < 4 then [ Add((string2reg ("A"^(string_of_int argno))), R2, Reg(R0)); ] else [] ) @ [ Sw(R2, sp, (Int32.mul (-4l) (Int32.of_int argno))); ] in compile_call_r (argno + 1) rest t_stack ( new_insts <@ mv_insts ) in compile_call_r 0 exp_list stack prev_insts let rec compile_stmt_r (is: RInstList.rlist) ((s,pos): Ast.stmt) (stack : virtualStack) : virtualStack * RInstList.rlist = match s with Using directly eliminates redundant reversing the list | Exp e -> compile_exp_r is e stack | Let(t_var, t_exp, t_stmt) -> let (stack1, insts1) = add_local_var t_var stack in let (stack2, insts2) = compile_exp_r (is <@ insts1) t_exp stack1 in let sw_insts = [(store_var stack2 t_var R2)] in let (stack3, insts3) = compile_stmt_r (insts2 <@ sw_insts) t_stmt stack2 in let (stack4, pop_insts) = pop_local_var t_var stack3 in (stack4, insts3 <@ pop_insts) | Seq (s1, s2) -> let(stack1, insts1) = compile_stmt_r is s1 stack in compile_stmt_r insts1 s2 stack1 | If(e, then_s, else_s) -> let else_l = new_label () in let end_l = new_label () in let (stack1, insts1) = compile_exp_r is e stack in Branch is e1 evaluates to false let branch_inst = [Beq(R2,R0,else_l)] in let (stack2, insts2) = compile_stmt_r (insts1 <@ branch_inst) then_s stack1 in let else_inst = [J(end_l); Label(else_l)] in let (stack3, insts3) = compile_stmt_r (insts2 <@ else_inst) else_s stack2 in (stack3, insts3 <@ [Label(end_l)]) | While(e, s) -> let test_l = new_label () in let top_l = new_label () in let head_inst = [J(test_l); Label(top_l)] in let (stack1, insts1) = compile_stmt_r (is <@ head_inst) s stack in let test_inst = [Label(test_l)] in let (stack2, insts2) = compile_exp_r (insts1 <@ test_inst) e stack1 in (stack2, insts2 <@ [Bne(R2,R0,top_l)]) | For(e1, e2, e3, s) -> let get_pos s = let (_,p) = s in p in Nastiness due to necesity of having position compile_stmt_r is ((Ast.Seq( (Ast.Exp e1, (get_pos e1)), (While( e2, (Ast.Seq(s, (Ast.Exp e3, (get_pos e3))), get_pos s)), pos))), pos) stack | Return (e) -> compile_exp_r is e stack compiles a Fish statement down to a list of MIPS instructions . * Note that a " Return " is accomplished by placing the resulting * value in R2 and then doing . * Note that a "Return" is accomplished by placing the resulting * value in R2 and then doing a Jr R31. *) let compile_stmt (s : Ast.stmt) (stack : virtualStack) : virtualStack * inst list = let(stack1, insts1) = compile_stmt_r RInstList.empty s stack in (stack1, RInstList.to_list insts1) let compile_function (f : func) : inst list = let Fn(signature) = f in let local_stack = { last_offset = 0l; contents = StringMap.empty } in let f_label = Label((sanitize_f_name signature.name)) in let (new_stack, prologue_code) = generate_prologue signature local_stack in let (new_stack, body_code) = compile_stmt signature.body new_stack in let (new_stack, epilogue_code) = generate_epilogue new_stack in Concate code blocks together ([ f_label; ] @ prologue_code @ body_code @ epilogue_code) let rec compile (p:Ast.program) : result = let rec compile_prog (prog : Ast.program) (compiled : result) = match prog with | [] -> compiled | f::rest -> let new_insts = compile_function f in compile_prog rest { code = compiled.code @ new_insts; data = compiled.data } in compile_prog p { code = []; data = [] } let result2string (res:result) : string = let code = res.code in let data = res.data in let strs = List.map (fun x -> (Mips.inst2string x) ^ "\n") code in let vaR8decl x = x ^ ":\t.word 0\n" in let readfile f = let stream = open_in f in let size = in_channel_length stream in let text = String.create size in let _ = really_input stream text 0 size in let _ = close_in stream in text in let debugcode = readfile "print.asm" in "\t.text\n" ^ "\t.align\t2\n" ^ "\t.globl main\n" ^ (String.concat "" strs) ^ "\n\n" ^ "\t.data\n" ^ "\t.align 0\n"^ (String.concat "" (List.map vaR8decl data)) ^ "\n" ^ debugcode
6539b16ee3d5ec95b400b69b55fe9ec961b97fc6a5052c666ca41f6ded5a3aca
chetmurthy/pa_ppx
pa_undo_deriving.ml
(* camlp5r *) (* pa_undo_deriving.ml,v *) Copyright ( c ) INRIA 2007 - 2017 #load "pa_extend.cmo"; #load "q_MLast.cmo"; #load "pa_macro.cmo"; #load "pa_macro_gram.cmo"; #load "pa_extfun.cmo"; open Asttools; open MLast; open Pa_ppx_utils ; open Pa_ppx_base ; open Pa_passthru ; open Ppxutil ; value flatten_declare_str_item l = l |> List.map (fun [ StDcl _ l -> uv l | x -> [x] ]) |> List.concat ; value flatten_declare_sig_item l = l |> List.map (fun [ SgDcl _ l -> uv l | x -> [x] ]) |> List.concat ; value is_deriving_inline_attribute (attr : attribute) = attr_id attr = "deriving_inline" ; value undo_deriving_inline tdl = let (last, tdl) = sep_last tdl in let (deriving_attr, other_attrs) = match filter_split is_deriving_inline_attribute (uv last.tdAttributes) with [ (([] | [_ ; _ :: _]), _) -> failwith "should only be one @@deriving_inline attribute" | ([a], others) -> (a, others) ] in let (loc_attrid, payload) = uv deriving_attr in let idloc = fst (uv loc_attrid) in let newattr = (<:vala< (idloc, "deriving") >>, payload) in let attrs = other_attrs @ [ <:vala< newattr >> ] in let last = { (last) with tdAttributes = <:vala< attrs >> } in tdl @ [ last ] ; value refold_deriving_inline_structure arg l = let rec rerec acc = fun [ [] -> List.rev acc | [ (<:str_item:< type $flag:nrfl$ $list:tdl$ >>) :: t ] when 1 = count is_deriving_inline_attribute (uv (fst (sep_last tdl)).tdAttributes) -> let tdl = undo_deriving_inline tdl in consrec [ <:str_item:< type $flag:nrfl$ $list:tdl$ >> :: acc ] t | [ h :: t ] -> rerec [h :: acc] t ] and consrec acc = fun [ [] -> failwith "refold_deriving_inline: unmatched @@deriving_inline and @@@end" | [ <:str_item< [@@@"end"] >> :: t ] -> rerec acc t | [ _ :: t ] -> consrec acc t ] in rerec [] l ; value refold_deriving_inline_signature arg l = let rec rerec acc = fun [ [] -> List.rev acc | [ (<:sig_item:< type $flag:nrfl$ $list:tdl$ >>) :: t ] when 1 = count is_deriving_inline_attribute (uv (fst (sep_last tdl)).tdAttributes) -> let tdl = undo_deriving_inline tdl in consrec [ <:sig_item:< type $flag:nrfl$ $list:tdl$ >> :: acc ] t | [ h :: t ] -> rerec [h :: acc] t ] and consrec acc = fun [ [] -> failwith "refold_deriving_inline: unmatched @@deriving_inline and @@@end" | [ <:sig_item< [@@@"end"] >> :: t ] -> rerec acc t | [ _ :: t ] -> consrec acc t ] in rerec [] l ; value rec structure_has_end_attribute l = List.exists (fun [ <:str_item< [@@@"end"] >> -> True | <:str_item< declare $list:l$ end >> -> structure_has_end_attribute l | _ -> False ]) l ; value rec signature_has_end_attribute l = List.exists (fun [ <:sig_item< [@@@"end"] >> -> True | <:sig_item< declare $list:l$ end >> -> signature_has_end_attribute l | _ -> False ]) l ; value implem_has_end_attribute (l,_) = List.exists (fun [ (<:str_item< [@@@"end"] >>,_) -> True | (<:str_item< declare $list:l$ end >>, _) -> structure_has_end_attribute l | _ -> False ]) l ; value interf_has_end_attribute (l,_) = List.exists (fun [ (<:sig_item< [@@@"end"] >>,_) -> True | (<:sig_item< declare $list:l$ end >>, _) -> signature_has_end_attribute l | _ -> False ]) l ; value registered_implem arg z = if not (implem_has_end_attribute z) then z else let (l, st) = z in let l = refold_deriving_inline_structure arg (List.map fst l) in (List.map (fun si -> (si, loc_of_str_item si)) l, st) ; value registered_interf arg z = if not (interf_has_end_attribute z) then z else let (l, st) = z in let l = refold_deriving_inline_signature arg (List.map fst l) in (List.map (fun si -> (si, loc_of_sig_item si)) l, st) ; value registered_structure arg z = if not (structure_has_end_attribute z) then z else refold_deriving_inline_structure arg z ; value registered_signature arg z = if not (signature_has_end_attribute z) then z else refold_deriving_inline_signature arg z ; value install () = let ef = EF.mk() in let ef = EF.{ (ef) with implem = extfun ef.implem with [ z -> fun arg fallback -> Some (registered_implem arg z) ] } in let ef = EF.{ (ef) with interf = extfun ef.interf with [ z -> fun arg fallback -> Some (registered_interf arg z) ] } in let ef = EF.{ (ef) with signature = extfun ef.signature with [ z -> fun arg fallback -> Some (registered_signature arg z) ] } in let ef = EF.{ (ef) with structure = extfun ef.structure with [ z -> fun arg fallback -> Some (registered_structure arg z) ] } in Pa_passthru.(install { name = "pa_undo_deriving" ; ef = ef ; pass = None ; before = [] ; after = [] }) ; install();
null
https://raw.githubusercontent.com/chetmurthy/pa_ppx/7c662fcf4897c978ae8a5ea230af0e8b2fa5858b/pa_undo_deriving/pa_undo_deriving.ml
ocaml
camlp5r pa_undo_deriving.ml,v
Copyright ( c ) INRIA 2007 - 2017 #load "pa_extend.cmo"; #load "q_MLast.cmo"; #load "pa_macro.cmo"; #load "pa_macro_gram.cmo"; #load "pa_extfun.cmo"; open Asttools; open MLast; open Pa_ppx_utils ; open Pa_ppx_base ; open Pa_passthru ; open Ppxutil ; value flatten_declare_str_item l = l |> List.map (fun [ StDcl _ l -> uv l | x -> [x] ]) |> List.concat ; value flatten_declare_sig_item l = l |> List.map (fun [ SgDcl _ l -> uv l | x -> [x] ]) |> List.concat ; value is_deriving_inline_attribute (attr : attribute) = attr_id attr = "deriving_inline" ; value undo_deriving_inline tdl = let (last, tdl) = sep_last tdl in let (deriving_attr, other_attrs) = match filter_split is_deriving_inline_attribute (uv last.tdAttributes) with [ (([] | [_ ; _ :: _]), _) -> failwith "should only be one @@deriving_inline attribute" | ([a], others) -> (a, others) ] in let (loc_attrid, payload) = uv deriving_attr in let idloc = fst (uv loc_attrid) in let newattr = (<:vala< (idloc, "deriving") >>, payload) in let attrs = other_attrs @ [ <:vala< newattr >> ] in let last = { (last) with tdAttributes = <:vala< attrs >> } in tdl @ [ last ] ; value refold_deriving_inline_structure arg l = let rec rerec acc = fun [ [] -> List.rev acc | [ (<:str_item:< type $flag:nrfl$ $list:tdl$ >>) :: t ] when 1 = count is_deriving_inline_attribute (uv (fst (sep_last tdl)).tdAttributes) -> let tdl = undo_deriving_inline tdl in consrec [ <:str_item:< type $flag:nrfl$ $list:tdl$ >> :: acc ] t | [ h :: t ] -> rerec [h :: acc] t ] and consrec acc = fun [ [] -> failwith "refold_deriving_inline: unmatched @@deriving_inline and @@@end" | [ <:str_item< [@@@"end"] >> :: t ] -> rerec acc t | [ _ :: t ] -> consrec acc t ] in rerec [] l ; value refold_deriving_inline_signature arg l = let rec rerec acc = fun [ [] -> List.rev acc | [ (<:sig_item:< type $flag:nrfl$ $list:tdl$ >>) :: t ] when 1 = count is_deriving_inline_attribute (uv (fst (sep_last tdl)).tdAttributes) -> let tdl = undo_deriving_inline tdl in consrec [ <:sig_item:< type $flag:nrfl$ $list:tdl$ >> :: acc ] t | [ h :: t ] -> rerec [h :: acc] t ] and consrec acc = fun [ [] -> failwith "refold_deriving_inline: unmatched @@deriving_inline and @@@end" | [ <:sig_item< [@@@"end"] >> :: t ] -> rerec acc t | [ _ :: t ] -> consrec acc t ] in rerec [] l ; value rec structure_has_end_attribute l = List.exists (fun [ <:str_item< [@@@"end"] >> -> True | <:str_item< declare $list:l$ end >> -> structure_has_end_attribute l | _ -> False ]) l ; value rec signature_has_end_attribute l = List.exists (fun [ <:sig_item< [@@@"end"] >> -> True | <:sig_item< declare $list:l$ end >> -> signature_has_end_attribute l | _ -> False ]) l ; value implem_has_end_attribute (l,_) = List.exists (fun [ (<:str_item< [@@@"end"] >>,_) -> True | (<:str_item< declare $list:l$ end >>, _) -> structure_has_end_attribute l | _ -> False ]) l ; value interf_has_end_attribute (l,_) = List.exists (fun [ (<:sig_item< [@@@"end"] >>,_) -> True | (<:sig_item< declare $list:l$ end >>, _) -> signature_has_end_attribute l | _ -> False ]) l ; value registered_implem arg z = if not (implem_has_end_attribute z) then z else let (l, st) = z in let l = refold_deriving_inline_structure arg (List.map fst l) in (List.map (fun si -> (si, loc_of_str_item si)) l, st) ; value registered_interf arg z = if not (interf_has_end_attribute z) then z else let (l, st) = z in let l = refold_deriving_inline_signature arg (List.map fst l) in (List.map (fun si -> (si, loc_of_sig_item si)) l, st) ; value registered_structure arg z = if not (structure_has_end_attribute z) then z else refold_deriving_inline_structure arg z ; value registered_signature arg z = if not (signature_has_end_attribute z) then z else refold_deriving_inline_signature arg z ; value install () = let ef = EF.mk() in let ef = EF.{ (ef) with implem = extfun ef.implem with [ z -> fun arg fallback -> Some (registered_implem arg z) ] } in let ef = EF.{ (ef) with interf = extfun ef.interf with [ z -> fun arg fallback -> Some (registered_interf arg z) ] } in let ef = EF.{ (ef) with signature = extfun ef.signature with [ z -> fun arg fallback -> Some (registered_signature arg z) ] } in let ef = EF.{ (ef) with structure = extfun ef.structure with [ z -> fun arg fallback -> Some (registered_structure arg z) ] } in Pa_passthru.(install { name = "pa_undo_deriving" ; ef = ef ; pass = None ; before = [] ; after = [] }) ; install();
7a317efce7c7865c354f835999ffc6c777502ec6e10151a59822759838e69bd6
lisp-polymorph/polymorph.data-structures
package.lisp
package.lisp (uiop:define-package #:polymorph.data-structures (:use) (:mix #:polymorphic-functions #:polymorph.maths #:introspect-ctype #:polymorph.copy-cast #:polymorph.macros #:polymorph.access #:polymorph.traversable #:common-lisp) (:reexport #:polymorph.traversable) (:import-from #:introspect-ctype #:default #:ind) (:import-from #:polymorph.traversable #:next) (:shadow #:intersection #:difference #:union #:subsetp #:supersetp) ;; TODO export stuff here (:export #:dl-list #:front #:back #:push-front #:push-back #:pop-front #:pop-back #:size #:empty-p))
null
https://raw.githubusercontent.com/lisp-polymorph/polymorph.data-structures/ef99e898f115ff6bc224d0497844dda4070df682/src/package.lisp
lisp
TODO export stuff here
package.lisp (uiop:define-package #:polymorph.data-structures (:use) (:mix #:polymorphic-functions #:polymorph.maths #:introspect-ctype #:polymorph.copy-cast #:polymorph.macros #:polymorph.access #:polymorph.traversable #:common-lisp) (:reexport #:polymorph.traversable) (:import-from #:introspect-ctype #:default #:ind) (:import-from #:polymorph.traversable #:next) (:shadow #:intersection #:difference #:union #:subsetp #:supersetp) (:export #:dl-list #:front #:back #:push-front #:push-back #:pop-front #:pop-back #:size #:empty-p))
584d036be7fc0e4fc55331b336d7a709201a921c04c725cded63bacb772184ca
binsec/binsec
binpatcher.ml
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2022 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 , version 2.1 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Binpatcher_options module PatchMap = struct type t = Loader_types.u8 Virtual_address.Map.t let add_bytes vbase bytes vmap = let len = Binstream.length bytes in let rec aux map i = if i < len then let byte = Binstream.get_byte_exn bytes i in let map' = Virtual_address.Map.add (Virtual_address.add_int i vbase) byte map in aux map' (succ i) else map in aux vmap 0 let of_list l = List.fold_left (fun vmap (vaddr, opcode) -> add_bytes vaddr opcode vmap) Virtual_address.Map.empty l let load_file filename = let map = let parser = Parser.patchmap and lexer = Lexer.token in Parse_utils.read_file ~parser ~lexer ~filename in let open! Virtual_address in Map.fold add_bytes map Map.empty let empty = Virtual_address.Map.empty end module WritableLoader = struct open Loader_types type t = { img : Loader.Img.t; patches : int Basic_types.Int.Map.t } let create img patches = { img; patches } let get_offset img address = match Loader_utils.find_section_by_address img ~address with | Some section -> let p = Loader.Section.pos section in let offset = address - p.virt in Some (p.raw + offset) | None -> Logger.debug "Concrete offset not found for address %x" address; None let offset img vmap = Virtual_address.Map.fold (fun vaddr byte cmap -> match get_offset img (vaddr :> int) with | Some caddr -> Basic_types.Int.Map.add caddr byte cmap | None -> cmap) vmap Basic_types.Int.Map.empty let create img patchmap = create img (patchmap |> offset img) let create_from_files ~executable ~patch_file () = let img = Loader.load_file executable in let patches = PatchMap.load_file patch_file in create img patches let get_int i t = match Basic_types.Int.Map.find i t.patches with | c -> Logger.debug "Patching address %x with byte %x" i c; c | exception Not_found -> Loader.read_offset t.img i let dim t = Loader.Offset.dim t.img let pp_to_file ~filename t = Logger.debug "Writing patched binary to file %s" filename; let oc = open_out_bin filename in for i = 0 to dim t - 1 do let v = get_int i t in let c = Char.chr v in Printf.fprintf oc "%c" c done; close_out oc let get i t = get_int i t end let run ~executable = let patch_file = Binpatcher_options.PatchFile.get () in let wloader = WritableLoader.create_from_files ~executable ~patch_file () in let dst = Binpatcher_options.PatchOutFile.get () in WritableLoader.pp_to_file ~filename:dst wloader let run_default () = if Kernel_options.ExecFile.is_set () && Binpatcher_options.PatchFile.is_set () then run ~executable:(Kernel_options.ExecFile.get ()) let _ = Cli.Boot.enlist ~name:"binpatcher" ~f:run_default
null
https://raw.githubusercontent.com/binsec/binsec/8ed9991d36451a3ae7487b966c4b38acca21a5b3/src/binpatcher/binpatcher.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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 file is part of BINSEC . Copyright ( C ) 2016 - 2022 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Binpatcher_options module PatchMap = struct type t = Loader_types.u8 Virtual_address.Map.t let add_bytes vbase bytes vmap = let len = Binstream.length bytes in let rec aux map i = if i < len then let byte = Binstream.get_byte_exn bytes i in let map' = Virtual_address.Map.add (Virtual_address.add_int i vbase) byte map in aux map' (succ i) else map in aux vmap 0 let of_list l = List.fold_left (fun vmap (vaddr, opcode) -> add_bytes vaddr opcode vmap) Virtual_address.Map.empty l let load_file filename = let map = let parser = Parser.patchmap and lexer = Lexer.token in Parse_utils.read_file ~parser ~lexer ~filename in let open! Virtual_address in Map.fold add_bytes map Map.empty let empty = Virtual_address.Map.empty end module WritableLoader = struct open Loader_types type t = { img : Loader.Img.t; patches : int Basic_types.Int.Map.t } let create img patches = { img; patches } let get_offset img address = match Loader_utils.find_section_by_address img ~address with | Some section -> let p = Loader.Section.pos section in let offset = address - p.virt in Some (p.raw + offset) | None -> Logger.debug "Concrete offset not found for address %x" address; None let offset img vmap = Virtual_address.Map.fold (fun vaddr byte cmap -> match get_offset img (vaddr :> int) with | Some caddr -> Basic_types.Int.Map.add caddr byte cmap | None -> cmap) vmap Basic_types.Int.Map.empty let create img patchmap = create img (patchmap |> offset img) let create_from_files ~executable ~patch_file () = let img = Loader.load_file executable in let patches = PatchMap.load_file patch_file in create img patches let get_int i t = match Basic_types.Int.Map.find i t.patches with | c -> Logger.debug "Patching address %x with byte %x" i c; c | exception Not_found -> Loader.read_offset t.img i let dim t = Loader.Offset.dim t.img let pp_to_file ~filename t = Logger.debug "Writing patched binary to file %s" filename; let oc = open_out_bin filename in for i = 0 to dim t - 1 do let v = get_int i t in let c = Char.chr v in Printf.fprintf oc "%c" c done; close_out oc let get i t = get_int i t end let run ~executable = let patch_file = Binpatcher_options.PatchFile.get () in let wloader = WritableLoader.create_from_files ~executable ~patch_file () in let dst = Binpatcher_options.PatchOutFile.get () in WritableLoader.pp_to_file ~filename:dst wloader let run_default () = if Kernel_options.ExecFile.is_set () && Binpatcher_options.PatchFile.is_set () then run ~executable:(Kernel_options.ExecFile.get ()) let _ = Cli.Boot.enlist ~name:"binpatcher" ~f:run_default
fdeac9a787e85cc0b240b29fb57961495d1ed1611aae22f9b2e21a725ececf6e
blockapps/eth-pruner
Restore.hs
module Restore where import Control.Monad.IO.Class (liftIO) import Data.Default import qualified Database.LevelDB as DB import Database restore :: (DB.MonadResource m) => String -> String -> m () restore originDir toDir = do inDB <- DB.open originDir def outDB <- DB.open toDir def iter <- DB.iterOpen inDB def liftIO $ ldbForEach iter (f outDB) return () where f outDB k v = do mVal <- getValByKey outDB k case mVal of Nothing -> insertToLvlDB outDB k v Just _ -> return ()
null
https://raw.githubusercontent.com/blockapps/eth-pruner/513fcc884c93974a29b380ca80669dc0aebec125/src/Restore.hs
haskell
module Restore where import Control.Monad.IO.Class (liftIO) import Data.Default import qualified Database.LevelDB as DB import Database restore :: (DB.MonadResource m) => String -> String -> m () restore originDir toDir = do inDB <- DB.open originDir def outDB <- DB.open toDir def iter <- DB.iterOpen inDB def liftIO $ ldbForEach iter (f outDB) return () where f outDB k v = do mVal <- getValByKey outDB k case mVal of Nothing -> insertToLvlDB outDB k v Just _ -> return ()
95bccc89f141691b41ec7d42b773d95a7120c89d85d42ee5291e92edd01982ba
Lovesan/bike
invocation-cache.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- Copyright ( C ) 2019 , < lovesan.ru at gmail.com > ;;; 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. (in-package #:bike) Implement our own version of DLR (deftype member-kind () '(member :method :property :field :indexer :constructor)) (defstruct (invocation-entry (:constructor make-ientry) (:copier nil) (:predicate invocation-entry-p) (:conc-name ientry-)) (type (required-slot) :type dotnet-type :read-only t) (name (required-slot) :type dotnet-name :read-only t) (kind (required-slot) :type member-kind :read-only t) (type-arg-count 0 :type non-negative-fixnum :read-only t) (type-args '() :type list :read-only t) (arg-type-count 0 :type non-negative-fixnum :read-only t) (arg-types '() :type list :read-only t) (reader nil :type (or null function) :read-only t) (reader-delegate nil :type (or null dotnet-object) :read-only t) (writer nil :type (or null function) :read-only t) (writer-delegate nil :type (or null dotnet-object) :read-only t) (next nil :type (or null invocation-entry))) (defmacro with-ientry ((&rest slots) entry-form &body body) (with-gensyms (entry) (let ((accessors (%collect-accessors 'ientry- slots))) `(let ((,entry ,entry-form)) (declare (type invocation-entry ,entry)) (with-accessors ,accessors ,entry ,@body))))) (defconstant +min-invocation-cache-buckets+ 64) (defconstant +max-invocation-cache-count+ (min most-positive-fixnum 10000)) (defconstant +invocation-cache-rehash-threshold+ 1.5) (defstruct (invocation-cache (:constructor make-icache) (:copier nil) (:predicate invocation-cache-p) (:conc-name icache-)) (buckets (make-array +min-invocation-cache-buckets+ :initial-element nil) :type simple-vector) (count 0 :type non-negative-fixnum) (lock (make-rwlock) :type rwlock :read-only t)) (#+sbcl sb-ext:defglobal #-sbcl defvar +invocation-cache+ nil) (declaim (type (or null invocation-cache) +invocation-cache+)) (defmacro with-icache ((&rest slots) &body body) (with-gensyms (cache) (let ((accessors (%collect-accessors 'icache- slots))) `(let ((,cache +invocation-cache+)) (declare (type invocation-cache ,cache)) (with-accessors ,accessors ,cache ,@body))))) (defun ientry-hash-code* (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '())) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types)) (let ((code (logxor (%get-hash-code type) (sxhash name) (sxhash kind) (sxhash type-arg-count) (sxhash arg-type-count)))) (declare (type (signed-byte #.+pointer-bits+) code)) (dolist (type-arg type-args) (setf code (logxor code (%get-hash-code type-arg)))) (dolist (arg-type arg-types code) (setf code (logxor code (%get-hash-code arg-type)))))) (defun ientry-hash-code (entry) (declare (type invocation-entry entry)) (with-ientry (type name kind type-arg-count type-args arg-type-count arg-types) entry (ientry-hash-code* type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types))) (defun ientry-equals* (entry type* name* kind* &key ((:type-arg-count type-arg-count*) 0) ((:type-args type-args*) '()) ((:arg-type-count arg-type-count*) 0) ((:arg-types arg-types*) '())) (declare (type invocation-entry entry) (type dotnet-type type*) (type dotnet-name name*) (type member-kind kind*) (type non-negative-fixnum arg-type-count* type-arg-count*) (type list arg-types* type-args*)) (with-ientry (type name kind type-arg-count type-args arg-type-count arg-types) entry (flet ((types-equal (left right) (declare (type list left right)) (loop :for a :of-type dotnet-type :in left :and b :of-type dotnet-type :in right :when (not (bike-equals a b)) :do (return nil) :finally (return t)))) (and (bike-equals type type*) (string= name name*) (eq kind kind*) (= type-arg-count type-arg-count*) (= arg-type-count arg-type-count*) (types-equal type-args type-args*) (types-equal arg-types arg-types*))))) (defun ientry-equals (left right) (declare (type invocation-entry left right)) (with-ientry (type name kind type-arg-count type-args arg-type-count arg-types) right (ientry-equals* left type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types))) (defun %get-ientry (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '())) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types)) (with-icache (buckets) (let* ((vector buckets) (hash-code (ientry-hash-code* type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types)) (nbucket (mod hash-code (length vector)))) (loop :for entry = (svref vector nbucket) :then (ientry-next entry) :while entry :do (when (ientry-equals* entry type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types) (return entry)))))) (defun get-ientry (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '())) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types)) "Retrieves invocation entry from invocation cache" (with-icache (lock) (with-read-lock (lock) (%get-ientry type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types)))) (defun %clear-invocation-cache () (with-icache (buckets count lock) (let ((vector buckets)) (setf count 0) (dotimes (i (length vector)) (setf (svref vector i) nil)))) (values)) (defun clear-invocation-cache () "Clears an invocation cache" (with-icache (lock) (with-write-lock (lock) (%clear-invocation-cache)))) (defun %resize-icache () (with-icache (buckets count) (if (= count +max-invocation-cache-count+) ;; simply clear the cache ;; TODO: do something more smart (%clear-invocation-cache) (let* ((vector buckets) (size (length vector)) (new-size (min most-positive-fixnum (1+ (* size 2))))) (when (> new-size size) (let ((new-vector (make-array new-size :initial-element nil))) (dotimes (i size) (let ((bucket-entries (loop :for entry = (svref vector i) :then (ientry-next entry) :while entry :collect entry))) (dolist (entry bucket-entries) (let* ((hash-code (ientry-hash-code entry)) (nbucket (mod hash-code new-size)) (prev (svref new-vector nbucket))) (setf (svref new-vector nbucket) entry (ientry-next entry) prev))))) (setf buckets new-vector)))))) (values)) (defun add-ientry (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '()) (reader nil) (reader-delegate nil) (writer nil) (writer-delegate nil)) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types) (type (or null function) reader writer) (type (or null dotnet-object) reader-delegate writer-delegate)) "Gets or adds an invocation entry to invocation cache" (with-icache (buckets count lock) (with-write-lock (lock) (or (%get-ientry type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types) (let ((vector buckets)) (when (> (/ count (length vector)) +invocation-cache-rehash-threshold+) (%resize-icache) (setf vector buckets)) (let* ((hash-code (ientry-hash-code* type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types)) (nbucket (mod hash-code (length vector))) (prev (svref vector nbucket)) (entry (make-ientry :type type :name name :kind kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types :reader reader :reader-delegate reader-delegate :writer writer :writer-delegate writer-delegate :next prev))) (setf (svref vector nbucket) entry) (incf count) entry)))))) (defun initialize-invocation-cache () (setf +invocation-cache+ (make-icache)) (values)) (uiop:register-image-restore-hook #'initialize-invocation-cache (null +invocation-cache+)) ;;; vim: ft=lisp et
null
https://raw.githubusercontent.com/Lovesan/bike/3f43b6c503f6fb3d40d02c75b99e8525253a6bb5/src/invocation-cache.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be 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. simply clear the cache TODO: do something more smart vim: ft=lisp et
Copyright ( C ) 2019 , < lovesan.ru at gmail.com > files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package #:bike) Implement our own version of DLR (deftype member-kind () '(member :method :property :field :indexer :constructor)) (defstruct (invocation-entry (:constructor make-ientry) (:copier nil) (:predicate invocation-entry-p) (:conc-name ientry-)) (type (required-slot) :type dotnet-type :read-only t) (name (required-slot) :type dotnet-name :read-only t) (kind (required-slot) :type member-kind :read-only t) (type-arg-count 0 :type non-negative-fixnum :read-only t) (type-args '() :type list :read-only t) (arg-type-count 0 :type non-negative-fixnum :read-only t) (arg-types '() :type list :read-only t) (reader nil :type (or null function) :read-only t) (reader-delegate nil :type (or null dotnet-object) :read-only t) (writer nil :type (or null function) :read-only t) (writer-delegate nil :type (or null dotnet-object) :read-only t) (next nil :type (or null invocation-entry))) (defmacro with-ientry ((&rest slots) entry-form &body body) (with-gensyms (entry) (let ((accessors (%collect-accessors 'ientry- slots))) `(let ((,entry ,entry-form)) (declare (type invocation-entry ,entry)) (with-accessors ,accessors ,entry ,@body))))) (defconstant +min-invocation-cache-buckets+ 64) (defconstant +max-invocation-cache-count+ (min most-positive-fixnum 10000)) (defconstant +invocation-cache-rehash-threshold+ 1.5) (defstruct (invocation-cache (:constructor make-icache) (:copier nil) (:predicate invocation-cache-p) (:conc-name icache-)) (buckets (make-array +min-invocation-cache-buckets+ :initial-element nil) :type simple-vector) (count 0 :type non-negative-fixnum) (lock (make-rwlock) :type rwlock :read-only t)) (#+sbcl sb-ext:defglobal #-sbcl defvar +invocation-cache+ nil) (declaim (type (or null invocation-cache) +invocation-cache+)) (defmacro with-icache ((&rest slots) &body body) (with-gensyms (cache) (let ((accessors (%collect-accessors 'icache- slots))) `(let ((,cache +invocation-cache+)) (declare (type invocation-cache ,cache)) (with-accessors ,accessors ,cache ,@body))))) (defun ientry-hash-code* (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '())) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types)) (let ((code (logxor (%get-hash-code type) (sxhash name) (sxhash kind) (sxhash type-arg-count) (sxhash arg-type-count)))) (declare (type (signed-byte #.+pointer-bits+) code)) (dolist (type-arg type-args) (setf code (logxor code (%get-hash-code type-arg)))) (dolist (arg-type arg-types code) (setf code (logxor code (%get-hash-code arg-type)))))) (defun ientry-hash-code (entry) (declare (type invocation-entry entry)) (with-ientry (type name kind type-arg-count type-args arg-type-count arg-types) entry (ientry-hash-code* type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types))) (defun ientry-equals* (entry type* name* kind* &key ((:type-arg-count type-arg-count*) 0) ((:type-args type-args*) '()) ((:arg-type-count arg-type-count*) 0) ((:arg-types arg-types*) '())) (declare (type invocation-entry entry) (type dotnet-type type*) (type dotnet-name name*) (type member-kind kind*) (type non-negative-fixnum arg-type-count* type-arg-count*) (type list arg-types* type-args*)) (with-ientry (type name kind type-arg-count type-args arg-type-count arg-types) entry (flet ((types-equal (left right) (declare (type list left right)) (loop :for a :of-type dotnet-type :in left :and b :of-type dotnet-type :in right :when (not (bike-equals a b)) :do (return nil) :finally (return t)))) (and (bike-equals type type*) (string= name name*) (eq kind kind*) (= type-arg-count type-arg-count*) (= arg-type-count arg-type-count*) (types-equal type-args type-args*) (types-equal arg-types arg-types*))))) (defun ientry-equals (left right) (declare (type invocation-entry left right)) (with-ientry (type name kind type-arg-count type-args arg-type-count arg-types) right (ientry-equals* left type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types))) (defun %get-ientry (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '())) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types)) (with-icache (buckets) (let* ((vector buckets) (hash-code (ientry-hash-code* type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types)) (nbucket (mod hash-code (length vector)))) (loop :for entry = (svref vector nbucket) :then (ientry-next entry) :while entry :do (when (ientry-equals* entry type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types) (return entry)))))) (defun get-ientry (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '())) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types)) "Retrieves invocation entry from invocation cache" (with-icache (lock) (with-read-lock (lock) (%get-ientry type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types)))) (defun %clear-invocation-cache () (with-icache (buckets count lock) (let ((vector buckets)) (setf count 0) (dotimes (i (length vector)) (setf (svref vector i) nil)))) (values)) (defun clear-invocation-cache () "Clears an invocation cache" (with-icache (lock) (with-write-lock (lock) (%clear-invocation-cache)))) (defun %resize-icache () (with-icache (buckets count) (if (= count +max-invocation-cache-count+) (%clear-invocation-cache) (let* ((vector buckets) (size (length vector)) (new-size (min most-positive-fixnum (1+ (* size 2))))) (when (> new-size size) (let ((new-vector (make-array new-size :initial-element nil))) (dotimes (i size) (let ((bucket-entries (loop :for entry = (svref vector i) :then (ientry-next entry) :while entry :collect entry))) (dolist (entry bucket-entries) (let* ((hash-code (ientry-hash-code entry)) (nbucket (mod hash-code new-size)) (prev (svref new-vector nbucket))) (setf (svref new-vector nbucket) entry (ientry-next entry) prev))))) (setf buckets new-vector)))))) (values)) (defun add-ientry (type name kind &key (type-arg-count 0) (type-args '()) (arg-type-count 0) (arg-types '()) (reader nil) (reader-delegate nil) (writer nil) (writer-delegate nil)) (declare (type dotnet-type type) (type dotnet-name name) (type member-kind kind) (type non-negative-fixnum type-arg-count arg-type-count) (type list type-args arg-types) (type (or null function) reader writer) (type (or null dotnet-object) reader-delegate writer-delegate)) "Gets or adds an invocation entry to invocation cache" (with-icache (buckets count lock) (with-write-lock (lock) (or (%get-ientry type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types) (let ((vector buckets)) (when (> (/ count (length vector)) +invocation-cache-rehash-threshold+) (%resize-icache) (setf vector buckets)) (let* ((hash-code (ientry-hash-code* type name kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types)) (nbucket (mod hash-code (length vector))) (prev (svref vector nbucket)) (entry (make-ientry :type type :name name :kind kind :type-arg-count type-arg-count :type-args type-args :arg-type-count arg-type-count :arg-types arg-types :reader reader :reader-delegate reader-delegate :writer writer :writer-delegate writer-delegate :next prev))) (setf (svref vector nbucket) entry) (incf count) entry)))))) (defun initialize-invocation-cache () (setf +invocation-cache+ (make-icache)) (values)) (uiop:register-image-restore-hook #'initialize-invocation-cache (null +invocation-cache+))
f0bb9f645445f638424540f6d0fb7e19eef5f5ee21ffa8b37ad7fa927db4ce40
erlang-lager/lager
pr_composite_test.erl
-module(pr_composite_test). -compile([{parse_transform, lager_transform}]). -record(a, {field1 :: term(), field2 :: term()}). -record(b, {field1 :: term() , field2 :: term()}). -include_lib("eunit/include/eunit.hrl"). nested_record_test() -> A = #a{field1 = x, field2 = y}, B = #b{field1 = A, field2 = {}}, Pr_B = lager:pr(B, ?MODULE), ?assertEqual({'$lager_record', b, [{field1, {'$lager_record', a, [{field1, x},{field2, y}]}}, {field2, {}}]}, Pr_B). list_field_test() -> As = [#a{field1 = 1, field2 = a2}, #a{field1 = 2, field2 = a2}], B = #b{field1 = As, field2 = b2}, Pr_B = lager:pr(B, ?MODULE), ?assertEqual({'$lager_record', b, [{field1, [{'$lager_record', a, [{field1, 1},{field2, a2}]}, {'$lager_record', a, [{field1, 2},{field2, a2}]}]}, {field2, b2}]}, Pr_B). list_of_records_test() -> As = [#a{field1 = 1, field2 = a2}, #a{field1 = 2, field2 = a2}], Pr_As = lager:pr(As, ?MODULE), ?assertEqual([{'$lager_record', a, [{field1, 1},{field2, a2}]}, {'$lager_record', a, [{field1, 2},{field2, a2}]}], Pr_As). improper_list_test() -> A = #a{field1 = [1|2], field2 = a2}, Pr_A = lager:pr(A, ?MODULE), ?assertEqual({'$lager_record',a, [{field1,[1|2]},{field2,a2}]}, Pr_A).
null
https://raw.githubusercontent.com/erlang-lager/lager/8b87339a43721a382eabe35a71f4f1e0e664c0b3/test/pr_composite_test.erl
erlang
-module(pr_composite_test). -compile([{parse_transform, lager_transform}]). -record(a, {field1 :: term(), field2 :: term()}). -record(b, {field1 :: term() , field2 :: term()}). -include_lib("eunit/include/eunit.hrl"). nested_record_test() -> A = #a{field1 = x, field2 = y}, B = #b{field1 = A, field2 = {}}, Pr_B = lager:pr(B, ?MODULE), ?assertEqual({'$lager_record', b, [{field1, {'$lager_record', a, [{field1, x},{field2, y}]}}, {field2, {}}]}, Pr_B). list_field_test() -> As = [#a{field1 = 1, field2 = a2}, #a{field1 = 2, field2 = a2}], B = #b{field1 = As, field2 = b2}, Pr_B = lager:pr(B, ?MODULE), ?assertEqual({'$lager_record', b, [{field1, [{'$lager_record', a, [{field1, 1},{field2, a2}]}, {'$lager_record', a, [{field1, 2},{field2, a2}]}]}, {field2, b2}]}, Pr_B). list_of_records_test() -> As = [#a{field1 = 1, field2 = a2}, #a{field1 = 2, field2 = a2}], Pr_As = lager:pr(As, ?MODULE), ?assertEqual([{'$lager_record', a, [{field1, 1},{field2, a2}]}, {'$lager_record', a, [{field1, 2},{field2, a2}]}], Pr_As). improper_list_test() -> A = #a{field1 = [1|2], field2 = a2}, Pr_A = lager:pr(A, ?MODULE), ?assertEqual({'$lager_record',a, [{field1,[1|2]},{field2,a2}]}, Pr_A).
8a6f8a4677669869d6339d9b7cfbf6f47d9eb547104fef7aed3c393cbb28ca73
threatgrid/ctia
hooks_service_core.clj
(ns ctia.flows.hooks-service-core "Handle hooks ([Cf. #159]())." (:require [clojure.tools.logging :as log] [ctia.flows.hooks.event-hooks :as event-hooks] [ctia.flows.hook-protocol :as prot] [ctia.schemas.services :refer [ConfigServiceFns]] [ctia.flows.hooks-service.schemas :refer [ApplyHooksOptions Context EntityOrEvent HookType HooksMap]] [schema.core :as s] [schema-tools.core :as st])) (defn- doc-list [& s] (with-meta [] {:doc (apply str s)})) (s/defn ^:private empty-hooks :- HooksMap [] {:before-create (doc-list "`before-create` hooks are triggered on" " create routes before the entity is saved in the DB.") :after-create (doc-list "`after-create` hooks are called after an entity was created.") :before-update (doc-list "`before-update` hooks are triggered on" " update routes before the entity is saved in the DB.") :after-update (doc-list "`after-update` hooks are called after an entity was updated.") :before-delete (doc-list "`before-delete` hooks are called before an entity is deleted.") :after-delete (doc-list "`after-delete` hooks are called after an entity is deleted.") :event (doc-list "`event` hooks are called with an event during any CRUD activity.")}) (s/defn reset-hooks! :- HooksMap [{:keys [hooks]} :- Context get-in-config :- (st/get-in ConfigServiceFns [:get-in-config])] (reset! hooks (-> (empty-hooks) (event-hooks/register-hooks get-in-config)))) (s/defn add-hook! :- HooksMap "Add a `Hook` for the hook `hook-type`" [{:keys [hooks]} :- Context hook-type :- HookType hook :- (s/protocol prot/Hook)] (swap! hooks update hook-type conj hook)) (s/defn add-hooks! :- HooksMap "Add a list of `Hook` for the hook `hook-type`" [{:keys [hooks]} :- Context hook-type :- HookType hook-list :- [(s/protocol prot/Hook)]] (swap! hooks update hook-type into hook-list)) (s/defn init-hooks! :- HooksMap "Initialize all hooks" [{:keys [hooks]} :- Context] (doseq [hook-list (vals @hooks) hook hook-list] (prot/init hook)) @hooks) (s/defn destroy-hooks! "Should call all destructor for each hook in reverse order." [{:keys [hooks]} :- Context] (doseq [hook-list (vals @hooks) hook (reverse hook-list)] (prot/destroy hook))) (s/defn apply-hooks "Apply the registered hooks for a given hook-type to the passed in data. Data may be an entity (or an event) and a previous entity. Accepts read-only?, in which case the result of the hooks do not change the result. In any hook that returns nil, the result is ignored and the input entity is kept." [{:keys [hooks]} :- Context {:keys [hook-type entity prev-entity read-only?]} :- ApplyHooksOptions] (loop [[hook & more-hooks :as hooks] (get @hooks hook-type) result entity] (if (empty? hooks) result (let [handle-result (prot/handle hook result prev-entity)] (if (or read-only? (nil? handle-result)) (recur more-hooks result) (recur more-hooks handle-result)))))) (s/defn apply-event-hooks [context :- Context event :- EntityOrEvent] (apply-hooks context {:hook-type :event :entity event :read-only? true})) (s/defn shutdown! "Normally this should not be called directly since init! registers a shutdown hook" [context :- Context] (destroy-hooks! context)) (s/defn init :- Context [context] (assoc context :hooks (atom (empty-hooks)))) (s/defn start :- Context "Initialize all hooks" [{:keys [hooks] :as context} :- Context get-in-config :- (st/get-in ConfigServiceFns [:get-in-config])] (reset-hooks! context get-in-config) (init-hooks! context) (log/info "Hooks Initialized: " (pr-str @hooks)) context) (s/defn stop "Should call all destructor for each hook in reverse order." [context :- Context] (shutdown! context) (dissoc context :hooks))
null
https://raw.githubusercontent.com/threatgrid/ctia/32857663cdd7ac385161103dbafa8dc4f98febf0/src/ctia/flows/hooks_service_core.clj
clojure
(ns ctia.flows.hooks-service-core "Handle hooks ([Cf. #159]())." (:require [clojure.tools.logging :as log] [ctia.flows.hooks.event-hooks :as event-hooks] [ctia.flows.hook-protocol :as prot] [ctia.schemas.services :refer [ConfigServiceFns]] [ctia.flows.hooks-service.schemas :refer [ApplyHooksOptions Context EntityOrEvent HookType HooksMap]] [schema.core :as s] [schema-tools.core :as st])) (defn- doc-list [& s] (with-meta [] {:doc (apply str s)})) (s/defn ^:private empty-hooks :- HooksMap [] {:before-create (doc-list "`before-create` hooks are triggered on" " create routes before the entity is saved in the DB.") :after-create (doc-list "`after-create` hooks are called after an entity was created.") :before-update (doc-list "`before-update` hooks are triggered on" " update routes before the entity is saved in the DB.") :after-update (doc-list "`after-update` hooks are called after an entity was updated.") :before-delete (doc-list "`before-delete` hooks are called before an entity is deleted.") :after-delete (doc-list "`after-delete` hooks are called after an entity is deleted.") :event (doc-list "`event` hooks are called with an event during any CRUD activity.")}) (s/defn reset-hooks! :- HooksMap [{:keys [hooks]} :- Context get-in-config :- (st/get-in ConfigServiceFns [:get-in-config])] (reset! hooks (-> (empty-hooks) (event-hooks/register-hooks get-in-config)))) (s/defn add-hook! :- HooksMap "Add a `Hook` for the hook `hook-type`" [{:keys [hooks]} :- Context hook-type :- HookType hook :- (s/protocol prot/Hook)] (swap! hooks update hook-type conj hook)) (s/defn add-hooks! :- HooksMap "Add a list of `Hook` for the hook `hook-type`" [{:keys [hooks]} :- Context hook-type :- HookType hook-list :- [(s/protocol prot/Hook)]] (swap! hooks update hook-type into hook-list)) (s/defn init-hooks! :- HooksMap "Initialize all hooks" [{:keys [hooks]} :- Context] (doseq [hook-list (vals @hooks) hook hook-list] (prot/init hook)) @hooks) (s/defn destroy-hooks! "Should call all destructor for each hook in reverse order." [{:keys [hooks]} :- Context] (doseq [hook-list (vals @hooks) hook (reverse hook-list)] (prot/destroy hook))) (s/defn apply-hooks "Apply the registered hooks for a given hook-type to the passed in data. Data may be an entity (or an event) and a previous entity. Accepts read-only?, in which case the result of the hooks do not change the result. In any hook that returns nil, the result is ignored and the input entity is kept." [{:keys [hooks]} :- Context {:keys [hook-type entity prev-entity read-only?]} :- ApplyHooksOptions] (loop [[hook & more-hooks :as hooks] (get @hooks hook-type) result entity] (if (empty? hooks) result (let [handle-result (prot/handle hook result prev-entity)] (if (or read-only? (nil? handle-result)) (recur more-hooks result) (recur more-hooks handle-result)))))) (s/defn apply-event-hooks [context :- Context event :- EntityOrEvent] (apply-hooks context {:hook-type :event :entity event :read-only? true})) (s/defn shutdown! "Normally this should not be called directly since init! registers a shutdown hook" [context :- Context] (destroy-hooks! context)) (s/defn init :- Context [context] (assoc context :hooks (atom (empty-hooks)))) (s/defn start :- Context "Initialize all hooks" [{:keys [hooks] :as context} :- Context get-in-config :- (st/get-in ConfigServiceFns [:get-in-config])] (reset-hooks! context get-in-config) (init-hooks! context) (log/info "Hooks Initialized: " (pr-str @hooks)) context) (s/defn stop "Should call all destructor for each hook in reverse order." [context :- Context] (shutdown! context) (dissoc context :hooks))
22b74e93f01b61b6c7fab7b15b7579d1cc925046a0dde429733cad64d7c331a1
jabber-at/ejabberd-contrib
fusco_lib_tests.erl
%%%----------------------------------------------------------------------------- ( C ) 1999 - 2013 , Erlang Solutions Ltd @author < > @author Corbacho < > %%% @doc %%% @end %%%----------------------------------------------------------------------------- -module(fusco_lib_tests). -copyright("2013, Erlang Solutions Ltd."). -include("../include/fusco_types.hrl"). -include("../include/fusco.hrl"). -include_lib("eunit/include/eunit.hrl"). parse_url_test_() -> [ ?_assertEqual(#fusco_url{ host = "host", port = 80, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("")), ?_assertEqual(#fusco_url{ host = "host", port = 80, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("/")), ?_assertEqual(#fusco_url{ host = "host", port = 443, path = "/", is_ssl = true, user = "", password = "" }, fusco_lib:parse_url("")), ?_assertEqual(#fusco_url{ host = "host", port = 443, path = "/", is_ssl = true, user = "", password = "" }, fusco_lib:parse_url("/")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180/")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180/foo")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erlang" }, fusco_lib:parse_url(":erlang@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erl@ng" }, fusco_lib:parse_url(":erl%40ng@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "" }, fusco_lib:parse_url("@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("http://@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe:arm", password = "erlang" }, fusco_lib:parse_url(":erlang@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe:arm", password = "erlang/otp" }, fusco_lib:parse_url(":erlang%2Fotp@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "::1", port = 80, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("http://[::1]/foo/bar")), ?_assertEqual(#fusco_url{ host = "::1", port = 180, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("http://[::1]:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "::1", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erlang" }, fusco_lib:parse_url(":erlang@[::1]:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "1080:0:0:0:8:800:200c:417a", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erlang" }, fusco_lib:parse_url(":erlang@[1080:0:0:0:8:800:200C:417A]:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "www.example.com", port = 80, path = "/?a=b", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("")) ].
null
https://raw.githubusercontent.com/jabber-at/ejabberd-contrib/d5eb036b786c822d9fd56f881d27e31688ec6e91/ejabberd_auth_http/deps/fusco/test/fusco_lib_tests.erl
erlang
----------------------------------------------------------------------------- @doc @end -----------------------------------------------------------------------------
( C ) 1999 - 2013 , Erlang Solutions Ltd @author < > @author Corbacho < > -module(fusco_lib_tests). -copyright("2013, Erlang Solutions Ltd."). -include("../include/fusco_types.hrl"). -include("../include/fusco.hrl"). -include_lib("eunit/include/eunit.hrl"). parse_url_test_() -> [ ?_assertEqual(#fusco_url{ host = "host", port = 80, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("")), ?_assertEqual(#fusco_url{ host = "host", port = 80, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("/")), ?_assertEqual(#fusco_url{ host = "host", port = 443, path = "/", is_ssl = true, user = "", password = "" }, fusco_lib:parse_url("")), ?_assertEqual(#fusco_url{ host = "host", port = 443, path = "/", is_ssl = true, user = "", password = "" }, fusco_lib:parse_url("/")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180/")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180/foo")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url(":180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erlang" }, fusco_lib:parse_url(":erlang@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erl@ng" }, fusco_lib:parse_url(":erl%40ng@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "" }, fusco_lib:parse_url("@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("http://@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe:arm", password = "erlang" }, fusco_lib:parse_url(":erlang@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "host", port = 180, path = "/foo/bar", is_ssl = false, user = "joe:arm", password = "erlang/otp" }, fusco_lib:parse_url(":erlang%2Fotp@host:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "::1", port = 80, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("http://[::1]/foo/bar")), ?_assertEqual(#fusco_url{ host = "::1", port = 180, path = "/foo/bar", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("http://[::1]:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "::1", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erlang" }, fusco_lib:parse_url(":erlang@[::1]:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "1080:0:0:0:8:800:200c:417a", port = 180, path = "/foo/bar", is_ssl = false, user = "joe", password = "erlang" }, fusco_lib:parse_url(":erlang@[1080:0:0:0:8:800:200C:417A]:180/foo/bar")), ?_assertEqual(#fusco_url{ host = "www.example.com", port = 80, path = "/?a=b", is_ssl = false, user = "", password = "" }, fusco_lib:parse_url("")) ].
49b84c1053df251560225aa8e925a63a423573be8cf7383d2bf12dbb179e81db
ocaml-community/ulex
utf8.ml
exception MalFormed (* cf *) let width = Array.make 256 (-1) let () = for i = 0 to 127 do width.(i) <- 1 done; for i = 192 to 223 do width.(i) <- 2 done; for i = 224 to 239 do width.(i) <- 3 done; for i = 240 to 247 do width.(i) <- 4 done let next s i = match s.[i] with | '\000'..'\127' as c -> Char.code c | '\192'..'\223' as c -> let n1 = Char.code c in let n2 = Char.code s.[i+1] in if (n2 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x1f) lsl 6) lor (n2 land 0x3f) | '\224'..'\239' as c -> let n1 = Char.code c in let n2 = Char.code s.[i+1] in let n3 = Char.code s.[i+2] in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) then raise MalFormed; let p = ((n1 land 0x0f) lsl 12) lor ((n2 land 0x3f) lsl 6) lor (n3 land 0x3f) in if (p >= 0xd800) && (p <= 0xdf00) then raise MalFormed; p | '\240'..'\247' as c -> let n1 = Char.code c in let n2 = Char.code s.[i+1] in let n3 = Char.code s.[i+2] in let n4 = Char.code s.[i+3] in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) || (n4 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x07) lsl 18) lor ((n2 land 0x3f) lsl 12) lor ((n3 land 0x3f) lsl 6) lor (n4 land 0x3f) | _ -> raise MalFormed With this implementation , a truncated code point will result in Stream . Failure , not in MalFormed . in Stream.Failure, not in MalFormed. *) let from_stream s = match Stream.next s with | '\000'..'\127' as c -> Char.code c | '\192'..'\223' as c -> let n1 = Char.code c in let n2 = Char.code (Stream.next s) in if (n2 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x1f) lsl 6) lor (n2 land 0x3f) | '\224'..'\239' as c -> let n1 = Char.code c in let n2 = Char.code (Stream.next s) in let n3 = Char.code (Stream.next s) in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x0f) lsl 12) lor ((n2 land 0x3f) lsl 6) lor (n3 land 0x3f) | '\240'..'\247' as c -> let n1 = Char.code c in let n2 = Char.code (Stream.next s) in let n3 = Char.code (Stream.next s) in let n4 = Char.code (Stream.next s) in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) || (n4 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x07) lsl 18) lor ((n2 land 0x3f) lsl 12) lor ((n3 land 0x3f) lsl 6) lor (n4 land 0x3f) | _ -> raise MalFormed let compute_len s pos bytes = let rec aux n i = if i >= pos + bytes then if i = pos + bytes then n else raise MalFormed else let w = width.(Char.code s.[i]) in if w > 0 then aux (succ n) (i + w) else raise MalFormed in aux 0 pos let rec blit_to_int s spos a apos n = if n > 0 then begin a.(apos) <- next s spos; blit_to_int s (spos + width.(Char.code s.[spos])) a (succ apos) (pred n) end let to_int_array s pos bytes = let n = compute_len s pos bytes in let a = Array.make n 0 in blit_to_int s pos a 0 n; a (**************************) let width_code_point p = if p <= 0x7f then 1 else if p <= 0x7ff then 2 else if p <= 0xffff then 3 else if p <= 0x10ffff then 4 else raise MalFormed let store b p = if p <= 0x7f then Buffer.add_char b (Char.chr p) else if p <= 0x7ff then ( Buffer.add_char b (Char.chr (0xc0 lor (p lsr 6))); Buffer.add_char b (Char.chr (0x80 lor (p land 0x3f))) ) else if p <= 0xffff then ( if (p >= 0xd800 && p < 0xe000) then raise MalFormed; Buffer.add_char b (Char.chr (0xe0 lor (p lsr 12))); Buffer.add_char b (Char.chr (0x80 lor ((p lsr 6) land 0x3f))); Buffer.add_char b (Char.chr (0x80 lor (p land 0x3f))) ) else if p <= 0x10ffff then ( Buffer.add_char b (Char.chr (0xf0 lor (p lsr 18))); Buffer.add_char b (Char.chr (0x80 lor ((p lsr 12) land 0x3f))); Buffer.add_char b (Char.chr (0x80 lor ((p lsr 6) land 0x3f))); Buffer.add_char b (Char.chr (0x80 lor (p land 0x3f))) ) else raise MalFormed let from_int_array a apos len = let b = Buffer.create (len * 4) in let rec aux apos len = if len > 0 then (store b a.(apos); aux (succ apos) (pred len)) else Buffer.contents b in aux apos len let stream_from_char_stream s = Stream.from (fun _ -> try Some (from_stream s) with Stream.Failure -> None)
null
https://raw.githubusercontent.com/ocaml-community/ulex/9a01902864e023939c9021c1320ad81497f1ef3d/utf8.ml
ocaml
cf ************************
exception MalFormed let width = Array.make 256 (-1) let () = for i = 0 to 127 do width.(i) <- 1 done; for i = 192 to 223 do width.(i) <- 2 done; for i = 224 to 239 do width.(i) <- 3 done; for i = 240 to 247 do width.(i) <- 4 done let next s i = match s.[i] with | '\000'..'\127' as c -> Char.code c | '\192'..'\223' as c -> let n1 = Char.code c in let n2 = Char.code s.[i+1] in if (n2 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x1f) lsl 6) lor (n2 land 0x3f) | '\224'..'\239' as c -> let n1 = Char.code c in let n2 = Char.code s.[i+1] in let n3 = Char.code s.[i+2] in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) then raise MalFormed; let p = ((n1 land 0x0f) lsl 12) lor ((n2 land 0x3f) lsl 6) lor (n3 land 0x3f) in if (p >= 0xd800) && (p <= 0xdf00) then raise MalFormed; p | '\240'..'\247' as c -> let n1 = Char.code c in let n2 = Char.code s.[i+1] in let n3 = Char.code s.[i+2] in let n4 = Char.code s.[i+3] in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) || (n4 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x07) lsl 18) lor ((n2 land 0x3f) lsl 12) lor ((n3 land 0x3f) lsl 6) lor (n4 land 0x3f) | _ -> raise MalFormed With this implementation , a truncated code point will result in Stream . Failure , not in MalFormed . in Stream.Failure, not in MalFormed. *) let from_stream s = match Stream.next s with | '\000'..'\127' as c -> Char.code c | '\192'..'\223' as c -> let n1 = Char.code c in let n2 = Char.code (Stream.next s) in if (n2 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x1f) lsl 6) lor (n2 land 0x3f) | '\224'..'\239' as c -> let n1 = Char.code c in let n2 = Char.code (Stream.next s) in let n3 = Char.code (Stream.next s) in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x0f) lsl 12) lor ((n2 land 0x3f) lsl 6) lor (n3 land 0x3f) | '\240'..'\247' as c -> let n1 = Char.code c in let n2 = Char.code (Stream.next s) in let n3 = Char.code (Stream.next s) in let n4 = Char.code (Stream.next s) in if (n2 lsr 6 != 0b10) || (n3 lsr 6 != 0b10) || (n4 lsr 6 != 0b10) then raise MalFormed; ((n1 land 0x07) lsl 18) lor ((n2 land 0x3f) lsl 12) lor ((n3 land 0x3f) lsl 6) lor (n4 land 0x3f) | _ -> raise MalFormed let compute_len s pos bytes = let rec aux n i = if i >= pos + bytes then if i = pos + bytes then n else raise MalFormed else let w = width.(Char.code s.[i]) in if w > 0 then aux (succ n) (i + w) else raise MalFormed in aux 0 pos let rec blit_to_int s spos a apos n = if n > 0 then begin a.(apos) <- next s spos; blit_to_int s (spos + width.(Char.code s.[spos])) a (succ apos) (pred n) end let to_int_array s pos bytes = let n = compute_len s pos bytes in let a = Array.make n 0 in blit_to_int s pos a 0 n; a let width_code_point p = if p <= 0x7f then 1 else if p <= 0x7ff then 2 else if p <= 0xffff then 3 else if p <= 0x10ffff then 4 else raise MalFormed let store b p = if p <= 0x7f then Buffer.add_char b (Char.chr p) else if p <= 0x7ff then ( Buffer.add_char b (Char.chr (0xc0 lor (p lsr 6))); Buffer.add_char b (Char.chr (0x80 lor (p land 0x3f))) ) else if p <= 0xffff then ( if (p >= 0xd800 && p < 0xe000) then raise MalFormed; Buffer.add_char b (Char.chr (0xe0 lor (p lsr 12))); Buffer.add_char b (Char.chr (0x80 lor ((p lsr 6) land 0x3f))); Buffer.add_char b (Char.chr (0x80 lor (p land 0x3f))) ) else if p <= 0x10ffff then ( Buffer.add_char b (Char.chr (0xf0 lor (p lsr 18))); Buffer.add_char b (Char.chr (0x80 lor ((p lsr 12) land 0x3f))); Buffer.add_char b (Char.chr (0x80 lor ((p lsr 6) land 0x3f))); Buffer.add_char b (Char.chr (0x80 lor (p land 0x3f))) ) else raise MalFormed let from_int_array a apos len = let b = Buffer.create (len * 4) in let rec aux apos len = if len > 0 then (store b a.(apos); aux (succ apos) (pred len)) else Buffer.contents b in aux apos len let stream_from_char_stream s = Stream.from (fun _ -> try Some (from_stream s) with Stream.Failure -> None)
43857ec9fe0e30689cfefadb849860ff41d6fb78fed577dff9b52b7045ae3b93
CardanoSolutions/kupo
Health.hs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. # LANGUAGE RecordWildCards # module Kupo.Data.Health ( -- * Health Health (..) , emptyHealth * ConnectionStatus , ConnectionStatus (..) , mkPrometheusMetrics ) where import Kupo.Prelude import Kupo.Data.Cardano ( Point , SlotNo (..) , getPointSlotNo , slotNoToJson ) import Data.ByteString.Builder ( Builder ) import Kupo.Version ( version ) import System.Metrics.Prometheus.Encode.Text ( encodeMetrics ) import System.Metrics.Prometheus.Metric ( MetricSample (..) ) import System.Metrics.Prometheus.Metric.Counter ( CounterSample (..) ) import System.Metrics.Prometheus.Metric.Gauge ( GaugeSample (..) ) import System.Metrics.Prometheus.MetricId ( Labels (..) , MetricId (..) , makeName ) import System.Metrics.Prometheus.Registry ( RegistrySample (..) ) import qualified Data.Aeson.Encoding as Json import qualified Data.Map as Map -- | Information about the overall state of the application. data Health = Health { connectionStatus :: !ConnectionStatus -- ^ Condition of the connection with the underlying node. , mostRecentCheckpoint :: !(Maybe Point) -- ^ Absolute slot number of the most recent database checkpoint. , mostRecentNodeTip :: !(Maybe SlotNo) -- ^ Absolute slot number of the tip of the node } deriving stock (Generic, Eq, Show) instance ToJSON Health where toEncoding Health{..} = Json.pairs $ mconcat [ Json.pair "connection_status" (toEncoding connectionStatus) , Json.pair "most_recent_checkpoint" (maybe Json.null_ (slotNoToJson . getPointSlotNo) mostRecentCheckpoint) , Json.pair "most_recent_node_tip" (maybe Json.null_ slotNoToJson mostRecentNodeTip) , Json.pair "version" (toEncoding version) ] emptyHealth :: Health emptyHealth = Health { connectionStatus = Disconnected , mostRecentCheckpoint = Nothing , mostRecentNodeTip = Nothing } -- | Reflect the current state of the connection with the underlying node. data ConnectionStatus = Connected | Disconnected deriving stock (Generic, Eq, Show, Enum, Bounded) instance ToJSON ConnectionStatus where toEncoding = \case Connected -> Json.text "connected" Disconnected -> Json.text "disconnected" mkPrometheusMetrics :: Health -> Builder mkPrometheusMetrics Health{..} = prometheusMetrics & Map.fromList & Map.mapKeys (\k -> (MetricId (makeName $ "kupo_" <> k) (Labels mempty))) & RegistrySample & encodeMetrics where mkGauge :: Double -> MetricSample mkGauge = GaugeMetricSample . GaugeSample mkCounter :: Int -> MetricSample mkCounter = CounterMetricSample . CounterSample prometheusMetrics :: [(Text, MetricSample)] prometheusMetrics = mconcat [ [ ( "connection_status" , mkGauge $ case connectionStatus of Connected -> 1 Disconnected -> 0 ) ] , [ ( "most_recent_checkpoint" , mkCounter $ fromEnum $ unSlotNo $ getPointSlotNo s ) | Just s <- [mostRecentCheckpoint] ] , [ ( "most_recent_node_tip" , mkCounter $ fromEnum $ unSlotNo s ) | Just s <- [mostRecentNodeTip] ] ]
null
https://raw.githubusercontent.com/CardanoSolutions/kupo/1ee9006d1513037cf0b662feaecbc444d6584bce/src/Kupo/Data/Health.hs
haskell
* Health | Information about the overall state of the application. ^ Condition of the connection with the underlying node. ^ Absolute slot number of the most recent database checkpoint. ^ Absolute slot number of the tip of the node | Reflect the current state of the connection with the underlying node.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. # LANGUAGE RecordWildCards # module Kupo.Data.Health Health (..) , emptyHealth * ConnectionStatus , ConnectionStatus (..) , mkPrometheusMetrics ) where import Kupo.Prelude import Kupo.Data.Cardano ( Point , SlotNo (..) , getPointSlotNo , slotNoToJson ) import Data.ByteString.Builder ( Builder ) import Kupo.Version ( version ) import System.Metrics.Prometheus.Encode.Text ( encodeMetrics ) import System.Metrics.Prometheus.Metric ( MetricSample (..) ) import System.Metrics.Prometheus.Metric.Counter ( CounterSample (..) ) import System.Metrics.Prometheus.Metric.Gauge ( GaugeSample (..) ) import System.Metrics.Prometheus.MetricId ( Labels (..) , MetricId (..) , makeName ) import System.Metrics.Prometheus.Registry ( RegistrySample (..) ) import qualified Data.Aeson.Encoding as Json import qualified Data.Map as Map data Health = Health { connectionStatus :: !ConnectionStatus , mostRecentCheckpoint :: !(Maybe Point) , mostRecentNodeTip :: !(Maybe SlotNo) } deriving stock (Generic, Eq, Show) instance ToJSON Health where toEncoding Health{..} = Json.pairs $ mconcat [ Json.pair "connection_status" (toEncoding connectionStatus) , Json.pair "most_recent_checkpoint" (maybe Json.null_ (slotNoToJson . getPointSlotNo) mostRecentCheckpoint) , Json.pair "most_recent_node_tip" (maybe Json.null_ slotNoToJson mostRecentNodeTip) , Json.pair "version" (toEncoding version) ] emptyHealth :: Health emptyHealth = Health { connectionStatus = Disconnected , mostRecentCheckpoint = Nothing , mostRecentNodeTip = Nothing } data ConnectionStatus = Connected | Disconnected deriving stock (Generic, Eq, Show, Enum, Bounded) instance ToJSON ConnectionStatus where toEncoding = \case Connected -> Json.text "connected" Disconnected -> Json.text "disconnected" mkPrometheusMetrics :: Health -> Builder mkPrometheusMetrics Health{..} = prometheusMetrics & Map.fromList & Map.mapKeys (\k -> (MetricId (makeName $ "kupo_" <> k) (Labels mempty))) & RegistrySample & encodeMetrics where mkGauge :: Double -> MetricSample mkGauge = GaugeMetricSample . GaugeSample mkCounter :: Int -> MetricSample mkCounter = CounterMetricSample . CounterSample prometheusMetrics :: [(Text, MetricSample)] prometheusMetrics = mconcat [ [ ( "connection_status" , mkGauge $ case connectionStatus of Connected -> 1 Disconnected -> 0 ) ] , [ ( "most_recent_checkpoint" , mkCounter $ fromEnum $ unSlotNo $ getPointSlotNo s ) | Just s <- [mostRecentCheckpoint] ] , [ ( "most_recent_node_tip" , mkCounter $ fromEnum $ unSlotNo s ) | Just s <- [mostRecentNodeTip] ] ]
95c48922fd715d4eec9d788cea8261b6748933fd7ad937d158c24cb16a36c00d
GaloisInc/HaLVM
Xenstore.hs
Copyright 2006 - 2008 , Galois , Inc. This software is distributed under a standard , three - clause BSD license . -- Please see the file LICENSE, distributed with this software, for specific -- terms and conditions. An example showing how programs can interact with the . import Control.Concurrent import Control.Exception import Control.Monad import Hypervisor.Console import Hypervisor.Debug import Hypervisor.ErrorCodes import Hypervisor.XenStore import System.FilePath import Prelude hiding (getLine) main :: IO () main = do con <- initXenConsole xs <- initXenStore me <- xsGetDomId xs here <- xsGetDomainPath xs me writeConsole con ("Hello! This is an interactive XenStore thing for " ++ show me ++ "\n") writeConsole con ("Valid commands: quit, ls, cd\n\n") writeDebugConsole "Starting interaction loop!\n" runPrompt con xs here runPrompt :: Console -> XenStore -> FilePath -> IO () runPrompt con xs here = do writeConsole con (here ++ "> ") inquery <- getLine con case words inquery of ("quit":_) -> return () ("ls" :_) -> do contents <- filter (/= "") `fmap` xsDirectory xs here values <- mapM (getValue xs) (map (here </>) contents) let contents' = map (forceSize 25) contents values' = map (forceSize 40) values forM_ (zip contents' values') $ \ (key, value) -> writeConsole con (key ++ " ==> " ++ value ++ "\n") runPrompt con xs here ("cd" :x:_) -> do case x of ".." -> runPrompt con xs (takeDirectory here) d -> runPrompt con xs (here </> d) _ -> do writeConsole con "Unrecognized command.\n" runPrompt con xs here getValue :: XenStore -> String -> IO String getValue xs key = handle handleException (emptify `fmap` xsRead xs key) where handleException :: ErrorCode -> IO String handleException _ = return "<read error>" emptify "" = "<empty>" emptify s = s forceSize :: Int -> String -> String forceSize n str | length str > n = "..." ++ drop (length str - (n - 3)) str | length str < n = str ++ (replicate (n - length str) ' ') | otherwise = str getLine :: Console -> IO String getLine con = do nextC <- readConsole con 1 writeConsole con nextC case nextC of "\r" -> writeConsole con "\n" >> return "" [x] -> (x:) `fmap` getLine con _ -> fail "More than one character back?"
null
https://raw.githubusercontent.com/GaloisInc/HaLVM/3ec1d7e4b6bcb91304ba2bfe8ee280cb1699f24d/examples/Core/Xenstore/Xenstore.hs
haskell
Please see the file LICENSE, distributed with this software, for specific terms and conditions.
Copyright 2006 - 2008 , Galois , Inc. This software is distributed under a standard , three - clause BSD license . An example showing how programs can interact with the . import Control.Concurrent import Control.Exception import Control.Monad import Hypervisor.Console import Hypervisor.Debug import Hypervisor.ErrorCodes import Hypervisor.XenStore import System.FilePath import Prelude hiding (getLine) main :: IO () main = do con <- initXenConsole xs <- initXenStore me <- xsGetDomId xs here <- xsGetDomainPath xs me writeConsole con ("Hello! This is an interactive XenStore thing for " ++ show me ++ "\n") writeConsole con ("Valid commands: quit, ls, cd\n\n") writeDebugConsole "Starting interaction loop!\n" runPrompt con xs here runPrompt :: Console -> XenStore -> FilePath -> IO () runPrompt con xs here = do writeConsole con (here ++ "> ") inquery <- getLine con case words inquery of ("quit":_) -> return () ("ls" :_) -> do contents <- filter (/= "") `fmap` xsDirectory xs here values <- mapM (getValue xs) (map (here </>) contents) let contents' = map (forceSize 25) contents values' = map (forceSize 40) values forM_ (zip contents' values') $ \ (key, value) -> writeConsole con (key ++ " ==> " ++ value ++ "\n") runPrompt con xs here ("cd" :x:_) -> do case x of ".." -> runPrompt con xs (takeDirectory here) d -> runPrompt con xs (here </> d) _ -> do writeConsole con "Unrecognized command.\n" runPrompt con xs here getValue :: XenStore -> String -> IO String getValue xs key = handle handleException (emptify `fmap` xsRead xs key) where handleException :: ErrorCode -> IO String handleException _ = return "<read error>" emptify "" = "<empty>" emptify s = s forceSize :: Int -> String -> String forceSize n str | length str > n = "..." ++ drop (length str - (n - 3)) str | length str < n = str ++ (replicate (n - length str) ' ') | otherwise = str getLine :: Console -> IO String getLine con = do nextC <- readConsole con 1 writeConsole con nextC case nextC of "\r" -> writeConsole con "\n" >> return "" [x] -> (x:) `fmap` getLine con _ -> fail "More than one character back?"
c80c22eac51a989f12df3a20118e9896c1695409fa623be29b060bdd2e9c3dfc
gren-lang/compiler
PossibleFilePath.hs
module Gren.PossibleFilePath ( PossibleFilePath (..), mapWith, encodeJson, other, is, toChars, ) where import Data.Utf8 qualified as Utf8 import Json.Encode qualified as E data PossibleFilePath a = Is FilePath | Other a deriving (Eq) mapWith :: (a -> b) -> PossibleFilePath a -> PossibleFilePath b mapWith fn possibleFP = case possibleFP of Is filePath -> Is filePath Other a -> Other $ fn a other :: PossibleFilePath a -> Maybe a other possibleFP = case possibleFP of Is _ -> Nothing Other a -> Just a is :: PossibleFilePath a -> Bool is possibleFP = case possibleFP of Is _ -> True Other _ -> False encodeJson :: (a -> E.Value) -> PossibleFilePath a -> E.Value encodeJson encoderForNonFP possibleFP = case possibleFP of Is filePath -> E.string $ Utf8.fromChars $ "local:" ++ filePath Other a -> encoderForNonFP a toChars :: (a -> String) -> PossibleFilePath a -> String toChars otherToString pfp = case pfp of Is fp -> fp Other a -> otherToString a
null
https://raw.githubusercontent.com/gren-lang/compiler/d15699406d55636a1c0884a31bdc8f6bed995b83/builder/src/Gren/PossibleFilePath.hs
haskell
module Gren.PossibleFilePath ( PossibleFilePath (..), mapWith, encodeJson, other, is, toChars, ) where import Data.Utf8 qualified as Utf8 import Json.Encode qualified as E data PossibleFilePath a = Is FilePath | Other a deriving (Eq) mapWith :: (a -> b) -> PossibleFilePath a -> PossibleFilePath b mapWith fn possibleFP = case possibleFP of Is filePath -> Is filePath Other a -> Other $ fn a other :: PossibleFilePath a -> Maybe a other possibleFP = case possibleFP of Is _ -> Nothing Other a -> Just a is :: PossibleFilePath a -> Bool is possibleFP = case possibleFP of Is _ -> True Other _ -> False encodeJson :: (a -> E.Value) -> PossibleFilePath a -> E.Value encodeJson encoderForNonFP possibleFP = case possibleFP of Is filePath -> E.string $ Utf8.fromChars $ "local:" ++ filePath Other a -> encoderForNonFP a toChars :: (a -> String) -> PossibleFilePath a -> String toChars otherToString pfp = case pfp of Is fp -> fp Other a -> otherToString a
dbbadfb550ea9b50bbab04d82a4c9eafaa6543d7d4496770579fbbb30961d305
xclerc/ocamljava
mapReduce.mli
* This file is part of library . * Copyright ( C ) 2007 - 2015 . * * 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 . * * library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program . If not , see < / > . * This file is part of OCaml-Java library. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java 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. * * OCaml-Java library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see </>. *) (** Map/reduce computations. *) module type Computation = sig type input (** The type of input values. *) type key (** The type of keys. *) type value (** The type of values. *) type output (** The type of output values. *) val compare_keys : key -> key -> int (** Ordering over keys. *) val map : input -> (key * value) list (** {i map} operation, turning an input value into a list of key/value couples. The various calls to [map] are done in parallel by pool threads. *) val combine : key -> value -> value -> value * { i combine } operation , turning two values into one for a given key . The calls to [ combine ] are done sequentially by the main thread as soon as several values are available for a given key . The calls to [combine] are done sequentially by the main thread as soon as several values are available for a given key. *) val reduce : key -> value -> output -> output (** {i reduce} operation, folding over all key/value couple in order to produce the final result. *) end (** Description of a computation. *) module type S = sig type input (** The type of input values. *) type output (** The type of output values. *) val compute : ThreadPoolExecutor.t -> input Stream.t -> output -> output * Iterates over the passed stream using pool threads to execute { i map } operations over the various input values , and applies { i combine } operation over values having identical keys as soon as they are available . Then , folds over key / value couple through the { i reduce } operation , using the third parameter as the inital value . {i map} operations over the various input values, and applies {i combine} operation over values having identical keys as soon as they are available. Then, folds over key/value couple through the {i reduce} operation, using the third parameter as the inital value. *) end (** Signature of a map/reduce computation. *) module Make (C : Computation) : S with type input = C.input and type output = C.output (** Builds a map/reduce implementation for the passed computation. *)
null
https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/library/concurrent/src/mapreduce/mapReduce.mli
ocaml
* Map/reduce computations. * The type of input values. * The type of keys. * The type of values. * The type of output values. * Ordering over keys. * {i map} operation, turning an input value into a list of key/value couples. The various calls to [map] are done in parallel by pool threads. * {i reduce} operation, folding over all key/value couple in order to produce the final result. * Description of a computation. * The type of input values. * The type of output values. * Signature of a map/reduce computation. * Builds a map/reduce implementation for the passed computation.
* This file is part of library . * Copyright ( C ) 2007 - 2015 . * * 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 . * * library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program . If not , see < / > . * This file is part of OCaml-Java library. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java 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. * * OCaml-Java library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see </>. *) module type Computation = sig type input type key type value type output val compare_keys : key -> key -> int val map : input -> (key * value) list val combine : key -> value -> value -> value * { i combine } operation , turning two values into one for a given key . The calls to [ combine ] are done sequentially by the main thread as soon as several values are available for a given key . The calls to [combine] are done sequentially by the main thread as soon as several values are available for a given key. *) val reduce : key -> value -> output -> output end module type S = sig type input type output val compute : ThreadPoolExecutor.t -> input Stream.t -> output -> output * Iterates over the passed stream using pool threads to execute { i map } operations over the various input values , and applies { i combine } operation over values having identical keys as soon as they are available . Then , folds over key / value couple through the { i reduce } operation , using the third parameter as the inital value . {i map} operations over the various input values, and applies {i combine} operation over values having identical keys as soon as they are available. Then, folds over key/value couple through the {i reduce} operation, using the third parameter as the inital value. *) end module Make (C : Computation) : S with type input = C.input and type output = C.output
b9d5ac8bbccf09e126ad0ff6ee01021a29eeea1cc05d22e4a042a754a8b1bc23
soulomoon/SICP
Exercise4.29.scm
Exercise 4.29 : Exhibit a program that you would expect to run much more slowly without memoization than with memoization . Also , consider the following interaction , where the i d procedure is defined as in Exercise 4.27 and count starts at 0 : ; (define (square x) (* x x)) ; ; ; L - Eval input : ; (square (id 10)) ; ; ; L - Eval value : ; ⟨response⟩ ; ; ; L - Eval input : ; count ; ; ; L - Eval value : ; ⟨response⟩ Give the responses both when the evaluator and when it does not . is: L - Eval input : (square (id 10)) L - Eval value : 100 L - Eval input : count L - Eval value : 1 not: L - Eval input : (square (id 10)) L - Eval value : 100 L - Eval input : count L - Eval value : 2
null
https://raw.githubusercontent.com/soulomoon/SICP/1c6cbf5ecf6397eaeb990738a938d48c193af1bb/Chapter4/Exercise4.29.scm
scheme
(define (square x) (* x x)) ; ; L - Eval input : (square (id 10)) ; ; L - Eval value : ⟨response⟩ ; ; L - Eval input : count ; ; L - Eval value : ⟨response⟩
Exercise 4.29 : Exhibit a program that you would expect to run much more slowly without memoization than with memoization . Also , consider the following interaction , where the i d procedure is defined as in Exercise 4.27 and count starts at 0 : Give the responses both when the evaluator and when it does not . is: L - Eval input : (square (id 10)) L - Eval value : 100 L - Eval input : count L - Eval value : 1 not: L - Eval input : (square (id 10)) L - Eval value : 100 L - Eval input : count L - Eval value : 2
1dd25e8b0e55f9519aa01b93c82db55744b6f15acc53e69122d5d133a237fd80
LexiFi/dead_code_analyzer
anonFn.ml
let f ?(a = 0) ?(b = 0) x = a + b + x let g ?(a = 0) ?(b = 0) x = a + b + x let h ?(a = 0) ?(b = 0) x = a + b + x
null
https://raw.githubusercontent.com/LexiFi/dead_code_analyzer/c44dc2ea5ccb13df2145e9316e21c39f09dad506/examples/dir/anonFn.ml
ocaml
let f ?(a = 0) ?(b = 0) x = a + b + x let g ?(a = 0) ?(b = 0) x = a + b + x let h ?(a = 0) ?(b = 0) x = a + b + x
dc2f221337ebc6224404b860ab4d25a14c628d2793018c0d0c1b13f9722e408c
bcc32/advent-of-code
a.ml
open! Core let visited = Int.Hash_set.create () let rec dfs edges x = if not (Hash_set.mem visited x) then ( Hash_set.add visited x; Map.find edges x |> Option.iter ~f:(List.iter ~f:(fun other -> dfs edges other))) ;; let () = let pipes = In_channel.with_file (Sys.get_argv ()).(1) ~f:In_channel.input_lines |> List.map ~f:(fun line -> let index = String.substr_index_exn line ~pattern:"<->" in let left = String.subo line ~len:(index - 1) in let right = String.subo line ~pos:(index + 4) in let self = Int.of_string left in let others = right |> String.split ~on:',' |> List.map ~f:String.strip |> List.map ~f:Int.of_string in self, others) |> Int.Map.of_alist_exn in dfs pipes 0; Hash_set.length visited |> printf "%d\n" ;;
null
https://raw.githubusercontent.com/bcc32/advent-of-code/653c0f130e2fb2f599d4e76804e02af54c9bb19f/2017/12/a.ml
ocaml
open! Core let visited = Int.Hash_set.create () let rec dfs edges x = if not (Hash_set.mem visited x) then ( Hash_set.add visited x; Map.find edges x |> Option.iter ~f:(List.iter ~f:(fun other -> dfs edges other))) ;; let () = let pipes = In_channel.with_file (Sys.get_argv ()).(1) ~f:In_channel.input_lines |> List.map ~f:(fun line -> let index = String.substr_index_exn line ~pattern:"<->" in let left = String.subo line ~len:(index - 1) in let right = String.subo line ~pos:(index + 4) in let self = Int.of_string left in let others = right |> String.split ~on:',' |> List.map ~f:String.strip |> List.map ~f:Int.of_string in self, others) |> Int.Map.of_alist_exn in dfs pipes 0; Hash_set.length visited |> printf "%d\n" ;;
ee66a02e72d1a65351a5fb3b4da2d123b404f3b7353234e7e2b9c06ee41d1d2a
racket/drracket
module-language-tools.rkt
#lang racket/base (provide module-language-tools@) (require mrlib/switchable-button mrlib/bitmap-label mrlib/close-icon racket/contract racket/contract/option racket/place racket/format racket/unit racket/class racket/math racket/gui/base syntax-color/module-lexer framework framework/private/srcloc-panel framework/private/logging-timer drracket/private/drsig "local-member-names.rkt" "insulated-read-language.rkt" "eval-helpers-and-pref-init.rkt" string-constants) (define op (current-output-port)) (define (oprintf . args) (apply fprintf op args)) (define-unit module-language-tools@ (import [prefix drracket:unit: drracket:unit^] [prefix drracket:module-language: drracket:module-language/int^] [prefix drracket:language: drracket:language^] [prefix drracket:language-configuration: drracket:language-configuration^] [prefix drracket:init: drracket:init/int^] [prefix drracket:rep: drracket:rep^] [prefix drracket: drracket:interface^]) (export drracket:module-language-tools/int^) (define-struct opt-in/out-toolbar-button (make-button id number) #:transparent) (define opt-out-toolbar-buttons '()) (define opt-in-toolbar-buttons '()) (define (add-opt-out-toolbar-button make-button id #:number [number #f]) (set! opt-out-toolbar-buttons (cons (make-opt-in/out-toolbar-button make-button id number) opt-out-toolbar-buttons))) (define (add-opt-in-toolbar-button make-button id #:number [number #f]) (set! opt-in-toolbar-buttons (cons (make-opt-in/out-toolbar-button make-button id number) opt-in-toolbar-buttons))) (define-local-member-name set-lang-toolbar-buttons get-lang-toolbar-buttons remove-toolbar-button get-toolbar-button-panel get-online-expansion-monitor-pcs with-language-specific-default-extensions-and-filters get-hash-lang-error-state set-hash-lang-error-state update-hash-lang-error-gui-state) (define tab-mixin (mixin (drracket:unit:tab<%>) (drracket:module-language-tools:tab<%>) (inherit get-frame) (define toolbar-buttons '()) (define/public (get-lang-toolbar-buttons) toolbar-buttons) (define/public (set-lang-toolbar-buttons bs ns) (for-each (λ (old-button) (send (get-frame) remove-toolbar-button old-button)) toolbar-buttons) (set! toolbar-buttons bs) (send (get-frame) register-toolbar-buttons toolbar-buttons #:numbers ns) (send (get-frame) when-initialized (λ () (send (send (get-frame) get-toolbar-button-panel) change-children (λ (l) toolbar-buttons)))) (send (get-frame) sort-toolbar-buttons-panel)) (define the-hash-lang-error-state #f) (define/public (get-hash-lang-error-state) the-hash-lang-error-state) (define/public (set-hash-lang-error-state s) (set! the-hash-lang-error-state s) (when (equal? (send (get-frame) get-current-tab) this) (send (get-frame) update-hash-lang-error-gui-state the-hash-lang-error-state))) (define/public (show-#lang-error) (message-box (string-constant drracket) (hash-lang-error-state-more-info-msg the-hash-lang-error-state))) (super-new))) (define frame-mixin (mixin (drracket:unit:frame<%>) (drracket:module-language-tools:frame<%>) (inherit unregister-toolbar-button get-definitions-text sort-toolbar-buttons-panel get-current-tab) (define toolbar-button-panel #f) (define/public (when-initialized thunk) (cond [toolbar-button-panel (thunk)] [else (set! after-initialized (let ([old-after-initialized after-initialized]) (λ () (old-after-initialized) (thunk))))])) (define after-initialized void) (define/public (get-toolbar-button-panel) toolbar-button-panel) (define/public (remove-toolbar-button button) (send toolbar-button-panel change-children (λ (l) (remq button l))) (unregister-toolbar-button button) (sort-toolbar-buttons-panel)) (define/augment (on-tab-change old-tab new-tab) (inner (void) on-tab-change old-tab new-tab) (when toolbar-button-panel (send toolbar-button-panel change-children (λ (l) (send new-tab get-lang-toolbar-buttons))) (sort-toolbar-buttons-panel)) (when hash-lang-error-parent-panel (unless (equal? (send new-tab get-hash-lang-error-state) (send old-tab get-hash-lang-error-state)) (update-hash-lang-error-gui-state (send new-tab get-hash-lang-error-state))))) (define/override (file-menu:open-callback menu evt) (send (get-definitions-text) with-language-specific-default-extensions-and-filters (λ () (super file-menu:open-callback menu evt)))) (define hash-lang-error-parent-panel #f) (define hash-lang-error-panel #f) (define hash-lang-error-message #f) ;; state : (or/c hash-lang-error-state? #f) ;; -- string is the error message (define/public (update-hash-lang-error-gui-state state) (cond [(hash-lang-error-state? state) (send hash-lang-error-message set-msgs (list (hash-lang-error-state-display-msg state)) #t (hash-lang-error-state-more-info-msg state) '()) (send hash-lang-error-parent-panel change-children (λ (x) (append (remq hash-lang-error-panel x) (list hash-lang-error-panel))))] [else (send hash-lang-error-parent-panel change-children (λ (x) (remq hash-lang-error-panel x)))])) (define/override (make-root-area-container cls parent) (set! hash-lang-error-parent-panel (super make-root-area-container vertical-pane% parent)) (define root (make-object cls hash-lang-error-parent-panel)) (set! hash-lang-error-panel (new-horizontal-panel% [stretchable-height #f] [parent hash-lang-error-parent-panel])) (new message% [label "#lang "] [parent hash-lang-error-panel]) (set! hash-lang-error-message (new drracket:module-language:error-message% [parent hash-lang-error-panel] [stretchable-width #t] [msgs '("hi")] [err? #f])) (new button% [parent hash-lang-error-panel] [label (string-append (string-constant module-language-#lang-flush-cache) (case (car (get-default-shortcut-prefix)) [(cmd) (if (equal? (system-type) 'macosx) " (⌘⇧D)" "")] [(control) " (Ctrl+Shift-D)"] [else ""]))] [font small-control-font] [callback (λ (b evt) (send (send (get-current-tab) get-defs) move-to-new-language #t))]) (new button% [parent hash-lang-error-panel] [label (string-constant module-language-#lang-error-more-information)] [font small-control-font] [callback (λ (b evt) (send (get-current-tab) show-#lang-error))]) (new close-icon% [parent hash-lang-error-panel] [callback (λ () (send (get-current-tab) set-hash-lang-error-state #f))]) (send hash-lang-error-parent-panel change-children (λ (l) (remq hash-lang-error-panel l))) root) (super-new) (inherit get-button-panel) (set! toolbar-button-panel (new panel:horizontal-discrete-sizes% [parent (get-button-panel)] [alignment '(right center)] [stretchable-width #t])) (after-initialized) (set! after-initialized void) (define/public (initialize-module-language) (let ([defs (get-definitions-text)]) (when (send defs get-in-module-language?) (send defs move-to-new-language)))))) (struct hash-lang-error-state (display-msg more-info-msg) #:transparent) (define-local-member-name range-indent) (define ml-tools-text<%> (interface () range-indent)) (define ml-tools-text-mixin (mixin (text:basic<%>) (ml-tools-text<%>) (inherit position-paragraph paragraph-start-position delete insert begin-edit-sequence end-edit-sequence) (define/public (range-indent range-indentation-function start end) (define substs (range-indentation-function this start end)) (and substs (let () (define start-line (position-paragraph start #f)) (define end-line (position-paragraph end #t)) (begin-edit-sequence) (let loop ([substs substs] [line start-line]) (unless (or (null? substs) (line . > . end-line)) (define pos (paragraph-start-position line)) (define del-amt (caar substs)) (define insert-str (cadar substs)) (unless (zero? del-amt) (delete pos (+ pos del-amt))) (unless (equal? insert-str "") (insert insert-str pos)) (loop (cdr substs) (add1 line)))) (end-edit-sequence) #t))) (super-new))) (define (interactions-text-mixin t) (only-interactions-text-mixin (ml-tools-text-mixin t))) (define only-interactions-text-mixin (mixin (racket:text<%> drracket:rep:text<%> ml-tools-text<%>) () (inherit get-definitions-text compute-racket-amount-to-indent get-start-position get-end-position range-indent last-position get-surrogate set-surrogate) (define/augment (compute-amount-to-indent pos) (define defs (get-definitions-text)) (cond [(send defs get-in-module-language?) (or ((send defs get-indentation-function) this pos) (compute-racket-amount-to-indent pos))] [else (compute-racket-amount-to-indent pos)])) (define/override (tabify-selection [start (get-start-position)] [end (get-end-position)]) (define defs (get-definitions-text)) (unless (and (send defs get-in-module-language?) (range-indent (send defs get-range-indentation-function) start end)) (super tabify-selection start end))) (define/override (tabify-all) (define defs (get-definitions-text)) (unless (and (send defs get-in-module-language?) (range-indent (send defs get-range-indentation-function) 0 (last-position))) (super tabify-all))) (define/override (reset-console) (when (send (get-definitions-text) get-in-module-language?) (define ints-surrogate (get-surrogate)) (when ints-surrogate ;; when ints-surrogate is #f, then we ;; should in a language other than the module ;; language so we can safely skip this (define the-irl (send (get-definitions-text) get-irl)) (send ints-surrogate set-get-token (call-read-language the-irl 'color-lexer (waive-option module-lexer))) (send ints-surrogate set-matches (call-read-language the-irl 'drracket:paren-matches racket:default-paren-matches)) (set-surrogate ints-surrogate))) (super reset-console)) (super-new))) (define (definitions-text-mixin t) (only-definitions-text-mixin (ml-tools-text-mixin t))) (define only-definitions-text-mixin (mixin (text:basic<%> racket:text<%> drracket:unit:definitions-text<%> drracket:module-language:big-defs/ints-label<%> ml-tools-text<%>) (drracket:module-language-tools:definitions-text<%>) (inherit get-next-settings range-indent get-filename set-lang-wants-big-defs/ints-labels? get-tab last-position get-start-position get-end-position insert delete begin-edit-sequence end-edit-sequence position-paragraph paragraph-start-position set-surrogate get-keymap) (define in-module-language? #f) ;; true when we are in the module language (define hash-lang-language #f) ;; non-false is the string that was parsed for the language ;; non-false means that an edit before this location ;; means that the language might have changed ;; (this will be the end of the #lang line if there is one, ;; or it will be some conservative place if there isn't) (define hash-lang-last-location #f) ;; the region between 0 and `hash-lang-comment-end-position` (unless it is #f) ;; is known to be a comment and so edits there might not change the #lang line ;; if `hash-lang-comment-end-position` is #f, then we don't have a comment region to track and so all edits before ` hash - lang - last - location ` will reload the # lang extensions (define hash-lang-comment-end-position #f) (define/private (set-hash-lang-comment-end+last-location _hash-lang-last-location _hash-lang-comment-end-position) (unless (or (and (not _hash-lang-last-location) (not _hash-lang-comment-end-position)) (and (natural? _hash-lang-last-location) (natural? _hash-lang-comment-end-position) (<= _hash-lang-comment-end-position _hash-lang-last-location))) (error 'set-hash-lang-comment-end+last-location (string-append "hash-lang-last-location and hash-lang-comment-end-position invariant broken;\n" " expected both to be #f or the comment-end to precede the last\n" " hash-lang-last-location: ~s\n" " hash-lang-comment-end-position: ~s") _hash-lang-last-location _hash-lang-comment-end-position)) (set! hash-lang-last-location _hash-lang-last-location) (set! hash-lang-comment-end-position _hash-lang-comment-end-position)) (define/public (irl-get-read-language-port-start+end) (get-read-language-port-start+end the-irl)) (define/public (irl-get-read-language-name) (get-read-language-name the-irl)) (define/private (irl-blew-up exn) (define sp (open-output-string)) (parameterize ([current-error-port sp]) (drracket:init:original-error-display-handler (exn-message exn) exn)) (send (get-tab) set-hash-lang-error-state (hash-lang-error-state (regexp-replace* #rx"\n" (exn-message exn) " ") (get-output-string sp)))) (define/public (get-in-module-language?) in-module-language?) (define/augment (after-insert start len) (inner (void) after-insert start len) (when (and hash-lang-last-location hash-lang-comment-end-position) (cond [(<= start hash-lang-comment-end-position) (set-hash-lang-comment-end+last-location (+ hash-lang-last-location len) (+ hash-lang-comment-end-position len))] [(<= start hash-lang-last-location) (set-hash-lang-comment-end+last-location (+ hash-lang-last-location len) hash-lang-comment-end-position)])) (modification-at start)) (define/augment (after-delete start len) (inner (void) after-delete start len) (when (and hash-lang-last-location hash-lang-comment-end-position) (cond [(<= (+ start len) hash-lang-comment-end-position) ;; a deletion entirely inside the comment region, so we optimistically ;; update `hash-lang-comment-end-position` and `hash-lang-last-location` ;; and the comment check in `modification-at` will confirm (set-hash-lang-comment-end+last-location (- hash-lang-last-location len) (- hash-lang-comment-end-position len))] [(> start hash-lang-last-location) ;; here the deletion is entirely after and so we don't need to update anything (void)] [else ;; here the deletion spans the end of the comment region and possibly the lang line . Just give up and reload # lang extensions (set-hash-lang-comment-end+last-location #f #f)])) (modification-at start)) (define/augment (after-save-file success?) (inner (void) after-save-file success?) (when success? (filename-maybe-changed))) (define/augment (after-load-file success?) (inner (void) after-load-file success?) (when success? (filename-maybe-changed))) (define last-filename #f) (define/private (filename-maybe-changed) (define this-filename (get-filename)) (unless (equal? last-filename this-filename) (set! last-filename this-filename) (modification-at #f))) (define timer #f) ;; modification-at : (or/c #f number) -> void ;; checks to see if the lang line has changed when start is in the region of the lang line , or when start is # f , or ;; when there is no #lang line known. (define/private (modification-at start) (define (start-the-move-to-new-language-timer) (unless timer (set! timer (new logging-timer% [notify-callback (λ () (when in-module-language? (move-to-new-language)))] [just-once? #t]))) (send timer stop) (send timer start 200 #t)) (send (send (get-tab) get-frame) when-initialized (λ () (when in-module-language? (when (or (not start) (not hash-lang-last-location) (<= start hash-lang-last-location)) (cond [(and start hash-lang-last-location hash-lang-comment-end-position (<= start hash-lang-comment-end-position)) (define prt (open-input-text-editor this)) (port-count-lines! prt) (skip-past-comments prt) (define-values (_1 _2 current-end-of-comments+1) (port-next-location prt)) (unless (= hash-lang-comment-end-position (- current-end-of-comments+1 1)) (start-the-move-to-new-language-timer))] [else (start-the-move-to-new-language-timer)])))))) (define/private (update-in-module-language? new-one) (unless (equal? new-one in-module-language?) (set! in-module-language? new-one) (cond [in-module-language? (move-to-new-language)] [else (set! hash-lang-language #f) (set-hash-lang-comment-end+last-location #f #f) (clear-things-out)]))) (define/public (move-to-new-language [flush-irl-cache? #f]) (when timer (send timer stop)) (send (get-tab) set-hash-lang-error-state #f) (define port (open-input-text-editor this)) (reset-irl! the-irl port (get-irl-directory) flush-irl-cache?) (set!-values (hash-lang-comment-end-position hash-lang-last-location) (get-read-language-port-start+end the-irl)) (set! hash-lang-language (and hash-lang-last-location (get-text hash-lang-comment-end-position hash-lang-last-location))) (when hash-lang-language (preferences:set 'drracket:most-recent-lang-line (string-append hash-lang-language "\n"))) (unless hash-lang-last-location (set-hash-lang-comment-end+last-location (get-read-language-last-position the-irl) 0)) (clear-things-out) (define mode (or (get-definitions-text-surrogate the-irl) (new racket:text-mode% [include-paren-keymap? #f]))) (send mode set-get-token (get-insulated-module-lexer the-irl)) (define paren-matches (call-read-language the-irl 'drracket:paren-matches racket:default-paren-matches)) (send mode set-matches paren-matches) (set-surrogate mode) (define lang-wants-big-defs/ints-labels? (and (call-read-language the-irl 'drracket:show-big-defs/ints-labels #f) #t)) (set-lang-wants-big-defs/ints-labels? lang-wants-big-defs/ints-labels?) (send (send (get-tab) get-ints) set-lang-wants-big-defs/ints-labels? lang-wants-big-defs/ints-labels?) (set! extra-default-filters (or (call-read-language the-irl 'drracket:default-filters #f) '())) (set! default-extension (or (call-read-language the-irl 'drracket:default-extension #f) "")) (set! indentation-function (or (call-read-language the-irl 'drracket:indentation #f) (λ (x y) #f))) (set! range-indentation-function (or (call-read-language the-irl 'drracket:range-indentation #f) (λ (x y z) #f))) (set! grouping-position (or (call-read-language the-irl 'drracket:grouping-position #f) default-grouping-position)) (set! lang-keymap (new keymap:aug-keymap%)) (for ([key+proc (in-list (call-read-language the-irl 'drracket:keystrokes '()))]) (define key (list-ref key+proc 0)) (define proc (list-ref key+proc 1)) (define name (let loop ([counter #f]) (define name (if counter (~a (object-name proc) counter) (~a (object-name proc)))) (cond [(send lang-keymap is-function-added? name) (loop (+ (or counter 0) 1))] [else name]))) (send lang-keymap add-function name proc) (send lang-keymap map-function key name)) (send lang-keymap chain-to-keymap (make-paren-matches-keymap paren-matches (call-read-language the-irl 'drracket:quote-matches (list #\" #\|))) #t) (send (get-keymap) chain-to-keymap lang-keymap #t) (register-new-buttons (or (call-read-language the-irl 'drracket:toolbar-buttons #f) (call-read-language the-irl 'drscheme:toolbar-buttons #f)) (let ([drracket-opt-out (call-read-language the-irl 'drracket:opt-out-toolbar-buttons '())] [drscheme-opt-out (call-read-language the-irl 'drscheme:opt-out-toolbar-buttons '())]) (and drracket-opt-out drscheme-opt-out (append drracket-opt-out drscheme-opt-out))) (call-read-language the-irl 'drracket:opt-in-toolbar-buttons '()))) ;; removes language-specific customizations (define/private (clear-things-out) (define tab (get-tab)) (define ints (send tab get-ints)) (set-surrogate (new racket:text-mode%)) (send ints set-surrogate (new racket:text-mode%)) (set-lang-wants-big-defs/ints-labels? #f) (send ints set-lang-wants-big-defs/ints-labels? #f) (set! extra-default-filters '()) (set! default-extension "") (set! indentation-function (λ (x y) #f)) (set! range-indentation-function (λ (x y z) #f)) (set! grouping-position default-grouping-position) (when lang-keymap (send (get-keymap) remove-chained-keymap lang-keymap) (set! lang-keymap #f)) (send tab set-lang-toolbar-buttons '() '())) (define/private (register-new-buttons buttons opt-out-ids opt-in-ids) cleaned - up - buttons : ( listof ( list / c string ? ;; (is-a?/c bitmap%) ;; (-> (is-a?/c drracket:unit:frame<%>) any) ;; (or/c real? #f))) (define cleaned-up-buttons (cond [(not buttons) '()] [else (for/list ([button (in-list buttons)]) (if (= 3 (length button)) (append button (list #f)) button))])) (define tab (get-tab)) (define frame (send tab get-frame)) (send frame when-initialized (λ () (send frame begin-container-sequence) ;; avoid any time with both sets of buttons in the ;; panel so the window doesn't get too wide (send (send frame get-toolbar-button-panel) change-children (λ (prev) '())) (define directly-specified-buttons (map (λ (button-spec) (new switchable-button% [label (list-ref button-spec 0)] [bitmap (list-ref button-spec 1)] [parent (send frame get-toolbar-button-panel)] [callback (lambda (button) ((list-ref button-spec 2) frame))])) cleaned-up-buttons)) (define directly-specified-button-numbers (map (λ (button-spec) (list-ref button-spec 3)) cleaned-up-buttons)) (define (get-opt-in/out-buttons+numbers opt-in?) (define (flip? b) (if opt-in? (not b) b)) (define opt-in/out-ids (if opt-in? opt-in-ids opt-out-ids)) (define opt-in/out-toolbar-buttons (if opt-in? opt-in-toolbar-buttons opt-out-toolbar-buttons)) (cond [(eq? opt-in/out-ids #f) '()] [else (for/list ([opt-in/out-toolbar-button (in-list opt-in/out-toolbar-buttons)] #:unless (flip? (member (opt-in/out-toolbar-button-id opt-in/out-toolbar-button) opt-in/out-ids))) (list ((opt-in/out-toolbar-button-make-button opt-in/out-toolbar-button) frame (send frame get-toolbar-button-panel)) (opt-in/out-toolbar-button-number opt-in/out-toolbar-button)))])) (define opt-out-buttons+numbers (get-opt-in/out-buttons+numbers #f)) (define opt-in-buttons+numbers (get-opt-in/out-buttons+numbers #t)) (send tab set-lang-toolbar-buttons (append directly-specified-buttons (map (λ (x) (list-ref x 0)) opt-out-buttons+numbers) (map (λ (x) (list-ref x 0)) opt-in-buttons+numbers)) (append directly-specified-button-numbers (map (λ (x) (list-ref x 1)) opt-out-buttons+numbers) (map (λ (x) (list-ref x 1)) opt-in-buttons+numbers))) (send frame end-container-sequence)))) (inherit get-text) (define/private (get-lang-name pos) (cond [(zero? pos) '<<unknown>>] [else (let ([str (get-text 0 pos)]) (if (char-whitespace? (string-ref str (- (string-length str) 1))) (substring str 0 (- (string-length str) 1)) str))])) ;; online-expansion-monitor-table : hash[(cons mod-path id) -o> (cons/c local-pc remote-pc)] (define online-expansion-monitor-table (make-hash)) (define/public (get-online-expansion-monitor-pcs an-online-expansion-handler) (define key (cons (online-expansion-handler-mod-path an-online-expansion-handler) (online-expansion-handler-id an-online-expansion-handler))) (define old (hash-ref online-expansion-monitor-table key #f)) (cond [old (values (car old) (cdr old))] [else (define-values (local-pc remote-pc) (place-channel)) (hash-set! online-expansion-monitor-table key (cons local-pc remote-pc)) (values local-pc remote-pc)])) (define/augment (after-set-next-settings settings) (update-in-module-language? (is-a? (drracket:language-configuration:language-settings-language settings) drracket:module-language:module-language<%>)) (inner (void) after-set-next-settings settings)) (define/override (put-file dir default-name) (with-language-specific-default-extensions-and-filters (λ () (super put-file dir default-name)))) (define/override (get-file dir) (with-language-specific-default-extensions-and-filters (λ () (super get-file dir)))) (define extra-default-filters '()) (define default-extension "") (define indentation-function (λ (x y) #f)) (define/public (get-indentation-function) indentation-function) (define range-indentation-function (λ (x y z) #f)) (define/public (get-range-indentation-function) range-indentation-function) (define grouping-position default-grouping-position) (define lang-keymap #f) (define/public (with-language-specific-default-extensions-and-filters t) (parameterize ([finder:default-extension default-extension] [finder:default-filters (append extra-default-filters (finder:default-filters))]) (t))) (inherit compute-racket-amount-to-indent) (define/augment (compute-amount-to-indent pos) (cond [in-module-language? (or (indentation-function this pos) (compute-racket-amount-to-indent pos))] [else (compute-racket-amount-to-indent pos)])) (define/override (tabify-selection [start (get-start-position)] [end (get-end-position)]) (unless (and in-module-language? (range-indent range-indentation-function start end)) (super tabify-selection start end))) (define/override (tabify-all) (unless (and in-module-language? (range-indent range-indentation-function 0 (last-position))) (super tabify-all))) (define/override (find-up-sexp start-pos) (*-sexp start-pos 'up (λ () (super find-up-sexp start-pos)))) (define/override (find-down-sexp start-pos) (*-sexp start-pos 'down (λ () (super find-down-sexp start-pos)))) (define/override (get-backward-sexp start-pos) (*-sexp start-pos 'backward (λ () (super get-backward-sexp start-pos)))) (define/override (get-forward-sexp start-pos) (*-sexp start-pos 'forward (λ () (super get-forward-sexp start-pos)))) (inherit get-limit) (define/private (*-sexp start-pos direction do-super) (define irl-answer (grouping-position this start-pos (get-limit start-pos) direction)) (cond [(equal? irl-answer #t) (do-super)] [else irl-answer])) (define/private (get-irl-directory) (define tmp-b (box #f)) (define fn (get-filename tmp-b)) (when (unbox tmp-b) (set! fn #f)) (define the-dir (get-init-dir fn)) the-dir) (super-new) (define the-irl (make-irl (get-irl-directory) (λ (exn) (irl-blew-up exn)))) (define/public (get-irl) the-irl) (set! in-module-language? (is-a? (drracket:language-configuration:language-settings-language (get-next-settings)) drracket:module-language:module-language<%>)))) (define paren-matches-keymaps (make-hash)) (define (make-paren-matches-keymap paren-matches quote-matches) (define keymap-cache-key (cons paren-matches quote-matches)) (cond [(hash-ref paren-matches-keymaps keymap-cache-key #f) => car] [else (define keymap (new keymap:aug-keymap%)) (define alt-as-meta-keymap (new keymap:aug-keymap%)) (for ([paren-match (in-list paren-matches)]) (define open-str (symbol->string (list-ref paren-match 0))) (define close-str (symbol->string (list-ref paren-match 1))) (when (and (= 1 (string-length open-str)) (= 1 (string-length close-str))) (racket:map-pairs-keybinding-functions keymap (string-ref open-str 0) (string-ref close-str 0) #:alt-as-meta-keymap alt-as-meta-keymap))) (for ([c (in-list quote-matches)]) (racket:map-pairs-keybinding-functions keymap c c)) (when (> (hash-count paren-matches-keymaps) 20) (set! paren-matches-keymaps (make-hash))) (hash-set! paren-matches-keymaps keymap-cache-key (list keymap alt-as-meta-keymap)) (when (preferences:get 'framework:alt-as-meta) (send keymap chain-to-keymap alt-as-meta-keymap #f)) keymap])) (define (adjust-alt-as-meta on?) (for ([(_ keymap+alt-as-meta-keymap) (in-hash paren-matches-keymaps)]) (define-values (keymap alt-as-meta-keymap) (apply values keymap+alt-as-meta-keymap)) (send keymap remove-chained-keymap alt-as-meta-keymap) (when on? (send keymap chain-to-keymap alt-as-meta-keymap #f)))) (preferences:add-callback 'framework:alt-as-meta (λ (p v) (adjust-alt-as-meta v))) (define default-grouping-position (λ (text start limit dir) #t)) (define no-more-online-expansion-handlers? #f) (define (no-more-online-expansion-handlers) (set! no-more-online-expansion-handlers? #t)) (define-values (done done?) (let () (struct done ()) (values (done) done?))) (define-values (start start?) (let () (struct start ()) (values (start) start?))) ;; mod-path : module-path? ;; id : symbol? ;; local-handler : ... -> ... (struct online-expansion-handler (mod-path id local-handler monitor?)) (define online-expansion-handlers '()) (define (get-online-expansion-handlers) (cond [no-more-online-expansion-handlers? online-expansion-handlers] [else (error 'get-online-expansion-handlers "online-expansion-handlers can still be registered")])) (define (add-online-expansion-handler mod-path id local-handler) (check-bad-registration 'add-online-expansion-handler mod-path id local-handler) (set! online-expansion-handlers (cons (online-expansion-handler mod-path id local-handler #f) online-expansion-handlers))) (define (add-online-expansion-monitor mod-path id local-handler) (check-bad-registration 'add-online-expansion-monitor mod-path id local-handler) (set! online-expansion-handlers (cons (online-expansion-handler mod-path id local-handler #t) online-expansion-handlers))) (define (check-bad-registration who mod-path id local-handler) (when no-more-online-expansion-handlers? (error who "no more online-expansion-handlers can be registered; got ~e ~e ~e" mod-path id local-handler)) (for ([handler (in-list online-expansion-handlers)]) (when (and (equal? (online-expansion-handler-mod-path handler) mod-path) (equal? (online-expansion-handler-id handler) id)) (error who (string-append "already registered a handler with the same mod-path and id\n" " mod-path: ~e\n" " id: ~e") mod-path id)))) (define online-expansion-pref-funcs '()) (define (get-online-expansion-pref-funcs) online-expansion-pref-funcs) (define online-expansion-prefs '()) (define (register-online-expansion-pref func) (set! online-expansion-pref-funcs (cons func online-expansion-pref-funcs))))
null
https://raw.githubusercontent.com/racket/drracket/a6f6392b6d95c717db9c5fd0c1325444d23b60d9/drracket/drracket/private/module-language-tools.rkt
racket
state : (or/c hash-lang-error-state? #f) -- string is the error message when ints-surrogate is #f, then we should in a language other than the module language so we can safely skip this true when we are in the module language non-false is the string that was parsed for the language non-false means that an edit before this location means that the language might have changed (this will be the end of the #lang line if there is one, or it will be some conservative place if there isn't) the region between 0 and `hash-lang-comment-end-position` (unless it is #f) is known to be a comment and so edits there might not change the #lang line if `hash-lang-comment-end-position` is #f, then we don't have a comment region to track a deletion entirely inside the comment region, so we optimistically update `hash-lang-comment-end-position` and `hash-lang-last-location` and the comment check in `modification-at` will confirm here the deletion is entirely after and so we don't need to update anything here the deletion spans the end of the comment region and possibly modification-at : (or/c #f number) -> void checks to see if the lang line has changed when start when there is no #lang line known. removes language-specific customizations (is-a?/c bitmap%) (-> (is-a?/c drracket:unit:frame<%>) any) (or/c real? #f))) avoid any time with both sets of buttons in the panel so the window doesn't get too wide online-expansion-monitor-table : hash[(cons mod-path id) -o> (cons/c local-pc remote-pc)] mod-path : module-path? id : symbol? local-handler : ... -> ...
#lang racket/base (provide module-language-tools@) (require mrlib/switchable-button mrlib/bitmap-label mrlib/close-icon racket/contract racket/contract/option racket/place racket/format racket/unit racket/class racket/math racket/gui/base syntax-color/module-lexer framework framework/private/srcloc-panel framework/private/logging-timer drracket/private/drsig "local-member-names.rkt" "insulated-read-language.rkt" "eval-helpers-and-pref-init.rkt" string-constants) (define op (current-output-port)) (define (oprintf . args) (apply fprintf op args)) (define-unit module-language-tools@ (import [prefix drracket:unit: drracket:unit^] [prefix drracket:module-language: drracket:module-language/int^] [prefix drracket:language: drracket:language^] [prefix drracket:language-configuration: drracket:language-configuration^] [prefix drracket:init: drracket:init/int^] [prefix drracket:rep: drracket:rep^] [prefix drracket: drracket:interface^]) (export drracket:module-language-tools/int^) (define-struct opt-in/out-toolbar-button (make-button id number) #:transparent) (define opt-out-toolbar-buttons '()) (define opt-in-toolbar-buttons '()) (define (add-opt-out-toolbar-button make-button id #:number [number #f]) (set! opt-out-toolbar-buttons (cons (make-opt-in/out-toolbar-button make-button id number) opt-out-toolbar-buttons))) (define (add-opt-in-toolbar-button make-button id #:number [number #f]) (set! opt-in-toolbar-buttons (cons (make-opt-in/out-toolbar-button make-button id number) opt-in-toolbar-buttons))) (define-local-member-name set-lang-toolbar-buttons get-lang-toolbar-buttons remove-toolbar-button get-toolbar-button-panel get-online-expansion-monitor-pcs with-language-specific-default-extensions-and-filters get-hash-lang-error-state set-hash-lang-error-state update-hash-lang-error-gui-state) (define tab-mixin (mixin (drracket:unit:tab<%>) (drracket:module-language-tools:tab<%>) (inherit get-frame) (define toolbar-buttons '()) (define/public (get-lang-toolbar-buttons) toolbar-buttons) (define/public (set-lang-toolbar-buttons bs ns) (for-each (λ (old-button) (send (get-frame) remove-toolbar-button old-button)) toolbar-buttons) (set! toolbar-buttons bs) (send (get-frame) register-toolbar-buttons toolbar-buttons #:numbers ns) (send (get-frame) when-initialized (λ () (send (send (get-frame) get-toolbar-button-panel) change-children (λ (l) toolbar-buttons)))) (send (get-frame) sort-toolbar-buttons-panel)) (define the-hash-lang-error-state #f) (define/public (get-hash-lang-error-state) the-hash-lang-error-state) (define/public (set-hash-lang-error-state s) (set! the-hash-lang-error-state s) (when (equal? (send (get-frame) get-current-tab) this) (send (get-frame) update-hash-lang-error-gui-state the-hash-lang-error-state))) (define/public (show-#lang-error) (message-box (string-constant drracket) (hash-lang-error-state-more-info-msg the-hash-lang-error-state))) (super-new))) (define frame-mixin (mixin (drracket:unit:frame<%>) (drracket:module-language-tools:frame<%>) (inherit unregister-toolbar-button get-definitions-text sort-toolbar-buttons-panel get-current-tab) (define toolbar-button-panel #f) (define/public (when-initialized thunk) (cond [toolbar-button-panel (thunk)] [else (set! after-initialized (let ([old-after-initialized after-initialized]) (λ () (old-after-initialized) (thunk))))])) (define after-initialized void) (define/public (get-toolbar-button-panel) toolbar-button-panel) (define/public (remove-toolbar-button button) (send toolbar-button-panel change-children (λ (l) (remq button l))) (unregister-toolbar-button button) (sort-toolbar-buttons-panel)) (define/augment (on-tab-change old-tab new-tab) (inner (void) on-tab-change old-tab new-tab) (when toolbar-button-panel (send toolbar-button-panel change-children (λ (l) (send new-tab get-lang-toolbar-buttons))) (sort-toolbar-buttons-panel)) (when hash-lang-error-parent-panel (unless (equal? (send new-tab get-hash-lang-error-state) (send old-tab get-hash-lang-error-state)) (update-hash-lang-error-gui-state (send new-tab get-hash-lang-error-state))))) (define/override (file-menu:open-callback menu evt) (send (get-definitions-text) with-language-specific-default-extensions-and-filters (λ () (super file-menu:open-callback menu evt)))) (define hash-lang-error-parent-panel #f) (define hash-lang-error-panel #f) (define hash-lang-error-message #f) (define/public (update-hash-lang-error-gui-state state) (cond [(hash-lang-error-state? state) (send hash-lang-error-message set-msgs (list (hash-lang-error-state-display-msg state)) #t (hash-lang-error-state-more-info-msg state) '()) (send hash-lang-error-parent-panel change-children (λ (x) (append (remq hash-lang-error-panel x) (list hash-lang-error-panel))))] [else (send hash-lang-error-parent-panel change-children (λ (x) (remq hash-lang-error-panel x)))])) (define/override (make-root-area-container cls parent) (set! hash-lang-error-parent-panel (super make-root-area-container vertical-pane% parent)) (define root (make-object cls hash-lang-error-parent-panel)) (set! hash-lang-error-panel (new-horizontal-panel% [stretchable-height #f] [parent hash-lang-error-parent-panel])) (new message% [label "#lang "] [parent hash-lang-error-panel]) (set! hash-lang-error-message (new drracket:module-language:error-message% [parent hash-lang-error-panel] [stretchable-width #t] [msgs '("hi")] [err? #f])) (new button% [parent hash-lang-error-panel] [label (string-append (string-constant module-language-#lang-flush-cache) (case (car (get-default-shortcut-prefix)) [(cmd) (if (equal? (system-type) 'macosx) " (⌘⇧D)" "")] [(control) " (Ctrl+Shift-D)"] [else ""]))] [font small-control-font] [callback (λ (b evt) (send (send (get-current-tab) get-defs) move-to-new-language #t))]) (new button% [parent hash-lang-error-panel] [label (string-constant module-language-#lang-error-more-information)] [font small-control-font] [callback (λ (b evt) (send (get-current-tab) show-#lang-error))]) (new close-icon% [parent hash-lang-error-panel] [callback (λ () (send (get-current-tab) set-hash-lang-error-state #f))]) (send hash-lang-error-parent-panel change-children (λ (l) (remq hash-lang-error-panel l))) root) (super-new) (inherit get-button-panel) (set! toolbar-button-panel (new panel:horizontal-discrete-sizes% [parent (get-button-panel)] [alignment '(right center)] [stretchable-width #t])) (after-initialized) (set! after-initialized void) (define/public (initialize-module-language) (let ([defs (get-definitions-text)]) (when (send defs get-in-module-language?) (send defs move-to-new-language)))))) (struct hash-lang-error-state (display-msg more-info-msg) #:transparent) (define-local-member-name range-indent) (define ml-tools-text<%> (interface () range-indent)) (define ml-tools-text-mixin (mixin (text:basic<%>) (ml-tools-text<%>) (inherit position-paragraph paragraph-start-position delete insert begin-edit-sequence end-edit-sequence) (define/public (range-indent range-indentation-function start end) (define substs (range-indentation-function this start end)) (and substs (let () (define start-line (position-paragraph start #f)) (define end-line (position-paragraph end #t)) (begin-edit-sequence) (let loop ([substs substs] [line start-line]) (unless (or (null? substs) (line . > . end-line)) (define pos (paragraph-start-position line)) (define del-amt (caar substs)) (define insert-str (cadar substs)) (unless (zero? del-amt) (delete pos (+ pos del-amt))) (unless (equal? insert-str "") (insert insert-str pos)) (loop (cdr substs) (add1 line)))) (end-edit-sequence) #t))) (super-new))) (define (interactions-text-mixin t) (only-interactions-text-mixin (ml-tools-text-mixin t))) (define only-interactions-text-mixin (mixin (racket:text<%> drracket:rep:text<%> ml-tools-text<%>) () (inherit get-definitions-text compute-racket-amount-to-indent get-start-position get-end-position range-indent last-position get-surrogate set-surrogate) (define/augment (compute-amount-to-indent pos) (define defs (get-definitions-text)) (cond [(send defs get-in-module-language?) (or ((send defs get-indentation-function) this pos) (compute-racket-amount-to-indent pos))] [else (compute-racket-amount-to-indent pos)])) (define/override (tabify-selection [start (get-start-position)] [end (get-end-position)]) (define defs (get-definitions-text)) (unless (and (send defs get-in-module-language?) (range-indent (send defs get-range-indentation-function) start end)) (super tabify-selection start end))) (define/override (tabify-all) (define defs (get-definitions-text)) (unless (and (send defs get-in-module-language?) (range-indent (send defs get-range-indentation-function) 0 (last-position))) (super tabify-all))) (define/override (reset-console) (when (send (get-definitions-text) get-in-module-language?) (define ints-surrogate (get-surrogate)) (when ints-surrogate (define the-irl (send (get-definitions-text) get-irl)) (send ints-surrogate set-get-token (call-read-language the-irl 'color-lexer (waive-option module-lexer))) (send ints-surrogate set-matches (call-read-language the-irl 'drracket:paren-matches racket:default-paren-matches)) (set-surrogate ints-surrogate))) (super reset-console)) (super-new))) (define (definitions-text-mixin t) (only-definitions-text-mixin (ml-tools-text-mixin t))) (define only-definitions-text-mixin (mixin (text:basic<%> racket:text<%> drracket:unit:definitions-text<%> drracket:module-language:big-defs/ints-label<%> ml-tools-text<%>) (drracket:module-language-tools:definitions-text<%>) (inherit get-next-settings range-indent get-filename set-lang-wants-big-defs/ints-labels? get-tab last-position get-start-position get-end-position insert delete begin-edit-sequence end-edit-sequence position-paragraph paragraph-start-position set-surrogate get-keymap) (define hash-lang-last-location #f) and so all edits before ` hash - lang - last - location ` will reload the # lang extensions (define hash-lang-comment-end-position #f) (define/private (set-hash-lang-comment-end+last-location _hash-lang-last-location _hash-lang-comment-end-position) (unless (or (and (not _hash-lang-last-location) (not _hash-lang-comment-end-position)) (and (natural? _hash-lang-last-location) (natural? _hash-lang-comment-end-position) (<= _hash-lang-comment-end-position _hash-lang-last-location))) (error 'set-hash-lang-comment-end+last-location (string-append "hash-lang-last-location and hash-lang-comment-end-position invariant broken;\n" " expected both to be #f or the comment-end to precede the last\n" " hash-lang-last-location: ~s\n" " hash-lang-comment-end-position: ~s") _hash-lang-last-location _hash-lang-comment-end-position)) (set! hash-lang-last-location _hash-lang-last-location) (set! hash-lang-comment-end-position _hash-lang-comment-end-position)) (define/public (irl-get-read-language-port-start+end) (get-read-language-port-start+end the-irl)) (define/public (irl-get-read-language-name) (get-read-language-name the-irl)) (define/private (irl-blew-up exn) (define sp (open-output-string)) (parameterize ([current-error-port sp]) (drracket:init:original-error-display-handler (exn-message exn) exn)) (send (get-tab) set-hash-lang-error-state (hash-lang-error-state (regexp-replace* #rx"\n" (exn-message exn) " ") (get-output-string sp)))) (define/public (get-in-module-language?) in-module-language?) (define/augment (after-insert start len) (inner (void) after-insert start len) (when (and hash-lang-last-location hash-lang-comment-end-position) (cond [(<= start hash-lang-comment-end-position) (set-hash-lang-comment-end+last-location (+ hash-lang-last-location len) (+ hash-lang-comment-end-position len))] [(<= start hash-lang-last-location) (set-hash-lang-comment-end+last-location (+ hash-lang-last-location len) hash-lang-comment-end-position)])) (modification-at start)) (define/augment (after-delete start len) (inner (void) after-delete start len) (when (and hash-lang-last-location hash-lang-comment-end-position) (cond [(<= (+ start len) hash-lang-comment-end-position) (set-hash-lang-comment-end+last-location (- hash-lang-last-location len) (- hash-lang-comment-end-position len))] [(> start hash-lang-last-location) (void)] [else the lang line . Just give up and reload # lang extensions (set-hash-lang-comment-end+last-location #f #f)])) (modification-at start)) (define/augment (after-save-file success?) (inner (void) after-save-file success?) (when success? (filename-maybe-changed))) (define/augment (after-load-file success?) (inner (void) after-load-file success?) (when success? (filename-maybe-changed))) (define last-filename #f) (define/private (filename-maybe-changed) (define this-filename (get-filename)) (unless (equal? last-filename this-filename) (set! last-filename this-filename) (modification-at #f))) (define timer #f) is in the region of the lang line , or when start is # f , or (define/private (modification-at start) (define (start-the-move-to-new-language-timer) (unless timer (set! timer (new logging-timer% [notify-callback (λ () (when in-module-language? (move-to-new-language)))] [just-once? #t]))) (send timer stop) (send timer start 200 #t)) (send (send (get-tab) get-frame) when-initialized (λ () (when in-module-language? (when (or (not start) (not hash-lang-last-location) (<= start hash-lang-last-location)) (cond [(and start hash-lang-last-location hash-lang-comment-end-position (<= start hash-lang-comment-end-position)) (define prt (open-input-text-editor this)) (port-count-lines! prt) (skip-past-comments prt) (define-values (_1 _2 current-end-of-comments+1) (port-next-location prt)) (unless (= hash-lang-comment-end-position (- current-end-of-comments+1 1)) (start-the-move-to-new-language-timer))] [else (start-the-move-to-new-language-timer)])))))) (define/private (update-in-module-language? new-one) (unless (equal? new-one in-module-language?) (set! in-module-language? new-one) (cond [in-module-language? (move-to-new-language)] [else (set! hash-lang-language #f) (set-hash-lang-comment-end+last-location #f #f) (clear-things-out)]))) (define/public (move-to-new-language [flush-irl-cache? #f]) (when timer (send timer stop)) (send (get-tab) set-hash-lang-error-state #f) (define port (open-input-text-editor this)) (reset-irl! the-irl port (get-irl-directory) flush-irl-cache?) (set!-values (hash-lang-comment-end-position hash-lang-last-location) (get-read-language-port-start+end the-irl)) (set! hash-lang-language (and hash-lang-last-location (get-text hash-lang-comment-end-position hash-lang-last-location))) (when hash-lang-language (preferences:set 'drracket:most-recent-lang-line (string-append hash-lang-language "\n"))) (unless hash-lang-last-location (set-hash-lang-comment-end+last-location (get-read-language-last-position the-irl) 0)) (clear-things-out) (define mode (or (get-definitions-text-surrogate the-irl) (new racket:text-mode% [include-paren-keymap? #f]))) (send mode set-get-token (get-insulated-module-lexer the-irl)) (define paren-matches (call-read-language the-irl 'drracket:paren-matches racket:default-paren-matches)) (send mode set-matches paren-matches) (set-surrogate mode) (define lang-wants-big-defs/ints-labels? (and (call-read-language the-irl 'drracket:show-big-defs/ints-labels #f) #t)) (set-lang-wants-big-defs/ints-labels? lang-wants-big-defs/ints-labels?) (send (send (get-tab) get-ints) set-lang-wants-big-defs/ints-labels? lang-wants-big-defs/ints-labels?) (set! extra-default-filters (or (call-read-language the-irl 'drracket:default-filters #f) '())) (set! default-extension (or (call-read-language the-irl 'drracket:default-extension #f) "")) (set! indentation-function (or (call-read-language the-irl 'drracket:indentation #f) (λ (x y) #f))) (set! range-indentation-function (or (call-read-language the-irl 'drracket:range-indentation #f) (λ (x y z) #f))) (set! grouping-position (or (call-read-language the-irl 'drracket:grouping-position #f) default-grouping-position)) (set! lang-keymap (new keymap:aug-keymap%)) (for ([key+proc (in-list (call-read-language the-irl 'drracket:keystrokes '()))]) (define key (list-ref key+proc 0)) (define proc (list-ref key+proc 1)) (define name (let loop ([counter #f]) (define name (if counter (~a (object-name proc) counter) (~a (object-name proc)))) (cond [(send lang-keymap is-function-added? name) (loop (+ (or counter 0) 1))] [else name]))) (send lang-keymap add-function name proc) (send lang-keymap map-function key name)) (send lang-keymap chain-to-keymap (make-paren-matches-keymap paren-matches (call-read-language the-irl 'drracket:quote-matches (list #\" #\|))) #t) (send (get-keymap) chain-to-keymap lang-keymap #t) (register-new-buttons (or (call-read-language the-irl 'drracket:toolbar-buttons #f) (call-read-language the-irl 'drscheme:toolbar-buttons #f)) (let ([drracket-opt-out (call-read-language the-irl 'drracket:opt-out-toolbar-buttons '())] [drscheme-opt-out (call-read-language the-irl 'drscheme:opt-out-toolbar-buttons '())]) (and drracket-opt-out drscheme-opt-out (append drracket-opt-out drscheme-opt-out))) (call-read-language the-irl 'drracket:opt-in-toolbar-buttons '()))) (define/private (clear-things-out) (define tab (get-tab)) (define ints (send tab get-ints)) (set-surrogate (new racket:text-mode%)) (send ints set-surrogate (new racket:text-mode%)) (set-lang-wants-big-defs/ints-labels? #f) (send ints set-lang-wants-big-defs/ints-labels? #f) (set! extra-default-filters '()) (set! default-extension "") (set! indentation-function (λ (x y) #f)) (set! range-indentation-function (λ (x y z) #f)) (set! grouping-position default-grouping-position) (when lang-keymap (send (get-keymap) remove-chained-keymap lang-keymap) (set! lang-keymap #f)) (send tab set-lang-toolbar-buttons '() '())) (define/private (register-new-buttons buttons opt-out-ids opt-in-ids) cleaned - up - buttons : ( listof ( list / c string ? (define cleaned-up-buttons (cond [(not buttons) '()] [else (for/list ([button (in-list buttons)]) (if (= 3 (length button)) (append button (list #f)) button))])) (define tab (get-tab)) (define frame (send tab get-frame)) (send frame when-initialized (λ () (send frame begin-container-sequence) (send (send frame get-toolbar-button-panel) change-children (λ (prev) '())) (define directly-specified-buttons (map (λ (button-spec) (new switchable-button% [label (list-ref button-spec 0)] [bitmap (list-ref button-spec 1)] [parent (send frame get-toolbar-button-panel)] [callback (lambda (button) ((list-ref button-spec 2) frame))])) cleaned-up-buttons)) (define directly-specified-button-numbers (map (λ (button-spec) (list-ref button-spec 3)) cleaned-up-buttons)) (define (get-opt-in/out-buttons+numbers opt-in?) (define (flip? b) (if opt-in? (not b) b)) (define opt-in/out-ids (if opt-in? opt-in-ids opt-out-ids)) (define opt-in/out-toolbar-buttons (if opt-in? opt-in-toolbar-buttons opt-out-toolbar-buttons)) (cond [(eq? opt-in/out-ids #f) '()] [else (for/list ([opt-in/out-toolbar-button (in-list opt-in/out-toolbar-buttons)] #:unless (flip? (member (opt-in/out-toolbar-button-id opt-in/out-toolbar-button) opt-in/out-ids))) (list ((opt-in/out-toolbar-button-make-button opt-in/out-toolbar-button) frame (send frame get-toolbar-button-panel)) (opt-in/out-toolbar-button-number opt-in/out-toolbar-button)))])) (define opt-out-buttons+numbers (get-opt-in/out-buttons+numbers #f)) (define opt-in-buttons+numbers (get-opt-in/out-buttons+numbers #t)) (send tab set-lang-toolbar-buttons (append directly-specified-buttons (map (λ (x) (list-ref x 0)) opt-out-buttons+numbers) (map (λ (x) (list-ref x 0)) opt-in-buttons+numbers)) (append directly-specified-button-numbers (map (λ (x) (list-ref x 1)) opt-out-buttons+numbers) (map (λ (x) (list-ref x 1)) opt-in-buttons+numbers))) (send frame end-container-sequence)))) (inherit get-text) (define/private (get-lang-name pos) (cond [(zero? pos) '<<unknown>>] [else (let ([str (get-text 0 pos)]) (if (char-whitespace? (string-ref str (- (string-length str) 1))) (substring str 0 (- (string-length str) 1)) str))])) (define online-expansion-monitor-table (make-hash)) (define/public (get-online-expansion-monitor-pcs an-online-expansion-handler) (define key (cons (online-expansion-handler-mod-path an-online-expansion-handler) (online-expansion-handler-id an-online-expansion-handler))) (define old (hash-ref online-expansion-monitor-table key #f)) (cond [old (values (car old) (cdr old))] [else (define-values (local-pc remote-pc) (place-channel)) (hash-set! online-expansion-monitor-table key (cons local-pc remote-pc)) (values local-pc remote-pc)])) (define/augment (after-set-next-settings settings) (update-in-module-language? (is-a? (drracket:language-configuration:language-settings-language settings) drracket:module-language:module-language<%>)) (inner (void) after-set-next-settings settings)) (define/override (put-file dir default-name) (with-language-specific-default-extensions-and-filters (λ () (super put-file dir default-name)))) (define/override (get-file dir) (with-language-specific-default-extensions-and-filters (λ () (super get-file dir)))) (define extra-default-filters '()) (define default-extension "") (define indentation-function (λ (x y) #f)) (define/public (get-indentation-function) indentation-function) (define range-indentation-function (λ (x y z) #f)) (define/public (get-range-indentation-function) range-indentation-function) (define grouping-position default-grouping-position) (define lang-keymap #f) (define/public (with-language-specific-default-extensions-and-filters t) (parameterize ([finder:default-extension default-extension] [finder:default-filters (append extra-default-filters (finder:default-filters))]) (t))) (inherit compute-racket-amount-to-indent) (define/augment (compute-amount-to-indent pos) (cond [in-module-language? (or (indentation-function this pos) (compute-racket-amount-to-indent pos))] [else (compute-racket-amount-to-indent pos)])) (define/override (tabify-selection [start (get-start-position)] [end (get-end-position)]) (unless (and in-module-language? (range-indent range-indentation-function start end)) (super tabify-selection start end))) (define/override (tabify-all) (unless (and in-module-language? (range-indent range-indentation-function 0 (last-position))) (super tabify-all))) (define/override (find-up-sexp start-pos) (*-sexp start-pos 'up (λ () (super find-up-sexp start-pos)))) (define/override (find-down-sexp start-pos) (*-sexp start-pos 'down (λ () (super find-down-sexp start-pos)))) (define/override (get-backward-sexp start-pos) (*-sexp start-pos 'backward (λ () (super get-backward-sexp start-pos)))) (define/override (get-forward-sexp start-pos) (*-sexp start-pos 'forward (λ () (super get-forward-sexp start-pos)))) (inherit get-limit) (define/private (*-sexp start-pos direction do-super) (define irl-answer (grouping-position this start-pos (get-limit start-pos) direction)) (cond [(equal? irl-answer #t) (do-super)] [else irl-answer])) (define/private (get-irl-directory) (define tmp-b (box #f)) (define fn (get-filename tmp-b)) (when (unbox tmp-b) (set! fn #f)) (define the-dir (get-init-dir fn)) the-dir) (super-new) (define the-irl (make-irl (get-irl-directory) (λ (exn) (irl-blew-up exn)))) (define/public (get-irl) the-irl) (set! in-module-language? (is-a? (drracket:language-configuration:language-settings-language (get-next-settings)) drracket:module-language:module-language<%>)))) (define paren-matches-keymaps (make-hash)) (define (make-paren-matches-keymap paren-matches quote-matches) (define keymap-cache-key (cons paren-matches quote-matches)) (cond [(hash-ref paren-matches-keymaps keymap-cache-key #f) => car] [else (define keymap (new keymap:aug-keymap%)) (define alt-as-meta-keymap (new keymap:aug-keymap%)) (for ([paren-match (in-list paren-matches)]) (define open-str (symbol->string (list-ref paren-match 0))) (define close-str (symbol->string (list-ref paren-match 1))) (when (and (= 1 (string-length open-str)) (= 1 (string-length close-str))) (racket:map-pairs-keybinding-functions keymap (string-ref open-str 0) (string-ref close-str 0) #:alt-as-meta-keymap alt-as-meta-keymap))) (for ([c (in-list quote-matches)]) (racket:map-pairs-keybinding-functions keymap c c)) (when (> (hash-count paren-matches-keymaps) 20) (set! paren-matches-keymaps (make-hash))) (hash-set! paren-matches-keymaps keymap-cache-key (list keymap alt-as-meta-keymap)) (when (preferences:get 'framework:alt-as-meta) (send keymap chain-to-keymap alt-as-meta-keymap #f)) keymap])) (define (adjust-alt-as-meta on?) (for ([(_ keymap+alt-as-meta-keymap) (in-hash paren-matches-keymaps)]) (define-values (keymap alt-as-meta-keymap) (apply values keymap+alt-as-meta-keymap)) (send keymap remove-chained-keymap alt-as-meta-keymap) (when on? (send keymap chain-to-keymap alt-as-meta-keymap #f)))) (preferences:add-callback 'framework:alt-as-meta (λ (p v) (adjust-alt-as-meta v))) (define default-grouping-position (λ (text start limit dir) #t)) (define no-more-online-expansion-handlers? #f) (define (no-more-online-expansion-handlers) (set! no-more-online-expansion-handlers? #t)) (define-values (done done?) (let () (struct done ()) (values (done) done?))) (define-values (start start?) (let () (struct start ()) (values (start) start?))) (struct online-expansion-handler (mod-path id local-handler monitor?)) (define online-expansion-handlers '()) (define (get-online-expansion-handlers) (cond [no-more-online-expansion-handlers? online-expansion-handlers] [else (error 'get-online-expansion-handlers "online-expansion-handlers can still be registered")])) (define (add-online-expansion-handler mod-path id local-handler) (check-bad-registration 'add-online-expansion-handler mod-path id local-handler) (set! online-expansion-handlers (cons (online-expansion-handler mod-path id local-handler #f) online-expansion-handlers))) (define (add-online-expansion-monitor mod-path id local-handler) (check-bad-registration 'add-online-expansion-monitor mod-path id local-handler) (set! online-expansion-handlers (cons (online-expansion-handler mod-path id local-handler #t) online-expansion-handlers))) (define (check-bad-registration who mod-path id local-handler) (when no-more-online-expansion-handlers? (error who "no more online-expansion-handlers can be registered; got ~e ~e ~e" mod-path id local-handler)) (for ([handler (in-list online-expansion-handlers)]) (when (and (equal? (online-expansion-handler-mod-path handler) mod-path) (equal? (online-expansion-handler-id handler) id)) (error who (string-append "already registered a handler with the same mod-path and id\n" " mod-path: ~e\n" " id: ~e") mod-path id)))) (define online-expansion-pref-funcs '()) (define (get-online-expansion-pref-funcs) online-expansion-pref-funcs) (define online-expansion-prefs '()) (define (register-online-expansion-pref func) (set! online-expansion-pref-funcs (cons func online-expansion-pref-funcs))))
e4f41c7b7823b12138febde18b91da97827ca3b73f882f92bcaed87fff9c5f82
39aldo39/klfc
Types.hs
{-# LANGUAGE ConstraintKinds #-} module Layout.Types ( Action , DeadKey'(..) , BaseChar'(..) , BaseChar , ActionResult'(..) , ActionResult , ActionMap , DeadKey , Letter(..) , Key , _pos , _shortcutPos , _shiftlevels , _letters , _capslock , Information , _fullName , _name , _copyright , _company , _localeId , _version , _description , Layout , _info , _singletonKeys , _mods , _variants , _keys , SingletonKey(..) , _sPos , _sLetter , Variant(..) , Logger , Mod(..) , Modifier , ModifierEffect(..) , Shiftstate , Shiftlevel , Pos ) where import Layout.Action (Action) import Layout.DeadKey (DeadKey'(..), BaseChar'(..), ActionResult'(..)) import Layout.Key (BaseChar, ActionResult, ActionMap, DeadKey, Letter(..), Key, _pos, _shortcutPos, _shiftlevels, _letters, _capslock) import Layout.Layout (Information(..), _fullName, _name, _copyright, _company, _localeId, _version, _description, Layout(..), _info, _singletonKeys, _mods, _variants, _keys, SingletonKey(..), _sPos, _sLetter, Variant(..)) import Layout.Mod (Mod(..)) import Layout.Modifier (Modifier, Shiftstate, Shiftlevel) import Layout.ModifierEffect (ModifierEffect(..)) import Layout.Pos (Pos) import Control.Monad.Writer (MonadWriter) type Logger = MonadWriter [String]
null
https://raw.githubusercontent.com/39aldo39/klfc/83908c54c955b9c160b999bc8f0892401ba4adbf/src/Layout/Types.hs
haskell
# LANGUAGE ConstraintKinds #
module Layout.Types ( Action , DeadKey'(..) , BaseChar'(..) , BaseChar , ActionResult'(..) , ActionResult , ActionMap , DeadKey , Letter(..) , Key , _pos , _shortcutPos , _shiftlevels , _letters , _capslock , Information , _fullName , _name , _copyright , _company , _localeId , _version , _description , Layout , _info , _singletonKeys , _mods , _variants , _keys , SingletonKey(..) , _sPos , _sLetter , Variant(..) , Logger , Mod(..) , Modifier , ModifierEffect(..) , Shiftstate , Shiftlevel , Pos ) where import Layout.Action (Action) import Layout.DeadKey (DeadKey'(..), BaseChar'(..), ActionResult'(..)) import Layout.Key (BaseChar, ActionResult, ActionMap, DeadKey, Letter(..), Key, _pos, _shortcutPos, _shiftlevels, _letters, _capslock) import Layout.Layout (Information(..), _fullName, _name, _copyright, _company, _localeId, _version, _description, Layout(..), _info, _singletonKeys, _mods, _variants, _keys, SingletonKey(..), _sPos, _sLetter, Variant(..)) import Layout.Mod (Mod(..)) import Layout.Modifier (Modifier, Shiftstate, Shiftlevel) import Layout.ModifierEffect (ModifierEffect(..)) import Layout.Pos (Pos) import Control.Monad.Writer (MonadWriter) type Logger = MonadWriter [String]
bc28434834e7462c9a91c69e5dfb6d8a697804fd3ea871b96c995ab1e8507477
vert-x/mod-lang-clojure
server.clj
Copyright 2013 the original author or authors . ;; 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 example.pubsub.server (:require [vertx.net :as net] [vertx.shareddata :as shared] [clojure.string :as string] [vertx.stream :as stream] [vertx.eventbus :as bus] [vertx.buffer :as buf])) (defn connect-handler [sock] (stream/on-data sock (fn [buf!] (buf/parse-delimited buf! "\n" (fn [line] (let [[cmd topic msg] (-> line str string/trim (string/split #",")) topic-set! (and topic (shared/get-set topic)) sock-id (.writeHandlerID sock)] (condp = cmd "subscribe" (do (println "subscribing to" topic) (shared/add! topic-set! sock-id)) "unsubscribe" (do (println "unsubscribing from" topic) (shared/remove! topic-set! sock-id)) "publish" (do (println "publishing to" topic "with" msg) (doseq [target topic-set!] (bus/send target (buf/buffer (str msg "\n"))))) (stream/write sock (format "unknown command: %s\n" cmd))))))))) (-> (net/server) (net/on-connect connect-handler) (net/listen 1234)) (println "Starting TCP pub-sub server on localhost:1234")
null
https://raw.githubusercontent.com/vert-x/mod-lang-clojure/dcf713460b8f46c08d0db6e7bf8537f1dd91f297/examples/pubsub/server.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 2013 the original author or authors . distributed under the License is distributed on an " AS IS " BASIS , (ns example.pubsub.server (:require [vertx.net :as net] [vertx.shareddata :as shared] [clojure.string :as string] [vertx.stream :as stream] [vertx.eventbus :as bus] [vertx.buffer :as buf])) (defn connect-handler [sock] (stream/on-data sock (fn [buf!] (buf/parse-delimited buf! "\n" (fn [line] (let [[cmd topic msg] (-> line str string/trim (string/split #",")) topic-set! (and topic (shared/get-set topic)) sock-id (.writeHandlerID sock)] (condp = cmd "subscribe" (do (println "subscribing to" topic) (shared/add! topic-set! sock-id)) "unsubscribe" (do (println "unsubscribing from" topic) (shared/remove! topic-set! sock-id)) "publish" (do (println "publishing to" topic "with" msg) (doseq [target topic-set!] (bus/send target (buf/buffer (str msg "\n"))))) (stream/write sock (format "unknown command: %s\n" cmd))))))))) (-> (net/server) (net/on-connect connect-handler) (net/listen 1234)) (println "Starting TCP pub-sub server on localhost:1234")
3d46beb49aa035973523e09a8d312e52d14dbc7ab05c1f1955663171ff716960
ocaml-ppx/ppx
syntax.ml
(* When upstreaming this, we need to make sure it's built from the lexer's keyword_table rather than duplicated. *) let keywords = [ "and"; "as"; "assert"; "asr"; "begin"; "class"; "constraint"; "do"; "done" ; "downto"; "else"; "end"; "exception"; "external"; "false"; "for"; "fun" ; "function"; "functor"; "if"; "in"; "include"; "inherit"; "initializer" ; "land"; "lazy"; "let"; "lor"; "lsl"; "lsr"; "lxor"; "match"; "method" ; "mod"; "module"; "mutable"; "new"; "nonrec"; "object"; "of"; "open"; "or" ; "private"; "rec"; "sig"; "struct"; "then"; "to"; "true"; "try"; "type" ; "val"; "virtual"; "when"; "while"; "with" ]
null
https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/astlib/syntax.ml
ocaml
When upstreaming this, we need to make sure it's built from the lexer's keyword_table rather than duplicated.
let keywords = [ "and"; "as"; "assert"; "asr"; "begin"; "class"; "constraint"; "do"; "done" ; "downto"; "else"; "end"; "exception"; "external"; "false"; "for"; "fun" ; "function"; "functor"; "if"; "in"; "include"; "inherit"; "initializer" ; "land"; "lazy"; "let"; "lor"; "lsl"; "lsr"; "lxor"; "match"; "method" ; "mod"; "module"; "mutable"; "new"; "nonrec"; "object"; "of"; "open"; "or" ; "private"; "rec"; "sig"; "struct"; "then"; "to"; "true"; "try"; "type" ; "val"; "virtual"; "when"; "while"; "with" ]
59371f9a4d98d729e701af885142a74890ecb0e0afd5e7bfafa4689e1b1e4826
jwiegley/notes
folded.hs
import Control.Applicative import Control.Lens import Data.Data.Lens data Type = Foo Int | Bar String | Baz Int deriving Show data Foozle = Foozle [Type] deriving Show _foozle :: Traversal Type Type String String _foozle f x@(Bar a) = Bar <$> f a _foozle _ x = pure x main = print $ Foozle [ Foo 1, Bar "Hello", Baz 2] ^. to (\(Foozle a) -> a) . folded . _foozle
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/f719a3d41696d48f6005/misc/folded.hs
haskell
import Control.Applicative import Control.Lens import Data.Data.Lens data Type = Foo Int | Bar String | Baz Int deriving Show data Foozle = Foozle [Type] deriving Show _foozle :: Traversal Type Type String String _foozle f x@(Bar a) = Bar <$> f a _foozle _ x = pure x main = print $ Foozle [ Foo 1, Bar "Hello", Baz 2] ^. to (\(Foozle a) -> a) . folded . _foozle
317b3e539f34393bf7fd22ae3d0b82ca1508f391f62f0c351fe14c97a48252bd
chenyukang/eopl
46.scm
(load-relative "../libs/init.scm") (load-relative "./base/scheduler.scm") (load-relative "./base/semaphores.scm") (load-relative "./base/store.scm") (load-relative "./base/queues.scm") (load-relative "./base/thread-cases.scm") (load-relative "./base/environments.scm") (load-relative "./base/test.scm") based on 45 , restart thread with the remaining thime . ;; see the new stuff, ;; here notice the buggy part (define the-lexical-spec '((whitespace (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number) )) (define the-grammar '((program (expression) a-program) (expression (number) const-exp) ;; like list(n1,...,nk) in exceptions language. Sorry about that. (expression ("[" (separated-list number ",") "]") const-list-exp) (expression (identifier) var-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("proc" "(" identifier ")" expression) proc-exp) (expression ("(" expression expression ")") call-exp) (expression ("begin" expression (arbno ";" expression) "end") begin-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ;; arbitrary number of unary procedures ("letrec" (arbno identifier "(" identifier ")" "=" expression) "in" expression) letrec-exp) (expression ("set" identifier "=" expression) set-exp) (expression ("spawn" "(" expression ")") spawn-exp) ;;new stuff (expression ("yield" "(" ")") yield-exp) (expression ("mutex" "(" ")") mutex-exp) (expression ("wait" "(" expression ")") wait-exp) (expression ("signal" "(" expression ")") signal-exp) ;; other unary operators (expression (unop "(" expression ")") unop-exp) (unop ("car") car-unop) (unop ("cdr") cdr-unop) (unop ("null?") null?-unop) (unop ("zero?") zero?-unop) (unop ("print") print-unop) )) ;;;;;;;;;;;;;;;; sllgen boilerplate ;;;;;;;;;;;;;;;; (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define show-the-datatypes (lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar))) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) ;;;;;;;;;;;;;;;; expressed values ;;;;;;;;;;;;;;;; (define-datatype expval expval? (num-val (value number?)) (bool-val (boolean boolean?)) (proc-val (proc proc?)) (list-val (lst (list-of expval?))) (mutex-val (mutex mutex?)) ) ;;; extractors: (define expval->num (lambda (v) (cases expval v (num-val (num) num) (else (expval-extractor-error 'num v))))) (define expval->bool (lambda (v) (cases expval v (bool-val (bool) bool) (else (expval-extractor-error 'bool v))))) (define expval->proc (lambda (v) (cases expval v (proc-val (proc) proc) (else (expval-extractor-error 'proc v))))) (define expval->list (lambda (v) (cases expval v (list-val (lst) lst) (else (expval-extractor-error 'list v))))) (define expval->mutex (lambda (v) (cases expval v (mutex-val (l) l) (else (expval-extractor-error 'mutex v))))) (define expval-extractor-error (lambda (variant value) (error 'expval-extractors "Looking for a ~s, found ~s" variant value))) ;;;;;;;;;;;;;;;; mutexes ;;;;;;;;;;;;;;;; (define-datatype mutex mutex? (a-mutex (ref-to-closed? reference?) ; ref to bool ref to ( listof thread ) ;;;;;;;;;;;;;;;; procedures ;;;;;;;;;;;;;;;; (define-datatype proc proc? (procedure (bvar symbol?) (body expression?) (env environment?))) ;; used by begin-exp (define fresh-identifier (let ((sn 0)) (lambda (identifier) (set! sn (+ sn 1)) (string->symbol (string-append (symbol->string identifier) "%" ; this can't appear in an input identifier (number->string sn)))))) ;;;;;;;;;;;;;;;; continuations ;;;;;;;;;;;;;;;; (define-datatype continuation continuation? (end-main-thread-cont) (end-subthread-cont) (diff1-cont (exp2 expression?) (env environment?) (cont continuation?)) (diff2-cont (val1 expval?) (cont continuation?)) (if-test-cont (exp2 expression?) (exp3 expression?) (env environment?) (cont continuation?)) (rator-cont (rand expression?) (env environment?) (cont continuation?)) (rand-cont (val1 expval?) (cont continuation?)) (set-rhs-cont (loc reference?) (cont continuation?)) (spawn-cont (saved-cont continuation?)) (wait-cont (saved-cont continuation?)) (signal-cont (saved-cont continuation?)) (unop-arg-cont (unop1 unop?) (cont continuation?)) (restore-yield-cont (saved-cont continuation?) (remaining-time integer?)) ) value - of - program : Program * Int - > ExpVal (define value-of-program (lambda (timeslice pgm) (initialize-store!) (initialize-scheduler! timeslice) (cases program pgm (a-program (exp1) (value-of/k exp1 (init-env) (end-main-thread-cont)))))) (define trace-interp (make-parameter #f)) ;; value-of/k : Exp * Env * Cont -> FinalAnswer Page 182 (define value-of/k (lambda (exp env cont) (if (trace-interp) (printf "value-of/k: ~s~%" exp)) (cases expression exp (const-exp (num) (apply-cont cont (num-val num))) (const-list-exp (nums) (apply-cont cont (list-val (map num-val nums)))) (var-exp (var) (apply-cont cont (deref (apply-env env var)))) (diff-exp (exp1 exp2) (value-of/k exp1 env (diff1-cont exp2 env cont))) (if-exp (exp1 exp2 exp3) (value-of/k exp1 env (if-test-cont exp2 exp3 env cont))) (proc-exp (var body) (apply-cont cont (proc-val (procedure var body env)))) (call-exp (rator rand) (value-of/k rator env (rator-cont rand env cont))) (let-exp (var exp1 body) ; implemented like a macro! (value-of/k (call-exp (proc-exp var body) exp1) env cont)) (begin-exp (exp exps) ; this one, too (if (null? exps) (value-of/k exp env cont) (value-of/k (call-exp (proc-exp (fresh-identifier 'dummy) (begin-exp (car exps) (cdr exps))) exp) env cont))) (letrec-exp (p-names b-vars p-bodies letrec-body) (value-of/k letrec-body (extend-env-rec* p-names b-vars p-bodies env) cont)) (set-exp (id exp) (value-of/k exp env (set-rhs-cont (apply-env env id) cont))) (spawn-exp (exp) (value-of/k exp env (spawn-cont cont))) ;;new stuff ;;buggy here, we need to save time as remain-time, ;;for lambda() will execute at later pointer, where the the-time-remaining ;;will changed (yield-exp () (let ((time the-time-remaining)) (begin (place-on-ready-queue! (lambda () (apply-cont (restore-yield-cont cont time) (num-val 99)))) (run-next-thread)))) (mutex-exp () (apply-cont cont (mutex-val (new-mutex)))) (wait-exp (exp) (value-of/k exp env (wait-cont cont))) (signal-exp (exp) (value-of/k exp env (signal-cont cont))) (unop-exp (unop1 exp) (value-of/k exp env (unop-arg-cont unop1 cont))) ))) ;; apply-cont : Cont * Exp -> FinalAnswer (define apply-cont (lambda (cont val) (if (time-expired?) (begin (place-on-ready-queue! (lambda () (apply-cont cont val))) (run-next-thread)) (begin (begin ( printf " dec time : ~% " the - time - remaining ) (decrement-timer!) ) (cases continuation cont (end-main-thread-cont () (set-final-answer! val) (run-next-thread)) (end-subthread-cont () (run-next-thread)) (diff1-cont (exp2 saved-env saved-cont) (value-of/k exp2 saved-env (diff2-cont val saved-cont))) (diff2-cont (val1 saved-cont) (let ((n1 (expval->num val1)) (n2 (expval->num val))) (apply-cont saved-cont (num-val (- n1 n2))))) (if-test-cont (exp2 exp3 env cont) (if (expval->bool val) (value-of/k exp2 env cont) (value-of/k exp3 env cont))) (rator-cont (rand saved-env saved-cont) (value-of/k rand saved-env (rand-cont val saved-cont))) (rand-cont (val1 saved-cont) (let ((proc (expval->proc val1))) (apply-procedure proc val saved-cont))) (set-rhs-cont (loc cont) (begin (setref! loc val) (apply-cont cont (num-val 26)))) (spawn-cont (saved-cont) (let ((proc1 (expval->proc val))) (place-on-ready-queue! (lambda () (apply-procedure proc1 (num-val 28) (end-subthread-cont)))) (apply-cont saved-cont (num-val 73)))) (wait-cont (saved-cont) (wait-for-mutex (expval->mutex val) (lambda () (apply-cont saved-cont (num-val 52))))) (signal-cont (saved-cont) (signal-mutex (expval->mutex val) (lambda () (apply-cont saved-cont (num-val 53))))) (unop-arg-cont (unop1 cont) (apply-unop unop1 val cont)) (restore-yield-cont (saved-cont remaining-time) (begin (printf "remain-time: ~a~%" remaining-time) (set! the-time-remaining remaining-time) (apply-cont saved-cont val))) ))))) (define apply-procedure (lambda (proc1 arg cont) (cases proc proc1 (procedure (var body saved-env) (value-of/k body (extend-env var (newref arg) saved-env) cont))))) (define apply-unop (lambda (unop1 arg cont) (cases unop unop1 (zero?-unop () (apply-cont cont (bool-val (zero? (expval->num arg))))) (car-unop () (let ((lst (expval->list arg))) (apply-cont cont (car lst)))) (cdr-unop () (let ((lst (expval->list arg))) (apply-cont cont (list-val (cdr lst))))) (null?-unop () (apply-cont cont (bool-val (null? (expval->list arg))))) (print-unop () (begin (printf "~a~%" (expval->num arg)) (apply-cont cont (num-val 1)))) ))) (define run (lambda (timeslice string) (value-of-program timeslice (scan&parse string)))) (define run-all (lambda (timeslice) (run-tests! (lambda (string) (run timeslice string)) equal-answer? test-list))) (define run-one (lambda (timeslice test-name) (let ((the-test (assoc test-name test-list))) (cond ((assoc test-name test-list) => (lambda (test) (run timeslice (cadr test)))) (else (error 'run-one "no such test: ~s" test-name)))))) ;;new stuff (run 10 "let wait_time = proc(n) letrec waitloop(k) = if zero?(k) then print(1) else begin (waitloop -(k, 1)) end in (waitloop n) ( wait_time 2 ) ; yield ( ) end " ) (add-test! '(yield-test "begin 33; 44 ; yield() end" 99)) (run-all 10)
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/ch5/46.scm
scheme
see the new stuff, here notice the buggy part like list(n1,...,nk) in exceptions language. Sorry about that. arbitrary number of unary procedures new stuff other unary operators sllgen boilerplate ;;;;;;;;;;;;;;;; expressed values ;;;;;;;;;;;;;;;; extractors: mutexes ;;;;;;;;;;;;;;;; ref to bool procedures ;;;;;;;;;;;;;;;; used by begin-exp this can't appear in an input identifier continuations ;;;;;;;;;;;;;;;; value-of/k : Exp * Env * Cont -> FinalAnswer implemented like a macro! this one, too new stuff buggy here, we need to save time as remain-time, for lambda() will execute at later pointer, where the the-time-remaining will changed apply-cont : Cont * Exp -> FinalAnswer new stuff yield ( ) end " )
(load-relative "../libs/init.scm") (load-relative "./base/scheduler.scm") (load-relative "./base/semaphores.scm") (load-relative "./base/store.scm") (load-relative "./base/queues.scm") (load-relative "./base/thread-cases.scm") (load-relative "./base/environments.scm") (load-relative "./base/test.scm") based on 45 , restart thread with the remaining thime . (define the-lexical-spec '((whitespace (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number) )) (define the-grammar '((program (expression) a-program) (expression (number) const-exp) (expression ("[" (separated-list number ",") "]") const-list-exp) (expression (identifier) var-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("proc" "(" identifier ")" expression) proc-exp) (expression ("(" expression expression ")") call-exp) (expression ("begin" expression (arbno ";" expression) "end") begin-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ("letrec" (arbno identifier "(" identifier ")" "=" expression) "in" expression) letrec-exp) (expression ("set" identifier "=" expression) set-exp) (expression ("spawn" "(" expression ")") spawn-exp) (expression ("yield" "(" ")") yield-exp) (expression ("mutex" "(" ")") mutex-exp) (expression ("wait" "(" expression ")") wait-exp) (expression ("signal" "(" expression ")") signal-exp) (expression (unop "(" expression ")") unop-exp) (unop ("car") car-unop) (unop ("cdr") cdr-unop) (unop ("null?") null?-unop) (unop ("zero?") zero?-unop) (unop ("print") print-unop) )) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define show-the-datatypes (lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar))) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define-datatype expval expval? (num-val (value number?)) (bool-val (boolean boolean?)) (proc-val (proc proc?)) (list-val (lst (list-of expval?))) (mutex-val (mutex mutex?)) ) (define expval->num (lambda (v) (cases expval v (num-val (num) num) (else (expval-extractor-error 'num v))))) (define expval->bool (lambda (v) (cases expval v (bool-val (bool) bool) (else (expval-extractor-error 'bool v))))) (define expval->proc (lambda (v) (cases expval v (proc-val (proc) proc) (else (expval-extractor-error 'proc v))))) (define expval->list (lambda (v) (cases expval v (list-val (lst) lst) (else (expval-extractor-error 'list v))))) (define expval->mutex (lambda (v) (cases expval v (mutex-val (l) l) (else (expval-extractor-error 'mutex v))))) (define expval-extractor-error (lambda (variant value) (error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define-datatype mutex mutex? (a-mutex ref to ( listof thread ) (define-datatype proc proc? (procedure (bvar symbol?) (body expression?) (env environment?))) (define fresh-identifier (let ((sn 0)) (lambda (identifier) (set! sn (+ sn 1)) (string->symbol (string-append (symbol->string identifier) (number->string sn)))))) (define-datatype continuation continuation? (end-main-thread-cont) (end-subthread-cont) (diff1-cont (exp2 expression?) (env environment?) (cont continuation?)) (diff2-cont (val1 expval?) (cont continuation?)) (if-test-cont (exp2 expression?) (exp3 expression?) (env environment?) (cont continuation?)) (rator-cont (rand expression?) (env environment?) (cont continuation?)) (rand-cont (val1 expval?) (cont continuation?)) (set-rhs-cont (loc reference?) (cont continuation?)) (spawn-cont (saved-cont continuation?)) (wait-cont (saved-cont continuation?)) (signal-cont (saved-cont continuation?)) (unop-arg-cont (unop1 unop?) (cont continuation?)) (restore-yield-cont (saved-cont continuation?) (remaining-time integer?)) ) value - of - program : Program * Int - > ExpVal (define value-of-program (lambda (timeslice pgm) (initialize-store!) (initialize-scheduler! timeslice) (cases program pgm (a-program (exp1) (value-of/k exp1 (init-env) (end-main-thread-cont)))))) (define trace-interp (make-parameter #f)) Page 182 (define value-of/k (lambda (exp env cont) (if (trace-interp) (printf "value-of/k: ~s~%" exp)) (cases expression exp (const-exp (num) (apply-cont cont (num-val num))) (const-list-exp (nums) (apply-cont cont (list-val (map num-val nums)))) (var-exp (var) (apply-cont cont (deref (apply-env env var)))) (diff-exp (exp1 exp2) (value-of/k exp1 env (diff1-cont exp2 env cont))) (if-exp (exp1 exp2 exp3) (value-of/k exp1 env (if-test-cont exp2 exp3 env cont))) (proc-exp (var body) (apply-cont cont (proc-val (procedure var body env)))) (call-exp (rator rand) (value-of/k rator env (rator-cont rand env cont))) (value-of/k (call-exp (proc-exp var body) exp1) env cont)) (if (null? exps) (value-of/k exp env cont) (value-of/k (call-exp (proc-exp (fresh-identifier 'dummy) (begin-exp (car exps) (cdr exps))) exp) env cont))) (letrec-exp (p-names b-vars p-bodies letrec-body) (value-of/k letrec-body (extend-env-rec* p-names b-vars p-bodies env) cont)) (set-exp (id exp) (value-of/k exp env (set-rhs-cont (apply-env env id) cont))) (spawn-exp (exp) (value-of/k exp env (spawn-cont cont))) (yield-exp () (let ((time the-time-remaining)) (begin (place-on-ready-queue! (lambda () (apply-cont (restore-yield-cont cont time) (num-val 99)))) (run-next-thread)))) (mutex-exp () (apply-cont cont (mutex-val (new-mutex)))) (wait-exp (exp) (value-of/k exp env (wait-cont cont))) (signal-exp (exp) (value-of/k exp env (signal-cont cont))) (unop-exp (unop1 exp) (value-of/k exp env (unop-arg-cont unop1 cont))) ))) (define apply-cont (lambda (cont val) (if (time-expired?) (begin (place-on-ready-queue! (lambda () (apply-cont cont val))) (run-next-thread)) (begin (begin ( printf " dec time : ~% " the - time - remaining ) (decrement-timer!) ) (cases continuation cont (end-main-thread-cont () (set-final-answer! val) (run-next-thread)) (end-subthread-cont () (run-next-thread)) (diff1-cont (exp2 saved-env saved-cont) (value-of/k exp2 saved-env (diff2-cont val saved-cont))) (diff2-cont (val1 saved-cont) (let ((n1 (expval->num val1)) (n2 (expval->num val))) (apply-cont saved-cont (num-val (- n1 n2))))) (if-test-cont (exp2 exp3 env cont) (if (expval->bool val) (value-of/k exp2 env cont) (value-of/k exp3 env cont))) (rator-cont (rand saved-env saved-cont) (value-of/k rand saved-env (rand-cont val saved-cont))) (rand-cont (val1 saved-cont) (let ((proc (expval->proc val1))) (apply-procedure proc val saved-cont))) (set-rhs-cont (loc cont) (begin (setref! loc val) (apply-cont cont (num-val 26)))) (spawn-cont (saved-cont) (let ((proc1 (expval->proc val))) (place-on-ready-queue! (lambda () (apply-procedure proc1 (num-val 28) (end-subthread-cont)))) (apply-cont saved-cont (num-val 73)))) (wait-cont (saved-cont) (wait-for-mutex (expval->mutex val) (lambda () (apply-cont saved-cont (num-val 52))))) (signal-cont (saved-cont) (signal-mutex (expval->mutex val) (lambda () (apply-cont saved-cont (num-val 53))))) (unop-arg-cont (unop1 cont) (apply-unop unop1 val cont)) (restore-yield-cont (saved-cont remaining-time) (begin (printf "remain-time: ~a~%" remaining-time) (set! the-time-remaining remaining-time) (apply-cont saved-cont val))) ))))) (define apply-procedure (lambda (proc1 arg cont) (cases proc proc1 (procedure (var body saved-env) (value-of/k body (extend-env var (newref arg) saved-env) cont))))) (define apply-unop (lambda (unop1 arg cont) (cases unop unop1 (zero?-unop () (apply-cont cont (bool-val (zero? (expval->num arg))))) (car-unop () (let ((lst (expval->list arg))) (apply-cont cont (car lst)))) (cdr-unop () (let ((lst (expval->list arg))) (apply-cont cont (list-val (cdr lst))))) (null?-unop () (apply-cont cont (bool-val (null? (expval->list arg))))) (print-unop () (begin (printf "~a~%" (expval->num arg)) (apply-cont cont (num-val 1)))) ))) (define run (lambda (timeslice string) (value-of-program timeslice (scan&parse string)))) (define run-all (lambda (timeslice) (run-tests! (lambda (string) (run timeslice string)) equal-answer? test-list))) (define run-one (lambda (timeslice test-name) (let ((the-test (assoc test-name test-list))) (cond ((assoc test-name test-list) => (lambda (test) (run timeslice (cadr test)))) (else (error 'run-one "no such test: ~s" test-name)))))) (run 10 "let wait_time = proc(n) letrec waitloop(k) = if zero?(k) then print(1) else begin (waitloop -(k, 1)) end in (waitloop n) (add-test! '(yield-test "begin 33; 44 ; yield() end" 99)) (run-all 10)
deb8772770630ff430a9d1b38d8930f6bed0a2d005bdf5b11274ac63d806b84b
haskell-repa/repa
Flatten.hs
module Data.Array.Repa.Vector.Operators.Flatten (Flatten2 (..)) where import Data.Array.Repa.Repr.Stream import Data.Array.Repa.Repr.Chain import Data.Array.Repa.Vector.Base import Data.Array.Repa.Stream.Flatten as S import Data.Array.Repa as R import qualified Data.Vector.Unboxed as U -- | Flatten a vector of tuples into a vector of their elements. -- TODO : use less general result representations for unboxeded , delayed , chained sources . class Flatten2 r a where type Flatten2R r vflatten2 :: Vector r (a, a) -> Vector (Flatten2R r) a instance U.Unbox a => Flatten2 U a where type Flatten2R U = S vflatten2 vec = vflatten2 (vstream vec) {-# INLINE [1] vflatten2 #-} instance U.Unbox a => Flatten2 D a where type Flatten2R D = S vflatten2 vec = vflatten2 (vstream vec) {-# INLINE [1] vflatten2 #-} instance U.Unbox a => Flatten2 N a where type Flatten2R N = S vflatten2 vec = vflatten2 (vstream vec) {-# INLINE [1] vflatten2 #-} instance U.Unbox a => Flatten2 S a where type Flatten2R S = S vflatten2 (AStream _ dstream _) = vcacheStream $ S.flatten2D dstream {-# INLINE [1] vflatten2 #-}
null
https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/icebox/abandoned/repa-vector-old/chains/Data/Array/Repa/Vector/Operators/Flatten.hs
haskell
| Flatten a vector of tuples into a vector of their elements. # INLINE [1] vflatten2 # # INLINE [1] vflatten2 # # INLINE [1] vflatten2 # # INLINE [1] vflatten2 #
module Data.Array.Repa.Vector.Operators.Flatten (Flatten2 (..)) where import Data.Array.Repa.Repr.Stream import Data.Array.Repa.Repr.Chain import Data.Array.Repa.Vector.Base import Data.Array.Repa.Stream.Flatten as S import Data.Array.Repa as R import qualified Data.Vector.Unboxed as U TODO : use less general result representations for unboxeded , delayed , chained sources . class Flatten2 r a where type Flatten2R r vflatten2 :: Vector r (a, a) -> Vector (Flatten2R r) a instance U.Unbox a => Flatten2 U a where type Flatten2R U = S vflatten2 vec = vflatten2 (vstream vec) instance U.Unbox a => Flatten2 D a where type Flatten2R D = S vflatten2 vec = vflatten2 (vstream vec) instance U.Unbox a => Flatten2 N a where type Flatten2R N = S vflatten2 vec = vflatten2 (vstream vec) instance U.Unbox a => Flatten2 S a where type Flatten2R S = S vflatten2 (AStream _ dstream _) = vcacheStream $ S.flatten2D dstream
31b896a1075b62768d654777a06a454a77527ef2914ddfe01118ba6babe5b2b8
vbmithr/ocaml-ftx
ftx.ml
open Sexplib.Std let strfloat = let open Json_encoding in union [ case float (fun s -> Some s) (fun s -> s) ; case string (fun s -> Some (string_of_float s)) float_of_string ; ] module Ezjsonm_encoding = struct include Json_encoding.Make(Json_repr.Ezjsonm) let destruct_safe encoding value = try destruct encoding value with exn -> Format.eprintf "%a@." (Json_encoding.print_error ?print_unknown:None) exn ; raise exn end module Ptime = struct include Ptime let t_of_sexp sexp = let sexp_str = string_of_sexp sexp in match of_rfc3339 sexp_str with | Ok (t, _, _) -> t | _ -> invalid_arg "Ptime.t_of_sexp" let sexp_of_t t = sexp_of_string (to_rfc3339 ~frac_s:7 t) let unix_encoding = let open Json_encoding in conv Ptime.to_float_s (fun ts -> match Ptime.of_float_s ts with | None -> invalid_arg "Ptime.encoding" | Some ts -> ts) float let rfc3339_encoding = let open Json_encoding in conv (Ptime.to_rfc3339) (fun s -> match Ptime.of_rfc3339 s with | Ok (v, _, _) -> v | _ -> failwith "rfc3339_encoding") string let encoding = let open Json_encoding in union [ case unix_encoding (fun a -> Some a) (fun a -> a) ; case rfc3339_encoding (fun a -> Some a) (fun a -> a) ; ] end
null
https://raw.githubusercontent.com/vbmithr/ocaml-ftx/d3aae520c1ed859162b62b09a8fdb003063be66d/src/ftx.ml
ocaml
open Sexplib.Std let strfloat = let open Json_encoding in union [ case float (fun s -> Some s) (fun s -> s) ; case string (fun s -> Some (string_of_float s)) float_of_string ; ] module Ezjsonm_encoding = struct include Json_encoding.Make(Json_repr.Ezjsonm) let destruct_safe encoding value = try destruct encoding value with exn -> Format.eprintf "%a@." (Json_encoding.print_error ?print_unknown:None) exn ; raise exn end module Ptime = struct include Ptime let t_of_sexp sexp = let sexp_str = string_of_sexp sexp in match of_rfc3339 sexp_str with | Ok (t, _, _) -> t | _ -> invalid_arg "Ptime.t_of_sexp" let sexp_of_t t = sexp_of_string (to_rfc3339 ~frac_s:7 t) let unix_encoding = let open Json_encoding in conv Ptime.to_float_s (fun ts -> match Ptime.of_float_s ts with | None -> invalid_arg "Ptime.encoding" | Some ts -> ts) float let rfc3339_encoding = let open Json_encoding in conv (Ptime.to_rfc3339) (fun s -> match Ptime.of_rfc3339 s with | Ok (v, _, _) -> v | _ -> failwith "rfc3339_encoding") string let encoding = let open Json_encoding in union [ case unix_encoding (fun a -> Some a) (fun a -> a) ; case rfc3339_encoding (fun a -> Some a) (fun a -> a) ; ] end
64a3e8ff30d4c6bfa23f39b22e5b05dbd5016fed6eb6423ff9588b1d4016eaf1
takikawa/racket-ppa
get-extend.rkt
#lang racket/unit (require racket/class drracket/private/drsig framework/private/logging-timer) (import [prefix drracket:unit: drracket:unit^] [prefix drracket:frame: drracket:frame^] [prefix drracket:rep: drracket:rep^] [prefix drracket:debug: drracket:debug^] [prefix drracket:tracing: drracket:tracing^] [prefix drracket:module-language: drracket:module-language/int^] [prefix drracket:module-language-tools: drracket:module-language-tools/int^]) (export drracket:get/extend^) (define re-extension-allowed? #f) (define (allow-re-extension!) (set! re-extension-allowed? #t)) (define (disallow-re-extension!) (set! re-extension-allowed? #f)) (define (make-extender get-base% name [final-mixin values]) (define extend-name (string->symbol (format "extend-~a" name))) (define names-for-changes '()) (define extensions '()) (define built-yet? #f) (define built #f) (define ((verify f) %) (define new% (f %)) (if (and (class? new%) (subclass? new% %)) new% (error extend-name "expected output of extension to create a subclass of its input, got: ~a" new%))) (define (add-extender extension [before? #t] #:name-for-changes [name-for-changes #f]) (cond [(and (symbol? name-for-changes) (member name-for-changes names-for-changes)) (cond [re-extension-allowed? (set! extensions (for/list ([e-extension (in-list extensions)] [e-name (in-list names-for-changes)]) (if (equal? e-name name-for-changes) extension e-extension))) (set! built-yet? #f) (set! built #f)] [else (error extend-name "attempted to use name ~s multiple times without first enabling re-extensions" name-for-changes)])] [else (when built-yet? (cond [re-extension-allowed? (set! built-yet? #f) (set! built #f)] [else (error extend-name "cannot build a new extension of ~a after initialization" name-for-changes)])) (set! extensions (if before? (cons (verify extension) extensions) (append extensions (list (verify extension))))) (set! names-for-changes (if before? (cons name-for-changes names-for-changes) (append names-for-changes (list name-for-changes))))])) (define (get-built) (unless built-yet? (set! built-yet? #t) (set! built (final-mixin ((apply compose extensions) (get-base%))))) built) (values (procedure-rename add-extender extend-name) (procedure-rename get-built (string->symbol (format "get-~a" name))))) (define (get-base-tab%) (drracket:module-language:module-language-online-expand-tab-mixin (drracket:module-language-tools:tab-mixin (drracket:tracing:tab-mixin (drracket:debug:test-coverage-tab-mixin (drracket:debug:profile-tab-mixin drracket:unit:tab%)))))) (define-values (extend-tab get-tab) (make-extender get-base-tab% 'tab%)) (define (get-base-interactions-canvas%) drracket:unit:interactions-canvas%) (define-values (extend-interactions-canvas get-interactions-canvas) (make-extender get-base-interactions-canvas% 'interactions-canvas%)) (define (get-base-definitions-canvas%) drracket:unit:definitions-canvas%) (define-values (extend-definitions-canvas get-definitions-canvas) (make-extender get-base-definitions-canvas% 'definitions-canvas%)) (define (get-base-unit-frame%) (drracket:module-language-tools:frame-mixin (drracket:tracing:frame-mixin (drracket:debug:test-coverage-frame-mixin (drracket:debug:profile-unit-frame-mixin drracket:unit:frame%))))) (define-values (extend-unit-frame get-unit-frame) (make-extender get-base-unit-frame% 'drracket:unit:frame)) (define (get-base-interactions-text%) (drracket:module-language-tools:interactions-text-mixin (drracket:module-language:module-language-online-expand-rep-mixin (drracket:module-language:module-language-big-defs/ints-interactions-text-mixin (drracket:debug:test-coverage-interactions-text-mixin drracket:rep:text%))))) (define-values (extend-interactions-text get-interactions-text) (make-extender get-base-interactions-text% 'interactions-text%)) (define (get-base-definitions-text%) (drracket:module-language:module-language-online-expand-text-mixin (drracket:module-language-tools:definitions-text-mixin (drracket:module-language:module-language-big-defs/ints-definitions-text-mixin (drracket:debug:test-coverage-definitions-text-mixin (drracket:debug:profile-definitions-text-mixin (drracket:module-language:modes-mixin (drracket:unit:get-definitions-text%)))))))) (define-values (extend-definitions-text get-definitions-text) (make-extender get-base-definitions-text% 'definitions-text% (let ([add-on-paint-logging (λ (%) (class % (define/override (on-paint before? dc left top right bottom dx dy draw-caret) (log-timeline (format "on-paint method of ~a area: ~a" (object-name this) (* (- right left) (- bottom top))) (super on-paint before? dc left top right bottom dx dy draw-caret))) (super-new)))]) add-on-paint-logging)))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/share/pkgs/drracket/drracket/private/get-extend.rkt
racket
#lang racket/unit (require racket/class drracket/private/drsig framework/private/logging-timer) (import [prefix drracket:unit: drracket:unit^] [prefix drracket:frame: drracket:frame^] [prefix drracket:rep: drracket:rep^] [prefix drracket:debug: drracket:debug^] [prefix drracket:tracing: drracket:tracing^] [prefix drracket:module-language: drracket:module-language/int^] [prefix drracket:module-language-tools: drracket:module-language-tools/int^]) (export drracket:get/extend^) (define re-extension-allowed? #f) (define (allow-re-extension!) (set! re-extension-allowed? #t)) (define (disallow-re-extension!) (set! re-extension-allowed? #f)) (define (make-extender get-base% name [final-mixin values]) (define extend-name (string->symbol (format "extend-~a" name))) (define names-for-changes '()) (define extensions '()) (define built-yet? #f) (define built #f) (define ((verify f) %) (define new% (f %)) (if (and (class? new%) (subclass? new% %)) new% (error extend-name "expected output of extension to create a subclass of its input, got: ~a" new%))) (define (add-extender extension [before? #t] #:name-for-changes [name-for-changes #f]) (cond [(and (symbol? name-for-changes) (member name-for-changes names-for-changes)) (cond [re-extension-allowed? (set! extensions (for/list ([e-extension (in-list extensions)] [e-name (in-list names-for-changes)]) (if (equal? e-name name-for-changes) extension e-extension))) (set! built-yet? #f) (set! built #f)] [else (error extend-name "attempted to use name ~s multiple times without first enabling re-extensions" name-for-changes)])] [else (when built-yet? (cond [re-extension-allowed? (set! built-yet? #f) (set! built #f)] [else (error extend-name "cannot build a new extension of ~a after initialization" name-for-changes)])) (set! extensions (if before? (cons (verify extension) extensions) (append extensions (list (verify extension))))) (set! names-for-changes (if before? (cons name-for-changes names-for-changes) (append names-for-changes (list name-for-changes))))])) (define (get-built) (unless built-yet? (set! built-yet? #t) (set! built (final-mixin ((apply compose extensions) (get-base%))))) built) (values (procedure-rename add-extender extend-name) (procedure-rename get-built (string->symbol (format "get-~a" name))))) (define (get-base-tab%) (drracket:module-language:module-language-online-expand-tab-mixin (drracket:module-language-tools:tab-mixin (drracket:tracing:tab-mixin (drracket:debug:test-coverage-tab-mixin (drracket:debug:profile-tab-mixin drracket:unit:tab%)))))) (define-values (extend-tab get-tab) (make-extender get-base-tab% 'tab%)) (define (get-base-interactions-canvas%) drracket:unit:interactions-canvas%) (define-values (extend-interactions-canvas get-interactions-canvas) (make-extender get-base-interactions-canvas% 'interactions-canvas%)) (define (get-base-definitions-canvas%) drracket:unit:definitions-canvas%) (define-values (extend-definitions-canvas get-definitions-canvas) (make-extender get-base-definitions-canvas% 'definitions-canvas%)) (define (get-base-unit-frame%) (drracket:module-language-tools:frame-mixin (drracket:tracing:frame-mixin (drracket:debug:test-coverage-frame-mixin (drracket:debug:profile-unit-frame-mixin drracket:unit:frame%))))) (define-values (extend-unit-frame get-unit-frame) (make-extender get-base-unit-frame% 'drracket:unit:frame)) (define (get-base-interactions-text%) (drracket:module-language-tools:interactions-text-mixin (drracket:module-language:module-language-online-expand-rep-mixin (drracket:module-language:module-language-big-defs/ints-interactions-text-mixin (drracket:debug:test-coverage-interactions-text-mixin drracket:rep:text%))))) (define-values (extend-interactions-text get-interactions-text) (make-extender get-base-interactions-text% 'interactions-text%)) (define (get-base-definitions-text%) (drracket:module-language:module-language-online-expand-text-mixin (drracket:module-language-tools:definitions-text-mixin (drracket:module-language:module-language-big-defs/ints-definitions-text-mixin (drracket:debug:test-coverage-definitions-text-mixin (drracket:debug:profile-definitions-text-mixin (drracket:module-language:modes-mixin (drracket:unit:get-definitions-text%)))))))) (define-values (extend-definitions-text get-definitions-text) (make-extender get-base-definitions-text% 'definitions-text% (let ([add-on-paint-logging (λ (%) (class % (define/override (on-paint before? dc left top right bottom dx dy draw-caret) (log-timeline (format "on-paint method of ~a area: ~a" (object-name this) (* (- right left) (- bottom top))) (super on-paint before? dc left top right bottom dx dy draw-caret))) (super-new)))]) add-on-paint-logging)))
4aafe0b6aec359f18954a0131454e7f925423b5a4e6e76f301fb483098922c1d
abhinav/pinch
Bits.hs
{-# LANGUAGE CPP #-} # LANGUAGE MagicHash # -- | Module : Pinch . Internal . Bits Copyright : ( c ) 2015 -- License : BSD3 -- Maintainer : < > -- Stability : experimental -- -- Provides unchecked bitwise shift operations. Similar versions of @shiftR@ -- are used by @ByteString.Builder.Prim@. module Pinch.Internal.Bits ( w16ShiftL , w32ShiftL , w64ShiftL ) where #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) import GHC.Base ( Int (..), #if MIN_VERSION_base(4,16,0) uncheckedShiftLWord16#, uncheckedShiftLWord32#, #endif #if MIN_VERSION_ghc_prim(0,9,0) uncheckedShiftL64#, #else uncheckedShiftL#, #endif ) import GHC.Word (Word16 (..), Word32 (..), Word64 (..)) #else import Data.Bits (shiftL) import Data.Word (Word16, Word32, Word64) #endif # INLINE w16ShiftL # w16ShiftL :: Word16 -> Int -> Word16 # INLINE w32ShiftL # w32ShiftL :: Word32 -> Int -> Word32 # INLINE w64ShiftL # w64ShiftL :: Word64 -> Int -> Word64 If we 're not on GHC , the regular shiftL will be returned . #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) #if MIN_VERSION_base(4,16,0) w16ShiftL (W16# w) (I# i) = W16# (w `uncheckedShiftLWord16#` i) w32ShiftL (W32# w) (I# i) = W32# (w `uncheckedShiftLWord32#` i) #else w16ShiftL (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i) w32ShiftL (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i) #endif #if MIN_VERSION_ghc_prim(0,9,0) w64ShiftL (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i) #else w64ShiftL (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i) #endif #else w16ShiftL = shiftL w32ShiftL = shiftL w64ShiftL = shiftL #endif
null
https://raw.githubusercontent.com/abhinav/pinch/2ac323ab7c64b5fdf8a5f8206f790ef03ec8a23c/src/Pinch/Internal/Bits.hs
haskell
# LANGUAGE CPP # | License : BSD3 Stability : experimental Provides unchecked bitwise shift operations. Similar versions of @shiftR@ are used by @ByteString.Builder.Prim@.
# LANGUAGE MagicHash # Module : Pinch . Internal . Bits Copyright : ( c ) 2015 Maintainer : < > module Pinch.Internal.Bits ( w16ShiftL , w32ShiftL , w64ShiftL ) where #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) import GHC.Base ( Int (..), #if MIN_VERSION_base(4,16,0) uncheckedShiftLWord16#, uncheckedShiftLWord32#, #endif #if MIN_VERSION_ghc_prim(0,9,0) uncheckedShiftL64#, #else uncheckedShiftL#, #endif ) import GHC.Word (Word16 (..), Word32 (..), Word64 (..)) #else import Data.Bits (shiftL) import Data.Word (Word16, Word32, Word64) #endif # INLINE w16ShiftL # w16ShiftL :: Word16 -> Int -> Word16 # INLINE w32ShiftL # w32ShiftL :: Word32 -> Int -> Word32 # INLINE w64ShiftL # w64ShiftL :: Word64 -> Int -> Word64 If we 're not on GHC , the regular shiftL will be returned . #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) #if MIN_VERSION_base(4,16,0) w16ShiftL (W16# w) (I# i) = W16# (w `uncheckedShiftLWord16#` i) w32ShiftL (W32# w) (I# i) = W32# (w `uncheckedShiftLWord32#` i) #else w16ShiftL (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i) w32ShiftL (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i) #endif #if MIN_VERSION_ghc_prim(0,9,0) w64ShiftL (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i) #else w64ShiftL (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i) #endif #else w16ShiftL = shiftL w32ShiftL = shiftL w64ShiftL = shiftL #endif
068d49cb034037a4ab6690869d7bd667460a4d8344e79540efc70aa3955c350f
the-dr-lazy/cascade
Create.hs
| Module : Test . Cascade . Api . StateMachine . Command . Project . Create Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Test.Cascade.Api.StateMachine.Command.Project.Create Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Test.Cascade.Api.StateMachine.Command.Project.Create ( create ) where import qualified Cascade.Api.Data.Project as Project import qualified Cascade.Api.Hedgehog.Gen.Api.Project as Gen import Cascade.Api.Network.TestClient ( AuthToken ) import qualified Cascade.Api.Network.TestClient.Api.User.Projects as Cascade.Api.User.Projects import qualified Cascade.Api.Servant.Response as Response import Cascade.Api.Test.Prelude ( evalUnion ) import Control.Lens ( at, has, ix, non, (?~), (^.), (^@..) ) import Data.Generics.Labels () import qualified Data.Map.Strict as Map import Hedgehog import qualified Hedgehog.Gen as Gen import Test.Cascade.Api.StateMachine.Model ( Model ) import qualified Test.Cascade.Api.StateMachine.Model.Lens as Model.Lens create :: MonadGen g => MonadIO m => MonadTest m => Command g m Model create = Command generator execute [Require require, Update update] data Create (v :: Type -> Type) = Create { creatable :: Project.Creatable , username :: Text , token :: Var AuthToken v } deriving stock (Generic, Show) instance HTraversable Create where htraverse f Create {..} = Create creatable username <$> htraverse f token generator :: MonadGen g => Model Symbolic -> Maybe (g (Create Symbolic)) generator model = case model ^@.. Model.Lens.indexTokenByUsername of [] -> Nothing usernameTokenAList -> Just do creatable <- Gen.project (username, token) <- Gen.element usernameTokenAList pure $ Create { .. } require :: Model Symbolic -> Create Symbolic -> Bool require model Create { username } = model |> has (#authToken . #byUsername . ix username) execute :: MonadIO m => MonadTest m => Create Concrete -> m Project.Id execute Create { creatable, token } = do label "[Project/Create]" response <- evalIO $ Cascade.Api.User.Projects.create (concrete token) creatable readable <- ensure response pure $ readable ^. #id update :: Ord1 v => Model v -> Create v -> Var Project.Id v -> Model v update model Create { username, creatable } projectId = model |> (#project . #byUsername . at username . non Map.empty . at projectId) ?~ creatable ensure :: MonadTest m => Cascade.Api.User.Projects.CreateResponse -> m Project.Readable ensure response = do Response.Created project <- (response ^. #responseBody) |> evalUnion @(Response.Created Project.Readable) pure project
null
https://raw.githubusercontent.com/the-dr-lazy/cascade/014a5589a2763ce373e8c84a211cddc479872b44/cascade-api/test/Test/Cascade/Api/StateMachine/Command/Project/Create.hs
haskell
| Module : Test . Cascade . Api . StateMachine . Command . Project . Create Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Test.Cascade.Api.StateMachine.Command.Project.Create Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Test.Cascade.Api.StateMachine.Command.Project.Create ( create ) where import qualified Cascade.Api.Data.Project as Project import qualified Cascade.Api.Hedgehog.Gen.Api.Project as Gen import Cascade.Api.Network.TestClient ( AuthToken ) import qualified Cascade.Api.Network.TestClient.Api.User.Projects as Cascade.Api.User.Projects import qualified Cascade.Api.Servant.Response as Response import Cascade.Api.Test.Prelude ( evalUnion ) import Control.Lens ( at, has, ix, non, (?~), (^.), (^@..) ) import Data.Generics.Labels () import qualified Data.Map.Strict as Map import Hedgehog import qualified Hedgehog.Gen as Gen import Test.Cascade.Api.StateMachine.Model ( Model ) import qualified Test.Cascade.Api.StateMachine.Model.Lens as Model.Lens create :: MonadGen g => MonadIO m => MonadTest m => Command g m Model create = Command generator execute [Require require, Update update] data Create (v :: Type -> Type) = Create { creatable :: Project.Creatable , username :: Text , token :: Var AuthToken v } deriving stock (Generic, Show) instance HTraversable Create where htraverse f Create {..} = Create creatable username <$> htraverse f token generator :: MonadGen g => Model Symbolic -> Maybe (g (Create Symbolic)) generator model = case model ^@.. Model.Lens.indexTokenByUsername of [] -> Nothing usernameTokenAList -> Just do creatable <- Gen.project (username, token) <- Gen.element usernameTokenAList pure $ Create { .. } require :: Model Symbolic -> Create Symbolic -> Bool require model Create { username } = model |> has (#authToken . #byUsername . ix username) execute :: MonadIO m => MonadTest m => Create Concrete -> m Project.Id execute Create { creatable, token } = do label "[Project/Create]" response <- evalIO $ Cascade.Api.User.Projects.create (concrete token) creatable readable <- ensure response pure $ readable ^. #id update :: Ord1 v => Model v -> Create v -> Var Project.Id v -> Model v update model Create { username, creatable } projectId = model |> (#project . #byUsername . at username . non Map.empty . at projectId) ?~ creatable ensure :: MonadTest m => Cascade.Api.User.Projects.CreateResponse -> m Project.Readable ensure response = do Response.Created project <- (response ^. #responseBody) |> evalUnion @(Response.Created Project.Readable) pure project
e771fcc97bbd52696b3816a8a166e1638e35da7c8ffd4dd8fa30c4d09f5627f2
jwiegley/notes
ComonadGraph.hs
{-# LANGUAGE RankNTypes #-} -- a tiny annotated graph library 2010 module Data.Graph.Annotated where import Data.Sequence as S import Data.Sequence (Sequence, ViewL(..), ViewR(..), (><)) import Data.Vector as V import Data.Ix import qualified Data.Graph as G import Data.Graph (Graph) import Control.Monad.Writer.Instances class PFunctor f where first :: (a -> b) -> f a c -> f b c a simple safe graph library based on Data . Graph for prototyping -- TODO: use Vector [Int] or Rope (Vector [Int]) newtype Graph b = Graph { runGraph :: G.Graph } newtype Vertex b = Vertex { vertexId :: Int } deriving (Enum,Ix,Eq,Ord,Show,Typeable) vertices :: Graph b -> [Vertex b] vertices = fmap Vertex . G.vertices . runGraph dfs :: Graph b -> [Vertex b] -> Forest (Vertex b) dfs g vs = fmap Vertex <$> G.dfs (runGraph g) (vertexId <$> vs) dff :: Graph b -> Forest (Vertex b) dff g = Vertex <$> G.dff (runGraph g) topSort :: Graph b -> [Vertex b] topSort g = Vertex <$> G.topSort (runGraph g) components :: Graph b -> Forest (Vertex b) components g = fmap Vertex <$> G.components (runGraph g) newtype Edge b = Edge (Vertex b, Vertex b) deriving (Ix,Eq,Ord,Show,Typeable) edges :: Graph b -> [Edge b] edges = fmap Edge . G.edges . runGraph newtype NodeAnn a b = NodeAnn (G.Table a) instance PFunctor NodeAnn where first f (NodeAnn t) = NodeAnn (f <$> t) indegree :: Graph b -> NodeAnn Int b indegree = NodeAnn . G.indegree . runGraph outdegree :: Graph b -> NodeAnn Int b outdegree = NodeAnn . G.outdegree . runGraph data Degree b = Degree { indegree :: NodeAnn Int b, outDegree :: NodeAnn Int b } degree :: Graph b -> (Degree `Annotated` Graph) b degree g = (g, Degree (indegree g) (outdegree g)) newtype k b = ( Map k IntSet ) ( IntMap [ k ] ) tag : : Ord k = > k - > Vertex b - > k b - > k b lookup : : k b - > k - > [ Vertex b ] -- used internally, expose? class Functor w => Comonad w where extract :: w a -> a extend :: (w a -> b) -> w a -> w b duplicate :: w a -> w (w a) duplicate = extend id extend f = fmap f . duplicate instance Comonad ((,)e) where extract = snd extend f ea = (fst ea, f ea) duplicate f ea@(e,_) = (e, f ea) type Annotated f s b = (s b, f b) -- existentially wrapped annotation data = forall ( ( f ` Annotated ` s ) b ) runAnn : : ( forall b. ( f ` Annotated ` s ) b - > r ) - > r runAnn ( a ) k = k a -- a boxed up annotated structure newtype Ann f s = Ann { runAnn :: forall r. (forall b. (f `Annotated` s) b -> r) -> r } -- we can transpose node annotations easily data Transpose b class TransposableAnn f where transposeAnn :: (f `Annotated` Graph) a -> f (Transpose a) instance TransposableAnn (NodeAnn a) where transposeAnn (NodeAnn t) = NodeAnn t transpose :: TransposableAnn f => (f `Annotated` Graph) b -> (f `Annotated` Graph) (Transpose b) transpose g = (G.transpose (runGraph g), transposeAnn g)
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/f719a3d41696d48f6005/ComonadGraph.hs
haskell
# LANGUAGE RankNTypes # a tiny annotated graph library TODO: use Vector [Int] or Rope (Vector [Int]) used internally, expose? existentially wrapped annotation a boxed up annotated structure we can transpose node annotations easily
2010 module Data.Graph.Annotated where import Data.Sequence as S import Data.Sequence (Sequence, ViewL(..), ViewR(..), (><)) import Data.Vector as V import Data.Ix import qualified Data.Graph as G import Data.Graph (Graph) import Control.Monad.Writer.Instances class PFunctor f where first :: (a -> b) -> f a c -> f b c a simple safe graph library based on Data . Graph for prototyping newtype Graph b = Graph { runGraph :: G.Graph } newtype Vertex b = Vertex { vertexId :: Int } deriving (Enum,Ix,Eq,Ord,Show,Typeable) vertices :: Graph b -> [Vertex b] vertices = fmap Vertex . G.vertices . runGraph dfs :: Graph b -> [Vertex b] -> Forest (Vertex b) dfs g vs = fmap Vertex <$> G.dfs (runGraph g) (vertexId <$> vs) dff :: Graph b -> Forest (Vertex b) dff g = Vertex <$> G.dff (runGraph g) topSort :: Graph b -> [Vertex b] topSort g = Vertex <$> G.topSort (runGraph g) components :: Graph b -> Forest (Vertex b) components g = fmap Vertex <$> G.components (runGraph g) newtype Edge b = Edge (Vertex b, Vertex b) deriving (Ix,Eq,Ord,Show,Typeable) edges :: Graph b -> [Edge b] edges = fmap Edge . G.edges . runGraph newtype NodeAnn a b = NodeAnn (G.Table a) instance PFunctor NodeAnn where first f (NodeAnn t) = NodeAnn (f <$> t) indegree :: Graph b -> NodeAnn Int b indegree = NodeAnn . G.indegree . runGraph outdegree :: Graph b -> NodeAnn Int b outdegree = NodeAnn . G.outdegree . runGraph data Degree b = Degree { indegree :: NodeAnn Int b, outDegree :: NodeAnn Int b } degree :: Graph b -> (Degree `Annotated` Graph) b degree g = (g, Degree (indegree g) (outdegree g)) newtype k b = ( Map k IntSet ) ( IntMap [ k ] ) tag : : Ord k = > k - > Vertex b - > k b - > k b lookup : : k b - > k - > [ Vertex b ] class Functor w => Comonad w where extract :: w a -> a extend :: (w a -> b) -> w a -> w b duplicate :: w a -> w (w a) duplicate = extend id extend f = fmap f . duplicate instance Comonad ((,)e) where extract = snd extend f ea = (fst ea, f ea) duplicate f ea@(e,_) = (e, f ea) type Annotated f s b = (s b, f b) data = forall ( ( f ` Annotated ` s ) b ) runAnn : : ( forall b. ( f ` Annotated ` s ) b - > r ) - > r runAnn ( a ) k = k a newtype Ann f s = Ann { runAnn :: forall r. (forall b. (f `Annotated` s) b -> r) -> r } data Transpose b class TransposableAnn f where transposeAnn :: (f `Annotated` Graph) a -> f (Transpose a) instance TransposableAnn (NodeAnn a) where transposeAnn (NodeAnn t) = NodeAnn t transpose :: TransposableAnn f => (f `Annotated` Graph) b -> (f `Annotated` Graph) (Transpose b) transpose g = (G.transpose (runGraph g), transposeAnn g)
9087828cd5ccc643ed0fa65f8b1cfc2e7cba2e8d8e396daa8e35cf3a15870f55
mstksg/inCode
invariant.hs
#!/usr/bin/env stack stack --install - ghc ghci --resolver lts-16 --package prettyprinter --package functor - combinators-0.3.6.0 --package aeson --package vinyl-0.13.0 --package contravariant --package scientific --package text --package semigroupoids --package free --package invariant --package aeson - better - errors --package kan - extensions # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} import Control.Monad import Data.Functor.Contravariant import Data.Functor.Invariant.DecAlt import Data.Functor.Invariant.DivAp import Data.Functor.Plus import Data.HFunctor import Data.HFunctor.HTraversable import Data.HFunctor.Interpret import Data.Scientific import qualified Data.Aeson as Aeson import qualified Data.Aeson.BetterErrors as A import qualified Data.Aeson.Types as Aeson import qualified Data.Text as T import qualified Data.Text.Prettyprint.Doc as PP data Schema a = RecordType (DivAp Field a) | SumType (DecAlt Choice a) | SchemaLeaf (Primitive a) data Field a = Field { fieldName :: String , fieldValue :: Schema a } data Choice a = Choice { choiceName :: String , choiceValue :: Schema a } data Primitive a = PString (a -> String) (String -> Maybe a) | PNumber (a -> Scientific) (Scientific -> Maybe a) | PBool (a -> Bool) (Bool -> Maybe a) pString :: Primitive String pString = PString id Just pInt :: Primitive Int pInt = PNumber fromIntegral toBoundedInteger data Customer = CPerson { cpName :: String, cpAge :: Int } | CBusiness { cbEmployees :: Int } deriving Show customerSchema :: Schema Customer customerSchema = SumType $ swerve (\case CPerson x y -> Left (x,y); CBusiness x -> Right x) (uncurry CPerson) CBusiness (inject Choice { choiceName = "Person" , choiceValue = RecordType $ gathered (inject Field { fieldName = "Name", fieldValue = SchemaLeaf pString }) (inject Field { fieldName = "Age" , fieldValue = SchemaLeaf pInt }) } ) (inject Choice { choiceName = "Business" , choiceValue = RecordType $ inject Field { fieldName = "Age" , fieldValue = SchemaLeaf pInt } } ) schemaDoc :: String -- ^ name -> Schema x -- ^ schema -> PP.Doc a schemaDoc title = \case RecordType fs -> PP.vsep [ PP.pretty ("{" <> title <> "}") , PP.indent 2 . PP.vsep $ htoList (\fld -> "*" PP.<+> PP.indent 2 (fieldDoc fld)) fs ] SumType cs -> PP.vsep [ PP.pretty ("(" <> title <> ")") , "Choice of:" , PP.indent 2 . PP.vsep $ htoList choiceDoc cs ] SchemaLeaf p -> PP.pretty (title <> ":") PP.<+> primDoc p where fieldDoc :: Field x -> PP.Doc a fieldDoc (Field name val) = schemaDoc name val choiceDoc :: Choice x -> PP.Doc a choiceDoc (Choice name val) = schemaDoc name val primDoc :: Primitive x -> PP.Doc a primDoc = \case PString _ _ -> "string" PNumber _ _ -> "number" PBool _ _ -> "bool" schemaToValue :: Schema a -> a -> Aeson.Value schemaToValue = \case RecordType fs -> Aeson.object . getOp (runContraDivAp fieldToValue fs) SumType cs -> getOp (runContraDecAlt choiceToValue cs) SchemaLeaf p -> primToValue p where choiceToValue :: Choice x -> Op Aeson.Value x choiceToValue (Choice name val) = Op $ \x -> Aeson.object [ "tag" Aeson..= T.pack name , "contents" Aeson..= schemaToValue val x ] fieldToValue :: Field x -> Op [Aeson.Pair] x fieldToValue (Field name val) = Op $ \x -> [T.pack name Aeson..= schemaToValue val x] primToValue :: Primitive x -> x -> Aeson.Value primToValue = \case PString f _ -> Aeson.String . T.pack . f PNumber f _ -> Aeson.Number . f PBool f _ -> Aeson.Bool . f schemaParser :: Schema a -> A.Parse String a schemaParser = \case RecordType fs -> runCoDivAp fieldParser fs SumType cs -> runCoDecAlt choiceParser cs SchemaLeaf p -> primParser p where choiceParser :: Choice b -> A.Parse String b choiceParser (Choice name val) = do tag <- A.key "tag" A.asString unless (tag == name) $ A.throwCustomError "Tag does not match" A.key "contents" $ schemaParser val fieldParser :: Field b -> A.Parse String b fieldParser (Field name val) = A.key (T.pack name) (schemaParser val) primParser :: Primitive b -> A.Parse String b primParser = \case PString _ f -> A.withString $ maybe (Left "error validating string") Right . f PNumber _ f -> A.withScientific $ maybe (Left "error validating number") Right . f PBool _ f -> A.withBool $ maybe (Left "error validating bool") Right . f testRoundTrip :: Schema a -> a -> Either (A.ParseError String) a testRoundTrip sch = A.parseValue (schemaParser sch) . schemaToValue sch main :: IO () main = pure () instance Monad f => Alt (A.ParseT e f) where (<!>) = (A.<|>) instance (Monad f) => Plus (A.ParseT String f) where zero = A.throwCustomError "No options were validated" instance Monad m => Apply (A.ParseT e m) where (<.>) = (<*>)
null
https://raw.githubusercontent.com/mstksg/inCode/e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a/code-samples/functor-structures/invariant.hs
haskell
install - ghc ghci --resolver lts-16 --package prettyprinter --package functor - combinators-0.3.6.0 --package aeson --package vinyl-0.13.0 --package contravariant --package scientific --package text --package semigroupoids --package free --package invariant --package aeson - better - errors --package kan - extensions # LANGUAGE OverloadedStrings # # LANGUAGE TypeSynonymInstances # ^ name ^ schema
#!/usr/bin/env stack # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # import Control.Monad import Data.Functor.Contravariant import Data.Functor.Invariant.DecAlt import Data.Functor.Invariant.DivAp import Data.Functor.Plus import Data.HFunctor import Data.HFunctor.HTraversable import Data.HFunctor.Interpret import Data.Scientific import qualified Data.Aeson as Aeson import qualified Data.Aeson.BetterErrors as A import qualified Data.Aeson.Types as Aeson import qualified Data.Text as T import qualified Data.Text.Prettyprint.Doc as PP data Schema a = RecordType (DivAp Field a) | SumType (DecAlt Choice a) | SchemaLeaf (Primitive a) data Field a = Field { fieldName :: String , fieldValue :: Schema a } data Choice a = Choice { choiceName :: String , choiceValue :: Schema a } data Primitive a = PString (a -> String) (String -> Maybe a) | PNumber (a -> Scientific) (Scientific -> Maybe a) | PBool (a -> Bool) (Bool -> Maybe a) pString :: Primitive String pString = PString id Just pInt :: Primitive Int pInt = PNumber fromIntegral toBoundedInteger data Customer = CPerson { cpName :: String, cpAge :: Int } | CBusiness { cbEmployees :: Int } deriving Show customerSchema :: Schema Customer customerSchema = SumType $ swerve (\case CPerson x y -> Left (x,y); CBusiness x -> Right x) (uncurry CPerson) CBusiness (inject Choice { choiceName = "Person" , choiceValue = RecordType $ gathered (inject Field { fieldName = "Name", fieldValue = SchemaLeaf pString }) (inject Field { fieldName = "Age" , fieldValue = SchemaLeaf pInt }) } ) (inject Choice { choiceName = "Business" , choiceValue = RecordType $ inject Field { fieldName = "Age" , fieldValue = SchemaLeaf pInt } } ) schemaDoc -> PP.Doc a schemaDoc title = \case RecordType fs -> PP.vsep [ PP.pretty ("{" <> title <> "}") , PP.indent 2 . PP.vsep $ htoList (\fld -> "*" PP.<+> PP.indent 2 (fieldDoc fld)) fs ] SumType cs -> PP.vsep [ PP.pretty ("(" <> title <> ")") , "Choice of:" , PP.indent 2 . PP.vsep $ htoList choiceDoc cs ] SchemaLeaf p -> PP.pretty (title <> ":") PP.<+> primDoc p where fieldDoc :: Field x -> PP.Doc a fieldDoc (Field name val) = schemaDoc name val choiceDoc :: Choice x -> PP.Doc a choiceDoc (Choice name val) = schemaDoc name val primDoc :: Primitive x -> PP.Doc a primDoc = \case PString _ _ -> "string" PNumber _ _ -> "number" PBool _ _ -> "bool" schemaToValue :: Schema a -> a -> Aeson.Value schemaToValue = \case RecordType fs -> Aeson.object . getOp (runContraDivAp fieldToValue fs) SumType cs -> getOp (runContraDecAlt choiceToValue cs) SchemaLeaf p -> primToValue p where choiceToValue :: Choice x -> Op Aeson.Value x choiceToValue (Choice name val) = Op $ \x -> Aeson.object [ "tag" Aeson..= T.pack name , "contents" Aeson..= schemaToValue val x ] fieldToValue :: Field x -> Op [Aeson.Pair] x fieldToValue (Field name val) = Op $ \x -> [T.pack name Aeson..= schemaToValue val x] primToValue :: Primitive x -> x -> Aeson.Value primToValue = \case PString f _ -> Aeson.String . T.pack . f PNumber f _ -> Aeson.Number . f PBool f _ -> Aeson.Bool . f schemaParser :: Schema a -> A.Parse String a schemaParser = \case RecordType fs -> runCoDivAp fieldParser fs SumType cs -> runCoDecAlt choiceParser cs SchemaLeaf p -> primParser p where choiceParser :: Choice b -> A.Parse String b choiceParser (Choice name val) = do tag <- A.key "tag" A.asString unless (tag == name) $ A.throwCustomError "Tag does not match" A.key "contents" $ schemaParser val fieldParser :: Field b -> A.Parse String b fieldParser (Field name val) = A.key (T.pack name) (schemaParser val) primParser :: Primitive b -> A.Parse String b primParser = \case PString _ f -> A.withString $ maybe (Left "error validating string") Right . f PNumber _ f -> A.withScientific $ maybe (Left "error validating number") Right . f PBool _ f -> A.withBool $ maybe (Left "error validating bool") Right . f testRoundTrip :: Schema a -> a -> Either (A.ParseError String) a testRoundTrip sch = A.parseValue (schemaParser sch) . schemaToValue sch main :: IO () main = pure () instance Monad f => Alt (A.ParseT e f) where (<!>) = (A.<|>) instance (Monad f) => Plus (A.ParseT String f) where zero = A.throwCustomError "No options were validated" instance Monad m => Apply (A.ParseT e m) where (<.>) = (<*>)
f907ed32940229ac07d7dbe1506ca3dcf525876b59855b69d1a2e76aa8f18fed
jacekschae/learn-reitit-course-files
routes.clj
(ns cheffy.conversation.routes (:require [cheffy.middleware :as mw] [cheffy.conversation.db :as conversation-db] [ring.util.response :as rr] [cheffy.responses :as responses]) (:import (java.util UUID))) (defn routes [env] (let [db (:jdbc-url env)] ["/conversation" {:swagger {:tags ["conversations"]} :middleware [[mw/wrap-auth0]]} ["" {:get {:handler (fn [request] (let [uid (-> request :claims :sub)] (rr/response (conversation-db/dispatch [:find-conversation-by-uid db {:uid uid}])))) :responses {200 {:body vector?}} :summary "List conversations"} :post {:handler (fn [request] (let [message (-> request :parameters :body) message-id (str (UUID/randomUUID)) from (-> request :claims :sub) conversation-id (conversation-db/dispatch [:start-conversation db (assoc message :message-id message-id :from from)])] (rr/created (str responses/base-url "/v1/conversations/" conversation-id) {:conversation-id conversation-id}))) :parameters {:body {:message-body string? :to string?}} :responses {201 {:body {:conversation-id string?}}} :summary "Start a conversation"}}] ["/:conversation-id" {:middleware [[mw/wrap-conversation-participant db]]} ["" {:get {:handler (fn [request] (let [conversation-id (-> request :parameters :path :conversation-id)] (rr/response (conversation-db/dispatch [:find-messages-by-conversation db {:converstaion-id conversation-id}])))) :parameters {:path {:conversation-id string?}} :responses {200 {:body vector?}} :summary "List conversation messages"} :post {:handler (fn [request] (let [conversation-id (-> request :parameters :path :conversation-id) message (-> request :parameters :body) message-id (str (UUID/randomUUID)) from (-> request :claims :sub)] (conversation-db/dispatch [:insert-message db (assoc message :message-id message-id :conversation-id conversation-id :from from)]) (rr/created (str responses/base-url "/v1/conversations" conversation-id) {:conversation-id conversation-id}))) :parameters {:path {:conversation-id string?} :body {:message-body string? :to string?}} :responses {201 {:body {:conversation-id string?}}} :summary "Create message"} :put {:handler (fn [request] (let [uid (-> request :claims :uid) conversation-id (-> request :parameters :path :conversation-id) updated? (conversation-db/dispatch [:clear-notifications db {:uid uid :conversation-id conversation-id}])] (when updated? (rr/status 204)))) :parameters {:path {:conversation-id string?}} :responses {204 {:body nil?}} :summary "Update notifications"}}]]]))
null
https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/57-conversation-tests/src/cheffy/conversation/routes.clj
clojure
(ns cheffy.conversation.routes (:require [cheffy.middleware :as mw] [cheffy.conversation.db :as conversation-db] [ring.util.response :as rr] [cheffy.responses :as responses]) (:import (java.util UUID))) (defn routes [env] (let [db (:jdbc-url env)] ["/conversation" {:swagger {:tags ["conversations"]} :middleware [[mw/wrap-auth0]]} ["" {:get {:handler (fn [request] (let [uid (-> request :claims :sub)] (rr/response (conversation-db/dispatch [:find-conversation-by-uid db {:uid uid}])))) :responses {200 {:body vector?}} :summary "List conversations"} :post {:handler (fn [request] (let [message (-> request :parameters :body) message-id (str (UUID/randomUUID)) from (-> request :claims :sub) conversation-id (conversation-db/dispatch [:start-conversation db (assoc message :message-id message-id :from from)])] (rr/created (str responses/base-url "/v1/conversations/" conversation-id) {:conversation-id conversation-id}))) :parameters {:body {:message-body string? :to string?}} :responses {201 {:body {:conversation-id string?}}} :summary "Start a conversation"}}] ["/:conversation-id" {:middleware [[mw/wrap-conversation-participant db]]} ["" {:get {:handler (fn [request] (let [conversation-id (-> request :parameters :path :conversation-id)] (rr/response (conversation-db/dispatch [:find-messages-by-conversation db {:converstaion-id conversation-id}])))) :parameters {:path {:conversation-id string?}} :responses {200 {:body vector?}} :summary "List conversation messages"} :post {:handler (fn [request] (let [conversation-id (-> request :parameters :path :conversation-id) message (-> request :parameters :body) message-id (str (UUID/randomUUID)) from (-> request :claims :sub)] (conversation-db/dispatch [:insert-message db (assoc message :message-id message-id :conversation-id conversation-id :from from)]) (rr/created (str responses/base-url "/v1/conversations" conversation-id) {:conversation-id conversation-id}))) :parameters {:path {:conversation-id string?} :body {:message-body string? :to string?}} :responses {201 {:body {:conversation-id string?}}} :summary "Create message"} :put {:handler (fn [request] (let [uid (-> request :claims :uid) conversation-id (-> request :parameters :path :conversation-id) updated? (conversation-db/dispatch [:clear-notifications db {:uid uid :conversation-id conversation-id}])] (when updated? (rr/status 204)))) :parameters {:path {:conversation-id string?}} :responses {204 {:body nil?}} :summary "Update notifications"}}]]]))
2200cd1f79c4eb9492d49c518e466c8c4cf739ed9b1a100ae6f7077dc7a8be6a
nasser/magic
generated_types.clj
(ns magic.analyzer.generated-types (:require [magic.analyzer.types :as types]) (:import [System.Reflection TypeAttributes])) (def ^:dynamic *reusable-types* nil) (def public TypeAttributes/Public) (def interface (enum-or TypeAttributes/Public TypeAttributes/Abstract TypeAttributes/Interface)) (def public-sealed (enum-or TypeAttributes/Public TypeAttributes/Sealed)) (defn type-match [type super interfaces attributes] (when (and (= super (.BaseType type)) (= attributes (.Attributes type)) (= (into #{} interfaces) (into #{} (.GetInterfaces type)))) type)) (defn define-new-type [module-builder name super interfaces attributes] (types/type-lookup-cache-evict! name) (if module-builder (.DefineType module-builder name attributes super (into-array Type interfaces)) (throw (Exception. (str "no module builder provided when defining new type " name ", was magic.emission/*module* bound?"))))) (defn fresh-type [module-builder name super interfaces attributes] (if *reusable-types* (if-let [type (some #(type-match % super interfaces attributes) @*reusable-types*)] (do (swap! *reusable-types* disj type) type) (do (println "[fresh-type] making new type") (define-new-type module-builder name super interfaces attributes))) (define-new-type module-builder name super interfaces attributes))) (defn deftype-type [module-builder name interfaces] (fresh-type module-builder name Object interfaces public)) (defn gen-interface-type [module-builder name interfaces] (fresh-type module-builder name Object interfaces interface)) (defn fn-type [module-builder name interfaces] (fresh-type module-builder name clojure.lang.AFunction interfaces public)) (defn variadic-fn-type [module-builder name interfaces] (fresh-type module-builder name clojure.lang.RestFn interfaces public)) (defn proxy-type [module-builder name super interfaces] (fresh-type module-builder name super (conj interfaces clojure.lang.IProxy) public)) (defn reify-type [module-builder name interfaces] (fresh-type module-builder name Object interfaces public-sealed))
null
https://raw.githubusercontent.com/nasser/magic/7a46f773bc7785c82d9527d52c1a8c28ac16e195/src/magic/analyzer/generated_types.clj
clojure
(ns magic.analyzer.generated-types (:require [magic.analyzer.types :as types]) (:import [System.Reflection TypeAttributes])) (def ^:dynamic *reusable-types* nil) (def public TypeAttributes/Public) (def interface (enum-or TypeAttributes/Public TypeAttributes/Abstract TypeAttributes/Interface)) (def public-sealed (enum-or TypeAttributes/Public TypeAttributes/Sealed)) (defn type-match [type super interfaces attributes] (when (and (= super (.BaseType type)) (= attributes (.Attributes type)) (= (into #{} interfaces) (into #{} (.GetInterfaces type)))) type)) (defn define-new-type [module-builder name super interfaces attributes] (types/type-lookup-cache-evict! name) (if module-builder (.DefineType module-builder name attributes super (into-array Type interfaces)) (throw (Exception. (str "no module builder provided when defining new type " name ", was magic.emission/*module* bound?"))))) (defn fresh-type [module-builder name super interfaces attributes] (if *reusable-types* (if-let [type (some #(type-match % super interfaces attributes) @*reusable-types*)] (do (swap! *reusable-types* disj type) type) (do (println "[fresh-type] making new type") (define-new-type module-builder name super interfaces attributes))) (define-new-type module-builder name super interfaces attributes))) (defn deftype-type [module-builder name interfaces] (fresh-type module-builder name Object interfaces public)) (defn gen-interface-type [module-builder name interfaces] (fresh-type module-builder name Object interfaces interface)) (defn fn-type [module-builder name interfaces] (fresh-type module-builder name clojure.lang.AFunction interfaces public)) (defn variadic-fn-type [module-builder name interfaces] (fresh-type module-builder name clojure.lang.RestFn interfaces public)) (defn proxy-type [module-builder name super interfaces] (fresh-type module-builder name super (conj interfaces clojure.lang.IProxy) public)) (defn reify-type [module-builder name interfaces] (fresh-type module-builder name Object interfaces public-sealed))
a3e1d7cb0c402505adc5879f827f9eddff787f4680e3ff879b150ac5b2da2e83
betaveros/bcodex
IntExpr.hs
module Text.Bcodex.IntExpr (parseIntExpr) where import Text.Read (readMaybe) Parse an expression such as " 1 " , " -1 " , " i " , " 3 + 4i " , into a list of values produced by substiting 0 , 1 etc . for i. Right now , only very simple -- expressions are supported: sums of constants and multiples of i. parseIntAtom :: String -> Maybe [Int] parseIntAtom "" = Just $ repeat 0 parseIntAtom "i" = Just [0..] parseIntAtom s | Just n <- readMaybe s = Just $ repeat n | Just n <- readMaybe $ init s, 'i' <- last s = Just [0,n..] | otherwise = Nothing -- modifier will be id or negate parseModifiedIntExpr :: (Int -> Int) -> String -> Maybe [Int] parseModifiedIntExpr modifier s = case break (`elem` "+-") s of (atom, "") -> map modifier <$> parseIntAtom atom (atom, sign:s') -> do atomList <- map modifier <$> parseIntAtom atom let modifier' = case sign of '+' -> id '-' -> negate _ -> error "impossible sign in parseModifiedIntExpr!" expr <- parseModifiedIntExpr modifier' s' return $ zipWith (+) atomList expr parseIntExpr :: String -> Maybe [Int] parseIntExpr = parseModifiedIntExpr id
null
https://raw.githubusercontent.com/betaveros/bcodex/90fadbf8215efa932212ae95fb5573df835f0c90/Text/Bcodex/IntExpr.hs
haskell
expressions are supported: sums of constants and multiples of i. modifier will be id or negate
module Text.Bcodex.IntExpr (parseIntExpr) where import Text.Read (readMaybe) Parse an expression such as " 1 " , " -1 " , " i " , " 3 + 4i " , into a list of values produced by substiting 0 , 1 etc . for i. Right now , only very simple parseIntAtom :: String -> Maybe [Int] parseIntAtom "" = Just $ repeat 0 parseIntAtom "i" = Just [0..] parseIntAtom s | Just n <- readMaybe s = Just $ repeat n | Just n <- readMaybe $ init s, 'i' <- last s = Just [0,n..] | otherwise = Nothing parseModifiedIntExpr :: (Int -> Int) -> String -> Maybe [Int] parseModifiedIntExpr modifier s = case break (`elem` "+-") s of (atom, "") -> map modifier <$> parseIntAtom atom (atom, sign:s') -> do atomList <- map modifier <$> parseIntAtom atom let modifier' = case sign of '+' -> id '-' -> negate _ -> error "impossible sign in parseModifiedIntExpr!" expr <- parseModifiedIntExpr modifier' s' return $ zipWith (+) atomList expr parseIntExpr :: String -> Maybe [Int] parseIntExpr = parseModifiedIntExpr id
389d785c3b8122ba5d3a26709eaee78ab4e2d94e7346fba669c0315af3a9b514
lrascao/simple_web_server
simple_web_server_app.erl
-module(simple_web_server_app). -behaviour(application). -export([start/2, stop/1]). start(_Type, _StartArgs) -> {ok, _} = simple_web_server:http_start(), simple_web_server_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/lrascao/simple_web_server/d5418f3dca4c436c29223fbb518713e30fb228d0/src/simple_web_server_app.erl
erlang
-module(simple_web_server_app). -behaviour(application). -export([start/2, stop/1]). start(_Type, _StartArgs) -> {ok, _} = simple_web_server:http_start(), simple_web_server_sup:start_link(). stop(_State) -> ok.
d430a61dd07cf0ad0e12225fcebf3d0104705274b7355551b53f17fa04905ecf
Tavistock/lseq-tree
base.cljc
(ns lseq-tree.base (:require [lseq-tree.util :refer [pow]])) (defrecord Base [size]) (defn bit [{:keys [size]} n] (+ size n)) (defn sum [{:keys [size] :as base} level] (let [x (bit base level) y (- size 1)] (- (/ (* x (+ x 1)) 2) (/ (* y (+ y 1)) 2)))) (defn interval [base lower upper level] (loop [lower lower, upper upper depth 0, acc 0, common-root true, low-greater false] (if (> depth level) acc (let [low-val (or (-> lower :triple :path) 0) up-val (or (-> upper :triple :path) 0) diverge? (and common-root (not (== low-val up-val))) common-root (if diverge? false common-root) low-greater (if diverge? (> low-val up-val) low-greater) up-val1 (if low-greater (dec (pow 2 (bit base depth))) up-val) acc1 (+ acc (- up-val1 low-val (if (or common-root low-greater (not= depth level)) 0 1))) acc2 (if (not= depth level) (* acc1 (pow 2 (bit base (+ depth 1)))) acc1)] (recur (-> lower :children first), (-> upper :children first) (inc depth) acc2, common-root, low-greater))))) (defn depth-max [base n] (int (dec (pow 2 (bit base n))))) (defn base ([] (base 3)) ([n] (Base. n)))
null
https://raw.githubusercontent.com/Tavistock/lseq-tree/4b75e43477fdeb421c5bf56f65be71c108378673/src/lseq_tree/base.cljc
clojure
(ns lseq-tree.base (:require [lseq-tree.util :refer [pow]])) (defrecord Base [size]) (defn bit [{:keys [size]} n] (+ size n)) (defn sum [{:keys [size] :as base} level] (let [x (bit base level) y (- size 1)] (- (/ (* x (+ x 1)) 2) (/ (* y (+ y 1)) 2)))) (defn interval [base lower upper level] (loop [lower lower, upper upper depth 0, acc 0, common-root true, low-greater false] (if (> depth level) acc (let [low-val (or (-> lower :triple :path) 0) up-val (or (-> upper :triple :path) 0) diverge? (and common-root (not (== low-val up-val))) common-root (if diverge? false common-root) low-greater (if diverge? (> low-val up-val) low-greater) up-val1 (if low-greater (dec (pow 2 (bit base depth))) up-val) acc1 (+ acc (- up-val1 low-val (if (or common-root low-greater (not= depth level)) 0 1))) acc2 (if (not= depth level) (* acc1 (pow 2 (bit base (+ depth 1)))) acc1)] (recur (-> lower :children first), (-> upper :children first) (inc depth) acc2, common-root, low-greater))))) (defn depth-max [base n] (int (dec (pow 2 (bit base n))))) (defn base ([] (base 3)) ([n] (Base. n)))
a60064247099faa1b56b48fbf750e5fbbe7f5970e17881bf38960fc0bf846932
protolude/protolude
Protolude.hs
# LANGUAGE CPP # # LANGUAGE Trustworthy # {-# LANGUAGE BangPatterns #-} # LANGUAGE FlexibleContexts # # LANGUAGE NoImplicitPrelude # # LANGUAGE ExplicitNamespaces # # OPTIONS_GHC -fno - warn - unused - imports # module Protolude ( -- * Base functions module Base, identity, pass, #if !MIN_VERSION_base(4,8,0) (&), scanl', #endif -- * Function functions module Function, applyN, -- * List functions module List, map, uncons, unsnoc, -- * Data Structures module DataStructures, -- * Show functions module Show, show, print, -- * Bool functions module Bool, -- * Monad functions module Monad, liftIO1, liftIO2, -- * Functor functions module Functor, -- * Either functions module Either, -- * Applicative functions module Applicative, guarded, guardedA, -- * String conversion module ConvertText, -- * Debug functions module Debug, -- * Panic functions module Panic, -- * Exception functions module Exception, Protolude.throwIO, Protolude.throwTo, -- * Semiring functions module Semiring, -- * String functions module String, -- * Safe functions module Safe, -- * Eq functions module Eq, * functions module Ord, * functions module Traversable, -- * Foldable functions module Foldable, -- * Semigroup functions #if MIN_VERSION_base(4,9,0) module Semigroup, #endif -- * Monoid functions module Monoid, -- * Bifunctor functions module Bifunctor, -- * Bifunctor functions module Hashable, -- * Deepseq functions module DeepSeq, -- * Tuple functions module Tuple, module Typeable, #if MIN_VERSION_base(4,7,0) -- * Typelevel programming module Typelevel, #endif -- * Monads module Fail, module State, module Reader, module Except, module Trans, module ST, module STM, -- * Integers module Int, module Bits, -- * Complex functions module Complex, * functions module Char, -- * Maybe functions module Maybe, -- * Generics functions module Generics, -- * ByteString functions module ByteString, LByteString, -- * Text functions module Text, LText, -- * Read functions module Read, readMaybe, readEither, -- * System functions module System, die, -- * Concurrency functions module Concurrency, -- * Foreign functions module Foreign, ) where -- Protolude module exports. import Protolude.Debug as Debug import Protolude.List as List import Protolude.Show as Show import Protolude.Bool as Bool import Protolude.Monad as Monad import Protolude.Functor as Functor import Protolude.Either as Either import Protolude.Applicative as Applicative import Protolude.ConvertText as ConvertText import Protolude.Panic as Panic import Protolude.Exceptions as Exception import Protolude.Semiring as Semiring import qualified Protolude.Conv as Conv import Protolude.Base as Base hiding ( putStr -- Overriden by Show.putStr , putStrLn -- Overriden by Show.putStrLn , print -- Overriden by Protolude.print Overriden by Protolude.show , showFloat -- Custom Show instances deprecated. , showList -- Custom Show instances deprecated. , showSigned -- Custom Show instances deprecated. , showSignedFloat -- Custom Show instances deprecated. , showsPrec -- Custom Show instances deprecated. ) import qualified Protolude.Base as PBase -- Used for 'show', not exported. import Data.String (String) import Data.String as String (IsString) -- Maybe'ized version of partial functions import Protolude.Safe as Safe ( headMay , headDef , initMay , initDef , initSafe , tailMay , tailDef , tailSafe , lastDef , lastMay , foldr1May , foldl1May , foldl1May' , maximumMay , minimumMay , maximumDef , minimumDef , atMay , atDef ) Applicatives import Control.Applicative as Applicative ( Applicative(..) , Alternative(..) , Const(Const,getConst) , ZipList(ZipList,getZipList) , (<**>) , liftA , liftA2 , liftA3 , optional ) -- Base typeclasses import Data.Eq as Eq ( Eq(..) ) import Data.Ord as Ord ( Ord(..) , Ordering(LT,EQ,GT) , Down(Down) , comparing ) import Data.Traversable as Traversable import Data.Foldable as Foldable ( Foldable, fold, foldMap, foldr, foldr', foldl, foldl', toList, #if MIN_VERSION_base(4,8,0) null, length, #endif elem, maximum, minimum, foldrM, foldlM, traverse_, for_, mapM_, forM_, sequence_, sequenceA_, asum, msum, concat, concatMap, and, or, any, all, maximumBy, minimumBy, notElem, find, ) import Data.Functor.Identity as Functor ( Identity(Identity, runIdentity) ) #if MIN_VERSION_base(4,9,0) import Data.List.NonEmpty as List ( NonEmpty((:|)) , nonEmpty ) import Data.Semigroup as Semigroup ( Semigroup(sconcat, stimes) , WrappedMonoid , diff , cycle1 , stimesMonoid , stimesIdempotent , stimesIdempotentMonoid , mtimesDefault ) #endif #if MIN_VERSION_base(4,9,0) && !MIN_VERSION_base(4,16,0) import Data.Semigroup as Semigroup ( Option(..) , option ) #endif import Data.Monoid as Monoid #if !MIN_VERSION_base(4,8,0) import Protolude.Bifunctor as Bifunctor (Bifunctor(bimap, first, second)) #else import Data.Bifunctor as Bifunctor (Bifunctor(bimap, first, second)) #endif -- Deepseq import Control.DeepSeq as DeepSeq ( NFData(..) , ($!!) , deepseq , force ) -- Data structures import Data.Tuple as Tuple ( fst , snd , curry , uncurry , swap ) import Data.List as List ( splitAt , break , intercalate , isPrefixOf , isInfixOf , isSuffixOf , drop , filter , reverse , replicate , take , sortBy , sort , intersperse , transpose , subsequences , permutations , scanl #if MIN_VERSION_base(4,8,0) , scanl' #endif , scanr , iterate , repeat , cycle , unfoldr , takeWhile , dropWhile , group , inits , tails , zipWith , zip , unzip , genericLength , genericTake , genericDrop , genericSplitAt , genericReplicate ) #if !MIN_VERSION_base(4,8,0) These imports are required for the ' rewrite rules import GHC.Exts (build) import Data.List (tail) #endif -- Hashing import Data.Hashable as Hashable ( Hashable , hash , hashWithSalt , hashUsing ) import Data.Map as DataStructures (Map) import Data.Set as DataStructures (Set) import Data.Sequence as DataStructures (Seq) import Data.IntMap as DataStructures (IntMap) import Data.IntSet as DataStructures (IntSet) import Data.Typeable as Typeable ( TypeRep , Typeable , typeOf , cast , gcast #if MIN_VERSION_base(4,7,0) , typeRep , eqT #endif ) #if MIN_VERSION_base(4,7,0) import Data.Proxy as Typelevel ( Proxy(..) ) import Data.Type.Coercion as Typelevel ( Coercion(..) , coerceWith , repr ) import Data.Type.Equality as Typelevel ( (:~:)(..) , type (==) , sym , trans , castWith , gcastWith ) #endif #if MIN_VERSION_base(4,8,0) import Data.Void as Typelevel ( Void , absurd , vacuous ) #endif import Control.Monad.Fail as Fail ( MonadFail ) Monad transformers import Control.Monad.State as State ( MonadState , State , StateT(StateT) , put , get , gets , modify , state , withState , runState , execState , evalState , runStateT , execStateT , evalStateT ) import Control.Monad.Reader as Reader ( MonadReader , Reader , ReaderT(ReaderT) , ask , asks , local , reader , runReader , runReaderT ) import Control.Monad.Trans.Except as Except ( throwE , catchE ) import Control.Monad.Except as Except ( MonadError , Except , ExceptT(ExceptT) , throwError , catchError , runExcept , runExceptT , mapExcept , mapExceptT , withExcept , withExceptT ) import Control.Monad.Trans as Trans ( MonadIO , lift , liftIO ) -- Base types import Data.Int as Int ( Int , Int8 , Int16 , Int32 , Int64 ) import Data.Bits as Bits ( Bits, (.&.), (.|.), xor, complement, shift, rotate, #if MIN_VERSION_base(4,7,0) zeroBits, #endif bit, setBit, clearBit, complementBit, testBit, #if MIN_VERSION_base(4,7,0) bitSizeMaybe, #endif bitSize, isSigned, shiftL, shiftR, rotateL, rotateR, popCount, #if MIN_VERSION_base(4,7,0) FiniteBits, finiteBitSize, bitDefault, testBitDefault, popCountDefault, #endif #if MIN_VERSION_base(4,8,0) toIntegralSized, countLeadingZeros, countTrailingZeros, #endif ) import Data.Word as Bits ( Word , Word8 , Word16 , Word32 , Word64 #if MIN_VERSION_base(4,7,0) , byteSwap16 , byteSwap32 , byteSwap64 #endif ) import Data.Either as Either ( Either(Left,Right) , either , lefts , rights , partitionEithers #if MIN_VERSION_base(4,7,0) , isLeft , isRight #endif ) import Data.Complex as Complex ( Complex((:+)) , realPart , imagPart , mkPolar , cis , polar , magnitude , phase , conjugate ) import Data.Char as Char ( Char , ord , chr , digitToInt , intToDigit , toUpper , toLower , toTitle , isAscii , isLetter , isDigit , isHexDigit , isPrint , isAlpha , isAlphaNum , isUpper , isLower , isSpace , isControl ) import Data.Bool as Bool ( Bool(True, False), (&&), (||), not, otherwise ) import Data.Maybe as Maybe ( Maybe(Nothing, Just) , maybe , isJust , isNothing , fromMaybe , listToMaybe , maybeToList , catMaybes , mapMaybe ) import Data.Function as Function ( const , (.) , ($) , flip , fix , on #if MIN_VERSION_base(4,8,0) , (&) #endif ) Genericss import GHC.Generics as Generics ( Generic(..) , Generic1 , Rep , K1(..) , M1(..) , U1(..) , V1 , D1 , C1 , S1 , (:+:)(..) , (:*:)(..) , (:.:)(..) , Rec0 , Constructor(..) , Datatype(..) , Selector(..) , Fixity(..) , Associativity(..) #if ( __GLASGOW_HASKELL__ >= 800 ) , Meta(..) , FixityI(..) , URec #endif ) ByteString import qualified Data.ByteString.Lazy import Data.ByteString as ByteString (ByteString) -- Text import Data.Text as Text ( Text , lines , words , unlines , unwords ) import qualified Data.Text.Lazy import Data.Text.IO as Text ( getLine , getContents , interact , readFile , writeFile , appendFile ) import Data.Text.Lazy as Text ( toStrict , fromStrict ) import Data.Text.Encoding as Text ( encodeUtf8 , decodeUtf8 , decodeUtf8' , decodeUtf8With ) import Data.Text.Encoding.Error as Text ( OnDecodeError , OnError , UnicodeException , lenientDecode , strictDecode , ignore , replace ) -- IO import System.Environment as System (getArgs) import qualified System.Exit import System.Exit as System ( ExitCode(..) , exitWith , exitFailure , exitSuccess ) import System.IO as System ( Handle , FilePath , IOMode(..) , stdin , stdout , stderr , withFile , openFile ) -- ST import Control.Monad.ST as ST ( ST , runST , fixST ) -- Concurrency and Parallelism import Control.Exception as Exception ( Exception, toException, fromException, #if MIN_VERSION_base(4,8,0) displayException, #endif SomeException(SomeException) , IOException , ArithException( Overflow, Underflow, LossOfPrecision, DivideByZero, Denormal, RatioZeroDenominator ) , ArrayException(IndexOutOfBounds, UndefinedElement) , AssertionFailed(AssertionFailed) #if MIN_VERSION_base(4,7,0) , SomeAsyncException(SomeAsyncException) , asyncExceptionToException , asyncExceptionFromException #endif , AsyncException(StackOverflow, HeapOverflow, ThreadKilled, UserInterrupt) , NonTermination(NonTermination) , NestedAtomically(NestedAtomically) , BlockedIndefinitelyOnMVar(BlockedIndefinitelyOnMVar) , BlockedIndefinitelyOnSTM(BlockedIndefinitelyOnSTM) #if MIN_VERSION_base(4,8,0) , AllocationLimitExceeded(AllocationLimitExceeded) #endif #if MIN_VERSION_base(4,10,0) , CompactionFailed(CompactionFailed) #endif , Deadlock(Deadlock) , NoMethodError(NoMethodError) , PatternMatchFail(PatternMatchFail) , RecConError(RecConError) , RecSelError(RecSelError) , RecUpdError(RecUpdError) #if MIN_VERSION_base(4,9,0) , ErrorCall(ErrorCall, ErrorCallWithLocation) #else , ErrorCall(ErrorCall) #endif #if MIN_VERSION_base(4,9,0) , TypeError(TypeError) #endif , ioError , catch , catches , Handler(Handler) , catchJust , handle , handleJust , try , tryJust , evaluate , mapException , mask , mask_ , uninterruptibleMask , uninterruptibleMask_ , MaskingState(..) , getMaskingState #if MIN_VERSION_base(4,9,0) , interruptible #endif , allowInterrupt , bracket , bracket_ , bracketOnError , finally , onException ) import qualified Control.Exception as PException import Control.Monad.STM as STM ( STM , atomically #if !(MIN_VERSION_stm(2,5,0)) , always , alwaysSucceeds #endif , retry , orElse , check , throwSTM , catchSTM ) import Control.Concurrent.MVar as Concurrency ( MVar , newEmptyMVar , newMVar , takeMVar , putMVar , readMVar , swapMVar , tryTakeMVar , tryPutMVar , isEmptyMVar , withMVar #if MIN_VERSION_base(4,7,0) , withMVarMasked #endif , modifyMVar_ , modifyMVar , modifyMVarMasked_ , modifyMVarMasked #if MIN_VERSION_base(4,7,0) , tryReadMVar , mkWeakMVar #endif , addMVarFinalizer ) import Control.Concurrent.Chan as Concurrency ( Chan , newChan , writeChan , readChan , dupChan , getChanContents , writeList2Chan ) import Control.Concurrent.QSem as Concurrency ( QSem , newQSem , waitQSem , signalQSem ) import Control.Concurrent.QSemN as Concurrency ( QSemN , newQSemN , waitQSemN , signalQSemN ) import Control.Concurrent as Concurrency ( ThreadId , forkIO , forkFinally , forkIOWithUnmask , killThread , forkOn , forkOnWithUnmask , getNumCapabilities , setNumCapabilities , threadCapability , yield , threadDelay , threadWaitRead , threadWaitWrite #if MIN_VERSION_base(4,7,0) , threadWaitReadSTM , threadWaitWriteSTM #endif , rtsSupportsBoundThreads , forkOS #if MIN_VERSION_base(4,9,0) , forkOSWithUnmask #endif , isCurrentThreadBound , runInBoundThread , runInUnboundThread , mkWeakThreadId , myThreadId ) import Control.Concurrent.Async as Concurrency ( Async(..) , Concurrently(..) , async , asyncBound , asyncOn , withAsync , withAsyncBound , withAsyncOn , wait , poll , waitCatch , cancel , cancelWith , asyncThreadId , waitAny , waitAnyCatch , waitAnyCancel , waitAnyCatchCancel , waitEither , waitEitherCatch , waitEitherCancel , waitEitherCatchCancel , waitEither_ , waitBoth , link , link2 , race , race_ , concurrently ) import Foreign.Ptr as Foreign (IntPtr, WordPtr) import Foreign.Storable as Foreign (Storable) import Foreign.StablePtr as Foreign (StablePtr) -- Read instances hiding unsafe builtins (read) import qualified Text.Read as Read import Text.Read as Read ( Read , reads ) -- Type synonymss for lazy texts type LText = Data.Text.Lazy.Text type LByteString = Data.ByteString.Lazy.ByteString #if !MIN_VERSION_base(4,8,0) infixl 1 & (&) :: a -> (a -> b) -> b x & f = f x #endif -- | The identity function, returns the give value unchanged. identity :: a -> a identity x = x map :: Functor.Functor f => (a -> b) -> f a -> f b map = Functor.fmap uncons :: [a] -> Maybe (a, [a]) uncons [] = Nothing uncons (x:xs) = Just (x, xs) unsnoc :: [x] -> Maybe ([x],x) unsnoc = Foldable.foldr go Nothing where go x mxs = Just (case mxs of Nothing -> ([], x) Just (xs, e) -> (x:xs, e)) -- | Apply a function n times to a given value applyN :: Int -> (a -> a) -> a -> a applyN n f = Foldable.foldr (.) identity (List.replicate n f) -- | Parse a string using the 'Read' instance. Succeeds if there is exactly one valid result . -- > > > ( " 123 " : : Text ) : : Maybe Int Just 123 -- > > > ( " hello " : : Text ) : : Maybe Int -- Nothing readMaybe :: (Read b, Conv.StringConv a String) => a -> Maybe b readMaybe = Read.readMaybe . Conv.toS -- | Parse a string using the 'Read' instance. Succeeds if there is exactly one valid result . -- A 'Left' value indicates a parse error. -- > > > readEither " 123 " : : Either Text Int Right 123 -- -- >>> readEither "hello" :: Either Text Int -- Left "Prelude.read: no parse" readEither :: (Read a, Conv.StringConv String e, Conv.StringConv e String) => e -> Either e a readEither = first Conv.toS . Read.readEither . Conv.toS -- | The print function outputs a value of any printable type to the standard -- output device. Printable types are those that are instances of class Show; -- print converts values to strings for output using the show operation and adds -- a newline. print :: (Trans.MonadIO m, PBase.Show a) => a -> m () print = liftIO . PBase.print -- | Lifted throwIO throwIO :: (Trans.MonadIO m, Exception e) => e -> m a throwIO = liftIO . PException.throwIO -- | Lifted throwTo throwTo :: (Trans.MonadIO m, Exception e) => ThreadId -> e -> m () throwTo tid e = liftIO (PException.throwTo tid e) -- | Do nothing returning unit inside applicative. pass :: Applicative f => f () pass = pure () guarded :: (Alternative f) => (a -> Bool) -> a -> f a guarded p x = Bool.bool empty (pure x) (p x) guardedA :: (Functor.Functor f, Alternative t) => (a -> f Bool) -> a -> f (t a) guardedA p x = Bool.bool empty (pure x) `Functor.fmap` p x | Lift an ' IO ' operation with 1 argument into another monad liftIO1 :: MonadIO m => (a -> IO b) -> a -> m b liftIO1 = (.) liftIO | Lift an ' IO ' operation with 2 arguments into another monad liftIO2 :: MonadIO m => (a -> b -> IO c) -> a -> b -> m c liftIO2 = ((.).(.)) liftIO show :: (Show a, Conv.StringConv String b) => a -> b show x = Conv.toS (PBase.show x) {-# SPECIALIZE show :: Show a => a -> Text #-} # SPECIALIZE show : : Show a = > a - > LText # {-# SPECIALIZE show :: Show a => a -> String #-} #if MIN_VERSION_base(4,8,0) -- | Terminate main process with failure die :: Text -> IO a die err = System.Exit.die (ConvertText.toS err) #else -- | Terminate main process with failure die :: Text -> IO a die err = hPutStrLn stderr err >> exitFailure #endif #if !MIN_VERSION_base(4,8,0) This is a literal copy of the implementation in GHC.List in base-4.10.1.0 . | A strictly accumulating version of ' ' # NOINLINE [ 1 ] ' # scanl' :: (b -> a -> b) -> b -> [a] -> [b] scanl' = scanlGo' where scanlGo' :: (b -> a -> b) -> b -> [a] -> [b] scanlGo' f !q ls = q : (case ls of [] -> [] x:xs -> scanlGo' f (f q x) xs) # RULES " ' " [ ~1 ] forall f a bs . ' f a bs = build ( \c n - > a ` c ` foldr ( scanlFB ' f c ) ( flipSeqScanl ' n ) bs a ) " scanlList ' " [ 1 ] forall f a bs . foldr ( scanlFB ' f ( :)) ( flipSeqScanl ' [ ] ) bs a = tail ( ' f a bs ) # "scanl'" [~1] forall f a bs . scanl' f a bs = build (\c n -> a `c` foldr (scanlFB' f c) (flipSeqScanl' n) bs a) "scanlList'" [1] forall f a bs . foldr (scanlFB' f (:)) (flipSeqScanl' []) bs a = tail (scanl' f a bs) #-} {-# INLINE [0] scanlFB' #-} scanlFB' :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c scanlFB' f c = \b g -> \x -> let !b' = f x b in b' `c` g b' {-# INLINE [0] flipSeqScanl' #-} flipSeqScanl' :: a -> b -> a flipSeqScanl' a !_b = a #endif
null
https://raw.githubusercontent.com/protolude/protolude/3e249724fd0ead27370c8c297b1ecd38f92cbd5b/src/Protolude.hs
haskell
# LANGUAGE BangPatterns # * Base functions * Function functions * List functions * Data Structures * Show functions * Bool functions * Monad functions * Functor functions * Either functions * Applicative functions * String conversion * Debug functions * Panic functions * Exception functions * Semiring functions * String functions * Safe functions * Eq functions * Foldable functions * Semigroup functions * Monoid functions * Bifunctor functions * Bifunctor functions * Deepseq functions * Tuple functions * Typelevel programming * Monads * Integers * Complex functions * Maybe functions * Generics functions * ByteString functions * Text functions * Read functions * System functions * Concurrency functions * Foreign functions Protolude module exports. Overriden by Show.putStr Overriden by Show.putStrLn Overriden by Protolude.print Custom Show instances deprecated. Custom Show instances deprecated. Custom Show instances deprecated. Custom Show instances deprecated. Custom Show instances deprecated. Used for 'show', not exported. Maybe'ized version of partial functions Base typeclasses Deepseq Data structures Hashing Base types Text IO ST Concurrency and Parallelism Read instances hiding unsafe builtins (read) Type synonymss for lazy texts | The identity function, returns the give value unchanged. | Apply a function n times to a given value | Parse a string using the 'Read' instance. Nothing | Parse a string using the 'Read' instance. A 'Left' value indicates a parse error. >>> readEither "hello" :: Either Text Int Left "Prelude.read: no parse" | The print function outputs a value of any printable type to the standard output device. Printable types are those that are instances of class Show; print converts values to strings for output using the show operation and adds a newline. | Lifted throwIO | Lifted throwTo | Do nothing returning unit inside applicative. # SPECIALIZE show :: Show a => a -> Text # # SPECIALIZE show :: Show a => a -> String # | Terminate main process with failure | Terminate main process with failure # INLINE [0] scanlFB' # # INLINE [0] flipSeqScanl' #
# LANGUAGE CPP # # LANGUAGE Trustworthy # # LANGUAGE FlexibleContexts # # LANGUAGE NoImplicitPrelude # # LANGUAGE ExplicitNamespaces # # OPTIONS_GHC -fno - warn - unused - imports # module Protolude ( module Base, identity, pass, #if !MIN_VERSION_base(4,8,0) (&), scanl', #endif module Function, applyN, module List, map, uncons, unsnoc, module DataStructures, module Show, show, print, module Bool, module Monad, liftIO1, liftIO2, module Functor, module Either, module Applicative, guarded, guardedA, module ConvertText, module Debug, module Panic, module Exception, Protolude.throwIO, Protolude.throwTo, module Semiring, module String, module Safe, module Eq, * functions module Ord, * functions module Traversable, module Foldable, #if MIN_VERSION_base(4,9,0) module Semigroup, #endif module Monoid, module Bifunctor, module Hashable, module DeepSeq, module Tuple, module Typeable, #if MIN_VERSION_base(4,7,0) module Typelevel, #endif module Fail, module State, module Reader, module Except, module Trans, module ST, module STM, module Int, module Bits, module Complex, * functions module Char, module Maybe, module Generics, module ByteString, LByteString, module Text, LText, module Read, readMaybe, readEither, module System, die, module Concurrency, module Foreign, ) where import Protolude.Debug as Debug import Protolude.List as List import Protolude.Show as Show import Protolude.Bool as Bool import Protolude.Monad as Monad import Protolude.Functor as Functor import Protolude.Either as Either import Protolude.Applicative as Applicative import Protolude.ConvertText as ConvertText import Protolude.Panic as Panic import Protolude.Exceptions as Exception import Protolude.Semiring as Semiring import qualified Protolude.Conv as Conv import Protolude.Base as Base hiding ( Overriden by Protolude.show ) import qualified Protolude.Base as PBase import Data.String (String) import Data.String as String (IsString) import Protolude.Safe as Safe ( headMay , headDef , initMay , initDef , initSafe , tailMay , tailDef , tailSafe , lastDef , lastMay , foldr1May , foldl1May , foldl1May' , maximumMay , minimumMay , maximumDef , minimumDef , atMay , atDef ) Applicatives import Control.Applicative as Applicative ( Applicative(..) , Alternative(..) , Const(Const,getConst) , ZipList(ZipList,getZipList) , (<**>) , liftA , liftA2 , liftA3 , optional ) import Data.Eq as Eq ( Eq(..) ) import Data.Ord as Ord ( Ord(..) , Ordering(LT,EQ,GT) , Down(Down) , comparing ) import Data.Traversable as Traversable import Data.Foldable as Foldable ( Foldable, fold, foldMap, foldr, foldr', foldl, foldl', toList, #if MIN_VERSION_base(4,8,0) null, length, #endif elem, maximum, minimum, foldrM, foldlM, traverse_, for_, mapM_, forM_, sequence_, sequenceA_, asum, msum, concat, concatMap, and, or, any, all, maximumBy, minimumBy, notElem, find, ) import Data.Functor.Identity as Functor ( Identity(Identity, runIdentity) ) #if MIN_VERSION_base(4,9,0) import Data.List.NonEmpty as List ( NonEmpty((:|)) , nonEmpty ) import Data.Semigroup as Semigroup ( Semigroup(sconcat, stimes) , WrappedMonoid , diff , cycle1 , stimesMonoid , stimesIdempotent , stimesIdempotentMonoid , mtimesDefault ) #endif #if MIN_VERSION_base(4,9,0) && !MIN_VERSION_base(4,16,0) import Data.Semigroup as Semigroup ( Option(..) , option ) #endif import Data.Monoid as Monoid #if !MIN_VERSION_base(4,8,0) import Protolude.Bifunctor as Bifunctor (Bifunctor(bimap, first, second)) #else import Data.Bifunctor as Bifunctor (Bifunctor(bimap, first, second)) #endif import Control.DeepSeq as DeepSeq ( NFData(..) , ($!!) , deepseq , force ) import Data.Tuple as Tuple ( fst , snd , curry , uncurry , swap ) import Data.List as List ( splitAt , break , intercalate , isPrefixOf , isInfixOf , isSuffixOf , drop , filter , reverse , replicate , take , sortBy , sort , intersperse , transpose , subsequences , permutations , scanl #if MIN_VERSION_base(4,8,0) , scanl' #endif , scanr , iterate , repeat , cycle , unfoldr , takeWhile , dropWhile , group , inits , tails , zipWith , zip , unzip , genericLength , genericTake , genericDrop , genericSplitAt , genericReplicate ) #if !MIN_VERSION_base(4,8,0) These imports are required for the ' rewrite rules import GHC.Exts (build) import Data.List (tail) #endif import Data.Hashable as Hashable ( Hashable , hash , hashWithSalt , hashUsing ) import Data.Map as DataStructures (Map) import Data.Set as DataStructures (Set) import Data.Sequence as DataStructures (Seq) import Data.IntMap as DataStructures (IntMap) import Data.IntSet as DataStructures (IntSet) import Data.Typeable as Typeable ( TypeRep , Typeable , typeOf , cast , gcast #if MIN_VERSION_base(4,7,0) , typeRep , eqT #endif ) #if MIN_VERSION_base(4,7,0) import Data.Proxy as Typelevel ( Proxy(..) ) import Data.Type.Coercion as Typelevel ( Coercion(..) , coerceWith , repr ) import Data.Type.Equality as Typelevel ( (:~:)(..) , type (==) , sym , trans , castWith , gcastWith ) #endif #if MIN_VERSION_base(4,8,0) import Data.Void as Typelevel ( Void , absurd , vacuous ) #endif import Control.Monad.Fail as Fail ( MonadFail ) Monad transformers import Control.Monad.State as State ( MonadState , State , StateT(StateT) , put , get , gets , modify , state , withState , runState , execState , evalState , runStateT , execStateT , evalStateT ) import Control.Monad.Reader as Reader ( MonadReader , Reader , ReaderT(ReaderT) , ask , asks , local , reader , runReader , runReaderT ) import Control.Monad.Trans.Except as Except ( throwE , catchE ) import Control.Monad.Except as Except ( MonadError , Except , ExceptT(ExceptT) , throwError , catchError , runExcept , runExceptT , mapExcept , mapExceptT , withExcept , withExceptT ) import Control.Monad.Trans as Trans ( MonadIO , lift , liftIO ) import Data.Int as Int ( Int , Int8 , Int16 , Int32 , Int64 ) import Data.Bits as Bits ( Bits, (.&.), (.|.), xor, complement, shift, rotate, #if MIN_VERSION_base(4,7,0) zeroBits, #endif bit, setBit, clearBit, complementBit, testBit, #if MIN_VERSION_base(4,7,0) bitSizeMaybe, #endif bitSize, isSigned, shiftL, shiftR, rotateL, rotateR, popCount, #if MIN_VERSION_base(4,7,0) FiniteBits, finiteBitSize, bitDefault, testBitDefault, popCountDefault, #endif #if MIN_VERSION_base(4,8,0) toIntegralSized, countLeadingZeros, countTrailingZeros, #endif ) import Data.Word as Bits ( Word , Word8 , Word16 , Word32 , Word64 #if MIN_VERSION_base(4,7,0) , byteSwap16 , byteSwap32 , byteSwap64 #endif ) import Data.Either as Either ( Either(Left,Right) , either , lefts , rights , partitionEithers #if MIN_VERSION_base(4,7,0) , isLeft , isRight #endif ) import Data.Complex as Complex ( Complex((:+)) , realPart , imagPart , mkPolar , cis , polar , magnitude , phase , conjugate ) import Data.Char as Char ( Char , ord , chr , digitToInt , intToDigit , toUpper , toLower , toTitle , isAscii , isLetter , isDigit , isHexDigit , isPrint , isAlpha , isAlphaNum , isUpper , isLower , isSpace , isControl ) import Data.Bool as Bool ( Bool(True, False), (&&), (||), not, otherwise ) import Data.Maybe as Maybe ( Maybe(Nothing, Just) , maybe , isJust , isNothing , fromMaybe , listToMaybe , maybeToList , catMaybes , mapMaybe ) import Data.Function as Function ( const , (.) , ($) , flip , fix , on #if MIN_VERSION_base(4,8,0) , (&) #endif ) Genericss import GHC.Generics as Generics ( Generic(..) , Generic1 , Rep , K1(..) , M1(..) , U1(..) , V1 , D1 , C1 , S1 , (:+:)(..) , (:*:)(..) , (:.:)(..) , Rec0 , Constructor(..) , Datatype(..) , Selector(..) , Fixity(..) , Associativity(..) #if ( __GLASGOW_HASKELL__ >= 800 ) , Meta(..) , FixityI(..) , URec #endif ) ByteString import qualified Data.ByteString.Lazy import Data.ByteString as ByteString (ByteString) import Data.Text as Text ( Text , lines , words , unlines , unwords ) import qualified Data.Text.Lazy import Data.Text.IO as Text ( getLine , getContents , interact , readFile , writeFile , appendFile ) import Data.Text.Lazy as Text ( toStrict , fromStrict ) import Data.Text.Encoding as Text ( encodeUtf8 , decodeUtf8 , decodeUtf8' , decodeUtf8With ) import Data.Text.Encoding.Error as Text ( OnDecodeError , OnError , UnicodeException , lenientDecode , strictDecode , ignore , replace ) import System.Environment as System (getArgs) import qualified System.Exit import System.Exit as System ( ExitCode(..) , exitWith , exitFailure , exitSuccess ) import System.IO as System ( Handle , FilePath , IOMode(..) , stdin , stdout , stderr , withFile , openFile ) import Control.Monad.ST as ST ( ST , runST , fixST ) import Control.Exception as Exception ( Exception, toException, fromException, #if MIN_VERSION_base(4,8,0) displayException, #endif SomeException(SomeException) , IOException , ArithException( Overflow, Underflow, LossOfPrecision, DivideByZero, Denormal, RatioZeroDenominator ) , ArrayException(IndexOutOfBounds, UndefinedElement) , AssertionFailed(AssertionFailed) #if MIN_VERSION_base(4,7,0) , SomeAsyncException(SomeAsyncException) , asyncExceptionToException , asyncExceptionFromException #endif , AsyncException(StackOverflow, HeapOverflow, ThreadKilled, UserInterrupt) , NonTermination(NonTermination) , NestedAtomically(NestedAtomically) , BlockedIndefinitelyOnMVar(BlockedIndefinitelyOnMVar) , BlockedIndefinitelyOnSTM(BlockedIndefinitelyOnSTM) #if MIN_VERSION_base(4,8,0) , AllocationLimitExceeded(AllocationLimitExceeded) #endif #if MIN_VERSION_base(4,10,0) , CompactionFailed(CompactionFailed) #endif , Deadlock(Deadlock) , NoMethodError(NoMethodError) , PatternMatchFail(PatternMatchFail) , RecConError(RecConError) , RecSelError(RecSelError) , RecUpdError(RecUpdError) #if MIN_VERSION_base(4,9,0) , ErrorCall(ErrorCall, ErrorCallWithLocation) #else , ErrorCall(ErrorCall) #endif #if MIN_VERSION_base(4,9,0) , TypeError(TypeError) #endif , ioError , catch , catches , Handler(Handler) , catchJust , handle , handleJust , try , tryJust , evaluate , mapException , mask , mask_ , uninterruptibleMask , uninterruptibleMask_ , MaskingState(..) , getMaskingState #if MIN_VERSION_base(4,9,0) , interruptible #endif , allowInterrupt , bracket , bracket_ , bracketOnError , finally , onException ) import qualified Control.Exception as PException import Control.Monad.STM as STM ( STM , atomically #if !(MIN_VERSION_stm(2,5,0)) , always , alwaysSucceeds #endif , retry , orElse , check , throwSTM , catchSTM ) import Control.Concurrent.MVar as Concurrency ( MVar , newEmptyMVar , newMVar , takeMVar , putMVar , readMVar , swapMVar , tryTakeMVar , tryPutMVar , isEmptyMVar , withMVar #if MIN_VERSION_base(4,7,0) , withMVarMasked #endif , modifyMVar_ , modifyMVar , modifyMVarMasked_ , modifyMVarMasked #if MIN_VERSION_base(4,7,0) , tryReadMVar , mkWeakMVar #endif , addMVarFinalizer ) import Control.Concurrent.Chan as Concurrency ( Chan , newChan , writeChan , readChan , dupChan , getChanContents , writeList2Chan ) import Control.Concurrent.QSem as Concurrency ( QSem , newQSem , waitQSem , signalQSem ) import Control.Concurrent.QSemN as Concurrency ( QSemN , newQSemN , waitQSemN , signalQSemN ) import Control.Concurrent as Concurrency ( ThreadId , forkIO , forkFinally , forkIOWithUnmask , killThread , forkOn , forkOnWithUnmask , getNumCapabilities , setNumCapabilities , threadCapability , yield , threadDelay , threadWaitRead , threadWaitWrite #if MIN_VERSION_base(4,7,0) , threadWaitReadSTM , threadWaitWriteSTM #endif , rtsSupportsBoundThreads , forkOS #if MIN_VERSION_base(4,9,0) , forkOSWithUnmask #endif , isCurrentThreadBound , runInBoundThread , runInUnboundThread , mkWeakThreadId , myThreadId ) import Control.Concurrent.Async as Concurrency ( Async(..) , Concurrently(..) , async , asyncBound , asyncOn , withAsync , withAsyncBound , withAsyncOn , wait , poll , waitCatch , cancel , cancelWith , asyncThreadId , waitAny , waitAnyCatch , waitAnyCancel , waitAnyCatchCancel , waitEither , waitEitherCatch , waitEitherCancel , waitEitherCatchCancel , waitEither_ , waitBoth , link , link2 , race , race_ , concurrently ) import Foreign.Ptr as Foreign (IntPtr, WordPtr) import Foreign.Storable as Foreign (Storable) import Foreign.StablePtr as Foreign (StablePtr) import qualified Text.Read as Read import Text.Read as Read ( Read , reads ) type LText = Data.Text.Lazy.Text type LByteString = Data.ByteString.Lazy.ByteString #if !MIN_VERSION_base(4,8,0) infixl 1 & (&) :: a -> (a -> b) -> b x & f = f x #endif identity :: a -> a identity x = x map :: Functor.Functor f => (a -> b) -> f a -> f b map = Functor.fmap uncons :: [a] -> Maybe (a, [a]) uncons [] = Nothing uncons (x:xs) = Just (x, xs) unsnoc :: [x] -> Maybe ([x],x) unsnoc = Foldable.foldr go Nothing where go x mxs = Just (case mxs of Nothing -> ([], x) Just (xs, e) -> (x:xs, e)) applyN :: Int -> (a -> a) -> a -> a applyN n f = Foldable.foldr (.) identity (List.replicate n f) Succeeds if there is exactly one valid result . > > > ( " 123 " : : Text ) : : Maybe Int Just 123 > > > ( " hello " : : Text ) : : Maybe Int readMaybe :: (Read b, Conv.StringConv a String) => a -> Maybe b readMaybe = Read.readMaybe . Conv.toS Succeeds if there is exactly one valid result . > > > readEither " 123 " : : Either Text Int Right 123 readEither :: (Read a, Conv.StringConv String e, Conv.StringConv e String) => e -> Either e a readEither = first Conv.toS . Read.readEither . Conv.toS print :: (Trans.MonadIO m, PBase.Show a) => a -> m () print = liftIO . PBase.print throwIO :: (Trans.MonadIO m, Exception e) => e -> m a throwIO = liftIO . PException.throwIO throwTo :: (Trans.MonadIO m, Exception e) => ThreadId -> e -> m () throwTo tid e = liftIO (PException.throwTo tid e) pass :: Applicative f => f () pass = pure () guarded :: (Alternative f) => (a -> Bool) -> a -> f a guarded p x = Bool.bool empty (pure x) (p x) guardedA :: (Functor.Functor f, Alternative t) => (a -> f Bool) -> a -> f (t a) guardedA p x = Bool.bool empty (pure x) `Functor.fmap` p x | Lift an ' IO ' operation with 1 argument into another monad liftIO1 :: MonadIO m => (a -> IO b) -> a -> m b liftIO1 = (.) liftIO | Lift an ' IO ' operation with 2 arguments into another monad liftIO2 :: MonadIO m => (a -> b -> IO c) -> a -> b -> m c liftIO2 = ((.).(.)) liftIO show :: (Show a, Conv.StringConv String b) => a -> b show x = Conv.toS (PBase.show x) # SPECIALIZE show : : Show a = > a - > LText # #if MIN_VERSION_base(4,8,0) die :: Text -> IO a die err = System.Exit.die (ConvertText.toS err) #else die :: Text -> IO a die err = hPutStrLn stderr err >> exitFailure #endif #if !MIN_VERSION_base(4,8,0) This is a literal copy of the implementation in GHC.List in base-4.10.1.0 . | A strictly accumulating version of ' ' # NOINLINE [ 1 ] ' # scanl' :: (b -> a -> b) -> b -> [a] -> [b] scanl' = scanlGo' where scanlGo' :: (b -> a -> b) -> b -> [a] -> [b] scanlGo' f !q ls = q : (case ls of [] -> [] x:xs -> scanlGo' f (f q x) xs) # RULES " ' " [ ~1 ] forall f a bs . ' f a bs = build ( \c n - > a ` c ` foldr ( scanlFB ' f c ) ( flipSeqScanl ' n ) bs a ) " scanlList ' " [ 1 ] forall f a bs . foldr ( scanlFB ' f ( :)) ( flipSeqScanl ' [ ] ) bs a = tail ( ' f a bs ) # "scanl'" [~1] forall f a bs . scanl' f a bs = build (\c n -> a `c` foldr (scanlFB' f c) (flipSeqScanl' n) bs a) "scanlList'" [1] forall f a bs . foldr (scanlFB' f (:)) (flipSeqScanl' []) bs a = tail (scanl' f a bs) #-} scanlFB' :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c scanlFB' f c = \b g -> \x -> let !b' = f x b in b' `c` g b' flipSeqScanl' :: a -> b -> a flipSeqScanl' a !_b = a #endif
be9b146b6ee281297bcf4aba3c705f66e638e0e746a2961f052b082e59dec949
monadbobo/ocaml-core
job.mli
open Core.Std type 'execution_context t val create : 'execution_context -> ('a -> unit) -> 'a -> 'execution_context t val execution_context : 'execution_context t -> 'execution_context val run : _ t -> unit
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/async/core/lib/job.mli
ocaml
open Core.Std type 'execution_context t val create : 'execution_context -> ('a -> unit) -> 'a -> 'execution_context t val execution_context : 'execution_context t -> 'execution_context val run : _ t -> unit
1bec9b2edfc144732cb7cee0e44f73992f7e4fbca5ca1f0b93dcf696611eb0bf
unison-code/uni-instr-sel
Base.hs
| Copyright : Copyright ( c ) 2012 - 2017 , < > License : BSD3 ( see the LICENSE file ) Maintainer : Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <> License : BSD3 (see the LICENSE file) Maintainer : -} Main authors : < > Main authors: Gabriel Hjort Blindell <> -} {-# LANGUAGE DeriveDataTypeable #-} module UniIS.Drivers.Base ( CheckAction (..) , MakeAction (..) , PlotAction (..) , TransformAction (..) , Options (..) , module Language.InstrSel.DriverTools ) where import System.Console.CmdArgs ( Data , Typeable ) import Language.InstrSel.DriverTools -------------- -- Data types -------------- -- | Options that can be given on the command line. data Options = Options { command :: String , functionFile :: Maybe String , patternMatchsetFile :: Maybe String , modelFile :: Maybe String , arrayIndexMaplistsFile :: Maybe String , solutionFile :: Maybe String , targetName :: Maybe String , instructionID :: Maybe Integer , outFile :: Maybe String , makeAction :: MakeAction , transformAction :: TransformAction , plotAction :: PlotAction , showEdgeNumbers :: Maybe Bool , hideNullInstructions :: Maybe Bool , hideKillInstructions :: Maybe Bool , altLimit :: Maybe Int , checkAction :: CheckAction } deriving (Data, Typeable) -- | Represents 'make' actions. data MakeAction = MakeNothing | MakeFunctionGraphFromLLVM | MakePatternMatchset | MakeArrayIndexMaplists | MakeLowLevelModelDump | MakeLowLevelSolutionDump | MakeHighLevelCPModel | MakeAssemblyCode deriving (Eq, Typeable, Data) -- | Represents 'transform' actions. data TransformAction = TransformNothing | RemoveRedundantConversionsInFunctionGraph | RemoveDeadCodeInFunctionGraph | EnforcePhiNodeInvariantsInFunctionGraph | RemovePhiNodeRedundanciesInFunctionGraph | LowerPointersInFunctionGraph | CopyExtendFunctionGraph | CombineConstantsInFunctionGraph | AlternativeExtendPatternMatchset | AddOperandsToHighLevelCPModel | RaiseLowLevelCPSolution | LowerHighLevelCPModel deriving (Eq, Typeable, Data) -- | Represents 'plot' actions. data PlotAction = PlotNothing | PlotFunctionFullGraph | PlotFunctionControlFlowGraph | PlotFunctionSSAGraph | PlotPatternFullGraph | PlotPatternControlFlowGraph | PlotPatternSSAGraph | PlotCoverAllMatches | PlotCoverPerMatch deriving (Eq, Typeable, Data) -- | Represents 'check' actions. data CheckAction = CheckNothing | CheckFunctionGraphCoverage | CheckFunctionGraphLocationOverlap | CheckFunctionIntegrity | CheckPatternIntegrity deriving (Eq, Typeable, Data)
null
https://raw.githubusercontent.com/unison-code/uni-instr-sel/2edb2f3399ea43e75f33706261bd6b93bedc6762/uni-is/UniIS/Drivers/Base.hs
haskell
# LANGUAGE DeriveDataTypeable # ------------ Data types ------------ | Options that can be given on the command line. | Represents 'make' actions. | Represents 'transform' actions. | Represents 'plot' actions. | Represents 'check' actions.
| Copyright : Copyright ( c ) 2012 - 2017 , < > License : BSD3 ( see the LICENSE file ) Maintainer : Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <> License : BSD3 (see the LICENSE file) Maintainer : -} Main authors : < > Main authors: Gabriel Hjort Blindell <> -} module UniIS.Drivers.Base ( CheckAction (..) , MakeAction (..) , PlotAction (..) , TransformAction (..) , Options (..) , module Language.InstrSel.DriverTools ) where import System.Console.CmdArgs ( Data , Typeable ) import Language.InstrSel.DriverTools data Options = Options { command :: String , functionFile :: Maybe String , patternMatchsetFile :: Maybe String , modelFile :: Maybe String , arrayIndexMaplistsFile :: Maybe String , solutionFile :: Maybe String , targetName :: Maybe String , instructionID :: Maybe Integer , outFile :: Maybe String , makeAction :: MakeAction , transformAction :: TransformAction , plotAction :: PlotAction , showEdgeNumbers :: Maybe Bool , hideNullInstructions :: Maybe Bool , hideKillInstructions :: Maybe Bool , altLimit :: Maybe Int , checkAction :: CheckAction } deriving (Data, Typeable) data MakeAction = MakeNothing | MakeFunctionGraphFromLLVM | MakePatternMatchset | MakeArrayIndexMaplists | MakeLowLevelModelDump | MakeLowLevelSolutionDump | MakeHighLevelCPModel | MakeAssemblyCode deriving (Eq, Typeable, Data) data TransformAction = TransformNothing | RemoveRedundantConversionsInFunctionGraph | RemoveDeadCodeInFunctionGraph | EnforcePhiNodeInvariantsInFunctionGraph | RemovePhiNodeRedundanciesInFunctionGraph | LowerPointersInFunctionGraph | CopyExtendFunctionGraph | CombineConstantsInFunctionGraph | AlternativeExtendPatternMatchset | AddOperandsToHighLevelCPModel | RaiseLowLevelCPSolution | LowerHighLevelCPModel deriving (Eq, Typeable, Data) data PlotAction = PlotNothing | PlotFunctionFullGraph | PlotFunctionControlFlowGraph | PlotFunctionSSAGraph | PlotPatternFullGraph | PlotPatternControlFlowGraph | PlotPatternSSAGraph | PlotCoverAllMatches | PlotCoverPerMatch deriving (Eq, Typeable, Data) data CheckAction = CheckNothing | CheckFunctionGraphCoverage | CheckFunctionGraphLocationOverlap | CheckFunctionIntegrity | CheckPatternIntegrity deriving (Eq, Typeable, Data)
7977c4a81b0ca3ea763a989f2bea30aad23fb18e6bf4ee949bb1414ff0f25ef7
antono/guix-debian
time.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2012 < > Copyright © 2013 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages time) #:use-module (guix licenses) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu)) (define-public time (package (name "time") (version "1.7") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "0va9063fcn7xykv658v2s9gilj2fq4rcdxx2mn2mmy1v4ndafzp3")))) (build-system gnu-build-system) (arguments '(#:phases (alist-replace 'configure (lambda* (#:key outputs #:allow-other-keys) ;; This old `configure' script doesn't support ;; variables passed as arguments. (let ((out (assoc-ref outputs "out"))) (setenv "CONFIG_SHELL" (which "bash")) (zero? (system* "./configure" (string-append "--prefix=" out))))) %standard-phases))) (home-page "/") (synopsis "Run a command, then display its resource usage") (description "Time is a command that displays information about the resources that a program uses. The display output of the program can be customized or saved to a file.") (license gpl2+)))
null
https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/time.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This old `configure' script doesn't support variables passed as arguments.
Copyright © 2012 < > Copyright © 2013 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages time) #:use-module (guix licenses) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu)) (define-public time (package (name "time") (version "1.7") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "0va9063fcn7xykv658v2s9gilj2fq4rcdxx2mn2mmy1v4ndafzp3")))) (build-system gnu-build-system) (arguments '(#:phases (alist-replace 'configure (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (setenv "CONFIG_SHELL" (which "bash")) (zero? (system* "./configure" (string-append "--prefix=" out))))) %standard-phases))) (home-page "/") (synopsis "Run a command, then display its resource usage") (description "Time is a command that displays information about the resources that a program uses. The display output of the program can be customized or saved to a file.") (license gpl2+)))
2c6341ffc7c51723a48121c07394279849a13e2c3e9ca43ee7c494d896e59267
willijar/LENS
connectivity-map.lisp
;; Application to send packets at regular intervals. Copyright ( C ) 2014 Dr. Author : Dr. < > ;; Keywords: ;;; Copying: This file is part of Lisp Educational Network Simulator ( LENS ) ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; LENS is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. ;;; Commentary: The packets received satatistic will give connectivity map ;;; Code: (in-package :lens.wsn) (defclass connectivity-map (application) ((header-overhead :initform 8) (payload-overhead :initform 32) (priority :parameter t :initform 1 :reader priority :initarg :priority) (packet-spacing :parameter t :type time-type :initform 1d-1 :reader packet-spacing) (packets-per-node :parameter t :type integer :initform 100 :reader packets-per-node) (packets-sent :initform 0 :type integer :accessor packets-sent) (send-packet :type timer-message :initform (make-instance 'timer-message))) (:metaclass module-class) (:documentation "Application module that will generate [[packets-per-node]] packets at intervals of [[packets-per-spacing]] - useful to determine connectivity statistics of a network.")) (defmethod startup((application connectivity-map)) (call-next-method) (set-timer application 'send-packet (* (packets-per-node application) (packet-spacing application) (nodeid (node application))))) (defmethod handle-timer((application connectivity-map) (timer (eql 'send-packet))) (unless (>= (packets-sent application) (packets-per-node application)) (to-network application (encapsulate application (incf (packets-sent application))) broadcast-network-address) (set-timer application 'send-packet (packet-spacing application))))
null
https://raw.githubusercontent.com/willijar/LENS/646bc4ca5d4add3fa7e0728f14128e96240a9f36/networks/wsn/application/connectivity-map.lisp
lisp
Application to send packets at regular intervals. Keywords: Copying: This program is free software: you can redistribute it and/or modify (at your option) any later version. LENS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. Commentary: Code:
Copyright ( C ) 2014 Dr. Author : Dr. < > This file is part of Lisp Educational Network Simulator ( LENS ) it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License The packets received satatistic will give connectivity map (in-package :lens.wsn) (defclass connectivity-map (application) ((header-overhead :initform 8) (payload-overhead :initform 32) (priority :parameter t :initform 1 :reader priority :initarg :priority) (packet-spacing :parameter t :type time-type :initform 1d-1 :reader packet-spacing) (packets-per-node :parameter t :type integer :initform 100 :reader packets-per-node) (packets-sent :initform 0 :type integer :accessor packets-sent) (send-packet :type timer-message :initform (make-instance 'timer-message))) (:metaclass module-class) (:documentation "Application module that will generate [[packets-per-node]] packets at intervals of [[packets-per-spacing]] - useful to determine connectivity statistics of a network.")) (defmethod startup((application connectivity-map)) (call-next-method) (set-timer application 'send-packet (* (packets-per-node application) (packet-spacing application) (nodeid (node application))))) (defmethod handle-timer((application connectivity-map) (timer (eql 'send-packet))) (unless (>= (packets-sent application) (packets-per-node application)) (to-network application (encapsulate application (incf (packets-sent application))) broadcast-network-address) (set-timer application 'send-packet (packet-spacing application))))