_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
280e5d5dbd4d4e82e9e0859a7a7b0f3ee84fd2a168da95219a38b7df31919270
huangz1990/SICP-answers
test-63-tree-list-1.scm
(load "test-manager/load.scm") (load "63-tree-list-1.scm") (define-each-check (equal? (tree->list-1 (make-tree 7 (make-tree 3 (make-tree 1 '() '()) (make-tree 5 '() '())) (make-tree 9 '() (make-tree 11 '() '())))) (list 1 3 5 7 9 11)) ) (run-registered-tests)
null
https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/test-63-tree-list-1.scm
scheme
(load "test-manager/load.scm") (load "63-tree-list-1.scm") (define-each-check (equal? (tree->list-1 (make-tree 7 (make-tree 3 (make-tree 1 '() '()) (make-tree 5 '() '())) (make-tree 9 '() (make-tree 11 '() '())))) (list 1 3 5 7 9 11)) ) (run-registered-tests)
6073e30f8dfd7b3965200d58aeed6bc6b2eb793588edd3dd5e210edd63455579
adolenc/cl-neovim
api-low-level.lisp
(in-package :cl-neovim-tests) (in-suite api-low-level-test-suite) (test manual-sync-calls "Test #'call/s (sync) manual calls" (is (= (nvim:call/s t "vim_eval" "3 + 2") 5)) (is (= (nvim:call/s nvim:*nvim-instance* "vim_eval" "3 + 2") 5)) (signals error (nvim:call/s nvim:*nvim-instance* "some_nonexistent_fn")) (signals error (nvim:call/s nvim:*nvim-instance* "vim_command" "throw 'error'")) (signals error (nvim:call/s NIL "vim_eval" "3 + 2"))) (test manual-async-calls "Test #'call/a (async) manual calls" (is (= 3 (result-from-nvim/a (nvim:call/a t "vim_set_var" "lisp_host_test_tmp_result" 3)))) (is-true (nvim:call/a t "vim_eval" "3 + 2")) (signals-no-error (nvim:call/a nvim:*nvim-instance* "some_nonexistent_fn")) (signals-no-error (nvim:call/a nvim:*nvim-instance* "vim_command" "throw 'error'"))) (test generating-api (let ((api (nvim::retrieve-api))) (is (equal '("error_types" "functions" "types" "ui_events" "version") (sort (alexandria:hash-table-keys api) #'string<))) (let ((function-metadata (nvim::parse-api api))) (is (every #'(lambda (mdata) (find :name mdata)) function-metadata)) (is (every #'(lambda (mdata) (find :parameters mdata)) function-metadata)))))
null
https://raw.githubusercontent.com/adolenc/cl-neovim/7212d305206aaae331a3e2d0d2597b671cec01f4/t/api-low-level.lisp
lisp
(in-package :cl-neovim-tests) (in-suite api-low-level-test-suite) (test manual-sync-calls "Test #'call/s (sync) manual calls" (is (= (nvim:call/s t "vim_eval" "3 + 2") 5)) (is (= (nvim:call/s nvim:*nvim-instance* "vim_eval" "3 + 2") 5)) (signals error (nvim:call/s nvim:*nvim-instance* "some_nonexistent_fn")) (signals error (nvim:call/s nvim:*nvim-instance* "vim_command" "throw 'error'")) (signals error (nvim:call/s NIL "vim_eval" "3 + 2"))) (test manual-async-calls "Test #'call/a (async) manual calls" (is (= 3 (result-from-nvim/a (nvim:call/a t "vim_set_var" "lisp_host_test_tmp_result" 3)))) (is-true (nvim:call/a t "vim_eval" "3 + 2")) (signals-no-error (nvim:call/a nvim:*nvim-instance* "some_nonexistent_fn")) (signals-no-error (nvim:call/a nvim:*nvim-instance* "vim_command" "throw 'error'"))) (test generating-api (let ((api (nvim::retrieve-api))) (is (equal '("error_types" "functions" "types" "ui_events" "version") (sort (alexandria:hash-table-keys api) #'string<))) (let ((function-metadata (nvim::parse-api api))) (is (every #'(lambda (mdata) (find :name mdata)) function-metadata)) (is (every #'(lambda (mdata) (find :parameters mdata)) function-metadata)))))
f1c085e7e85501a2d58b65054446edd0f26efad5544c204fba509849056a3878
hikettei/cl-waffe
figure.lisp
(in-package :cl-termgraph) (defparameter *dif* 1/16) (defparameter *positive-lines* `("⠒⠒" "⣠⣤" "⣠⣰" "⣠⣼" "⡜⡜" "⣼⡜" "⡇⡇")) (defparameter *negative-lines* `("⠒⠒" "⣤⣄" "⣆⣄" "⣧⣄" "⢣⢣" "⢣⣧" "⡇⡇")) (defgeneric plot (frame pallet)) (defmacro mbind (&rest args) `(multiple-value-bind ,@args)) (defclass figure-graph-frame (simple-graph-frame) ((figure :accessor figure :initarg :figure :initform nil) (from :accessor figurefrom :initarg :from :initform nil) (end :accessor figureend :initarg :end :initform nil) (name :accessor name :initarg :name :initform nil))) (defclass parameter-graph-frame (figure-graph-frame) ((parameter :accessor parameter :initarg :parameter :initform nil) (by :accessor move-by :initarg :by :initform 1) (pstart :accessor pstart :initarg :pstart :initform -3) (pend :accessor pend :initarg :pend :initform 3))) (defmethod collect-figure-points ((frame figure-graph-frame)) (with-slots ((figure figure) (s from) (e end)) frame (loop for i from s to (1- e) by *dif* collect (handler-case (funcall figure i) (error (x) ; set as undefined (declare (ignore x)) `(,i . nil)) (:no-error (x) `(,i . ,x)))))) (defun max-points (points) (loop for i in (map 'list #'(lambda (p) (cdr p)) points) maximize i)) (defun min-points (points) (loop for i in (map 'list #'(lambda (p) (cdr p)) points) minimize i)) (defun maxmin-points (points) (values (max-points points) (min-points points))) (defmacro choose-line (p1 p2 p3 &optional (opt 0)) `(let ((ti (+ ,opt (3p-tilt-ave ,p1 ,p2 ,p3)))) (cond ((= ti 0) (first *positive-lines*)) ((and (< 0 ti) (< ti 0.5)) (second *positive-lines*)) ((and (<= 0.5 ti) (< ti 1.0)) (third *positive-lines*)) ((and (<= 1.0 ti) (< ti 1.5)) (fourth *positive-lines*)) ((and (<= 1.5 ti) (< ti 3.0)) (fifth *positive-lines*)) ((and (<= 3.0 ti) (< ti 4.5)) (sixth *positive-lines*)) ((>= ti 4.5) (seventh *positive-lines*)) ((and (< -0.5 ti) (<= ti 0)) (second *negative-lines*)) ((and (< -1.0 ti) (<= ti -0.5)) (third *negative-lines*)) ((and (< -1.5 ti) (<= ti -1.0)) (fourth *negative-lines*)) ((and (< -3.0 ti) (<= ti -1.5)) (fifth *negative-lines*)) ((and (< -4.5 ti) (<= ti -3.0)) (sixth *negative-lines*)) ((<= ti -4.5) (seventh *negative-lines*))))) (defmacro tilt (p1 p2) `(if (and ,p1 ,p2) (/ (- (cdr ,p1) (cdr ,p2)) (- (car ,p1) (car ,p2))) 0)) (defmacro 3p-tilt-ave (p1 p2 p3) `(/ (+ (tilt ,p1 ,p2) (tilt ,p2 ,p3)) 2)) (defun render (frame pallet) (with-output-to-string (graph) (loop for y from 1 to (slot-value frame 'height) do (loop for x from 0 to (1- (slot-value frame 'width)) do (write-string (aref pallet x (- (slot-value frame 'height) y)) graph)) (write-char #\Newline graph)))) (defun make-listplot-frame (x y) (make-array `(,x ,y) :initial-element " ")) (defun mean (list) (if (= (length list) 0) 0 (/ (apply #'+ list) (length list)))) (defun pick-color (line color) (case color (:black (black line)) (:red (red line)) (:green (green line)) (:blue (blue line)) (:yellow (yellow line)) (:magenta (magenta line)) (:white (white line)) (:cyan (cyan line)) (T (error "No such color: ~a" color)))) (defun eq-ntimes (width &optional (word "=")) (with-output-to-string (str) (dotimes (_ (* 2 width)) (format str word)))) (defun format-title (title start-from width word &optional default-base) (let ((base (if default-base default-base (eq-ntimes width word)))) (setf (subseq base start-from (+ start-from (length title))) title) base)) (defun init-line (frame color) (let ((x (first (array-dimensions frame)))) (loop for i from 0 to (1- x) do (setf (aref frame i 0) (pick-color "–" color))))) (defun repeat0-ntimes (n) (let ((a `(0))) (dotimes (_ (1- n)) (push 0 a)) a)) ; 共通のheightでlistの値をnormalizeしておくこと (defun listplot-write (frame list &optional (color :blue)) (let* ((x (first (array-dimensions frame))) ( y ( second ( array - dimensions frame ) ) ) (list-width (length list)) (list (if (< (length list) x) (concatenate 'list list (repeat0-ntimes (- x (length list)))) list)) (points-per-1frame (/ (max x list-width) (min x list-width))) (plot-points (loop for i from 0 to (1- list-width) by points-per-1frame collect (mean (loop for l from (1+ i) to (+ i points-per-1frame) by 1 collect (nth (1- (round l)) list))))) (plot-points-tmp (concatenate 'list plot-points `(0 0 0)))) (dotimes (i (- (length plot-points) 1)) (let ((point-y (nth i plot-points-tmp)) (line (case i (0 (choose-line (cons 0 (car plot-points-tmp)) (cons 1 (second plot-points-tmp)) (cons 2 (third plot-points-tmp)))) (T (choose-line (cons (1- i) (nth (1- i) plot-points-tmp)) (cons i (nth i plot-points-tmp)) (cons (1+ i) (nth (1+ i) plot-points-tmp))))))) (setf (aref frame (min i (1- x)) (round point-y)) (pick-color line color)))))) (defun listplot-print (frame &key (x-label "x") (y-label "y") (descriptions) (title "No title:") (stream t)) ; descriptions an list of `(:color "name" max min) (declare (ignore stream)) (let ((width-len (car (array-dimensions frame)))) (let ((graph (with-output-to-string (result) (if title (format result "||~a||~C~a~C" title #\newline y-label #\newline) (format result "~a~C" y-label #\newline)) ;(if y-max ; (format result "~a_~C" y-max #\newline)) (loop for y from 1 to (second (array-dimensions frame)) do (progn (loop for x from 0 to (1- (car (array-dimensions frame))) do (progn (write-string (aref frame x (- (second (array-dimensions frame)) y)) result))) (write-char #\newline result))) (write-string (format-title x-label (* 1 (- width-len (1+ (length x-label)))) width-len " " (format-title "0" 0 width-len " ")) result) (write-char #\newline result) (if descriptions (let ((max-desc-title (apply #'max (map 'list #'(lambda (desc) (length (second desc))) descriptions)))) (dolist (desc descriptions) (write-string (pick-color (format nil "|~a: (~a ... ~a)~C" (format-title (second desc) 1 width-len "" (eq-ntimes max-desc-title " ")) (third desc) (fourth desc) #\newline) (car desc)) result))))))) (princ graph))))
null
https://raw.githubusercontent.com/hikettei/cl-waffe/a471a3cca5aa2aca049a04f8771d999f3dc013ca/source/cl-termgraph/figure.lisp
lisp
set as undefined 共通のheightでlistの値をnormalizeしておくこと descriptions an list of `(:color "name" max min) (if y-max (format result "~a_~C" y-max #\newline))
(in-package :cl-termgraph) (defparameter *dif* 1/16) (defparameter *positive-lines* `("⠒⠒" "⣠⣤" "⣠⣰" "⣠⣼" "⡜⡜" "⣼⡜" "⡇⡇")) (defparameter *negative-lines* `("⠒⠒" "⣤⣄" "⣆⣄" "⣧⣄" "⢣⢣" "⢣⣧" "⡇⡇")) (defgeneric plot (frame pallet)) (defmacro mbind (&rest args) `(multiple-value-bind ,@args)) (defclass figure-graph-frame (simple-graph-frame) ((figure :accessor figure :initarg :figure :initform nil) (from :accessor figurefrom :initarg :from :initform nil) (end :accessor figureend :initarg :end :initform nil) (name :accessor name :initarg :name :initform nil))) (defclass parameter-graph-frame (figure-graph-frame) ((parameter :accessor parameter :initarg :parameter :initform nil) (by :accessor move-by :initarg :by :initform 1) (pstart :accessor pstart :initarg :pstart :initform -3) (pend :accessor pend :initarg :pend :initform 3))) (defmethod collect-figure-points ((frame figure-graph-frame)) (with-slots ((figure figure) (s from) (e end)) frame (loop for i from s to (1- e) by *dif* collect (handler-case (funcall figure i) (declare (ignore x)) `(,i . nil)) (:no-error (x) `(,i . ,x)))))) (defun max-points (points) (loop for i in (map 'list #'(lambda (p) (cdr p)) points) maximize i)) (defun min-points (points) (loop for i in (map 'list #'(lambda (p) (cdr p)) points) minimize i)) (defun maxmin-points (points) (values (max-points points) (min-points points))) (defmacro choose-line (p1 p2 p3 &optional (opt 0)) `(let ((ti (+ ,opt (3p-tilt-ave ,p1 ,p2 ,p3)))) (cond ((= ti 0) (first *positive-lines*)) ((and (< 0 ti) (< ti 0.5)) (second *positive-lines*)) ((and (<= 0.5 ti) (< ti 1.0)) (third *positive-lines*)) ((and (<= 1.0 ti) (< ti 1.5)) (fourth *positive-lines*)) ((and (<= 1.5 ti) (< ti 3.0)) (fifth *positive-lines*)) ((and (<= 3.0 ti) (< ti 4.5)) (sixth *positive-lines*)) ((>= ti 4.5) (seventh *positive-lines*)) ((and (< -0.5 ti) (<= ti 0)) (second *negative-lines*)) ((and (< -1.0 ti) (<= ti -0.5)) (third *negative-lines*)) ((and (< -1.5 ti) (<= ti -1.0)) (fourth *negative-lines*)) ((and (< -3.0 ti) (<= ti -1.5)) (fifth *negative-lines*)) ((and (< -4.5 ti) (<= ti -3.0)) (sixth *negative-lines*)) ((<= ti -4.5) (seventh *negative-lines*))))) (defmacro tilt (p1 p2) `(if (and ,p1 ,p2) (/ (- (cdr ,p1) (cdr ,p2)) (- (car ,p1) (car ,p2))) 0)) (defmacro 3p-tilt-ave (p1 p2 p3) `(/ (+ (tilt ,p1 ,p2) (tilt ,p2 ,p3)) 2)) (defun render (frame pallet) (with-output-to-string (graph) (loop for y from 1 to (slot-value frame 'height) do (loop for x from 0 to (1- (slot-value frame 'width)) do (write-string (aref pallet x (- (slot-value frame 'height) y)) graph)) (write-char #\Newline graph)))) (defun make-listplot-frame (x y) (make-array `(,x ,y) :initial-element " ")) (defun mean (list) (if (= (length list) 0) 0 (/ (apply #'+ list) (length list)))) (defun pick-color (line color) (case color (:black (black line)) (:red (red line)) (:green (green line)) (:blue (blue line)) (:yellow (yellow line)) (:magenta (magenta line)) (:white (white line)) (:cyan (cyan line)) (T (error "No such color: ~a" color)))) (defun eq-ntimes (width &optional (word "=")) (with-output-to-string (str) (dotimes (_ (* 2 width)) (format str word)))) (defun format-title (title start-from width word &optional default-base) (let ((base (if default-base default-base (eq-ntimes width word)))) (setf (subseq base start-from (+ start-from (length title))) title) base)) (defun init-line (frame color) (let ((x (first (array-dimensions frame)))) (loop for i from 0 to (1- x) do (setf (aref frame i 0) (pick-color "–" color))))) (defun repeat0-ntimes (n) (let ((a `(0))) (dotimes (_ (1- n)) (push 0 a)) a)) (defun listplot-write (frame list &optional (color :blue)) (let* ((x (first (array-dimensions frame))) ( y ( second ( array - dimensions frame ) ) ) (list-width (length list)) (list (if (< (length list) x) (concatenate 'list list (repeat0-ntimes (- x (length list)))) list)) (points-per-1frame (/ (max x list-width) (min x list-width))) (plot-points (loop for i from 0 to (1- list-width) by points-per-1frame collect (mean (loop for l from (1+ i) to (+ i points-per-1frame) by 1 collect (nth (1- (round l)) list))))) (plot-points-tmp (concatenate 'list plot-points `(0 0 0)))) (dotimes (i (- (length plot-points) 1)) (let ((point-y (nth i plot-points-tmp)) (line (case i (0 (choose-line (cons 0 (car plot-points-tmp)) (cons 1 (second plot-points-tmp)) (cons 2 (third plot-points-tmp)))) (T (choose-line (cons (1- i) (nth (1- i) plot-points-tmp)) (cons i (nth i plot-points-tmp)) (cons (1+ i) (nth (1+ i) plot-points-tmp))))))) (setf (aref frame (min i (1- x)) (round point-y)) (pick-color line color)))))) (defun listplot-print (frame &key (x-label "x") (y-label "y") (descriptions) (title "No title:") (stream t)) (declare (ignore stream)) (let ((width-len (car (array-dimensions frame)))) (let ((graph (with-output-to-string (result) (if title (format result "||~a||~C~a~C" title #\newline y-label #\newline) (format result "~a~C" y-label #\newline)) (loop for y from 1 to (second (array-dimensions frame)) do (progn (loop for x from 0 to (1- (car (array-dimensions frame))) do (progn (write-string (aref frame x (- (second (array-dimensions frame)) y)) result))) (write-char #\newline result))) (write-string (format-title x-label (* 1 (- width-len (1+ (length x-label)))) width-len " " (format-title "0" 0 width-len " ")) result) (write-char #\newline result) (if descriptions (let ((max-desc-title (apply #'max (map 'list #'(lambda (desc) (length (second desc))) descriptions)))) (dolist (desc descriptions) (write-string (pick-color (format nil "|~a: (~a ... ~a)~C" (format-title (second desc) 1 width-len "" (eq-ntimes max-desc-title " ")) (third desc) (fourth desc) #\newline) (car desc)) result))))))) (princ graph))))
f2967bc61e0fd333613f9b2a3ccf89a452e29b3600d3fc2ffbde8bfda62fa6d6
tomjridge/kv-hash
nv_map_ii.ml
(** NOTE this doesn't have a values file... it just combines partition and bucket *) open Util open Bucket_intf open Bucket_store_intf open Nv_map_ii_intf module Partition_ii = Partition.Partition_ii module Util_ = struct (** Create an initial n-way partition, with values provided by alloc *) let initial_partitioning ~alloc ~n = let stride = Int.max_int / n in Base.List.range ~stride ~start:`inclusive ~stop:`inclusive 0 ((n-1)*stride) |> fun ks -> List.rev ks |> List.rev_map (fun x -> x,alloc ()) |> fun krs -> Partition_ii.of_list krs end open Util_ module Make_1(Raw_bucket:BUCKET)(Bucket_store : BUCKET_STORE with type raw_bucket=Raw_bucket.t) = struct type raw_bucket = Bucket_store.raw_bucket type k = int type v = int (* Runtime handle *) type t = { bucket_store : Bucket_store.t; mutable freelist : Freelist.t; mutable partition : Partition_ii.t; (* NOTE mutable *) } (* abbrev *) let alloc t = Freelist.alloc t.freelist FIXME just have a single create with values , not fnames create with an initial partition and let create_fpn ~buckets_fn ~partition ~min_free_blk = let bucket_store = Bucket_store.create ~fn:buckets_fn () in let freelist = Freelist.create ~min_free:min_free_blk in { bucket_store; freelist; partition; } let create_fp ~buckets_fn ~partition = let min_free_blk = Partition_ii.suc_max_value partition in create_fpn ~buckets_fn ~partition ~min_free_blk let create_fn ~buckets_fn ~n = let alloc_counter = ref 1 in let alloc () = !alloc_counter |> fun r -> incr alloc_counter; r in let partition = initial_partitioning ~alloc ~n in let min_free_blk = !alloc_counter in create_fpn ~buckets_fn ~partition ~min_free_blk let create_f ~buckets_fn = let n = Config.config.initial_number_of_partitions in create_fn ~buckets_fn ~n let close t = Bucket_store.close t.bucket_store; (* FIXME sync partition for reopen *) () NOTE there should only be one rw process let open_rw ~buckets_fn ~partition_fn ~freelist_fn = let buckets = Bucket_store.open_ ~fn:buckets_fn in let partition = Partition_ii.read_fn ~fn:partition_fn in let freelist = Freelist.load_no_promote ~fn:freelist_fn in { bucket_store=buckets; freelist; partition } (* FIXME if we open from an RO instance, some of the files may no longer exist, so we should take care to catch exceptions, close opened fds etc *) let open_ro ~buckets_fn ~partition_fn = let buckets = Bucket_store.open_ ~fn:buckets_fn in let partition = Partition_ii.read_fn ~fn:partition_fn in let freelist = Freelist.create ~min_free:Int.max_int in (* this freelist will throw an error on attempt to allocate *) { bucket_store=buckets; freelist; partition } we have the potential for confusion if we read a bucket twice into different arrays ; this should only happen for concurrent threads , when we assume one of the threads is a reader , so will not mutate the bucket into different arrays; this should only happen for concurrent threads, when we assume one of the threads is a reader, so will not mutate the bucket *) let find_bucket t k = Partition_ii.find t.partition k |> fun (k,blk_i) -> (* blk_i is the blk index within the store *) let bucket = Bucket_store.read_bucket t.bucket_store blk_i in k,blk_i,bucket * { 2 Public interface : insert , find ( FIXME delete ) } (* FIXME we are syncing on each modification; may be worth caching? *) (** NOTE the insert function is only called in the merge process *) let insert t k v = trace(fun () -> Printf.sprintf "insert: inserting %d %d\n%!" k v); (* find bucket *) let k1,blk_i,bucket = find_bucket t k in Raw_bucket.insert bucket.raw_bucket k v |> function | `Ok -> Bucket_store.write_bucket t.bucket_store bucket | `Split(kvs1,k2,kvs2) -> let r1,r2 = alloc t,alloc t in let b1 = Bucket_store.read_bucket t.bucket_store r1 in Raw_bucket.init_sorted b1.raw_bucket kvs1; let b2 = Bucket_store.read_bucket t.bucket_store r2 in Raw_bucket.init_sorted b2.raw_bucket kvs2; Partition_ii.split t.partition ~k1 ~r1 ~k2 ~r2; Bucket_store.write_bucket t.bucket_store b1; Bucket_store.write_bucket t.bucket_store b2; Freelist.free t.freelist blk_i; (* free the old bucket *) trace(fun () -> Printf.sprintf "insert: split partition %d into %d %d\n%!" k1 k1 k2); () let find_opt t k = let _,_,bucket = find_bucket t k in Raw_bucket.find bucket.raw_bucket k let get_freelist t = t.freelist * { 2 Debugging } let export t = Partition_ii.to_list t.partition |> fun krs -> List.rev krs |> List.rev_map (fun (k,_) -> find_bucket t k |> function (_,_,b) -> Raw_bucket.export b.raw_bucket) |> fun buckets -> {partition=krs;buckets} let _ : t -> export_t = export let show t = let open Sexplib.Std in export t |> fun e -> Sexplib.Sexp.to_string_hum [%message "Partition, buckets" ~partition:(e.partition : (int*int) list) ~buckets:(e.buckets: exported_bucket list) ] |> print_endline let get_partition t = t.partition let show_bucket t k = find_bucket t k |> fun (_,_,b) -> Raw_bucket.show b.raw_bucket let get_bucket t k = find_bucket t k |> fun (_,_,b) -> b.raw_bucket end (* Make_1 *) module Make_2 : functor (Raw_bucket:BUCKET) (Bucket_store : BUCKET_STORE with type raw_bucket=Raw_bucket.t) -> Nv_map_ii_intf.S with type raw_bucket=Raw_bucket.t = Make_1 module Make = Make_2 (** Standard instance *) module Nv_map_ii0 = Make_1(Bucket.Bucket0)(Bucket_store.Bucket_store0)
null
https://raw.githubusercontent.com/tomjridge/kv-hash/a07c202a7f228d2a09a655cf782e3eb1d9301ef6/src/nv_map_ii.ml
ocaml
* NOTE this doesn't have a values file... it just combines partition and bucket * Create an initial n-way partition, with values provided by alloc Runtime handle NOTE mutable abbrev FIXME sync partition for reopen FIXME if we open from an RO instance, some of the files may no longer exist, so we should take care to catch exceptions, close opened fds etc this freelist will throw an error on attempt to allocate blk_i is the blk index within the store FIXME we are syncing on each modification; may be worth caching? * NOTE the insert function is only called in the merge process find bucket free the old bucket Make_1 * Standard instance
open Util open Bucket_intf open Bucket_store_intf open Nv_map_ii_intf module Partition_ii = Partition.Partition_ii module Util_ = struct let initial_partitioning ~alloc ~n = let stride = Int.max_int / n in Base.List.range ~stride ~start:`inclusive ~stop:`inclusive 0 ((n-1)*stride) |> fun ks -> List.rev ks |> List.rev_map (fun x -> x,alloc ()) |> fun krs -> Partition_ii.of_list krs end open Util_ module Make_1(Raw_bucket:BUCKET)(Bucket_store : BUCKET_STORE with type raw_bucket=Raw_bucket.t) = struct type raw_bucket = Bucket_store.raw_bucket type k = int type v = int type t = { bucket_store : Bucket_store.t; mutable freelist : Freelist.t; } let alloc t = Freelist.alloc t.freelist FIXME just have a single create with values , not fnames create with an initial partition and let create_fpn ~buckets_fn ~partition ~min_free_blk = let bucket_store = Bucket_store.create ~fn:buckets_fn () in let freelist = Freelist.create ~min_free:min_free_blk in { bucket_store; freelist; partition; } let create_fp ~buckets_fn ~partition = let min_free_blk = Partition_ii.suc_max_value partition in create_fpn ~buckets_fn ~partition ~min_free_blk let create_fn ~buckets_fn ~n = let alloc_counter = ref 1 in let alloc () = !alloc_counter |> fun r -> incr alloc_counter; r in let partition = initial_partitioning ~alloc ~n in let min_free_blk = !alloc_counter in create_fpn ~buckets_fn ~partition ~min_free_blk let create_f ~buckets_fn = let n = Config.config.initial_number_of_partitions in create_fn ~buckets_fn ~n let close t = Bucket_store.close t.bucket_store; () NOTE there should only be one rw process let open_rw ~buckets_fn ~partition_fn ~freelist_fn = let buckets = Bucket_store.open_ ~fn:buckets_fn in let partition = Partition_ii.read_fn ~fn:partition_fn in let freelist = Freelist.load_no_promote ~fn:freelist_fn in { bucket_store=buckets; freelist; partition } let open_ro ~buckets_fn ~partition_fn = let buckets = Bucket_store.open_ ~fn:buckets_fn in let partition = Partition_ii.read_fn ~fn:partition_fn in let freelist = Freelist.create ~min_free:Int.max_int in { bucket_store=buckets; freelist; partition } we have the potential for confusion if we read a bucket twice into different arrays ; this should only happen for concurrent threads , when we assume one of the threads is a reader , so will not mutate the bucket into different arrays; this should only happen for concurrent threads, when we assume one of the threads is a reader, so will not mutate the bucket *) let find_bucket t k = Partition_ii.find t.partition k |> fun (k,blk_i) -> let bucket = Bucket_store.read_bucket t.bucket_store blk_i in k,blk_i,bucket * { 2 Public interface : insert , find ( FIXME delete ) } let insert t k v = trace(fun () -> Printf.sprintf "insert: inserting %d %d\n%!" k v); let k1,blk_i,bucket = find_bucket t k in Raw_bucket.insert bucket.raw_bucket k v |> function | `Ok -> Bucket_store.write_bucket t.bucket_store bucket | `Split(kvs1,k2,kvs2) -> let r1,r2 = alloc t,alloc t in let b1 = Bucket_store.read_bucket t.bucket_store r1 in Raw_bucket.init_sorted b1.raw_bucket kvs1; let b2 = Bucket_store.read_bucket t.bucket_store r2 in Raw_bucket.init_sorted b2.raw_bucket kvs2; Partition_ii.split t.partition ~k1 ~r1 ~k2 ~r2; Bucket_store.write_bucket t.bucket_store b1; Bucket_store.write_bucket t.bucket_store b2; trace(fun () -> Printf.sprintf "insert: split partition %d into %d %d\n%!" k1 k1 k2); () let find_opt t k = let _,_,bucket = find_bucket t k in Raw_bucket.find bucket.raw_bucket k let get_freelist t = t.freelist * { 2 Debugging } let export t = Partition_ii.to_list t.partition |> fun krs -> List.rev krs |> List.rev_map (fun (k,_) -> find_bucket t k |> function (_,_,b) -> Raw_bucket.export b.raw_bucket) |> fun buckets -> {partition=krs;buckets} let _ : t -> export_t = export let show t = let open Sexplib.Std in export t |> fun e -> Sexplib.Sexp.to_string_hum [%message "Partition, buckets" ~partition:(e.partition : (int*int) list) ~buckets:(e.buckets: exported_bucket list) ] |> print_endline let get_partition t = t.partition let show_bucket t k = find_bucket t k |> fun (_,_,b) -> Raw_bucket.show b.raw_bucket let get_bucket t k = find_bucket t k |> fun (_,_,b) -> b.raw_bucket module Make_2 : functor (Raw_bucket:BUCKET) (Bucket_store : BUCKET_STORE with type raw_bucket=Raw_bucket.t) -> Nv_map_ii_intf.S with type raw_bucket=Raw_bucket.t = Make_1 module Make = Make_2 module Nv_map_ii0 = Make_1(Bucket.Bucket0)(Bucket_store.Bucket_store0)
b3a8bf421439e4a247953cbac3e2ecec82c690febf5d702660b31dadcf17b5a8
imandra-ai/iex-auction-model
mechanical_markets.ml
open Helpers;; open Iex_model.Prelude;; open Iex_model.Price;; open Iex_model.Order;; open Iex_model.Priority;; open Iex_model.Fill;; open Iex_model.Clearing_price;; open Iex_model.Auction;; (**********************************************) (*** Mechanical Markets Blog Post Example ***) (**********************************************) (* -curious-feature-of-iex-auctions/ *) This first example explores the behaviour discussed in the paragraph beginning : " My understanding is that a hidden order submitted after these LOC orders could gain priority without providing a better price . " the paragraph beginning: "My understanding is that a hidden order submitted after these LOC orders could gain priority without providing a better price." *) let blog_post_example = let mdata = { nbb = cents 1009; nbo = cents 1013; iex_signal = None; short_circuit_breaker = false; } in The order book from clearing price example 1 A limit - on - close buy and sell , both at $ 10.10 let buys = [ loc (cents 1010) 1500 ] in let sells = [ loc (cents 1010) 1000 ] in Conduct the auction for the orders from clearing price example 1 begin match conduct_auction(buys, sells, mdata) with (* The auction goes ahead and results in a single fill *) | Some { clearing_price; fills = [ fill ] } -> The auction price is 10.10 assert (clearing_price = cents 1010); 1000 shares execute assert (fill.fill_qty = 1000); The LOC buy and sell order on the auction book receives an execution assert (fill.buy_id = (List.hd buys).order_id); assert (fill.sell_id = (List.hd sells).order_id); | _ -> assert false end; (* Consider the following hidden buy order *) A non - displayed limit order at $ 10.11 let hidden_bid = mk_order (ContLimit (cents 1011, NonDisplayed)) 1000 in (* Run the auction again with the hidden bid on the continuous book *) begin match conduct_auction(hidden_bid :: buys, sells, mdata) with (* Again, the auction goes ahead and results in a single execution *) | Some { clearing_price; fills = [ fill ] } -> (* The auction price is unaffected by the new order *) assert (clearing_price = cents 1010); 1000 shares still execute assert (fill.fill_qty = 1000); (* But it's now the hidden bid which receives an execution *) assert (fill.buy_id <> (List.hd buys).order_id); assert (fill.buy_id = hidden_bid.order_id); assert (fill.sell_id = (List.hd sells).order_id); | _ -> assert false end ;; (* Next we consider the behaviour discussed in the "potentially problematic example". *) (* If all displayed orders for a security are on IEX then we can compute the nbbo just from the continuous order book *) let rec most_agg_displayed_limit(side, orders) = match orders with | [] -> if side = Buy then 0 else max_int | order :: orders -> let most_agg = most_agg_displayed_limit(side, orders) in match order.order_type with | ContLimit (limit, Displayed) -> more_aggressive_of(side, limit, most_agg) | _ -> most_agg ;; let compute_mdata(buys, sells) = let nbb = most_agg_displayed_limit(Buy, buys) in let nbo = most_agg_displayed_limit(Sell, sells) in { nbb = nbb; nbo = nbo; iex_signal = None; short_circuit_breaker = false; } ;; let rec sublist i j = function | [] -> [] | x :: xs -> if j <= 0 then [] else if i <= 0 then x :: sublist 0 (j - 1) xs else sublist (i - 1) (j - 1) xs ;; Blog post example 2 let blog_post_example2 = Override auction and auction_price so that they calculate the NBBO from the displayed limit orders on IEX the NBBO from the displayed limit orders on IEX *) let auction(buys, sells) = let mdata = compute_mdata(buys, sells) in match conduct_auction(buys, sells, mdata) with | Some { fills; _ } -> fills | None -> assert false in let auction_price(buys, sells) = let mdata = compute_mdata(buys, sells) in match conduct_auction(buys, sells, mdata) with | Some { clearing_price; _ } -> clearing_price | None -> assert false in The closing auction book contains 1 LOC buy at $ 10.00 for 1,000 shares , and 1 LOC sell at $ 10.00 for 10,000 shares 1,000 shares, and 1 LOC sell at $10.00 for 10,000 shares *) let auction_buy = loc (cents 1000) 1000 in let auction_sell = loc (cents 1000) 10000 in (* A helper for constructing limit orders *) let displayed_limit price qty = mk_order (ContLimit (price, Displayed)) qty in The continuous book contains displayed bids at every price from $ 10.05 down to $ 10.00 and a sell at $ 10.07 from $10.05 down to $10.00 and a sell at $10.07 *) let continuous_sells = [ displayed_limit (cents 1007) 2000 ] in let continuous_buys = [ displayed_limit (cents 1005) 10000; displayed_limit (cents 1004) 10000; displayed_limit (cents 1003) 10000; displayed_limit (cents 1002) 10000; displayed_limit (cents 1001) 10000; displayed_limit (cents 1000) 10000; ] in let buys = auction_buy :: continuous_buys in let sells = auction_sell :: continuous_sells in Assume that all displayed quantity is on IEX . Therefore the NBBO is $ 10.05/$10.07 the NBBO is $10.05/$10.07 *) let mdata = compute_mdata(buys, sells) in assert (mdata.nbb = cents 1005); assert (mdata.nbo = cents 1007); If the auction were to take place now the clearing price would be $ 10.05 . Also , remember which orders were filled would be $10.05. Also, remember which orders were filled *) assert (auction_price(buys, sells) = cents 1005); let filled_buys = List.map (fun fill -> fill.buy_id) (auction(buys, sells)) in Now each bidder considers whether they would benefit from cancelling their displayed order and submitting a new hidden order at $ 10.06 from cancelling their displayed order and submitting a new hidden order at $10.06 *) let replace order = let new_order = mk_order (ContLimit (cents 1006, NonDisplayed)) 10000 in (* We'll reuse the previous order id so we can track whose order is whose *) { new_order with order_id = order.order_id } in let consider (current_order, reference_price, mdata) = (* The bidder considers whether submitting a new order would increase their priority in the auction. They also observe that the auction price should decrease (although they don't have enough information to actually check this). *) has_priority(Buy, replace(current_order), current_order, mdata, Some reference_price) in The first five bidders each consider in turn let five_bidders = sublist 1 6 buys in let buys = List.fold_left (fun buys order -> let ref_price = auction_price(buys, sells) in let mdata = compute_mdata(buys, sells) in if consider (order, ref_price, mdata) then (* The bidder decides to resubmit their order *) First they delete their order let buys = List.filter (fun o -> o.order_id <> order.order_id) buys in (* And then submit a new_order *) let buys = replace(order) :: buys in (* Confirm that the auction price does decrease *) assert (auction_price(buys, sells) < ref_price); buys else ( (* The bidder decides not to resubmit their order *) (* This should not happen *) assert false; ) ) buys five_bidders in If the auction were to take place now the clearing price would be $ 10.00 . However , the same orders get filled would be $10.00. However, the same orders get filled *) assert (auction_price(buys, sells) = cents 1000); let filled_buys' = List.map (fun fill -> fill.buy_id) (auction(buys, sells)) in assert (filled_buys = filled_buys') ;;
null
https://raw.githubusercontent.com/imandra-ai/iex-auction-model/41436bd1506992c69188179a330cee1e5244222b/examples/mechanical_markets.ml
ocaml
******************************************** ** Mechanical Markets Blog Post Example ** ******************************************** -curious-feature-of-iex-auctions/ The auction goes ahead and results in a single fill Consider the following hidden buy order Run the auction again with the hidden bid on the continuous book Again, the auction goes ahead and results in a single execution The auction price is unaffected by the new order But it's now the hidden bid which receives an execution Next we consider the behaviour discussed in the "potentially problematic example". If all displayed orders for a security are on IEX then we can compute the nbbo just from the continuous order book A helper for constructing limit orders We'll reuse the previous order id so we can track whose order is whose The bidder considers whether submitting a new order would increase their priority in the auction. They also observe that the auction price should decrease (although they don't have enough information to actually check this). The bidder decides to resubmit their order And then submit a new_order Confirm that the auction price does decrease The bidder decides not to resubmit their order This should not happen
open Helpers;; open Iex_model.Prelude;; open Iex_model.Price;; open Iex_model.Order;; open Iex_model.Priority;; open Iex_model.Fill;; open Iex_model.Clearing_price;; open Iex_model.Auction;; This first example explores the behaviour discussed in the paragraph beginning : " My understanding is that a hidden order submitted after these LOC orders could gain priority without providing a better price . " the paragraph beginning: "My understanding is that a hidden order submitted after these LOC orders could gain priority without providing a better price." *) let blog_post_example = let mdata = { nbb = cents 1009; nbo = cents 1013; iex_signal = None; short_circuit_breaker = false; } in The order book from clearing price example 1 A limit - on - close buy and sell , both at $ 10.10 let buys = [ loc (cents 1010) 1500 ] in let sells = [ loc (cents 1010) 1000 ] in Conduct the auction for the orders from clearing price example 1 begin match conduct_auction(buys, sells, mdata) with | Some { clearing_price; fills = [ fill ] } -> The auction price is 10.10 assert (clearing_price = cents 1010); 1000 shares execute assert (fill.fill_qty = 1000); The LOC buy and sell order on the auction book receives an execution assert (fill.buy_id = (List.hd buys).order_id); assert (fill.sell_id = (List.hd sells).order_id); | _ -> assert false end; A non - displayed limit order at $ 10.11 let hidden_bid = mk_order (ContLimit (cents 1011, NonDisplayed)) 1000 in begin match conduct_auction(hidden_bid :: buys, sells, mdata) with | Some { clearing_price; fills = [ fill ] } -> assert (clearing_price = cents 1010); 1000 shares still execute assert (fill.fill_qty = 1000); assert (fill.buy_id <> (List.hd buys).order_id); assert (fill.buy_id = hidden_bid.order_id); assert (fill.sell_id = (List.hd sells).order_id); | _ -> assert false end ;; let rec most_agg_displayed_limit(side, orders) = match orders with | [] -> if side = Buy then 0 else max_int | order :: orders -> let most_agg = most_agg_displayed_limit(side, orders) in match order.order_type with | ContLimit (limit, Displayed) -> more_aggressive_of(side, limit, most_agg) | _ -> most_agg ;; let compute_mdata(buys, sells) = let nbb = most_agg_displayed_limit(Buy, buys) in let nbo = most_agg_displayed_limit(Sell, sells) in { nbb = nbb; nbo = nbo; iex_signal = None; short_circuit_breaker = false; } ;; let rec sublist i j = function | [] -> [] | x :: xs -> if j <= 0 then [] else if i <= 0 then x :: sublist 0 (j - 1) xs else sublist (i - 1) (j - 1) xs ;; Blog post example 2 let blog_post_example2 = Override auction and auction_price so that they calculate the NBBO from the displayed limit orders on IEX the NBBO from the displayed limit orders on IEX *) let auction(buys, sells) = let mdata = compute_mdata(buys, sells) in match conduct_auction(buys, sells, mdata) with | Some { fills; _ } -> fills | None -> assert false in let auction_price(buys, sells) = let mdata = compute_mdata(buys, sells) in match conduct_auction(buys, sells, mdata) with | Some { clearing_price; _ } -> clearing_price | None -> assert false in The closing auction book contains 1 LOC buy at $ 10.00 for 1,000 shares , and 1 LOC sell at $ 10.00 for 10,000 shares 1,000 shares, and 1 LOC sell at $10.00 for 10,000 shares *) let auction_buy = loc (cents 1000) 1000 in let auction_sell = loc (cents 1000) 10000 in let displayed_limit price qty = mk_order (ContLimit (price, Displayed)) qty in The continuous book contains displayed bids at every price from $ 10.05 down to $ 10.00 and a sell at $ 10.07 from $10.05 down to $10.00 and a sell at $10.07 *) let continuous_sells = [ displayed_limit (cents 1007) 2000 ] in let continuous_buys = [ displayed_limit (cents 1005) 10000; displayed_limit (cents 1004) 10000; displayed_limit (cents 1003) 10000; displayed_limit (cents 1002) 10000; displayed_limit (cents 1001) 10000; displayed_limit (cents 1000) 10000; ] in let buys = auction_buy :: continuous_buys in let sells = auction_sell :: continuous_sells in Assume that all displayed quantity is on IEX . Therefore the NBBO is $ 10.05/$10.07 the NBBO is $10.05/$10.07 *) let mdata = compute_mdata(buys, sells) in assert (mdata.nbb = cents 1005); assert (mdata.nbo = cents 1007); If the auction were to take place now the clearing price would be $ 10.05 . Also , remember which orders were filled would be $10.05. Also, remember which orders were filled *) assert (auction_price(buys, sells) = cents 1005); let filled_buys = List.map (fun fill -> fill.buy_id) (auction(buys, sells)) in Now each bidder considers whether they would benefit from cancelling their displayed order and submitting a new hidden order at $ 10.06 from cancelling their displayed order and submitting a new hidden order at $10.06 *) let replace order = let new_order = mk_order (ContLimit (cents 1006, NonDisplayed)) 10000 in { new_order with order_id = order.order_id } in let consider (current_order, reference_price, mdata) = has_priority(Buy, replace(current_order), current_order, mdata, Some reference_price) in The first five bidders each consider in turn let five_bidders = sublist 1 6 buys in let buys = List.fold_left (fun buys order -> let ref_price = auction_price(buys, sells) in let mdata = compute_mdata(buys, sells) in if consider (order, ref_price, mdata) then First they delete their order let buys = List.filter (fun o -> o.order_id <> order.order_id) buys in let buys = replace(order) :: buys in assert (auction_price(buys, sells) < ref_price); buys else ( assert false; ) ) buys five_bidders in If the auction were to take place now the clearing price would be $ 10.00 . However , the same orders get filled would be $10.00. However, the same orders get filled *) assert (auction_price(buys, sells) = cents 1000); let filled_buys' = List.map (fun fill -> fill.buy_id) (auction(buys, sells)) in assert (filled_buys = filled_buys') ;;
8f80674608fd18f72f9189c88110f6c31c612188805b5276d32e08e686688fed
startalkIM/ejabberd
fast_xml.erl
%%%---------------------------------------------------------------------- %%% File : fxml_app.erl Author : < > %%% Purpose : Fast XML application Created : 1 May 2013 by < > %%% %%% Copyright ( C ) 2002 - 2019 ProcessOne , SARL . All Rights Reserved . %%% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% -2.0 %%% %%% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -module(fast_xml). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% Application callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% This function is called whenever an application is started using application : start/[1,2 ] , and should start the processes of the %% application. If the application is structured according to the OTP %% design principles as a supervision tree, this means starting the %% top supervisor of the tree. %% @spec start(StartType , ) - > { ok , Pid } | { ok , Pid , State } | %% {error, Reason} %% StartType = normal | {takeover, Node} | {failover, Node} = term ( ) %% @end %%-------------------------------------------------------------------- start(_StartType, _StartArgs) -> case {fxml:load_nif(), fxml_stream:load_nif()} of {ok, ok} -> fxml_sup:start_link(); {{error,_} = E1, _} -> E1; {_, {error,_} = E2} -> E2 end. %%-------------------------------------------------------------------- @private %% @doc %% This function is called whenever an application has stopped. It %% is intended to be the opposite of Module:start/2 and should do %% any necessary cleaning up. The return value is ignored. %% %% @spec stop(State) -> void() %% @end %%-------------------------------------------------------------------- stop(_State) -> ok. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/deps/fast_xml/src/fast_xml.erl
erlang
---------------------------------------------------------------------- File : fxml_app.erl Purpose : Fast XML application 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. ---------------------------------------------------------------------- Application callbacks =================================================================== Application callbacks =================================================================== -------------------------------------------------------------------- @doc This function is called whenever an application is started using application. If the application is structured according to the OTP design principles as a supervision tree, this means starting the top supervisor of the tree. {error, Reason} StartType = normal | {takeover, Node} | {failover, Node} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function is called whenever an application has stopped. It is intended to be the opposite of Module:start/2 and should do any necessary cleaning up. The return value is ignored. @spec stop(State) -> void() @end -------------------------------------------------------------------- =================================================================== ===================================================================
Author : < > Created : 1 May 2013 by < > Copyright ( C ) 2002 - 2019 ProcessOne , SARL . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(fast_xml). -behaviour(application). -export([start/2, stop/1]). @private application : start/[1,2 ] , and should start the processes of the @spec start(StartType , ) - > { ok , Pid } | { ok , Pid , State } | = term ( ) start(_StartType, _StartArgs) -> case {fxml:load_nif(), fxml_stream:load_nif()} of {ok, ok} -> fxml_sup:start_link(); {{error,_} = E1, _} -> E1; {_, {error,_} = E2} -> E2 end. @private stop(_State) -> ok. Internal functions
5713c27feb2a08f250a27a6f515948c462a22d12e41fa6761dfeda9aa19bd8b1
OCamlPro/liquidity
liquidClientSigs.ml
module Liquidity = LiquidityLang module type LANG = sig module Source : sig * type const * ( \ * type expr * \ ) * type contract * type datatype * type loc_info * type location * * val unit : const * val tuple : const list - > const * val list_big_maps : const - > datatype - > ( bm_id * datatype * datatype ) list * ( \ * val string_of_const : const - > string * \ ) * val storage : contract - > datatype * val entries : contract - > ( string * datatype ) list * val apply_big_map_subst : ( int * ( const * const ) list ) list - > const - > const * default_empty_const : datatype - > const * * val print_loc : Format.formatter - > location - > unit * * val parse_contract : from - > contract * * val datatype : datatype Lazy_superposed.superposer * val const : const Lazy_superposed.superposer * contract : contract Lazy_superposed.superposer * * ( \**/ * unsused * * \ ) * val const_encoding : const Json_encoding.encoding * contract_encoding : contract Json_encoding.encoding * val datatype_encoding : datatype Json_encoding.encoding * * end * type const * (\* type expr *\) * type contract * type datatype * type loc_info * type location * * val unit : const * val tuple : const list -> const * val list_big_maps : const -> datatype -> (bm_id * datatype * datatype) list * (\* val string_of_const : const -> string *\) * val storage : contract -> datatype * val entries : contract -> (string * datatype) list * val apply_big_map_subst : (int * (const * const) list) list -> const -> const * val default_empty_const : datatype -> const * * val print_loc : Format.formatter -> location -> unit * * val parse_contract : from -> contract * * val datatype : datatype Lazy_superposed.superposer * val const : const Lazy_superposed.superposer * val contract : contract Lazy_superposed.superposer * * (\**/* unsused **\) * val const_encoding : const Json_encoding.encoding * val contract_encoding : contract Json_encoding.encoding * val datatype_encoding : datatype Json_encoding.encoding * * end *) module Target : sig type const (* type expr *) type contract type location type datatype val name : string val unit : const val compare_loc : location -> location -> int val next_loc : location -> location val loc_encoding : location Json_encoding.encoding val const_encoding : const Json_encoding.encoding val contract_encoding : contract Json_encoding.encoding val datatype_encoding : datatype Json_encoding.encoding val datatype : datatype Lazy_superposed.superposer val const : const Lazy_superposed.superposer val contract : contract Lazy_superposed.superposer end val compile_contract : Liquidity.contract -> Target.contract * Liquidity.compiled_init * (Target.location * (Liquidity.location * Liquidity.loc_info)) list val decompile_contract : Target.contract -> Liquidity.contract val compile_const : ?ty:Liquidity.datatype -> Liquidity.const -> Target.const val decompile_const : ?ty:Liquidity.datatype -> Target.const -> Liquidity.const val compile_datatype : Liquidity.datatype -> Target.datatype end
null
https://raw.githubusercontent.com/OCamlPro/liquidity/3578de34cf751f54b9e4c001a95625d2041b2962/tools/client/liquidClientSigs.ml
ocaml
type expr
module Liquidity = LiquidityLang module type LANG = sig module Source : sig * type const * ( \ * type expr * \ ) * type contract * type datatype * type loc_info * type location * * val unit : const * val tuple : const list - > const * val list_big_maps : const - > datatype - > ( bm_id * datatype * datatype ) list * ( \ * val string_of_const : const - > string * \ ) * val storage : contract - > datatype * val entries : contract - > ( string * datatype ) list * val apply_big_map_subst : ( int * ( const * const ) list ) list - > const - > const * default_empty_const : datatype - > const * * val print_loc : Format.formatter - > location - > unit * * val parse_contract : from - > contract * * val datatype : datatype Lazy_superposed.superposer * val const : const Lazy_superposed.superposer * contract : contract Lazy_superposed.superposer * * ( \**/ * unsused * * \ ) * val const_encoding : const Json_encoding.encoding * contract_encoding : contract Json_encoding.encoding * val datatype_encoding : datatype Json_encoding.encoding * * end * type const * (\* type expr *\) * type contract * type datatype * type loc_info * type location * * val unit : const * val tuple : const list -> const * val list_big_maps : const -> datatype -> (bm_id * datatype * datatype) list * (\* val string_of_const : const -> string *\) * val storage : contract -> datatype * val entries : contract -> (string * datatype) list * val apply_big_map_subst : (int * (const * const) list) list -> const -> const * val default_empty_const : datatype -> const * * val print_loc : Format.formatter -> location -> unit * * val parse_contract : from -> contract * * val datatype : datatype Lazy_superposed.superposer * val const : const Lazy_superposed.superposer * val contract : contract Lazy_superposed.superposer * * (\**/* unsused **\) * val const_encoding : const Json_encoding.encoding * val contract_encoding : contract Json_encoding.encoding * val datatype_encoding : datatype Json_encoding.encoding * * end *) module Target : sig type const type contract type location type datatype val name : string val unit : const val compare_loc : location -> location -> int val next_loc : location -> location val loc_encoding : location Json_encoding.encoding val const_encoding : const Json_encoding.encoding val contract_encoding : contract Json_encoding.encoding val datatype_encoding : datatype Json_encoding.encoding val datatype : datatype Lazy_superposed.superposer val const : const Lazy_superposed.superposer val contract : contract Lazy_superposed.superposer end val compile_contract : Liquidity.contract -> Target.contract * Liquidity.compiled_init * (Target.location * (Liquidity.location * Liquidity.loc_info)) list val decompile_contract : Target.contract -> Liquidity.contract val compile_const : ?ty:Liquidity.datatype -> Liquidity.const -> Target.const val decompile_const : ?ty:Liquidity.datatype -> Target.const -> Liquidity.const val compile_datatype : Liquidity.datatype -> Target.datatype end
96798250574369c82d2331ee31058b2cbed408a31cca1b84cbdec0c7c321b409
glguy/5puzzle
Cube.hs
module Main where import Ersatz import Booleans import Linear import Select import SparseMap import Control.Applicative import Data.List (nub, permutations) import Data.Traversable (for) import Control.Monad import Data.Foldable(for_) import Prelude hiding ((&&), (||), not, all, any,or,not) data Piece = Piece Int Int Int deriving (Eq, Show) type Coord = V3 Int -- | Compute all the unique orientations of a piece along each of the 3 axes . orientations :: Piece -> [Piece] orientations (Piece x y z) = nub [ Piece x' y' z' | [x',y',z'] <- permutations [x,y,z] ] blank, cube, flat, thick :: Piece cube = Piece 1 1 1 flat = Piece 4 2 1 thick = Piece 2 2 3 blank = Piece 0 0 0 -- | Compute a bitmap of the locations that a piece covers -- when placed at a particular location cover :: Coord -> Piece -> SparseMap (V3 Int) Bit cover (V3 x y z) (Piece dx dy dz) = trueList (liftA3 V3 [x..x+dx-1] [y..y+dy-1] [z..z+dz-1]) locations :: [Coord] locations = liftA3 V3 [0..4] [0..4] [0..4] selectOrientation :: MonadSAT s m => Select Piece -> m (Select Piece) selectOrientation x = join <$> traverse (selectList . orientations) x solution :: MonadSAT s m => m [Select Piece] solution = do (pieces, orientedPieces, coverMaps) <- unzip3 <$> for locations (\loc -> do p <- selectList [blank,cube,flat,thick] po <- selectOrientation p let pcov = runSelectWith (cover loc) po return (p,po,pcov)) assert $ true === (falseList locations || or coverMaps) assert $ coverOne (trueList locations) coverMaps assert $ count cube pieces === 5 assert $ count thick pieces === 6 assert $ count flat pieces === 6 assert $ count blank pieces === (125-6-6-5) return orientedPieces count :: Eq a => a -> [Select a] -> Bits count target xs = countBits (map eltToBit xs) where eltToBit elt = pure target === elt main :: IO () main = do Just res <- getModel solution putStrLn "color(\"BurlyWood\",0.8){" for_ (zip locations res) $ \(V3 x y z, piece) -> case piece of Piece 0 0 0 -> return () Piece dx dy dz -> putStrLn $ "translate(" ++ show (map recenter [x,y,z]) ++ "){" ++ "cube(" ++ show (map gap [dx,dy,dz]) ++ ");}" putStrLn "}" where gap, recenter :: Int -> Double gap x = fromIntegral x - 0.2 recenter x = fromIntegral x - 2.5
null
https://raw.githubusercontent.com/glguy/5puzzle/4d86cf9fad3ec3f70c57a167417adea6a3f9f30b/Cube.hs
haskell
| Compute all the unique orientations of a piece along each | Compute a bitmap of the locations that a piece covers when placed at a particular location
module Main where import Ersatz import Booleans import Linear import Select import SparseMap import Control.Applicative import Data.List (nub, permutations) import Data.Traversable (for) import Control.Monad import Data.Foldable(for_) import Prelude hiding ((&&), (||), not, all, any,or,not) data Piece = Piece Int Int Int deriving (Eq, Show) type Coord = V3 Int of the 3 axes . orientations :: Piece -> [Piece] orientations (Piece x y z) = nub [ Piece x' y' z' | [x',y',z'] <- permutations [x,y,z] ] blank, cube, flat, thick :: Piece cube = Piece 1 1 1 flat = Piece 4 2 1 thick = Piece 2 2 3 blank = Piece 0 0 0 cover :: Coord -> Piece -> SparseMap (V3 Int) Bit cover (V3 x y z) (Piece dx dy dz) = trueList (liftA3 V3 [x..x+dx-1] [y..y+dy-1] [z..z+dz-1]) locations :: [Coord] locations = liftA3 V3 [0..4] [0..4] [0..4] selectOrientation :: MonadSAT s m => Select Piece -> m (Select Piece) selectOrientation x = join <$> traverse (selectList . orientations) x solution :: MonadSAT s m => m [Select Piece] solution = do (pieces, orientedPieces, coverMaps) <- unzip3 <$> for locations (\loc -> do p <- selectList [blank,cube,flat,thick] po <- selectOrientation p let pcov = runSelectWith (cover loc) po return (p,po,pcov)) assert $ true === (falseList locations || or coverMaps) assert $ coverOne (trueList locations) coverMaps assert $ count cube pieces === 5 assert $ count thick pieces === 6 assert $ count flat pieces === 6 assert $ count blank pieces === (125-6-6-5) return orientedPieces count :: Eq a => a -> [Select a] -> Bits count target xs = countBits (map eltToBit xs) where eltToBit elt = pure target === elt main :: IO () main = do Just res <- getModel solution putStrLn "color(\"BurlyWood\",0.8){" for_ (zip locations res) $ \(V3 x y z, piece) -> case piece of Piece 0 0 0 -> return () Piece dx dy dz -> putStrLn $ "translate(" ++ show (map recenter [x,y,z]) ++ "){" ++ "cube(" ++ show (map gap [dx,dy,dz]) ++ ");}" putStrLn "}" where gap, recenter :: Int -> Double gap x = fromIntegral x - 0.2 recenter x = fromIntegral x - 2.5
1585f702803970db6d358637dcda2afa9466da287bf41656b27afb0abd479708
ucsd-progsys/dsolve
dotprod2.ml
let dotprod v1 v2 = begin let sum = ref 0 in let i = ref 0 in let sz = size v1 in let rec loop = if !i < sz then (i := !i + 1; sum := (get v1 i) * (get v2 i) + !sum; loop) else () in loop; !sum end ;;
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/tests/POPL2008/dotprod2.ml
ocaml
let dotprod v1 v2 = begin let sum = ref 0 in let i = ref 0 in let sz = size v1 in let rec loop = if !i < sz then (i := !i + 1; sum := (get v1 i) * (get v2 i) + !sum; loop) else () in loop; !sum end ;;
52a7d684ad630f33d44dd8619d468b3e4108e86e3c5490a0b64ab3f3cf9eb56e
arne-schroppe/dash
BuiltInDefinitions.hs
module Language.Dash.BuiltIn.BuiltInDefinitions ( builtInFunctions , builtInSymbols , bifStringConcatName , bifListConcatName , bifToStringName , bifStringConcatOperator , tupleSymbolName , recordSymbolName , listConsSymbolName , listEmptySymbolName , trueSymbolName , falseSymbolName , preamble , moduleOwner , errorSymbolName , runtimeErrorSymbolName ) where import Data.Maybe (fromJust) import Language.Dash.IR.Data import Language.Dash.IR.Opcode runtimeErrorSymbolName, errorSymbolName, nilSymbolName, tupleSymbolName, recordSymbolName, listConsSymbolName, listEmptySymbolName, trueSymbolName, falseSymbolName, numberTypeSymbolName, stringTypeSymbolName, symbolTypeSymbolName, functionTypeSymbolName :: String trueSymbolName = "true" falseSymbolName = "false" nilSymbolName = "nil" Note : If you change these names , also change them in Types.hs tupleSymbolName = "$_tuple" recordSymbolName = "$_record" listConsSymbolName = "$_list" listEmptySymbolName = "$_empty_list" numberTypeSymbolName = "number" stringTypeSymbolName = "string" symbolTypeSymbolName = "symbol" functionTypeSymbolName = "function" errorSymbolName = "error" runtimeErrorSymbolName = "runtime_error" builtInSymbols :: [(String, SymId)] builtInSymbols = map f d where f (s, i) = (s, mkSymId i) d = zip syms [0..length syms] 0 1 2 -- TODO prevent user from accessing these directly 3 4 5 6 7 8 9 10 -- TODO should probably be 0 11 ] moduleOwner :: SymId moduleOwner = mkSymId 0 bifStringConcatName, bifListConcatName, bifStringLengthName, bifSubStringName, bifToStringName, bifStringConcatOperator :: String bifStringConcatName = "concatenate_strings" bifListConcatName = "concatenate" bifStringLengthName = "string_length" bifSubStringName = "sub_string" bifToStringName = "to_string" bifStringConcatOperator = "^+" -- TODO instead of "special" handling for primops, we could also add a bif for every primop and then inline some functions -- (e.g. those with less than n opcodes, etc) -- type Arity = Int builtInFunctions :: [(Name, Arity, [Opcode])] builtInFunctions = [ (bifStringConcatName, 2, [ OpcStrLen 2 0, OpcStrLen 3 1, OpcAdd 4 2 3, OpcNewStr 5 4, OpcLoadI 6 0, -- index OpcLoadI 7 1, -- loop1: OpcLT 8 2 6, -- is index >= length? OpcJmpTrue 8 4, -- jmp to next OpcGetChar 9 0 6, OpcPutChar 9 5 6, OpcAdd 6 6 7, jmp to loop1 -- next: OpcLoadI 6 0, -- loop2: OpcLT 8 3 6, OpcJmpTrue 8 5, -- jmp to done OpcGetChar 9 1 6, OpcAdd 10 2 6, OpcPutChar 9 5 10, OpcAdd 6 6 7, jmp to -- done: OpcMove 0 5, OpcRet 0 ]), (bifStringLengthName, 1, [ OpcStrLen 0 0, OpcRet 0 ]), TODO truncate length if needed OpcNewStr 3 1, OpcLoadI 6 1, OpcLoadI 7 0, -- counter -- loop1: TODO this is ugly . Fix our off - by - one error properly OpcLT 4 1 9, -- is index >= length? OpcJmpTrue 4 5, -- jmp to next OpcAdd 8 7 0, OpcGetChar 5 2 8, OpcPutChar 5 3 7, OpcAdd 7 7 6, jmp to loop1 -- next: OpcMove 0 3, OpcRet 0 ]), ("<=", 2, [ OpcLT 2 0 1, OpcJmpTrue 2 1, OpcEq 2 0 1, OpcMove 0 2, OpcRet 0 ]), (">=", 2, [ OpcGT 2 0 1, OpcJmpTrue 2 1, OpcEq 2 0 1, OpcMove 0 2, OpcRet 0 ]), ("!=", 2, [ OpcEq 2 0 1, OpcNot 0 2, OpcRet 0 ]), ("to_number", 1, [ OpcLoadPS 1 (fromJust $ lookup numberTypeSymbolName builtInSymbols), OpcConvert 0 0 1, OpcRet 0 ]), (bifToStringName, 1, [ OpcLoadPS 1 (fromJust $ lookup stringTypeSymbolName builtInSymbols), OpcConvert 0 0 1, OpcRet 0 ]) ] returnActionId, readLineActionId, printLineActionId :: Int returnActionId = 0 readLineActionId = 1 printLineActionId = 2 preamble :: String preamble = "\n\ \ io = module \n\ \ bind action next = \n\ \ match action with \n\ \ :_internal_io<type, param, :nil> -> :_internal_io<type, param, next> \n\ \ :_internal_io<type, param, n0> -> :_internal_io<type, param, (x -> bind (n0 x) next)> \n\ \ _ -> :error<:" ++ runtimeErrorSymbolName ++ ", \"io-bind: Expected an io action as first argument\">\n\ \ end \n\ \ \n\ \ return a = \n\ \ :_internal_io<" ++ show returnActionId ++ ", a, :nil> \n\ \ \n\ \ read_line = \n\ \ :_internal_io<" ++ show readLineActionId ++ ", :nil, :nil> \n\ \ \n\ \ print a = \n\ \ :_internal_io<" ++ show printLineActionId ++ ", a, :nil> \n\ \ \n\ \ print_line a = \n\ \ :_internal_io<" ++ show printLineActionId ++ ", (a " ++ bifStringConcatOperator ++ " \"\\n\"), :nil> \n\ \ end \n\ \ \n\ \ head ls = \n\ \ match ls with \n\ \ [a | _] -> a \n\ \ _ -> :error<:" ++ runtimeErrorSymbolName ++ ",\"Empty list!\"> \n\ \ end \n\ \ \n\ \ tail ls = \n\ \ match ls with \n\ \ [_ | as] -> as \n\ \ _ -> [] \n\ \ end \n\ \ \n\ \ map f ls = \n\ \ match ls with \n\ \ [] -> [] \n\ \ [a | rest] -> [f a | map f rest] \n\ \ end \n\ \ \n\ \ foldr f z ls = \n\ \ match ls with \n\ \ [] -> z \n\ \ [a | rest] -> f a (foldr f z rest) \n\ \ end \n\ \ \n\ \ " ++ bifListConcatName ++ " a b = \n\ \ match a with \n\ \ [] -> b \n\ \ [hd | tl] -> [hd | " ++ bifListConcatName ++ " tl b] \n\ \ end \n\ \ \n\ \ reverse l = \n\ \ rev_list' l acc = \n\ \ match l with \n\ \ [] -> acc \n\ \ [hd | tl] -> rev_list' tl [hd | acc] \n\ \ end \n\ \ rev_list' l [] \n\ \ \n\ \ \n\ \ filter f ls = \n\ \ match ls with \n\ \ [] -> [] \n\ \ [x | xs] -> \n\ \ if f x \n\ \ then [x | filter f xs] \n\ \ else filter f xs \n\ \ end \n\ \ \n\ \ length list = \n\ \ len' l acc = \n\ \ match l with \n\ \ [] -> acc \n\ \ [_ | as] -> len' as (acc + 1) \n\ \ x -> :error<:" ++ runtimeErrorSymbolName ++ ", \"Not a list\"> \n\ \ end \n\ \ len' list 0 \n\ \ \n\ \ \n\ \ sequence m ms = \n\ \ k a b = \n\ \ do m with \n\ \ l <- a \n\ \ ls <- b \n\ \ return [l | ls] \n\ \ end \n\ \ foldr k (m.return []) ms \n\ \ \n\ \ m_map m action ls = \n\ \ sequence m (map action ls) \n\ \\n"
null
https://raw.githubusercontent.com/arne-schroppe/dash/82df755edc6555cba808539970ab6ff225c18b35/src/Language/Dash/BuiltIn/BuiltInDefinitions.hs
haskell
TODO prevent user from accessing these directly TODO should probably be 0 TODO instead of "special" handling for primops, we could (e.g. those with less than n opcodes, etc) index loop1: is index >= length? jmp to next next: loop2: jmp to done done: counter loop1: is index >= length? jmp to next next:
module Language.Dash.BuiltIn.BuiltInDefinitions ( builtInFunctions , builtInSymbols , bifStringConcatName , bifListConcatName , bifToStringName , bifStringConcatOperator , tupleSymbolName , recordSymbolName , listConsSymbolName , listEmptySymbolName , trueSymbolName , falseSymbolName , preamble , moduleOwner , errorSymbolName , runtimeErrorSymbolName ) where import Data.Maybe (fromJust) import Language.Dash.IR.Data import Language.Dash.IR.Opcode runtimeErrorSymbolName, errorSymbolName, nilSymbolName, tupleSymbolName, recordSymbolName, listConsSymbolName, listEmptySymbolName, trueSymbolName, falseSymbolName, numberTypeSymbolName, stringTypeSymbolName, symbolTypeSymbolName, functionTypeSymbolName :: String trueSymbolName = "true" falseSymbolName = "false" nilSymbolName = "nil" Note : If you change these names , also change them in Types.hs tupleSymbolName = "$_tuple" recordSymbolName = "$_record" listConsSymbolName = "$_list" listEmptySymbolName = "$_empty_list" numberTypeSymbolName = "number" stringTypeSymbolName = "string" symbolTypeSymbolName = "symbol" functionTypeSymbolName = "function" errorSymbolName = "error" runtimeErrorSymbolName = "runtime_error" builtInSymbols :: [(String, SymId)] builtInSymbols = map f d where f (s, i) = (s, mkSymId i) d = zip syms [0..length syms] 0 1 3 4 5 6 7 8 9 11 ] moduleOwner :: SymId moduleOwner = mkSymId 0 bifStringConcatName, bifListConcatName, bifStringLengthName, bifSubStringName, bifToStringName, bifStringConcatOperator :: String bifStringConcatName = "concatenate_strings" bifListConcatName = "concatenate" bifStringLengthName = "string_length" bifSubStringName = "sub_string" bifToStringName = "to_string" bifStringConcatOperator = "^+" also add a bif for every primop and then inline some functions type Arity = Int builtInFunctions :: [(Name, Arity, [Opcode])] builtInFunctions = [ (bifStringConcatName, 2, [ OpcStrLen 2 0, OpcStrLen 3 1, OpcAdd 4 2 3, OpcNewStr 5 4, OpcLoadI 7 1, OpcGetChar 9 0 6, OpcPutChar 9 5 6, OpcAdd 6 6 7, jmp to loop1 OpcLoadI 6 0, OpcLT 8 3 6, OpcGetChar 9 1 6, OpcAdd 10 2 6, OpcPutChar 9 5 10, OpcAdd 6 6 7, jmp to OpcMove 0 5, OpcRet 0 ]), (bifStringLengthName, 1, [ OpcStrLen 0 0, OpcRet 0 ]), TODO truncate length if needed OpcNewStr 3 1, OpcLoadI 6 1, TODO this is ugly . Fix our off - by - one error properly OpcAdd 8 7 0, OpcGetChar 5 2 8, OpcPutChar 5 3 7, OpcAdd 7 7 6, jmp to loop1 OpcMove 0 3, OpcRet 0 ]), ("<=", 2, [ OpcLT 2 0 1, OpcJmpTrue 2 1, OpcEq 2 0 1, OpcMove 0 2, OpcRet 0 ]), (">=", 2, [ OpcGT 2 0 1, OpcJmpTrue 2 1, OpcEq 2 0 1, OpcMove 0 2, OpcRet 0 ]), ("!=", 2, [ OpcEq 2 0 1, OpcNot 0 2, OpcRet 0 ]), ("to_number", 1, [ OpcLoadPS 1 (fromJust $ lookup numberTypeSymbolName builtInSymbols), OpcConvert 0 0 1, OpcRet 0 ]), (bifToStringName, 1, [ OpcLoadPS 1 (fromJust $ lookup stringTypeSymbolName builtInSymbols), OpcConvert 0 0 1, OpcRet 0 ]) ] returnActionId, readLineActionId, printLineActionId :: Int returnActionId = 0 readLineActionId = 1 printLineActionId = 2 preamble :: String preamble = "\n\ \ io = module \n\ \ bind action next = \n\ \ match action with \n\ \ :_internal_io<type, param, :nil> -> :_internal_io<type, param, next> \n\ \ :_internal_io<type, param, n0> -> :_internal_io<type, param, (x -> bind (n0 x) next)> \n\ \ _ -> :error<:" ++ runtimeErrorSymbolName ++ ", \"io-bind: Expected an io action as first argument\">\n\ \ end \n\ \ \n\ \ return a = \n\ \ :_internal_io<" ++ show returnActionId ++ ", a, :nil> \n\ \ \n\ \ read_line = \n\ \ :_internal_io<" ++ show readLineActionId ++ ", :nil, :nil> \n\ \ \n\ \ print a = \n\ \ :_internal_io<" ++ show printLineActionId ++ ", a, :nil> \n\ \ \n\ \ print_line a = \n\ \ :_internal_io<" ++ show printLineActionId ++ ", (a " ++ bifStringConcatOperator ++ " \"\\n\"), :nil> \n\ \ end \n\ \ \n\ \ head ls = \n\ \ match ls with \n\ \ [a | _] -> a \n\ \ _ -> :error<:" ++ runtimeErrorSymbolName ++ ",\"Empty list!\"> \n\ \ end \n\ \ \n\ \ tail ls = \n\ \ match ls with \n\ \ [_ | as] -> as \n\ \ _ -> [] \n\ \ end \n\ \ \n\ \ map f ls = \n\ \ match ls with \n\ \ [] -> [] \n\ \ [a | rest] -> [f a | map f rest] \n\ \ end \n\ \ \n\ \ foldr f z ls = \n\ \ match ls with \n\ \ [] -> z \n\ \ [a | rest] -> f a (foldr f z rest) \n\ \ end \n\ \ \n\ \ " ++ bifListConcatName ++ " a b = \n\ \ match a with \n\ \ [] -> b \n\ \ [hd | tl] -> [hd | " ++ bifListConcatName ++ " tl b] \n\ \ end \n\ \ \n\ \ reverse l = \n\ \ rev_list' l acc = \n\ \ match l with \n\ \ [] -> acc \n\ \ [hd | tl] -> rev_list' tl [hd | acc] \n\ \ end \n\ \ rev_list' l [] \n\ \ \n\ \ \n\ \ filter f ls = \n\ \ match ls with \n\ \ [] -> [] \n\ \ [x | xs] -> \n\ \ if f x \n\ \ then [x | filter f xs] \n\ \ else filter f xs \n\ \ end \n\ \ \n\ \ length list = \n\ \ len' l acc = \n\ \ match l with \n\ \ [] -> acc \n\ \ [_ | as] -> len' as (acc + 1) \n\ \ x -> :error<:" ++ runtimeErrorSymbolName ++ ", \"Not a list\"> \n\ \ end \n\ \ len' list 0 \n\ \ \n\ \ \n\ \ sequence m ms = \n\ \ k a b = \n\ \ do m with \n\ \ l <- a \n\ \ ls <- b \n\ \ return [l | ls] \n\ \ end \n\ \ foldr k (m.return []) ms \n\ \ \n\ \ m_map m action ls = \n\ \ sequence m (map action ls) \n\ \\n"
aa954085b9ba9ec6d44c52dddfcfa7589dbddafef21d5bb14a417d9e33413440
UCSD-PL/refscript
Lexer.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE NoMonomorphismRestriction # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TupleSections # {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} module Language.Rsc.Parser.Lexer where import Prelude hiding (mapM) import Text.Parsec hiding (State, parse) import Text.Parsec.Language (emptyDef) import Text.Parsec.Token (identLetter, identStart) import qualified Text.Parsec.Token as T jsLexer = T.makeTokenParser $ emptyDef { identStart = letter <|> oneOf "$_" , identLetter = alphaNum <|> oneOf "$_" } identifier = T.identifier jsLexer
null
https://raw.githubusercontent.com/UCSD-PL/refscript/884306fef72248ac41ecdbb928bbd7b06ca71bd4/src/Language/Rsc/Parser/Lexer.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeSynonymInstances # # LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE NoMonomorphismRestriction # # LANGUAGE TupleSections # module Language.Rsc.Parser.Lexer where import Prelude hiding (mapM) import Text.Parsec hiding (State, parse) import Text.Parsec.Language (emptyDef) import Text.Parsec.Token (identLetter, identStart) import qualified Text.Parsec.Token as T jsLexer = T.makeTokenParser $ emptyDef { identStart = letter <|> oneOf "$_" , identLetter = alphaNum <|> oneOf "$_" } identifier = T.identifier jsLexer
d54447285e2101c7b150d91dc990976538b9bee8f199a746fd12b6d46135ffc8
Bodigrim/ntru
EES677EP1.hs
| NTRU cryptographic system using the EES677EP1 parameter set , for use at the 192 - bit security level . NTRU cryptographic system using the EES677EP1 parameter set, for use at the 192-bit security level. -} module Math.NTRU.EES677EP1 (keyGen, encrypt, decrypt) where import qualified Math.NTRU as NTRU | Generates a random PublicKey - PrivateKey pair ^ A tuple representing ( PublicKey , PrivateKey ) where PrivateKey = 1 + pf , per < enahncement#2 > . keyGen = NTRU.keyGen (NTRU.genParams "EES677EP1") | Encrypts a message with the given public key encrypt :: [Integer] -- ^ A list of ASCII values representing the message -> [Integer] -- ^ A list of numbers representing the public key -> IO [Integer] -- ^ A list of numbers representing the ciphertext encrypt = NTRU.encrypt (NTRU.genParams "EES677EP1") | Decrypts and verifies a cyphertext with the given keys decrypt :: [Integer] -- ^ A list of numbers representing the private key -> [Integer] -- ^ A list of numbers representing the public key -> [Integer] -- ^ A list of numbers representing the ciphertext -> Maybe [Integer] -- ^ A list of numbers representing the original message, or nothing on failure decrypt = NTRU.decrypt (NTRU.genParams "EES677EP1")
null
https://raw.githubusercontent.com/Bodigrim/ntru/1974391559eb49ee1960db423b667867dfce946b/src/Math/NTRU/EES677EP1.hs
haskell
^ A list of ASCII values representing the message ^ A list of numbers representing the public key ^ A list of numbers representing the ciphertext ^ A list of numbers representing the private key ^ A list of numbers representing the public key ^ A list of numbers representing the ciphertext ^ A list of numbers representing the original message, or nothing on failure
| NTRU cryptographic system using the EES677EP1 parameter set , for use at the 192 - bit security level . NTRU cryptographic system using the EES677EP1 parameter set, for use at the 192-bit security level. -} module Math.NTRU.EES677EP1 (keyGen, encrypt, decrypt) where import qualified Math.NTRU as NTRU | Generates a random PublicKey - PrivateKey pair ^ A tuple representing ( PublicKey , PrivateKey ) where PrivateKey = 1 + pf , per < enahncement#2 > . keyGen = NTRU.keyGen (NTRU.genParams "EES677EP1") | Encrypts a message with the given public key encrypt = NTRU.encrypt (NTRU.genParams "EES677EP1") | Decrypts and verifies a cyphertext with the given keys decrypt = NTRU.decrypt (NTRU.genParams "EES677EP1")
fe1fb6c7cf64ad2df06b091e267227d111cd3acae58a1177a70f825749adb403
kevinlynx/ext-blog
drawer-dispatch.lisp
;;;; drawer-dispatcher.lisp ;;;; ;;;; This file is a part of ext-blog, a common lisp blog engine. ;;;; See file doc/LICENSE for license details. ;;;; Author : ( kevinlynx at gmail dot com ) (in-package #:ext-blog) (export '(render-page)) (defclass drawer-dispatcher() ()) (defgeneric render-page (blog theme route args) (:documentation "Render blog page by the blog theme")) (defun get-theme (blog data) (if blog (let ((type (getf data :type))) (case type (:admin (blog-admin-theme blog)) (:normal (blog-theme blog)) (:api nil))) ;; the blog has not been initialized, so we use a temp theme. ;; but if there's no :admin theme, it will crash. (get-default-theme :admin))) (defmethod restas:render-object ((drawer drawer-dispatcher) (data list)) (let* ((blog (getf data :blog)) (theme (get-theme blog data))) (if theme (render-page blog theme (restas:route-symbol restas:*route*) (getf data :args)) (car (getf data :args)))))
null
https://raw.githubusercontent.com/kevinlynx/ext-blog/4f6a6f0ab64f9384d53d41d1208ebaa7b9575534/src/drawer-dispatch.lisp
lisp
drawer-dispatcher.lisp This file is a part of ext-blog, a common lisp blog engine. See file doc/LICENSE for license details. the blog has not been initialized, so we use a temp theme. but if there's no :admin theme, it will crash.
Author : ( kevinlynx at gmail dot com ) (in-package #:ext-blog) (export '(render-page)) (defclass drawer-dispatcher() ()) (defgeneric render-page (blog theme route args) (:documentation "Render blog page by the blog theme")) (defun get-theme (blog data) (if blog (let ((type (getf data :type))) (case type (:admin (blog-admin-theme blog)) (:normal (blog-theme blog)) (:api nil))) (get-default-theme :admin))) (defmethod restas:render-object ((drawer drawer-dispatcher) (data list)) (let* ((blog (getf data :blog)) (theme (get-theme blog data))) (if theme (render-page blog theme (restas:route-symbol restas:*route*) (getf data :args)) (car (getf data :args)))))
36d0966700d44169e445984e7e3a6238228c3e9978630a35c6685612bc544eda
ToTal/total
version.ml
let logo = " _______________ _ \n" ^ "|__ _____ __| | |\n" ^ " | | ___ | | __ _| |\n" ^ " | |/ _ \\| |/ _` | |\n" ^ " | | (_) | | (_| | |\n" ^ " |_|\\___/|_|\\__,_|_|\n" let logo_alt = " ____________________ _ _ \n" ^ " | __ ________ __(_) | |\n" ^ " | |__) |_ _ _ __| | _ __ _| |\n" ^ " | ___/ _` | '__| | | |/ _` | |\n" ^ " | | | (_| | | | | | | (_| | |\n" ^ " |_| \\__,_|_| |_| |_|\\__,_|_|\n" let version = "0.00 transitional" ;; let print_version () = print_endline (if !Config.totality_is_tainted then logo_alt else logo); print_endline ("Version: " ^ version);
null
https://raw.githubusercontent.com/ToTal/total/fa9c677c9110afd5fb423a4fe24eafff2fd08507/version.ml
ocaml
let logo = " _______________ _ \n" ^ "|__ _____ __| | |\n" ^ " | | ___ | | __ _| |\n" ^ " | |/ _ \\| |/ _` | |\n" ^ " | | (_) | | (_| | |\n" ^ " |_|\\___/|_|\\__,_|_|\n" let logo_alt = " ____________________ _ _ \n" ^ " | __ ________ __(_) | |\n" ^ " | |__) |_ _ _ __| | _ __ _| |\n" ^ " | ___/ _` | '__| | | |/ _` | |\n" ^ " | | | (_| | | | | | | (_| | |\n" ^ " |_| \\__,_|_| |_| |_|\\__,_|_|\n" let version = "0.00 transitional" ;; let print_version () = print_endline (if !Config.totality_is_tainted then logo_alt else logo); print_endline ("Version: " ^ version);
f40adda7cca1db590ef9d413dc946ac026f0b93ddf1938e5b93682b68b306412
modular-macros/ocaml-macros
cmi_format.mli
(**************************************************************************) (* *) (* OCaml *) (* *) (* Fabrice Le Fessant, INRIA Saclay *) (* *) Copyright 2012 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) type pers_flags = | Rectypes | Deprecated of string | Opaque | Unsafe_string type cmi_infos = { cmi_name : string; cmi_sign : Types.signature_item list; cmi_crcs : (string * Digest.t option) list; cmi_flags : pers_flags list; } (* write the magic + the cmi information *) val output_cmi : string -> out_channel -> cmi_infos -> Digest.t (* read the cmi information (the magic is supposed to have already been read) *) val input_cmi : in_channel -> cmi_infos (* read a cmi from a filename, checking the magic *) val read_cmi : string -> cmi_infos (* Error report *) type error = Not_an_interface of string | Wrong_version_interface of string * string | Corrupted_interface of string exception Error of error open Format val report_error: formatter -> error -> unit
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/typing/cmi_format.mli
ocaml
************************************************************************ OCaml Fabrice Le Fessant, INRIA Saclay en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ write the magic + the cmi information read the cmi information (the magic is supposed to have already been read) read a cmi from a filename, checking the magic Error report
Copyright 2012 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the type pers_flags = | Rectypes | Deprecated of string | Opaque | Unsafe_string type cmi_infos = { cmi_name : string; cmi_sign : Types.signature_item list; cmi_crcs : (string * Digest.t option) list; cmi_flags : pers_flags list; } val output_cmi : string -> out_channel -> cmi_infos -> Digest.t val input_cmi : in_channel -> cmi_infos val read_cmi : string -> cmi_infos type error = Not_an_interface of string | Wrong_version_interface of string * string | Corrupted_interface of string exception Error of error open Format val report_error: formatter -> error -> unit
c55bd0b45dc7d86e98b23a46640e55fc7c08018a78867c7ccefef914e430cfa9
emmabastas/elm-embed
JavaScript.hs
{-# LANGUAGE OverloadedStrings #-} module Generate.JavaScript ( generate , generateForRepl , generateForReplEndpoint ) where import Prelude hiding (cycle, print) import qualified Data.ByteString.Builder as B import Data.Monoid ((<>)) import qualified Data.List as List import Data.Map ((!)) import qualified Data.Map as Map import qualified Data.Name as Name import qualified Data.Set as Set import qualified Data.Utf8 as Utf8 import qualified AST.Canonical as Can import qualified AST.Optimized as Opt import qualified Data.Index as Index import qualified Elm.Kernel as K import qualified Elm.ModuleName as ModuleName import qualified Generate.JavaScript.Builder as JS import qualified Generate.JavaScript.Expression as Expr import qualified Generate.JavaScript.Functions as Functions import qualified Generate.JavaScript.Runner as Runner import qualified Generate.JavaScript.Name as JsName import qualified Generate.Mode as Mode import qualified Reporting.Doc as D import qualified Reporting.Render.Type as RT import qualified Reporting.Render.Type.Localizer as L -- GENERATE type Graph = Map.Map Opt.Global Opt.Node type Generators = Map.Map ModuleName.Canonical [Opt.Generator] generate :: Mode.Mode -> Opt.GlobalGraph -> Generators -> B.Builder generate mode (Opt.GlobalGraph graph _) generators = let state = Map.foldrWithKey (addMain mode graph) emptyState generators in Functions.functions <> stateToBuilder state <> toGeneratorsList mode generators <> Runner.runner addMain :: Mode.Mode -> Graph -> ModuleName.Canonical -> [Opt.Generator] -> State -> State addMain mode graph home generators state = foldr (\(Opt.Generator name _ _ ) s -> addGlobal mode graph s name) state generators perfNote :: Mode.Mode -> B.Builder perfNote mode = case mode of Mode.Prod _ -> "" Mode.Dev Nothing -> "console.warn('Compiled in DEV mode. Follow the advice at " <> B.stringUtf8 (D.makeNakedLink "optimize") <> " for better performance and smaller assets.');" Mode.Dev (Just _) -> "console.warn('Compiled in DEBUG mode. Follow the advice at " <> B.stringUtf8 (D.makeNakedLink "optimize") <> " for better performance and smaller assets.');" -- GENERATE FOR REPL generateForRepl :: Bool -> L.Localizer -> Opt.GlobalGraph -> ModuleName.Canonical -> Name.Name -> Can.Annotation -> B.Builder generateForRepl ansi localizer (Opt.GlobalGraph graph _) home name (Can.Forall _ tipe) = let mode = Mode.Dev Nothing debugState = addGlobal mode graph emptyState (Opt.Global ModuleName.debug "toString") evalState = addGlobal mode graph debugState (Opt.Global home name) in "process.on('uncaughtException', function(err) { process.stderr.write(err.toString() + '\\n'); process.exit(1); });" <> Functions.functions <> stateToBuilder evalState <> print ansi localizer home name tipe print :: Bool -> L.Localizer -> ModuleName.Canonical -> Name.Name -> Can.Type -> B.Builder print ansi localizer home name tipe = let value = JsName.toBuilder (JsName.fromGlobal home name) toString = JsName.toBuilder (JsName.fromKernel Name.debug "toAnsiString") tipeDoc = RT.canToDoc localizer RT.None tipe bool = if ansi then "true" else "false" in "var _value = " <> toString <> "(" <> bool <> ", " <> value <> ");\n\ \var _type = " <> B.stringUtf8 (show (D.toString tipeDoc)) <> ";\n\ \function _print(t) { console.log(_value + (" <> bool <> " ? '\x1b[90m' + t + '\x1b[0m' : t)); }\n\ \if (_value.length + 3 + _type.length >= 80 || _type.indexOf('\\n') >= 0) {\n\ \ _print('\\n : ' + _type.split('\\n').join('\\n '));\n\ \} else {\n\ \ _print(' : ' + _type);\n\ \}\n" -- GENERATE FOR REPL ENDPOINT generateForReplEndpoint :: L.Localizer -> Opt.GlobalGraph -> ModuleName.Canonical -> Maybe Name.Name -> Can.Annotation -> B.Builder generateForReplEndpoint localizer (Opt.GlobalGraph graph _) home maybeName (Can.Forall _ tipe) = let name = maybe Name.replValueToPrint id maybeName mode = Mode.Dev Nothing debugState = addGlobal mode graph emptyState (Opt.Global ModuleName.debug "toString") evalState = addGlobal mode graph debugState (Opt.Global home name) in Functions.functions <> stateToBuilder evalState <> postMessage localizer home maybeName tipe postMessage :: L.Localizer -> ModuleName.Canonical -> Maybe Name.Name -> Can.Type -> B.Builder postMessage localizer home maybeName tipe = let name = maybe Name.replValueToPrint id maybeName value = JsName.toBuilder (JsName.fromGlobal home name) toString = JsName.toBuilder (JsName.fromKernel Name.debug "toAnsiString") tipeDoc = RT.canToDoc localizer RT.None tipe toName n = "\"" <> Name.toBuilder n <> "\"" in "self.postMessage({\n\ \ name: " <> maybe "null" toName maybeName <> ",\n\ \ value: " <> toString <> "(true, " <> value <> "),\n\ \ type: " <> B.stringUtf8 (show (D.toString tipeDoc)) <> "\n\ \});\n" GRAPH TRAVERSAL STATE data State = State { _revKernels :: [B.Builder] , _revBuilders :: [B.Builder] , _seenGlobals :: Set.Set Opt.Global } emptyState :: State emptyState = State mempty [] Set.empty stateToBuilder :: State -> B.Builder stateToBuilder (State revKernels revBuilders _) = prependBuilders revKernels (prependBuilders revBuilders mempty) prependBuilders :: [B.Builder] -> B.Builder -> B.Builder prependBuilders revBuilders monolith = List.foldl' (\m b -> b <> m) monolith revBuilders -- ADD DEPENDENCIES addGlobal :: Mode.Mode -> Graph -> State -> Opt.Global -> State addGlobal mode graph state@(State revKernels builders seen) global = if Set.member global seen then state else addGlobalHelp mode graph global $ State revKernels builders (Set.insert global seen) addGlobalHelp :: Mode.Mode -> Graph -> Opt.Global -> State -> State addGlobalHelp mode graph global state = let addDeps deps someState = Set.foldl' (addGlobal mode graph) someState deps in case graph ! global of Opt.Define expr deps -> addStmt (addDeps deps state) ( var global (Expr.generate mode expr) ) Opt.DefineTailFunc argNames body deps -> addStmt (addDeps deps state) ( let (Opt.Global _ name) = global in var global (Expr.generateTailDef mode name argNames body) ) Opt.Ctor index arity -> addStmt state ( var global (Expr.generateCtor mode global index arity) ) Opt.Link linkedGlobal -> addGlobal mode graph state linkedGlobal Opt.Cycle names values functions deps -> addStmt (addDeps deps state) ( generateCycle mode global names values functions ) Opt.Manager effectsType -> generateManager mode graph global effectsType state Opt.Kernel chunks deps -> if isDebugger global && not (Mode.isDebug mode) then state else addKernel (addDeps deps state) (generateKernel mode chunks) Opt.Enum index -> addStmt state ( generateEnum mode global index ) Opt.Box -> addStmt (addGlobal mode graph state identity) ( generateBox mode global ) Opt.PortIncoming decoder deps -> addStmt (addDeps deps state) ( generatePort mode global "incomingPort" decoder ) Opt.PortOutgoing encoder deps -> addStmt (addDeps deps state) ( generatePort mode global "outgoingPort" encoder ) addStmt :: State -> JS.Stmt -> State addStmt state stmt = addBuilder state (JS.stmtToBuilder stmt) addBuilder :: State -> B.Builder -> State addBuilder (State revKernels revBuilders seen) builder = State revKernels (builder:revBuilders) seen addKernel :: State -> B.Builder -> State addKernel (State revKernels revBuilders seen) kernel = State (kernel:revKernels) revBuilders seen var :: Opt.Global -> Expr.Code -> JS.Stmt var (Opt.Global home name) code = JS.Var (JsName.fromGlobal home name) (Expr.codeToExpr code) isDebugger :: Opt.Global -> Bool isDebugger (Opt.Global (ModuleName.Canonical _ home) _) = home == Name.debugger -- GENERATE CYCLES generateCycle :: Mode.Mode -> Opt.Global -> [Name.Name] -> [(Name.Name, Opt.Expr)] -> [Opt.Def] -> JS.Stmt generateCycle mode (Opt.Global home _) names values functions = JS.Block [ JS.Block $ map (generateCycleFunc mode home) functions , JS.Block $ map (generateSafeCycle mode home) values , case map (generateRealCycle home) values of [] -> JS.EmptyStmt realBlock@(_:_) -> case mode of Mode.Prod _ -> JS.Block realBlock Mode.Dev _ -> JS.Try (JS.Block realBlock) JsName.dollar $ JS.Throw $ JS.String $ "Some top-level definitions from `" <> Name.toBuilder (ModuleName._module home) <> "` are causing infinite recursion:\\n" <> drawCycle names <> "\\n\\nThese errors are very tricky, so read " <> B.stringUtf8 (D.makeNakedLink "bad-recursion") <> " to learn how to fix it!" ] generateCycleFunc :: Mode.Mode -> ModuleName.Canonical -> Opt.Def -> JS.Stmt generateCycleFunc mode home def = case def of Opt.Def name expr -> JS.Var (JsName.fromGlobal home name) (Expr.codeToExpr (Expr.generate mode expr)) Opt.TailDef name args expr -> JS.Var (JsName.fromGlobal home name) (Expr.codeToExpr (Expr.generateTailDef mode name args expr)) generateSafeCycle :: Mode.Mode -> ModuleName.Canonical -> (Name.Name, Opt.Expr) -> JS.Stmt generateSafeCycle mode home (name, expr) = JS.FunctionStmt (JsName.fromCycle home name) [] $ Expr.codeToStmtList (Expr.generate mode expr) generateRealCycle :: ModuleName.Canonical -> (Name.Name, expr) -> JS.Stmt generateRealCycle home (name, _) = let safeName = JsName.fromCycle home name realName = JsName.fromGlobal home name in JS.Block [ JS.Var realName (JS.Call (JS.Ref safeName) []) , JS.ExprStmt $ JS.Assign (JS.LRef safeName) $ JS.Function Nothing [] [ JS.Return (JS.Ref realName) ] ] drawCycle :: [Name.Name] -> B.Builder drawCycle names = let topLine = "\\n ┌─────┐" nameLine name = "\\n │ " <> Name.toBuilder name midLine = "\\n │ ↓" bottomLine = "\\n └─────┘" in mconcat (topLine : List.intersperse midLine (map nameLine names) ++ [ bottomLine ]) -- GENERATE KERNEL generateKernel :: Mode.Mode -> [K.Chunk] -> B.Builder generateKernel mode chunks = List.foldr (addChunk mode) mempty chunks addChunk :: Mode.Mode -> K.Chunk -> B.Builder -> B.Builder addChunk mode chunk builder = case chunk of K.JS javascript -> B.byteString javascript <> builder K.ElmVar home name -> JsName.toBuilder (JsName.fromGlobal home name) <> builder K.JsVar home name -> JsName.toBuilder (JsName.fromKernel home name) <> builder K.ElmField name -> JsName.toBuilder (Expr.generateField mode name) <> builder K.JsField int -> JsName.toBuilder (JsName.fromInt int) <> builder K.JsEnum int -> B.intDec int <> builder K.Debug -> case mode of Mode.Dev _ -> builder Mode.Prod _ -> "_UNUSED" <> builder K.Prod -> case mode of Mode.Dev _ -> "_UNUSED" <> builder Mode.Prod _ -> builder -- GENERATE ENUM generateEnum :: Mode.Mode -> Opt.Global -> Index.ZeroBased -> JS.Stmt generateEnum mode global@(Opt.Global home name) index = JS.Var (JsName.fromGlobal home name) $ case mode of Mode.Dev _ -> Expr.codeToExpr (Expr.generateCtor mode global index 0) Mode.Prod _ -> JS.Int (Index.toMachine index) -- GENERATE BOX generateBox :: Mode.Mode -> Opt.Global -> JS.Stmt generateBox mode global@(Opt.Global home name) = JS.Var (JsName.fromGlobal home name) $ case mode of Mode.Dev _ -> Expr.codeToExpr (Expr.generateCtor mode global Index.first 1) Mode.Prod _ -> JS.Ref (JsName.fromGlobal ModuleName.basics Name.identity) # NOINLINE identity # identity :: Opt.Global identity = Opt.Global ModuleName.basics Name.identity -- GENERATE PORTS generatePort :: Mode.Mode -> Opt.Global -> Name.Name -> Opt.Expr -> JS.Stmt generatePort mode (Opt.Global home name) makePort converter = JS.Var (JsName.fromGlobal home name) $ JS.Call (JS.Ref (JsName.fromKernel Name.platform makePort)) [ JS.String (Name.toBuilder name) , Expr.codeToExpr (Expr.generate mode converter) ] -- GENERATE MANAGER generateManager :: Mode.Mode -> Graph -> Opt.Global -> Opt.EffectsType -> State -> State generateManager mode graph (Opt.Global home@(ModuleName.Canonical _ moduleName) _) effectsType state = let managerLVar = JS.LBracket (JS.Ref (JsName.fromKernel Name.platform "effectManagers")) (JS.String (Name.toBuilder moduleName)) (deps, args, stmts) = generateManagerHelp home effectsType createManager = JS.ExprStmt $ JS.Assign managerLVar $ JS.Call (JS.Ref (JsName.fromKernel Name.platform "createManager")) args in addStmt (List.foldl' (addGlobal mode graph) state deps) $ JS.Block (createManager : stmts) generateLeaf :: ModuleName.Canonical -> Name.Name -> JS.Stmt generateLeaf home@(ModuleName.Canonical _ moduleName) name = JS.Var (JsName.fromGlobal home name) $ JS.Call leaf [ JS.String (Name.toBuilder moduleName) ] # NOINLINE leaf # leaf :: JS.Expr leaf = JS.Ref (JsName.fromKernel Name.platform "leaf") generateManagerHelp :: ModuleName.Canonical -> Opt.EffectsType -> ([Opt.Global], [JS.Expr], [JS.Stmt]) generateManagerHelp home effectsType = let dep name = Opt.Global home name ref name = JS.Ref (JsName.fromGlobal home name) in case effectsType of Opt.Cmd -> ( [ dep "init", dep "onEffects", dep "onSelfMsg", dep "cmdMap" ] , [ ref "init", ref "onEffects", ref "onSelfMsg", ref "cmdMap" ] , [ generateLeaf home "command" ] ) Opt.Sub -> ( [ dep "init", dep "onEffects", dep "onSelfMsg", dep "subMap" ] , [ ref "init", ref "onEffects", ref "onSelfMsg", JS.Int 0, ref "subMap" ] , [ generateLeaf home "subscription" ] ) Opt.Fx -> ( [ dep "init", dep "onEffects", dep "onSelfMsg", dep "cmdMap", dep "subMap" ] , [ ref "init", ref "onEffects", ref "onSelfMsg", ref "cmdMap", ref "subMap" ] , [ generateLeaf home "command" , generateLeaf home "subscription" ] ) -- MAIN EXPORTS toGeneratorsList :: Mode.Mode -> Generators -> B.Builder toGeneratorsList mode generators = let generatorsExpr = JS.Object $ map (\((ModuleName.Canonical _ mn), generators) -> ( JsName.fromLocal mn , JS.Object $ map (\(Opt.Generator (Opt.Global mn name) _ _) -> ( JsName.fromLocal name , JS.Ref $ JsName.fromGlobal mn name ) ) generators ) ) (Map.toList generators) in "var generators = " <> JS.exprToBuilder generatorsExpr <> ";"
null
https://raw.githubusercontent.com/emmabastas/elm-embed/c2c4f9dcc5c4f47480f728247ff7b4d0700d7476/compiler/src/Generate/JavaScript.hs
haskell
# LANGUAGE OverloadedStrings # GENERATE GENERATE FOR REPL GENERATE FOR REPL ENDPOINT ADD DEPENDENCIES GENERATE CYCLES GENERATE KERNEL GENERATE ENUM GENERATE BOX GENERATE PORTS GENERATE MANAGER MAIN EXPORTS
module Generate.JavaScript ( generate , generateForRepl , generateForReplEndpoint ) where import Prelude hiding (cycle, print) import qualified Data.ByteString.Builder as B import Data.Monoid ((<>)) import qualified Data.List as List import Data.Map ((!)) import qualified Data.Map as Map import qualified Data.Name as Name import qualified Data.Set as Set import qualified Data.Utf8 as Utf8 import qualified AST.Canonical as Can import qualified AST.Optimized as Opt import qualified Data.Index as Index import qualified Elm.Kernel as K import qualified Elm.ModuleName as ModuleName import qualified Generate.JavaScript.Builder as JS import qualified Generate.JavaScript.Expression as Expr import qualified Generate.JavaScript.Functions as Functions import qualified Generate.JavaScript.Runner as Runner import qualified Generate.JavaScript.Name as JsName import qualified Generate.Mode as Mode import qualified Reporting.Doc as D import qualified Reporting.Render.Type as RT import qualified Reporting.Render.Type.Localizer as L type Graph = Map.Map Opt.Global Opt.Node type Generators = Map.Map ModuleName.Canonical [Opt.Generator] generate :: Mode.Mode -> Opt.GlobalGraph -> Generators -> B.Builder generate mode (Opt.GlobalGraph graph _) generators = let state = Map.foldrWithKey (addMain mode graph) emptyState generators in Functions.functions <> stateToBuilder state <> toGeneratorsList mode generators <> Runner.runner addMain :: Mode.Mode -> Graph -> ModuleName.Canonical -> [Opt.Generator] -> State -> State addMain mode graph home generators state = foldr (\(Opt.Generator name _ _ ) s -> addGlobal mode graph s name) state generators perfNote :: Mode.Mode -> B.Builder perfNote mode = case mode of Mode.Prod _ -> "" Mode.Dev Nothing -> "console.warn('Compiled in DEV mode. Follow the advice at " <> B.stringUtf8 (D.makeNakedLink "optimize") <> " for better performance and smaller assets.');" Mode.Dev (Just _) -> "console.warn('Compiled in DEBUG mode. Follow the advice at " <> B.stringUtf8 (D.makeNakedLink "optimize") <> " for better performance and smaller assets.');" generateForRepl :: Bool -> L.Localizer -> Opt.GlobalGraph -> ModuleName.Canonical -> Name.Name -> Can.Annotation -> B.Builder generateForRepl ansi localizer (Opt.GlobalGraph graph _) home name (Can.Forall _ tipe) = let mode = Mode.Dev Nothing debugState = addGlobal mode graph emptyState (Opt.Global ModuleName.debug "toString") evalState = addGlobal mode graph debugState (Opt.Global home name) in "process.on('uncaughtException', function(err) { process.stderr.write(err.toString() + '\\n'); process.exit(1); });" <> Functions.functions <> stateToBuilder evalState <> print ansi localizer home name tipe print :: Bool -> L.Localizer -> ModuleName.Canonical -> Name.Name -> Can.Type -> B.Builder print ansi localizer home name tipe = let value = JsName.toBuilder (JsName.fromGlobal home name) toString = JsName.toBuilder (JsName.fromKernel Name.debug "toAnsiString") tipeDoc = RT.canToDoc localizer RT.None tipe bool = if ansi then "true" else "false" in "var _value = " <> toString <> "(" <> bool <> ", " <> value <> ");\n\ \var _type = " <> B.stringUtf8 (show (D.toString tipeDoc)) <> ";\n\ \function _print(t) { console.log(_value + (" <> bool <> " ? '\x1b[90m' + t + '\x1b[0m' : t)); }\n\ \if (_value.length + 3 + _type.length >= 80 || _type.indexOf('\\n') >= 0) {\n\ \ _print('\\n : ' + _type.split('\\n').join('\\n '));\n\ \} else {\n\ \ _print(' : ' + _type);\n\ \}\n" generateForReplEndpoint :: L.Localizer -> Opt.GlobalGraph -> ModuleName.Canonical -> Maybe Name.Name -> Can.Annotation -> B.Builder generateForReplEndpoint localizer (Opt.GlobalGraph graph _) home maybeName (Can.Forall _ tipe) = let name = maybe Name.replValueToPrint id maybeName mode = Mode.Dev Nothing debugState = addGlobal mode graph emptyState (Opt.Global ModuleName.debug "toString") evalState = addGlobal mode graph debugState (Opt.Global home name) in Functions.functions <> stateToBuilder evalState <> postMessage localizer home maybeName tipe postMessage :: L.Localizer -> ModuleName.Canonical -> Maybe Name.Name -> Can.Type -> B.Builder postMessage localizer home maybeName tipe = let name = maybe Name.replValueToPrint id maybeName value = JsName.toBuilder (JsName.fromGlobal home name) toString = JsName.toBuilder (JsName.fromKernel Name.debug "toAnsiString") tipeDoc = RT.canToDoc localizer RT.None tipe toName n = "\"" <> Name.toBuilder n <> "\"" in "self.postMessage({\n\ \ name: " <> maybe "null" toName maybeName <> ",\n\ \ value: " <> toString <> "(true, " <> value <> "),\n\ \ type: " <> B.stringUtf8 (show (D.toString tipeDoc)) <> "\n\ \});\n" GRAPH TRAVERSAL STATE data State = State { _revKernels :: [B.Builder] , _revBuilders :: [B.Builder] , _seenGlobals :: Set.Set Opt.Global } emptyState :: State emptyState = State mempty [] Set.empty stateToBuilder :: State -> B.Builder stateToBuilder (State revKernels revBuilders _) = prependBuilders revKernels (prependBuilders revBuilders mempty) prependBuilders :: [B.Builder] -> B.Builder -> B.Builder prependBuilders revBuilders monolith = List.foldl' (\m b -> b <> m) monolith revBuilders addGlobal :: Mode.Mode -> Graph -> State -> Opt.Global -> State addGlobal mode graph state@(State revKernels builders seen) global = if Set.member global seen then state else addGlobalHelp mode graph global $ State revKernels builders (Set.insert global seen) addGlobalHelp :: Mode.Mode -> Graph -> Opt.Global -> State -> State addGlobalHelp mode graph global state = let addDeps deps someState = Set.foldl' (addGlobal mode graph) someState deps in case graph ! global of Opt.Define expr deps -> addStmt (addDeps deps state) ( var global (Expr.generate mode expr) ) Opt.DefineTailFunc argNames body deps -> addStmt (addDeps deps state) ( let (Opt.Global _ name) = global in var global (Expr.generateTailDef mode name argNames body) ) Opt.Ctor index arity -> addStmt state ( var global (Expr.generateCtor mode global index arity) ) Opt.Link linkedGlobal -> addGlobal mode graph state linkedGlobal Opt.Cycle names values functions deps -> addStmt (addDeps deps state) ( generateCycle mode global names values functions ) Opt.Manager effectsType -> generateManager mode graph global effectsType state Opt.Kernel chunks deps -> if isDebugger global && not (Mode.isDebug mode) then state else addKernel (addDeps deps state) (generateKernel mode chunks) Opt.Enum index -> addStmt state ( generateEnum mode global index ) Opt.Box -> addStmt (addGlobal mode graph state identity) ( generateBox mode global ) Opt.PortIncoming decoder deps -> addStmt (addDeps deps state) ( generatePort mode global "incomingPort" decoder ) Opt.PortOutgoing encoder deps -> addStmt (addDeps deps state) ( generatePort mode global "outgoingPort" encoder ) addStmt :: State -> JS.Stmt -> State addStmt state stmt = addBuilder state (JS.stmtToBuilder stmt) addBuilder :: State -> B.Builder -> State addBuilder (State revKernels revBuilders seen) builder = State revKernels (builder:revBuilders) seen addKernel :: State -> B.Builder -> State addKernel (State revKernels revBuilders seen) kernel = State (kernel:revKernels) revBuilders seen var :: Opt.Global -> Expr.Code -> JS.Stmt var (Opt.Global home name) code = JS.Var (JsName.fromGlobal home name) (Expr.codeToExpr code) isDebugger :: Opt.Global -> Bool isDebugger (Opt.Global (ModuleName.Canonical _ home) _) = home == Name.debugger generateCycle :: Mode.Mode -> Opt.Global -> [Name.Name] -> [(Name.Name, Opt.Expr)] -> [Opt.Def] -> JS.Stmt generateCycle mode (Opt.Global home _) names values functions = JS.Block [ JS.Block $ map (generateCycleFunc mode home) functions , JS.Block $ map (generateSafeCycle mode home) values , case map (generateRealCycle home) values of [] -> JS.EmptyStmt realBlock@(_:_) -> case mode of Mode.Prod _ -> JS.Block realBlock Mode.Dev _ -> JS.Try (JS.Block realBlock) JsName.dollar $ JS.Throw $ JS.String $ "Some top-level definitions from `" <> Name.toBuilder (ModuleName._module home) <> "` are causing infinite recursion:\\n" <> drawCycle names <> "\\n\\nThese errors are very tricky, so read " <> B.stringUtf8 (D.makeNakedLink "bad-recursion") <> " to learn how to fix it!" ] generateCycleFunc :: Mode.Mode -> ModuleName.Canonical -> Opt.Def -> JS.Stmt generateCycleFunc mode home def = case def of Opt.Def name expr -> JS.Var (JsName.fromGlobal home name) (Expr.codeToExpr (Expr.generate mode expr)) Opt.TailDef name args expr -> JS.Var (JsName.fromGlobal home name) (Expr.codeToExpr (Expr.generateTailDef mode name args expr)) generateSafeCycle :: Mode.Mode -> ModuleName.Canonical -> (Name.Name, Opt.Expr) -> JS.Stmt generateSafeCycle mode home (name, expr) = JS.FunctionStmt (JsName.fromCycle home name) [] $ Expr.codeToStmtList (Expr.generate mode expr) generateRealCycle :: ModuleName.Canonical -> (Name.Name, expr) -> JS.Stmt generateRealCycle home (name, _) = let safeName = JsName.fromCycle home name realName = JsName.fromGlobal home name in JS.Block [ JS.Var realName (JS.Call (JS.Ref safeName) []) , JS.ExprStmt $ JS.Assign (JS.LRef safeName) $ JS.Function Nothing [] [ JS.Return (JS.Ref realName) ] ] drawCycle :: [Name.Name] -> B.Builder drawCycle names = let topLine = "\\n ┌─────┐" nameLine name = "\\n │ " <> Name.toBuilder name midLine = "\\n │ ↓" bottomLine = "\\n └─────┘" in mconcat (topLine : List.intersperse midLine (map nameLine names) ++ [ bottomLine ]) generateKernel :: Mode.Mode -> [K.Chunk] -> B.Builder generateKernel mode chunks = List.foldr (addChunk mode) mempty chunks addChunk :: Mode.Mode -> K.Chunk -> B.Builder -> B.Builder addChunk mode chunk builder = case chunk of K.JS javascript -> B.byteString javascript <> builder K.ElmVar home name -> JsName.toBuilder (JsName.fromGlobal home name) <> builder K.JsVar home name -> JsName.toBuilder (JsName.fromKernel home name) <> builder K.ElmField name -> JsName.toBuilder (Expr.generateField mode name) <> builder K.JsField int -> JsName.toBuilder (JsName.fromInt int) <> builder K.JsEnum int -> B.intDec int <> builder K.Debug -> case mode of Mode.Dev _ -> builder Mode.Prod _ -> "_UNUSED" <> builder K.Prod -> case mode of Mode.Dev _ -> "_UNUSED" <> builder Mode.Prod _ -> builder generateEnum :: Mode.Mode -> Opt.Global -> Index.ZeroBased -> JS.Stmt generateEnum mode global@(Opt.Global home name) index = JS.Var (JsName.fromGlobal home name) $ case mode of Mode.Dev _ -> Expr.codeToExpr (Expr.generateCtor mode global index 0) Mode.Prod _ -> JS.Int (Index.toMachine index) generateBox :: Mode.Mode -> Opt.Global -> JS.Stmt generateBox mode global@(Opt.Global home name) = JS.Var (JsName.fromGlobal home name) $ case mode of Mode.Dev _ -> Expr.codeToExpr (Expr.generateCtor mode global Index.first 1) Mode.Prod _ -> JS.Ref (JsName.fromGlobal ModuleName.basics Name.identity) # NOINLINE identity # identity :: Opt.Global identity = Opt.Global ModuleName.basics Name.identity generatePort :: Mode.Mode -> Opt.Global -> Name.Name -> Opt.Expr -> JS.Stmt generatePort mode (Opt.Global home name) makePort converter = JS.Var (JsName.fromGlobal home name) $ JS.Call (JS.Ref (JsName.fromKernel Name.platform makePort)) [ JS.String (Name.toBuilder name) , Expr.codeToExpr (Expr.generate mode converter) ] generateManager :: Mode.Mode -> Graph -> Opt.Global -> Opt.EffectsType -> State -> State generateManager mode graph (Opt.Global home@(ModuleName.Canonical _ moduleName) _) effectsType state = let managerLVar = JS.LBracket (JS.Ref (JsName.fromKernel Name.platform "effectManagers")) (JS.String (Name.toBuilder moduleName)) (deps, args, stmts) = generateManagerHelp home effectsType createManager = JS.ExprStmt $ JS.Assign managerLVar $ JS.Call (JS.Ref (JsName.fromKernel Name.platform "createManager")) args in addStmt (List.foldl' (addGlobal mode graph) state deps) $ JS.Block (createManager : stmts) generateLeaf :: ModuleName.Canonical -> Name.Name -> JS.Stmt generateLeaf home@(ModuleName.Canonical _ moduleName) name = JS.Var (JsName.fromGlobal home name) $ JS.Call leaf [ JS.String (Name.toBuilder moduleName) ] # NOINLINE leaf # leaf :: JS.Expr leaf = JS.Ref (JsName.fromKernel Name.platform "leaf") generateManagerHelp :: ModuleName.Canonical -> Opt.EffectsType -> ([Opt.Global], [JS.Expr], [JS.Stmt]) generateManagerHelp home effectsType = let dep name = Opt.Global home name ref name = JS.Ref (JsName.fromGlobal home name) in case effectsType of Opt.Cmd -> ( [ dep "init", dep "onEffects", dep "onSelfMsg", dep "cmdMap" ] , [ ref "init", ref "onEffects", ref "onSelfMsg", ref "cmdMap" ] , [ generateLeaf home "command" ] ) Opt.Sub -> ( [ dep "init", dep "onEffects", dep "onSelfMsg", dep "subMap" ] , [ ref "init", ref "onEffects", ref "onSelfMsg", JS.Int 0, ref "subMap" ] , [ generateLeaf home "subscription" ] ) Opt.Fx -> ( [ dep "init", dep "onEffects", dep "onSelfMsg", dep "cmdMap", dep "subMap" ] , [ ref "init", ref "onEffects", ref "onSelfMsg", ref "cmdMap", ref "subMap" ] , [ generateLeaf home "command" , generateLeaf home "subscription" ] ) toGeneratorsList :: Mode.Mode -> Generators -> B.Builder toGeneratorsList mode generators = let generatorsExpr = JS.Object $ map (\((ModuleName.Canonical _ mn), generators) -> ( JsName.fromLocal mn , JS.Object $ map (\(Opt.Generator (Opt.Global mn name) _ _) -> ( JsName.fromLocal name , JS.Ref $ JsName.fromGlobal mn name ) ) generators ) ) (Map.toList generators) in "var generators = " <> JS.exprToBuilder generatorsExpr <> ";"
f21fb171a161cf18345fbbbbd63fb19df71e29bb2e16fe515f4256da23d44ec9
rescript-association/reanalyze
Noalloc.ml
let processCallee ~env ~funDef ~loc callee = match callee with | CL.Path.Pident id -> ( let id = CL.Ident.name id in match env |> Il.Env.find ~id with | Some (FunDef funDefCallee) -> funDef |> Il.FunDef.emit ~instr:(Il.Call funDefCallee.id) | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Callee not recognized: %s" id); assert false) | _ -> ( match callee |> CL.Path.name with | "Pervasives.+" | "Stdlib.+" -> funDef |> Il.FunDef.emit ~instr:Il.I32Add | "Pervasives.+." | "Stdlib.+." -> funDef |> Il.FunDef.emit ~instr:Il.F64Add | "Pervasives.*." | "Stdlib.*." -> funDef |> Il.FunDef.emit ~instr:Il.F64Mul | name -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Callee not recognized: %s" name); assert false) let rec processTyp ~(funDef : Il.funDef) ~loc (typ : CL.Types.type_expr) = match Compat.get_desc typ with | Ttuple ts -> let scopes = ts |> List.map (processTyp ~funDef ~loc) in Il.Tuple scopes | Tlink t -> t |> processTyp ~funDef ~loc | Tsubst _ -> Compat.getTSubst (Compat.get_desc typ) |> processTyp ~funDef ~loc | Tconstr _ | Tvar _ -> let offset = funDef.nextOffset in funDef.nextOffset <- offset + 1; Il.Local offset | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Type not supported"); assert false let rec sizeOfTyp ~loc (typ : CL.Types.type_expr) = match Compat.get_desc typ with | Tlink t -> t |> sizeOfTyp ~loc | Tsubst _ -> Compat.getTSubst (Compat.get_desc typ) |> sizeOfTyp ~loc | Tconstr (Pident id, [], _) -> ( match CL.Ident.name id with | "int" -> 4 | "string" -> 4 | name -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Size of type %s not supported" name); assert false) | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Size of type not supported"); assert false let rec emitLocalSetBackwards ~(funDef : Il.funDef) ~(scope : Il.scope) = match scope with | Tuple scopes -> List.rev scopes |> List.iter (fun s -> emitLocalSetBackwards ~funDef ~scope:s) | Local offset -> let instr = Il.LocalSet offset in funDef |> Il.FunDef.emit ~instr let rec processFunDefPat ~funDef ~env ~mem (pat : CL.Typedtree.pattern) = match pat.pat_desc with | Tpat_var (id, _) | Tpat_alias ({pat_desc = Tpat_any}, id, _) -> let scope = pat.pat_type |> processTyp ~funDef ~loc:pat.pat_loc in let newEnv = env |> Il.Env.add ~id:(id |> CL.Ident.name) ~def:(LocalScope scope) in (newEnv, scope) | Tpat_construct _ when Compat.unboxPatCstrTxt pat.pat_desc = CL.Longident.Lident "()" -> (env, Il.Tuple []) | Tpat_tuple pats -> let newEnv, scopes = pats |> List.fold_left (fun (e, scopes) p -> let newEnv, scope = p |> processFunDefPat ~funDef ~env:e ~mem in (newEnv, scope :: scopes)) (env, []) in (newEnv, Il.Tuple scopes) | _ -> Log_.warning ~count:false ~loc:pat.pat_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Argument pattern not supported"); assert false let rec processFunDef ~funDef ~env ~mem ~params (expr : CL.Typedtree.expression) = match expr.exp_desc with | Texp_function { arg_label = Nolabel; param; cases = [{c_lhs; c_guard = None; c_rhs}]; partial = Total; } -> let newEnv, typ = c_lhs |> processFunDefPat ~funDef ~env ~mem in c_rhs |> processFunDef ~funDef ~env:newEnv ~mem ~params:((param, typ) :: params) | _ -> funDef.numParams <- funDef.nextOffset; (env, expr, params) let translateConst ~loc ~mem (const : CL.Asttypes.constant) = match const with | Const_int n -> Il.I32 (n |> Int32.of_int) | Const_float s -> let sWithDecimal = match (s.[String.length s - 1] [@doesNotRaise]) = '.' with | true -> s ^ "0" | false -> s in Il.F64 sWithDecimal | Const_string _ -> let index = mem |> Il.Mem.allocString ~string:(const |> Compat.getConstString) in Il.I32 (index |> Int32.of_int) | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Constant not supported"); assert false let processConst ~funDef ~loc ~mem (const_ : CL.Asttypes.constant) = let const = const_ |> translateConst ~loc ~mem in funDef |> Il.FunDef.emit ~instr:(Il.Const const) let rec processLocalBinding ~env ~(pat : CL.Typedtree.pattern) ~(scope : Il.scope) = match (pat.pat_desc, scope) with | Tpat_var (id, _), _ -> env |> Il.Env.add ~id:(id |> CL.Ident.name) ~def:(LocalScope scope) | Tpat_tuple pats, Tuple scopes -> let patsAndScopes = (List.combine pats scopes [@doesNotRaise]) in patsAndScopes |> List.fold_left (fun e (p, s) -> processLocalBinding ~env:e ~pat:p ~scope:s) env | Tpat_any, _ -> env | _ -> assert false and processExpr ~funDef ~env ~mem (expr : CL.Typedtree.expression) = match expr.exp_desc with | Texp_constant const -> const |> processConst ~funDef ~loc:expr.exp_loc ~mem | Texp_ident (id, _, _) -> ( let id = CL.Path.name id in let rec emitScope (scope : Il.scope) = match scope with | Local offset -> funDef |> Il.FunDef.emit ~instr:(Il.LocalGet offset) | Tuple scopes -> scopes |> List.iter emitScope in match env |> Il.Env.find ~id with | Some (LocalScope scope) -> emitScope scope | Some (GlobalDef {init}) -> let rec emitInit (init : Il.Init.t) = match init with | Const const -> funDef |> Il.FunDef.emit ~instr:(Il.Const const) | Tuple is -> is |> List.iter emitInit in emitInit init | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Id not found: %s" id); assert false) | Texp_apply ({exp_desc = Texp_ident (callee, _, vd); exp_loc = callee_loc}, args) -> let kind = vd.val_type |> Il.Kind.fromType in args |> List.iteri (fun i ((argLabel : CL.Asttypes.arg_label), argOpt) -> match (argLabel, argOpt) with | Nolabel, Some (arg : CL.Typedtree.expression) -> (match kind with | Arrow (declKinds, _) -> let declKind = (declKinds.(i) [@doesNotRaise]) in let argKind = arg.exp_type |> Il.Kind.fromType in if argKind <> declKind then Log_.warning ~count:true ~loc:arg.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Function call to @{<info>%s@}: parameter %d has kind \ @{<info>%s@} but the supplied argument has kind \ @{<info>%s@}" (callee |> CL.Path.name) i (declKind |> Il.Kind.toString) (argKind |> Il.Kind.toString)) | _ -> assert false); arg |> processExpr ~funDef ~env ~mem | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Argument not supported")); callee |> processCallee ~env ~funDef ~loc:callee_loc | Texp_function _ -> let env, body, params = expr |> processFunDef ~funDef ~env ~mem ~params:[] in if params = [] then ( Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Cannot decode function parameters"); assert false); body |> processExpr ~funDef ~env ~mem | Texp_tuple l -> l |> List.iter (processExpr ~funDef ~env ~mem) | Texp_let (Nonrecursive, [vb], inExpr) -> let scope = vb.vb_expr.exp_type |> processTyp ~funDef ~loc:vb.vb_expr.exp_loc in vb.vb_expr |> processExpr ~funDef ~env ~mem; emitLocalSetBackwards ~funDef ~scope; let newEnv = processLocalBinding ~env ~pat:vb.vb_pat ~scope in inExpr |> processExpr ~funDef ~env:newEnv ~mem | Texp_record {fields; extended_expression = None} -> let firstIndex = ref 0 in fields |> Array.iteri (fun i (_ld, (rld : CL.Typedtree.record_label_definition)) -> match rld with | Kept _ -> assert false | Overridden ({loc}, e) -> let size = e.exp_type |> sizeOfTyp ~loc in let index = mem |> Il.Mem.alloc ~size in if i = 0 then firstIndex := index; funDef |> Il.FunDef.emit ~instr:(Il.Const (I32 0l)); e |> processExpr ~funDef ~env ~mem; funDef |> Il.FunDef.emit ~instr:(Il.I32Store index)); funDef |> Il.FunDef.emit ~instr:(Il.Const (I32 (!firstIndex |> Int32.of_int))) | Texp_field (e, {loc}, {lbl_name; lbl_all}) -> let offset = ref 0 in lbl_all |> Array.exists (fun (ld : CL.Types.label_description) -> if ld.lbl_name = lbl_name then true else let size = ld.lbl_arg |> sizeOfTyp ~loc in offset := !offset + size; false) |> ignore; let index = !offset in funDef |> Il.FunDef.emit ~instr:(Il.Const (I32 0l)); e |> processExpr ~funDef ~env ~mem; funDef |> Il.FunDef.emit ~instr:(Il.I32Load index) | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Expression not supported"); assert false let rec processGlobal ~env ~id ~mem (expr : CL.Typedtree.expression) = match expr.exp_desc with | Texp_constant const_ -> let const = const_ |> translateConst ~loc:expr.exp_loc ~mem in Il.Init.Const const | Texp_ident (id1, _, _) -> ( let id1 = CL.Path.name id1 in match env |> Il.Env.find ~id:id1 with | Some (GlobalDef globalDef) -> globalDef.init | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "processGlobal Id not found: %s" id); assert false) | Texp_tuple es -> Tuple (es |> List.map (processGlobal ~env ~id ~mem)) | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "processGlobal not supported yet"); assert false let envRef = ref (Il.Env.create ()) let memRef = ref (Il.Mem.create ()) let processValueBinding ~id ~(expr : CL.Typedtree.expression) = let id = CL.Ident.name id in Log_.item "no-alloc binding for %s@." id; let kind = Il.Kind.fromType expr.exp_type in match kind with | Arrow _ -> let funDef = Il.FunDef.create ~id ~kind in envRef := !envRef |> Il.Env.add ~id ~def:(FunDef funDef); expr |> processExpr ~funDef ~env:!envRef ~mem:!memRef | _ -> let init = expr |> processGlobal ~env:!envRef ~id ~mem:!memRef in envRef := !envRef |> Il.Env.add ~id ~def:(GlobalDef {id; init}) let collectValueBinding super self (vb : CL.Typedtree.value_binding) = (match vb.vb_pat.pat_desc with | Tpat_var (id, _) when vb.vb_attributes |> Annotation.hasAttribute (( = ) "noalloc") -> processValueBinding ~id ~expr:vb.CL.Typedtree.vb_expr | _ -> ()); let r = super.CL.Tast_mapper.value_binding self vb in r let traverseStructure = let super = CL.Tast_mapper.default in let value_binding self vb = vb |> collectValueBinding super self in {super with value_binding} let processCmt (cmt_infos : CL.Cmt_format.cmt_infos) = match cmt_infos.cmt_annots with | Interface _ -> () | Implementation structure -> structure |> traverseStructure.structure traverseStructure |> ignore | _ -> () let reportResults ~ppf = !memRef |> Il.Mem.dump ~ppf; !envRef |> Il.Env.dump ~ppf
null
https://raw.githubusercontent.com/rescript-association/reanalyze/d3ef53812b412521253bc0597e98421dd9083c82/src/Noalloc.ml
ocaml
let processCallee ~env ~funDef ~loc callee = match callee with | CL.Path.Pident id -> ( let id = CL.Ident.name id in match env |> Il.Env.find ~id with | Some (FunDef funDefCallee) -> funDef |> Il.FunDef.emit ~instr:(Il.Call funDefCallee.id) | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Callee not recognized: %s" id); assert false) | _ -> ( match callee |> CL.Path.name with | "Pervasives.+" | "Stdlib.+" -> funDef |> Il.FunDef.emit ~instr:Il.I32Add | "Pervasives.+." | "Stdlib.+." -> funDef |> Il.FunDef.emit ~instr:Il.F64Add | "Pervasives.*." | "Stdlib.*." -> funDef |> Il.FunDef.emit ~instr:Il.F64Mul | name -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Callee not recognized: %s" name); assert false) let rec processTyp ~(funDef : Il.funDef) ~loc (typ : CL.Types.type_expr) = match Compat.get_desc typ with | Ttuple ts -> let scopes = ts |> List.map (processTyp ~funDef ~loc) in Il.Tuple scopes | Tlink t -> t |> processTyp ~funDef ~loc | Tsubst _ -> Compat.getTSubst (Compat.get_desc typ) |> processTyp ~funDef ~loc | Tconstr _ | Tvar _ -> let offset = funDef.nextOffset in funDef.nextOffset <- offset + 1; Il.Local offset | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Type not supported"); assert false let rec sizeOfTyp ~loc (typ : CL.Types.type_expr) = match Compat.get_desc typ with | Tlink t -> t |> sizeOfTyp ~loc | Tsubst _ -> Compat.getTSubst (Compat.get_desc typ) |> sizeOfTyp ~loc | Tconstr (Pident id, [], _) -> ( match CL.Ident.name id with | "int" -> 4 | "string" -> 4 | name -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Size of type %s not supported" name); assert false) | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Size of type not supported"); assert false let rec emitLocalSetBackwards ~(funDef : Il.funDef) ~(scope : Il.scope) = match scope with | Tuple scopes -> List.rev scopes |> List.iter (fun s -> emitLocalSetBackwards ~funDef ~scope:s) | Local offset -> let instr = Il.LocalSet offset in funDef |> Il.FunDef.emit ~instr let rec processFunDefPat ~funDef ~env ~mem (pat : CL.Typedtree.pattern) = match pat.pat_desc with | Tpat_var (id, _) | Tpat_alias ({pat_desc = Tpat_any}, id, _) -> let scope = pat.pat_type |> processTyp ~funDef ~loc:pat.pat_loc in let newEnv = env |> Il.Env.add ~id:(id |> CL.Ident.name) ~def:(LocalScope scope) in (newEnv, scope) | Tpat_construct _ when Compat.unboxPatCstrTxt pat.pat_desc = CL.Longident.Lident "()" -> (env, Il.Tuple []) | Tpat_tuple pats -> let newEnv, scopes = pats |> List.fold_left (fun (e, scopes) p -> let newEnv, scope = p |> processFunDefPat ~funDef ~env:e ~mem in (newEnv, scope :: scopes)) (env, []) in (newEnv, Il.Tuple scopes) | _ -> Log_.warning ~count:false ~loc:pat.pat_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Argument pattern not supported"); assert false let rec processFunDef ~funDef ~env ~mem ~params (expr : CL.Typedtree.expression) = match expr.exp_desc with | Texp_function { arg_label = Nolabel; param; cases = [{c_lhs; c_guard = None; c_rhs}]; partial = Total; } -> let newEnv, typ = c_lhs |> processFunDefPat ~funDef ~env ~mem in c_rhs |> processFunDef ~funDef ~env:newEnv ~mem ~params:((param, typ) :: params) | _ -> funDef.numParams <- funDef.nextOffset; (env, expr, params) let translateConst ~loc ~mem (const : CL.Asttypes.constant) = match const with | Const_int n -> Il.I32 (n |> Int32.of_int) | Const_float s -> let sWithDecimal = match (s.[String.length s - 1] [@doesNotRaise]) = '.' with | true -> s ^ "0" | false -> s in Il.F64 sWithDecimal | Const_string _ -> let index = mem |> Il.Mem.allocString ~string:(const |> Compat.getConstString) in Il.I32 (index |> Int32.of_int) | _ -> Log_.warning ~count:false ~loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Constant not supported"); assert false let processConst ~funDef ~loc ~mem (const_ : CL.Asttypes.constant) = let const = const_ |> translateConst ~loc ~mem in funDef |> Il.FunDef.emit ~instr:(Il.Const const) let rec processLocalBinding ~env ~(pat : CL.Typedtree.pattern) ~(scope : Il.scope) = match (pat.pat_desc, scope) with | Tpat_var (id, _), _ -> env |> Il.Env.add ~id:(id |> CL.Ident.name) ~def:(LocalScope scope) | Tpat_tuple pats, Tuple scopes -> let patsAndScopes = (List.combine pats scopes [@doesNotRaise]) in patsAndScopes |> List.fold_left (fun e (p, s) -> processLocalBinding ~env:e ~pat:p ~scope:s) env | Tpat_any, _ -> env | _ -> assert false and processExpr ~funDef ~env ~mem (expr : CL.Typedtree.expression) = match expr.exp_desc with | Texp_constant const -> const |> processConst ~funDef ~loc:expr.exp_loc ~mem | Texp_ident (id, _, _) -> ( let id = CL.Path.name id in let rec emitScope (scope : Il.scope) = match scope with | Local offset -> funDef |> Il.FunDef.emit ~instr:(Il.LocalGet offset) | Tuple scopes -> scopes |> List.iter emitScope in match env |> Il.Env.find ~id with | Some (LocalScope scope) -> emitScope scope | Some (GlobalDef {init}) -> let rec emitInit (init : Il.Init.t) = match init with | Const const -> funDef |> Il.FunDef.emit ~instr:(Il.Const const) | Tuple is -> is |> List.iter emitInit in emitInit init | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Id not found: %s" id); assert false) | Texp_apply ({exp_desc = Texp_ident (callee, _, vd); exp_loc = callee_loc}, args) -> let kind = vd.val_type |> Il.Kind.fromType in args |> List.iteri (fun i ((argLabel : CL.Asttypes.arg_label), argOpt) -> match (argLabel, argOpt) with | Nolabel, Some (arg : CL.Typedtree.expression) -> (match kind with | Arrow (declKinds, _) -> let declKind = (declKinds.(i) [@doesNotRaise]) in let argKind = arg.exp_type |> Il.Kind.fromType in if argKind <> declKind then Log_.warning ~count:true ~loc:arg.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Function call to @{<info>%s@}: parameter %d has kind \ @{<info>%s@} but the supplied argument has kind \ @{<info>%s@}" (callee |> CL.Path.name) i (declKind |> Il.Kind.toString) (argKind |> Il.Kind.toString)) | _ -> assert false); arg |> processExpr ~funDef ~env ~mem | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Argument not supported")); callee |> processCallee ~env ~funDef ~loc:callee_loc | Texp_function _ -> let env, body, params = expr |> processFunDef ~funDef ~env ~mem ~params:[] in if params = [] then ( Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Cannot decode function parameters"); assert false); body |> processExpr ~funDef ~env ~mem | Texp_tuple l -> l |> List.iter (processExpr ~funDef ~env ~mem) | Texp_let (Nonrecursive, [vb], inExpr) -> let scope = vb.vb_expr.exp_type |> processTyp ~funDef ~loc:vb.vb_expr.exp_loc in vb.vb_expr |> processExpr ~funDef ~env ~mem; emitLocalSetBackwards ~funDef ~scope; let newEnv = processLocalBinding ~env ~pat:vb.vb_pat ~scope in inExpr |> processExpr ~funDef ~env:newEnv ~mem | Texp_record {fields; extended_expression = None} -> let firstIndex = ref 0 in fields |> Array.iteri (fun i (_ld, (rld : CL.Typedtree.record_label_definition)) -> match rld with | Kept _ -> assert false | Overridden ({loc}, e) -> let size = e.exp_type |> sizeOfTyp ~loc in let index = mem |> Il.Mem.alloc ~size in if i = 0 then firstIndex := index; funDef |> Il.FunDef.emit ~instr:(Il.Const (I32 0l)); e |> processExpr ~funDef ~env ~mem; funDef |> Il.FunDef.emit ~instr:(Il.I32Store index)); funDef |> Il.FunDef.emit ~instr:(Il.Const (I32 (!firstIndex |> Int32.of_int))) | Texp_field (e, {loc}, {lbl_name; lbl_all}) -> let offset = ref 0 in lbl_all |> Array.exists (fun (ld : CL.Types.label_description) -> if ld.lbl_name = lbl_name then true else let size = ld.lbl_arg |> sizeOfTyp ~loc in offset := !offset + size; false) |> ignore; let index = !offset in funDef |> Il.FunDef.emit ~instr:(Il.Const (I32 0l)); e |> processExpr ~funDef ~env ~mem; funDef |> Il.FunDef.emit ~instr:(Il.I32Load index) | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "Expression not supported"); assert false let rec processGlobal ~env ~id ~mem (expr : CL.Typedtree.expression) = match expr.exp_desc with | Texp_constant const_ -> let const = const_ |> translateConst ~loc:expr.exp_loc ~mem in Il.Init.Const const | Texp_ident (id1, _, _) -> ( let id1 = CL.Path.name id1 in match env |> Il.Env.find ~id:id1 with | Some (GlobalDef globalDef) -> globalDef.init | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "processGlobal Id not found: %s" id); assert false) | Texp_tuple es -> Tuple (es |> List.map (processGlobal ~env ~id ~mem)) | _ -> Log_.warning ~count:false ~loc:expr.exp_loc ~name:"Noalloc" (fun ppf () -> Format.fprintf ppf "processGlobal not supported yet"); assert false let envRef = ref (Il.Env.create ()) let memRef = ref (Il.Mem.create ()) let processValueBinding ~id ~(expr : CL.Typedtree.expression) = let id = CL.Ident.name id in Log_.item "no-alloc binding for %s@." id; let kind = Il.Kind.fromType expr.exp_type in match kind with | Arrow _ -> let funDef = Il.FunDef.create ~id ~kind in envRef := !envRef |> Il.Env.add ~id ~def:(FunDef funDef); expr |> processExpr ~funDef ~env:!envRef ~mem:!memRef | _ -> let init = expr |> processGlobal ~env:!envRef ~id ~mem:!memRef in envRef := !envRef |> Il.Env.add ~id ~def:(GlobalDef {id; init}) let collectValueBinding super self (vb : CL.Typedtree.value_binding) = (match vb.vb_pat.pat_desc with | Tpat_var (id, _) when vb.vb_attributes |> Annotation.hasAttribute (( = ) "noalloc") -> processValueBinding ~id ~expr:vb.CL.Typedtree.vb_expr | _ -> ()); let r = super.CL.Tast_mapper.value_binding self vb in r let traverseStructure = let super = CL.Tast_mapper.default in let value_binding self vb = vb |> collectValueBinding super self in {super with value_binding} let processCmt (cmt_infos : CL.Cmt_format.cmt_infos) = match cmt_infos.cmt_annots with | Interface _ -> () | Implementation structure -> structure |> traverseStructure.structure traverseStructure |> ignore | _ -> () let reportResults ~ppf = !memRef |> Il.Mem.dump ~ppf; !envRef |> Il.Env.dump ~ppf
3622987dc688d01c011ec3d61938d3782582faaba313af4b8d5d432a6f593539
abdulapopoola/SICPBook
Ex1.05.scm
Exercise 1.5 (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) (test 0 (p)) Applicative order - this always evaluates the arguments first ;and generates results (i.e. primitives) to be passed into other expressions. As such , the evaluation of the p parameter will lead to an infinite loop . ;; ;; ;Normal order - evaluation of arguments only occurs when they are needed As such , the evaluation of the p parameter ( which causes an infinite loop ) ;never occurs because of the comparision with 0 and thus the result will be a 0.
null
https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%201/1.1/Ex1.05.scm
scheme
and generates results (i.e. primitives) to be passed into other expressions. Normal order - evaluation of arguments only occurs when they are needed never occurs because of the comparision with 0 and thus the result will be a 0.
Exercise 1.5 (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) (test 0 (p)) Applicative order - this always evaluates the arguments first As such , the evaluation of the p parameter will lead to an infinite loop . As such , the evaluation of the p parameter ( which causes an infinite loop )
fee051eb06807aaeb888f30fe01734aa9a973d639bb4dba8d92d7619e1257675
gojek/ziggurat
batch_proto_deserializer.clj
(ns ziggurat.middleware.batch.batch-proto-deserializer (:require [ziggurat.middleware.default :refer [deserialize-message]])) (defn- deserialize-key-and-value [key-proto-class value-proto-class topic-entity flatten-protobuf-struct?] (fn [message] (let [key (:key message) value (:value message) deserialized-key (when (some? key) (deserialize-message key key-proto-class (name topic-entity) flatten-protobuf-struct?)) deserialized-value (when (some? value) (deserialize-message value value-proto-class (name topic-entity) flatten-protobuf-struct?))] (assoc (assoc message :key deserialized-key) :value deserialized-value)))) (defn deserialize-batch-of-proto-messages "This is a middleware function that takes in a sequence of proto message and calls forms a lazy sequence of de-serialized messages before passing it to the handler-fn" ([handler-fn key-proto-class value-proto-class topic-entity] (deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class topic-entity false)) ([handler-fn key-proto-class value-proto-class topic-entity flatten-protobuf-struct?] (fn [batch-message] (let [key-value-deserializer (deserialize-key-and-value key-proto-class value-proto-class topic-entity flatten-protobuf-struct?)] (handler-fn (map key-value-deserializer batch-message))))))
null
https://raw.githubusercontent.com/gojek/ziggurat/f5e0822af8410ea79b7734ef2f41bc98fad3c17f/src/ziggurat/middleware/batch/batch_proto_deserializer.clj
clojure
(ns ziggurat.middleware.batch.batch-proto-deserializer (:require [ziggurat.middleware.default :refer [deserialize-message]])) (defn- deserialize-key-and-value [key-proto-class value-proto-class topic-entity flatten-protobuf-struct?] (fn [message] (let [key (:key message) value (:value message) deserialized-key (when (some? key) (deserialize-message key key-proto-class (name topic-entity) flatten-protobuf-struct?)) deserialized-value (when (some? value) (deserialize-message value value-proto-class (name topic-entity) flatten-protobuf-struct?))] (assoc (assoc message :key deserialized-key) :value deserialized-value)))) (defn deserialize-batch-of-proto-messages "This is a middleware function that takes in a sequence of proto message and calls forms a lazy sequence of de-serialized messages before passing it to the handler-fn" ([handler-fn key-proto-class value-proto-class topic-entity] (deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class topic-entity false)) ([handler-fn key-proto-class value-proto-class topic-entity flatten-protobuf-struct?] (fn [batch-message] (let [key-value-deserializer (deserialize-key-and-value key-proto-class value-proto-class topic-entity flatten-protobuf-struct?)] (handler-fn (map key-value-deserializer batch-message))))))
b7496805692dd01ebdffa368dafd2ffe5ccec43793300d85ba109ff4dfdb94d6
erlcloud/erlcloud
erlcloud_s3_tests.erl
-*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*- -module(erlcloud_s3_tests). -include_lib("eunit/include/eunit.hrl"). -include("erlcloud.hrl"). -include("erlcloud_aws.hrl"). -include("erlcloud_s3_test_data.hrl"). %% Unit tests for s3. %% Currently only test error handling and retries. %%%=================================================================== %%% Test entry points %%%=================================================================== operation_test_() -> {foreach, fun start/0, fun stop/1, [ fun get_bucket_policy_tests/1, fun get_bucket_notification_test/1, fun get_bucket_notification_no_prefix_test/1, fun get_bucket_notification_no_suffix_test/1, fun put_object_tests/1, fun error_handling_tests/1, fun dns_compliant_name_tests/1, fun get_bucket_lifecycle_tests/1, fun put_bucket_lifecycle_tests/1, fun delete_bucket_lifecycle_tests/1, fun encode_bucket_lifecycle_tests/1, fun list_inventory_configurations_test/1, fun get_inventory_configuration_test/1, fun put_bucket_inventory_test/1, fun delete_bucket_inventory_test/1, fun encode_inventory_test/1, fun delete_objects_batch_tests/1, fun delete_objects_batch_single_tests/1, fun delete_objects_batch_with_err_tests/1, fun delete_objects_batch_mixed_tests/1, fun put_bucket_encryption_test/1, fun get_bucket_encryption_test/1, fun get_bucket_encryption_not_found_test/1, fun delete_bucket_encryption_test/1, fun hackney_proxy_put_validation_test/1, fun get_bucket_and_key/1 ]}. start() -> meck:new(erlcloud_httpc), ok. stop(_) -> meck:unload(erlcloud_httpc). config() -> config(#aws_config{s3_follow_redirect = true}). config(Config) -> Config#aws_config{ access_key_id = string:copies("A", 20), secret_access_key = string:copies("a", 40)}. httpc_expect(Response) -> httpc_expect(get, Response). httpc_expect(Method, Response) -> fun(_Url, Method2, _Headers, _Body, _Timeout, _Config = #aws_config{hackney_client_options = #hackney_client_options{insecure = Insecure, proxy = Proxy, proxy_auth = Proxy_auth}, http_client = Http_client}) -> case Http_client of hackney -> Method = Method2, Insecure = false, Proxy = <<"10.10.10.10">>, Proxy_auth = {<<"AAAA">>, <<"BBBB">>}; _else -> Method = Method2, Insecure = true, Proxy = undefined, Proxy_auth = undefined end, Response end. get_bucket_lifecycle_tests(_) -> Response = {ok, {{200, "OK"}, [], <<" <LifecycleConfiguration xmlns=\"-03-01/\"> <Rule> <ID>Archive and then delete rule</ID> <Prefix>projectdocs/</Prefix> <Status>Enabled</Status> <Transition> <Days>30</Days> <StorageClass>STANDARD_IA</StorageClass> </Transition> <Transition> <Days>365</Days> <StorageClass>GLACIER</StorageClass> </Transition> <Expiration> <Days>3650</Days> </Expiration> </Rule></LifecycleConfiguration>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_lifecycle("BucketName", config()), ?_assertEqual({ok, [[{expiration,[{days,3650}]}, {id,"Archive and then delete rule"}, {prefix,"projectdocs/"}, {status,"Enabled"}, {transition,[[{days,30},{storage_class,"STANDARD_IA"}], [{days,365},{storage_class,"GLACIER"}]]}]]}, Result). put_bucket_lifecycle_tests(_) -> Response = {ok, {{200,"OK"}, [{"server","AmazonS3"}, {"content-length","0"}, {"date","Mon, 18 Jan 2016 09:14:29 GMT"}, {"x-amz-request-id","911850E447C20DE3"}, {"x-amz-id-2", "lzs7n4Z/9iwJ9Xd+s5s2nnwT6XIp2uhfkRMWvgqTeTXRr9JXl91s/kDnzLnA5eZQYvUVA7vyxLY="}], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Policy = [[{expiration,[{days,3650}]}, {id,"Archive and then delete rule"}, {prefix,"projectdocs/"}, {status,"Enabled"}, {transition,[[{days,30},{storage_class,"STANDARD_IA"}], [{days,365},{storage_class,"GLACIER"}]]}]], Result = erlcloud_s3:put_bucket_lifecycle("BucketName", Policy, config()), Result1 = erlcloud_s3:put_bucket_lifecycle("BucketName", <<"Policy">>, config()), [?_assertEqual(ok, Result), ?_assertEqual(ok, Result1)]. delete_bucket_lifecycle_tests(_) -> Response = {ok, {{200, "OK"}, [], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(delete, Response)), Result = erlcloud_s3:delete_bucket_lifecycle("BucketName", config()), ?_assertEqual(ok, Result). encode_bucket_lifecycle_tests(_) -> Expected = "<?xml version=\"1.0\"?><LifecycleConfiguration><Rule><Expiration><Days>3650</Days></Expiration><ID>Archive and then delete rule</ID><Prefix>projectdocs/</Prefix><Status>Enabled</Status><Transition><Days>30</Days><StorageClass>STANDARD_IA</StorageClass></Transition><Transition><Days>365</Days><StorageClass>GLACIER</StorageClass></Transition></Rule></LifecycleConfiguration>", Policy = [ [{expiration,[{days,3650}]}, {id,"Archive and then delete rule"}, {prefix,"projectdocs/"}, {status,"Enabled"}, {transition,[[{days,30},{storage_class,"STANDARD_IA"}], [{days,365},{storage_class,"GLACIER"}]]} ] ], Expected2 = "<?xml version=\"1.0\"?><LifecycleConfiguration><Rule><ID>al_s3--GLACIER-policy</ID><Prefix></Prefix><Status>Enabled</Status><Transition><Days>10</Days><StorageClass>GLACIER</StorageClass></Transition></Rule><Rule><ID>ed-test-console</ID><Prefix></Prefix><Status>Enabled</Status><Transition><Days>20</Days><StorageClass>GLACIER</StorageClass></Transition></Rule></LifecycleConfiguration>", Policy2 = [[{id,"al_s3--GLACIER-policy"}, {prefix,[]}, {status,"Enabled"}, {transition,[[{days,"10"}, {storage_class,"GLACIER"}]]}], [{id,"ed-test-console"}, {prefix,[]}, {status,"Enabled"}, {transition,[[{days,20},{storage_class,"GLACIER"}]]}]], Result = erlcloud_s3:encode_lifecycle(Policy), Result2 = erlcloud_s3:encode_lifecycle(Policy2), [?_assertEqual(Expected, Result), ?_assertEqual(Expected2, Result2)]. set_bucket_notification_test_() -> [?_assertEqual({'NotificationConfiguration',[]}, erlcloud_s3:create_notification_xml([])), ?_assertError( function_clause, erlcloud_s3:create_notification_param_xml({filter,[{foo, "bar"}]}, [])), ?_assertEqual( [{'Filter',[{'S3Key', [{'FilterRule',[{'Name',["Prefix"]}, {'Value',["images/"]}]}]}]}], erlcloud_s3:create_notification_param_xml({filter,[{prefix, "images/"}]}, [])), ?_assertEqual( [{'Filter',[{'S3Key', [{'FilterRule',[{'Name',["Suffix"]}, {'Value',["jpg"]}]}]}]}], erlcloud_s3:create_notification_param_xml({filter,[{suffix, "jpg"}]}, [])), ?_assertEqual( [{'Filter',[{'S3Key', [{'FilterRule',[{'Name',["Prefix"]}, {'Value',["images/"]}]}, {'FilterRule',[{'Name',["Suffix"]}, {'Value',["jpg"]}]}]}]}], erlcloud_s3:create_notification_param_xml({filter,[{prefix, "images/"}, {suffix, "jpg"}]}, [])), ?_assertEqual(?S3_BUCKET_EVENTS_SIMPLE_XML_FORM, erlcloud_s3:create_notification_xml(?S3_BUCKET_EVENTS_LIST))]. get_bucket_notification_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_EVENT_XML_CONFIG}}, meck:expect(erlcloud_httpc, request, fun("", _, _, _, _, _) -> Response end), ?_assertEqual(?S3_BUCKET_EVENTS_LIST, erlcloud_s3:get_bucket_attribute("BucketName", notification, config())). get_bucket_notification_no_prefix_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_EVENT_XML_CONFIG_NO_PREFIX}}, meck:expect(erlcloud_httpc, request, fun("", _, _, _, _, _) -> Response end), ?_assertEqual(?S3_BUCKET_EVENTS_LIST_NO_PREFIX, erlcloud_s3:get_bucket_attribute("BucketName", notification, config())). get_bucket_notification_no_suffix_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_EVENT_XML_CONFIG_NO_SUFFIX}}, meck:expect(erlcloud_httpc, request, fun("", _, _, _, _, _) -> Response end), ?_assertEqual(?S3_BUCKET_EVENTS_LIST_NO_SUFFIX, erlcloud_s3:get_bucket_attribute("BucketName", notification, config())). get_bucket_policy_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_policy("BucketName", config()), ?_assertEqual({ok, "TestBody"}, Result). put_object_tests(_) -> Response = {ok, {{200, "OK"}, [{"x-amz-version-id", "version_id"}], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Result = erlcloud_s3:put_object("BucketName", "Key", "Data", config()), ?_assertEqual([{version_id, "version_id"} ,{"x-amz-version-id", "version_id"} ], Result). dns_compliant_name_tests(_) -> [?_assertEqual(true, erlcloud_util:is_dns_compliant_name("goodname123")), ?_assertEqual(true, erlcloud_util:is_dns_compliant_name("good.name")), ?_assertEqual(true, erlcloud_util:is_dns_compliant_name("good-name")), ?_assertEqual(true, erlcloud_util:is_dns_compliant_name("good--name")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name("Bad.name")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name("badname.")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name(".bad.name")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name("bad.name--"))]. error_handling_no_retry() -> Response = {ok, {{500, "Internal Server Error"}, [], <<"TestBody">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_policy("BucketName", config()), ?_assertEqual({error,{http_error,500,"Internal Server Error",<<"TestBody">>}}, Result). error_handling_default_retry() -> Response1 = {ok, {{500, "Internal Server Error"}, [], <<"TestBody">>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "BucketName", config(#aws_config{retry = fun erlcloud_retry:default_retry/1})), ?_assertEqual({ok, "TestBody"}, Result). error_handling_httpc_error() -> Response1 = {error, timeout}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "BucketName", config(#aws_config{retry = fun erlcloud_retry:default_retry/1})), ?_assertEqual({ok, "TestBody"}, Result). %% Handle redirect by using location from error message. error_handling_redirect_message() -> Response1 = {ok, {{307,"Temporary Redirect"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>bucket.name.s3.eu-central-1.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). %% Handle redirect by using url from location header. error_handling_redirect_location() -> Response1 = {ok, {{301,"Temporary Redirect"}, [{"server","AmazonS3"}, {"date","Wed, 22 Jul 2015 09:58:03 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"location", "-test-frankfurt.s3.eu-central-1.amazonaws.com/"}, {"x-amz-id-2", "YIgyI9Lb9I/dMpDrRASSD8w5YsNAyhRlF+PDF0jlf9Hq6eVLvSkuj+ftZI2RmU5eXnOKW1Wqh20="}, {"x-amz-request-id","FAECC30C2CD53BCA"} ], <<>>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). %% Handle redirect by using bucket region from "x-amz-bucket-region" header. error_handling_redirect_bucket_region() -> Response1 = {ok, {{301,"Temporary Redirect"}, [{"server","AmazonS3"}, {"date","Wed, 22 Jul 2015 09:58:03 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"x-amz-id-2", "YIgyI9Lb9I/dMpDrRASSD8w5YsNAyhRlF+PDF0jlf9Hq6eVLvSkuj+ftZI2RmU5eXnOKW1Wqh20="}, {"x-amz-request-id","FAECC30C2CD53BCA"}, {"x-amz-bucket-region","us-west-1"} ], <<>>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). %% Handle redirect by using bucket region from "x-amz-bucket-region" header. error_handling_redirect_error() -> Response1 = {ok, {{301,"Temporary Redirect"}, [{"server","AmazonS3"}, {"date","Wed, 22 Jul 2015 09:58:03 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"x-amz-id-2", "YIgyI9Lb9I/dMpDrRASSD8w5YsNAyhRlF+PDF0jlf9Hq6eVLvSkuj+ftZI2RmU5eXnOKW1Wqh20="}, {"x-amz-request-id","FAECC30C2CD53BCA"}, {"x-amz-bucket-region","us-west-1"} ], <<>>}}, Response2 = {ok,{{404,"Not Found"}, [{"server","AmazonS3"}, {"date","Tue, 25 Aug 2015 17:49:02 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"x-amz-id-2", "yjPxn58opjPoTJNIm5sPRjFrRlg4c50Ef9hT1m2nPvamKnr7nePMzKN4gStUSTtf0yp6+b/dzrA="}, {"x-amz-request-id","5DE771B2AD75F413"}], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>NoSuchBucketPolicy</Code><Message>The bu">>}}, Response3 = {ok, {{301,"Moved Permanently"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>s3.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result1 = erlcloud_s3:get_bucket_policy( "bucket.name", config()), meck:sequence(erlcloud_httpc, request, 6, [Response1]), Result2 = erlcloud_s3:get_bucket_policy( "bucket.name", config(#aws_config{s3_follow_redirect = false})), meck:sequence(erlcloud_httpc, request, 6, [Response3, Response2]), Result3 = erlcloud_s3:get_bucket_policy( "bucket.name", config(#aws_config{s3_follow_redirect = true})), [?_assertMatch({error,{http_error,404,"Not Found",_}}, Result1), ?_assertMatch({error,{http_error,301,"Temporary Redirect",_}}, Result2), ?_assertMatch({error,{http_error,404,"Not Found",_}}, Result3)]. Handle two sequential redirects . error_handling_double_redirect() -> Response1 = {ok, {{301,"Moved Permanently"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>s3.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, Response2 = {ok, {{307,"Temporary Redirect"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>bucket.name.s3.eu-central-1.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, Response3 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2, Response3]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). error_handling_tests(_) -> [error_handling_no_retry(), error_handling_default_retry(), error_handling_httpc_error(), error_handling_redirect_message(), error_handling_redirect_location(), error_handling_redirect_bucket_region(), error_handling_redirect_error(), error_handling_double_redirect() ]. Bucket Inventory tests list_inventory_configurations_test(_)-> Response = {ok, {{200, "OK"}, [], <<" <ListInventoryConfigurationsResult xmlns=\"-03-01/\"> <InventoryConfiguration> <Id>report1</Id> <IsEnabled>true</IsEnabled> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::destination-bucket</Bucket> <Prefix>prefix1</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <Filter> <Prefix>prefix/One</Prefix> </Filter> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration> <InventoryConfiguration> <Id>report2</Id> <IsEnabled>true</IsEnabled> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::bucket2</Bucket> <Prefix>prefix2</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <Filter> <Prefix>prefix/Two</Prefix> </Filter> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration> <InventoryConfiguration> <Id>report3</Id> <IsEnabled>true</IsEnabled> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::bucket3</Bucket> <Prefix>prefix3</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <Filter> <Prefix>prefix/Three</Prefix> </Filter> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration> <IsTruncated>false</IsTruncated> </ListInventoryConfigurationsResult> ">>}}, ExpectedResult = {ok, [ {inventory_configuration, [ [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "prefix/One"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], [ {id, "report2"}, {is_enabled, "true"}, {filter, [{prefix, "prefix/Two"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::bucket2"}, {prefix, "prefix2"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], [ {id, "report3"}, {is_enabled, "true"}, {filter, [{prefix, "prefix/Three"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::bucket3"}, {prefix, "prefix3"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ] ]} ]}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:list_bucket_inventory("BucketName", config()), ?_assertEqual( ExpectedResult, Result). get_inventory_configuration_test(_) -> Response = {ok, {{200, "OK"}, [], <<" <InventoryConfiguration xmlns=\"-03-01/\"> <Id>report1</Id> <IsEnabled>true</IsEnabled> <Filter> <Prefix>filterPrefix</Prefix> </Filter> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::destination-bucket</Bucket> <Prefix>prefix1</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration>">>}}, ExpectedResult = {ok, [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "filterPrefix"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ]}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_inventory("BucketName", "report1", config()), ?_assertEqual( ExpectedResult, Result). encode_inventory_test(_)-> ExpectedXml = "<?xml version=\"1.0\"?>" "<InventoryConfiguration xmlns=\"-03-01/\">" "<Id>report1</Id>" "<IsEnabled>true</IsEnabled>" "<Filter>" "<Prefix>filterPrefix</Prefix>" "</Filter>" "<Destination>" "<S3BucketDestination>" "<Format>CSV</Format>" "<AccountId>123456789012</AccountId>" "<Bucket>arn:aws:s3:::destination-bucket</Bucket>" "<Prefix>prefix1</Prefix>" "</S3BucketDestination>" "</Destination>" "<Schedule>" "<Frequency>Daily</Frequency>" "</Schedule>" "<IncludedObjectVersions>All</IncludedObjectVersions>" "<OptionalFields>" "<Field>Size</Field>" "<Field>LastModifiedDate</Field>" "<Field>ETag</Field>" "<Field>StorageClass</Field>" "<Field>IsMultipartUploaded</Field>" "<Field>ReplicationStatus</Field>" "</OptionalFields>" "</InventoryConfiguration>", Inventory = [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "filterPrefix"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], Result = erlcloud_s3:encode_inventory(Inventory), ?_assertEqual(ExpectedXml, Result). put_bucket_inventory_test(_) -> Response = {ok, { {200,"OK"}, [ {"server","AmazonS3"}, {"content-length","0"}, {"date","Mon, 31 Oct 2016 12:00:00 GMT"}, {"x-amz-request-id","236A8905248E5A01"}, {"x-amz-id-2", "YgIPIfBiKa2bj0KMg95r/0zo3emzU4dzsD4rcKCHQUAdQkf3ShJTOOpXUueF6QKo"} ], <<>> } }, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Inventory = [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "filterPrefix"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], Result = erlcloud_s3:put_bucket_inventory("BucketName", Inventory, config()), ?_assertEqual(ok, Result). delete_bucket_inventory_test(_) -> Response = {ok, { {204,"No Content"}, [ {"server","AmazonS3"}, {"date","Wed, 14 May 2014 02:11:22 GMT"}, {"x-amz-request-id","0CF038E9BCF63097"}, {"x-amz-id-2", "0FmFIWsh/PpBuzZ0JFRC55ZGVmQW4SHJ7xVDqKwhEdJmf3q63RtrvH8ZuxW1Bol5"} ], <<>> } }, meck:expect(erlcloud_httpc, request, httpc_expect(delete, Response)), Result = erlcloud_s3:delete_bucket_inventory("BucketName", "report1", config()), ?_assertEqual(ok, Result). delete_objects_batch_single_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?><DeleteResult xmlns=\"-03-01/\"><Deleted><Key>sample1.txt</Key></Deleted></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample1.txt"], config()), ?_assertEqual([{deleted,["sample1.txt"]},{error,[]}], Result). delete_objects_batch_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <DeleteResult xmlns=\"-03-01/\"><Deleted><Key>sample1.txt</Key></Deleted><Deleted><Key>sample2.txt</Key></Deleted><Deleted><Key>sample3.txt</Key></Deleted></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample1.txt","sample2.txt","sample3.txt"], config()), ?_assertEqual([{deleted,["sample1.txt", "sample2.txt","sample3.txt"]},{error,[]}], Result). delete_objects_batch_with_err_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?><DeleteResult xmlns=\"-03-01/\"><Error><Key>sample2.txt</Key><Code>AccessDenied</Code><Message>Access Denied</Message></Error></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample2.txt"], config()), ?_assertEqual([{deleted,[]}, {error,[{"sample2.txt","AccessDenied","Access Denied"}]}], Result). delete_objects_batch_mixed_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?><DeleteResult xmlns=\"-03-01/\"><Deleted><Key>sample1.txt</Key></Deleted><Error><Key>sample2.txt</Key><Code>AccessDenied</Code><Message>Access Denied</Message></Error></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample2.txt"], config()), ?_assertEqual([{deleted,["sample1.txt"]}, {error,[{"sample2.txt","AccessDenied","Access Denied"}]}], Result). put_bucket_encryption_test(_) -> Response = {ok, {{201, "Created"}, [], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Cfg = config(), KMSKey = "arn:aws:kms:us-east-1:1234/5678example", Result1 = erlcloud_s3:put_bucket_encryption("bucket", "AES256", Cfg), Result2 = erlcloud_s3:put_bucket_encryption("bucket", "aws:kms", KMSKey, Cfg), [ ?_assertEqual(ok, Result1), ?_assertEqual(ok, Result2) ]. get_bucket_encryption_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_ENCRYPTION}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_encryption("bucket", config()), ?_assertEqual( {ok, [{sse_algorithm, "aws:kms"}, {kms_master_key_id, "arn:aws:kms:us-east-1:1234/5678example"}]}, Result ). get_bucket_encryption_not_found_test(_) -> Response = {ok, {{404, "Not Found"}, [], ?S3_BUCKET_ENCRYPTION_NOT_FOUND}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_encryption("bucket", config()), ?_assertEqual( {error, {http_error, 404, "Not Found", ?S3_BUCKET_ENCRYPTION_NOT_FOUND}}, Result ). delete_bucket_encryption_test(_) -> Response = {ok, {{204, "No Content"}, [], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(delete, Response)), Result = erlcloud_s3:delete_bucket_encryption("bucket", config()), ?_assertEqual(ok, Result). hackney_proxy_put_validation_test(_) -> Response = {ok, {{200, "OK"}, [{"x-amz-version-id", "version_id"}], <<>>}}, Config2 = #aws_config{hackney_client_options = #hackney_client_options{insecure = false, proxy = <<"10.10.10.10">>, proxy_auth = {<<"AAAA">>, <<"BBBB">>}}, http_client = hackney}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Result = erlcloud_s3:put_object("BucketName", "Key", "Data", config(Config2)), ?_assertEqual([{version_id, "version_id"} ,{"x-amz-version-id", "version_id"} ], Result). get_bucket_and_key(_) -> ErlcloudS3ExportExample = "", Result = erlcloud_s3:get_bucket_and_key(ErlcloudS3ExportExample), ?_assertEqual({"some_bucket","path_to_file"}, Result).
null
https://raw.githubusercontent.com/erlcloud/erlcloud/d1d60130929436b5524a0e70ae17f6da6a2a14b9/test/erlcloud_s3_tests.erl
erlang
Unit tests for s3. Currently only test error handling and retries. =================================================================== Test entry points =================================================================== Handle redirect by using location from error message. Handle redirect by using url from location header. Handle redirect by using bucket region from "x-amz-bucket-region" header. Handle redirect by using bucket region from "x-amz-bucket-region" header.
-*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*- -module(erlcloud_s3_tests). -include_lib("eunit/include/eunit.hrl"). -include("erlcloud.hrl"). -include("erlcloud_aws.hrl"). -include("erlcloud_s3_test_data.hrl"). operation_test_() -> {foreach, fun start/0, fun stop/1, [ fun get_bucket_policy_tests/1, fun get_bucket_notification_test/1, fun get_bucket_notification_no_prefix_test/1, fun get_bucket_notification_no_suffix_test/1, fun put_object_tests/1, fun error_handling_tests/1, fun dns_compliant_name_tests/1, fun get_bucket_lifecycle_tests/1, fun put_bucket_lifecycle_tests/1, fun delete_bucket_lifecycle_tests/1, fun encode_bucket_lifecycle_tests/1, fun list_inventory_configurations_test/1, fun get_inventory_configuration_test/1, fun put_bucket_inventory_test/1, fun delete_bucket_inventory_test/1, fun encode_inventory_test/1, fun delete_objects_batch_tests/1, fun delete_objects_batch_single_tests/1, fun delete_objects_batch_with_err_tests/1, fun delete_objects_batch_mixed_tests/1, fun put_bucket_encryption_test/1, fun get_bucket_encryption_test/1, fun get_bucket_encryption_not_found_test/1, fun delete_bucket_encryption_test/1, fun hackney_proxy_put_validation_test/1, fun get_bucket_and_key/1 ]}. start() -> meck:new(erlcloud_httpc), ok. stop(_) -> meck:unload(erlcloud_httpc). config() -> config(#aws_config{s3_follow_redirect = true}). config(Config) -> Config#aws_config{ access_key_id = string:copies("A", 20), secret_access_key = string:copies("a", 40)}. httpc_expect(Response) -> httpc_expect(get, Response). httpc_expect(Method, Response) -> fun(_Url, Method2, _Headers, _Body, _Timeout, _Config = #aws_config{hackney_client_options = #hackney_client_options{insecure = Insecure, proxy = Proxy, proxy_auth = Proxy_auth}, http_client = Http_client}) -> case Http_client of hackney -> Method = Method2, Insecure = false, Proxy = <<"10.10.10.10">>, Proxy_auth = {<<"AAAA">>, <<"BBBB">>}; _else -> Method = Method2, Insecure = true, Proxy = undefined, Proxy_auth = undefined end, Response end. get_bucket_lifecycle_tests(_) -> Response = {ok, {{200, "OK"}, [], <<" <LifecycleConfiguration xmlns=\"-03-01/\"> <Rule> <ID>Archive and then delete rule</ID> <Prefix>projectdocs/</Prefix> <Status>Enabled</Status> <Transition> <Days>30</Days> <StorageClass>STANDARD_IA</StorageClass> </Transition> <Transition> <Days>365</Days> <StorageClass>GLACIER</StorageClass> </Transition> <Expiration> <Days>3650</Days> </Expiration> </Rule></LifecycleConfiguration>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_lifecycle("BucketName", config()), ?_assertEqual({ok, [[{expiration,[{days,3650}]}, {id,"Archive and then delete rule"}, {prefix,"projectdocs/"}, {status,"Enabled"}, {transition,[[{days,30},{storage_class,"STANDARD_IA"}], [{days,365},{storage_class,"GLACIER"}]]}]]}, Result). put_bucket_lifecycle_tests(_) -> Response = {ok, {{200,"OK"}, [{"server","AmazonS3"}, {"content-length","0"}, {"date","Mon, 18 Jan 2016 09:14:29 GMT"}, {"x-amz-request-id","911850E447C20DE3"}, {"x-amz-id-2", "lzs7n4Z/9iwJ9Xd+s5s2nnwT6XIp2uhfkRMWvgqTeTXRr9JXl91s/kDnzLnA5eZQYvUVA7vyxLY="}], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Policy = [[{expiration,[{days,3650}]}, {id,"Archive and then delete rule"}, {prefix,"projectdocs/"}, {status,"Enabled"}, {transition,[[{days,30},{storage_class,"STANDARD_IA"}], [{days,365},{storage_class,"GLACIER"}]]}]], Result = erlcloud_s3:put_bucket_lifecycle("BucketName", Policy, config()), Result1 = erlcloud_s3:put_bucket_lifecycle("BucketName", <<"Policy">>, config()), [?_assertEqual(ok, Result), ?_assertEqual(ok, Result1)]. delete_bucket_lifecycle_tests(_) -> Response = {ok, {{200, "OK"}, [], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(delete, Response)), Result = erlcloud_s3:delete_bucket_lifecycle("BucketName", config()), ?_assertEqual(ok, Result). encode_bucket_lifecycle_tests(_) -> Expected = "<?xml version=\"1.0\"?><LifecycleConfiguration><Rule><Expiration><Days>3650</Days></Expiration><ID>Archive and then delete rule</ID><Prefix>projectdocs/</Prefix><Status>Enabled</Status><Transition><Days>30</Days><StorageClass>STANDARD_IA</StorageClass></Transition><Transition><Days>365</Days><StorageClass>GLACIER</StorageClass></Transition></Rule></LifecycleConfiguration>", Policy = [ [{expiration,[{days,3650}]}, {id,"Archive and then delete rule"}, {prefix,"projectdocs/"}, {status,"Enabled"}, {transition,[[{days,30},{storage_class,"STANDARD_IA"}], [{days,365},{storage_class,"GLACIER"}]]} ] ], Expected2 = "<?xml version=\"1.0\"?><LifecycleConfiguration><Rule><ID>al_s3--GLACIER-policy</ID><Prefix></Prefix><Status>Enabled</Status><Transition><Days>10</Days><StorageClass>GLACIER</StorageClass></Transition></Rule><Rule><ID>ed-test-console</ID><Prefix></Prefix><Status>Enabled</Status><Transition><Days>20</Days><StorageClass>GLACIER</StorageClass></Transition></Rule></LifecycleConfiguration>", Policy2 = [[{id,"al_s3--GLACIER-policy"}, {prefix,[]}, {status,"Enabled"}, {transition,[[{days,"10"}, {storage_class,"GLACIER"}]]}], [{id,"ed-test-console"}, {prefix,[]}, {status,"Enabled"}, {transition,[[{days,20},{storage_class,"GLACIER"}]]}]], Result = erlcloud_s3:encode_lifecycle(Policy), Result2 = erlcloud_s3:encode_lifecycle(Policy2), [?_assertEqual(Expected, Result), ?_assertEqual(Expected2, Result2)]. set_bucket_notification_test_() -> [?_assertEqual({'NotificationConfiguration',[]}, erlcloud_s3:create_notification_xml([])), ?_assertError( function_clause, erlcloud_s3:create_notification_param_xml({filter,[{foo, "bar"}]}, [])), ?_assertEqual( [{'Filter',[{'S3Key', [{'FilterRule',[{'Name',["Prefix"]}, {'Value',["images/"]}]}]}]}], erlcloud_s3:create_notification_param_xml({filter,[{prefix, "images/"}]}, [])), ?_assertEqual( [{'Filter',[{'S3Key', [{'FilterRule',[{'Name',["Suffix"]}, {'Value',["jpg"]}]}]}]}], erlcloud_s3:create_notification_param_xml({filter,[{suffix, "jpg"}]}, [])), ?_assertEqual( [{'Filter',[{'S3Key', [{'FilterRule',[{'Name',["Prefix"]}, {'Value',["images/"]}]}, {'FilterRule',[{'Name',["Suffix"]}, {'Value',["jpg"]}]}]}]}], erlcloud_s3:create_notification_param_xml({filter,[{prefix, "images/"}, {suffix, "jpg"}]}, [])), ?_assertEqual(?S3_BUCKET_EVENTS_SIMPLE_XML_FORM, erlcloud_s3:create_notification_xml(?S3_BUCKET_EVENTS_LIST))]. get_bucket_notification_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_EVENT_XML_CONFIG}}, meck:expect(erlcloud_httpc, request, fun("", _, _, _, _, _) -> Response end), ?_assertEqual(?S3_BUCKET_EVENTS_LIST, erlcloud_s3:get_bucket_attribute("BucketName", notification, config())). get_bucket_notification_no_prefix_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_EVENT_XML_CONFIG_NO_PREFIX}}, meck:expect(erlcloud_httpc, request, fun("", _, _, _, _, _) -> Response end), ?_assertEqual(?S3_BUCKET_EVENTS_LIST_NO_PREFIX, erlcloud_s3:get_bucket_attribute("BucketName", notification, config())). get_bucket_notification_no_suffix_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_EVENT_XML_CONFIG_NO_SUFFIX}}, meck:expect(erlcloud_httpc, request, fun("", _, _, _, _, _) -> Response end), ?_assertEqual(?S3_BUCKET_EVENTS_LIST_NO_SUFFIX, erlcloud_s3:get_bucket_attribute("BucketName", notification, config())). get_bucket_policy_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_policy("BucketName", config()), ?_assertEqual({ok, "TestBody"}, Result). put_object_tests(_) -> Response = {ok, {{200, "OK"}, [{"x-amz-version-id", "version_id"}], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Result = erlcloud_s3:put_object("BucketName", "Key", "Data", config()), ?_assertEqual([{version_id, "version_id"} ,{"x-amz-version-id", "version_id"} ], Result). dns_compliant_name_tests(_) -> [?_assertEqual(true, erlcloud_util:is_dns_compliant_name("goodname123")), ?_assertEqual(true, erlcloud_util:is_dns_compliant_name("good.name")), ?_assertEqual(true, erlcloud_util:is_dns_compliant_name("good-name")), ?_assertEqual(true, erlcloud_util:is_dns_compliant_name("good--name")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name("Bad.name")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name("badname.")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name(".bad.name")), ?_assertEqual(false, erlcloud_util:is_dns_compliant_name("bad.name--"))]. error_handling_no_retry() -> Response = {ok, {{500, "Internal Server Error"}, [], <<"TestBody">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_policy("BucketName", config()), ?_assertEqual({error,{http_error,500,"Internal Server Error",<<"TestBody">>}}, Result). error_handling_default_retry() -> Response1 = {ok, {{500, "Internal Server Error"}, [], <<"TestBody">>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "BucketName", config(#aws_config{retry = fun erlcloud_retry:default_retry/1})), ?_assertEqual({ok, "TestBody"}, Result). error_handling_httpc_error() -> Response1 = {error, timeout}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "BucketName", config(#aws_config{retry = fun erlcloud_retry:default_retry/1})), ?_assertEqual({ok, "TestBody"}, Result). error_handling_redirect_message() -> Response1 = {ok, {{307,"Temporary Redirect"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>bucket.name.s3.eu-central-1.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). error_handling_redirect_location() -> Response1 = {ok, {{301,"Temporary Redirect"}, [{"server","AmazonS3"}, {"date","Wed, 22 Jul 2015 09:58:03 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"location", "-test-frankfurt.s3.eu-central-1.amazonaws.com/"}, {"x-amz-id-2", "YIgyI9Lb9I/dMpDrRASSD8w5YsNAyhRlF+PDF0jlf9Hq6eVLvSkuj+ftZI2RmU5eXnOKW1Wqh20="}, {"x-amz-request-id","FAECC30C2CD53BCA"} ], <<>>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). error_handling_redirect_bucket_region() -> Response1 = {ok, {{301,"Temporary Redirect"}, [{"server","AmazonS3"}, {"date","Wed, 22 Jul 2015 09:58:03 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"x-amz-id-2", "YIgyI9Lb9I/dMpDrRASSD8w5YsNAyhRlF+PDF0jlf9Hq6eVLvSkuj+ftZI2RmU5eXnOKW1Wqh20="}, {"x-amz-request-id","FAECC30C2CD53BCA"}, {"x-amz-bucket-region","us-west-1"} ], <<>>}}, Response2 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). error_handling_redirect_error() -> Response1 = {ok, {{301,"Temporary Redirect"}, [{"server","AmazonS3"}, {"date","Wed, 22 Jul 2015 09:58:03 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"x-amz-id-2", "YIgyI9Lb9I/dMpDrRASSD8w5YsNAyhRlF+PDF0jlf9Hq6eVLvSkuj+ftZI2RmU5eXnOKW1Wqh20="}, {"x-amz-request-id","FAECC30C2CD53BCA"}, {"x-amz-bucket-region","us-west-1"} ], <<>>}}, Response2 = {ok,{{404,"Not Found"}, [{"server","AmazonS3"}, {"date","Tue, 25 Aug 2015 17:49:02 GMT"}, {"transfer-encoding","chunked"}, {"content-type","application/xml"}, {"x-amz-id-2", "yjPxn58opjPoTJNIm5sPRjFrRlg4c50Ef9hT1m2nPvamKnr7nePMzKN4gStUSTtf0yp6+b/dzrA="}, {"x-amz-request-id","5DE771B2AD75F413"}], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>NoSuchBucketPolicy</Code><Message>The bu">>}}, Response3 = {ok, {{301,"Moved Permanently"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>s3.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2]), Result1 = erlcloud_s3:get_bucket_policy( "bucket.name", config()), meck:sequence(erlcloud_httpc, request, 6, [Response1]), Result2 = erlcloud_s3:get_bucket_policy( "bucket.name", config(#aws_config{s3_follow_redirect = false})), meck:sequence(erlcloud_httpc, request, 6, [Response3, Response2]), Result3 = erlcloud_s3:get_bucket_policy( "bucket.name", config(#aws_config{s3_follow_redirect = true})), [?_assertMatch({error,{http_error,404,"Not Found",_}}, Result1), ?_assertMatch({error,{http_error,301,"Temporary Redirect",_}}, Result2), ?_assertMatch({error,{http_error,404,"Not Found",_}}, Result3)]. Handle two sequential redirects . error_handling_double_redirect() -> Response1 = {ok, {{301,"Moved Permanently"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>s3.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, Response2 = {ok, {{307,"Temporary Redirect"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>TemporaryRedirect</Code>" "<Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message>" "<Bucket>bucket.name</Bucket>" "<Endpoint>bucket.name.s3.eu-central-1.amazonaws.com</Endpoint>" "<RequestId>5B157C1FD7B351A9</RequestId>" "<HostId>IbIGCfmLGzCxQ14C14VuqbjzLjWZ61M1xF3y9ovUu/j/Qj//BXsrbsAuYQJN//FARyvYtOmj8K0=</HostId></Error>">>}}, Response3 = {ok, {{200, "OK"}, [], <<"TestBody">>}}, meck:sequence(erlcloud_httpc, request, 6, [Response1, Response2, Response3]), Result = erlcloud_s3:get_bucket_policy( "bucket.name", config()), ?_assertEqual({ok, "TestBody"}, Result). error_handling_tests(_) -> [error_handling_no_retry(), error_handling_default_retry(), error_handling_httpc_error(), error_handling_redirect_message(), error_handling_redirect_location(), error_handling_redirect_bucket_region(), error_handling_redirect_error(), error_handling_double_redirect() ]. Bucket Inventory tests list_inventory_configurations_test(_)-> Response = {ok, {{200, "OK"}, [], <<" <ListInventoryConfigurationsResult xmlns=\"-03-01/\"> <InventoryConfiguration> <Id>report1</Id> <IsEnabled>true</IsEnabled> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::destination-bucket</Bucket> <Prefix>prefix1</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <Filter> <Prefix>prefix/One</Prefix> </Filter> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration> <InventoryConfiguration> <Id>report2</Id> <IsEnabled>true</IsEnabled> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::bucket2</Bucket> <Prefix>prefix2</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <Filter> <Prefix>prefix/Two</Prefix> </Filter> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration> <InventoryConfiguration> <Id>report3</Id> <IsEnabled>true</IsEnabled> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::bucket3</Bucket> <Prefix>prefix3</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <Filter> <Prefix>prefix/Three</Prefix> </Filter> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration> <IsTruncated>false</IsTruncated> </ListInventoryConfigurationsResult> ">>}}, ExpectedResult = {ok, [ {inventory_configuration, [ [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "prefix/One"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], [ {id, "report2"}, {is_enabled, "true"}, {filter, [{prefix, "prefix/Two"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::bucket2"}, {prefix, "prefix2"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], [ {id, "report3"}, {is_enabled, "true"}, {filter, [{prefix, "prefix/Three"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::bucket3"}, {prefix, "prefix3"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ] ]} ]}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:list_bucket_inventory("BucketName", config()), ?_assertEqual( ExpectedResult, Result). get_inventory_configuration_test(_) -> Response = {ok, {{200, "OK"}, [], <<" <InventoryConfiguration xmlns=\"-03-01/\"> <Id>report1</Id> <IsEnabled>true</IsEnabled> <Filter> <Prefix>filterPrefix</Prefix> </Filter> <Destination> <S3BucketDestination> <Format>CSV</Format> <AccountId>123456789012</AccountId> <Bucket>arn:aws:s3:::destination-bucket</Bucket> <Prefix>prefix1</Prefix> </S3BucketDestination> </Destination> <Schedule> <Frequency>Daily</Frequency> </Schedule> <IncludedObjectVersions>All</IncludedObjectVersions> <OptionalFields> <Field>Size</Field> <Field>LastModifiedDate</Field> <Field>ETag</Field> <Field>StorageClass</Field> <Field>IsMultipartUploaded</Field> <Field>ReplicationStatus</Field> </OptionalFields> </InventoryConfiguration>">>}}, ExpectedResult = {ok, [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "filterPrefix"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ]}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_inventory("BucketName", "report1", config()), ?_assertEqual( ExpectedResult, Result). encode_inventory_test(_)-> ExpectedXml = "<?xml version=\"1.0\"?>" "<InventoryConfiguration xmlns=\"-03-01/\">" "<Id>report1</Id>" "<IsEnabled>true</IsEnabled>" "<Filter>" "<Prefix>filterPrefix</Prefix>" "</Filter>" "<Destination>" "<S3BucketDestination>" "<Format>CSV</Format>" "<AccountId>123456789012</AccountId>" "<Bucket>arn:aws:s3:::destination-bucket</Bucket>" "<Prefix>prefix1</Prefix>" "</S3BucketDestination>" "</Destination>" "<Schedule>" "<Frequency>Daily</Frequency>" "</Schedule>" "<IncludedObjectVersions>All</IncludedObjectVersions>" "<OptionalFields>" "<Field>Size</Field>" "<Field>LastModifiedDate</Field>" "<Field>ETag</Field>" "<Field>StorageClass</Field>" "<Field>IsMultipartUploaded</Field>" "<Field>ReplicationStatus</Field>" "</OptionalFields>" "</InventoryConfiguration>", Inventory = [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "filterPrefix"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], Result = erlcloud_s3:encode_inventory(Inventory), ?_assertEqual(ExpectedXml, Result). put_bucket_inventory_test(_) -> Response = {ok, { {200,"OK"}, [ {"server","AmazonS3"}, {"content-length","0"}, {"date","Mon, 31 Oct 2016 12:00:00 GMT"}, {"x-amz-request-id","236A8905248E5A01"}, {"x-amz-id-2", "YgIPIfBiKa2bj0KMg95r/0zo3emzU4dzsD4rcKCHQUAdQkf3ShJTOOpXUueF6QKo"} ], <<>> } }, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Inventory = [ {id, "report1"}, {is_enabled, "true"}, {filter, [{prefix, "filterPrefix"}]}, {destination, [{s3_bucket_destination, [ {format, "CSV"}, {account_id, "123456789012"}, {bucket, "arn:aws:s3:::destination-bucket"}, {prefix, "prefix1"}]}] }, {schedule, [{frequency, "Daily"}]}, {included_object_versions, "All"}, {optional_fields, [ {field, [ "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "ReplicationStatus" ]} ]} ], Result = erlcloud_s3:put_bucket_inventory("BucketName", Inventory, config()), ?_assertEqual(ok, Result). delete_bucket_inventory_test(_) -> Response = {ok, { {204,"No Content"}, [ {"server","AmazonS3"}, {"date","Wed, 14 May 2014 02:11:22 GMT"}, {"x-amz-request-id","0CF038E9BCF63097"}, {"x-amz-id-2", "0FmFIWsh/PpBuzZ0JFRC55ZGVmQW4SHJ7xVDqKwhEdJmf3q63RtrvH8ZuxW1Bol5"} ], <<>> } }, meck:expect(erlcloud_httpc, request, httpc_expect(delete, Response)), Result = erlcloud_s3:delete_bucket_inventory("BucketName", "report1", config()), ?_assertEqual(ok, Result). delete_objects_batch_single_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?><DeleteResult xmlns=\"-03-01/\"><Deleted><Key>sample1.txt</Key></Deleted></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample1.txt"], config()), ?_assertEqual([{deleted,["sample1.txt"]},{error,[]}], Result). delete_objects_batch_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <DeleteResult xmlns=\"-03-01/\"><Deleted><Key>sample1.txt</Key></Deleted><Deleted><Key>sample2.txt</Key></Deleted><Deleted><Key>sample3.txt</Key></Deleted></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample1.txt","sample2.txt","sample3.txt"], config()), ?_assertEqual([{deleted,["sample1.txt", "sample2.txt","sample3.txt"]},{error,[]}], Result). delete_objects_batch_with_err_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?><DeleteResult xmlns=\"-03-01/\"><Error><Key>sample2.txt</Key><Code>AccessDenied</Code><Message>Access Denied</Message></Error></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample2.txt"], config()), ?_assertEqual([{deleted,[]}, {error,[{"sample2.txt","AccessDenied","Access Denied"}]}], Result). delete_objects_batch_mixed_tests(_) -> Response = {ok, {{200, "OK"}, [], <<"<?xml version=\"1.0\" encoding=\"UTF-8\"?><DeleteResult xmlns=\"-03-01/\"><Deleted><Key>sample1.txt</Key></Deleted><Error><Key>sample2.txt</Key><Code>AccessDenied</Code><Message>Access Denied</Message></Error></DeleteResult>">>}}, meck:expect(erlcloud_httpc, request, httpc_expect(post, Response)), Result = erlcloud_s3:delete_objects_batch("BucketName",["sample2.txt"], config()), ?_assertEqual([{deleted,["sample1.txt"]}, {error,[{"sample2.txt","AccessDenied","Access Denied"}]}], Result). put_bucket_encryption_test(_) -> Response = {ok, {{201, "Created"}, [], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Cfg = config(), KMSKey = "arn:aws:kms:us-east-1:1234/5678example", Result1 = erlcloud_s3:put_bucket_encryption("bucket", "AES256", Cfg), Result2 = erlcloud_s3:put_bucket_encryption("bucket", "aws:kms", KMSKey, Cfg), [ ?_assertEqual(ok, Result1), ?_assertEqual(ok, Result2) ]. get_bucket_encryption_test(_) -> Response = {ok, {{200, "OK"}, [], ?S3_BUCKET_ENCRYPTION}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_encryption("bucket", config()), ?_assertEqual( {ok, [{sse_algorithm, "aws:kms"}, {kms_master_key_id, "arn:aws:kms:us-east-1:1234/5678example"}]}, Result ). get_bucket_encryption_not_found_test(_) -> Response = {ok, {{404, "Not Found"}, [], ?S3_BUCKET_ENCRYPTION_NOT_FOUND}}, meck:expect(erlcloud_httpc, request, httpc_expect(Response)), Result = erlcloud_s3:get_bucket_encryption("bucket", config()), ?_assertEqual( {error, {http_error, 404, "Not Found", ?S3_BUCKET_ENCRYPTION_NOT_FOUND}}, Result ). delete_bucket_encryption_test(_) -> Response = {ok, {{204, "No Content"}, [], <<>>}}, meck:expect(erlcloud_httpc, request, httpc_expect(delete, Response)), Result = erlcloud_s3:delete_bucket_encryption("bucket", config()), ?_assertEqual(ok, Result). hackney_proxy_put_validation_test(_) -> Response = {ok, {{200, "OK"}, [{"x-amz-version-id", "version_id"}], <<>>}}, Config2 = #aws_config{hackney_client_options = #hackney_client_options{insecure = false, proxy = <<"10.10.10.10">>, proxy_auth = {<<"AAAA">>, <<"BBBB">>}}, http_client = hackney}, meck:expect(erlcloud_httpc, request, httpc_expect(put, Response)), Result = erlcloud_s3:put_object("BucketName", "Key", "Data", config(Config2)), ?_assertEqual([{version_id, "version_id"} ,{"x-amz-version-id", "version_id"} ], Result). get_bucket_and_key(_) -> ErlcloudS3ExportExample = "", Result = erlcloud_s3:get_bucket_and_key(ErlcloudS3ExportExample), ?_assertEqual({"some_bucket","path_to_file"}, Result).
e3a5867f3a8e1eacd4475b93b08982f2415bb4e66e49bc4005e3bc1cdabc816c
pedestal/pedestal-app
tracking_map.cljs
Copyright 2013 Relevance , Inc. ; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( ) ; which can be found in the file epl-v10.html at the root of this distribution. ; ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; ; You must not remove this notice, or any other, from this software. (ns io.pedestal.app.data.tracking-map (:require [io.pedestal.app.data.change :as chg])) (declare plain-map merge-when-tracking-map record-change) (deftype TrackingMap [basis map change-map] Object (toString [_] (pr-str map)) IWithMeta (-with-meta [_ meta] (TrackingMap. basis (-with-meta map meta) change-map)) IMeta (-meta [_] (-meta map)) ICollection (-conj [coll entry] (if (vector? entry) (-assoc coll (-nth entry 0) (-nth entry 1)) (reduce -conj coll entry))) IEmptyableCollection (-empty [_] (-empty map)) IEquiv (-equiv [_ other] (-equiv map other)) IHash (-hash [_] (-hash map)) ISeqable (-seq [_] (-seq map)) ICounted (-count [_] (-count map)) ILookup (-lookup [coll k] (-lookup coll k nil)) (-lookup [_ k not-found] (if-let [v (-lookup map k)] (cond (instance? TrackingMap v) (TrackingMap. basis (.-map v) (update-in change-map [:context] (fnil conj []) k)) (map? v) (TrackingMap. basis v (update-in change-map [:context] (fnil conj []) k)) :else v) not-found)) IAssociative (-assoc [_ k v] (TrackingMap. basis (-assoc map k (plain-map v)) (record-change :assoc map k v change-map))) (-contains-key? [_ k] (-contains-key? map k)) IMap (-dissoc [_ k] (TrackingMap. basis (-dissoc map k) (record-change :dissoc map k nil change-map))) IKVReduce (-kv-reduce [_ f init] (-kv-reduce map f init)) IFn (-invoke [_ k] (-lookup map k)) (-invoke [_ k not-found] (-lookup map k not-found)) IEditableCollection (-as-transient [_] (-as-transient map)) IDeref (-deref [o] map)) (defn- plain-map [m] (if (instance? TrackingMap m) (.-map m) m)) (defn- merge-when-tracking-map [change-map tracking-map] (merge-with (comp set concat) change-map (dissoc (when (instance? TrackingMap tracking-map) (.-change-map tracking-map)) :context))) (defn- record-change [action map key val change-map] (let [{:keys [context updated] :as cs} change-map change (if (seq context) (conj context key) [key]) cs (cond (= action :dissoc) (update-in cs [:removed] (fnil conj #{}) change) (and (get map key) (not= (get map key) (plain-map val))) (update-in cs [:updated] (fnil conj #{}) change) (not (get map key)) (update-in cs [:added] (fnil conj #{}) change) :else cs) cs (cond (and (= action :assoc) (map? val) (not (instance? TrackingMap val))) (update-in cs [:inspect] (fnil conj #{}) change) (and (= action :assoc) (nil? val)) (update-in cs [:inspect] (fnil conj #{}) change) :else cs)] (merge-when-tracking-map cs val))) (defn changes [v] (when (instance? TrackingMap v) (chg/compact (.-basis v) (.-map v) (.-change-map v)))) (defn tracking-map [map] (TrackingMap. map map {}))
null
https://raw.githubusercontent.com/pedestal/pedestal-app/509ab766a54921c0fbb2dd7c6a3cb20223b8e1a1/app/src/io/pedestal/app/data/tracking_map.cljs
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright 2013 Relevance , Inc. Eclipse Public License 1.0 ( ) (ns io.pedestal.app.data.tracking-map (:require [io.pedestal.app.data.change :as chg])) (declare plain-map merge-when-tracking-map record-change) (deftype TrackingMap [basis map change-map] Object (toString [_] (pr-str map)) IWithMeta (-with-meta [_ meta] (TrackingMap. basis (-with-meta map meta) change-map)) IMeta (-meta [_] (-meta map)) ICollection (-conj [coll entry] (if (vector? entry) (-assoc coll (-nth entry 0) (-nth entry 1)) (reduce -conj coll entry))) IEmptyableCollection (-empty [_] (-empty map)) IEquiv (-equiv [_ other] (-equiv map other)) IHash (-hash [_] (-hash map)) ISeqable (-seq [_] (-seq map)) ICounted (-count [_] (-count map)) ILookup (-lookup [coll k] (-lookup coll k nil)) (-lookup [_ k not-found] (if-let [v (-lookup map k)] (cond (instance? TrackingMap v) (TrackingMap. basis (.-map v) (update-in change-map [:context] (fnil conj []) k)) (map? v) (TrackingMap. basis v (update-in change-map [:context] (fnil conj []) k)) :else v) not-found)) IAssociative (-assoc [_ k v] (TrackingMap. basis (-assoc map k (plain-map v)) (record-change :assoc map k v change-map))) (-contains-key? [_ k] (-contains-key? map k)) IMap (-dissoc [_ k] (TrackingMap. basis (-dissoc map k) (record-change :dissoc map k nil change-map))) IKVReduce (-kv-reduce [_ f init] (-kv-reduce map f init)) IFn (-invoke [_ k] (-lookup map k)) (-invoke [_ k not-found] (-lookup map k not-found)) IEditableCollection (-as-transient [_] (-as-transient map)) IDeref (-deref [o] map)) (defn- plain-map [m] (if (instance? TrackingMap m) (.-map m) m)) (defn- merge-when-tracking-map [change-map tracking-map] (merge-with (comp set concat) change-map (dissoc (when (instance? TrackingMap tracking-map) (.-change-map tracking-map)) :context))) (defn- record-change [action map key val change-map] (let [{:keys [context updated] :as cs} change-map change (if (seq context) (conj context key) [key]) cs (cond (= action :dissoc) (update-in cs [:removed] (fnil conj #{}) change) (and (get map key) (not= (get map key) (plain-map val))) (update-in cs [:updated] (fnil conj #{}) change) (not (get map key)) (update-in cs [:added] (fnil conj #{}) change) :else cs) cs (cond (and (= action :assoc) (map? val) (not (instance? TrackingMap val))) (update-in cs [:inspect] (fnil conj #{}) change) (and (= action :assoc) (nil? val)) (update-in cs [:inspect] (fnil conj #{}) change) :else cs)] (merge-when-tracking-map cs val))) (defn changes [v] (when (instance? TrackingMap v) (chg/compact (.-basis v) (.-map v) (.-change-map v)))) (defn tracking-map [map] (TrackingMap. map map {}))
8c941459252b4483c27a75f9cf50589c7d6818a5a0527fda7ee881bc67f950e1
jumarko/clojure-experiments
day_02.clj
(ns clojure-experiments.advent-of-code.advent-2022.day-02 " Input: " (:require [clojure-experiments.advent-of-code.advent-2022.utils :as utils] [clojure.string :as str])) (def input (->> (utils/read-input "02") (map #(str/split % #" ")))) Puzzle 1 (def mapping {"A" :rock "B" :paper "C" :scissors "X" :rock "Y" :paper "Z" :scissors}) (def rules {:rock {:paper :lost :scissors :win} :paper {:rock :win :scissors :lost} :scissors {:paper :win :rock :lost}}) (def points {:rock 1 :paper 2 :scissors 3 :lost 0 :draw 3 :win 6}) ;; first, try to get points for the outcome of a round (->> (first input) (map mapping) ;; => (:scissors :rock) (get-in rules) ;; => :lost points) ;; => 0 ;; ... but that isn't enough because we also need points for the shape we selected (->> (first input) (map mapping) ;; => (:scissors :rock) ((juxt first #(get-in rules %))) ;; => [:scissors :lost] (map points) = > ( 3 0 ) ) ;; That's good - now ecanpsulate the logic in a function and run it for all the rounds (defn score-round [round] (->> round (map mapping) ((juxt first #(get-in rules %))) (map points))) ;; just sanity check (assert (= [3 0] (score-round (first input)))) (take 10 (map score-round input )) = > ( ( 3 0 ) ( 3 0 ) ( 3 0 ) ( 1 6 ) ( 3 0 ) ( 3 0 ) ( 1 0 ) ( 2 6 ) ( 2 nil ) ( 2 0 ) ) ( 2 nil ) above is suspicious - let 's debug it ( just put a breakpoint or prn in the function ) (score-round (nth input 8)) ;; ... Oh yeah, the input is "B" "Y" which means (:paper :paper) ;; I don't have such combination in `rules` => let's fix it! (def rules {:rock {:rock :draw :paper :lost :scissors :win} :paper {:paper :draw :rock :win :scissors :lost} :scissors {:scissors :draw :paper :win :rock :lost}}) (score-round (nth input 8)) = > ( 2 3 ) ;; that's better - let's look at more data (take 20 (map score-round input )) = > ( ( 3 0 ) ( 3 0 ) ( 3 0 ) ( 1 6 ) ( 3 0 ) ( 3 0 ) ( 1 0 ) ( 2 6 ) ( 2 3 ) ( 2 0 ) ( 3 6 ) ( 3 0 ) ( 3 0 ) ( 3 6 ) ( 2 3 ) ( 3 0 ) ( 3 6 ) ( 2 0 ) ( 3 6 ) ( 2 0 ) ) ;; looks reasonable. ;; how about computing the final score then? (defn score-round [round] (->> round (map mapping) ((juxt first #(get-in rules %))) (map points) ;; this is the new thing (apply +))) (score-round (nth input 8)) = > 5 (defn total-score [input] (apply + (map score-round input))) (def puzzle-1 (partial total-score input)) (puzzle-1) = > 11454 ;; WHOOPS - the answer is too low... let's try to figure out what's wrong... ;; refactor the function to be able to debug more easily and separate concerns (defn play [round] (->> round (map mapping) ((juxt first #(get-in rules %))))) (play (nth input 8)) ;; => [:paper :draw] (defn score-round [round] (->> (play round) (map points) ;; this is the new thing (apply +))) (assert (= 5 (score-round (nth input 8)))) ;; first try on the sample input (def sample-input [["A" "Y"] ["B" "X"] ["C" "Z"]]) (total-score sample-input) = > 15 ;; that looks correct! ;; now try to spot some odd data - especially `nil`s (->> input (map play) (filter #(some nil? %))) ;; => () ... hmmm , no nils - what else could be wrong ? ;; Back to the basics - read the text! = > the first item is what _ opponent _ is going to play , not me ! ! ! ;; So we need to fix the `play` function (defn play [round] (->> round (map mapping) notice ` second ` and ` reverse ` to flip the order ((juxt second #(get-in rules (reverse %)))))) (map mapping (first input)) ;; => (:scissors :rock) (play (first input)) ;; => [:scissors :lost] ; this is OLD result ;; => [:rock :win] ; this is NEW result ;; Let's try agin (total-score sample-input) = > 15 ; still the same (assert (= 14069 (puzzle-1))) = > 14069 ; CORRECT ! ! ! Part 2 : " Anyway , the second column says how the round needs to end : ;;; - X means you need to lose, ;;; - Y means you need to end the round in a draw, ;;; - and Z means you need to win. Good luck!" (def mapping {"A" :rock "B" :paper "C" :scissors "X" :lost "Y" :draw "Z" :win}) (map mapping (first input)) ;; => (:scissors :lost) ;; TODO: this duplicates the knowledge in `rules` to some extent ;; I found this to be the easiest approach but there should be an alternative (def rules2 {:rock {:lost :scissors :win :paper :draw :rock} :paper {:lost :rock :win :scissors :draw :paper} :scissors {:lost :paper :win :rock :draw :scissors}}) ;; compare to rules: (comment (def rules {:rock {:rock :draw :paper :lost :scissors :win} :paper {:paper :draw :rock :win :scissors :lost} ... so I could actually flip it and simply the ` play ` ( puzzle 1 ) function too ! ? :scissors {:scissors :draw :paper :win :rock :lost}}) ) (defn find-shape [[opponents-shape outcome]] (get-in rules2 [opponents-shape outcome])) (find-shape (map mapping (first input))) ;; => :paper (defn play2 [round] (->> round (map mapping) ` second ` returns the outcome , the other function finds the shape to play based on that ((juxt second find-shape)))) these functions stay the same but need to use ` play2 ` (defn score-round2 [round] (->> (play2 round) (map points) (apply +))) (defn total-score2 [input] (apply + (map score-round2 input))) (play2 (first input)) ;; => [:lost :paper] (score-round2 (first input)) = > 2 (map play2 sample-input) ;; => ([:draw :rock] [:lost :rock] [:win :rock]) (assert (= 12 (total-score2 sample-input))) (assert (= 12411 (total-score2 input)))
null
https://raw.githubusercontent.com/jumarko/clojure-experiments/cee85d5a927d81983152ad9a8ff479466bc8ed34/src/clojure_experiments/advent_of_code/advent_2022/day_02.clj
clojure
first, try to get points for the outcome of a round => (:scissors :rock) => :lost => 0 ... but that isn't enough because we also need points for the shape we selected => (:scissors :rock) => [:scissors :lost] That's good - now ecanpsulate the logic in a function and run it for all the rounds just sanity check ... Oh yeah, the input is "B" "Y" which means (:paper :paper) I don't have such combination in `rules` => let's fix it! that's better - let's look at more data looks reasonable. how about computing the final score then? this is the new thing WHOOPS - the answer is too low... let's try to figure out what's wrong... refactor the function to be able to debug more easily and separate concerns => [:paper :draw] this is the new thing first try on the sample input that looks correct! now try to spot some odd data - especially `nil`s => () Back to the basics - read the text! So we need to fix the `play` function => (:scissors :rock) => [:scissors :lost] ; this is OLD result => [:rock :win] ; this is NEW result Let's try agin still the same CORRECT ! ! ! - X means you need to lose, - Y means you need to end the round in a draw, - and Z means you need to win. Good luck!" => (:scissors :lost) TODO: this duplicates the knowledge in `rules` to some extent I found this to be the easiest approach but there should be an alternative compare to rules: => :paper => [:lost :paper] => ([:draw :rock] [:lost :rock] [:win :rock])
(ns clojure-experiments.advent-of-code.advent-2022.day-02 " Input: " (:require [clojure-experiments.advent-of-code.advent-2022.utils :as utils] [clojure.string :as str])) (def input (->> (utils/read-input "02") (map #(str/split % #" ")))) Puzzle 1 (def mapping {"A" :rock "B" :paper "C" :scissors "X" :rock "Y" :paper "Z" :scissors}) (def rules {:rock {:paper :lost :scissors :win} :paper {:rock :win :scissors :lost} :scissors {:paper :win :rock :lost}}) (def points {:rock 1 :paper 2 :scissors 3 :lost 0 :draw 3 :win 6}) (->> (first input) (map mapping) (get-in rules) points) (->> (first input) (map mapping) ((juxt first #(get-in rules %))) (map points) = > ( 3 0 ) ) (defn score-round [round] (->> round (map mapping) ((juxt first #(get-in rules %))) (map points))) (assert (= [3 0] (score-round (first input)))) (take 10 (map score-round input )) = > ( ( 3 0 ) ( 3 0 ) ( 3 0 ) ( 1 6 ) ( 3 0 ) ( 3 0 ) ( 1 0 ) ( 2 6 ) ( 2 nil ) ( 2 0 ) ) ( 2 nil ) above is suspicious - let 's debug it ( just put a breakpoint or prn in the function ) (score-round (nth input 8)) (def rules {:rock {:rock :draw :paper :lost :scissors :win} :paper {:paper :draw :rock :win :scissors :lost} :scissors {:scissors :draw :paper :win :rock :lost}}) (score-round (nth input 8)) = > ( 2 3 ) (take 20 (map score-round input )) = > ( ( 3 0 ) ( 3 0 ) ( 3 0 ) ( 1 6 ) ( 3 0 ) ( 3 0 ) ( 1 0 ) ( 2 6 ) ( 2 3 ) ( 2 0 ) ( 3 6 ) ( 3 0 ) ( 3 0 ) ( 3 6 ) ( 2 3 ) ( 3 0 ) ( 3 6 ) ( 2 0 ) ( 3 6 ) ( 2 0 ) ) (defn score-round [round] (->> round (map mapping) ((juxt first #(get-in rules %))) (map points) (apply +))) (score-round (nth input 8)) = > 5 (defn total-score [input] (apply + (map score-round input))) (def puzzle-1 (partial total-score input)) (puzzle-1) = > 11454 (defn play [round] (->> round (map mapping) ((juxt first #(get-in rules %))))) (play (nth input 8)) (defn score-round [round] (->> (play round) (map points) (apply +))) (assert (= 5 (score-round (nth input 8)))) (def sample-input [["A" "Y"] ["B" "X"] ["C" "Z"]]) (total-score sample-input) = > 15 (->> input (map play) (filter #(some nil? %))) ... hmmm , no nils - what else could be wrong ? = > the first item is what _ opponent _ is going to play , not me ! ! ! (defn play [round] (->> round (map mapping) notice ` second ` and ` reverse ` to flip the order ((juxt second #(get-in rules (reverse %)))))) (map mapping (first input)) (play (first input)) (total-score sample-input) (assert (= 14069 (puzzle-1))) Part 2 : " Anyway , the second column says how the round needs to end : (def mapping {"A" :rock "B" :paper "C" :scissors "X" :lost "Y" :draw "Z" :win}) (map mapping (first input)) (def rules2 {:rock {:lost :scissors :win :paper :draw :rock} :paper {:lost :rock :win :scissors :draw :paper} :scissors {:lost :paper :win :rock :draw :scissors}}) (comment (def rules {:rock {:rock :draw :paper :lost :scissors :win} :paper {:paper :draw :rock :win :scissors :lost} ... so I could actually flip it and simply the ` play ` ( puzzle 1 ) function too ! ? :scissors {:scissors :draw :paper :win :rock :lost}}) ) (defn find-shape [[opponents-shape outcome]] (get-in rules2 [opponents-shape outcome])) (find-shape (map mapping (first input))) (defn play2 [round] (->> round (map mapping) ` second ` returns the outcome , the other function finds the shape to play based on that ((juxt second find-shape)))) these functions stay the same but need to use ` play2 ` (defn score-round2 [round] (->> (play2 round) (map points) (apply +))) (defn total-score2 [input] (apply + (map score-round2 input))) (play2 (first input)) (score-round2 (first input)) = > 2 (map play2 sample-input) (assert (= 12 (total-score2 sample-input))) (assert (= 12411 (total-score2 input)))
d6f0f3c72709477e6efe057cc04f03c97bd15ef8307d122a338d19d5d3c22421
triffon/fp-2022-23
02.sum.rkt
#lang racket (require rackunit rackunit/text-ui) # # # Зад 2 Сумата на всички числа от ` l ` (define (sum l) 'тук) (define l1 '(1 2 3 4 5 6 7 8)) (define l2 '(0 (12 13) (21 22))) (run-tests (test-suite "sum tests" (check-eq? (sum '()) 0) (check-eq? (sum l1) 36) (check-eq? (sum '(-5 5 4)) 4)) 'verbose)
null
https://raw.githubusercontent.com/triffon/fp-2022-23/56690db370b1c838170e56a4d83bc5ed55d7a785/exercises/cs2/04.scheme.lists/02.sum.rkt
racket
#lang racket (require rackunit rackunit/text-ui) # # # Зад 2 Сумата на всички числа от ` l ` (define (sum l) 'тук) (define l1 '(1 2 3 4 5 6 7 8)) (define l2 '(0 (12 13) (21 22))) (run-tests (test-suite "sum tests" (check-eq? (sum '()) 0) (check-eq? (sum l1) 36) (check-eq? (sum '(-5 5 4)) 4)) 'verbose)
645a4926a9bf9e64158df9ffb809114c7f3ec6b69ae8899928b3e8b135279972
Octachron/codept
b.ml
type t open C
null
https://raw.githubusercontent.com/Octachron/codept/2d2a95fde3f67cdd0f5a1b68d8b8b47aefef9290/tests/complex/mixed/b.ml
ocaml
type t open C
f88a744048d5916f428bee480b213186a2123d51db17b4f2f8fb1081acee61b7
apache/dubbo-erlang
userOperator.erl
-module(userOperator). -include_lib("dubboerl/include/dubbo.hrl"). -include_lib("dubboerl/include/hessian.hrl"). -define(CURRENT_CLASS_NAME,<<"org.apache.dubbo.erlang.sample.service.facade.UserOperator"/utf8>>). -define(CURRENT_CLASS_VERSION,<<"0.0.0"/utf8>>). -include("dubbo_sample_service.hrl"). %% API -export([ getUserInfo/1, getUserInfo/2, genUserId/0, genUserId/1, queryUserInfo/1, queryUserInfo/2, queryUserList/1, queryUserList/2]). -export([get_method_999_list/0]). %% behaviour -callback getUserInfo(Arg0::list())-> #userInfo{}. -callback genUserId()-> list(). -callback queryUserInfo(Arg0::#userInfoRequest{})-> #userInfo{}. -callback queryUserList(Arg0::list())-> #userRes{}. get_method_999_list()-> [ getUserInfo, genUserId, queryUserInfo, queryUserList]. -spec getUserInfo(Arg0::list())-> {ok,reference()}| {ok,reference(),Data::#userInfo{},RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. getUserInfo(Arg0)-> getUserInfo(Arg0 ,#{}). getUserInfo(Arg0, RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"getUserInfo">>, parameterDesc = <<"Ljava/lang/String;"/utf8>>, parameterTypes = [ #type_def{foreign_type = <<"java.lang.String">>, native_type = string, fieldnames = []} ], parameters = [ Arg0 ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption). -spec genUserId()-> {ok,reference()}| {ok,reference(),Data::list(),RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. genUserId()-> genUserId( #{}). genUserId( RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"genUserId">>, parameterDesc = <<""/utf8>>, parameterTypes = [ ], parameters = [ ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption). -spec queryUserInfo(Arg0::#userInfoRequest{})-> {ok,reference()}| {ok,reference(),Data::#userInfo{},RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. queryUserInfo(Arg0)-> queryUserInfo(Arg0 ,#{}). queryUserInfo(Arg0, RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"queryUserInfo">>, parameterDesc = <<"Lorg/apache/dubbo/erlang/sample/service/bean/UserInfoRequest;"/utf8>>, parameterTypes = [ #type_def{foreign_type = <<"org.apache.dubbo.erlang.sample.service.bean.UserInfoRequest">>, native_type = userInfoRequest, fieldnames = record_info(fields,userInfoRequest)} ], parameters = [ Arg0 ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption). -spec queryUserList(Arg0::list())-> {ok,reference()}| {ok,reference(),Data::#userRes{},RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. queryUserList(Arg0)-> queryUserList(Arg0 ,#{}). queryUserList(Arg0, RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"queryUserList">>, parameterDesc = <<"Ljava/lang/String;"/utf8>>, parameterTypes = [ #type_def{foreign_type = <<"java.lang.String">>, native_type = string, fieldnames = []} ], parameters = [ Arg0 ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption).
null
https://raw.githubusercontent.com/apache/dubbo-erlang/24e0c1a9028b50d2e9e05e3fe26f4e3335384acc/samples/dubboerl_demo/apps/dubbo_sample_service/src/userOperator.erl
erlang
API behaviour
-module(userOperator). -include_lib("dubboerl/include/dubbo.hrl"). -include_lib("dubboerl/include/hessian.hrl"). -define(CURRENT_CLASS_NAME,<<"org.apache.dubbo.erlang.sample.service.facade.UserOperator"/utf8>>). -define(CURRENT_CLASS_VERSION,<<"0.0.0"/utf8>>). -include("dubbo_sample_service.hrl"). -export([ getUserInfo/1, getUserInfo/2, genUserId/0, genUserId/1, queryUserInfo/1, queryUserInfo/2, queryUserList/1, queryUserList/2]). -export([get_method_999_list/0]). -callback getUserInfo(Arg0::list())-> #userInfo{}. -callback genUserId()-> list(). -callback queryUserInfo(Arg0::#userInfoRequest{})-> #userInfo{}. -callback queryUserList(Arg0::list())-> #userRes{}. get_method_999_list()-> [ getUserInfo, genUserId, queryUserInfo, queryUserList]. -spec getUserInfo(Arg0::list())-> {ok,reference()}| {ok,reference(),Data::#userInfo{},RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. getUserInfo(Arg0)-> getUserInfo(Arg0 ,#{}). getUserInfo(Arg0, RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"getUserInfo">>, parameterDesc = <<"Ljava/lang/String;"/utf8>>, parameterTypes = [ #type_def{foreign_type = <<"java.lang.String">>, native_type = string, fieldnames = []} ], parameters = [ Arg0 ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption). -spec genUserId()-> {ok,reference()}| {ok,reference(),Data::list(),RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. genUserId()-> genUserId( #{}). genUserId( RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"genUserId">>, parameterDesc = <<""/utf8>>, parameterTypes = [ ], parameters = [ ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption). -spec queryUserInfo(Arg0::#userInfoRequest{})-> {ok,reference()}| {ok,reference(),Data::#userInfo{},RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. queryUserInfo(Arg0)-> queryUserInfo(Arg0 ,#{}). queryUserInfo(Arg0, RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"queryUserInfo">>, parameterDesc = <<"Lorg/apache/dubbo/erlang/sample/service/bean/UserInfoRequest;"/utf8>>, parameterTypes = [ #type_def{foreign_type = <<"org.apache.dubbo.erlang.sample.service.bean.UserInfoRequest">>, native_type = userInfoRequest, fieldnames = record_info(fields,userInfoRequest)} ], parameters = [ Arg0 ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption). -spec queryUserList(Arg0::list())-> {ok,reference()}| {ok,reference(),Data::#userRes{},RpcContent::list()}| {error,Reason::timeout|no_provider|any()}. queryUserList(Arg0)-> queryUserList(Arg0 ,#{}). queryUserList(Arg0, RequestOption)-> Data = #dubbo_rpc_invocation{ className = ?CURRENT_CLASS_NAME, classVersion = ?CURRENT_CLASS_VERSION, methodName = <<"queryUserList">>, parameterDesc = <<"Ljava/lang/String;"/utf8>>, parameterTypes = [ #type_def{foreign_type = <<"java.lang.String">>, native_type = string, fieldnames = []} ], parameters = [ Arg0 ], attachments = [ {<<"path">>, ?CURRENT_CLASS_NAME}, {<<"interface">> , ?CURRENT_CLASS_NAME} ] }, Request = dubbo_adapter:reference(Data), dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption).
81f886157eb9042545aeb3eb481de1f35b7bfc30e0c414d4687f5fafa230b91d
rtrusso/scp
sasm-util.scm
;; sasm-util.scm ;; ;; A command-line tool that is used to run the sasm analysis engine ;; on sasm source files and produce useful messages to the console. (need util/list) (need util/string) (need util/filesystem) (need util/io) (need sasm/sasm-machine) (need sasm/sasm-eval) (need sasm/sasm-interp-spec) (need sasm/sasm-tx) (need sasm/sasm-ast) (need sasm/sasm-visitor) (need sasm/sasm-analyze) (need sasm/sasm-parse) (need sasm/sasm-rewrite) (need sasm/sasm-codegen) (define *sasm-util-output-port* #f) (define (sasm-util-output-port) (if *sasm-util-output-port* *sasm-util-output-port* (current-output-port))) (define (display-symbol-list title symbols) (display title (sasm-util-output-port)) (for-each (lambda (x) (display " " (sasm-util-output-port)) (write x (sasm-util-output-port))) symbols) (newline (sasm-util-output-port))) (define (process-file file) (let ((code (read-file-fully file))) (let ((ast (sasm-parse-program code))) (if (not ast) (error "SASM parse error in file " file) (let ((externs (sasm-program-extern-symbols ast)) (defined (sasm-program-defined-symbols ast)) (referenced (sasm-program-referenced-symbols ast))) (if (not (sasm-program-analyze-symbols! "main" ast)) (error "One or more errors encountered")) (let* ((rewrite (sasm-rewrite-ast ast)) (rewrite-ast (sasm-parse-program rewrite))) (display-symbol-list ";; externs:" externs) (display-symbol-list ";; defined:" defined) (display-symbol-list ";; referenced:" referenced) (newline (sasm-util-output-port)) (newline (sasm-util-output-port)) (for-each (lambda (code) (sasm-pretty-print code (sasm-util-output-port)) (newline (sasm-util-output-port))) rewrite) )))))) (define (command-line args) (define (iter files args) (cond ((null? args) (for-each process-file (reverse files))) (else (let ((arg (car args)) (rest (cdr args))) (cond ((starts-with? arg "--out=") (set! *sasm-util-output-port* (open-output-file (string-strip-prefix arg "--out="))) (iter files rest)) (else (iter (cons arg files) rest))))))) (iter '() args)) (command-line (cdr (vector->list *argv*)))
null
https://raw.githubusercontent.com/rtrusso/scp/2051e76df14bd36aef81aba519ffafa62b260f5c/src/sasm-util.scm
scheme
sasm-util.scm A command-line tool that is used to run the sasm analysis engine on sasm source files and produce useful messages to the console.
(need util/list) (need util/string) (need util/filesystem) (need util/io) (need sasm/sasm-machine) (need sasm/sasm-eval) (need sasm/sasm-interp-spec) (need sasm/sasm-tx) (need sasm/sasm-ast) (need sasm/sasm-visitor) (need sasm/sasm-analyze) (need sasm/sasm-parse) (need sasm/sasm-rewrite) (need sasm/sasm-codegen) (define *sasm-util-output-port* #f) (define (sasm-util-output-port) (if *sasm-util-output-port* *sasm-util-output-port* (current-output-port))) (define (display-symbol-list title symbols) (display title (sasm-util-output-port)) (for-each (lambda (x) (display " " (sasm-util-output-port)) (write x (sasm-util-output-port))) symbols) (newline (sasm-util-output-port))) (define (process-file file) (let ((code (read-file-fully file))) (let ((ast (sasm-parse-program code))) (if (not ast) (error "SASM parse error in file " file) (let ((externs (sasm-program-extern-symbols ast)) (defined (sasm-program-defined-symbols ast)) (referenced (sasm-program-referenced-symbols ast))) (if (not (sasm-program-analyze-symbols! "main" ast)) (error "One or more errors encountered")) (let* ((rewrite (sasm-rewrite-ast ast)) (rewrite-ast (sasm-parse-program rewrite))) (display-symbol-list ";; externs:" externs) (display-symbol-list ";; defined:" defined) (display-symbol-list ";; referenced:" referenced) (newline (sasm-util-output-port)) (newline (sasm-util-output-port)) (for-each (lambda (code) (sasm-pretty-print code (sasm-util-output-port)) (newline (sasm-util-output-port))) rewrite) )))))) (define (command-line args) (define (iter files args) (cond ((null? args) (for-each process-file (reverse files))) (else (let ((arg (car args)) (rest (cdr args))) (cond ((starts-with? arg "--out=") (set! *sasm-util-output-port* (open-output-file (string-strip-prefix arg "--out="))) (iter files rest)) (else (iter (cons arg files) rest))))))) (iter '() args)) (command-line (cdr (vector->list *argv*)))
553b296789367fdaba3222004eae771988592ab5bcf047a3aae02160def8ea10
Stratus3D/programming_erlang_exercises
erlang_tips.erl
-module(erlang_tips). -include_lib("stdlib/include/qlc.hrl"). -record(user, {name, email, password}). -record(tip, {url, description, date}). -record(abuse, {ip_address, num_visits}). -export([all_users/0, get_user/1, add_user/3, all_tips/0, get_tip/1, add_tip/3, all_abuse/0, get_abuse/1, add_abuse/2, start_database/0, create_database/0, reset_tables/0]). % Change these if your node names are different -define(NODE_NAMES, ['node1@localhost', 'node2@localhost']). %%%=================================================================== %%% Primary API %%%=================================================================== all_users() -> % Get all users in the user table do(qlc:q([X || X <- mnesia:table(user)])). get_user(Email) -> % Select a user from the user table by email address do(qlc:q([X || X <- mnesia:table(user), X#user.email == Email])). add_user(Name, Email, Password) -> % Create a user record and store it in the database User = #user{name=Name, email=Email, password=Password}, F = fun() -> mnesia:write(User) end, mnesia:transaction(F). all_tips() -> % Get all tips in the tip table do(qlc:q([X || X <- mnesia:table(tip)])). get_tip(Url) -> % Select a tip from the tip table by url do(qlc:q([X || X <- mnesia:table(tip), X#tip.url == Url])). add_tip(Url, Description, Date) -> % Create a tip record and store it in the database Tip = #tip{url=Url, description=Description, date=Date}, F = fun() -> mnesia:write(Tip) end, mnesia:transaction(F). all_abuse() -> % Get all abuse records in the abuse table do(qlc:q([X || X <- mnesia:table(abuse)])). get_abuse(IpAddress) -> % Select an abuse record from the abuse table by IP address do(qlc:q([X || X <- mnesia:table(abuse), X#abuse.ip_address == IpAddress])). add_abuse(IpAddress, NumVisits) -> % Create an abuse record and store it in the database Abuse = #abuse{ip_address=IpAddress, num_visits=NumVisits}, F = fun() -> mnesia:write(Abuse) end, mnesia:transaction(F). start_database() -> % Get the database in a state where we can query it start_mnesia(?NODE_NAMES), mnesia:wait_for_tables([user,tip,abuse], 20000). create_database() -> % Create schema ok = mnesia:create_schema(?NODE_NAMES), % Start mnesia on every node if it's not already started start_mnesia(?NODE_NAMES), % Table Storage DiskCopies = {disc_copies, ?NODE_NAMES}, % Create tables {atomic, ok} = mnesia:create_table(user, [{attributes, record_info(fields, user)}, DiskCopies]), {atomic, ok} = mnesia:create_table(tip, [{attributes, record_info(fields, tip)}, DiskCopies]), {atomic, ok} = mnesia:create_table(abuse, [{attributes, record_info(fields, abuse)}, DiskCopies]), ok. reset_tables() -> % Empty all the tables in the database mnesia:clear_table(user), mnesia:clear_table(tip), mnesia:clear_table(abuse). %%%=================================================================== %%% Private functions %%%=================================================================== do(Q) -> F = fun() -> qlc:e(Q) end, {atomic, Val} = mnesia:transaction(F), Val. start_mnesia(Nodes) -> lists:map(fun(Node) -> ok = rpc:call(Node, mnesia, start, []) end, Nodes).
null
https://raw.githubusercontent.com/Stratus3D/programming_erlang_exercises/e4fd01024812059d338facc20f551e7dff4dac7e/chapter_20/exercise_2/erlang_tips.erl
erlang
Change these if your node names are different =================================================================== Primary API =================================================================== Get all users in the user table Select a user from the user table by email address Create a user record and store it in the database Get all tips in the tip table Select a tip from the tip table by url Create a tip record and store it in the database Get all abuse records in the abuse table Select an abuse record from the abuse table by IP address Create an abuse record and store it in the database Get the database in a state where we can query it Create schema Start mnesia on every node if it's not already started Table Storage Create tables Empty all the tables in the database =================================================================== Private functions ===================================================================
-module(erlang_tips). -include_lib("stdlib/include/qlc.hrl"). -record(user, {name, email, password}). -record(tip, {url, description, date}). -record(abuse, {ip_address, num_visits}). -export([all_users/0, get_user/1, add_user/3, all_tips/0, get_tip/1, add_tip/3, all_abuse/0, get_abuse/1, add_abuse/2, start_database/0, create_database/0, reset_tables/0]). -define(NODE_NAMES, ['node1@localhost', 'node2@localhost']). all_users() -> do(qlc:q([X || X <- mnesia:table(user)])). get_user(Email) -> do(qlc:q([X || X <- mnesia:table(user), X#user.email == Email])). add_user(Name, Email, Password) -> User = #user{name=Name, email=Email, password=Password}, F = fun() -> mnesia:write(User) end, mnesia:transaction(F). all_tips() -> do(qlc:q([X || X <- mnesia:table(tip)])). get_tip(Url) -> do(qlc:q([X || X <- mnesia:table(tip), X#tip.url == Url])). add_tip(Url, Description, Date) -> Tip = #tip{url=Url, description=Description, date=Date}, F = fun() -> mnesia:write(Tip) end, mnesia:transaction(F). all_abuse() -> do(qlc:q([X || X <- mnesia:table(abuse)])). get_abuse(IpAddress) -> do(qlc:q([X || X <- mnesia:table(abuse), X#abuse.ip_address == IpAddress])). add_abuse(IpAddress, NumVisits) -> Abuse = #abuse{ip_address=IpAddress, num_visits=NumVisits}, F = fun() -> mnesia:write(Abuse) end, mnesia:transaction(F). start_database() -> start_mnesia(?NODE_NAMES), mnesia:wait_for_tables([user,tip,abuse], 20000). create_database() -> ok = mnesia:create_schema(?NODE_NAMES), start_mnesia(?NODE_NAMES), DiskCopies = {disc_copies, ?NODE_NAMES}, {atomic, ok} = mnesia:create_table(user, [{attributes, record_info(fields, user)}, DiskCopies]), {atomic, ok} = mnesia:create_table(tip, [{attributes, record_info(fields, tip)}, DiskCopies]), {atomic, ok} = mnesia:create_table(abuse, [{attributes, record_info(fields, abuse)}, DiskCopies]), ok. reset_tables() -> mnesia:clear_table(user), mnesia:clear_table(tip), mnesia:clear_table(abuse). do(Q) -> F = fun() -> qlc:e(Q) end, {atomic, Val} = mnesia:transaction(F), Val. start_mnesia(Nodes) -> lists:map(fun(Node) -> ok = rpc:call(Node, mnesia, start, []) end, Nodes).
138cafe2e634c58c537754e853fa7037ec4181643601e1b55c898814b84061fe
realworldocaml/book
sexp_pretty_intf.ml
open! Base module type S = sig type sexp type 'a writer = Config.t -> 'a -> sexp -> unit (** [pp_formatter conf fmt sexp] will mutate the fmt with functions such as [set_formatter_tag_functions] *) val pp_formatter : Caml.Format.formatter writer val pp_formatter' : next:(unit -> sexp option) -> Config.t -> Caml.Format.formatter -> unit val pp_buffer : Buffer.t writer val pp_out_channel : Caml.out_channel writer val pp_blit : (string, unit) Blit.sub writer * [ pretty_string ] needs to allocate . If you care about performance , using one of the [ pp _ * ] functions above is advised . [pp_*] functions above is advised. *) val pretty_string : Config.t -> sexp -> string val sexp_to_string : sexp -> string end (** Pretty-printing of S-expressions *) module type Sexp_pretty = sig module Config = Config module type S = S include S with type sexp := Sexp.t module Sexp_with_layout : S with type sexp := Sexplib.Sexp.With_layout.t_or_comment module Normalize : sig type t = (* Contains a sexp with associated comments. *) | Sexp of sexp * string list | Comment of comment and comment = | Line_comment of string (* Does not contain the "#|" "|#"; contains its indentation size. *) | Block_comment of int * string list | Sexp_comment of comment list * sexp and sexp = | Atom of string | List of t list val of_sexp_or_comment : Config.t -> Sexplib.Sexp.With_layout.t_or_comment -> t end val sexp_to_sexp_or_comment : Sexp.t -> Sexplib.Sexp.With_layout.t_or_comment end
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/sexp_pretty/src/sexp_pretty_intf.ml
ocaml
* [pp_formatter conf fmt sexp] will mutate the fmt with functions such as [set_formatter_tag_functions] * Pretty-printing of S-expressions Contains a sexp with associated comments. Does not contain the "#|" "|#"; contains its indentation size.
open! Base module type S = sig type sexp type 'a writer = Config.t -> 'a -> sexp -> unit val pp_formatter : Caml.Format.formatter writer val pp_formatter' : next:(unit -> sexp option) -> Config.t -> Caml.Format.formatter -> unit val pp_buffer : Buffer.t writer val pp_out_channel : Caml.out_channel writer val pp_blit : (string, unit) Blit.sub writer * [ pretty_string ] needs to allocate . If you care about performance , using one of the [ pp _ * ] functions above is advised . [pp_*] functions above is advised. *) val pretty_string : Config.t -> sexp -> string val sexp_to_string : sexp -> string end module type Sexp_pretty = sig module Config = Config module type S = S include S with type sexp := Sexp.t module Sexp_with_layout : S with type sexp := Sexplib.Sexp.With_layout.t_or_comment module Normalize : sig type t = | Sexp of sexp * string list | Comment of comment and comment = | Line_comment of string | Block_comment of int * string list | Sexp_comment of comment list * sexp and sexp = | Atom of string | List of t list val of_sexp_or_comment : Config.t -> Sexplib.Sexp.With_layout.t_or_comment -> t end val sexp_to_sexp_or_comment : Sexp.t -> Sexplib.Sexp.With_layout.t_or_comment end
61aaad0eb9e231e48c00733605b86f778fef55ee9cf944a3e12d13ed5ddc2904
rsnikhil/Forvis_RISCV-ISA-Spec
TestHeapSafety.hs
# LANGUAGE PartialTypeSignatures , ScopedTypeVariables , TupleSections , FlexibleInstances , MultiParamTypeClasses # module TestHeapSafety where From libraries import Control.Arrow (second, (***)) import Control.Exception.Base (assert) import Control.Monad.Reader import Control.Lens hiding (elements) import Data.Bits import Data.List (zip4,unzip4) import Data.Maybe import qualified Data.List as List import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Debug.Trace import Test.QuickCheck import Text.PrettyPrint (Doc, (<+>), ($$)) import qualified Text.PrettyPrint as P -- From /src import Arch_Defs import Bit_Utils import CSR_File import Encoder import Forvis_Spec_I import Forvis_Spec_Instr_Fetch import GPR_File import Machine_State import Memory -- From . import Gen import Run_Program_PIPE import PIPE import Printing import Terminal import MachineLenses TODO : Rename to TestState to reveal abstractions with stack type TestState = MStatePair ------------------------------------------------------------------------------------ -- Printing prettyMStatePair :: PolicyPlus -> MStatePair -> Doc prettyMStatePair pplus (M (m1, p1) (m2, p2)) = let ppol = policy pplus in P.vcat [ P.text "PC:" <+> pretty pplus (f_pc m1, p_pc p1) (f_pc m2, p_pc p2) , P.text "Registers:" $$ P.nest 2 (pretty pplus (f_gprs m1, p_gprs p1) (f_gprs m2, p_gprs p2)) , P.text "Memories:" $$ P.nest 2 (pretty pplus (f_mem m1, p_mem p1) (f_mem m2, p_mem p2)) , P.text "Reachable:" <+> pretty pplus (reachable p1) (reachable p2) ] print_mstatepair :: PolicyPlus -> MStatePair -> IO () print_mstatepair pplus m = putStrLn $ P.render $ prettyMStatePair pplus m verboseTracing = False --verboseTracing = True printTrace pplus tr1 tr2 = putStrLn $ P.render $ prettyTrace pplus tr1 tr2 prettyTrace :: PolicyPlus -> [(Machine_State, PIPE_State)] -> [(Machine_State, PIPE_State)] -> Doc prettyTrace pplus [] [] = P.empty prettyTrace pplus [(m1,p1)] [(m2,p2)] = prettyMStatePair pplus (M (m1,p1) (m2,p2)) prettyTrace pplus (tr1@((m1,p1):_)) (tr2@((m2,p2):_)) = prettyMStatePair pplus (M (m1,p1) (m2,p2)) $$ P.text "" $$ P.text "Trace:" $$ prettyDiffs pplus tr1 tr2 prettyDiffs :: PolicyPlus -> [(Machine_State, PIPE_State)] -> [(Machine_State, PIPE_State)] -> Doc prettyDiffs pplus ((m11,p11):(m12,p12):tr1) ((m21,p21):(m22,p22):tr2) = (if verboseTracing then P.text "----------------------------------------------------------------" $$ P.nest 10 (P.text "Raw Machine 1 memory:" $$ P.nest 3 (P.text (show $ f_dm $ f_mem m12))) $$ P.nest 10 (P.text "Raw Machine 1 tags:" $$ P.nest 3 (P.text (show $ p_mem p12))) $$ P.nest 10 (P.text "Raw Machine 2 memory:" $$ P.nest 3 (P.text (show $ f_dm $ f_mem m22))) $$ P.nest 10 (P.text "Raw Machine 2 tags:" $$ P.nest 3 (P.text (show $ p_mem p22))) $$ P.nest 10 (P.text "Machine 1:" $$ P.nest 3 (pretty pplus m12 p12) $$ P.text "Machine 2" $$ P.nest 3 (pretty pplus m22 p22) ) else P.empty) $$ pretty pplus (calcDiff pplus (m11,p11) (m12,p12)) (calcDiff pplus (m21,p21) (m22,p22)) $$ prettyDiffs pplus ((m12,p12):tr1) ((m22,p22):tr2) prettyDiffs pplus [(m1,p1)] [(m2,p2)] = P.text "" $$ P.text "Final:" $$ prettyMStatePair pplus (M (m1,p1) (m2,p2)) prettyDiffs _ _ _ = P.empty data Diff = Diff { d_pc :: (Integer, TagSet) -- value and tag of the current PC , d_instr :: Maybe Instr_I -- current instruction , d_reg :: [(GPR_Addr, Integer, TagSet)] -- change in registers , d_mem :: [(Integer, Integer, TagSet)] -- Change in memory } Generic " find diffs " function : Takes two association lists l1 and -- l2, both assumed sorted by their keys and both representing * infinite * maps with some default value d ( passed as third -- parameter), and returns a list of changes -- N.b . In the cases where we are returning something , we first have -- to check whether the thing we are returning is equal to d! (And -- not return it in this case.) diff :: (Ord a, Eq b) => [(a, b)] -> [(a, b)] -> b -> [(a, (b, b))] diff [] [] d = [] diff ((x1,y1):l1) [] d = (if y1==d then [] else [(x1,(y1,d))]) ++ diff l1 [] d diff [] ((x2,y2):l2) d = (if y2==d then [] else [(x2,(d,y2))]) ++ diff [] l2 d diff ((x1,y1):l1) ((x2,y2):l2) d | x1 < x2 = (if y1==d then [] else [(x1,(y1,d))]) ++ diff l1 ((x2,y2):l2) d | x1 > x2 = (if y2==d then [] else [(x2,(d,y2))]) ++ diff ((x1,y1):l1) l2 d | otherwise = (if y1==y2 then [] else [(x1,(y1,y2))]) ++ diff l1 l2 d calcDiff :: PolicyPlus -> (Machine_State, PIPE_State) -> (Machine_State, PIPE_State) -> Diff calcDiff pplus (m1,p1) (m2,p2) = Diff { d_pc = (f_pc m1, p_pc p1) , d_instr = case fst $ instr_fetch m1 of Fetch u32 -> decode_I RV32 u32 _ -> error "Bad instr fetch in calcDiff" , d_reg = let GPR_File r1 = f_gprs m1 GPR_File r2 = f_gprs m2 GPR_FileT t1 = p_gprs p1 GPR_FileT t2 = p_gprs p2 reg_diff = filter (\((i1,d1),(i2,d2)) -> assert (i1 == i2) $ d1 /= d2) (zip (Map.assocs r1) (Map.assocs r2)) tag_diff = filter (\((i1,l1),(i2,l2)) -> assert (i1 == i2) $ l1 /= l2) (zip (Map.assocs t1) (Map.assocs t2)) in case (reg_diff, tag_diff) of ([], []) -> [] ([((i,_),(_,d))],[((j,_),(_,l))]) | i == j -> [(i,d,l)] ([((i,_),(_,d))],[]) -> catMaybes [(i,d,) <$> Map.lookup i t2] ([],[((i,_),(_,l))]) -> catMaybes [(i,,l) <$> Map.lookup i r2] TODO ( ! ) error $ "More than one diff in register file:" ++ " registers = " ++ show reg_diff ++ " and tags = " ++ show tag_diff , d_mem = let Mem dm1 _ = f_mem m1 Mem dm2 _ = f_mem m2 MemT pm1 = p_mem p1 MemT pm2 = p_mem p2 both1 = map (\((i,d),(j,t)) -> assert (i==j) $ (i,(d,t))) $ zip (Map.assocs dm1) (Map.assocs pm1) both2 = map (\((i,d),(j,t)) -> assert (i==j) $ (i,(d,t))) $ zip (Map.assocs dm2) (Map.assocs pm2) diffs = diff both1 both2 (uninitialized_word, emptyInstTag pplus) extract (i,(_,(d,t))) = (i,d,t) in map extract diffs } -- data_diff = filter ( ) ) - > if i1 = = i2 then d1 /= d2 else error $ " DIFF : " + + show ( " i1 " , i1 , " d1 " , d1 , " i2 " , i2 , " d2 " , d2 , " dm1 " , dm1 , " dm2 " , dm2 ) ) -- assert ( i1 = = i2 ) $ d1 /= d2 ) -- (zip (Map.assocs dm1) (Map.assocs dm2)) -- tag_diff = -- filter (\((i1,l1),(i2,l2)) -> assert (i1 == i2) $ l1 /= l2) (zip (Map.assocs pm1) (Map.assocs pm2)) -- in case (data_diff, tag_diff) of -- ([], []) -> Nothing -- ([((i,_),(_,d))],[((j,_),(_,l))]) | i == j -> Just (i,d,l) ( [ ( ( i,_),(_,d ) ) ] , [ ] ) - > -- (i,d,) <$> Map.lookup i pm2 -- ([],[((i,_),(_,l))]) -> -- (i,,l) <$> Map.lookup i dm2 _ - > error $ " More than one diff in memory file : " + + -- " data = " ++ show data_diff ++ -- " and tags = " ++ show tag_diff prettyRegDiff pplus ((i,d,l):r1) ((i', d', l'):r2) | i == i', d == d', l == l' = (P.char 'r' P.<> P.integer i <+> P.text "<-" <+> pretty pplus d l) $$ prettyRegDiff pplus r1 r2 | otherwise = (ppStrong (P.char 'r' P.<> P.integer i <+> P.text "<-" <+> pretty pplus d l <||> P.char 'r' P.<> P.integer i' <+> P.text "<-" <+> pretty pplus d' l')) $$ prettyRegDiff pplus r1 r2 prettyRegDiff _ [] [] = P.empty TODO ( ): This can happen a lot now ... prettyRegDiff _ r1 r2 = P.text $ "<prettyRegDiff??> " ++ show (r1,r2) prettyMemDiff pplus ((i,d,l):m1) ((i', d', l'):m2) | i == i', d == d', l == l' = (P.char '[' P.<> P.integer i P.<> P.char ']' <+> P.text "<-" <+> pretty pplus d l) $$ prettyMemDiff pplus m1 m2 | otherwise = (ppStrong (P.char '[' P.<> P.integer i P.<> P.char ']' <+> P.text "<-" <+> pretty pplus d l <||> P.char '[' P.<> P.integer i' P.<> P.char ']' <+> P.text "<-" <+> pretty pplus d' l')) $$ prettyMemDiff pplus m1 m2 prettyMemDiff _ [] [] = P.empty prettyMemDiff _ _ _ = P.text "<prettyMemDiff??>" instance CoupledPP (Maybe Instr_I) (Maybe Instr_I) where pretty pplus (Just i1) (Just i2) | i1 == i2 = pp pplus i1 | otherwise = ppStrong (pp pplus i1 <||> pp pplus i2) pretty _ Nothing Nothing = P.text "<Bad instr>" instance CoupledPP Diff Diff where pretty pplus d1 d2 = P.hcat [ pad 17 (pretty pplus (d_pc d1) (d_pc d2)) , P.text " " , pad 17 (pretty pplus (d_instr d1) (d_instr d2)) , P.text " " , prettyRegDiff pplus (d_reg d1) (d_reg d2) , prettyMemDiff pplus (d_mem d1) (d_mem d2) ] -- Null "show" functions, for things that we don't want QuickCheck trying to print instance Show Machine_State where show _ = "" instance Show MStatePair where show _ = "" ------------------------------------------------------------------------------------ Reachability {- A stupid n^2 reachability algorithm for now. If we find it is too slow as memories get larger, we could improve it like this: - As we go along, maintain a set of "reachable colors" plus a map from "unreachable colors" to the addresses tagged with each of them. If an unreachable color ever becomes reachable, then add it to the reachable set and recursively traverse the things on its list. -} cellColorOf :: TagSet -> Maybe Color cellColorOf t = -- trace ("cellColorOf " ++ show t ++ " i.e. " ++ show (toExt t)) $ join $ List.lookup "heap.Cell" (toExt t) -- pointerColorOf :: TagSet -> P (Maybe Color) -- pointerColorOf t = do -- ppol <- askPolicy let l = t -- -- Ughly: case ( [ " test","CP " ] l , [ " test","Pointer " ] l ) of -- (Just [_,p], _) -> return p -- (_, Just [p]) -> return p -- _ -> return Nothing pointerColorOf :: TagSet -> Maybe Color pointerColorOf t = join $ List.lookup "heap.Pointer" (toExt t) envColorOf :: TagSet -> Maybe Color envColorOf t = do join $ List.lookup "heap.Env" (toExt t) reachableInOneStep :: MemT -> Set Color -> Set Color reachableInOneStep m s = foldl (\s t -> case (cellColorOf t, pointerColorOf t) of (Just c, Just p) | Set.member c s -> Set.insert p s _ -> s ) s (Map.elems $ unMemT m) reachableLoop :: MemT -> Set Color -> Set Color reachableLoop m s = let s' = reachableInOneStep m s in if s == s' then s else reachableLoop m s' registerColors :: PIPE_State -> Set Color registerColors pstate = foldl (\s t -> case pointerColorOf t of Just c -> Set.insert c s Nothing -> s ) Set.empty (unGPRT $ p_gprs pstate) reachable :: PIPE_State -> Set Color reachable p = reachableLoop (p_mem p) $ registerColors p sameReachablePart :: MStatePair -> Bool sameReachablePart (M (s1, p1) (s2, p2)) = let r1 = reachable p1 r2 = reachable p2 filterAux [] _ = [] filterAux _ [] = [] filterAux ((i,d):ds) ((j,t):ts) | i == j = case cellColorOf t of Just c' | Set.member c' r1 -> d : filterAux ds ts _ -> filterAux ds ts | i < j = filterAux ds ((j,t):ts) | i > j = filterAux ((i,d):ds) ts f1 = filterAux (Map.assocs $ f_dm $ f_mem s1) (Map.assocs $ unMemT $ p_mem p1) f2 = filterAux (Map.assocs $ f_dm $ f_mem s2) (Map.assocs $ unMemT $ p_mem p2) in r1 == r2 && (f_gprs s1 == f_gprs s2) && (f1 == f2) ------------------------------------------------------------------------------------------ -- Generation GPR 's are hard coded to be [ 0 .. 31 ] , but we only use a couple of them maxReg = 3 -- Generate a random register for source genSourceReg :: Machine_State -> Gen GPR_Addr genSourceReg ms = choose (0, maxReg) -- Generate a target register GPR -- For now, just avoid R0 genTargetReg :: Machine_State -> Gen GPR_Addr genTargetReg ms = choose (1, maxReg) -- Generate an immediate up to number -- Multiple of 4 genImm :: Integer -> Gen InstrField -- -- (Hmm - Why did we never generate 0 at some point?) n = ( 4 * ) < $ > choose ( 1 , n ` div ` 4 ) genImm n = (4*) <$> choose (0, n `div` 4) -- Picks out valid (data registers + content + min immediate + max immediate + tag), -- (jump registers + min immediate), -- integer registers groupRegisters :: PolicyPlus -> GPR_File -> GPR_FileT -> ([(GPR_Addr, Integer, Integer, Integer, TagSet)], [(GPR_Addr, Integer)], [GPR_Addr]) groupRegisters pplus (GPR_File rs) (GPR_FileT ts) = -- Assuming that the register files are same length and they have no holes let regs = Map.assocs rs tags = Map.assocs ts rts = zip regs tags validData ((reg_id,reg_content),(_reg_id, reg_tag)) | reg_content >= dataMemLow pplus && reg_content <= dataMemHigh pplus && isJust (pointerColorOf reg_tag) = Just (reg_id, reg_content, 0, dataMemHigh pplus - reg_content, reg_tag) | reg_content == 0 && isJust (pointerColorOf reg_tag) = We can allow a 0 register by adding at least 4 Just (reg_id, 0, dataMemLow pplus, dataMemHigh pplus, reg_tag) | otherwise = Nothing validJump ((reg_id,reg_content),(_, reg_tag)) | reg_content < instrLow pplus && isJust (envColorOf reg_tag) = Just (reg_id, instrLow pplus - reg_content) | otherwise = Nothing dataRegs = map (fromJust) $ filter (isJust) $ map validData rts controlRegs = map (fromJust) $ filter (isJust) $ map validJump rts arithRegs = map fst regs in (dataRegs, controlRegs, arithRegs) -- All locations that can be accessed using color 'c' between 'lo' and 'hi' reachableLocsBetween :: PolicyPlus -> Mem -> MemT -> Integer -> Integer -> TagSet -> [Integer] reachableLocsBetween pplus (Mem m _) (MemT pm) lo hi t = case pointerColorOf t of Just c -> map fst $ filter (\(i,t) -> case cellColorOf t of Just c' -> c == c' && i >= lo && i <= hi _ -> False ) (Map.assocs pm) _ -> [] allocInstTag :: PolicyPlus -> TagSet allocInstTag pplus = fromExt [("heap.Alloc", Nothing), ("heap.Inst", Nothing)] genInstr :: PolicyPlus -> Machine_State -> PIPE_State -> Gen (Instr_I, TagSet) genInstr pplus ms ps = let (dataRegs, ctrlRegs, arithRegs) = groupRegisters pplus (f_gprs ms) (p_gprs ps) onNonEmpty [] _= 0 onNonEmpty _ n = n in frequency [ (onNonEmpty arithRegs 1, ADDI rs <- elements arithRegs rd <- genTargetReg ms imm <- genImm (dataMemHigh pplus) ( Old comment ? " Need to figure out what to do with " ) alloc <- frequency [(2, pure $ emptyInstTag pplus), (3, pure $ allocInstTag pplus)] return (ADDI rd rs imm, alloc)) , (onNonEmpty dataRegs 3, do -- LOAD (rs,content,min_imm,max_imm,tag) <- elements dataRegs let locs = --traceShow (content, min_imm, max_imm, tag) $ reachableLocsBetween pplus (f_mem ms) (p_mem ps) (content+min_imm) (content+max_imm) tag rd <- genTargetReg ms imm <- frequency [ -- Generate a reachable location) (--traceShow locs $ onNonEmpty locs 1, do addr <- elements locs return $ addr - content) , (1, (min_imm+) <$> genImm (max_imm - min_imm)) ] let tag = emptyInstTag pplus return (LW rd rs imm, tag) ) , (onNonEmpty dataRegs 3 * onNonEmpty arithRegs 1, do -- STORE (rd,content, min_imm,max_imm,tag) <- elements dataRegs rs <- genTargetReg ms imm <- (min_imm+) <$> genImm (max_imm - min_imm) let tag = emptyInstTag pplus return (SW rd rs imm, tag)) , (onNonEmpty arithRegs 1, do -- ADD rs1 <- elements arithRegs rs2 <- elements arithRegs rd <- genTargetReg ms let tag = emptyInstTag pplus return (ADD rd rs1 rs2, tag)) ] randInstr :: PolicyPlus -> Machine_State -> Gen (Instr_I, TagSet) randInstr pplus ms = ADDI rs <- genSourceReg ms rd <- genTargetReg ms imm <- genImm 4 alloc <- frequency [(1, pure $ emptyInstTag pplus), (4, pure $ allocInstTag pplus)] return (ADDI rd rs imm, alloc)) , (1, do -- LOAD rs <- genSourceReg ms rd <- genTargetReg ms imm <- genImm 4 let tag = emptyInstTag pplus return (LW rd rs imm, tag)) , (1, do -- STORE rs <- genSourceReg ms rd <- genTargetReg ms imm <- genImm 4 let tag = emptyInstTag pplus return (SW rd rs imm, tag)) , (1, do -- ADD rs1 <- genSourceReg ms rs2 <- genSourceReg ms rd <- genTargetReg ms let tag = emptyInstTag pplus return (ADD rd rs1 rs2, tag)) ] genColor :: Gen Color genColor = frequency [ (1, pure $ 0) , (4, choose (0, 4)) ] Only colors up to 2 ( for registers ) genColorLow :: Gen Color genColorLow = frequency [ (1, pure $ 0) , (2, choose (0,2)) ] Focus on unreachable colors genColorHigh :: Gen Color genColorHigh = frequency [ (1, pure $ 0) , (1, choose (1,2) ) , (3, choose (3,4) ) ] genMTagM :: PolicyPlus -> Gen TagSet genMTagM pplus = do c1 <- genColor c2 <- genColor return $ fromExt [("heap.Cell", Just c1), ("heap.Pointer", Just c2)] genDataMemory :: PolicyPlus -> Gen (Mem, MemT) genDataMemory pplus = do let idx = [dataMemLow pplus, (dataMemLow pplus)+4..(dataMemHigh pplus)] BCP : This always puts 4 in every location ! t <- genMTagM pplus return ((i, d),(i,t))) idx let (m,pm) = unzip combined return (Mem (Map.fromList m) Nothing, MemT $ Map.fromList pm) setInstrI :: Machine_State -> Instr_I -> Machine_State setInstrI ms i = ms & fmem . at (f_pc ms) ?~ (encode_I RV32 i) WAS : ms { f_mem = ( f_mem ms ) { f_dm = Map.insert ( f_pc ms ) ( encode_I RV32 i ) ( f_dm $ f_mem ms ) } } setInstrTagI :: Machine_State -> PIPE_State -> TagSet -> PIPE_State setInstrTagI ms ps it = ps & pmem . at (f_pc ms) ?~ it WAS : ps { p_mem = ( MemT $ Map.insert ( f_pc ms ) ( it ) ( unMemT $ p_mem ps ) ) } -- | Generation by execution receives an initial machine X PIPE state and -- | generates instructions until n steps have been executed. -- | Returns the original machines with just the instruction memory locations -- | updated. genByExec :: PolicyPlus -> Int -> Machine_State -> PIPE_State -> Gen (Machine_State, PIPE_State) genByExec pplus n init_ms init_ps = exec_aux n init_ms init_ps init_ms init_ps where exec_aux 0 ims ips ms ps = return (ims, ips) exec_aux n ims ips ms ps -- Check if an instruction already exists | Map.member (f_pc ms) (f_dm $ f_mem ms) = case fetch_and_execute pplus ms ps of Right (ms'', ps'') -> exec_aux (n-1) ims ips ms'' ps'' Left err -> -- trace ("Warning: Fetch and execute failed with " ++ show n -- ++ " steps remaining and error: " ++ show err) $ return (ms, ps) | otherwise = do -- Generate an instruction for the current state (is, it) <- genInstr pplus ms ps -- Update the i-memory of both the machine we're stepping... let ms' = ms & fmem . at (f_pc ms) ?~ (encode_I RV32 is) ps' = ps & pmem . at (f_pc ms) ?~ it .. and the i - memory of the inital pair _ at the f_pc ms location _ ims' = ims & fmem . at (f_pc ms) ?~ (encode_I RV32 is) ips' = ips & pmem . at (f_pc ms) ?~ it -- Proceed with execution -- traceShow ("Instruction generated...", is) $ case fetch_and_execute pplus ms' ps' of Right (ms'', ps'') -> -- trace "Successful execution" $ exec_aux (n-1) ims' ips' ms'' ps'' Left err -> -- trace ("Warning: Fetch and execute failed with " -- ++ show n ++ " steps remaining and error: " ++ show err) $ return (ims', ips') genGPRs :: Machine_State -> Gen Machine_State Map ( Map ) genGPRs m = do ds <- replicateM 3 $ genImm 40 return $ m & fgpr %~ Map.union (Map.fromList $ zip [1..] ds) Map.union ( Map.fromList $ zip [ 1 .. ] ds ) rs -- [d1, d2, d3] <- let rs ' : : Map . Map Integer Integer = Map.insert 1 d1 $ Map.insert 2 d2 $ Map.insert 3 d3 rs return $ GPR_File rs ' mkPointerTagSet pplus c = fromExt [("heap.Pointer", Just c)] genGPRTs :: PolicyPlus -> PIPE_State -> Gen PIPE_State genGPRTs pplus p = do cs <- (map $ mkPointerTagSet (policy pplus)) <$> (replicateM 3 genColorLow) return $ p & pgpr %~ Map.union (Map.fromList $ zip [1..] cs) let rs ' : : Map . Map Integer TagSet = Map.insert 1 c1 $ Map.insert 2 c2 $ Map.insert 3 return $ GPR_FileT rs ' genMachine :: PolicyPlus -> Gen (Machine_State, PIPE_State) genMachine pplus = do -- registers (mm,pm) <- genDataMemory pplus let ms = initMachine & fmem_mem .~ mm --{f_mem = mem} & fmem . at (f_pc initMachine) ?~ (encode_I RV32 $ JAL 0 1000) ps = init_pipe_state pplus & pmem_mem .~ pm & pmem . at (f_pc ms) ?~ (emptyInstTag pplus) -- ps = init_pipe_state pplus & pmem_mem .~ pm ms2 = setInstrI ms ( JAL 0 1000 ) ps2 = ( emptyInstTag pplus ) -- Needed ? ? ms' <- genGPRs ms ps' <- genGPRTs pplus ps (ms_fin, ps_fin) <- genByExec pplus maxInstrsToGenerate ms' ps' -- let ms_fin' = ms_fin & -- -- final_mem = f_dm $ f_mem ms_fin res_mem = foldr ( \a mem - > Map.insert a ( fromJust $ Map.lookup a final_mem ) mem ) ( f_dm $ f_mem ms ' ) instrlocs -- ms_fin' = -- ms' {f_mem = (f_mem ms') { f_dm = res_mem } } -- final_pmem = unMemT $ p_mem ps_fin res_pmem = foldr ( \a pmem - > Map.insert a ( fromJust $ Map.lookup a final_pmem ) pmem ) ( unMemT $ p_mem ps ' ) instrlocs -- ps_fin' = -- ps' {p_mem = MemT res_pmem} return (ms_fin, ps_fin) varyUnreachableMem :: PolicyPlus -> Set Color -> Mem -> MemT -> Gen (Mem, MemT) varyUnreachableMem pplus r (Mem m ra) (MemT pm) = do combined <- mapM (\((i,d),(j,t)) -> do case cellColorOf t of Just c' | Set.member c' r -> return ((i,d),(j,t)) | otherwise -> do d' <- genImm 12 -- TODO: This makes no sense return ((i,d'),(j,t)) -- TODO: Here we could scramble v _ -> return ((i,d),(j,t)) ) $ zip (Map.assocs m) (Map.assocs pm) let (m', pm') = unzip combined return (Mem (Map.fromList m') ra, MemT (Map.fromList pm')) varyUnreachable :: PolicyPlus -> (Machine_State, PIPE_State) -> Gen MStatePair varyUnreachable pplus (m, p) = do let r = reachable p (mem', pmem') <- varyUnreachableMem pplus r (f_mem m) (p_mem p) return $ M (m,p) (m & fmem_mem .~ mem', p & pmem_mem .~ pmem') genMStatePair :: PolicyPlus -> Gen MStatePair genMStatePair pplus = genMachine pplus >>= varyUnreachable pplus ------------------------------------------------------------------------------------------ -- Shrinking -- Tag shrinking basically amounts to shrinking the colors -- of things to C 0. Assuming that C 0 is always reachable. We ca n't change the Tag type . We ca n't change the Color -- arbitrarily. shrinkColor :: Color -> [Color] shrinkColor (0) = [] shrinkColor (1) = [0] shrinkColor (n) = [0,n-1] shrinkTag :: TagSet -> [TagSet] shrinkTag t = case toExt t of [("heap.Alloc", Nothing), ("heap.Instr", Nothing)] -> [fromExt [("heap.Instr", Nothing)]] [("heap.Pointer", Just cp)] -> [fromExt [("heap.Pointer", Just cp')] | cp' <- shrinkColor cp] [("heap.Cell", Just cc), ("heap.Pointer", Just cp)] -> [fromExt [("heap.Cell", Just cc'), ("heap.Pointer", Just cp )] | cc' <- shrinkColor cc] ++ [fromExt [("heap.Cell", Just cc), ("heap.Pointer", Just cp')] | cp' <- shrinkColor cp] _ -> [] -- INV: If we're shrinking registers, everything should already be equal. shrinkRegister :: PolicyPlus -> (Integer, TagSet) -> [(Integer, TagSet)] shrinkRegister pplus (d,t) = [(d',t') | d' <- shrink d, t' <- shrinkTag t] shrinkVector :: (a -> [a]) -> [a] -> [[a]] shrinkVector f [] = [] shrinkVector f (h:t) = map (:t) (f h) ++ map (h:) (shrinkVector f t) -- INV: The register files are also identical shrinkGPRs :: PolicyPlus -> (GPR_File, GPR_FileT) -> (GPR_File, GPR_FileT) -> [((GPR_File, GPR_FileT),(GPR_File, GPR_FileT))] shrinkGPRs pplus (GPR_File d1, GPR_FileT t1) (GPR_File d2, GPR_FileT t2) = assert ( d1==d2 & & t1 = = t2 ) $ let combined :: [((GPR_Addr, GPR_Val), (InstrField, TagSet), (GPR_Addr, GPR_Val), (InstrField, TagSet))] combined = zip4 (Map.assocs d1) (Map.assocs t1) (Map.assocs d2) (Map.assocs t2) in [ ((GPR_File $ Map.fromList d1', GPR_FileT $ Map.fromList t1'), (GPR_File $ Map.fromList d2', GPR_FileT $ Map.fromList t2')) | (d1',t1',d2',t2') <- map unzip4 $ shrinkVector shrinkR combined ] where shrinkR :: ((GPR_Addr, GPR_Val), (InstrField, TagSet), (GPR_Addr, GPR_Val), (InstrField, TagSet)) -> [((GPR_Addr, GPR_Val), (InstrField, TagSet), (GPR_Addr, GPR_Val), (InstrField, TagSet))] shrinkR ((i1,v1),(j1,l1),(i2,v2),(j2,l2)) = [ ((i1,v'),(j1,l1),(i2,v'),(j2,l2)) | v' <- shrink v1 ] ++ [ ((i1,v1),(j1,l'),(i2,v2),(j2,l')) | l' <- shrinkTag l1 ] -- To shrink an instruction, try converting it to a noop (ADD 0 0 0) shrinkInstr :: Instr_I -> [Instr_I] shrinkInstr (ADD 0 0 0) = [] Do not shrink the initial JAL shrinkInstr (JAL 0 1000) = [] shrinkInstr _ = [ADD 0 0 0] type IndexedTaggedInt = ((Integer,Integer), (Integer,TagSet)) -- Have to perform the same thing to both memories at once -- We also need the set of reachable things for data memories -- INV: Original memories contain identical indices shrinkMems :: PolicyPlus -> Set Color -> (Mem, MemT) -> (Mem, MemT) -> [((Mem, MemT), (Mem,MemT))] shrinkMems pplus reachable (Mem m1 i1, MemT t1) (Mem m2 i2, MemT t2) = let m1' = Map.assocs m1 t1' = Map.assocs t1 m2' = Map.assocs m2 t2' = Map.assocs t2 isData i = i >= dataMemLow pplus && i <= dataMemHigh pplus isInstr i = i == 0 || i >= instrLow pplus shrinkMemLoc :: (Integer, Integer, TagSet) -> (Integer, Integer, TagSet) -> [ (IndexedTaggedInt, IndexedTaggedInt) ] shrinkMemLoc (j,d1,l1) (_,d2,l2) | isInstr j = case (decode_I RV32 d1, decode_I RV32 d2) of -- Both (identical) instructions (Just i1, Just i2) | i1 == i2 && l1 == l2 -> -- Shrink instruction [ (((j, d'), (j, l1)), ((j, d'),(j, l1))) | d' <- encode_I RV32 <$> shrinkInstr i1] ++ -- Or shrink tag (alloc) [ (((j, d1), (j, l')), ((j, d1),(j, l'))) | l' <- shrinkTag l1 ] | otherwise -> error $ "Distinguishable memory locations: " ++ show (j,d1,l1,d2,l2) _ -> error "Instructions can't be decoded while shrinking" | otherwise = traceShow ( " Shrinking ... " , l1 , l2 ) $ undefined case (cellColorOf l1, pointerColorOf l1, cellColorOf l2, pointerColorOf l2) of (Just loc1, Just _, Just loc2, Just _) -- Both reachable, everything should be identical | Set.member loc1 reachable && Set.member loc2 reachable && l1 == l2 && d1 == d2 -> shrink the first and copy -- Shrink data [ (((j, d'), (j, l1)), ((j, d'),(j, l1))) | d' <- shrink d1 ] ++ -- Or shrink tag [ (((j, d1), (j, l')), ((j, d2),(j, l'))) | l' <- shrinkTag l1 ] -- Both unreachable, shrink independently | not (Set.member loc1 reachable) && not (Set.member loc2 reachable) -> Shrink first data value [ (((j, d1'), (j, l1)), ((j, d2),(j, l2))) | d1' <- shrink d1 ] ++ Shrink first tag to something unreachable [ (((j, d1), (j, l1')), ((j, d2),(j, l2))) | l1' <- shrinkTag l1, not $ Set.member (fromJust $ cellColorOf l1') reachable ] ++ Shrink first tag to something reachable ( and make sure first and second components are the same ! ) [ (((j, d1), (j, l1')), ((j, d1),(j, l1'))) | l1' <- shrinkTag l1, Set.member (fromJust $ cellColorOf l1') reachable ] ++ ... same for second register state [ (((j, d1), (j, l1)), ((j, d2'),(j, l2))) | d2' <- shrink d2 ] ++ [ (((j, d1), (j, l1)), ((j, d2),(j, l2'))) | l2' <- shrinkTag l2, not $ Set.member (fromJust $ cellColorOf l2') reachable ] ++ [ (((j, d1), (j, l2')), ((j, d1),(j, l2'))) | l2' <- shrinkTag l2, Set.member (fromJust $ cellColorOf l2') reachable ] | otherwise -> error $ "Not both reachable or unreachable?" ++ show (d1,l1,d2,l2) otherwise -> error "Data memory without cell or pointer color?" shrinkMemAux :: [ IndexedTaggedInt ] -> [ IndexedTaggedInt] -> [ ([IndexedTaggedInt], [IndexedTaggedInt]) ] shrinkMemAux [] [] = [] shrinkMemAux (((j1,d1),(_,l1)):more1) (((j2,d2),(_,l2)):more2) = -- Shrink Current memory location and rebuild mem [ ((loc1':more1), (loc2':more2)) | (loc1', loc2') <- shrinkMemLoc (j1,d1,l1) (j2,d2,l2) ] ++ -- Keep current memory location and shrink something later on [ ( ((j1,d1),(j1,l1)) : more1', ((j2,d2),(j2,l2)) : more2' ) | (more1', more2') <- shrinkMemAux more1 more2 ] indexTagedIntsToMem :: Maybe (Integer,Integer) -> [IndexedTaggedInt] -> (Mem, MemT) indexTagedIntsToMem i itis = ((flip Mem i) . Map.fromList) *** (MemT . Map.fromList) $ unzip itis in map (indexTagedIntsToMem i1 *** indexTagedIntsToMem i2) $ shrinkMemAux (zip m1' t1') (zip m2' t2') shrinkMStatePair :: PolicyPlus -> MStatePair -> [MStatePair] shrinkMStatePair pplus (M (m1,p1) (m2,p2)) = let r = trace "Calculating Reachable" $ reachable p1 -- Shrink Memories in [ M (m1 & fmem_mem .~ mem1, p1 & pmem_mem .~ pmem1) (m2 & fmem_mem .~ mem2, p2 & pmem_mem .~ pmem2) | ((mem1, pmem1), (mem2, pmem2)) <- traceShow ("Shrinking memories") $ shrinkMems pplus r (f_mem m1, p_mem p1) (f_mem m2, p_mem p2) ] ++ [ M (m1 & fgpr_gpr .~ gpr1, p1 & pgpr_gpr .~ pgpr1) (m2 & fgpr_gpr .~ gpr2, p2 & pgpr_gpr .~ pgpr2) | ((gpr1, pgpr1), (gpr2, pgpr2)) <- traceShow ("Shrinking GPRS") $ shrinkGPRs pplus (f_gprs m1, p_gprs p1) (f_gprs m2, p_gprs p2) ] ------------------------------------------------------------------------------------------ -- Top-level non-interference policy : - for each program p and machine state s1 - for each s2 that agrees with s on ( the pure values stored in ) memory cells colored with reachable colors - p coterminates on s1 and s2 - moreover , if it terminates in s1 ' and s2 ' , then s1 ' and s2 ' also agree on all reachable memory cells Note that this is quite an intensional property -- not so easy for programmers to reason about their implications ! Also , an interesting extension is to add a stack , either ( initially ) in hardware or ( harder ) protected with tags so that called procedures can not access their callers ' stack frames . This gives a more interesting ( though , pragmatically , still rather weak ) property . To get a pragmatically more useful property , something like " sealed capabilities " ( aka closures ) or a protected stack is needed . - for each program p and machine state s1 - for each s2 that agrees with s on (the pure values stored in) memory cells colored with reachable colors - p coterminates on s1 and s2 - moreover, if it terminates in s1' and s2', then s1' and s2' also agree on all reachable memory cells Note that this is quite an intensional property -- not so easy for programmers to reason about their implications! Also, an interesting extension is to add a stack, either (initially) in hardware or (harder) protected with tags so that called procedures cannot access their callers' stack frames. This gives a more interesting (though, pragmatically, still rather weak) property. To get a pragmatically more useful property, something like "sealed capabilities" (aka closures) or a protected stack is needed. -} prop_NI' pplus count maxcount trace (M (m1,p1) (m2,p2)) = let run_state1 = mstate_run_state_read m1 run_state2 = mstate_run_state_read m2 m1' = mstate_io_tick m1 m2' = mstate_io_tick m2 trace' = ((m1,p1),(m2,p2)) : trace in if count >= maxcount then label "Out of gas" $ property True -- TODO: Check for traps too else if run_state1 /= Run_State_Running || run_state2 /= Run_State_Running then label (let (s1,s2) = (show run_state1, show run_state2) in if s1==s2 then s1 else (s1 ++ " / " ++ s2)) $ property True else case (fetch_and_execute pplus m1' p1, fetch_and_execute pplus m2' p2) of (Right (m1r,p1r), Right (m2r, p2r)) -> (whenFail (do putStrLn $ "Reachable parts differ after execution!" let finalTrace = reverse $ ((m1r,p1r), (m2r, p2r)) : trace' uncurry (printTrace pplus) (unzip finalTrace)) $ property $ sameReachablePart (M (m1r,p1r) (m2r, p2r))) .&&. prop_NI' pplus (count+1) maxcount trace' (M (m1r,p1r) (m2r, p2r)) (Left s1, Left s2) -> label ("Pipe trap " ++ s1 ++ " / " ++ s2) $ property True (Left s1, _) -> label ("Pipe trap " ++ s1) $ property True (_, Left s2) -> label ("Pipe trap " ++ s2) $ property True maxInstrsToGenerate :: Int maxInstrsToGenerate = 10 prop :: PolicyPlus -> MStatePair -> Property prop pplus ms = prop_NI' pplus 0 maxInstrsToGenerate [] ms ------------------------------------------------------------------------------------------ -- The heap-safety policy load_policy = do ppol <- load_pipe_policy "heap.main" let pplus = PolicyPlus { policy = ppol , initGPR = fromExt [("heap.Pointer", Just 0)] , initMem = -- TODO: Might be better to make it some separate " Uninitialized " tag ? fromExt [("heap.Cell", Just 0), ("heap.Pointer", Just 0)] , initPC = fromExt [("heap.Env", Nothing)] , initNextColor = 5 , emptyInstTag = fromExt [("heap.Inst", Nothing)] , dataMemLow = 4 Was 40 , but that seems like a lot ! ( 8 may be too little ! ) , instrLow = 1000 } return pplus main_trace = do pplus <- load_policy (M (ms1,ps1) (ms2,ps2)) <- head <$> sample' (genMStatePair pplus) let (res, tr) = run_loop pplus 10 ps1 ms1 (ps', ms') : _ = tr putStrLn "" putStrLn " Initial state : " -- print_coupled pplus ms1 ps1 -- putStrLn "_______________________________________________________________________" putStrLn " Final state : " -- print_coupled pplus ms' ps' -- putStrLn "_______________________________________________________________________" -- putStrLn "Trace:" let finalTrace = {- map flipboth $ -} reverse $ zip tr tr uncurry (printTrace pplus) (unzip finalTrace) ( reverse tr ) putStrLn (show res) The real one main_test = do pplus <- load_policy quickCheckWith stdArgs{maxSuccess=1000} $ forAllShrink (genMStatePair pplus) shrinkMStatePair pplus mp + + concatMap ( shrinkMStatePair pplus ) ( shrinkMStatePair pplus mp ) ) $ \m -> prop pplus m main = main_test
null
https://raw.githubusercontent.com/rsnikhil/Forvis_RISCV-ISA-Spec/0c5590a12f4b39644d0497fa6285ad5e33003dfc/micropolicies/TestHeapSafety.hs
haskell
From /src From . ---------------------------------------------------------------------------------- Printing verboseTracing = True value and tag of the current PC current instruction change in registers Change in memory l2, both assumed sorted by their keys and both representing parameter), and returns a list of changes to check whether the thing we are returning is equal to d! (And not return it in this case.) data_diff = assert ( i1 = = i2 ) $ d1 /= d2 ) (zip (Map.assocs dm1) (Map.assocs dm2)) tag_diff = filter (\((i1,l1),(i2,l2)) -> assert (i1 == i2) $ l1 /= l2) (zip (Map.assocs pm1) (Map.assocs pm2)) in case (data_diff, tag_diff) of ([], []) -> Nothing ([((i,_),(_,d))],[((j,_),(_,l))]) | i == j -> Just (i,d,l) (i,d,) <$> Map.lookup i pm2 ([],[((i,_),(_,l))]) -> (i,,l) <$> Map.lookup i dm2 " data = " ++ show data_diff ++ " and tags = " ++ show tag_diff Null "show" functions, for things that we don't want QuickCheck trying to print ---------------------------------------------------------------------------------- A stupid n^2 reachability algorithm for now. If we find it is too slow as memories get larger, we could improve it like this: - As we go along, maintain a set of "reachable colors" plus a map from "unreachable colors" to the addresses tagged with each of them. If an unreachable color ever becomes reachable, then add it to the reachable set and recursively traverse the things on its list. trace ("cellColorOf " ++ show t ++ " i.e. " ++ show (toExt t)) $ pointerColorOf :: TagSet -> P (Maybe Color) pointerColorOf t = do ppol <- askPolicy -- Ughly: (Just [_,p], _) -> return p (_, Just [p]) -> return p _ -> return Nothing ---------------------------------------------------------------------------------------- Generation Generate a random register for source Generate a target register GPR For now, just avoid R0 Generate an immediate up to number Multiple of 4 -- (Hmm - Why did we never generate 0 at some point?) Picks out valid (data registers + content + min immediate + max immediate + tag), (jump registers + min immediate), integer registers Assuming that the register files are same length and they have no holes All locations that can be accessed using color 'c' between 'lo' and 'hi' LOAD traceShow (content, min_imm, max_imm, tag) $ Generate a reachable location) traceShow locs $ STORE ADD LOAD STORE ADD | Generation by execution receives an initial machine X PIPE state and | generates instructions until n steps have been executed. | Returns the original machines with just the instruction memory locations | updated. Check if an instruction already exists trace ("Warning: Fetch and execute failed with " ++ show n ++ " steps remaining and error: " ++ show err) $ Generate an instruction for the current state Update the i-memory of both the machine we're stepping... Proceed with execution traceShow ("Instruction generated...", is) $ trace "Successful execution" $ trace ("Warning: Fetch and execute failed with " ++ show n ++ " steps remaining and error: " ++ show err) $ [d1, d2, d3] <- registers {f_mem = mem} ps = init_pipe_state pplus & pmem_mem .~ pm Needed ? ? let ms_fin' = ms_fin & final_mem = f_dm $ f_mem ms_fin ms_fin' = ms' {f_mem = (f_mem ms') { f_dm = res_mem } } ps_fin' = ps' {p_mem = MemT res_pmem} TODO: This makes no sense TODO: Here we could scramble v ---------------------------------------------------------------------------------------- Shrinking Tag shrinking basically amounts to shrinking the colors of things to C 0. Assuming that C 0 is always reachable. arbitrarily. INV: If we're shrinking registers, everything should already be equal. INV: The register files are also identical To shrink an instruction, try converting it to a noop (ADD 0 0 0) Have to perform the same thing to both memories at once We also need the set of reachable things for data memories INV: Original memories contain identical indices Both (identical) instructions Shrink instruction Or shrink tag (alloc) Both reachable, everything should be identical Shrink data Or shrink tag Both unreachable, shrink independently Shrink Current memory location and rebuild mem Keep current memory location and shrink something later on Shrink Memories ---------------------------------------------------------------------------------------- Top-level non-interference policy not so easy for not so easy for TODO: Check for traps too ---------------------------------------------------------------------------------------- The heap-safety policy TODO: Might be better to make it some separate print_coupled pplus ms1 ps1 putStrLn "_______________________________________________________________________" print_coupled pplus ms' ps' putStrLn "_______________________________________________________________________" putStrLn "Trace:" map flipboth $
# LANGUAGE PartialTypeSignatures , ScopedTypeVariables , TupleSections , FlexibleInstances , MultiParamTypeClasses # module TestHeapSafety where From libraries import Control.Arrow (second, (***)) import Control.Exception.Base (assert) import Control.Monad.Reader import Control.Lens hiding (elements) import Data.Bits import Data.List (zip4,unzip4) import Data.Maybe import qualified Data.List as List import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Debug.Trace import Test.QuickCheck import Text.PrettyPrint (Doc, (<+>), ($$)) import qualified Text.PrettyPrint as P import Arch_Defs import Bit_Utils import CSR_File import Encoder import Forvis_Spec_I import Forvis_Spec_Instr_Fetch import GPR_File import Machine_State import Memory import Gen import Run_Program_PIPE import PIPE import Printing import Terminal import MachineLenses TODO : Rename to TestState to reveal abstractions with stack type TestState = MStatePair prettyMStatePair :: PolicyPlus -> MStatePair -> Doc prettyMStatePair pplus (M (m1, p1) (m2, p2)) = let ppol = policy pplus in P.vcat [ P.text "PC:" <+> pretty pplus (f_pc m1, p_pc p1) (f_pc m2, p_pc p2) , P.text "Registers:" $$ P.nest 2 (pretty pplus (f_gprs m1, p_gprs p1) (f_gprs m2, p_gprs p2)) , P.text "Memories:" $$ P.nest 2 (pretty pplus (f_mem m1, p_mem p1) (f_mem m2, p_mem p2)) , P.text "Reachable:" <+> pretty pplus (reachable p1) (reachable p2) ] print_mstatepair :: PolicyPlus -> MStatePair -> IO () print_mstatepair pplus m = putStrLn $ P.render $ prettyMStatePair pplus m verboseTracing = False printTrace pplus tr1 tr2 = putStrLn $ P.render $ prettyTrace pplus tr1 tr2 prettyTrace :: PolicyPlus -> [(Machine_State, PIPE_State)] -> [(Machine_State, PIPE_State)] -> Doc prettyTrace pplus [] [] = P.empty prettyTrace pplus [(m1,p1)] [(m2,p2)] = prettyMStatePair pplus (M (m1,p1) (m2,p2)) prettyTrace pplus (tr1@((m1,p1):_)) (tr2@((m2,p2):_)) = prettyMStatePair pplus (M (m1,p1) (m2,p2)) $$ P.text "" $$ P.text "Trace:" $$ prettyDiffs pplus tr1 tr2 prettyDiffs :: PolicyPlus -> [(Machine_State, PIPE_State)] -> [(Machine_State, PIPE_State)] -> Doc prettyDiffs pplus ((m11,p11):(m12,p12):tr1) ((m21,p21):(m22,p22):tr2) = (if verboseTracing then P.text "----------------------------------------------------------------" $$ P.nest 10 (P.text "Raw Machine 1 memory:" $$ P.nest 3 (P.text (show $ f_dm $ f_mem m12))) $$ P.nest 10 (P.text "Raw Machine 1 tags:" $$ P.nest 3 (P.text (show $ p_mem p12))) $$ P.nest 10 (P.text "Raw Machine 2 memory:" $$ P.nest 3 (P.text (show $ f_dm $ f_mem m22))) $$ P.nest 10 (P.text "Raw Machine 2 tags:" $$ P.nest 3 (P.text (show $ p_mem p22))) $$ P.nest 10 (P.text "Machine 1:" $$ P.nest 3 (pretty pplus m12 p12) $$ P.text "Machine 2" $$ P.nest 3 (pretty pplus m22 p22) ) else P.empty) $$ pretty pplus (calcDiff pplus (m11,p11) (m12,p12)) (calcDiff pplus (m21,p21) (m22,p22)) $$ prettyDiffs pplus ((m12,p12):tr1) ((m22,p22):tr2) prettyDiffs pplus [(m1,p1)] [(m2,p2)] = P.text "" $$ P.text "Final:" $$ prettyMStatePair pplus (M (m1,p1) (m2,p2)) prettyDiffs _ _ _ = P.empty } Generic " find diffs " function : Takes two association lists l1 and * infinite * maps with some default value d ( passed as third N.b . In the cases where we are returning something , we first have diff :: (Ord a, Eq b) => [(a, b)] -> [(a, b)] -> b -> [(a, (b, b))] diff [] [] d = [] diff ((x1,y1):l1) [] d = (if y1==d then [] else [(x1,(y1,d))]) ++ diff l1 [] d diff [] ((x2,y2):l2) d = (if y2==d then [] else [(x2,(d,y2))]) ++ diff [] l2 d diff ((x1,y1):l1) ((x2,y2):l2) d | x1 < x2 = (if y1==d then [] else [(x1,(y1,d))]) ++ diff l1 ((x2,y2):l2) d | x1 > x2 = (if y2==d then [] else [(x2,(d,y2))]) ++ diff ((x1,y1):l1) l2 d | otherwise = (if y1==y2 then [] else [(x1,(y1,y2))]) ++ diff l1 l2 d calcDiff :: PolicyPlus -> (Machine_State, PIPE_State) -> (Machine_State, PIPE_State) -> Diff calcDiff pplus (m1,p1) (m2,p2) = Diff { d_pc = (f_pc m1, p_pc p1) , d_instr = case fst $ instr_fetch m1 of Fetch u32 -> decode_I RV32 u32 _ -> error "Bad instr fetch in calcDiff" , d_reg = let GPR_File r1 = f_gprs m1 GPR_File r2 = f_gprs m2 GPR_FileT t1 = p_gprs p1 GPR_FileT t2 = p_gprs p2 reg_diff = filter (\((i1,d1),(i2,d2)) -> assert (i1 == i2) $ d1 /= d2) (zip (Map.assocs r1) (Map.assocs r2)) tag_diff = filter (\((i1,l1),(i2,l2)) -> assert (i1 == i2) $ l1 /= l2) (zip (Map.assocs t1) (Map.assocs t2)) in case (reg_diff, tag_diff) of ([], []) -> [] ([((i,_),(_,d))],[((j,_),(_,l))]) | i == j -> [(i,d,l)] ([((i,_),(_,d))],[]) -> catMaybes [(i,d,) <$> Map.lookup i t2] ([],[((i,_),(_,l))]) -> catMaybes [(i,,l) <$> Map.lookup i r2] TODO ( ! ) error $ "More than one diff in register file:" ++ " registers = " ++ show reg_diff ++ " and tags = " ++ show tag_diff , d_mem = let Mem dm1 _ = f_mem m1 Mem dm2 _ = f_mem m2 MemT pm1 = p_mem p1 MemT pm2 = p_mem p2 both1 = map (\((i,d),(j,t)) -> assert (i==j) $ (i,(d,t))) $ zip (Map.assocs dm1) (Map.assocs pm1) both2 = map (\((i,d),(j,t)) -> assert (i==j) $ (i,(d,t))) $ zip (Map.assocs dm2) (Map.assocs pm2) diffs = diff both1 both2 (uninitialized_word, emptyInstTag pplus) extract (i,(_,(d,t))) = (i,d,t) in map extract diffs } filter ( ) ) - > if i1 = = i2 then d1 /= d2 else error $ " DIFF : " + + show ( " i1 " , i1 , " d1 " , d1 , " i2 " , i2 , " d2 " , d2 , " dm1 " , dm1 , " dm2 " , dm2 ) ) ( [ ( ( i,_),(_,d ) ) ] , [ ] ) - > _ - > error $ " More than one diff in memory file : " + + prettyRegDiff pplus ((i,d,l):r1) ((i', d', l'):r2) | i == i', d == d', l == l' = (P.char 'r' P.<> P.integer i <+> P.text "<-" <+> pretty pplus d l) $$ prettyRegDiff pplus r1 r2 | otherwise = (ppStrong (P.char 'r' P.<> P.integer i <+> P.text "<-" <+> pretty pplus d l <||> P.char 'r' P.<> P.integer i' <+> P.text "<-" <+> pretty pplus d' l')) $$ prettyRegDiff pplus r1 r2 prettyRegDiff _ [] [] = P.empty TODO ( ): This can happen a lot now ... prettyRegDiff _ r1 r2 = P.text $ "<prettyRegDiff??> " ++ show (r1,r2) prettyMemDiff pplus ((i,d,l):m1) ((i', d', l'):m2) | i == i', d == d', l == l' = (P.char '[' P.<> P.integer i P.<> P.char ']' <+> P.text "<-" <+> pretty pplus d l) $$ prettyMemDiff pplus m1 m2 | otherwise = (ppStrong (P.char '[' P.<> P.integer i P.<> P.char ']' <+> P.text "<-" <+> pretty pplus d l <||> P.char '[' P.<> P.integer i' P.<> P.char ']' <+> P.text "<-" <+> pretty pplus d' l')) $$ prettyMemDiff pplus m1 m2 prettyMemDiff _ [] [] = P.empty prettyMemDiff _ _ _ = P.text "<prettyMemDiff??>" instance CoupledPP (Maybe Instr_I) (Maybe Instr_I) where pretty pplus (Just i1) (Just i2) | i1 == i2 = pp pplus i1 | otherwise = ppStrong (pp pplus i1 <||> pp pplus i2) pretty _ Nothing Nothing = P.text "<Bad instr>" instance CoupledPP Diff Diff where pretty pplus d1 d2 = P.hcat [ pad 17 (pretty pplus (d_pc d1) (d_pc d2)) , P.text " " , pad 17 (pretty pplus (d_instr d1) (d_instr d2)) , P.text " " , prettyRegDiff pplus (d_reg d1) (d_reg d2) , prettyMemDiff pplus (d_mem d1) (d_mem d2) ] instance Show Machine_State where show _ = "" instance Show MStatePair where show _ = "" Reachability cellColorOf :: TagSet -> Maybe Color cellColorOf t = join $ List.lookup "heap.Cell" (toExt t) let l = t case ( [ " test","CP " ] l , [ " test","Pointer " ] l ) of pointerColorOf :: TagSet -> Maybe Color pointerColorOf t = join $ List.lookup "heap.Pointer" (toExt t) envColorOf :: TagSet -> Maybe Color envColorOf t = do join $ List.lookup "heap.Env" (toExt t) reachableInOneStep :: MemT -> Set Color -> Set Color reachableInOneStep m s = foldl (\s t -> case (cellColorOf t, pointerColorOf t) of (Just c, Just p) | Set.member c s -> Set.insert p s _ -> s ) s (Map.elems $ unMemT m) reachableLoop :: MemT -> Set Color -> Set Color reachableLoop m s = let s' = reachableInOneStep m s in if s == s' then s else reachableLoop m s' registerColors :: PIPE_State -> Set Color registerColors pstate = foldl (\s t -> case pointerColorOf t of Just c -> Set.insert c s Nothing -> s ) Set.empty (unGPRT $ p_gprs pstate) reachable :: PIPE_State -> Set Color reachable p = reachableLoop (p_mem p) $ registerColors p sameReachablePart :: MStatePair -> Bool sameReachablePart (M (s1, p1) (s2, p2)) = let r1 = reachable p1 r2 = reachable p2 filterAux [] _ = [] filterAux _ [] = [] filterAux ((i,d):ds) ((j,t):ts) | i == j = case cellColorOf t of Just c' | Set.member c' r1 -> d : filterAux ds ts _ -> filterAux ds ts | i < j = filterAux ds ((j,t):ts) | i > j = filterAux ((i,d):ds) ts f1 = filterAux (Map.assocs $ f_dm $ f_mem s1) (Map.assocs $ unMemT $ p_mem p1) f2 = filterAux (Map.assocs $ f_dm $ f_mem s2) (Map.assocs $ unMemT $ p_mem p2) in r1 == r2 && (f_gprs s1 == f_gprs s2) && (f1 == f2) GPR 's are hard coded to be [ 0 .. 31 ] , but we only use a couple of them maxReg = 3 genSourceReg :: Machine_State -> Gen GPR_Addr genSourceReg ms = choose (0, maxReg) genTargetReg :: Machine_State -> Gen GPR_Addr genTargetReg ms = choose (1, maxReg) genImm :: Integer -> Gen InstrField n = ( 4 * ) < $ > choose ( 1 , n ` div ` 4 ) genImm n = (4*) <$> choose (0, n `div` 4) groupRegisters :: PolicyPlus -> GPR_File -> GPR_FileT -> ([(GPR_Addr, Integer, Integer, Integer, TagSet)], [(GPR_Addr, Integer)], [GPR_Addr]) groupRegisters pplus (GPR_File rs) (GPR_FileT ts) = let regs = Map.assocs rs tags = Map.assocs ts rts = zip regs tags validData ((reg_id,reg_content),(_reg_id, reg_tag)) | reg_content >= dataMemLow pplus && reg_content <= dataMemHigh pplus && isJust (pointerColorOf reg_tag) = Just (reg_id, reg_content, 0, dataMemHigh pplus - reg_content, reg_tag) | reg_content == 0 && isJust (pointerColorOf reg_tag) = We can allow a 0 register by adding at least 4 Just (reg_id, 0, dataMemLow pplus, dataMemHigh pplus, reg_tag) | otherwise = Nothing validJump ((reg_id,reg_content),(_, reg_tag)) | reg_content < instrLow pplus && isJust (envColorOf reg_tag) = Just (reg_id, instrLow pplus - reg_content) | otherwise = Nothing dataRegs = map (fromJust) $ filter (isJust) $ map validData rts controlRegs = map (fromJust) $ filter (isJust) $ map validJump rts arithRegs = map fst regs in (dataRegs, controlRegs, arithRegs) reachableLocsBetween :: PolicyPlus -> Mem -> MemT -> Integer -> Integer -> TagSet -> [Integer] reachableLocsBetween pplus (Mem m _) (MemT pm) lo hi t = case pointerColorOf t of Just c -> map fst $ filter (\(i,t) -> case cellColorOf t of Just c' -> c == c' && i >= lo && i <= hi _ -> False ) (Map.assocs pm) _ -> [] allocInstTag :: PolicyPlus -> TagSet allocInstTag pplus = fromExt [("heap.Alloc", Nothing), ("heap.Inst", Nothing)] genInstr :: PolicyPlus -> Machine_State -> PIPE_State -> Gen (Instr_I, TagSet) genInstr pplus ms ps = let (dataRegs, ctrlRegs, arithRegs) = groupRegisters pplus (f_gprs ms) (p_gprs ps) onNonEmpty [] _= 0 onNonEmpty _ n = n in frequency [ (onNonEmpty arithRegs 1, ADDI rs <- elements arithRegs rd <- genTargetReg ms imm <- genImm (dataMemHigh pplus) ( Old comment ? " Need to figure out what to do with " ) alloc <- frequency [(2, pure $ emptyInstTag pplus), (3, pure $ allocInstTag pplus)] return (ADDI rd rs imm, alloc)) , (onNonEmpty dataRegs 3, (rs,content,min_imm,max_imm,tag) <- elements dataRegs reachableLocsBetween pplus (f_mem ms) (p_mem ps) (content+min_imm) (content+max_imm) tag rd <- genTargetReg ms onNonEmpty locs 1, do addr <- elements locs return $ addr - content) , (1, (min_imm+) <$> genImm (max_imm - min_imm)) ] let tag = emptyInstTag pplus return (LW rd rs imm, tag) ) , (onNonEmpty dataRegs 3 * onNonEmpty arithRegs 1, (rd,content, min_imm,max_imm,tag) <- elements dataRegs rs <- genTargetReg ms imm <- (min_imm+) <$> genImm (max_imm - min_imm) let tag = emptyInstTag pplus return (SW rd rs imm, tag)) , (onNonEmpty arithRegs 1, rs1 <- elements arithRegs rs2 <- elements arithRegs rd <- genTargetReg ms let tag = emptyInstTag pplus return (ADD rd rs1 rs2, tag)) ] randInstr :: PolicyPlus -> Machine_State -> Gen (Instr_I, TagSet) randInstr pplus ms = ADDI rs <- genSourceReg ms rd <- genTargetReg ms imm <- genImm 4 alloc <- frequency [(1, pure $ emptyInstTag pplus), (4, pure $ allocInstTag pplus)] return (ADDI rd rs imm, alloc)) rs <- genSourceReg ms rd <- genTargetReg ms imm <- genImm 4 let tag = emptyInstTag pplus return (LW rd rs imm, tag)) rs <- genSourceReg ms rd <- genTargetReg ms imm <- genImm 4 let tag = emptyInstTag pplus return (SW rd rs imm, tag)) rs1 <- genSourceReg ms rs2 <- genSourceReg ms rd <- genTargetReg ms let tag = emptyInstTag pplus return (ADD rd rs1 rs2, tag)) ] genColor :: Gen Color genColor = frequency [ (1, pure $ 0) , (4, choose (0, 4)) ] Only colors up to 2 ( for registers ) genColorLow :: Gen Color genColorLow = frequency [ (1, pure $ 0) , (2, choose (0,2)) ] Focus on unreachable colors genColorHigh :: Gen Color genColorHigh = frequency [ (1, pure $ 0) , (1, choose (1,2) ) , (3, choose (3,4) ) ] genMTagM :: PolicyPlus -> Gen TagSet genMTagM pplus = do c1 <- genColor c2 <- genColor return $ fromExt [("heap.Cell", Just c1), ("heap.Pointer", Just c2)] genDataMemory :: PolicyPlus -> Gen (Mem, MemT) genDataMemory pplus = do let idx = [dataMemLow pplus, (dataMemLow pplus)+4..(dataMemHigh pplus)] BCP : This always puts 4 in every location ! t <- genMTagM pplus return ((i, d),(i,t))) idx let (m,pm) = unzip combined return (Mem (Map.fromList m) Nothing, MemT $ Map.fromList pm) setInstrI :: Machine_State -> Instr_I -> Machine_State setInstrI ms i = ms & fmem . at (f_pc ms) ?~ (encode_I RV32 i) WAS : ms { f_mem = ( f_mem ms ) { f_dm = Map.insert ( f_pc ms ) ( encode_I RV32 i ) ( f_dm $ f_mem ms ) } } setInstrTagI :: Machine_State -> PIPE_State -> TagSet -> PIPE_State setInstrTagI ms ps it = ps & pmem . at (f_pc ms) ?~ it WAS : ps { p_mem = ( MemT $ Map.insert ( f_pc ms ) ( it ) ( unMemT $ p_mem ps ) ) } genByExec :: PolicyPlus -> Int -> Machine_State -> PIPE_State -> Gen (Machine_State, PIPE_State) genByExec pplus n init_ms init_ps = exec_aux n init_ms init_ps init_ms init_ps where exec_aux 0 ims ips ms ps = return (ims, ips) exec_aux n ims ips ms ps | Map.member (f_pc ms) (f_dm $ f_mem ms) = case fetch_and_execute pplus ms ps of Right (ms'', ps'') -> exec_aux (n-1) ims ips ms'' ps'' Left err -> return (ms, ps) | otherwise = do (is, it) <- genInstr pplus ms ps let ms' = ms & fmem . at (f_pc ms) ?~ (encode_I RV32 is) ps' = ps & pmem . at (f_pc ms) ?~ it .. and the i - memory of the inital pair _ at the f_pc ms location _ ims' = ims & fmem . at (f_pc ms) ?~ (encode_I RV32 is) ips' = ips & pmem . at (f_pc ms) ?~ it case fetch_and_execute pplus ms' ps' of Right (ms'', ps'') -> exec_aux (n-1) ims' ips' ms'' ps'' Left err -> return (ims', ips') genGPRs :: Machine_State -> Gen Machine_State Map ( Map ) genGPRs m = do ds <- replicateM 3 $ genImm 40 return $ m & fgpr %~ Map.union (Map.fromList $ zip [1..] ds) Map.union ( Map.fromList $ zip [ 1 .. ] ds ) rs let rs ' : : Map . Map Integer Integer = Map.insert 1 d1 $ Map.insert 2 d2 $ Map.insert 3 d3 rs return $ GPR_File rs ' mkPointerTagSet pplus c = fromExt [("heap.Pointer", Just c)] genGPRTs :: PolicyPlus -> PIPE_State -> Gen PIPE_State genGPRTs pplus p = do cs <- (map $ mkPointerTagSet (policy pplus)) <$> (replicateM 3 genColorLow) return $ p & pgpr %~ Map.union (Map.fromList $ zip [1..] cs) let rs ' : : Map . Map Integer TagSet = Map.insert 1 c1 $ Map.insert 2 c2 $ Map.insert 3 return $ GPR_FileT rs ' genMachine :: PolicyPlus -> Gen (Machine_State, PIPE_State) genMachine pplus = do (mm,pm) <- genDataMemory pplus let ms = initMachine & fmem . at (f_pc initMachine) ?~ (encode_I RV32 $ JAL 0 1000) ps = init_pipe_state pplus & pmem_mem .~ pm & pmem . at (f_pc ms) ?~ (emptyInstTag pplus) ms2 = setInstrI ms ( JAL 0 1000 ) ms' <- genGPRs ms ps' <- genGPRTs pplus ps (ms_fin, ps_fin) <- genByExec pplus maxInstrsToGenerate ms' ps' res_mem = foldr ( \a mem - > Map.insert a ( fromJust $ Map.lookup a final_mem ) mem ) ( f_dm $ f_mem ms ' ) instrlocs final_pmem = unMemT $ p_mem ps_fin res_pmem = foldr ( \a pmem - > Map.insert a ( fromJust $ Map.lookup a final_pmem ) pmem ) ( unMemT $ p_mem ps ' ) instrlocs return (ms_fin, ps_fin) varyUnreachableMem :: PolicyPlus -> Set Color -> Mem -> MemT -> Gen (Mem, MemT) varyUnreachableMem pplus r (Mem m ra) (MemT pm) = do combined <- mapM (\((i,d),(j,t)) -> do case cellColorOf t of Just c' | Set.member c' r -> return ((i,d),(j,t)) _ -> return ((i,d),(j,t)) ) $ zip (Map.assocs m) (Map.assocs pm) let (m', pm') = unzip combined return (Mem (Map.fromList m') ra, MemT (Map.fromList pm')) varyUnreachable :: PolicyPlus -> (Machine_State, PIPE_State) -> Gen MStatePair varyUnreachable pplus (m, p) = do let r = reachable p (mem', pmem') <- varyUnreachableMem pplus r (f_mem m) (p_mem p) return $ M (m,p) (m & fmem_mem .~ mem', p & pmem_mem .~ pmem') genMStatePair :: PolicyPlus -> Gen MStatePair genMStatePair pplus = genMachine pplus >>= varyUnreachable pplus We ca n't change the Tag type . We ca n't change the Color shrinkColor :: Color -> [Color] shrinkColor (0) = [] shrinkColor (1) = [0] shrinkColor (n) = [0,n-1] shrinkTag :: TagSet -> [TagSet] shrinkTag t = case toExt t of [("heap.Alloc", Nothing), ("heap.Instr", Nothing)] -> [fromExt [("heap.Instr", Nothing)]] [("heap.Pointer", Just cp)] -> [fromExt [("heap.Pointer", Just cp')] | cp' <- shrinkColor cp] [("heap.Cell", Just cc), ("heap.Pointer", Just cp)] -> [fromExt [("heap.Cell", Just cc'), ("heap.Pointer", Just cp )] | cc' <- shrinkColor cc] ++ [fromExt [("heap.Cell", Just cc), ("heap.Pointer", Just cp')] | cp' <- shrinkColor cp] _ -> [] shrinkRegister :: PolicyPlus -> (Integer, TagSet) -> [(Integer, TagSet)] shrinkRegister pplus (d,t) = [(d',t') | d' <- shrink d, t' <- shrinkTag t] shrinkVector :: (a -> [a]) -> [a] -> [[a]] shrinkVector f [] = [] shrinkVector f (h:t) = map (:t) (f h) ++ map (h:) (shrinkVector f t) shrinkGPRs :: PolicyPlus -> (GPR_File, GPR_FileT) -> (GPR_File, GPR_FileT) -> [((GPR_File, GPR_FileT),(GPR_File, GPR_FileT))] shrinkGPRs pplus (GPR_File d1, GPR_FileT t1) (GPR_File d2, GPR_FileT t2) = assert ( d1==d2 & & t1 = = t2 ) $ let combined :: [((GPR_Addr, GPR_Val), (InstrField, TagSet), (GPR_Addr, GPR_Val), (InstrField, TagSet))] combined = zip4 (Map.assocs d1) (Map.assocs t1) (Map.assocs d2) (Map.assocs t2) in [ ((GPR_File $ Map.fromList d1', GPR_FileT $ Map.fromList t1'), (GPR_File $ Map.fromList d2', GPR_FileT $ Map.fromList t2')) | (d1',t1',d2',t2') <- map unzip4 $ shrinkVector shrinkR combined ] where shrinkR :: ((GPR_Addr, GPR_Val), (InstrField, TagSet), (GPR_Addr, GPR_Val), (InstrField, TagSet)) -> [((GPR_Addr, GPR_Val), (InstrField, TagSet), (GPR_Addr, GPR_Val), (InstrField, TagSet))] shrinkR ((i1,v1),(j1,l1),(i2,v2),(j2,l2)) = [ ((i1,v'),(j1,l1),(i2,v'),(j2,l2)) | v' <- shrink v1 ] ++ [ ((i1,v1),(j1,l'),(i2,v2),(j2,l')) | l' <- shrinkTag l1 ] shrinkInstr :: Instr_I -> [Instr_I] shrinkInstr (ADD 0 0 0) = [] Do not shrink the initial JAL shrinkInstr (JAL 0 1000) = [] shrinkInstr _ = [ADD 0 0 0] type IndexedTaggedInt = ((Integer,Integer), (Integer,TagSet)) shrinkMems :: PolicyPlus -> Set Color -> (Mem, MemT) -> (Mem, MemT) -> [((Mem, MemT), (Mem,MemT))] shrinkMems pplus reachable (Mem m1 i1, MemT t1) (Mem m2 i2, MemT t2) = let m1' = Map.assocs m1 t1' = Map.assocs t1 m2' = Map.assocs m2 t2' = Map.assocs t2 isData i = i >= dataMemLow pplus && i <= dataMemHigh pplus isInstr i = i == 0 || i >= instrLow pplus shrinkMemLoc :: (Integer, Integer, TagSet) -> (Integer, Integer, TagSet) -> [ (IndexedTaggedInt, IndexedTaggedInt) ] shrinkMemLoc (j,d1,l1) (_,d2,l2) | isInstr j = case (decode_I RV32 d1, decode_I RV32 d2) of (Just i1, Just i2) | i1 == i2 && l1 == l2 -> [ (((j, d'), (j, l1)), ((j, d'),(j, l1))) | d' <- encode_I RV32 <$> shrinkInstr i1] ++ [ (((j, d1), (j, l')), ((j, d1),(j, l'))) | l' <- shrinkTag l1 ] | otherwise -> error $ "Distinguishable memory locations: " ++ show (j,d1,l1,d2,l2) _ -> error "Instructions can't be decoded while shrinking" | otherwise = traceShow ( " Shrinking ... " , l1 , l2 ) $ undefined case (cellColorOf l1, pointerColorOf l1, cellColorOf l2, pointerColorOf l2) of (Just loc1, Just _, Just loc2, Just _) | Set.member loc1 reachable && Set.member loc2 reachable && l1 == l2 && d1 == d2 -> shrink the first and copy [ (((j, d'), (j, l1)), ((j, d'),(j, l1))) | d' <- shrink d1 ] ++ [ (((j, d1), (j, l')), ((j, d2),(j, l'))) | l' <- shrinkTag l1 ] | not (Set.member loc1 reachable) && not (Set.member loc2 reachable) -> Shrink first data value [ (((j, d1'), (j, l1)), ((j, d2),(j, l2))) | d1' <- shrink d1 ] ++ Shrink first tag to something unreachable [ (((j, d1), (j, l1')), ((j, d2),(j, l2))) | l1' <- shrinkTag l1, not $ Set.member (fromJust $ cellColorOf l1') reachable ] ++ Shrink first tag to something reachable ( and make sure first and second components are the same ! ) [ (((j, d1), (j, l1')), ((j, d1),(j, l1'))) | l1' <- shrinkTag l1, Set.member (fromJust $ cellColorOf l1') reachable ] ++ ... same for second register state [ (((j, d1), (j, l1)), ((j, d2'),(j, l2))) | d2' <- shrink d2 ] ++ [ (((j, d1), (j, l1)), ((j, d2),(j, l2'))) | l2' <- shrinkTag l2, not $ Set.member (fromJust $ cellColorOf l2') reachable ] ++ [ (((j, d1), (j, l2')), ((j, d1),(j, l2'))) | l2' <- shrinkTag l2, Set.member (fromJust $ cellColorOf l2') reachable ] | otherwise -> error $ "Not both reachable or unreachable?" ++ show (d1,l1,d2,l2) otherwise -> error "Data memory without cell or pointer color?" shrinkMemAux :: [ IndexedTaggedInt ] -> [ IndexedTaggedInt] -> [ ([IndexedTaggedInt], [IndexedTaggedInt]) ] shrinkMemAux [] [] = [] shrinkMemAux (((j1,d1),(_,l1)):more1) (((j2,d2),(_,l2)):more2) = [ ((loc1':more1), (loc2':more2)) | (loc1', loc2') <- shrinkMemLoc (j1,d1,l1) (j2,d2,l2) ] ++ [ ( ((j1,d1),(j1,l1)) : more1', ((j2,d2),(j2,l2)) : more2' ) | (more1', more2') <- shrinkMemAux more1 more2 ] indexTagedIntsToMem :: Maybe (Integer,Integer) -> [IndexedTaggedInt] -> (Mem, MemT) indexTagedIntsToMem i itis = ((flip Mem i) . Map.fromList) *** (MemT . Map.fromList) $ unzip itis in map (indexTagedIntsToMem i1 *** indexTagedIntsToMem i2) $ shrinkMemAux (zip m1' t1') (zip m2' t2') shrinkMStatePair :: PolicyPlus -> MStatePair -> [MStatePair] shrinkMStatePair pplus (M (m1,p1) (m2,p2)) = let r = trace "Calculating Reachable" $ reachable p1 in [ M (m1 & fmem_mem .~ mem1, p1 & pmem_mem .~ pmem1) (m2 & fmem_mem .~ mem2, p2 & pmem_mem .~ pmem2) | ((mem1, pmem1), (mem2, pmem2)) <- traceShow ("Shrinking memories") $ shrinkMems pplus r (f_mem m1, p_mem p1) (f_mem m2, p_mem p2) ] ++ [ M (m1 & fgpr_gpr .~ gpr1, p1 & pgpr_gpr .~ pgpr1) (m2 & fgpr_gpr .~ gpr2, p2 & pgpr_gpr .~ pgpr2) | ((gpr1, pgpr1), (gpr2, pgpr2)) <- traceShow ("Shrinking GPRS") $ shrinkGPRs pplus (f_gprs m1, p_gprs p1) (f_gprs m2, p_gprs p2) ] : - for each program p and machine state s1 - for each s2 that agrees with s on ( the pure values stored in ) memory cells colored with reachable colors - p coterminates on s1 and s2 - moreover , if it terminates in s1 ' and s2 ' , then s1 ' and s2 ' also agree on all reachable memory cells programmers to reason about their implications ! Also , an interesting extension is to add a stack , either ( initially ) in hardware or ( harder ) protected with tags so that called procedures can not access their callers ' stack frames . This gives a more interesting ( though , pragmatically , still rather weak ) property . To get a pragmatically more useful property , something like " sealed capabilities " ( aka closures ) or a protected stack is needed . - for each program p and machine state s1 - for each s2 that agrees with s on (the pure values stored in) memory cells colored with reachable colors - p coterminates on s1 and s2 - moreover, if it terminates in s1' and s2', then s1' and s2' also agree on all reachable memory cells programmers to reason about their implications! Also, an interesting extension is to add a stack, either (initially) in hardware or (harder) protected with tags so that called procedures cannot access their callers' stack frames. This gives a more interesting (though, pragmatically, still rather weak) property. To get a pragmatically more useful property, something like "sealed capabilities" (aka closures) or a protected stack is needed. -} prop_NI' pplus count maxcount trace (M (m1,p1) (m2,p2)) = let run_state1 = mstate_run_state_read m1 run_state2 = mstate_run_state_read m2 m1' = mstate_io_tick m1 m2' = mstate_io_tick m2 trace' = ((m1,p1),(m2,p2)) : trace in if count >= maxcount then label "Out of gas" $ property True else if run_state1 /= Run_State_Running || run_state2 /= Run_State_Running then label (let (s1,s2) = (show run_state1, show run_state2) in if s1==s2 then s1 else (s1 ++ " / " ++ s2)) $ property True else case (fetch_and_execute pplus m1' p1, fetch_and_execute pplus m2' p2) of (Right (m1r,p1r), Right (m2r, p2r)) -> (whenFail (do putStrLn $ "Reachable parts differ after execution!" let finalTrace = reverse $ ((m1r,p1r), (m2r, p2r)) : trace' uncurry (printTrace pplus) (unzip finalTrace)) $ property $ sameReachablePart (M (m1r,p1r) (m2r, p2r))) .&&. prop_NI' pplus (count+1) maxcount trace' (M (m1r,p1r) (m2r, p2r)) (Left s1, Left s2) -> label ("Pipe trap " ++ s1 ++ " / " ++ s2) $ property True (Left s1, _) -> label ("Pipe trap " ++ s1) $ property True (_, Left s2) -> label ("Pipe trap " ++ s2) $ property True maxInstrsToGenerate :: Int maxInstrsToGenerate = 10 prop :: PolicyPlus -> MStatePair -> Property prop pplus ms = prop_NI' pplus 0 maxInstrsToGenerate [] ms load_policy = do ppol <- load_pipe_policy "heap.main" let pplus = PolicyPlus { policy = ppol , initGPR = fromExt [("heap.Pointer", Just 0)] , initMem = " Uninitialized " tag ? fromExt [("heap.Cell", Just 0), ("heap.Pointer", Just 0)] , initPC = fromExt [("heap.Env", Nothing)] , initNextColor = 5 , emptyInstTag = fromExt [("heap.Inst", Nothing)] , dataMemLow = 4 Was 40 , but that seems like a lot ! ( 8 may be too little ! ) , instrLow = 1000 } return pplus main_trace = do pplus <- load_policy (M (ms1,ps1) (ms2,ps2)) <- head <$> sample' (genMStatePair pplus) let (res, tr) = run_loop pplus 10 ps1 ms1 (ps', ms') : _ = tr putStrLn "" putStrLn " Initial state : " putStrLn " Final state : " uncurry (printTrace pplus) (unzip finalTrace) ( reverse tr ) putStrLn (show res) The real one main_test = do pplus <- load_policy quickCheckWith stdArgs{maxSuccess=1000} $ forAllShrink (genMStatePair pplus) shrinkMStatePair pplus mp + + concatMap ( shrinkMStatePair pplus ) ( shrinkMStatePair pplus mp ) ) $ \m -> prop pplus m main = main_test
11163f9d6d7b09da7f5aaddb4533c176514915a342a5f14c8d3a44bd74f38ad8
argp/bap
batScanf.mli
* BatScanf - Extended Scanf module * Copyright ( C ) 1996 * 2009 , LIFO , Universite d'Orleans * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * BatScanf - Extended Scanf module * Copyright (C) 1996 Pierre Weis * 2009 David Rajchenbach-Teller, LIFO, Universite d'Orleans * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) * Formatted input functions . @author ( Base module ) @author @author Pierre Weis (Base module) @author David Teller *) * { 6 Introduction } * { 7 Functional input with format strings } * The module [ Scanf ] provides formatted input functions or { e scanners } . The formatted input functions can read from any kind of input , including strings , files , or anything that can return characters . The more general source of characters is named a { e scanning buffer } and has type { ! Scanning.scanbuf } . The more general formatted input function reads from any scanning buffer and is named [ bscanf ] . Generally speaking , the formatted input functions have 3 arguments : - the first argument is a source of characters for the input , - the second argument is a format string that specifies the values to read , - the third argument is a { e receiver function } that is applied to the values read . Hence , a typical call to the formatted input function { ! Scanf.bscanf } is [ bscanf ib fmt f ] , where : - [ ib ] is a source of characters ( typically a { e scanning buffer } with type { ! Scanning.scanbuf } ) , - [ fmt ] is a format string ( the same format strings as those used to print material with module { ! Printf } or { ! Format } ) , - [ f ] is a function that has as many arguments as the number of values to read in the input . The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a {e scanning buffer} and has type {!Scanning.scanbuf}. The more general formatted input function reads from any scanning buffer and is named [bscanf]. Generally speaking, the formatted input functions have 3 arguments: - the first argument is a source of characters for the input, - the second argument is a format string that specifies the values to read, - the third argument is a {e receiver function} that is applied to the values read. Hence, a typical call to the formatted input function {!Scanf.bscanf} is [bscanf ib fmt f], where: - [ib] is a source of characters (typically a {e scanning buffer} with type {!Scanning.scanbuf}), - [fmt] is a format string (the same format strings as those used to print material with module {!Printf} or {!Format}), - [f] is a function that has as many arguments as the number of values to read in the input. *) * { 7 A simple example } * As suggested above , the expression [ bscanf ib " % d " f ] reads a decimal integer [ n ] from the source of characters [ ib ] and returns [ f n ] . For instance , - if we use [ stdib ] as the source of characters ( { ! Scanning.stdib } is the predefined input buffer that reads from standard input ) , - if we define the receiver [ f ] as [ let f x = x + 1 ] , then [ bscanf stdib " % d " f ] reads an integer [ n ] from the standard input and returns [ f n ] ( that is [ n + 1 ] ) . Thus , if we evaluate [ bscanf stdib " % d " f ] , and then enter [ 41 ] at the keyboard , we get [ 42 ] as the final result . integer [n] from the source of characters [ib] and returns [f n]. For instance, - if we use [stdib] as the source of characters ({!Scanning.stdib} is the predefined input buffer that reads from standard input), - if we define the receiver [f] as [let f x = x + 1], then [bscanf stdib "%d" f] reads an integer [n] from the standard input and returns [f n] (that is [n + 1]). Thus, if we evaluate [bscanf stdib "%d" f], and then enter [41] at the keyboard, we get [42] as the final result. *) * { 7 Formatted input as a functional feature } (** The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assigment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time. *) * { 6 Scanning buffers } module Scanning : sig type scanbuf = Scanf.Scanning.scanbuf;; * The type of scanning buffers . A scanning buffer is the source from which a formatted input function gets characters . The scanning buffer holds the current state of the scan , plus a function to get the next char from the input , and a token buffer to store the string matched so far . Note : a scan may often require to examine one character in advance ; when this ` ` lookahead '' character does not belong to the token read , it is stored back in the scanning buffer and becomes the next character read . formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far. Note: a scan may often require to examine one character in advance; when this ``lookahead'' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character read. *) val stdib : scanbuf;; * The scanning buffer reading from [ stdin ] . [ stdib ] is equivalent to [ Scanning.from_input stdin ] . Note : when input is read interactively from [ stdin ] , the newline character that triggers the evaluation is incorporated in the input ; thus , scanning specifications must properly skip this character ( simply add a [ ' \n ' ] as the last character of the format string ) . [stdib] is equivalent to [Scanning.from_input stdin]. Note: when input is read interactively from [stdin], the newline character that triggers the evaluation is incorporated in the input; thus, scanning specifications must properly skip this character (simply add a ['\n'] as the last character of the format string). *) val from_string : string -> scanbuf;; * [ Scanning.from_string s ] returns a scanning buffer which reads from the given string . Reading starts from the first character in the string . The end - of - input condition is set when the end of the string is reached . given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached. *) val from_file : string -> scanbuf;; (** Bufferized file reading in text mode. The efficient and usual way to scan text mode files (in effect, [from_file] returns a scanning buffer that reads characters in large chunks, rather than one character at a time as buffers returned by [from_channel] do). [Scanning.from_file fname] returns a scanning buffer which reads from the given file [fname] in text mode. *) val from_file_bin : string -> scanbuf;; (** Bufferized file reading in binary mode. *) val from_function : (unit -> char) -> scanbuf;; * [ Scanning.from_function f ] returns a scanning buffer with the given function as its reading method . When scanning needs one more character , the given function is called . When the function has no more character to provide , it must signal an end - of - input condition by raising the exception [ End_of_file ] . function as its reading method. When scanning needs one more character, the given function is called. When the function has no more character to provide, it must signal an end-of-input condition by raising the exception [End_of_file]. *) val from_input : BatIO.input -> scanbuf;; (** [Scanning.from_channel ic] returns a scanning buffer which reads from the input channel [ic], starting at the current reading position. *) val end_of_input : scanbuf -> bool;; (** [Scanning.end_of_input ib] tests the end-of-input condition of the given scanning buffer. *) val beginning_of_input : scanbuf -> bool;; (** [Scanning.beginning_of_input ib] tests the beginning of input condition of the given scanning buffer. *) val name_of_input : scanbuf -> string;; (** [Scanning.file_name_of_input ib] returns the name of the character source for the scanning buffer [ib]. *) * { 6 Obsolete } {6 Obsolete} *) val from_channel : BatIO.input -> scanbuf;; (** @obsolete use {!from_input}*) end;; * { 6 Type of formatted input functions } type ('a, 'b, 'c, 'd) scanner = ('a, Scanning.scanbuf, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c;; * The type of formatted input scanners : [ ( ' a , ' b , ' c , 'd ) scanner ] is the type of a formatted input function that reads from some scanning buffer according to some format string ; more precisely , if [ scan ] is some formatted input function , then [ scan ib fmt f ] applies [ f ] to the arguments specified by the format string [ fmt ] , when [ scan ] has read those arguments from the scanning input buffer [ ib ] . For instance , the [ scanf ] function below has type [ ( ' a , ' b , ' c , 'd ) scanner ] , since it is a formatted input function that reads from [ stdib ] : [ f ] applies [ f ] to the arguments specified by [ fmt ] , reading those arguments from [ stdin ] as expected . If the format [ fmt ] has some [ % r ] indications , the corresponding input functions must be provided before the receiver [ f ] argument . For instance , if [ read_elem ] is an input function for values of type [ t ] , then [ bscanf ib " % r ; " read_elem f ] reads a value [ v ] of type [ t ] followed by a [ ' ; ' ] character , and returns [ f v ] . type of a formatted input function that reads from some scanning buffer according to some format string; more precisely, if [scan] is some formatted input function, then [scan ib fmt f] applies [f] to the arguments specified by the format string [fmt], when [scan] has read those arguments from the scanning input buffer [ib]. For instance, the [scanf] function below has type [('a, 'b, 'c, 'd) scanner], since it is a formatted input function that reads from [stdib]: [scanf fmt f] applies [f] to the arguments specified by [fmt], reading those arguments from [stdin] as expected. If the format [fmt] has some [%r] indications, the corresponding input functions must be provided before the receiver [f] argument. For instance, if [read_elem] is an input function for values of type [t], then [bscanf ib "%r;" read_elem f] reads a value [v] of type [t] followed by a [';'] character, and returns [f v]. *) exception Scan_failure of string;; (** The exception that formatted input functions raise when the input cannot be read according to the given format. *) * { 6 The general formatted input function } val bscanf : Scanning.scanbuf -> ('a, 'b, 'c, 'd) scanner;; * [ bscanf ib fmt r1 ... rN f ] reads arguments for the function [ f ] , from the scanning buffer [ ib ] , according to the format string [ fmt ] , and applies [ f ] to these values . The result of this call to [ f ] is returned as the result of the entire [ bscanf ] call . For instance , if [ f ] is the function [ fun s i - > i + 1 ] , then [ Scanf.sscanf " x= 1 " " % s = % i " f ] returns [ 2 ] . Arguments [ r1 ] to [ rN ] are user - defined input functions that read the argument corresponding to a [ % r ] conversion . scanning buffer [ib], according to the format string [fmt], and applies [f] to these values. The result of this call to [f] is returned as the result of the entire [bscanf] call. For instance, if [f] is the function [fun s i -> i + 1], then [Scanf.sscanf "x= 1" "%s = %i" f] returns [2]. Arguments [r1] to [rN] are user-defined input functions that read the argument corresponding to a [%r] conversion. *) * { 6 Format string description } * The format is a character string which contains three types of objects : - plain characters , which are simply matched with the characters of the input , - conversion specifications , each of which causes reading and conversion of one argument for the function [ f ] , - scanning indications to specify boundaries of tokens . objects: - plain characters, which are simply matched with the characters of the input, - conversion specifications, each of which causes reading and conversion of one argument for the function [f], - scanning indications to specify boundaries of tokens. *) * { 7 The space character in format strings } * As mentioned above , a plain character in the format string is just matched with the characters of the input ; however , one character is a special exception to this simple rule : the space character ( ASCII code 32 ) does not match a single space character , but any amount of ` ` whitespace '' in the input . More precisely , a space inside the format string matches { e any number } of tab , space , line feed and carriage return characters . Matching { e any } amount of whitespace , a space in the format string also matches no amount of whitespace at all ; hence , the call [ bscanf ib " Price = % d $ " ( fun p - > p ) ] and returns [ 1 ] when reading an input with various whitespace in it , such as [ Price = 1 $ ] , [ Price = 1 $ ] , or even [ Price=1 $ ] . matched with the characters of the input; however, one character is a special exception to this simple rule: the space character (ASCII code 32) does not match a single space character, but any amount of ``whitespace'' in the input. More precisely, a space inside the format string matches {e any number} of tab, space, line feed and carriage return characters. Matching {e any} amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call [bscanf ib "Price = %d $" (fun p -> p)] succeds and returns [1] when reading an input with various whitespace in it, such as [Price = 1 $], [Price = 1 $], or even [Price=1$]. *) * { 7 Conversion specifications in format strings } * Conversion specifications consist in the [ % ] character , followed by an optional flag , an optional field width , and followed by one or two conversion characters . The conversion characters and their meanings are : - [ d ] : reads an optionally signed decimal integer . - [ i ] : reads an optionally signed integer ( usual input formats for hexadecimal ( [ 0x[d]+ ] and [ 0X[d]+ ] ) , octal ( [ 0o[d]+ ] ) , and binary [ 0b[d]+ ] notations are understood ) . - [ u ] : reads an unsigned decimal integer . - [ x ] or [ X ] : reads an unsigned hexadecimal integer . - [ o ] : reads an unsigned octal integer . - [ s ] : reads a string argument that spreads as much as possible , until the following bounding condition holds : a whitespace has been found , a scanning indication has been encountered , or the end - of - input has been reached . Hence , this conversion always succeeds : it returns an empty string , if the bounding condition holds when the scan begins . - [ S ] : reads a delimited string argument ( delimiters and special escaped characters follow the lexical conventions of OCaml ) . - [ c ] : reads a single character . To test the current input character without reading it , specify a null field width , i.e. use specification [ % 0c ] . @raise Invalid_argument , if the field width specification is greater than 1 . - [ C ] : reads a single delimited character ( delimiters and special escaped characters follow the lexical conventions of OCaml ) . - [ f ] , [ e ] , [ E ] , [ g ] , [ G ] : reads an optionally signed floating - point number in decimal notation , in the style [ dddd.ddd e / E+-dd ] . - [ F ] : reads a floating point number according to the lexical conventions of OCaml ( hence the decimal point is mandatory if the exponent part is not mentioned ) . - [ B ] : reads a boolean argument ( [ true ] or [ false ] ) . - [ b ] : reads a boolean argument ( for backward compatibility ; do not use in new programs ) . - [ ld ] , [ li ] , [ lu ] , [ lx ] , [ lX ] , [ lo ] : reads an [ int32 ] argument to the format specified by the second letter ( decimal , hexadecimal , etc ) . - [ nd ] , [ ni ] , [ nu ] , [ nx ] , [ nX ] , [ no ] : reads a [ nativeint ] argument to the format specified by the second letter . - [ Ld ] , [ Li ] , [ ] , [ Lx ] , [ LX ] , [ Lo ] : reads an [ int64 ] argument to the format specified by the second letter . - [ \ [ range \ ] ] : reads characters that matches one of the characters mentioned in the range of characters [ range ] ( or not mentioned in it , if the range starts with [ ^ ] ) . Reads a [ string ] that can be empty , if the next input character does not match the range . The set of characters from [ c1 ] to [ c2 ] ( inclusively ) is denoted by [ c1 - c2 ] . Hence , [ % \[0 - 9\ ] ] returns a string representing a decimal number or an empty string if no decimal digit is found ; similarly , [ % \[\\048-\\057\\065-\\070\ ] ] returns a string of hexadecimal digits . If a closing bracket appears in a range , it must occur as the first character of the range ( or just after the [ ^ ] in case of range negation ) ; hence [ ] ] matches a [ \ ] ] character and [ \[^\]\ ] ] matches any character that is not [ \ ] ] . - [ r ] : user - defined reader . Takes the next [ ri ] formatted input function and applies it to the scanning buffer [ ib ] to read the next argument . The input function [ ri ] must therefore have type [ Scanning.scanbuf - > ' a ] and the argument read has type [ ' a ] . - [ \ { fmt % \ } ] : reads a format string argument . The format string read must have the same type as the format string specification [ fmt ] . For instance , [ " % \{%i%\ } " ] reads any format string that can read a value of type [ int ] ; hence [ Scanf.sscanf " fmt:\\\"number is % u\\\ " " " fmt:%\{%i%\ } " ] succeeds and returns the format string [ " number is % u " ] . - [ \ ( fmt % \ ) ] : scanning format substitution . Reads a format string to replace [ fmt ] . The format string read must have the same type as the format string specification [ fmt ] . For instance , [ " % \ ( % i% \ ) " ] reads any format string that can read a value of type [ int ] ; hence [ Scanf.sscanf " \\\"%4d\\\"1234.00 " " % \(%i%\ ) " ] is equivalent to [ Scanf.sscanf " 1234.00 " " % 4d " ] . - [ l ] : returns the number of lines read so far . - [ n ] : returns the number of characters read so far . - [ N ] or [ L ] : returns the number of tokens read so far . - [ ! ] : matches the end of input condition . - [ % ] : matches one [ % ] character in the input . Following the [ % ] character that introduces a conversion , there may be the special flag [ _ ] : the conversion that follows occurs as usual , but the resulting value is discarded . For instance , if [ f ] is the function [ fun i - > i + 1 ] , then [ Scanf.sscanf " x = 1 " " % _ s = % i " f ] returns [ 2 ] . The field width is composed of an optional integer literal indicating the maximal width of the token to read . For instance , [ % 6d ] reads an integer , having at most 6 decimal digits ; [ % 4f ] reads a float with at most 4 characters ; and [ % 8\[\\000-\\255\ ] ] returns the next 8 characters ( or all the characters still available , if fewer than 8 characters are available in the input ) . Notes : - as mentioned above , a [ % s ] convertion always succeeds , even if there is nothing to read in the input : it simply returns [ " " ] . - in addition to the relevant digits , [ ' _ ' ] characters may appear inside numbers ( this is reminiscent to the usual OCaml lexical conventions ) . If stricter scanning is desired , use the range conversion facility instead of the number conversions . - the [ scanf ] facility is not intended for heavy duty lexical analysis and parsing . If it appears not expressive enough for your needs , several alternative exists : regular expressions ( module [ ] ) , stream parsers , [ ocamllex]-generated lexers , [ ocamlyacc]-generated parsers . an optional flag, an optional field width, and followed by one or two conversion characters. The conversion characters and their meanings are: - [d]: reads an optionally signed decimal integer. - [i]: reads an optionally signed integer (usual input formats for hexadecimal ([0x[d]+] and [0X[d]+]), octal ([0o[d]+]), and binary [0b[d]+] notations are understood). - [u]: reads an unsigned decimal integer. - [x] or [X]: reads an unsigned hexadecimal integer. - [o]: reads an unsigned octal integer. - [s]: reads a string argument that spreads as much as possible, until the following bounding condition holds: a whitespace has been found, a scanning indication has been encountered, or the end-of-input has been reached. Hence, this conversion always succeeds: it returns an empty string, if the bounding condition holds when the scan begins. - [S]: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml). - [c]: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification [%0c]. @raise Invalid_argument, if the field width specification is greater than 1. - [C]: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml). - [f], [e], [E], [g], [G]: reads an optionally signed floating-point number in decimal notation, in the style [dddd.ddd e/E+-dd]. - [F]: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned). - [B]: reads a boolean argument ([true] or [false]). - [b]: reads a boolean argument (for backward compatibility; do not use in new programs). - [ld], [li], [lu], [lx], [lX], [lo]: reads an [int32] argument to the format specified by the second letter (decimal, hexadecimal, etc). - [nd], [ni], [nu], [nx], [nX], [no]: reads a [nativeint] argument to the format specified by the second letter. - [Ld], [Li], [Lu], [Lx], [LX], [Lo]: reads an [int64] argument to the format specified by the second letter. - [\[ range \]]: reads characters that matches one of the characters mentioned in the range of characters [range] (or not mentioned in it, if the range starts with [^]). Reads a [string] that can be empty, if the next input character does not match the range. The set of characters from [c1] to [c2] (inclusively) is denoted by [c1-c2]. Hence, [%\[0-9\]] returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, [%\[\\048-\\057\\065-\\070\]] returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the [^] in case of range negation); hence [\[\]\]] matches a [\]] character and [\[^\]\]] matches any character that is not [\]]. - [r]: user-defined reader. Takes the next [ri] formatted input function and applies it to the scanning buffer [ib] to read the next argument. The input function [ri] must therefore have type [Scanning.scanbuf -> 'a] and the argument read has type ['a]. - [\{ fmt %\}]: reads a format string argument. The format string read must have the same type as the format string specification [fmt]. For instance, ["%\{%i%\}"] reads any format string that can read a value of type [int]; hence [Scanf.sscanf "fmt:\\\"number is %u\\\"" "fmt:%\{%i%\}"] succeeds and returns the format string ["number is %u"]. - [\( fmt %\)]: scanning format substitution. Reads a format string to replace [fmt]. The format string read must have the same type as the format string specification [fmt]. For instance, ["%\( %i% \)"] reads any format string that can read a value of type [int]; hence [Scanf.sscanf "\\\"%4d\\\"1234.00" "%\(%i%\)"] is equivalent to [Scanf.sscanf "1234.00" "%4d"]. - [l]: returns the number of lines read so far. - [n]: returns the number of characters read so far. - [N] or [L]: returns the number of tokens read so far. - [!]: matches the end of input condition. - [%]: matches one [%] character in the input. Following the [%] character that introduces a conversion, there may be the special flag [_]: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if [f] is the function [fun i -> i + 1], then [Scanf.sscanf "x = 1" "%_s = %i" f] returns [2]. The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, [%6d] reads an integer, having at most 6 decimal digits; [%4f] reads a float with at most 4 characters; and [%8\[\\000-\\255\]] returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input). Notes: - as mentioned above, a [%s] convertion always succeeds, even if there is nothing to read in the input: it simply returns [""]. - in addition to the relevant digits, ['_'] characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions. - the [scanf] facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module [Str]), stream parsers, [ocamllex]-generated lexers, [ocamlyacc]-generated parsers. *) * { 7 Scanning indications in format strings } * Scanning indications appear just after the string conversions [ % s ] and [ % \ [ range \ ] ] to delimit the end of the token . A scanning indication is introduced by a [ @ ] character , followed by some constant character [ c ] . It means that the string token should end just before the next matching [ c ] ( which is skipped ) . If no [ c ] character is encountered , the string token spreads as much as possible . For instance , [ " % s@\t " ] reads a string up to the next tab character or to the end of input . If a scanning indication [ \@c ] does not follow a string conversion , it is treated as a plain [ c ] character . Note : - the scanning indications introduce slight differences in the syntax of [ Scanf ] format strings , compared to those used for the [ Printf ] module . However , the scanning indications are similar to those used in the [ Format ] module ; hence , when producing formatted text to be scanned by [ ! Scanf.bscanf ] , it is wise to use printing functions from the [ Format ] module ( or , if you need to use functions from [ Printf ] , banish or carefully double check the format strings that contain [ ' \@ ' ] characters ) . and [%\[ range \]] to delimit the end of the token. A scanning indication is introduced by a [@] character, followed by some constant character [c]. It means that the string token should end just before the next matching [c] (which is skipped). If no [c] character is encountered, the string token spreads as much as possible. For instance, ["%s@\t"] reads a string up to the next tab character or to the end of input. If a scanning indication [\@c] does not follow a string conversion, it is treated as a plain [c] character. Note: - the scanning indications introduce slight differences in the syntax of [Scanf] format strings, compared to those used for the [Printf] module. However, the scanning indications are similar to those used in the [Format] module; hence, when producing formatted text to be scanned by [!Scanf.bscanf], it is wise to use printing functions from the [Format] module (or, if you need to use functions from [Printf], banish or carefully double check the format strings that contain ['\@'] characters). *) * { 7 Exceptions during scanning } (** Scanners may raise the following exceptions when the input cannot be read according to the format string: - @raise Scanf.Scan_failure if the input does not match the format. - @raise Failure if a conversion to a number is not possible. - @raise End_of_file if the end of input is encountered while some more characters are needed to read the current conversion specification. - @raise Invalid_argument if the format string is invalid. Note: - as a consequence, scanning a [%s] conversion never raises exception [End_of_file]: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or [""] if none were read. *) * { 6 Specialized formatted input functions } val fscanf : in_channel -> ('a, 'b, 'c, 'd) scanner;; * Same as { ! Scanf.bscanf } , but reads from the given channel . Warning : since all formatted input functions operate from a scanning buffer , be aware that each [ fscanf ] invocation will operate with a scanning buffer reading from the given channel . This extra level of bufferization can lead to strange scanning behaviour if you use low level primitives on the channel ( reading characters , seeking the reading position , and so on ) . As a consequence , never mixt direct low level reading and high level scanning from the same input channel . Warning: since all formatted input functions operate from a scanning buffer, be aware that each [fscanf] invocation will operate with a scanning buffer reading from the given channel. This extra level of bufferization can lead to strange scanning behaviour if you use low level primitives on the channel (reading characters, seeking the reading position, and so on). As a consequence, never mixt direct low level reading and high level scanning from the same input channel. *) val sscanf : string -> ('a, 'b, 'c, 'd) scanner;; (** Same as {!Scanf.bscanf}, but reads from the given string. *) val scanf : ('a, 'b, 'c, 'd) scanner;; (** Same as {!Scanf.bscanf}, but reads from the predefined scanning buffer {!Scanf.Scanning.stdib} that is connected to [stdin]. *) val kscanf : Scanning.scanbuf -> (Scanning.scanbuf -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner;; (** Same as {!Scanf.bscanf}, but takes an additional function argument [ef] that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function [ef] with the scanning buffer and the exception that aborted the scanning process. *) * { 6 Reading format strings from input } val bscanf_format : Scanning.scanbuf -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g;; (** [bscanf_format ib fmt f] reads a format string token from the scannning buffer [ib], according to the given format string [fmt], and applies [f] to the resulting format string value. @raise Scan_failure if the format string value read does not have the same type as [fmt]. *) val sscanf_format : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g;; (** Same as {!Scanf.bscanf_format}, but reads from the given string. *) val format_from_string : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6;; (** [format_from_string s fmt] converts a string argument to a format string, according to the given format string [fmt]. @raise Scan_failure if [s], considered as a format string, does not have the same type as [fmt]. *)
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batScanf.mli
ocaml
* The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assigment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time. * Bufferized file reading in text mode. The efficient and usual way to scan text mode files (in effect, [from_file] returns a scanning buffer that reads characters in large chunks, rather than one character at a time as buffers returned by [from_channel] do). [Scanning.from_file fname] returns a scanning buffer which reads from the given file [fname] in text mode. * Bufferized file reading in binary mode. * [Scanning.from_channel ic] returns a scanning buffer which reads from the input channel [ic], starting at the current reading position. * [Scanning.end_of_input ib] tests the end-of-input condition of the given scanning buffer. * [Scanning.beginning_of_input ib] tests the beginning of input condition of the given scanning buffer. * [Scanning.file_name_of_input ib] returns the name of the character source for the scanning buffer [ib]. * @obsolete use {!from_input} * The exception that formatted input functions raise when the input cannot be read according to the given format. * Scanners may raise the following exceptions when the input cannot be read according to the format string: - @raise Scanf.Scan_failure if the input does not match the format. - @raise Failure if a conversion to a number is not possible. - @raise End_of_file if the end of input is encountered while some more characters are needed to read the current conversion specification. - @raise Invalid_argument if the format string is invalid. Note: - as a consequence, scanning a [%s] conversion never raises exception [End_of_file]: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or [""] if none were read. * Same as {!Scanf.bscanf}, but reads from the given string. * Same as {!Scanf.bscanf}, but reads from the predefined scanning buffer {!Scanf.Scanning.stdib} that is connected to [stdin]. * Same as {!Scanf.bscanf}, but takes an additional function argument [ef] that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function [ef] with the scanning buffer and the exception that aborted the scanning process. * [bscanf_format ib fmt f] reads a format string token from the scannning buffer [ib], according to the given format string [fmt], and applies [f] to the resulting format string value. @raise Scan_failure if the format string value read does not have the same type as [fmt]. * Same as {!Scanf.bscanf_format}, but reads from the given string. * [format_from_string s fmt] converts a string argument to a format string, according to the given format string [fmt]. @raise Scan_failure if [s], considered as a format string, does not have the same type as [fmt].
* BatScanf - Extended Scanf module * Copyright ( C ) 1996 * 2009 , LIFO , Universite d'Orleans * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * BatScanf - Extended Scanf module * Copyright (C) 1996 Pierre Weis * 2009 David Rajchenbach-Teller, LIFO, Universite d'Orleans * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) * Formatted input functions . @author ( Base module ) @author @author Pierre Weis (Base module) @author David Teller *) * { 6 Introduction } * { 7 Functional input with format strings } * The module [ Scanf ] provides formatted input functions or { e scanners } . The formatted input functions can read from any kind of input , including strings , files , or anything that can return characters . The more general source of characters is named a { e scanning buffer } and has type { ! Scanning.scanbuf } . The more general formatted input function reads from any scanning buffer and is named [ bscanf ] . Generally speaking , the formatted input functions have 3 arguments : - the first argument is a source of characters for the input , - the second argument is a format string that specifies the values to read , - the third argument is a { e receiver function } that is applied to the values read . Hence , a typical call to the formatted input function { ! Scanf.bscanf } is [ bscanf ib fmt f ] , where : - [ ib ] is a source of characters ( typically a { e scanning buffer } with type { ! Scanning.scanbuf } ) , - [ fmt ] is a format string ( the same format strings as those used to print material with module { ! Printf } or { ! Format } ) , - [ f ] is a function that has as many arguments as the number of values to read in the input . The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a {e scanning buffer} and has type {!Scanning.scanbuf}. The more general formatted input function reads from any scanning buffer and is named [bscanf]. Generally speaking, the formatted input functions have 3 arguments: - the first argument is a source of characters for the input, - the second argument is a format string that specifies the values to read, - the third argument is a {e receiver function} that is applied to the values read. Hence, a typical call to the formatted input function {!Scanf.bscanf} is [bscanf ib fmt f], where: - [ib] is a source of characters (typically a {e scanning buffer} with type {!Scanning.scanbuf}), - [fmt] is a format string (the same format strings as those used to print material with module {!Printf} or {!Format}), - [f] is a function that has as many arguments as the number of values to read in the input. *) * { 7 A simple example } * As suggested above , the expression [ bscanf ib " % d " f ] reads a decimal integer [ n ] from the source of characters [ ib ] and returns [ f n ] . For instance , - if we use [ stdib ] as the source of characters ( { ! Scanning.stdib } is the predefined input buffer that reads from standard input ) , - if we define the receiver [ f ] as [ let f x = x + 1 ] , then [ bscanf stdib " % d " f ] reads an integer [ n ] from the standard input and returns [ f n ] ( that is [ n + 1 ] ) . Thus , if we evaluate [ bscanf stdib " % d " f ] , and then enter [ 41 ] at the keyboard , we get [ 42 ] as the final result . integer [n] from the source of characters [ib] and returns [f n]. For instance, - if we use [stdib] as the source of characters ({!Scanning.stdib} is the predefined input buffer that reads from standard input), - if we define the receiver [f] as [let f x = x + 1], then [bscanf stdib "%d" f] reads an integer [n] from the standard input and returns [f n] (that is [n + 1]). Thus, if we evaluate [bscanf stdib "%d" f], and then enter [41] at the keyboard, we get [42] as the final result. *) * { 7 Formatted input as a functional feature } * { 6 Scanning buffers } module Scanning : sig type scanbuf = Scanf.Scanning.scanbuf;; * The type of scanning buffers . A scanning buffer is the source from which a formatted input function gets characters . The scanning buffer holds the current state of the scan , plus a function to get the next char from the input , and a token buffer to store the string matched so far . Note : a scan may often require to examine one character in advance ; when this ` ` lookahead '' character does not belong to the token read , it is stored back in the scanning buffer and becomes the next character read . formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far. Note: a scan may often require to examine one character in advance; when this ``lookahead'' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character read. *) val stdib : scanbuf;; * The scanning buffer reading from [ stdin ] . [ stdib ] is equivalent to [ Scanning.from_input stdin ] . Note : when input is read interactively from [ stdin ] , the newline character that triggers the evaluation is incorporated in the input ; thus , scanning specifications must properly skip this character ( simply add a [ ' \n ' ] as the last character of the format string ) . [stdib] is equivalent to [Scanning.from_input stdin]. Note: when input is read interactively from [stdin], the newline character that triggers the evaluation is incorporated in the input; thus, scanning specifications must properly skip this character (simply add a ['\n'] as the last character of the format string). *) val from_string : string -> scanbuf;; * [ Scanning.from_string s ] returns a scanning buffer which reads from the given string . Reading starts from the first character in the string . The end - of - input condition is set when the end of the string is reached . given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached. *) val from_file : string -> scanbuf;; val from_file_bin : string -> scanbuf;; val from_function : (unit -> char) -> scanbuf;; * [ Scanning.from_function f ] returns a scanning buffer with the given function as its reading method . When scanning needs one more character , the given function is called . When the function has no more character to provide , it must signal an end - of - input condition by raising the exception [ End_of_file ] . function as its reading method. When scanning needs one more character, the given function is called. When the function has no more character to provide, it must signal an end-of-input condition by raising the exception [End_of_file]. *) val from_input : BatIO.input -> scanbuf;; val end_of_input : scanbuf -> bool;; val beginning_of_input : scanbuf -> bool;; val name_of_input : scanbuf -> string;; * { 6 Obsolete } {6 Obsolete} *) val from_channel : BatIO.input -> scanbuf;; end;; * { 6 Type of formatted input functions } type ('a, 'b, 'c, 'd) scanner = ('a, Scanning.scanbuf, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c;; * The type of formatted input scanners : [ ( ' a , ' b , ' c , 'd ) scanner ] is the type of a formatted input function that reads from some scanning buffer according to some format string ; more precisely , if [ scan ] is some formatted input function , then [ scan ib fmt f ] applies [ f ] to the arguments specified by the format string [ fmt ] , when [ scan ] has read those arguments from the scanning input buffer [ ib ] . For instance , the [ scanf ] function below has type [ ( ' a , ' b , ' c , 'd ) scanner ] , since it is a formatted input function that reads from [ stdib ] : [ f ] applies [ f ] to the arguments specified by [ fmt ] , reading those arguments from [ stdin ] as expected . If the format [ fmt ] has some [ % r ] indications , the corresponding input functions must be provided before the receiver [ f ] argument . For instance , if [ read_elem ] is an input function for values of type [ t ] , then [ bscanf ib " % r ; " read_elem f ] reads a value [ v ] of type [ t ] followed by a [ ' ; ' ] character , and returns [ f v ] . type of a formatted input function that reads from some scanning buffer according to some format string; more precisely, if [scan] is some formatted input function, then [scan ib fmt f] applies [f] to the arguments specified by the format string [fmt], when [scan] has read those arguments from the scanning input buffer [ib]. For instance, the [scanf] function below has type [('a, 'b, 'c, 'd) scanner], since it is a formatted input function that reads from [stdib]: [scanf fmt f] applies [f] to the arguments specified by [fmt], reading those arguments from [stdin] as expected. If the format [fmt] has some [%r] indications, the corresponding input functions must be provided before the receiver [f] argument. For instance, if [read_elem] is an input function for values of type [t], then [bscanf ib "%r;" read_elem f] reads a value [v] of type [t] followed by a [';'] character, and returns [f v]. *) exception Scan_failure of string;; * { 6 The general formatted input function } val bscanf : Scanning.scanbuf -> ('a, 'b, 'c, 'd) scanner;; * [ bscanf ib fmt r1 ... rN f ] reads arguments for the function [ f ] , from the scanning buffer [ ib ] , according to the format string [ fmt ] , and applies [ f ] to these values . The result of this call to [ f ] is returned as the result of the entire [ bscanf ] call . For instance , if [ f ] is the function [ fun s i - > i + 1 ] , then [ Scanf.sscanf " x= 1 " " % s = % i " f ] returns [ 2 ] . Arguments [ r1 ] to [ rN ] are user - defined input functions that read the argument corresponding to a [ % r ] conversion . scanning buffer [ib], according to the format string [fmt], and applies [f] to these values. The result of this call to [f] is returned as the result of the entire [bscanf] call. For instance, if [f] is the function [fun s i -> i + 1], then [Scanf.sscanf "x= 1" "%s = %i" f] returns [2]. Arguments [r1] to [rN] are user-defined input functions that read the argument corresponding to a [%r] conversion. *) * { 6 Format string description } * The format is a character string which contains three types of objects : - plain characters , which are simply matched with the characters of the input , - conversion specifications , each of which causes reading and conversion of one argument for the function [ f ] , - scanning indications to specify boundaries of tokens . objects: - plain characters, which are simply matched with the characters of the input, - conversion specifications, each of which causes reading and conversion of one argument for the function [f], - scanning indications to specify boundaries of tokens. *) * { 7 The space character in format strings } * As mentioned above , a plain character in the format string is just matched with the characters of the input ; however , one character is a special exception to this simple rule : the space character ( ASCII code 32 ) does not match a single space character , but any amount of ` ` whitespace '' in the input . More precisely , a space inside the format string matches { e any number } of tab , space , line feed and carriage return characters . Matching { e any } amount of whitespace , a space in the format string also matches no amount of whitespace at all ; hence , the call [ bscanf ib " Price = % d $ " ( fun p - > p ) ] and returns [ 1 ] when reading an input with various whitespace in it , such as [ Price = 1 $ ] , [ Price = 1 $ ] , or even [ Price=1 $ ] . matched with the characters of the input; however, one character is a special exception to this simple rule: the space character (ASCII code 32) does not match a single space character, but any amount of ``whitespace'' in the input. More precisely, a space inside the format string matches {e any number} of tab, space, line feed and carriage return characters. Matching {e any} amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call [bscanf ib "Price = %d $" (fun p -> p)] succeds and returns [1] when reading an input with various whitespace in it, such as [Price = 1 $], [Price = 1 $], or even [Price=1$]. *) * { 7 Conversion specifications in format strings } * Conversion specifications consist in the [ % ] character , followed by an optional flag , an optional field width , and followed by one or two conversion characters . The conversion characters and their meanings are : - [ d ] : reads an optionally signed decimal integer . - [ i ] : reads an optionally signed integer ( usual input formats for hexadecimal ( [ 0x[d]+ ] and [ 0X[d]+ ] ) , octal ( [ 0o[d]+ ] ) , and binary [ 0b[d]+ ] notations are understood ) . - [ u ] : reads an unsigned decimal integer . - [ x ] or [ X ] : reads an unsigned hexadecimal integer . - [ o ] : reads an unsigned octal integer . - [ s ] : reads a string argument that spreads as much as possible , until the following bounding condition holds : a whitespace has been found , a scanning indication has been encountered , or the end - of - input has been reached . Hence , this conversion always succeeds : it returns an empty string , if the bounding condition holds when the scan begins . - [ S ] : reads a delimited string argument ( delimiters and special escaped characters follow the lexical conventions of OCaml ) . - [ c ] : reads a single character . To test the current input character without reading it , specify a null field width , i.e. use specification [ % 0c ] . @raise Invalid_argument , if the field width specification is greater than 1 . - [ C ] : reads a single delimited character ( delimiters and special escaped characters follow the lexical conventions of OCaml ) . - [ f ] , [ e ] , [ E ] , [ g ] , [ G ] : reads an optionally signed floating - point number in decimal notation , in the style [ dddd.ddd e / E+-dd ] . - [ F ] : reads a floating point number according to the lexical conventions of OCaml ( hence the decimal point is mandatory if the exponent part is not mentioned ) . - [ B ] : reads a boolean argument ( [ true ] or [ false ] ) . - [ b ] : reads a boolean argument ( for backward compatibility ; do not use in new programs ) . - [ ld ] , [ li ] , [ lu ] , [ lx ] , [ lX ] , [ lo ] : reads an [ int32 ] argument to the format specified by the second letter ( decimal , hexadecimal , etc ) . - [ nd ] , [ ni ] , [ nu ] , [ nx ] , [ nX ] , [ no ] : reads a [ nativeint ] argument to the format specified by the second letter . - [ Ld ] , [ Li ] , [ ] , [ Lx ] , [ LX ] , [ Lo ] : reads an [ int64 ] argument to the format specified by the second letter . - [ \ [ range \ ] ] : reads characters that matches one of the characters mentioned in the range of characters [ range ] ( or not mentioned in it , if the range starts with [ ^ ] ) . Reads a [ string ] that can be empty , if the next input character does not match the range . The set of characters from [ c1 ] to [ c2 ] ( inclusively ) is denoted by [ c1 - c2 ] . Hence , [ % \[0 - 9\ ] ] returns a string representing a decimal number or an empty string if no decimal digit is found ; similarly , [ % \[\\048-\\057\\065-\\070\ ] ] returns a string of hexadecimal digits . If a closing bracket appears in a range , it must occur as the first character of the range ( or just after the [ ^ ] in case of range negation ) ; hence [ ] ] matches a [ \ ] ] character and [ \[^\]\ ] ] matches any character that is not [ \ ] ] . - [ r ] : user - defined reader . Takes the next [ ri ] formatted input function and applies it to the scanning buffer [ ib ] to read the next argument . The input function [ ri ] must therefore have type [ Scanning.scanbuf - > ' a ] and the argument read has type [ ' a ] . - [ \ { fmt % \ } ] : reads a format string argument . The format string read must have the same type as the format string specification [ fmt ] . For instance , [ " % \{%i%\ } " ] reads any format string that can read a value of type [ int ] ; hence [ Scanf.sscanf " fmt:\\\"number is % u\\\ " " " fmt:%\{%i%\ } " ] succeeds and returns the format string [ " number is % u " ] . - [ \ ( fmt % \ ) ] : scanning format substitution . Reads a format string to replace [ fmt ] . The format string read must have the same type as the format string specification [ fmt ] . For instance , [ " % \ ( % i% \ ) " ] reads any format string that can read a value of type [ int ] ; hence [ Scanf.sscanf " \\\"%4d\\\"1234.00 " " % \(%i%\ ) " ] is equivalent to [ Scanf.sscanf " 1234.00 " " % 4d " ] . - [ l ] : returns the number of lines read so far . - [ n ] : returns the number of characters read so far . - [ N ] or [ L ] : returns the number of tokens read so far . - [ ! ] : matches the end of input condition . - [ % ] : matches one [ % ] character in the input . Following the [ % ] character that introduces a conversion , there may be the special flag [ _ ] : the conversion that follows occurs as usual , but the resulting value is discarded . For instance , if [ f ] is the function [ fun i - > i + 1 ] , then [ Scanf.sscanf " x = 1 " " % _ s = % i " f ] returns [ 2 ] . The field width is composed of an optional integer literal indicating the maximal width of the token to read . For instance , [ % 6d ] reads an integer , having at most 6 decimal digits ; [ % 4f ] reads a float with at most 4 characters ; and [ % 8\[\\000-\\255\ ] ] returns the next 8 characters ( or all the characters still available , if fewer than 8 characters are available in the input ) . Notes : - as mentioned above , a [ % s ] convertion always succeeds , even if there is nothing to read in the input : it simply returns [ " " ] . - in addition to the relevant digits , [ ' _ ' ] characters may appear inside numbers ( this is reminiscent to the usual OCaml lexical conventions ) . If stricter scanning is desired , use the range conversion facility instead of the number conversions . - the [ scanf ] facility is not intended for heavy duty lexical analysis and parsing . If it appears not expressive enough for your needs , several alternative exists : regular expressions ( module [ ] ) , stream parsers , [ ocamllex]-generated lexers , [ ocamlyacc]-generated parsers . an optional flag, an optional field width, and followed by one or two conversion characters. The conversion characters and their meanings are: - [d]: reads an optionally signed decimal integer. - [i]: reads an optionally signed integer (usual input formats for hexadecimal ([0x[d]+] and [0X[d]+]), octal ([0o[d]+]), and binary [0b[d]+] notations are understood). - [u]: reads an unsigned decimal integer. - [x] or [X]: reads an unsigned hexadecimal integer. - [o]: reads an unsigned octal integer. - [s]: reads a string argument that spreads as much as possible, until the following bounding condition holds: a whitespace has been found, a scanning indication has been encountered, or the end-of-input has been reached. Hence, this conversion always succeeds: it returns an empty string, if the bounding condition holds when the scan begins. - [S]: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml). - [c]: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification [%0c]. @raise Invalid_argument, if the field width specification is greater than 1. - [C]: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml). - [f], [e], [E], [g], [G]: reads an optionally signed floating-point number in decimal notation, in the style [dddd.ddd e/E+-dd]. - [F]: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned). - [B]: reads a boolean argument ([true] or [false]). - [b]: reads a boolean argument (for backward compatibility; do not use in new programs). - [ld], [li], [lu], [lx], [lX], [lo]: reads an [int32] argument to the format specified by the second letter (decimal, hexadecimal, etc). - [nd], [ni], [nu], [nx], [nX], [no]: reads a [nativeint] argument to the format specified by the second letter. - [Ld], [Li], [Lu], [Lx], [LX], [Lo]: reads an [int64] argument to the format specified by the second letter. - [\[ range \]]: reads characters that matches one of the characters mentioned in the range of characters [range] (or not mentioned in it, if the range starts with [^]). Reads a [string] that can be empty, if the next input character does not match the range. The set of characters from [c1] to [c2] (inclusively) is denoted by [c1-c2]. Hence, [%\[0-9\]] returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, [%\[\\048-\\057\\065-\\070\]] returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the [^] in case of range negation); hence [\[\]\]] matches a [\]] character and [\[^\]\]] matches any character that is not [\]]. - [r]: user-defined reader. Takes the next [ri] formatted input function and applies it to the scanning buffer [ib] to read the next argument. The input function [ri] must therefore have type [Scanning.scanbuf -> 'a] and the argument read has type ['a]. - [\{ fmt %\}]: reads a format string argument. The format string read must have the same type as the format string specification [fmt]. For instance, ["%\{%i%\}"] reads any format string that can read a value of type [int]; hence [Scanf.sscanf "fmt:\\\"number is %u\\\"" "fmt:%\{%i%\}"] succeeds and returns the format string ["number is %u"]. - [\( fmt %\)]: scanning format substitution. Reads a format string to replace [fmt]. The format string read must have the same type as the format string specification [fmt]. For instance, ["%\( %i% \)"] reads any format string that can read a value of type [int]; hence [Scanf.sscanf "\\\"%4d\\\"1234.00" "%\(%i%\)"] is equivalent to [Scanf.sscanf "1234.00" "%4d"]. - [l]: returns the number of lines read so far. - [n]: returns the number of characters read so far. - [N] or [L]: returns the number of tokens read so far. - [!]: matches the end of input condition. - [%]: matches one [%] character in the input. Following the [%] character that introduces a conversion, there may be the special flag [_]: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if [f] is the function [fun i -> i + 1], then [Scanf.sscanf "x = 1" "%_s = %i" f] returns [2]. The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, [%6d] reads an integer, having at most 6 decimal digits; [%4f] reads a float with at most 4 characters; and [%8\[\\000-\\255\]] returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input). Notes: - as mentioned above, a [%s] convertion always succeeds, even if there is nothing to read in the input: it simply returns [""]. - in addition to the relevant digits, ['_'] characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions. - the [scanf] facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module [Str]), stream parsers, [ocamllex]-generated lexers, [ocamlyacc]-generated parsers. *) * { 7 Scanning indications in format strings } * Scanning indications appear just after the string conversions [ % s ] and [ % \ [ range \ ] ] to delimit the end of the token . A scanning indication is introduced by a [ @ ] character , followed by some constant character [ c ] . It means that the string token should end just before the next matching [ c ] ( which is skipped ) . If no [ c ] character is encountered , the string token spreads as much as possible . For instance , [ " % s@\t " ] reads a string up to the next tab character or to the end of input . If a scanning indication [ \@c ] does not follow a string conversion , it is treated as a plain [ c ] character . Note : - the scanning indications introduce slight differences in the syntax of [ Scanf ] format strings , compared to those used for the [ Printf ] module . However , the scanning indications are similar to those used in the [ Format ] module ; hence , when producing formatted text to be scanned by [ ! Scanf.bscanf ] , it is wise to use printing functions from the [ Format ] module ( or , if you need to use functions from [ Printf ] , banish or carefully double check the format strings that contain [ ' \@ ' ] characters ) . and [%\[ range \]] to delimit the end of the token. A scanning indication is introduced by a [@] character, followed by some constant character [c]. It means that the string token should end just before the next matching [c] (which is skipped). If no [c] character is encountered, the string token spreads as much as possible. For instance, ["%s@\t"] reads a string up to the next tab character or to the end of input. If a scanning indication [\@c] does not follow a string conversion, it is treated as a plain [c] character. Note: - the scanning indications introduce slight differences in the syntax of [Scanf] format strings, compared to those used for the [Printf] module. However, the scanning indications are similar to those used in the [Format] module; hence, when producing formatted text to be scanned by [!Scanf.bscanf], it is wise to use printing functions from the [Format] module (or, if you need to use functions from [Printf], banish or carefully double check the format strings that contain ['\@'] characters). *) * { 7 Exceptions during scanning } * { 6 Specialized formatted input functions } val fscanf : in_channel -> ('a, 'b, 'c, 'd) scanner;; * Same as { ! Scanf.bscanf } , but reads from the given channel . Warning : since all formatted input functions operate from a scanning buffer , be aware that each [ fscanf ] invocation will operate with a scanning buffer reading from the given channel . This extra level of bufferization can lead to strange scanning behaviour if you use low level primitives on the channel ( reading characters , seeking the reading position , and so on ) . As a consequence , never mixt direct low level reading and high level scanning from the same input channel . Warning: since all formatted input functions operate from a scanning buffer, be aware that each [fscanf] invocation will operate with a scanning buffer reading from the given channel. This extra level of bufferization can lead to strange scanning behaviour if you use low level primitives on the channel (reading characters, seeking the reading position, and so on). As a consequence, never mixt direct low level reading and high level scanning from the same input channel. *) val sscanf : string -> ('a, 'b, 'c, 'd) scanner;; val scanf : ('a, 'b, 'c, 'd) scanner;; val kscanf : Scanning.scanbuf -> (Scanning.scanbuf -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner;; * { 6 Reading format strings from input } val bscanf_format : Scanning.scanbuf -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g;; val sscanf_format : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g;; val format_from_string : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6;;
f3c810b5bd1f1bb3425fd9a29c977c42c2587b7ed391553ccb0dc69f71e95442
uw-unsat/serval-sosp19
serval-llvm.rkt
#lang racket/base (require racket/port serval/llvm/parse serval/llvm/print) (define m (bytes->module (port->bytes))) (print-module m)
null
https://raw.githubusercontent.com/uw-unsat/serval-sosp19/175c42660fad84b44e4c9f6f723fd3c9450d65d4/serval/serval/bin/serval-llvm.rkt
racket
#lang racket/base (require racket/port serval/llvm/parse serval/llvm/print) (define m (bytes->module (port->bytes))) (print-module m)
17c23da6afc7c1905e90113fd237afe514fc07b9b9ec62da2eddafb1a6b1ea90
adomokos/haskell-katas
Ex16_HofsFunctionApplicationSpec.hs
module Ex16_HofsFunctionApplicationSpec ( spec ) where import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "Function application with $" $ do it "let's get rid of parens" $ do pending double the list of 1 - 6 and sum its values 41 `shouldBe` 42 sqrt of 3 + 4 + 9 3 `shouldBe` 4 double 1 - 5 , sum of elements greater than 5 5 `shouldBe` 24
null
https://raw.githubusercontent.com/adomokos/haskell-katas/be06d23192e6aca4297814455247fc74814ccbf1/test/Ex16_HofsFunctionApplicationSpec.hs
haskell
module Ex16_HofsFunctionApplicationSpec ( spec ) where import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "Function application with $" $ do it "let's get rid of parens" $ do pending double the list of 1 - 6 and sum its values 41 `shouldBe` 42 sqrt of 3 + 4 + 9 3 `shouldBe` 4 double 1 - 5 , sum of elements greater than 5 5 `shouldBe` 24
5c6d8aaa5d8d7fe6606e65a403a2fc9e3c6c4412c715b250defa66595fa9bb0f
MyDataFlow/ttalk-server
rest_stream_response_sup.erl
%% Feel free to use, reuse and abuse the code in this file. @private -module(rest_stream_response_sup). -behaviour(supervisor). %% API. -export([start_link/0]). %% supervisor. -export([init/1]). %% API. -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %% supervisor. init([]) -> Procs = [], {ok, {{one_for_one, 10, 10}, Procs}}.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/cowboy/examples/rest_stream_response/src/rest_stream_response_sup.erl
erlang
Feel free to use, reuse and abuse the code in this file. API. supervisor. API. supervisor.
@private -module(rest_stream_response_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> Procs = [], {ok, {{one_for_one, 10, 10}, Procs}}.
87b2370167c173962d3821256237ae2c5ad6aae7456cbeec50f59b0a4376ac89
fendor/hsimport
ModuleTest15.hs
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where
null
https://raw.githubusercontent.com/fendor/hsimport/9be9918b06545cfd7282e4db08c2b88f1d8162cd/tests/inputFiles/ModuleTest15.hs
haskell
# Language PatternGuards #
module Blub ( blub , foo , bar ) where
daa21b39f5c1d6f3067727e421556592dffb7d851311fa1a1e893774aecbf31a
tanakh/Peggy
LeftRec.hs
module Text.Peggy.LeftRec ( removeLeftRecursion, ) where import Text.Peggy.Syntax -- Remove only direct left recursion -- TODO: indirect left recursion removeLeftRecursion :: Syntax -> Syntax removeLeftRecursion = concatMap remove where remove (Definition nont typ (Choice es)) | not $ null alphas = [ Definition nont typ $ Choice [ Semantic (Sequence $ beta : [NonTerminal rest]) betaFrag | beta <- betas ] , Definition rest ("(" ++ typ ++ ") -> (" ++ typ ++")") $ Choice $ [ Sequence $ fs ++ [NonTerminal rest] | Sequence (_: fs) <- alphas ] ++ [ Semantic (Sequence $ fs ++ [NonTerminal rest]) (alphaFrag cf $ length (filter hasSemantic fs) + 1) | Semantic (Sequence (_: fs)) cf <- alphas ] ++ [ Semantic Empty idFrag ] ] where rest = nont ++ "_tail" (alphas, betas) = span isLeftRec es idFrag = [ Snippet "id" ] betaFrag = [ Argument 2 , Snippet " " , Argument 1 ] alphaFrag org ano = [ Snippet "\\v999 -> " , Argument ano , Snippet " ( " ] ++ map trans org ++ [ Snippet " )" ] trans (Argument n) | n == 1 = Argument 999 | otherwise = Argument (n - 1) trans e = e isLeftRec (Sequence (NonTerminal nt : _)) = nt == nont isLeftRec (Semantic e _) = isLeftRec e isLeftRec (Named _ e) = isLeftRec e isLeftRec _ = False hasSemantic (Terminals _ _ _) = False hasSemantic (And _) = False hasSemantic (Not _) = False hasSemantic _ = True remove d@(Definition nont _ (NonTerminal nt)) | nont == nt = error "cannot remove left recursion" | otherwise = [d] remove e = [e]
null
https://raw.githubusercontent.com/tanakh/Peggy/78280548d137c9ada703de0e4c9af1cd3cb8f728/Text/Peggy/LeftRec.hs
haskell
Remove only direct left recursion TODO: indirect left recursion
module Text.Peggy.LeftRec ( removeLeftRecursion, ) where import Text.Peggy.Syntax removeLeftRecursion :: Syntax -> Syntax removeLeftRecursion = concatMap remove where remove (Definition nont typ (Choice es)) | not $ null alphas = [ Definition nont typ $ Choice [ Semantic (Sequence $ beta : [NonTerminal rest]) betaFrag | beta <- betas ] , Definition rest ("(" ++ typ ++ ") -> (" ++ typ ++")") $ Choice $ [ Sequence $ fs ++ [NonTerminal rest] | Sequence (_: fs) <- alphas ] ++ [ Semantic (Sequence $ fs ++ [NonTerminal rest]) (alphaFrag cf $ length (filter hasSemantic fs) + 1) | Semantic (Sequence (_: fs)) cf <- alphas ] ++ [ Semantic Empty idFrag ] ] where rest = nont ++ "_tail" (alphas, betas) = span isLeftRec es idFrag = [ Snippet "id" ] betaFrag = [ Argument 2 , Snippet " " , Argument 1 ] alphaFrag org ano = [ Snippet "\\v999 -> " , Argument ano , Snippet " ( " ] ++ map trans org ++ [ Snippet " )" ] trans (Argument n) | n == 1 = Argument 999 | otherwise = Argument (n - 1) trans e = e isLeftRec (Sequence (NonTerminal nt : _)) = nt == nont isLeftRec (Semantic e _) = isLeftRec e isLeftRec (Named _ e) = isLeftRec e isLeftRec _ = False hasSemantic (Terminals _ _ _) = False hasSemantic (And _) = False hasSemantic (Not _) = False hasSemantic _ = True remove d@(Definition nont _ (NonTerminal nt)) | nont == nt = error "cannot remove left recursion" | otherwise = [d] remove e = [e]
7e49c121b626d58650fcdf23df04aa7217ad84898a5ef816e68e355fd028d61d
Odie/gd-edit
level.clj
(ns gd-edit.commands.level (:require [gd-edit.globals :as globals] [gd-edit.db-utils :as dbu] [gd-edit.printer :as printer] [gd-edit.level :refer :all] [clojure.data :refer [diff]] [gd-edit.utils :as u])) (defn fields-for--modify-character-level [character new-level] (dbu/coerce-map-numbers-using-reference {:character-level new-level :level-in-bio new-level :max-level new-level :experience (xp-total-at-level new-level) :skill-points (let [points-to-award (- (skill-points-total-at-level new-level) (skill-points-total-at-level (character :character-level)))] (max 0 (+ (:skill-points character) points-to-award))) :attribute-points (let [points-to-award (- (attribute-points-total-at-level new-level) (attribute-points-total-at-level (character :character-level)))] (max 0 (+ (:attribute-points character) points-to-award))) :masteries-allowed (max 2 (:masteries-allowed character))} character)) (defn modify-character-level [character new-level] (merge character (fields-for--modify-character-level character new-level))) (defn level-handler [[input tokens]] (cond (empty? tokens) (u/print-line "usage: level <new-level>") :else (let [level (dbu/coerce-str-to-type (first tokens) java.lang.Integer) level-limit (-> (dbu/record-by-name "records/creatures/pc/playerlevels.dbr") (get "maxPlayerLevel"))] (cond (= level :failed) (do (u/print-line "That's not a valid integer") :level-should-be-an-integer) (< level 1) (do (u/print-line "Please enter a level value that is 1 or greater") :level-should-be-positive) (> level level-limit) (do (u/print-line "Sorry, max allowed level is" level-limit) :max-level-exceeded) :else (let [modified-character (merge @globals/character (fields-for--modify-character-level @globals/character level))] (u/print-line "Changing level to" level) (u/newline-) (u/print-line "Updating the following fields:") (printer/print-map-difference (diff @globals/character modified-character)) (swap! globals/character modify-character-level level) :ok)))))
null
https://raw.githubusercontent.com/Odie/gd-edit/d1ac46fd6eb89c9571199641d9cc2f95e68d139b/src/gd_edit/commands/level.clj
clojure
(ns gd-edit.commands.level (:require [gd-edit.globals :as globals] [gd-edit.db-utils :as dbu] [gd-edit.printer :as printer] [gd-edit.level :refer :all] [clojure.data :refer [diff]] [gd-edit.utils :as u])) (defn fields-for--modify-character-level [character new-level] (dbu/coerce-map-numbers-using-reference {:character-level new-level :level-in-bio new-level :max-level new-level :experience (xp-total-at-level new-level) :skill-points (let [points-to-award (- (skill-points-total-at-level new-level) (skill-points-total-at-level (character :character-level)))] (max 0 (+ (:skill-points character) points-to-award))) :attribute-points (let [points-to-award (- (attribute-points-total-at-level new-level) (attribute-points-total-at-level (character :character-level)))] (max 0 (+ (:attribute-points character) points-to-award))) :masteries-allowed (max 2 (:masteries-allowed character))} character)) (defn modify-character-level [character new-level] (merge character (fields-for--modify-character-level character new-level))) (defn level-handler [[input tokens]] (cond (empty? tokens) (u/print-line "usage: level <new-level>") :else (let [level (dbu/coerce-str-to-type (first tokens) java.lang.Integer) level-limit (-> (dbu/record-by-name "records/creatures/pc/playerlevels.dbr") (get "maxPlayerLevel"))] (cond (= level :failed) (do (u/print-line "That's not a valid integer") :level-should-be-an-integer) (< level 1) (do (u/print-line "Please enter a level value that is 1 or greater") :level-should-be-positive) (> level level-limit) (do (u/print-line "Sorry, max allowed level is" level-limit) :max-level-exceeded) :else (let [modified-character (merge @globals/character (fields-for--modify-character-level @globals/character level))] (u/print-line "Changing level to" level) (u/newline-) (u/print-line "Updating the following fields:") (printer/print-map-difference (diff @globals/character modified-character)) (swap! globals/character modify-character-level level) :ok)))))
e2f850059f91107d185bcc915017ee76dc14951c1990bc02344b526cb880506a
bscarlet/llvm-general
FloatingPointPredicate.hs
# LANGUAGE MultiParamTypeClasses , TemplateHaskell # MultiParamTypeClasses, TemplateHaskell #-} module LLVM.General.Internal.FloatingPointPredicate where import LLVM.General.Internal.Coding import qualified LLVM.General.Internal.FFI.LLVMCTypes as FFI import qualified LLVM.General.AST.FloatingPointPredicate as A.FPPred genCodingInstance [t| A.FPPred.FloatingPointPredicate |] ''FFI.FCmpPredicate [ (FFI.fCmpPredFalse, A.FPPred.False), (FFI.fCmpPredOEQ, A.FPPred.OEQ), (FFI.fCmpPredOGT, A.FPPred.OGT), (FFI.fCmpPredOGE, A.FPPred.OGE), (FFI.fCmpPredOLT, A.FPPred.OLT), (FFI.fCmpPredOLE, A.FPPred.OLE), (FFI.fCmpPredONE, A.FPPred.ONE), (FFI.fCmpPredORD, A.FPPred.ORD), (FFI.fCmpPredUNO, A.FPPred.UNO), (FFI.fCmpPredUEQ, A.FPPred.UEQ), (FFI.fCmpPredUGT, A.FPPred.UGT), (FFI.fCmpPredUGE, A.FPPred.UGE), (FFI.fCmpPredULT, A.FPPred.ULT), (FFI.fCmpPredULE, A.FPPred.ULE), (FFI.fCmpPredUNE, A.FPPred.UNE), (FFI.fcmpPredTrue, A.FPPred.True) ]
null
https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/LLVM/General/Internal/FloatingPointPredicate.hs
haskell
# LANGUAGE MultiParamTypeClasses , TemplateHaskell # MultiParamTypeClasses, TemplateHaskell #-} module LLVM.General.Internal.FloatingPointPredicate where import LLVM.General.Internal.Coding import qualified LLVM.General.Internal.FFI.LLVMCTypes as FFI import qualified LLVM.General.AST.FloatingPointPredicate as A.FPPred genCodingInstance [t| A.FPPred.FloatingPointPredicate |] ''FFI.FCmpPredicate [ (FFI.fCmpPredFalse, A.FPPred.False), (FFI.fCmpPredOEQ, A.FPPred.OEQ), (FFI.fCmpPredOGT, A.FPPred.OGT), (FFI.fCmpPredOGE, A.FPPred.OGE), (FFI.fCmpPredOLT, A.FPPred.OLT), (FFI.fCmpPredOLE, A.FPPred.OLE), (FFI.fCmpPredONE, A.FPPred.ONE), (FFI.fCmpPredORD, A.FPPred.ORD), (FFI.fCmpPredUNO, A.FPPred.UNO), (FFI.fCmpPredUEQ, A.FPPred.UEQ), (FFI.fCmpPredUGT, A.FPPred.UGT), (FFI.fCmpPredUGE, A.FPPred.UGE), (FFI.fCmpPredULT, A.FPPred.ULT), (FFI.fCmpPredULE, A.FPPred.ULE), (FFI.fCmpPredUNE, A.FPPred.UNE), (FFI.fcmpPredTrue, A.FPPred.True) ]
445fe903afd053d22b1881edc639ec43d3dfc70993b0a564048ce2885843f02d
mbutterick/aoc-racket
star2.rkt
7491 a dec -511 if x >= -4 pq inc -45 if cfa == 7 vby dec 69 if tl < 1 yg dec 844 if v > -6 tl inc -756 if u != 9 l inc -267 if f == 0 hnd dec 74 if qcg < 9 pq inc 4 if f >= 0 pq dec -168 if u < 2 vby inc -778 if jus == 0 yg inc 676 if pq < 179 f dec 12 if u == 0 zo dec 347 if e == 0 q inc -934 if u >= -5 jus dec 40 if ewg > -2 f inc 8 if t != -7 u inc 610 if pq > 170 pq dec 565 if pq >= 176 ss dec 948 if x != -6 a dec 387 if ewg == 0 qcg inc -513 if v < 7 f dec -289 if uwm != -7 ewg dec 269 if u == 610 t dec 614 if ewg <= -263 f dec 411 if cfa <= 9 yg inc -62 if l != -271 x dec 210 if ss == -948 e dec 376 if l >= -259 jus dec 709 if v < 9 ewg inc -787 if l <= -266 tl inc -643 if vby == -847 zo inc 201 if e == 0 f dec -379 if t == -614 jus inc -963 if zo <= -147 v inc 653 if tl == -1399 ss dec 238 if v > 652 jus inc 551 if u <= 614 qcg inc 731 if ss > -1190 a inc 503 if x < -200 vby inc 209 if x != -204 f dec 434 if f > 260 t dec -364 if uwm > -6 vpd dec 616 if vpd < 8 v inc 100 if ss <= -1182 f dec -825 if a != 623 vby dec -51 if vpd > -620 v dec 861 if ss < -1184 hnd inc 270 if u >= 607 vpd dec -111 if a >= 637 a dec -720 if vpd < -615 l dec 882 if qcg < 215 zo inc -720 if ewg != -1062 q inc 109 if yg <= -229 a dec -599 if vby <= -586 vpd inc -111 if q != -827 cfa dec -775 if pq == 172 hnd dec -402 if txc == 0 t dec -886 if txc > -9 t dec -805 if ewg >= -1057 e dec -483 if yg < -224 pq dec 400 if pq == 172 t dec 125 if vby < -583 qos dec 318 if q <= -821 q dec 882 if qos <= -313 pq inc 333 if pq >= -232 v dec -378 if u <= 611 txc dec 863 if l != -260 vby dec 60 if x <= -218 u dec 386 if u != 610 q dec 876 if l == -267 l dec -884 if e == 483 u dec -445 if qos != -318 cfa dec -412 if v > 260 hnd dec -376 if q == -2580 yg dec -458 if a >= 1942 tl dec 783 if l <= 614 qos inc -864 if f <= 1081 uwm dec 872 if x > -211 t dec 988 if qos < -1187 jus dec -489 if x >= -212 ewg inc 410 if cfa < 1181 x inc 694 if vby == -587 q dec -185 if f <= 1084 txc dec -801 if v >= 263 uwm inc -52 if ewg > -1065 tl dec 535 if u <= 607 v dec 252 if yg == 228 jus dec 671 if t == 1319 yg inc 386 if l != 609 f dec 914 if cfa > 1185 yg inc -365 if zo > -870 ewg dec -439 if tl > -1393 qcg dec -325 if pq < 110 pq inc 303 if v >= 18 u inc -85 if vpd != -727 pq inc 41 if qos >= -1182 uwm inc -824 if cfa < 1178 txc inc 85 if hnd >= 591 hnd inc -107 if vpd == -727 x inc -73 if uwm < -917 e inc -257 if pq <= 458 v dec 122 if jus == 291 v inc 886 if qcg > 538 hnd inc -348 if cfa == 1187 yg dec 350 if u == 610 a dec 516 if ewg != -1051 qos dec 68 if f > 158 t dec 277 if qcg != 538 txc inc 594 if f == 164 ewg dec 873 if uwm == -932 yg dec 152 if l < 621 ewg inc 930 if v > 774 ss dec -229 if zo != -858 e inc 275 if ss >= -963 e inc -649 if tl != -1409 zo inc 976 if uwm >= -928 v dec -812 if e == -150 hnd inc -207 if v > 789 pq inc -614 if uwm >= -927 ss dec 16 if txc > 608 qos dec 312 if ss == -973 yg inc 615 if u <= 619 e inc -842 if ewg < -125 txc inc 109 if f <= 171 f dec 179 if t > 1045 pq dec 806 if ss <= -969 a inc -665 if hnd == 143 qos dec 31 if yg > 361 q dec -924 if uwm == -924 a dec 590 if pq > -975 cfa inc -56 if qos > -1597 vpd inc 318 if qcg != 548 cfa dec 755 if t > 1030 u inc -853 if vpd >= -414 uwm dec 247 if v != 789 qcg inc -746 if v < 784 vby dec -290 if u >= -247 v inc 474 if t != 1049 u dec -681 if q < -1464 uwm inc 290 if e < -983 f dec 220 if tl > -1393 ss inc 241 if l >= 615 ewg inc -502 if tl <= -1390 vby inc -960 if zo <= 113 a dec -112 if tl <= -1397 qos dec 787 if q <= -1470 x dec 836 if ewg > -631 ewg inc -665 if f <= 166 qcg inc 56 if pq >= -978 qcg dec -441 if vby >= -1257 l inc 176 if l != 615 jus dec -403 if cfa > 383 vpd dec 428 if qos <= -2371 u dec 232 if t < 1048 v dec 254 if f >= 158 txc inc 590 if vpd != -829 a dec -882 if txc > 1314 v inc -610 if v < 1007 e inc -388 if yg >= 357 qcg inc 229 if x != -419 hnd dec 873 if cfa <= 377 f dec -699 if vby > -1265 txc inc 38 if yg != 360 v dec -794 if jus == 291 txc inc -382 if jus <= 294 f inc 4 if uwm == -881 vpd inc -853 if hnd == -730 a inc 872 if cfa < 383 ss inc -131 if f > 858 jus dec -389 if txc > 978 vpd inc -61 if hnd >= -735 uwm dec -961 if cfa <= 384 f dec -264 if q <= -1481 f dec 946 if cfa >= 371 uwm dec 376 if pq > -978 qcg dec 652 if x == -425 vpd dec 285 if qcg <= -128 t dec -750 if l <= 799 cfa inc 638 if yg < 367 e inc -139 if hnd != -738 f inc 510 if qcg <= -128 v dec 114 if zo >= 107 zo inc -783 if uwm != -302 pq dec 116 if tl < -1397 tl inc 83 if uwm > -297 l inc 400 if qos >= -2383 l dec 0 if ss != -872 qcg inc -62 if tl != -1312 vby dec -417 if uwm == -303 ewg inc 356 if uwm == -296 zo dec 138 if hnd == -730 qcg inc 58 if cfa <= 1014 txc inc 283 if qos < -2379 qcg dec 572 if cfa <= 1017 x dec 213 if qos <= -2374 zo dec -884 if yg > 367 uwm dec 868 if q != -1483 zo dec -983 if ss == -863 ss inc -635 if tl == -1316 zo dec 383 if ewg == -931 ss inc -911 if q != -1469 txc inc -569 if v < 1079 v inc 372 if ewg > -947 v dec 936 if yg != 353 x dec -972 if a == 2041 yg dec 756 if q != -1467 vpd dec -696 if vpd >= -2034 txc dec -822 if cfa != 1021 l inc -211 if pq >= -1088 qcg dec -770 if e > -1520 qcg inc -787 if hnd != -725 vpd dec -689 if uwm <= -1161 l dec -219 if vpd >= -1347 l dec -344 if uwm <= -1163 f inc -545 if e > -1526 hnd dec 856 if e > -1518 cfa dec 993 if jus == 291 e dec -559 if txc > 1505 e inc -179 if txc < 1510 yg inc -230 if tl <= -1324 ss inc 117 if vby == -1257 f inc -398 if a >= 2035 x inc 302 if zo == 181 vpd dec 739 if vpd != -1355 t inc -165 if hnd <= -1585 pq inc 948 if ewg <= -930 ss dec -489 if cfa >= 15 ewg dec -937 if qos < -2377 q dec 209 if pq == -139 f dec -911 if v <= 515 zo dec -437 if x > 336 vpd inc 907 if jus < 300 e dec 957 if q == -1683 jus inc 153 if tl <= -1320 v inc 752 if qcg <= -717 tl inc -884 if q != -1688 a inc 363 if txc >= 1502 qos inc 469 if vpd > -1183 tl inc -524 if l > 1540 cfa dec -632 if e > -2102 f dec -31 if e < -2091 hnd inc 602 if hnd > -1594 e dec -373 if v == 1260 qcg dec 61 if t <= 1630 v inc -982 if vpd == -1183 uwm dec -308 if a != 2408 l dec 996 if qos > -1912 yg dec 977 if qcg != -775 tl inc 56 if t == 1624 pq dec -106 if l != 554 hnd dec 770 if ewg == 0 qos inc 553 if zo <= 180 f inc -879 if hnd < -1749 e dec -556 if f > -450 zo inc 564 if e >= -1166 qcg dec 937 if f <= -449 v inc -552 if q > -1693 a dec 450 if uwm != -854 a inc 18 if e <= -1162 ewg dec 754 if v <= 698 ewg dec -47 if uwm != -847 cfa inc 374 if vby < -1251 e dec 369 if e > -1162 hnd dec -203 if yg != -1371 ss dec -919 if q < -1677 txc dec 937 if qcg >= -1729 vby inc -105 if a >= 1972 ss inc -204 if txc <= 573 jus inc 626 if a >= 1968 ss dec 783 if v != 708 t inc -734 if cfa >= 1021 vby inc 899 if qcg == -1720 jus inc -5 if pq > -32 uwm dec -717 if zo <= 733 hnd inc -613 if x > 332 l inc -854 if pq <= -28 e inc 615 if u != 206 ss dec 944 if uwm > -862 a inc -491 if f > -451 yg inc 595 if txc < 580 cfa dec -628 if uwm < -849 uwm dec 171 if uwm <= -848 e dec 397 if vpd != -1171 tl dec -491 if l != -297 t dec 610 if q >= -1692 v inc 634 if vby < -456 jus dec 401 if vby != -471 ss inc 576 if a != 1481 f inc 885 if pq > -36 hnd dec 102 if x == 334 x dec -578 if e != -1567 txc inc -122 if cfa != 1660 e inc -915 if txc <= 451 uwm dec 683 if v >= 1336 a dec -523 if yg <= -771 jus dec 72 if cfa != 1650 u dec 524 if vpd != -1171 e inc 786 if qcg <= -1711 e inc -254 if q <= -1687 tl dec 992 if ewg > 50 vby dec 157 if u != -309 x dec -774 if cfa == 1655 v inc 842 if vby <= -612 t inc 64 if uwm < -1703 e inc 928 if f < 440 a dec -150 if hnd <= -2463 vpd inc -685 if yg == -776 tl inc -963 if a == 2154 ewg inc -804 if qos != -1363 tl dec -363 if ewg > -762 tl inc -769 if zo < 730 yg inc 635 if zo <= 732 tl inc -283 if jus < 447 uwm dec -918 if tl >= -3069 q dec -216 if jus != 452 a dec 727 if e == -763 q dec 467 if hnd > -2470 qos dec -420 if u <= -316 cfa dec 686 if q < -1930 tl dec 953 if v > 2182 f dec 473 if a != 1427 a inc 110 if uwm < -784 u inc -543 if qos == -938 x inc 591 if qcg != -1721 x dec 58 if f > 435 a dec -670 if yg < -774 pq inc -119 if hnd < -2468 ewg dec -254 if ss == -2031 cfa dec 279 if pq < -151 pq inc 274 if uwm > -801 tl inc -361 if cfa != 697 ss inc 797 if v > 2174 uwm inc -8 if x >= 2218 l dec -769 if u != -861 ewg inc -899 if vby >= -610 hnd inc -950 if qcg < -1712 jus inc 905 if e != -757 v dec 825 if vby >= -610 uwm dec -905 if a <= 2214 vpd inc -154 if l <= -301 vpd dec -345 if pq == 122 yg inc 75 if ss >= -1240 pq inc 208 if ewg <= -761 u dec -569 if qos >= -942 vby inc -840 if l >= -297 uwm inc 219 if u != -285 tl dec 956 if vby >= -625 zo inc -885 if vpd != -1673 ewg inc 536 if a < 2212 u inc -628 if ss > -1244 q inc 94 if ewg >= -216 cfa dec 212 if uwm >= 316 pq inc 776 if q != -1943 x dec 244 if zo < 745 vby inc 267 if pq <= 899 jus inc 512 if vby < -352 v inc 942 if jus < 1852 qos dec 364 if t > 341 qcg inc -695 if cfa <= 483 zo dec 221 if e < -758 u inc 218 if vby == -353 e inc -423 if hnd != -3419 f inc 631 if ss >= -1244 ss inc -487 if t < 352 txc dec 351 if l == -308 pq inc 581 if qos > -1305 q inc -740 if uwm != 324 v dec -929 if x <= 1981 jus dec -782 if u == -702 yg inc 197 if vpd < -1663 ewg inc 604 if ss != -1721 tl dec -426 if qos == -1308 zo inc 627 if q < -1941 f inc 815 if ewg == 383 f dec -567 if x != 1981 u inc 836 if tl > -5332 ewg inc -787 if ss >= -1715 uwm dec -513 if qcg <= -2423 l dec 396 if zo != 511 f dec 928 if u <= 139 txc inc -2 if cfa == 478 vpd dec -936 if t != 352 zo inc -269 if q <= -1931 zo inc -600 if zo != 246 f dec 723 if hnd > -3416 v inc -707 if vby < -348 a dec -205 if l <= -710 qos dec -396 if jus < 2651 cfa dec 107 if qos > -913 a inc 861 if txc >= 456 uwm inc -700 if hnd == -3420 x dec -347 if uwm >= 331 t dec -857 if qcg < -2408 a dec -876 if a >= 2204 qos inc 563 if pq < 1487 x dec -11 if cfa >= 363 yg inc -114 if e <= -759 vby inc 439 if pq < 1485 a inc 394 if x < 1989 zo inc -996 if zo <= 246 jus dec -685 if hnd != -3426 t dec 465 if q != -1929 txc inc 728 if vpd >= -742 vby dec -134 if hnd < -3412 jus inc -485 if e >= -765 v inc 220 if l == -697 f inc 470 if txc <= 1175 e dec 783 if uwm == 324 jus dec -697 if cfa >= 369 qos dec 790 if vpd >= -737 jus inc 654 if l < -693 tl dec -803 if a >= 3470 txc dec -738 if vpd <= -745 uwm inc 67 if cfa != 371 f dec -702 if l < -692 x dec -280 if qos == -1133 jus inc 917 if ewg == 383 e inc -198 if yg <= -610 v dec -387 if hnd <= -3415 u inc 751 if uwm >= 318 a dec -432 if pq >= 1485 t inc -946 if vby >= 218 pq dec -76 if f >= 2690 txc dec 16 if qcg >= -2415 t dec 302 if txc != 1158 pq dec -818 if uwm <= 316 q dec -404 if zo < -748 f inc -563 if yg != -625 x inc -686 if e != -1750 txc dec -413 if vby >= 214 uwm dec 968 if vpd != -730 e dec 908 if txc <= 1575 cfa dec -787 if a >= 3470 yg inc -393 if qcg >= -2417 cfa inc -874 if uwm == -644 ss inc 466 if ewg < 387 zo dec -858 if vpd < -731 ss dec 566 if txc <= 1562 vpd dec -237 if tl != -4529 yg inc -486 if vpd < -494 cfa dec 635 if qos >= -1131 jus dec -62 if x > 1572 cfa dec 76 if e >= -2643 a inc -207 if ewg == 383 pq inc -674 if yg < -1497 zo inc -952 if jus != 5182 tl inc -258 if yg <= -1488 cfa dec -818 if txc <= 1580 tl inc 695 if pq >= 1548 e inc 919 if q == -1530 t inc -340 if u >= 881 e dec -449 if vby >= 218 ewg dec -468 if cfa == 1102 yg inc 617 if pq != 1548 zo dec 809 if pq <= 1563 vby dec -685 if uwm == -644 cfa inc -157 if e < -1283 zo inc 65 if uwm <= -640 f dec 729 if e != -1278 l inc -313 if hnd > -3423 jus dec 180 if x >= 1574 jus inc -520 if ss < -1255 hnd dec -493 if f >= 1403 jus inc -783 if qos < -1136 e dec -486 if t <= -848 u dec 248 if q >= -1530 u inc -379 if vby != 901 pq inc 590 if qcg > -2408 l inc 757 if uwm <= -644 q dec 283 if uwm >= -644 t inc 681 if tl > -4097 uwm inc 359 if ss < -1248 v dec -725 if ss > -1260 x dec 584 if txc != 1573 ss dec 938 if x < 1002 cfa dec -19 if ewg <= 851 f dec 909 if u == 258 v dec -295 if f < 498 l inc -132 if uwm >= -291 u inc 921 if l >= -390 pq inc -253 if u == 1189 l inc -431 if jus != 4473 qos dec -855 if qos <= -1132 qos dec 691 if yg >= -882 jus inc 117 if cfa >= 955 qcg dec 438 if yg < -875 tl dec -922 if tl <= -4088 ewg dec -424 if qcg == -2862 l dec 249 if x < 1004 tl inc 388 if e >= -800 ss inc -962 if q > -1820 zo inc -141 if ss <= -3147 pq inc -508 if vby < 908 t inc -64 if l == -638 cfa dec 534 if qos <= -968 v inc 906 if tl == -2780 hnd inc -830 if f != 497 qcg dec -186 if vby >= 907 uwm dec -155 if t < -242 ss dec -312 if hnd <= -4251 tl inc -619 if x == 996 txc inc -620 if e == -798 uwm dec 861 if l == -638 t inc 715 if t > -233 cfa dec 603 if zo > -1726 cfa inc -523 if pq > 1042 a dec 547 if uwm == -1151 l dec -8 if jus < 4593 e inc -601 if t <= -230 qcg dec -637 if yg >= -879 l dec 814 if qos != -969 jus inc 204 if tl < -3399 yg dec 111 if pq > 1050 qcg inc -188 if qos >= -971 a dec 760 if vpd > -504 jus dec -523 if hnd != -4247 q dec 664 if e <= -1398 txc inc -8 if q >= -2477 e inc -333 if yg >= -888 txc inc -222 if u >= 1173 jus dec 304 if x < 987 a inc -766 if vby < 912 qos inc 464 if pq > 1037 cfa inc 500 if q >= -2479 jus dec 49 if u < 1187 hnd inc -440 if cfa >= 403 txc inc -741 if yg <= -873 ewg inc 836 if hnd > -4696 v dec -890 if vpd != -500 q dec 954 if vpd != -509 t inc 846 if e > -1739 ewg dec -458 if vpd == -500 t inc -995 if e <= -1732 u dec -987 if q < -3427 l dec -303 if pq < 1054 t dec 527 if qos <= -498 ewg inc 607 if hnd >= -4689 l dec 203 if e >= -1733 zo dec -961 if qcg != -3032 t dec 880 if a >= 1741 x dec -447 if t != -1787 pq inc 735 if pq > 1043 f inc 386 if u > 2167 t dec 886 if hnd != -4689 e inc 395 if yg < -889 a dec -361 if txc != -24 q inc 837 if e >= -1732 uwm inc 779 if qcg >= -3050 ewg dec -506 if ewg <= 2761 e inc 367 if v >= 4717 jus dec 710 if vby <= 908 v inc 956 if l != -531 e inc -724 if cfa != 417 a dec -54 if v < 5685 qos inc -463 if tl >= -3405 a inc 634 if hnd < -4695 txc dec -613 if x <= 1450 t inc -595 if txc > 602 zo inc 807 if yg < -870 uwm dec -253 if x != 1444 v dec 249 if u != 2173 cfa dec 286 if pq != 1791 jus dec 340 if ewg < 3261 e inc 391 if yg <= -879 v inc -554 if qos >= -961 u inc 118 if a < 2168 ss dec -898 if txc == 590 ewg inc 757 if l > -525 tl dec -250 if u != 2284 f inc -51 if l > -525 f inc 574 if x >= 1437 e inc -55 if yg >= -881 yg dec -832 if tl == -3391 yg dec 176 if vby <= 899 u dec 215 if a <= 2155 x inc -411 if ewg <= 3264 u inc -76 if vby <= 912 q dec -479 if ss > -3163 qos dec -136 if tl < -3398 ss inc -631 if qos <= -839 cfa dec 561 if pq < 1786 ss inc -817 if uwm > -119 qos dec -544 if l >= -522 qos dec -82 if u != 2205 vpd dec 427 if qcg >= -3049 u dec 296 if uwm > -115 x inc -533 if tl >= -3405 ss inc -529 if q > -2125 e inc 745 if uwm < -109 cfa inc -488 if l == -530 vpd inc 778 if txc > 593 jus dec -399 if l < -526 u inc 144 if x < 500 t dec -554 if u < 2066 txc inc -200 if u > 2055 zo inc 382 if qos != -750 pq inc -191 if jus != 4409 vby dec 602 if a >= 2150 qcg dec -517 if tl < -3397 jus dec -416 if jus == 4413 uwm inc 157 if f != 1066 vpd dec -888 if yg == -880 tl dec 79 if qcg > -2533 pq dec 604 if e < -1006 hnd dec -901 if l != -522 qcg dec 328 if qos != -744 yg inc -412 if cfa != -938 ewg dec -571 if vpd < 744 cfa inc -925 if qos == -750 qcg dec -605 if yg < -1284 x inc 470 if pq >= 987 hnd dec 82 if yg < -1286 qcg dec -874 if pq != 987 x dec 457 if hnd <= -3862 ewg dec -591 if qos > -752 ss dec -820 if zo >= 39 v inc -967 if tl != -3482 v inc 742 if jus > 4825 f dec -381 if cfa != -1862 qcg inc -868 if cfa <= -1850 qcg dec -358 if x < 518 txc inc -23 if x != 503 l dec -239 if jus <= 4830 qcg inc -771 if pq == 996 hnd dec -724 if vby <= 310 cfa inc -823 if hnd > -3140 v dec -558 if x > 504 t inc -89 if uwm > -118 jus inc 432 if ss <= -3678 jus inc -343 if zo >= 31 yg dec 474 if ewg == 4420 q dec 330 if jus >= 4915 qos dec 805 if zo == 46 qcg inc 670 if t >= -1326 f dec 945 if vby > 310 jus inc -68 if q <= -2440 tl dec -424 if a == 2159 tl inc 460 if u <= 2063 f dec -759 if uwm != -120 v inc 507 if qcg == -2078 zo inc 881 if pq <= 990 qcg inc -792 if yg <= -1769 qos dec -730 if ewg <= 4420 f inc 968 if pq <= 989 tl dec -539 if txc < 376 vpd dec 823 if ewg >= 4429 qos dec -476 if ss <= -3692 qos dec 609 if vby > 303 u inc -266 if x == 506 v inc -99 if pq < 990 q dec -627 if ss <= -3680 qos dec 372 if t >= -1334 cfa inc 959 if qcg >= -2086 x dec -893 if hnd > -3156 x inc 69 if vby > 300 qcg inc 333 if ss <= -3673 e dec 525 if u < 2064 yg inc 402 if tl == -2055 ewg dec 938 if u > 2050 tl dec 989 if e != -1526 f inc 894 if cfa != -1854 t inc -834 if txc >= 370 yg dec 197 if ss != -3682 f inc -741 if zo >= 926 l dec -257 if v != 5659 a dec -713 if a > 2158 jus inc -279 if ewg <= 3487 v dec -910 if ss < -3673 e dec -601 if cfa >= -1854 tl dec -106 if ewg > 3477 x inc -144 if yg < -1361 zo dec -454 if ss != -3678 a inc -887 if l > -43 ss inc 184 if ewg >= 3490 jus dec 865 if txc == 371 q dec 156 if cfa == -1853 ss inc 435 if a != 1989 l inc -121 if a < 1995 qos dec 846 if f < 4076 jus inc -580 if q == -1974 vby inc 11 if e != -938 q dec -355 if hnd >= -3146 vpd dec -49 if jus <= 3132 cfa inc -311 if uwm != -123 vby inc -541 if a >= 1990 f dec -11 if ss < -3238 e inc 964 if zo == 1374 pq inc -380 if yg > -1369 q dec -140 if x > 1320 jus inc -605 if yg < -1362 ss inc -520 if pq > 616 uwm inc -686 if jus != 2528 jus inc 523 if e <= 32 pq inc 658 if x >= 1329 pq inc -513 if vby >= 320 q dec 161 if x != 1330 u dec 943 if a == 1985 yg inc 785 if cfa < -2156 hnd dec -969 if txc > 362 ss inc 74 if l < -146 ss dec 63 if cfa >= -2171 txc inc 331 if ss > -3246 qcg dec 229 if uwm <= -792 u inc -497 if v == 6570 uwm dec -725 if cfa >= -2163 f dec -439 if u != 616 a dec 11 if v >= 6563 e dec 176 if u != 618 v inc 921 if e < -138 e dec 656 if a == 1974 hnd dec 64 if qcg == -1983 hnd inc 779 if v > 7481 tl inc 421 if cfa == -2157 ewg dec -732 if uwm == -800 x dec 223 if q <= -1473 zo inc 74 if ss == -3242 ss dec -594 if uwm <= -793 x inc -507 if ss < -2639 f dec -68 if e == -800 cfa dec -763 if jus == 3044 t inc 931 if a <= 1978 pq inc -602 if ewg <= 4217 ss dec 512 if l <= -154 t dec 145 if qcg > -1989 cfa inc -621 if f == 4147 e inc 430 if f > 4145 f dec -800 if ss > -3157 a dec 496 if v > 7482 qcg dec 289 if t <= -1369 yg inc -634 if vpd >= 783 e dec 722 if ewg <= 4214 ewg dec 506 if qcg != -2272 q dec 911 if f == 4947 f inc -515 if tl < -2932 x dec 788 if qcg >= -2280 a dec -542 if yg != -1218 yg inc -124 if ss != -3155 v dec 510 if vpd != 795 l inc 920 if vpd == 783 u dec 314 if tl != -2940 tl dec 375 if pq == 663 tl inc 358 if jus != 3049 x dec 41 if uwm <= -805 zo inc 844 if yg != -1343 v inc -463 if ss <= -3148 hnd dec 99 if hnd >= -1462 v dec 357 if pq > 670 v dec 974 if u < 294 e inc -375 if e < -1090 u inc -501 if yg <= -1336 zo inc -563 if a <= 2018 t inc -602 if v == 6518 qos inc 366 if vby >= 316 jus inc -366 if t >= -1985 f inc -218 if u > -202 zo inc 932 if jus >= 2676 l inc -50 if qcg > -2268 ewg inc 170 if pq == 670 hnd dec 605 if f < 4221 pq inc 746 if u <= -205 f inc 582 if uwm == -800 x dec -43 if tl != -2955 ss dec -420 if q >= -2395 jus dec -493 if ss > -2736 x dec 977 if ss >= -2736 uwm inc 956 if e < -1461 l dec -397 if vpd <= 791 vpd inc 548 if pq > 655 vby dec -958 if t != -1976 pq dec -565 if jus >= 3163 q dec -667 if yg >= -1345 cfa dec -6 if jus < 3179 e inc 842 if tl <= -2953 q inc 680 if jus > 3166 txc dec -618 if l > 238 cfa dec -494 if l >= 242 t dec -969 if uwm <= 163 ss dec 421 if ss != -2734 t inc -548 if tl <= -2949 uwm dec -835 if t >= -1546 tl inc -393 if f == 4796 vpd dec 643 if cfa == -1530 x inc 768 if vby == 314 a inc -252 if jus == 3171 f inc 177 if f >= 4797 v dec -352 if e >= -615 yg inc -913 if jus < 3181 qos dec -893 if l == 242 a inc -627 if vby <= 321 txc dec -351 if tl != -3343 cfa dec -913 if zo < 3150 txc dec -750 if txc < 1672 a inc 803 if hnd == -2176 jus dec 188 if jus < 3178 zo dec -350 if ewg > 4206 f dec -941 if ewg >= 4206 pq inc -603 if hnd > -2175 q inc 360 if t <= -1547 pq dec 475 if pq >= 630 yg inc 931 if l >= 235 t dec 361 if x > -399 a dec -383 if yg <= -1313 f dec -777 if t != -1914 yg inc 169 if uwm > 149 qos inc 239 if t >= -1920 vby dec -903 if txc < 2424 jus dec 889 if jus >= 2983 v inc -172 if cfa <= -1514 v inc -278 if e >= -633 t dec -929 if hnd != -2164 a inc 918 if t >= -996 x inc -690 if vby == 1217 zo dec 268 if txc >= 2420 v dec -591 if t >= -989 x inc -620 if vpd != 1332 l inc 51 if ewg < 4220 f inc -518 if qcg != -2267 vby dec 898 if uwm == 156 jus dec -53 if l == 293 hnd dec -127 if qos == -105 uwm dec -99 if q >= -692 q inc 340 if hnd >= -2175 vpd dec 740 if vby <= 321 a inc -931 if qos > -105 hnd inc -25 if qos < -100 pq dec 366 if tl >= -3353 f dec -126 if a <= 2449 yg dec 642 if ss >= -2739 ss inc 735 if jus > 2156 t dec -329 if qos <= -104 q inc -292 if x > -1714 vpd inc -406 if hnd != -2183 e dec -367 if tl != -3343 yg inc 891 if x == -1707 uwm dec -520 if vpd >= 184 yg inc -180 if jus == 2147 uwm inc -767 if l >= 300 txc inc -728 if jus == 2147 q dec -876 if zo == 3232 ss dec -255 if vpd > 187 qcg inc -360 if t > -667 jus dec 357 if v != 6658 ss dec 239 if t > -652 cfa inc 349 if txc < 1701 cfa inc 185 if hnd <= -2188 q dec 858 if vby <= 323 ss dec 290 if yg == -1081 cfa dec -473 if yg > -1073 qcg inc -333 if ss < -2766 l dec 539 if hnd > -2200 v inc -210 if hnd <= -2190 e inc 531 if a < 2447 yg dec -156 if e != 265 t dec -188 if q < -610 vpd inc 757 if qos == -106 zo dec 801 if x > -1713 u dec -49 if a < 2445 qos inc -451 if tl >= -3352 q dec -531 if x >= -1712 a inc 32 if jus > 1784 ss inc -258 if pq != 261 cfa dec 445 if l >= -251 t inc 897 if l <= -256 e dec -199 if hnd < -2182 vby inc 309 if v == 6449 ewg dec 839 if qos == -565 hnd inc 961 if hnd >= -2199 cfa inc -780 if qcg == -2974 ewg dec 443 if qcg == -2965 hnd inc -901 if uwm < 780 ss inc 597 if vpd == 947 txc inc 453 if yg > -930 u dec -871 if a < 2468 x dec -789 if u > -160 jus dec 702 if f >= 6127 v inc -298 if u < -141 uwm dec 424 if uwm == 775 cfa dec -497 if pq == 259 ewg dec 984 if t == -470 vpd dec -287 if t > -478 q dec -288 if zo == 2431 a dec -402 if l < -240 cfa dec 560 if cfa == -926 u inc -127 if jus == 1790 yg dec -832 if yg > -930 uwm inc 366 if hnd < -2128 tl dec 18 if l > -252 vby dec -423 if vpd < 1239 u dec -879 if ewg == 2780 uwm inc 204 if uwm >= 711 l inc 545 if ewg > 2794 t dec 383 if uwm == 921 t inc 464 if vby != 1054 jus inc -997 if vby < 1060 u inc 347 if uwm <= 926 v inc 468 if tl >= -3372 v dec 797 if v <= 6626 u inc 971 if l >= -252 ewg dec -319 if vpd < 1239 hnd dec 893 if x < -913 tl inc -593 if txc <= 2148 qcg inc 382 if q >= 193 pq dec -987 if tl >= -3951 yg inc -111 if jus == 793 tl dec -780 if uwm != 919 pq inc -914 if tl < -3176 t dec 677 if jus >= 789 ewg dec -842 if cfa <= -944 uwm inc 736 if pq >= -648 ewg inc 106 if jus > 784 f dec -472 if jus != 785 e inc 382 if qos != -549 vpd inc 955 if yg < -197 txc dec -976 if pq == -660 a inc 453 if x != -908 q inc 287 if t >= -1072 uwm inc 422 if l > -255 hnd dec -230 if qcg <= -2580 v dec 868 if ewg == 3212 x dec -567 if l < -238 tl dec 595 if jus != 788 u dec -860 if pq != -662 e inc -541 if cfa >= -940 f dec 330 if vby < 1059 tl dec -41 if qcg == -2583 f inc -394 if u != 1899 a dec -962 if x < -353 a dec 303 if vpd != 2189 u inc -371 if q < 493 yg inc 0 if tl < -3734 hnd dec -273 if e >= 311 t dec -138 if qcg > -2588 e dec 644 if f == 5877 qcg dec 968 if yg < -202 x dec 208 if tl <= -3730 u dec -776 if txc < 2153 q inc -432 if vpd == 2189 cfa dec -325 if uwm != 1344 e dec -384 if zo >= 2429 ss dec -879 if a < 3332 u inc -571 if t != -925 t dec 970 if l >= -244 ewg dec 713 if uwm > 1333 a dec 527 if uwm < 1348 f inc -962 if u == 1737 cfa dec -790 if e < 704 cfa inc 516 if yg > -210 uwm dec 654 if zo == 2428 qcg inc -176 if ewg != 2507 u inc -92 if e >= 696 a inc -14 if yg == -204 vby inc -72 if v < 4956 a dec -983 if q <= 62 yg inc 422 if cfa > 696 jus inc 685 if t > -938 e inc 449 if jus < 1483 v dec 593 if t >= -932 v dec 595 if q >= 55 e inc 332 if e <= 1154 tl dec -34 if ewg == 2499 ewg inc 24 if f < 5872 ewg dec -129 if txc == 2146 pq dec 815 if hnd != -2531 tl inc 456 if a == 3764 tl dec 942 if a <= 3773 x inc 610 if x >= -558 u inc -68 if txc < 2150 ewg dec -897 if jus == 1474 vpd inc -158 if jus != 1475 e inc 852 if v != 3775 pq inc 169 if zo >= 2427 zo dec -82 if v >= 3765 qcg inc 221 if u < 1584 ss dec 958 if tl > -4640 a inc -545 if f >= 5868 ss dec -864 if qcg != -3515 t inc 980 if cfa < 698 zo dec 58 if f > 5867 q dec 43 if u == 1575 qos dec -992 if vpd == 2031 t dec -823 if x >= -564 x inc 647 if qos != 445 l inc 231 if l == -246 ewg inc -776 if zo < 2464 q dec 367 if q > 13 jus dec 956 if v != 3770 txc dec 952 if v != 3766 x inc 145 if qcg >= -3507 e dec 597 if x <= 236 cfa inc -860 if f <= 5878 f inc -649 if jus != 512 tl inc -885 if f != 5227 qcg inc -610 if q == -353 ewg dec 342 if txc <= 2137 hnd dec 495 if yg >= -207 vby dec -713 if q < -345 ewg dec 72 if cfa > -174 jus inc 897 if zo == 2455 v dec -582 if zo > 2452 x dec 368 if f >= 5212
null
https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/2017/d08/star2.rkt
racket
7491 a dec -511 if x >= -4 pq inc -45 if cfa == 7 vby dec 69 if tl < 1 yg dec 844 if v > -6 tl inc -756 if u != 9 l inc -267 if f == 0 hnd dec 74 if qcg < 9 pq inc 4 if f >= 0 pq dec -168 if u < 2 vby inc -778 if jus == 0 yg inc 676 if pq < 179 f dec 12 if u == 0 zo dec 347 if e == 0 q inc -934 if u >= -5 jus dec 40 if ewg > -2 f inc 8 if t != -7 u inc 610 if pq > 170 pq dec 565 if pq >= 176 ss dec 948 if x != -6 a dec 387 if ewg == 0 qcg inc -513 if v < 7 f dec -289 if uwm != -7 ewg dec 269 if u == 610 t dec 614 if ewg <= -263 f dec 411 if cfa <= 9 yg inc -62 if l != -271 x dec 210 if ss == -948 e dec 376 if l >= -259 jus dec 709 if v < 9 ewg inc -787 if l <= -266 tl inc -643 if vby == -847 zo inc 201 if e == 0 f dec -379 if t == -614 jus inc -963 if zo <= -147 v inc 653 if tl == -1399 ss dec 238 if v > 652 jus inc 551 if u <= 614 qcg inc 731 if ss > -1190 a inc 503 if x < -200 vby inc 209 if x != -204 f dec 434 if f > 260 t dec -364 if uwm > -6 vpd dec 616 if vpd < 8 v inc 100 if ss <= -1182 f dec -825 if a != 623 vby dec -51 if vpd > -620 v dec 861 if ss < -1184 hnd inc 270 if u >= 607 vpd dec -111 if a >= 637 a dec -720 if vpd < -615 l dec 882 if qcg < 215 zo inc -720 if ewg != -1062 q inc 109 if yg <= -229 a dec -599 if vby <= -586 vpd inc -111 if q != -827 cfa dec -775 if pq == 172 hnd dec -402 if txc == 0 t dec -886 if txc > -9 t dec -805 if ewg >= -1057 e dec -483 if yg < -224 pq dec 400 if pq == 172 t dec 125 if vby < -583 qos dec 318 if q <= -821 q dec 882 if qos <= -313 pq inc 333 if pq >= -232 v dec -378 if u <= 611 txc dec 863 if l != -260 vby dec 60 if x <= -218 u dec 386 if u != 610 q dec 876 if l == -267 l dec -884 if e == 483 u dec -445 if qos != -318 cfa dec -412 if v > 260 hnd dec -376 if q == -2580 yg dec -458 if a >= 1942 tl dec 783 if l <= 614 qos inc -864 if f <= 1081 uwm dec 872 if x > -211 t dec 988 if qos < -1187 jus dec -489 if x >= -212 ewg inc 410 if cfa < 1181 x inc 694 if vby == -587 q dec -185 if f <= 1084 txc dec -801 if v >= 263 uwm inc -52 if ewg > -1065 tl dec 535 if u <= 607 v dec 252 if yg == 228 jus dec 671 if t == 1319 yg inc 386 if l != 609 f dec 914 if cfa > 1185 yg inc -365 if zo > -870 ewg dec -439 if tl > -1393 qcg dec -325 if pq < 110 pq inc 303 if v >= 18 u inc -85 if vpd != -727 pq inc 41 if qos >= -1182 uwm inc -824 if cfa < 1178 txc inc 85 if hnd >= 591 hnd inc -107 if vpd == -727 x inc -73 if uwm < -917 e inc -257 if pq <= 458 v dec 122 if jus == 291 v inc 886 if qcg > 538 hnd inc -348 if cfa == 1187 yg dec 350 if u == 610 a dec 516 if ewg != -1051 qos dec 68 if f > 158 t dec 277 if qcg != 538 txc inc 594 if f == 164 ewg dec 873 if uwm == -932 yg dec 152 if l < 621 ewg inc 930 if v > 774 ss dec -229 if zo != -858 e inc 275 if ss >= -963 e inc -649 if tl != -1409 zo inc 976 if uwm >= -928 v dec -812 if e == -150 hnd inc -207 if v > 789 pq inc -614 if uwm >= -927 ss dec 16 if txc > 608 qos dec 312 if ss == -973 yg inc 615 if u <= 619 e inc -842 if ewg < -125 txc inc 109 if f <= 171 f dec 179 if t > 1045 pq dec 806 if ss <= -969 a inc -665 if hnd == 143 qos dec 31 if yg > 361 q dec -924 if uwm == -924 a dec 590 if pq > -975 cfa inc -56 if qos > -1597 vpd inc 318 if qcg != 548 cfa dec 755 if t > 1030 u inc -853 if vpd >= -414 uwm dec 247 if v != 789 qcg inc -746 if v < 784 vby dec -290 if u >= -247 v inc 474 if t != 1049 u dec -681 if q < -1464 uwm inc 290 if e < -983 f dec 220 if tl > -1393 ss inc 241 if l >= 615 ewg inc -502 if tl <= -1390 vby inc -960 if zo <= 113 a dec -112 if tl <= -1397 qos dec 787 if q <= -1470 x dec 836 if ewg > -631 ewg inc -665 if f <= 166 qcg inc 56 if pq >= -978 qcg dec -441 if vby >= -1257 l inc 176 if l != 615 jus dec -403 if cfa > 383 vpd dec 428 if qos <= -2371 u dec 232 if t < 1048 v dec 254 if f >= 158 txc inc 590 if vpd != -829 a dec -882 if txc > 1314 v inc -610 if v < 1007 e inc -388 if yg >= 357 qcg inc 229 if x != -419 hnd dec 873 if cfa <= 377 f dec -699 if vby > -1265 txc inc 38 if yg != 360 v dec -794 if jus == 291 txc inc -382 if jus <= 294 f inc 4 if uwm == -881 vpd inc -853 if hnd == -730 a inc 872 if cfa < 383 ss inc -131 if f > 858 jus dec -389 if txc > 978 vpd inc -61 if hnd >= -735 uwm dec -961 if cfa <= 384 f dec -264 if q <= -1481 f dec 946 if cfa >= 371 uwm dec 376 if pq > -978 qcg dec 652 if x == -425 vpd dec 285 if qcg <= -128 t dec -750 if l <= 799 cfa inc 638 if yg < 367 e inc -139 if hnd != -738 f inc 510 if qcg <= -128 v dec 114 if zo >= 107 zo inc -783 if uwm != -302 pq dec 116 if tl < -1397 tl inc 83 if uwm > -297 l inc 400 if qos >= -2383 l dec 0 if ss != -872 qcg inc -62 if tl != -1312 vby dec -417 if uwm == -303 ewg inc 356 if uwm == -296 zo dec 138 if hnd == -730 qcg inc 58 if cfa <= 1014 txc inc 283 if qos < -2379 qcg dec 572 if cfa <= 1017 x dec 213 if qos <= -2374 zo dec -884 if yg > 367 uwm dec 868 if q != -1483 zo dec -983 if ss == -863 ss inc -635 if tl == -1316 zo dec 383 if ewg == -931 ss inc -911 if q != -1469 txc inc -569 if v < 1079 v inc 372 if ewg > -947 v dec 936 if yg != 353 x dec -972 if a == 2041 yg dec 756 if q != -1467 vpd dec -696 if vpd >= -2034 txc dec -822 if cfa != 1021 l inc -211 if pq >= -1088 qcg dec -770 if e > -1520 qcg inc -787 if hnd != -725 vpd dec -689 if uwm <= -1161 l dec -219 if vpd >= -1347 l dec -344 if uwm <= -1163 f inc -545 if e > -1526 hnd dec 856 if e > -1518 cfa dec 993 if jus == 291 e dec -559 if txc > 1505 e inc -179 if txc < 1510 yg inc -230 if tl <= -1324 ss inc 117 if vby == -1257 f inc -398 if a >= 2035 x inc 302 if zo == 181 vpd dec 739 if vpd != -1355 t inc -165 if hnd <= -1585 pq inc 948 if ewg <= -930 ss dec -489 if cfa >= 15 ewg dec -937 if qos < -2377 q dec 209 if pq == -139 f dec -911 if v <= 515 zo dec -437 if x > 336 vpd inc 907 if jus < 300 e dec 957 if q == -1683 jus inc 153 if tl <= -1320 v inc 752 if qcg <= -717 tl inc -884 if q != -1688 a inc 363 if txc >= 1502 qos inc 469 if vpd > -1183 tl inc -524 if l > 1540 cfa dec -632 if e > -2102 f dec -31 if e < -2091 hnd inc 602 if hnd > -1594 e dec -373 if v == 1260 qcg dec 61 if t <= 1630 v inc -982 if vpd == -1183 uwm dec -308 if a != 2408 l dec 996 if qos > -1912 yg dec 977 if qcg != -775 tl inc 56 if t == 1624 pq dec -106 if l != 554 hnd dec 770 if ewg == 0 qos inc 553 if zo <= 180 f inc -879 if hnd < -1749 e dec -556 if f > -450 zo inc 564 if e >= -1166 qcg dec 937 if f <= -449 v inc -552 if q > -1693 a dec 450 if uwm != -854 a inc 18 if e <= -1162 ewg dec 754 if v <= 698 ewg dec -47 if uwm != -847 cfa inc 374 if vby < -1251 e dec 369 if e > -1162 hnd dec -203 if yg != -1371 ss dec -919 if q < -1677 txc dec 937 if qcg >= -1729 vby inc -105 if a >= 1972 ss inc -204 if txc <= 573 jus inc 626 if a >= 1968 ss dec 783 if v != 708 t inc -734 if cfa >= 1021 vby inc 899 if qcg == -1720 jus inc -5 if pq > -32 uwm dec -717 if zo <= 733 hnd inc -613 if x > 332 l inc -854 if pq <= -28 e inc 615 if u != 206 ss dec 944 if uwm > -862 a inc -491 if f > -451 yg inc 595 if txc < 580 cfa dec -628 if uwm < -849 uwm dec 171 if uwm <= -848 e dec 397 if vpd != -1171 tl dec -491 if l != -297 t dec 610 if q >= -1692 v inc 634 if vby < -456 jus dec 401 if vby != -471 ss inc 576 if a != 1481 f inc 885 if pq > -36 hnd dec 102 if x == 334 x dec -578 if e != -1567 txc inc -122 if cfa != 1660 e inc -915 if txc <= 451 uwm dec 683 if v >= 1336 a dec -523 if yg <= -771 jus dec 72 if cfa != 1650 u dec 524 if vpd != -1171 e inc 786 if qcg <= -1711 e inc -254 if q <= -1687 tl dec 992 if ewg > 50 vby dec 157 if u != -309 x dec -774 if cfa == 1655 v inc 842 if vby <= -612 t inc 64 if uwm < -1703 e inc 928 if f < 440 a dec -150 if hnd <= -2463 vpd inc -685 if yg == -776 tl inc -963 if a == 2154 ewg inc -804 if qos != -1363 tl dec -363 if ewg > -762 tl inc -769 if zo < 730 yg inc 635 if zo <= 732 tl inc -283 if jus < 447 uwm dec -918 if tl >= -3069 q dec -216 if jus != 452 a dec 727 if e == -763 q dec 467 if hnd > -2470 qos dec -420 if u <= -316 cfa dec 686 if q < -1930 tl dec 953 if v > 2182 f dec 473 if a != 1427 a inc 110 if uwm < -784 u inc -543 if qos == -938 x inc 591 if qcg != -1721 x dec 58 if f > 435 a dec -670 if yg < -774 pq inc -119 if hnd < -2468 ewg dec -254 if ss == -2031 cfa dec 279 if pq < -151 pq inc 274 if uwm > -801 tl inc -361 if cfa != 697 ss inc 797 if v > 2174 uwm inc -8 if x >= 2218 l dec -769 if u != -861 ewg inc -899 if vby >= -610 hnd inc -950 if qcg < -1712 jus inc 905 if e != -757 v dec 825 if vby >= -610 uwm dec -905 if a <= 2214 vpd inc -154 if l <= -301 vpd dec -345 if pq == 122 yg inc 75 if ss >= -1240 pq inc 208 if ewg <= -761 u dec -569 if qos >= -942 vby inc -840 if l >= -297 uwm inc 219 if u != -285 tl dec 956 if vby >= -625 zo inc -885 if vpd != -1673 ewg inc 536 if a < 2212 u inc -628 if ss > -1244 q inc 94 if ewg >= -216 cfa dec 212 if uwm >= 316 pq inc 776 if q != -1943 x dec 244 if zo < 745 vby inc 267 if pq <= 899 jus inc 512 if vby < -352 v inc 942 if jus < 1852 qos dec 364 if t > 341 qcg inc -695 if cfa <= 483 zo dec 221 if e < -758 u inc 218 if vby == -353 e inc -423 if hnd != -3419 f inc 631 if ss >= -1244 ss inc -487 if t < 352 txc dec 351 if l == -308 pq inc 581 if qos > -1305 q inc -740 if uwm != 324 v dec -929 if x <= 1981 jus dec -782 if u == -702 yg inc 197 if vpd < -1663 ewg inc 604 if ss != -1721 tl dec -426 if qos == -1308 zo inc 627 if q < -1941 f inc 815 if ewg == 383 f dec -567 if x != 1981 u inc 836 if tl > -5332 ewg inc -787 if ss >= -1715 uwm dec -513 if qcg <= -2423 l dec 396 if zo != 511 f dec 928 if u <= 139 txc inc -2 if cfa == 478 vpd dec -936 if t != 352 zo inc -269 if q <= -1931 zo inc -600 if zo != 246 f dec 723 if hnd > -3416 v inc -707 if vby < -348 a dec -205 if l <= -710 qos dec -396 if jus < 2651 cfa dec 107 if qos > -913 a inc 861 if txc >= 456 uwm inc -700 if hnd == -3420 x dec -347 if uwm >= 331 t dec -857 if qcg < -2408 a dec -876 if a >= 2204 qos inc 563 if pq < 1487 x dec -11 if cfa >= 363 yg inc -114 if e <= -759 vby inc 439 if pq < 1485 a inc 394 if x < 1989 zo inc -996 if zo <= 246 jus dec -685 if hnd != -3426 t dec 465 if q != -1929 txc inc 728 if vpd >= -742 vby dec -134 if hnd < -3412 jus inc -485 if e >= -765 v inc 220 if l == -697 f inc 470 if txc <= 1175 e dec 783 if uwm == 324 jus dec -697 if cfa >= 369 qos dec 790 if vpd >= -737 jus inc 654 if l < -693 tl dec -803 if a >= 3470 txc dec -738 if vpd <= -745 uwm inc 67 if cfa != 371 f dec -702 if l < -692 x dec -280 if qos == -1133 jus inc 917 if ewg == 383 e inc -198 if yg <= -610 v dec -387 if hnd <= -3415 u inc 751 if uwm >= 318 a dec -432 if pq >= 1485 t inc -946 if vby >= 218 pq dec -76 if f >= 2690 txc dec 16 if qcg >= -2415 t dec 302 if txc != 1158 pq dec -818 if uwm <= 316 q dec -404 if zo < -748 f inc -563 if yg != -625 x inc -686 if e != -1750 txc dec -413 if vby >= 214 uwm dec 968 if vpd != -730 e dec 908 if txc <= 1575 cfa dec -787 if a >= 3470 yg inc -393 if qcg >= -2417 cfa inc -874 if uwm == -644 ss inc 466 if ewg < 387 zo dec -858 if vpd < -731 ss dec 566 if txc <= 1562 vpd dec -237 if tl != -4529 yg inc -486 if vpd < -494 cfa dec 635 if qos >= -1131 jus dec -62 if x > 1572 cfa dec 76 if e >= -2643 a inc -207 if ewg == 383 pq inc -674 if yg < -1497 zo inc -952 if jus != 5182 tl inc -258 if yg <= -1488 cfa dec -818 if txc <= 1580 tl inc 695 if pq >= 1548 e inc 919 if q == -1530 t inc -340 if u >= 881 e dec -449 if vby >= 218 ewg dec -468 if cfa == 1102 yg inc 617 if pq != 1548 zo dec 809 if pq <= 1563 vby dec -685 if uwm == -644 cfa inc -157 if e < -1283 zo inc 65 if uwm <= -640 f dec 729 if e != -1278 l inc -313 if hnd > -3423 jus dec 180 if x >= 1574 jus inc -520 if ss < -1255 hnd dec -493 if f >= 1403 jus inc -783 if qos < -1136 e dec -486 if t <= -848 u dec 248 if q >= -1530 u inc -379 if vby != 901 pq inc 590 if qcg > -2408 l inc 757 if uwm <= -644 q dec 283 if uwm >= -644 t inc 681 if tl > -4097 uwm inc 359 if ss < -1248 v dec -725 if ss > -1260 x dec 584 if txc != 1573 ss dec 938 if x < 1002 cfa dec -19 if ewg <= 851 f dec 909 if u == 258 v dec -295 if f < 498 l inc -132 if uwm >= -291 u inc 921 if l >= -390 pq inc -253 if u == 1189 l inc -431 if jus != 4473 qos dec -855 if qos <= -1132 qos dec 691 if yg >= -882 jus inc 117 if cfa >= 955 qcg dec 438 if yg < -875 tl dec -922 if tl <= -4088 ewg dec -424 if qcg == -2862 l dec 249 if x < 1004 tl inc 388 if e >= -800 ss inc -962 if q > -1820 zo inc -141 if ss <= -3147 pq inc -508 if vby < 908 t inc -64 if l == -638 cfa dec 534 if qos <= -968 v inc 906 if tl == -2780 hnd inc -830 if f != 497 qcg dec -186 if vby >= 907 uwm dec -155 if t < -242 ss dec -312 if hnd <= -4251 tl inc -619 if x == 996 txc inc -620 if e == -798 uwm dec 861 if l == -638 t inc 715 if t > -233 cfa dec 603 if zo > -1726 cfa inc -523 if pq > 1042 a dec 547 if uwm == -1151 l dec -8 if jus < 4593 e inc -601 if t <= -230 qcg dec -637 if yg >= -879 l dec 814 if qos != -969 jus inc 204 if tl < -3399 yg dec 111 if pq > 1050 qcg inc -188 if qos >= -971 a dec 760 if vpd > -504 jus dec -523 if hnd != -4247 q dec 664 if e <= -1398 txc inc -8 if q >= -2477 e inc -333 if yg >= -888 txc inc -222 if u >= 1173 jus dec 304 if x < 987 a inc -766 if vby < 912 qos inc 464 if pq > 1037 cfa inc 500 if q >= -2479 jus dec 49 if u < 1187 hnd inc -440 if cfa >= 403 txc inc -741 if yg <= -873 ewg inc 836 if hnd > -4696 v dec -890 if vpd != -500 q dec 954 if vpd != -509 t inc 846 if e > -1739 ewg dec -458 if vpd == -500 t inc -995 if e <= -1732 u dec -987 if q < -3427 l dec -303 if pq < 1054 t dec 527 if qos <= -498 ewg inc 607 if hnd >= -4689 l dec 203 if e >= -1733 zo dec -961 if qcg != -3032 t dec 880 if a >= 1741 x dec -447 if t != -1787 pq inc 735 if pq > 1043 f inc 386 if u > 2167 t dec 886 if hnd != -4689 e inc 395 if yg < -889 a dec -361 if txc != -24 q inc 837 if e >= -1732 uwm inc 779 if qcg >= -3050 ewg dec -506 if ewg <= 2761 e inc 367 if v >= 4717 jus dec 710 if vby <= 908 v inc 956 if l != -531 e inc -724 if cfa != 417 a dec -54 if v < 5685 qos inc -463 if tl >= -3405 a inc 634 if hnd < -4695 txc dec -613 if x <= 1450 t inc -595 if txc > 602 zo inc 807 if yg < -870 uwm dec -253 if x != 1444 v dec 249 if u != 2173 cfa dec 286 if pq != 1791 jus dec 340 if ewg < 3261 e inc 391 if yg <= -879 v inc -554 if qos >= -961 u inc 118 if a < 2168 ss dec -898 if txc == 590 ewg inc 757 if l > -525 tl dec -250 if u != 2284 f inc -51 if l > -525 f inc 574 if x >= 1437 e inc -55 if yg >= -881 yg dec -832 if tl == -3391 yg dec 176 if vby <= 899 u dec 215 if a <= 2155 x inc -411 if ewg <= 3264 u inc -76 if vby <= 912 q dec -479 if ss > -3163 qos dec -136 if tl < -3398 ss inc -631 if qos <= -839 cfa dec 561 if pq < 1786 ss inc -817 if uwm > -119 qos dec -544 if l >= -522 qos dec -82 if u != 2205 vpd dec 427 if qcg >= -3049 u dec 296 if uwm > -115 x inc -533 if tl >= -3405 ss inc -529 if q > -2125 e inc 745 if uwm < -109 cfa inc -488 if l == -530 vpd inc 778 if txc > 593 jus dec -399 if l < -526 u inc 144 if x < 500 t dec -554 if u < 2066 txc inc -200 if u > 2055 zo inc 382 if qos != -750 pq inc -191 if jus != 4409 vby dec 602 if a >= 2150 qcg dec -517 if tl < -3397 jus dec -416 if jus == 4413 uwm inc 157 if f != 1066 vpd dec -888 if yg == -880 tl dec 79 if qcg > -2533 pq dec 604 if e < -1006 hnd dec -901 if l != -522 qcg dec 328 if qos != -744 yg inc -412 if cfa != -938 ewg dec -571 if vpd < 744 cfa inc -925 if qos == -750 qcg dec -605 if yg < -1284 x inc 470 if pq >= 987 hnd dec 82 if yg < -1286 qcg dec -874 if pq != 987 x dec 457 if hnd <= -3862 ewg dec -591 if qos > -752 ss dec -820 if zo >= 39 v inc -967 if tl != -3482 v inc 742 if jus > 4825 f dec -381 if cfa != -1862 qcg inc -868 if cfa <= -1850 qcg dec -358 if x < 518 txc inc -23 if x != 503 l dec -239 if jus <= 4830 qcg inc -771 if pq == 996 hnd dec -724 if vby <= 310 cfa inc -823 if hnd > -3140 v dec -558 if x > 504 t inc -89 if uwm > -118 jus inc 432 if ss <= -3678 jus inc -343 if zo >= 31 yg dec 474 if ewg == 4420 q dec 330 if jus >= 4915 qos dec 805 if zo == 46 qcg inc 670 if t >= -1326 f dec 945 if vby > 310 jus inc -68 if q <= -2440 tl dec -424 if a == 2159 tl inc 460 if u <= 2063 f dec -759 if uwm != -120 v inc 507 if qcg == -2078 zo inc 881 if pq <= 990 qcg inc -792 if yg <= -1769 qos dec -730 if ewg <= 4420 f inc 968 if pq <= 989 tl dec -539 if txc < 376 vpd dec 823 if ewg >= 4429 qos dec -476 if ss <= -3692 qos dec 609 if vby > 303 u inc -266 if x == 506 v inc -99 if pq < 990 q dec -627 if ss <= -3680 qos dec 372 if t >= -1334 cfa inc 959 if qcg >= -2086 x dec -893 if hnd > -3156 x inc 69 if vby > 300 qcg inc 333 if ss <= -3673 e dec 525 if u < 2064 yg inc 402 if tl == -2055 ewg dec 938 if u > 2050 tl dec 989 if e != -1526 f inc 894 if cfa != -1854 t inc -834 if txc >= 370 yg dec 197 if ss != -3682 f inc -741 if zo >= 926 l dec -257 if v != 5659 a dec -713 if a > 2158 jus inc -279 if ewg <= 3487 v dec -910 if ss < -3673 e dec -601 if cfa >= -1854 tl dec -106 if ewg > 3477 x inc -144 if yg < -1361 zo dec -454 if ss != -3678 a inc -887 if l > -43 ss inc 184 if ewg >= 3490 jus dec 865 if txc == 371 q dec 156 if cfa == -1853 ss inc 435 if a != 1989 l inc -121 if a < 1995 qos dec 846 if f < 4076 jus inc -580 if q == -1974 vby inc 11 if e != -938 q dec -355 if hnd >= -3146 vpd dec -49 if jus <= 3132 cfa inc -311 if uwm != -123 vby inc -541 if a >= 1990 f dec -11 if ss < -3238 e inc 964 if zo == 1374 pq inc -380 if yg > -1369 q dec -140 if x > 1320 jus inc -605 if yg < -1362 ss inc -520 if pq > 616 uwm inc -686 if jus != 2528 jus inc 523 if e <= 32 pq inc 658 if x >= 1329 pq inc -513 if vby >= 320 q dec 161 if x != 1330 u dec 943 if a == 1985 yg inc 785 if cfa < -2156 hnd dec -969 if txc > 362 ss inc 74 if l < -146 ss dec 63 if cfa >= -2171 txc inc 331 if ss > -3246 qcg dec 229 if uwm <= -792 u inc -497 if v == 6570 uwm dec -725 if cfa >= -2163 f dec -439 if u != 616 a dec 11 if v >= 6563 e dec 176 if u != 618 v inc 921 if e < -138 e dec 656 if a == 1974 hnd dec 64 if qcg == -1983 hnd inc 779 if v > 7481 tl inc 421 if cfa == -2157 ewg dec -732 if uwm == -800 x dec 223 if q <= -1473 zo inc 74 if ss == -3242 ss dec -594 if uwm <= -793 x inc -507 if ss < -2639 f dec -68 if e == -800 cfa dec -763 if jus == 3044 t inc 931 if a <= 1978 pq inc -602 if ewg <= 4217 ss dec 512 if l <= -154 t dec 145 if qcg > -1989 cfa inc -621 if f == 4147 e inc 430 if f > 4145 f dec -800 if ss > -3157 a dec 496 if v > 7482 qcg dec 289 if t <= -1369 yg inc -634 if vpd >= 783 e dec 722 if ewg <= 4214 ewg dec 506 if qcg != -2272 q dec 911 if f == 4947 f inc -515 if tl < -2932 x dec 788 if qcg >= -2280 a dec -542 if yg != -1218 yg inc -124 if ss != -3155 v dec 510 if vpd != 795 l inc 920 if vpd == 783 u dec 314 if tl != -2940 tl dec 375 if pq == 663 tl inc 358 if jus != 3049 x dec 41 if uwm <= -805 zo inc 844 if yg != -1343 v inc -463 if ss <= -3148 hnd dec 99 if hnd >= -1462 v dec 357 if pq > 670 v dec 974 if u < 294 e inc -375 if e < -1090 u inc -501 if yg <= -1336 zo inc -563 if a <= 2018 t inc -602 if v == 6518 qos inc 366 if vby >= 316 jus inc -366 if t >= -1985 f inc -218 if u > -202 zo inc 932 if jus >= 2676 l inc -50 if qcg > -2268 ewg inc 170 if pq == 670 hnd dec 605 if f < 4221 pq inc 746 if u <= -205 f inc 582 if uwm == -800 x dec -43 if tl != -2955 ss dec -420 if q >= -2395 jus dec -493 if ss > -2736 x dec 977 if ss >= -2736 uwm inc 956 if e < -1461 l dec -397 if vpd <= 791 vpd inc 548 if pq > 655 vby dec -958 if t != -1976 pq dec -565 if jus >= 3163 q dec -667 if yg >= -1345 cfa dec -6 if jus < 3179 e inc 842 if tl <= -2953 q inc 680 if jus > 3166 txc dec -618 if l > 238 cfa dec -494 if l >= 242 t dec -969 if uwm <= 163 ss dec 421 if ss != -2734 t inc -548 if tl <= -2949 uwm dec -835 if t >= -1546 tl inc -393 if f == 4796 vpd dec 643 if cfa == -1530 x inc 768 if vby == 314 a inc -252 if jus == 3171 f inc 177 if f >= 4797 v dec -352 if e >= -615 yg inc -913 if jus < 3181 qos dec -893 if l == 242 a inc -627 if vby <= 321 txc dec -351 if tl != -3343 cfa dec -913 if zo < 3150 txc dec -750 if txc < 1672 a inc 803 if hnd == -2176 jus dec 188 if jus < 3178 zo dec -350 if ewg > 4206 f dec -941 if ewg >= 4206 pq inc -603 if hnd > -2175 q inc 360 if t <= -1547 pq dec 475 if pq >= 630 yg inc 931 if l >= 235 t dec 361 if x > -399 a dec -383 if yg <= -1313 f dec -777 if t != -1914 yg inc 169 if uwm > 149 qos inc 239 if t >= -1920 vby dec -903 if txc < 2424 jus dec 889 if jus >= 2983 v inc -172 if cfa <= -1514 v inc -278 if e >= -633 t dec -929 if hnd != -2164 a inc 918 if t >= -996 x inc -690 if vby == 1217 zo dec 268 if txc >= 2420 v dec -591 if t >= -989 x inc -620 if vpd != 1332 l inc 51 if ewg < 4220 f inc -518 if qcg != -2267 vby dec 898 if uwm == 156 jus dec -53 if l == 293 hnd dec -127 if qos == -105 uwm dec -99 if q >= -692 q inc 340 if hnd >= -2175 vpd dec 740 if vby <= 321 a inc -931 if qos > -105 hnd inc -25 if qos < -100 pq dec 366 if tl >= -3353 f dec -126 if a <= 2449 yg dec 642 if ss >= -2739 ss inc 735 if jus > 2156 t dec -329 if qos <= -104 q inc -292 if x > -1714 vpd inc -406 if hnd != -2183 e dec -367 if tl != -3343 yg inc 891 if x == -1707 uwm dec -520 if vpd >= 184 yg inc -180 if jus == 2147 uwm inc -767 if l >= 300 txc inc -728 if jus == 2147 q dec -876 if zo == 3232 ss dec -255 if vpd > 187 qcg inc -360 if t > -667 jus dec 357 if v != 6658 ss dec 239 if t > -652 cfa inc 349 if txc < 1701 cfa inc 185 if hnd <= -2188 q dec 858 if vby <= 323 ss dec 290 if yg == -1081 cfa dec -473 if yg > -1073 qcg inc -333 if ss < -2766 l dec 539 if hnd > -2200 v inc -210 if hnd <= -2190 e inc 531 if a < 2447 yg dec -156 if e != 265 t dec -188 if q < -610 vpd inc 757 if qos == -106 zo dec 801 if x > -1713 u dec -49 if a < 2445 qos inc -451 if tl >= -3352 q dec -531 if x >= -1712 a inc 32 if jus > 1784 ss inc -258 if pq != 261 cfa dec 445 if l >= -251 t inc 897 if l <= -256 e dec -199 if hnd < -2182 vby inc 309 if v == 6449 ewg dec 839 if qos == -565 hnd inc 961 if hnd >= -2199 cfa inc -780 if qcg == -2974 ewg dec 443 if qcg == -2965 hnd inc -901 if uwm < 780 ss inc 597 if vpd == 947 txc inc 453 if yg > -930 u dec -871 if a < 2468 x dec -789 if u > -160 jus dec 702 if f >= 6127 v inc -298 if u < -141 uwm dec 424 if uwm == 775 cfa dec -497 if pq == 259 ewg dec 984 if t == -470 vpd dec -287 if t > -478 q dec -288 if zo == 2431 a dec -402 if l < -240 cfa dec 560 if cfa == -926 u inc -127 if jus == 1790 yg dec -832 if yg > -930 uwm inc 366 if hnd < -2128 tl dec 18 if l > -252 vby dec -423 if vpd < 1239 u dec -879 if ewg == 2780 uwm inc 204 if uwm >= 711 l inc 545 if ewg > 2794 t dec 383 if uwm == 921 t inc 464 if vby != 1054 jus inc -997 if vby < 1060 u inc 347 if uwm <= 926 v inc 468 if tl >= -3372 v dec 797 if v <= 6626 u inc 971 if l >= -252 ewg dec -319 if vpd < 1239 hnd dec 893 if x < -913 tl inc -593 if txc <= 2148 qcg inc 382 if q >= 193 pq dec -987 if tl >= -3951 yg inc -111 if jus == 793 tl dec -780 if uwm != 919 pq inc -914 if tl < -3176 t dec 677 if jus >= 789 ewg dec -842 if cfa <= -944 uwm inc 736 if pq >= -648 ewg inc 106 if jus > 784 f dec -472 if jus != 785 e inc 382 if qos != -549 vpd inc 955 if yg < -197 txc dec -976 if pq == -660 a inc 453 if x != -908 q inc 287 if t >= -1072 uwm inc 422 if l > -255 hnd dec -230 if qcg <= -2580 v dec 868 if ewg == 3212 x dec -567 if l < -238 tl dec 595 if jus != 788 u dec -860 if pq != -662 e inc -541 if cfa >= -940 f dec 330 if vby < 1059 tl dec -41 if qcg == -2583 f inc -394 if u != 1899 a dec -962 if x < -353 a dec 303 if vpd != 2189 u inc -371 if q < 493 yg inc 0 if tl < -3734 hnd dec -273 if e >= 311 t dec -138 if qcg > -2588 e dec 644 if f == 5877 qcg dec 968 if yg < -202 x dec 208 if tl <= -3730 u dec -776 if txc < 2153 q inc -432 if vpd == 2189 cfa dec -325 if uwm != 1344 e dec -384 if zo >= 2429 ss dec -879 if a < 3332 u inc -571 if t != -925 t dec 970 if l >= -244 ewg dec 713 if uwm > 1333 a dec 527 if uwm < 1348 f inc -962 if u == 1737 cfa dec -790 if e < 704 cfa inc 516 if yg > -210 uwm dec 654 if zo == 2428 qcg inc -176 if ewg != 2507 u inc -92 if e >= 696 a inc -14 if yg == -204 vby inc -72 if v < 4956 a dec -983 if q <= 62 yg inc 422 if cfa > 696 jus inc 685 if t > -938 e inc 449 if jus < 1483 v dec 593 if t >= -932 v dec 595 if q >= 55 e inc 332 if e <= 1154 tl dec -34 if ewg == 2499 ewg inc 24 if f < 5872 ewg dec -129 if txc == 2146 pq dec 815 if hnd != -2531 tl inc 456 if a == 3764 tl dec 942 if a <= 3773 x inc 610 if x >= -558 u inc -68 if txc < 2150 ewg dec -897 if jus == 1474 vpd inc -158 if jus != 1475 e inc 852 if v != 3775 pq inc 169 if zo >= 2427 zo dec -82 if v >= 3765 qcg inc 221 if u < 1584 ss dec 958 if tl > -4640 a inc -545 if f >= 5868 ss dec -864 if qcg != -3515 t inc 980 if cfa < 698 zo dec 58 if f > 5867 q dec 43 if u == 1575 qos dec -992 if vpd == 2031 t dec -823 if x >= -564 x inc 647 if qos != 445 l inc 231 if l == -246 ewg inc -776 if zo < 2464 q dec 367 if q > 13 jus dec 956 if v != 3770 txc dec 952 if v != 3766 x inc 145 if qcg >= -3507 e dec 597 if x <= 236 cfa inc -860 if f <= 5878 f inc -649 if jus != 512 tl inc -885 if f != 5227 qcg inc -610 if q == -353 ewg dec 342 if txc <= 2137 hnd dec 495 if yg >= -207 vby dec -713 if q < -345 ewg dec 72 if cfa > -174 jus inc 897 if zo == 2455 v dec -582 if zo > 2452 x dec 368 if f >= 5212
abad38c664a681bd39647ed633e6d86ba2e329b2e3cb05c0bc7624809b39184f
zellige/zellige
MvtFeaturesSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Data.Geometry.Types.MvtFeaturesSpec where import qualified Data.Aeson as Aeson import qualified Data.HashMap.Strict as HashMapStrict import qualified Data.Scientific as Scientific import qualified Data.Sequence as Sequence import qualified Data.Geometry.VectorTile.VectorTile as VectorTile import Test.Hspec (Spec, describe, it, shouldBe) import qualified Data.Geometry.Types.MvtFeatures as TypesMvtFeatures spec :: Spec spec = do testConvertProps testAddKeyValue testConvertProps :: Spec testConvertProps = describe "Simple" $ it "Simple conversion of an Aeson value" $ do let testVals = Aeson.Object (HashMapStrict.fromList [("key1", Aeson.Number (Scientific.fromFloatDigits (1.0 :: Float))), ("key2", Aeson.String "string"), ("key3", Aeson.Bool True)]) actual = TypesMvtFeatures.convertProps testVals actual `shouldBe` HashMapStrict.fromList [("key1", VectorTile.Do 1.0), ("key2", VectorTile.St "string"), ("key3", VectorTile.B True)] testAddKeyValue :: Spec testAddKeyValue = describe "Simple" $ do it "Simple add a new key value" $ do let expected = (1, HashMapStrict.fromList [(5,0)], Sequence.fromList [5]) actual = TypesMvtFeatures.addKeyValue 0 (5 :: Int) HashMapStrict.empty Sequence.empty id actual `shouldBe` expected it "Add to an existing" $ do let expected = (2, HashMapStrict.fromList [(5,0), (6,1)], Sequence.fromList [5,6]) actual = TypesMvtFeatures.addKeyValue 1 (6 :: Int) (HashMapStrict.fromList ([(5,0)] :: [(Int, Int)]))(Sequence.fromList ([5] :: [Int])) id actual `shouldBe` expected
null
https://raw.githubusercontent.com/zellige/zellige/87e6dab11ac4c1843009043580f14422a1d83ebf/test/Data/Geometry/Types/MvtFeaturesSpec.hs
haskell
# LANGUAGE OverloadedStrings #
module Data.Geometry.Types.MvtFeaturesSpec where import qualified Data.Aeson as Aeson import qualified Data.HashMap.Strict as HashMapStrict import qualified Data.Scientific as Scientific import qualified Data.Sequence as Sequence import qualified Data.Geometry.VectorTile.VectorTile as VectorTile import Test.Hspec (Spec, describe, it, shouldBe) import qualified Data.Geometry.Types.MvtFeatures as TypesMvtFeatures spec :: Spec spec = do testConvertProps testAddKeyValue testConvertProps :: Spec testConvertProps = describe "Simple" $ it "Simple conversion of an Aeson value" $ do let testVals = Aeson.Object (HashMapStrict.fromList [("key1", Aeson.Number (Scientific.fromFloatDigits (1.0 :: Float))), ("key2", Aeson.String "string"), ("key3", Aeson.Bool True)]) actual = TypesMvtFeatures.convertProps testVals actual `shouldBe` HashMapStrict.fromList [("key1", VectorTile.Do 1.0), ("key2", VectorTile.St "string"), ("key3", VectorTile.B True)] testAddKeyValue :: Spec testAddKeyValue = describe "Simple" $ do it "Simple add a new key value" $ do let expected = (1, HashMapStrict.fromList [(5,0)], Sequence.fromList [5]) actual = TypesMvtFeatures.addKeyValue 0 (5 :: Int) HashMapStrict.empty Sequence.empty id actual `shouldBe` expected it "Add to an existing" $ do let expected = (2, HashMapStrict.fromList [(5,0), (6,1)], Sequence.fromList [5,6]) actual = TypesMvtFeatures.addKeyValue 1 (6 :: Int) (HashMapStrict.fromList ([(5,0)] :: [(Int, Int)]))(Sequence.fromList ([5] :: [Int])) id actual `shouldBe` expected
bc74a80596df07e6a9c2d011e113499e610e71bd30d20b24142e4855718505b2
racket/pkg-build
pkg-list.rkt
#lang racket/base (require racket/cmdline pkg/lib) (define scope 'installation) (command-line #:once-each [("--user") "User scope" (set! scope 'user)]) (write (installed-pkg-names #:scope scope))
null
https://raw.githubusercontent.com/racket/pkg-build/31fea3651b501e2ad333cf6133527290abd2eed1/private/pkg-list.rkt
racket
#lang racket/base (require racket/cmdline pkg/lib) (define scope 'installation) (command-line #:once-each [("--user") "User scope" (set! scope 'user)]) (write (installed-pkg-names #:scope scope))
3a9bf0533d13bf2be9fc1c557e9b3d555dee771568a9de215ce09b98eb46fe24
input-output-hk/plutus-apps
Helpers.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # module Helpers where import Control.Concurrent qualified as IO import Control.Concurrent.Async qualified as IO import Control.Monad (void, when) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Function ((&)) import Data.Map qualified as Map import Data.Set qualified as Set import GHC.Stack qualified as GHC import Streaming.Prelude qualified as S import System.Directory qualified as IO import System.Environment qualified as IO import System.FilePath ((</>)) import System.IO qualified as IO import System.IO.Temp qualified as IO import System.Info qualified as IO import Hedgehog (MonadTest) import Hedgehog qualified as H import Hedgehog.Extras.Stock.CallStack qualified as H import Hedgehog.Extras.Stock.IO.Network.Sprocket qualified as IO import Hedgehog.Extras.Test qualified as HE import Hedgehog.Extras.Test.Base qualified as H import Cardano.Api qualified as C import Cardano.Api.Shelley qualified as C import Cardano.Streaming qualified as CS import Ouroboros.Network.Protocol.LocalTxSubmission.Type (SubmitResult (SubmitFail, SubmitSuccess)) import Test.Runtime qualified as TN import Testnet.Cardano qualified as TN import Testnet.Conf qualified as TC (Conf (..), ProjectBase (ProjectBase), YamlFilePath (YamlFilePath), mkConf) -- | Start a testnet. startTestnet :: TN.TestnetOptions -> FilePath -> FilePath -> H.Integration (C.LocalNodeConnectInfo C.CardanoMode, TC.Conf, TN.TestnetRuntime) startTestnet testnetOptions base tempAbsBasePath' = do configurationTemplate <- H.noteShow $ base </> "configuration/defaults/byron-mainnet/configuration.yaml" conf :: TC.Conf <- HE.noteShowM $ TC.mkConf (TC.ProjectBase base) (TC.YamlFilePath configurationTemplate) (tempAbsBasePath' <> "/") Nothing tn <- TN.testnet testnetOptions conf Boilerplate codecs used for protocol serialisation . The number -- of epochSlots is specific to each blockchain instance. This value what the cardano main and testnet uses . Only applies to the -- era. socketPathAbs <- getSocketPathAbs conf tn let epochSlots = C.EpochSlots 21600 localNodeConnectInfo = C.LocalNodeConnectInfo { C.localConsensusModeParams = C.CardanoModeParams epochSlots , C.localNodeNetworkId = getNetworkId tn , C.localNodeSocketPath = socketPathAbs } pure (localNodeConnectInfo, conf, tn) getNetworkId :: TN.TestnetRuntime -> C.NetworkId getNetworkId tn = C.Testnet $ C.NetworkMagic $ fromIntegral (TN.testnetMagic tn) getSocketPathAbs :: (MonadTest m, MonadIO m) => TC.Conf -> TN.TestnetRuntime -> m FilePath getSocketPathAbs conf tn = do let tempAbsPath = TC.tempAbsPath conf socketPath <- IO.sprocketArgumentName <$> H.headM (TN.nodeSprocket <$> TN.bftNodes tn) H.note =<< (liftIO $ IO.canonicalizePath $ tempAbsPath </> socketPath) getPoolSocketPathAbs :: (MonadTest m, MonadIO m) => TC.Conf -> TN.TestnetRuntime -> m FilePath getPoolSocketPathAbs conf tn = do let tempAbsPath = TC.tempAbsPath conf socketPath <- IO.sprocketArgumentName <$> H.headM (TN.poolNodeSprocket <$> TN.poolNodes tn) H.note =<< (liftIO $ IO.canonicalizePath $ tempAbsPath </> socketPath) readAs :: (C.HasTextEnvelope a, MonadIO m, MonadTest m) => C.AsType a -> FilePath -> m a readAs as path = do path' <- H.note path H.leftFailM . liftIO $ C.readFileTextEnvelope as path' -- | An empty transaction emptyTxBodyContent :: C.IsShelleyBasedEra era => (C.TxValidityLowerBound era, C.TxValidityUpperBound era) -> C.ProtocolParameters -> C.TxBodyContent C.BuildTx era emptyTxBodyContent validityRange pparams = C.TxBodyContent { C.txIns = [] , C.txInsCollateral = C.TxInsCollateralNone , C.txInsReference = C.TxInsReferenceNone , C.txOuts = [] , C.txTotalCollateral = C.TxTotalCollateralNone , C.txReturnCollateral = C.TxReturnCollateralNone , C.txFee = C.TxFeeExplicit (txFeesExplicitInShelleyBasedEra C.shelleyBasedEra) 0 , C.txValidityRange = validityRange , C.txMetadata = C.TxMetadataNone , C.txAuxScripts = C.TxAuxScriptsNone , C.txExtraKeyWits = C.TxExtraKeyWitnessesNone , C.txProtocolParams = C.BuildTxWith $ Just pparams , C.txWithdrawals = C.TxWithdrawalsNone , C.txCertificates = C.TxCertificatesNone , C.txUpdateProposal = C.TxUpdateProposalNone , C.txMintValue = C.TxMintNone , C.txScriptValidity = C.TxScriptValidityNone } getProtocolParams :: forall era m . (C.IsShelleyBasedEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> m C.ProtocolParameters getProtocolParams localNodeConnectInfo = do eraInMode <- H.nothingFail $ C.toEraInMode (C.shelleyBasedToCardanoEra (C.shelleyBasedEra @era)) C.CardanoMode H.leftFailM . H.leftFailM . liftIO $ C.queryNodeLocalState localNodeConnectInfo Nothing $ C.QueryInEra eraInMode $ C.QueryInShelleyBasedEra C.shelleyBasedEra C.QueryProtocolParameters findUTxOByAddress :: (C.IsShelleyBasedEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> C.Address a -> m (C.UTxO era) findUTxOByAddress localNodeConnectInfo address = do let query = C.QueryInShelleyBasedEra C.shelleyBasedEra $ C.QueryUTxO $ C.QueryUTxOByAddress $ Set.singleton (C.toAddressAny address) eraInMode <- H.nothingFail $ C.toEraInMode (C.shelleyBasedToCardanoEra C.shelleyBasedEra) C.CardanoMode H.leftFailM . H.leftFailM . liftIO $ C.queryNodeLocalState localNodeConnectInfo Nothing $ C.QueryInEra eraInMode query -- | Get [TxIn] and total value for an address. getAddressTxInsValue :: forall era m a. (C.IsShelleyBasedEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> C.Address a -> m ([C.TxIn], C.Lovelace) getAddressTxInsValue con address = do utxo <- findUTxOByAddress @era con address let (txIns, txOuts) = unzip $ Map.toList $ C.unUTxO utxo values = map (\case C.TxOut _ v _ _ -> C.txOutValueToLovelace v) txOuts pure (txIns, sum values) submitTx :: (C.IsCardanoEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> C.Tx era -> m () submitTx localNodeConnectInfo tx = do eraInMode <- H.nothingFail $ C.toEraInMode C.cardanoEra C.CardanoMode submitResult :: SubmitResult (C.TxValidationErrorInMode C.CardanoMode) <- liftIO $ C.submitTxToNodeLocal localNodeConnectInfo $ C.TxInMode tx eraInMode failOnTxSubmitFail submitResult where failOnTxSubmitFail :: (Show a, MonadTest m) => SubmitResult a -> m () failOnTxSubmitFail = \case SubmitFail reason -> H.failMessage GHC.callStack $ "Transaction failed: " <> show reason SubmitSuccess -> pure () | Block until a transaction with @txId@ is sent over the local chainsync protocol . awaitTxId :: C.LocalNodeConnectInfo C.CardanoMode -> C.TxId -> IO () awaitTxId con txId = do chan :: IO.Chan [C.TxId] <- IO.newChan let indexer = CS.blocks con C.ChainPointAtGenesis & CS.ignoreRollbacks & S.map bimTxIds & S.chain (IO.writeChan chan) void $ (IO.link =<<) $ IO.async $ void $ S.effects indexer let loop = do txIds <- IO.readChan chan when (txId `notElem` txIds) loop loop | Submit the argument transaction and await for it to be accepted into the blockhain . submitAwaitTx :: (C.IsCardanoEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> (C.Tx era, C.TxBody era) -> m () submitAwaitTx con (tx, txBody) = do submitTx con tx liftIO $ awaitTxId con $ C.getTxId txBody mkTransferTx :: forall era m. (C.IsShelleyBasedEra era, MonadIO m, MonadTest m, MonadFail m) => C.NetworkId -> C.LocalNodeConnectInfo C.CardanoMode -> (C.TxValidityLowerBound era, C.TxValidityUpperBound era) -> C.Address C.ShelleyAddr -> C.Address C.ShelleyAddr -> [C.ShelleyWitnessSigningKey] -> C.Lovelace -> m (C.Tx era, C.TxBody era) mkTransferTx networkId con validityRange from to keyWitnesses howMuch = do pparams <- getProtocolParams @era con (txIns, totalLovelace) <- getAddressTxInsValue @era con from let tx0 = (emptyTxBodyContent validityRange pparams) { C.txIns = map (, C.BuildTxWith $ C.KeyWitness C.KeyWitnessForSpending) txIns , C.txOuts = [mkAddressAdaTxOut to totalLovelace] } txBody0 :: C.TxBody era <- HE.leftFail $ C.makeTransactionBody tx0 let fee = calculateFee pparams (length $ C.txIns tx0) (length $ C.txOuts tx0) 0 (length keyWitnesses) networkId txBody0 :: C.Lovelace when (howMuch + fee >= totalLovelace) $ fail "Not enough funds" let tx = tx0 { C.txFee = C.TxFeeExplicit (txFeesExplicitInShelleyBasedEra C.shelleyBasedEra) fee , C.txOuts = [ mkAddressAdaTxOut to howMuch , mkAddressAdaTxOut from $ totalLovelace - howMuch - fee ]} txBody :: C.TxBody era <- HE.leftFail $ C.makeTransactionBody tx return (C.signShelleyTransaction txBody keyWitnesses, txBody) mkAddressValueTxOut :: (C.IsShelleyBasedEra era) => C.Address C.ShelleyAddr -> C.TxOutValue era -> C.TxOut ctx era mkAddressValueTxOut address value = C.TxOut (C.AddressInEra (C.ShelleyAddressInEra C.shelleyBasedEra) address) value C.TxOutDatumNone C.ReferenceScriptNone mkAddressAdaTxOut :: (C.IsShelleyBasedEra era) => C.Address C.ShelleyAddr -> C.Lovelace -> C.TxOut ctx era mkAddressAdaTxOut address lovelace = let txOutValue = case C.multiAssetSupportedInEra $ C.shelleyBasedToCardanoEra C.shelleyBasedEra of Left adaOnlyInEra -> C.TxOutAdaOnly adaOnlyInEra lovelace Right multiAssetInEra -> C.TxOutValue multiAssetInEra $ C.lovelaceToValue lovelace in mkAddressValueTxOut address txOutValue -- | Adapted from: -- -output-hk/cardano-node/blob/d15ff2b736452857612dd533c1ddeea2405a2630/cardano-cli/src/Cardano/CLI/Shelley/Run/Transaction.hs#L1105-L1112 -- -output-hk/cardano-node/blob/d15ff2b736452857612dd533c1ddeea2405a2630/cardano-cli/src/Cardano/CLI/Shelley/Run/Transaction.hs#L1121-L1128 calculateFee :: C.IsShelleyBasedEra era => C.ProtocolParameters -> Int -> Int -> Int -> Int -> C.NetworkId -> C.TxBody era -> C.Lovelace calculateFee pparams nInputs nOutputs nByronKeyWitnesses nShelleyKeyWitnesses networkId txBody = C.estimateTransactionFee networkId (C.protocolParamTxFeeFixed pparams) (C.protocolParamTxFeePerByte pparams) (C.makeSignedTransaction [] txBody) nInputs nOutputs nByronKeyWitnesses nShelleyKeyWitnesses -- | Add fee to transaction body, return transaction with the fee -- applied, and also the fee in lovelace. calculateAndUpdateTxFee :: H.MonadTest m => C.ProtocolParameters -> C.NetworkId -> Int -> Int -> C.TxBodyContent C.BuildTx C.AlonzoEra -> m (C.Lovelace, C.TxBodyContent C.BuildTx C.AlonzoEra) calculateAndUpdateTxFee pparams networkId lengthTxIns lengthKeyWitnesses txbc = do txb <- HE.leftFail $ C.makeTransactionBody txbc let feeLovelace = calculateFee pparams lengthTxIns (length $ C.txOuts txbc) 0 lengthKeyWitnesses networkId txb :: C.Lovelace fee = C.TxFeeExplicit C.TxFeesExplicitInAlonzoEra feeLovelace txbc' = txbc { C.txFee = fee } return (feeLovelace, txbc') -- | This is a copy of the workspace from hedgehog - extras : Hedgehog . Extras . Test . Base , which for sets the systemTemp folder to /tmp . -- -- It creates a temporary folder with @prefixPath@, which is removed after the supplied function @f@ returns . workspace :: (MonadTest m, MonadIO m, GHC.HasCallStack) => FilePath -> (FilePath -> m ()) -> m () workspace prefixPath f = GHC.withFrozenCallStack $ do systemTemp <- case IO.os of "darwin" -> pure "/tmp" _ -> H.evalIO IO.getCanonicalTemporaryDirectory maybeKeepWorkspace <- H.evalIO $ IO.lookupEnv "KEEP_WORKSPACE" let systemPrefixPath = systemTemp <> "/" <> prefixPath H.evalIO $ IO.createDirectoryIfMissing True systemPrefixPath ws <- H.evalIO $ IO.createTempDirectory systemPrefixPath "test" H.annotate $ "Workspace: " <> ws liftIO $ IO.writeFile (ws <> "/module") H.callerModuleName f ws when (IO.os /= "mingw32" && maybeKeepWorkspace /= Just "1") $ do H.evalIO $ IO.removeDirectoryRecursive ws setDarwinTmpdir :: IO () setDarwinTmpdir = when (IO.os == "darwin") $ IO.setEnv "TMPDIR" "/tmp" -- * Accessors bimTxIds :: C.BlockInMode mode -> [C.TxId] bimTxIds (C.BlockInMode block _) = blockTxIds block blockTxIds :: C.Block era -> [C.TxId] blockTxIds (C.Block (C.BlockHeader _slotNo _ _blockNo) txs) = map (C.getTxId . C.getTxBody) txs bimSlotNo :: C.BlockInMode mode -> C.SlotNo bimSlotNo (C.BlockInMode (C.Block (C.BlockHeader slotNo _ _blockNo) _txs) _era) = slotNo bimBlockNo :: C.BlockInMode mode -> C.BlockNo bimBlockNo (C.BlockInMode (C.Block (C.BlockHeader _slotNo _ blockNo) _txs) _era) = blockNo | Should probably move in . txFeesExplicitInShelleyBasedEra :: C.ShelleyBasedEra era -> C.TxFeesExplicitInEra era txFeesExplicitInShelleyBasedEra shelleyBased = case shelleyBased of C.ShelleyBasedEraShelley -> C.TxFeesExplicitInShelleyEra C.ShelleyBasedEraAllegra -> C.TxFeesExplicitInAllegraEra C.ShelleyBasedEraMary -> C.TxFeesExplicitInMaryEra C.ShelleyBasedEraAlonzo -> C.TxFeesExplicitInAlonzoEra C.ShelleyBasedEraBabbage -> C.TxFeesExplicitInBabbageEra addressAnyToShelley :: C.AddressAny -> Maybe (C.Address C.ShelleyAddr) addressAnyToShelley (C.AddressShelley a) = Just a addressAnyToShelley _ = Nothing
null
https://raw.githubusercontent.com/input-output-hk/plutus-apps/38979da68816ab84faf6bfec6d0e7b6d47af651a/marconi-chain-index/test-lib/Helpers.hs
haskell
| Start a testnet. of epochSlots is specific to each blockchain instance. This value era. | An empty transaction | Get [TxIn] and total value for an address. | Adapted from: -output-hk/cardano-node/blob/d15ff2b736452857612dd533c1ddeea2405a2630/cardano-cli/src/Cardano/CLI/Shelley/Run/Transaction.hs#L1105-L1112 -output-hk/cardano-node/blob/d15ff2b736452857612dd533c1ddeea2405a2630/cardano-cli/src/Cardano/CLI/Shelley/Run/Transaction.hs#L1121-L1128 | Add fee to transaction body, return transaction with the fee applied, and also the fee in lovelace. | This is a copy of the workspace from It creates a temporary folder with @prefixPath@, which is removed * Accessors
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # module Helpers where import Control.Concurrent qualified as IO import Control.Concurrent.Async qualified as IO import Control.Monad (void, when) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Function ((&)) import Data.Map qualified as Map import Data.Set qualified as Set import GHC.Stack qualified as GHC import Streaming.Prelude qualified as S import System.Directory qualified as IO import System.Environment qualified as IO import System.FilePath ((</>)) import System.IO qualified as IO import System.IO.Temp qualified as IO import System.Info qualified as IO import Hedgehog (MonadTest) import Hedgehog qualified as H import Hedgehog.Extras.Stock.CallStack qualified as H import Hedgehog.Extras.Stock.IO.Network.Sprocket qualified as IO import Hedgehog.Extras.Test qualified as HE import Hedgehog.Extras.Test.Base qualified as H import Cardano.Api qualified as C import Cardano.Api.Shelley qualified as C import Cardano.Streaming qualified as CS import Ouroboros.Network.Protocol.LocalTxSubmission.Type (SubmitResult (SubmitFail, SubmitSuccess)) import Test.Runtime qualified as TN import Testnet.Cardano qualified as TN import Testnet.Conf qualified as TC (Conf (..), ProjectBase (ProjectBase), YamlFilePath (YamlFilePath), mkConf) startTestnet :: TN.TestnetOptions -> FilePath -> FilePath -> H.Integration (C.LocalNodeConnectInfo C.CardanoMode, TC.Conf, TN.TestnetRuntime) startTestnet testnetOptions base tempAbsBasePath' = do configurationTemplate <- H.noteShow $ base </> "configuration/defaults/byron-mainnet/configuration.yaml" conf :: TC.Conf <- HE.noteShowM $ TC.mkConf (TC.ProjectBase base) (TC.YamlFilePath configurationTemplate) (tempAbsBasePath' <> "/") Nothing tn <- TN.testnet testnetOptions conf Boilerplate codecs used for protocol serialisation . The number what the cardano main and testnet uses . Only applies to the socketPathAbs <- getSocketPathAbs conf tn let epochSlots = C.EpochSlots 21600 localNodeConnectInfo = C.LocalNodeConnectInfo { C.localConsensusModeParams = C.CardanoModeParams epochSlots , C.localNodeNetworkId = getNetworkId tn , C.localNodeSocketPath = socketPathAbs } pure (localNodeConnectInfo, conf, tn) getNetworkId :: TN.TestnetRuntime -> C.NetworkId getNetworkId tn = C.Testnet $ C.NetworkMagic $ fromIntegral (TN.testnetMagic tn) getSocketPathAbs :: (MonadTest m, MonadIO m) => TC.Conf -> TN.TestnetRuntime -> m FilePath getSocketPathAbs conf tn = do let tempAbsPath = TC.tempAbsPath conf socketPath <- IO.sprocketArgumentName <$> H.headM (TN.nodeSprocket <$> TN.bftNodes tn) H.note =<< (liftIO $ IO.canonicalizePath $ tempAbsPath </> socketPath) getPoolSocketPathAbs :: (MonadTest m, MonadIO m) => TC.Conf -> TN.TestnetRuntime -> m FilePath getPoolSocketPathAbs conf tn = do let tempAbsPath = TC.tempAbsPath conf socketPath <- IO.sprocketArgumentName <$> H.headM (TN.poolNodeSprocket <$> TN.poolNodes tn) H.note =<< (liftIO $ IO.canonicalizePath $ tempAbsPath </> socketPath) readAs :: (C.HasTextEnvelope a, MonadIO m, MonadTest m) => C.AsType a -> FilePath -> m a readAs as path = do path' <- H.note path H.leftFailM . liftIO $ C.readFileTextEnvelope as path' emptyTxBodyContent :: C.IsShelleyBasedEra era => (C.TxValidityLowerBound era, C.TxValidityUpperBound era) -> C.ProtocolParameters -> C.TxBodyContent C.BuildTx era emptyTxBodyContent validityRange pparams = C.TxBodyContent { C.txIns = [] , C.txInsCollateral = C.TxInsCollateralNone , C.txInsReference = C.TxInsReferenceNone , C.txOuts = [] , C.txTotalCollateral = C.TxTotalCollateralNone , C.txReturnCollateral = C.TxReturnCollateralNone , C.txFee = C.TxFeeExplicit (txFeesExplicitInShelleyBasedEra C.shelleyBasedEra) 0 , C.txValidityRange = validityRange , C.txMetadata = C.TxMetadataNone , C.txAuxScripts = C.TxAuxScriptsNone , C.txExtraKeyWits = C.TxExtraKeyWitnessesNone , C.txProtocolParams = C.BuildTxWith $ Just pparams , C.txWithdrawals = C.TxWithdrawalsNone , C.txCertificates = C.TxCertificatesNone , C.txUpdateProposal = C.TxUpdateProposalNone , C.txMintValue = C.TxMintNone , C.txScriptValidity = C.TxScriptValidityNone } getProtocolParams :: forall era m . (C.IsShelleyBasedEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> m C.ProtocolParameters getProtocolParams localNodeConnectInfo = do eraInMode <- H.nothingFail $ C.toEraInMode (C.shelleyBasedToCardanoEra (C.shelleyBasedEra @era)) C.CardanoMode H.leftFailM . H.leftFailM . liftIO $ C.queryNodeLocalState localNodeConnectInfo Nothing $ C.QueryInEra eraInMode $ C.QueryInShelleyBasedEra C.shelleyBasedEra C.QueryProtocolParameters findUTxOByAddress :: (C.IsShelleyBasedEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> C.Address a -> m (C.UTxO era) findUTxOByAddress localNodeConnectInfo address = do let query = C.QueryInShelleyBasedEra C.shelleyBasedEra $ C.QueryUTxO $ C.QueryUTxOByAddress $ Set.singleton (C.toAddressAny address) eraInMode <- H.nothingFail $ C.toEraInMode (C.shelleyBasedToCardanoEra C.shelleyBasedEra) C.CardanoMode H.leftFailM . H.leftFailM . liftIO $ C.queryNodeLocalState localNodeConnectInfo Nothing $ C.QueryInEra eraInMode query getAddressTxInsValue :: forall era m a. (C.IsShelleyBasedEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> C.Address a -> m ([C.TxIn], C.Lovelace) getAddressTxInsValue con address = do utxo <- findUTxOByAddress @era con address let (txIns, txOuts) = unzip $ Map.toList $ C.unUTxO utxo values = map (\case C.TxOut _ v _ _ -> C.txOutValueToLovelace v) txOuts pure (txIns, sum values) submitTx :: (C.IsCardanoEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> C.Tx era -> m () submitTx localNodeConnectInfo tx = do eraInMode <- H.nothingFail $ C.toEraInMode C.cardanoEra C.CardanoMode submitResult :: SubmitResult (C.TxValidationErrorInMode C.CardanoMode) <- liftIO $ C.submitTxToNodeLocal localNodeConnectInfo $ C.TxInMode tx eraInMode failOnTxSubmitFail submitResult where failOnTxSubmitFail :: (Show a, MonadTest m) => SubmitResult a -> m () failOnTxSubmitFail = \case SubmitFail reason -> H.failMessage GHC.callStack $ "Transaction failed: " <> show reason SubmitSuccess -> pure () | Block until a transaction with @txId@ is sent over the local chainsync protocol . awaitTxId :: C.LocalNodeConnectInfo C.CardanoMode -> C.TxId -> IO () awaitTxId con txId = do chan :: IO.Chan [C.TxId] <- IO.newChan let indexer = CS.blocks con C.ChainPointAtGenesis & CS.ignoreRollbacks & S.map bimTxIds & S.chain (IO.writeChan chan) void $ (IO.link =<<) $ IO.async $ void $ S.effects indexer let loop = do txIds <- IO.readChan chan when (txId `notElem` txIds) loop loop | Submit the argument transaction and await for it to be accepted into the blockhain . submitAwaitTx :: (C.IsCardanoEra era, MonadIO m, MonadTest m) => C.LocalNodeConnectInfo C.CardanoMode -> (C.Tx era, C.TxBody era) -> m () submitAwaitTx con (tx, txBody) = do submitTx con tx liftIO $ awaitTxId con $ C.getTxId txBody mkTransferTx :: forall era m. (C.IsShelleyBasedEra era, MonadIO m, MonadTest m, MonadFail m) => C.NetworkId -> C.LocalNodeConnectInfo C.CardanoMode -> (C.TxValidityLowerBound era, C.TxValidityUpperBound era) -> C.Address C.ShelleyAddr -> C.Address C.ShelleyAddr -> [C.ShelleyWitnessSigningKey] -> C.Lovelace -> m (C.Tx era, C.TxBody era) mkTransferTx networkId con validityRange from to keyWitnesses howMuch = do pparams <- getProtocolParams @era con (txIns, totalLovelace) <- getAddressTxInsValue @era con from let tx0 = (emptyTxBodyContent validityRange pparams) { C.txIns = map (, C.BuildTxWith $ C.KeyWitness C.KeyWitnessForSpending) txIns , C.txOuts = [mkAddressAdaTxOut to totalLovelace] } txBody0 :: C.TxBody era <- HE.leftFail $ C.makeTransactionBody tx0 let fee = calculateFee pparams (length $ C.txIns tx0) (length $ C.txOuts tx0) 0 (length keyWitnesses) networkId txBody0 :: C.Lovelace when (howMuch + fee >= totalLovelace) $ fail "Not enough funds" let tx = tx0 { C.txFee = C.TxFeeExplicit (txFeesExplicitInShelleyBasedEra C.shelleyBasedEra) fee , C.txOuts = [ mkAddressAdaTxOut to howMuch , mkAddressAdaTxOut from $ totalLovelace - howMuch - fee ]} txBody :: C.TxBody era <- HE.leftFail $ C.makeTransactionBody tx return (C.signShelleyTransaction txBody keyWitnesses, txBody) mkAddressValueTxOut :: (C.IsShelleyBasedEra era) => C.Address C.ShelleyAddr -> C.TxOutValue era -> C.TxOut ctx era mkAddressValueTxOut address value = C.TxOut (C.AddressInEra (C.ShelleyAddressInEra C.shelleyBasedEra) address) value C.TxOutDatumNone C.ReferenceScriptNone mkAddressAdaTxOut :: (C.IsShelleyBasedEra era) => C.Address C.ShelleyAddr -> C.Lovelace -> C.TxOut ctx era mkAddressAdaTxOut address lovelace = let txOutValue = case C.multiAssetSupportedInEra $ C.shelleyBasedToCardanoEra C.shelleyBasedEra of Left adaOnlyInEra -> C.TxOutAdaOnly adaOnlyInEra lovelace Right multiAssetInEra -> C.TxOutValue multiAssetInEra $ C.lovelaceToValue lovelace in mkAddressValueTxOut address txOutValue calculateFee :: C.IsShelleyBasedEra era => C.ProtocolParameters -> Int -> Int -> Int -> Int -> C.NetworkId -> C.TxBody era -> C.Lovelace calculateFee pparams nInputs nOutputs nByronKeyWitnesses nShelleyKeyWitnesses networkId txBody = C.estimateTransactionFee networkId (C.protocolParamTxFeeFixed pparams) (C.protocolParamTxFeePerByte pparams) (C.makeSignedTransaction [] txBody) nInputs nOutputs nByronKeyWitnesses nShelleyKeyWitnesses calculateAndUpdateTxFee :: H.MonadTest m => C.ProtocolParameters -> C.NetworkId -> Int -> Int -> C.TxBodyContent C.BuildTx C.AlonzoEra -> m (C.Lovelace, C.TxBodyContent C.BuildTx C.AlonzoEra) calculateAndUpdateTxFee pparams networkId lengthTxIns lengthKeyWitnesses txbc = do txb <- HE.leftFail $ C.makeTransactionBody txbc let feeLovelace = calculateFee pparams lengthTxIns (length $ C.txOuts txbc) 0 lengthKeyWitnesses networkId txb :: C.Lovelace fee = C.TxFeeExplicit C.TxFeesExplicitInAlonzoEra feeLovelace txbc' = txbc { C.txFee = fee } return (feeLovelace, txbc') hedgehog - extras : Hedgehog . Extras . Test . Base , which for sets the systemTemp folder to /tmp . after the supplied function @f@ returns . workspace :: (MonadTest m, MonadIO m, GHC.HasCallStack) => FilePath -> (FilePath -> m ()) -> m () workspace prefixPath f = GHC.withFrozenCallStack $ do systemTemp <- case IO.os of "darwin" -> pure "/tmp" _ -> H.evalIO IO.getCanonicalTemporaryDirectory maybeKeepWorkspace <- H.evalIO $ IO.lookupEnv "KEEP_WORKSPACE" let systemPrefixPath = systemTemp <> "/" <> prefixPath H.evalIO $ IO.createDirectoryIfMissing True systemPrefixPath ws <- H.evalIO $ IO.createTempDirectory systemPrefixPath "test" H.annotate $ "Workspace: " <> ws liftIO $ IO.writeFile (ws <> "/module") H.callerModuleName f ws when (IO.os /= "mingw32" && maybeKeepWorkspace /= Just "1") $ do H.evalIO $ IO.removeDirectoryRecursive ws setDarwinTmpdir :: IO () setDarwinTmpdir = when (IO.os == "darwin") $ IO.setEnv "TMPDIR" "/tmp" bimTxIds :: C.BlockInMode mode -> [C.TxId] bimTxIds (C.BlockInMode block _) = blockTxIds block blockTxIds :: C.Block era -> [C.TxId] blockTxIds (C.Block (C.BlockHeader _slotNo _ _blockNo) txs) = map (C.getTxId . C.getTxBody) txs bimSlotNo :: C.BlockInMode mode -> C.SlotNo bimSlotNo (C.BlockInMode (C.Block (C.BlockHeader slotNo _ _blockNo) _txs) _era) = slotNo bimBlockNo :: C.BlockInMode mode -> C.BlockNo bimBlockNo (C.BlockInMode (C.Block (C.BlockHeader _slotNo _ blockNo) _txs) _era) = blockNo | Should probably move in . txFeesExplicitInShelleyBasedEra :: C.ShelleyBasedEra era -> C.TxFeesExplicitInEra era txFeesExplicitInShelleyBasedEra shelleyBased = case shelleyBased of C.ShelleyBasedEraShelley -> C.TxFeesExplicitInShelleyEra C.ShelleyBasedEraAllegra -> C.TxFeesExplicitInAllegraEra C.ShelleyBasedEraMary -> C.TxFeesExplicitInMaryEra C.ShelleyBasedEraAlonzo -> C.TxFeesExplicitInAlonzoEra C.ShelleyBasedEraBabbage -> C.TxFeesExplicitInBabbageEra addressAnyToShelley :: C.AddressAny -> Maybe (C.Address C.ShelleyAddr) addressAnyToShelley (C.AddressShelley a) = Just a addressAnyToShelley _ = Nothing
93746270bab8c6f1f03018ac733e05612fc9f46405531ac9cd8fa8a89b95758e
timbertson/opam2nix
download.ml
type error = [ `download_failed of string ] let string_of_error (`download_failed desc) = "Download failed: " ^ desc let max_concurrency = 10 module Ctx = struct type t = unit Lwt_pool.t let init () = Curl.global_init Curl.CURLINIT_GLOBALALL; (* Pool is used only for concurrency limiting, * it doesn't actually manage resources *) Lwt_pool.create max_concurrency ~dispose:(fun () -> Lwt.return_unit) (fun () -> Lwt.return_unit) let destroy t = Lwt_main.run (Lwt_pool.clear t); Curl.global_cleanup () let use = Lwt_pool.use end let fetch (ctx: Ctx.t) ~dest url : (unit, [> error] ) Result.t Lwt.t = Ctx.use ctx (fun () -> Printf.eprintf " [ downloading %s ]\n" url; flush stderr; let connection = Curl.init () in let capath = try Some (Unix.getenv "CURL_CA_BUNDLE") with Not_found -> None in capath |> Option.may (Curl.set_cainfo connection); Curl.set_writefunction connection (fun s -> output_string dest s; String.length s); Curl.set_followlocation connection true; Curl.set_url connection url; (Lwt.finalize (fun () -> Curl_lwt.perform connection) (fun () -> Curl.cleanup connection; close_out dest; Lwt.return_unit) ) |> Lwt.map (function | Curl.CURLE_OK -> Ok () | err -> ( Printf.eprintf "Curl error: %s\n" (Curl.strerror err); Error (`download_failed url) ) ) )
null
https://raw.githubusercontent.com/timbertson/opam2nix/6f2fbdf3730d49bf8fadc22374a2e270bee9400d/src/download.ml
ocaml
Pool is used only for concurrency limiting, * it doesn't actually manage resources
type error = [ `download_failed of string ] let string_of_error (`download_failed desc) = "Download failed: " ^ desc let max_concurrency = 10 module Ctx = struct type t = unit Lwt_pool.t let init () = Curl.global_init Curl.CURLINIT_GLOBALALL; Lwt_pool.create max_concurrency ~dispose:(fun () -> Lwt.return_unit) (fun () -> Lwt.return_unit) let destroy t = Lwt_main.run (Lwt_pool.clear t); Curl.global_cleanup () let use = Lwt_pool.use end let fetch (ctx: Ctx.t) ~dest url : (unit, [> error] ) Result.t Lwt.t = Ctx.use ctx (fun () -> Printf.eprintf " [ downloading %s ]\n" url; flush stderr; let connection = Curl.init () in let capath = try Some (Unix.getenv "CURL_CA_BUNDLE") with Not_found -> None in capath |> Option.may (Curl.set_cainfo connection); Curl.set_writefunction connection (fun s -> output_string dest s; String.length s); Curl.set_followlocation connection true; Curl.set_url connection url; (Lwt.finalize (fun () -> Curl_lwt.perform connection) (fun () -> Curl.cleanup connection; close_out dest; Lwt.return_unit) ) |> Lwt.map (function | Curl.CURLE_OK -> Ok () | err -> ( Printf.eprintf "Curl error: %s\n" (Curl.strerror err); Error (`download_failed url) ) ) )
b82c13009acf8d736e94c9724f3b742b0a70916eacf02a04146f69570cbcca97
AtnNn/haskell-rethinkdb
Functions.hs
# LANGUAGE FlexibleInstances , OverloadedStrings , GADTs # -- | ReQL Functions -- ReQL was designed for dynamic languages . Many operations take -- optional positional and named arguments. -- -- Optional named arguments can be added using `ex`, for example -- `upsert = ex insert ["conflict" := "update"]` -- -- For optional positional arguments this module defines an extra -- function if the functionality is not available otherwise. For -- example `argmax` for `max` and `splitOn` for `split` but `skip` -- instead of `sliceFrom` and `avg . (!k)` instead of `avgOf k`. module Database.RethinkDB.Functions where import Data.Text (Text) import Control.Monad.State import Control.Applicative import Data.Maybe import Data.Default import Data.Monoid import Database.RethinkDB.Wire.Term as Term import Database.RethinkDB.ReQL import {-# SOURCE #-} Database.RethinkDB.MapReduce import Database.RethinkDB.Types import Database.RethinkDB.Datum hiding (Error) import Prelude (($), (.)) import qualified Prelude as P -- $setup -- -- Get the doctests ready -- > > > : load Database . RethinkDB.Doctest > > > import qualified Database . as R -- >>> :set -XOverloadedStrings > > > default ( Datum , ReQL , String , Int , Double ) -- >>> h <- doctestConnect -- $init_doctests -- >>> try' $ run' h $ dbCreate "doctests" -- >>> try' $ run' h $ tableCreate "foo" -- >>> try' $ run' h $ delete $ table "foo" -- >>> try' $ run' h $ tableCreate "bar" -- >>> try' $ run' h $ delete $ table "bar" -- >>> try' $ run' h $ tableDrop "bar" -- >>> try' $ run' h $ tableCreate (table "posts") -- >>> try' $ run' h $ delete $ table "posts" -- >>> try' $ run' h $ tableCreate (table "places") -- >>> try' $ run' h $ delete $ table "places" -- >>> try' $ run' h $ tableCreate (table "users"){ tablePrimaryKey = Just "name" } -- >>> try' $ run' h $ delete $ table "users" -- >>> try' $ run' h $ table "users" # indexDrop "occupation" -- >>> try' $ run' h $ table "users" # indexDrop "location" -- >>> try' $ run' h $ table "users" # indexDrop "friends" -- | Create a table on the server -- -- > >>> run' h $ tableCreate (table "posts") def -- > [{"created":1}] -- > >>> run' h $ tableCreate (table "users"){ tablePrimaryKey = Just "name" } def -- > [{"created":1}] -- > >>> run' h $ tableCreate (Table (Just "doctests") "bar" (Just "name")) def -- > [{"created":1}] -- > >>> run' h $ ex tableCreate ["datacenter":="orion"] (Table (Just "doctests") "bar" (Just "name")) def -- > [{"created":1}] tableCreate :: Table -> ReQL tableCreate (Table mdb table_name pkey) = withQuerySettings $ \QuerySettings{ queryDefaultDatabase = ddb } -> op' TABLE_CREATE (fromMaybe ddb mdb, table_name) $ catMaybes [ ("primary_key" :=) <$> pkey ] -- | Insert a document or a list of documents into a table -- > > > run h $ table " users " # insert ( map ( \x - > [ " name":=x ] ) [ " bill " , " bob " , " " : : Text ] ) : : IO WriteResponse -- {inserted:3} > > > run h $ table " posts " # insert [ " author " : = str " bill " , " message " : = str " hi " , " i d " : = 1 ] : : IO WriteResponse -- {inserted:1} > > > run h $ table " posts " # insert [ " author " : = str " bill " , " message " : = str " hello " , " i d " : = 2 , " flag " : = str " deleted " ] : : IO WriteResponse -- {inserted:1} > > > run h $ table " posts " # insert [ " author " : = str " bob " , " message " : = str " lorem ipsum " , " i d " : = 3 , " flag " : = str " pinned " ] : : IO WriteResponse -- {inserted:1} insert :: (Expr object) => object -> Table -> ReQL insert a tb = op INSERT (tb, a) -- | Add to or modify the contents of a document -- -- >>> run h $ table "users" # getAll "name" [str "bob"] # update (const ["occupation" := str "tailor"]) :: IO WriteResponse -- {replaced:1} update :: (Expr selection, Expr a) => (ReQL -> a) -> selection -> ReQL update f s = op UPDATE (s, expr . f) -- | Replace a document with another -- > > > run h $ replace ( \user - > [ " name " : = user!"name " , " occupation " : = str " clothier " ] ) . R.filter ( ( R.== str " tailor " ) . ( ! ? " occupation " ) ) $ table " users " : : IO WriteResponse -- {replaced:1} replace :: (Expr selection, Expr a) => (ReQL -> a) -> selection -> ReQL replace f s = op REPLACE (s, expr . f) -- | Delete the documents -- -- >>> run h $ delete . getAll "name" [str "bob"] $ table "users" :: IO WriteResponse -- {deleted:1} delete :: (Expr selection) => selection -> ReQL delete s = op Term.DELETE [s] -- | Like map but for write queries -- -- >>> _ <- run' h $ table "users" # replace (without ["post_count"]) > > > run h $ forEach ( \user - > table " users " # get ( user!"name " ) # ex update [ nonAtomic ] ( const [ " post_count " : = R.count ( table " posts " # R.filter ( \post - > post!"author " R.== user!"name " ) ) ] ) ) ( table " users " ) : : IO WriteResponse { replaced:2 } forEach :: (Expr a, Expr s) => (ReQL -> a) -> s -> ReQL forEach f s = op FOR_EACH (s, expr P.. f) -- | A table -- > > > fmap sort $ run h $ table " users " : : IO [ Datum ] -- [{"post_count":2,"name":"bill"},{"post_count":0,"name":"nancy"}] table :: Text -> Table table n = Table Nothing n Nothing -- | Drop a table -- -- >>> run' h $ tableDrop (table "foo") -- {"config_changes":[{"new_val":null,"old_val":{"primary_key":"id","write_acks":"majority","durability":"hard","name":"foo","shards":...,"id":...,"db":"doctests"}}],"tables_dropped":1} tableDrop :: Table -> ReQL tableDrop (Table mdb table_name _) = withQuerySettings $ \QuerySettings{ queryDefaultDatabase = ddb } -> op TABLE_DROP (fromMaybe ddb mdb, table_name) -- | List the tables in a database -- > > > fmap sort $ run h $ tableList ( db " doctests " ) : : IO [ String ] -- ["places","posts","users"] tableList :: Database -> ReQL tableList name = op TABLE_LIST [name] infixl 6 +, - infixl 7 *, / -- | Addition or concatenation -- Use the instance , or a qualified operator . -- > > > run h $ 2 + 5 7 > > > run h $ str " foo " " bar " " foobar " (+) :: (Expr a, Expr b) => a -> b -> ReQL (+) a b = op ADD (a, b) -- | Subtraction -- > > > run h $ 2 - 5 -- -3 (-) :: (Expr a, Expr b) => a -> b -> ReQL (-) a b = op SUB (a, b) -- | Multiplication -- > > > run h $ 2 * 5 10 (*) :: (Expr a, Expr b) => a -> b -> ReQL (*) a b = op MUL (a, b) -- | Division -- > > > run h $ 2 R./ 5 0.4 (/) :: (Expr a, Expr b) => a -> b -> ReQL (/) a b = op DIV (a, b) -- | Mod -- > > > run h $ 5 ` mod ` 2 1 mod :: (Expr a, Expr b) => a -> b -> ReQL mod a b = op MOD (a, b) infixr 2 || infixr 3 && -- | Boolean or -- -- >>> run h $ True R.|| False -- true (||) :: (Expr a, Expr b) => a -> b -> ReQL a || b = op OR (a, b) -- | Boolean and -- -- >>> run h $ True R.&& False -- false (&&) :: (Expr a, Expr b) => a -> b -> ReQL a && b = op AND (a, b) infix 4 ==, /= -- | Test for equality -- > > > run h $ [ " a " : = 1 ] R.== [ " a " : = 1 ] -- true (==) :: (Expr a, Expr b) => a -> b -> ReQL a == b = op EQ (a, b) -- | Test for inequality -- > > > run h $ 1 R./= False -- true (/=) :: (Expr a, Expr b) => a -> b -> ReQL a /= b = op NE (a, b) infix 4 >, <, <=, >= -- | Greater than -- > > > run h $ 3 R. > 2 -- true (>) :: (Expr a, Expr b) => a -> b -> ReQL a > b = op GT (a, b) -- | Lesser than -- > > > run h $ ( str " a " ) R. < ( str " b " ) -- true (<) :: (Expr a, Expr b) => a -> b -> ReQL a < b = op LT (a, b) -- | Greater than or equal to -- -- >>> run h $ [1] R.>= Null -- false (>=) :: (Expr a, Expr b) => a -> b -> ReQL a >= b = op GE (a, b) -- | Lesser than or equal to -- > > > run h $ 2 R.<= 2 -- true (<=) :: (Expr a, Expr b) => a -> b -> ReQL a <= b = op LE (a, b) -- | Negation -- > > > run h $ R.not False -- true > > > run h $ R.not Null -- true not :: (Expr a) => a -> ReQL not a = op NOT [a] -- * Lists and Streams -- | The size of a sequence or an array. -- -- >>> run h $ count (table "users") 2 count :: (Expr a) => a -> ReQL count e = op COUNT [e] | Join two sequences . -- -- >>> run h $ [1,2,3] `union` ["a", "b", "c" :: Text] -- [1,2,3,"a","b","c"] union :: (Expr a, Expr b) => a -> b -> ReQL union a b = op UNION (a, b) -- | Map a function over a sequence -- > > > run h $ R.map ( ! " a " ) [ [ " a " : = 1 ] , [ " a " : = 2 ] ] -- [1,2] map :: (Expr a, Expr b) => (ReQL -> b) -> a -> ReQL map f a = op MAP (a, expr P.. f) -- | Filter a sequence given a predicate -- > > > run h $ R.filter ( R. < 4 ) [ 3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ] [ 3,1,1,2 ] filter :: (Expr predicate, Expr seq) => predicate -> seq -> ReQL filter f a = op' FILTER (a, f) ["default" := op ERROR ()] -- | Query all the documents whose value for the given index is in a given range -- -- >>> run h $ table "users" # between "name" (Closed $ str "a") (Open $ str "c") -- [{"post_count":2,"name":"bill"}] between :: (Expr left, Expr right, Expr seq) => Index -> Bound left -> Bound right -> seq -> ReQL between i a b e = op' BETWEEN [expr e, expr $ getBound a, expr $ getBound b] $ idx P.++ ["left_bound" ?:= closedOrOpen a, "right_bound" ?:= closedOrOpen b] where idx = case i of PrimaryKey -> []; Index name -> ["index" := name] -- | Append a datum to a sequence -- > > > run h $ append 3 [ 1 , 2 ] -- [1,2,3] append :: (Expr a, Expr b) => a -> b -> ReQL append a b = op APPEND (b, a) -- | Map a function of a sequence and concat the results -- > > > run h $ concatMap i d [ [ 1 , 2 ] , [ 3 ] , [ 4 , 5 ] ] [ 1,2,3,4,5 ] concatMap :: (Expr a, Expr b) => (ReQL -> b) -> a -> ReQL concatMap f e = op CONCAT_MAP (e, expr P.. f) | SQL - like inner join of two sequences -- > > > sorted $ run ' h $ innerJoin ( post - > user!"name " R.== post!"author " ) ( table " users " ) ( table " posts " ) # R.zip # orderBy [ asc " i d " ] # pluck [ " name " , " message " ] -- [{"name":"bill","message":"hello"},{"name":"bill","message":"hi"}] innerJoin :: (Expr a, Expr b, Expr c) => (ReQL -> ReQL -> c) -> a -> b -> ReQL innerJoin f a b = op INNER_JOIN (a, b, fmap expr P.. f) | SQL - like outer join of two sequences -- > > > sorted $ run ' h $ outerJoin ( post - > user!"name " R.== post!"author " ) ( table " users " ) ( table " posts " ) # R.zip # orderBy [ asc " i d " , asc " name " ] # pluck [ " name " , " message " ] -- [{"name":"bill","message":"hello"},{"name":"bill","message":"hi"},{"name":"nancy"}] outerJoin :: (Expr a, Expr b, Expr c) => (ReQL -> ReQL -> c) -> a -> b -> ReQL outerJoin f a b = op OUTER_JOIN (a, b, fmap expr P.. f) -- | An efficient inner_join that uses a key for the left table and an index for the right table. -- > > > sorted $ run ' h $ table " posts " # eqJoin " author " ( table " users " ) " name " # R.zip # orderBy [ asc " i d " ] # pluck [ " name " , " message " ] -- [{"name":"bill","message":"hello"},{"name":"bill","message":"hi"}] eqJoin :: (Expr fun, Expr right, Expr left) => fun -> right -> Index -> left -> ReQL eqJoin key right (Index idx) left = op' EQ_JOIN (left, key, right) ["index" := idx] eqJoin key right PrimaryKey left = op EQ_JOIN (left, key, right) -- | Drop elements from the head of a sequence. -- > > > run h $ skip 2 [ 1 , 2 , 3 , 4 ] [ 3,4 ] skip :: (Expr n, Expr seq) => n -> seq -> ReQL skip a b = op SKIP (b, a) -- | Limit the size of a sequence. -- > > > run h $ limit 2 [ 1 , 2 , 3 , 4 ] -- [1,2] limit :: (Expr n, Expr seq) => n -> seq -> ReQL limit n s = op LIMIT (s, n) -- | Cut out part of a sequence -- > > > run h $ slice 2 4 [ 1 , 2 , 3 , 4 , 5 ] [ 3,4 ] slice :: (Expr a, Expr b, Expr c) => a -> b -> c -> ReQL slice n m s = op SLICE (s, n, m) -- | Get nth element of a sequence -- > > > run h $ nth 2 [ 1 , 2 , 3 , 4 , 5 ] 3 nth :: (Expr a, Expr seq) => a -> seq -> ReQL nth a s = op NTH (s, a) -- | Reduce a sequence to a single value -- > > > run h $ reduce0 ( + ) 0 [ 1 , 2 , 3 ] 6 reduce0 :: (Expr base, Expr seq, Expr a) => (ReQL -> ReQL -> a) -> base -> seq -> ReQL reduce0 f b s = op REDUCE (s `union` [b], fmap expr P.. f) -- | Reduce a non-empty sequence to a single value -- > > > run h $ reduce ( + ) [ 1 , 2 , 3 ] 6 reduce :: (Expr a, Expr s) => (ReQL -> ReQL -> a) -> s -> ReQL reduce f s = op REDUCE (s, fmap expr P.. f) -- | Filter out identical elements of the sequence -- -- >>> fmap sort $ run h $ distinct (table "posts" ! "flag") :: IO [String] -- ["deleted","pinned"] distinct :: (Expr s) => s -> ReQL distinct s = op DISTINCT [s] -- | Merge the "left" and "right" attributes of the objects in a sequence. -- > > > fmap sort $ run h $ table " posts " # eqJoin " author " ( table " users " ) " name " # R.zip : : IO [ Datum ] -- [{"post_count":2,"flag":"deleted","name":"bill","author":"bill","id":2,"message":"hello"},{"post_count":2,"name":"bill","author":"bill","id":1,"message":"hi"}] zip :: (Expr a) => a -> ReQL zip a = op ZIP [a] -- | Order a sequence by the given keys -- > > > run ' h $ table " users " # orderBy [ desc " post_count " , asc " name " ] # pluck [ " name " , " post_count " ] -- [{"post_count":2,"name":"bill"},{"post_count":0,"name":"nancy"}] -- -- >>> run' h $ table "users" # ex orderBy ["index":="name"] [] # pluck ["name"] -- [{"name":"bill"},{"name":"nancy"}] orderBy :: (Expr s) => [ReQL] -> s -> ReQL orderBy o s = op ORDER_BY (expr s : P.map expr o) -- | Ascending order asc :: ReQL -> ReQL asc f = op ASC [f] -- | Descending order desc :: ReQL -> ReQL desc f = op DESC [f] -- | Turn a grouping function and a reduction function into a grouped map reduce operation -- > > > run ' h $ table " posts " # orderBy [ asc " i d " ] # group ( ! " author " ) ( reduce ( \a b - > a + " \n " + b ) . R.map ( ! " message " ) ) -- [{"group":"bill","reduction":"hi\nhello"},{"group":"bob","reduction":"lorem ipsum"}] > > > run ' h $ table " users " # group ( ( ! 0 ) . splitOn " " . ( ! " name " ) ) ( \users - > let pc = users!"post_count " in [ avg pc , R.sum pc ] ) [ { " group":"b","reduction":[2,2]},{"group":"n","reduction":[0,0 ] } ] group :: (Expr group, Expr reduction, Expr seq) => (ReQL -> group) -> (ReQL -> reduction) -> seq -> ReQL group g f s = ReQL $ do mr <- termToMapReduce (expr . f) runReQL $ op UNGROUP [mr $ op GROUP (expr s, expr . g)] -- | Rewrite multiple reductions into a single map/reduce operation mapReduce :: (Expr reduction, Expr seq) => (ReQL -> reduction) -> seq -> ReQL mapReduce f s = ReQL $ do mr <- termToMapReduce (expr . f) runReQL $ mr (expr s) -- | The sum of a sequence -- > > > run h $ sum [ 1 , 2 , 3 ] 6 sum :: (Expr s) => s -> ReQL sum s = op SUM [s] -- | The average of a sequence -- > > > run h $ avg [ 1 , 2 , 3 , 4 ] 2.5 avg :: (Expr s) => s -> ReQL avg s = op AVG [s] -- | Minimum value min :: Expr s => s -> ReQL min s = op MIN [s] -- | Value that minimizes the function argmin :: (Expr s, Expr a) => (ReQL -> a) -> s -> ReQL argmin f s = op MIN (s, expr . f) -- | Minimum value max :: Expr s => s -> ReQL max s = op MAX [s] -- | Floor rounds number to interger below -- > > > run h $ R.floor 2.9 2 floor :: Expr s => s -> ReQL floor s = op FLOOR [s] -- | Ceil rounds number to integer above -- > > > run h $ R.ceil 2.1 3 ceil :: Expr s => s -> ReQL ceil s = op CEIL [s] -- | Round rounds number to nearest integer -- > > > run h $ R.round 2.5 3 round :: Expr s => s -> ReQL round s = op ROUND [s] -- | Value that maximizes the function argmax :: (Expr s, Expr a) => (ReQL -> a) -> s -> ReQL argmax f s = op MAX (s, expr . f) -- * Accessors infixl 9 ! -- | Get a single field from an object or an element of an array -- -- >>> run h $ ["foo" := True] ! "foo" -- true -- > > > run h $ [ 1 , 2 , 3 ] ! 0 1 -- -- Or a single field from each object in a sequence -- -- >>> run h $ [["foo" := True], ["foo" := False]] ! "foo" -- [true,false] (!) :: (Expr s) => s -> ReQL -> ReQL s ! k = op BRACKET (s, k) -- | Get a single field, or null if not present -- -- >>> run' h $ empty !? "foo" -- null (!?) :: (Expr s) => s -> ReQL -> ReQL s !? k = P.flip apply [expr s, k] $ \s' k' -> op DEFAULT (op BRACKET (s', k'), Null) -- | Keep only the given attributes -- > > > run ' h $ [ [ " a " : = 1 , " b " : = 2 ] , [ " a " : = 2 , " c " : = 7 ] , [ " b " : = 4 ] ] # pluck [ " a " ] -- [{"a":1},{"a":2},{}] pluck :: (Expr o) => [ReQL] -> o -> ReQL pluck ks e = op PLUCK (cons e $ arr (P.map expr ks)) -- | Remove the given attributes from an object -- > > > run ' h $ [ [ " a " : = 1 , " b " : = 2 ] , [ " a " : = 2 , " c " : = 7 ] , [ " b " : = 4 ] ] # without [ " a " ] [ { " } ] without :: (Expr o) => [ReQL] -> o -> ReQL without ks e = op WITHOUT (cons e $ arr (P.map expr ks)) -- | Test if a sequence contains a given element -- > > > run ' h $ [ 1,2,3 ] # contains 1 -- true contains :: (Expr x, Expr seq) => x -> seq -> ReQL contains x s = op CONTAINS (s, x) | Merge two objects together -- NOTE : This driver is based on the official JavaScript driver , you are correct to expect the same semantics . However the order of composition is flipped by putting the first argument last . -- > > > run ' h $ merge [ " a " : = 1 , " b " : = 1 ] [ " b " : = 1 , " c " : = 2 ] -- {"a":1,"b":1,"c":2} merge :: (Expr a, Expr b) => a -> b -> ReQL merge a b = op MERGE (b, a) -- | Literal objects, in a merge or update, are not processed recursively. -- > > > run ' h $ [ " a " : = [ " b " : = 1 ] ] # merge [ " a " : = literal [ " c " : = 2 ] ] -- {"a":{"c":2}} literal :: Expr a => a -> ReQL literal a = op LITERAL [a] -- | Remove fields when doing a merge or update -- > > > run ' h $ [ " a " : = [ " b " : = 1 ] ] # merge [ " a " : = remove ] -- {} remove :: ReQL remove = op LITERAL () | Evaluate a JavaScript expression -- -- >>> run' h $ js "Math.PI" 3.141592653589793 > > > let r_sin x = js " Math.sin " ` apply ` [ x ] -- >>> run h $ R.map r_sin [pi, pi/2] [ 1.2246 ... ,1 ] js :: ReQL -> ReQL js s = op JAVASCRIPT [s] -- | Server-side if -- > > > run h $ branch ( 1 R. < 2 ) 3 4 3 branch :: (Expr a, Expr b, Expr c) => a -> b -> c -> ReQL branch a b c = op BRANCH (a, b, c) -- | Abort the query with an error -- -- >>> run' h $ R.error (str "haha") R./ 2 + 1 -- *** Exception: RethinkDB: Runtime error: haha in add(div({- HERE - } error("haha " ) , 2 ) , 1 ) error :: (Expr s) => s -> ReQL error m = op ERROR [m] -- | Create a Database reference -- -- >>> run' h $ db "test" # info -- {"name":"test","id":...,"type":"DB"} db :: Text -> Database db = Database -- | Create a database on the server -- -- >>> run' h $ dbCreate "dev" -- {"config_changes":[{"new_val":{"name":"dev","id":...},"old_val":null}],"dbs_created":1} dbCreate :: Text -> ReQL dbCreate db_name = op DB_CREATE [expr db_name] -- | Drop a database -- -- >>> run' h $ dbDrop (db "dev") -- {"config_changes":[{"new_val":null,"old_val":{"name":"dev","id":...}}],"tables_dropped":0,"dbs_dropped":1} dbDrop :: Database -> ReQL dbDrop (Database name) = op DB_DROP [name] -- | List the databases on the server -- -- >>> _ <- run' h $ dbList dbList :: ReQL dbList = op DB_LIST () -- | Create an index on the table from the given function -- -- >>> run' h $ table "users" # indexCreate "occupation" (!"occupation") -- {"created":1} -- >>> run' h $ table "users" # ex indexCreate ["multi":=True] "friends" (!"friends") -- {"created":1} -- >>> run' h $ table "users" # ex indexCreate ["geo":=True] "location" (!"location") -- {"created":1} indexCreate :: (Expr fun) => Text -> fun -> Table -> ReQL indexCreate name f tbl = op INDEX_CREATE (tbl, expr name, f) -- | Get the status of the given indexes -- -- > run' h $ table "users" # indexStatus [] indexStatus :: Expr table => [ReQL] -> table -> ReQL indexStatus ixes tbl = op INDEX_STATUS (tbl, op ARGS [ixes]) -- | Wait for an index to be built -- -- > run' h $ table "users" # indexWait [] indexWait :: Expr table => [ReQL] -> table -> ReQL indexWait ixes tbl = op INDEX_STATUS (tbl, op ARGS [ixes]) indexRename :: Expr table => ReQL -> ReQL -> table -> ReQL indexRename from to tbl = op INDEX_RENAME (tbl, from, to) -- | Ensures that writes on a given table are written to permanent storage -- -- >>> run' h $ sync (table "users") -- {"synced":1} sync :: Expr table => table -> ReQL sync tbl = op SYNC [tbl] -- | List the indexes on the table -- -- >>> run' h $ indexList (table "users") [ " friends","location","occupation " ] indexList :: Table -> ReQL indexList tbl = op INDEX_LIST [tbl] -- | Drop an index -- -- >>> run' h $ table "users" # indexDrop "occupation" -- {"dropped":1} indexDrop :: Key -> Table -> ReQL indexDrop name tbl = op INDEX_DROP (tbl, name) -- | Retreive documents by their indexed value -- -- >>> run' h $ table "users" # getAll PrimaryKey [str "bill"] -- [{"post_count":2,"name":"bill"}] getAll :: (Expr values) => Index -> values -> Table -> ReQL getAll idx xs tbl = op' GET_ALL (tbl, op ARGS [xs]) $ case idx of Index i -> ["index" := i] PrimaryKey -> [] -- | Get a document by primary key -- -- >>> run' h $ table "users" # get "nancy" -- {"post_count":0,"name":"nancy"} get :: Expr s => ReQL -> s -> ReQL get k e = op Term.GET (e, k) -- | Convert a value to a different type -- > > > run h $ coerceTo " STRING " 1 " 1 " coerceTo :: (Expr x) => ReQL -> x -> ReQL coerceTo t a = op COERCE_TO (a, t) -- | Convert a value to an array -- > > > run h $ asArray $ [ " a " : = 1 , " b " : = 2 ] : : IO [ ( String , Int ) ] [ ( " ) ] asArray :: Expr x => x -> ReQL asArray = coerceTo "ARRAY" -- | Convert a value to a string -- > > > run h $ asString $ [ " a " : = 1 , " b " : = 2 ] -- "{\"a\":1,\"b\":2}" asString :: Expr x => x -> ReQL asString = coerceTo "STRING" -- | Convert a value to a number -- > > > run h $ asNumber ( str " 34 " ) 34 asNumber :: Expr x => x -> ReQL asNumber = coerceTo "NUMBER" -- | Convert a value to an object -- > > > run ' h $ asObject $ [ ( str " ) ] -- {"a":1,"b":2} asObject :: Expr x => x -> ReQL asObject = coerceTo "OBJECT" -- | Convert a value to a boolean asBool :: Expr x => x -> ReQL asBool = coerceTo "BOOL" | Like followed by pluck -- > > > run ' h $ [ [ " a " : = 1 , " b " : = 2 ] , [ " a " : = 2 , " c " : = 7 ] , [ " b " : = 4 ] ] # withFields [ " a " ] -- [{"a":1},{"a":2}] withFields :: Expr seq => [ReQL] -> seq -> ReQL withFields p s = op WITH_FIELDS (s, p) -- | The position in the sequence of the elements that match the predicate -- > > > run h $ indexesOf ( match " ba . " ) [ str " foo " , " bar " , " baz " ] -- [1,2] indexesOf :: (Expr fun, Expr seq) => fun -> seq -> ReQL indexesOf f s = op OFFSETS_OF (s, f) -- | Test if a sequence is empty -- > > > run h $ isEmpty [ 1 ] -- false isEmpty :: Expr seq => seq -> ReQL isEmpty s = op IS_EMPTY [s] -- | Select a given number of elements from a sequence with uniform random distribution -- > > > _ < - run ' h $ sample 3 [ 0,1,2,3,4,5,6,7,8,9 ] sample :: (Expr n, Expr seq) => n -> seq -> ReQL sample n s = op SAMPLE (s, n) -- | Prepend an element to an array -- > > > run h $ prepend 1 [ 2,3 ] -- [1,2,3] prepend :: (Expr datum, Expr array) => datum -> array -> ReQL prepend d a = op PREPEND (a, d) | The different of two lists -- > > > run h $ [ 1,2,3,4,5 ] # difference [ 2,5 ] [ 1,3,4 ] difference :: (Expr a, Expr b) => a -> b -> ReQL difference a b = op DIFFERENCE (b, a) -- | Insert a datum into an array if it is not yet present -- > > > run h $ setInsert 3 [ 1,2,4,4,5 ] [ 1,2,4,5,3 ] setInsert :: (Expr datum, Expr array) => datum -> array -> ReQL setInsert d a = op SET_INSERT (a, d) | The union of two sets -- > > > run h $ [ 1,2 ] ` setUnion ` [ 2,3 ] [ 2,3,1 ] setUnion :: (Expr a, Expr b) => a -> b -> ReQL setUnion a b = op SET_UNION (b, a) | The intersection of two sets -- > > > run h $ [ 1,2 ] ` setIntersection ` [ 2,3 ] [ 2 ] setIntersection :: (Expr a, Expr b) => a -> b -> ReQL setIntersection a b = op SET_INTERSECTION (b, a) | The difference of two sets -- > > > run h $ [ 2,3 ] # setDifference [ 1,2 ] [ 3 ] setDifference :: (Expr set, Expr remove) => remove -> set -> ReQL setDifference r s = op SET_DIFFERENCE (s, r) -- | Test if an object has the given fields -- > > > run h $ hasFields " a " $ [ " a " : = 1 ] -- true hasFields :: (Expr obj) => ReQL -> obj -> ReQL hasFields p o = op HAS_FIELDS (o, expr p) -- | Insert a datum at the given position in an array -- > > > run h $ insertAt 1 4 [ 1,2,3 ] -- [1,4,2,3] insertAt :: (Expr n, Expr datum, Expr array) => n -> datum -> array -> ReQL insertAt n d a = op INSERT_AT (a, n, d) -- | Splice an array at a given position inside another array -- > > > run h $ spliceAt 2 [ 4,5 ] [ 1,2,3 ] [ 1,2,4,5,3 ] spliceAt :: (Expr n, Expr replace, Expr array) => n -> replace -> array -> ReQL spliceAt n s a = op SPLICE_AT (a, n, s) -- | Delete an element from an array -- > > > run h $ deleteAt 1 [ 1,2,3 ] -- [1,3] deleteAt :: (Expr n, Expr array) => n -> array -> ReQL deleteAt n a = op DELETE_AT (a, n) -- | Change an element in an array -- > > > run h $ changeAt 1 4 [ 1,2,3 ] -- [1,4,3] changeAt :: (Expr n, Expr datum, Expr array) => n -> datum -> array -> ReQL changeAt n d a = op CHANGE_AT (a, n, d) -- | The list of keys of the given object -- > > > run h $ keys [ " a " : = 1 , " b " : = 2 ] -- ["a","b"] keys :: Expr object => object -> ReQL keys o = op KEYS [o] -- | The list of values of the given object -- > > > run h $ values [ " a " : = 1 , " b " : = 2 ] -- [1,2] values :: Expr object => object -> ReQL values o = op VALUES [o] -- | Match a string to a regular expression. -- -- >>> run' h $ str "foobar" # match "f(.)+[bc](.+)" { " groups":[{"start":2,"end":3,"str":"o"},{"start":4,"end":6,"str":"ar"}],"start":0,"end":6,"str":"foobar " } match :: (Expr string) => ReQL -> string -> ReQL match r s = op MATCH (s, r) -- | Apply a function to a list of arguments. -- -- Called /do/ in the official drivers -- > > > run h $ ( \x - > x R. * 2 ) ` apply ` [ 4 ] 8 apply :: (Expr fun, Expr arg) => fun -> [arg] -> ReQL f `apply` as = op FUNCALL (expr f : P.map expr as) -- | Catch some expections inside the query. -- Called /default/ in the official drivers -- > > > run h $ R.handle ( const 0 ) $ [ " a " : = 1 ] ! " b " 0 > > > run h $ R.handle ( expr . i d ) $ [ " a " : = 1 ] ! " b " -- "No attribute `b` in object:\n{\n\t\"a\":\t1\n}" handle :: (Expr instead, Expr reql) => (ReQL -> instead) -> reql -> ReQL handle h r = op DEFAULT (r, expr . h) -- | A string representing the type of an expression -- -- >>> run h $ typeOf 1 -- "NUMBER" typeOf :: Expr a => a -> ReQL typeOf a = op TYPE_OF [a] -- | Get information on a given expression. Useful for tables and databases. -- > > > run h $ info $ table " users " -- {"primary_key":"name","doc_count_estimates":...,"name":"users","id":...,"indexes":["friends","location"],"type":"TABLE","db":{"name":"doctests","id":...,"type":"DB"}} info :: Expr a => a -> ReQL info a = op INFO [a] -- | Parse a json string into an object -- -- >>> run' h $ json "{\"a\":1}" -- {"a":1} json :: ReQL -> ReQL json s = op Term.JSON [s] -- | Flipped function application infixl 8 # (#) :: (Expr a, Expr b) => a -> (a -> b) -> ReQL x # f = expr (f x) -- | Convert to upper case -- > > > run h $ upcase ( str " " ) " FOO " upcase :: Expr str => str -> ReQL upcase s = op UPCASE [s] -- | Convert to lower case -- > > > run h $ downcase ( str " " ) -- "foo" downcase :: Expr str => str -> ReQL downcase s = op DOWNCASE [s] -- | Split a string on whitespace characters -- -- >>> run' h $ split (str "foo bar") [ " " ] split :: Expr str => str -> ReQL split s = op SPLIT [s] -- | Split a string on a given delimiter -- -- >>> run' h $ str "foo, bar" # splitOn "," -- ["foo"," bar"] -- -- >>> run' h $ str "foo" # splitOn "" -- ["f","o","o"] splitOn :: Expr str => ReQL -> str -> ReQL splitOn sep s = op SPLIT [expr s, sep] -- | Split a string up to a given number of times -- > > > run ' h $ str " a : b : c : d " # splitMax " : " 2 -- ["a","b","c:d"] splitMax :: Expr str => ReQL -> ReQL -> str -> ReQL splitMax sep n s = op SPLIT [expr s, sep, n] | A random float between 0 and 1 -- > > > run ' h $ ( \x - > x R. < 1 R. & & x R.>= 0 ) ` apply ` [ random ] -- true random :: ReQL random = op RANDOM () -- | A random number between 0 and n -- > > > run ' h $ ( \x - > x R. < 10 R. & & x R.>= 0 ) ` apply ` [ randomTo 10 ] -- true randomTo :: ReQL -> ReQL randomTo n = op RANDOM [n] -- | A random number between 0 and n -- > > > run ' h $ ( \x - > x R. < 10 R. & & x R.>= 5 ) ` apply ` [ randomFromTo 5 10 ] -- true randomFromTo :: ReQL -> ReQL -> ReQL randomFromTo n m = op RANDOM [n, m] data HttpOptions = HttpOptions { httpTimeout :: Maybe P.Int, httpReattempts :: Maybe P.Int, httpRedirects :: Maybe P.Int, httpVerify :: Maybe P.Bool, httpResultFormat :: Maybe HttpResultFormat, httpMethod :: Maybe HttpMethod, httpAuth :: Maybe [Attribute Dynamic], httpParams :: Maybe [Attribute Dynamic], httpHeader :: Maybe [Attribute Dynamic], httpData :: Maybe ReQL, httpPage :: Maybe PaginationStrategy, httpPageLimit :: Maybe P.Int } data HttpResultFormat = FormatAuto | FormatJSON | FormatJSONP | FormatBinary instance Expr HttpResultFormat where expr FormatAuto = "auto" expr FormatJSON = "json" expr FormatJSONP = "jsonp" expr FormatBinary = "binary" data HttpMethod = GET | POST | PUT | PATCH | DELETE | HEAD deriving P.Show instance Expr HttpMethod where expr = str P.. P.show data PaginationStrategy = LinkNext | PaginationFunction (ReQL -> ReQL) instance Expr PaginationStrategy where expr LinkNext = "link-next" expr (PaginationFunction f) = expr f instance Default HttpOptions where def = HttpOptions { httpTimeout = Nothing, httpReattempts = Nothing, httpRedirects = Nothing, httpVerify = Nothing, httpResultFormat = Nothing, httpMethod = Nothing, httpAuth = Nothing, httpParams = Nothing, httpHeader = Nothing, httpData = Nothing, httpPage = Nothing, httpPageLimit = Nothing } -- | Retrieve data from the specified URL over HTTP -- > > > _ < - run ' h $ http " " def { = Just [ " foo " : = 1 ] } > > > _ < - run ' h $ http " " def { = Just PUT , httpData = Just $ expr [ " foo " : = " bar " ] } http :: Expr url => url -> HttpOptions -> ReQL http url opts = op' HTTP [url] $ render opts where render ho = let go :: Expr x => (HttpOptions -> Maybe x) -> Text -> [Attribute Static] go f s = maybe [] (\x -> [s := x]) (f ho) in mconcat [ go httpTimeout "timeout", go httpReattempts "reattempts", go httpRedirects "redirects", go httpVerify "verify", go httpResultFormat "result_format", go httpMethod "method", go httpAuth "auth", go httpParams "params", go httpHeader "header", go httpData "data", go httpPage "page", go httpPageLimit "page_limit" ] -- | Splice a list of values into an argument list args :: Expr array => array -> ReQL args a = op ARGS [a] -- | Return an infinite stream of objects representing changes to a table -- > > > cursor < - run h $ table " posts " # changes : : IO ( Cursor Datum ) > > > run h $ table " posts " # insert [ " author " : = " bill " , " message " : = " bye " , " i d " : = 4 ] : : IO WriteResponse -- {inserted:1} -- >>> next cursor -- Just {"new_val":{"author":"bill","id":4,"message":"bye"},"old_val":null} changes :: Expr seq => seq -> ReQL changes s = op CHANGES [s] -- | Optional argument for returning an array of objects describing the changes made -- > > > run h $ table " users " # ex insert [ returnChanges ] [ " name " : = " sabrina " ] : : IO WriteResponse -- {inserted:1,changes:[{"old_val":null,"new_val":{"name":"sabrina"}}]} returnChanges :: Attribute a returnChanges = "return_changes" := P.True -- | Optional argument for changes includeStates :: Attribute a includeStates = "include_states" := P.True -- | Optional argument for changes includeInitial :: Attribute a includeInitial = "include_initial" := P.True -- | Optional argument for non-atomic writes -- > > > run ' h $ table " users " # get " sabrina " # update ( merge [ " lucky_number " : = random ] ) * * * Exception : RethinkDB : Runtime error : Could not prove argument deterministic . Maybe you want to use the non_atomic flag ? -- in -- {- HERE -} -- update( get(table(db("doctests " ) , " users " ) , " sabrina " ) , ( \b - > merge(b , { lucky_number : random ( ) } ) ) ) > > > run h $ table " users " # get " sabrina " # ex update [ nonAtomic ] ( merge [ " lucky_number " : = random ] ) : : IO WriteResponse -- {replaced:1} nonAtomic :: Attribute a nonAtomic = "non_atomic" := P.True data ConflictResolution = Error | Replace | Update instance Expr ConflictResolution where expr Error = "error" expr Replace = "replace" expr Update = "update" conflict :: ConflictResolution -> Attribute a conflict cr = "conflict" := cr -- | Generate a UUID -- -- >>> run h uuid -- "...-...-...-..." uuid :: ReQL uuid = op UUID () -- | Generate a Version 5 UUID -- -- >>> run h $ uuid5 "foo" -- "aa32a020-8c2d-5ff1-823b-ad3fa5d067eb" uuid5 :: Expr name => name -> ReQL uuid5 name = op UUID [name] | Generate numbers starting from 0 -- > > > run h $ range 10 -- [0,1,2,3,4,5,6,7,8,9] range :: ReQL -> ReQL range n = op RANGE [n] -- | Generate numbers within a range -- > > > run h $ rangeFromTo 2 4 [ 2,3 ] rangeFromTo :: ReQL -> ReQL -> ReQL rangeFromTo a b = op RANGE (a, b) | Generate numbers starting from 0 -- > > > run ' h $ rangeAll # limit 4 -- [0,1,2,3] rangeAll :: ReQL rangeAll = op RANGE () -- | Wait for tables to be ready -- -- >>> run h $ table "users" # wait -- {"ready":1} wait :: Expr table => table -> ReQL wait t = op WAIT [t] -- | Convert an object or value to a JSON string -- -- >>> run h $ toJSON "a" -- "\"a\"" toJSON :: Expr a => a -> ReQL toJSON a = op TO_JSON_STRING [a] | Map over two sequences -- > > > run h $ zipWith ( + ) [ 1,2 ] [ 3,4 ] [ 4,6 ] zipWith :: (Expr left, Expr right, Expr b) => (ReQL -> ReQL -> b) -> left -> right -> ReQL zipWith f a b = op MAP (a, b, \x y -> expr (f x y)) -- | Map over multiple sequences -- > > > run ' h $ zipWithN ( \a b c - > expr $ a + b * c ) [ [ 1,2],[3,4],[5,6 ] ] -- [16,26] zipWithN :: (Arr a, Expr f) => f -> a -> ReQL zipWithN f s = op MAP $ arr s <> arr [f] -- | Change a table's configuration -- > > > run h $ table " users " # reconfigure 2 1 { " " : ... reconfigure :: (Expr table, Expr replicas) => ReQL -> replicas -> table -> ReQL reconfigure shards replicas t = op' RECONFIGURE [t] ["shards" := shards, "replicas" := replicas] -- | Rebalance a table's shards -- -- >>> run h $ table "users" # rebalance -- {"rebalanced":1,"status_changes":[{"new_val":{"status":{"all_replicas_ready":...,"ready_for_outdated_reads":... rebalance :: Expr table => table -> ReQL rebalance t = op REBALANCE [t] -- | Get the config for a table or database -- -- >>> run h $ table "users" # config -- {"primary_key":"name","write_acks":"majority","durability":"hard","name":"users","shards":...,"id":...,"db":"doctests"} config :: Expr table => table -> ReQL config t = op CONFIG [t] -- | Get the status of a table -- -- >>> run h $ table "users" # status -- {"status":{"all_replicas_ready":true,"ready_for_outdated_reads":true,... status :: Expr table => table -> ReQL status t = op STATUS [t]
null
https://raw.githubusercontent.com/AtnNn/haskell-rethinkdb/a62da54d2570d436815831bcc4136ab736fb23f6/Database/RethinkDB/Functions.hs
haskell
| ReQL Functions optional positional and named arguments. Optional named arguments can be added using `ex`, for example `upsert = ex insert ["conflict" := "update"]` For optional positional arguments this module defines an extra function if the functionality is not available otherwise. For example `argmax` for `max` and `splitOn` for `split` but `skip` instead of `sliceFrom` and `avg . (!k)` instead of `avgOf k`. # SOURCE # $setup Get the doctests ready >>> :set -XOverloadedStrings >>> h <- doctestConnect $init_doctests >>> try' $ run' h $ dbCreate "doctests" >>> try' $ run' h $ tableCreate "foo" >>> try' $ run' h $ delete $ table "foo" >>> try' $ run' h $ tableCreate "bar" >>> try' $ run' h $ delete $ table "bar" >>> try' $ run' h $ tableDrop "bar" >>> try' $ run' h $ tableCreate (table "posts") >>> try' $ run' h $ delete $ table "posts" >>> try' $ run' h $ tableCreate (table "places") >>> try' $ run' h $ delete $ table "places" >>> try' $ run' h $ tableCreate (table "users"){ tablePrimaryKey = Just "name" } >>> try' $ run' h $ delete $ table "users" >>> try' $ run' h $ table "users" # indexDrop "occupation" >>> try' $ run' h $ table "users" # indexDrop "location" >>> try' $ run' h $ table "users" # indexDrop "friends" | Create a table on the server > >>> run' h $ tableCreate (table "posts") def > [{"created":1}] > >>> run' h $ tableCreate (table "users"){ tablePrimaryKey = Just "name" } def > [{"created":1}] > >>> run' h $ tableCreate (Table (Just "doctests") "bar" (Just "name")) def > [{"created":1}] > >>> run' h $ ex tableCreate ["datacenter":="orion"] (Table (Just "doctests") "bar" (Just "name")) def > [{"created":1}] | Insert a document or a list of documents into a table {inserted:3} {inserted:1} {inserted:1} {inserted:1} | Add to or modify the contents of a document >>> run h $ table "users" # getAll "name" [str "bob"] # update (const ["occupation" := str "tailor"]) :: IO WriteResponse {replaced:1} | Replace a document with another {replaced:1} | Delete the documents >>> run h $ delete . getAll "name" [str "bob"] $ table "users" :: IO WriteResponse {deleted:1} | Like map but for write queries >>> _ <- run' h $ table "users" # replace (without ["post_count"]) | A table [{"post_count":2,"name":"bill"},{"post_count":0,"name":"nancy"}] | Drop a table >>> run' h $ tableDrop (table "foo") {"config_changes":[{"new_val":null,"old_val":{"primary_key":"id","write_acks":"majority","durability":"hard","name":"foo","shards":...,"id":...,"db":"doctests"}}],"tables_dropped":1} | List the tables in a database ["places","posts","users"] | Addition or concatenation | Subtraction -3 | Multiplication | Division | Mod | Boolean or >>> run h $ True R.|| False true | Boolean and >>> run h $ True R.&& False false | Test for equality true | Test for inequality true | Greater than true | Lesser than true | Greater than or equal to >>> run h $ [1] R.>= Null false | Lesser than or equal to true | Negation true true * Lists and Streams | The size of a sequence or an array. >>> run h $ count (table "users") >>> run h $ [1,2,3] `union` ["a", "b", "c" :: Text] [1,2,3,"a","b","c"] | Map a function over a sequence [1,2] | Filter a sequence given a predicate | Query all the documents whose value for the given index is in a given range >>> run h $ table "users" # between "name" (Closed $ str "a") (Open $ str "c") [{"post_count":2,"name":"bill"}] | Append a datum to a sequence [1,2,3] | Map a function of a sequence and concat the results [{"name":"bill","message":"hello"},{"name":"bill","message":"hi"}] [{"name":"bill","message":"hello"},{"name":"bill","message":"hi"},{"name":"nancy"}] | An efficient inner_join that uses a key for the left table and an index for the right table. [{"name":"bill","message":"hello"},{"name":"bill","message":"hi"}] | Drop elements from the head of a sequence. | Limit the size of a sequence. [1,2] | Cut out part of a sequence | Get nth element of a sequence | Reduce a sequence to a single value | Reduce a non-empty sequence to a single value | Filter out identical elements of the sequence >>> fmap sort $ run h $ distinct (table "posts" ! "flag") :: IO [String] ["deleted","pinned"] | Merge the "left" and "right" attributes of the objects in a sequence. [{"post_count":2,"flag":"deleted","name":"bill","author":"bill","id":2,"message":"hello"},{"post_count":2,"name":"bill","author":"bill","id":1,"message":"hi"}] | Order a sequence by the given keys [{"post_count":2,"name":"bill"},{"post_count":0,"name":"nancy"}] >>> run' h $ table "users" # ex orderBy ["index":="name"] [] # pluck ["name"] [{"name":"bill"},{"name":"nancy"}] | Ascending order | Descending order | Turn a grouping function and a reduction function into a grouped map reduce operation [{"group":"bill","reduction":"hi\nhello"},{"group":"bob","reduction":"lorem ipsum"}] | Rewrite multiple reductions into a single map/reduce operation | The sum of a sequence | The average of a sequence | Minimum value | Value that minimizes the function | Minimum value | Floor rounds number to interger below | Ceil rounds number to integer above | Round rounds number to nearest integer | Value that maximizes the function * Accessors | Get a single field from an object or an element of an array >>> run h $ ["foo" := True] ! "foo" true Or a single field from each object in a sequence >>> run h $ [["foo" := True], ["foo" := False]] ! "foo" [true,false] | Get a single field, or null if not present >>> run' h $ empty !? "foo" null | Keep only the given attributes [{"a":1},{"a":2},{}] | Remove the given attributes from an object | Test if a sequence contains a given element true {"a":1,"b":1,"c":2} | Literal objects, in a merge or update, are not processed recursively. {"a":{"c":2}} | Remove fields when doing a merge or update {} >>> run' h $ js "Math.PI" >>> run h $ R.map r_sin [pi, pi/2] | Server-side if | Abort the query with an error >>> run' h $ R.error (str "haha") R./ 2 + 1 *** Exception: RethinkDB: Runtime error: haha HERE - } error("haha " ) , 2 ) , 1 ) error :: (Expr s) => s -> ReQL error m = op ERROR [m] -- | Create a Database reference -- -- >>> run' h $ db "test" # info -- {"name":"test","id":...,"type":"DB"} db :: Text -> Database db = Database -- | Create a database on the server -- -- >>> run' h $ dbCreate "dev" -- {"config_changes":[{"new_val":{"name":"dev","id":...},"old_val":null}],"dbs_created":1} dbCreate :: Text -> ReQL dbCreate db_name = op DB_CREATE [expr db_name] -- | Drop a database -- -- >>> run' h $ dbDrop (db "dev") -- {"config_changes":[{"new_val":null,"old_val":{"name":"dev","id":...}}],"tables_dropped":0,"dbs_dropped":1} dbDrop :: Database -> ReQL dbDrop (Database name) = op DB_DROP [name] -- | List the databases on the server -- -- >>> _ <- run' h $ dbList dbList :: ReQL dbList = op DB_LIST () -- | Create an index on the table from the given function -- -- >>> run' h $ table "users" # indexCreate "occupation" (!"occupation") -- {"created":1} -- >>> run' h $ table "users" # ex indexCreate ["multi":=True] "friends" (!"friends") -- {"created":1} -- >>> run' h $ table "users" # ex indexCreate ["geo":=True] "location" (!"location") -- {"created":1} indexCreate :: (Expr fun) => Text -> fun -> Table -> ReQL indexCreate name f tbl = op INDEX_CREATE (tbl, expr name, f) -- | Get the status of the given indexes -- -- > run' h $ table "users" # indexStatus [] indexStatus :: Expr table => [ReQL] -> table -> ReQL indexStatus ixes tbl = op INDEX_STATUS (tbl, op ARGS [ixes]) -- | Wait for an index to be built -- -- > run' h $ table "users" # indexWait [] indexWait :: Expr table => [ReQL] -> table -> ReQL indexWait ixes tbl = op INDEX_STATUS (tbl, op ARGS [ixes]) indexRename :: Expr table => ReQL -> ReQL -> table -> ReQL indexRename from to tbl = op INDEX_RENAME (tbl, from, to) -- | Ensures that writes on a given table are written to permanent storage -- -- >>> run' h $ sync (table "users") -- {"synced":1} sync :: Expr table => table -> ReQL sync tbl = op SYNC [tbl] -- | List the indexes on the table -- -- >>> run' h $ indexList (table "users") [ " friends","location","occupation " ] indexList :: Table -> ReQL indexList tbl = op INDEX_LIST [tbl] -- | Drop an index -- -- >>> run' h $ table "users" # indexDrop "occupation" -- {"dropped":1} indexDrop :: Key -> Table -> ReQL indexDrop name tbl = op INDEX_DROP (tbl, name) -- | Retreive documents by their indexed value -- -- >>> run' h $ table "users" # getAll PrimaryKey [str "bill"] -- [{"post_count":2,"name":"bill"}] getAll :: (Expr values) => Index -> values -> Table -> ReQL getAll idx xs tbl = op' GET_ALL (tbl, op ARGS [xs]) $ case idx of Index i -> ["index" := i] PrimaryKey -> [] -- | Get a document by primary key -- -- >>> run' h $ table "users" # get "nancy" -- {"post_count":0,"name":"nancy"} get :: Expr s => ReQL -> s -> ReQL get k e = op Term.GET (e, k) -- | Convert a value to a different type -- > > > run h $ coerceTo " STRING " 1 " 1 " coerceTo :: (Expr x) => ReQL -> x -> ReQL coerceTo t a = op COERCE_TO (a, t) -- | Convert a value to an array -- > > > run h $ asArray $ [ " a " : = 1 , " b " : = 2 ] : : IO [ ( String , Int ) ] [ ( " ) ] asArray :: Expr x => x -> ReQL asArray = coerceTo "ARRAY" -- | Convert a value to a string -- > > > run h $ asString $ [ " a " : = 1 , " b " : = 2 ] -- "{\"a\":1,\"b\":2}" asString :: Expr x => x -> ReQL asString = coerceTo "STRING" -- | Convert a value to a number -- > > > run h $ asNumber ( str " 34 " ) 34 asNumber :: Expr x => x -> ReQL asNumber = coerceTo "NUMBER" -- | Convert a value to an object -- > > > run ' h $ asObject $ [ ( str " ) ] -- {"a":1,"b":2} asObject :: Expr x => x -> ReQL asObject = coerceTo "OBJECT" -- | Convert a value to a boolean asBool :: Expr x => x -> ReQL asBool = coerceTo "BOOL" | Like followed by pluck -- > > > run ' h $ [ [ " a " : = 1 , " b " : = 2 ] , [ " a " : = 2 , " c " : = 7 ] , [ " b " : = 4 ] ] # withFields [ " a " ] -- [{"a":1},{"a":2}] withFields :: Expr seq => [ReQL] -> seq -> ReQL withFields p s = op WITH_FIELDS (s, p) -- | The position in the sequence of the elements that match the predicate -- > > > run h $ indexesOf ( match " ba . " ) [ str " foo " , " bar " , " baz " ] -- [1,2] indexesOf :: (Expr fun, Expr seq) => fun -> seq -> ReQL indexesOf f s = op OFFSETS_OF (s, f) -- | Test if a sequence is empty -- > > > run h $ isEmpty [ 1 ] -- false isEmpty :: Expr seq => seq -> ReQL isEmpty s = op IS_EMPTY [s] -- | Select a given number of elements from a sequence with uniform random distribution -- > > > _ < - run ' h $ sample 3 [ 0,1,2,3,4,5,6,7,8,9 ] sample :: (Expr n, Expr seq) => n -> seq -> ReQL sample n s = op SAMPLE (s, n) -- | Prepend an element to an array -- > > > run h $ prepend 1 [ 2,3 ] -- [1,2,3] prepend :: (Expr datum, Expr array) => datum -> array -> ReQL prepend d a = op PREPEND (a, d) | The different of two lists -- > > > run h $ [ 1,2,3,4,5 ] # difference [ 2,5 ] [ 1,3,4 ] difference :: (Expr a, Expr b) => a -> b -> ReQL difference a b = op DIFFERENCE (b, a) -- | Insert a datum into an array if it is not yet present -- > > > run h $ setInsert 3 [ 1,2,4,4,5 ] [ 1,2,4,5,3 ] setInsert :: (Expr datum, Expr array) => datum -> array -> ReQL setInsert d a = op SET_INSERT (a, d) | The union of two sets -- > > > run h $ [ 1,2 ] ` setUnion ` [ 2,3 ] [ 2,3,1 ] setUnion :: (Expr a, Expr b) => a -> b -> ReQL setUnion a b = op SET_UNION (b, a) | The intersection of two sets -- > > > run h $ [ 1,2 ] ` setIntersection ` [ 2,3 ] [ 2 ] setIntersection :: (Expr a, Expr b) => a -> b -> ReQL setIntersection a b = op SET_INTERSECTION (b, a) | The difference of two sets -- > > > run h $ [ 2,3 ] # setDifference [ 1,2 ] [ 3 ] setDifference :: (Expr set, Expr remove) => remove -> set -> ReQL setDifference r s = op SET_DIFFERENCE (s, r) -- | Test if an object has the given fields -- > > > run h $ hasFields " a " $ [ " a " : = 1 ] -- true hasFields :: (Expr obj) => ReQL -> obj -> ReQL hasFields p o = op HAS_FIELDS (o, expr p) -- | Insert a datum at the given position in an array -- > > > run h $ insertAt 1 4 [ 1,2,3 ] -- [1,4,2,3] insertAt :: (Expr n, Expr datum, Expr array) => n -> datum -> array -> ReQL insertAt n d a = op INSERT_AT (a, n, d) -- | Splice an array at a given position inside another array -- > > > run h $ spliceAt 2 [ 4,5 ] [ 1,2,3 ] [ 1,2,4,5,3 ] spliceAt :: (Expr n, Expr replace, Expr array) => n -> replace -> array -> ReQL spliceAt n s a = op SPLICE_AT (a, n, s) -- | Delete an element from an array -- > > > run h $ deleteAt 1 [ 1,2,3 ] -- [1,3] deleteAt :: (Expr n, Expr array) => n -> array -> ReQL deleteAt n a = op DELETE_AT (a, n) -- | Change an element in an array -- > > > run h $ changeAt 1 4 [ 1,2,3 ] -- [1,4,3] changeAt :: (Expr n, Expr datum, Expr array) => n -> datum -> array -> ReQL changeAt n d a = op CHANGE_AT (a, n, d) -- | The list of keys of the given object -- > > > run h $ keys [ " a " : = 1 , " b " : = 2 ] -- ["a","b"] keys :: Expr object => object -> ReQL keys o = op KEYS [o] -- | The list of values of the given object -- > > > run h $ values [ " a " : = 1 , " b " : = 2 ] -- [1,2] values :: Expr object => object -> ReQL values o = op VALUES [o] -- | Match a string to a regular expression. -- -- >>> run' h $ str "foobar" # match "f(.)+[bc](.+)" { " groups":[{"start":2,"end":3,"str":"o"},{"start":4,"end":6,"str":"ar"}],"start":0,"end":6,"str":"foobar " } match :: (Expr string) => ReQL -> string -> ReQL match r s = op MATCH (s, r) -- | Apply a function to a list of arguments. -- -- Called /do/ in the official drivers -- > > > run h $ ( \x - > x R. * 2 ) ` apply ` [ 4 ] 8 apply :: (Expr fun, Expr arg) => fun -> [arg] -> ReQL f `apply` as = op FUNCALL (expr f : P.map expr as) -- | Catch some expections inside the query. -- Called /default/ in the official drivers -- > > > run h $ R.handle ( const 0 ) $ [ " a " : = 1 ] ! " b " 0 > > > run h $ R.handle ( expr . i d ) $ [ " a " : = 1 ] ! " b " -- "No attribute `b` in object:\n{\n\t\"a\":\t1\n}" handle :: (Expr instead, Expr reql) => (ReQL -> instead) -> reql -> ReQL handle h r = op DEFAULT (r, expr . h) -- | A string representing the type of an expression -- -- >>> run h $ typeOf 1 -- "NUMBER" typeOf :: Expr a => a -> ReQL typeOf a = op TYPE_OF [a] -- | Get information on a given expression. Useful for tables and databases. -- > > > run h $ info $ table " users " -- {"primary_key":"name","doc_count_estimates":...,"name":"users","id":...,"indexes":["friends","location"],"type":"TABLE","db":{"name":"doctests","id":...,"type":"DB"}} info :: Expr a => a -> ReQL info a = op INFO [a] -- | Parse a json string into an object -- -- >>> run' h $ json "{\"a\":1}" -- {"a":1} json :: ReQL -> ReQL json s = op Term.JSON [s] -- | Flipped function application infixl 8 # (#) :: (Expr a, Expr b) => a -> (a -> b) -> ReQL x # f = expr (f x) -- | Convert to upper case -- > > > run h $ upcase ( str " " ) " FOO " upcase :: Expr str => str -> ReQL upcase s = op UPCASE [s] -- | Convert to lower case -- > > > run h $ downcase ( str " " ) -- "foo" downcase :: Expr str => str -> ReQL downcase s = op DOWNCASE [s] -- | Split a string on whitespace characters -- -- >>> run' h $ split (str "foo bar") [ " " ] split :: Expr str => str -> ReQL split s = op SPLIT [s] -- | Split a string on a given delimiter -- -- >>> run' h $ str "foo, bar" # splitOn "," -- ["foo"," bar"] -- -- >>> run' h $ str "foo" # splitOn "" -- ["f","o","o"] splitOn :: Expr str => ReQL -> str -> ReQL splitOn sep s = op SPLIT [expr s, sep] -- | Split a string up to a given number of times -- > > > run ' h $ str " a : b : c : d " # splitMax " : " 2 -- ["a","b","c:d"] splitMax :: Expr str => ReQL -> ReQL -> str -> ReQL splitMax sep n s = op SPLIT [expr s, sep, n] | A random float between 0 and 1 -- > > > run ' h $ ( \x - > x R. < 1 R. & & x R.>= 0 ) ` apply ` [ random ] -- true random :: ReQL random = op RANDOM () -- | A random number between 0 and n -- > > > run ' h $ ( \x - > x R. < 10 R. & & x R.>= 0 ) ` apply ` [ randomTo 10 ] -- true randomTo :: ReQL -> ReQL randomTo n = op RANDOM [n] -- | A random number between 0 and n -- > > > run ' h $ ( \x - > x R. < 10 R. & & x R.>= 5 ) ` apply ` [ randomFromTo 5 10 ] -- true randomFromTo :: ReQL -> ReQL -> ReQL randomFromTo n m = op RANDOM [n, m] data HttpOptions = HttpOptions { httpTimeout :: Maybe P.Int, httpReattempts :: Maybe P.Int, httpRedirects :: Maybe P.Int, httpVerify :: Maybe P.Bool, httpResultFormat :: Maybe HttpResultFormat, httpMethod :: Maybe HttpMethod, httpAuth :: Maybe [Attribute Dynamic], httpParams :: Maybe [Attribute Dynamic], httpHeader :: Maybe [Attribute Dynamic], httpData :: Maybe ReQL, httpPage :: Maybe PaginationStrategy, httpPageLimit :: Maybe P.Int } data HttpResultFormat = FormatAuto | FormatJSON | FormatJSONP | FormatBinary instance Expr HttpResultFormat where expr FormatAuto = "auto" expr FormatJSON = "json" expr FormatJSONP = "jsonp" expr FormatBinary = "binary" data HttpMethod = GET | POST | PUT | PATCH | DELETE | HEAD deriving P.Show instance Expr HttpMethod where expr = str P.. P.show data PaginationStrategy = LinkNext | PaginationFunction (ReQL -> ReQL) instance Expr PaginationStrategy where expr LinkNext = "link-next" expr (PaginationFunction f) = expr f instance Default HttpOptions where def = HttpOptions { httpTimeout = Nothing, httpReattempts = Nothing, httpRedirects = Nothing, httpVerify = Nothing, httpResultFormat = Nothing, httpMethod = Nothing, httpAuth = Nothing, httpParams = Nothing, httpHeader = Nothing, httpData = Nothing, httpPage = Nothing, httpPageLimit = Nothing } -- | Retrieve data from the specified URL over HTTP -- > > > _ < - run ' h $ http " " def { = Just [ " foo " : = 1 ] } > > > _ < - run ' h $ http " " def { = Just PUT , httpData = Just $ expr [ " foo " : = " bar " ] } http :: Expr url => url -> HttpOptions -> ReQL http url opts = op' HTTP [url] $ render opts where render ho = let go :: Expr x => (HttpOptions -> Maybe x) -> Text -> [Attribute Static] go f s = maybe [] (\x -> [s := x]) (f ho) in mconcat [ go httpTimeout "timeout", go httpReattempts "reattempts", go httpRedirects "redirects", go httpVerify "verify", go httpResultFormat "result_format", go httpMethod "method", go httpAuth "auth", go httpParams "params", go httpHeader "header", go httpData "data", go httpPage "page", go httpPageLimit "page_limit" ] -- | Splice a list of values into an argument list args :: Expr array => array -> ReQL args a = op ARGS [a] -- | Return an infinite stream of objects representing changes to a table -- > > > cursor < - run h $ table " posts " # changes : : IO ( Cursor Datum ) > > > run h $ table " posts " # insert [ " author " : = " bill " , " message " : = " bye " , " i d " : = 4 ] : : IO WriteResponse -- {inserted:1} -- >>> next cursor -- Just {"new_val":{"author":"bill","id":4,"message":"bye"},"old_val":null} changes :: Expr seq => seq -> ReQL changes s = op CHANGES [s] -- | Optional argument for returning an array of objects describing the changes made -- > > > run h $ table " users " # ex insert [ returnChanges ] [ " name " : = " sabrina " ] : : IO WriteResponse -- {inserted:1,changes:[{"old_val":null,"new_val":{"name":"sabrina"}}]} returnChanges :: Attribute a returnChanges = "return_changes" := P.True -- | Optional argument for changes includeStates :: Attribute a includeStates = "include_states" := P.True -- | Optional argument for changes includeInitial :: Attribute a includeInitial = "include_initial" := P.True -- | Optional argument for non-atomic writes -- > > > run ' h $ table " users " # get " sabrina " # update ( merge [ " lucky_number " : = random ] ) * * * Exception : RethinkDB : Runtime error : Could not prove argument deterministic . Maybe you want to use the non_atomic flag ? -- in -- {- HERE update( {replaced:1} | Generate a UUID >>> run h uuid "...-...-...-..." | Generate a Version 5 UUID >>> run h $ uuid5 "foo" "aa32a020-8c2d-5ff1-823b-ad3fa5d067eb" [0,1,2,3,4,5,6,7,8,9] | Generate numbers within a range [0,1,2,3] | Wait for tables to be ready >>> run h $ table "users" # wait {"ready":1} | Convert an object or value to a JSON string >>> run h $ toJSON "a" "\"a\"" | Map over multiple sequences [16,26] | Change a table's configuration | Rebalance a table's shards >>> run h $ table "users" # rebalance {"rebalanced":1,"status_changes":[{"new_val":{"status":{"all_replicas_ready":...,"ready_for_outdated_reads":... | Get the config for a table or database >>> run h $ table "users" # config {"primary_key":"name","write_acks":"majority","durability":"hard","name":"users","shards":...,"id":...,"db":"doctests"} | Get the status of a table >>> run h $ table "users" # status {"status":{"all_replicas_ready":true,"ready_for_outdated_reads":true,...
# LANGUAGE FlexibleInstances , OverloadedStrings , GADTs # ReQL was designed for dynamic languages . Many operations take module Database.RethinkDB.Functions where import Data.Text (Text) import Control.Monad.State import Control.Applicative import Data.Maybe import Data.Default import Data.Monoid import Database.RethinkDB.Wire.Term as Term import Database.RethinkDB.ReQL import Database.RethinkDB.Types import Database.RethinkDB.Datum hiding (Error) import Prelude (($), (.)) import qualified Prelude as P > > > : load Database . RethinkDB.Doctest > > > import qualified Database . as R > > > default ( Datum , ReQL , String , Int , Double ) tableCreate :: Table -> ReQL tableCreate (Table mdb table_name pkey) = withQuerySettings $ \QuerySettings{ queryDefaultDatabase = ddb } -> op' TABLE_CREATE (fromMaybe ddb mdb, table_name) $ catMaybes [ ("primary_key" :=) <$> pkey ] > > > run h $ table " users " # insert ( map ( \x - > [ " name":=x ] ) [ " bill " , " bob " , " " : : Text ] ) : : IO WriteResponse > > > run h $ table " posts " # insert [ " author " : = str " bill " , " message " : = str " hi " , " i d " : = 1 ] : : IO WriteResponse > > > run h $ table " posts " # insert [ " author " : = str " bill " , " message " : = str " hello " , " i d " : = 2 , " flag " : = str " deleted " ] : : IO WriteResponse > > > run h $ table " posts " # insert [ " author " : = str " bob " , " message " : = str " lorem ipsum " , " i d " : = 3 , " flag " : = str " pinned " ] : : IO WriteResponse insert :: (Expr object) => object -> Table -> ReQL insert a tb = op INSERT (tb, a) update :: (Expr selection, Expr a) => (ReQL -> a) -> selection -> ReQL update f s = op UPDATE (s, expr . f) > > > run h $ replace ( \user - > [ " name " : = user!"name " , " occupation " : = str " clothier " ] ) . R.filter ( ( R.== str " tailor " ) . ( ! ? " occupation " ) ) $ table " users " : : IO WriteResponse replace :: (Expr selection, Expr a) => (ReQL -> a) -> selection -> ReQL replace f s = op REPLACE (s, expr . f) delete :: (Expr selection) => selection -> ReQL delete s = op Term.DELETE [s] > > > run h $ forEach ( \user - > table " users " # get ( user!"name " ) # ex update [ nonAtomic ] ( const [ " post_count " : = R.count ( table " posts " # R.filter ( \post - > post!"author " R.== user!"name " ) ) ] ) ) ( table " users " ) : : IO WriteResponse { replaced:2 } forEach :: (Expr a, Expr s) => (ReQL -> a) -> s -> ReQL forEach f s = op FOR_EACH (s, expr P.. f) > > > fmap sort $ run h $ table " users " : : IO [ Datum ] table :: Text -> Table table n = Table Nothing n Nothing tableDrop :: Table -> ReQL tableDrop (Table mdb table_name _) = withQuerySettings $ \QuerySettings{ queryDefaultDatabase = ddb } -> op TABLE_DROP (fromMaybe ddb mdb, table_name) > > > fmap sort $ run h $ tableList ( db " doctests " ) : : IO [ String ] tableList :: Database -> ReQL tableList name = op TABLE_LIST [name] infixl 6 +, - infixl 7 *, / Use the instance , or a qualified operator . > > > run h $ 2 + 5 7 > > > run h $ str " foo " " bar " " foobar " (+) :: (Expr a, Expr b) => a -> b -> ReQL (+) a b = op ADD (a, b) > > > run h $ 2 - 5 (-) :: (Expr a, Expr b) => a -> b -> ReQL (-) a b = op SUB (a, b) > > > run h $ 2 * 5 10 (*) :: (Expr a, Expr b) => a -> b -> ReQL (*) a b = op MUL (a, b) > > > run h $ 2 R./ 5 0.4 (/) :: (Expr a, Expr b) => a -> b -> ReQL (/) a b = op DIV (a, b) > > > run h $ 5 ` mod ` 2 1 mod :: (Expr a, Expr b) => a -> b -> ReQL mod a b = op MOD (a, b) infixr 2 || infixr 3 && (||) :: (Expr a, Expr b) => a -> b -> ReQL a || b = op OR (a, b) (&&) :: (Expr a, Expr b) => a -> b -> ReQL a && b = op AND (a, b) infix 4 ==, /= > > > run h $ [ " a " : = 1 ] R.== [ " a " : = 1 ] (==) :: (Expr a, Expr b) => a -> b -> ReQL a == b = op EQ (a, b) > > > run h $ 1 R./= False (/=) :: (Expr a, Expr b) => a -> b -> ReQL a /= b = op NE (a, b) infix 4 >, <, <=, >= > > > run h $ 3 R. > 2 (>) :: (Expr a, Expr b) => a -> b -> ReQL a > b = op GT (a, b) > > > run h $ ( str " a " ) R. < ( str " b " ) (<) :: (Expr a, Expr b) => a -> b -> ReQL a < b = op LT (a, b) (>=) :: (Expr a, Expr b) => a -> b -> ReQL a >= b = op GE (a, b) > > > run h $ 2 R.<= 2 (<=) :: (Expr a, Expr b) => a -> b -> ReQL a <= b = op LE (a, b) > > > run h $ R.not False > > > run h $ R.not Null not :: (Expr a) => a -> ReQL not a = op NOT [a] 2 count :: (Expr a) => a -> ReQL count e = op COUNT [e] | Join two sequences . union :: (Expr a, Expr b) => a -> b -> ReQL union a b = op UNION (a, b) > > > run h $ R.map ( ! " a " ) [ [ " a " : = 1 ] , [ " a " : = 2 ] ] map :: (Expr a, Expr b) => (ReQL -> b) -> a -> ReQL map f a = op MAP (a, expr P.. f) > > > run h $ R.filter ( R. < 4 ) [ 3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ] [ 3,1,1,2 ] filter :: (Expr predicate, Expr seq) => predicate -> seq -> ReQL filter f a = op' FILTER (a, f) ["default" := op ERROR ()] between :: (Expr left, Expr right, Expr seq) => Index -> Bound left -> Bound right -> seq -> ReQL between i a b e = op' BETWEEN [expr e, expr $ getBound a, expr $ getBound b] $ idx P.++ ["left_bound" ?:= closedOrOpen a, "right_bound" ?:= closedOrOpen b] where idx = case i of PrimaryKey -> []; Index name -> ["index" := name] > > > run h $ append 3 [ 1 , 2 ] append :: (Expr a, Expr b) => a -> b -> ReQL append a b = op APPEND (b, a) > > > run h $ concatMap i d [ [ 1 , 2 ] , [ 3 ] , [ 4 , 5 ] ] [ 1,2,3,4,5 ] concatMap :: (Expr a, Expr b) => (ReQL -> b) -> a -> ReQL concatMap f e = op CONCAT_MAP (e, expr P.. f) | SQL - like inner join of two sequences > > > sorted $ run ' h $ innerJoin ( post - > user!"name " R.== post!"author " ) ( table " users " ) ( table " posts " ) # R.zip # orderBy [ asc " i d " ] # pluck [ " name " , " message " ] innerJoin :: (Expr a, Expr b, Expr c) => (ReQL -> ReQL -> c) -> a -> b -> ReQL innerJoin f a b = op INNER_JOIN (a, b, fmap expr P.. f) | SQL - like outer join of two sequences > > > sorted $ run ' h $ outerJoin ( post - > user!"name " R.== post!"author " ) ( table " users " ) ( table " posts " ) # R.zip # orderBy [ asc " i d " , asc " name " ] # pluck [ " name " , " message " ] outerJoin :: (Expr a, Expr b, Expr c) => (ReQL -> ReQL -> c) -> a -> b -> ReQL outerJoin f a b = op OUTER_JOIN (a, b, fmap expr P.. f) > > > sorted $ run ' h $ table " posts " # eqJoin " author " ( table " users " ) " name " # R.zip # orderBy [ asc " i d " ] # pluck [ " name " , " message " ] eqJoin :: (Expr fun, Expr right, Expr left) => fun -> right -> Index -> left -> ReQL eqJoin key right (Index idx) left = op' EQ_JOIN (left, key, right) ["index" := idx] eqJoin key right PrimaryKey left = op EQ_JOIN (left, key, right) > > > run h $ skip 2 [ 1 , 2 , 3 , 4 ] [ 3,4 ] skip :: (Expr n, Expr seq) => n -> seq -> ReQL skip a b = op SKIP (b, a) > > > run h $ limit 2 [ 1 , 2 , 3 , 4 ] limit :: (Expr n, Expr seq) => n -> seq -> ReQL limit n s = op LIMIT (s, n) > > > run h $ slice 2 4 [ 1 , 2 , 3 , 4 , 5 ] [ 3,4 ] slice :: (Expr a, Expr b, Expr c) => a -> b -> c -> ReQL slice n m s = op SLICE (s, n, m) > > > run h $ nth 2 [ 1 , 2 , 3 , 4 , 5 ] 3 nth :: (Expr a, Expr seq) => a -> seq -> ReQL nth a s = op NTH (s, a) > > > run h $ reduce0 ( + ) 0 [ 1 , 2 , 3 ] 6 reduce0 :: (Expr base, Expr seq, Expr a) => (ReQL -> ReQL -> a) -> base -> seq -> ReQL reduce0 f b s = op REDUCE (s `union` [b], fmap expr P.. f) > > > run h $ reduce ( + ) [ 1 , 2 , 3 ] 6 reduce :: (Expr a, Expr s) => (ReQL -> ReQL -> a) -> s -> ReQL reduce f s = op REDUCE (s, fmap expr P.. f) distinct :: (Expr s) => s -> ReQL distinct s = op DISTINCT [s] > > > fmap sort $ run h $ table " posts " # eqJoin " author " ( table " users " ) " name " # R.zip : : IO [ Datum ] zip :: (Expr a) => a -> ReQL zip a = op ZIP [a] > > > run ' h $ table " users " # orderBy [ desc " post_count " , asc " name " ] # pluck [ " name " , " post_count " ] orderBy :: (Expr s) => [ReQL] -> s -> ReQL orderBy o s = op ORDER_BY (expr s : P.map expr o) asc :: ReQL -> ReQL asc f = op ASC [f] desc :: ReQL -> ReQL desc f = op DESC [f] > > > run ' h $ table " posts " # orderBy [ asc " i d " ] # group ( ! " author " ) ( reduce ( \a b - > a + " \n " + b ) . R.map ( ! " message " ) ) > > > run ' h $ table " users " # group ( ( ! 0 ) . splitOn " " . ( ! " name " ) ) ( \users - > let pc = users!"post_count " in [ avg pc , R.sum pc ] ) [ { " group":"b","reduction":[2,2]},{"group":"n","reduction":[0,0 ] } ] group :: (Expr group, Expr reduction, Expr seq) => (ReQL -> group) -> (ReQL -> reduction) -> seq -> ReQL group g f s = ReQL $ do mr <- termToMapReduce (expr . f) runReQL $ op UNGROUP [mr $ op GROUP (expr s, expr . g)] mapReduce :: (Expr reduction, Expr seq) => (ReQL -> reduction) -> seq -> ReQL mapReduce f s = ReQL $ do mr <- termToMapReduce (expr . f) runReQL $ mr (expr s) > > > run h $ sum [ 1 , 2 , 3 ] 6 sum :: (Expr s) => s -> ReQL sum s = op SUM [s] > > > run h $ avg [ 1 , 2 , 3 , 4 ] 2.5 avg :: (Expr s) => s -> ReQL avg s = op AVG [s] min :: Expr s => s -> ReQL min s = op MIN [s] argmin :: (Expr s, Expr a) => (ReQL -> a) -> s -> ReQL argmin f s = op MIN (s, expr . f) max :: Expr s => s -> ReQL max s = op MAX [s] > > > run h $ R.floor 2.9 2 floor :: Expr s => s -> ReQL floor s = op FLOOR [s] > > > run h $ R.ceil 2.1 3 ceil :: Expr s => s -> ReQL ceil s = op CEIL [s] > > > run h $ R.round 2.5 3 round :: Expr s => s -> ReQL round s = op ROUND [s] argmax :: (Expr s, Expr a) => (ReQL -> a) -> s -> ReQL argmax f s = op MAX (s, expr . f) infixl 9 ! > > > run h $ [ 1 , 2 , 3 ] ! 0 1 (!) :: (Expr s) => s -> ReQL -> ReQL s ! k = op BRACKET (s, k) (!?) :: (Expr s) => s -> ReQL -> ReQL s !? k = P.flip apply [expr s, k] $ \s' k' -> op DEFAULT (op BRACKET (s', k'), Null) > > > run ' h $ [ [ " a " : = 1 , " b " : = 2 ] , [ " a " : = 2 , " c " : = 7 ] , [ " b " : = 4 ] ] # pluck [ " a " ] pluck :: (Expr o) => [ReQL] -> o -> ReQL pluck ks e = op PLUCK (cons e $ arr (P.map expr ks)) > > > run ' h $ [ [ " a " : = 1 , " b " : = 2 ] , [ " a " : = 2 , " c " : = 7 ] , [ " b " : = 4 ] ] # without [ " a " ] [ { " } ] without :: (Expr o) => [ReQL] -> o -> ReQL without ks e = op WITHOUT (cons e $ arr (P.map expr ks)) > > > run ' h $ [ 1,2,3 ] # contains 1 contains :: (Expr x, Expr seq) => x -> seq -> ReQL contains x s = op CONTAINS (s, x) | Merge two objects together NOTE : This driver is based on the official JavaScript driver , you are correct to expect the same semantics . However the order of composition is flipped by putting the first argument last . > > > run ' h $ merge [ " a " : = 1 , " b " : = 1 ] [ " b " : = 1 , " c " : = 2 ] merge :: (Expr a, Expr b) => a -> b -> ReQL merge a b = op MERGE (b, a) > > > run ' h $ [ " a " : = [ " b " : = 1 ] ] # merge [ " a " : = literal [ " c " : = 2 ] ] literal :: Expr a => a -> ReQL literal a = op LITERAL [a] > > > run ' h $ [ " a " : = [ " b " : = 1 ] ] # merge [ " a " : = remove ] remove :: ReQL remove = op LITERAL () | Evaluate a JavaScript expression 3.141592653589793 > > > let r_sin x = js " Math.sin " ` apply ` [ x ] [ 1.2246 ... ,1 ] js :: ReQL -> ReQL js s = op JAVASCRIPT [s] > > > run h $ branch ( 1 R. < 2 ) 3 4 3 branch :: (Expr a, Expr b, Expr c) => a -> b -> c -> ReQL branch a b c = op BRANCH (a, b, c) get(table(db("doctests " ) , " users " ) , " sabrina " ) , ( \b - > merge(b , { lucky_number : random ( ) } ) ) ) > > > run h $ table " users " # get " sabrina " # ex update [ nonAtomic ] ( merge [ " lucky_number " : = random ] ) : : IO WriteResponse nonAtomic :: Attribute a nonAtomic = "non_atomic" := P.True data ConflictResolution = Error | Replace | Update instance Expr ConflictResolution where expr Error = "error" expr Replace = "replace" expr Update = "update" conflict :: ConflictResolution -> Attribute a conflict cr = "conflict" := cr uuid :: ReQL uuid = op UUID () uuid5 :: Expr name => name -> ReQL uuid5 name = op UUID [name] | Generate numbers starting from 0 > > > run h $ range 10 range :: ReQL -> ReQL range n = op RANGE [n] > > > run h $ rangeFromTo 2 4 [ 2,3 ] rangeFromTo :: ReQL -> ReQL -> ReQL rangeFromTo a b = op RANGE (a, b) | Generate numbers starting from 0 > > > run ' h $ rangeAll # limit 4 rangeAll :: ReQL rangeAll = op RANGE () wait :: Expr table => table -> ReQL wait t = op WAIT [t] toJSON :: Expr a => a -> ReQL toJSON a = op TO_JSON_STRING [a] | Map over two sequences > > > run h $ zipWith ( + ) [ 1,2 ] [ 3,4 ] [ 4,6 ] zipWith :: (Expr left, Expr right, Expr b) => (ReQL -> ReQL -> b) -> left -> right -> ReQL zipWith f a b = op MAP (a, b, \x y -> expr (f x y)) > > > run ' h $ zipWithN ( \a b c - > expr $ a + b * c ) [ [ 1,2],[3,4],[5,6 ] ] zipWithN :: (Arr a, Expr f) => f -> a -> ReQL zipWithN f s = op MAP $ arr s <> arr [f] > > > run h $ table " users " # reconfigure 2 1 { " " : ... reconfigure :: (Expr table, Expr replicas) => ReQL -> replicas -> table -> ReQL reconfigure shards replicas t = op' RECONFIGURE [t] ["shards" := shards, "replicas" := replicas] rebalance :: Expr table => table -> ReQL rebalance t = op REBALANCE [t] config :: Expr table => table -> ReQL config t = op CONFIG [t] status :: Expr table => table -> ReQL status t = op STATUS [t]
d65edf20b6868fe295e22e2a5c7a18d65b133a0897dc05be646fc0ef74c36a72
ingolia-lab/RiboSeq
SVMLight.hs
{-# LANGUAGE BangPatterns #-} module Bio.RiboSeq.SVMLight where import Control.Monad import qualified Data.ByteString.Char8 as BS import Data.Char (isSpace) import Data.List import Data.Monoid import Numeric import System.Exit import System.FilePath import System.IO (IOMode(..), withFile) import System.Process import qualified Data.Vector.Unboxed as U verbose :: Bool verbose = True myRawSystem :: String -> [String] -> IO ExitCode myRawSystem execu arglist = do when verbose $ putStrLn (unwords $ execu : arglist) rawSystem execu arglist targetYes, targetNo, targetQuery :: BS.ByteString targetYes = BS.pack "+1" targetNo = BS.pack "-1" targetQuery = BS.pack "0" exampleLine :: BS.ByteString -> [(Int, Double)] -> Maybe BS.ByteString -> BS.ByteString exampleLine target features minfo = BS.unwords $ target : (BS.pack featuresStr) : infobs where infobs = maybe [] (\info -> [ BS.singleton '#', info ]) minfo featuresStr = foldr ($) "" . intersperse (' ' :) . map showsFeature $ features showsFeature (fidx, fval) = shows fidx . (':' :) . showEFloat (Just 4) fval data SVMMode = SVMClassification | SVMRegression | SVMPreference deriving (Show, Eq, Ord, Enum) modeOpts :: SVMMode -> [String] modeOpts SVMClassification = [ "-z", "c" ] modeOpts SVMRegression = [ "-z", "r" ] modeOpts SVMPreference = [ "-z", "p" ] data SVMKernel = SVMLinear | SVMPolynomial { degree :: Maybe Int, scaling :: Maybe Double, baseline :: Maybe Double } | SVMRadial { gamma :: Maybe Double } | SVMSigmoid { scaling :: Maybe Double, baseline :: Maybe Double } deriving (Show) kernelOpts :: SVMKernel -> [String] kernelOpts SVMLinear = [ "-t", "0" ] kernelOpts (SVMPolynomial md ms mc) = concat [ [ "-t", "1" ] , maybe [] (\d -> [ "-d", show d ]) md , maybe [] (\s -> [ "-s", show s ]) ms , maybe [] (\c -> [ "-c", show c ]) mc ] kernelOpts (SVMRadial mg) = [ "-t", "2" ] ++ maybe [] (\g -> [ "-g", show g ]) mg kernelOpts (SVMSigmoid ms mc) = concat [ [ "-t", "3" ] , maybe [] (\s -> [ "-s", show s ]) ms , maybe [] (\c -> [ "-c", show c ]) mc ] data RunSVMLearn = RunSVMLearn { learnBinary :: FilePath , examplesIn :: FilePath , modelOut :: FilePath , mode :: Maybe SVMMode -- -z , learnVerbose :: Maybe Int -- -v , softMargin :: Maybe Double -- -c , width :: Maybe Double -- -w , positiveWeight :: Maybe Double -- -j , biasedPlane :: Maybe Bool -- -b , removeRetrain :: Maybe Bool -- -i , positiveTrans :: Maybe Double -- -p , kernel :: Maybe SVMKernel -- -t and -d, -g, -s, -r, -u , maxQPSize :: Maybe Int -- -q , maxNewVar :: Maybe Int -- -n , kernelCache :: Maybe Int -- -m , termEps :: Maybe Double -- -e , shrinkIter :: Maybe Int -- -h , checkFinalOpt :: Maybe Bool -- -f , maxIter :: Maybe Int -- -# } deriving (Show) defaultLearn :: RunSVMLearn defaultLearn = RunSVMLearn { learnBinary = error "SVMLight: no svm_learn binary specified" , examplesIn = error "SVMLight: no examples input file specified" , modelOut = error "SVMLight: no model output file specified" , mode = Nothing, learnVerbose = Nothing, softMargin = Nothing, width = Nothing , positiveWeight = Nothing, biasedPlane = Nothing, removeRetrain = Nothing , positiveTrans = Nothing , kernel = Nothing , maxQPSize = Nothing, maxNewVar = Nothing, kernelCache = Nothing, termEps = Nothing , shrinkIter = Nothing, checkFinalOpt = Nothing, maxIter = Nothing } learnOpts :: RunSVMLearn -> [String] learnOpts svmLearn = concat [ zOpts, vOpts, cOpts, wOpts, jOpts, bOpts, iOpts , pOpts , maybe [] kernelOpts . kernel $ svmLearn , qOpts, nOpts, mOpts, eOpts, hOpts, fOpts, poundOpts ] where zOpts = maybe [] modeOpts . mode $ svmLearn vOpts = maybe [] (\v -> [ "-v", show v ]) . learnVerbose $ svmLearn cOpts = maybe [] (\c -> [ "-c", show c ]) . softMargin $ svmLearn wOpts = maybe [] (\w -> [ "-w", show w ]) . width $ svmLearn jOpts = maybe [] (\j -> [ "-j", show j ]) . positiveWeight $ svmLearn bOpts = maybe [] (\b -> [ "-b", if b then "1" else "0" ]) . biasedPlane $ svmLearn iOpts = maybe [] (\i -> [ "-i", if i then "1" else "0" ]) . removeRetrain $ svmLearn pOpts = maybe [] (\p -> [ "-p", show p ]) . positiveTrans $ svmLearn qOpts = maybe [] (\q -> [ "-q", show q ]) . maxQPSize $ svmLearn nOpts = maybe [] (\n -> [ "-n", show n ]) . maxNewVar $ svmLearn mOpts = maybe [] (\m -> [ "-m", show m ]) . kernelCache $ svmLearn eOpts = maybe [] (\e -> [ "-e", show e ]) . termEps $ svmLearn hOpts = maybe [] (\h -> [ "-h", show h ]) . shrinkIter $ svmLearn fOpts = maybe [] (\f -> [ "-f", if f then "1" else "0" ]) . checkFinalOpt $ svmLearn poundOpts = maybe [] (\p -> [ "-#", show p ]) . maxIter $ svmLearn runSVMLearn :: RunSVMLearn -> IO ExitCode runSVMLearn svmLearn = myRawSystem (learnBinary svmLearn) $ learnOpts svmLearn ++ [ examplesIn svmLearn, modelOut svmLearn ] data RunSVMClassify = RunSVMClassify { classifyBinary :: FilePath , queriesIn :: FilePath , modelIn :: FilePath , decisionsOut :: FilePath , classifyVerbose :: Maybe Int -- -v } deriving (Show) defaultClassify :: RunSVMClassify defaultClassify = RunSVMClassify { classifyBinary = error "SVMLight: no svm_classify binary specified" , queriesIn = error "SVMLight: no examples input file specified" , modelIn = error "SVMLight: no model input file specified" , decisionsOut = error "SVMLight: No decisions output file specified" , classifyVerbose = Nothing } classifyOpts :: RunSVMClassify -> [String] classifyOpts svmLearn = concat [ vOpts ] where vOpts = maybe [] (\v -> [ "-v", show v ]) . classifyVerbose $ svmLearn runSVMClassify :: RunSVMClassify -> IO ExitCode runSVMClassify svmClassify = myRawSystem (classifyBinary svmClassify) $ classifyOpts svmClassify ++ [ queriesIn svmClassify, modelIn svmClassify, decisionsOut svmClassify ] -- runSVMClassifyWithScore :: RunSVMClassify -> IO ExitCode -- runSVMClassifyWithScore classify = bracket mkScoreTmp rmScoreTmp $ \scorename -> -- let classifyTmp = classify { decisionsOut = scorename } -- in runSVMClassify classifyTmp >>= \ec -> do when ( ec = = ExitSuccess ) $ pasteScore ( queriesIn classify ) ( decisionsOut classify ) return ec where mkScoreTmp = ( decisionsOut classify + + " XXXXXX " ) > > = \(name , h ) - > -- hClose h >> return name rmScoreTmp scorename = doesFileExist > > = flip when ( removeFile ) pasteScore :: FilePath -> FilePath -> FilePath -> IO () pasteScore queryFilename scoreFilename pastedFilename = do query <- liftM BS.lines . BS.readFile $ queryFilename score <- liftM BS.lines . BS.readFile $ scoreFilename withFile pastedFilename WriteMode $ \hout -> mapM_ (BS.hPutStrLn hout) $ map pasteLine $ mergeScore query score where base = BS.dropWhile isSpace . BS.drop 1 unscored q0 = BS.concat [ base q0, BS.pack "\tn/a" ] scored q0 sc0 = BS.concat [ base . BS.dropWhile (/= '#') $ q0, BS.singleton '\t', sc0 ] pasteLine (q0, sc0) | BS.null sc0 = unscored q0 | otherwise = scored q0 sc0 mergeScore :: [BS.ByteString] -> [BS.ByteString] -> [(BS.ByteString, BS.ByteString)] mergeScore query score = unfoldr merge (query, score) where merge ([], []) = Nothing merge ([], rest) = error $ "pasteScore: remaining scores: " ++ show rest merge ((q0:qrest), []) | isComment q0 = Just ((q0, BS.empty), (qrest, [])) | otherwise = error $ "Ran out of scores for " ++ show q0 merge ((q0:qrest), scs@(sc0:screst)) | isComment q0 = Just ((q0, BS.empty), (qrest, scs)) | otherwise = Just ((q0, sc0), (qrest, screst)) isComment = maybe blankQuery ((== '#') . fst) . BS.uncons blankQuery = error "Blank example line" data TestData a = TestData { truePos, falsePos, trueNeg, falseNeg :: !a } deriving (Show) type TestCount = TestData Int type TestScore = TestData (U.Vector Double) instance Monoid a => Monoid (TestData a) where mempty = TestData mempty mempty mempty mempty (TestData tp1 fp1 tn1 fn1) `mappend` (TestData tp2 fp2 tn2 fn2) = TestData (tp1 `mappend` tp2) (fp1 `mappend` fp2) (tn1 `mappend` tn2) (fn1 `mappend` fn2) mconcat tds = TestData { truePos = mconcat $ map truePos tds , falsePos = mconcat $ map falsePos tds , trueNeg = mconcat $ map trueNeg tds , falseNeg = mconcat $ map falseNeg tds } negatives :: TestCount -> Int negatives tc = trueNeg tc + falsePos tc positives :: TestCount -> Int positives tc = truePos tc + falseNeg tc calledPositives :: TestCount -> Int calledPositives tc = truePos tc + falsePos tc calledNegatives :: TestCount -> Int calledNegatives tc = trueNeg tc + falseNeg tc specificity :: TestCount -> Double specificity tc = (fromIntegral . trueNeg $ tc) / (fromIntegral . negatives $ tc) sensitivity :: TestCount -> Double sensitivity tc = (fromIntegral . truePos $ tc) / (fromIntegral . positives $ tc) displayTestCount :: TestCount -> String displayTestCount tc = intercalate "\t" [ show . truePos $ tc, show . falsePos $ tc , show . trueNeg $ tc, show . falseNeg $ tc , showf . specificity $ tc , showf . sensitivity $ tc ] where showf = flip (showFFloat (Just 3)) "" checkTest :: FilePath -> FilePath -> IO TestCount checkTest examples score = do ex <- liftM BS.lines . BS.readFile $ examples sc <- liftM BS.lines . BS.readFile $ score let ls = filter scored $ mergeScore ex sc return $! foldl' addScore (TestData 0 0 0 0) ls where addScore cts0 (exline, scline) = let exval = readSignedDouble . BS.takeWhile (not . isSpace) $ exline scval = readSignedDouble . BS.takeWhile (not . isSpace) $ scline in case (exval > 0, scval > 0) of (True, True ) -> cts0 { truePos = truePos cts0 + 1 } (False, True ) -> cts0 { falsePos = falsePos cts0 + 1 } (False, False) -> cts0 { trueNeg = trueNeg cts0 + 1 } (True, False) -> cts0 { falseNeg = falseNeg cts0 + 1 } readSignedDouble :: BS.ByteString -> Double readSignedDouble xstr = case BS.uncons xstr of Just ('+', pxstr) -> readDouble pxstr _ -> readDouble xstr readDouble xstr = case reads . BS.unpack $ xstr of [(x, "")] -> x _ -> error $ "readDouble: malformed Double " ++ show xstr scored (_q0, sc0) = not . BS.null $ sc0 partitionTest :: FilePath -> FilePath -> IO TestScore partitionTest examples score = do ex <- liftM BS.lines . BS.readFile $ examples sc <- liftM BS.lines . BS.readFile $ score let ls = filter scored $ mergeScore ex sc return $! foldl' addScore (TestData U.empty U.empty U.empty U.empty) ls where addScore tsc0 (exline, scline) = let exval = readSignedDouble . BS.takeWhile (not . isSpace) $ exline scval = readSignedDouble . BS.takeWhile (not . isSpace) $ scline in case (exval > 0, scval > 0) of (True, True ) -> tsc0 { truePos = truePos tsc0 `U.snoc` scval } (False, True ) -> tsc0 { falsePos = falsePos tsc0 `U.snoc` scval } (False, False) -> tsc0 { trueNeg = trueNeg tsc0 `U.snoc` scval } (True, False) -> tsc0 { falseNeg = falseNeg tsc0 `U.snoc` scval } readSignedDouble :: BS.ByteString -> Double readSignedDouble xstr = case BS.uncons xstr of Just ('+', pxstr) -> readDouble pxstr _ -> readDouble xstr readDouble xstr = case reads . BS.unpack $ xstr of [(x, "")] -> x _ -> error $ "readDouble: malformed Double " ++ show xstr scored (_q0, sc0) = not . BS.null $ sc0 countPartition :: TestScore -> TestCount countPartition tsc0 = TestData { truePos = U.length . truePos $ tsc0 , falsePos = U.length . falsePos $ tsc0 , trueNeg = U.length . trueNeg $ tsc0 , falseNeg = U.length . falseNeg $ tsc0 }
null
https://raw.githubusercontent.com/ingolia-lab/RiboSeq/a14390cd95528910a258434c7b84c787f5e1d119/src/Bio/RiboSeq/SVMLight.hs
haskell
# LANGUAGE BangPatterns # -z -v -c -w -j -b -i -p -t and -d, -g, -s, -r, -u -q -n -m -e -h -f -# -v runSVMClassifyWithScore :: RunSVMClassify -> IO ExitCode runSVMClassifyWithScore classify = bracket mkScoreTmp rmScoreTmp $ \scorename -> let classifyTmp = classify { decisionsOut = scorename } in runSVMClassify classifyTmp >>= \ec -> do hClose h >> return name
module Bio.RiboSeq.SVMLight where import Control.Monad import qualified Data.ByteString.Char8 as BS import Data.Char (isSpace) import Data.List import Data.Monoid import Numeric import System.Exit import System.FilePath import System.IO (IOMode(..), withFile) import System.Process import qualified Data.Vector.Unboxed as U verbose :: Bool verbose = True myRawSystem :: String -> [String] -> IO ExitCode myRawSystem execu arglist = do when verbose $ putStrLn (unwords $ execu : arglist) rawSystem execu arglist targetYes, targetNo, targetQuery :: BS.ByteString targetYes = BS.pack "+1" targetNo = BS.pack "-1" targetQuery = BS.pack "0" exampleLine :: BS.ByteString -> [(Int, Double)] -> Maybe BS.ByteString -> BS.ByteString exampleLine target features minfo = BS.unwords $ target : (BS.pack featuresStr) : infobs where infobs = maybe [] (\info -> [ BS.singleton '#', info ]) minfo featuresStr = foldr ($) "" . intersperse (' ' :) . map showsFeature $ features showsFeature (fidx, fval) = shows fidx . (':' :) . showEFloat (Just 4) fval data SVMMode = SVMClassification | SVMRegression | SVMPreference deriving (Show, Eq, Ord, Enum) modeOpts :: SVMMode -> [String] modeOpts SVMClassification = [ "-z", "c" ] modeOpts SVMRegression = [ "-z", "r" ] modeOpts SVMPreference = [ "-z", "p" ] data SVMKernel = SVMLinear | SVMPolynomial { degree :: Maybe Int, scaling :: Maybe Double, baseline :: Maybe Double } | SVMRadial { gamma :: Maybe Double } | SVMSigmoid { scaling :: Maybe Double, baseline :: Maybe Double } deriving (Show) kernelOpts :: SVMKernel -> [String] kernelOpts SVMLinear = [ "-t", "0" ] kernelOpts (SVMPolynomial md ms mc) = concat [ [ "-t", "1" ] , maybe [] (\d -> [ "-d", show d ]) md , maybe [] (\s -> [ "-s", show s ]) ms , maybe [] (\c -> [ "-c", show c ]) mc ] kernelOpts (SVMRadial mg) = [ "-t", "2" ] ++ maybe [] (\g -> [ "-g", show g ]) mg kernelOpts (SVMSigmoid ms mc) = concat [ [ "-t", "3" ] , maybe [] (\s -> [ "-s", show s ]) ms , maybe [] (\c -> [ "-c", show c ]) mc ] data RunSVMLearn = RunSVMLearn { learnBinary :: FilePath , examplesIn :: FilePath , modelOut :: FilePath } deriving (Show) defaultLearn :: RunSVMLearn defaultLearn = RunSVMLearn { learnBinary = error "SVMLight: no svm_learn binary specified" , examplesIn = error "SVMLight: no examples input file specified" , modelOut = error "SVMLight: no model output file specified" , mode = Nothing, learnVerbose = Nothing, softMargin = Nothing, width = Nothing , positiveWeight = Nothing, biasedPlane = Nothing, removeRetrain = Nothing , positiveTrans = Nothing , kernel = Nothing , maxQPSize = Nothing, maxNewVar = Nothing, kernelCache = Nothing, termEps = Nothing , shrinkIter = Nothing, checkFinalOpt = Nothing, maxIter = Nothing } learnOpts :: RunSVMLearn -> [String] learnOpts svmLearn = concat [ zOpts, vOpts, cOpts, wOpts, jOpts, bOpts, iOpts , pOpts , maybe [] kernelOpts . kernel $ svmLearn , qOpts, nOpts, mOpts, eOpts, hOpts, fOpts, poundOpts ] where zOpts = maybe [] modeOpts . mode $ svmLearn vOpts = maybe [] (\v -> [ "-v", show v ]) . learnVerbose $ svmLearn cOpts = maybe [] (\c -> [ "-c", show c ]) . softMargin $ svmLearn wOpts = maybe [] (\w -> [ "-w", show w ]) . width $ svmLearn jOpts = maybe [] (\j -> [ "-j", show j ]) . positiveWeight $ svmLearn bOpts = maybe [] (\b -> [ "-b", if b then "1" else "0" ]) . biasedPlane $ svmLearn iOpts = maybe [] (\i -> [ "-i", if i then "1" else "0" ]) . removeRetrain $ svmLearn pOpts = maybe [] (\p -> [ "-p", show p ]) . positiveTrans $ svmLearn qOpts = maybe [] (\q -> [ "-q", show q ]) . maxQPSize $ svmLearn nOpts = maybe [] (\n -> [ "-n", show n ]) . maxNewVar $ svmLearn mOpts = maybe [] (\m -> [ "-m", show m ]) . kernelCache $ svmLearn eOpts = maybe [] (\e -> [ "-e", show e ]) . termEps $ svmLearn hOpts = maybe [] (\h -> [ "-h", show h ]) . shrinkIter $ svmLearn fOpts = maybe [] (\f -> [ "-f", if f then "1" else "0" ]) . checkFinalOpt $ svmLearn poundOpts = maybe [] (\p -> [ "-#", show p ]) . maxIter $ svmLearn runSVMLearn :: RunSVMLearn -> IO ExitCode runSVMLearn svmLearn = myRawSystem (learnBinary svmLearn) $ learnOpts svmLearn ++ [ examplesIn svmLearn, modelOut svmLearn ] data RunSVMClassify = RunSVMClassify { classifyBinary :: FilePath , queriesIn :: FilePath , modelIn :: FilePath , decisionsOut :: FilePath } deriving (Show) defaultClassify :: RunSVMClassify defaultClassify = RunSVMClassify { classifyBinary = error "SVMLight: no svm_classify binary specified" , queriesIn = error "SVMLight: no examples input file specified" , modelIn = error "SVMLight: no model input file specified" , decisionsOut = error "SVMLight: No decisions output file specified" , classifyVerbose = Nothing } classifyOpts :: RunSVMClassify -> [String] classifyOpts svmLearn = concat [ vOpts ] where vOpts = maybe [] (\v -> [ "-v", show v ]) . classifyVerbose $ svmLearn runSVMClassify :: RunSVMClassify -> IO ExitCode runSVMClassify svmClassify = myRawSystem (classifyBinary svmClassify) $ classifyOpts svmClassify ++ [ queriesIn svmClassify, modelIn svmClassify, decisionsOut svmClassify ] when ( ec = = ExitSuccess ) $ pasteScore ( queriesIn classify ) ( decisionsOut classify ) return ec where mkScoreTmp = ( decisionsOut classify + + " XXXXXX " ) > > = \(name , h ) - > rmScoreTmp scorename = doesFileExist > > = flip when ( removeFile ) pasteScore :: FilePath -> FilePath -> FilePath -> IO () pasteScore queryFilename scoreFilename pastedFilename = do query <- liftM BS.lines . BS.readFile $ queryFilename score <- liftM BS.lines . BS.readFile $ scoreFilename withFile pastedFilename WriteMode $ \hout -> mapM_ (BS.hPutStrLn hout) $ map pasteLine $ mergeScore query score where base = BS.dropWhile isSpace . BS.drop 1 unscored q0 = BS.concat [ base q0, BS.pack "\tn/a" ] scored q0 sc0 = BS.concat [ base . BS.dropWhile (/= '#') $ q0, BS.singleton '\t', sc0 ] pasteLine (q0, sc0) | BS.null sc0 = unscored q0 | otherwise = scored q0 sc0 mergeScore :: [BS.ByteString] -> [BS.ByteString] -> [(BS.ByteString, BS.ByteString)] mergeScore query score = unfoldr merge (query, score) where merge ([], []) = Nothing merge ([], rest) = error $ "pasteScore: remaining scores: " ++ show rest merge ((q0:qrest), []) | isComment q0 = Just ((q0, BS.empty), (qrest, [])) | otherwise = error $ "Ran out of scores for " ++ show q0 merge ((q0:qrest), scs@(sc0:screst)) | isComment q0 = Just ((q0, BS.empty), (qrest, scs)) | otherwise = Just ((q0, sc0), (qrest, screst)) isComment = maybe blankQuery ((== '#') . fst) . BS.uncons blankQuery = error "Blank example line" data TestData a = TestData { truePos, falsePos, trueNeg, falseNeg :: !a } deriving (Show) type TestCount = TestData Int type TestScore = TestData (U.Vector Double) instance Monoid a => Monoid (TestData a) where mempty = TestData mempty mempty mempty mempty (TestData tp1 fp1 tn1 fn1) `mappend` (TestData tp2 fp2 tn2 fn2) = TestData (tp1 `mappend` tp2) (fp1 `mappend` fp2) (tn1 `mappend` tn2) (fn1 `mappend` fn2) mconcat tds = TestData { truePos = mconcat $ map truePos tds , falsePos = mconcat $ map falsePos tds , trueNeg = mconcat $ map trueNeg tds , falseNeg = mconcat $ map falseNeg tds } negatives :: TestCount -> Int negatives tc = trueNeg tc + falsePos tc positives :: TestCount -> Int positives tc = truePos tc + falseNeg tc calledPositives :: TestCount -> Int calledPositives tc = truePos tc + falsePos tc calledNegatives :: TestCount -> Int calledNegatives tc = trueNeg tc + falseNeg tc specificity :: TestCount -> Double specificity tc = (fromIntegral . trueNeg $ tc) / (fromIntegral . negatives $ tc) sensitivity :: TestCount -> Double sensitivity tc = (fromIntegral . truePos $ tc) / (fromIntegral . positives $ tc) displayTestCount :: TestCount -> String displayTestCount tc = intercalate "\t" [ show . truePos $ tc, show . falsePos $ tc , show . trueNeg $ tc, show . falseNeg $ tc , showf . specificity $ tc , showf . sensitivity $ tc ] where showf = flip (showFFloat (Just 3)) "" checkTest :: FilePath -> FilePath -> IO TestCount checkTest examples score = do ex <- liftM BS.lines . BS.readFile $ examples sc <- liftM BS.lines . BS.readFile $ score let ls = filter scored $ mergeScore ex sc return $! foldl' addScore (TestData 0 0 0 0) ls where addScore cts0 (exline, scline) = let exval = readSignedDouble . BS.takeWhile (not . isSpace) $ exline scval = readSignedDouble . BS.takeWhile (not . isSpace) $ scline in case (exval > 0, scval > 0) of (True, True ) -> cts0 { truePos = truePos cts0 + 1 } (False, True ) -> cts0 { falsePos = falsePos cts0 + 1 } (False, False) -> cts0 { trueNeg = trueNeg cts0 + 1 } (True, False) -> cts0 { falseNeg = falseNeg cts0 + 1 } readSignedDouble :: BS.ByteString -> Double readSignedDouble xstr = case BS.uncons xstr of Just ('+', pxstr) -> readDouble pxstr _ -> readDouble xstr readDouble xstr = case reads . BS.unpack $ xstr of [(x, "")] -> x _ -> error $ "readDouble: malformed Double " ++ show xstr scored (_q0, sc0) = not . BS.null $ sc0 partitionTest :: FilePath -> FilePath -> IO TestScore partitionTest examples score = do ex <- liftM BS.lines . BS.readFile $ examples sc <- liftM BS.lines . BS.readFile $ score let ls = filter scored $ mergeScore ex sc return $! foldl' addScore (TestData U.empty U.empty U.empty U.empty) ls where addScore tsc0 (exline, scline) = let exval = readSignedDouble . BS.takeWhile (not . isSpace) $ exline scval = readSignedDouble . BS.takeWhile (not . isSpace) $ scline in case (exval > 0, scval > 0) of (True, True ) -> tsc0 { truePos = truePos tsc0 `U.snoc` scval } (False, True ) -> tsc0 { falsePos = falsePos tsc0 `U.snoc` scval } (False, False) -> tsc0 { trueNeg = trueNeg tsc0 `U.snoc` scval } (True, False) -> tsc0 { falseNeg = falseNeg tsc0 `U.snoc` scval } readSignedDouble :: BS.ByteString -> Double readSignedDouble xstr = case BS.uncons xstr of Just ('+', pxstr) -> readDouble pxstr _ -> readDouble xstr readDouble xstr = case reads . BS.unpack $ xstr of [(x, "")] -> x _ -> error $ "readDouble: malformed Double " ++ show xstr scored (_q0, sc0) = not . BS.null $ sc0 countPartition :: TestScore -> TestCount countPartition tsc0 = TestData { truePos = U.length . truePos $ tsc0 , falsePos = U.length . falsePos $ tsc0 , trueNeg = U.length . trueNeg $ tsc0 , falseNeg = U.length . falseNeg $ tsc0 }
b51870608c5ba0601a07cb02728a8df4123d8080be19261e782c2a0de95b583f
TorXakis/TorXakis
Boute.hs
TorXakis - Model Based Testing Copyright ( c ) 2015 - 2017 TNO and Radboud University See LICENSE at root directory of this repository . TorXakis - Model Based Testing Copyright (c) 2015-2017 TNO and Radboud University See LICENSE at root directory of this repository. -} ----------------------------------------------------------------------------- -- | Module : Boute Division and Modulo Copyright : ( c ) TNO and Radboud University License : BSD3 ( see the file license.txt ) -- Maintainer : ( Embedded Systems Innovation by ) -- Stability : experimental -- Portability : portable -- Define div and mod according to 's Euclidean definition , that is , -- so as to satisfy the formula -- -- @ -- (for all ((m Int) (n Int)) -- (=> (distinct n 0) -- (let ((q (div m n)) (r (mod m n))) -- (and (= m (+ (* n q) r)) ( < = 0 r ( - ( abs n ) 1 ) ) ) ) ) ) -- @ -- Boute , ( April 1992 ) . The definition of the functions div and mod . ACM Transactions on Programming Languages and Systems ( TOPLAS ) ACM Press . 14 ( 2 ): 127 - 144 . doi:10.1145/128861.128862 . ----------------------------------------------------------------------------- module Boute ( Boute.divMod , Boute.div , Boute.mod ) where | operator divMod on the provided integer values . -- -- @ -- (for all ((m Int) (n Int)) -- (=> (distinct n 0) -- (let ((q (div m n)) (r (mod m n))) -- (and (= m (+ (* n q) r)) ( < = 0 r ( - ( abs n ) 1 ) ) ) ) ) ) -- @ divMod :: Integer -> Integer -> (Integer, Integer) divMod _ 0 = error "divMod: division by zero" divMod m n = if n > 0 || pm == 0 then pdm else (pd+1, pm-n) where pdm@(pd, pm) = Prelude.divMod m n -- | operator divide on the provided integer values. div :: Integer -> Integer -> Integer div m = fst . Boute.divMod m -- | operator modulo on the provided integer values. -- -- @ -- (for all ((m Int) (n Int)) -- (=> (distinct n 0) ( < = 0 ( mod m n ) ( - ( abs n ) 1 ) ) ) ) -- @ mod :: Integer -> Integer -> Integer mod m = snd . Boute.divMod m
null
https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/sys/valexpr/src/Boute.hs
haskell
--------------------------------------------------------------------------- | Stability : experimental Portability : portable so as to satisfy the formula @ (for all ((m Int) (n Int)) (=> (distinct n 0) (let ((q (div m n)) (r (mod m n))) (and (= m (+ (* n q) r)) @ --------------------------------------------------------------------------- @ (for all ((m Int) (n Int)) (=> (distinct n 0) (let ((q (div m n)) (r (mod m n))) (and (= m (+ (* n q) r)) @ | operator divide on the provided integer values. | operator modulo on the provided integer values. @ (for all ((m Int) (n Int)) (=> (distinct n 0) @
TorXakis - Model Based Testing Copyright ( c ) 2015 - 2017 TNO and Radboud University See LICENSE at root directory of this repository . TorXakis - Model Based Testing Copyright (c) 2015-2017 TNO and Radboud University See LICENSE at root directory of this repository. -} Module : Boute Division and Modulo Copyright : ( c ) TNO and Radboud University License : BSD3 ( see the file license.txt ) Maintainer : ( Embedded Systems Innovation by ) Define div and mod according to 's Euclidean definition , that is , ( < = 0 r ( - ( abs n ) 1 ) ) ) ) ) ) Boute , ( April 1992 ) . The definition of the functions div and mod . ACM Transactions on Programming Languages and Systems ( TOPLAS ) ACM Press . 14 ( 2 ): 127 - 144 . doi:10.1145/128861.128862 . module Boute ( Boute.divMod , Boute.div , Boute.mod ) where | operator divMod on the provided integer values . ( < = 0 r ( - ( abs n ) 1 ) ) ) ) ) ) divMod :: Integer -> Integer -> (Integer, Integer) divMod _ 0 = error "divMod: division by zero" divMod m n = if n > 0 || pm == 0 then pdm else (pd+1, pm-n) where pdm@(pd, pm) = Prelude.divMod m n div :: Integer -> Integer -> Integer div m = fst . Boute.divMod m ( < = 0 ( mod m n ) ( - ( abs n ) 1 ) ) ) ) mod :: Integer -> Integer -> Integer mod m = snd . Boute.divMod m
710cb14ed6a64a4954433ac757c0719e2ab7fe818bc50b09861d2f35537e02a9
Simre1/haskell-game
Strategy.hs
# OPTIONS_HADDOCK not - home # module Polysemy.Internal.Strategy where import Polysemy.Internal import Polysemy.Internal.Combinators import Polysemy.Internal.Tactics (Inspector(..)) data Strategy m f n z a where GetInitialState :: Strategy m f n z (f ()) HoistInterpretation :: (a -> n b) -> Strategy m f n z (f a -> m (f b)) GetInspector :: Strategy m f n z (Inspector f) ------------------------------------------------------------------------------ -- | 'Strategic' is an environment in which you're capable of explicitly -- threading higher-order effect states to the final monad. This is a variant of @Tactics@ ( see ' Polysemy . Tactical ' ) , and usage -- is extremely similar. -- @since 1.2.0.0 type Strategic m n a = forall f. Functor f => Sem (WithStrategy m f n) (m (f a)) ------------------------------------------------------------------------------ | @since 1.2.0.0 type WithStrategy m f n = '[Strategy m f n] ------------------------------------------------------------------------------ | Internal function to process Strategies in terms of ' Polysemy . Final.withWeavingToFinal ' . -- @since 1.2.0.0 runStrategy :: Functor f => Sem '[Strategy m f n] a -> f () -> (forall x. f (n x) -> m (f x)) -> (forall x. f x -> Maybe x) -> a runStrategy sem = \s wv ins -> run $ interpret (\case GetInitialState -> pure s HoistInterpretation f -> pure $ \fa -> wv (f <$> fa) GetInspector -> pure (Inspector ins) ) sem # INLINE runStrategy # ------------------------------------------------------------------------------ -- | Get a natural transformation capable of potentially inspecting values -- inside of @f@. Binding the result of 'getInspectorS' produces a function that -- can sometimes peek inside values returned by 'bindS'. -- -- This is often useful for running callback functions that are not managed by -- polysemy code. -- -- See also 'Polysemy.getInspectorT' -- @since 1.2.0.0 getInspectorS :: forall m f n. Sem (WithStrategy m f n) (Inspector f) getInspectorS = send (GetInspector @m @f @n) # INLINE getInspectorS # ------------------------------------------------------------------------------ -- | Get the stateful environment of the world at the moment the -- @Strategy@ is to be run. -- -- Prefer 'pureS', 'liftS', 'runS', or 'bindS' instead of using this function -- directly. -- @since 1.2.0.0 getInitialStateS :: forall m f n. Sem (WithStrategy m f n) (f ()) getInitialStateS = send (GetInitialState @m @f @n) # INLINE getInitialStateS # ------------------------------------------------------------------------------ -- | Embed a value into 'Strategic'. -- @since 1.2.0.0 pureS :: Applicative m => a -> Strategic m n a pureS a = pure . (a <$) <$> getInitialStateS # INLINE pureS # ------------------------------------------------------------------------------ -- | Lifts an action of the final monad into 'Strategic'. -- -- /Note/: you don't need to use this function if you already have a monadic -- action with the functorial state threaded into it, by the use of -- 'runS' or 'bindS'. -- In these cases, you need only use 'pure' to embed the action into the -- 'Strategic' environment. -- @since 1.2.0.0 liftS :: Functor m => m a -> Strategic m n a liftS m = do s <- getInitialStateS pure $ fmap (<$ s) m # INLINE liftS # ------------------------------------------------------------------------------ -- | Lifts a monadic action into the stateful environment, in terms -- of the final monad. -- The stateful environment will be the same as the one that the @Strategy@ -- is initially run in. -- -- Use 'bindS' if you'd prefer to explicitly manage your stateful environment. -- @since 1.2.0.0 runS :: n a -> Sem (WithStrategy m f n) (m (f a)) runS na = bindS (const na) <*> getInitialStateS # INLINE runS # ------------------------------------------------------------------------------ -- | Embed a kleisli action into the stateful environment, in terms of the final monad . You can use ' bindS ' to get an effect parameter of the form @a - > n b@ -- into something that can be used after calling 'runS' on an effect parameter -- @n a@. -- @since 1.2.0.0 bindS :: (a -> n b) -> Sem (WithStrategy m f n) (f a -> m (f b)) bindS = send . HoistInterpretation # INLINE bindS #
null
https://raw.githubusercontent.com/Simre1/haskell-game/272a0674157aedc7b0e0ee00da8d3a464903dc67/polysemy/src/Polysemy/Internal/Strategy.hs
haskell
---------------------------------------------------------------------------- | 'Strategic' is an environment in which you're capable of explicitly threading higher-order effect states to the final monad. is extremely similar. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- | Get a natural transformation capable of potentially inspecting values inside of @f@. Binding the result of 'getInspectorS' produces a function that can sometimes peek inside values returned by 'bindS'. This is often useful for running callback functions that are not managed by polysemy code. See also 'Polysemy.getInspectorT' ---------------------------------------------------------------------------- | Get the stateful environment of the world at the moment the @Strategy@ is to be run. Prefer 'pureS', 'liftS', 'runS', or 'bindS' instead of using this function directly. ---------------------------------------------------------------------------- | Embed a value into 'Strategic'. ---------------------------------------------------------------------------- | Lifts an action of the final monad into 'Strategic'. /Note/: you don't need to use this function if you already have a monadic action with the functorial state threaded into it, by the use of 'runS' or 'bindS'. In these cases, you need only use 'pure' to embed the action into the 'Strategic' environment. ---------------------------------------------------------------------------- | Lifts a monadic action into the stateful environment, in terms of the final monad. The stateful environment will be the same as the one that the @Strategy@ is initially run in. Use 'bindS' if you'd prefer to explicitly manage your stateful environment. ---------------------------------------------------------------------------- | Embed a kleisli action into the stateful environment, in terms of the final into something that can be used after calling 'runS' on an effect parameter @n a@.
# OPTIONS_HADDOCK not - home # module Polysemy.Internal.Strategy where import Polysemy.Internal import Polysemy.Internal.Combinators import Polysemy.Internal.Tactics (Inspector(..)) data Strategy m f n z a where GetInitialState :: Strategy m f n z (f ()) HoistInterpretation :: (a -> n b) -> Strategy m f n z (f a -> m (f b)) GetInspector :: Strategy m f n z (Inspector f) This is a variant of @Tactics@ ( see ' Polysemy . Tactical ' ) , and usage @since 1.2.0.0 type Strategic m n a = forall f. Functor f => Sem (WithStrategy m f n) (m (f a)) | @since 1.2.0.0 type WithStrategy m f n = '[Strategy m f n] | Internal function to process Strategies in terms of ' Polysemy . Final.withWeavingToFinal ' . @since 1.2.0.0 runStrategy :: Functor f => Sem '[Strategy m f n] a -> f () -> (forall x. f (n x) -> m (f x)) -> (forall x. f x -> Maybe x) -> a runStrategy sem = \s wv ins -> run $ interpret (\case GetInitialState -> pure s HoistInterpretation f -> pure $ \fa -> wv (f <$> fa) GetInspector -> pure (Inspector ins) ) sem # INLINE runStrategy # @since 1.2.0.0 getInspectorS :: forall m f n. Sem (WithStrategy m f n) (Inspector f) getInspectorS = send (GetInspector @m @f @n) # INLINE getInspectorS # @since 1.2.0.0 getInitialStateS :: forall m f n. Sem (WithStrategy m f n) (f ()) getInitialStateS = send (GetInitialState @m @f @n) # INLINE getInitialStateS # @since 1.2.0.0 pureS :: Applicative m => a -> Strategic m n a pureS a = pure . (a <$) <$> getInitialStateS # INLINE pureS # @since 1.2.0.0 liftS :: Functor m => m a -> Strategic m n a liftS m = do s <- getInitialStateS pure $ fmap (<$ s) m # INLINE liftS # @since 1.2.0.0 runS :: n a -> Sem (WithStrategy m f n) (m (f a)) runS na = bindS (const na) <*> getInitialStateS # INLINE runS # monad . You can use ' bindS ' to get an effect parameter of the form @a - > n b@ @since 1.2.0.0 bindS :: (a -> n b) -> Sem (WithStrategy m f n) (f a -> m (f b)) bindS = send . HoistInterpretation # INLINE bindS #
25cac150efa07af92d1376399769cd9334d217111940a63a413ddd873539fc11
brownplt/Resugarer
lang-min-macros-cps.rkt
#lang racket (require redex) (require "resugar-redex.rkt") (require "lang-min.rkt") (define-macro Let [(Let x e b) (apply (lambda x b) e)]) (define-macro CpsM [(CpsM ($λ x y)) (lambda x (lambda k_ (! CpsT y k_)))] [(CpsM x) (begin x)]) (define-macro CpsT [(CpsT ($apply x y) k) (CpsT x (! lambda f_ (CpsT y (lambda e_ (apply f_ e_ k)))))] [(CpsT x k_) (Let k k_ (apply k (CpsM x)))]) (define-macro Cps [(Cps x) (Let halt (lambda h_ h_) (CpsT x halt))]) (define-macro CpsM* [(CpsM* ($λ v e)) (lambda v (lambda k (CpsC* e k)))] [(CpsM* x) x]) (define-macro CpsC* [(CpsC* ($λ v e) c) (apply c (CpsM* ($λ v e)))] [(CpsC* ($apply f e) c) (CpsK* f (lambda f_ (CpsK* e (lambda e_ (apply f_ e_ c)))))] [(CpsC* x c) (apply c (CpsM* x))]) (define-macro CpsK* [(CpsK* ($λ v e) k) (apply k (CpsM* ($λ e)))] [(CpsK* ($apply f e) k) (CpsK* f (lambda f_ (CpsK* e (lambda e_ (apply f_ e_ k)))))] [(CpsK* x c) (apply c (CpsM* x))]) (define-macro Fischer [(Fischer ($λ x y)) (lambda k (apply k (! lambda x (! lambda k (! apply (Fischer y) (! lambda m (apply k m)))))))] [(Fischer ($apply x y)) (lambda k (! apply (Fischer x) (! lambda m (! apply (Fischer y) (! lambda n (apply (apply m n) (lambda a (apply k a))))))))] [(Fischer x) (lambda k (! apply k x))]) (test-eval (Cps ($apply ($λ x (+ x 1)) 3))) (test-eval (Cps ($apply ($apply ($λ f ($λ x ($apply f ($apply f x)))) ($λ x (+ x 1))) (+ 1 2)))) ( test - eval ( CpsT ( $ apply ( $ apply ( $ λ f ( $ λ x ( $ apply f ( $ apply f x ) ) ) ) ( $ λ x ( + x 1 ) ) ) ( + 1 2 ) ) ( lambda h h ) ) ) ( test - eval ( Cps ( $ apply ( $ λ f ( $ apply f 1 ) ) ( $ λ x ( + x 1 ) ) ) ) ) ( test - eval ( CpsK * ( $ apply ( $ λ f ( $ apply f 1 ) ) ( $ λ x ( + x 1 ) ) ) ( lambda h h ) ) ) ( test - eval ( Lets [ ^ [ ^ x 1 ] [ ^ y ( + 1 2 ) ] ] ( + x y ) ) ) ( test - eval ( apply ( Fischer ( $ apply ( $ λ x ( + x 1 ) ) 3 ) ) ( lambda h h ) ) ) ( test - eval ( apply ( Fischer ( $ apply ( $ apply ( $ λ f ( $ λ x ( $ apply f ( $ apply f x ) ) ) ) ( $ λ x ( + x 1 ) ) ) ( + 1 2 ) ) ) ( lambda h h ) ) )
null
https://raw.githubusercontent.com/brownplt/Resugarer/1353b4309c101f0f1ac2df2cba7f3cba1f0a3a37/prototype/lang-min-macros-cps.rkt
racket
#lang racket (require redex) (require "resugar-redex.rkt") (require "lang-min.rkt") (define-macro Let [(Let x e b) (apply (lambda x b) e)]) (define-macro CpsM [(CpsM ($λ x y)) (lambda x (lambda k_ (! CpsT y k_)))] [(CpsM x) (begin x)]) (define-macro CpsT [(CpsT ($apply x y) k) (CpsT x (! lambda f_ (CpsT y (lambda e_ (apply f_ e_ k)))))] [(CpsT x k_) (Let k k_ (apply k (CpsM x)))]) (define-macro Cps [(Cps x) (Let halt (lambda h_ h_) (CpsT x halt))]) (define-macro CpsM* [(CpsM* ($λ v e)) (lambda v (lambda k (CpsC* e k)))] [(CpsM* x) x]) (define-macro CpsC* [(CpsC* ($λ v e) c) (apply c (CpsM* ($λ v e)))] [(CpsC* ($apply f e) c) (CpsK* f (lambda f_ (CpsK* e (lambda e_ (apply f_ e_ c)))))] [(CpsC* x c) (apply c (CpsM* x))]) (define-macro CpsK* [(CpsK* ($λ v e) k) (apply k (CpsM* ($λ e)))] [(CpsK* ($apply f e) k) (CpsK* f (lambda f_ (CpsK* e (lambda e_ (apply f_ e_ k)))))] [(CpsK* x c) (apply c (CpsM* x))]) (define-macro Fischer [(Fischer ($λ x y)) (lambda k (apply k (! lambda x (! lambda k (! apply (Fischer y) (! lambda m (apply k m)))))))] [(Fischer ($apply x y)) (lambda k (! apply (Fischer x) (! lambda m (! apply (Fischer y) (! lambda n (apply (apply m n) (lambda a (apply k a))))))))] [(Fischer x) (lambda k (! apply k x))]) (test-eval (Cps ($apply ($λ x (+ x 1)) 3))) (test-eval (Cps ($apply ($apply ($λ f ($λ x ($apply f ($apply f x)))) ($λ x (+ x 1))) (+ 1 2)))) ( test - eval ( CpsT ( $ apply ( $ apply ( $ λ f ( $ λ x ( $ apply f ( $ apply f x ) ) ) ) ( $ λ x ( + x 1 ) ) ) ( + 1 2 ) ) ( lambda h h ) ) ) ( test - eval ( Cps ( $ apply ( $ λ f ( $ apply f 1 ) ) ( $ λ x ( + x 1 ) ) ) ) ) ( test - eval ( CpsK * ( $ apply ( $ λ f ( $ apply f 1 ) ) ( $ λ x ( + x 1 ) ) ) ( lambda h h ) ) ) ( test - eval ( Lets [ ^ [ ^ x 1 ] [ ^ y ( + 1 2 ) ] ] ( + x y ) ) ) ( test - eval ( apply ( Fischer ( $ apply ( $ λ x ( + x 1 ) ) 3 ) ) ( lambda h h ) ) ) ( test - eval ( apply ( Fischer ( $ apply ( $ apply ( $ λ f ( $ λ x ( $ apply f ( $ apply f x ) ) ) ) ( $ λ x ( + x 1 ) ) ) ( + 1 2 ) ) ) ( lambda h h ) ) )
86b01500adec6e6d3b36c29b191bf5deab59d89fc440ba3c407115a4f0de2cb1
yoriyuki/Camomile
test_uCol.ml
$ I d : test - uCol.ml , v 1.13 2006/08/13 21:23:08 yori Exp $ (* Copyright 2002,2003,2004,2005,2006 Yamagata Yoriyuki *) open CamomileLibraryTest.Camomile open UPervasives open Blender open Printf open TestUColJapanese let rec lex_compare_aux i t1 t2 = if i >= UText.length t1 then if i >= UText.length t2 then 0 else ~-1 else if i >= UText.length t2 then 1 else match Pervasives.compare (UText.get t1 i) (UText.get t2 i) with 0 -> lex_compare_aux (i + 1) t1 t2 | sgn -> sgn let lex_compare t1 t2 = lex_compare_aux 0 t1 t2 let blank = Str.regexp "[ \t]+" let line_pat = Str.regexp "\\([^;]+\\);.*$" let comment_pat = Str.regexp "^#.*" let uchar_of_code code = uchar_of_int (int_of_string ("0x"^code)) let us_of_cs cs = List.map uchar_of_code cs let parse_line line = if Str.string_match line_pat line 0 then let s = Str.matched_group 1 line in let cs = Str.split blank s in let us = us_of_cs cs in UText.init (List.length us) (fun i -> List.nth us i) else invalid_arg (sprintf "Malformed_line %s:" line) let print_char u = sprintf "%04X " (int_of_uchar u) let print_text t = let buf = Buffer.create (5 * UText.length t) in UText.iter (fun u -> Buffer.add_string buf (print_char u)) t; Buffer.contents buf let sgn_of i = if i < 0 then -1 else if i = 0 then 0 else if i > 0 then 1 else assert false module Ucomp = UCol.Make ((UText : UnicodeString.Type with type t = UText.t)) let uca ~desc variable c = let prev = ref (UText.init 0 (fun _ -> uchar_of_int 0)) in let prev_key = ref (Ucomp.sort_key ~variable !prev) in let prev_line = ref "" in try while true do let line = input_line c in if Str.string_match comment_pat line 0 then () else let t = parse_line line in let t_key = Ucomp.sort_key ~variable t in let sgn = compare !prev_key t_key in let sgn1 = Ucomp.compare ~variable !prev t in let sgn2 = Ucomp.compare_with_key ~variable !prev_key t in let sgn3 = ~- (Ucomp.compare_with_key ~variable t_key !prev) in test ~desc ~body:(fun () -> expect_pass ~body:(fun () -> expect_true ~msg:(lazy (sprintf "the previous line is greater than the current:\n\ value: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn <= 0); if sgn = 0 then expect_true ~msg:(lazy (sprintf "the previous line and the current are equal but\ code point order is not correct.\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (lex_compare !prev t <= 0); expect_true ~msg:(lazy (sprintf "comparison by compare is different from \ comparison by keys.\n\ value by compare: %i\n\ value by sort key: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn1 sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn > 0 && sgn1 > 0 || sgn = 0 && sgn1 = 0 || sgn < 0 && sgn1 < 0); expect_true ~msg:(lazy (sprintf "comparison by compare_with_key prev_key current \ is different from comparison by keys.\n\ value by compare_with_key prev_key current: %i\n\ value by sort key: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn2 sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn > 0 && sgn2 > 0 || sgn = 0 && sgn2 = 0 || sgn < 0 && sgn2 < 0); expect_true ~msg:(lazy (sprintf "comparison by compare_with_key current_key prev \ is different from comparison by keys.\n\ value by compare_with_key current_key prev: %i\n\ value by sort key: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn3 sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn > 0 && sgn3 > 0 || sgn = 0 && sgn3 = 0 || sgn < 0 && sgn3 < 0))); prev := t; prev_key := t_key; prev_line := line done with End_of_file -> () let _ = read_file (input_filename "unidata/CollationTest_SHIFTED.txt") (uca ~desc:"Shifted" `Shifted) let _ = read_file (input_filename "unidata/CollationTest_NON_IGNORABLE.txt") (uca ~desc:"Non ignorable" `Non_ignorable) module UTF8Comp = UCol.Make (UTF8) let print_text_utf8 t = let buf = Buffer.create (5 * UTF8.length t) in UTF8.iter (fun u -> Buffer.add_string buf (print_char u)) t; Buffer.contents buf let locale_test ~desc ?variable ~locale c = let prev = ref "" in let prev_key = ref (UTF8Comp.sort_key ?variable ~locale "") in try while true do let line = input_line c in if Str.string_match comment_pat line 0 then () else let key = UTF8Comp.sort_key ?variable ~locale line in let sgn = sgn_of (UTF8Comp.compare ?variable ~locale !prev line) in let sgn1 = sgn_of (Pervasives.compare !prev_key key) in let sgn2 = sgn_of (UTF8Comp.compare_with_key ?variable ~locale !prev_key line) in let sgn3 = - sgn_of (UTF8Comp.compare_with_key ?variable ~locale key !prev) in test ~desc ~body:(fun () -> expect_pass ~body:(fun () -> expect_true ~msg:(lazy (sprintf "the previous key is greater than the current:\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n" sgn !prev (print_text_utf8 !prev) (String.escaped !prev_key) line (print_text_utf8 line) (String.escaped key))) (sgn1 <= 0); expect_true ~msg:(lazy (sprintf "The comparison results differ\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n\ previous - current comparison : %d\n\ previous key - current key comparison : %d\n\ previous key - current comparison : %d\n\ previous - current key comparison : %d\n" sgn !prev (print_text_utf8 !prev) (String.escaped !prev_key) line (print_text_utf8 line) (String.escaped key) sgn sgn1 sgn2 sgn3)) (sgn = sgn1 && sgn1 = sgn2 && sgn2 = sgn3))); prev := line; prev_key := key done with End_of_file -> () let _ = read_file (input_filename "data/fr_CA") (locale_test ~desc:"Canadian French" ~variable:`Shift_Trimmed ~locale:"fr_CA") let _ = read_file (input_filename "data/th18057") (locale_test ~desc:"Thai" ~variable:`Non_ignorable ~locale:"th_TH") let test_list ~desc ?variable ~locale list = let rec loop prev prev_key = function [] -> () | t :: rest -> let key = UTF8Comp.sort_key ?variable ~locale t in let sgn = sgn_of (UTF8Comp.compare ?variable ~locale prev t) in let sgn1 = sgn_of (Pervasives.compare prev_key key) in let sgn2 = sgn_of (UTF8Comp.compare_with_key ?variable ~locale prev_key t) in let sgn3 = - sgn_of (UTF8Comp.compare_with_key ?variable ~locale key prev) in test ~desc ~body:(fun () -> expect_pass ~body:(fun () -> expect_true ~msg:(lazy (sprintf "the previous key is greater than the current:\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n" sgn prev (print_text_utf8 prev) (String.escaped prev_key) t (print_text_utf8 t) (String.escaped key))) (sgn1 < 0); if sgn1 = 0 then expect_true ~msg:(lazy (sprintf "the previous line and the current are equal but\ code point order is not correct.\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" prev (print_text_utf8 prev) (String.escaped prev_key) t (print_text_utf8 t) (String.escaped key))) (Pervasives.compare prev t <= 0); expect_true ~msg:(lazy (sprintf "The comparison results differ\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n previous - current comparison : %d\n previous key - current key comparison : %d\n previous key - current comparison : %d\n previous - current key comparison : %d\n" sgn prev (print_text_utf8 prev) (String.escaped prev_key) t (print_text_utf8 t) (String.escaped key) sgn sgn1 sgn2 sgn3)) (sgn = sgn1 && sgn1 = sgn2 && sgn2 = sgn3))); loop t key rest in loop "" (UTF8Comp.sort_key ?variable ~locale "") list Test for Scandinavian languages let () = test_list ~desc:"German: ä<b" ~locale:"de" ["a"; "ä"; "b"; "z"] let () = test_list ~desc:"Finish: b<ä" ~locale:"fi_FI" ["a"; "b"; "z"; "ä"] let () = test_list ~desc:"German: Ä<B" ~locale:"de" ["A"; "Ä"; "B"; "Z"] let () = test_list ~desc:"Finish: B<Ä" ~locale:"fi_FI" ["A"; "B"; "Z"; "Ä"] let () = test_list ~desc:"JISX 4061 test1" ~locale:"ja" jisx4061_test1 let () = test_list ~desc:"JISX 4061 test2" ~locale:"ja" jisx4061_test2 let () = test_list ~desc:"test_1 y < x" ~locale:"test_1" ["aaaaXbbbb"; "aaaaybbbb"; "aaaaxbbbb"; "aaaaZbbbb"; "aaaazbbbb"] let () = test_list ~desc:test_desc_1 ~locale:"test_1" test_list_1 let () = test_list ~desc:test_desc_2 ~locale:"test_1" test_list_2 let () = test_list ~desc:test_desc_3 ~locale:"test_1" test_list_3 let () = test_list ~desc:test_desc_4 ~locale:"test_1" test_list_4 let () = test_list ~desc:"test_1 &b <<< b|*" ~locale:"test_1" ["aaaabbbb"; "aaaab*b*"; "aaaabcbc"] let () = test_list ~desc:test_desc_5 ~locale:"test_1" test_list_5
null
https://raw.githubusercontent.com/yoriyuki/Camomile/d7d8843c88fae774f513610f8e09a613778e64b3/camomile-test/tester/test_uCol.ml
ocaml
Copyright 2002,2003,2004,2005,2006 Yamagata Yoriyuki
$ I d : test - uCol.ml , v 1.13 2006/08/13 21:23:08 yori Exp $ open CamomileLibraryTest.Camomile open UPervasives open Blender open Printf open TestUColJapanese let rec lex_compare_aux i t1 t2 = if i >= UText.length t1 then if i >= UText.length t2 then 0 else ~-1 else if i >= UText.length t2 then 1 else match Pervasives.compare (UText.get t1 i) (UText.get t2 i) with 0 -> lex_compare_aux (i + 1) t1 t2 | sgn -> sgn let lex_compare t1 t2 = lex_compare_aux 0 t1 t2 let blank = Str.regexp "[ \t]+" let line_pat = Str.regexp "\\([^;]+\\);.*$" let comment_pat = Str.regexp "^#.*" let uchar_of_code code = uchar_of_int (int_of_string ("0x"^code)) let us_of_cs cs = List.map uchar_of_code cs let parse_line line = if Str.string_match line_pat line 0 then let s = Str.matched_group 1 line in let cs = Str.split blank s in let us = us_of_cs cs in UText.init (List.length us) (fun i -> List.nth us i) else invalid_arg (sprintf "Malformed_line %s:" line) let print_char u = sprintf "%04X " (int_of_uchar u) let print_text t = let buf = Buffer.create (5 * UText.length t) in UText.iter (fun u -> Buffer.add_string buf (print_char u)) t; Buffer.contents buf let sgn_of i = if i < 0 then -1 else if i = 0 then 0 else if i > 0 then 1 else assert false module Ucomp = UCol.Make ((UText : UnicodeString.Type with type t = UText.t)) let uca ~desc variable c = let prev = ref (UText.init 0 (fun _ -> uchar_of_int 0)) in let prev_key = ref (Ucomp.sort_key ~variable !prev) in let prev_line = ref "" in try while true do let line = input_line c in if Str.string_match comment_pat line 0 then () else let t = parse_line line in let t_key = Ucomp.sort_key ~variable t in let sgn = compare !prev_key t_key in let sgn1 = Ucomp.compare ~variable !prev t in let sgn2 = Ucomp.compare_with_key ~variable !prev_key t in let sgn3 = ~- (Ucomp.compare_with_key ~variable t_key !prev) in test ~desc ~body:(fun () -> expect_pass ~body:(fun () -> expect_true ~msg:(lazy (sprintf "the previous line is greater than the current:\n\ value: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn <= 0); if sgn = 0 then expect_true ~msg:(lazy (sprintf "the previous line and the current are equal but\ code point order is not correct.\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (lex_compare !prev t <= 0); expect_true ~msg:(lazy (sprintf "comparison by compare is different from \ comparison by keys.\n\ value by compare: %i\n\ value by sort key: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn1 sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn > 0 && sgn1 > 0 || sgn = 0 && sgn1 = 0 || sgn < 0 && sgn1 < 0); expect_true ~msg:(lazy (sprintf "comparison by compare_with_key prev_key current \ is different from comparison by keys.\n\ value by compare_with_key prev_key current: %i\n\ value by sort key: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn2 sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn > 0 && sgn2 > 0 || sgn = 0 && sgn2 = 0 || sgn < 0 && sgn2 < 0); expect_true ~msg:(lazy (sprintf "comparison by compare_with_key current_key prev \ is different from comparison by keys.\n\ value by compare_with_key current_key prev: %i\n\ value by sort key: %i\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" sgn3 sgn !prev_line (print_text !prev) (String.escaped !prev_key) line (print_text t) (String.escaped t_key))) (sgn > 0 && sgn3 > 0 || sgn = 0 && sgn3 = 0 || sgn < 0 && sgn3 < 0))); prev := t; prev_key := t_key; prev_line := line done with End_of_file -> () let _ = read_file (input_filename "unidata/CollationTest_SHIFTED.txt") (uca ~desc:"Shifted" `Shifted) let _ = read_file (input_filename "unidata/CollationTest_NON_IGNORABLE.txt") (uca ~desc:"Non ignorable" `Non_ignorable) module UTF8Comp = UCol.Make (UTF8) let print_text_utf8 t = let buf = Buffer.create (5 * UTF8.length t) in UTF8.iter (fun u -> Buffer.add_string buf (print_char u)) t; Buffer.contents buf let locale_test ~desc ?variable ~locale c = let prev = ref "" in let prev_key = ref (UTF8Comp.sort_key ?variable ~locale "") in try while true do let line = input_line c in if Str.string_match comment_pat line 0 then () else let key = UTF8Comp.sort_key ?variable ~locale line in let sgn = sgn_of (UTF8Comp.compare ?variable ~locale !prev line) in let sgn1 = sgn_of (Pervasives.compare !prev_key key) in let sgn2 = sgn_of (UTF8Comp.compare_with_key ?variable ~locale !prev_key line) in let sgn3 = - sgn_of (UTF8Comp.compare_with_key ?variable ~locale key !prev) in test ~desc ~body:(fun () -> expect_pass ~body:(fun () -> expect_true ~msg:(lazy (sprintf "the previous key is greater than the current:\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n" sgn !prev (print_text_utf8 !prev) (String.escaped !prev_key) line (print_text_utf8 line) (String.escaped key))) (sgn1 <= 0); expect_true ~msg:(lazy (sprintf "The comparison results differ\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n\ previous - current comparison : %d\n\ previous key - current key comparison : %d\n\ previous key - current comparison : %d\n\ previous - current key comparison : %d\n" sgn !prev (print_text_utf8 !prev) (String.escaped !prev_key) line (print_text_utf8 line) (String.escaped key) sgn sgn1 sgn2 sgn3)) (sgn = sgn1 && sgn1 = sgn2 && sgn2 = sgn3))); prev := line; prev_key := key done with End_of_file -> () let _ = read_file (input_filename "data/fr_CA") (locale_test ~desc:"Canadian French" ~variable:`Shift_Trimmed ~locale:"fr_CA") let _ = read_file (input_filename "data/th18057") (locale_test ~desc:"Thai" ~variable:`Non_ignorable ~locale:"th_TH") let test_list ~desc ?variable ~locale list = let rec loop prev prev_key = function [] -> () | t :: rest -> let key = UTF8Comp.sort_key ?variable ~locale t in let sgn = sgn_of (UTF8Comp.compare ?variable ~locale prev t) in let sgn1 = sgn_of (Pervasives.compare prev_key key) in let sgn2 = sgn_of (UTF8Comp.compare_with_key ?variable ~locale prev_key t) in let sgn3 = - sgn_of (UTF8Comp.compare_with_key ?variable ~locale key prev) in test ~desc ~body:(fun () -> expect_pass ~body:(fun () -> expect_true ~msg:(lazy (sprintf "the previous key is greater than the current:\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n" sgn prev (print_text_utf8 prev) (String.escaped prev_key) t (print_text_utf8 t) (String.escaped key))) (sgn1 < 0); if sgn1 = 0 then expect_true ~msg:(lazy (sprintf "the previous line and the current are equal but\ code point order is not correct.\n\ previous line:%s\n\ %s \n\ key %s\n\ current lins:%s\n\ %s \n\ key %s\n" prev (print_text_utf8 prev) (String.escaped prev_key) t (print_text_utf8 t) (String.escaped key))) (Pervasives.compare prev t <= 0); expect_true ~msg:(lazy (sprintf "The comparison results differ\n\ value: %i\n\ previous: %s \n\ code : %s \n\ key %s\n\ current: %s \n\ code : %s \n\ key %s\n previous - current comparison : %d\n previous key - current key comparison : %d\n previous key - current comparison : %d\n previous - current key comparison : %d\n" sgn prev (print_text_utf8 prev) (String.escaped prev_key) t (print_text_utf8 t) (String.escaped key) sgn sgn1 sgn2 sgn3)) (sgn = sgn1 && sgn1 = sgn2 && sgn2 = sgn3))); loop t key rest in loop "" (UTF8Comp.sort_key ?variable ~locale "") list Test for Scandinavian languages let () = test_list ~desc:"German: ä<b" ~locale:"de" ["a"; "ä"; "b"; "z"] let () = test_list ~desc:"Finish: b<ä" ~locale:"fi_FI" ["a"; "b"; "z"; "ä"] let () = test_list ~desc:"German: Ä<B" ~locale:"de" ["A"; "Ä"; "B"; "Z"] let () = test_list ~desc:"Finish: B<Ä" ~locale:"fi_FI" ["A"; "B"; "Z"; "Ä"] let () = test_list ~desc:"JISX 4061 test1" ~locale:"ja" jisx4061_test1 let () = test_list ~desc:"JISX 4061 test2" ~locale:"ja" jisx4061_test2 let () = test_list ~desc:"test_1 y < x" ~locale:"test_1" ["aaaaXbbbb"; "aaaaybbbb"; "aaaaxbbbb"; "aaaaZbbbb"; "aaaazbbbb"] let () = test_list ~desc:test_desc_1 ~locale:"test_1" test_list_1 let () = test_list ~desc:test_desc_2 ~locale:"test_1" test_list_2 let () = test_list ~desc:test_desc_3 ~locale:"test_1" test_list_3 let () = test_list ~desc:test_desc_4 ~locale:"test_1" test_list_4 let () = test_list ~desc:"test_1 &b <<< b|*" ~locale:"test_1" ["aaaabbbb"; "aaaab*b*"; "aaaabcbc"] let () = test_list ~desc:test_desc_5 ~locale:"test_1" test_list_5
c8a5026f033e31dba28302532e00794d8166397f0a1e81493034dc647f4b664e
ocaml-multicore/ocaml-tsan
includecore.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Inclusion checks for the core language *) open Typedtree open Types type position = Errortrace.position = First | Second type primitive_mismatch = | Name | Arity | No_alloc of position | Native_name | Result_repr | Argument_repr of int type value_mismatch = | Primitive_mismatch of primitive_mismatch | Not_a_primitive | Type of Errortrace.moregen_error exception Dont_match of value_mismatch (* Documents which kind of private thing would be revealed *) type privacy_mismatch = | Private_type_abbreviation | Private_variant_type | Private_record_type | Private_extensible_variant | Private_row_type type type_kind = | Kind_abstract | Kind_record | Kind_variant | Kind_open type kind_mismatch = type_kind * type_kind type label_mismatch = | Type of Errortrace.equality_error | Mutability of position type record_change = (Types.label_declaration as 'ld, 'ld, label_mismatch) Diffing_with_keys.change type record_mismatch = | Label_mismatch of record_change list | Unboxed_float_representation of position type constructor_mismatch = | Type of Errortrace.equality_error | Arity | Inline_record of record_change list | Kind of position | Explicit_return_type of position type extension_constructor_mismatch = | Constructor_privacy | Constructor_mismatch of Ident.t * extension_constructor * extension_constructor * constructor_mismatch type variant_change = (Types.constructor_declaration as 'cd, 'cd, constructor_mismatch) Diffing_with_keys.change type private_variant_mismatch = | Only_outer_closed | Missing of position * string | Presence of string | Incompatible_types_for of string | Types of Errortrace.equality_error type private_object_mismatch = | Missing of string | Types of Errortrace.equality_error type type_mismatch = | Arity | Privacy of privacy_mismatch | Kind of kind_mismatch | Constraint of Errortrace.equality_error | Manifest of Errortrace.equality_error | Private_variant of type_expr * type_expr * private_variant_mismatch | Private_object of type_expr * type_expr * private_object_mismatch | Variance | Record_mismatch of record_mismatch | Variant_mismatch of variant_change list | Unboxed_representation of position | Immediate of Type_immediacy.Violation.t val value_descriptions: loc:Location.t -> Env.t -> string -> value_description -> value_description -> module_coercion val type_declarations: ?equality:bool -> loc:Location.t -> Env.t -> mark:bool -> string -> type_declaration -> Path.t -> type_declaration -> type_mismatch option val extension_constructors: loc:Location.t -> Env.t -> mark:bool -> Ident.t -> extension_constructor -> extension_constructor -> extension_constructor_mismatch option val : - > class_type - > class_type - > bool val class_types: Env.t -> class_type -> class_type -> bool *) val report_value_mismatch : string -> string -> Env.t -> Format.formatter -> value_mismatch -> unit val report_type_mismatch : string -> string -> string -> Env.t -> Format.formatter -> type_mismatch -> unit val report_extension_constructor_mismatch : string -> string -> string -> Env.t -> Format.formatter -> extension_constructor_mismatch -> unit
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/typing/includecore.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Inclusion checks for the core language Documents which kind of private thing would be revealed
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Typedtree open Types type position = Errortrace.position = First | Second type primitive_mismatch = | Name | Arity | No_alloc of position | Native_name | Result_repr | Argument_repr of int type value_mismatch = | Primitive_mismatch of primitive_mismatch | Not_a_primitive | Type of Errortrace.moregen_error exception Dont_match of value_mismatch type privacy_mismatch = | Private_type_abbreviation | Private_variant_type | Private_record_type | Private_extensible_variant | Private_row_type type type_kind = | Kind_abstract | Kind_record | Kind_variant | Kind_open type kind_mismatch = type_kind * type_kind type label_mismatch = | Type of Errortrace.equality_error | Mutability of position type record_change = (Types.label_declaration as 'ld, 'ld, label_mismatch) Diffing_with_keys.change type record_mismatch = | Label_mismatch of record_change list | Unboxed_float_representation of position type constructor_mismatch = | Type of Errortrace.equality_error | Arity | Inline_record of record_change list | Kind of position | Explicit_return_type of position type extension_constructor_mismatch = | Constructor_privacy | Constructor_mismatch of Ident.t * extension_constructor * extension_constructor * constructor_mismatch type variant_change = (Types.constructor_declaration as 'cd, 'cd, constructor_mismatch) Diffing_with_keys.change type private_variant_mismatch = | Only_outer_closed | Missing of position * string | Presence of string | Incompatible_types_for of string | Types of Errortrace.equality_error type private_object_mismatch = | Missing of string | Types of Errortrace.equality_error type type_mismatch = | Arity | Privacy of privacy_mismatch | Kind of kind_mismatch | Constraint of Errortrace.equality_error | Manifest of Errortrace.equality_error | Private_variant of type_expr * type_expr * private_variant_mismatch | Private_object of type_expr * type_expr * private_object_mismatch | Variance | Record_mismatch of record_mismatch | Variant_mismatch of variant_change list | Unboxed_representation of position | Immediate of Type_immediacy.Violation.t val value_descriptions: loc:Location.t -> Env.t -> string -> value_description -> value_description -> module_coercion val type_declarations: ?equality:bool -> loc:Location.t -> Env.t -> mark:bool -> string -> type_declaration -> Path.t -> type_declaration -> type_mismatch option val extension_constructors: loc:Location.t -> Env.t -> mark:bool -> Ident.t -> extension_constructor -> extension_constructor -> extension_constructor_mismatch option val : - > class_type - > class_type - > bool val class_types: Env.t -> class_type -> class_type -> bool *) val report_value_mismatch : string -> string -> Env.t -> Format.formatter -> value_mismatch -> unit val report_type_mismatch : string -> string -> string -> Env.t -> Format.formatter -> type_mismatch -> unit val report_extension_constructor_mismatch : string -> string -> string -> Env.t -> Format.formatter -> extension_constructor_mismatch -> unit
1a68ab90b232ab5ca73fc34677fcf6a4cda98fd1aa4c07800b7a9aa05f2fe865
RyanHope/ACT-R
production-compilation-issues.lisp
(clear-all) (defvar *val1*) (defvar *val2*) (defvar *responses*) (defvar *start-time*) (defvar *times*) (defvar *exp-length*) (defvar *task-over*) (defparameter *model* t) (defparameter *result-matrix* (make-array '(4 4 4) :initial-contents '((("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose")) (("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose")) (("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose")) (("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose"))))) (defun convert-key-to-index (key) (case key ((#\s #\S) 0) ((#\d #\D) 1) ((#\f #\F) 2) (t 3))) ;; This is only safe for virtual and Environment windows ;; because present-next-trial calls ACT-R commands. See ;; docs/device-interaction-issues.doc for more details. (defmethod rpm-window-key-event-handler ((win rpm-window) key) (unless *task-over* (if (eq key #\space) (if (= *exp-length* (length *responses*)) (setf *task-over* t) (present-next-trial)) (let* ((response-index (convert-key-to-index key)) (result (aref *result-matrix* *val1* *val2* response-index))) (push result *responses*) (push (- (get-time *model*) *start-time*) *times*) (present-feedback result))))) (defun present-feedback (result) (clear-exp-window) (add-text-to-exp-window :x 100 :y 100 :text result) (when *model* (schedule-event-relative 0 'proc-display))) (defun present-next-trial () (clear-exp-window) (setf *val1* (act-r-random 4)) (setf *val2* (act-r-random 4)) (add-text-to-exp-window :x 35 :y 50 :text (princ-to-string *val1*) :width 30) (add-text-to-exp-window :x 70 :y 50 :text (princ-to-string *val2*) :width 30) (when *model* (schedule-event-relative 0 'proc-display)) (setf *start-time* (get-time *model*))) (defun choice-game-trials (&key (n 200) (reset t) (output t)) (when reset (reset)) (let ((window (open-exp-window "Compilation task" :visible (not *model*)))) (setf *times* nil) (setf *responses* nil) (setf *task-over* nil) (setf *exp-length* n) (present-next-trial) (if *model* (progn (install-device window) (run-until-condition (lambda () *task-over*))) (while (not *task-over*) (allow-event-manager window))) (analyze-results output))) (defun choice-game-experiment (n &optional show-games) (let ((scores (make-list 20 :initial-element 0)) (times (make-list 20 :initial-element 0))) (dotimes (i n) (let ((result (choice-game-trials :output show-games))) (setf scores (mapcar '+ scores (first result))) (setf times (mapcar '+ times (second result))))) (format t "~%Average Score of ~d trials~%" n) (format t "~{~8,3f ~}" (mapcar (lambda (x) (/ x n)) scores)) (format t "~%Average Response times~%") (format t "~{~8,3f ~}" (mapcar (lambda (x) (ms-round (ms->seconds (/ x n)))) times)))) (defun analyze-results (output) (let ((data (list nil nil))) (format output "Score~%") (setf *responses* (reverse *responses*)) (while *responses* (let ((sum 0) (count 0)) (dotimes (i (min (length *responses*) 10)) (let ((result (pop *responses*))) (when (string-equal result "win") (incf sum)) (when (string-equal result "lose") (decf sum))) (incf count)) (format output " ~2d(~2d)" sum count) (push-last sum (first data)))) (format output "~%Average response times~%") (setf *times* (reverse *times*)) (while *times* (let ((sum 0) (count 0)) (dotimes (i (min (length *times*) 10)) (incf sum (pop *times*)) (incf count)) (format output "~8,3f" (ms-round (ms->seconds (/ sum count)))) (push-last (/ sum count) (second data)))) (format output "~%") data)) (define-model compilation-test (sgp :esc t :lf .5 :bll .5 :mp 18 :rt -3 :ans .25) (sgp :style-warnings nil) (chunk-type task state) (chunk-type number visual-rep) (chunk-type response key (is-response t)) (chunk-type trial num1 num2 result response) (define-chunks (win isa chunk) (draw isa chunk) (lose isa chunk) (attend-num-1 isa chunk) (encode-num-1 isa chunk) (find-num-2 isa chunk) (attend-num-2 isa chunk) (encode-num-2 isa chunk) (num2 isa chunk) (retrieve-past-trial isa chunk) (process-past-trial isa chunk) (respond isa chunk) (guess-other isa chunk) (detect-feedback isa chunk) (encode-feedback isa chunk)) (add-dm (zero isa number visual-rep "0") (one isa number visual-rep "1") (two isa number visual-rep "2") (three isa number visual-rep "3")) (add-dm (response-1 isa response key "s") (response-2 isa response key "d") (response-3 isa response key "f")) (set-similarities (win draw -.2) (win lose -.15) (zero one -.1) (one two -.1) (two three -.1) (zero two -.2) (one three -.2) (zero three -.3)) (set-all-base-levels 1000 -100) (goal-focus-fct (car (define-chunks (isa task)))) (p detect-trial-start =goal> isa task state nil =visual-location> isa visual-location ?visual> state free ?imaginal> state free ==> =goal> state attend-num-1 +imaginal> isa trial +visual> cmd move-attention screen-pos =visual-location) (p attend-num-1 =goal> isa task state attend-num-1 =visual> isa visual-object value =val ==> =goal> state encode-num-1 +retrieval> isa number visual-rep =val) (p encode-num-1 =goal> isa task state encode-num-1 =retrieval> isa number =imaginal> isa trial ==> =imaginal> num1 =retrieval =goal> state find-num-2 +visual-location> isa visual-location > screen-x current :attended nil) (p find-num-2 =goal> isa task state find-num-2 =visual-location> isa visual-location ?visual> state free ==> =goal> state attend-num-2 +visual> cmd move-attention screen-pos =visual-location) (p attend-num-2 =goal> isa task state attend-num-2 =visual> isa visual-object value =val ==> =goal> state encode-num-2 +retrieval> isa number visual-rep =val) (p encode-num-2 =goal> isa task state encode-num-2 =retrieval> isa number =imaginal> isa trial ==> =imaginal> num2 =retrieval =goal> state retrieve-past-trial) (p retrieve-past-trial =goal> isa task state retrieve-past-trial =imaginal> isa trial num1 =n1 num2 =n2 ==> =imaginal> +retrieval> isa trial num1 =n1 num2 =n2 result win =goal> state process-past-trial) (p no-past-trial =goal> isa task state process-past-trial ?retrieval> buffer failure ==> +retrieval> isa response =goal> state respond) (p retrieved-a-win =goal> isa task state process-past-trial =retrieval> isa trial result win response =response ==> +retrieval> =response =goal> state respond) (p retrieved-a-non-win =goal> isa task state process-past-trial =retrieval> isa trial - result win response =response ==> +retrieval> =response =goal> state guess-other) (p guess-other =goal> isa task state guess-other =retrieval> isa response key =key ==> +retrieval> isa response - key =key =goal> state respond) (p respond =goal> isa task state respond =retrieval> isa response key =key ?manual> state free =imaginal> isa trial ==> =imaginal> response =retrieval +manual> cmd press-key key =key =goal> state detect-feedback) (p respond-when-response-failure =goal> isa task state respond ?retrieval> buffer failure ?manual> state free =imaginal> isa trial ==> =imaginal> response response-2 +manual> cmd press-key key "d" =goal> state detect-feedback) (p detect-feedback =goal> isa task state detect-feedback =visual-location> isa visual-location ?visual> state free ==> +visual> cmd move-attention screen-pos =visual-location =goal> state encode-feedback) (p encode-feedback-win =goal> isa task state encode-feedback =imaginal> isa trial =visual> isa visual-object value "win" ?manual> state free ==> =imaginal> result win +manual> cmd press-key key space +goal> isa task) (p encode-feedback-lose =goal> isa task state encode-feedback =imaginal> isa trial =visual> isa visual-object value "lose" ?manual> state free ==> =imaginal> result lose +manual> cmd press-key key space +goal> isa task) (p encode-feedback-draw =goal> isa task state encode-feedback =imaginal> isa trial =visual> isa visual-object value "draw" ?manual> state free ==> =imaginal> result draw +manual> cmd press-key key space +goal> isa task) )
null
https://raw.githubusercontent.com/RyanHope/ACT-R/c65f3fe7057da0476281ad869c7963c84c0ad735/tutorial/unit7/production-compilation-issues.lisp
lisp
This is only safe for virtual and Environment windows because present-next-trial calls ACT-R commands. See docs/device-interaction-issues.doc for more details.
(clear-all) (defvar *val1*) (defvar *val2*) (defvar *responses*) (defvar *start-time*) (defvar *times*) (defvar *exp-length*) (defvar *task-over*) (defparameter *model* t) (defparameter *result-matrix* (make-array '(4 4 4) :initial-contents '((("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose")) (("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose")) (("win" "lose" "draw" "lose") ("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose")) (("win" "lose" "draw" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose") ("lose" "draw" "win" "lose"))))) (defun convert-key-to-index (key) (case key ((#\s #\S) 0) ((#\d #\D) 1) ((#\f #\F) 2) (t 3))) (defmethod rpm-window-key-event-handler ((win rpm-window) key) (unless *task-over* (if (eq key #\space) (if (= *exp-length* (length *responses*)) (setf *task-over* t) (present-next-trial)) (let* ((response-index (convert-key-to-index key)) (result (aref *result-matrix* *val1* *val2* response-index))) (push result *responses*) (push (- (get-time *model*) *start-time*) *times*) (present-feedback result))))) (defun present-feedback (result) (clear-exp-window) (add-text-to-exp-window :x 100 :y 100 :text result) (when *model* (schedule-event-relative 0 'proc-display))) (defun present-next-trial () (clear-exp-window) (setf *val1* (act-r-random 4)) (setf *val2* (act-r-random 4)) (add-text-to-exp-window :x 35 :y 50 :text (princ-to-string *val1*) :width 30) (add-text-to-exp-window :x 70 :y 50 :text (princ-to-string *val2*) :width 30) (when *model* (schedule-event-relative 0 'proc-display)) (setf *start-time* (get-time *model*))) (defun choice-game-trials (&key (n 200) (reset t) (output t)) (when reset (reset)) (let ((window (open-exp-window "Compilation task" :visible (not *model*)))) (setf *times* nil) (setf *responses* nil) (setf *task-over* nil) (setf *exp-length* n) (present-next-trial) (if *model* (progn (install-device window) (run-until-condition (lambda () *task-over*))) (while (not *task-over*) (allow-event-manager window))) (analyze-results output))) (defun choice-game-experiment (n &optional show-games) (let ((scores (make-list 20 :initial-element 0)) (times (make-list 20 :initial-element 0))) (dotimes (i n) (let ((result (choice-game-trials :output show-games))) (setf scores (mapcar '+ scores (first result))) (setf times (mapcar '+ times (second result))))) (format t "~%Average Score of ~d trials~%" n) (format t "~{~8,3f ~}" (mapcar (lambda (x) (/ x n)) scores)) (format t "~%Average Response times~%") (format t "~{~8,3f ~}" (mapcar (lambda (x) (ms-round (ms->seconds (/ x n)))) times)))) (defun analyze-results (output) (let ((data (list nil nil))) (format output "Score~%") (setf *responses* (reverse *responses*)) (while *responses* (let ((sum 0) (count 0)) (dotimes (i (min (length *responses*) 10)) (let ((result (pop *responses*))) (when (string-equal result "win") (incf sum)) (when (string-equal result "lose") (decf sum))) (incf count)) (format output " ~2d(~2d)" sum count) (push-last sum (first data)))) (format output "~%Average response times~%") (setf *times* (reverse *times*)) (while *times* (let ((sum 0) (count 0)) (dotimes (i (min (length *times*) 10)) (incf sum (pop *times*)) (incf count)) (format output "~8,3f" (ms-round (ms->seconds (/ sum count)))) (push-last (/ sum count) (second data)))) (format output "~%") data)) (define-model compilation-test (sgp :esc t :lf .5 :bll .5 :mp 18 :rt -3 :ans .25) (sgp :style-warnings nil) (chunk-type task state) (chunk-type number visual-rep) (chunk-type response key (is-response t)) (chunk-type trial num1 num2 result response) (define-chunks (win isa chunk) (draw isa chunk) (lose isa chunk) (attend-num-1 isa chunk) (encode-num-1 isa chunk) (find-num-2 isa chunk) (attend-num-2 isa chunk) (encode-num-2 isa chunk) (num2 isa chunk) (retrieve-past-trial isa chunk) (process-past-trial isa chunk) (respond isa chunk) (guess-other isa chunk) (detect-feedback isa chunk) (encode-feedback isa chunk)) (add-dm (zero isa number visual-rep "0") (one isa number visual-rep "1") (two isa number visual-rep "2") (three isa number visual-rep "3")) (add-dm (response-1 isa response key "s") (response-2 isa response key "d") (response-3 isa response key "f")) (set-similarities (win draw -.2) (win lose -.15) (zero one -.1) (one two -.1) (two three -.1) (zero two -.2) (one three -.2) (zero three -.3)) (set-all-base-levels 1000 -100) (goal-focus-fct (car (define-chunks (isa task)))) (p detect-trial-start =goal> isa task state nil =visual-location> isa visual-location ?visual> state free ?imaginal> state free ==> =goal> state attend-num-1 +imaginal> isa trial +visual> cmd move-attention screen-pos =visual-location) (p attend-num-1 =goal> isa task state attend-num-1 =visual> isa visual-object value =val ==> =goal> state encode-num-1 +retrieval> isa number visual-rep =val) (p encode-num-1 =goal> isa task state encode-num-1 =retrieval> isa number =imaginal> isa trial ==> =imaginal> num1 =retrieval =goal> state find-num-2 +visual-location> isa visual-location > screen-x current :attended nil) (p find-num-2 =goal> isa task state find-num-2 =visual-location> isa visual-location ?visual> state free ==> =goal> state attend-num-2 +visual> cmd move-attention screen-pos =visual-location) (p attend-num-2 =goal> isa task state attend-num-2 =visual> isa visual-object value =val ==> =goal> state encode-num-2 +retrieval> isa number visual-rep =val) (p encode-num-2 =goal> isa task state encode-num-2 =retrieval> isa number =imaginal> isa trial ==> =imaginal> num2 =retrieval =goal> state retrieve-past-trial) (p retrieve-past-trial =goal> isa task state retrieve-past-trial =imaginal> isa trial num1 =n1 num2 =n2 ==> =imaginal> +retrieval> isa trial num1 =n1 num2 =n2 result win =goal> state process-past-trial) (p no-past-trial =goal> isa task state process-past-trial ?retrieval> buffer failure ==> +retrieval> isa response =goal> state respond) (p retrieved-a-win =goal> isa task state process-past-trial =retrieval> isa trial result win response =response ==> +retrieval> =response =goal> state respond) (p retrieved-a-non-win =goal> isa task state process-past-trial =retrieval> isa trial - result win response =response ==> +retrieval> =response =goal> state guess-other) (p guess-other =goal> isa task state guess-other =retrieval> isa response key =key ==> +retrieval> isa response - key =key =goal> state respond) (p respond =goal> isa task state respond =retrieval> isa response key =key ?manual> state free =imaginal> isa trial ==> =imaginal> response =retrieval +manual> cmd press-key key =key =goal> state detect-feedback) (p respond-when-response-failure =goal> isa task state respond ?retrieval> buffer failure ?manual> state free =imaginal> isa trial ==> =imaginal> response response-2 +manual> cmd press-key key "d" =goal> state detect-feedback) (p detect-feedback =goal> isa task state detect-feedback =visual-location> isa visual-location ?visual> state free ==> +visual> cmd move-attention screen-pos =visual-location =goal> state encode-feedback) (p encode-feedback-win =goal> isa task state encode-feedback =imaginal> isa trial =visual> isa visual-object value "win" ?manual> state free ==> =imaginal> result win +manual> cmd press-key key space +goal> isa task) (p encode-feedback-lose =goal> isa task state encode-feedback =imaginal> isa trial =visual> isa visual-object value "lose" ?manual> state free ==> =imaginal> result lose +manual> cmd press-key key space +goal> isa task) (p encode-feedback-draw =goal> isa task state encode-feedback =imaginal> isa trial =visual> isa visual-object value "draw" ?manual> state free ==> =imaginal> result draw +manual> cmd press-key key space +goal> isa task) )
56913715e62004d4a95390690b27516f7cb60f518f28975ce752509099ebbf28
o1-labs/ppx_version
versioned_bad_wrapped_module_structure.ml
module Foo = struct module Unwrapped = struct module Stable = struct module V1 = struct type t [@@deriving version {wrapped}] end end end end
null
https://raw.githubusercontent.com/o1-labs/ppx_version/74df914452b6ea324020fd4a8780ce196f1bf14a/test/versioned_bad_wrapped_module_structure.ml
ocaml
module Foo = struct module Unwrapped = struct module Stable = struct module V1 = struct type t [@@deriving version {wrapped}] end end end end
25d0852a52b32e12759e350b38ceef04ca000a06c17429c046c455867f0ae551
23Skidoo/ghc-parmake
ReadP.hs
----------------------------------------------------------------------------- -- | Module : Distribution . Compat . ReadP Copyright : ( c ) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Portability : portable -- This is a library of parser combinators , originally written by . -- It parses all alternatives in parallel, so it never keeps hold of -- the beginning of the input string, a common source of space leaks with -- other parsers. The '(+++)' choice combinator is genuinely commutative; -- it makes no difference which branch is \"shorter\". -- See also 's paper /Parallel -- (<>). -- This version of ReadP has been locally hacked to make it H98 , by < mailto: > -- ----------------------------------------------------------------------------- module Distribution.Compat.ReadP ( -- * The 'ReadP' type : : * - > * ; instance Functor , Monad , MonadPlus -- * Primitive operations : : look, -- :: ReadP String (+++), -- :: ReadP a -> ReadP a -> ReadP a (<++), -- :: ReadP a -> ReadP a -> ReadP a gather, -- :: ReadP a -> ReadP (String, a) -- * Other operations pfail, -- :: ReadP a : : ( Bool ) - > ReadP Char : : ReadP Char string, -- :: String -> ReadP String : : ( Bool ) - > ReadP String : : ( Bool ) - > ReadP String : : ( ) choice, -- :: [ReadP a] -> ReadP a count, -- :: Int -> ReadP a -> ReadP [a] between, -- :: ReadP open -> ReadP close -> ReadP a -> ReadP a option, -- :: a -> ReadP a -> ReadP a optional, -- :: ReadP a -> ReadP () many, -- :: ReadP a -> ReadP [a] many1, -- :: ReadP a -> ReadP [a] skipMany, -- :: ReadP a -> ReadP () skipMany1, -- :: ReadP a -> ReadP () sepBy, -- :: ReadP a -> ReadP sep -> ReadP [a] sepBy1, -- :: ReadP a -> ReadP sep -> ReadP [a] endBy, -- :: ReadP a -> ReadP sep -> ReadP [a] endBy1, -- :: ReadP a -> ReadP sep -> ReadP [a] chainr, -- :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a chainl, -- :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a chainl1, -- :: ReadP a -> ReadP (a -> a -> a) -> ReadP a chainr1, -- :: ReadP a -> ReadP (a -> a -> a) -> ReadP a manyTill, -- :: ReadP a -> ReadP end -> ReadP [a] -- * Running a parser ReadS, -- :: *; = String -> [(a,String)] readP_to_S, -- :: ReadP a -> ReadS a readS_to_P -- :: ReadS a -> ReadP a ) where import Control.Monad( MonadPlus(..), liftM, liftM2, replicateM, ap, (>=>) ) import Data.Char (isSpace) import Control.Applicative as AP (Applicative(..), Alternative(empty, (<|>))) infixr 5 +++, <++ -- --------------------------------------------------------------------------- -- The P type -- is representation type -- should be kept abstract data P s a = Get (s -> P s a) | Look ([s] -> P s a) | Fail | Result a (P s a) | Final [(a,[s])] -- invariant: list is non-empty! Monad , MonadPlus instance Functor (P s) where fmap = liftM instance Applicative (P s) where pure x = Result x Fail (<*>) = ap instance Monad (P s) where return = AP.pure (Get f) >>= k = Get (f >=> k) (Look f) >>= k = Look (f >=> k) Fail >>= _ = Fail (Result x p) >>= k = k x `mplus` (p >>= k) (Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s] fail _ = Fail instance Alternative (P s) where empty = mzero (<|>) = mplus instance MonadPlus (P s) where mzero = Fail most common case : two gets are combined Get f1 `mplus` Get f2 = Get (\c -> f1 c `mplus` f2 c) -- results are delivered as soon as possible Result x p `mplus` q = Result x (p `mplus` q) p `mplus` Result x q = Result x (p `mplus` q) -- fail disappears Fail `mplus` p = p p `mplus` Fail = p two finals are combined final + look becomes one look and one final (= optimization ) final + sthg else becomes one look and one final Final r `mplus` Final t = Final (r ++ t) Final r `mplus` Look f = Look (\s -> Final (r ++ run (f s) s)) Final r `mplus` p = Look (\s -> Final (r ++ run p s)) Look f `mplus` Final r = Look (\s -> Final (run (f s) s ++ r)) p `mplus` Final r = Look (\s -> Final (run p s ++ r)) two looks are combined (= optimization ) -- look + sthg else floats upwards Look f `mplus` Look g = Look (\s -> f s `mplus` g s) Look f `mplus` p = Look (\s -> f s `mplus` p) p `mplus` Look f = Look (\s -> p `mplus` f s) -- --------------------------------------------------------------------------- -- The ReadP type newtype Parser r s a = R ((a -> P s r) -> P s r) type ReadP r a = Parser r Char a Functor , Monad , MonadPlus instance Functor (Parser r s) where fmap h (R f) = R (\k -> f (k . h)) instance Applicative (Parser r s) where pure x = R (\k -> k x) (<*>) = ap instance Monad (Parser r s) where return = AP.pure fail _ = R (const Fail) R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k)) instance MonadPlus ( Parser r s ) where mzero = mplus = ( + + + ) -- --------------------------------------------------------------------------- Operations over P final :: [(a,[s])] -> P s a -- Maintains invariant for Final constructor final [] = Fail final r = Final r run :: P c a -> ([c] -> [(a, [c])]) run (Get f) (c:s) = run (f c) s run (Look f) s = run (f s) s run (Result x p) s = (x,s) : run p s run (Final r) _ = r run _ _ = [] -- --------------------------------------------------------------------------- Operations over ReadP get :: ReadP r Char -- ^ Consumes and returns the next character. -- Fails if there is no input left. get = R Get look :: ReadP r String -- ^ Look-ahead: returns the part of the input that is left, without -- consuming it. look = R Look pfail :: ReadP r a -- ^ Always fails. pfail = R (const Fail) (+++) :: ReadP r a -> ReadP r a -> ReadP r a -- ^ Symmetric choice. R f1 +++ R f2 = R (\k -> f1 k `mplus` f2 k) (<++) :: ReadP a a -> ReadP r a -> ReadP r a -- ^ Local, exclusive, left-biased choice: If left parser -- locally produces any result at all, then right parser is -- not used. R f <++ q = do s <- look probe (f return) s 0 where probe (Get f') (c:s) n = probe (f' c) s (n+1 :: Int) probe (Look f') s n = probe (f' s) s n probe p@(Result _ _) _ n = discard n >> R (p >>=) probe (Final r) _ _ = R (Final r >>=) probe _ _ _ = q discard 0 = return () discard n = get >> discard (n-1 :: Int) gather :: ReadP (String -> P Char r) a -> ReadP r (String, a) -- ^ Transforms a parser into one that does the same, but -- in addition returns the exact characters read. IMPORTANT NOTE : ' gather ' gives a runtime error if its first argument -- is built using any occurrences of readS_to_P. gather (R m) = R (\k -> gath id (m (\a -> return (\s -> k (s,a))))) where gath l (Get f) = Get (\c -> gath (l.(c:)) (f c)) gath _ Fail = Fail gath l (Look f) = Look (gath l . f) gath l (Result k p) = k (l []) `mplus` gath l p gath _ (Final _) = error "do not use readS_to_P in gather!" -- --------------------------------------------------------------------------- -- Derived operations satisfy :: (Char -> Bool) -> ReadP r Char -- ^ Consumes and returns the next character, if it satisfies the -- specified predicate. satisfy p = do c <- get; if p c then return c else pfail char :: Char -> ReadP r Char ^ and returns the specified character . char c = satisfy (c ==) string :: String -> ReadP r String ^ and returns the specified string . string this = do s <- look; scan this s where scan [] _ = return this scan (x:xs) (y:ys) | x == y = get >> scan xs ys scan _ _ = pfail munch :: (Char -> Bool) -> ReadP r String ^ the first zero or more characters satisfying the predicate . munch p = do s <- look scan s where scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s) scan _ = do return "" munch1 :: (Char -> Bool) -> ReadP r String ^ the first one or more characters satisfying the predicate . munch1 p = do c <- get if p c then do s <- munch p; return (c:s) else pfail choice :: [ReadP r a] -> ReadP r a -- ^ Combines all parsers in the specified list. choice [] = pfail choice [p] = p choice (p:ps) = p +++ choice ps skipSpaces :: ReadP r () -- ^ Skips all whitespace. skipSpaces = do s <- look skip s where skip (c:s) | isSpace c = do _ <- get; skip s skip _ = do return () count :: Int -> ReadP r a -> ReadP r [a] ^ @ count n p @ parses @n@ occurrences of @p@ in sequence . A list of -- results is returned. count n p = replicateM n p between :: ReadP r open -> ReadP r close -> ReadP r a -> ReadP r a ^ @ between open close p @ parses @open@ , followed by and finally @close@. Only the value of @p@ is returned . between open close p = do _ <- open x <- p _ <- close return x option :: a -> ReadP r a -> ReadP r a -- ^ @option x p@ will either parse @p@ or return @x@ without consuming -- any input. option x p = p +++ return x optional :: ReadP r a -> ReadP r () ^ @optional p@ optionally parses @p@ and always returns @()@. optional p = (p >> return ()) +++ return () many :: ReadP r a -> ReadP r [a] ^ Parses zero or more occurrences of the given parser . many p = return [] +++ many1 p many1 :: ReadP r a -> ReadP r [a] ^ Parses one or more occurrences of the given parser . many1 p = liftM2 (:) p (many p) skipMany :: ReadP r a -> ReadP r () -- ^ Like 'many', but discards the result. skipMany p = many p >> return () skipMany1 :: ReadP r a -> ReadP r () -- ^ Like 'many1', but discards the result. skipMany1 p = p >> skipMany p sepBy :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @sepBy p sep@ parses zero or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy p sep = sepBy1 p sep +++ return [] sepBy1 :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @sepBy1 p sep@ parses one or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy1 p sep = liftM2 (:) p (many (sep >> p)) endBy :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @endBy p sep@ parses zero or more occurrences of @p@ , separated and ended by @sep@. endBy p sep = many (do x <- p ; _ <- sep ; return x) endBy1 :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @endBy p sep@ parses one or more occurrences of @p@ , separated and ended by @sep@. endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x) chainr :: ReadP r a -> ReadP r (a -> a -> a) -> a -> ReadP r a ^ @chainr p op x@ parses zero or more occurrences of @p@ , separated by @op@. -- Returns a value produced by a /right/ associative application of all -- functions returned by @op@. If there are no occurrences of @p@, @x@ is -- returned. chainr p op x = chainr1 p op +++ return x chainl :: ReadP r a -> ReadP r (a -> a -> a) -> a -> ReadP r a ^ @chainl p op x@ parses zero or more occurrences of @p@ , separated by @op@. -- Returns a value produced by a /left/ associative application of all -- functions returned by @op@. If there are no occurrences of @p@, @x@ is -- returned. chainl p op x = chainl1 p op +++ return x chainr1 :: ReadP r a -> ReadP r (a -> a -> a) -> ReadP r a ^ Like ' ' , but parses one or more occurrences of @p@. chainr1 p op = scan where scan = p >>= rest rest x = do f <- op y <- scan return (f x y) +++ return x chainl1 :: ReadP r a -> ReadP r (a -> a -> a) -> ReadP r a ^ Like ' chainl ' , but parses one or more occurrences of @p@. chainl1 p op = p >>= rest where rest x = do f <- op y <- p rest (f x y) +++ return x manyTill :: ReadP r a -> ReadP [a] end -> ReadP r [a] ^ @manyTill p end@ parses zero or more occurrences of @p@ , until @end@ succeeds . Returns a list of values returned by @p@. manyTill p end = scan where scan = (end >> return []) <++ (liftM2 (:) p scan) -- --------------------------------------------------------------------------- -- Converting between ReadP and Read readP_to_S :: ReadP a a -> ReadS a ^ Converts a parser into a Haskell ReadS - style function . This is the main way in which you can " a ' ReadP ' parser : -- the expanded type is -- @ readP_to_S :: ReadP a -> String -> [(a,String)] @ readP_to_S (R f) = run (f return) readS_to_P :: ReadS a -> ReadP r a -- ^ Converts a Haskell ReadS-style function into a parser. -- Warning: This introduces local backtracking in the resulting -- parser, and therefore a possible inefficiency. readS_to_P r = R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s']))
null
https://raw.githubusercontent.com/23Skidoo/ghc-parmake/c4d7fb042f5138588fa54d0153be1aee93db3835/src/Distribution/Compat/ReadP.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Portability : portable It parses all alternatives in parallel, so it never keeps hold of the beginning of the input string, a common source of space leaks with other parsers. The '(+++)' choice combinator is genuinely commutative; it makes no difference which branch is \"shorter\". (<>). --------------------------------------------------------------------------- * The 'ReadP' type * Primitive operations :: ReadP String :: ReadP a -> ReadP a -> ReadP a :: ReadP a -> ReadP a -> ReadP a :: ReadP a -> ReadP (String, a) * Other operations :: ReadP a :: String -> ReadP String :: [ReadP a] -> ReadP a :: Int -> ReadP a -> ReadP [a] :: ReadP open -> ReadP close -> ReadP a -> ReadP a :: a -> ReadP a -> ReadP a :: ReadP a -> ReadP () :: ReadP a -> ReadP [a] :: ReadP a -> ReadP [a] :: ReadP a -> ReadP () :: ReadP a -> ReadP () :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a :: ReadP a -> ReadP (a -> a -> a) -> ReadP a :: ReadP a -> ReadP (a -> a -> a) -> ReadP a :: ReadP a -> ReadP end -> ReadP [a] * Running a parser :: *; = String -> [(a,String)] :: ReadP a -> ReadS a :: ReadS a -> ReadP a --------------------------------------------------------------------------- The P type is representation type -- should be kept abstract invariant: list is non-empty! results are delivered as soon as possible fail disappears look + sthg else floats upwards --------------------------------------------------------------------------- The ReadP type --------------------------------------------------------------------------- Maintains invariant for Final constructor --------------------------------------------------------------------------- ^ Consumes and returns the next character. Fails if there is no input left. ^ Look-ahead: returns the part of the input that is left, without consuming it. ^ Always fails. ^ Symmetric choice. ^ Local, exclusive, left-biased choice: If left parser locally produces any result at all, then right parser is not used. ^ Transforms a parser into one that does the same, but in addition returns the exact characters read. is built using any occurrences of readS_to_P. --------------------------------------------------------------------------- Derived operations ^ Consumes and returns the next character, if it satisfies the specified predicate. ^ Combines all parsers in the specified list. ^ Skips all whitespace. results is returned. ^ @option x p@ will either parse @p@ or return @x@ without consuming any input. ^ Like 'many', but discards the result. ^ Like 'many1', but discards the result. Returns a value produced by a /right/ associative application of all functions returned by @op@. If there are no occurrences of @p@, @x@ is returned. Returns a value produced by a /left/ associative application of all functions returned by @op@. If there are no occurrences of @p@, @x@ is returned. --------------------------------------------------------------------------- Converting between ReadP and Read the expanded type is @ readP_to_S :: ReadP a -> String -> [(a,String)] @ ^ Converts a Haskell ReadS-style function into a parser. Warning: This introduces local backtracking in the resulting parser, and therefore a possible inefficiency.
Module : Distribution . Compat . ReadP Copyright : ( c ) The University of Glasgow 2002 This is a library of parser combinators , originally written by . See also 's paper /Parallel This version of ReadP has been locally hacked to make it H98 , by < mailto: > module Distribution.Compat.ReadP ( : : * - > * ; instance Functor , Monad , MonadPlus : : : : ( Bool ) - > ReadP Char : : ReadP Char : : ( Bool ) - > ReadP String : : ( Bool ) - > ReadP String : : ( ) ) where import Control.Monad( MonadPlus(..), liftM, liftM2, replicateM, ap, (>=>) ) import Data.Char (isSpace) import Control.Applicative as AP (Applicative(..), Alternative(empty, (<|>))) infixr 5 +++, <++ data P s a = Get (s -> P s a) | Look ([s] -> P s a) | Fail | Result a (P s a) Monad , MonadPlus instance Functor (P s) where fmap = liftM instance Applicative (P s) where pure x = Result x Fail (<*>) = ap instance Monad (P s) where return = AP.pure (Get f) >>= k = Get (f >=> k) (Look f) >>= k = Look (f >=> k) Fail >>= _ = Fail (Result x p) >>= k = k x `mplus` (p >>= k) (Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s] fail _ = Fail instance Alternative (P s) where empty = mzero (<|>) = mplus instance MonadPlus (P s) where mzero = Fail most common case : two gets are combined Get f1 `mplus` Get f2 = Get (\c -> f1 c `mplus` f2 c) Result x p `mplus` q = Result x (p `mplus` q) p `mplus` Result x q = Result x (p `mplus` q) Fail `mplus` p = p p `mplus` Fail = p two finals are combined final + look becomes one look and one final (= optimization ) final + sthg else becomes one look and one final Final r `mplus` Final t = Final (r ++ t) Final r `mplus` Look f = Look (\s -> Final (r ++ run (f s) s)) Final r `mplus` p = Look (\s -> Final (r ++ run p s)) Look f `mplus` Final r = Look (\s -> Final (run (f s) s ++ r)) p `mplus` Final r = Look (\s -> Final (run p s ++ r)) two looks are combined (= optimization ) Look f `mplus` Look g = Look (\s -> f s `mplus` g s) Look f `mplus` p = Look (\s -> f s `mplus` p) p `mplus` Look f = Look (\s -> p `mplus` f s) newtype Parser r s a = R ((a -> P s r) -> P s r) type ReadP r a = Parser r Char a Functor , Monad , MonadPlus instance Functor (Parser r s) where fmap h (R f) = R (\k -> f (k . h)) instance Applicative (Parser r s) where pure x = R (\k -> k x) (<*>) = ap instance Monad (Parser r s) where return = AP.pure fail _ = R (const Fail) R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k)) instance MonadPlus ( Parser r s ) where mzero = mplus = ( + + + ) Operations over P final :: [(a,[s])] -> P s a final [] = Fail final r = Final r run :: P c a -> ([c] -> [(a, [c])]) run (Get f) (c:s) = run (f c) s run (Look f) s = run (f s) s run (Result x p) s = (x,s) : run p s run (Final r) _ = r run _ _ = [] Operations over ReadP get :: ReadP r Char get = R Get look :: ReadP r String look = R Look pfail :: ReadP r a pfail = R (const Fail) (+++) :: ReadP r a -> ReadP r a -> ReadP r a R f1 +++ R f2 = R (\k -> f1 k `mplus` f2 k) (<++) :: ReadP a a -> ReadP r a -> ReadP r a R f <++ q = do s <- look probe (f return) s 0 where probe (Get f') (c:s) n = probe (f' c) s (n+1 :: Int) probe (Look f') s n = probe (f' s) s n probe p@(Result _ _) _ n = discard n >> R (p >>=) probe (Final r) _ _ = R (Final r >>=) probe _ _ _ = q discard 0 = return () discard n = get >> discard (n-1 :: Int) gather :: ReadP (String -> P Char r) a -> ReadP r (String, a) IMPORTANT NOTE : ' gather ' gives a runtime error if its first argument gather (R m) = R (\k -> gath id (m (\a -> return (\s -> k (s,a))))) where gath l (Get f) = Get (\c -> gath (l.(c:)) (f c)) gath _ Fail = Fail gath l (Look f) = Look (gath l . f) gath l (Result k p) = k (l []) `mplus` gath l p gath _ (Final _) = error "do not use readS_to_P in gather!" satisfy :: (Char -> Bool) -> ReadP r Char satisfy p = do c <- get; if p c then return c else pfail char :: Char -> ReadP r Char ^ and returns the specified character . char c = satisfy (c ==) string :: String -> ReadP r String ^ and returns the specified string . string this = do s <- look; scan this s where scan [] _ = return this scan (x:xs) (y:ys) | x == y = get >> scan xs ys scan _ _ = pfail munch :: (Char -> Bool) -> ReadP r String ^ the first zero or more characters satisfying the predicate . munch p = do s <- look scan s where scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s) scan _ = do return "" munch1 :: (Char -> Bool) -> ReadP r String ^ the first one or more characters satisfying the predicate . munch1 p = do c <- get if p c then do s <- munch p; return (c:s) else pfail choice :: [ReadP r a] -> ReadP r a choice [] = pfail choice [p] = p choice (p:ps) = p +++ choice ps skipSpaces :: ReadP r () skipSpaces = do s <- look skip s where skip (c:s) | isSpace c = do _ <- get; skip s skip _ = do return () count :: Int -> ReadP r a -> ReadP r [a] ^ @ count n p @ parses @n@ occurrences of @p@ in sequence . A list of count n p = replicateM n p between :: ReadP r open -> ReadP r close -> ReadP r a -> ReadP r a ^ @ between open close p @ parses @open@ , followed by and finally @close@. Only the value of @p@ is returned . between open close p = do _ <- open x <- p _ <- close return x option :: a -> ReadP r a -> ReadP r a option x p = p +++ return x optional :: ReadP r a -> ReadP r () ^ @optional p@ optionally parses @p@ and always returns @()@. optional p = (p >> return ()) +++ return () many :: ReadP r a -> ReadP r [a] ^ Parses zero or more occurrences of the given parser . many p = return [] +++ many1 p many1 :: ReadP r a -> ReadP r [a] ^ Parses one or more occurrences of the given parser . many1 p = liftM2 (:) p (many p) skipMany :: ReadP r a -> ReadP r () skipMany p = many p >> return () skipMany1 :: ReadP r a -> ReadP r () skipMany1 p = p >> skipMany p sepBy :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @sepBy p sep@ parses zero or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy p sep = sepBy1 p sep +++ return [] sepBy1 :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @sepBy1 p sep@ parses one or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy1 p sep = liftM2 (:) p (many (sep >> p)) endBy :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @endBy p sep@ parses zero or more occurrences of @p@ , separated and ended by @sep@. endBy p sep = many (do x <- p ; _ <- sep ; return x) endBy1 :: ReadP r a -> ReadP r sep -> ReadP r [a] ^ @endBy p sep@ parses one or more occurrences of @p@ , separated and ended by @sep@. endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x) chainr :: ReadP r a -> ReadP r (a -> a -> a) -> a -> ReadP r a ^ @chainr p op x@ parses zero or more occurrences of @p@ , separated by @op@. chainr p op x = chainr1 p op +++ return x chainl :: ReadP r a -> ReadP r (a -> a -> a) -> a -> ReadP r a ^ @chainl p op x@ parses zero or more occurrences of @p@ , separated by @op@. chainl p op x = chainl1 p op +++ return x chainr1 :: ReadP r a -> ReadP r (a -> a -> a) -> ReadP r a ^ Like ' ' , but parses one or more occurrences of @p@. chainr1 p op = scan where scan = p >>= rest rest x = do f <- op y <- scan return (f x y) +++ return x chainl1 :: ReadP r a -> ReadP r (a -> a -> a) -> ReadP r a ^ Like ' chainl ' , but parses one or more occurrences of @p@. chainl1 p op = p >>= rest where rest x = do f <- op y <- p rest (f x y) +++ return x manyTill :: ReadP r a -> ReadP [a] end -> ReadP r [a] ^ @manyTill p end@ parses zero or more occurrences of @p@ , until @end@ succeeds . Returns a list of values returned by @p@. manyTill p end = scan where scan = (end >> return []) <++ (liftM2 (:) p scan) readP_to_S :: ReadP a a -> ReadS a ^ Converts a parser into a Haskell ReadS - style function . This is the main way in which you can " a ' ReadP ' parser : readP_to_S (R f) = run (f return) readS_to_P :: ReadS a -> ReadP r a readS_to_P r = R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s']))
a02b5500edb3070d433cd51f0985a415d1c3298fa764129be58002b489d204c5
bscarlet/llvm-general
RMWOperation.hs
# LANGUAGE TemplateHaskell , MultiParamTypeClasses # TemplateHaskell, MultiParamTypeClasses #-} module LLVM.General.Internal.RMWOperation where import LLVM.General.AST.RMWOperation import qualified LLVM.General.Internal.FFI.LLVMCTypes as FFI import LLVM.General.Internal.Coding genCodingInstance [t| RMWOperation |] ''FFI.RMWOperation [ (FFI.rmwOperationXchg, Xchg), (FFI.rmwOperationAdd, Add), (FFI.rmwOperationSub, Sub), (FFI.rmwOperationAnd, And), (FFI.rmwOperationNand, Nand), (FFI.rmwOperationOr, Or), (FFI.rmwOperationXor, Xor), (FFI.rmwOperationMax, Max), (FFI.rmwOperationMin, Min), (FFI.rmwOperationUMax, UMax), (FFI.rmwOperationUMin, UMin) ]
null
https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/LLVM/General/Internal/RMWOperation.hs
haskell
# LANGUAGE TemplateHaskell , MultiParamTypeClasses # TemplateHaskell, MultiParamTypeClasses #-} module LLVM.General.Internal.RMWOperation where import LLVM.General.AST.RMWOperation import qualified LLVM.General.Internal.FFI.LLVMCTypes as FFI import LLVM.General.Internal.Coding genCodingInstance [t| RMWOperation |] ''FFI.RMWOperation [ (FFI.rmwOperationXchg, Xchg), (FFI.rmwOperationAdd, Add), (FFI.rmwOperationSub, Sub), (FFI.rmwOperationAnd, And), (FFI.rmwOperationNand, Nand), (FFI.rmwOperationOr, Or), (FFI.rmwOperationXor, Xor), (FFI.rmwOperationMax, Max), (FFI.rmwOperationMin, Min), (FFI.rmwOperationUMax, UMax), (FFI.rmwOperationUMin, UMin) ]
ae9e15564e55ab6bdea0c6d57ef1f99fb70406eef29d56516d9d924b64eeacfa
LambdaScientist/CLaSH-by-example
Sort.hs
-- {-# LANGUAGE ScopedTypeVariables #-} -- {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TupleSections # {-# LANGUAGE TypeFamilies #-} # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # # LANGUAGE Trustworthy # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE ExistentialQuantification # | Bitonic sorting network . See < > and < -flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm > . module CLaSH.Sort ( bitonicMerge, bitonicSort, bitonicSorterExample ) where import CLaSH.Prelude import CLaSH.Promoted.Nat import Data.Proxy (Proxy (..)) import Data . Singletons . Prelude ( TyFun , Apply , type ( @@ ) ) import Prelude ( Integer , ( + ) , , ( $ ) , undefined , i d , fst , Int , otherwise ) import CLaSH.Sized.Vector import CLaSH.Promoted.Nat import Data.Singletons import GHC.TypeLits import Data.Ord compareAndSwap :: (Ord a) => a -> a -> (a, a) compareAndSwap x y | x > y = (x, y) | otherwise = (y, x) | Bitonic merge . Parameterised by the recursive step - to do a bitonic merge on a vector half the size - because Clash can not handle recursive functions . bitonicMerge :: forall n a. (Ord a , KnownNat n) => (Vec n a -> Vec n a) -- ^ The recursive step -> Vec (2 * n) a -- ^ Input vector -> Vec (2 * n) a -- ^ Output vector bitonicMerge recurse input = recurse firstBitonic ++ recurse secondBitonic where partitioned :: Vec 2 (Vec n a) partitioned = unconcatI input firstBitonic, secondBitonic :: Vec n a (firstBitonic, secondBitonic) = unzip $ zipWith compareAndSwap (partitioned !! 0) (partitioned !! 1) | Bitonic sort . Parameterised by both the bitonic merge and the recursive step - a bitonic sort of half the size . bitonicSort :: forall n a. (KnownNat n, Ord a) => (Vec n a -> Vec n a) -- ^ The recursive step -> (Vec (2 * n) a -> Vec (2 * n) a) -- ^ Merge step -> Vec (2 * n) a -- ^ Input vector -> Vec (2 * n) a -- ^ Output vector bitonicSort recurse merge input = merge $ firstSorted ++ secondSorted where split :: Vec 2 (Vec n a) split = unconcatI input firstSorted, secondSorted :: Vec n a firstSorted = recurse $ split !! 0 secondSorted = reverse $ recurse $ split !! 1 | An example 16 element bitonic sorter . TODO : this can probably be generalised to any size using the dependently typed fold in the prelude . bitonicSorterExample :: forall a. (Ord a) => Vec 16 a -- ^ Input vector -> Vec 16 a -- ^ Sorted output vector bitonicSorterExample = sort16 where sort16 = bitonicSort sort8 merge16 merge16 = bitonicMerge merge8 sort8 = bitonicSort sort4 merge8 merge8 = bitonicMerge merge4 sort4 = bitonicSort sort2 merge4 merge4 = bitonicMerge merge2 sort2 = bitonicSort id merge2 merge2 = bitonicMerge id {-| generalised bitonic sorter. -} type ExpVec k a = Vec (2 ^ k) a data SplitHalf (a :: *) (f :: TyFun Nat *) :: * type instance Apply (SplitHalf a) k = (ExpVec k a -> ExpVec k a, ExpVec (k + 1) a -> ExpVec (k + 1) a) generateBitonicSortN2 :: forall k a . (Ord a, KnownNat k) => SNat k -> ExpVec k a -> ExpVec k a generateBitonicSortN2 k = fst $ dfold (Proxy :: Proxy (SplitHalf a)) step base (replicate k ()) where step :: SNat l -> () -> SplitHalf a @@ l -> SplitHalf a @@ (l+1) step SNat _ (sort, merge) = (bitonicSort sort merge, bitonicMerge merge) base = (id, bitonicMerge id) generateBitonicSortN2Base :: (KnownNat k, Ord a) => ExpVec k a -> ExpVec k a generateBitonicSortN2Base = generateBitonicSortN2 (snatProxy Proxy) {-| Examples -} testVec16 :: Num a => Vec 16 a testVec16 = 9 :> 2 :> 8 :> 6 :> 3 :> 7 :> 0 :> 1 :> 4 :> 5 :> 2 :> 8 :> 6 :> 3 :> 7 :> 0 :> Nil testVec8 :: Num a => Vec 8 a testVec8 = 9 :> 2 :> 8 :> 6 :> 3 :> 7 :> 0 :> 1 :> Nil testVec4 :: Num a => Vec 4 a testVec4 = 9 :> 2 :> 8 :> 6 :> Nil testVec2 :: Num a => Vec 2 a testVec2 = 2 :> 9 :> Nil sorter16 :: (Ord a) => Vec 16 a -> Vec 16 a sorter16 = generateBitonicSortN2Base sorter8 :: (Ord a) => Vec 8 a -> Vec 8 a sorter8 = generateBitonicSortN2Base sorter4 ::forall a. (Ord a) => Vec 4 a -> Vec 4 a sorter4 = generateBitonicSortN2Base sorter2 :: forall a. (Ord a) => Vec 2 a -> Vec 2 a sorter2 = generateBitonicSortN2Base example16 :: Vec 16 Int example16 = sorter16 testVec16 example8 :: Vec 8 Int example8 = sorter8 testVec8 example4 :: Vec 4 Int example4 = sorter4 testVec4 example2 :: Vec 2 Int example2 = sorter2 testVec2
null
https://raw.githubusercontent.com/LambdaScientist/CLaSH-by-example/e783cd2f2408e67baf7f36c10398c27036a78ef3/CLaSHExamples/PolymophicCLaSHExample/Sort.hs
haskell
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} # LANGUAGE BangPatterns # # LANGUAGE DataKinds # # LANGUAGE GADTs # # LANGUAGE KindSignatures # # LANGUAGE MagicHash # # LANGUAGE PatternSynonyms # # LANGUAGE Rank2Types # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # ^ The recursive step ^ Input vector ^ Output vector ^ The recursive step ^ Merge step ^ Input vector ^ Output vector ^ Input vector ^ Sorted output vector | generalised bitonic sorter. | Examples
# LANGUAGE TupleSections # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # # LANGUAGE Trustworthy # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE ExistentialQuantification # | Bitonic sorting network . See < > and < -flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm > . module CLaSH.Sort ( bitonicMerge, bitonicSort, bitonicSorterExample ) where import CLaSH.Prelude import CLaSH.Promoted.Nat import Data.Proxy (Proxy (..)) import Data . Singletons . Prelude ( TyFun , Apply , type ( @@ ) ) import Prelude ( Integer , ( + ) , , ( $ ) , undefined , i d , fst , Int , otherwise ) import CLaSH.Sized.Vector import CLaSH.Promoted.Nat import Data.Singletons import GHC.TypeLits import Data.Ord compareAndSwap :: (Ord a) => a -> a -> (a, a) compareAndSwap x y | x > y = (x, y) | otherwise = (y, x) | Bitonic merge . Parameterised by the recursive step - to do a bitonic merge on a vector half the size - because Clash can not handle recursive functions . bitonicMerge :: forall n a. (Ord a , KnownNat n) bitonicMerge recurse input = recurse firstBitonic ++ recurse secondBitonic where partitioned :: Vec 2 (Vec n a) partitioned = unconcatI input firstBitonic, secondBitonic :: Vec n a (firstBitonic, secondBitonic) = unzip $ zipWith compareAndSwap (partitioned !! 0) (partitioned !! 1) | Bitonic sort . Parameterised by both the bitonic merge and the recursive step - a bitonic sort of half the size . bitonicSort :: forall n a. (KnownNat n, Ord a) bitonicSort recurse merge input = merge $ firstSorted ++ secondSorted where split :: Vec 2 (Vec n a) split = unconcatI input firstSorted, secondSorted :: Vec n a firstSorted = recurse $ split !! 0 secondSorted = reverse $ recurse $ split !! 1 | An example 16 element bitonic sorter . TODO : this can probably be generalised to any size using the dependently typed fold in the prelude . bitonicSorterExample :: forall a. (Ord a) bitonicSorterExample = sort16 where sort16 = bitonicSort sort8 merge16 merge16 = bitonicMerge merge8 sort8 = bitonicSort sort4 merge8 merge8 = bitonicMerge merge4 sort4 = bitonicSort sort2 merge4 merge4 = bitonicMerge merge2 sort2 = bitonicSort id merge2 merge2 = bitonicMerge id type ExpVec k a = Vec (2 ^ k) a data SplitHalf (a :: *) (f :: TyFun Nat *) :: * type instance Apply (SplitHalf a) k = (ExpVec k a -> ExpVec k a, ExpVec (k + 1) a -> ExpVec (k + 1) a) generateBitonicSortN2 :: forall k a . (Ord a, KnownNat k) => SNat k -> ExpVec k a -> ExpVec k a generateBitonicSortN2 k = fst $ dfold (Proxy :: Proxy (SplitHalf a)) step base (replicate k ()) where step :: SNat l -> () -> SplitHalf a @@ l -> SplitHalf a @@ (l+1) step SNat _ (sort, merge) = (bitonicSort sort merge, bitonicMerge merge) base = (id, bitonicMerge id) generateBitonicSortN2Base :: (KnownNat k, Ord a) => ExpVec k a -> ExpVec k a generateBitonicSortN2Base = generateBitonicSortN2 (snatProxy Proxy) testVec16 :: Num a => Vec 16 a testVec16 = 9 :> 2 :> 8 :> 6 :> 3 :> 7 :> 0 :> 1 :> 4 :> 5 :> 2 :> 8 :> 6 :> 3 :> 7 :> 0 :> Nil testVec8 :: Num a => Vec 8 a testVec8 = 9 :> 2 :> 8 :> 6 :> 3 :> 7 :> 0 :> 1 :> Nil testVec4 :: Num a => Vec 4 a testVec4 = 9 :> 2 :> 8 :> 6 :> Nil testVec2 :: Num a => Vec 2 a testVec2 = 2 :> 9 :> Nil sorter16 :: (Ord a) => Vec 16 a -> Vec 16 a sorter16 = generateBitonicSortN2Base sorter8 :: (Ord a) => Vec 8 a -> Vec 8 a sorter8 = generateBitonicSortN2Base sorter4 ::forall a. (Ord a) => Vec 4 a -> Vec 4 a sorter4 = generateBitonicSortN2Base sorter2 :: forall a. (Ord a) => Vec 2 a -> Vec 2 a sorter2 = generateBitonicSortN2Base example16 :: Vec 16 Int example16 = sorter16 testVec16 example8 :: Vec 8 Int example8 = sorter8 testVec8 example4 :: Vec 4 Int example4 = sorter4 testVec4 example2 :: Vec 2 Int example2 = sorter2 testVec2
55571e0bee98685a66776c86add92594f1f5eaf3444b006e844a2299263250d2
xapi-project/xen-api
test_cpuid_helpers.ml
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) open Test_highlevel open Cpuid_helpers module StringOfFeatures = Generic.MakeStateless (struct module Io = struct type input_t = int64 array type output_t = string let string_of_input_t = Test_printers.(array int64) let string_of_output_t = Test_printers.string end let transform = Cpuid_helpers.string_of_features let tests = `QuickAndAutoDocumented [ ([|0L; 2L; 123L|], "00000000-00000002-0000007b") ; ([|0L|], "00000000") ; ([||], "") ] end) module FeaturesOfString = Generic.MakeStateless (struct module Io = struct type input_t = string type output_t = int64 array let string_of_input_t = Test_printers.string let string_of_output_t = Test_printers.(array int64) end let transform = Cpuid_helpers.features_of_string let tests = `QuickAndAutoDocumented [ ("00000000-00000002-0000007b", [|0L; 2L; 123L|]) ; ("00000000", [|0L|]) ; ("", [||]) ] end) module RoundTripFeaturesToFeatures = Generic.MakeStateless (struct module Io = struct type input_t = int64 array type output_t = int64 array let string_of_input_t = Test_printers.(array int64) let string_of_output_t = Test_printers.(array int64) end let transform x = x |> Cpuid_helpers.string_of_features |> Cpuid_helpers.features_of_string let tests = `QuickAndAutoDocumented (List.map (fun x -> (x, x)) [[|0L; 1L; 123L|]; [|1L|]; [|0L|]; [||]]) end) module RoundTripStringToString = Generic.MakeStateless (struct module Io = struct type input_t = string type output_t = string let string_of_input_t = Test_printers.string let string_of_output_t = Test_printers.string end let transform x = x |> Cpuid_helpers.features_of_string |> Cpuid_helpers.string_of_features let tests = `QuickAndAutoDocumented (List.map (fun x -> (x, x)) ["00000000-00000002-0000007b"; "00000001"; "00000000"; ""] ) end) module ParseFailure = Generic.MakeStateless (struct module Io = struct type input_t = string type output_t = exn let string_of_input_t = Test_printers.string let string_of_output_t = Test_printers.exn end exception NoExceptionRaised let transform x = try ignore (Cpuid_helpers.features_of_string x) ; raise NoExceptionRaised with e -> e let tests = `QuickAndAutoDocumented (List.map (fun x -> (x, InvalidFeatureString x)) ["foo bar baz"; "fgfg-1234"; "0123-foo"; "foo-0123"; "-1234"; "1234-"] ) end) module Extend = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = int64 array let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.(array int64) end let transform (arr0, arr1) = Cpuid_helpers.extend arr0 arr1 let tests = `QuickAndAutoDocumented [ (([||], [||]), [||]) ; (([||], [|0L; 2L|]), [|0L; 2L|]) ; (([|1L|], [||]), [||]) ; (([|1L|], [|0L|]), [|1L|]) ; (([|1L|], [|0L; 2L|]), [|1L; 2L|]) ; (([|1L; 0L|], [|0L; 2L|]), [|1L; 0L|]) ; (([|1L; 0L|], [|0L; 2L; 4L; 9L|]), [|1L; 0L; 4L; 9L|]) ] end) module ZeroExtend = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int type output_t = int64 array let string_of_input_t = Test_printers.(pair (array int64) int) let string_of_output_t = Test_printers.(array int64) end let transform (arr, len) = Cpuid_helpers.zero_extend arr len let tests = `QuickAndAutoDocumented [ (([|1L|], 2), [|1L; 0L|]) ; (([|1L|], 1), [|1L|]) ; (([||], 2), [|0L; 0L|]) ; (([||], 1), [|0L|]) ; (([||], 0), [||]) ; (([|1L; 2L|], 0), [||]) ; (([|1L; 2L|], 1), [|1L|]) ; (([|1L; 2L|], 2), [|1L; 2L|]) ] end) module Intersect = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = int64 array let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.(array int64) end let transform (a, b) = Cpuid_helpers.intersect a b let tests = `QuickAndAutoDocumented [ Intersect should follow monoid laws - identity and commutativity (([||], [||]), [||]) ; (([|1L; 2L; 3L|], [||]), [|1L; 2L; 3L|]) ; (([||], [|1L; 2L; 3L|]), [|1L; 2L; 3L|]) ; (([|7L; 3L|], [|5L|]), [|5L; 0L|]) ; (([|5L|], [|7L; 3L|]), [|5L; 0L|]) ; (([|1L|], [|1L|]), [|1L|]) ; (([|1L|], [|1L; 0L|]), [|1L; 0L|]) ; (([|1L; 2L; 3L|], [|1L; 1L; 1L|]), [|1L; 0L; 1L|]) ; (([|1L; 2L; 3L|], [|0L; 0L; 0L|]), [|0L; 0L; 0L|]) ; (([|0b00000000L|], [|0b11111111L|]), [|0b00000000L|]) ; (([|0b11111111L|], [|0b11111111L|]), [|0b11111111L|]) ; (([|0b01111111L|], [|0b11111111L|]), [|0b01111111L|]) ; (([|0b00000111L|], [|0b00001111L|]), [|0b00000111L|]) ; (([|0b00011111L|], [|0b00001111L|]), [|0b00001111L|]) ; ( ([|0b00000000L; 0b11111111L|], [|0b11111111L; 0b00000000L|]) , [|0b00000000L; 0b00000000L|] ) ; ( ([|0b11111111L; 0b01010101L|], [|0b11111111L; 0b01010101L|]) , [|0b11111111L; 0b01010101L|] ) ; ( ([|0b01111111L; 0b10000000L|], [|0b11111111L; 0b00000000L|]) , [|0b01111111L; 0b00000000L|] ) ; ( ([|0b00000111L; 0b11100000L|], [|0b00001111L; 0b11110000L|]) , [|0b00000111L; 0b11100000L|] ) ] end) module Equality = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = bool let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.bool end let transform (a, b) = Cpuid_helpers.(is_equal a b) let tests = `QuickAndAutoDocumented [ (([||], [||]), true) ; (([|1L; 2L; 3L|], [|1L; 2L; 3L|]), true) ; (([|1L; 2L; 3L|], [||]), false) ; (([||], [|1L; 2L; 3L|]), false) ; (([|7L; 0L|], [|7L|]), true) ; (([|7L|], [|7L; 0L|]), true) ; (([|7L; 1L; 0L|], [|7L; 1L|]), true) ; (([|7L; 1L|], [|7L; 1L|]), true) ; (([|7L; 1L|], [|7L|]), false) ; (([|7L|], [|7L; 1L|]), false) ; (([|1L; 7L|], [|7L; 1L|]), false) ] end) module Comparisons = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = bool * bool let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.(pair bool bool) end let transform (a, b) = Cpuid_helpers.(is_subset a b, is_strict_subset a b) let tests = `QuickAndAutoDocumented [ (* The following are counterintuitive, because intersection with the empty * set is treated as identity, and intersection is used in is_subset. * Since there are no empty feature sets in reality, these are artificial * scenarios. *) (([||], [||]), (true, false)) ; (([|1L; 2L; 3L|], [||]), (true, true)) ; (([||], [|1L; 2L; 3L|]), (false, false)) Note that feature flags are automatically zero - extended when compared . * These tests are relevant in upgrade scenarios , if new CPUID leaves are * introduced . * These tests are relevant in upgrade scenarios, if new CPUID leaves are * introduced. *) (([|7L; 3L|], [|5L|]), (false, false)) ; (([|5L|], [|7L; 3L|]), (true, true)) ; (([|1L|], [|1L|]), (true, false)) ; (([|1L|], [|1L; 0L|]), (true, false)) ; (([|1L; 0L|], [|1L|]), (true, false)) ; (* Below are the more common cases *) ( ( features_of_string "07cbfbff-04082201-20100800-00000001-00000000-00000000-00000000-00000000-00000000" , features_of_string "07c9cbf5-80082201-20100800-00000001-00000000-00000000-00000000-00000000-00000000" ) , (false, false) ) ; (([|0b00000000L|], [|0b11111111L|]), (true, true)) ; (([|0b11111111L|], [|0b11111111L|]), (true, false)) ; (([|0b01111111L|], [|0b11111111L|]), (true, true)) ; (([|0b00000111L|], [|0b00001111L|]), (true, true)) ; (([|0b00011111L|], [|0b00001111L|]), (false, false)) ; ( ([|0b00000000L; 0b11111111L|], [|0b11111111L; 0b00000000L|]) , (false, false) ) ; ( ([|0b11111111L; 0b01010101L|], [|0b11111111L; 0b01010101L|]) , (true, false) ) ; ( ([|0b01111111L; 0b10000000L|], [|0b11111111L; 0b00000000L|]) , (false, false) ) ; ( ([|0b00000111L; 0b11100000L|], [|0b00001111L; 0b11110000L|]) , (true, true) ) ] end) module Accessors = Generic.MakeStateless (struct module Io = struct type input_t = (string * string) list type output_t = string * int * int * int64 array * int64 array let string_of_input_t = Test_printers.(assoc_list string string) let string_of_output_t = Test_printers.(tuple5 string int int (array int64) (array int64)) end let transform record = let open Map_check in ( getf vendor record , getf socket_count record , getf cpu_count record , getf features_pv record , getf features_hvm record ) let tests = `QuickAndAutoDocumented [ ( [ ("vendor", "Intel") ; ("socket_count", "1") ; ("cpu_count", "1") ; ("features_pv", "00000001-00000002-00000003") ; ("features_hvm", "0000000a-0000000b-0000000c") ] , ("Intel", 1, 1, [|1L; 2L; 3L|], [|0xaL; 0xbL; 0xcL|]) ) ; ( [ ("vendor", "Amd") ; ("socket_count", "6") ; ("cpu_count", "24") ; ("features_pv", "00000001") ; ("features_hvm", "") ] , ("Amd", 6, 24, [|1L|], [||]) ) ] end) module Setters = Generic.MakeStateless (struct module Io = struct type input_t = string * int * int * int64 array * int64 array type output_t = (string * string) list let string_of_input_t = Test_printers.(tuple5 string int int (array int64) (array int64)) let string_of_output_t = Test_printers.(assoc_list string string) end let transform (name, sockets, cpus, pv, hvm) = let open Map_check in [] |> setf vendor name |> setf socket_count sockets |> setf cpu_count cpus |> setf features_pv pv |> setf features_hvm hvm |> List.sort compare let tests = `QuickAndAutoDocumented [ ( ("Intel", 1, 1, [|1L; 2L; 3L|], [|0xaL; 0xbL; 0xcL|]) , List.sort compare [ ("vendor", "Intel") ; ("socket_count", "1") ; ("cpu_count", "1") ; ("features_pv", "00000001-00000002-00000003") ; ("features_hvm", "0000000a-0000000b-0000000c") ] ) ; ( ("Amd", 6, 24, [|1L|], [||]) , List.sort compare [ ("vendor", "Amd") ; ("socket_count", "6") ; ("cpu_count", "24") ; ("features_pv", "00000001") ; ("features_hvm", "") ] ) ] end) module Modifiers = Generic.MakeStateless (struct module Io = struct type input_t = (string * string) list type output_t = (string * string) list let string_of_input_t = Test_printers.(assoc_list string string) let string_of_output_t = Test_printers.(assoc_list string string) end let transform record = let open Map_check in record |> setf vendor (getf vendor record) |> setf socket_count (getf socket_count record) |> setf cpu_count (getf cpu_count record) |> setf features_pv (getf features_pv record) |> setf features_hvm (getf features_hvm record) |> List.sort compare let tests = `QuickAndAutoDocumented [ ( [ ("cpu_count", "1") ; ("features_hvm", "0000000a-0000000b-0000000c") ; ("features_pv", "00000001-00000002-00000003") ; ("socket_count", "1") ; ("vendor", "Intel") ] , [ ("cpu_count", "1") ; ("features_hvm", "0000000a-0000000b-0000000c") ; ("features_pv", "00000001-00000002-00000003") ; ("socket_count", "1") ; ("vendor", "Intel") ] ) ] end) let domain_type : API.domain_type Test_printers.printer = Record_util.domain_type_to_string module NextBootCPUFeatures = Generic.MakeStateful (struct module Io = struct type input_t = (string * API.domain_type) list type output_t = string list let string_of_input_t = Test_printers.(list (pair string domain_type)) let string_of_output_t = Test_printers.(list string) end module State = Test_state.XapiDb let features_hvm = "feedface-feedface" let features_pv = "deadbeef-deadbeef" let load_input __context cases = let cpu_info = [ ("cpu_count", "1") ; ("socket_count", "1") ; ("vendor", "Abacus") ; ("features_pv", features_pv) ; ("features_hvm", features_hvm) ] in List.iter (fun self -> Db.Host.set_cpu_info ~__context ~self ~value:cpu_info) (Db.Host.get_all ~__context) ; Db.Pool.set_cpu_info ~__context ~self:(Db.Pool.get_all ~__context |> List.hd) ~value:cpu_info ; List.iter (fun (name_label, domain_type) -> ignore (Test_common.make_vm ~__context ~name_label ~domain_type ()) ) cases let extract_output __context vms = let get_flags (label, _) = let vm = List.hd (Db.VM.get_by_name_label ~__context ~label) in Cpuid_helpers.next_boot_cpu_features ~__context ~vm in List.map get_flags vms Tuples of ( ( features_hvm * features_pv ) list , ( expected last_boot_CPU_flags ) let tests = `QuickAndAutoDocumented [ ([("a", `hvm)], [features_hvm]) ; ([("a", `pv)], [features_pv]) ; ([("a", `pv_in_pvh)], [features_hvm]) ; ( [("a", `hvm); ("b", `pv); ("c", `pv_in_pvh)] , [features_hvm; features_pv; features_hvm] ) ] end) let string_of_unit_result = Fmt.(str "%a" Dump.(result ~ok:(any "()") ~error:exn)) module AssertVMIsCompatible = Generic.MakeStateful (struct module Io = struct type input_t = string * API.domain_type * (string * string) list type output_t = (unit, exn) result let string_of_input_t = Test_printers.(tuple3 string domain_type (assoc_list string string)) let string_of_output_t = string_of_unit_result end module State = Test_state.XapiDb let features_hvm_host = "feedface-feedface-feedface-feedface-feedface-00000000-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" let features_pv_host = "deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef" let features_hvm = "feedface-feedface-feedface-feedface-feedface-00000810-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" let features_pv = "deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef" let load_input __context (name_label, domain_type, last_boot_flags) = let cpu_info = [ ("cpu_count", "1") ; ("socket_count", "1") ; ("vendor", "Abacus") ; ("features_pv", features_pv) ; ("features_hvm", features_hvm) ; ("features_pv_host", features_pv_host) ; ("features_hvm_host", features_hvm_host) ] in List.iter (fun self -> Db.Host.set_cpu_info ~__context ~self ~value:cpu_info) (Db.Host.get_all ~__context) ; let cpu_info = List.filter (fun (k, _) -> not (Astring.String.is_suffix ~affix:"host" k)) cpu_info in Db.Pool.set_cpu_info ~__context ~self:(Db.Pool.get_all ~__context |> List.hd) ~value:cpu_info ; let self = Test_common.make_vm ~__context ~name_label ~domain_type () in Db.VM.set_last_boot_CPU_flags ~__context ~self ~value:last_boot_flags ; let metrics = Db.VM.get_metrics ~__context ~self in Db.VM_metrics.set_current_domain_type ~__context ~self:metrics ~value:domain_type ; Db.VM.set_power_state ~__context ~self ~value:`Running let extract_output __context (label, _, _) = let host = List.hd @@ Db.Host.get_all ~__context in let vm = List.hd (Db.VM.get_by_name_label ~__context ~label) in try Ok (Cpuid_helpers.assert_vm_is_compatible ~__context ~vm ~host ()) with Filter out opaquerefs which make matching this exception difficult | Api_errors.Server_error (vm_incompatible_with_this_host, data) -> Printexc.print_backtrace stderr ; Error (Api_errors.Server_error ( vm_incompatible_with_this_host , List.filter (fun s -> not @@ Astring.String.is_prefix ~affix:"OpaqueRef:" s) data ) ) | e -> Error e let tests = `QuickAndAutoDocumented [ HVM ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; (cpu_info_features_key, features_hvm) ] ) , Ok () ) ; ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe" ) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a CPU with features this host's CPU \ does not have." ] ) ) ) ; ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Napier's Bones") ; (cpu_info_features_key, features_hvm) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a host which had a CPU from a different \ vendor." ] ) ) ) ; (* PV *) ( ( "a" , `pv , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; (cpu_info_features_key, features_pv) ] ) , Ok () ) ; ( ( "a" , `pv , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe" ) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a CPU with features this host's CPU \ does not have." ] ) ) ) ; ( ( "a" , `pv , Xapi_globs. [ (cpu_info_vendor_key, "Napier's Bones") ; (cpu_info_features_key, features_pv) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a host which had a CPU from a different \ vendor." ] ) ) ) ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "feedface-feedface-feedface-feedface-feedface-00000810-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" ) ] ) , Ok () ) ; ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "feedface-feedface-feedface-feedface-feedface-00000811-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" ) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a CPU with features this host's CPU \ does not have." ] ) ) ) ] end) let tests = make_suite "cpuid_helpers_" [ ("string_of_features", StringOfFeatures.tests) ; ("features_of_string", FeaturesOfString.tests) ; ("roundtrip_features_to_features", RoundTripFeaturesToFeatures.tests) ; ("roundtrip_string_to_features", RoundTripStringToString.tests) ; ("parse_failure", ParseFailure.tests) ; ("extend", Extend.tests) ; ("zero_extend", ZeroExtend.tests) ; ("intersect", Intersect.tests) ; ("equality", Equality.tests) ; ("comparisons", Comparisons.tests) ; ("accessors", Accessors.tests) ; ("setters", Setters.tests) ; ("modifiers", Modifiers.tests) ; ("next_boot_cpu_features", NextBootCPUFeatures.tests) ; ("test_assert_vm_is_compatible", AssertVMIsCompatible.tests) ]
null
https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/tests/test_cpuid_helpers.ml
ocaml
The following are counterintuitive, because intersection with the empty * set is treated as identity, and intersection is used in is_subset. * Since there are no empty feature sets in reality, these are artificial * scenarios. Below are the more common cases PV
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) open Test_highlevel open Cpuid_helpers module StringOfFeatures = Generic.MakeStateless (struct module Io = struct type input_t = int64 array type output_t = string let string_of_input_t = Test_printers.(array int64) let string_of_output_t = Test_printers.string end let transform = Cpuid_helpers.string_of_features let tests = `QuickAndAutoDocumented [ ([|0L; 2L; 123L|], "00000000-00000002-0000007b") ; ([|0L|], "00000000") ; ([||], "") ] end) module FeaturesOfString = Generic.MakeStateless (struct module Io = struct type input_t = string type output_t = int64 array let string_of_input_t = Test_printers.string let string_of_output_t = Test_printers.(array int64) end let transform = Cpuid_helpers.features_of_string let tests = `QuickAndAutoDocumented [ ("00000000-00000002-0000007b", [|0L; 2L; 123L|]) ; ("00000000", [|0L|]) ; ("", [||]) ] end) module RoundTripFeaturesToFeatures = Generic.MakeStateless (struct module Io = struct type input_t = int64 array type output_t = int64 array let string_of_input_t = Test_printers.(array int64) let string_of_output_t = Test_printers.(array int64) end let transform x = x |> Cpuid_helpers.string_of_features |> Cpuid_helpers.features_of_string let tests = `QuickAndAutoDocumented (List.map (fun x -> (x, x)) [[|0L; 1L; 123L|]; [|1L|]; [|0L|]; [||]]) end) module RoundTripStringToString = Generic.MakeStateless (struct module Io = struct type input_t = string type output_t = string let string_of_input_t = Test_printers.string let string_of_output_t = Test_printers.string end let transform x = x |> Cpuid_helpers.features_of_string |> Cpuid_helpers.string_of_features let tests = `QuickAndAutoDocumented (List.map (fun x -> (x, x)) ["00000000-00000002-0000007b"; "00000001"; "00000000"; ""] ) end) module ParseFailure = Generic.MakeStateless (struct module Io = struct type input_t = string type output_t = exn let string_of_input_t = Test_printers.string let string_of_output_t = Test_printers.exn end exception NoExceptionRaised let transform x = try ignore (Cpuid_helpers.features_of_string x) ; raise NoExceptionRaised with e -> e let tests = `QuickAndAutoDocumented (List.map (fun x -> (x, InvalidFeatureString x)) ["foo bar baz"; "fgfg-1234"; "0123-foo"; "foo-0123"; "-1234"; "1234-"] ) end) module Extend = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = int64 array let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.(array int64) end let transform (arr0, arr1) = Cpuid_helpers.extend arr0 arr1 let tests = `QuickAndAutoDocumented [ (([||], [||]), [||]) ; (([||], [|0L; 2L|]), [|0L; 2L|]) ; (([|1L|], [||]), [||]) ; (([|1L|], [|0L|]), [|1L|]) ; (([|1L|], [|0L; 2L|]), [|1L; 2L|]) ; (([|1L; 0L|], [|0L; 2L|]), [|1L; 0L|]) ; (([|1L; 0L|], [|0L; 2L; 4L; 9L|]), [|1L; 0L; 4L; 9L|]) ] end) module ZeroExtend = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int type output_t = int64 array let string_of_input_t = Test_printers.(pair (array int64) int) let string_of_output_t = Test_printers.(array int64) end let transform (arr, len) = Cpuid_helpers.zero_extend arr len let tests = `QuickAndAutoDocumented [ (([|1L|], 2), [|1L; 0L|]) ; (([|1L|], 1), [|1L|]) ; (([||], 2), [|0L; 0L|]) ; (([||], 1), [|0L|]) ; (([||], 0), [||]) ; (([|1L; 2L|], 0), [||]) ; (([|1L; 2L|], 1), [|1L|]) ; (([|1L; 2L|], 2), [|1L; 2L|]) ] end) module Intersect = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = int64 array let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.(array int64) end let transform (a, b) = Cpuid_helpers.intersect a b let tests = `QuickAndAutoDocumented [ Intersect should follow monoid laws - identity and commutativity (([||], [||]), [||]) ; (([|1L; 2L; 3L|], [||]), [|1L; 2L; 3L|]) ; (([||], [|1L; 2L; 3L|]), [|1L; 2L; 3L|]) ; (([|7L; 3L|], [|5L|]), [|5L; 0L|]) ; (([|5L|], [|7L; 3L|]), [|5L; 0L|]) ; (([|1L|], [|1L|]), [|1L|]) ; (([|1L|], [|1L; 0L|]), [|1L; 0L|]) ; (([|1L; 2L; 3L|], [|1L; 1L; 1L|]), [|1L; 0L; 1L|]) ; (([|1L; 2L; 3L|], [|0L; 0L; 0L|]), [|0L; 0L; 0L|]) ; (([|0b00000000L|], [|0b11111111L|]), [|0b00000000L|]) ; (([|0b11111111L|], [|0b11111111L|]), [|0b11111111L|]) ; (([|0b01111111L|], [|0b11111111L|]), [|0b01111111L|]) ; (([|0b00000111L|], [|0b00001111L|]), [|0b00000111L|]) ; (([|0b00011111L|], [|0b00001111L|]), [|0b00001111L|]) ; ( ([|0b00000000L; 0b11111111L|], [|0b11111111L; 0b00000000L|]) , [|0b00000000L; 0b00000000L|] ) ; ( ([|0b11111111L; 0b01010101L|], [|0b11111111L; 0b01010101L|]) , [|0b11111111L; 0b01010101L|] ) ; ( ([|0b01111111L; 0b10000000L|], [|0b11111111L; 0b00000000L|]) , [|0b01111111L; 0b00000000L|] ) ; ( ([|0b00000111L; 0b11100000L|], [|0b00001111L; 0b11110000L|]) , [|0b00000111L; 0b11100000L|] ) ] end) module Equality = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = bool let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.bool end let transform (a, b) = Cpuid_helpers.(is_equal a b) let tests = `QuickAndAutoDocumented [ (([||], [||]), true) ; (([|1L; 2L; 3L|], [|1L; 2L; 3L|]), true) ; (([|1L; 2L; 3L|], [||]), false) ; (([||], [|1L; 2L; 3L|]), false) ; (([|7L; 0L|], [|7L|]), true) ; (([|7L|], [|7L; 0L|]), true) ; (([|7L; 1L; 0L|], [|7L; 1L|]), true) ; (([|7L; 1L|], [|7L; 1L|]), true) ; (([|7L; 1L|], [|7L|]), false) ; (([|7L|], [|7L; 1L|]), false) ; (([|1L; 7L|], [|7L; 1L|]), false) ] end) module Comparisons = Generic.MakeStateless (struct module Io = struct type input_t = int64 array * int64 array type output_t = bool * bool let string_of_input_t = Test_printers.(pair (array int64) (array int64)) let string_of_output_t = Test_printers.(pair bool bool) end let transform (a, b) = Cpuid_helpers.(is_subset a b, is_strict_subset a b) let tests = `QuickAndAutoDocumented [ (([||], [||]), (true, false)) ; (([|1L; 2L; 3L|], [||]), (true, true)) ; (([||], [|1L; 2L; 3L|]), (false, false)) Note that feature flags are automatically zero - extended when compared . * These tests are relevant in upgrade scenarios , if new CPUID leaves are * introduced . * These tests are relevant in upgrade scenarios, if new CPUID leaves are * introduced. *) (([|7L; 3L|], [|5L|]), (false, false)) ; (([|5L|], [|7L; 3L|]), (true, true)) ; (([|1L|], [|1L|]), (true, false)) ; (([|1L|], [|1L; 0L|]), (true, false)) ; (([|1L; 0L|], [|1L|]), (true, false)) ( ( features_of_string "07cbfbff-04082201-20100800-00000001-00000000-00000000-00000000-00000000-00000000" , features_of_string "07c9cbf5-80082201-20100800-00000001-00000000-00000000-00000000-00000000-00000000" ) , (false, false) ) ; (([|0b00000000L|], [|0b11111111L|]), (true, true)) ; (([|0b11111111L|], [|0b11111111L|]), (true, false)) ; (([|0b01111111L|], [|0b11111111L|]), (true, true)) ; (([|0b00000111L|], [|0b00001111L|]), (true, true)) ; (([|0b00011111L|], [|0b00001111L|]), (false, false)) ; ( ([|0b00000000L; 0b11111111L|], [|0b11111111L; 0b00000000L|]) , (false, false) ) ; ( ([|0b11111111L; 0b01010101L|], [|0b11111111L; 0b01010101L|]) , (true, false) ) ; ( ([|0b01111111L; 0b10000000L|], [|0b11111111L; 0b00000000L|]) , (false, false) ) ; ( ([|0b00000111L; 0b11100000L|], [|0b00001111L; 0b11110000L|]) , (true, true) ) ] end) module Accessors = Generic.MakeStateless (struct module Io = struct type input_t = (string * string) list type output_t = string * int * int * int64 array * int64 array let string_of_input_t = Test_printers.(assoc_list string string) let string_of_output_t = Test_printers.(tuple5 string int int (array int64) (array int64)) end let transform record = let open Map_check in ( getf vendor record , getf socket_count record , getf cpu_count record , getf features_pv record , getf features_hvm record ) let tests = `QuickAndAutoDocumented [ ( [ ("vendor", "Intel") ; ("socket_count", "1") ; ("cpu_count", "1") ; ("features_pv", "00000001-00000002-00000003") ; ("features_hvm", "0000000a-0000000b-0000000c") ] , ("Intel", 1, 1, [|1L; 2L; 3L|], [|0xaL; 0xbL; 0xcL|]) ) ; ( [ ("vendor", "Amd") ; ("socket_count", "6") ; ("cpu_count", "24") ; ("features_pv", "00000001") ; ("features_hvm", "") ] , ("Amd", 6, 24, [|1L|], [||]) ) ] end) module Setters = Generic.MakeStateless (struct module Io = struct type input_t = string * int * int * int64 array * int64 array type output_t = (string * string) list let string_of_input_t = Test_printers.(tuple5 string int int (array int64) (array int64)) let string_of_output_t = Test_printers.(assoc_list string string) end let transform (name, sockets, cpus, pv, hvm) = let open Map_check in [] |> setf vendor name |> setf socket_count sockets |> setf cpu_count cpus |> setf features_pv pv |> setf features_hvm hvm |> List.sort compare let tests = `QuickAndAutoDocumented [ ( ("Intel", 1, 1, [|1L; 2L; 3L|], [|0xaL; 0xbL; 0xcL|]) , List.sort compare [ ("vendor", "Intel") ; ("socket_count", "1") ; ("cpu_count", "1") ; ("features_pv", "00000001-00000002-00000003") ; ("features_hvm", "0000000a-0000000b-0000000c") ] ) ; ( ("Amd", 6, 24, [|1L|], [||]) , List.sort compare [ ("vendor", "Amd") ; ("socket_count", "6") ; ("cpu_count", "24") ; ("features_pv", "00000001") ; ("features_hvm", "") ] ) ] end) module Modifiers = Generic.MakeStateless (struct module Io = struct type input_t = (string * string) list type output_t = (string * string) list let string_of_input_t = Test_printers.(assoc_list string string) let string_of_output_t = Test_printers.(assoc_list string string) end let transform record = let open Map_check in record |> setf vendor (getf vendor record) |> setf socket_count (getf socket_count record) |> setf cpu_count (getf cpu_count record) |> setf features_pv (getf features_pv record) |> setf features_hvm (getf features_hvm record) |> List.sort compare let tests = `QuickAndAutoDocumented [ ( [ ("cpu_count", "1") ; ("features_hvm", "0000000a-0000000b-0000000c") ; ("features_pv", "00000001-00000002-00000003") ; ("socket_count", "1") ; ("vendor", "Intel") ] , [ ("cpu_count", "1") ; ("features_hvm", "0000000a-0000000b-0000000c") ; ("features_pv", "00000001-00000002-00000003") ; ("socket_count", "1") ; ("vendor", "Intel") ] ) ] end) let domain_type : API.domain_type Test_printers.printer = Record_util.domain_type_to_string module NextBootCPUFeatures = Generic.MakeStateful (struct module Io = struct type input_t = (string * API.domain_type) list type output_t = string list let string_of_input_t = Test_printers.(list (pair string domain_type)) let string_of_output_t = Test_printers.(list string) end module State = Test_state.XapiDb let features_hvm = "feedface-feedface" let features_pv = "deadbeef-deadbeef" let load_input __context cases = let cpu_info = [ ("cpu_count", "1") ; ("socket_count", "1") ; ("vendor", "Abacus") ; ("features_pv", features_pv) ; ("features_hvm", features_hvm) ] in List.iter (fun self -> Db.Host.set_cpu_info ~__context ~self ~value:cpu_info) (Db.Host.get_all ~__context) ; Db.Pool.set_cpu_info ~__context ~self:(Db.Pool.get_all ~__context |> List.hd) ~value:cpu_info ; List.iter (fun (name_label, domain_type) -> ignore (Test_common.make_vm ~__context ~name_label ~domain_type ()) ) cases let extract_output __context vms = let get_flags (label, _) = let vm = List.hd (Db.VM.get_by_name_label ~__context ~label) in Cpuid_helpers.next_boot_cpu_features ~__context ~vm in List.map get_flags vms Tuples of ( ( features_hvm * features_pv ) list , ( expected last_boot_CPU_flags ) let tests = `QuickAndAutoDocumented [ ([("a", `hvm)], [features_hvm]) ; ([("a", `pv)], [features_pv]) ; ([("a", `pv_in_pvh)], [features_hvm]) ; ( [("a", `hvm); ("b", `pv); ("c", `pv_in_pvh)] , [features_hvm; features_pv; features_hvm] ) ] end) let string_of_unit_result = Fmt.(str "%a" Dump.(result ~ok:(any "()") ~error:exn)) module AssertVMIsCompatible = Generic.MakeStateful (struct module Io = struct type input_t = string * API.domain_type * (string * string) list type output_t = (unit, exn) result let string_of_input_t = Test_printers.(tuple3 string domain_type (assoc_list string string)) let string_of_output_t = string_of_unit_result end module State = Test_state.XapiDb let features_hvm_host = "feedface-feedface-feedface-feedface-feedface-00000000-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" let features_pv_host = "deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef" let features_hvm = "feedface-feedface-feedface-feedface-feedface-00000810-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" let features_pv = "deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef" let load_input __context (name_label, domain_type, last_boot_flags) = let cpu_info = [ ("cpu_count", "1") ; ("socket_count", "1") ; ("vendor", "Abacus") ; ("features_pv", features_pv) ; ("features_hvm", features_hvm) ; ("features_pv_host", features_pv_host) ; ("features_hvm_host", features_hvm_host) ] in List.iter (fun self -> Db.Host.set_cpu_info ~__context ~self ~value:cpu_info) (Db.Host.get_all ~__context) ; let cpu_info = List.filter (fun (k, _) -> not (Astring.String.is_suffix ~affix:"host" k)) cpu_info in Db.Pool.set_cpu_info ~__context ~self:(Db.Pool.get_all ~__context |> List.hd) ~value:cpu_info ; let self = Test_common.make_vm ~__context ~name_label ~domain_type () in Db.VM.set_last_boot_CPU_flags ~__context ~self ~value:last_boot_flags ; let metrics = Db.VM.get_metrics ~__context ~self in Db.VM_metrics.set_current_domain_type ~__context ~self:metrics ~value:domain_type ; Db.VM.set_power_state ~__context ~self ~value:`Running let extract_output __context (label, _, _) = let host = List.hd @@ Db.Host.get_all ~__context in let vm = List.hd (Db.VM.get_by_name_label ~__context ~label) in try Ok (Cpuid_helpers.assert_vm_is_compatible ~__context ~vm ~host ()) with Filter out opaquerefs which make matching this exception difficult | Api_errors.Server_error (vm_incompatible_with_this_host, data) -> Printexc.print_backtrace stderr ; Error (Api_errors.Server_error ( vm_incompatible_with_this_host , List.filter (fun s -> not @@ Astring.String.is_prefix ~affix:"OpaqueRef:" s) data ) ) | e -> Error e let tests = `QuickAndAutoDocumented [ HVM ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; (cpu_info_features_key, features_hvm) ] ) , Ok () ) ; ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe" ) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a CPU with features this host's CPU \ does not have." ] ) ) ) ; ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Napier's Bones") ; (cpu_info_features_key, features_hvm) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a host which had a CPU from a different \ vendor." ] ) ) ) ( ( "a" , `pv , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; (cpu_info_features_key, features_pv) ] ) , Ok () ) ; ( ( "a" , `pv , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe-cafecafe" ) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a CPU with features this host's CPU \ does not have." ] ) ) ) ; ( ( "a" , `pv , Xapi_globs. [ (cpu_info_vendor_key, "Napier's Bones") ; (cpu_info_features_key, features_pv) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a host which had a CPU from a different \ vendor." ] ) ) ) ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "feedface-feedface-feedface-feedface-feedface-00000810-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" ) ] ) , Ok () ) ; ( ( "a" , `hvm , Xapi_globs. [ (cpu_info_vendor_key, "Abacus") ; ( cpu_info_features_key , "feedface-feedface-feedface-feedface-feedface-00000811-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface-feedface" ) ] ) , Error Api_errors.( Server_error ( vm_incompatible_with_this_host , [ "VM last booted on a CPU with features this host's CPU \ does not have." ] ) ) ) ] end) let tests = make_suite "cpuid_helpers_" [ ("string_of_features", StringOfFeatures.tests) ; ("features_of_string", FeaturesOfString.tests) ; ("roundtrip_features_to_features", RoundTripFeaturesToFeatures.tests) ; ("roundtrip_string_to_features", RoundTripStringToString.tests) ; ("parse_failure", ParseFailure.tests) ; ("extend", Extend.tests) ; ("zero_extend", ZeroExtend.tests) ; ("intersect", Intersect.tests) ; ("equality", Equality.tests) ; ("comparisons", Comparisons.tests) ; ("accessors", Accessors.tests) ; ("setters", Setters.tests) ; ("modifiers", Modifiers.tests) ; ("next_boot_cpu_features", NextBootCPUFeatures.tests) ; ("test_assert_vm_is_compatible", AssertVMIsCompatible.tests) ]
54300db256eda6828a4737175505e981b5a79d2200e13a53bbd551beed6e3d39
fractalide/fractalide
trigger.rkt
#lang racket (require fractalide/modules/rkt/rkt-fbp/agent fractalide/modules/rkt/rkt-fbp/def) (require/edge ${cardano-wallet.wcreate}) (define-agent #:input '("data" "trigger") #:output '("out" "msg") (define msg (recv (input "data"))) (define text "") (send (output "msg") (cons 'init (list (cons 'label text)))) (recv (input "trigger")) (send (output "out") msg) )
null
https://raw.githubusercontent.com/fractalide/fractalide/9c54ec2615fcc2a1f3363292d4eed2a0fcb9c3a5/modules/rkt/rkt-fbp/agents/cardano-wallet/wcreate/trigger.rkt
racket
#lang racket (require fractalide/modules/rkt/rkt-fbp/agent fractalide/modules/rkt/rkt-fbp/def) (require/edge ${cardano-wallet.wcreate}) (define-agent #:input '("data" "trigger") #:output '("out" "msg") (define msg (recv (input "data"))) (define text "") (send (output "msg") (cons 'init (list (cons 'label text)))) (recv (input "trigger")) (send (output "out") msg) )
4e733d6b4808e14c802d0e4d14aedb0e22f9ac1d31daeae941ee1a1b10cebd66
digital-asset/ghc
unboxedsums9.hs
# LANGUAGE UnboxedSums , UnboxedTuples , MagicHash # module Main where type UbxBool = (# (# #) | (# #) #) # NOINLINE packBool # packBool :: UbxBool -> Bool packBool (# _ | #) = True packBool (# | _ #) = False # NOINLINE unpackBool # unpackBool :: Bool -> UbxBool unpackBool True = (# (# #) | #) unpackBool False = (# | (# #) #) {-# NOINLINE showUbxBool #-} showUbxBool :: UbxBool -> String showUbxBool b = show (packBool b) main :: IO () main = do putStrLn (showUbxBool (unpackBool True)) putStrLn (showUbxBool (unpackBool False)) putStrLn (show (packBool (# (# #) | #))) putStrLn (show (packBool (# | (# #) #)))
null
https://raw.githubusercontent.com/digital-asset/ghc/323dc6fcb127f77c08423873efc0a088c071440a/testsuite/tests/unboxedsums/unboxedsums9.hs
haskell
# NOINLINE showUbxBool #
# LANGUAGE UnboxedSums , UnboxedTuples , MagicHash # module Main where type UbxBool = (# (# #) | (# #) #) # NOINLINE packBool # packBool :: UbxBool -> Bool packBool (# _ | #) = True packBool (# | _ #) = False # NOINLINE unpackBool # unpackBool :: Bool -> UbxBool unpackBool True = (# (# #) | #) unpackBool False = (# | (# #) #) showUbxBool :: UbxBool -> String showUbxBool b = show (packBool b) main :: IO () main = do putStrLn (showUbxBool (unpackBool True)) putStrLn (showUbxBool (unpackBool False)) putStrLn (show (packBool (# (# #) | #))) putStrLn (show (packBool (# | (# #) #)))
7eb4a50adb222ead33da2efa22cac8a7311763d25aa5debf53177e8474fc5932
xsc/claro
assertion.clj
(ns claro.resolution-with-batching.assertion (:require [claro.resolution-with-batching [muse :as muse] [urania :as urania] [claro :as claro]])) (let [fs {:muse muse/fetch-with-muse! :urania urania/fetch-with-urania! :claro claro/fetch-with-claro! :claro-and-projection claro/fetch-with-claro-and-projection!} results (->> (map (juxt key #((val %) 1)) fs) (partition-by second) (map #(map first %)))] (assert (= (count results) 1) (str "resolution returned different results. groups: " (pr-str results))))
null
https://raw.githubusercontent.com/xsc/claro/16db75b7a775a14f3b656362e8ee4f65dd8b0d49/benchmarks/claro/resolution_with_batching/assertion.clj
clojure
(ns claro.resolution-with-batching.assertion (:require [claro.resolution-with-batching [muse :as muse] [urania :as urania] [claro :as claro]])) (let [fs {:muse muse/fetch-with-muse! :urania urania/fetch-with-urania! :claro claro/fetch-with-claro! :claro-and-projection claro/fetch-with-claro-and-projection!} results (->> (map (juxt key #((val %) 1)) fs) (partition-by second) (map #(map first %)))] (assert (= (count results) 1) (str "resolution returned different results. groups: " (pr-str results))))
51070319f03844cf48ba6d8226f24e37b989af0046891ffb8998e4a75dc9e82c
argp/bap
batMap.mli
* BatMap - Additional map operations * Copyright ( C ) 1996 2009 , LIFO , Universite d'Orleans * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * BatMap - Additional map operations * Copyright (C) 1996 Xavier Leroy * 2009 David Rajchenbach-Teller, LIFO, Universite d'Orleans * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) * Association tables over ordered types . This module implements applicative association tables , also known as finite maps or dictionaries , given a total ordering function over the keys . All operations over maps are purely applicative ( no side - effects ) . The implementation uses balanced binary trees , and therefore searching and insertion take time logarithmic in the size of the map . { b Note } OCaml , Batteries Included , provides two implementations of maps : polymorphic maps and functorized maps . Functorized maps ( see { ! S } and { ! Make } ) are slightly more complex to use but offer stronger type - safety . Polymorphic maps make it easier to shoot yourself in the foot . In case of doubt , you should use functorized maps . { 4 Functorized maps } The important part is the { ! Make } module which builds association maps from a user - provided datatype and comparison function . In the { ! Make } module ( or its output signature { ! S } ) are documentated all functions available on maps . Here is a typical example of use : { [ module MyKeyType = struct type t = my_type let compare = my_compare_function end module = Map . Make(MyKeyType ) let some_map = MyMap.add something MyMap.empty ... ] } You can also use predefined maps such as { ! IntMap } for maps with integer keys . @author ( Base library ) @author @author @author @author This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. {b Note} OCaml, Batteries Included, provides two implementations of maps: polymorphic maps and functorized maps. Functorized maps (see {!S} and {!Make}) are slightly more complex to use but offer stronger type-safety. Polymorphic maps make it easier to shoot yourself in the foot. In case of doubt, you should use functorized maps. {4 Functorized maps} The important part is the {!Make} module which builds association maps from a user-provided datatype and comparison function. In the {!Make} module (or its output signature {!S}) are documentated all functions available on maps. Here is a typical example of use: {[ module MyKeyType = struct type t = my_type let compare = my_compare_function end module MyMap = Map.Make(MyKeyType) let some_map = MyMap.add something MyMap.empty ... ]} You can also use predefined maps such as {!IntMap} for maps with integer keys. @author Xavier Leroy (Base library) @author Nicolas Cannasse @author Markus Mottl @author David Rajchenbach-Teller @author Gabriel Scherer *) module type S = sig type key (** The type of the map keys. *) type (+'a) t (** The type of maps from type [key] to type ['a]. *) val empty: 'a t (** The empty map. *) val is_empty: 'a t -> bool (** Test whether a map is empty or not. *) val cardinal: 'a t -> int (** Return the number of bindings of a map. *) val add: key -> 'a -> 'a t -> 'a t (** [add x y m] returns a map containing the same bindings as [m], plus a binding of [x] to [y]. If [x] was already bound in [m], its previous binding disappears. *) val find: key -> 'a t -> 'a (** [find x m] returns the current binding of [x] in [m], or raises [Not_found] if no such binding exists. *) val remove: key -> 'a t -> 'a t (** [remove x m] returns a map containing the same bindings as [m], except for [x] which is unbound in the returned map. *) val modify: key -> ('a -> 'a) -> 'a t -> 'a t (** [modify k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [Not_found] is raised. @since 1.2.0 @raise Not_found if [k] is unbound in [m] (or [f] raises [Not_found]) *) val modify_def: 'a -> key -> ('a -> 'a) -> 'a t -> 'a t (** [modify_def v0 k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [f v0] is inserted (as if the value found were [v0]). @since 1.3.0 *) val modify_opt: key -> ('a option -> 'a option) -> 'a t -> 'a t * [ modify_opt k f m ] allows to modify the binding for [ k ] in [ m ] or absence thereof . @since 2.1 or absence thereof. @since 2.1 *) val extract : key -> 'a t -> 'a * 'a t * [ extract k m ] removes the current binding of [ k ] from [ m ] , returning the value [ k ] was bound to and the updated [ m ] . @since 1.4.0 returning the value [k] was bound to and the updated [m]. @since 1.4.0 *) val pop : 'a t -> (key * 'a) * 'a t * [ pop m ] returns a binding from [ m ] and [ m ] without that binding . @raise Not_found if [ m ] is empty @since 1.4.0 binding. @raise Not_found if [m] is empty @since 1.4.0 *) val mem: key -> 'a t -> bool (** [mem x m] returns [true] if [m] contains a binding for [x], and [false] otherwise. *) val iter: (key -> 'a -> unit) -> 'a t -> unit * [ iter f m ] applies [ f ] to all bindings in map [ m ] . [ f ] receives the key as first argument , and the associated value as second argument . The bindings are passed to [ f ] in increasing order with respect to the ordering over the type of the keys . Only current bindings are presented to [ f ] : bindings hidden by more recent bindings are not passed to [ f ] . [f] receives the key as first argument, and the associated value as second argument. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. Only current bindings are presented to [f]: bindings hidden by more recent bindings are not passed to [f]. *) val map: ('a -> 'b) -> 'a t -> 'b t (** [map f m] returns a map with same domain as [m], where the associated value [a] of all bindings of [m] has been replaced by the result of the application of [f] to [a]. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *) val mapi: (key -> 'a -> 'b) -> 'a t -> 'b t (** Same as {!Map.S.map}, but the function receives as arguments both the key and the associated value for each binding of the map. *) val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b (** [fold f m a] computes [(f kN dN ... (f k1 d1 (f k0 d0 a))...)], where [k0,k1..kN] are the keys of all bindings in [m] (in increasing order), and [d1 ... dN] are the associated data. *) val filterv: ('a -> bool) -> 'a t -> 'a t (**[filterv f m] returns a map where only the values [a] of [m] such that [f a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *) val filter: (key -> 'a -> bool) -> 'a t -> 'a t (**[filter f m] returns a map where only the key, values pairs [key], [a] of [m] such that [f key a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *) val filter_map: (key -> 'a -> 'b option) -> 'a t -> 'b t (** [filter_map f m] combines the features of [filter] and [map]. It calls calls [f key0 a0], [f key1 a1], [f keyn an] where [a0,a1..an] are the elements of [m] and [key0..keyn] the respective corresponding keys. It returns the map of pairs [keyi],[bi] such as [f keyi ai = Some bi] (when [f] returns [None], the corresponding element of [m] is discarded). *) val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int * Total ordering between maps . The first argument is a total ordering used to compare data associated with equal keys in the two maps . used to compare data associated with equal keys in the two maps. *) val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool * [ equal cmp ] tests whether the maps [ m1 ] and [ m2 ] are equal , that is , contain equal keys and associate them with equal data . [ cmp ] is the equality predicate used to compare the data associated with the keys . equal, that is, contain equal keys and associate them with equal data. [cmp] is the equality predicate used to compare the data associated with the keys. *) val keys : _ t -> key BatEnum.t (** Return an enumeration of all the keys of a map.*) val values: 'a t -> 'a BatEnum.t (** Return an enumeration of al the values of a map.*) val min_binding : 'a t -> (key * 'a) (** return the ([key,value]) pair with the smallest key *) val max_binding : 'a t -> (key * 'a) (** return the [(key,value)] pair with the largest key *) (* The following documentations comments are from stdlib's map.mli: - choose - split - singleton - partition *) val choose : 'a t -> (key * 'a) * Return one binding of the given map , or raise [ Not_found ] if the map is empty . Which binding is chosen is unspecified , but equal bindings will be chosen for equal maps . the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. *) val split : key -> 'a t -> ('a t * 'a option * 'a t) (** [split x m] returns a triple [(l, data, r)], where [l] is the map with all the bindings of [m] whose key is strictly less than [x]; [r] is the map with all the bindings of [m] whose key is strictly greater than [x]; [data] is [None] if [m] contains no binding for [x], or [Some v] if [m] binds [v] to [x]. *) val partition: (key -> 'a -> bool) -> 'a t -> 'a t * 'a t * [ partition p m ] returns a pair of maps [ ( m1 , m2 ) ] , where [ m1 ] contains all the bindings of [ s ] that satisfy the predicate [ p ] , and [ m2 ] is the map with all the bindings of [ s ] that do not satisfy [ p ] . @since 1.4.0 [m1] contains all the bindings of [s] that satisfy the predicate [p], and [m2] is the map with all the bindings of [s] that do not satisfy [p]. @since 1.4.0 *) val singleton: key -> 'a -> 'a t * [ singleton x y ] returns the one - element map that contains a binding [ y ] for [ x ] . for [x]. *) val bindings : 'a t -> (key * 'a) list * Return the list of all bindings of the given map . The returned list is sorted in increasing key order . Added for compatibility with stdlib 3.12 The returned list is sorted in increasing key order. Added for compatibility with stdlib 3.12 *) val enum : 'a t -> (key * 'a) BatEnum.t * Return an enumeration of ( key , value ) pairs of a map . The returned enumeration is sorted in increasing order with respect to the ordering [ Ord.compare ] , where [ ] is the argument given to { ! Map . Make } . The returned enumeration is sorted in increasing order with respect to the ordering [Ord.compare], where [Ord] is the argument given to {!Map.Make}. *) val backwards : 'a t -> (key * 'a) BatEnum.t * Return an enumeration of ( key , value ) pairs of a map . The returned enumeration is sorted in decreasing order with respect to the ordering [ Ord.compare ] , where [ ] is the argument given to { ! Map . Make } . The returned enumeration is sorted in decreasing order with respect to the ordering [Ord.compare], where [Ord] is the argument given to {!Map.Make}. *) val of_enum: (key * 'a) BatEnum.t -> 'a t (** Create a map from a (key, value) enumeration. *) val for_all: (key -> 'a -> bool) -> 'a t -> bool (** [for_all p m] checks if all the bindings of the map satisfy the predicate [p]. *) val exists: (key -> 'a -> bool) -> 'a t -> bool * [ exists p m ] checks if at least one binding of the map satisfy the predicate [ p ] . satisfy the predicate [p]. *) val merge: (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t (** [merge f m1 m2] computes a map whose keys is a subset of keys of [m1] and of [m2]. The presence of each such binding, and the corresponding value, is determined with the function [f]. *) (** {6 Boilerplate code}*) * { 7 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ?kvsep:string -> ('a BatInnerIO.output -> key -> unit) -> ('a BatInnerIO.output -> 'c -> unit) -> 'a BatInnerIO.output -> 'c t -> unit (** Output signature of the functor {!Map.Make}. *) * { 6 Override modules } (** The following modules replace functions defined in {!Map} with functions behaving slightly differently but having the same name. This is by design: the functions meant to override the corresponding functions of {!Map}. *) (** Operations on {!Map} without exceptions.*) module Exceptionless : sig val find: key -> 'a t -> 'a option end (** Infix operators over a {!BatMap} *) module Infix : sig val (-->) : 'a t -> key -> 'a (** [map-->key] returns the current binding of [key] in [map], or raises [Not_found]. Equivalent to [find key map]. *) val (<--) : 'a t -> key * 'a -> 'a t * [ , value ) ] returns a map containing the same bindings as [ map ] , plus a binding of [ key ] to [ value ] . If [ key ] was already bound in [ map ] , its previous binding disappears . Equivalent to [ add key value map ] [map], plus a binding of [key] to [value]. If [key] was already bound in [map], its previous binding disappears. Equivalent to [add key value map]*) end (** Operations on {!Map} with labels. This module overrides a number of functions of {!Map} by functions in which some arguments require labels. These labels are there to improve readability and safety and to let you change the order of arguments to functions. In every case, the behavior of the function is identical to that of the corresponding function of {!Map}. *) module Labels : sig val add : key:key -> data:'a -> 'a t -> 'a t val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit val map : f:('a -> 'b) -> 'a t -> 'b t val mapi : f:(key:key -> data:'a -> 'b) -> 'a t -> 'b t val filterv: f:('a -> bool) -> 'a t -> 'a t val filter:f:(key -> 'a -> bool) -> 'a t -> 'a t val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b val compare: cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int val equal: cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool end end module Make (Ord : BatInterfaces.OrderedType) : S with type key = Ord.t (** Functor building an implementation of the map structure given a totally ordered type. *) * { 4 Polymorphic maps } The functions below present the manipulation of polymorphic maps , as were provided by the Extlib PMap module . They are similar in functionality to the functorized { ! Make } module , but only uses the [ Pervasives.compare ] function to compare elements . If you need to compare using a custom comparison function , it is recommended to use the functorized maps provided by { ! Make } . The functions below present the manipulation of polymorphic maps, as were provided by the Extlib PMap module. They are similar in functionality to the functorized {!Make} module, but only uses the [Pervasives.compare] function to compare elements. If you need to compare using a custom comparison function, it is recommended to use the functorized maps provided by {!Make}. *) type ('a, 'b) t val empty : ('a, 'b) t (** The empty map, using [compare] as key comparison function. *) val is_empty : ('a, 'b) t -> bool (** returns true if the map is empty. *) val singleton : 'a -> 'b -> ('a, 'b) t (** creates a new map with a single binding *) val cardinal: ('a, 'b) t -> int (** Return the number of bindings of a map. *) val add : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t (** [add x y m] returns a map containing the same bindings as [m], plus a binding of [x] to [y]. If [x] was already bound in [m], its previous binding disappears. *) val find : 'a -> ('a, 'b) t -> 'b (** [find x m] returns the current binding of [x] in [m], or raises [Not_found] if no such binding exists. *) val remove : 'a -> ('a, 'b) t -> ('a, 'b) t (** [remove x m] returns a map containing the same bindings as [m], except for [x] which is unbound in the returned map. *) val mem : 'a -> ('a, 'b) t -> bool (** [mem x m] returns [true] if [m] contains a binding for [x], and [false] otherwise. *) val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit * [ iter f m ] applies [ f ] to all bindings in map [ m ] . [ f ] receives the key as first argument , and the associated value as second argument . The order in which the bindings are passed to [ f ] is unspecified . Only current bindings are presented to [ f ] : bindings hidden by more recent bindings are not passed to [ f ] . [f] receives the key as first argument, and the associated value as second argument. The order in which the bindings are passed to [f] is unspecified. Only current bindings are presented to [f]: bindings hidden by more recent bindings are not passed to [f]. *) val map : ('b -> 'c) -> ('a, 'b) t -> ('a, 'c) t (** [map f m] returns a map with same domain as [m], where the associated value [a] of all bindings of [m] has been replaced by the result of the application of [f] to [a]. The order in which the associated values are passed to [f] is unspecified. *) val mapi : ('a -> 'b -> 'c) -> ('a, 'b) t -> ('a, 'c) t (** Same as [map], but the function receives as arguments both the key and the associated value for each binding of the map. *) val fold : ('b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c * [ fold f m a ] computes [ ( f kN dN ... ( f k1 d1 ( f k0 d0 a ) ) ... ) ] , where ] are the keys of all bindings in [ m ] , and [ d0,d1 .. dN ] are the associated data . The order in which the bindings are presented to [ f ] is unspecified . where [k0,k1..kN] are the keys of all bindings in [m], and [d0,d1..dN] are the associated data. The order in which the bindings are presented to [f] is unspecified. *) val foldi : ('a -> 'b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c (** Same as [fold], but the function receives as arguments both the key and the associated value for each binding of the map. *) val filterv: ('a -> bool) -> ('key, 'a) t -> ('key, 'a) t (**[filterv f m] returns a map where only the values [a] of [m] such that [f a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *) val filter: ('key -> 'a -> bool) -> ('key, 'a) t -> ('key, 'a) t (**[filter f m] returns a map where only the (key, value) pairs [key], [a] of [m] such that [f key a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *) val filter_map: ('key -> 'a -> 'b option) -> ('key, 'a) t -> ('key, 'b) t (** [filter_map f m] combines the features of [filter] and [map]. It calls calls [f key0 a0], [f key1 a1], [f keyn an] where [a0..an] are the elements of [m] and [key0..keyn] the respective corresponding keys. It returns the map of pairs [keyi],[bi] such as [f keyi ai = Some bi] (when [f] returns [None], the corresponding element of [m] is discarded). *) (* The following documentations comments are from stdlib's map.mli: - choose - split *) val choose : ('key, 'a) t -> ('key * 'a) * Return one binding of the given map , or raise [ Not_found ] if the map is empty . Which binding is chosen is unspecified , but equal bindings will be chosen for equal maps . the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. *) val split : 'key -> ('key, 'a) t -> (('key, 'a) t * 'a option * ('key, 'a) t) (** [split x m] returns a triple [(l, data, r)], where [l] is the map with all the bindings of [m] whose key is strictly less than [x]; [r] is the map with all the bindings of [m] whose key is strictly greater than [x]; [data] is [None] if [m] contains no binding for [x], or [Some v] if [m] binds [v] to [x]. *) val min_binding : ('key, 'a) t -> ('key * 'a) (** returns the binding with the smallest key *) val max_binding : ('key, 'a) t -> ('key * 'a) (** returns the binding with the largest key *) val enum : ('a, 'b) t -> ('a * 'b) BatEnum.t (** creates an enumeration for this map, enumerating key,value pairs with the keys in increasing order. *) val backwards : ('a,'b) t -> ('a * 'b) BatEnum.t (** creates an enumeration for this map, enumerating key,value pairs with the keys in decreasing order. *) val keys : ('a,'b) t -> 'a BatEnum.t (** Return an enumeration of all the keys of a map.*) val values: ('a,'b) t -> 'b BatEnum.t (** Return an enumeration of al the values of a map.*) val of_enum : ('a * 'b) BatEnum.t -> ('a, 'b) t (** Creates a map from an enumeration *) val for_all : ('a -> 'b -> bool) -> ('a, 'b) t -> bool (** Tests whether all key value pairs satisfy some predicate function *) val exists : ('a -> 'b -> bool) -> ('a, 'b) t -> bool (** Tests whether some key value pair satisfies some predicate function *) documentation comment from INRIA 's stdlib val partition : ('a -> 'b -> bool) -> ('a, 'b) t -> ('a, 'b) t * ('a, 'b) t * [ partition p m ] returns a pair of maps [ ( m1 , m2 ) ] , where [ m1 ] contains all the bindings of [ s ] that satisfy the predicate [ p ] , and [ m2 ] is the map with all the bindings of [ s ] that do not satisfy [ p ] . contains all the bindings of [s] that satisfy the predicate [p], and [m2] is the map with all the bindings of [s] that do not satisfy [p]. *) val add_carry : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t * 'b option (** [add_carry k v m] adds the binding [(k,v)] to [m], returning the new map and optionally the previous value bound to [k]. *) val modify : 'a -> ('b -> 'b) -> ('a, 'b) t -> ('a, 'b) t (** [modify k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [Not_found] is raised. @since 1.2.0 @raise Not_found if [k] is unbound in [m] (or [f] raises [Not_found]) *) val modify_def: 'b -> 'a -> ('b -> 'b) -> ('a,'b) t -> ('a,'b) t (** [modify_def v0 k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [f v0] is inserted (as if the value found were [v0]). @since 1.3.0 *) val modify_opt: 'a -> ('b option -> 'b option) -> ('a,'b) t -> ('a,'b) t * [ modify_opt k f m ] allow to modify the binding for [ k ] in [ m ] or absence thereof . @since 2.1 or absence thereof. @since 2.1 *) val extract : 'a -> ('a, 'b) t -> 'b * ('a, 'b) t (** [extract k m] removes the current binding of [k] from [m], returning the value [k] was bound to and the updated [m]. *) val pop : ('a, 'b) t -> ('a * 'b) * ('a, 'b) t (** [pop m] returns a binding from [m] and [m] without that binding. *) val union : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ union ] merges two maps , using the comparison function of [ m1 ] . In case of conflicted bindings , [ m2 ] 's bindings override [ m1 ] 's . Equivalent to [ foldi add m2 m1 ] . The resulting map uses the comparison function of [ m1 ] . [m1]. In case of conflicted bindings, [m2]'s bindings override [m1]'s. Equivalent to [foldi add m2 m1]. The resulting map uses the comparison function of [m1]. *) val diff : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ diff ] removes all bindings of keys found in [ m2 ] from [ m1 ] , using the comparison function of [ m1 ] . Equivalent to [ foldi ( fun k _ v m - > remove k m ) m2 m1 ] The resulting map uses the comparison function of [ m1 ] . using the comparison function of [m1]. Equivalent to [foldi (fun k _v m -> remove k m) m2 m1] The resulting map uses the comparison function of [m1].*) val intersect : ('b -> 'c -> 'd) -> ('a, 'b) t -> ('a, 'c) t -> ('a, 'd) t * [ intersect merge_f m1 m2 ] returns a map with bindings only for keys bound in both [ m1 ] and [ m2 ] , and with [ k ] bound to [ merge_f v1 v2 ] , where [ v1 ] and [ v2 ] are [ k ] 's bindings in [ m1 ] and [ m2 ] . The resulting map uses the comparison function of [ m1 ] . keys bound in both [m1] and [m2], and with [k] bound to [merge_f v1 v2], where [v1] and [v2] are [k]'s bindings in [m1] and [m2]. The resulting map uses the comparison function of [m1]. *) val merge: ('key -> 'a option -> 'b option -> 'c option) -> ('key, 'a) t -> ('key, 'b) t -> ('key, 'c) t * [ merge f m1 m2 ] computes a map whose keys is a subset of keys of [ m1 ] and of [ m2 ] . The presence of each such binding , and the corresponding value , is determined with the function [ f ] . The resulting map uses the comparison function of [ m1 ] . and of [m2]. The presence of each such binding, and the corresponding value, is determined with the function [f]. The resulting map uses the comparison function of [m1]. *) val compare: ('b -> 'b -> int) -> ('a,'b) t -> ('a, 'b) t -> int val equal : ('b -> 'b -> bool) -> ('a,'b) t -> ('a, 'b) t -> bool (** Construct a comparison or equality function for maps based on a value comparison or equality function. Uses the key comparison function to compare keys *) (** Exceptionless versions of functions *) module Exceptionless : sig val find: 'a -> ('a,'b) t -> 'b option end * Infix operators over a { ! } module Infix : sig val (-->) : ('a, 'b) t -> 'a -> 'b (** [map-->key] returns the current binding of [key] in [map], or raises [Not_found]. Equivalent to [find key map]. *) val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t * [ , value ) ] returns a map containing the same bindings as [ map ] , plus a binding of [ key ] to [ value ] . If [ key ] was already bound in [ map ] , its previous binding disappears . Equivalent to [ add key value map ] [map], plus a binding of [key] to [value]. If [key] was already bound in [map], its previous binding disappears. Equivalent to [add key value map]*) end * Map find and insert from Infix val (-->) : ('a, 'b) t -> 'a -> 'b val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t val bindings : ('key, 'a) t -> ('key * 'a) list * Return the list of all bindings of the given map . The returned list is sorted in increasing key order . Added for compatibility with stdlib 3.12 The returned list is sorted in increasing key order. Added for compatibility with stdlib 3.12 *) (** {6 Boilerplate code}*) * { 7 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ?kvsep:string -> ('a BatInnerIO.output -> 'b -> unit) -> ('a BatInnerIO.output -> 'c -> unit) -> 'a BatInnerIO.output -> ('b, 'c) t -> unit (**/**) module type OrderedType = BatInterfaces.OrderedType (** Input signature of the functor {!Map.Make}. *) (**/**) module PMap : sig * { 4 Polymorphic maps } The functions below present the manipulation of polymorphic maps , as were provided by the Extlib PMap module . They are similar in functionality to the functorized { ! Make } module , but the compiler can not ensure that maps using different key ordering have different types : the responsibility of not mixing non - sensical comparison functions together is to the programmer . If in doubt , you should rather use the { ! Make } functor for additional safety . The functions below present the manipulation of polymorphic maps, as were provided by the Extlib PMap module. They are similar in functionality to the functorized {!Make} module, but the compiler cannot ensure that maps using different key ordering have different types: the responsibility of not mixing non-sensical comparison functions together is to the programmer. If in doubt, you should rather use the {!Make} functor for additional safety. *) type ('a, 'b) t val empty : ('a, 'b) t (** The empty map, using [compare] as key comparison function. *) val is_empty : ('a, 'b) t -> bool (** returns true if the map is empty. *) val create : ('a -> 'a -> int) -> ('a, 'b) t (** creates a new empty map, using the provided function for key comparison.*) val get_cmp : ('a, 'b) t -> ('a -> 'a -> int) (** returns the comparison function of the given map *) val singleton : ?cmp:('a -> 'a -> int) -> 'a -> 'b -> ('a, 'b) t (** creates a new map with a single binding *) val cardinal: ('a, 'b) t -> int (** Return the number of bindings of a map. *) val add : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t (** [add x y m] returns a map containing the same bindings as [m], plus a binding of [x] to [y]. If [x] was already bound in [m], its previous binding disappears. *) val find : 'a -> ('a, 'b) t -> 'b (** [find x m] returns the current binding of [x] in [m], or raises [Not_found] if no such binding exists. *) val remove : 'a -> ('a, 'b) t -> ('a, 'b) t (** [remove x m] returns a map containing the same bindings as [m], except for [x] which is unbound in the returned map. *) val mem : 'a -> ('a, 'b) t -> bool (** [mem x m] returns [true] if [m] contains a binding for [x], and [false] otherwise. *) val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit * [ iter f m ] applies [ f ] to all bindings in map [ m ] . [ f ] receives the key as first argument , and the associated value as second argument . The order in which the bindings are passed to [ f ] is unspecified . Only current bindings are presented to [ f ] : bindings hidden by more recent bindings are not passed to [ f ] . [f] receives the key as first argument, and the associated value as second argument. The order in which the bindings are passed to [f] is unspecified. Only current bindings are presented to [f]: bindings hidden by more recent bindings are not passed to [f]. *) val map : ('b -> 'c) -> ('a, 'b) t -> ('a, 'c) t (** [map f m] returns a map with same domain as [m], where the associated value [a] of all bindings of [m] has been replaced by the result of the application of [f] to [a]. The order in which the associated values are passed to [f] is unspecified. *) val mapi : ('a -> 'b -> 'c) -> ('a, 'b) t -> ('a, 'c) t (** Same as [map], but the function receives as arguments both the key and the associated value for each binding of the map. *) val fold : ('b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c * [ fold f m a ] computes [ ( f kN dN ... ( f k1 d1 ( f k0 d0 a ) ) ... ) ] , where [ k0,k1 .. kN ] are the keys of all bindings in [ m ] , and [ d0,d1 .. dN ] are the associated data . The order in which the bindings are presented to [ f ] is unspecified . where [k0,k1..kN] are the keys of all bindings in [m], and [d0,d1..dN] are the associated data. The order in which the bindings are presented to [f] is unspecified. *) val foldi : ('a -> 'b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c (** Same as [fold], but the function receives as arguments both the key and the associated value for each binding of the map. *) val filterv: ('a -> bool) -> ('key, 'a) t -> ('key, 'a) t (**[filterv f m] returns a map where only the values [a] of [m] such that [f a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *) val filter: ('key -> 'a -> bool) -> ('key, 'a) t -> ('key, 'a) t (**[filter f m] returns a map where only the (key, value) pairs [key], [a] of [m] such that [f key a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *) val filter_map: ('key -> 'a -> 'b option) -> ('key, 'a) t -> ('key, 'b) t (** [filter_map f m] combines the features of [filter] and [map]. It calls calls [f key0 a0], [f key1 a1], [f keyn an] where [a0..an] are the elements of [m] and [key0..keyn] the respective corresponding keys. It returns the map of pairs [keyi],[bi] such as [f keyi ai = Some bi] (when [f] returns [None], the corresponding element of [m] is discarded). *) (* The following documentations comments are from stdlib's map.mli: - choose - split *) val choose : ('key, 'a) t -> ('key * 'a) * Return one binding of the given map , or raise [ Not_found ] if the map is empty . Which binding is chosen is unspecified , but equal bindings will be chosen for equal maps . the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. *) val split : 'key -> ('key, 'a) t -> (('key, 'a) t * 'a option * ('key, 'a) t) (** [split x m] returns a triple [(l, data, r)], where [l] is the map with all the bindings of [m] whose key is strictly less than [x]; [r] is the map with all the bindings of [m] whose key is strictly greater than [x]; [data] is [None] if [m] contains no binding for [x], or [Some v] if [m] binds [v] to [x]. *) val min_binding : ('key, 'a) t -> ('key * 'a) (** returns the binding with the smallest key *) val max_binding : ('key, 'a) t -> ('key * 'a) (** returns the binding with the largest key *) val enum : ('a, 'b) t -> ('a * 'b) BatEnum.t (** creates an enumeration for this map, enumerating key,value pairs with the keys in increasing order. *) val backwards : ('a,'b) t -> ('a * 'b) BatEnum.t (** creates an enumeration for this map, enumerating key,value pairs with the keys in decreasing order. *) val keys : ('a,'b) t -> 'a BatEnum.t (** Return an enumeration of all the keys of a map.*) val values: ('a,'b) t -> 'b BatEnum.t (** Return an enumeration of al the values of a map.*) val of_enum : ?cmp:('a -> 'a -> int) -> ('a * 'b) BatEnum.t -> ('a, 'b) t (** creates a map from an enumeration, using the specified function for key comparison or [compare] by default. *) val for_all : ('a -> 'b -> bool) -> ('a, 'b) t -> bool (** Tests whether all key value pairs satisfy some predicate function *) val exists : ('a -> 'b -> bool) -> ('a, 'b) t -> bool (** Tests whether some key value pair satisfies some predicate function *) documentation comment from INRIA 's stdlib val partition : ('a -> 'b -> bool) -> ('a, 'b) t -> ('a, 'b) t * ('a, 'b) t (** [partition p m] returns a pair of maps [(m1, m2)], where [m1] contains all the bindings of [s] that satisfy the predicate [p], and [m2] is the map with all the bindings of [s] that do not satisfy [p]. *) val add_carry : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t * 'b option (** [add_carry k v m] adds the binding [(k,v)] to [m], returning the new map and optionally the previous value bound to [k]. *) val modify : 'a -> ('b -> 'b) -> ('a, 'b) t -> ('a, 'b) t (** [modify k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [Not_found] is raised. @since 1.2.0 @raise Not_found if [k] is unbound in [m] (or [f] raises [Not_found]) *) val modify_def: 'b -> 'a -> ('b -> 'b) -> ('a,'b) t -> ('a,'b) t (** [modify_def v0 k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [f v0] is inserted (as if the value found were [v0]). @since 1.3.0 *) val modify_opt: 'a -> ('b option -> 'b option) -> ('a,'b) t -> ('a,'b) t * [ modify_opt k f m ] allow to modify the binding for [ k ] in [ m ] or absence thereof . @since 2.1 or absence thereof. @since 2.1 *) val extract : 'a -> ('a, 'b) t -> 'b * ('a, 'b) t (** [extract k m] removes the current binding of [k] from [m], returning the value [k] was bound to and the updated [m]. *) val pop : ('a, 'b) t -> ('a * 'b) * ('a, 'b) t (** [pop m] returns a binding from [m] and [m] without that binding. *) val union : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ union ] merges two maps , using the comparison function of [ m1 ] . In case of conflicted bindings , [ m2 ] 's bindings override [ m1 ] 's . Equivalent to [ foldi add m2 m1 ] . The resulting map uses the comparison function of [ m1 ] . [m1]. In case of conflicted bindings, [m2]'s bindings override [m1]'s. Equivalent to [foldi add m2 m1]. The resulting map uses the comparison function of [m1]. *) val diff : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ diff ] removes all bindings of keys found in [ m2 ] from [ m1 ] , using the comparison function of [ m1 ] . Equivalent to [ foldi ( fun k _ v m - > remove k m ) m2 m1 ] The resulting map uses the comparison function of [ m1 ] . using the comparison function of [m1]. Equivalent to [foldi (fun k _v m -> remove k m) m2 m1] The resulting map uses the comparison function of [m1].*) val intersect : ('b -> 'c -> 'd) -> ('a, 'b) t -> ('a, 'c) t -> ('a, 'd) t * [ intersect merge_f m1 m2 ] returns a map with bindings only for keys bound in both [ m1 ] and [ m2 ] , and with [ k ] bound to [ merge_f v1 v2 ] , where [ v1 ] and [ v2 ] are [ k ] 's bindings in [ m1 ] and [ m2 ] . The resulting map uses the comparison function of [ m1 ] . keys bound in both [m1] and [m2], and with [k] bound to [merge_f v1 v2], where [v1] and [v2] are [k]'s bindings in [m1] and [m2]. The resulting map uses the comparison function of [m1]. *) val merge: ('key -> 'a option -> 'b option -> 'c option) -> ('key, 'a) t -> ('key, 'b) t -> ('key, 'c) t (** [merge f m1 m2] computes a map whose keys is a subset of keys of [m1] and of [m2]. The presence of each such binding, and the corresponding value, is determined with the function [f]. The resulting map uses the comparison function of [m1]. *) val merge_unsafe: ('key -> 'a option -> 'b option -> 'c option) -> ('key, 'a) t -> ('key, 'b) t -> ('key, 'c) t * Same as merge , but assumes the comparison function of both maps are equal . If it 's not the case , the result is a map using the comparison function of its first parameter , but which [ ' b option ] elements are passed to the function is unspecified . are equal. If it's not the case, the result is a map using the comparison function of its first parameter, but which ['b option] elements are passed to the function is unspecified. *) val compare: ('b -> 'b -> int) -> ('a,'b) t -> ('a, 'b) t -> int val equal : ('b -> 'b -> bool) -> ('a,'b) t -> ('a, 'b) t -> bool (** Construct a comparison or equality function for maps based on a value comparison or equality function. Uses the key comparison function to compare keys *) (** Exceptionless versions of functions *) module Exceptionless : sig val find: 'a -> ('a,'b) t -> 'b option end * Infix operators over a { ! } module Infix : sig val (-->) : ('a, 'b) t -> 'a -> 'b (** [map-->key] returns the current binding of [key] in [map], or raises [Not_found]. Equivalent to [find key map]. *) val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t * [ , value ) ] returns a map containing the same bindings as [ map ] , plus a binding of [ key ] to [ value ] . If [ key ] was already bound in [ map ] , its previous binding disappears . Equivalent to [ add key value map ] [map], plus a binding of [key] to [value]. If [key] was already bound in [map], its previous binding disappears. Equivalent to [add key value map]*) end * Map find and insert from Infix val (-->) : ('a, 'b) t -> 'a -> 'b val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t val bindings : ('key, 'a) t -> ('key * 'a) list * Return the list of all bindings of the given map . The returned list is sorted in increasing key order . Added for compatibility with stdlib 3.12 The returned list is sorted in increasing key order. Added for compatibility with stdlib 3.12 *) (** {6 Boilerplate code}*) * { 7 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ?kvsep:string -> ('a BatInnerIO.output -> 'b -> unit) -> ('a BatInnerIO.output -> 'c -> unit) -> 'a BatInnerIO.output -> ('b, 'c) t -> unit (** get the comparison function used for a polymorphic map *) val get_cmp : ('a, 'b) t -> ('a -> 'a -> int) PMap module
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batMap.mli
ocaml
* The type of the map keys. * The type of maps from type [key] to type ['a]. * The empty map. * Test whether a map is empty or not. * Return the number of bindings of a map. * [add x y m] returns a map containing the same bindings as [m], plus a binding of [x] to [y]. If [x] was already bound in [m], its previous binding disappears. * [find x m] returns the current binding of [x] in [m], or raises [Not_found] if no such binding exists. * [remove x m] returns a map containing the same bindings as [m], except for [x] which is unbound in the returned map. * [modify k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [Not_found] is raised. @since 1.2.0 @raise Not_found if [k] is unbound in [m] (or [f] raises [Not_found]) * [modify_def v0 k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [f v0] is inserted (as if the value found were [v0]). @since 1.3.0 * [mem x m] returns [true] if [m] contains a binding for [x], and [false] otherwise. * [map f m] returns a map with same domain as [m], where the associated value [a] of all bindings of [m] has been replaced by the result of the application of [f] to [a]. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. * Same as {!Map.S.map}, but the function receives as arguments both the key and the associated value for each binding of the map. * [fold f m a] computes [(f kN dN ... (f k1 d1 (f k0 d0 a))...)], where [k0,k1..kN] are the keys of all bindings in [m] (in increasing order), and [d1 ... dN] are the associated data. *[filterv f m] returns a map where only the values [a] of [m] such that [f a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *[filter f m] returns a map where only the key, values pairs [key], [a] of [m] such that [f key a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. * [filter_map f m] combines the features of [filter] and [map]. It calls calls [f key0 a0], [f key1 a1], [f keyn an] where [a0,a1..an] are the elements of [m] and [key0..keyn] the respective corresponding keys. It returns the map of pairs [keyi],[bi] such as [f keyi ai = Some bi] (when [f] returns [None], the corresponding element of [m] is discarded). * Return an enumeration of all the keys of a map. * Return an enumeration of al the values of a map. * return the ([key,value]) pair with the smallest key * return the [(key,value)] pair with the largest key The following documentations comments are from stdlib's map.mli: - choose - split - singleton - partition * [split x m] returns a triple [(l, data, r)], where [l] is the map with all the bindings of [m] whose key is strictly less than [x]; [r] is the map with all the bindings of [m] whose key is strictly greater than [x]; [data] is [None] if [m] contains no binding for [x], or [Some v] if [m] binds [v] to [x]. * Create a map from a (key, value) enumeration. * [for_all p m] checks if all the bindings of the map satisfy the predicate [p]. * [merge f m1 m2] computes a map whose keys is a subset of keys of [m1] and of [m2]. The presence of each such binding, and the corresponding value, is determined with the function [f]. * {6 Boilerplate code} * Output signature of the functor {!Map.Make}. * The following modules replace functions defined in {!Map} with functions behaving slightly differently but having the same name. This is by design: the functions meant to override the corresponding functions of {!Map}. * Operations on {!Map} without exceptions. * Infix operators over a {!BatMap} * [map-->key] returns the current binding of [key] in [map], or raises [Not_found]. Equivalent to [find key map]. * Operations on {!Map} with labels. This module overrides a number of functions of {!Map} by functions in which some arguments require labels. These labels are there to improve readability and safety and to let you change the order of arguments to functions. In every case, the behavior of the function is identical to that of the corresponding function of {!Map}. * Functor building an implementation of the map structure given a totally ordered type. * The empty map, using [compare] as key comparison function. * returns true if the map is empty. * creates a new map with a single binding * Return the number of bindings of a map. * [add x y m] returns a map containing the same bindings as [m], plus a binding of [x] to [y]. If [x] was already bound in [m], its previous binding disappears. * [find x m] returns the current binding of [x] in [m], or raises [Not_found] if no such binding exists. * [remove x m] returns a map containing the same bindings as [m], except for [x] which is unbound in the returned map. * [mem x m] returns [true] if [m] contains a binding for [x], and [false] otherwise. * [map f m] returns a map with same domain as [m], where the associated value [a] of all bindings of [m] has been replaced by the result of the application of [f] to [a]. The order in which the associated values are passed to [f] is unspecified. * Same as [map], but the function receives as arguments both the key and the associated value for each binding of the map. * Same as [fold], but the function receives as arguments both the key and the associated value for each binding of the map. *[filterv f m] returns a map where only the values [a] of [m] such that [f a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *[filter f m] returns a map where only the (key, value) pairs [key], [a] of [m] such that [f key a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. * [filter_map f m] combines the features of [filter] and [map]. It calls calls [f key0 a0], [f key1 a1], [f keyn an] where [a0..an] are the elements of [m] and [key0..keyn] the respective corresponding keys. It returns the map of pairs [keyi],[bi] such as [f keyi ai = Some bi] (when [f] returns [None], the corresponding element of [m] is discarded). The following documentations comments are from stdlib's map.mli: - choose - split * [split x m] returns a triple [(l, data, r)], where [l] is the map with all the bindings of [m] whose key is strictly less than [x]; [r] is the map with all the bindings of [m] whose key is strictly greater than [x]; [data] is [None] if [m] contains no binding for [x], or [Some v] if [m] binds [v] to [x]. * returns the binding with the smallest key * returns the binding with the largest key * creates an enumeration for this map, enumerating key,value pairs with the keys in increasing order. * creates an enumeration for this map, enumerating key,value pairs with the keys in decreasing order. * Return an enumeration of all the keys of a map. * Return an enumeration of al the values of a map. * Creates a map from an enumeration * Tests whether all key value pairs satisfy some predicate function * Tests whether some key value pair satisfies some predicate function * [add_carry k v m] adds the binding [(k,v)] to [m], returning the new map and optionally the previous value bound to [k]. * [modify k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [Not_found] is raised. @since 1.2.0 @raise Not_found if [k] is unbound in [m] (or [f] raises [Not_found]) * [modify_def v0 k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [f v0] is inserted (as if the value found were [v0]). @since 1.3.0 * [extract k m] removes the current binding of [k] from [m], returning the value [k] was bound to and the updated [m]. * [pop m] returns a binding from [m] and [m] without that binding. * Construct a comparison or equality function for maps based on a value comparison or equality function. Uses the key comparison function to compare keys * Exceptionless versions of functions * [map-->key] returns the current binding of [key] in [map], or raises [Not_found]. Equivalent to [find key map]. * {6 Boilerplate code} */* * Input signature of the functor {!Map.Make}. */* * The empty map, using [compare] as key comparison function. * returns true if the map is empty. * creates a new empty map, using the provided function for key comparison. * returns the comparison function of the given map * creates a new map with a single binding * Return the number of bindings of a map. * [add x y m] returns a map containing the same bindings as [m], plus a binding of [x] to [y]. If [x] was already bound in [m], its previous binding disappears. * [find x m] returns the current binding of [x] in [m], or raises [Not_found] if no such binding exists. * [remove x m] returns a map containing the same bindings as [m], except for [x] which is unbound in the returned map. * [mem x m] returns [true] if [m] contains a binding for [x], and [false] otherwise. * [map f m] returns a map with same domain as [m], where the associated value [a] of all bindings of [m] has been replaced by the result of the application of [f] to [a]. The order in which the associated values are passed to [f] is unspecified. * Same as [map], but the function receives as arguments both the key and the associated value for each binding of the map. * Same as [fold], but the function receives as arguments both the key and the associated value for each binding of the map. *[filterv f m] returns a map where only the values [a] of [m] such that [f a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. *[filter f m] returns a map where only the (key, value) pairs [key], [a] of [m] such that [f key a = true] remain. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. * [filter_map f m] combines the features of [filter] and [map]. It calls calls [f key0 a0], [f key1 a1], [f keyn an] where [a0..an] are the elements of [m] and [key0..keyn] the respective corresponding keys. It returns the map of pairs [keyi],[bi] such as [f keyi ai = Some bi] (when [f] returns [None], the corresponding element of [m] is discarded). The following documentations comments are from stdlib's map.mli: - choose - split * [split x m] returns a triple [(l, data, r)], where [l] is the map with all the bindings of [m] whose key is strictly less than [x]; [r] is the map with all the bindings of [m] whose key is strictly greater than [x]; [data] is [None] if [m] contains no binding for [x], or [Some v] if [m] binds [v] to [x]. * returns the binding with the smallest key * returns the binding with the largest key * creates an enumeration for this map, enumerating key,value pairs with the keys in increasing order. * creates an enumeration for this map, enumerating key,value pairs with the keys in decreasing order. * Return an enumeration of all the keys of a map. * Return an enumeration of al the values of a map. * creates a map from an enumeration, using the specified function for key comparison or [compare] by default. * Tests whether all key value pairs satisfy some predicate function * Tests whether some key value pair satisfies some predicate function * [partition p m] returns a pair of maps [(m1, m2)], where [m1] contains all the bindings of [s] that satisfy the predicate [p], and [m2] is the map with all the bindings of [s] that do not satisfy [p]. * [add_carry k v m] adds the binding [(k,v)] to [m], returning the new map and optionally the previous value bound to [k]. * [modify k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [Not_found] is raised. @since 1.2.0 @raise Not_found if [k] is unbound in [m] (or [f] raises [Not_found]) * [modify_def v0 k f m] replaces the previous binding for [k] with [f] applied to that value. If [k] is unbound in [m] or [Not_found] is raised during the search, [f v0] is inserted (as if the value found were [v0]). @since 1.3.0 * [extract k m] removes the current binding of [k] from [m], returning the value [k] was bound to and the updated [m]. * [pop m] returns a binding from [m] and [m] without that binding. * [merge f m1 m2] computes a map whose keys is a subset of keys of [m1] and of [m2]. The presence of each such binding, and the corresponding value, is determined with the function [f]. The resulting map uses the comparison function of [m1]. * Construct a comparison or equality function for maps based on a value comparison or equality function. Uses the key comparison function to compare keys * Exceptionless versions of functions * [map-->key] returns the current binding of [key] in [map], or raises [Not_found]. Equivalent to [find key map]. * {6 Boilerplate code} * get the comparison function used for a polymorphic map
* BatMap - Additional map operations * Copyright ( C ) 1996 2009 , LIFO , Universite d'Orleans * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * BatMap - Additional map operations * Copyright (C) 1996 Xavier Leroy * 2009 David Rajchenbach-Teller, LIFO, Universite d'Orleans * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) * Association tables over ordered types . This module implements applicative association tables , also known as finite maps or dictionaries , given a total ordering function over the keys . All operations over maps are purely applicative ( no side - effects ) . The implementation uses balanced binary trees , and therefore searching and insertion take time logarithmic in the size of the map . { b Note } OCaml , Batteries Included , provides two implementations of maps : polymorphic maps and functorized maps . Functorized maps ( see { ! S } and { ! Make } ) are slightly more complex to use but offer stronger type - safety . Polymorphic maps make it easier to shoot yourself in the foot . In case of doubt , you should use functorized maps . { 4 Functorized maps } The important part is the { ! Make } module which builds association maps from a user - provided datatype and comparison function . In the { ! Make } module ( or its output signature { ! S } ) are documentated all functions available on maps . Here is a typical example of use : { [ module MyKeyType = struct type t = my_type let compare = my_compare_function end module = Map . Make(MyKeyType ) let some_map = MyMap.add something MyMap.empty ... ] } You can also use predefined maps such as { ! IntMap } for maps with integer keys . @author ( Base library ) @author @author @author @author This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. {b Note} OCaml, Batteries Included, provides two implementations of maps: polymorphic maps and functorized maps. Functorized maps (see {!S} and {!Make}) are slightly more complex to use but offer stronger type-safety. Polymorphic maps make it easier to shoot yourself in the foot. In case of doubt, you should use functorized maps. {4 Functorized maps} The important part is the {!Make} module which builds association maps from a user-provided datatype and comparison function. In the {!Make} module (or its output signature {!S}) are documentated all functions available on maps. Here is a typical example of use: {[ module MyKeyType = struct type t = my_type let compare = my_compare_function end module MyMap = Map.Make(MyKeyType) let some_map = MyMap.add something MyMap.empty ... ]} You can also use predefined maps such as {!IntMap} for maps with integer keys. @author Xavier Leroy (Base library) @author Nicolas Cannasse @author Markus Mottl @author David Rajchenbach-Teller @author Gabriel Scherer *) module type S = sig type key type (+'a) t val empty: 'a t val is_empty: 'a t -> bool val cardinal: 'a t -> int val add: key -> 'a -> 'a t -> 'a t val find: key -> 'a t -> 'a val remove: key -> 'a t -> 'a t val modify: key -> ('a -> 'a) -> 'a t -> 'a t val modify_def: 'a -> key -> ('a -> 'a) -> 'a t -> 'a t val modify_opt: key -> ('a option -> 'a option) -> 'a t -> 'a t * [ modify_opt k f m ] allows to modify the binding for [ k ] in [ m ] or absence thereof . @since 2.1 or absence thereof. @since 2.1 *) val extract : key -> 'a t -> 'a * 'a t * [ extract k m ] removes the current binding of [ k ] from [ m ] , returning the value [ k ] was bound to and the updated [ m ] . @since 1.4.0 returning the value [k] was bound to and the updated [m]. @since 1.4.0 *) val pop : 'a t -> (key * 'a) * 'a t * [ pop m ] returns a binding from [ m ] and [ m ] without that binding . @raise Not_found if [ m ] is empty @since 1.4.0 binding. @raise Not_found if [m] is empty @since 1.4.0 *) val mem: key -> 'a t -> bool val iter: (key -> 'a -> unit) -> 'a t -> unit * [ iter f m ] applies [ f ] to all bindings in map [ m ] . [ f ] receives the key as first argument , and the associated value as second argument . The bindings are passed to [ f ] in increasing order with respect to the ordering over the type of the keys . Only current bindings are presented to [ f ] : bindings hidden by more recent bindings are not passed to [ f ] . [f] receives the key as first argument, and the associated value as second argument. The bindings are passed to [f] in increasing order with respect to the ordering over the type of the keys. Only current bindings are presented to [f]: bindings hidden by more recent bindings are not passed to [f]. *) val map: ('a -> 'b) -> 'a t -> 'b t val mapi: (key -> 'a -> 'b) -> 'a t -> 'b t val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val filterv: ('a -> bool) -> 'a t -> 'a t val filter: (key -> 'a -> bool) -> 'a t -> 'a t val filter_map: (key -> 'a -> 'b option) -> 'a t -> 'b t val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int * Total ordering between maps . The first argument is a total ordering used to compare data associated with equal keys in the two maps . used to compare data associated with equal keys in the two maps. *) val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool * [ equal cmp ] tests whether the maps [ m1 ] and [ m2 ] are equal , that is , contain equal keys and associate them with equal data . [ cmp ] is the equality predicate used to compare the data associated with the keys . equal, that is, contain equal keys and associate them with equal data. [cmp] is the equality predicate used to compare the data associated with the keys. *) val keys : _ t -> key BatEnum.t val values: 'a t -> 'a BatEnum.t val min_binding : 'a t -> (key * 'a) val max_binding : 'a t -> (key * 'a) val choose : 'a t -> (key * 'a) * Return one binding of the given map , or raise [ Not_found ] if the map is empty . Which binding is chosen is unspecified , but equal bindings will be chosen for equal maps . the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. *) val split : key -> 'a t -> ('a t * 'a option * 'a t) val partition: (key -> 'a -> bool) -> 'a t -> 'a t * 'a t * [ partition p m ] returns a pair of maps [ ( m1 , m2 ) ] , where [ m1 ] contains all the bindings of [ s ] that satisfy the predicate [ p ] , and [ m2 ] is the map with all the bindings of [ s ] that do not satisfy [ p ] . @since 1.4.0 [m1] contains all the bindings of [s] that satisfy the predicate [p], and [m2] is the map with all the bindings of [s] that do not satisfy [p]. @since 1.4.0 *) val singleton: key -> 'a -> 'a t * [ singleton x y ] returns the one - element map that contains a binding [ y ] for [ x ] . for [x]. *) val bindings : 'a t -> (key * 'a) list * Return the list of all bindings of the given map . The returned list is sorted in increasing key order . Added for compatibility with stdlib 3.12 The returned list is sorted in increasing key order. Added for compatibility with stdlib 3.12 *) val enum : 'a t -> (key * 'a) BatEnum.t * Return an enumeration of ( key , value ) pairs of a map . The returned enumeration is sorted in increasing order with respect to the ordering [ Ord.compare ] , where [ ] is the argument given to { ! Map . Make } . The returned enumeration is sorted in increasing order with respect to the ordering [Ord.compare], where [Ord] is the argument given to {!Map.Make}. *) val backwards : 'a t -> (key * 'a) BatEnum.t * Return an enumeration of ( key , value ) pairs of a map . The returned enumeration is sorted in decreasing order with respect to the ordering [ Ord.compare ] , where [ ] is the argument given to { ! Map . Make } . The returned enumeration is sorted in decreasing order with respect to the ordering [Ord.compare], where [Ord] is the argument given to {!Map.Make}. *) val of_enum: (key * 'a) BatEnum.t -> 'a t val for_all: (key -> 'a -> bool) -> 'a t -> bool val exists: (key -> 'a -> bool) -> 'a t -> bool * [ exists p m ] checks if at least one binding of the map satisfy the predicate [ p ] . satisfy the predicate [p]. *) val merge: (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t * { 7 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ?kvsep:string -> ('a BatInnerIO.output -> key -> unit) -> ('a BatInnerIO.output -> 'c -> unit) -> 'a BatInnerIO.output -> 'c t -> unit * { 6 Override modules } module Exceptionless : sig val find: key -> 'a t -> 'a option end module Infix : sig val (-->) : 'a t -> key -> 'a val (<--) : 'a t -> key * 'a -> 'a t * [ , value ) ] returns a map containing the same bindings as [ map ] , plus a binding of [ key ] to [ value ] . If [ key ] was already bound in [ map ] , its previous binding disappears . Equivalent to [ add key value map ] [map], plus a binding of [key] to [value]. If [key] was already bound in [map], its previous binding disappears. Equivalent to [add key value map]*) end module Labels : sig val add : key:key -> data:'a -> 'a t -> 'a t val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit val map : f:('a -> 'b) -> 'a t -> 'b t val mapi : f:(key:key -> data:'a -> 'b) -> 'a t -> 'b t val filterv: f:('a -> bool) -> 'a t -> 'a t val filter:f:(key -> 'a -> bool) -> 'a t -> 'a t val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b val compare: cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int val equal: cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool end end module Make (Ord : BatInterfaces.OrderedType) : S with type key = Ord.t * { 4 Polymorphic maps } The functions below present the manipulation of polymorphic maps , as were provided by the Extlib PMap module . They are similar in functionality to the functorized { ! Make } module , but only uses the [ Pervasives.compare ] function to compare elements . If you need to compare using a custom comparison function , it is recommended to use the functorized maps provided by { ! Make } . The functions below present the manipulation of polymorphic maps, as were provided by the Extlib PMap module. They are similar in functionality to the functorized {!Make} module, but only uses the [Pervasives.compare] function to compare elements. If you need to compare using a custom comparison function, it is recommended to use the functorized maps provided by {!Make}. *) type ('a, 'b) t val empty : ('a, 'b) t val is_empty : ('a, 'b) t -> bool val singleton : 'a -> 'b -> ('a, 'b) t val cardinal: ('a, 'b) t -> int val add : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t val find : 'a -> ('a, 'b) t -> 'b val remove : 'a -> ('a, 'b) t -> ('a, 'b) t val mem : 'a -> ('a, 'b) t -> bool val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit * [ iter f m ] applies [ f ] to all bindings in map [ m ] . [ f ] receives the key as first argument , and the associated value as second argument . The order in which the bindings are passed to [ f ] is unspecified . Only current bindings are presented to [ f ] : bindings hidden by more recent bindings are not passed to [ f ] . [f] receives the key as first argument, and the associated value as second argument. The order in which the bindings are passed to [f] is unspecified. Only current bindings are presented to [f]: bindings hidden by more recent bindings are not passed to [f]. *) val map : ('b -> 'c) -> ('a, 'b) t -> ('a, 'c) t val mapi : ('a -> 'b -> 'c) -> ('a, 'b) t -> ('a, 'c) t val fold : ('b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c * [ fold f m a ] computes [ ( f kN dN ... ( f k1 d1 ( f k0 d0 a ) ) ... ) ] , where ] are the keys of all bindings in [ m ] , and [ d0,d1 .. dN ] are the associated data . The order in which the bindings are presented to [ f ] is unspecified . where [k0,k1..kN] are the keys of all bindings in [m], and [d0,d1..dN] are the associated data. The order in which the bindings are presented to [f] is unspecified. *) val foldi : ('a -> 'b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c val filterv: ('a -> bool) -> ('key, 'a) t -> ('key, 'a) t val filter: ('key -> 'a -> bool) -> ('key, 'a) t -> ('key, 'a) t val filter_map: ('key -> 'a -> 'b option) -> ('key, 'a) t -> ('key, 'b) t val choose : ('key, 'a) t -> ('key * 'a) * Return one binding of the given map , or raise [ Not_found ] if the map is empty . Which binding is chosen is unspecified , but equal bindings will be chosen for equal maps . the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. *) val split : 'key -> ('key, 'a) t -> (('key, 'a) t * 'a option * ('key, 'a) t) val min_binding : ('key, 'a) t -> ('key * 'a) val max_binding : ('key, 'a) t -> ('key * 'a) val enum : ('a, 'b) t -> ('a * 'b) BatEnum.t val backwards : ('a,'b) t -> ('a * 'b) BatEnum.t val keys : ('a,'b) t -> 'a BatEnum.t val values: ('a,'b) t -> 'b BatEnum.t val of_enum : ('a * 'b) BatEnum.t -> ('a, 'b) t val for_all : ('a -> 'b -> bool) -> ('a, 'b) t -> bool val exists : ('a -> 'b -> bool) -> ('a, 'b) t -> bool documentation comment from INRIA 's stdlib val partition : ('a -> 'b -> bool) -> ('a, 'b) t -> ('a, 'b) t * ('a, 'b) t * [ partition p m ] returns a pair of maps [ ( m1 , m2 ) ] , where [ m1 ] contains all the bindings of [ s ] that satisfy the predicate [ p ] , and [ m2 ] is the map with all the bindings of [ s ] that do not satisfy [ p ] . contains all the bindings of [s] that satisfy the predicate [p], and [m2] is the map with all the bindings of [s] that do not satisfy [p]. *) val add_carry : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t * 'b option val modify : 'a -> ('b -> 'b) -> ('a, 'b) t -> ('a, 'b) t val modify_def: 'b -> 'a -> ('b -> 'b) -> ('a,'b) t -> ('a,'b) t val modify_opt: 'a -> ('b option -> 'b option) -> ('a,'b) t -> ('a,'b) t * [ modify_opt k f m ] allow to modify the binding for [ k ] in [ m ] or absence thereof . @since 2.1 or absence thereof. @since 2.1 *) val extract : 'a -> ('a, 'b) t -> 'b * ('a, 'b) t val pop : ('a, 'b) t -> ('a * 'b) * ('a, 'b) t val union : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ union ] merges two maps , using the comparison function of [ m1 ] . In case of conflicted bindings , [ m2 ] 's bindings override [ m1 ] 's . Equivalent to [ foldi add m2 m1 ] . The resulting map uses the comparison function of [ m1 ] . [m1]. In case of conflicted bindings, [m2]'s bindings override [m1]'s. Equivalent to [foldi add m2 m1]. The resulting map uses the comparison function of [m1]. *) val diff : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ diff ] removes all bindings of keys found in [ m2 ] from [ m1 ] , using the comparison function of [ m1 ] . Equivalent to [ foldi ( fun k _ v m - > remove k m ) m2 m1 ] The resulting map uses the comparison function of [ m1 ] . using the comparison function of [m1]. Equivalent to [foldi (fun k _v m -> remove k m) m2 m1] The resulting map uses the comparison function of [m1].*) val intersect : ('b -> 'c -> 'd) -> ('a, 'b) t -> ('a, 'c) t -> ('a, 'd) t * [ intersect merge_f m1 m2 ] returns a map with bindings only for keys bound in both [ m1 ] and [ m2 ] , and with [ k ] bound to [ merge_f v1 v2 ] , where [ v1 ] and [ v2 ] are [ k ] 's bindings in [ m1 ] and [ m2 ] . The resulting map uses the comparison function of [ m1 ] . keys bound in both [m1] and [m2], and with [k] bound to [merge_f v1 v2], where [v1] and [v2] are [k]'s bindings in [m1] and [m2]. The resulting map uses the comparison function of [m1]. *) val merge: ('key -> 'a option -> 'b option -> 'c option) -> ('key, 'a) t -> ('key, 'b) t -> ('key, 'c) t * [ merge f m1 m2 ] computes a map whose keys is a subset of keys of [ m1 ] and of [ m2 ] . The presence of each such binding , and the corresponding value , is determined with the function [ f ] . The resulting map uses the comparison function of [ m1 ] . and of [m2]. The presence of each such binding, and the corresponding value, is determined with the function [f]. The resulting map uses the comparison function of [m1]. *) val compare: ('b -> 'b -> int) -> ('a,'b) t -> ('a, 'b) t -> int val equal : ('b -> 'b -> bool) -> ('a,'b) t -> ('a, 'b) t -> bool module Exceptionless : sig val find: 'a -> ('a,'b) t -> 'b option end * Infix operators over a { ! } module Infix : sig val (-->) : ('a, 'b) t -> 'a -> 'b val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t * [ , value ) ] returns a map containing the same bindings as [ map ] , plus a binding of [ key ] to [ value ] . If [ key ] was already bound in [ map ] , its previous binding disappears . Equivalent to [ add key value map ] [map], plus a binding of [key] to [value]. If [key] was already bound in [map], its previous binding disappears. Equivalent to [add key value map]*) end * Map find and insert from Infix val (-->) : ('a, 'b) t -> 'a -> 'b val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t val bindings : ('key, 'a) t -> ('key * 'a) list * Return the list of all bindings of the given map . The returned list is sorted in increasing key order . Added for compatibility with stdlib 3.12 The returned list is sorted in increasing key order. Added for compatibility with stdlib 3.12 *) * { 7 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ?kvsep:string -> ('a BatInnerIO.output -> 'b -> unit) -> ('a BatInnerIO.output -> 'c -> unit) -> 'a BatInnerIO.output -> ('b, 'c) t -> unit module type OrderedType = BatInterfaces.OrderedType module PMap : sig * { 4 Polymorphic maps } The functions below present the manipulation of polymorphic maps , as were provided by the Extlib PMap module . They are similar in functionality to the functorized { ! Make } module , but the compiler can not ensure that maps using different key ordering have different types : the responsibility of not mixing non - sensical comparison functions together is to the programmer . If in doubt , you should rather use the { ! Make } functor for additional safety . The functions below present the manipulation of polymorphic maps, as were provided by the Extlib PMap module. They are similar in functionality to the functorized {!Make} module, but the compiler cannot ensure that maps using different key ordering have different types: the responsibility of not mixing non-sensical comparison functions together is to the programmer. If in doubt, you should rather use the {!Make} functor for additional safety. *) type ('a, 'b) t val empty : ('a, 'b) t val is_empty : ('a, 'b) t -> bool val create : ('a -> 'a -> int) -> ('a, 'b) t val get_cmp : ('a, 'b) t -> ('a -> 'a -> int) val singleton : ?cmp:('a -> 'a -> int) -> 'a -> 'b -> ('a, 'b) t val cardinal: ('a, 'b) t -> int val add : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t val find : 'a -> ('a, 'b) t -> 'b val remove : 'a -> ('a, 'b) t -> ('a, 'b) t val mem : 'a -> ('a, 'b) t -> bool val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit * [ iter f m ] applies [ f ] to all bindings in map [ m ] . [ f ] receives the key as first argument , and the associated value as second argument . The order in which the bindings are passed to [ f ] is unspecified . Only current bindings are presented to [ f ] : bindings hidden by more recent bindings are not passed to [ f ] . [f] receives the key as first argument, and the associated value as second argument. The order in which the bindings are passed to [f] is unspecified. Only current bindings are presented to [f]: bindings hidden by more recent bindings are not passed to [f]. *) val map : ('b -> 'c) -> ('a, 'b) t -> ('a, 'c) t val mapi : ('a -> 'b -> 'c) -> ('a, 'b) t -> ('a, 'c) t val fold : ('b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c * [ fold f m a ] computes [ ( f kN dN ... ( f k1 d1 ( f k0 d0 a ) ) ... ) ] , where [ k0,k1 .. kN ] are the keys of all bindings in [ m ] , and [ d0,d1 .. dN ] are the associated data . The order in which the bindings are presented to [ f ] is unspecified . where [k0,k1..kN] are the keys of all bindings in [m], and [d0,d1..dN] are the associated data. The order in which the bindings are presented to [f] is unspecified. *) val foldi : ('a -> 'b -> 'c -> 'c) -> ('a , 'b) t -> 'c -> 'c val filterv: ('a -> bool) -> ('key, 'a) t -> ('key, 'a) t val filter: ('key -> 'a -> bool) -> ('key, 'a) t -> ('key, 'a) t val filter_map: ('key -> 'a -> 'b option) -> ('key, 'a) t -> ('key, 'b) t val choose : ('key, 'a) t -> ('key * 'a) * Return one binding of the given map , or raise [ Not_found ] if the map is empty . Which binding is chosen is unspecified , but equal bindings will be chosen for equal maps . the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. *) val split : 'key -> ('key, 'a) t -> (('key, 'a) t * 'a option * ('key, 'a) t) val min_binding : ('key, 'a) t -> ('key * 'a) val max_binding : ('key, 'a) t -> ('key * 'a) val enum : ('a, 'b) t -> ('a * 'b) BatEnum.t val backwards : ('a,'b) t -> ('a * 'b) BatEnum.t val keys : ('a,'b) t -> 'a BatEnum.t val values: ('a,'b) t -> 'b BatEnum.t val of_enum : ?cmp:('a -> 'a -> int) -> ('a * 'b) BatEnum.t -> ('a, 'b) t val for_all : ('a -> 'b -> bool) -> ('a, 'b) t -> bool val exists : ('a -> 'b -> bool) -> ('a, 'b) t -> bool documentation comment from INRIA 's stdlib val partition : ('a -> 'b -> bool) -> ('a, 'b) t -> ('a, 'b) t * ('a, 'b) t val add_carry : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t * 'b option val modify : 'a -> ('b -> 'b) -> ('a, 'b) t -> ('a, 'b) t val modify_def: 'b -> 'a -> ('b -> 'b) -> ('a,'b) t -> ('a,'b) t val modify_opt: 'a -> ('b option -> 'b option) -> ('a,'b) t -> ('a,'b) t * [ modify_opt k f m ] allow to modify the binding for [ k ] in [ m ] or absence thereof . @since 2.1 or absence thereof. @since 2.1 *) val extract : 'a -> ('a, 'b) t -> 'b * ('a, 'b) t val pop : ('a, 'b) t -> ('a * 'b) * ('a, 'b) t val union : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ union ] merges two maps , using the comparison function of [ m1 ] . In case of conflicted bindings , [ m2 ] 's bindings override [ m1 ] 's . Equivalent to [ foldi add m2 m1 ] . The resulting map uses the comparison function of [ m1 ] . [m1]. In case of conflicted bindings, [m2]'s bindings override [m1]'s. Equivalent to [foldi add m2 m1]. The resulting map uses the comparison function of [m1]. *) val diff : ('a, 'b) t -> ('a, 'b) t -> ('a, 'b) t * [ diff ] removes all bindings of keys found in [ m2 ] from [ m1 ] , using the comparison function of [ m1 ] . Equivalent to [ foldi ( fun k _ v m - > remove k m ) m2 m1 ] The resulting map uses the comparison function of [ m1 ] . using the comparison function of [m1]. Equivalent to [foldi (fun k _v m -> remove k m) m2 m1] The resulting map uses the comparison function of [m1].*) val intersect : ('b -> 'c -> 'd) -> ('a, 'b) t -> ('a, 'c) t -> ('a, 'd) t * [ intersect merge_f m1 m2 ] returns a map with bindings only for keys bound in both [ m1 ] and [ m2 ] , and with [ k ] bound to [ merge_f v1 v2 ] , where [ v1 ] and [ v2 ] are [ k ] 's bindings in [ m1 ] and [ m2 ] . The resulting map uses the comparison function of [ m1 ] . keys bound in both [m1] and [m2], and with [k] bound to [merge_f v1 v2], where [v1] and [v2] are [k]'s bindings in [m1] and [m2]. The resulting map uses the comparison function of [m1]. *) val merge: ('key -> 'a option -> 'b option -> 'c option) -> ('key, 'a) t -> ('key, 'b) t -> ('key, 'c) t val merge_unsafe: ('key -> 'a option -> 'b option -> 'c option) -> ('key, 'a) t -> ('key, 'b) t -> ('key, 'c) t * Same as merge , but assumes the comparison function of both maps are equal . If it 's not the case , the result is a map using the comparison function of its first parameter , but which [ ' b option ] elements are passed to the function is unspecified . are equal. If it's not the case, the result is a map using the comparison function of its first parameter, but which ['b option] elements are passed to the function is unspecified. *) val compare: ('b -> 'b -> int) -> ('a,'b) t -> ('a, 'b) t -> int val equal : ('b -> 'b -> bool) -> ('a,'b) t -> ('a, 'b) t -> bool module Exceptionless : sig val find: 'a -> ('a,'b) t -> 'b option end * Infix operators over a { ! } module Infix : sig val (-->) : ('a, 'b) t -> 'a -> 'b val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t * [ , value ) ] returns a map containing the same bindings as [ map ] , plus a binding of [ key ] to [ value ] . If [ key ] was already bound in [ map ] , its previous binding disappears . Equivalent to [ add key value map ] [map], plus a binding of [key] to [value]. If [key] was already bound in [map], its previous binding disappears. Equivalent to [add key value map]*) end * Map find and insert from Infix val (-->) : ('a, 'b) t -> 'a -> 'b val (<--) : ('a, 'b) t -> 'a * 'b -> ('a, 'b) t val bindings : ('key, 'a) t -> ('key * 'a) list * Return the list of all bindings of the given map . The returned list is sorted in increasing key order . Added for compatibility with stdlib 3.12 The returned list is sorted in increasing key order. Added for compatibility with stdlib 3.12 *) * { 7 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ?kvsep:string -> ('a BatInnerIO.output -> 'b -> unit) -> ('a BatInnerIO.output -> 'c -> unit) -> 'a BatInnerIO.output -> ('b, 'c) t -> unit val get_cmp : ('a, 'b) t -> ('a -> 'a -> int) PMap module
d20f355c9dd2f120fefe9cd4220725d483a95478c08b6eadd2e4373384106ce3
amuletml/amulet
TypeOverlay.hs
# LANGUAGE DeriveGeneric , OverloadedStrings , DuplicateRecordFields , FlexibleContexts , TypeFamilies # module AmuletLsp.Features.TypeOverlay ( OverlayData(OverlayData) , getTypeOverlay , resolveTypeOverlay ) where import Control.Lens hiding (List) import qualified Data.Text as T import Data.Aeson.Types import Data.Foldable import Data.Span import GHC.Generics import Language.LSP.Types import Syntax.Types import Syntax import AmuletLsp.Features import Text.Pretty.Semantic data OverlayData = OverlayData { name :: T.Text , id :: Int , file :: Int } deriving Generic instance ToJSON OverlayData instance FromJSON OverlayData -- | Get the unresolved type overlay for this program. -- -- The provided name is the unique "name" for this file. While we could pass the ' NormalizedUri ' , this should be more memory efficient . getTypeOverlay :: Name -> [Toplevel Resolved] -> [CodeLens] getTypeOverlay (TgName _ modu) = getTops [] where getTop ac (LetStmt _ _ b _) = foldl getBinding ac b getTop ac (Module _ _ (ModStruct ms _)) = getTops ac ms getTop ac (Open (ModStruct ms _)) = getTops ac ms getTop ac (Include (ModStruct ms _)) = getTops ac ms getTop ac _ = ac getTops = foldl' getTop mk :: Var Resolved -> Span -> CodeLens mk (TgName c n) p = CodeLens (firstLine (rangeOf p)) Nothing (Just (toJSON (OverlayData c n modu))) mk TgInternal{} _ = error "Impossible binding to TgInternal" getBinding :: [CodeLens] -> Binding Resolved -> [CodeLens] getBinding ac (Binding v vp _ _ _) = mk v vp:ac getBinding ac (Matching p _ pos) | Just v <- singleVar p = mk v pos:ac getBinding ac _ = ac singleVar :: Pattern Resolved -> Maybe (Var Resolved) singleVar (Capture v _) = Just v singleVar (PType p _ _) = singleVar p singleVar _ = Nothing getTypeOverlay TgInternal{} = error "Impossible" -- | Resolve a type overlay, updating the lens with the type of the -- embedded variable. resolveTypeOverlay :: Env -> OverlayData -> CodeLens -> Maybe CodeLens resolveTypeOverlay env (OverlayData v n _) (CodeLens range Nothing _) = let var = TgName v n in case env ^. names . at var of Nothing -> Nothing Just ty -> let cmd = Command (renderBasic $ pretty var <+> colon <+> displayTypeTyped ty) "" Nothing in Just (CodeLens range (Just cmd) Nothing) resolveTypeOverlay _ _ c@(CodeLens _ Just{} _) = Just c
null
https://raw.githubusercontent.com/amuletml/amulet/fcba0b7e198b8d354e95722bbe118bccc8483f4e/bin/AmuletLsp/Features/TypeOverlay.hs
haskell
| Get the unresolved type overlay for this program. The provided name is the unique "name" for this file. While we could | Resolve a type overlay, updating the lens with the type of the embedded variable.
# LANGUAGE DeriveGeneric , OverloadedStrings , DuplicateRecordFields , FlexibleContexts , TypeFamilies # module AmuletLsp.Features.TypeOverlay ( OverlayData(OverlayData) , getTypeOverlay , resolveTypeOverlay ) where import Control.Lens hiding (List) import qualified Data.Text as T import Data.Aeson.Types import Data.Foldable import Data.Span import GHC.Generics import Language.LSP.Types import Syntax.Types import Syntax import AmuletLsp.Features import Text.Pretty.Semantic data OverlayData = OverlayData { name :: T.Text , id :: Int , file :: Int } deriving Generic instance ToJSON OverlayData instance FromJSON OverlayData pass the ' NormalizedUri ' , this should be more memory efficient . getTypeOverlay :: Name -> [Toplevel Resolved] -> [CodeLens] getTypeOverlay (TgName _ modu) = getTops [] where getTop ac (LetStmt _ _ b _) = foldl getBinding ac b getTop ac (Module _ _ (ModStruct ms _)) = getTops ac ms getTop ac (Open (ModStruct ms _)) = getTops ac ms getTop ac (Include (ModStruct ms _)) = getTops ac ms getTop ac _ = ac getTops = foldl' getTop mk :: Var Resolved -> Span -> CodeLens mk (TgName c n) p = CodeLens (firstLine (rangeOf p)) Nothing (Just (toJSON (OverlayData c n modu))) mk TgInternal{} _ = error "Impossible binding to TgInternal" getBinding :: [CodeLens] -> Binding Resolved -> [CodeLens] getBinding ac (Binding v vp _ _ _) = mk v vp:ac getBinding ac (Matching p _ pos) | Just v <- singleVar p = mk v pos:ac getBinding ac _ = ac singleVar :: Pattern Resolved -> Maybe (Var Resolved) singleVar (Capture v _) = Just v singleVar (PType p _ _) = singleVar p singleVar _ = Nothing getTypeOverlay TgInternal{} = error "Impossible" resolveTypeOverlay :: Env -> OverlayData -> CodeLens -> Maybe CodeLens resolveTypeOverlay env (OverlayData v n _) (CodeLens range Nothing _) = let var = TgName v n in case env ^. names . at var of Nothing -> Nothing Just ty -> let cmd = Command (renderBasic $ pretty var <+> colon <+> displayTypeTyped ty) "" Nothing in Just (CodeLens range (Just cmd) Nothing) resolveTypeOverlay _ _ c@(CodeLens _ Just{} _) = Just c
80eb16b1cf89901eb503b8cbbf50db46a9302541f4837ec9b8d737c93ed1c7bc
fetburner/Coq2SML
ccproof.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (* This file uses the (non-compressed) union-find structure to generate *) (* proof-trees that will be transformed into proof-terms in cctac.ml4 *) open Util open Names open Term open Ccalgo type rule= Ax of constr | SymAx of constr | Refl of term | Trans of proof*proof | Congr of proof*proof | Inject of proof*constructor*int*int and proof = {p_lhs:term;p_rhs:term;p_rule:rule} let prefl t = {p_lhs=t;p_rhs=t;p_rule=Refl t} let pcongr p1 p2 = match p1.p_rule,p2.p_rule with Refl t1, Refl t2 -> prefl (Appli (t1,t2)) | _, _ -> {p_lhs=Appli (p1.p_lhs,p2.p_lhs); p_rhs=Appli (p1.p_rhs,p2.p_rhs); p_rule=Congr (p1,p2)} let rec ptrans p1 p3= match p1.p_rule,p3.p_rule with Refl _, _ ->p3 | _, Refl _ ->p1 | Trans(p1,p2), _ ->ptrans p1 (ptrans p2 p3) | Congr(p1,p2), Congr(p3,p4) ->pcongr (ptrans p1 p3) (ptrans p2 p4) | Congr(p1,p2), Trans({p_rule=Congr(p3,p4)},p5) -> ptrans (pcongr (ptrans p1 p3) (ptrans p2 p4)) p5 | _, _ -> if term_equal p1.p_rhs p3.p_lhs then {p_lhs=p1.p_lhs; p_rhs=p3.p_rhs; p_rule=Trans (p1,p3)} else anomaly "invalid cc transitivity" let rec psym p = match p.p_rule with Refl _ -> p | SymAx s -> {p_lhs=p.p_rhs; p_rhs=p.p_lhs; p_rule=Ax s} | Ax s-> {p_lhs=p.p_rhs; p_rhs=p.p_lhs; p_rule=SymAx s} | Inject (p0,c,n,a)-> {p_lhs=p.p_rhs; p_rhs=p.p_lhs; p_rule=Inject (psym p0,c,n,a)} | Trans (p1,p2)-> ptrans (psym p2) (psym p1) | Congr (p1,p2)-> pcongr (psym p1) (psym p2) let pax axioms s = let l,r = Constrhash.find axioms s in {p_lhs=l; p_rhs=r; p_rule=Ax s} let psymax axioms s = let l,r = Constrhash.find axioms s in {p_lhs=r; p_rhs=l; p_rule=SymAx s} let rec nth_arg t n= match t with Appli (t1,t2)-> if n>0 then nth_arg t1 (n-1) else t2 | _ -> anomaly "nth_arg: not enough args" let pinject p c n a = {p_lhs=nth_arg p.p_lhs (n-a); p_rhs=nth_arg p.p_rhs (n-a); p_rule=Inject(p,c,n,a)} let build_proof uf= let axioms = axioms uf in let rec equal_proof i j= if i=j then prefl (term uf i) else let (li,lj)=join_path uf i j in ptrans (path_proof i li) (psym (path_proof j lj)) and edge_proof ((i,j),eq)= let pi=equal_proof i eq.lhs in let pj=psym (equal_proof j eq.rhs) in let pij= match eq.rule with Axiom (s,reversed)-> if reversed then psymax axioms s else pax axioms s | Congruence ->congr_proof eq.lhs eq.rhs | Injection (ti,ipac,tj,jpac,k) -> let p=ind_proof ti ipac tj jpac in let cinfo= get_constructor_info uf ipac.cnode in pinject p cinfo.ci_constr cinfo.ci_nhyps k in ptrans (ptrans pi pij) pj and constr_proof i t ipac= if ipac.args=[] then equal_proof i t else let npac=tail_pac ipac in let (j,arg)=subterms uf t in let targ=term uf arg in let rj=find uf j in let u=find_pac uf rj npac in let p=constr_proof j u npac in ptrans (equal_proof i t) (pcongr p (prefl targ)) and path_proof i=function [] -> prefl (term uf i) | x::q->ptrans (path_proof (snd (fst x)) q) (edge_proof x) and congr_proof i j= let (i1,i2) = subterms uf i and (j1,j2) = subterms uf j in pcongr (equal_proof i1 j1) (equal_proof i2 j2) and ind_proof i ipac j jpac= let p=equal_proof i j and p1=constr_proof i i ipac and p2=constr_proof j j jpac in ptrans (psym p1) (ptrans p p2) in function `Prove (i,j) -> equal_proof i j | `Discr (i,ci,j,cj)-> ind_proof i ci j cj
null
https://raw.githubusercontent.com/fetburner/Coq2SML/322d613619edbb62edafa999bff24b1993f37612/coq-8.4pl4/plugins/cc/ccproof.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** This file uses the (non-compressed) union-find structure to generate proof-trees that will be transformed into proof-terms in cctac.ml4
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Util open Names open Term open Ccalgo type rule= Ax of constr | SymAx of constr | Refl of term | Trans of proof*proof | Congr of proof*proof | Inject of proof*constructor*int*int and proof = {p_lhs:term;p_rhs:term;p_rule:rule} let prefl t = {p_lhs=t;p_rhs=t;p_rule=Refl t} let pcongr p1 p2 = match p1.p_rule,p2.p_rule with Refl t1, Refl t2 -> prefl (Appli (t1,t2)) | _, _ -> {p_lhs=Appli (p1.p_lhs,p2.p_lhs); p_rhs=Appli (p1.p_rhs,p2.p_rhs); p_rule=Congr (p1,p2)} let rec ptrans p1 p3= match p1.p_rule,p3.p_rule with Refl _, _ ->p3 | _, Refl _ ->p1 | Trans(p1,p2), _ ->ptrans p1 (ptrans p2 p3) | Congr(p1,p2), Congr(p3,p4) ->pcongr (ptrans p1 p3) (ptrans p2 p4) | Congr(p1,p2), Trans({p_rule=Congr(p3,p4)},p5) -> ptrans (pcongr (ptrans p1 p3) (ptrans p2 p4)) p5 | _, _ -> if term_equal p1.p_rhs p3.p_lhs then {p_lhs=p1.p_lhs; p_rhs=p3.p_rhs; p_rule=Trans (p1,p3)} else anomaly "invalid cc transitivity" let rec psym p = match p.p_rule with Refl _ -> p | SymAx s -> {p_lhs=p.p_rhs; p_rhs=p.p_lhs; p_rule=Ax s} | Ax s-> {p_lhs=p.p_rhs; p_rhs=p.p_lhs; p_rule=SymAx s} | Inject (p0,c,n,a)-> {p_lhs=p.p_rhs; p_rhs=p.p_lhs; p_rule=Inject (psym p0,c,n,a)} | Trans (p1,p2)-> ptrans (psym p2) (psym p1) | Congr (p1,p2)-> pcongr (psym p1) (psym p2) let pax axioms s = let l,r = Constrhash.find axioms s in {p_lhs=l; p_rhs=r; p_rule=Ax s} let psymax axioms s = let l,r = Constrhash.find axioms s in {p_lhs=r; p_rhs=l; p_rule=SymAx s} let rec nth_arg t n= match t with Appli (t1,t2)-> if n>0 then nth_arg t1 (n-1) else t2 | _ -> anomaly "nth_arg: not enough args" let pinject p c n a = {p_lhs=nth_arg p.p_lhs (n-a); p_rhs=nth_arg p.p_rhs (n-a); p_rule=Inject(p,c,n,a)} let build_proof uf= let axioms = axioms uf in let rec equal_proof i j= if i=j then prefl (term uf i) else let (li,lj)=join_path uf i j in ptrans (path_proof i li) (psym (path_proof j lj)) and edge_proof ((i,j),eq)= let pi=equal_proof i eq.lhs in let pj=psym (equal_proof j eq.rhs) in let pij= match eq.rule with Axiom (s,reversed)-> if reversed then psymax axioms s else pax axioms s | Congruence ->congr_proof eq.lhs eq.rhs | Injection (ti,ipac,tj,jpac,k) -> let p=ind_proof ti ipac tj jpac in let cinfo= get_constructor_info uf ipac.cnode in pinject p cinfo.ci_constr cinfo.ci_nhyps k in ptrans (ptrans pi pij) pj and constr_proof i t ipac= if ipac.args=[] then equal_proof i t else let npac=tail_pac ipac in let (j,arg)=subterms uf t in let targ=term uf arg in let rj=find uf j in let u=find_pac uf rj npac in let p=constr_proof j u npac in ptrans (equal_proof i t) (pcongr p (prefl targ)) and path_proof i=function [] -> prefl (term uf i) | x::q->ptrans (path_proof (snd (fst x)) q) (edge_proof x) and congr_proof i j= let (i1,i2) = subterms uf i and (j1,j2) = subterms uf j in pcongr (equal_proof i1 j1) (equal_proof i2 j2) and ind_proof i ipac j jpac= let p=equal_proof i j and p1=constr_proof i i ipac and p2=constr_proof j j jpac in ptrans (psym p1) (ptrans p p2) in function `Prove (i,j) -> equal_proof i j | `Discr (i,ci,j,cj)-> ind_proof i ci j cj
f2a2b544fffb328c7cee2cf632d0acbb25eae4bdf3062b77df37e6acb04d6a3a
rvalentini/fix.core
field_generator.clj
(ns fix.generator.field-generator (:require [fix.parser.xml-parser :as parser] [taoensso.timbre :refer [info]])) (defn- extract-enums [value-tags] (let [result (map (fn [value-tag] {(get-in value-tag [:attrs :enum]) (get-in value-tag [:attrs :description])}) value-tags)] (reduce merge {} result))) (defn- extract-definition [fields] (info "Number of fields found:" (count fields)) (let [gen-fields (map (fn [field] (let [name (get-in field [:attrs :name]) type (keyword (get-in field [:attrs :type])) number (keyword (get-in field [:attrs :number])) enums (extract-enums (get-in field [:content])) result {number {:name name :type type}}] (if (not-empty enums) (assoc-in result [number :values] enums) result))) fields)] (reduce merge {} gen-fields))) (defn- generate-source-file [fields] (spit "resources/fields.edn" (extract-definition fields))) (defn -main [& _] (info "Generating FIX5.0 SP2 FIELD sources ... !") (let [[fields _] (parser/parse "resources/FIX50SP2_FIXT11_combined.xml")] (generate-source-file fields)))
null
https://raw.githubusercontent.com/rvalentini/fix.core/bb4476842d0c876f8cced95b3e350cf64ce3ceae/src/fix/generator/field_generator.clj
clojure
(ns fix.generator.field-generator (:require [fix.parser.xml-parser :as parser] [taoensso.timbre :refer [info]])) (defn- extract-enums [value-tags] (let [result (map (fn [value-tag] {(get-in value-tag [:attrs :enum]) (get-in value-tag [:attrs :description])}) value-tags)] (reduce merge {} result))) (defn- extract-definition [fields] (info "Number of fields found:" (count fields)) (let [gen-fields (map (fn [field] (let [name (get-in field [:attrs :name]) type (keyword (get-in field [:attrs :type])) number (keyword (get-in field [:attrs :number])) enums (extract-enums (get-in field [:content])) result {number {:name name :type type}}] (if (not-empty enums) (assoc-in result [number :values] enums) result))) fields)] (reduce merge {} gen-fields))) (defn- generate-source-file [fields] (spit "resources/fields.edn" (extract-definition fields))) (defn -main [& _] (info "Generating FIX5.0 SP2 FIELD sources ... !") (let [[fields _] (parser/parse "resources/FIX50SP2_FIXT11_combined.xml")] (generate-source-file fields)))
4e44fa421a03725e55c59a58f958b1be7002d1e05887e2930539fe2c4fb5a597
rems-project/cerberus
pp_prelude.ml
module P = PPrint let (!^) = P.(!^) let (^^) = P.(^^) let (^/^) = P.(^/^) let (^//^) = P.(^//^) let (^^^) x y = TODO , was : x ^^ P.space ^^ y if P.requirement y = 0 then x else x ^^ P.space ^^ y let comma_list f = P.separate_map ( P.comma ^^ P.space ) f let comma_list f xs = P.flow (P.comma ^^ P.break 1) (List.map f xs) let semi_list f = P.separate_map ( P.semi ^^ P.space ) f let semi_list f xs = P.flow (P.semi ^^ P.break 1) (List.map f xs) let with_grouped_arg d1 d2 = P.ifflat (d1 ^^ P.parens d2) (d1 ^^ P.parens (P.nest 2 (P.hardline ^^ d2) ^^ P.hardline)) let with_grouped_args ?(sep=P.comma) d1 ds = P.ifflat (d1 ^^ P.parens (P.separate (sep ^^ P.space) ds)) (d1 ^^ P.parens (P.separate_map P.comma (fun z -> P.nest 2 (P.hardline ^^ z) ^^ P.hardline) ds))
null
https://raw.githubusercontent.com/rems-project/cerberus/dbfab2643ce6cedb54d2a52cbcb3673e03bfd161/util/pp_prelude.ml
ocaml
module P = PPrint let (!^) = P.(!^) let (^^) = P.(^^) let (^/^) = P.(^/^) let (^//^) = P.(^//^) let (^^^) x y = TODO , was : x ^^ P.space ^^ y if P.requirement y = 0 then x else x ^^ P.space ^^ y let comma_list f = P.separate_map ( P.comma ^^ P.space ) f let comma_list f xs = P.flow (P.comma ^^ P.break 1) (List.map f xs) let semi_list f = P.separate_map ( P.semi ^^ P.space ) f let semi_list f xs = P.flow (P.semi ^^ P.break 1) (List.map f xs) let with_grouped_arg d1 d2 = P.ifflat (d1 ^^ P.parens d2) (d1 ^^ P.parens (P.nest 2 (P.hardline ^^ d2) ^^ P.hardline)) let with_grouped_args ?(sep=P.comma) d1 ds = P.ifflat (d1 ^^ P.parens (P.separate (sep ^^ P.space) ds)) (d1 ^^ P.parens (P.separate_map P.comma (fun z -> P.nest 2 (P.hardline ^^ z) ^^ P.hardline) ds))
9254949392a823877d66828a8f736f810aba67b8083eef41440ab08e099c02be
erlang/otp
id_transform_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2003 - 2022 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(id_transform_SUITE). -author(''). -include_lib("kernel/include/file.hrl"). -export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1, init_per_group/2,end_per_group/2, id_transform/1]). -export([check/2,check2/1,g/0,f/1,t/1,t1/1,t2/1,t3/1,t4/1, t5/1,apa/1,new_fun/0]). %% Serves as test... -hej(hopp). -include_lib("common_test/include/ct.hrl"). suite() -> [{ct_hooks,[ts_install_cth]}]. all() -> [id_transform]. groups() -> []. init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. %% Test erl_id_trans. id_transform(Config) when is_list(Config) -> File = filename:join([code:lib_dir(stdlib),"examples", "erl_id_trans.erl"]), {ok,erl_id_trans,Bin} = compile:file(File, [binary,report]), {module,erl_id_trans} = code:load_binary(erl_id_trans, File, Bin), case test_server:is_valgrind() of false -> ct:timetrap({hours,1}), run_in_test_suite(); true -> {skip,"Valgrind (too slow)"} end. run_in_test_suite() -> SuperDir = filename:dirname(filename:dirname(code:which(?MODULE))), TestDirs = filelib:wildcard(filename:join([SuperDir,"*_test"])), AbsDirs = [filename:absname(X) || X <- code:get_path()], Dirs = ordsets:from_list(AbsDirs ++ TestDirs), run_list(Dirs). run_list(PathL) -> io:format("Where to search for beam files:\n~p\n", [PathL]), io:format("Searching for beam files ...~n",[]), Beams = collect_beams(PathL, []), io:format("~p beam files\n", [length(Beams)]), io:format("Applying erl_id_trans to found beam files...~n",[]), Res = [do_trans(X) || X <- Beams], io:format("...done~n",[]), Successes = [X || {ok,X} <- Res], SevereFailures = [{F,E} || {failed,{F,{transform,E}}} <- Res], BeamLib = [{F,E} || {failed,{F,{beam_lib,E}}} <- Res], io:format("~p files processed", [length(Res)]), io:format("~p files successfully transformed", [length(Successes)]), case length(SevereFailures) of 0 -> ok; SevLen -> io:format("\n~p severe failures:\n~p", [SevLen,SevereFailures]) end, case BeamLib of [] -> ok; _ -> io:format("\nbeam_lib failures:\n~p", [BeamLib]) end, case length(SevereFailures) of 0 -> ok; Len -> {failed,integer_to_list(Len)++" failures"} end. collect_beams([P0|Ps], Acc) -> Wc = filename:join(filename:absname(P0), "*.beam"), collect_beams(Ps, filelib:wildcard(Wc)++Acc); collect_beams([], Acc) -> Acc. do_trans(Beam) -> case beam_lib:chunks(Beam, [abstract_code]) of {ok,{_Mod,[{abstract_code,no_abstract_code}]}} -> {failed,{Beam,{beam_lib,no_debug_info}}}; {ok,{_Mod,[{abstract_code,{raw_abstract_v1,Abst}}]}} -> do_trans_1(Beam, Abst); {ok,{_Mod,[{abstract_code,{Tag,_}}]}} -> {failed,{Beam,{beam_lib,{wrong_type_of_debug_info,Tag}}}}; {ok,{_Mod,[{abstract_code,_}]}} -> {failed,{Beam,{beam_lib,unknown_type_of_debug_info}}}; {error,beam_lib,{missing_chunk,_,_}} -> {failed,{Beam,{beam_lib,no_debug_info}}}; Error -> {failed,{Beam,{beam_lib,Error}}} end. do_trans_1(File, Tree0) -> case catch erl_id_trans:parse_transform(Tree0, []) of Tree0 when is_list(Tree0) -> {ok,File}; Tree when is_list(Tree) -> {failed,{File,{transform,output_not_same_as_input}}}; {'EXIT', Reason} -> {failed,{File,{transform,{crash,Reason}}}}; Else -> {failed,{File,{transform,{unknown,Else}}}} end. %% From here on there's only fake code to serve as test cases %% for the id_transform. %% They need to be exported. check(X,_Y) when X -> true; check(A,_) when atom(A) -> atom; check(A,_) when erlang:is_list(A) -> list; check(A,B) when erlang:'+'(A,B) -> atom; check(_,_) -> false. check2(A) -> case A of "hej" ++ "hopp" -> a; [$l,$e,$k] ++ "hopp" -> a; [1] ++ [2] -> b end. -record(x,{x,y}). -record(y,{x=1,y=0}). g() -> #y.y. f(#y.y) -> vansinne; f(X) when X =:= #y.y -> {#y.y,_Y} = {X,hej}; f(#x{_='_'}) -> hopp; f(#x{x=true,y=true}) -> babba; f(A) when A == #x{x=true,y=true} -> true; f(A) when A#x.x == 4 -> #x{x = 1, _ = 2}; f(X) -> if X#x.y -> ok; element(3,X) -> banan; true -> nok end. Stolen from erl_lint_SUITE.erl -record(apa, {}). t(A) when atom(A) -> atom; t(A) when binary(A) -> binary; t(A) when float(A) -> float; t(A) when function(A) -> function; t(A) when integer(A) -> integer; t(A) when is_atom(A) -> is_atom; t(A) when is_binary(A) -> is_binary; t(A) when is_float(A) -> is_float; t(A) when is_function(A) -> is_function; t(A) when is_integer(A) -> is_integer; t(A) when is_list(A) -> is_list; t(A) when is_number(A) -> is_number; t(A) when is_pid(A) -> is_pid; t(A) when is_port(A) -> is_port; t(A) when is_record(A, apa) -> is_record; t(A) when is_reference(A) -> is_reference; t(A) when is_tuple(A) -> is_tuple; t(A) when list(A) -> list; t(A) when number(A) -> number; t(A) when pid(A) -> pid; t(A) when port(A) -> port; t(A) when record(A, apa) -> record; t(A) when reference(A) -> reference; t(A) when tuple(A) -> tuple. t1(A) when atom(A), atom(A) -> atom; t1(A) when binary(A), binary(A) -> binary; t1(A) when float(A), float(A) -> float; t1(A) when function(A), function(A) -> function; t1(A) when integer(A), integer(A) -> integer; t1(A) when is_atom(A), is_atom(A) -> is_atom; t1(A) when is_binary(A), is_binary(A) -> is_binary; t1(A) when is_float(A), is_float(A) -> is_float; t1(A) when is_function(A), is_function(A) -> is_function; t1(A) when is_integer(A), is_integer(A) -> is_integer; t1(A) when is_list(A), is_list(A) -> is_list; t1(A) when is_number(A), is_number(A) -> is_number; t1(A) when is_pid(A), is_pid(A) -> is_pid; t1(A) when is_port(A), is_port(A) -> is_port; t1(A) when is_record(A, apa), is_record(A, apa) -> is_record; t1(A) when is_reference(A), is_reference(A) -> is_reference; t1(A) when is_tuple(A), is_tuple(A) -> is_tuple; t1(A) when list(A), list(A) -> list; t1(A) when number(A), number(A) -> number; t1(A) when pid(A), pid(A) -> pid; t1(A) when port(A), port(A) -> port; t1(A) when record(A, apa), record(A, apa) -> record; t1(A) when reference(A), reference(A) -> reference; t1(A) when tuple(A), tuple(A) -> tuple. t2(A) when atom(A); atom(A) -> atom; t2(A) when binary(A); binary(A) -> binary; t2(A) when float(A); float(A) -> float; t2(A) when function(A); function(A) -> function; t2(A) when integer(A); integer(A) -> integer; t2(A) when is_atom(A); is_atom(A) -> is_atom; t2(A) when is_binary(A); is_binary(A) -> is_binary; t2(A) when is_float(A); is_float(A) -> is_float; t2(A) when is_function(A); is_function(A) -> is_function; t2(A) when is_integer(A); is_integer(A) -> is_integer; t2(A) when is_list(A); is_list(A) -> is_list; t2(A) when is_number(A); is_number(A) -> is_number; t2(A) when is_pid(A); is_pid(A) -> is_pid; t2(A) when is_port(A); is_port(A) -> is_port; t2(A) when is_record(A, apa); is_record(A, apa) -> is_record; t2(A) when is_reference(A); is_reference(A) -> is_reference; t2(A) when is_tuple(A); is_tuple(A) -> is_tuple; t2(A) when list(A); list(A) -> list; t2(A) when number(A); number(A) -> number; t2(A) when pid(A); pid(A) -> pid; t2(A) when port(A); port(A) -> port; t2(A) when record(A, apa); record(A, apa) -> record; t2(A) when reference(A); reference(A) -> reference; t2(A) when tuple(A); tuple(A) -> tuple. t3(A) when is_atom(A) or is_atom(A) -> is_atom; t3(A) when is_binary(A) or is_binary(A) -> is_binary; t3(A) when is_float(A) or is_float(A) -> is_float; t3(A) when is_function(A) or is_function(A) -> is_function; t3(A) when is_integer(A) or is_integer(A) -> is_integer; t3(A) when is_list(A) or is_list(A) -> is_list; t3(A) when is_number(A) or is_number(A) -> is_number; t3(A) when is_pid(A) or is_pid(A) -> is_pid; t3(A) when is_port(A) or is_port(A) -> is_port; t3(A) when is_record(A, apa) or is_record(A, apa) -> is_record; t3(A) when is_reference(A) or is_reference(A) -> is_reference; t3(A) when is_tuple(A) or is_tuple(A) -> is_tuple; t3(A) when record(A, apa) -> foo; t3(A) when erlang:is_record(A, apa) -> foo; t3(A) when is_record(A, apa) -> foo; t3(A) when record({apa}, apa) -> {A,foo}. t4(A) when erlang:is_record({apa}, apa) -> {A,foo}. t5(A) when is_record({apa}, apa) -> {A,foo}. -record(apa2,{a=a,b=foo:bar()}). apa(1) -> [X || X <- [], #apa2{a = a} == {r,X,foo}]; apa(2) -> [X || X <- [], #apa2{b = b} == {r,X,foo}]; apa(3) -> [X || X <- [], 3 == X#apa2.a]. new_fun() -> lists:map(fun erlang:abs/1, [-1,3,4]).
null
https://raw.githubusercontent.com/erlang/otp/eccc556e79f315d1f87c10fb46f2c4af50a63f20/lib/stdlib/test/id_transform_SUITE.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% Serves as test... Test erl_id_trans. From here on there's only fake code to serve as test cases for the id_transform. They need to be exported.
Copyright Ericsson AB 2003 - 2022 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(id_transform_SUITE). -author(''). -include_lib("kernel/include/file.hrl"). -export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1, init_per_group/2,end_per_group/2, id_transform/1]). -export([check/2,check2/1,g/0,f/1,t/1,t1/1,t2/1,t3/1,t4/1, t5/1,apa/1,new_fun/0]). -hej(hopp). -include_lib("common_test/include/ct.hrl"). suite() -> [{ct_hooks,[ts_install_cth]}]. all() -> [id_transform]. groups() -> []. init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. id_transform(Config) when is_list(Config) -> File = filename:join([code:lib_dir(stdlib),"examples", "erl_id_trans.erl"]), {ok,erl_id_trans,Bin} = compile:file(File, [binary,report]), {module,erl_id_trans} = code:load_binary(erl_id_trans, File, Bin), case test_server:is_valgrind() of false -> ct:timetrap({hours,1}), run_in_test_suite(); true -> {skip,"Valgrind (too slow)"} end. run_in_test_suite() -> SuperDir = filename:dirname(filename:dirname(code:which(?MODULE))), TestDirs = filelib:wildcard(filename:join([SuperDir,"*_test"])), AbsDirs = [filename:absname(X) || X <- code:get_path()], Dirs = ordsets:from_list(AbsDirs ++ TestDirs), run_list(Dirs). run_list(PathL) -> io:format("Where to search for beam files:\n~p\n", [PathL]), io:format("Searching for beam files ...~n",[]), Beams = collect_beams(PathL, []), io:format("~p beam files\n", [length(Beams)]), io:format("Applying erl_id_trans to found beam files...~n",[]), Res = [do_trans(X) || X <- Beams], io:format("...done~n",[]), Successes = [X || {ok,X} <- Res], SevereFailures = [{F,E} || {failed,{F,{transform,E}}} <- Res], BeamLib = [{F,E} || {failed,{F,{beam_lib,E}}} <- Res], io:format("~p files processed", [length(Res)]), io:format("~p files successfully transformed", [length(Successes)]), case length(SevereFailures) of 0 -> ok; SevLen -> io:format("\n~p severe failures:\n~p", [SevLen,SevereFailures]) end, case BeamLib of [] -> ok; _ -> io:format("\nbeam_lib failures:\n~p", [BeamLib]) end, case length(SevereFailures) of 0 -> ok; Len -> {failed,integer_to_list(Len)++" failures"} end. collect_beams([P0|Ps], Acc) -> Wc = filename:join(filename:absname(P0), "*.beam"), collect_beams(Ps, filelib:wildcard(Wc)++Acc); collect_beams([], Acc) -> Acc. do_trans(Beam) -> case beam_lib:chunks(Beam, [abstract_code]) of {ok,{_Mod,[{abstract_code,no_abstract_code}]}} -> {failed,{Beam,{beam_lib,no_debug_info}}}; {ok,{_Mod,[{abstract_code,{raw_abstract_v1,Abst}}]}} -> do_trans_1(Beam, Abst); {ok,{_Mod,[{abstract_code,{Tag,_}}]}} -> {failed,{Beam,{beam_lib,{wrong_type_of_debug_info,Tag}}}}; {ok,{_Mod,[{abstract_code,_}]}} -> {failed,{Beam,{beam_lib,unknown_type_of_debug_info}}}; {error,beam_lib,{missing_chunk,_,_}} -> {failed,{Beam,{beam_lib,no_debug_info}}}; Error -> {failed,{Beam,{beam_lib,Error}}} end. do_trans_1(File, Tree0) -> case catch erl_id_trans:parse_transform(Tree0, []) of Tree0 when is_list(Tree0) -> {ok,File}; Tree when is_list(Tree) -> {failed,{File,{transform,output_not_same_as_input}}}; {'EXIT', Reason} -> {failed,{File,{transform,{crash,Reason}}}}; Else -> {failed,{File,{transform,{unknown,Else}}}} end. check(X,_Y) when X -> true; check(A,_) when atom(A) -> atom; check(A,_) when erlang:is_list(A) -> list; check(A,B) when erlang:'+'(A,B) -> atom; check(_,_) -> false. check2(A) -> case A of "hej" ++ "hopp" -> a; [$l,$e,$k] ++ "hopp" -> a; [1] ++ [2] -> b end. -record(x,{x,y}). -record(y,{x=1,y=0}). g() -> #y.y. f(#y.y) -> vansinne; f(X) when X =:= #y.y -> {#y.y,_Y} = {X,hej}; f(#x{_='_'}) -> hopp; f(#x{x=true,y=true}) -> babba; f(A) when A == #x{x=true,y=true} -> true; f(A) when A#x.x == 4 -> #x{x = 1, _ = 2}; f(X) -> if X#x.y -> ok; element(3,X) -> banan; true -> nok end. Stolen from erl_lint_SUITE.erl -record(apa, {}). t(A) when atom(A) -> atom; t(A) when binary(A) -> binary; t(A) when float(A) -> float; t(A) when function(A) -> function; t(A) when integer(A) -> integer; t(A) when is_atom(A) -> is_atom; t(A) when is_binary(A) -> is_binary; t(A) when is_float(A) -> is_float; t(A) when is_function(A) -> is_function; t(A) when is_integer(A) -> is_integer; t(A) when is_list(A) -> is_list; t(A) when is_number(A) -> is_number; t(A) when is_pid(A) -> is_pid; t(A) when is_port(A) -> is_port; t(A) when is_record(A, apa) -> is_record; t(A) when is_reference(A) -> is_reference; t(A) when is_tuple(A) -> is_tuple; t(A) when list(A) -> list; t(A) when number(A) -> number; t(A) when pid(A) -> pid; t(A) when port(A) -> port; t(A) when record(A, apa) -> record; t(A) when reference(A) -> reference; t(A) when tuple(A) -> tuple. t1(A) when atom(A), atom(A) -> atom; t1(A) when binary(A), binary(A) -> binary; t1(A) when float(A), float(A) -> float; t1(A) when function(A), function(A) -> function; t1(A) when integer(A), integer(A) -> integer; t1(A) when is_atom(A), is_atom(A) -> is_atom; t1(A) when is_binary(A), is_binary(A) -> is_binary; t1(A) when is_float(A), is_float(A) -> is_float; t1(A) when is_function(A), is_function(A) -> is_function; t1(A) when is_integer(A), is_integer(A) -> is_integer; t1(A) when is_list(A), is_list(A) -> is_list; t1(A) when is_number(A), is_number(A) -> is_number; t1(A) when is_pid(A), is_pid(A) -> is_pid; t1(A) when is_port(A), is_port(A) -> is_port; t1(A) when is_record(A, apa), is_record(A, apa) -> is_record; t1(A) when is_reference(A), is_reference(A) -> is_reference; t1(A) when is_tuple(A), is_tuple(A) -> is_tuple; t1(A) when list(A), list(A) -> list; t1(A) when number(A), number(A) -> number; t1(A) when pid(A), pid(A) -> pid; t1(A) when port(A), port(A) -> port; t1(A) when record(A, apa), record(A, apa) -> record; t1(A) when reference(A), reference(A) -> reference; t1(A) when tuple(A), tuple(A) -> tuple. t2(A) when atom(A); atom(A) -> atom; t2(A) when binary(A); binary(A) -> binary; t2(A) when float(A); float(A) -> float; t2(A) when function(A); function(A) -> function; t2(A) when integer(A); integer(A) -> integer; t2(A) when is_atom(A); is_atom(A) -> is_atom; t2(A) when is_binary(A); is_binary(A) -> is_binary; t2(A) when is_float(A); is_float(A) -> is_float; t2(A) when is_function(A); is_function(A) -> is_function; t2(A) when is_integer(A); is_integer(A) -> is_integer; t2(A) when is_list(A); is_list(A) -> is_list; t2(A) when is_number(A); is_number(A) -> is_number; t2(A) when is_pid(A); is_pid(A) -> is_pid; t2(A) when is_port(A); is_port(A) -> is_port; t2(A) when is_record(A, apa); is_record(A, apa) -> is_record; t2(A) when is_reference(A); is_reference(A) -> is_reference; t2(A) when is_tuple(A); is_tuple(A) -> is_tuple; t2(A) when list(A); list(A) -> list; t2(A) when number(A); number(A) -> number; t2(A) when pid(A); pid(A) -> pid; t2(A) when port(A); port(A) -> port; t2(A) when record(A, apa); record(A, apa) -> record; t2(A) when reference(A); reference(A) -> reference; t2(A) when tuple(A); tuple(A) -> tuple. t3(A) when is_atom(A) or is_atom(A) -> is_atom; t3(A) when is_binary(A) or is_binary(A) -> is_binary; t3(A) when is_float(A) or is_float(A) -> is_float; t3(A) when is_function(A) or is_function(A) -> is_function; t3(A) when is_integer(A) or is_integer(A) -> is_integer; t3(A) when is_list(A) or is_list(A) -> is_list; t3(A) when is_number(A) or is_number(A) -> is_number; t3(A) when is_pid(A) or is_pid(A) -> is_pid; t3(A) when is_port(A) or is_port(A) -> is_port; t3(A) when is_record(A, apa) or is_record(A, apa) -> is_record; t3(A) when is_reference(A) or is_reference(A) -> is_reference; t3(A) when is_tuple(A) or is_tuple(A) -> is_tuple; t3(A) when record(A, apa) -> foo; t3(A) when erlang:is_record(A, apa) -> foo; t3(A) when is_record(A, apa) -> foo; t3(A) when record({apa}, apa) -> {A,foo}. t4(A) when erlang:is_record({apa}, apa) -> {A,foo}. t5(A) when is_record({apa}, apa) -> {A,foo}. -record(apa2,{a=a,b=foo:bar()}). apa(1) -> [X || X <- [], #apa2{a = a} == {r,X,foo}]; apa(2) -> [X || X <- [], #apa2{b = b} == {r,X,foo}]; apa(3) -> [X || X <- [], 3 == X#apa2.a]. new_fun() -> lists:map(fun erlang:abs/1, [-1,3,4]).
f839c5c7a74a2d60bff07197ae025109772742602a140defb76ce678f54be52c
silent-entertainment/claxiom
exporters.lisp
(in-package #:claxiom) (defmethod export-cell (format cell-language cell-type cell) (format t "~s~%" (list :default-cell format cell-language cell-type)) (list :exported format cell-language cell-type (mapcar #'car cell))) (defun export-cells (format book) (map-cells (lambda (cell) (export-cell format (aget :cell-language cell) (aget :cell-type cell) cell)) book)) (defmethod mimetype-of (format) "text/plain") (defmethod export-as (format (book notebook)) (format nil "~{~a~%~%~}" (export-cells format book))) ;;;;;;;;;; Default :lisp exporter (defmethod filename-of ((format (eql :lisp)) book) (format nil "~a.lisp" (notebook-name book))) (defmethod mimetype-of ((format (eql :lisp))) "text/x-common-lisp") (defmethod export-as ((format (eql :lisp)) (book notebook)) (format nil ";; Generated by :claxiom from ~a ~%~%~{~a~^~%~%~}~%" (notebook-id book) (export-cells :lisp book))) (defmethod export-cell ((format (eql :lisp)) (cell-language (eql :common-lisp)) cell-type cell) nil) (defmethod export-cell ((format (eql :lisp)) (cell-language (eql :common-lisp)) (cell-type (eql :code)) cell) (format nil ";;; Cell ~a~%~a" (aget :id cell) (aget :contents cell))) ;;;;;;;;;; Default :html exporter (defmethod filename-of ((format (eql :html)) book) (format nil "~a.html" (notebook-name book))) (defun slurp (filename) (with-open-file (s filename) (apply #'concatenate 'string (loop for ln = (read-line s nil nil) while ln collect ln)))) (defmethod mimetype-of ((format (eql :html))) "text/html") (defmethod export-as ((format (eql :html)) (book notebook)) (with-html-output-to-string (s nil :prologue t :indent t) (:html (:head (:title (str (notebook-name book))) (:script :type "text/javascript" (str *base-js*)) (:style :type "text/css" :media "screen" (fmt "<!-- ~a -->" (slurp (merge-pathnames "static/css/codemirror.css" *static*)))) (:style :type "text/css" :media "screen" (fmt "<!-- ~a -->" (cl-css:css (loop for v being the hash-values of *addon-css-rules* append v)))) (:style :type "text/css" :media "screen" (fmt "<!-- ~a -->" *notebook-css*))) (:body (:h1 (str (notebook-name book))) (:ul :class "cells" (str (format nil "~{~a~}" (export-cells format book)))))))) (defun -cell-class (cell) (format nil "cell ~(~a~)" (aget :cell-type cell))) (defun -cell-comment (cell) (format nil "<!-- Cell ~a -->~%" (aget :id cell))) (defun -html-value (cell) (aget :value (first (aget :values (first (aget :result cell)))))) (defmethod export-cell ((format (eql :html)) cell-language (cell-type (eql :markup)) cell) (html-to-str (-cell-comment cell) (:li :class (-cell-class cell) :cell-id (aget :id cell) (str (-html-value cell))))) (defmethod export-cell ((format (eql :html)) cell-language (cell-type (eql :code)) cell) (html-to-str (-cell-comment cell) (:li :class (-cell-class cell) :cell-id (aget :id cell) (:pre :class "cell-contents" (str (aget :contents cell))) (case (aget :cell-noise cell) (:silent nil) (t (htm (:pre :class "results" (str (-html-value cell))))))))) (defmethod export-cell ((format (eql :html)) (cell-language (eql :common-lisp)) (cell-type (eql :parenscript)) cell) (html-to-str (-cell-comment cell) (:script :type "text/javascript" (str (-html-value cell))) (case (aget :cell-noise cell) (:silent nil) (:verbose (htm (:li :class (-cell-class cell) :cell-id (aget :id cell) (:pre :class "cell-contents" (str (aget :contents cell))) (:pre :class "result" (str (-html-value cell)))))) (t (htm (:li :class (-cell-class cell) :cell-id (aget :id cell) (:pre :class "cell-contents" (str (aget :contents cell))))))))) (defun export-book-formats () (loop for m in (closer-mop:generic-function-methods #'export-as) for (fmt _) = (closer-mop:method-specializers m) when (typep fmt 'closer-mop:eql-specializer) collect (closer-mop:eql-specializer-object fmt)))
null
https://raw.githubusercontent.com/silent-entertainment/claxiom/44c6122ec46859fd881772bfc24ca3a141fb153a/src/exporters.lisp
lisp
Default :lisp exporter Default :html exporter
(in-package #:claxiom) (defmethod export-cell (format cell-language cell-type cell) (format t "~s~%" (list :default-cell format cell-language cell-type)) (list :exported format cell-language cell-type (mapcar #'car cell))) (defun export-cells (format book) (map-cells (lambda (cell) (export-cell format (aget :cell-language cell) (aget :cell-type cell) cell)) book)) (defmethod mimetype-of (format) "text/plain") (defmethod export-as (format (book notebook)) (format nil "~{~a~%~%~}" (export-cells format book))) (defmethod filename-of ((format (eql :lisp)) book) (format nil "~a.lisp" (notebook-name book))) (defmethod mimetype-of ((format (eql :lisp))) "text/x-common-lisp") (defmethod export-as ((format (eql :lisp)) (book notebook)) (format nil ";; Generated by :claxiom from ~a ~%~%~{~a~^~%~%~}~%" (notebook-id book) (export-cells :lisp book))) (defmethod export-cell ((format (eql :lisp)) (cell-language (eql :common-lisp)) cell-type cell) nil) (defmethod export-cell ((format (eql :lisp)) (cell-language (eql :common-lisp)) (cell-type (eql :code)) cell) (format nil ";;; Cell ~a~%~a" (aget :id cell) (aget :contents cell))) (defmethod filename-of ((format (eql :html)) book) (format nil "~a.html" (notebook-name book))) (defun slurp (filename) (with-open-file (s filename) (apply #'concatenate 'string (loop for ln = (read-line s nil nil) while ln collect ln)))) (defmethod mimetype-of ((format (eql :html))) "text/html") (defmethod export-as ((format (eql :html)) (book notebook)) (with-html-output-to-string (s nil :prologue t :indent t) (:html (:head (:title (str (notebook-name book))) (:script :type "text/javascript" (str *base-js*)) (:style :type "text/css" :media "screen" (fmt "<!-- ~a -->" (slurp (merge-pathnames "static/css/codemirror.css" *static*)))) (:style :type "text/css" :media "screen" (fmt "<!-- ~a -->" (cl-css:css (loop for v being the hash-values of *addon-css-rules* append v)))) (:style :type "text/css" :media "screen" (fmt "<!-- ~a -->" *notebook-css*))) (:body (:h1 (str (notebook-name book))) (:ul :class "cells" (str (format nil "~{~a~}" (export-cells format book)))))))) (defun -cell-class (cell) (format nil "cell ~(~a~)" (aget :cell-type cell))) (defun -cell-comment (cell) (format nil "<!-- Cell ~a -->~%" (aget :id cell))) (defun -html-value (cell) (aget :value (first (aget :values (first (aget :result cell)))))) (defmethod export-cell ((format (eql :html)) cell-language (cell-type (eql :markup)) cell) (html-to-str (-cell-comment cell) (:li :class (-cell-class cell) :cell-id (aget :id cell) (str (-html-value cell))))) (defmethod export-cell ((format (eql :html)) cell-language (cell-type (eql :code)) cell) (html-to-str (-cell-comment cell) (:li :class (-cell-class cell) :cell-id (aget :id cell) (:pre :class "cell-contents" (str (aget :contents cell))) (case (aget :cell-noise cell) (:silent nil) (t (htm (:pre :class "results" (str (-html-value cell))))))))) (defmethod export-cell ((format (eql :html)) (cell-language (eql :common-lisp)) (cell-type (eql :parenscript)) cell) (html-to-str (-cell-comment cell) (:script :type "text/javascript" (str (-html-value cell))) (case (aget :cell-noise cell) (:silent nil) (:verbose (htm (:li :class (-cell-class cell) :cell-id (aget :id cell) (:pre :class "cell-contents" (str (aget :contents cell))) (:pre :class "result" (str (-html-value cell)))))) (t (htm (:li :class (-cell-class cell) :cell-id (aget :id cell) (:pre :class "cell-contents" (str (aget :contents cell))))))))) (defun export-book-formats () (loop for m in (closer-mop:generic-function-methods #'export-as) for (fmt _) = (closer-mop:method-specializers m) when (typep fmt 'closer-mop:eql-specializer) collect (closer-mop:eql-specializer-object fmt)))
27b6d4aa5d3bc5dd5317cdb1fe2726a1956fe315efe03089590733c05bb25e8a
wooga/erlang_prelude
ep_lists_tests.erl
-module(ep_lists_tests). -include_lib("eunit/include/eunit.hrl"). -define(IT, ep_lists). find_first_test() -> List = [1, 2, 3, 4], Pred = fun (X) -> X < 4 andalso X =/= 1 end, False = fun (_) -> false end, ?assertEqual({value, 2}, ?IT:find_first(Pred, List)), ?assertEqual({value, 3}, ?IT:find_first(Pred, lists:reverse(List))), ?assertEqual(default, ?IT:find_first(False, List, default)). group_by_test() -> F = fun erlang:integer_to_list/1, L = [1, 2, 3, 3, 2, 1], ?assertEqual([{"1", [1, 1]}, {"2", [2, 2]}, {"3", [3, 3]}], lists:sort(?IT:group_by(F, L))).
null
https://raw.githubusercontent.com/wooga/erlang_prelude/ce7e96ef58dee98e8f67232b21cd5aabc7963f2f/test/ep_lists_tests.erl
erlang
-module(ep_lists_tests). -include_lib("eunit/include/eunit.hrl"). -define(IT, ep_lists). find_first_test() -> List = [1, 2, 3, 4], Pred = fun (X) -> X < 4 andalso X =/= 1 end, False = fun (_) -> false end, ?assertEqual({value, 2}, ?IT:find_first(Pred, List)), ?assertEqual({value, 3}, ?IT:find_first(Pred, lists:reverse(List))), ?assertEqual(default, ?IT:find_first(False, List, default)). group_by_test() -> F = fun erlang:integer_to_list/1, L = [1, 2, 3, 3, 2, 1], ?assertEqual([{"1", [1, 1]}, {"2", [2, 2]}, {"3", [3, 3]}], lists:sort(?IT:group_by(F, L))).
8ff69ebad677e6d2a585103dd1b20c72f396daca155e106c1ad26764d4588043
olsner/sedition
Interpret.hs
# LANGUAGE OverloadedStrings , CPP , TypeFamilies , NamedFieldPuns , RecordWildCards , ScopedTypeVariables # # OPTIONS_GHC -fwarn - incomplete - patterns # module Interpret (runProgram, inputListFile) where #define DEBUG 0 import Compiler.Hoopl as H hiding ((<*>)) import Control.Concurrent import Control.Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.State.Strict import Data.Array import qualified Data.ByteString.Char8 as C import Data.Char import Data.Map (Map) import qualified Data.Map as M import Data.Set (Set) import qualified Data.Set as S import Data.Maybe import Network.Socket import System.Exit import System.IO #if DEBUG import System.IO.Unsafe #endif import System.Random import Text.Printf (printf) import Text.Regex.Posix hiding (match) import AST import Bus import IR (Program) import qualified IR newtype Mailbox a = Mailbox (MVar a) Just to make SedState Showable instance Show (Mailbox a) where show _ = "Mailbox {}" data IPCState = IPCState { box :: Mailbox (Either (Maybe S) S) , bus :: Bus S , passenger :: Passenger S } deriving (Show) data File = NormalFile { Check if file is at EOF . May require reading one more character and may -- thus block, but doesn't have to read the whole line. fileIsEOF :: IO Bool, Get a line or return Nothing if at EOF . fileMaybeGetLine :: IO (Maybe S), -- Read a fulle line like fileMaybeGetLine but don't consume the line -- returned until another call to fileMaybeGetLine. filePeekLine :: IO (Maybe S), -- Output a string (without newline at the end) filePutStr :: S -> IO () } | SocketFile Socket instance Show File where show (NormalFile {}) = "NormalFile{}" show (SocketFile s) = "SocketFile " ++ show s nullFile = NormalFile (pure True) (pure Nothing) (pure Nothing) (\_ -> pure ()) rawHandleFile :: Handle -> Handle -> File rawHandleFile inh outh = NormalFile (hIsEOF inh) (hMaybeGetLine inh) (error "filePeekLine in rawHandleFile") (C.hPutStr outh) handleFile :: Handle -> Handle -> IO File handleFile inh outh = threadedFile (rawHandleFile inh outh) threadedFile :: File -> IO File threadedFile file@NormalFile{} = do nextLine :: MVar (Maybe S) <- newEmptyMVar let readThread :: IO () readThread = do line <- fileMaybeGetLine file putMVar nextLine line Stop reading on EOF when (isJust line) readThread maybeGetLine :: IO (Maybe S) maybeGetLine = takeMVar nextLine peekLine :: IO (Maybe S) peekLine = readMVar nextLine isEOF :: IO Bool isEOF = isNothing <$> readMVar nextLine _ <- forkIO readThread return (NormalFile isEOF maybeGetLine peekLine (filePutStr file)) threadedFile (SocketFile _) = error "Can't wrap a server socket in a threaded file" inputListFile :: [FilePath] -> IO File inputListFile [] = handleFile stdin stdout inputListFile inputs = do current :: MVar Handle <- newEmptyMVar inputs <- newMVar inputs let nextFile :: IO a -> a -> IO a nextFile cont eof = do fs <- takeMVar inputs case fs of [] -> putMVar inputs [] >> return eof (f:fs) -> do putMVar inputs fs putMVar current =<< openFile f ReadMode cont isEOF :: IO Bool isEOF = do h <- takeMVar current eof <- hIsEOF h if eof then nextFile isEOF True else putMVar current h >> return False maybeGetLine :: IO (Maybe S) maybeGetLine = do h <- takeMVar current line <- hMaybeGetLine h case line of Nothing -> nextFile maybeGetLine Nothing Just line -> putMVar current h >> return (Just line) nextFile (return ()) () threadedFile (NormalFile isEOF maybeGetLine (error "filePeekLine in inputListFile") C.putStr) outputHandleFile h = nullFile { filePutStr = putstr } where putstr s = do C.hPutStr h s hFlush h -- TODO Close files on exit so their buffers get flushed. Probably requires adding some shutdown code? inputHandleFile h = (rawHandleFile h h) { filePutStr = \_ -> return () } outputFile path = outputHandleFile <$> openFile path WriteMode inputFile path = inputHandleFile <$> openFile path ReadMode fileFile write path = catch (f path) errorHandler where f | write = outputFile | otherwise = inputFile errorHandler :: IOException -> IO File errorHandler _ = return nullFile hMaybeGetLine :: Handle -> IO (Maybe S) hMaybeGetLine h = do eof <- hIsEOF h if eof then pure Nothing else Just <$> C.hGetLine h data RE = RE S Regex instance Show RE where show (RE s _) = show s instance Eq RE where RE s _ == RE t _ = s == t instance Ord RE where compare (RE s _) (RE t _) = compare s t type Match = [MatchArray] TODO Use the stuff from Collections , e.g. SVarMap , MVarMap and PredSet data SedState program = SedState { program :: program , files :: Map Int File , lineNumber :: Int , lastRegex :: Maybe RE , predicates :: Set Int , strings :: Map Int S , matches :: Map Int Match , regexps :: Map IR.RE RE , ipcState :: Maybe IPCState } deriving (Show) debug :: MonadIO m => String -> m () #if DEBUG debug s = liftIO $ withMVar putstrlock $ \() -> do t <- myThreadId System.IO.putStrLn (show t ++ ": " ++ s) putstrlock = unsafePerformIO (newMVar ()) #else debug _ = return () #endif fatal msg = error ("ERROR: " ++ msg) -- The wheels on the bus go round and round... busRider p b = forever $ putMVar b . Right =<< ride p newIPCState = do bus <- newBus passenger <- board bus box <- newEmptyMVar _ <- forkIO (busRider passenger box) return IPCState { box = Mailbox box, bus = bus, passenger = passenger } forkIPCState Nothing = return Nothing forkIPCState (Just state) = do passenger <- board (bus state) box <- newEmptyMVar _ <- forkIO (busRider passenger box) return $ Just state { passenger = passenger, box = Mailbox box } initialState ipc pgm file0 = do ipcState <- if ipc then Just <$> newIPCState else return Nothing return SedState { program = pgm , files = M.singleton 0 file0 , lineNumber = 0 , strings = M.empty , matches = M.empty , regexps = M.empty , lastRegex = Nothing , predicates = S.empty , ipcState = ipcState } forkState pgm = get >>= \state -> liftIO $ do ipcState' <- forkIPCState (ipcState state) return state { program = pgm , lineNumber = 0 , predicates = S.empty , ipcState = ipcState' } setPred (IR.Pred n) b = modify $ \s -> s { predicates = f (predicates s) } where f | b = S.insert n | otherwise = S.delete n getPred (IR.Pred n) = S.member n . predicates <$> get setString :: IR.SVar -> S -> SedM () setString (IR.SVar n) value = modify $ \s -> s { strings = M.insert n value (strings s) } -- TODO Figure out why synsedizer triggers a fromJust error here... we -- shouldn't be reading unset strings... getString (IR.SVar n) = gets (fromMaybe "" . M.lookup n . strings) setMatch :: IR.MVar -> Match -> SedM () setMatch (IR.MVar n) value = modify $ \s -> s { matches = M.insert n value (matches s) } getMatch (IR.MVar n) = gets (fromJust . M.lookup n . matches) runIRLabel :: H.Label -> SedM () runIRLabel entry = do GMany _ blocks _ <- program <$> get block <- case mapLookup entry blocks of Nothing -> error ("Entry " ++ show entry ++ " not found in graph?") Just block -> return block runIRBlock block runIRBlock block = do let lift f n z = z >> f n foldBlockNodesF (lift runIR_debug) block (return ()) runIR_debug :: IR.Insn e x -> SedM () runIR_debug i@(IR.Comment _) = runIR i runIR_debug i = do debug (show i) runIR i runIR :: IR.Insn e x -> SedM () runIR (IR.Label _) = return () runIR (IR.Branch l) = runIRLabel l runIR (IR.SetP p val) = setPred p val runIR (IR.SetS s expr) = setString s =<< evalStringExpr expr runIR (IR.SetM m expr) = setMatch m =<< case expr of IR.Match svar re -> checkRE svar =<< getRegex re IR.MatchLastRE svar -> checkRE svar =<< getLastRegex IR.NextMatch m2 _ -> tail <$> getMatch m2 IR.MVarRef m2 -> getMatch m2 runIR (IR.If c t f) = do b <- evalCond c runIRLabel (if b then t else f) runIR (IR.Listen i maybeHost port) = doListen i maybeHost port runIR (IR.Accept s c) = doAccept s c runIR (IR.Fork entry next) = do pgm <- program <$> get state <- forkState pgm forkIO_ $ do debug ("start of fork") put state runIRLabel entry debug ("end of fork") debug ("parent is after fork") runIRLabel next runIR (IR.Redirect i j) = redirectFile i j runIR (IR.CloseFile i) = closeFile i runIR (IR.SetLastRE re) = setLastRegex =<< getRegex re runIR (IR.Message s) = doMessage =<< getString s runIR (IR.Print i s) = printTo i =<< getString s runIR (IR.Quit code) = liftIO (exitWith code) runIR (IR.Comment s) = debug ("*** " ++ s) runIR (IR.Wait i) = waitLineOrEvent i runIR (IR.Read svar i) = do l <- maybeGetLine i case l of Just s -> setString svar s TODO EOF should be visible to the program rather than exiting directly . runIR (IR.GetMessage svar) = do state <- gets (fromJust . ipcState) let Mailbox v = box state Right message <- liftIO (takeMVar v) setString svar message runIR (IR.ReadFile svar i) = do setString svar =<< readWholeFile i runIR (IR.OpenFile i write path) = setFile i =<< liftIO (fileFile write (C.unpack path)) runIR (IR.ShellExec svar) = do cmd <- getString svar fatal ("ShellExec not allowed (would run " ++ show cmd ++ ")") --runIR cmd = fatal ("runIR: Unhandled instruction " ++ show cmd) evalCond cond = case cond of IR.Line l -> gets ((l ==) . lineNumber) IR.EndLine l -> gets ((l <) . lineNumber) IR.AtEOF fd -> liftIO . fileIsEOF =<< gets (fromJust . M.lookup fd . files) IR.PendingIPC -> hasPendingIPC =<< gets ipcState IR.IsMatch m -> not . null <$> getMatch m IR.PRef p -> getPred p getRegex src = state f where f s | Just re <- M.lookup src (regexps s) = (re, s) | otherwise = (re, s { regexps = M.insert src re (regexps s) }) where re = compileRE src setLastRegex :: RE -> SedM () setLastRegex re = modify $ \state -> state { lastRegex = Just re } getLastRegex :: SedM RE getLastRegex = do last <- gets lastRegex case last of Just re -> return re Nothing -> fatal "no previous regular expression" compileRE :: IR.RE -> RE compileRE (IR.RE _ s ere _) = RE s (makeRegexOpts compOpt defaultExecOpt s) where compOpt | ere = compExtended | otherwise = blankCompOpt -- When we know used tags, see if we can do a match without capturing. TODO Use matchOnce instead to avoid unnecessary work . ( NextMatch handling -- gets more tricky since it will need to know how to "continue" after a -- previous match.) checkRE svar (RE _ re) = matchAll re <$> getString svar evalStringExpr :: IR.StringExpr -> SedM S evalStringExpr (IR.SConst s) = return s evalStringExpr (IR.SVarRef svar) = getString svar evalStringExpr (IR.SRandomString) = liftIO randomString evalStringExpr (IR.STrans from to str) = trans from to <$> getString str evalStringExpr (IR.SAppendNL a b) = do a <- getString a b <- getString b return (C.concat [a, "\n", b]) evalStringExpr (IR.SAppend a b) = do a <- getString a b <- getString b return (a <> b) evalStringExpr (IR.SSubstring s start end) = do s <- getString s startix <- resolve start s endix <- resolve end s return (substring startix endix s) where substring start end = C.take (end - start) . C.drop start resolve IR.SIStart _ = return 0 resolve IR.SIEnd s = return (C.length s) resolve (IR.SIMatchStart m) _ = groupStart 0 m resolve (IR.SIMatchEnd m) _ = groupEnd 0 m resolve (IR.SIGroupStart m i) _ = groupStart i m resolve (IR.SIGroupEnd m i) _ = groupEnd i m groupStart i m = fst . (! i) . head <$> getMatch m groupLen i m = snd . (! i) . head <$> getMatch m groupEnd i m = (+) <$> groupStart i m <*> groupLen i m evalStringExpr (IR.SFormatLiteral w s) = formatLiteral w <$> getString s evalStringExpr (IR.SGetLineNumber) = gets (C.pack . show . lineNumber) TODO We ought to provide secure random numbers randomString = C.pack <$> replicateM 32 (randomRIO ('A','Z')) type SedPM p a = StateT (SedState p) IO a type SedM a = SedPM Program a doListen i maybeHost port = do let hints = defaultHints { addrFlags = [AI_PASSIVE], addrSocketType = Stream } let maybeHost' = fmap C.unpack maybeHost s <- liftIO $ do addr:_ <- getAddrInfo (Just hints) maybeHost' (Just (show port)) s <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) setSocketOption s ReuseAddr 1 bind s (addrAddress addr) listen s 7 return s debug ("now listening on " ++ show i) replaceFile i (SocketFile s) doAccept i j = do Just (SocketFile s) <- getFile i debug ("accepting from " ++ show i ++ " to " ++ show j) (c,addr) <- liftIO $ accept s debug ("accepted: " ++ show addr) h <- liftIO $ socketToHandle c ReadWriteMode replaceFile j =<< liftIO (handleFile h h) doMessage m = gets ipcState >>= f where f Nothing = return () f (Just ipcState) = do debug ("Messaging " ++ show m) liftIO (drive (bus ipcState) m) trans :: S -> S -> S -> S trans from to p = C.map f p where f c | Just i <- C.elemIndex c from = C.index to i | otherwise = c -- C.init because Print appends a newline and this output always ends with a -- newline. The added newline is relevant to get the correct $ at the end of -- the formatted literal. formatLiteral :: Int -> S -> S formatLiteral width s = C.init (lineWrap width (C.lines (escape s <> "\n"))) where escape = C.concatMap escapeChar escapeChar '\\' = "\\\\" escapeChar c | isPrint c && ord c < 128 = C.singleton c | otherwise = C.pack (printf "\\%03o" (ord c)) lineWrap 0 ss = C.concat (map (<> eol) ss) lineWrap width ss = C.concat (concatMap (wrap width) ss) eol = "$\n" cont = "\\\n" wrap width s | C.null s2 = [s1, eol] | otherwise = s1 : cont : wrap width s2 where (s1,s2) = C.splitAt (width - 1) s closeFile i = do f <- getFile i debug ("Closing " ++ show i ++ ": " ++ show f) The underlying socket / files may be used by other threads , so do n't -- actually close them . Let them be garbage collected instead . case M.lookup i ( files state ) of Just ( SocketFile s ) - > sClose s Just ( HandleFile h ) - > hClose h _ - > return ( ) -- actually close them. Let them be garbage collected instead. case M.lookup i (files state) of Just (SocketFile s) -> sClose s Just (HandleFile h) -> hClose h _ -> return () -} delFile i replaceFile i f = do closeFile i setFile i f redirectFile i j = do f <- getFile j case f of Just f -> replaceFile i f >> delFile j Nothing -> closeFile i getFile i = gets (M.lookup i . files) setFile i f = modify $ \state -> state { files = M.insert i f (files state) } delFile i = modify $ \state -> state { files = M.delete i (files state) } printTo i s = putStrTo i (C.append s "\n") putStrTo i s = do Just f <- getFile i liftIO (filePutStr f s) incrementLineNumber = modify $ \state -> state { lineNumber = lineNumber state + 1 } maybeGetLine :: Int -> StateT (SedState p) IO (Maybe S) maybeGetLine i = do maybeLine <- liftIO . fileMaybeGetLine =<< fromJust <$> getFile i case maybeLine of Just l | 0 <- i -> incrementLineNumber >> return (Just l) _ -> return maybeLine readWholeFile i = go True "" where go firstLine acc = do maybeLine <- maybeGetLine i case maybeLine of Just l -> go False (if firstLine then l else acc <> "\n" <> l) Nothing -> return acc peekLine :: Int -> StateT (SedState p) IO (Maybe S) peekLine i = do liftIO . filePeekLine =<< fromJust <$> getFile i forkIO_ :: StateT s IO () -> StateT s IO () forkIO_ m = unliftIO forkIO m >> return () unliftIO :: (IO b -> IO a) -> StateT s IO b -> StateT s IO a unliftIO f m = do state <- get liftIO (f (evalStateT m state)) waitLineOrEvent :: Int -> StateT (SedState p) IO () waitLineOrEvent i = do state <- gets ipcState case state of Just state -> do let Mailbox v = box state forkIO_ (liftIO . putMVar v . Left =<< peekLine i) liftIO (() <$ takeMVar v) Nothing -> () <$ peekLine i hasPendingIPC (Just (IPCState { box = Mailbox mvar })) = do val <- liftIO (tryTakeMVar mvar) case val of Just (Right _) -> return True _ -> return False hasPendingIPC _ = return False runProgram :: Bool -> (H.Label, Program) -> File -> IO ExitCode runProgram ipc (label, program) file0 = do state <- initialState ipc program file0 evalStateT (runIRLabel label) state return ExitSuccess
null
https://raw.githubusercontent.com/olsner/sedition/483e283289a84764eec71c39dd66b017b8b00bf8/Interpret.hs
haskell
thus block, but doesn't have to read the whole line. Read a fulle line like fileMaybeGetLine but don't consume the line returned until another call to fileMaybeGetLine. Output a string (without newline at the end) TODO Close files on exit so their buffers get flushed. Probably requires adding some shutdown code? The wheels on the bus go round and round... TODO Figure out why synsedizer triggers a fromJust error here... we shouldn't be reading unset strings... runIR cmd = fatal ("runIR: Unhandled instruction " ++ show cmd) When we know used tags, see if we can do a match without capturing. gets more tricky since it will need to know how to "continue" after a previous match.) C.init because Print appends a newline and this output always ends with a newline. The added newline is relevant to get the correct $ at the end of the formatted literal. actually close them . Let them be garbage collected instead . actually close them. Let them be garbage collected instead.
# LANGUAGE OverloadedStrings , CPP , TypeFamilies , NamedFieldPuns , RecordWildCards , ScopedTypeVariables # # OPTIONS_GHC -fwarn - incomplete - patterns # module Interpret (runProgram, inputListFile) where #define DEBUG 0 import Compiler.Hoopl as H hiding ((<*>)) import Control.Concurrent import Control.Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.State.Strict import Data.Array import qualified Data.ByteString.Char8 as C import Data.Char import Data.Map (Map) import qualified Data.Map as M import Data.Set (Set) import qualified Data.Set as S import Data.Maybe import Network.Socket import System.Exit import System.IO #if DEBUG import System.IO.Unsafe #endif import System.Random import Text.Printf (printf) import Text.Regex.Posix hiding (match) import AST import Bus import IR (Program) import qualified IR newtype Mailbox a = Mailbox (MVar a) Just to make SedState Showable instance Show (Mailbox a) where show _ = "Mailbox {}" data IPCState = IPCState { box :: Mailbox (Either (Maybe S) S) , bus :: Bus S , passenger :: Passenger S } deriving (Show) data File = NormalFile { Check if file is at EOF . May require reading one more character and may fileIsEOF :: IO Bool, Get a line or return Nothing if at EOF . fileMaybeGetLine :: IO (Maybe S), filePeekLine :: IO (Maybe S), filePutStr :: S -> IO () } | SocketFile Socket instance Show File where show (NormalFile {}) = "NormalFile{}" show (SocketFile s) = "SocketFile " ++ show s nullFile = NormalFile (pure True) (pure Nothing) (pure Nothing) (\_ -> pure ()) rawHandleFile :: Handle -> Handle -> File rawHandleFile inh outh = NormalFile (hIsEOF inh) (hMaybeGetLine inh) (error "filePeekLine in rawHandleFile") (C.hPutStr outh) handleFile :: Handle -> Handle -> IO File handleFile inh outh = threadedFile (rawHandleFile inh outh) threadedFile :: File -> IO File threadedFile file@NormalFile{} = do nextLine :: MVar (Maybe S) <- newEmptyMVar let readThread :: IO () readThread = do line <- fileMaybeGetLine file putMVar nextLine line Stop reading on EOF when (isJust line) readThread maybeGetLine :: IO (Maybe S) maybeGetLine = takeMVar nextLine peekLine :: IO (Maybe S) peekLine = readMVar nextLine isEOF :: IO Bool isEOF = isNothing <$> readMVar nextLine _ <- forkIO readThread return (NormalFile isEOF maybeGetLine peekLine (filePutStr file)) threadedFile (SocketFile _) = error "Can't wrap a server socket in a threaded file" inputListFile :: [FilePath] -> IO File inputListFile [] = handleFile stdin stdout inputListFile inputs = do current :: MVar Handle <- newEmptyMVar inputs <- newMVar inputs let nextFile :: IO a -> a -> IO a nextFile cont eof = do fs <- takeMVar inputs case fs of [] -> putMVar inputs [] >> return eof (f:fs) -> do putMVar inputs fs putMVar current =<< openFile f ReadMode cont isEOF :: IO Bool isEOF = do h <- takeMVar current eof <- hIsEOF h if eof then nextFile isEOF True else putMVar current h >> return False maybeGetLine :: IO (Maybe S) maybeGetLine = do h <- takeMVar current line <- hMaybeGetLine h case line of Nothing -> nextFile maybeGetLine Nothing Just line -> putMVar current h >> return (Just line) nextFile (return ()) () threadedFile (NormalFile isEOF maybeGetLine (error "filePeekLine in inputListFile") C.putStr) outputHandleFile h = nullFile { filePutStr = putstr } where putstr s = do C.hPutStr h s inputHandleFile h = (rawHandleFile h h) { filePutStr = \_ -> return () } outputFile path = outputHandleFile <$> openFile path WriteMode inputFile path = inputHandleFile <$> openFile path ReadMode fileFile write path = catch (f path) errorHandler where f | write = outputFile | otherwise = inputFile errorHandler :: IOException -> IO File errorHandler _ = return nullFile hMaybeGetLine :: Handle -> IO (Maybe S) hMaybeGetLine h = do eof <- hIsEOF h if eof then pure Nothing else Just <$> C.hGetLine h data RE = RE S Regex instance Show RE where show (RE s _) = show s instance Eq RE where RE s _ == RE t _ = s == t instance Ord RE where compare (RE s _) (RE t _) = compare s t type Match = [MatchArray] TODO Use the stuff from Collections , e.g. SVarMap , MVarMap and PredSet data SedState program = SedState { program :: program , files :: Map Int File , lineNumber :: Int , lastRegex :: Maybe RE , predicates :: Set Int , strings :: Map Int S , matches :: Map Int Match , regexps :: Map IR.RE RE , ipcState :: Maybe IPCState } deriving (Show) debug :: MonadIO m => String -> m () #if DEBUG debug s = liftIO $ withMVar putstrlock $ \() -> do t <- myThreadId System.IO.putStrLn (show t ++ ": " ++ s) putstrlock = unsafePerformIO (newMVar ()) #else debug _ = return () #endif fatal msg = error ("ERROR: " ++ msg) busRider p b = forever $ putMVar b . Right =<< ride p newIPCState = do bus <- newBus passenger <- board bus box <- newEmptyMVar _ <- forkIO (busRider passenger box) return IPCState { box = Mailbox box, bus = bus, passenger = passenger } forkIPCState Nothing = return Nothing forkIPCState (Just state) = do passenger <- board (bus state) box <- newEmptyMVar _ <- forkIO (busRider passenger box) return $ Just state { passenger = passenger, box = Mailbox box } initialState ipc pgm file0 = do ipcState <- if ipc then Just <$> newIPCState else return Nothing return SedState { program = pgm , files = M.singleton 0 file0 , lineNumber = 0 , strings = M.empty , matches = M.empty , regexps = M.empty , lastRegex = Nothing , predicates = S.empty , ipcState = ipcState } forkState pgm = get >>= \state -> liftIO $ do ipcState' <- forkIPCState (ipcState state) return state { program = pgm , lineNumber = 0 , predicates = S.empty , ipcState = ipcState' } setPred (IR.Pred n) b = modify $ \s -> s { predicates = f (predicates s) } where f | b = S.insert n | otherwise = S.delete n getPred (IR.Pred n) = S.member n . predicates <$> get setString :: IR.SVar -> S -> SedM () setString (IR.SVar n) value = modify $ \s -> s { strings = M.insert n value (strings s) } getString (IR.SVar n) = gets (fromMaybe "" . M.lookup n . strings) setMatch :: IR.MVar -> Match -> SedM () setMatch (IR.MVar n) value = modify $ \s -> s { matches = M.insert n value (matches s) } getMatch (IR.MVar n) = gets (fromJust . M.lookup n . matches) runIRLabel :: H.Label -> SedM () runIRLabel entry = do GMany _ blocks _ <- program <$> get block <- case mapLookup entry blocks of Nothing -> error ("Entry " ++ show entry ++ " not found in graph?") Just block -> return block runIRBlock block runIRBlock block = do let lift f n z = z >> f n foldBlockNodesF (lift runIR_debug) block (return ()) runIR_debug :: IR.Insn e x -> SedM () runIR_debug i@(IR.Comment _) = runIR i runIR_debug i = do debug (show i) runIR i runIR :: IR.Insn e x -> SedM () runIR (IR.Label _) = return () runIR (IR.Branch l) = runIRLabel l runIR (IR.SetP p val) = setPred p val runIR (IR.SetS s expr) = setString s =<< evalStringExpr expr runIR (IR.SetM m expr) = setMatch m =<< case expr of IR.Match svar re -> checkRE svar =<< getRegex re IR.MatchLastRE svar -> checkRE svar =<< getLastRegex IR.NextMatch m2 _ -> tail <$> getMatch m2 IR.MVarRef m2 -> getMatch m2 runIR (IR.If c t f) = do b <- evalCond c runIRLabel (if b then t else f) runIR (IR.Listen i maybeHost port) = doListen i maybeHost port runIR (IR.Accept s c) = doAccept s c runIR (IR.Fork entry next) = do pgm <- program <$> get state <- forkState pgm forkIO_ $ do debug ("start of fork") put state runIRLabel entry debug ("end of fork") debug ("parent is after fork") runIRLabel next runIR (IR.Redirect i j) = redirectFile i j runIR (IR.CloseFile i) = closeFile i runIR (IR.SetLastRE re) = setLastRegex =<< getRegex re runIR (IR.Message s) = doMessage =<< getString s runIR (IR.Print i s) = printTo i =<< getString s runIR (IR.Quit code) = liftIO (exitWith code) runIR (IR.Comment s) = debug ("*** " ++ s) runIR (IR.Wait i) = waitLineOrEvent i runIR (IR.Read svar i) = do l <- maybeGetLine i case l of Just s -> setString svar s TODO EOF should be visible to the program rather than exiting directly . runIR (IR.GetMessage svar) = do state <- gets (fromJust . ipcState) let Mailbox v = box state Right message <- liftIO (takeMVar v) setString svar message runIR (IR.ReadFile svar i) = do setString svar =<< readWholeFile i runIR (IR.OpenFile i write path) = setFile i =<< liftIO (fileFile write (C.unpack path)) runIR (IR.ShellExec svar) = do cmd <- getString svar fatal ("ShellExec not allowed (would run " ++ show cmd ++ ")") evalCond cond = case cond of IR.Line l -> gets ((l ==) . lineNumber) IR.EndLine l -> gets ((l <) . lineNumber) IR.AtEOF fd -> liftIO . fileIsEOF =<< gets (fromJust . M.lookup fd . files) IR.PendingIPC -> hasPendingIPC =<< gets ipcState IR.IsMatch m -> not . null <$> getMatch m IR.PRef p -> getPred p getRegex src = state f where f s | Just re <- M.lookup src (regexps s) = (re, s) | otherwise = (re, s { regexps = M.insert src re (regexps s) }) where re = compileRE src setLastRegex :: RE -> SedM () setLastRegex re = modify $ \state -> state { lastRegex = Just re } getLastRegex :: SedM RE getLastRegex = do last <- gets lastRegex case last of Just re -> return re Nothing -> fatal "no previous regular expression" compileRE :: IR.RE -> RE compileRE (IR.RE _ s ere _) = RE s (makeRegexOpts compOpt defaultExecOpt s) where compOpt | ere = compExtended | otherwise = blankCompOpt TODO Use matchOnce instead to avoid unnecessary work . ( NextMatch handling checkRE svar (RE _ re) = matchAll re <$> getString svar evalStringExpr :: IR.StringExpr -> SedM S evalStringExpr (IR.SConst s) = return s evalStringExpr (IR.SVarRef svar) = getString svar evalStringExpr (IR.SRandomString) = liftIO randomString evalStringExpr (IR.STrans from to str) = trans from to <$> getString str evalStringExpr (IR.SAppendNL a b) = do a <- getString a b <- getString b return (C.concat [a, "\n", b]) evalStringExpr (IR.SAppend a b) = do a <- getString a b <- getString b return (a <> b) evalStringExpr (IR.SSubstring s start end) = do s <- getString s startix <- resolve start s endix <- resolve end s return (substring startix endix s) where substring start end = C.take (end - start) . C.drop start resolve IR.SIStart _ = return 0 resolve IR.SIEnd s = return (C.length s) resolve (IR.SIMatchStart m) _ = groupStart 0 m resolve (IR.SIMatchEnd m) _ = groupEnd 0 m resolve (IR.SIGroupStart m i) _ = groupStart i m resolve (IR.SIGroupEnd m i) _ = groupEnd i m groupStart i m = fst . (! i) . head <$> getMatch m groupLen i m = snd . (! i) . head <$> getMatch m groupEnd i m = (+) <$> groupStart i m <*> groupLen i m evalStringExpr (IR.SFormatLiteral w s) = formatLiteral w <$> getString s evalStringExpr (IR.SGetLineNumber) = gets (C.pack . show . lineNumber) TODO We ought to provide secure random numbers randomString = C.pack <$> replicateM 32 (randomRIO ('A','Z')) type SedPM p a = StateT (SedState p) IO a type SedM a = SedPM Program a doListen i maybeHost port = do let hints = defaultHints { addrFlags = [AI_PASSIVE], addrSocketType = Stream } let maybeHost' = fmap C.unpack maybeHost s <- liftIO $ do addr:_ <- getAddrInfo (Just hints) maybeHost' (Just (show port)) s <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) setSocketOption s ReuseAddr 1 bind s (addrAddress addr) listen s 7 return s debug ("now listening on " ++ show i) replaceFile i (SocketFile s) doAccept i j = do Just (SocketFile s) <- getFile i debug ("accepting from " ++ show i ++ " to " ++ show j) (c,addr) <- liftIO $ accept s debug ("accepted: " ++ show addr) h <- liftIO $ socketToHandle c ReadWriteMode replaceFile j =<< liftIO (handleFile h h) doMessage m = gets ipcState >>= f where f Nothing = return () f (Just ipcState) = do debug ("Messaging " ++ show m) liftIO (drive (bus ipcState) m) trans :: S -> S -> S -> S trans from to p = C.map f p where f c | Just i <- C.elemIndex c from = C.index to i | otherwise = c formatLiteral :: Int -> S -> S formatLiteral width s = C.init (lineWrap width (C.lines (escape s <> "\n"))) where escape = C.concatMap escapeChar escapeChar '\\' = "\\\\" escapeChar c | isPrint c && ord c < 128 = C.singleton c | otherwise = C.pack (printf "\\%03o" (ord c)) lineWrap 0 ss = C.concat (map (<> eol) ss) lineWrap width ss = C.concat (concatMap (wrap width) ss) eol = "$\n" cont = "\\\n" wrap width s | C.null s2 = [s1, eol] | otherwise = s1 : cont : wrap width s2 where (s1,s2) = C.splitAt (width - 1) s closeFile i = do f <- getFile i debug ("Closing " ++ show i ++ ": " ++ show f) The underlying socket / files may be used by other threads , so do n't case M.lookup i ( files state ) of Just ( SocketFile s ) - > sClose s Just ( HandleFile h ) - > hClose h _ - > return ( ) case M.lookup i (files state) of Just (SocketFile s) -> sClose s Just (HandleFile h) -> hClose h _ -> return () -} delFile i replaceFile i f = do closeFile i setFile i f redirectFile i j = do f <- getFile j case f of Just f -> replaceFile i f >> delFile j Nothing -> closeFile i getFile i = gets (M.lookup i . files) setFile i f = modify $ \state -> state { files = M.insert i f (files state) } delFile i = modify $ \state -> state { files = M.delete i (files state) } printTo i s = putStrTo i (C.append s "\n") putStrTo i s = do Just f <- getFile i liftIO (filePutStr f s) incrementLineNumber = modify $ \state -> state { lineNumber = lineNumber state + 1 } maybeGetLine :: Int -> StateT (SedState p) IO (Maybe S) maybeGetLine i = do maybeLine <- liftIO . fileMaybeGetLine =<< fromJust <$> getFile i case maybeLine of Just l | 0 <- i -> incrementLineNumber >> return (Just l) _ -> return maybeLine readWholeFile i = go True "" where go firstLine acc = do maybeLine <- maybeGetLine i case maybeLine of Just l -> go False (if firstLine then l else acc <> "\n" <> l) Nothing -> return acc peekLine :: Int -> StateT (SedState p) IO (Maybe S) peekLine i = do liftIO . filePeekLine =<< fromJust <$> getFile i forkIO_ :: StateT s IO () -> StateT s IO () forkIO_ m = unliftIO forkIO m >> return () unliftIO :: (IO b -> IO a) -> StateT s IO b -> StateT s IO a unliftIO f m = do state <- get liftIO (f (evalStateT m state)) waitLineOrEvent :: Int -> StateT (SedState p) IO () waitLineOrEvent i = do state <- gets ipcState case state of Just state -> do let Mailbox v = box state forkIO_ (liftIO . putMVar v . Left =<< peekLine i) liftIO (() <$ takeMVar v) Nothing -> () <$ peekLine i hasPendingIPC (Just (IPCState { box = Mailbox mvar })) = do val <- liftIO (tryTakeMVar mvar) case val of Just (Right _) -> return True _ -> return False hasPendingIPC _ = return False runProgram :: Bool -> (H.Label, Program) -> File -> IO ExitCode runProgram ipc (label, program) file0 = do state <- initialState ipc program file0 evalStateT (runIRLabel label) state return ExitSuccess
0886de6bebfcaaedaf6cf2ba0a5d38c73fa78b1ed36e9120959c52aa9d23a643
clojure/core.typed
rbt.clj
(ns clojure.core.typed.test.rbt (:refer-clojure :exclude [let]) (:require [clojure.core.typed :refer [ann print-env print-filterset ann-form defalias U IFn let Rec] :as t])) ;------------------------------- ; 'Normal' types ;------------------------------- (defalias EntryT "The payload" '{:key Number :datum Number}) (defalias Empty "A terminating node." '{:tree ':Empty}) (defalias Red "A red node" (t/TFn [[l :variance :covariant] [r :variance :covariant]] '{:tree ':Red :entry EntryT :left l :right r})) (defalias Black "A black node" (t/TFn [[l :variance :covariant] [r :variance :covariant]] '{:tree ':Black :entry EntryT :left l :right r})) ;------------------------------- ; 'Refinement' types ;------------------------------- (defalias rbt "Trees with only black children for red nodes" (Rec [rbt] (U Empty (Black rbt rbt) ( Red bt bt ) (Red (U Empty (Black rbt rbt)) (U Empty (Black rbt rbt)))))) (defalias bt "Like rbt but additionally the root node is black" (Rec [bt] (U Empty (Black rbt rbt)))) (defalias red "Trees with a red root" (Red bt bt)) (defalias badRoot "Invariant possibly violated at the root" (U Empty (Black rbt bt) (Red rbt bt) (Red bt rbt))) (defalias badLeft "Invariant possibly violated at the left child" (U Empty (Black rbt rbt) (Red bt bt) (Black badRoot rbt))) (defalias badRight "Invariant possibly violated at the right child" (U Empty (Black rbt rbt) (Red bt bt) (Black rbt badRoot))) ; This is an implementation of red-black tree invariant checking. Invariants are copied from PhD dissertation " Practical Refinement Type Checking " . ; restore-right (Black (e,l,r)) >=> dict where ( 1 ) , l , r ) is ordered , ( 2 ) Black ( e , l , r ) hash black height n , ( 3 ) color invariant may be violated at the root of r : ; one of its children must be red. and dict is re - balanced red / black tree ( satisfying all inv 's ) ; and the same black height n. (ann restore-right (IFn [badRight -> rbt])) (defn restore-right [tmap] (cond (and (-> tmap :tree #{:Black}) (-> tmap :left :tree #{:Red}) (-> tmap :right :tree #{:Red}) (-> tmap :right :left :tree #{:Red})) (let [{lt :left rt :right e :entry} tmap] ;re-color {:tree :Red :entry e :left (assoc lt :tree :Black) :right (assoc rt :tree :Black)}) (and (-> tmap :tree #{:Black}) (-> tmap :left :tree #{:Red}) (-> tmap :right :tree #{:Red}) (-> tmap :right :right :tree #{:Red})) (let [{lt :left rt :right e :entry} tmap] ;re-color {:tree :Red :entry e :left (assoc lt :tree :Black) :right (assoc rt :tree :Black)}) (and (-> tmap :tree #{:Black}) (-> tmap :right :tree #{:Red}) (-> tmap :right :left :tree #{:Red})) (let [{e :entry l :left {re :entry {rle :entry rll :left rlr :right} :left rr :right} :right} tmap] ;l is black, deep rotate {:tree :Black :entry rle :left {:tree :Red :entry e :left l :right rll} :right {:tree :Red :entry re :left rlr :right rr}}) (and (-> tmap :tree #{:Black}) (-> tmap :right :tree #{:Red}) (-> tmap :right :right :tree #{:Red})) (let [{e :entry l :left {re :entry rl :left rr :right} :right} tmap] ;l is black, shallow rotate {:tree :Black :entry re :left {:tree :Red :entry e :left l :right rl} :right rr}) :else tmap)) ;; (* val ins : 'a dict -> 'a dict inserts entry *) ;; (* ins (Red _) may violate color invariant at root *) ;; (* ins (Black _) or ins (Empty) will be red/black tree *) ;; (* ins preserves black height *) (ann insert (IFn [rbt EntryT -> rbt])) (defn insert [dict {:keys [key datum] :as entry}] (let [ ;; (*[ ins1 :> 'a rbt -> 'a badRoot ;; & 'a bt -> 'a rbt ]*) ins1 :- (IFn [bt -> rbt] [rbt -> (U rbt badRoot)]) (fn ins1 [{:keys [tree] :as tmap}] (cond (#{:Empty} tree) {:tree :Red :entry entry :left {:tree :Empty} :right {:tree :Empty}} (#{:Red} tree) (let [{{key1 :key datum1 :datum :as entry1} :entry :keys [left right]} tmap] (cond (= key key1) {:tree :Red :entry entry :left left :right right} (< key key1) {:tree :Red :entry entry1 :left (ins1 left) :right right} :else {:tree :Red :entry entry1 :left left :right (ins1 right)})) (#{:Black} tree) (let [{{key1 :key datum1 :datum :as e1} :entry l :left r :right} tmap] (cond (= key key1) {:tree :Black :entry entry :left l :right r} ; (< key key1) (restore-left {:tree :Black ; :entry e1 ; :left (ins1 l) ; :right r}) :else (restore-right {:tree :Black :entry e1 :left l :right (ins1 r)}))) :else (assert nil "Should never happen")))] (let [{:keys [tree l r] :as res} (ins1 dict)] (cond (and (-> tree #{:Red}) (or (-> l :tree #{:Red}) (-> r :tree #{:Red}))) (assoc res :tree :Black) ;re-color :else res)))) ;depend on sequential matching
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/test/clojure/core/typed/test/rbt.clj
clojure
------------------------------- 'Normal' types ------------------------------- ------------------------------- 'Refinement' types ------------------------------- This is an implementation of red-black tree invariant checking. restore-right (Black (e,l,r)) >=> dict one of its children must be red. and the same black height n. re-color re-color l is black, deep rotate l is black, shallow rotate (* val ins : 'a dict -> 'a dict inserts entry *) (* ins (Red _) may violate color invariant at root *) (* ins (Black _) or ins (Empty) will be red/black tree *) (* ins preserves black height *) (*[ ins1 :> 'a rbt -> 'a badRoot & 'a bt -> 'a rbt ]*) (< key key1) (restore-left {:tree :Black :entry e1 :left (ins1 l) :right r}) re-color depend on sequential matching
(ns clojure.core.typed.test.rbt (:refer-clojure :exclude [let]) (:require [clojure.core.typed :refer [ann print-env print-filterset ann-form defalias U IFn let Rec] :as t])) (defalias EntryT "The payload" '{:key Number :datum Number}) (defalias Empty "A terminating node." '{:tree ':Empty}) (defalias Red "A red node" (t/TFn [[l :variance :covariant] [r :variance :covariant]] '{:tree ':Red :entry EntryT :left l :right r})) (defalias Black "A black node" (t/TFn [[l :variance :covariant] [r :variance :covariant]] '{:tree ':Black :entry EntryT :left l :right r})) (defalias rbt "Trees with only black children for red nodes" (Rec [rbt] (U Empty (Black rbt rbt) ( Red bt bt ) (Red (U Empty (Black rbt rbt)) (U Empty (Black rbt rbt)))))) (defalias bt "Like rbt but additionally the root node is black" (Rec [bt] (U Empty (Black rbt rbt)))) (defalias red "Trees with a red root" (Red bt bt)) (defalias badRoot "Invariant possibly violated at the root" (U Empty (Black rbt bt) (Red rbt bt) (Red bt rbt))) (defalias badLeft "Invariant possibly violated at the left child" (U Empty (Black rbt rbt) (Red bt bt) (Black badRoot rbt))) (defalias badRight "Invariant possibly violated at the right child" (U Empty (Black rbt rbt) (Red bt bt) (Black rbt badRoot))) Invariants are copied from PhD dissertation " Practical Refinement Type Checking " . where ( 1 ) , l , r ) is ordered , ( 2 ) Black ( e , l , r ) hash black height n , ( 3 ) color invariant may be violated at the root of r : and dict is re - balanced red / black tree ( satisfying all inv 's ) (ann restore-right (IFn [badRight -> rbt])) (defn restore-right [tmap] (cond (and (-> tmap :tree #{:Black}) (-> tmap :left :tree #{:Red}) (-> tmap :right :tree #{:Red}) (-> tmap :right :left :tree #{:Red})) (let [{lt :left rt :right e :entry} tmap] {:tree :Red :entry e :left (assoc lt :tree :Black) :right (assoc rt :tree :Black)}) (and (-> tmap :tree #{:Black}) (-> tmap :left :tree #{:Red}) (-> tmap :right :tree #{:Red}) (-> tmap :right :right :tree #{:Red})) (let [{lt :left rt :right e :entry} tmap] {:tree :Red :entry e :left (assoc lt :tree :Black) :right (assoc rt :tree :Black)}) (and (-> tmap :tree #{:Black}) (-> tmap :right :tree #{:Red}) (-> tmap :right :left :tree #{:Red})) (let [{e :entry l :left {re :entry {rle :entry rll :left rlr :right} :left rr :right} :right} tmap] {:tree :Black :entry rle :left {:tree :Red :entry e :left l :right rll} :right {:tree :Red :entry re :left rlr :right rr}}) (and (-> tmap :tree #{:Black}) (-> tmap :right :tree #{:Red}) (-> tmap :right :right :tree #{:Red})) (let [{e :entry l :left {re :entry rl :left rr :right} :right} tmap] {:tree :Black :entry re :left {:tree :Red :entry e :left l :right rl} :right rr}) :else tmap)) (ann insert (IFn [rbt EntryT -> rbt])) (defn insert [dict {:keys [key datum] :as entry}] (let [ ins1 :- (IFn [bt -> rbt] [rbt -> (U rbt badRoot)]) (fn ins1 [{:keys [tree] :as tmap}] (cond (#{:Empty} tree) {:tree :Red :entry entry :left {:tree :Empty} :right {:tree :Empty}} (#{:Red} tree) (let [{{key1 :key datum1 :datum :as entry1} :entry :keys [left right]} tmap] (cond (= key key1) {:tree :Red :entry entry :left left :right right} (< key key1) {:tree :Red :entry entry1 :left (ins1 left) :right right} :else {:tree :Red :entry entry1 :left left :right (ins1 right)})) (#{:Black} tree) (let [{{key1 :key datum1 :datum :as e1} :entry l :left r :right} tmap] (cond (= key key1) {:tree :Black :entry entry :left l :right r} :else (restore-right {:tree :Black :entry e1 :left l :right (ins1 r)}))) :else (assert nil "Should never happen")))] (let [{:keys [tree l r] :as res} (ins1 dict)] (cond (and (-> tree #{:Red}) (or (-> l :tree #{:Red}) (-> r :tree #{:Red}))) (assoc res
32d7e9151fd3664398d3cc07143ae9a76326f04f4c34651fac0042050863b265
siclait/6.824-cljlabs-2020
nocrash.clj
(ns map-reduce.plugin.nocrash (:require [clojure.string :as string] [map-reduce.plugin :as plugin])) (defn mapf [filename contents] [{:key "a" :value filename} {:key "b" :value (count filename)} {:key "c" :value (count contents)} {:key "d" :value "xyzzy"}]) (defn reducef [_ vs] (string/join " " (sort vs))) (defmethod plugin/load-plugin :nocrash [_] {:mapf mapf :reducef reducef})
null
https://raw.githubusercontent.com/siclait/6.824-cljlabs-2020/0c7ad7ae07d7617b1eb7240080c65f1937ca8a2d/map-reduce/src/map_reduce/plugin/nocrash.clj
clojure
(ns map-reduce.plugin.nocrash (:require [clojure.string :as string] [map-reduce.plugin :as plugin])) (defn mapf [filename contents] [{:key "a" :value filename} {:key "b" :value (count filename)} {:key "c" :value (count contents)} {:key "d" :value "xyzzy"}]) (defn reducef [_ vs] (string/join " " (sort vs))) (defmethod plugin/load-plugin :nocrash [_] {:mapf mapf :reducef reducef})
fb292d518d3abf2ede695805f9a504662f3fe6c3f226b3fe9c5c868b83fe8122
euslisp/EusLisp
kclgabriel.lsp
(defparameter re (make-array 1025 :initial-element 0.0)) (defparameter im (make-array 1025 :initial-element 0.0)) #+kcl (defmacro while (cond &rest body) `(do () ((not ,cond)) . ,body)) (defun fft (areal aimag) (let (ar ai i j k m n le le1 ip nv2 nm1 ur ui wr wi tr ti) (declare (type float ur ui wr wi tr ti) ; (type float-vector ar ai) (type fixnum i j m n ip nv2 nm1 le1)) ;; initialize (setq ar areal ai aimag n (length ar) n (1- n) nv2 (floor (/ n 2)) nm1 (1- n) m 0 i 1) (while (< i n) (setq m (1+ m) i (+ i i))) (when (not (equal n (expt 2 m))) (error "array size is not a power of 2")) ;; interchange elements in bit-reversal order (setq j 1 i 1) (while (< i n) (when (< i j) (setq tr (aref ar j) ti (aref ai j)) (setf (aref ar j) (aref ar i)) (setf (aref ai j) (aref ai i)) (setf (aref ar i) tr) (setf (aref ai i) ti)) (setq k nv2) (while (< k j) (setq j (- j k) k (/ k 2))) (setq j (+ j k) i (1+ i)) ) (format t "n=~d~%" n) (do ((l 1 (1+ l))) ((> l m)) (setq le (expt 2 l) le1 (floor (/ le 2)) ur 1.0 ui 0.0 wr (cos (/ pi (float le1))) wi (sin (/ pi (float le1)))) ;; repeat butterflies (do ((j 1 (1+ j))) ((> j le1)) ;; do a butterfly (do ((i j (+ i le))) ((> i n)) (setq ip (+ i le1) tr (- (* (aref ar ip) ur) (* (aref ai ip) ui)) ti (+ (* (aref ar ip) ui) (* (aref ai ip) ur))) (setf (aref ar ip) (- (aref ar i) tr)) (setf (aref ai ip) (- (aref ai i) ti)) (setf (aref ar i) (+ (aref ar i) tr)) (setf (aref ai i) (+ (aref ai i) ti)))) (setq tr (- (* ur wr) (* ui wi)) ti (+ (* ur wi) (* ui wr)) ur tr ui ti)) t)) (defmacro fft-bench () `(dotimes (i 10) (fft re im))) (defun deriv-aux (a) (list '/ (deriv a) a)) (defun deriv (a) (cond ((atom a) (cond ((eq a 'x) 1) (t 0))) ((eq (car a) '+) (cons '+ (mapcar #'deriv (cdr a)))) ((eq (car a) '-) (cons '- (mapcar #'deriv (cdr a)))) ((eq (car a) '*) (list '* a (cons '+ (mapcar #'deriv-aux (cdr a))))) ((eq (car a) '/) (list '- (list '/ (deriv (cadr a)) (caddr a)) (list '/ (cadr a) (list '* (caddr a) (caddr a) (deriv (caddr a)))))) (t 'error))) (defun run () (dotimes (i 1000.) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)))) ;;; ;;; PUZZLE ;;; (eval-when (compile load eval) (defconstant size 511) (defconstant classmax 3) (defconstant typemax 12)) (defvar *iii* 0) (defvar *kount* 0) (defvar *d* 8.) (defvar piececount (make-array (1+ classmax) :initial-element 0)) (defvar class (make-array (1+ typemax) :initial-element 0)) (defvar piecemax (make-array (1+ typemax) :initial-element 0)) (defvar puzzle (make-array (1+ size))) (defvar p (make-array (list (1+ typemax) (1+ size)))) (defun fit (i j) (let ((end (aref piecemax i))) (do ((k 0 (1+ k))) ((> k end) t) (cond ((aref p i k) (cond ((aref puzzle (+ j k)) (return nil)))))))) (defun place (i j) (let ((end (aref piecemax i))) (do (( k 0 (1+ k))) ((> k end)) (cond ((aref p i k) (setf (aref puzzle (+ j k)) t)))) (setf (aref piececount (aref class i)) (- (aref piececount (aref class i)) 1)) (do ((k j (1+ k))) ((> k size) (print "Puzzle filled") 0) (unless (aref puzzle k) (return k))))) (defun puzzle-remove (i j) (let ((end (aref piecemax i))) (do ((k 0 (1+ k))) ((> k end)) (cond ((aref p i k) (setf (aref puzzle (+ j k)) nil)))) (setf (aref piececount (aref class i)) (+ (aref piececount (aref class i)) 1)))) (defun trial (j) (let ((k 0) (hhh)) (do ((i 0 (1+ i))) ((> i typemax) (setq *kount* (1+ *kount*)) nil) (cond ((not (= (aref piececount (aref class i)) 0)) (cond ((fit i j) (setq k (place i j)) ; (print k) (cond ((or (setq hhh (trial k)) (= k 0)) (format t "~%Piece ~4d at ~4d kount=~4d k=~d trial=~a." (+ i 1) (+ k 1) (incf *kount*) k hhh) (return-from trial t)) (t (puzzle-remove i j)))))))))) (defun definepiece (iclass ii jj kk) (let ((index 0)) (do ((i 0 (1+ i))) ((> i ii)) (do ((j 0 (1+ j))) ((> j jj)) (do ((k 0 (1+ k))) ((> k kk)) (setq index (+ i (* *d* (+ j (* *d* k))))) (setf (aref p *iii* index) t)))) (setf (aref class *iii*) iclass) (setf (aref piecemax *iii*) index) (cond ((not (= *iii* typemax)) (setq *iii* (+ *iii* 1)))))) (defun start () (do ((m 0 (1+ m))) ((> m size)) (setf (aref puzzle m) t)) (do ((i 1 (1+ i))) ((> i 5)) (do ((j 1 (1+ j))) ((> j 5)) (do ((k 1 (1+ k))) ((> k 5)) (setf (aref puzzle (+ i (* *d* (+ j (* *d* k))))) nil)))) (do ((i 0 (1+ i))) ((> i typemax)) (do ((m 0 (1+ m))) ((> m size )) (setf (aref p i m) nil))) (setq *iii* 0) (definepiece 0 3 1 0) (definepiece 0 1 0 3) (definepiece 0 0 3 1) (definepiece 0 1 3 0) (definepiece 0 3 0 1) (definepiece 0 0 1 3) (definepiece 1 2 0 0) (definepiece 1 0 2 0) (definepiece 1 0 0 2) (definepiece 2 1 1 0) (definepiece 2 1 0 1) (definepiece 2 0 1 1) (definepiece 3 1 1 1) (setf (aref piececount 0) 13.) (setf (aref piececount 1) 3) (setf (aref piececount 2) 1) (setf (aref piececount 3) 1) (let ((m (+ 1 (* *d* (1+ *d*)))) (n 0) (*kount* 0)) (cond ((fit 0 m) (setq n (place 0 m))) (t (format t "~% error."))) (cond ((trial n) (format t "~%success in ~4d trials." *kount*)) (t (format t "~% Failure.")))))
null
https://raw.githubusercontent.com/euslisp/EusLisp/5aa9241268257356a6ba2d7fbaf920a098cc18c4/contrib/bench/kclgabriel.lsp
lisp
(type float-vector ar ai) initialize interchange elements in bit-reversal order repeat butterflies do a butterfly PUZZLE (print k)
(defparameter re (make-array 1025 :initial-element 0.0)) (defparameter im (make-array 1025 :initial-element 0.0)) #+kcl (defmacro while (cond &rest body) `(do () ((not ,cond)) . ,body)) (defun fft (areal aimag) (let (ar ai i j k m n le le1 ip nv2 nm1 ur ui wr wi tr ti) (declare (type float ur ui wr wi tr ti) (type fixnum i j m n ip nv2 nm1 le1)) (setq ar areal ai aimag n (length ar) n (1- n) nv2 (floor (/ n 2)) nm1 (1- n) m 0 i 1) (while (< i n) (setq m (1+ m) i (+ i i))) (when (not (equal n (expt 2 m))) (error "array size is not a power of 2")) (setq j 1 i 1) (while (< i n) (when (< i j) (setq tr (aref ar j) ti (aref ai j)) (setf (aref ar j) (aref ar i)) (setf (aref ai j) (aref ai i)) (setf (aref ar i) tr) (setf (aref ai i) ti)) (setq k nv2) (while (< k j) (setq j (- j k) k (/ k 2))) (setq j (+ j k) i (1+ i)) ) (format t "n=~d~%" n) (do ((l 1 (1+ l))) ((> l m)) (setq le (expt 2 l) le1 (floor (/ le 2)) ur 1.0 ui 0.0 wr (cos (/ pi (float le1))) wi (sin (/ pi (float le1)))) (do ((j 1 (1+ j))) ((> j le1)) (do ((i j (+ i le))) ((> i n)) (setq ip (+ i le1) tr (- (* (aref ar ip) ur) (* (aref ai ip) ui)) ti (+ (* (aref ar ip) ui) (* (aref ai ip) ur))) (setf (aref ar ip) (- (aref ar i) tr)) (setf (aref ai ip) (- (aref ai i) ti)) (setf (aref ar i) (+ (aref ar i) tr)) (setf (aref ai i) (+ (aref ai i) ti)))) (setq tr (- (* ur wr) (* ui wi)) ti (+ (* ur wi) (* ui wr)) ur tr ui ti)) t)) (defmacro fft-bench () `(dotimes (i 10) (fft re im))) (defun deriv-aux (a) (list '/ (deriv a) a)) (defun deriv (a) (cond ((atom a) (cond ((eq a 'x) 1) (t 0))) ((eq (car a) '+) (cons '+ (mapcar #'deriv (cdr a)))) ((eq (car a) '-) (cons '- (mapcar #'deriv (cdr a)))) ((eq (car a) '*) (list '* a (cons '+ (mapcar #'deriv-aux (cdr a))))) ((eq (car a) '/) (list '- (list '/ (deriv (cadr a)) (caddr a)) (list '/ (cadr a) (list '* (caddr a) (caddr a) (deriv (caddr a)))))) (t 'error))) (defun run () (dotimes (i 1000.) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)) (deriv '(+ (* 3 x x) (* a x x) (*b x) 5)))) (eval-when (compile load eval) (defconstant size 511) (defconstant classmax 3) (defconstant typemax 12)) (defvar *iii* 0) (defvar *kount* 0) (defvar *d* 8.) (defvar piececount (make-array (1+ classmax) :initial-element 0)) (defvar class (make-array (1+ typemax) :initial-element 0)) (defvar piecemax (make-array (1+ typemax) :initial-element 0)) (defvar puzzle (make-array (1+ size))) (defvar p (make-array (list (1+ typemax) (1+ size)))) (defun fit (i j) (let ((end (aref piecemax i))) (do ((k 0 (1+ k))) ((> k end) t) (cond ((aref p i k) (cond ((aref puzzle (+ j k)) (return nil)))))))) (defun place (i j) (let ((end (aref piecemax i))) (do (( k 0 (1+ k))) ((> k end)) (cond ((aref p i k) (setf (aref puzzle (+ j k)) t)))) (setf (aref piececount (aref class i)) (- (aref piececount (aref class i)) 1)) (do ((k j (1+ k))) ((> k size) (print "Puzzle filled") 0) (unless (aref puzzle k) (return k))))) (defun puzzle-remove (i j) (let ((end (aref piecemax i))) (do ((k 0 (1+ k))) ((> k end)) (cond ((aref p i k) (setf (aref puzzle (+ j k)) nil)))) (setf (aref piececount (aref class i)) (+ (aref piececount (aref class i)) 1)))) (defun trial (j) (let ((k 0) (hhh)) (do ((i 0 (1+ i))) ((> i typemax) (setq *kount* (1+ *kount*)) nil) (cond ((not (= (aref piececount (aref class i)) 0)) (cond ((fit i j) (setq k (place i j)) (cond ((or (setq hhh (trial k)) (= k 0)) (format t "~%Piece ~4d at ~4d kount=~4d k=~d trial=~a." (+ i 1) (+ k 1) (incf *kount*) k hhh) (return-from trial t)) (t (puzzle-remove i j)))))))))) (defun definepiece (iclass ii jj kk) (let ((index 0)) (do ((i 0 (1+ i))) ((> i ii)) (do ((j 0 (1+ j))) ((> j jj)) (do ((k 0 (1+ k))) ((> k kk)) (setq index (+ i (* *d* (+ j (* *d* k))))) (setf (aref p *iii* index) t)))) (setf (aref class *iii*) iclass) (setf (aref piecemax *iii*) index) (cond ((not (= *iii* typemax)) (setq *iii* (+ *iii* 1)))))) (defun start () (do ((m 0 (1+ m))) ((> m size)) (setf (aref puzzle m) t)) (do ((i 1 (1+ i))) ((> i 5)) (do ((j 1 (1+ j))) ((> j 5)) (do ((k 1 (1+ k))) ((> k 5)) (setf (aref puzzle (+ i (* *d* (+ j (* *d* k))))) nil)))) (do ((i 0 (1+ i))) ((> i typemax)) (do ((m 0 (1+ m))) ((> m size )) (setf (aref p i m) nil))) (setq *iii* 0) (definepiece 0 3 1 0) (definepiece 0 1 0 3) (definepiece 0 0 3 1) (definepiece 0 1 3 0) (definepiece 0 3 0 1) (definepiece 0 0 1 3) (definepiece 1 2 0 0) (definepiece 1 0 2 0) (definepiece 1 0 0 2) (definepiece 2 1 1 0) (definepiece 2 1 0 1) (definepiece 2 0 1 1) (definepiece 3 1 1 1) (setf (aref piececount 0) 13.) (setf (aref piececount 1) 3) (setf (aref piececount 2) 1) (setf (aref piececount 3) 1) (let ((m (+ 1 (* *d* (1+ *d*)))) (n 0) (*kount* 0)) (cond ((fit 0 m) (setq n (place 0 m))) (t (format t "~% error."))) (cond ((trial n) (format t "~%success in ~4d trials." *kount*)) (t (format t "~% Failure.")))))
144c9461285d0bcb224ca42a423814b21aa66e8ab8dca0dbc7bedc1c282aff0d
lemmaandrew/CodingBatHaskell
groupSum6.hs
{- From Given an array of ints, is it possible to choose a group of some of the ints, beginning at the start index, such that the group sums to the given target? However, with the additional constraint that all 6's must be chosen. (No loops needed.) -} import Test.Hspec ( hspec, describe, it, shouldBe ) groupSum6 :: Int -> [Int] -> Int -> Bool groupSum6 start nums target = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "True" $ groupSum6 0 [5,6,2] 8 `shouldBe` True it "False" $ groupSum6 0 [5,6,2] 9 `shouldBe` False it "False" $ groupSum6 0 [5,6,2] 7 `shouldBe` False it "True" $ groupSum6 0 [1] 1 `shouldBe` True it "False" $ groupSum6 0 [9] 1 `shouldBe` False it "True" $ groupSum6 0 [] 0 `shouldBe` True it "True" $ groupSum6 0 [3,2,4,6] 8 `shouldBe` True it "True" $ groupSum6 0 [6,2,4,3] 8 `shouldBe` True it "False" $ groupSum6 0 [5,2,4,6] 9 `shouldBe` False it "False" $ groupSum6 0 [6,2,4,5] 9 `shouldBe` False it "False" $ groupSum6 0 [3,2,4,6] 3 `shouldBe` False it "True" $ groupSum6 0 [1,6,2,6,4] 12 `shouldBe` True it "True" $ groupSum6 0 [1,6,2,6,4] 13 `shouldBe` True it "False" $ groupSum6 0 [1,6,2,6,4] 4 `shouldBe` False it "False" $ groupSum6 0 [1,6,2,6,4] 9 `shouldBe` False it "True" $ groupSum6 0 [1,6,2,6,5] 14 `shouldBe` True it "True" $ groupSum6 0 [1,6,2,6,5] 15 `shouldBe` True it "False" $ groupSum6 0 [1,6,2,6,5] 16 `shouldBe` False
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Recursion-2/groupSum6.hs
haskell
From Given an array of ints, is it possible to choose a group of some of the ints, beginning at the start index, such that the group sums to the given target? However, with the additional constraint that all 6's must be chosen. (No loops needed.)
import Test.Hspec ( hspec, describe, it, shouldBe ) groupSum6 :: Int -> [Int] -> Int -> Bool groupSum6 start nums target = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "True" $ groupSum6 0 [5,6,2] 8 `shouldBe` True it "False" $ groupSum6 0 [5,6,2] 9 `shouldBe` False it "False" $ groupSum6 0 [5,6,2] 7 `shouldBe` False it "True" $ groupSum6 0 [1] 1 `shouldBe` True it "False" $ groupSum6 0 [9] 1 `shouldBe` False it "True" $ groupSum6 0 [] 0 `shouldBe` True it "True" $ groupSum6 0 [3,2,4,6] 8 `shouldBe` True it "True" $ groupSum6 0 [6,2,4,3] 8 `shouldBe` True it "False" $ groupSum6 0 [5,2,4,6] 9 `shouldBe` False it "False" $ groupSum6 0 [6,2,4,5] 9 `shouldBe` False it "False" $ groupSum6 0 [3,2,4,6] 3 `shouldBe` False it "True" $ groupSum6 0 [1,6,2,6,4] 12 `shouldBe` True it "True" $ groupSum6 0 [1,6,2,6,4] 13 `shouldBe` True it "False" $ groupSum6 0 [1,6,2,6,4] 4 `shouldBe` False it "False" $ groupSum6 0 [1,6,2,6,4] 9 `shouldBe` False it "True" $ groupSum6 0 [1,6,2,6,5] 14 `shouldBe` True it "True" $ groupSum6 0 [1,6,2,6,5] 15 `shouldBe` True it "False" $ groupSum6 0 [1,6,2,6,5] 16 `shouldBe` False
86b3537d2a12b315d0dcebde41a84436113c3c6ca05026c9504fd411ad57409e
fortytools/holumbus
IndexConfig.hs
# OPTIONS # -- ------------------------------------------------------------ module Hayoo.IndexConfig where import Data.Char.Properties.XMLCharProps import Hayoo.HackagePackage import Hayoo.Haddock import Hayoo.Signature import Holumbus.Crawler import Holumbus.Crawler.IndexerCore import Text.Regex.XMLSchema.String (matchSubex) import Text.XML.HXT.Core -- ------------------------------------------------------------ ix'Names :: [String] ix'module :: String ix'hierarchy :: String ix'package :: String ix'name :: String ix'partial :: String ix'signature :: String ix'normalized :: String ix'description :: String ix'rawsig :: String ix'Names@[ ix'module , ix'hierarchy , ix'package , ix'name , ix'partial , ix'signature , ix'normalized , ix'description , ix'rawsig ] = [ "module" , "hierarchy" , "package" , "name" , "partial" , "signature" , "normalized" , "description" , "rawsig" ] hayooIndexContextConfig :: [IndexContextConfig] hayooIndexContextConfig = [ ixModule , ixHierachy , ixPackage , ixName , ixPartial , ixSignature , ixNormalizedSig , ixDescription , ixRawSig ] where ixDefault = IndexContextConfig { ixc_name = "default" , ixc_collectText = getHtmlPlainText , ixc_textToWords = deleteNotAllowedChars >>> words , ixc_boringWord = boringWord } ixModule = ixDefault { ixc_name = ix'module , ixc_collectText = getAttrValue "module" , ixc_textToWords = return , ixc_boringWord = null } ixHierachy = ixModule { ixc_name = ix'hierarchy , ixc_textToWords = tokenize "[^.]+" -- split module name at . } ixPackage = ixDefault { ixc_name = ix'package , ixc_collectText = getAttrValue "package" , ixc_textToWords = return , ixc_boringWord = \ x -> null x || x == "unknownpackage" } ixName = ixDefault { ixc_name = ix'name is simpler than : fromLA $ getAllText ( deep $ trtdWithClass (= = " " ) ) -- TODO 2.8 version tokenize " [ ^ ( ): ] + " > > > take 1 , ixc_boringWord = null -- (`elem` ["type", "class", "data", "module"]) } ixPartial = ixName { ixc_name = ix'partial , ixc_textToWords = deCamel >>> tokenize typeIdent , ixc_boringWord = boringWord } ixSignature = ixDefault { ixc_name = ix'signature , ixc_collectText = getAttrValue "signature" , ixc_textToWords = stripSignature >>> return , ixc_boringWord = not . isSignature } ixRawSig = ixDefault { ixc_name = ix'rawsig , ixc_collectText = getAttrValue "rawsig" , ixc_textToWords = words , ixc_boringWord = null } ixNormalizedSig = ixSignature { ixc_name = ix'normalized , ixc_textToWords = normalizeSignature >>> return } ixDescription = ixDefault { ixc_name = ix'description , ixc_collectText = fromLA $ getAllText hayooGetDescr , ixc_textToWords = tokenize descrWord } -- ----------------------------------------------------------------------------- pk'Names :: [String] pk'author :: String pk'synopsis :: String pk'pkgdescr :: String pk'dependencies :: String pk'pkgname :: String pk'category :: String pk'Names@[ pk'category , pk'pkgname , pk'dependencies , pk'pkgdescr , pk'synopsis , pk'author ] = [ "category" , "pkgname" , "dependencies" , "pkgdescr" , "synopsis" , "author" ] hayooPkgIndexContextConfig :: [IndexContextConfig] hayooPkgIndexContextConfig = [ ixCategory , ixPkgName , ixDepends , ixDescription , ixSynopsis , ixAuthor ] where ixDefault = IndexContextConfig { ixc_name = "default" , ixc_collectText = getHtmlPlainText , ixc_textToWords = deleteNotAllowedChars >>> words , ixc_boringWord = boringWord } ixCategory = ixDefault { ixc_name = pk'category , ixc_collectText = fromLA getPkgCategory , ixc_textToWords = words } ixPkgName = ixDefault { ixc_name = pk'pkgname , ixc_collectText = fromLA $ getPkgName , ixc_textToWords = splitDash } ixDepends = ixDefault { ixc_name = pk'dependencies , ixc_collectText = fromLA $ getPkgDependencies >>^ unwords , ixc_textToWords = words } ixDescription = ixDefault { ixc_name = pk'pkgdescr , ixc_collectText = fromLA $ getPkgDescr , ixc_textToWords = tokenize descrWord } ixSynopsis = ixDescription { ixc_name = pk'synopsis , ixc_collectText = fromLA $ getPkgSynopsis } ixAuthor = ixDescription { ixc_name = pk'author , ixc_collectText = fromLA $ listA (getPkgAuthor <+> getPkgMaintainer) >>^ unwords } -- ----------------------------------------------------------------------------- please : " - " as 1 . char in set ! ! ! -- words start with a letter, end with a letter or digit and may contain -, . and @ and digits descrWord :: String descrWord = "[A-Za-z][-A-Za-z0-9.@]*[A-Za-z0-9]" -- ----------------------------------------------------------------------------- deCamel :: String -> String deCamel = deCamel' False where deCamel' _ [] = [] deCamel' _ ('_' : xs) = ' ' : deCamel' True xs deCamel' cap (x : xs) | isCap x = ( if cap then id else (' ' :) ) $ x : deCamel' True xs | otherwise = x : deCamel' (isCap x) xs where isCap = (`elem` ['A'..'Z']) -- ----------------------------------------------------------------------------- boringWord :: String -> Bool boringWord w = null w || (null . tail $ w) || not (any isXmlLetter w) isAllowedWordChar :: Char -> Bool isAllowedWordChar c = isXmlLetter c || isXmlDigit c || c `elem` "_-" deleteNotAllowedChars :: String -> String deleteNotAllowedChars = map notAllowedToSpace where notAllowedToSpace c | isAllowedWordChar c = c | otherwise = ' ' splitDash :: String -> [String] splitDash s = ( s : (map (\ x -> if x == '-' then ' ' else x) >>> words >>> drop 1 $ s ) ) matchPars :: String -> [(String, String)] matchPars = matchSubex "[(]({m}.+)[)]" removePars :: String -> [String] removePars xs = case matchPars xs of [("m", xs')] -> [xs, xs'] _ -> [xs] -- -----------------------------------------------------------------------------
null
https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/Hayoo/HayooIndexer/Hayoo/IndexConfig.hs
haskell
------------------------------------------------------------ ------------------------------------------------------------ split module name at . TODO 2.8 version (`elem` ["type", "class", "data", "module"]) ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- words start with a letter, end with a letter or digit and may contain -, . and @ and digits ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -----------------------------------------------------------------------------
# OPTIONS # module Hayoo.IndexConfig where import Data.Char.Properties.XMLCharProps import Hayoo.HackagePackage import Hayoo.Haddock import Hayoo.Signature import Holumbus.Crawler import Holumbus.Crawler.IndexerCore import Text.Regex.XMLSchema.String (matchSubex) import Text.XML.HXT.Core ix'Names :: [String] ix'module :: String ix'hierarchy :: String ix'package :: String ix'name :: String ix'partial :: String ix'signature :: String ix'normalized :: String ix'description :: String ix'rawsig :: String ix'Names@[ ix'module , ix'hierarchy , ix'package , ix'name , ix'partial , ix'signature , ix'normalized , ix'description , ix'rawsig ] = [ "module" , "hierarchy" , "package" , "name" , "partial" , "signature" , "normalized" , "description" , "rawsig" ] hayooIndexContextConfig :: [IndexContextConfig] hayooIndexContextConfig = [ ixModule , ixHierachy , ixPackage , ixName , ixPartial , ixSignature , ixNormalizedSig , ixDescription , ixRawSig ] where ixDefault = IndexContextConfig { ixc_name = "default" , ixc_collectText = getHtmlPlainText , ixc_textToWords = deleteNotAllowedChars >>> words , ixc_boringWord = boringWord } ixModule = ixDefault { ixc_name = ix'module , ixc_collectText = getAttrValue "module" , ixc_textToWords = return , ixc_boringWord = null } ixHierachy = ixModule { ixc_name = ix'hierarchy } ixPackage = ixDefault { ixc_name = ix'package , ixc_collectText = getAttrValue "package" , ixc_textToWords = return , ixc_boringWord = \ x -> null x || x == "unknownpackage" } ixName = ixDefault { ixc_name = ix'name tokenize " [ ^ ( ): ] + " > > > take 1 } ixPartial = ixName { ixc_name = ix'partial , ixc_textToWords = deCamel >>> tokenize typeIdent , ixc_boringWord = boringWord } ixSignature = ixDefault { ixc_name = ix'signature , ixc_collectText = getAttrValue "signature" , ixc_textToWords = stripSignature >>> return , ixc_boringWord = not . isSignature } ixRawSig = ixDefault { ixc_name = ix'rawsig , ixc_collectText = getAttrValue "rawsig" , ixc_textToWords = words , ixc_boringWord = null } ixNormalizedSig = ixSignature { ixc_name = ix'normalized , ixc_textToWords = normalizeSignature >>> return } ixDescription = ixDefault { ixc_name = ix'description , ixc_collectText = fromLA $ getAllText hayooGetDescr , ixc_textToWords = tokenize descrWord } pk'Names :: [String] pk'author :: String pk'synopsis :: String pk'pkgdescr :: String pk'dependencies :: String pk'pkgname :: String pk'category :: String pk'Names@[ pk'category , pk'pkgname , pk'dependencies , pk'pkgdescr , pk'synopsis , pk'author ] = [ "category" , "pkgname" , "dependencies" , "pkgdescr" , "synopsis" , "author" ] hayooPkgIndexContextConfig :: [IndexContextConfig] hayooPkgIndexContextConfig = [ ixCategory , ixPkgName , ixDepends , ixDescription , ixSynopsis , ixAuthor ] where ixDefault = IndexContextConfig { ixc_name = "default" , ixc_collectText = getHtmlPlainText , ixc_textToWords = deleteNotAllowedChars >>> words , ixc_boringWord = boringWord } ixCategory = ixDefault { ixc_name = pk'category , ixc_collectText = fromLA getPkgCategory , ixc_textToWords = words } ixPkgName = ixDefault { ixc_name = pk'pkgname , ixc_collectText = fromLA $ getPkgName , ixc_textToWords = splitDash } ixDepends = ixDefault { ixc_name = pk'dependencies , ixc_collectText = fromLA $ getPkgDependencies >>^ unwords , ixc_textToWords = words } ixDescription = ixDefault { ixc_name = pk'pkgdescr , ixc_collectText = fromLA $ getPkgDescr , ixc_textToWords = tokenize descrWord } ixSynopsis = ixDescription { ixc_name = pk'synopsis , ixc_collectText = fromLA $ getPkgSynopsis } ixAuthor = ixDescription { ixc_name = pk'author , ixc_collectText = fromLA $ listA (getPkgAuthor <+> getPkgMaintainer) >>^ unwords } please : " - " as 1 . char in set ! ! ! descrWord :: String descrWord = "[A-Za-z][-A-Za-z0-9.@]*[A-Za-z0-9]" deCamel :: String -> String deCamel = deCamel' False where deCamel' _ [] = [] deCamel' _ ('_' : xs) = ' ' : deCamel' True xs deCamel' cap (x : xs) | isCap x = ( if cap then id else (' ' :) ) $ x : deCamel' True xs | otherwise = x : deCamel' (isCap x) xs where isCap = (`elem` ['A'..'Z']) boringWord :: String -> Bool boringWord w = null w || (null . tail $ w) || not (any isXmlLetter w) isAllowedWordChar :: Char -> Bool isAllowedWordChar c = isXmlLetter c || isXmlDigit c || c `elem` "_-" deleteNotAllowedChars :: String -> String deleteNotAllowedChars = map notAllowedToSpace where notAllowedToSpace c | isAllowedWordChar c = c | otherwise = ' ' splitDash :: String -> [String] splitDash s = ( s : (map (\ x -> if x == '-' then ' ' else x) >>> words >>> drop 1 $ s ) ) matchPars :: String -> [(String, String)] matchPars = matchSubex "[(]({m}.+)[)]" removePars :: String -> [String] removePars xs = case matchPars xs of [("m", xs')] -> [xs, xs'] _ -> [xs]
9068cff63e1a69184c77f4a41fd066bf45e30b0dc79398dc3578e5b19602b840
vituscze/norri
Compile.hs
| Allows the abstract syntax tree to be compiled into C++ template -- metaprogram. module Compiler.Compile ( -- * Module compiling compileModule , compileTopLevel -- * Top level entities compiling , compileType , compileDataDef , compileValDef -- * Expression compiling , compileExpr ) where import Data.Char import Data.List import Compiler.AST import Utility -- | Left opening brace surrounded by newlines. lbrace :: String lbrace = "\n{\n" -- | Right closing brace surrounded by newlines. rbrace :: String rbrace = "\n};\n" -- | Print a @struct@ given its name and contents. -- > > > struct " s " " int x ; " -- struct s -- { -- int x; -- }; struct :: String -- ^ Name of the @struct@. -> String -- ^ Content of the @struct@. -> String struct name content = concat ["struct ", name, lbrace, content, rbrace] -- | Print a @template@ given its name, contents and the (only) template -- argument. -- -- >>> putStrLn $ template "x" "s" "int y;" -- template <typename x> -- struct s -- { -- int y; -- }; template :: String -- ^ Name of the template argument. -> String -- ^ Name of the @struct@. -> String -- ^ Content of the @struct@. -> String template arg name content = "template <typename " ++ arg ++ ">\n" ++ struct name content -- | Print a @template@ @struct@ forward declaration. -- > > > " s " -- template <typename> -- struct s; fwdTemplate :: String -- ^ Name of the @struct@. -> String fwdTemplate name = "template <typename>\nstruct " ++ name ++ ";\n" | Print a @typedef@ which identifies type expression @what@ with @type@. -- -- >>> putStrLn $ typedef "int" -- typedef int type; typedef :: String -- ^ Type expression. -> String typedef what = "typedef " ++ what ++ " " ++ ty ++ ";" -- | Print a type expression extracting inner @type@ from another type. -- > > > innerType " vector " -- typename vector::type innerType :: String -- ^ Type expression. -> String innerType what = "typename " ++ what ++ "::" ++ ty -- | Print a nested hierarchy of @struct@ures used for lambda abstraction. -- -- >>> putStrLn $ innerApply "x" "s" "int x;" -- struct s -- { -- struct type -- { -- template <typename x> -- struct apply -- { -- int x; -- }; -- }; -- }; innerApply :: String -- ^ Name of the template argument. -> String -- ^ Name of the @struct@. -> String -- ^ Content of the @struct@. -> String innerApply arg name = struct name . struct ty . template arg apply -- | Print a list of declarations. -- -- This is just a name-flavored 'concat'. decls :: [String] -- ^ List of declarations. -> String decls = concat -- | 'String' constant for inner @template@ used for lambda abstractions. apply :: String apply = "apply" -- | 'String' constant for inner @typedef@s. ty :: String ty = "type" | ' String ' constant for the @dummy@ type . dummy :: String dummy = "__dummy" -- | Compile whole module. -- -- Compiles all top level entities contained in module. compileModule :: Module -> String compileModule (Module m) = intercalate sep $ map compileTopLevel m where sep = "\n\n" -- | Compile a top level declaration. compileTopLevel :: TopLevel -> String compileTopLevel tl = case tl of Data dd -> compileDataDef dd Value vd -> compileValDef vd Type _ -> "" -- Types are erased. Assume _ -> "" -- So are type assumptions. -- | Compile a type signature. -- Since type signatures have no correspondence in the template C++ code , no C++ code is produced . compileType :: TypeSig -> String compileType _ = "" -- | Compile a data definition. -- -- Note that since this language doesn't allow pattern matching, this -- function will automatically define an appropriate eliminator for the -- data type. compileDataDef :: DataDef -> String compileDataDef (DataDef (TyCon tyConName _) variants) = decls [ intercalate sep $ zipWith defineCtor variants [0 ..] , defineElim variants ] where sep = "\n\n" localArg n = "__ctor_arg" ++ show n localStruct n = "__ctor_local" ++ show n ctorStruct = "__ctor_top_local" elimStruct = "__elim_top_local" primDataStruct = "__data" applyAlt = "apply_alt" -- Compile a single data constructor. defineCtor :: Variant -- ^ Data constructor. ^ Numeric suffix for . -> String defineCtor (DataCon cname ts) n = struct cname . decls $ [ go 0 ctorStruct [] ts , typedef $ innerType ctorStruct ] where go :: Int -> String -> [String] -> [Type] -> String go _ name args [] = struct name . typedef . concat $ [ primDataStruct , "<" , show n , ", " , dummy , concatMap ((", " ++) . innerType) (reverse args) , ">" ] go u name args (_:rest) = innerApply localA name . decls $ [ go (u + 1) localS (localA:args) rest , typedef $ innerType localS ] where localA = localArg u localS = localStruct u -- Compile an eliminator for the whole data type. defineElim :: [Variant] -> String defineElim vs = struct (firstToLower tyConName) . decls $ [ go 0 elimStruct [] vs , typedef $ innerType elimStruct ] where firstToLower [] = [] firstToLower (c:cs) = toLower c:cs ^ Numeric suffix for . -> String -- ^ Outer @struct@ name. -> [String] -- ^ Names of eliminator arguments. -> [Variant] -- ^ Data constructors. -> String go _ name args [] = struct name . struct ty . decls . intersperse "\n" $ [ fwdTemplate applyAlt ] ++ zipWith3 handleCase vs (reverse args) [0 ..] ++ [ template typeArg apply . typedef . innerType . concat $ [ applyAlt , "<" , innerType typeArg , ">" ] ] where typeArg = "__type_arg" go u name args (_:rest) = innerApply localA name . decls $ [ go (u + 1) localS (localA:args) rest , typedef $ innerType localS ] where localA = localArg u localS = localStruct u -- Compile a @template@ specialization which deconstructs @n@-th -- constructor and applies the corresponding elimination function to -- all its fields. handleCase :: Variant -- ^ 'Variant' to be compiled. -> String -- ^ Argument name. -> Int -- ^ Argument position. -> String handleCase (DataCon _ ts) arg n = concat [ "template <typename " , dummy , concatMap (", typename " ++) args , ">\nstruct " , applyAlt , "<" , primDataStruct , "<" , show n , ", " , dummy , concatMap (", " ++) args , "> >" , lbrace , decls $ wrapFields ++ [ compileExpr localS . foldl1 App . map Var $ arg:map (extra ++) args , typedef $ innerType localS ] , rbrace ] where -- Names of all constructor fields. args = zipWith (const $ (fieldA ++) . show) ts [0 :: Int ..] -- Create a wrapper @struct@ures so the data type can -- contain the values directly rather than just the -- expression names. -- -- This would otherwise lead to all kinds of problems with -- expressions not being interchangeable even though their -- values are. wrapFields = map wrapStruct args where wrapStruct name = struct (extra ++ name) $ typedef name fieldA = "__field_arg" localS = "__local_case" -- Prefix for the wrapped structures. extra = "__extra" -- | Compile a value definition. compileValDef :: ValueDef -> String compileValDef (ValueDef name expr) = struct name . decls $ [ compileExpr defStruct expr , typedef . innerType $ defStruct ] where defStruct = "__def" -- | Compile and expression given a name of @struct@ it should be declared in. compileExpr :: String -- ^ Name of the @struct@. -> Expr -> String compileExpr = go (0 :: Int) where localStruct n = "__local" ++ show n leftStruct n = "__left" ++ show n rightStruct n = "__right" ++ show n ^ Numeric suffix for . -> String -- ^ Outer @struct@ name. -> Expr -- ^ Expression to be compiled. -> String go _ name (Var v) = struct name . typedef . innerType $ v go u name (Lam x expr) = innerApply x name . decls $ [ go (u + 1) local expr , typedef $ innerType local ] where local = localStruct u go u name (App e1 e2) = struct name . decls $ [ go (u + 1) left e1 , go (u + 1) right e2 , typedef . concat $ [ "typename " , left , "::type::template apply<" , right , ">::type" ] ] where left = leftStruct u right = rightStruct u go u name (Let dec expr) = struct name . decls $ map compileValDef dec ++ [ go (u + 1) local expr , typedef $ innerType local ] where local = localStruct u go u name (SetType expr _) = go u name expr go _ name (NumLit n) = struct name . typedef $ "Int<" ++ show n ++ ">" go _ name (BoolLit b) = struct name . typedef $ "Bool<" ++ uncap (show b) ++ ">" -- Fixed point operator is transformed into language primitive -- "fix" and a lambda abstraction. go u name (Fix x expr) = go u name (App (Var "fix") (Lam x expr))
null
https://raw.githubusercontent.com/vituscze/norri/133aef0b42b2c5bdd789ce2fa2655aecfcb96424/src/Compiler/Compile.hs
haskell
metaprogram. * Module compiling * Top level entities compiling * Expression compiling | Left opening brace surrounded by newlines. | Right closing brace surrounded by newlines. | Print a @struct@ given its name and contents. struct s { int x; }; ^ Name of the @struct@. ^ Content of the @struct@. | Print a @template@ given its name, contents and the (only) template argument. >>> putStrLn $ template "x" "s" "int y;" template <typename x> struct s { int y; }; ^ Name of the template argument. ^ Name of the @struct@. ^ Content of the @struct@. | Print a @template@ @struct@ forward declaration. template <typename> struct s; ^ Name of the @struct@. >>> putStrLn $ typedef "int" typedef int type; ^ Type expression. | Print a type expression extracting inner @type@ from another type. typename vector::type ^ Type expression. | Print a nested hierarchy of @struct@ures used for lambda abstraction. >>> putStrLn $ innerApply "x" "s" "int x;" struct s { struct type { template <typename x> struct apply { int x; }; }; }; ^ Name of the template argument. ^ Name of the @struct@. ^ Content of the @struct@. | Print a list of declarations. This is just a name-flavored 'concat'. ^ List of declarations. | 'String' constant for inner @template@ used for lambda abstractions. | 'String' constant for inner @typedef@s. | Compile whole module. Compiles all top level entities contained in module. | Compile a top level declaration. Types are erased. So are type assumptions. | Compile a type signature. | Compile a data definition. Note that since this language doesn't allow pattern matching, this function will automatically define an appropriate eliminator for the data type. Compile a single data constructor. ^ Data constructor. Compile an eliminator for the whole data type. ^ Outer @struct@ name. ^ Names of eliminator arguments. ^ Data constructors. Compile a @template@ specialization which deconstructs @n@-th constructor and applies the corresponding elimination function to all its fields. ^ 'Variant' to be compiled. ^ Argument name. ^ Argument position. Names of all constructor fields. Create a wrapper @struct@ures so the data type can contain the values directly rather than just the expression names. This would otherwise lead to all kinds of problems with expressions not being interchangeable even though their values are. Prefix for the wrapped structures. | Compile a value definition. | Compile and expression given a name of @struct@ it should be declared in. ^ Name of the @struct@. ^ Outer @struct@ name. ^ Expression to be compiled. Fixed point operator is transformed into language primitive "fix" and a lambda abstraction.
| Allows the abstract syntax tree to be compiled into C++ template module Compiler.Compile ( compileModule , compileTopLevel , compileType , compileDataDef , compileValDef , compileExpr ) where import Data.Char import Data.List import Compiler.AST import Utility lbrace :: String lbrace = "\n{\n" rbrace :: String rbrace = "\n};\n" > > > struct " s " " int x ; " -> String struct name content = concat ["struct ", name, lbrace, content, rbrace] -> String template arg name content = "template <typename " ++ arg ++ ">\n" ++ struct name content > > > " s " -> String fwdTemplate name = "template <typename>\nstruct " ++ name ++ ";\n" | Print a @typedef@ which identifies type expression @what@ with @type@. -> String typedef what = "typedef " ++ what ++ " " ++ ty ++ ";" > > > innerType " vector " -> String innerType what = "typename " ++ what ++ "::" ++ ty -> String innerApply arg name = struct name . struct ty . template arg apply -> String decls = concat apply :: String apply = "apply" ty :: String ty = "type" | ' String ' constant for the @dummy@ type . dummy :: String dummy = "__dummy" compileModule :: Module -> String compileModule (Module m) = intercalate sep $ map compileTopLevel m where sep = "\n\n" compileTopLevel :: TopLevel -> String compileTopLevel tl = case tl of Data dd -> compileDataDef dd Value vd -> compileValDef vd Since type signatures have no correspondence in the template C++ code , no C++ code is produced . compileType :: TypeSig -> String compileType _ = "" compileDataDef :: DataDef -> String compileDataDef (DataDef (TyCon tyConName _) variants) = decls [ intercalate sep $ zipWith defineCtor variants [0 ..] , defineElim variants ] where sep = "\n\n" localArg n = "__ctor_arg" ++ show n localStruct n = "__ctor_local" ++ show n ctorStruct = "__ctor_top_local" elimStruct = "__elim_top_local" primDataStruct = "__data" applyAlt = "apply_alt" ^ Numeric suffix for . -> String defineCtor (DataCon cname ts) n = struct cname . decls $ [ go 0 ctorStruct [] ts , typedef $ innerType ctorStruct ] where go :: Int -> String -> [String] -> [Type] -> String go _ name args [] = struct name . typedef . concat $ [ primDataStruct , "<" , show n , ", " , dummy , concatMap ((", " ++) . innerType) (reverse args) , ">" ] go u name args (_:rest) = innerApply localA name . decls $ [ go (u + 1) localS (localA:args) rest , typedef $ innerType localS ] where localA = localArg u localS = localStruct u defineElim :: [Variant] -> String defineElim vs = struct (firstToLower tyConName) . decls $ [ go 0 elimStruct [] vs , typedef $ innerType elimStruct ] where firstToLower [] = [] firstToLower (c:cs) = toLower c:cs ^ Numeric suffix for . -> String go _ name args [] = struct name . struct ty . decls . intersperse "\n" $ [ fwdTemplate applyAlt ] ++ zipWith3 handleCase vs (reverse args) [0 ..] ++ [ template typeArg apply . typedef . innerType . concat $ [ applyAlt , "<" , innerType typeArg , ">" ] ] where typeArg = "__type_arg" go u name args (_:rest) = innerApply localA name . decls $ [ go (u + 1) localS (localA:args) rest , typedef $ innerType localS ] where localA = localArg u localS = localStruct u -> String handleCase (DataCon _ ts) arg n = concat [ "template <typename " , dummy , concatMap (", typename " ++) args , ">\nstruct " , applyAlt , "<" , primDataStruct , "<" , show n , ", " , dummy , concatMap (", " ++) args , "> >" , lbrace , decls $ wrapFields ++ [ compileExpr localS . foldl1 App . map Var $ arg:map (extra ++) args , typedef $ innerType localS ] , rbrace ] where args = zipWith (const $ (fieldA ++) . show) ts [0 :: Int ..] wrapFields = map wrapStruct args where wrapStruct name = struct (extra ++ name) $ typedef name fieldA = "__field_arg" localS = "__local_case" extra = "__extra" compileValDef :: ValueDef -> String compileValDef (ValueDef name expr) = struct name . decls $ [ compileExpr defStruct expr , typedef . innerType $ defStruct ] where defStruct = "__def" -> Expr -> String compileExpr = go (0 :: Int) where localStruct n = "__local" ++ show n leftStruct n = "__left" ++ show n rightStruct n = "__right" ++ show n ^ Numeric suffix for . -> String go _ name (Var v) = struct name . typedef . innerType $ v go u name (Lam x expr) = innerApply x name . decls $ [ go (u + 1) local expr , typedef $ innerType local ] where local = localStruct u go u name (App e1 e2) = struct name . decls $ [ go (u + 1) left e1 , go (u + 1) right e2 , typedef . concat $ [ "typename " , left , "::type::template apply<" , right , ">::type" ] ] where left = leftStruct u right = rightStruct u go u name (Let dec expr) = struct name . decls $ map compileValDef dec ++ [ go (u + 1) local expr , typedef $ innerType local ] where local = localStruct u go u name (SetType expr _) = go u name expr go _ name (NumLit n) = struct name . typedef $ "Int<" ++ show n ++ ">" go _ name (BoolLit b) = struct name . typedef $ "Bool<" ++ uncap (show b) ++ ">" go u name (Fix x expr) = go u name (App (Var "fix") (Lam x expr))
1475433469a86b6fd6fc008451e9afa829177d00f6525d85e16ba4bb68c41e6e
andgate/type-theory-compiler
Pretty.hs
# OPTIONS_GHC -fno - warn - orphans # # LANGUAGE LambdaCase , OverloadedStrings , FlexibleInstances , ViewPatterns # , OverloadedStrings , FlexibleInstances , ViewPatterns #-} module Language.STLC.Pretty where import Language.STLC.Syntax import qualified Data.List.NonEmpty as NE import Unbound.Generics.LocallyNameless import Data.Text.Prettyprint.Doc instance Pretty Module where pretty (Module _ n ds) = vsep (("module" <+> pretty n <> line):(pretty <$> ds)) instance Pretty Defn where pretty = \case FuncDefn f -> pretty (FreshP f) <> line ExternDefn ex -> pretty ex <> line DataTypeDefn dt -> pretty dt <> line instance Pretty Extern where pretty (Extern _ n paramtys retty) = hsep ["extern", pretty n, ":", pretty (tarr paramtys retty)] instance Pretty DataType where pretty (DataType _ n []) = "type" <+> pretty n pretty (DataType _ n (c:[])) = "type" <+> pretty n <+> "=" <+> pretty c pretty (DataType _ n (c:cs)) = vsep [ "type" <+> pretty n , indent 2 $ vsep $ [ "=" <+> pretty c ] ++ ["|" <+> pretty c' | c' <- cs] ] instance Pretty ConstrDefn where pretty = \case ConstrDefn _ n tys -> pretty n <+> hsep (pretty <$> tys) RecordDefn _ n (NE.toList -> ens) -> pretty n <+> encloseSep lbrace rbrace comma (pretty <$> ens) instance Pretty Entry where pretty (Entry _ n ty) = pretty n <+> ":" <+> pretty ty instance Pretty Type where pretty = \case TArr a b -> pretty a <+> "->" <+> pretty b TCon n -> pretty n TInt i -> "I" <> pretty i TUInt i -> "U" <> pretty i TFp i -> "F" <> pretty i TTuple t (NE.toList -> ts) -> tupled $ pretty <$> (t:ts) TArray i ty | isAType ty -> pretty ty <> brackets (pretty i) | True -> parens (pretty ty) <> brackets (pretty i) TVect i ty | isAType ty -> pretty ty <> brackets (pretty i) | True -> parens (pretty ty) <> angles (pretty i) TPtr ty | isAType ty -> "*" <> pretty ty | True -> "*" <> parens (pretty ty) TLoc ty _ -> pretty ty TParens ty -> parens $ pretty ty instance Pretty Exp where pretty = pretty . FreshP class PrettyFresh a where prettyFresh :: Fresh m => a -> m (Doc ann) newtype FreshP a = FreshP a instance PrettyFresh a => Pretty (FreshP a) where pretty (FreshP a) = runFreshM $ prettyFresh a instance PrettyFresh Func where prettyFresh (Func _ ty n bnd) = do (ps, body) <- unbind bnd let ps' = do p <- ps let p' = pretty p return $ if isAPat p then p' else parens p' body' <- prettyFresh body case ps' of [] -> if isAExp body || isBExp body then return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> "=" <+> body' ] else return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> "=" , indent 2 body' ] _ -> if isAExp body || isBExp body then return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> hsep ps' <+> "=" <+> body' ] else return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> hsep ps' , indent 2 ("=" <+> align body') ] instance PrettyFresh Exp where prettyFresh = \case EVar n -> return $ pretty (name2String n) ELit l -> prettyFresh l EApp f (NE.toList -> xs) -> do f' <- wrapBExpFresh f xs' <- mapM wrapBExpFresh xs return $ hsep (f':xs') EType e ty -> do e' <- prettyFresh e let ty' = pretty ty if isAExp e || isBExp e then return $ hsep [e', ":", ty'] else return $ hsep [parens e', ":", ty'] ECast e ty -> do e' <- prettyFresh e let ty' = pretty ty if isAExp e || isBExp e then return $ hsep [e', "as", ty'] else return $ hsep [parens e', "as", ty'] ELoc e _ -> prettyFresh e EParens e -> parens <$> prettyFresh e ELam bnd -> do (NE.toList -> ps, body) <- unbind bnd body' <- prettyFresh body return $ align $ vsep [ "\\" <+> hsep (pretty <$> ps) <+> "->" , indent 4 body' ] ELet bnd -> do (r_qs, body) <- unbind bnd let (ps, es) = unzip [ (p, e) | (p, Embed e) <- NE.toList (unrec r_qs)] let ps' = pretty <$> ps es' <- mapM prettyFresh es let qs' = [ q' <+> "=" <+> e' | (q', e') <- zip ps' es' ] body' <- prettyFresh body return $ vsep [ "let" <+> align (vsep qs') , "in" <+> body' ] EIf p t f -> do p' <- prettyFresh p t' <- prettyFresh t f' <- prettyFresh f return $ vsep [ "if" <+> p' , indent 2 ("then" <+> t') , indent 2 f' ] ECase e cls -> do e' <- prettyFresh e cls' <- mapM prettyFresh (NE.toList cls) return $ vsep $ [ "case" <+> e' <+> "of" , indent 2 (vsep cls')] ERef e -> do e' <- prettyFresh e if isAExp e then return $ "&" <> e' else return $ "&" <> parens e' EDeref e -> do e' <- prettyFresh e if isAExp e then return $ "*" <> e' else return $ "*" <> parens e' ETuple e (NE.toList -> es) -> tupled <$> mapM prettyFresh (e:es) ECon n [] -> return $ pretty n ECon n args -> do args' <- mapM prettyFresh args return $ pretty n <+> hsep args' ENewCon n [] -> return $ "new" <+> pretty n ENewCon n args -> do args' <- mapM prettyFresh args return $ "new" <+> pretty n <+> hsep args' EFree e -> do e' <- prettyFresh e return $ "free" <+> e' EGet e m -> do e' <- wrapBExpFresh e return $ e' <> "." <> pretty m EGetI e i -> do e' <- wrapBExpFresh e i' <- prettyFresh i return $ e' <> brackets i' ESet rhs lhs -> do lhs' <- prettyFresh lhs rhs' <- prettyFresh rhs return $ lhs' <+> "<-" <> rhs' ENewArray xs -> do xs' <- mapM prettyFresh xs return $ "new" <+> list xs' ENewArrayI i -> do i' <- prettyFresh i return $ "new" <+> "Array" <> brackets i' EResizeArray e i -> do e' <- wrapBExpFresh e i' <- prettyFresh i return $ "resize" <+> e' <> brackets i' ENewVect xs -> do xs' <- mapM prettyFresh xs return $ "new" <+> encloseSep "<" ">" "," xs' ENewVectI i -> do i' <- prettyFresh i return $ "new" <+> "Vect" <> angles i' ENewString str -> return $ "new" <+> dquotes (pretty str) EOp op -> prettyFresh op instance PrettyFresh Lit where prettyFresh = \case LNull -> return "null" LBool b -> return $ pretty b LInt i -> return $ pretty i LDouble d -> return $ pretty d LChar c -> return $ squotes $ pretty c LString s -> return $ dquotes $ pretty s LArray es -> do es' <- mapM prettyFresh es return $ list es' LArrayI i -> do i' <- prettyFresh i return $ "Array" <> brackets i' LVect es -> do es' <- mapM prettyFresh es return $ encloseSep "<" ">" "," es' LVectI i -> do i' <- prettyFresh i return $ "Vect" <> angles i' instance PrettyFresh Else where prettyFresh = \case Elif _ p t f -> do p' <- prettyFresh p t' <- prettyFresh t f' <- prettyFresh f return $ vsep [ "elif" <+> p' , "then" <+> t' , f' ] Else _ body -> do body' <- prettyFresh body return $ "else" <+> body' instance Pretty Pat where pretty = \case PVar v -> pretty $ name2String v PCon n [] -> pretty n PCon n ps -> let ps' = do p <- ps return $ if isAPat p then pretty p else parens $ pretty p in pretty n <+> hsep ps' PTuple p (NE.toList -> ps) -> tupled $ pretty <$> (p:ps) PWild -> "_" PType p ty -> hsep [pretty p, ":", pretty ty] PLoc p _ -> pretty p PParens p -> parens $ pretty p instance PrettyFresh Clause where prettyFresh (Clause _ bnd) = do (p, e) <- unbind bnd let p' = if isAPat p || isBPat p then pretty p else parens $ pretty p e' <- prettyFresh e if isAExp e || isBExp e then return $ p' <+> "->" <+> e' else return $ vcat [ p' <+> "->" , indent 2 e' , mempty ] instance PrettyFresh Op where prettyFresh = \case OpAdd a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#add", a', b'] OpSub a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#sub", a', b'] OpMul a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#mul", a', b'] OpDiv a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#div", a', b'] OpRem a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#rem", a', b'] OpNeg a -> do a' <- wrapBExpFresh a return $ hsep ["#neg", a'] OpAnd a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#and", a', b'] OpOr a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#or", a', b'] OpXor a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#xor", a', b'] OpShR a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#shr", a', b'] OpShL a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#shl", a', b'] OpEq a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#eq", a', b'] OpNeq a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#neq", a', b'] OpLT a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#lt", a', b'] OpLE a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#le", a', b'] OpGT a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#gt", a', b'] OpGE a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#ge", a', b'] ----------------------------------------------------------------------- -- Helpers ----------------------------------------------------------------------- wrapBExpFresh :: Fresh m => Exp -> m (Doc ann) wrapBExpFresh e | isAExp e = prettyFresh e | True = parens <$> prettyFresh e isBExp :: Exp -> Bool isBExp = \case EVar _ -> False ELit _ -> False EApp _ _ -> True EType _ _ -> False ECast _ _ -> False ELoc e _ -> isBExp e EParens _ -> False ELam _ -> False ELet _ -> False EIf _ _ _ -> False ECase _ _ -> False ERef _ -> False EDeref _ -> False ETuple _ _ -> False ECon _ [] -> False ECon _ _ -> True ENewCon _ _ -> True EFree _ -> True EGet _ _ -> False EGetI _ _ -> False ESet _ _ -> True ENewArray _ -> True ENewArrayI _ -> True EResizeArray _ _ -> True ENewVect _ -> True ENewVectI _ -> True ENewString _ -> True EOp _ -> True isAExp :: Exp -> Bool isAExp = \case EVar _ -> True ELit _ -> True EApp _ _ -> False EType _ _ -> False ECast _ _ -> False ELoc e _ -> isAExp e EParens _ -> True ELam _ -> False ELet _ -> False EIf _ _ _ -> False ECase _ _ -> False ERef _ -> True EDeref _ -> True ETuple _ _ -> True ECon _ [] -> True ECon _ _ -> False ENewCon _ _ -> False EFree _ -> False EGet e _ -> isAExp e EGetI e _ -> isAExp e ESet _ _ -> False ENewArray _ -> False ENewArrayI _ -> False EResizeArray _ _ -> False ENewVect _ -> False ENewVectI _ -> False ENewString _ -> False EOp _ -> False isAType :: Type -> Bool isAType = \case TArr _ _ -> False TCon _ -> True TInt _ -> True TUInt _ -> True TFp _ -> True TTuple _ _ -> True TArray _ _ -> True TVect _ _ -> True TPtr _ -> True TLoc ty _ -> isAType ty TParens _ -> True isAPat :: Pat -> Bool isAPat = \case PVar _ -> True PCon _ [] -> True PCon _ _ -> False PTuple _ _ -> True PWild -> True PType _ _ -> False PLoc p _ -> isAPat p PParens _ -> True isBPat :: Pat -> Bool isBPat = \case PVar _ -> False PCon _ [] -> False PCon _ _ -> True PTuple _ _ -> False PWild -> False PType _ _ -> False PLoc p _ -> isBPat p PParens _ -> False
null
https://raw.githubusercontent.com/andgate/type-theory-compiler/a404f085d19a19b16ae8c26616707dc46707ea10/stlc/src/Language/STLC/Pretty.hs
haskell
--------------------------------------------------------------------- Helpers ---------------------------------------------------------------------
# OPTIONS_GHC -fno - warn - orphans # # LANGUAGE LambdaCase , OverloadedStrings , FlexibleInstances , ViewPatterns # , OverloadedStrings , FlexibleInstances , ViewPatterns #-} module Language.STLC.Pretty where import Language.STLC.Syntax import qualified Data.List.NonEmpty as NE import Unbound.Generics.LocallyNameless import Data.Text.Prettyprint.Doc instance Pretty Module where pretty (Module _ n ds) = vsep (("module" <+> pretty n <> line):(pretty <$> ds)) instance Pretty Defn where pretty = \case FuncDefn f -> pretty (FreshP f) <> line ExternDefn ex -> pretty ex <> line DataTypeDefn dt -> pretty dt <> line instance Pretty Extern where pretty (Extern _ n paramtys retty) = hsep ["extern", pretty n, ":", pretty (tarr paramtys retty)] instance Pretty DataType where pretty (DataType _ n []) = "type" <+> pretty n pretty (DataType _ n (c:[])) = "type" <+> pretty n <+> "=" <+> pretty c pretty (DataType _ n (c:cs)) = vsep [ "type" <+> pretty n , indent 2 $ vsep $ [ "=" <+> pretty c ] ++ ["|" <+> pretty c' | c' <- cs] ] instance Pretty ConstrDefn where pretty = \case ConstrDefn _ n tys -> pretty n <+> hsep (pretty <$> tys) RecordDefn _ n (NE.toList -> ens) -> pretty n <+> encloseSep lbrace rbrace comma (pretty <$> ens) instance Pretty Entry where pretty (Entry _ n ty) = pretty n <+> ":" <+> pretty ty instance Pretty Type where pretty = \case TArr a b -> pretty a <+> "->" <+> pretty b TCon n -> pretty n TInt i -> "I" <> pretty i TUInt i -> "U" <> pretty i TFp i -> "F" <> pretty i TTuple t (NE.toList -> ts) -> tupled $ pretty <$> (t:ts) TArray i ty | isAType ty -> pretty ty <> brackets (pretty i) | True -> parens (pretty ty) <> brackets (pretty i) TVect i ty | isAType ty -> pretty ty <> brackets (pretty i) | True -> parens (pretty ty) <> angles (pretty i) TPtr ty | isAType ty -> "*" <> pretty ty | True -> "*" <> parens (pretty ty) TLoc ty _ -> pretty ty TParens ty -> parens $ pretty ty instance Pretty Exp where pretty = pretty . FreshP class PrettyFresh a where prettyFresh :: Fresh m => a -> m (Doc ann) newtype FreshP a = FreshP a instance PrettyFresh a => Pretty (FreshP a) where pretty (FreshP a) = runFreshM $ prettyFresh a instance PrettyFresh Func where prettyFresh (Func _ ty n bnd) = do (ps, body) <- unbind bnd let ps' = do p <- ps let p' = pretty p return $ if isAPat p then p' else parens p' body' <- prettyFresh body case ps' of [] -> if isAExp body || isBExp body then return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> "=" <+> body' ] else return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> "=" , indent 2 body' ] _ -> if isAExp body || isBExp body then return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> hsep ps' <+> "=" <+> body' ] else return $ vsep [ pretty n <+> ":" <+> pretty ty , pretty n <+> hsep ps' , indent 2 ("=" <+> align body') ] instance PrettyFresh Exp where prettyFresh = \case EVar n -> return $ pretty (name2String n) ELit l -> prettyFresh l EApp f (NE.toList -> xs) -> do f' <- wrapBExpFresh f xs' <- mapM wrapBExpFresh xs return $ hsep (f':xs') EType e ty -> do e' <- prettyFresh e let ty' = pretty ty if isAExp e || isBExp e then return $ hsep [e', ":", ty'] else return $ hsep [parens e', ":", ty'] ECast e ty -> do e' <- prettyFresh e let ty' = pretty ty if isAExp e || isBExp e then return $ hsep [e', "as", ty'] else return $ hsep [parens e', "as", ty'] ELoc e _ -> prettyFresh e EParens e -> parens <$> prettyFresh e ELam bnd -> do (NE.toList -> ps, body) <- unbind bnd body' <- prettyFresh body return $ align $ vsep [ "\\" <+> hsep (pretty <$> ps) <+> "->" , indent 4 body' ] ELet bnd -> do (r_qs, body) <- unbind bnd let (ps, es) = unzip [ (p, e) | (p, Embed e) <- NE.toList (unrec r_qs)] let ps' = pretty <$> ps es' <- mapM prettyFresh es let qs' = [ q' <+> "=" <+> e' | (q', e') <- zip ps' es' ] body' <- prettyFresh body return $ vsep [ "let" <+> align (vsep qs') , "in" <+> body' ] EIf p t f -> do p' <- prettyFresh p t' <- prettyFresh t f' <- prettyFresh f return $ vsep [ "if" <+> p' , indent 2 ("then" <+> t') , indent 2 f' ] ECase e cls -> do e' <- prettyFresh e cls' <- mapM prettyFresh (NE.toList cls) return $ vsep $ [ "case" <+> e' <+> "of" , indent 2 (vsep cls')] ERef e -> do e' <- prettyFresh e if isAExp e then return $ "&" <> e' else return $ "&" <> parens e' EDeref e -> do e' <- prettyFresh e if isAExp e then return $ "*" <> e' else return $ "*" <> parens e' ETuple e (NE.toList -> es) -> tupled <$> mapM prettyFresh (e:es) ECon n [] -> return $ pretty n ECon n args -> do args' <- mapM prettyFresh args return $ pretty n <+> hsep args' ENewCon n [] -> return $ "new" <+> pretty n ENewCon n args -> do args' <- mapM prettyFresh args return $ "new" <+> pretty n <+> hsep args' EFree e -> do e' <- prettyFresh e return $ "free" <+> e' EGet e m -> do e' <- wrapBExpFresh e return $ e' <> "." <> pretty m EGetI e i -> do e' <- wrapBExpFresh e i' <- prettyFresh i return $ e' <> brackets i' ESet rhs lhs -> do lhs' <- prettyFresh lhs rhs' <- prettyFresh rhs return $ lhs' <+> "<-" <> rhs' ENewArray xs -> do xs' <- mapM prettyFresh xs return $ "new" <+> list xs' ENewArrayI i -> do i' <- prettyFresh i return $ "new" <+> "Array" <> brackets i' EResizeArray e i -> do e' <- wrapBExpFresh e i' <- prettyFresh i return $ "resize" <+> e' <> brackets i' ENewVect xs -> do xs' <- mapM prettyFresh xs return $ "new" <+> encloseSep "<" ">" "," xs' ENewVectI i -> do i' <- prettyFresh i return $ "new" <+> "Vect" <> angles i' ENewString str -> return $ "new" <+> dquotes (pretty str) EOp op -> prettyFresh op instance PrettyFresh Lit where prettyFresh = \case LNull -> return "null" LBool b -> return $ pretty b LInt i -> return $ pretty i LDouble d -> return $ pretty d LChar c -> return $ squotes $ pretty c LString s -> return $ dquotes $ pretty s LArray es -> do es' <- mapM prettyFresh es return $ list es' LArrayI i -> do i' <- prettyFresh i return $ "Array" <> brackets i' LVect es -> do es' <- mapM prettyFresh es return $ encloseSep "<" ">" "," es' LVectI i -> do i' <- prettyFresh i return $ "Vect" <> angles i' instance PrettyFresh Else where prettyFresh = \case Elif _ p t f -> do p' <- prettyFresh p t' <- prettyFresh t f' <- prettyFresh f return $ vsep [ "elif" <+> p' , "then" <+> t' , f' ] Else _ body -> do body' <- prettyFresh body return $ "else" <+> body' instance Pretty Pat where pretty = \case PVar v -> pretty $ name2String v PCon n [] -> pretty n PCon n ps -> let ps' = do p <- ps return $ if isAPat p then pretty p else parens $ pretty p in pretty n <+> hsep ps' PTuple p (NE.toList -> ps) -> tupled $ pretty <$> (p:ps) PWild -> "_" PType p ty -> hsep [pretty p, ":", pretty ty] PLoc p _ -> pretty p PParens p -> parens $ pretty p instance PrettyFresh Clause where prettyFresh (Clause _ bnd) = do (p, e) <- unbind bnd let p' = if isAPat p || isBPat p then pretty p else parens $ pretty p e' <- prettyFresh e if isAExp e || isBExp e then return $ p' <+> "->" <+> e' else return $ vcat [ p' <+> "->" , indent 2 e' , mempty ] instance PrettyFresh Op where prettyFresh = \case OpAdd a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#add", a', b'] OpSub a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#sub", a', b'] OpMul a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#mul", a', b'] OpDiv a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#div", a', b'] OpRem a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#rem", a', b'] OpNeg a -> do a' <- wrapBExpFresh a return $ hsep ["#neg", a'] OpAnd a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#and", a', b'] OpOr a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#or", a', b'] OpXor a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#xor", a', b'] OpShR a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#shr", a', b'] OpShL a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#shl", a', b'] OpEq a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#eq", a', b'] OpNeq a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#neq", a', b'] OpLT a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#lt", a', b'] OpLE a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#le", a', b'] OpGT a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#gt", a', b'] OpGE a b -> do a' <- wrapBExpFresh a b' <- wrapBExpFresh b return $ hsep ["#ge", a', b'] wrapBExpFresh :: Fresh m => Exp -> m (Doc ann) wrapBExpFresh e | isAExp e = prettyFresh e | True = parens <$> prettyFresh e isBExp :: Exp -> Bool isBExp = \case EVar _ -> False ELit _ -> False EApp _ _ -> True EType _ _ -> False ECast _ _ -> False ELoc e _ -> isBExp e EParens _ -> False ELam _ -> False ELet _ -> False EIf _ _ _ -> False ECase _ _ -> False ERef _ -> False EDeref _ -> False ETuple _ _ -> False ECon _ [] -> False ECon _ _ -> True ENewCon _ _ -> True EFree _ -> True EGet _ _ -> False EGetI _ _ -> False ESet _ _ -> True ENewArray _ -> True ENewArrayI _ -> True EResizeArray _ _ -> True ENewVect _ -> True ENewVectI _ -> True ENewString _ -> True EOp _ -> True isAExp :: Exp -> Bool isAExp = \case EVar _ -> True ELit _ -> True EApp _ _ -> False EType _ _ -> False ECast _ _ -> False ELoc e _ -> isAExp e EParens _ -> True ELam _ -> False ELet _ -> False EIf _ _ _ -> False ECase _ _ -> False ERef _ -> True EDeref _ -> True ETuple _ _ -> True ECon _ [] -> True ECon _ _ -> False ENewCon _ _ -> False EFree _ -> False EGet e _ -> isAExp e EGetI e _ -> isAExp e ESet _ _ -> False ENewArray _ -> False ENewArrayI _ -> False EResizeArray _ _ -> False ENewVect _ -> False ENewVectI _ -> False ENewString _ -> False EOp _ -> False isAType :: Type -> Bool isAType = \case TArr _ _ -> False TCon _ -> True TInt _ -> True TUInt _ -> True TFp _ -> True TTuple _ _ -> True TArray _ _ -> True TVect _ _ -> True TPtr _ -> True TLoc ty _ -> isAType ty TParens _ -> True isAPat :: Pat -> Bool isAPat = \case PVar _ -> True PCon _ [] -> True PCon _ _ -> False PTuple _ _ -> True PWild -> True PType _ _ -> False PLoc p _ -> isAPat p PParens _ -> True isBPat :: Pat -> Bool isBPat = \case PVar _ -> False PCon _ [] -> False PCon _ _ -> True PTuple _ _ -> False PWild -> False PType _ _ -> False PLoc p _ -> isBPat p PParens _ -> False
ad2b8479be221ec1c596085ff22cd4cbd53b061e9b9c4eb9b8f55c464a780232
reasonml/reason
printer_maker.ml
open Reason_omp type parse_itype = [ `ML | `Reason | `Binary | `BinaryReason | `Auto ] type print_itype = [ `ML | `Reason | `Binary | `BinaryReason | `AST | `None ] exception Invalid_config of string module type PRINTER = sig type t val parse : use_stdin:bool -> parse_itype -> string -> ((t * Reason_comment.t list) * bool) val print : print_itype -> string -> bool -> out_channel -> Format.formatter -> ((t * Reason_comment.t list) -> unit) end let err s = raise (Invalid_config s) let prepare_output_file name = match name with | Some name -> open_out_bin name | None -> set_binary_mode_out stdout true; stdout let close_output_file output_file output_chan = match output_file with | Some _ -> close_out output_chan | None -> () let ocamlBinaryParser use_stdin filename = let chan = match use_stdin with | true -> stdin | false -> let file_chan = open_in_bin filename in seek_in file_chan 0; file_chan in match Ast_io.from_channel chan with | Result.Error _ -> assert false | Result.Ok (_, Ast_io.Impl ((module Version), ast)) -> let module Convert = Convert(Version)(OCaml_408) in ((Obj.magic (Convert.copy_structure ast), []), true, false) | Result.Ok (_, Ast_io.Intf ((module Version), ast)) -> let module Convert = Convert(Version)(OCaml_408) in ((Obj.magic (Convert.copy_signature ast), []), true, true) let reasonBinaryParser use_stdin filename = let chan = match use_stdin with | true -> stdin | false -> let file_chan = open_in_bin filename in seek_in file_chan 0; file_chan in let (_, _, ast, comments, parsedAsML, parsedAsInterface) = input_value chan in ((ast, comments), parsedAsML, parsedAsInterface)
null
https://raw.githubusercontent.com/reasonml/reason/4f6ff7616bfa699059d642a3d16d8905d83555f6/src/refmt/printer_maker.ml
ocaml
open Reason_omp type parse_itype = [ `ML | `Reason | `Binary | `BinaryReason | `Auto ] type print_itype = [ `ML | `Reason | `Binary | `BinaryReason | `AST | `None ] exception Invalid_config of string module type PRINTER = sig type t val parse : use_stdin:bool -> parse_itype -> string -> ((t * Reason_comment.t list) * bool) val print : print_itype -> string -> bool -> out_channel -> Format.formatter -> ((t * Reason_comment.t list) -> unit) end let err s = raise (Invalid_config s) let prepare_output_file name = match name with | Some name -> open_out_bin name | None -> set_binary_mode_out stdout true; stdout let close_output_file output_file output_chan = match output_file with | Some _ -> close_out output_chan | None -> () let ocamlBinaryParser use_stdin filename = let chan = match use_stdin with | true -> stdin | false -> let file_chan = open_in_bin filename in seek_in file_chan 0; file_chan in match Ast_io.from_channel chan with | Result.Error _ -> assert false | Result.Ok (_, Ast_io.Impl ((module Version), ast)) -> let module Convert = Convert(Version)(OCaml_408) in ((Obj.magic (Convert.copy_structure ast), []), true, false) | Result.Ok (_, Ast_io.Intf ((module Version), ast)) -> let module Convert = Convert(Version)(OCaml_408) in ((Obj.magic (Convert.copy_signature ast), []), true, true) let reasonBinaryParser use_stdin filename = let chan = match use_stdin with | true -> stdin | false -> let file_chan = open_in_bin filename in seek_in file_chan 0; file_chan in let (_, _, ast, comments, parsedAsML, parsedAsInterface) = input_value chan in ((ast, comments), parsedAsML, parsedAsInterface)
6bf7deb7b1895d1016bf0d3e730af5b39e42b58ba052487f3cda8c2a3756b23d
charleso/bantam
Login.hs
# LANGUAGE NoImplicitPrelude # module Bantam.Service.Api.Login ( Login (..) ) where import Bantam.Service.Data import P data Login m = Login { login :: Email -> Password -> m (Maybe SessionId) , getSession :: SessionId -> m (Maybe Email) , createAccount :: Email -> Password -> m (Maybe SessionId) }
null
https://raw.githubusercontent.com/charleso/bantam/3af8d08f8e649cb5690815d17e6c79a3a9033d47/bantam-service/src/Bantam/Service/Api/Login.hs
haskell
# LANGUAGE NoImplicitPrelude # module Bantam.Service.Api.Login ( Login (..) ) where import Bantam.Service.Data import P data Login m = Login { login :: Email -> Password -> m (Maybe SessionId) , getSession :: SessionId -> m (Maybe Email) , createAccount :: Email -> Password -> m (Maybe SessionId) }
8a7962db1fd39f070ae0f9d226659890781044b2e558a6d7b6b00cfe3332d3e6
TorXakis/TorXakis
Constant.hs
TorXakis - Model Based Testing Copyright ( c ) 2015 - 2017 TNO and Radboud University See LICENSE at root directory of this repository . TorXakis - Model Based Testing Copyright (c) 2015-2017 TNO and Radboud University See LICENSE at root directory of this repository. -} -------------------------------------------------------------------------------- -- | Module : TorXakis . Compiler . . Constant Copyright : ( c ) TNO and Radboud University License : BSD3 ( see the file license.txt ) -- Maintainer : ( Embedded Systems Innovation by ) -- Stability : experimental -- Portability : portable -- -- Compilation to 'TorXakis' @Constant@'s. -------------------------------------------------------------------------------- module TorXakis.Compiler.ValExpr.Constant (constToConstant) where import qualified Constant import SortId (SortId) import TorXakis.Parser.Data (Const (AnyConst, BoolConst, IntConst, RegexConst, StringConst)) -- | Transform a constant declaration into a 'TorXakis' @Constant@. constToConstant :: SortId -> Const -> Constant.Constant constToConstant _ (BoolConst b) = Constant.Cbool b constToConstant _ (IntConst i) = Constant.Cint i constToConstant _ (StringConst s) = Constant.Cstring s constToConstant _ (RegexConst s) = Constant.Cregex s constToConstant sId AnyConst = Constant.Cany sId
null
https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/sys/txs-compiler/src/TorXakis/Compiler/ValExpr/Constant.hs
haskell
------------------------------------------------------------------------------ | Stability : experimental Portability : portable Compilation to 'TorXakis' @Constant@'s. ------------------------------------------------------------------------------ | Transform a constant declaration into a 'TorXakis' @Constant@.
TorXakis - Model Based Testing Copyright ( c ) 2015 - 2017 TNO and Radboud University See LICENSE at root directory of this repository . TorXakis - Model Based Testing Copyright (c) 2015-2017 TNO and Radboud University See LICENSE at root directory of this repository. -} Module : TorXakis . Compiler . . Constant Copyright : ( c ) TNO and Radboud University License : BSD3 ( see the file license.txt ) Maintainer : ( Embedded Systems Innovation by ) module TorXakis.Compiler.ValExpr.Constant (constToConstant) where import qualified Constant import SortId (SortId) import TorXakis.Parser.Data (Const (AnyConst, BoolConst, IntConst, RegexConst, StringConst)) constToConstant :: SortId -> Const -> Constant.Constant constToConstant _ (BoolConst b) = Constant.Cbool b constToConstant _ (IntConst i) = Constant.Cint i constToConstant _ (StringConst s) = Constant.Cstring s constToConstant _ (RegexConst s) = Constant.Cregex s constToConstant sId AnyConst = Constant.Cany sId
b131d94810c711965dd1bce4e03b13414db2fd30a7ec5d8937106ca05d41aa9d
walkie/Hagl
TicTacToe.hs
| An implementation of the game Tic Tac Toe . Try playing against the minimax algorithm by running in GHCi : > > > playTicTacToe Valid moves are the integers [ 0 .. 8 ] , where each integer names square of the board , starting in the upper left and proceeding in the order that you would read a book . The named square must be empty . An implementation of the game Tic Tac Toe. Try playing against the minimax algorithm by running in GHCi: >>> playTicTacToe Valid moves are the integers [0..8], where each integer names square of the board, starting in the upper left and proceeding in the order that you would read a book. The named square must be empty. -} module Hagl.Example.TicTacToe where import Control.Monad.Trans (liftIO) import Data.List (elemIndices, intersperse, transpose) import Text.Printf (printf) import Hagl -- -- * Game represetation. -- -- | Each square either has an X, an O, or is empty. data Square = X | O | E deriving Eq | A board is a 3x3 grid of squares , represented as a 9 - element list . type Board = [Square] -- | A move is indicated by a naming the index of the square to put your mark in , [ 0 .. 8 ] . type Mark = Int | A trivial data type for Tic Tac Toe . data TicTacToe = TicTacToe -- | The initial board. start :: Board start = replicate 9 E -- | The mark corresponding to each player. xo 1 = X xo 2 = O -- | Get a list of empty squares. markable :: Board -> [Mark] markable = elemIndices E -- | The player whose turn it is. who :: Board -> PlayerID who b = if (odd . length . markable) b then 1 else 2 -- | Player p marks square m. mark :: Board -> Mark -> Board mark b m = take m b ++ xo (who b) : drop (m+1) b | True if player has won . win :: PlayerID -> Board -> Bool win p b = any (all (xo p ==)) (h ++ v ++ d) where h = chunk 3 b v = transpose h d = map (map (b !!)) [[0,4,8],[2,4,6]] -- | True if the game is over. end :: Board -> Bool end b = null (markable b) || win 1 b || win 2 b -- | The payoff awarded for a final state. pay :: Board -> Payoff pay b | win 1 b = winner 2 1 | win 2 b = winner 2 2 | otherwise = tie 2 -- | Play a game against minimax! playTicTacToe = evalGame TicTacToe ["Puny Human" ::: human, "Minimax" ::: minimax] (run >> printScore) where run = printGame >> step >>= maybe run (\p -> printGame >> return p) -- Game instance instance Game TicTacToe where type TreeType TicTacToe = Discrete type Move TicTacToe = Mark type State TicTacToe = Board gameTree _ = stateTreeD who end markable mark pay start -- -- * Pretty printing -- instance Show Square where show X = "X" show O = "O" show E = " " -- | A string representation of the game board. showGame :: Board -> String showGame = concat . intersperse "\n" . intersperse line . map row . chunk 3 . map show where row [a,b,c] = printf " %s | %s | %s " a b c line = "-----------" -- | Print out the game during game execution. printGame :: GameM m TicTacToe => m () printGame = gameState >>= liftIO . putStrLn . showGame
null
https://raw.githubusercontent.com/walkie/Hagl/ac1edda51c53d2b683c4ada3f1c3d4d14a285d38/src/Hagl/Example/TicTacToe.hs
haskell
* Game represetation. | Each square either has an X, an O, or is empty. | A move is indicated by a naming the index of the square to put your | The initial board. | The mark corresponding to each player. | Get a list of empty squares. | The player whose turn it is. | Player p marks square m. | True if the game is over. | The payoff awarded for a final state. | Play a game against minimax! Game instance * Pretty printing | A string representation of the game board. | Print out the game during game execution.
| An implementation of the game Tic Tac Toe . Try playing against the minimax algorithm by running in GHCi : > > > playTicTacToe Valid moves are the integers [ 0 .. 8 ] , where each integer names square of the board , starting in the upper left and proceeding in the order that you would read a book . The named square must be empty . An implementation of the game Tic Tac Toe. Try playing against the minimax algorithm by running in GHCi: >>> playTicTacToe Valid moves are the integers [0..8], where each integer names square of the board, starting in the upper left and proceeding in the order that you would read a book. The named square must be empty. -} module Hagl.Example.TicTacToe where import Control.Monad.Trans (liftIO) import Data.List (elemIndices, intersperse, transpose) import Text.Printf (printf) import Hagl data Square = X | O | E deriving Eq | A board is a 3x3 grid of squares , represented as a 9 - element list . type Board = [Square] mark in , [ 0 .. 8 ] . type Mark = Int | A trivial data type for Tic Tac Toe . data TicTacToe = TicTacToe start :: Board start = replicate 9 E xo 1 = X xo 2 = O markable :: Board -> [Mark] markable = elemIndices E who :: Board -> PlayerID who b = if (odd . length . markable) b then 1 else 2 mark :: Board -> Mark -> Board mark b m = take m b ++ xo (who b) : drop (m+1) b | True if player has won . win :: PlayerID -> Board -> Bool win p b = any (all (xo p ==)) (h ++ v ++ d) where h = chunk 3 b v = transpose h d = map (map (b !!)) [[0,4,8],[2,4,6]] end :: Board -> Bool end b = null (markable b) || win 1 b || win 2 b pay :: Board -> Payoff pay b | win 1 b = winner 2 1 | win 2 b = winner 2 2 | otherwise = tie 2 playTicTacToe = evalGame TicTacToe ["Puny Human" ::: human, "Minimax" ::: minimax] (run >> printScore) where run = printGame >> step >>= maybe run (\p -> printGame >> return p) instance Game TicTacToe where type TreeType TicTacToe = Discrete type Move TicTacToe = Mark type State TicTacToe = Board gameTree _ = stateTreeD who end markable mark pay start instance Show Square where show X = "X" show O = "O" show E = " " showGame :: Board -> String showGame = concat . intersperse "\n" . intersperse line . map row . chunk 3 . map show where row [a,b,c] = printf " %s | %s | %s " a b c line = "-----------" printGame :: GameM m TicTacToe => m () printGame = gameState >>= liftIO . putStrLn . showGame
706ac8ee3a5a99ec69768ad2c0ae25de0896cb8f687ce47c7c2fe6546cdef70c
runeksvendsen/restful-payment-channel-server
Types.hs
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # # LANGUAGE OverloadedStrings , DataKinds , FlexibleContexts , LambdaCase , TypeOperators # module PayChanServer.Config.Types ( module PayChanServer.Config.Types , Config ) where import AppPrelude.Types.Orphans () import AppPrelude.Util import qualified . Interface as Store import qualified PayChanServer.Callback.Interface as Callback import PaymentChannel.Types (ServerPayChanX, BtcAmount) import qualified PaymentChannel as BTC import qualified Network.Haskoin.Transaction as HT import qualified Network.Haskoin.Crypto as HC import qualified Crypto.Secp256k1 as Secp import Control.Lens.TH (makeLenses) import qualified Data.ByteString as BS import Data.Configurator.Types (Config, Configured, convert, Value(..)) import Data.Ratio import qualified BlockchainAPI.Types as BtcType import qualified Data.Tagged as Tag -- import Servant.Server.Internal.Context (Context(EmptyContext, (:.))) --- Tagged types getVal = Tag.unTagged data BTCConf = BTCConf data SettleHrs = SettleHrs data Charge = Charge data Dust = Dust data ChanDur = ChanDur data Callback = Callback type BtcConf = Tag.Tagged BTCConf Word type SettleHours = Tag.Tagged SettleHrs Word type OpenPrice = Tag.Tagged Charge BtcAmount type DustLimit = Tag.Tagged Dust BtcAmount type DurationHours= Tag.Tagged ChanDur Word data ChanConf = ChanConf { btcMinConf :: BtcConf , openPrice :: OpenPrice , dustLimit :: DustLimit , settlePeriod' :: SettleHours , minDuration :: DurationHours } toBtcConf : : ChanConf - > BTCConf . Config { .. } = BTCConf . Config -- { cDustLimit = BTC.getDustLimit -- , cSettlementPeriod = Tag.Tagged . fromIntegral $ Tag.unTagged settlePeriod' -- } data App = App { _callbackIface :: Callback.Interface , _listUnspent :: HC.Address -> IO (Either String [BtcType.TxInfo]) , _settleChannel :: ServerPayChanX -> IO HT.TxHash -- Dummy function if debug is enabled , _chanConf :: ChanConf , _settlePeriod :: Word , _basePath :: BS.ByteString , _areWeDebugging :: Bool } -- Template Haskell magic makeLenses ''App data BitcoinNet = Mainnet | Testnet3 data DBConf = DBConf Host Word Int data ServerDBConf = ServerDBConf String Word type Host = BS.ByteString getWord r = if denominator r /= 1 then Nothing else Just $ numerator r instance Configured BitcoinNet where convert (String "live") = return Mainnet convert (String "test") = return Testnet3 convert _ = Nothing instance Configured HC.Address where convert (String text) = HC.base58ToAddr . cs $ text convert _ = Nothing instance Configured BtcAmount where convert (Number r) = fmap fromIntegral (getWord r) convert _ = Nothing Decode private key as 64 hex chars instance Configured HC.PrvKey where convert (String text) = either (const Nothing) (fmap HC.makePrvKey . Secp.secKey) (hexDecode (cs text :: BS.ByteString)) convert _ = Nothing instance Configured BtcConf where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured SettleHours where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured DustLimit where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured OpenPrice where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured DurationHours where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing data ServerSettleConfig = ServerSettleConfig { confSettleTxFee :: BtcAmount, confSettlePeriod :: SettleHours }
null
https://raw.githubusercontent.com/runeksvendsen/restful-payment-channel-server/0fe65eadccad5ef2b840714623ec407e509ad00b/src/PayChanServer/Config/Types.hs
haskell
import Servant.Server.Internal.Context (Context(EmptyContext, (:.))) - Tagged types { cDustLimit = BTC.getDustLimit , cSettlementPeriod = Tag.Tagged . fromIntegral $ Tag.unTagged settlePeriod' } Dummy function if debug is enabled Template Haskell magic
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # # LANGUAGE OverloadedStrings , DataKinds , FlexibleContexts , LambdaCase , TypeOperators # module PayChanServer.Config.Types ( module PayChanServer.Config.Types , Config ) where import AppPrelude.Types.Orphans () import AppPrelude.Util import qualified . Interface as Store import qualified PayChanServer.Callback.Interface as Callback import PaymentChannel.Types (ServerPayChanX, BtcAmount) import qualified PaymentChannel as BTC import qualified Network.Haskoin.Transaction as HT import qualified Network.Haskoin.Crypto as HC import qualified Crypto.Secp256k1 as Secp import Control.Lens.TH (makeLenses) import qualified Data.ByteString as BS import Data.Configurator.Types (Config, Configured, convert, Value(..)) import Data.Ratio import qualified BlockchainAPI.Types as BtcType import qualified Data.Tagged as Tag getVal = Tag.unTagged data BTCConf = BTCConf data SettleHrs = SettleHrs data Charge = Charge data Dust = Dust data ChanDur = ChanDur data Callback = Callback type BtcConf = Tag.Tagged BTCConf Word type SettleHours = Tag.Tagged SettleHrs Word type OpenPrice = Tag.Tagged Charge BtcAmount type DustLimit = Tag.Tagged Dust BtcAmount type DurationHours= Tag.Tagged ChanDur Word data ChanConf = ChanConf { btcMinConf :: BtcConf , openPrice :: OpenPrice , dustLimit :: DustLimit , settlePeriod' :: SettleHours , minDuration :: DurationHours } toBtcConf : : ChanConf - > BTCConf . Config { .. } = BTCConf . Config data App = App { _callbackIface :: Callback.Interface , _listUnspent :: HC.Address -> IO (Either String [BtcType.TxInfo]) , _chanConf :: ChanConf , _settlePeriod :: Word , _basePath :: BS.ByteString , _areWeDebugging :: Bool } makeLenses ''App data BitcoinNet = Mainnet | Testnet3 data DBConf = DBConf Host Word Int data ServerDBConf = ServerDBConf String Word type Host = BS.ByteString getWord r = if denominator r /= 1 then Nothing else Just $ numerator r instance Configured BitcoinNet where convert (String "live") = return Mainnet convert (String "test") = return Testnet3 convert _ = Nothing instance Configured HC.Address where convert (String text) = HC.base58ToAddr . cs $ text convert _ = Nothing instance Configured BtcAmount where convert (Number r) = fmap fromIntegral (getWord r) convert _ = Nothing Decode private key as 64 hex chars instance Configured HC.PrvKey where convert (String text) = either (const Nothing) (fmap HC.makePrvKey . Secp.secKey) (hexDecode (cs text :: BS.ByteString)) convert _ = Nothing instance Configured BtcConf where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured SettleHours where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured DustLimit where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured OpenPrice where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing instance Configured DurationHours where convert (Number r) = fmap (Tag.Tagged . fromIntegral) (getWord r) convert _ = Nothing data ServerSettleConfig = ServerSettleConfig { confSettleTxFee :: BtcAmount, confSettlePeriod :: SettleHours }
54cf4ec43c919f955492551b6affc1ca265dd983a92ef8d84ecbc60c8d881a23
Metaxal/quickscript-extra
url2script.rkt
#lang racket/base License : [ Apache License , Version 2.0]( / licenses / LICENSE-2.0 ) or [ MIT license]( / licenses / MIT ) at your option . (require quickscript quickscript/base quickscript/utils racket/class racket/file racket/match racket/port racket/path racket/string racket/gui/base net/url browser/external) (script-help-string "Fetches a quickscript at a given url and adds it to the library.") (define dir user-script-dir) (define url2script-submod-name 'url2script-info) (define (parse-url str) ; Do not keep trailing anchors (set! str (regexp-replace #px"[#?].*" str "")) (match str ; We can extract the filename ; "" [(regexp #px"^\\.github(?:usercontent|)\\.com/[^/]+/[0-9a-f]+/raw/[0-9a-f]+/([^/]+)$" (list _ filename)) (values str filename)] ; "" ; "" [(or (regexp #px"^\\.github(?:usercontent|).com/[^/]+/[0-9a-f]+/raw$") (regexp #px"^\\.com/snippets/[0-9]+/raw$") (regexp #px"^\\.org/pastes/[0-9]+/raw$") (regexp #px"^/[0-9a-zA-Z]+$")) (values str #f)] ; "" ; "" ; "" [(or (regexp #px"^\\.github(?:usercontent|)\\.com/[^/]+/[0-9a-f]+$") (regexp #px"^\\.com/snippets/[0-9]+$") (regexp #px"^\\.org/pastes/[0-9]+$")) (values (string-append str "/raw") #f)] ; "" [(regexp #px"^/([0-9a-zA-Z]+)$" (list _ name)) (values (string-append "/" name) #f)] ; Any other kind of url, we assume a link to a raw file [else (values str #f)])) TODO : check it is indeed a ( valid ? ) ;; TODO: get-pure-port also handles files. This could be useful. ;; To prevent CDN caching, add "?cachebust=<some-random-number>" at the end of the url ;; (or "&cachebust=..."), just to make sure the url is different. (define (get-text-at-url aurl) (port->string (get-pure-port (string->url aurl) #:redirections 10) #:close? #t)) ;; Notice: Does not ask to replace (should be done prior). ;; Doesn't add a submodule if one already exists. ;; Allows the designer to give the default file name to save the script. (define (write-script fout text aurl #:filename [filename (file-name-from-path fout)]) (display-to-file text fout #:exists 'replace) (unless (has-submod? fout) (display-to-file #:exists 'append (string-append "\n" "(module " (symbol->string url2script-submod-name) " racket/base\n" " (provide filename url)\n" " (define filename " (format "~s" (and filename (path->string filename))) ")\n" " (define url " (format "~s" aurl) "))\n") fout))) Do n't allow file or network access in the url2script submodule , ;; in particular because this module is `require`d right after downloading, ;; before the user has a chance to look at the file. ;; This prevents write and execute access, including calls to `system` and ;; `process` and friends. (define dynreq-security-guard (make-security-guard (current-security-guard) (λ (sym pth access) (unless (or (equal? access '(exists)) (equal? access '(read))) (error (format "File access disabled ~a" (list sym pth access))))) (λ _ (error "Network access disabled")))) Get information from the url2script submodule . (define (get-submod f sym [fail-thunk (λ () #f)]) (parameterize ([current-security-guard dynreq-security-guard] [current-namespace (make-base-empty-namespace)] [current-environment-variables ; prevent writing to (actual) environment variables (environment-variables-copy (current-environment-variables))]) (dynamic-require `(submod (file ,(path->string f)) ,url2script-submod-name) sym fail-thunk))) Does the file contain a url2script submodule ? (define (has-submod? f) (with-handlers ([(λ (e) (and (exn:fail? e) (string-prefix? (exn-message e) "instantiate: unknown module"))) (λ (e) #f)]) (get-submod f (void)) #t)) ;====================; ;=== Quickscripts ===; ;====================; (define-script url2script #:label "Fetch script…" #:help-string "Asks for a URL and fetches the script" #:menu-path ("url2script") (λ (selection #:frame frame) (define str (get-text-from-user "url2script" (string-append "IMPORTANT:\nMake sure you trust the script before clicking on OK, " "It may run automatically.\n\n" "Enter a URL to gist, gitlab snippet or pasterack, or to a raw racket file:"))) (when str ; At a special commit, with the name at the end, which we could extract. (define-values (aurl maybe-filename) (parse-url str)) (define text (get-text-at-url aurl)) (define ftmp (make-temporary-file)) Write a first time to maybe - write and read the submod infos (write-script ftmp text aurl #:filename maybe-filename) (define filename (get-submod ftmp 'filename)) ; Ask the user for a filename and directory. Notice : If the directory is not in the Library 's paths , may not find the script . TODO : Check that it 's in the Library 's path and display a warning if not ? (define fout (put-file "url2script: Save script as…" frame dir (or filename ".rkt") ".rkt" '() '(("Racket source" "*.rkt") ("Any" "*.*")))) (when fout (write-script fout text str) (smart-open-file frame fout)) #f))) (define-script update-script #:label "Update current script" #:help-string "Updates a script that was downloaded with url2script" #:menu-path ("url2script") (λ (selection #:file f #:frame drfr) (when f (define submod-url (get-submod f 'url)) (cond [submod-url (define-values (aurl _name) (parse-url submod-url)) (define text (get-text-at-url aurl)) (define res (message-box "Attention" "This will rewrite the current file. Continue?" #f '(ok-cancel caution))) (when (eq? res 'ok) (write-script f text aurl) (when drfr (send drfr revert)))] [else (message-box "Error" "Unable to find original url. Script may not have been downloaded with url2script." #f '(ok stop))])) #f)) (define-script visit-script-at-url #:label "Visit published script (browser)" #:menu-path ("url2script") (λ (selection #:file f) (when f (define submod-url (get-submod f 'url)) (cond [submod-url (send-url submod-url)] [else (message-box "Error" "Unable to find original url. Script may not have been downloaded with url2script." #f '(ok stop))])))) (define-script more-scripts #:label "Get more scripts (browser)" #:menu-path ("url2script") #:help-string "Opens the Racket wiki page for DrRacket Quickscript scripts." (λ (str) (send-url "-Scripts-for-DrRacket") #f)) ;=============; ;=== Tests ===; ;=============; (module+ test (require rackunit) (let () (define f (make-temporary-file)) (define aurl "") (write-script f "#lang racket/base\n" aurl) (check-equal? (has-submod? f) #t) (check-equal? (get-submod f 'url) aurl) (write-to-file '(module mymod racket/base (displayln "yop")) f #:exists 'replace) (check-equal? (has-submod? f) #f) ; syntax error (check-exn exn:fail? (λ () (write-script f "#lang racket/base\nraise-me-well!\n" aurl))) ) (define (test-parse-url url) (call-with-values (λ () (parse-url url)) list)) (check-equal? (test-parse-url "") '("" #f)) (check-equal? (test-parse-url "") '("" #f)) (check-equal? (test-parse-url "") (list "" "letterfall.rkt")) (check-equal? (test-parse-url "#file-upcase-rkt") ; Filename is a little annoying to parse (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) ;; TODO: Check that updating a script where the source does not have a url2script-info ;; submodule produces a script that still has the submodule )
null
https://raw.githubusercontent.com/Metaxal/quickscript-extra/d07e75debd5952fce4cbdec3761d02a0a7baa281/scripts/url2script.rkt
racket
Do not keep trailing anchors We can extract the filename "" "" "" "" "" "" "" Any other kind of url, we assume a link to a raw file TODO: get-pure-port also handles files. This could be useful. To prevent CDN caching, add "?cachebust=<some-random-number>" at the end of the url (or "&cachebust=..."), just to make sure the url is different. Notice: Does not ask to replace (should be done prior). Doesn't add a submodule if one already exists. Allows the designer to give the default file name to save the script. in particular because this module is `require`d right after downloading, before the user has a chance to look at the file. This prevents write and execute access, including calls to `system` and `process` and friends. prevent writing to (actual) environment variables ====================; === Quickscripts ===; ====================; At a special commit, with the name at the end, which we could extract. Ask the user for a filename and directory. =============; === Tests ===; =============; syntax error Filename is a little annoying to parse TODO: Check that updating a script where the source does not have a url2script-info submodule produces a script that still has the submodule
#lang racket/base License : [ Apache License , Version 2.0]( / licenses / LICENSE-2.0 ) or [ MIT license]( / licenses / MIT ) at your option . (require quickscript quickscript/base quickscript/utils racket/class racket/file racket/match racket/port racket/path racket/string racket/gui/base net/url browser/external) (script-help-string "Fetches a quickscript at a given url and adds it to the library.") (define dir user-script-dir) (define url2script-submod-name 'url2script-info) (define (parse-url str) (set! str (regexp-replace #px"[#?].*" str "")) (match str [(regexp #px"^\\.github(?:usercontent|)\\.com/[^/]+/[0-9a-f]+/raw/[0-9a-f]+/([^/]+)$" (list _ filename)) (values str filename)] [(or (regexp #px"^\\.github(?:usercontent|).com/[^/]+/[0-9a-f]+/raw$") (regexp #px"^\\.com/snippets/[0-9]+/raw$") (regexp #px"^\\.org/pastes/[0-9]+/raw$") (regexp #px"^/[0-9a-zA-Z]+$")) (values str #f)] [(or (regexp #px"^\\.github(?:usercontent|)\\.com/[^/]+/[0-9a-f]+$") (regexp #px"^\\.com/snippets/[0-9]+$") (regexp #px"^\\.org/pastes/[0-9]+$")) (values (string-append str "/raw") #f)] [(regexp #px"^/([0-9a-zA-Z]+)$" (list _ name)) (values (string-append "/" name) #f)] [else (values str #f)])) TODO : check it is indeed a ( valid ? ) (define (get-text-at-url aurl) (port->string (get-pure-port (string->url aurl) #:redirections 10) #:close? #t)) (define (write-script fout text aurl #:filename [filename (file-name-from-path fout)]) (display-to-file text fout #:exists 'replace) (unless (has-submod? fout) (display-to-file #:exists 'append (string-append "\n" "(module " (symbol->string url2script-submod-name) " racket/base\n" " (provide filename url)\n" " (define filename " (format "~s" (and filename (path->string filename))) ")\n" " (define url " (format "~s" aurl) "))\n") fout))) Do n't allow file or network access in the url2script submodule , (define dynreq-security-guard (make-security-guard (current-security-guard) (λ (sym pth access) (unless (or (equal? access '(exists)) (equal? access '(read))) (error (format "File access disabled ~a" (list sym pth access))))) (λ _ (error "Network access disabled")))) Get information from the url2script submodule . (define (get-submod f sym [fail-thunk (λ () #f)]) (parameterize ([current-security-guard dynreq-security-guard] [current-namespace (make-base-empty-namespace)] [current-environment-variables (environment-variables-copy (current-environment-variables))]) (dynamic-require `(submod (file ,(path->string f)) ,url2script-submod-name) sym fail-thunk))) Does the file contain a url2script submodule ? (define (has-submod? f) (with-handlers ([(λ (e) (and (exn:fail? e) (string-prefix? (exn-message e) "instantiate: unknown module"))) (λ (e) #f)]) (get-submod f (void)) #t)) (define-script url2script #:label "Fetch script…" #:help-string "Asks for a URL and fetches the script" #:menu-path ("url2script") (λ (selection #:frame frame) (define str (get-text-from-user "url2script" (string-append "IMPORTANT:\nMake sure you trust the script before clicking on OK, " "It may run automatically.\n\n" "Enter a URL to gist, gitlab snippet or pasterack, or to a raw racket file:"))) (when str (define-values (aurl maybe-filename) (parse-url str)) (define text (get-text-at-url aurl)) (define ftmp (make-temporary-file)) Write a first time to maybe - write and read the submod infos (write-script ftmp text aurl #:filename maybe-filename) (define filename (get-submod ftmp 'filename)) Notice : If the directory is not in the Library 's paths , may not find the script . TODO : Check that it 's in the Library 's path and display a warning if not ? (define fout (put-file "url2script: Save script as…" frame dir (or filename ".rkt") ".rkt" '() '(("Racket source" "*.rkt") ("Any" "*.*")))) (when fout (write-script fout text str) (smart-open-file frame fout)) #f))) (define-script update-script #:label "Update current script" #:help-string "Updates a script that was downloaded with url2script" #:menu-path ("url2script") (λ (selection #:file f #:frame drfr) (when f (define submod-url (get-submod f 'url)) (cond [submod-url (define-values (aurl _name) (parse-url submod-url)) (define text (get-text-at-url aurl)) (define res (message-box "Attention" "This will rewrite the current file. Continue?" #f '(ok-cancel caution))) (when (eq? res 'ok) (write-script f text aurl) (when drfr (send drfr revert)))] [else (message-box "Error" "Unable to find original url. Script may not have been downloaded with url2script." #f '(ok stop))])) #f)) (define-script visit-script-at-url #:label "Visit published script (browser)" #:menu-path ("url2script") (λ (selection #:file f) (when f (define submod-url (get-submod f 'url)) (cond [submod-url (send-url submod-url)] [else (message-box "Error" "Unable to find original url. Script may not have been downloaded with url2script." #f '(ok stop))])))) (define-script more-scripts #:label "Get more scripts (browser)" #:menu-path ("url2script") #:help-string "Opens the Racket wiki page for DrRacket Quickscript scripts." (λ (str) (send-url "-Scripts-for-DrRacket") #f)) (module+ test (require rackunit) (let () (define f (make-temporary-file)) (define aurl "") (write-script f "#lang racket/base\n" aurl) (check-equal? (has-submod? f) #t) (check-equal? (get-submod f 'url) aurl) (write-to-file '(module mymod racket/base (displayln "yop")) f #:exists 'replace) (check-equal? (has-submod? f) #f) (check-exn exn:fail? (λ () (write-script f "#lang racket/base\nraise-me-well!\n" aurl))) ) (define (test-parse-url url) (call-with-values (λ () (parse-url url)) list)) (check-equal? (test-parse-url "") '("" #f)) (check-equal? (test-parse-url "") '("" #f)) (check-equal? (test-parse-url "") (list "" "letterfall.rkt")) (check-equal? (test-parse-url "#file-upcase-rkt") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) (check-equal? (test-parse-url "") (list "" #f)) )
5969118be270e6ecdf77354c681c4e10a9721bade788fe8cf78fb2625c78c758
clash-lang/clash-compiler
T1033.hs
module T1033 where import Clash.Explicit.Prelude import Clash.Prelude (HiddenClock, hasClock) import qualified Prelude as P # ANN topEntity ( Synthesize { t_name = " top " , t_inputs = [ PortName " wrong " ] , t_output = PortName " theOutput " } ) # (Synthesize { t_name = "top" , t_inputs = [ PortName "wrong"] , t_output = PortName "theOutput" } )#-} topEntity :: (Clock System, Reset System, Enable System) -> Signal System Int -> Signal System Int topEntity (clk, rst, en) i = register clk rst en 0 i
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldfail/TopEntity/T1033.hs
haskell
module T1033 where import Clash.Explicit.Prelude import Clash.Prelude (HiddenClock, hasClock) import qualified Prelude as P # ANN topEntity ( Synthesize { t_name = " top " , t_inputs = [ PortName " wrong " ] , t_output = PortName " theOutput " } ) # (Synthesize { t_name = "top" , t_inputs = [ PortName "wrong"] , t_output = PortName "theOutput" } )#-} topEntity :: (Clock System, Reset System, Enable System) -> Signal System Int -> Signal System Int topEntity (clk, rst, en) i = register clk rst en 0 i
4ebb0d6beaabe20b40d1b6e948e192437fcf940bf253b5a312271061f83fe9e7
mzp/coq-ruby
cctac.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) $ I d : cctac.mli 10637 2008 - 03 - 07 23:52:56Z letouzey $ open Term open Proof_type val proof_tac: Ccproof.proof -> Proof_type.tactic val cc_tactic : int -> constr list -> tactic val cc_fail : tactic val congruence_tac : int -> constr list -> tactic val f_equal : tactic
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/contrib/cc/cctac.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 **********************************************************************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * $ I d : cctac.mli 10637 2008 - 03 - 07 23:52:56Z letouzey $ open Term open Proof_type val proof_tac: Ccproof.proof -> Proof_type.tactic val cc_tactic : int -> constr list -> tactic val cc_fail : tactic val congruence_tac : int -> constr list -> tactic val f_equal : tactic
ec995a2987f770c36146231a911ecbac6d0301e891a7770c53cad4e7cef32591
brendanhay/terrafomo
DataSources.hs
-- This module is auto-generated. # LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - unused - imports # -- | Module : . PagerDuty . DataSources Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.PagerDuty.DataSources ( -- * pagerduty_escalation_policy newEscalationPolicyD , EscalationPolicyD (..) -- * pagerduty_extension_schema , newExtensionSchemaD , ExtensionSchemaD (..) -- * pagerduty_schedule , newScheduleD , ScheduleD (..) -- * pagerduty_team , newTeamD , TeamD (..) -- * pagerduty_user , newUserD , UserD (..) -- * pagerduty_vendor , newVendorD , VendorD (..) ) where import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import GHC.Base (Proxy#, proxy#, ($)) import Terrafomo.PagerDuty.Settings import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.Encode as Encode import qualified Terrafomo.HCL as TF import qualified Terrafomo.HIL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.PagerDuty.Provider as P import qualified Terrafomo.PagerDuty.Types as P import qualified Terrafomo.Schema as TF | The main @pagerduty_escalation_policy@ datasource definition . newtype EscalationPolicyD s = EscalationPolicyD { name :: TF.Expr s P.Text -- ^ @name@ -- - (Required) } deriving (P.Show) | Construct a new @pagerduty_escalation_policy@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_escalation_policy@ via : @ PagerDuty.newEscalationPolicyD ( PagerDuty . EscalationPolicyD { PagerDuty.name = name -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource EscalationPolicyD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref EscalationPolicyD s ) ( s I d ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource EscalationPolicyD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource EscalationPolicyD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_escalation_policy@ via: @ PagerDuty.newEscalationPolicyD (PagerDuty.EscalationPolicyD { PagerDuty.name = name -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource EscalationPolicyD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref EscalationPolicyD s) (Expr s Id) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource EscalationPolicyD s) (Set (Depends s)) #provider :: Lens' (DataSource EscalationPolicyD s) (Maybe PagerDuty) @ -} newEscalationPolicyD :: EscalationPolicyD s -- ^ The minimal/required arguments. -> P.DataSource EscalationPolicyD s newEscalationPolicyD = TF.unsafeDataSource "pagerduty_escalation_policy" (\EscalationPolicyD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource EscalationPolicyD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: EscalationPolicyD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: EscalationPolicyD s) instance Lens.HasField "id" (P.Const r) (TF.Ref EscalationPolicyD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) | The main @pagerduty_extension_schema@ datasource definition . newtype ExtensionSchemaD s = ExtensionSchemaD { name :: TF.Expr s P.Text -- ^ @name@ -- - (Required) } deriving (P.Show) | Construct a new @pagerduty_extension_schema@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_extension_schema@ via : @ PagerDuty.newExtensionSchemaD ( PagerDuty . ExtensionSchemaD { PagerDuty.name = name -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource ExtensionSchemaD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref ExtensionSchemaD s ) ( s I d ) # type : : Getting r ( Ref ExtensionSchemaD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource ExtensionSchemaD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource ExtensionSchemaD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_extension_schema@ via: @ PagerDuty.newExtensionSchemaD (PagerDuty.ExtensionSchemaD { PagerDuty.name = name -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource ExtensionSchemaD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref ExtensionSchemaD s) (Expr s Id) #type :: Getting r (Ref ExtensionSchemaD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource ExtensionSchemaD s) (Set (Depends s)) #provider :: Lens' (DataSource ExtensionSchemaD s) (Maybe PagerDuty) @ -} newExtensionSchemaD :: ExtensionSchemaD s -- ^ The minimal/required arguments. -> P.DataSource ExtensionSchemaD s newExtensionSchemaD = TF.unsafeDataSource "pagerduty_extension_schema" (\ExtensionSchemaD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource ExtensionSchemaD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: ExtensionSchemaD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: ExtensionSchemaD s) instance Lens.HasField "id" (P.Const r) (TF.Ref ExtensionSchemaD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "type" (P.Const r) (TF.Ref ExtensionSchemaD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "type")) -- | The main @pagerduty_schedule@ datasource definition. newtype ScheduleD s = ScheduleD { name :: TF.Expr s P.Text -- ^ @name@ -- - (Required) } deriving (P.Show) | Construct a new @pagerduty_schedule@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_schedule@ via : @ PagerDuty.newScheduleD ( PagerDuty . ScheduleD { PagerDuty.name = name -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource ScheduleD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref ScheduleD s ) ( s I d ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource ScheduleD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource ScheduleD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_schedule@ via: @ PagerDuty.newScheduleD (PagerDuty.ScheduleD { PagerDuty.name = name -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource ScheduleD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref ScheduleD s) (Expr s Id) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource ScheduleD s) (Set (Depends s)) #provider :: Lens' (DataSource ScheduleD s) (Maybe PagerDuty) @ -} newScheduleD :: ScheduleD s -- ^ The minimal/required arguments. -> P.DataSource ScheduleD s newScheduleD = TF.unsafeDataSource "pagerduty_schedule" (\ScheduleD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource ScheduleD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: ScheduleD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: ScheduleD s) instance Lens.HasField "id" (P.Const r) (TF.Ref ScheduleD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) -- | The main @pagerduty_team@ datasource definition. newtype TeamD s = TeamD { name :: TF.Expr s P.Text -- ^ @name@ -- - (Required) -- The name of the team to find in the PagerDuty API } deriving (P.Show) | Construct a new @pagerduty_team@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_team@ via : @ PagerDuty.newTeamD ( PagerDuty . TeamD { PagerDuty.name = name -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource TeamD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref TeamD s ) ( s I d ) # description : : Getting r ( Ref TeamD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource TeamD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource TeamD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_team@ via: @ PagerDuty.newTeamD (PagerDuty.TeamD { PagerDuty.name = name -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource TeamD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref TeamD s) (Expr s Id) #description :: Getting r (Ref TeamD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource TeamD s) (Set (Depends s)) #provider :: Lens' (DataSource TeamD s) (Maybe PagerDuty) @ -} newTeamD :: TeamD s -- ^ The minimal/required arguments. -> P.DataSource TeamD s newTeamD = TF.unsafeDataSource "pagerduty_team" (\TeamD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource TeamD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: TeamD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: TeamD s) instance Lens.HasField "id" (P.Const r) (TF.Ref TeamD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "description" (P.Const r) (TF.Ref TeamD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "description")) -- | The main @pagerduty_user@ datasource definition. newtype UserD s = UserD { email :: TF.Expr s P.Text -- ^ @email@ -- - (Required) } deriving (P.Show) | Construct a new @pagerduty_user@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_user@ via : @ PagerDuty.newUserD ( PagerDuty . UserD { PagerDuty.email = email -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # email : : Lens ' ( DataSource UserD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref UserD s ) ( s I d ) # name : : Getting r ( Ref UserD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource UserD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource UserD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_user@ via: @ PagerDuty.newUserD (PagerDuty.UserD { PagerDuty.email = email -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #email :: Lens' (DataSource UserD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref UserD s) (Expr s Id) #name :: Getting r (Ref UserD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource UserD s) (Set (Depends s)) #provider :: Lens' (DataSource UserD s) (Maybe PagerDuty) @ -} newUserD :: UserD s -- ^ The minimal/required arguments. -> P.DataSource UserD s newUserD = TF.unsafeDataSource "pagerduty_user" (\UserD{..} -> P.mempty <> TF.pair "email" email ) instance Lens.HasField "email" f (P.Resource UserD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (email :: UserD s -> TF.Expr s P.Text) (\s a -> s { email = a } :: UserD s) instance Lens.HasField "id" (P.Const r) (TF.Ref UserD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "name" (P.Const r) (TF.Ref UserD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "name")) -- | The main @pagerduty_vendor@ datasource definition. newtype VendorD s = VendorD { name :: TF.Expr s P.Text -- ^ @name@ -- - (Required) } deriving (P.Show) | Construct a new @pagerduty_vendor@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_vendor@ via : @ PagerDuty.newVendorD ( PagerDuty . VendorD { PagerDuty.name = name -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource VendorD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref VendorD s ) ( s I d ) # type : : Getting r ( Ref VendorD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource VendorD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource VendorD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_vendor@ via: @ PagerDuty.newVendorD (PagerDuty.VendorD { PagerDuty.name = name -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource VendorD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref VendorD s) (Expr s Id) #type :: Getting r (Ref VendorD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource VendorD s) (Set (Depends s)) #provider :: Lens' (DataSource VendorD s) (Maybe PagerDuty) @ -} newVendorD :: VendorD s -- ^ The minimal/required arguments. -> P.DataSource VendorD s newVendorD = TF.unsafeDataSource "pagerduty_vendor" (\VendorD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource VendorD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: VendorD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: VendorD s) instance Lens.HasField "id" (P.Const r) (TF.Ref VendorD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "type" (P.Const r) (TF.Ref VendorD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "type"))
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-pagerduty/gen/Terrafomo/PagerDuty/DataSources.hs
haskell
This module is auto-generated. | Stability : auto-generated * pagerduty_escalation_policy * pagerduty_extension_schema * pagerduty_schedule * pagerduty_team * pagerduty_user * pagerduty_vendor ^ @name@ - (Required) s Text Expr s Text ^ The minimal/required arguments. ^ @name@ - (Required) s Text Expr s Text ^ The minimal/required arguments. | The main @pagerduty_schedule@ datasource definition. ^ @name@ - (Required) s Text Expr s Text ^ The minimal/required arguments. | The main @pagerduty_team@ datasource definition. ^ @name@ - (Required) The name of the team to find in the PagerDuty API s Text Expr s Text ^ The minimal/required arguments. | The main @pagerduty_user@ datasource definition. ^ @email@ - (Required) s Text Expr s Text ^ The minimal/required arguments. | The main @pagerduty_vendor@ datasource definition. ^ @name@ - (Required) s Text Expr s Text ^ The minimal/required arguments.
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - unused - imports # Module : . PagerDuty . DataSources Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.PagerDuty.DataSources ( newEscalationPolicyD , EscalationPolicyD (..) , newExtensionSchemaD , ExtensionSchemaD (..) , newScheduleD , ScheduleD (..) , newTeamD , TeamD (..) , newUserD , UserD (..) , newVendorD , VendorD (..) ) where import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import GHC.Base (Proxy#, proxy#, ($)) import Terrafomo.PagerDuty.Settings import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.Encode as Encode import qualified Terrafomo.HCL as TF import qualified Terrafomo.HIL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.PagerDuty.Provider as P import qualified Terrafomo.PagerDuty.Types as P import qualified Terrafomo.Schema as TF | The main @pagerduty_escalation_policy@ datasource definition . newtype EscalationPolicyD s = EscalationPolicyD { name :: TF.Expr s P.Text } deriving (P.Show) | Construct a new @pagerduty_escalation_policy@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_escalation_policy@ via : @ PagerDuty.newEscalationPolicyD ( PagerDuty . EscalationPolicyD } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource EscalationPolicyD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref EscalationPolicyD s ) ( s I d ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource EscalationPolicyD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource EscalationPolicyD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_escalation_policy@ via: @ PagerDuty.newEscalationPolicyD (PagerDuty.EscalationPolicyD }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource EscalationPolicyD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref EscalationPolicyD s) (Expr s Id) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource EscalationPolicyD s) (Set (Depends s)) #provider :: Lens' (DataSource EscalationPolicyD s) (Maybe PagerDuty) @ -} newEscalationPolicyD -> P.DataSource EscalationPolicyD s newEscalationPolicyD = TF.unsafeDataSource "pagerduty_escalation_policy" (\EscalationPolicyD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource EscalationPolicyD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: EscalationPolicyD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: EscalationPolicyD s) instance Lens.HasField "id" (P.Const r) (TF.Ref EscalationPolicyD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) | The main @pagerduty_extension_schema@ datasource definition . newtype ExtensionSchemaD s = ExtensionSchemaD { name :: TF.Expr s P.Text } deriving (P.Show) | Construct a new @pagerduty_extension_schema@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_extension_schema@ via : @ PagerDuty.newExtensionSchemaD ( PagerDuty . ExtensionSchemaD } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource ExtensionSchemaD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref ExtensionSchemaD s ) ( s I d ) # type : : Getting r ( Ref ExtensionSchemaD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource ExtensionSchemaD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource ExtensionSchemaD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_extension_schema@ via: @ PagerDuty.newExtensionSchemaD (PagerDuty.ExtensionSchemaD }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource ExtensionSchemaD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref ExtensionSchemaD s) (Expr s Id) #type :: Getting r (Ref ExtensionSchemaD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource ExtensionSchemaD s) (Set (Depends s)) #provider :: Lens' (DataSource ExtensionSchemaD s) (Maybe PagerDuty) @ -} newExtensionSchemaD -> P.DataSource ExtensionSchemaD s newExtensionSchemaD = TF.unsafeDataSource "pagerduty_extension_schema" (\ExtensionSchemaD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource ExtensionSchemaD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: ExtensionSchemaD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: ExtensionSchemaD s) instance Lens.HasField "id" (P.Const r) (TF.Ref ExtensionSchemaD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "type" (P.Const r) (TF.Ref ExtensionSchemaD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "type")) newtype ScheduleD s = ScheduleD { name :: TF.Expr s P.Text } deriving (P.Show) | Construct a new @pagerduty_schedule@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_schedule@ via : @ PagerDuty.newScheduleD ( PagerDuty . ScheduleD } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource ScheduleD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref ScheduleD s ) ( s I d ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource ScheduleD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource ScheduleD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_schedule@ via: @ PagerDuty.newScheduleD (PagerDuty.ScheduleD }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource ScheduleD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref ScheduleD s) (Expr s Id) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource ScheduleD s) (Set (Depends s)) #provider :: Lens' (DataSource ScheduleD s) (Maybe PagerDuty) @ -} newScheduleD -> P.DataSource ScheduleD s newScheduleD = TF.unsafeDataSource "pagerduty_schedule" (\ScheduleD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource ScheduleD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: ScheduleD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: ScheduleD s) instance Lens.HasField "id" (P.Const r) (TF.Ref ScheduleD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) newtype TeamD s = TeamD { name :: TF.Expr s P.Text } deriving (P.Show) | Construct a new @pagerduty_team@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_team@ via : @ PagerDuty.newTeamD ( PagerDuty . TeamD } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource TeamD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref TeamD s ) ( s I d ) # description : : Getting r ( Ref TeamD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource TeamD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource TeamD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_team@ via: @ PagerDuty.newTeamD (PagerDuty.TeamD }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource TeamD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref TeamD s) (Expr s Id) #description :: Getting r (Ref TeamD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource TeamD s) (Set (Depends s)) #provider :: Lens' (DataSource TeamD s) (Maybe PagerDuty) @ -} newTeamD -> P.DataSource TeamD s newTeamD = TF.unsafeDataSource "pagerduty_team" (\TeamD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource TeamD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: TeamD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: TeamD s) instance Lens.HasField "id" (P.Const r) (TF.Ref TeamD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "description" (P.Const r) (TF.Ref TeamD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "description")) newtype UserD s = UserD { email :: TF.Expr s P.Text } deriving (P.Show) | Construct a new @pagerduty_user@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_user@ via : @ PagerDuty.newUserD ( PagerDuty . UserD } ) @ = = = Argument Reference The following arguments are supported : @ # email : : Lens ' ( DataSource UserD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref UserD s ) ( s I d ) # name : : Getting r ( Ref UserD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource UserD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource UserD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_user@ via: @ PagerDuty.newUserD (PagerDuty.UserD }) @ === Argument Reference The following arguments are supported: @ #email :: Lens' (DataSource UserD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref UserD s) (Expr s Id) #name :: Getting r (Ref UserD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource UserD s) (Set (Depends s)) #provider :: Lens' (DataSource UserD s) (Maybe PagerDuty) @ -} newUserD -> P.DataSource UserD s newUserD = TF.unsafeDataSource "pagerduty_user" (\UserD{..} -> P.mempty <> TF.pair "email" email ) instance Lens.HasField "email" f (P.Resource UserD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (email :: UserD s -> TF.Expr s P.Text) (\s a -> s { email = a } :: UserD s) instance Lens.HasField "id" (P.Const r) (TF.Ref UserD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "name" (P.Const r) (TF.Ref UserD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "name")) newtype VendorD s = VendorD { name :: TF.Expr s P.Text } deriving (P.Show) | Construct a new @pagerduty_vendor@ datasource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @pagerduty_vendor@ via : @ PagerDuty.newVendorD ( PagerDuty . VendorD } ) @ = = = Argument Reference The following arguments are supported : @ # name : : ' ( DataSource VendorD s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref VendorD s ) ( s I d ) # type : : Getting r ( Ref VendorD s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # depends_on : : ' ( DataSource VendorD s ) ( Set ( Depends s ) ) # provider : : ' ( DataSource VendorD s ) ( Maybe PagerDuty ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @pagerduty_vendor@ via: @ PagerDuty.newVendorD (PagerDuty.VendorD }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (DataSource VendorD s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref VendorD s) (Expr s Id) #type :: Getting r (Ref VendorD s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #depends_on :: Lens' (DataSource VendorD s) (Set (Depends s)) #provider :: Lens' (DataSource VendorD s) (Maybe PagerDuty) @ -} newVendorD -> P.DataSource VendorD s newVendorD = TF.unsafeDataSource "pagerduty_vendor" (\VendorD{..} -> P.mempty <> TF.pair "name" name ) instance Lens.HasField "name" f (P.Resource VendorD s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: VendorD s -> TF.Expr s P.Text) (\s a -> s { name = a } :: VendorD s) instance Lens.HasField "id" (P.Const r) (TF.Ref VendorD s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "type" (P.Const r) (TF.Ref VendorD s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "type"))
92ac734d1a2869e59a3aef0bbfd55536f953bbcfb0b6f241659edf0f8125deb3
masaomi-yamaguchi/synbit
LazyEnv.hs
# LANGUAGE UndecidableInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # {-# OPTIONS_GHC -Wunused-imports #-} module Synthesis.LazyEnv ( Env , empty , singleton , lookup , insert , insertAll , insertAll' , lookup' , foldrE , toList , fromList , select , remove , map , all , any) where import Control.Monad.Sharing import qualified Data.Monadic.List as L import Prelude hiding (lookup, map, any, all) import qualified Control.Applicative as A import Control.Monad (MonadPlus, mzero) data Env m a b = Nil | Cons Bool a (m b) (m (Env m a b)) instance (Monad m, Eq a, Shareable m b) => Shareable m (Env m a b) where shareArgs _ Nil = return Nil shareArgs f (Cons isShared k v xs) | isShared = return $ Cons True k v xs shareArgs f (Cons isShared k v xs) | otherwise = do v' <- f v xs' <- f xs return $ Cons True k v' xs' nil :: Monad m => m (Env m a b) nil = return Nil cons :: Monad m => a -> m b -> m (Env m a b) -> m (Env m a b) cons k v env = return $ Cons False k v env empty :: Monad m => m (Env m a b) empty = nil singleton :: Monad m => a -> m b -> m (Env m a b) singleton a b = cons a b empty lookup :: (Monad m, Ord a) => a -> m (Env m a b) -> m (Maybe (m b)) lookup x menv = do env <- menv case env of Nil -> return Nothing Cons _ k v rest -> do if k == x then return (Just v) else if k > x then return Nothing else lookup x rest mem :: (Monad m, Ord a) => a -> m (Env m a b) -> m Bool mem x env = do look <- lookup x env case look of Just _ -> return True Nothing -> return False insert :: (Monad m, Ord a) => a -> m b -> m (Env m a b) -> m (Env m a b) insert x v menv = do env <- menv case env of Nil -> cons x v nil Cons _ k v' rest -> do if k == x then cons x v rest else if k > x then cons x v (cons k v' rest) else cons k v' (insert x v rest) remove :: (Monad m, Ord a) => a -> m (Env m a b) -> m (Env m a b) remove x menv = do env <- menv case env of Nil -> nil Cons _ k v' rest -> do if k == x then rest else if k > x then cons k v' rest else cons k v' (remove x rest) insertAll :: (Monad m, Ord a) => m (Env m a b) -> m (Env m a b) -> m (Env m a b) insertAll mbind env = do bind <- mbind case bind of Nil -> env Cons _ k v rest -> do insert k v (insertAll rest env) insertAll' :: (Monad m, Ord a) => m (L.List m (a, m b)) -> m (Env m a b) -> m (Env m a b) insertAll' mbind env = do bind <- mbind case bind of L.Nil -> env L.Cons mkv rest -> do (k, v) <- mkv insert k v (insertAll' rest env) lookup' :: (Monad m, Ord a) => a -> m (L.List m (a, m b)) -> m (Maybe (m b)) lookup' x menv = do env <- menv case env of L.Nil -> return Nothing L.Cons mkv rest -> do (k, v) <- mkv if k == x then return (Just v) else lookup' x rest toList :: Monad m => m (Env m a b) -> m (L.List m (a, m b)) toList menv = do env <- menv case env of Nil -> return L.Nil Cons _ k v rest -> return $ L.Cons (return (k, v)) (toList rest) fromList :: (Monad m, Ord a) => m (L.List m (a, m b)) -> m (Env m a b) fromList l = insertAll' l nil foldrE :: Monad m => (a -> m b -> m c -> m c) -> m c -> m (Env m a b) -> m c foldrE f e ml = do l <- ml case l of Nil -> e Cons _ k v xs -> f k v (foldrE f e xs) select :: MonadPlus m => m (Env m a b) -> m (a, m b) select env = foldrE (\a b c -> (return (a, b)) A.<|> c) mzero env map :: Monad m => (a -> m b -> m b) -> m (Env m a b) -> m (Env m a b) map f menv = do env <- menv case env of Nil -> nil Cons _ k v rest -> cons k (f k v) (map f rest) all :: Monad m => (a -> m b -> m Bool) -> m (Env m a b) -> m Bool all f menv = do env <- menv case env of Nil -> return True Cons _ k v rest -> do bool <- f k v if bool then all f rest else return False any :: Monad m => (a -> m b -> m Bool) -> m (Env m a b) -> m Bool any f menv = do env <- menv case env of Nil -> return False Cons _ k v rest -> do bool <- f k v if bool then return True else any f rest
null
https://raw.githubusercontent.com/masaomi-yamaguchi/synbit/4553ae090dfcda4965a16b09130c1d6874b5a849/src/Synthesis/LazyEnv.hs
haskell
# OPTIONS_GHC -Wunused-imports #
# LANGUAGE UndecidableInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # module Synthesis.LazyEnv ( Env , empty , singleton , lookup , insert , insertAll , insertAll' , lookup' , foldrE , toList , fromList , select , remove , map , all , any) where import Control.Monad.Sharing import qualified Data.Monadic.List as L import Prelude hiding (lookup, map, any, all) import qualified Control.Applicative as A import Control.Monad (MonadPlus, mzero) data Env m a b = Nil | Cons Bool a (m b) (m (Env m a b)) instance (Monad m, Eq a, Shareable m b) => Shareable m (Env m a b) where shareArgs _ Nil = return Nil shareArgs f (Cons isShared k v xs) | isShared = return $ Cons True k v xs shareArgs f (Cons isShared k v xs) | otherwise = do v' <- f v xs' <- f xs return $ Cons True k v' xs' nil :: Monad m => m (Env m a b) nil = return Nil cons :: Monad m => a -> m b -> m (Env m a b) -> m (Env m a b) cons k v env = return $ Cons False k v env empty :: Monad m => m (Env m a b) empty = nil singleton :: Monad m => a -> m b -> m (Env m a b) singleton a b = cons a b empty lookup :: (Monad m, Ord a) => a -> m (Env m a b) -> m (Maybe (m b)) lookup x menv = do env <- menv case env of Nil -> return Nothing Cons _ k v rest -> do if k == x then return (Just v) else if k > x then return Nothing else lookup x rest mem :: (Monad m, Ord a) => a -> m (Env m a b) -> m Bool mem x env = do look <- lookup x env case look of Just _ -> return True Nothing -> return False insert :: (Monad m, Ord a) => a -> m b -> m (Env m a b) -> m (Env m a b) insert x v menv = do env <- menv case env of Nil -> cons x v nil Cons _ k v' rest -> do if k == x then cons x v rest else if k > x then cons x v (cons k v' rest) else cons k v' (insert x v rest) remove :: (Monad m, Ord a) => a -> m (Env m a b) -> m (Env m a b) remove x menv = do env <- menv case env of Nil -> nil Cons _ k v' rest -> do if k == x then rest else if k > x then cons k v' rest else cons k v' (remove x rest) insertAll :: (Monad m, Ord a) => m (Env m a b) -> m (Env m a b) -> m (Env m a b) insertAll mbind env = do bind <- mbind case bind of Nil -> env Cons _ k v rest -> do insert k v (insertAll rest env) insertAll' :: (Monad m, Ord a) => m (L.List m (a, m b)) -> m (Env m a b) -> m (Env m a b) insertAll' mbind env = do bind <- mbind case bind of L.Nil -> env L.Cons mkv rest -> do (k, v) <- mkv insert k v (insertAll' rest env) lookup' :: (Monad m, Ord a) => a -> m (L.List m (a, m b)) -> m (Maybe (m b)) lookup' x menv = do env <- menv case env of L.Nil -> return Nothing L.Cons mkv rest -> do (k, v) <- mkv if k == x then return (Just v) else lookup' x rest toList :: Monad m => m (Env m a b) -> m (L.List m (a, m b)) toList menv = do env <- menv case env of Nil -> return L.Nil Cons _ k v rest -> return $ L.Cons (return (k, v)) (toList rest) fromList :: (Monad m, Ord a) => m (L.List m (a, m b)) -> m (Env m a b) fromList l = insertAll' l nil foldrE :: Monad m => (a -> m b -> m c -> m c) -> m c -> m (Env m a b) -> m c foldrE f e ml = do l <- ml case l of Nil -> e Cons _ k v xs -> f k v (foldrE f e xs) select :: MonadPlus m => m (Env m a b) -> m (a, m b) select env = foldrE (\a b c -> (return (a, b)) A.<|> c) mzero env map :: Monad m => (a -> m b -> m b) -> m (Env m a b) -> m (Env m a b) map f menv = do env <- menv case env of Nil -> nil Cons _ k v rest -> cons k (f k v) (map f rest) all :: Monad m => (a -> m b -> m Bool) -> m (Env m a b) -> m Bool all f menv = do env <- menv case env of Nil -> return True Cons _ k v rest -> do bool <- f k v if bool then all f rest else return False any :: Monad m => (a -> m b -> m Bool) -> m (Env m a b) -> m Bool any f menv = do env <- menv case env of Nil -> return False Cons _ k v rest -> do bool <- f k v if bool then return True else any f rest
99c7767a24b2f82706eabb13f2ca09cfdd1286843750ee4e3d94944a82ae13e4
craigfe/sink
sink_kernel.ml
(** The canonical definitions of various standard types: *) let ( >> ) f g x = g (f x) type empty = | type ('a, 'b) either = Left of 'a | Right of 'b let absurd : type a. empty -> a = function _ -> .
null
https://raw.githubusercontent.com/craigfe/sink/c5431edfa1b06f1a09845a481c4afcb3e92f0667/src/sink/sink_kernel.ml
ocaml
* The canonical definitions of various standard types:
let ( >> ) f g x = g (f x) type empty = | type ('a, 'b) either = Left of 'a | Right of 'b let absurd : type a. empty -> a = function _ -> .
8722fc192068d6ce5532a640da599127ed709b1f48cd6924bd808ae4362bf001
josephwilk/functions-as-patterns
seq.clj
(ns functions-as-patterns.seq (:require [functions-as-patterns.color :as color] [functions-as-patterns.core :refer :all])) (def doc-dir (str (clojure.string/replace (:out (clojure.java.shell/sh "pwd")) "\n" "") "/doc" )) ;;Get shorter ;;;distinct filter remove take-nth for (render doc-dir (distinct (concat (take 2 (color/color-seq 2 color/rgb-highlight-color)) (take 2 (drop 3 (color/hues 5))) (color/color-seq 1 color/rgb-highlight-color)))) (render doc-dir (dedupe (concat (take 2 (color/color-seq 2 color/rgb-highlight-color)) (take 2 (drop 3 (color/hues 5))) (color/color-seq 1 color/rgb-highlight-color)))) ;;The pattern is more the fn than the filter/remove (render doc-dir (filter (fn [x] (= 0 (mod x 3))) (color/hues 10))) (render doc-dir (remove (fn [x] (= 0 (mod x 3))) (color/hues 10))) (render doc-dir (take-nth 3 (color/hues 7))) (render doc-dir (take 5 (for [x (range 5) y (range 5) :while (< y x)] [(color/int->color x) (color/int->color y)]))) ;;Get longer mapcat cycle interleave interpose (render doc-dir (cons color/rgb-highlight-color (color/color-seq 3 (last (color/hues 4))))) (render doc-dir (conj (color/color-seq 3 color/rgb-highlight-color) (last (color/hues 4)))) (render doc-dir (concat (color/color-seq 3) (color/color-seq 3 color/rgb-highlight-color))) (render doc-dir (cons color/rgb-highlight-color (color/color-seq 3 (last (color/hues 4))))) (render doc-dir (conj [(last (color/hues 4))] (color/color-seq 3 color/rgb-highlight-color) )) (render-titled doc-dir "vec" (conj [(last (color/hues 4))] (apply vector (color/color-seq 3 color/rgb-highlight-color)))) (render-titled doc-dir "list" (conj (list (last (color/hues 4))) (apply vector (color/color-seq 3 color/rgb-highlight-color)))) (render doc-dir (concat (color/color-seq 3) (color/color-seq 3 color/rgb-highlight-color))) ( view ( lazy - cat ( color / color - seq 3 ) ( color / color - seq 3 color / rgb - highlight - color ) ) ) (render doc-dir (mapcat (fn [x] x) [(color/color-seq 3) (color/color-seq 3 color/rgb-highlight-color)])) (render doc-dir (interpose color/rgb-highlight-color (color/color-seq 5))) (render doc-dir (interleave (color/hues 30 2 color/highlight-color) (color/color-seq 5))) ;;Tail-items rest nthrest next fnext nnext drop drop - while take - last for (render doc-dir (rest (cons (last (color/hues 4)) (color/color-seq 3 color/rgb-highlight-color)))) (render doc-dir (nthrest (color/hues 5) 2)) (render doc-dir (nthnext (color/hues 5) 2)) ;;Head-items ;;;take take-while butlast drop-last for (render doc-dir (butlast (cons (nth (color/hues 4) 2) (color/color-seq 2 color/rgb-highlight-color)))) (view (drop-last 2 (concat (color/color-seq 2) (color/color-seq 2 color/rgb-highlight-color)))) ;;Change ;;;flatten group-by partition partition-all partition-by split-at split-with filter ;;;remove replace shuffle (render doc-dir (shuffle (color/hues 7))) (render doc-dir (replace (color/hues 5 45) [0 3 4])) (render doc-dir (partition 3 (color/hues 7))) (render doc-dir (partition-all 3 (color/hues 7))) (render doc-dir (partition-by even? (color/hues 10))) (render doc-dir (split-at 2 (color/color-seq 3 color/rgb-highlight-color))) (render doc-dir (split-with even? (color/color-seq 3 color/rgb-highlight-color))) (render doc-dir (flatten (partition 2 (color/hues 10)))) (render doc-dir (flatten (partition 1 (partition-all 2 (color/hues 8))))) ;;Rearrange ;;;reverse sort sort-by compare (render doc-dir (reverse (color/hues 4 30))) (render doc-dir (sort (shuffle (shuffle (shuffle (color/hues 7 10)))))) ;;Process items map pmap map - indexed for replace seque (conj )
null
https://raw.githubusercontent.com/josephwilk/functions-as-patterns/a0ef526b2f8b44755d49dd252c78afef67d5c282/src/functions_as_patterns/seq.clj
clojure
Get shorter distinct filter remove take-nth for The pattern is more the fn than the filter/remove Get longer Tail-items Head-items take take-while butlast drop-last for Change flatten group-by partition partition-all partition-by split-at split-with filter remove replace shuffle Rearrange reverse sort sort-by compare Process items
(ns functions-as-patterns.seq (:require [functions-as-patterns.color :as color] [functions-as-patterns.core :refer :all])) (def doc-dir (str (clojure.string/replace (:out (clojure.java.shell/sh "pwd")) "\n" "") "/doc" )) (render doc-dir (distinct (concat (take 2 (color/color-seq 2 color/rgb-highlight-color)) (take 2 (drop 3 (color/hues 5))) (color/color-seq 1 color/rgb-highlight-color)))) (render doc-dir (dedupe (concat (take 2 (color/color-seq 2 color/rgb-highlight-color)) (take 2 (drop 3 (color/hues 5))) (color/color-seq 1 color/rgb-highlight-color)))) (render doc-dir (filter (fn [x] (= 0 (mod x 3))) (color/hues 10))) (render doc-dir (remove (fn [x] (= 0 (mod x 3))) (color/hues 10))) (render doc-dir (take-nth 3 (color/hues 7))) (render doc-dir (take 5 (for [x (range 5) y (range 5) :while (< y x)] [(color/int->color x) (color/int->color y)]))) mapcat cycle interleave interpose (render doc-dir (cons color/rgb-highlight-color (color/color-seq 3 (last (color/hues 4))))) (render doc-dir (conj (color/color-seq 3 color/rgb-highlight-color) (last (color/hues 4)))) (render doc-dir (concat (color/color-seq 3) (color/color-seq 3 color/rgb-highlight-color))) (render doc-dir (cons color/rgb-highlight-color (color/color-seq 3 (last (color/hues 4))))) (render doc-dir (conj [(last (color/hues 4))] (color/color-seq 3 color/rgb-highlight-color) )) (render-titled doc-dir "vec" (conj [(last (color/hues 4))] (apply vector (color/color-seq 3 color/rgb-highlight-color)))) (render-titled doc-dir "list" (conj (list (last (color/hues 4))) (apply vector (color/color-seq 3 color/rgb-highlight-color)))) (render doc-dir (concat (color/color-seq 3) (color/color-seq 3 color/rgb-highlight-color))) ( view ( lazy - cat ( color / color - seq 3 ) ( color / color - seq 3 color / rgb - highlight - color ) ) ) (render doc-dir (mapcat (fn [x] x) [(color/color-seq 3) (color/color-seq 3 color/rgb-highlight-color)])) (render doc-dir (interpose color/rgb-highlight-color (color/color-seq 5))) (render doc-dir (interleave (color/hues 30 2 color/highlight-color) (color/color-seq 5))) rest nthrest next fnext nnext drop drop - while take - last for (render doc-dir (rest (cons (last (color/hues 4)) (color/color-seq 3 color/rgb-highlight-color)))) (render doc-dir (nthrest (color/hues 5) 2)) (render doc-dir (nthnext (color/hues 5) 2)) (render doc-dir (butlast (cons (nth (color/hues 4) 2) (color/color-seq 2 color/rgb-highlight-color)))) (view (drop-last 2 (concat (color/color-seq 2) (color/color-seq 2 color/rgb-highlight-color)))) (render doc-dir (shuffle (color/hues 7))) (render doc-dir (replace (color/hues 5 45) [0 3 4])) (render doc-dir (partition 3 (color/hues 7))) (render doc-dir (partition-all 3 (color/hues 7))) (render doc-dir (partition-by even? (color/hues 10))) (render doc-dir (split-at 2 (color/color-seq 3 color/rgb-highlight-color))) (render doc-dir (split-with even? (color/color-seq 3 color/rgb-highlight-color))) (render doc-dir (flatten (partition 2 (color/hues 10)))) (render doc-dir (flatten (partition 1 (partition-all 2 (color/hues 8))))) (render doc-dir (reverse (color/hues 4 30))) (render doc-dir (sort (shuffle (shuffle (shuffle (color/hues 7 10)))))) map pmap map - indexed for replace seque (conj )
1fb0946cc3ece8bfbff2040f59714ea3c2984293e63eed2a06cea441c4275299
sarabander/p2pu-sicp
Ex1.33.scm
Depends on 1.20 , 1.21 , 1.28 (define (filtered-accumulate filter combiner null-value term a next b) (define (iter a result) (if (> a b) result (iter (next a) (combiner (if (filter a) (term a) null-value) result)))) (iter a null-value)) ;; test (+ (filtered-accumulate odd? + 0 identity 1 inc 10) 55 (+ (filtered-accumulate odd? + 0 cube 1 inc 10) 3025 3025 ;; a. input are primes between 2 and 50 ( result for reference point ) 10466 ;; with exhaustive prime test (define (sum-prime-squares a b) (filtered-accumulate prime? + 0 square a inc b)) with Miller - Rabin probabilistic test (define (sum-prime-squares a b) (filtered-accumulate miller-rabin-prime? + 0 square a inc b)) 10466 ( matches the previous result ) ;; b. (define rel-prime? (λ (n) (λ (i) (= (gcd i n) 1)))) ((rel-prime? 20) 9) ; #t (define (prod-rel-prime n) (filtered-accumulate (rel-prime? n) * 1 identity 1 inc (- n 1))) 2240 189 3628800
null
https://raw.githubusercontent.com/sarabander/p2pu-sicp/fbc49b67dac717da1487629fb2d7a7d86dfdbe32/1.3/Ex1.33.scm
scheme
test a. with exhaustive prime test b. #t
Depends on 1.20 , 1.21 , 1.28 (define (filtered-accumulate filter combiner null-value term a next b) (define (iter a result) (if (> a b) result (iter (next a) (combiner (if (filter a) (term a) null-value) result)))) (iter a null-value)) (+ (filtered-accumulate odd? + 0 identity 1 inc 10) 55 (+ (filtered-accumulate odd? + 0 cube 1 inc 10) 3025 3025 input are primes between 2 and 50 ( result for reference point ) 10466 (define (sum-prime-squares a b) (filtered-accumulate prime? + 0 square a inc b)) with Miller - Rabin probabilistic test (define (sum-prime-squares a b) (filtered-accumulate miller-rabin-prime? + 0 square a inc b)) 10466 ( matches the previous result ) (define rel-prime? (λ (n) (λ (i) (= (gcd i n) 1)))) (define (prod-rel-prime n) (filtered-accumulate (rel-prime? n) * 1 identity 1 inc (- n 1))) 2240 189 3628800
3310de140adb0cf7df50918d7b5dfc9a500f28cee5fae079bd1397cfc4f6438f
nuttycom/aftok
Types.hs
# LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE ExplicitForAll #-} # LANGUAGE TemplateHaskell # module Aftok.Payments.Types where import Aftok.Billing ( Billable, Billable', BillableId, requestExpiryPeriod, ) import Aftok.Currency (Currency (..), Currency' (..)) import Aftok.Currency.Bitcoin (Satoshi) import qualified Aftok.Currency.Bitcoin.Payments as B import Aftok.Currency.Zcash (Zatoshi) import qualified Aftok.Currency.Zcash.Payments as Z import qualified Aftok.Currency.Zcash.Zip321 as Z import Aftok.Types (ProjectId, UserId) import Control.Lens ( makeLenses, makePrisms, (^.), ) import Data.AffineSpace ((.+^)) import Data.Thyme.Clock as C import Data.Thyme.Time as C import Data.UUID newtype PaymentRequestId = PaymentRequestId UUID deriving (Show, Eq) makePrisms ''PaymentRequestId newtype PaymentId = PaymentId UUID deriving (Show, Eq) makePrisms ''PaymentId data NativeRequest currency where Bip70Request :: B.PaymentRequest -> NativeRequest Satoshi Zip321Request :: Z.PaymentRequest -> NativeRequest Zatoshi bip70Request :: NativeRequest currency -> Maybe B.PaymentRequest bip70Request = \case Bip70Request r -> Just r _ -> Nothing zip321Request :: NativeRequest currency -> Maybe Z.PaymentRequest zip321Request = \case Zip321Request r -> Just r _ -> Nothing data NativePayment currency where BitcoinPayment :: B.Payment -> NativePayment Satoshi ZcashPayment :: Z.Payment -> NativePayment Zatoshi data PaymentOps currency m = PaymentOps { newPaymentRequest :: Billable currency -> -- billing information C.Day -> -- payout date (billing date) C.UTCTime -> -- timestamp of payment request creation m (NativeRequest currency) } data PaymentRequest' (billable :: Type -> Type) currency = PaymentRequest { _billable :: billable currency, _createdAt :: C.UTCTime, _billingDate :: C.Day, _nativeRequest :: NativeRequest currency } makeLenses ''PaymentRequest' type PaymentRequest currency = PaymentRequest' (Const BillableId) currency type PaymentRequestDetail currency = PaymentRequest' (Billable' ProjectId UserId) currency data SomePaymentRequest (b :: Type -> Type) = forall c. SomePaymentRequest (PaymentRequest' b c) type SomePaymentRequestDetail = SomePaymentRequest (Billable' ProjectId UserId) paymentRequestCurrency :: PaymentRequest' b c -> Currency' c paymentRequestCurrency pr = case _nativeRequest pr of Bip70Request _ -> Currency' BTC Zip321Request _ -> Currency' ZEC isExpired :: forall c. UTCTime -> PaymentRequestDetail c -> Bool isExpired now req = let expiresAt = (req ^. createdAt) .+^ (req ^. (billable . requestExpiryPeriod)) in now >= expiresAt data Payment' (paymentRequest :: Type -> Type) currency = Payment { _paymentRequest :: paymentRequest currency, _paymentDate :: C.UTCTime, _nativePayment :: NativePayment currency } makeLenses ''Payment' data PaymentRequestError = AmountInvalid | NoRecipients type Payment currency = Payment' (Const PaymentRequestId) currency type PaymentDetail currency = Payment' (PaymentRequest' (Billable' ProjectId UserId)) currency
null
https://raw.githubusercontent.com/nuttycom/aftok/58feefe675cea908cf10619cc88ca4770152e82e/lib/Aftok/Payments/Types.hs
haskell
# LANGUAGE DeriveTraversable # # LANGUAGE ExplicitForAll # billing information payout date (billing date) timestamp of payment request creation
# LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE TemplateHaskell # module Aftok.Payments.Types where import Aftok.Billing ( Billable, Billable', BillableId, requestExpiryPeriod, ) import Aftok.Currency (Currency (..), Currency' (..)) import Aftok.Currency.Bitcoin (Satoshi) import qualified Aftok.Currency.Bitcoin.Payments as B import Aftok.Currency.Zcash (Zatoshi) import qualified Aftok.Currency.Zcash.Payments as Z import qualified Aftok.Currency.Zcash.Zip321 as Z import Aftok.Types (ProjectId, UserId) import Control.Lens ( makeLenses, makePrisms, (^.), ) import Data.AffineSpace ((.+^)) import Data.Thyme.Clock as C import Data.Thyme.Time as C import Data.UUID newtype PaymentRequestId = PaymentRequestId UUID deriving (Show, Eq) makePrisms ''PaymentRequestId newtype PaymentId = PaymentId UUID deriving (Show, Eq) makePrisms ''PaymentId data NativeRequest currency where Bip70Request :: B.PaymentRequest -> NativeRequest Satoshi Zip321Request :: Z.PaymentRequest -> NativeRequest Zatoshi bip70Request :: NativeRequest currency -> Maybe B.PaymentRequest bip70Request = \case Bip70Request r -> Just r _ -> Nothing zip321Request :: NativeRequest currency -> Maybe Z.PaymentRequest zip321Request = \case Zip321Request r -> Just r _ -> Nothing data NativePayment currency where BitcoinPayment :: B.Payment -> NativePayment Satoshi ZcashPayment :: Z.Payment -> NativePayment Zatoshi data PaymentOps currency m = PaymentOps { newPaymentRequest :: m (NativeRequest currency) } data PaymentRequest' (billable :: Type -> Type) currency = PaymentRequest { _billable :: billable currency, _createdAt :: C.UTCTime, _billingDate :: C.Day, _nativeRequest :: NativeRequest currency } makeLenses ''PaymentRequest' type PaymentRequest currency = PaymentRequest' (Const BillableId) currency type PaymentRequestDetail currency = PaymentRequest' (Billable' ProjectId UserId) currency data SomePaymentRequest (b :: Type -> Type) = forall c. SomePaymentRequest (PaymentRequest' b c) type SomePaymentRequestDetail = SomePaymentRequest (Billable' ProjectId UserId) paymentRequestCurrency :: PaymentRequest' b c -> Currency' c paymentRequestCurrency pr = case _nativeRequest pr of Bip70Request _ -> Currency' BTC Zip321Request _ -> Currency' ZEC isExpired :: forall c. UTCTime -> PaymentRequestDetail c -> Bool isExpired now req = let expiresAt = (req ^. createdAt) .+^ (req ^. (billable . requestExpiryPeriod)) in now >= expiresAt data Payment' (paymentRequest :: Type -> Type) currency = Payment { _paymentRequest :: paymentRequest currency, _paymentDate :: C.UTCTime, _nativePayment :: NativePayment currency } makeLenses ''Payment' data PaymentRequestError = AmountInvalid | NoRecipients type Payment currency = Payment' (Const PaymentRequestId) currency type PaymentDetail currency = Payment' (PaymentRequest' (Billable' ProjectId UserId)) currency
6db440d22279f8a38e6faf67f86c22d8218b929f00d8dad67ec105d2be55d2cc
Ptival/recursion-schemes-examples
Histoparamorphisms.hs
# LANGUAGE LambdaCase # -- | module Histoparamorphisms where import Control.Comonad.Cofree import Data.Functor.Foldable import Numeric.Natural import Prelude hiding (lookup) import Histomorphisms.Natural (changeAlgebraHelper) histoPara :: (Corecursive t, Recursive t) => (Base t (Cofree ((,) t) a) -> a) -> t -> a histoPara = ghisto distPara -- | DOES NOT WORK algebra :: [Natural] -> Maybe (Cofree ((,) Natural) [[Natural]]) -> [[Natural]] algebra denominations = \case Nothing -> [[]] Just history -> changeAlgebraHelper denominations (compress history) (lookup history) where compress :: Cofree ((,) Natural) [[Natural]] -> Natural compress (_ :< (p, _)) = p + 1 lookup :: Cofree ((,) Natural) [[Natural]] -> Natural -> [[Natural]] lookup (v :< _) 0 = v lookup (_ :< r) n = lookup inner (n - 1) where (_, inner) = r change :: [Natural] -> Natural -> [[Natural]] change denominations = histoPara (algebra denominations)
null
https://raw.githubusercontent.com/Ptival/recursion-schemes-examples/bd2a506d38887e9b5d4f2afc435fc7bddf12a92e/lib/Histoparamorphisms.hs
haskell
| | DOES NOT WORK
# LANGUAGE LambdaCase # module Histoparamorphisms where import Control.Comonad.Cofree import Data.Functor.Foldable import Numeric.Natural import Prelude hiding (lookup) import Histomorphisms.Natural (changeAlgebraHelper) histoPara :: (Corecursive t, Recursive t) => (Base t (Cofree ((,) t) a) -> a) -> t -> a histoPara = ghisto distPara algebra :: [Natural] -> Maybe (Cofree ((,) Natural) [[Natural]]) -> [[Natural]] algebra denominations = \case Nothing -> [[]] Just history -> changeAlgebraHelper denominations (compress history) (lookup history) where compress :: Cofree ((,) Natural) [[Natural]] -> Natural compress (_ :< (p, _)) = p + 1 lookup :: Cofree ((,) Natural) [[Natural]] -> Natural -> [[Natural]] lookup (v :< _) 0 = v lookup (_ :< r) n = lookup inner (n - 1) where (_, inner) = r change :: [Natural] -> Natural -> [[Natural]] change denominations = histoPara (algebra denominations)
96564a4828f420078625a418b0f14eb686bc85469547050f4962eb6a0184304f
weavejester/fact
core.clj
Copyright ( c ) . All rights reserved . The use and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (-1.0.php) which ;; can be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, from ;; this software. ;; fact.core: ;; ;; The core functionality of Fact. (ns fact.core (:import clojure.lang.IFn) (:import java.util.regex.Pattern) (:import java.io.FileNotFoundException)) ;; Create a fact (defstruct fact-info :doc :test :pending? :params :data) (defmacro fact "Define a documented fact that can be verified via a series of test values applied to a test expression. If the expression evaluates to true for all values, the fact is verified. e.g. (fact \"The length of a list equals the sum of the length of its parts\" [x (rand-seqs rand-ints) y (rand-seqs rand-ints)] (= (count (concat x y)) (+ (count x) (count y))))" ([doc] `(fact ~doc nil)) ([doc data-map & expr] (let [pairs (partition 2 data-map) params (map first pairs) data (map second pairs)] `(def ~(gensym "fact-") (struct-map fact-info :doc ~doc :test (fn [~@params] ~@expr) :pending? ~(nil? data-map) :params '~(vec params) :data ~(vec data)))))) ;; Generate sequences of test data (defmacro when-require "Execute a block of code only if the supplied namespace can be loaded." [ns & body] `(do (try (require ~ns) (catch FileNotFoundException e#)) (when (find-ns ~ns) (eval '(do ~@body))))) (derive java.util.Map ::collection) (derive java.util.Collection ::collection) (defmulti #^{:doc "Return a sequence of test values from a particular generator."} test-seq class) (defmethod test-seq ::collection [coll] (seq coll)) (defmethod test-seq IFn [func] (repeatedly func)) (prefer-method test-seq ::collection IFn) (when-require 're-rand (defmethod test-seq Pattern [re] (repeatedly #(re-rand/re-rand re)))) ;; Verify a fact by running tests (def #^{:doc "The maximum amount of test values to use per fact."} *max-amount* 50) (defn- make-test-cases "Make a sequence of test cases from a number of test value sequences. The number of test cases is limited to *max-amount*. If the values sequences are of uneven length, the sequences are repeated up to the length of the largest value sequence." [vals] (if (seq vals) (let [bounded-vals (map #(take *max-amount* (test-seq %)) vals) max-count (apply max (map count bounded-vals)) same-size-vals (map #(take max-count (cycle %)) bounded-vals)] (apply map vector same-size-vals)) [[]])) (defn- run-tests "Run a function with a collection of test-cases and return the results." [func test-cases] (for [vals test-cases] (try (if (apply func vals) [:success vals] [:failure vals]) (catch Exception e [:exception [e vals]]) (catch Error e [:exception [e vals]])))) (defn- filter-category "Filter a sequence of results matching the supplied category." [category results] (for [[cat vals] results :when (= cat category)] vals)) (defstruct result :fact :successes :failures :exceptions) (defn verify "Verify a single fact." [fact] (if (fact :pending?) (struct result fact nil nil nil) (let [results (run-tests (fact :test) (make-test-cases (fact :data)))] (struct-map result :fact fact :successes (filter-category :success results) :failures (filter-category :failure results) :exceptions (filter-category :exception results))))) ;; Verify all facts in a namespace (defn- get-facts "Get all the functions beginning with 'fact' from a namespace." [ns] (for [[sym var] (ns-publics ns) :when (.startsWith (name sym) "fact-")] (var-get var))) (defn verify-facts "Get a lazy list of results from all the facts in a namespace." ([] (verify-facts *ns*)) ([ns] (map verify (get-facts ns)))) (defn failure? "Did the fact fail?" [result] (not-empty (result :failures))) (defn exception? "Did the fact throw an exception?" [result] (not-empty (result :exceptions))) (defn pending? "Is the fact pending a verification test?" [result] (:pending? (result :fact)))
null
https://raw.githubusercontent.com/weavejester/fact/0b413fbf06ce7f8a582d0217e5feff8c4288f03e/src/fact/core.clj
clojure
Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. fact.core: The core functionality of Fact. Create a fact Generate sequences of test data Verify a fact by running tests Verify all facts in a namespace
Copyright ( c ) . All rights reserved . The use and distribution terms for this software are covered by the Eclipse (ns fact.core (:import clojure.lang.IFn) (:import java.util.regex.Pattern) (:import java.io.FileNotFoundException)) (defstruct fact-info :doc :test :pending? :params :data) (defmacro fact "Define a documented fact that can be verified via a series of test values applied to a test expression. If the expression evaluates to true for all values, the fact is verified. e.g. (fact \"The length of a list equals the sum of the length of its parts\" [x (rand-seqs rand-ints) y (rand-seqs rand-ints)] (= (count (concat x y)) (+ (count x) (count y))))" ([doc] `(fact ~doc nil)) ([doc data-map & expr] (let [pairs (partition 2 data-map) params (map first pairs) data (map second pairs)] `(def ~(gensym "fact-") (struct-map fact-info :doc ~doc :test (fn [~@params] ~@expr) :pending? ~(nil? data-map) :params '~(vec params) :data ~(vec data)))))) (defmacro when-require "Execute a block of code only if the supplied namespace can be loaded." [ns & body] `(do (try (require ~ns) (catch FileNotFoundException e#)) (when (find-ns ~ns) (eval '(do ~@body))))) (derive java.util.Map ::collection) (derive java.util.Collection ::collection) (defmulti #^{:doc "Return a sequence of test values from a particular generator."} test-seq class) (defmethod test-seq ::collection [coll] (seq coll)) (defmethod test-seq IFn [func] (repeatedly func)) (prefer-method test-seq ::collection IFn) (when-require 're-rand (defmethod test-seq Pattern [re] (repeatedly #(re-rand/re-rand re)))) (def #^{:doc "The maximum amount of test values to use per fact."} *max-amount* 50) (defn- make-test-cases "Make a sequence of test cases from a number of test value sequences. The number of test cases is limited to *max-amount*. If the values sequences are of uneven length, the sequences are repeated up to the length of the largest value sequence." [vals] (if (seq vals) (let [bounded-vals (map #(take *max-amount* (test-seq %)) vals) max-count (apply max (map count bounded-vals)) same-size-vals (map #(take max-count (cycle %)) bounded-vals)] (apply map vector same-size-vals)) [[]])) (defn- run-tests "Run a function with a collection of test-cases and return the results." [func test-cases] (for [vals test-cases] (try (if (apply func vals) [:success vals] [:failure vals]) (catch Exception e [:exception [e vals]]) (catch Error e [:exception [e vals]])))) (defn- filter-category "Filter a sequence of results matching the supplied category." [category results] (for [[cat vals] results :when (= cat category)] vals)) (defstruct result :fact :successes :failures :exceptions) (defn verify "Verify a single fact." [fact] (if (fact :pending?) (struct result fact nil nil nil) (let [results (run-tests (fact :test) (make-test-cases (fact :data)))] (struct-map result :fact fact :successes (filter-category :success results) :failures (filter-category :failure results) :exceptions (filter-category :exception results))))) (defn- get-facts "Get all the functions beginning with 'fact' from a namespace." [ns] (for [[sym var] (ns-publics ns) :when (.startsWith (name sym) "fact-")] (var-get var))) (defn verify-facts "Get a lazy list of results from all the facts in a namespace." ([] (verify-facts *ns*)) ([ns] (map verify (get-facts ns)))) (defn failure? "Did the fact fail?" [result] (not-empty (result :failures))) (defn exception? "Did the fact throw an exception?" [result] (not-empty (result :exceptions))) (defn pending? "Is the fact pending a verification test?" [result] (:pending? (result :fact)))
ae129fe21f7a67a5f09d2e8230c5659e996a74e86090f8dce1c81a33dd3c616b
liyang/thyme
Human.hs
# LANGUAGE CPP # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE ViewPatterns # #include "thyme.h" #if HLINT #include "cabal_macros.h" #endif -- | Vague textual descriptions of time durations. module Data.Thyme.Format.Human ( humanTimeDiff , humanTimeDiffs , humanRelTime , humanRelTimes ) where import Prelude #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Arrow import Control.Lens import Control.Monad import Data.AdditiveGroup import Data.AffineSpace import Data.Foldable import Data.Thyme.Internal.Micro import Data.Monoid import Data.Thyme.Clock.Internal import Data.VectorSpace data Unit = Unit { unit :: Micro , single :: ShowS , plural :: ShowS } LENS(Unit,plural,ShowS) -- | Display 'DiffTime' or 'NominalDiffTime' in a human-readable form. # INLINE humanTimeDiff # humanTimeDiff :: (TimeDiff d) => d -> String humanTimeDiff d = humanTimeDiffs d "" -- | Display 'DiffTime' or 'NominalDiffTime' in a human-readable form. {-# ANN humanTimeDiffs "HLint: ignore Use fromMaybe" #-} humanTimeDiffs :: (TimeDiff d) => d -> ShowS humanTimeDiffs td = (if signed < 0 then (:) '-' else id) . diff where signed@(Micro . abs -> us) = td ^. microseconds diff = maybe id id . getFirst . fold $ zipWith (approx us . unit) (tail units) units -- | Display one 'UTCTime' relative to another, in a human-readable form. # INLINE humanRelTime # humanRelTime :: UTCTime -> UTCTime -> String humanRelTime ref time = humanRelTimes ref time "" -- | Display one 'UTCTime' relative to another, in a human-readable form. humanRelTimes :: UTCTime -> UTCTime -> ShowS humanRelTimes ref time = thence $ humanTimeDiffs diff where (diff, thence) = case compare delta zeroV of LT -> (negateV delta, ((++) "in " .)) EQ -> (zeroV, const $ (++) "right now") GT -> (delta, (. (++) " ago")) where delta = time .-. ref approx :: Micro -> Micro -> Unit -> First ShowS approx us next Unit {..} = First $ shows n . inflection <$ guard (us < next) where n = fst $ microQuotRem (us ^+^ half) unit where half = Micro . fst $ microQuotRem unit (Micro 2) inflection = if n == 1 then single else plural units :: [Unit] units = scanl (&) (Unit (Micro 1) (" microsecond" ++) (" microseconds" ++)) [ times "millisecond" 1000 , times "second" 1000 , times "minute" 60 , times "hour" 60 , times "day" 24 , times "week" 7 , times "month" (30.4368 / 7) , times "year" 12 , times "decade" 10 , times "century" 10 >>> set _plural (" centuries" ++) , times "millennium" 10 >>> set _plural (" millennia" ++) , const (Unit maxBound id id) -- upper bound needed for humanTimeDiffs.diff ] where times :: String -> Rational -> Unit -> Unit times ((++) . (:) ' ' -> single) r Unit {unit} = Unit {unit = r *^ unit, plural = single . (:) 's', ..}
null
https://raw.githubusercontent.com/liyang/thyme/c0dcc251ff4f843672987c80b73ec4808bc009e4/src/Data/Thyme/Format/Human.hs
haskell
| Vague textual descriptions of time durations. | Display 'DiffTime' or 'NominalDiffTime' in a human-readable form. | Display 'DiffTime' or 'NominalDiffTime' in a human-readable form. # ANN humanTimeDiffs "HLint: ignore Use fromMaybe" # | Display one 'UTCTime' relative to another, in a human-readable form. | Display one 'UTCTime' relative to another, in a human-readable form. upper bound needed for humanTimeDiffs.diff
# LANGUAGE CPP # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE ViewPatterns # #include "thyme.h" #if HLINT #include "cabal_macros.h" #endif module Data.Thyme.Format.Human ( humanTimeDiff , humanTimeDiffs , humanRelTime , humanRelTimes ) where import Prelude #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Arrow import Control.Lens import Control.Monad import Data.AdditiveGroup import Data.AffineSpace import Data.Foldable import Data.Thyme.Internal.Micro import Data.Monoid import Data.Thyme.Clock.Internal import Data.VectorSpace data Unit = Unit { unit :: Micro , single :: ShowS , plural :: ShowS } LENS(Unit,plural,ShowS) # INLINE humanTimeDiff # humanTimeDiff :: (TimeDiff d) => d -> String humanTimeDiff d = humanTimeDiffs d "" humanTimeDiffs :: (TimeDiff d) => d -> ShowS humanTimeDiffs td = (if signed < 0 then (:) '-' else id) . diff where signed@(Micro . abs -> us) = td ^. microseconds diff = maybe id id . getFirst . fold $ zipWith (approx us . unit) (tail units) units # INLINE humanRelTime # humanRelTime :: UTCTime -> UTCTime -> String humanRelTime ref time = humanRelTimes ref time "" humanRelTimes :: UTCTime -> UTCTime -> ShowS humanRelTimes ref time = thence $ humanTimeDiffs diff where (diff, thence) = case compare delta zeroV of LT -> (negateV delta, ((++) "in " .)) EQ -> (zeroV, const $ (++) "right now") GT -> (delta, (. (++) " ago")) where delta = time .-. ref approx :: Micro -> Micro -> Unit -> First ShowS approx us next Unit {..} = First $ shows n . inflection <$ guard (us < next) where n = fst $ microQuotRem (us ^+^ half) unit where half = Micro . fst $ microQuotRem unit (Micro 2) inflection = if n == 1 then single else plural units :: [Unit] units = scanl (&) (Unit (Micro 1) (" microsecond" ++) (" microseconds" ++)) [ times "millisecond" 1000 , times "second" 1000 , times "minute" 60 , times "hour" 60 , times "day" 24 , times "week" 7 , times "month" (30.4368 / 7) , times "year" 12 , times "decade" 10 , times "century" 10 >>> set _plural (" centuries" ++) , times "millennium" 10 >>> set _plural (" millennia" ++) ] where times :: String -> Rational -> Unit -> Unit times ((++) . (:) ' ' -> single) r Unit {unit} = Unit {unit = r *^ unit, plural = single . (:) 's', ..}
1b31f19586fb025f2e5ef72a5a440ed52ff75a3b12fd93b24e5cf954b7566b6d
Fuuzetsu/h-booru
Gelbooru.hs
# LANGUAGE DataKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # # LANGUAGE UnicodeSyntax # {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : HBooru.Parsers.Gelbooru Copyright : ( c ) 2013 - 2014 -- License : GPL-3 -- -- Maintainer : -- Stability : experimental -- -- Module for parsing content from </ Gelbooru>. module HBooru.Parsers.Gelbooru where import Data.List import HBooru.Parsers.FieldParsers import HBooru.Types import Text.XML.HXT.Core hiding (mkName) | Record used for Gelbooru posts type GelbooruPost = PR '[ "height" , "score" , "file_url" , "parent_id" , "sample_url" , "sample_width" , "sample_height" , "preview_url" , "rating" , "tags" , "id" , "width" , "change" , "md5" , "creator_id" , "has_children" , "created_at" , "status" , "source" , "has_notes" , "has_comments" , "preview_width" , "preview_height" ] | XML parser for Gelbooru used by " Postable Gelbooru XML " instance . parsePost ∷ (Functor (cat XmlTree), ArrowXml cat) ⇒ cat XmlTree GelbooruPost parsePost = hasName "post" >>> heightA <:+> scoreA <:+> file_urlA <:+> parent_idA <:+> sample_urlA <:+> sample_widthA <:+> sample_heightA <:+> preview_urlA <:+> ratingA <:+> tagsA <:+> idA <:+> widthA <:+> changeA <:+> md5A <:+> creator_idA <:+> has_childrenA <:+> created_atA <:+> statusA <:+> sourceA <:+> has_notesA <:+> has_commentsA <:+> preview_widthA <:+> preview_heightA -- | We use this type and its 'Site' instance to distinguish -- between various parsers. data Gelbooru = Gelbooru deriving (Show, Eq) instance Postable Gelbooru XML where postUrl _ _ ts = let tags' = intercalate "+" ts in "=" ++ tags' hardLimit _ _ = Limit 100 instance PostablePaged Gelbooru XML instance Site Gelbooru where instance PostParser Gelbooru XML where type ImageTy Gelbooru XML = GelbooruPost parseResponse _ = runLA (xreadDoc /> parsePost) . getResponse instance Counted Gelbooru XML where parseCount _ = read . head . runLA (xreadDoc >>> hasName "posts" >>> getAttrValue "count") . getResponse
null
https://raw.githubusercontent.com/Fuuzetsu/h-booru/55167fd0f329b377a377aac4d30ff99f096457f1/src/HBooru/Parsers/Gelbooru.hs
haskell
# OPTIONS_HADDOCK show-extensions # | Module : HBooru.Parsers.Gelbooru License : GPL-3 Maintainer : Stability : experimental Module for parsing content from </ Gelbooru>. | We use this type and its 'Site' instance to distinguish between various parsers.
# LANGUAGE DataKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # # LANGUAGE UnicodeSyntax # Copyright : ( c ) 2013 - 2014 module HBooru.Parsers.Gelbooru where import Data.List import HBooru.Parsers.FieldParsers import HBooru.Types import Text.XML.HXT.Core hiding (mkName) | Record used for Gelbooru posts type GelbooruPost = PR '[ "height" , "score" , "file_url" , "parent_id" , "sample_url" , "sample_width" , "sample_height" , "preview_url" , "rating" , "tags" , "id" , "width" , "change" , "md5" , "creator_id" , "has_children" , "created_at" , "status" , "source" , "has_notes" , "has_comments" , "preview_width" , "preview_height" ] | XML parser for Gelbooru used by " Postable Gelbooru XML " instance . parsePost ∷ (Functor (cat XmlTree), ArrowXml cat) ⇒ cat XmlTree GelbooruPost parsePost = hasName "post" >>> heightA <:+> scoreA <:+> file_urlA <:+> parent_idA <:+> sample_urlA <:+> sample_widthA <:+> sample_heightA <:+> preview_urlA <:+> ratingA <:+> tagsA <:+> idA <:+> widthA <:+> changeA <:+> md5A <:+> creator_idA <:+> has_childrenA <:+> created_atA <:+> statusA <:+> sourceA <:+> has_notesA <:+> has_commentsA <:+> preview_widthA <:+> preview_heightA data Gelbooru = Gelbooru deriving (Show, Eq) instance Postable Gelbooru XML where postUrl _ _ ts = let tags' = intercalate "+" ts in "=" ++ tags' hardLimit _ _ = Limit 100 instance PostablePaged Gelbooru XML instance Site Gelbooru where instance PostParser Gelbooru XML where type ImageTy Gelbooru XML = GelbooruPost parseResponse _ = runLA (xreadDoc /> parsePost) . getResponse instance Counted Gelbooru XML where parseCount _ = read . head . runLA (xreadDoc >>> hasName "posts" >>> getAttrValue "count") . getResponse
89b9e322b7add7ffad431471fdf9ba7d7d7b22db7f5da0f1b6722f807970804f
backtracking/ocamlgraph
fixpoint.mli
(**************************************************************************) (* *) : a generic graph library for OCaml Copyright ( C ) 2004 - 2010 , and (* *) (* This software is free software; you can redistribute it and/or *) modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking (* described in file LICENSE. *) (* *) (* This software 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. *) (* *) (**************************************************************************) Copyright ( c ) 2010 - 2012 Technische Universitaet Muenchen * < > * All rights reserved . * Markus W. Weissmann <> * All rights reserved. *) * Fixpoint computation implemented using the work list algorithm . This module makes writing data - flow analysis easy . One of the simplest fixpoint analysis is that of reachability . Given a directed graph module [ G ] , its analysis can be implemented as follows : { [ module Reachability = Graph . . Make(G ) ( struct type vertex = G.E.vertex type edge = = G.t type data = bool let direction = Graph . . Forward let equal = ( =) let join = ( || ) let analyze _ = ( fun x - > x ) end ) ] } The types for [ vertex ] , [ edge ] and [ g ] are those of the graph to be analyzed . The [ data ] type is [ bool ] : It will tell if the vertex is reachable from the start vertex . The [ equal ] operation for [ bool ] is simply structural equality ; the [ join ] operation is logical or . The [ analyze ] function is very simple , too : If the predecessor vertex is reachable , so is the successor vertex of the edge . To use the analysis , an instance of a graph [ g ] is required . For this analysis a predicate [ is_root_vertex : G.E.vertex - > bool ] is required to initialize the reachability of the root vertex to [ true ] and of all other vertices to [ false ] . { [ let g = ... let result = Reachability.analyze is_root_vertex g ] } The [ result ] is a map of type [ G.E.vertex - > bool ] that can be queried for every vertex to tell if the vertex is reachable from the root vertex . @author @see " Introduction to Lattices and Order " B. A. Davey and , Cambridge University Press , 2002 @see " Fixed Point Theory " and , 2003 @see " Principles of Program Analysis " , and , Springer , 2005 @see " Ubersetzerbau 3 : Analyse und Transformation " and , Springer , 2010 This module makes writing data-flow analysis easy. One of the simplest fixpoint analysis is that of reachability. Given a directed graph module [G], its analysis can be implemented as follows: {[ module Reachability = Graph.Fixpoint.Make(G) (struct type vertex = G.E.vertex type edge = G.E.t type g = G.t type data = bool let direction = Graph.Fixpoint.Forward let equal = (=) let join = (||) let analyze _ = (fun x -> x) end) ]} The types for [vertex], [edge] and [g] are those of the graph to be analyzed. The [data] type is [bool]: It will tell if the vertex is reachable from the start vertex. The [equal] operation for [bool] is simply structural equality; the [join] operation is logical or. The [analyze] function is very simple, too: If the predecessor vertex is reachable, so is the successor vertex of the edge. To use the analysis, an instance of a graph [g] is required. For this analysis a predicate [is_root_vertex : G.E.vertex -> bool] is required to initialize the reachability of the root vertex to [true] and of all other vertices to [false]. {[ let g = ... let result = Reachability.analyze is_root_vertex g ]} The [result] is a map of type [G.E.vertex -> bool] that can be queried for every vertex to tell if the vertex is reachable from the root vertex. @author Markus W. Weissmann @see "Introduction to Lattices and Order" B. A. Davey and H. A. Priestley, Cambridge University Press, 2002 @see "Fixed Point Theory" Andrzej Granas and James Dugundji, Springer, 2003 @see "Principles of Program Analysis" Flemming Nielson, Hanne Riis Nielson and Chris Hankin, Springer, 2005 @see "Ubersetzerbau 3: Analyse und Transformation" Reinhard Wilhelm and Helmut Seidl, Springer, 2010 *) (** Minimal graph signature for work list algorithm *) module type G = sig type t module V : Sig.COMPARABLE module E : sig type t val dst : t -> V.t val src : t -> V.t end val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a val succ_e : t -> V.t -> E.t list val pred_e : t -> V.t -> E.t list val succ : t -> V.t -> V.t list val pred : t -> V.t -> V.t list end type direction = Forward | Backward (** Type of an analysis *) module type Analysis = sig type data (** information stored at each vertex *) type edge (** type of edges of the underlying graph *) type vertex (** type of vertices of the underlying graph *) type g (** type of the underlying graph *) val direction : direction (** the direction of the analysis *) val join : data -> data -> data (** operation how to join data when paths meet *) val equal : data -> data -> bool (** predicate to determine the fixpoint *) val analyze : edge -> data -> data * the actual analysis of one edge ; provided the edge and the incoming data , it needs to compute the outgoing data data, it needs to compute the outgoing data *) end module Make (G : G) (A : Analysis with type g = G.t with type edge = G.E.t with type vertex = G.V.t) : sig val analyze : (G.V.t -> A.data) -> A.g -> (G.V.t -> A.data) (** [analyze f g] computes the fixpoint on the given graph using the work list algorithm. Beware that a misconstructed Analysis will not terminate! [f] is used to create the initial analysis data. The function returned is a map to see what data was computed for which node. Beware of applying function [analyze] partially, to arguments [f] and [g] only. The result is a function that is to be used to query the result of the analysis. *) end
null
https://raw.githubusercontent.com/backtracking/ocamlgraph/1c028af097339ca8bc379436f7bd9477fa3a49cd/src/fixpoint.mli
ocaml
************************************************************************ This software is free software; you can redistribute it and/or described in file LICENSE. This software 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. ************************************************************************ * Minimal graph signature for work list algorithm * Type of an analysis * information stored at each vertex * type of edges of the underlying graph * type of vertices of the underlying graph * type of the underlying graph * the direction of the analysis * operation how to join data when paths meet * predicate to determine the fixpoint * [analyze f g] computes the fixpoint on the given graph using the work list algorithm. Beware that a misconstructed Analysis will not terminate! [f] is used to create the initial analysis data. The function returned is a map to see what data was computed for which node. Beware of applying function [analyze] partially, to arguments [f] and [g] only. The result is a function that is to be used to query the result of the analysis.
: a generic graph library for OCaml Copyright ( C ) 2004 - 2010 , and modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking Copyright ( c ) 2010 - 2012 Technische Universitaet Muenchen * < > * All rights reserved . * Markus W. Weissmann <> * All rights reserved. *) * Fixpoint computation implemented using the work list algorithm . This module makes writing data - flow analysis easy . One of the simplest fixpoint analysis is that of reachability . Given a directed graph module [ G ] , its analysis can be implemented as follows : { [ module Reachability = Graph . . Make(G ) ( struct type vertex = G.E.vertex type edge = = G.t type data = bool let direction = Graph . . Forward let equal = ( =) let join = ( || ) let analyze _ = ( fun x - > x ) end ) ] } The types for [ vertex ] , [ edge ] and [ g ] are those of the graph to be analyzed . The [ data ] type is [ bool ] : It will tell if the vertex is reachable from the start vertex . The [ equal ] operation for [ bool ] is simply structural equality ; the [ join ] operation is logical or . The [ analyze ] function is very simple , too : If the predecessor vertex is reachable , so is the successor vertex of the edge . To use the analysis , an instance of a graph [ g ] is required . For this analysis a predicate [ is_root_vertex : G.E.vertex - > bool ] is required to initialize the reachability of the root vertex to [ true ] and of all other vertices to [ false ] . { [ let g = ... let result = Reachability.analyze is_root_vertex g ] } The [ result ] is a map of type [ G.E.vertex - > bool ] that can be queried for every vertex to tell if the vertex is reachable from the root vertex . @author @see " Introduction to Lattices and Order " B. A. Davey and , Cambridge University Press , 2002 @see " Fixed Point Theory " and , 2003 @see " Principles of Program Analysis " , and , Springer , 2005 @see " Ubersetzerbau 3 : Analyse und Transformation " and , Springer , 2010 This module makes writing data-flow analysis easy. One of the simplest fixpoint analysis is that of reachability. Given a directed graph module [G], its analysis can be implemented as follows: {[ module Reachability = Graph.Fixpoint.Make(G) (struct type vertex = G.E.vertex type edge = G.E.t type g = G.t type data = bool let direction = Graph.Fixpoint.Forward let equal = (=) let join = (||) let analyze _ = (fun x -> x) end) ]} The types for [vertex], [edge] and [g] are those of the graph to be analyzed. The [data] type is [bool]: It will tell if the vertex is reachable from the start vertex. The [equal] operation for [bool] is simply structural equality; the [join] operation is logical or. The [analyze] function is very simple, too: If the predecessor vertex is reachable, so is the successor vertex of the edge. To use the analysis, an instance of a graph [g] is required. For this analysis a predicate [is_root_vertex : G.E.vertex -> bool] is required to initialize the reachability of the root vertex to [true] and of all other vertices to [false]. {[ let g = ... let result = Reachability.analyze is_root_vertex g ]} The [result] is a map of type [G.E.vertex -> bool] that can be queried for every vertex to tell if the vertex is reachable from the root vertex. @author Markus W. Weissmann @see "Introduction to Lattices and Order" B. A. Davey and H. A. Priestley, Cambridge University Press, 2002 @see "Fixed Point Theory" Andrzej Granas and James Dugundji, Springer, 2003 @see "Principles of Program Analysis" Flemming Nielson, Hanne Riis Nielson and Chris Hankin, Springer, 2005 @see "Ubersetzerbau 3: Analyse und Transformation" Reinhard Wilhelm and Helmut Seidl, Springer, 2010 *) module type G = sig type t module V : Sig.COMPARABLE module E : sig type t val dst : t -> V.t val src : t -> V.t end val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a val succ_e : t -> V.t -> E.t list val pred_e : t -> V.t -> E.t list val succ : t -> V.t -> V.t list val pred : t -> V.t -> V.t list end type direction = Forward | Backward module type Analysis = sig type data type edge type vertex type g val direction : direction val join : data -> data -> data val equal : data -> data -> bool val analyze : edge -> data -> data * the actual analysis of one edge ; provided the edge and the incoming data , it needs to compute the outgoing data data, it needs to compute the outgoing data *) end module Make (G : G) (A : Analysis with type g = G.t with type edge = G.E.t with type vertex = G.V.t) : sig val analyze : (G.V.t -> A.data) -> A.g -> (G.V.t -> A.data) end
0d88145624d9d74d490667f470f8c2cebab545c5a007e381972c85a86095022f
jvranish/TheExperiment
Lexer.hs
module Language.TheExperiment.Parser.Lexer where import Data.Char import Text.Parsec import Text.Parsec.Expr import qualified Text.Parsec.Token as T import Control.Monad import qualified Control.Monad.Trans.State as S import Language.TheExperiment.AST.Expression type ParserOperator = Operator String Operators (S.State SourcePos) (Expr ()) newtype Operators = Operators [(ParserOperator, Rational)] type EParser a = ParsecT String Operators (S.State SourcePos) a opChars :: Monad m => ParsecT String u m Char opChars = oneOf ":!#$%&*+./<=>?@\\^|-~" upperIdent :: EParser String upperIdent = T.identifier $ T.makeTokenParser $ eLanguageDef { T.identStart = oneOf ['A'..'Z'] } lowerIdent :: EParser String lowerIdent = T.identifier $ T.makeTokenParser $ eLanguageDef { T.identStart = oneOf ['a'..'z'] } liftMp :: (SourcePos -> () -> a -> b) -> EParser a -> EParser b liftMp f = liftM3 f getPosition (return ()) liftM2p :: (SourcePos -> () -> a -> b -> c) -> EParser a -> EParser b -> EParser c liftM2p f = liftM4 f getPosition (return ()) liftM3p :: (SourcePos -> () -> a -> b -> c -> d) -> EParser a -> EParser b -> EParser c -> EParser d liftM3p f = liftM5 f getPosition (return ()) liftM6 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m a6 -> m r liftM6 f m1 m2 m3 m4 m5 m6 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; x5 <- m5; x6 <- m6; return (f x1 x2 x3 x4 x5 x6) } liftM4p :: (SourcePos -> () -> a -> b -> c -> d -> e) -> EParser a -> EParser b -> EParser c -> EParser d -> EParser e liftM4p f = liftM6 f getPosition (return ()) eLanguageDef :: Monad m => T.GenLanguageDef String u m eLanguageDef = T.LanguageDef { T.commentStart = "/*" , T.commentEnd = "*/" , T.commentLine = "//" , T.nestedComments = True , T.identStart = letter <|> char '_' , T.identLetter = alphaNum <|> char '_' , T.opStart = opChars , T.opLetter = opChars , T.reservedOpNames = [] , T.reservedNames = ["block", "def", "if", "else", "elif", "type", "var", "while", "foreign", "return"] , T.caseSensitive = True } lexer :: Monad m => T.GenTokenParser String u m lexer = T.makeTokenParser eLanguageDef parens :: EParser a -> EParser a parens = T.parens lexer operator :: EParser String operator = T.operator lexer identifier :: EParser String identifier = T.identifier lexer lexeme :: EParser a -> EParser a lexeme = T.lexeme lexer comma :: EParser String comma = T.comma lexer whiteSpace :: EParser () whiteSpace = T.whiteSpace lexer commaSep1 :: EParser a -> EParser [a] commaSep1 = T.commaSep1 lexer commaSep :: EParser a -> EParser [a] commaSep = T.commaSep lexer symbol :: String -> EParser String symbol = T.symbol lexer reserved :: String -> EParser () reserved = T.reserved lexer reservedOp :: String -> EParser () reservedOp = T.reservedOp lexer stringLiteral :: EParser String stringLiteral = T.stringLiteral lexer charLiteral :: EParser Char charLiteral = T.charLiteral lexer rational :: EParser Rational rational = liftM (either toRational toRational) (T.naturalOrFloat lexer) number :: Integer -> EParser Char -> EParser Integer number base baseDigit = do{ digits <- many1 baseDigit ; let n = foldl (\x d -> base*x + toInteger (digitToInt d)) 0 digits ; seq n (return n) } float :: EParser Double float = T.float lexer decimal :: EParser Integer decimal = T.decimal lexer octal :: EParser Integer octal = T.octal lexer hexadecimal :: EParser Integer hexadecimal = T.hexadecimal lexer parseLex :: EParser a -> EParser a parseLex p = do whiteSpace x <- p eof return x
null
https://raw.githubusercontent.com/jvranish/TheExperiment/54ca832d2f62a928a992b4c23dadf9653d13a5a7/src/Language/TheExperiment/Parser/Lexer.hs
haskell
module Language.TheExperiment.Parser.Lexer where import Data.Char import Text.Parsec import Text.Parsec.Expr import qualified Text.Parsec.Token as T import Control.Monad import qualified Control.Monad.Trans.State as S import Language.TheExperiment.AST.Expression type ParserOperator = Operator String Operators (S.State SourcePos) (Expr ()) newtype Operators = Operators [(ParserOperator, Rational)] type EParser a = ParsecT String Operators (S.State SourcePos) a opChars :: Monad m => ParsecT String u m Char opChars = oneOf ":!#$%&*+./<=>?@\\^|-~" upperIdent :: EParser String upperIdent = T.identifier $ T.makeTokenParser $ eLanguageDef { T.identStart = oneOf ['A'..'Z'] } lowerIdent :: EParser String lowerIdent = T.identifier $ T.makeTokenParser $ eLanguageDef { T.identStart = oneOf ['a'..'z'] } liftMp :: (SourcePos -> () -> a -> b) -> EParser a -> EParser b liftMp f = liftM3 f getPosition (return ()) liftM2p :: (SourcePos -> () -> a -> b -> c) -> EParser a -> EParser b -> EParser c liftM2p f = liftM4 f getPosition (return ()) liftM3p :: (SourcePos -> () -> a -> b -> c -> d) -> EParser a -> EParser b -> EParser c -> EParser d liftM3p f = liftM5 f getPosition (return ()) liftM6 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m a6 -> m r liftM6 f m1 m2 m3 m4 m5 m6 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; x5 <- m5; x6 <- m6; return (f x1 x2 x3 x4 x5 x6) } liftM4p :: (SourcePos -> () -> a -> b -> c -> d -> e) -> EParser a -> EParser b -> EParser c -> EParser d -> EParser e liftM4p f = liftM6 f getPosition (return ()) eLanguageDef :: Monad m => T.GenLanguageDef String u m eLanguageDef = T.LanguageDef { T.commentStart = "/*" , T.commentEnd = "*/" , T.commentLine = "//" , T.nestedComments = True , T.identStart = letter <|> char '_' , T.identLetter = alphaNum <|> char '_' , T.opStart = opChars , T.opLetter = opChars , T.reservedOpNames = [] , T.reservedNames = ["block", "def", "if", "else", "elif", "type", "var", "while", "foreign", "return"] , T.caseSensitive = True } lexer :: Monad m => T.GenTokenParser String u m lexer = T.makeTokenParser eLanguageDef parens :: EParser a -> EParser a parens = T.parens lexer operator :: EParser String operator = T.operator lexer identifier :: EParser String identifier = T.identifier lexer lexeme :: EParser a -> EParser a lexeme = T.lexeme lexer comma :: EParser String comma = T.comma lexer whiteSpace :: EParser () whiteSpace = T.whiteSpace lexer commaSep1 :: EParser a -> EParser [a] commaSep1 = T.commaSep1 lexer commaSep :: EParser a -> EParser [a] commaSep = T.commaSep lexer symbol :: String -> EParser String symbol = T.symbol lexer reserved :: String -> EParser () reserved = T.reserved lexer reservedOp :: String -> EParser () reservedOp = T.reservedOp lexer stringLiteral :: EParser String stringLiteral = T.stringLiteral lexer charLiteral :: EParser Char charLiteral = T.charLiteral lexer rational :: EParser Rational rational = liftM (either toRational toRational) (T.naturalOrFloat lexer) number :: Integer -> EParser Char -> EParser Integer number base baseDigit = do{ digits <- many1 baseDigit ; let n = foldl (\x d -> base*x + toInteger (digitToInt d)) 0 digits ; seq n (return n) } float :: EParser Double float = T.float lexer decimal :: EParser Integer decimal = T.decimal lexer octal :: EParser Integer octal = T.octal lexer hexadecimal :: EParser Integer hexadecimal = T.hexadecimal lexer parseLex :: EParser a -> EParser a parseLex p = do whiteSpace x <- p eof return x
44b8f5db69b6dadd9489e09d146bc9666b02459e30c9a6d912b1e7d835002a98
informatimago/lisp
invoice.lisp
-*- mode : lisp ; coding : utf-8 -*- ;;;;**************************************************************************** FILE : invoices.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp USER - INTERFACE : Common - Lisp ;;;;DESCRIPTION ;;;; ;;;; This package exports classes and functions used for accounting: ;;;; invoices, customers/providers, movements, taxes... ;;;; < PJB > < > MODIFICATIONS 2004 - 10 - 17 < PJB > Completed conversion to Common - Lisp . 2004 - 10 - 11 < PJB > Converted to Common - Lisp from emacs lisp . 2002 - 09 - 09 < PJB > Added generate - invoice . ? ? < PJB > Creation . ;;;; Currencies are handled, but multicurrency accounting is not. ;;;;LEGAL AGPL3 ;;;; Copyright 1990 - 2016 ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details . ;;;; You should have received a copy of the GNU Affero General Public License ;;;; along with this program. If not, see </> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.INVOICE.INVOICE" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ISO4217") #+mocl (:shadowing-import-from "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING" "*TRACE-OUTPUT*" "*LOAD-VERBOSE*" "*LOAD-PRINT*" "ARRAY-DISPLACEMENT" "CHANGE-CLASS" "COMPILE" "COMPLEX" "ENSURE-DIRECTORIES-EXIST" "FILE-WRITE-DATE" "INVOKE-DEBUGGER" "*DEBUGGER-HOOK*" "LOAD" "LOGICAL-PATHNAME-TRANSLATIONS" "MACHINE-INSTANCE" "MACHINE-VERSION" "NSET-DIFFERENCE" "RENAME-FILE" "SUBSTITUTE-IF" "TRANSLATE-LOGICAL-PATHNAME" "PRINT-NOT-READABLE" "PRINT-NOT-READABLE-OBJECT") (:export "LOAD-JOURNAL" "JOURNAL-ENTRY" "LINE" "PERSON" "GENERATE" "TRIMESTRE" "MAKE-BANK-REFERENCE" "JOURNAL" "MOVEMENT" "INVOICE-SET" "INVOICE" "INVOICE-LINE" "FISCAL-PERSON" "BANK-REFERENCE" "PJB-OBJECT" "*JOURNAL*" "*INVOICE-SET*" "*CURRENCY-READTABLE*") (:shadow "ABS" "ZEROP" "ROUND" "/=" "=" ">=" ">" "<=" "<" "/" "*" "-" "+") (:documentation " This package exports classes and functions used for accounting: invoices, customers/providers, movements, taxes... License: AGPL3 Copyright Pascal J. Bourguignon 1990 - 2012 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </> ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.INVOICE.INVOICE") ;;; parameters (defparameter *vat-rates* '(0/100 4/100 7/100 16/100) "The valid VAT rates in the country of the user.") (defparameter *invoice-directory-path* '(:absolute "HOME""PASCAL""JOBS""FREE-LANCE""INVOICES") "The directory where the generated invoices are stored.") (defparameter *invoice-set-file-path* (make-pathname :directory *invoice-directory-path* :name "INVOICES" :type "DATA") "Path to the file where invoices are stored.") ;;; global variables: (defparameter *default-currency* (find-currency :eur) "The currency used when no prefix currency code is given to #m") (defparameter *max-movement-amount* nil "The maximum movement amount (ht or ttc, expressed in the currency of the movement (weak, I know).") (defparameter *invoice-set* nil "Current Invoice Set (instance of INVOICE-SET).") ;;invoice-set (defparameter *journal* nil "Current Journal (instance of JOURNAL).") ;;;--------------------------------------------------------------------- (defgeneric abs (self)) (defgeneric add-entry (self entry)) (defgeneric add-invoice (self invoice)) (defgeneric add-line (self line)) (defgeneric add-person (self person &optional fisc)) (defgeneric amount-ht (self)) (defgeneric compute-totals (self)) (defgeneric credit-ht (self)) (defgeneric credit-vat (self)) (defgeneric currency (self)) (defgeneric amount-magnitude (self)) (defgeneric debit-ht (self)) (defgeneric debit-vat (self)) (defgeneric debit-vat-corriente (self)) (defgeneric debit-vat-inversion (self)) (defgeneric ensure-sorted (self)) (defgeneric extract (self year trimestre)) (defgeneric generate (invoice &key stream verbose language &allow-other-keys) (:documentation " DO: Generate this invoice into a file in the directory *INVOICE-DIRECTORY-PATH*. RETURN: The path to the file generated. ")) (defgeneric get-invoice-with-issuer-and-number (self issuer-fiscal-id invoice-number)) (defgeneric get-person-with-fiscal-id (self fiscal-id)) (defgeneric invoices (self)) (defgeneric is-credit (self)) (defgeneric is-refund (self)) (defgeneric negativep (self)) (defgeneric positivep (self)) (defgeneric reset (self)) (defgeneric round (self &optional divisor)) (defgeneric vat-rate (self)) (defgeneric write-invoice-file (self &key language)) (defgeneric zerop (self)) ;;;--------------------------------------------------------------------- Monetary Amounts & Currency Syntax ;;;--------------------------------------------------------------------- ;; Since floating point arithmetic is not adapted to accounting, ;; we will use integers for monetary amounts, and percentages will be expressed as rationnals : 16 % = 16/100 ;; 123.45 ¤ = 12345 ¢ = # 978m123.45 ;; ;; In addition monetary amounts are tagged with a currency, and ;; arithmetic operations are type-restricted. ;; ;; The reader syntax is: # [currency-code] m|M [+|-] digit+ [ . digit* ] ;; The currency code must be a numeric code of a currency found ;; in (com.informatimago.common-lisp.cesarum.iso4217:get-currencies), ;; otherwise a read-time error is issued. ;; When the currency-code is not present, the currency designated ;; by *DEFAULT-CURRENCY* is used. ;; The number of digits after the decimal point must not be superior ;; to the minor unit attribute of the currency. ;; The value is converted to an integer number of minor unit and ;; the read result is an AMOUNT structure gathering the currency ;; and the value. ;; ;; The operations defined on AMOUNT values are: ;; ;; c: amount* --> boolean ;; with c in { <, <=, >, >=, =, /= }. ;; ;; +: amount* --> amount ;; -: amount* --> amount * : amount X real * -- > amount ( commutatif and associatif ) ;; /: amount X real* --> amount (not commutatif and not associatif) ;; [ set * = closure of the set ] ;; ;; For now, all these operations work only when the currency of all amount ;; involved is the same. ;; ;; These Common-Lisp operators are shadowed, and functions are defined for ;; them, that extend the normal numeric functions for amounts. ;; ;; The AMOUNT structure has a printer that prints different format ;; depending on the *PRINT-READABLY*. It uses the reader syntax defined above when * PRINT - READABLY * is true , or a " ~V$ ~3A " format printing ;; the value followed by the alphabetic code of the currency. (defstruct (amount (:predicate amountp) #|(:PRINT-OBJECT PRINT-OBJECT)|#) "An amount of money." currency (value 0 :type integer)) (defmethod print-object ((self amount) stream) (if *print-readably* (format stream "#~DM~V$" (currency-numeric-code (amount-currency self)) (currency-minor-unit (amount-currency self)) (amount-magnitude self)) (format stream "~V$ ~A" (currency-minor-unit (amount-currency self)) (amount-magnitude self) (currency-alphabetic-code (amount-currency self)))) self) ;;PRINT-OBJECT (defmethod currency ((self number)) (declare (ignorable self)) nil) (defmethod currency ((self amount)) (amount-currency self)) (defmethod amount-magnitude ((self number)) self) (defmethod amount-magnitude ((self amount)) " RETURN: A real equal to the value of the amount. " (* (amount-value self) (aref #(1 1/10 1/100 1/1000 1/10000) (currency-minor-unit (amount-currency self))))) (defparameter *zero-amounts* (make-hash-table :test (function eq)) "A cache of 0 amount for the various currencies used.") (defun amount-zero (currency) " RETURN: A null amount of the given currency. " (let ((zero (gethash (find-currency currency) *zero-amounts*))) (unless zero (setf zero (setf (gethash (find-currency currency) *zero-amounts*) (make-amount :currency (find-currency currency) :value 0)))) zero)) ;;AMOUNT-ZERO (defmethod abs ((self number)) (common-lisp:abs self)) (defmethod abs ((self amount)) (make-amount :currency (amount-currency self) :value (common-lisp:abs (amount-value self)))) (defmethod zerop ((self number)) (common-lisp:zerop self)) (defmethod zerop ((self amount)) (common-lisp:zerop (amount-value self))) (defmethod positivep ((self number)) (common-lisp:<= 0 self)) (defmethod positivep ((self amount)) (common-lisp:<= 0 (amount-value self))) (defmethod negativep ((self number)) (common-lisp:> 0 self)) (defmethod negativep ((self amount)) (common-lisp:> 0 (amount-value self))) (defmethod round ((self real) &optional (divisor 1)) (common-lisp:round self divisor)) (defmethod round ((self amount) &optional (divisor 1)) (make-amount :currency (amount-currency self) :value (common-lisp:round (amount-value self) divisor))) (defun euro-round (magnitude currency) " MAGNITUDE: A REAL CURRENCY: The currency of the amount. RETURN: An integer in minor unit rounded according to the Euro rule." (let ((rounder (aref #(1 1/10 1/100 1/1000 1/10000) (currency-minor-unit currency)))) (round (+ magnitude (* (signum magnitude) (/ rounder 10))) rounder))) (defun euro-value-round (value) " VALUE: A REAL CURRENCY: The currency of the amount. RETURN: An integer in minor unit rounded according to the Euro rule." EURO - VALUE - ROUND ;; (with-output-to-string (out) ( dolist ( * print - readably * ' ( t nil ) ) ( print ( make - amount : currency ( find - currency : EUR ) : value 12345 ) out ) ) ) (define-condition multi-currency-error (error) ((format-control :initarg :format-control :accessor format-control) (format-arguments :initarg :format-arguments :accessor format-arguments) (operation :initarg :operation :accessor multi-currency-error-operation) (amounts :initarg :amounts :accessor multi-currency-error-amounts)) (:report (lambda (self stream) (let ((*print-pretty* nil)) (format stream "~A: (~A ~{~A~^, ~})~%~A" (class-name (class-of self)) (multi-currency-error-operation self) (multi-currency-error-amounts self) (apply (function format) nil (format-control self) (format-arguments self))))))) (defun mcerror (operation amounts format-control &rest format-arguments) (error 'multi-currency-error :operation operation :amounts amounts :format-control format-control :format-arguments format-arguments)) (defun types-of-arguments (args) (labels ((display (item) (cond ((symbolp item) (symbol-name item)) ((atom item) item) (t (mapcar (function display) item))))) (mapcar (lambda (arg) (display (type-of arg))) args))) (defmacro make-comparison-method (name operator) " DO: Generate a comparison method. " `(defun ,name (&rest args) (cond ((every (function numberp) args) (apply (function ,operator) args)) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (apply (function ,operator) (mapcar (function amount-value) args)) (mcerror ',name args "Comparison not implemented yet.")))) (t (mcerror ',name args "Incompatible types: ~A" (types-of-arguments args)))))) (make-comparison-method < common-lisp:<) (make-comparison-method <= common-lisp:<=) (make-comparison-method > common-lisp:>) (make-comparison-method >= common-lisp:>=) (make-comparison-method = common-lisp:=) (make-comparison-method /= common-lisp:/=) (defun + (&rest args) " DO: A Generic addition with numbers or amounts. " (setf args (remove 0 args :key (lambda (x) (if (typep x 'amount) (amount-value x) x)) :test (function equal))) (cond ((every (function numberp) args) (apply (function common-lisp:+) args)) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (make-amount :currency currency :value (apply (function common-lisp:+) (mapcar (function amount-value) args))) (mcerror '+ args "Addtion not implemented yet.")))) (t (mcerror '+ args "Incompatible types: ~A" (types-of-arguments args))))) (defun - (&rest args) " DO: A Generic substraction with numbers or amounts. " (setf args (cons (car args) (remove 0 (cdr args) :key (lambda (x) (if (typep x 'amount) (amount-value x) x)) :test (function equal)))) (cond ((every (function numberp) args) (apply (function common-lisp:-) args)) ((zerop (first args)) (- (apply (function +) (rest args)))) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (make-amount :currency currency :value (apply (function common-lisp:-) (mapcar (function amount-value) args))) (mcerror '- args "Substraction not implemented yet.")))) (t (mcerror '- args "Incompatible types: ~A" (types-of-arguments args))))) (defun * (&rest args) " DO: A Generic multiplication with numbers or amounts. " (if (every (function numberp) args) (apply (function common-lisp:*) args) (let ((p (position-if (function amountp) args))) (cond ((or (null p) (not (every (lambda (x) (or (amountp x)(realp x))) args))) (mcerror '* args "Incompatible types: ~A" (types-of-arguments args))) ((position-if (function amountp) args :start (1+ p)) (mcerror '* args "Cannot multiply moneys.")) (t (make-amount :currency (amount-currency (nth p args)) :value (euro-value-round (apply (function common-lisp:*) (mapcar (lambda (x) (if (amountp x) (amount-value x) x)) args))))))))) (defun / (&rest args) " DO: A Generic division with numbers or amounts. " (cond ((every (function numberp) args) (apply (function common-lisp:/) args)) ((and (cadr args) two arguments (amountp (first args)) (amountp (second args))) ; both amounts ;; then return a number: (/ (amount-value (first args)) (amount-value (second args)))) ((and (amountp (car args)) (cdr args) ;; cannot take the inverse of an amount! (every (function realp) (cdr args))) (make-amount :currency (amount-currency (car args)) :value (euro-value-round (apply (function common-lisp:/) (amount-value (car args)) (cdr args))))) (t (mcerror '/ args "Incompatible types: ~A" (types-of-arguments args))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun currency-syntax (stream char infix) (declare (ignore char)) (let ((currency (or infix *default-currency*))) (setf currency (find-currency currency)) (unless currency (mcerror 'currency-syntax (or infix *default-currency*) "Invalid currency designator ~S" (or infix *default-currency*))) (assert (<= 0 (currency-minor-unit currency) 4) () "Unexpected minor unit for currency: ~S" currency) (let ((left '()) (right '()) (dot nil) (sign 1)) (let ((ch (read-char stream nil nil))) (cond ((null ch)) ((char= ch (character "-" )) (setf sign -1)) ((char= ch (character "+" ))) (t (unread-char ch stream)))) (loop for ch = (peek-char nil stream nil nil) while (and ch (digit-char-p ch)) do (push (read-char stream) left) finally (setf dot (and ch (char= (character ".") ch)))) (when (zerop (length left)) (mcerror 'currency-syntax currency "Missing an amount after #M")) (when dot (when (zerop (currency-minor-unit currency)) (mcerror 'currency-syntax currency "There is no decimal point in ~A" (currency-name currency))) (read-char stream) ;; eat the dot (loop for ch = (peek-char nil stream nil nil) while (and ch (digit-char-p ch)) do (push (read-char stream) right)) (when (< (currency-minor-unit currency) (length right)) (mcerror 'currency-syntax currency "Too many digits after the decimal point for ~A" (currency-name currency)))) (loop for i from (length right) below (currency-minor-unit currency) do (push (character "0") right)) (make-amount :currency currency ;; (WITH-STANDARD-IO-SYNTAX ( INTERN ( CURRENCY - ALPHABETIC - CODE CURRENCY ) " KEYWORD " ) ) :value (* sign (parse-integer (map 'string (function identity) (nreverse (nconc right left))))) : divisor ( AREF # ( 1 10 100 1000 10000 ) ;; (CURRENCY-MINOR-UNIT CURRENCY)) )))) ;;currency-syntax (defparameter *currency-readtable* (copy-readtable *readtable*) "The readtable used to read currencies.") (set-dispatch-macro-character #\# #\M (function currency-syntax) *currency-readtable*) (set-dispatch-macro-character #\# #\M (function currency-syntax) *currency-readtable*) ) ;;eval-when ;; (let ((*readtable* *currency-readtable*)) ;; (mapcar ;; (lambda (s) ;; (let ((cnt 0)) ;; (list s ;; (handler-case (multiple-value-bind (r l) (read-from-string s) ( setf cnt l ) r ) ;; (error (err) ;; (apply (function format) nil #||*error-output*||# ;; (simple-condition-format-control err) ;; (simple-condition-format-arguments err)))) ( subseq s cnt ) ) ) ) ' ( " # M123.45 " " # 840m123.45 " " # 548m123 " " # 788m123.456 " " # 840m123 " " # 840m123.xyz " " # 840m123.4 " " # 840m123.45 " " # 840m123.456 " " # 197M123.45 " " # 548m123 " " # 548m123.xyz " " # 548m123.4 " " # 548m123.45 " " # 548m123.456 " " # 788m123 " " # 788m123.xyz " " # 788m123.4 " " # 788m123.45 " " # 788m123.456 " " # 788m123.4567 " " # 788m123.45678 " ) ) ) ;; ( let ( ( * readtable * * currency - readtable * ) ) ( read - from - string " # 197M123.45 " ) ) ;; (let ((*readtable* *currency-readtable*)) (read-from-string "#M960" )) ( let ( ( * readtable * * currency - readtable * ) ) ( read - from - string " # 978M978 " ) ) ;;;--------------------------------------------------------------------- ;;; DATE ;;;--------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +seconds-in-a-day+ (cl:* 24 3600) "Number of seconds in a day.") );;eval-when (defstruct (date #|(:PRINT-OBJECT PRINT-OBJECT)|#) year month day) (defmethod print-object ((self date) stream) (format stream "~4,'0D-~2,'0D-~2,'0D" (date-year self) (date-month self) (date-day self)) self) (defun date-from-string (yyyy-mm-dd) (let ((ymd (split-string yyyy-mm-dd "-"))) (make-date :year (parse-integer (nth 0 ymd)) :month (parse-integer (nth 1 ymd)) :day (parse-integer (nth 2 ymd))))) ;;DATE-FROM-STRING (defun date-after (a b) (or (> (date-year a) (date-year b)) (and (= (date-year a) (date-year b)) (or (> (date-month a) (date-month b)) (and (= (date-month a) (date-month b)) (> (date-day a) (date-day b))))))) ;;DATE-AFTER (defun date-in-year-trimestre (date year trimestre) " RETURN: Whether the given date is within the given YEAR and TRIMESTRE. " (and (= (date-year date) year) (member (date-month date) (elt '((1 2 3) (4 5 6) (7 8 9) (10 11 12)) (- trimestre 1))))) ;;DATE-IN-YEAR-TRIMESTRE (defun calendar-current-date () " RETURN: The date today. " (multiple-value-bind (se mi ho da mo ye dw ds zo) (get-decoded-time) (declare (ignore se mi ho dw ds zo)) (make-date :year ye :month mo :day da))) ;;CALENDAR-CURRENT-DATE (defun local-time-zone () " RETURN: The local time zone, as returned by GET-DECODED-TIME. " (multiple-value-bind (se mi ho da mo ye dw ds zone) (get-decoded-time) (declare (ignore se mi ho da mo ye dw ds)) zone)) ;;LOCAL-TIME-ZONE (defun universal-time-to-date (utime) " RETURN: the given universal time formated in the ISO8601 YYYY-MM-DD format. " (multiple-value-bind (se mi ho da mo ye dw ds zo) (decode-universal-time utime 0) (declare (ignore se mi ho dw ds zo)) (format nil "~4,'0D-~2,'0D--~2,'0D" ye mo da))) ;;UNIVERSAL-TIME-TO-DATE (defun date-to-universal-time (date-string) " DATE-STRING: A date in the ISO8601 format 'YYYY-MM-DD'. RETURN: A number of seconds since 1900-01-01 00:00:00 GMT. " (let ((ymd (split-string date-string "-"))) (encode-universal-time 0 0 0 (parse-integer (third ymd)) (parse-integer (second ymd)) (parse-integer (first ymd)) 0))) ;;DATE-TO-UNIVERSAL-TIME (defun date-format (utime &key (language :en)) (multiple-value-bind (se mi ho day month year dw ds zo) (decode-universal-time utime 0) (declare (ignore se mi ho dw ds zo)) (case language ((:fr) (format nil "~D~A ~A ~D" day (if (= 1 day) "er" "") (aref #("Janvier" "Février" "Mars" "Avril" "Mai" "Juin" "Juillet" "Août" "Septembre" "Octobre" "Novembre" "Décembre") (1- month)) year)) ((:es) (format nil "~D de ~A de ~D" day (aref #("Enero" "Febrero" "Marzo" "Abril" "Mayo" "Junio" "Julio" "Augosto" "Septiembre" "Octobre" "Noviembre" "Diciembre") (1- month)) year)) (otherwise (format nil "~A ~D~A, ~D" (aref #("January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December") (1- month)) day (case (mod day 10) ((1) "st") ((2) "nd") ((3) "rd") (otherwise "th")) year))))) ;;;--------------------------------------------------------------------- ;;; Pjb-Object ;;;--------------------------------------------------------------------- (defclass pjb-object () ((object-id :initform nil :initarg :object-id :accessor object-id :type (or null string) :documentation "The user-level ID of this object.")) (:documentation "This is a root class for my classes.")) ;;;--------------------------------------------------------------------- ;;; BANK-REFERENCE ;;;--------------------------------------------------------------------- (defclass bank-reference (pjb-object) ((bank-name :initform nil :initarg :bank-name :accessor bank-name :type (or null string) :documentation "The name of the bank.") (bank-address :initform nil :initarg :bank-address :accessor bank-address :type (or null string) :documentation "The address of the bank.") (branch-name :initform nil :initarg :branch-name :accessor branch-name :type (or null string) :documentation "The name of the branch.") (swift-code :initform nil :initarg :swift-code :accessor swift-code :type (or null string) :documentation "The swift-code of the bank.") (account-number :initform nil :initarg :account-number :accessor account-number :type (or null string) :documentation "The account number. It should be an IBAN in Europe.") (beneficiary-name :initform nil :initarg :beneficiary-name :accessor beneficiary-name :type (or null string) :documentation "The beneficiary's name.")) (:documentation "A bank account reference.")) ;;BANK-REFERENCE ;;;--------------------------------------------------------------------- ;;; FISCAL-PERSON ;;;--------------------------------------------------------------------- (defclass fiscal-person (pjb-object) ((fiscal-id :initform nil :initarg :fiscal-id :accessor fiscal-id :type (or null string) :documentation "The fiscal ID of the person, ie. the European fiscal ID.") (name :initform nil :initarg :name :accessor name :type (or null string) :documentation "The name of the person.") (address :initform nil :initarg :address :accessor address :type (or null string) :documentation "The address of the person.") (phone :initform nil :initarg :phone :accessor phone :type (or null string) :documentation "The phone number of the person.") (fax :initform nil :initarg :fax :accessor fax :type (or null string) :documentation "The fax number of the person.") (web :initform nil :initarg :web :accessor web :type (or null string) :documentation "The URL of the web site of this person.") (email :initform nil :initarg :email :accessor email :type (or null string) :documentation "The fax number of the person.") (bank-reference :initform nil :initarg :bank-reference :accessor bank-reference :type (or null bank-reference) :documentation "The bank reference of the person.") (language :initform :es :initarg :language :accessor language :type symbol ;; :es :en :fr :de :documentation "The language (two-letter code) used by this person.") (fisc :initform nil :initarg :fisc :accessor fisc :type boolean :documentation "Whether this person is the fiscal administration.")) (:documentation "A person (physical or moral) identified by a fiscal identification number." )) ;;FISCAL-PERSON (defmethod initialize-instance :after ((self fiscal-person) &rest arguments) (unless (getf arguments :object-id) (setf (object-id self) (or (fiscal-id self) (name self)))) self) ;;;--------------------------------------------------------------------- Invoice - Line ;;;--------------------------------------------------------------------- (defclass invoice-line (pjb-object) ((description :initform "" :initarg :description :accessor description :type string :documentation "The description of this line.") (currency :initform (find-currency :eur) :initarg :currency :accessor currency :type symbol :documentation "The currency of this line.") (amount-ht :initform (amount-zero *default-currency*) :initarg :amount-ht :accessor amount-ht :type amount :documentation "The amount excluding the taxes of this line.") (vat-rate :initform 0/100 :initarg :vat-rate :accessor vat-rate :type ratio :documentation "The rate of VAT for this line (0.00 <= vat-rate <= 0.50).") (amount-vat :initform (amount-zero *default-currency*) :initarg :amount-vat :accessor amount-vat :type amount :documentation "The amount of VAT for this line. ( = amount-ht * (1+vat-rate) )") (amount-ttc :initform (amount-zero *default-currency*) :initarg :amount-ttc :accessor amount-ttc :type amount :documentation "The amount including the taxes of this line.")) (:documentation "An Invoice Line.")) ;;;--------------------------------------------------------------------- ;;; INVOICE ;;;--------------------------------------------------------------------- (defclass invoice (pjb-object) ((date :initform nil :initarg :date :accessor date :type (or null string) :documentation "'YYYY-MM-DD' The date of the invoice.") (issuer-fiscal-id :initform nil :initarg :issuer-fiscal-id :accessor issuer-fiscal-id :type (or null string) :documentation "The fiscal ID of the issuer of this invoice.") (invoice-number :initform nil :initarg :invoice-number :accessor invoice-number :type (or null string) :documentation "The invoice number.") (payer-fiscal-id :initform nil :initarg :payer-fiscal-id :accessor payer-fiscal-id :type (or null string) :documentation "The fiscal ID of the payer of this invoice.") (title :initform "" :initarg :title :accessor title :type (or null string) :documentation "The title of this invoice.") (currency :initform (find-currency :eur) :initarg :currency :accessor currency :type symbol :documentation "The currency of this invoice.") (lines :initform nil :accessor lines :type list :documentation "(list of Invoice-Line) The line items of this invoice.") (total-ht :initform (amount-zero *default-currency*) :accessor total-ht :type amount :documentation "The total excluding taxes of this invoice.") (total-vat :initform (amount-zero *default-currency*) :accessor total-vat :type amount :documentation "The total of VAT.") (total-ttc :initform (amount-zero *default-currency*) :accessor total-ttc :type amount :documentation "The total including taxes of this invoice.") ) (:documentation "An invoice, either outgoing or incoming. The amounts of the invoice may be negative when it's a refund.")) (defmethod initialize-instance :after ((self invoice) &rest arguments) (unless (getf arguments :object-id) (setf (object-id self) (concatenate 'string (issuer-fiscal-id self) ":" (invoice-number self)))) self) ;;;--------------------------------------------------------------------- ;;; INVOICE-SET ;;;--------------------------------------------------------------------- (defclass invoice-set (pjb-object) ((fiscal-id :initform nil :initarg :fiscal-id :accessor fiscal-id :type (or null string) :documentation "The fiscal id of the owner of this invoice set.") (fisc-fiscal-ids :initform nil :initarg :fisc-fiscal-ids :accessor fisc-fiscal-ids :type list :documentation "(list of string) List of fiscal-id of fisc entity. An invoice issued by on of these entities is actually a tax.") (persons :initform nil :initarg :persons :accessor persons :type list :documentation "The list of known Fiscal-Person.") (invoices :initform nil :initarg :invoices :accessor invoices :type list :documentation "The list of known Invoices.") ) (:documentation "This class gather all the data sets about invoices and fiscal persons.") ) ;;INVOICE-SET ;;;--------------------------------------------------------------------- ;;; INVOICE-LINE ;;;--------------------------------------------------------------------- ;; check = ( a-ttc | a-ht ) & ( a-vat | vat-rate ) ;; error = ~check | ( ~a-ttc & ~a-ht ) | ( ~a-vat & ~vat-rate ) ) ;; ;; (insert ;; (carnot '( a-ttc a-ht a-vat vat-rate check) ;; '((check . (lambda (a-ttc a-ht a-vat vat-rate check) ;; (and (or a-ttc a-ht) (or a-vat vat-rate)) ;; )) ;; (error . (lambda (a-ttc a-ht a-vat vat-rate check) ;; (or (not check) ;; (and (not a-ttc) (not a-ht)) ;; (and (not a-vat) (not vat-rate))) ))))) ;; ;; +-------+------+-------+----------+-------+-------+-------+ ;; | a-ttc | a-ht | a-vat | vat-rate | check | check | error | ;; +-------+------+-------+----------+-------+-------+-------+ | OUI | OUI | OUI | OUI | OUI | X | . | | OUI | OUI | OUI | OUI | NON | X | X | ;; | OUI | OUI | OUI | NON | OUI | X | . | ;; | OUI | OUI | OUI | NON | NON | X | X | | OUI | OUI | NON | OUI | OUI | X | . | | OUI | OUI | NON | OUI | NON | X | X | ;; | OUI | OUI | NON | NON | OUI | . | X | ;; | OUI | OUI | NON | NON | NON | . | X | | OUI | NON | OUI | OUI | OUI | X | . | | OUI | NON | OUI | OUI | NON | X | X | ;; | OUI | NON | OUI | NON | OUI | X | . | ;; | OUI | NON | OUI | NON | NON | X | X | | OUI | NON | NON | OUI | OUI | X | . | | OUI | NON | NON | OUI | NON | X | X | ;; | OUI | NON | NON | NON | OUI | . | X | ;; | OUI | NON | NON | NON | NON | . | X | | NON | OUI | OUI | OUI | OUI | X | . | | NON | OUI | OUI | OUI | NON | X | X | ;; | NON | OUI | OUI | NON | OUI | X | . | ;; | NON | OUI | OUI | NON | NON | X | X | | NON | OUI | NON | OUI | OUI | X | . | | NON | OUI | NON | OUI | NON | X | X | ;; | NON | OUI | NON | NON | OUI | . | X | ;; | NON | OUI | NON | NON | NON | . | X | | NON | NON | OUI | OUI | OUI | . | X | | NON | NON | OUI | OUI | NON | . | X | ;; | NON | NON | OUI | NON | OUI | . | X | ;; | NON | NON | OUI | NON | NON | . | X | | NON | NON | NON | OUI | OUI | . | X | | NON | NON | NON | OUI | NON | . | X | ;; | NON | NON | NON | NON | OUI | . | X | ;; | NON | NON | NON | NON | NON | . | X | ;; +-------+------+-------+----------+-------+-------+-------+ (defmethod initialize-instance ((self invoice-line) &key object-id description currency amount-ht vat-rate amount-vat amount-ttc &allow-other-keys) " DO: Checks that the values for the fields are within limits. " (when (or (and (not amount-ttc) (not amount-ht)) (and (not amount-vat) (not vat-rate))) (error "Not enought amount data defined for this line ~S." self)) (unless amount-ttc (setf amount-ttc (cond (amount-vat (+ amount-ht amount-vat)) (vat-rate (* amount-ht (+ 1 vat-rate))) ;; last case should not occur. (t (if (zerop vat-rate) amount-ht (/ (* amount-vat (+ 1 vat-rate)) vat-rate)))))) (unless amount-ht (setf amount-ht (cond (amount-vat (- amount-ttc amount-vat)) (vat-rate (/ amount-ttc (+ 1 vat-rate))) ;; last case should not occur. (t (if (zerop vat-rate) amount-ttc (/ amount-vat vat-rate)))))) (unless amount-vat (setf amount-vat (- amount-ttc amount-ht))) (unless vat-rate (setf vat-rate (if (zerop (amount-magnitude amount-ht)) 0 (/ (round (* (/ (amount-magnitude amount-vat) (amount-magnitude amount-ht)) 100)) 100)))) (when (null currency) (setf currency (currency amount-ttc))) ;; (check-vat amount-ttc amount-ht amount-vat vat-rate) (call-next-method self :object-id object-id :description description :currency currency :amount-ht amount-ht :vat-rate vat-rate :amount-vat amount-vat :amount-ttc amount-ttc)) ;;;--------------------------------------------------------------------- ;;; INVOICE ;;;--------------------------------------------------------------------- (defmethod compute-totals ((self invoice)) " DO: Compute the totals. " (let* ((th (amount-zero (currency self))) (tv th) (tt th)) (dolist (line (lines self)) (setf th (+ th (amount-ht line)) tv (+ tv (amount-vat line)) tt (+ tt (amount-ttc line)))) (setf (total-ht self) th (total-vat self) tv (total-ttc self) tt))) ;;COMPUTE-TOTALS (defmethod vat-rate ((self invoice)) " RETURN: A computed VAT rate for this invoice. " (if (zerop (amount-magnitude (total-ht self))) 0 (/ (round (* 100 (/ (amount-magnitude (total-vat self)) (amount-magnitude (total-ht self))))) 100))) (defmethod add-line ((self invoice) (line invoice-line)) " PRE: (eq (find-currency (currency self))(find-currency (currency line))) DO: Add the line. " (assert (eq (find-currency (currency self)) (find-currency (currency line)))) (setf (lines self) (append (lines self) (list line))) (compute-totals self)) ;;ADD-LINE (defmethod is-refund ((self invoice)) " RETURN: Whether this invoice is a refund invoice. " (negativep (total-ttc self))) ;;IS-REFUND (deftranslation *invoice-strings* "Phone:" :en :idem :fr "Téléphone :" :es "Teléfono :") (deftranslation *invoice-strings* "Fax:" :en :idem :fr "Télécopie :" :es "Telécopia :") (deftranslation *invoice-strings* "Email:" :en :idem :fr "Couriel :" :es "Email :") (deftranslation *invoice-strings* "VAT Immatriculation:" :en :idem :fr "TVA Intracommunautaire :" :es "Imatriculación IVA :") (deftranslation *invoice-strings* "INVOICE" :en :idem :fr "FACTURE" :es "FACTURA") (deftranslation *invoice-strings* "Date:" :en :idem :fr "Date :" :es "Fecha :") (deftranslation *invoice-strings* "Invoice no.:" :en :idem :fr "Facture nº :" :es "Nº de factura :") (deftranslation *invoice-strings* "Billing address:" :en :idem :fr "Adresse de facturation :" :es "Dirección de factura :") (deftranslation *invoice-strings* "Description" :en :idem :fr "Description" :es "Descripción") (deftranslation *invoice-strings* "Price" :en :idem :fr "Prix" :es "Precio") (deftranslation *invoice-strings* "Total" :en :idem :fr "Total HT" :es "Base imponible") (deftranslation *invoice-strings* "VAT ~5,1F %" :en :idem :fr "TVA ~5,1F %" :es "IVA ~5,1F %") (deftranslation *invoice-strings* "IRPF ~5,1F %" :en "" :fr "" :es :idem) (deftranslation *invoice-strings* "Total VAT Incl." :en :idem :fr "Total TTC" :es "Total factura") (deftranslation *invoice-strings* "PAYMENT-METHOD" :en "Method of Payment: Bank Transfer Please make your payment using the details below, before ~A." :fr "Mode de règlement : À régler par virement bancaire au compte suivant, avant le ~A." :es "Forma de pago : Transferencia bancaria a la cuenta siguiente, antes del ~A.") ;;*INVOICE-STRINGS* (deftranslation *invoice-strings* "Payment Bank" :en :idem :fr "Banque destinataire" :es "Banco") (deftranslation *invoice-strings* "Branch Name" :en :idem :fr "Agence" :es "Oficina") (deftranslation *invoice-strings* "Account Number (IBAN)" :en :idem :fr "Numéro de compte (IBAN)" :es "Número de cuenta (IBAN)") (deftranslation *invoice-strings* "Beneficiary" :en :idem :fr "Bénéficiaire" :es "Beneficiario") (deftranslation *invoice-strings* "SWIFT Code" :en :idem :fr "Code SWIFT" :es "Código SWIFT") (deftranslation *invoice-strings* "Currency change" :en :idem :fr "Change devises" :es "Cambio devisas") (defmacro longest-localized-length (table language fields) `(loop for fname in ,fields maximize (length (localize ,table ,language fname)) into increment finally (return increment))) ;;LONGEST-LOCALIZED-LENGTH (defparameter +line-chars+ (coerce #(#\LINEFEED #\RETURN #\NEWLINE #\PAGE) 'string) "A string containing the new-line characters.") (defun split-lines (text &key delete-empty-lines) " DELETE-EMPTY-LINES: When true, lines that are stripped empty are removed. RETURN: A list of stripped and splitted lines from the TEXT. " (let ((lines (split-string text +line-chars+))) (map-into lines (lambda (line) (string-trim " " line)) lines) (if delete-empty-lines (delete "" lines :test (function string=)) SPLIT - LINES (defun align-following-lines (text left-margin) " DO: Format the TEXT inserting LEFT-MARGIN spaces before each line but the first. " (format nil (format nil "~~{~~A~~^~~%~VA~~}" left-margin "") (split-lines text))) ;;ALIGN-FOLLOWING-LINES (defun print-person-address (title left-margin person &key (language :fr) (stream t)) " DO: Insert into the current buffer at the current point the address and phone, fax and email of the given person, prefixed by the title and with a left-margin of `left-margin' characters. If the length of the title is greater than the `left-margin' then the length of the title is used instead. LANGUAGE: The default language is French (:FR), :EN and :ES are also available for English and Spanish. " (unless title (setf title "")) (when (< left-margin (length title)) (setf left-margin (length title))) ;; title / name (format stream "~A~A~%" (string-pad title left-margin) (name person)) ;; address (format stream (format nil "~~{~VA~~A~~%~~}" left-margin "") (split-lines (address person) :delete-empty-lines t)) ;; other fields (let* ((fields '("Phone:" "Fax:" "Email:" "VAT Immatriculation:")) (slots '(phone fax email fiscal-id)) (increment (loop for fname in fields for slot in slots when (slot-value person slot) maximize (length (localize *invoice-strings* language fname)) into increment finally (return increment)))) (loop for fname in fields for slot in slots when (slot-value person slot) do (format stream "~VA~A ~A~%" left-margin "" (string-pad (localize *invoice-strings* language fname) increment) (slot-value person slot))))) ;;PRINT-PERSON-ADDRESS (defun show-tva (montant-ht &key (stream t) (vat-rate 16/100 vat-rate-p) (irpf nil irpf-p) (language :es) (alt-language :es)) "Affiche le montant HT donné, la TVA, le montant TTC. En option le taux de TVA. La facture est dans la devise du montant. Une ou deux langues peuvent aussi être indiquées (:es, :fr, :en). Une option :irpf ou :no-irpf peut être indiquée pour forcer la déduction IRPF, sinon elle est appliquée par défaut uniquement dans le cas où le taux de TVA est 16% et la langue est 'es (sans langue secondaire) et la currency :EUR. (show-tva #978m750.00 :vat-rate 16/100 :language :en :alt-language :es) donne : ---------------------------------------------------- ----------------- (Base imponible ) Total : 750.00 EUR (IVA 16.0 % ) VAT 16.0 % : + 120.00 EUR (Total factura ) Total VAT Incl. : = 870.00 EUR ---------------------------------------------------- ----------------- " (let* ((line-form " ~52A ~17A~%") (desc-line (make-string 52 :initial-element (character "-"))) (pric-line (make-string 17 :initial-element (character "-"))) (base-lab-gau "") (tvat-lab-gau "") (irpf-lab-gau "") (tota-lab-gau "") (base-lab-dro) (tvat-lab-dro) (irpf-lab-dro) (tota-lab-dro) (taux-tva nil) (taux-tva-present nil) empeze la actividad el 2000/07 entonces 2003/07 es -18 % . (taux-irpf (if (date-after (calendar-current-date) (make-date :year 2003 :month 6 :day 30)) -18/100 -9/100)) (show-irpf nil) (force-show-irpf nil) (montant-tva) (montant-irpf) (montant-ttc) (lang-pri nil) (lang-sec nil)) (when irpf-p (if irpf (setf show-irpf t force-show-irpf t) (setf show-irpf nil force-show-irpf t))) (setf lang-pri language lang-sec alt-language) (setf taux-tva vat-rate) (if vat-rate-p (setf taux-tva-present t) (setf taux-tva 0/100 taux-tva-present nil)) (when (equal lang-pri lang-sec) (setf lang-sec nil)) (if (and (null lang-sec) (not taux-tva-present) (string-equal lang-pri :es)) (setf taux-tva 16/100)) (unless force-show-irpf (setf show-irpf (and (eq (find-currency :eur) (currency montant-ht)) (string-equal lang-pri :es) (null lang-sec) (= taux-tva 16/100) ;; (equal (fiscal-id *invoice-set*) ;; (issuer-fiscal-id self)) ))) (setf montant-tva (* montant-ht taux-tva)) (setf montant-irpf (if show-irpf (* montant-ht taux-irpf) (amount-zero (currency montant-ht)))) (setf montant-ttc (+ montant-ht montant-tva montant-irpf)) (setf base-lab-dro (format nil "~16@A :" (localize *invoice-strings* lang-pri "Total"))) (setf tvat-lab-dro (format nil "~16@A :" (format nil (localize *invoice-strings* lang-pri "VAT ~5,1F %") (* 100 taux-tva)))) (setf irpf-lab-dro (format nil "~16@A :" (format nil (localize *invoice-strings* lang-pri "IRPF ~5,1F %") (* 100 taux-irpf)))) (setf tota-lab-dro (format nil "~16@A :" (localize *invoice-strings* lang-pri "Total VAT Incl."))) (when lang-sec (setf base-lab-gau (format nil "(~16@A) " (localize *invoice-strings* lang-sec "Total"))) (setf tvat-lab-gau (format nil "(~16@A) " (format nil (localize *invoice-strings* lang-sec "VAT ~5,1F %") (* 100 taux-tva)))) (setf irpf-lab-gau (format nil "(~16@A) " (format nil (localize *invoice-strings* lang-sec "IRPF ~5,1F %") (* 100 taux-irpf)))) (setf tota-lab-gau (format nil "(~16@A) " (localize *invoice-strings* lang-sec "Total VAT Incl.")))) (format stream "~%") (format stream line-form desc-line pric-line) (format stream line-form (concatenate 'string base-lab-gau base-lab-dro) (format nil " ~16@A" montant-ht)) (format stream line-form (concatenate 'string tvat-lab-gau tvat-lab-dro) (format nil "+~16@A" montant-tva)) (when show-irpf (format stream line-form (concatenate 'string irpf-lab-gau irpf-lab-dro) (format nil "-~16@A" (- montant-irpf)))) (format stream line-form (concatenate 'string tota-lab-gau tota-lab-dro) (format nil "=~16@A" montant-ttc)) (format stream line-form desc-line pric-line))) ;;SHOW-TVA (defun clean-title-for-file-name (title-string) " RETURN: A string containing the first word of title-string as plain ASCII. DO: Remove accents from the returned word. " ;;(STRING-REMOVE-ACCENTS (string-downcase (subseq title-string 0 (position-if-not (function alphanumericp) title-string)))) ;;CLEAN-TITLE-FOR-FILE-NAME (defmethod generate ((self invoice) &key (stream t) (verbose nil) (language :es language-p)) " DO: Generate this invoice into a file in the directory *INVOICE-DIRECTORY-PATH*. RETURN: The path to the file generated. " (let* ((payer (get-person-with-fiscal-id *invoice-set* (payer-fiscal-id self))) (issuer (get-person-with-fiscal-id *invoice-set* (issuer-fiscal-id self)))) (when verbose (format *trace-output* "Generating ~A ~A ~A ~A~%" (class-name (class-of self)) (date self) issuer (invoice-number self))) (unless language-p (setf language (or (language payer) :es))) (print-person-address "" 1 issuer :language language :stream stream) (format stream " ~%") (let* ((title (localize *invoice-strings* language "INVOICE")) (width (+ 8 (length title))) (title-b (concatenate 'string "|" (string-pad title width :justification :center) "|")) (line-b (concatenate 'string "+" (make-string width :initial-element (character "-")) "+"))) (format stream " ~A~%" (string-pad line-b 72 :justification :center)) (format stream " ~A~%" (string-pad title-b 72 :justification :center)) (format stream " ~A~%" (string-pad line-b 72 :justification :center))) (format stream " ~%") (let ((increment (longest-localized-length *invoice-strings* language '("Date:" "Invoice no.:" "Billing address:")))) (format stream " ~A ~A~%" (string-pad (localize *invoice-strings* language "Date:") increment) (date-format (date-to-universal-time (date self)) :language language)) (format stream " ~%") (format stream " ~A ~A~%" (string-pad (localize *invoice-strings* language "Invoice no.:") increment) (invoice-number self)) (format stream " ~%") (print-person-address (concatenate 'string " " (localize *invoice-strings* language "Billing address:")) (+ 2 increment) payer :language language) (format stream " ~%")) (let ((line-form " ~52@A ~17@A~%") (desc-line (make-string 52 :initial-element (character "-"))) (pric-line (make-string 17 :initial-element (character "-")))) (format stream line-form desc-line pric-line) (format stream line-form (localize *invoice-strings* language "Description") (localize *invoice-strings* language "Price")) (format stream line-form desc-line pric-line) (dolist (invo-line (lines self)) (let* ((desc (split-lines (description invo-line))) (last-length (length (car (last desc))))) (format stream "~{~% ~A~}" desc) (if (<= last-length 55) (format stream "~VA ~16@A" (- 55 last-length) "" (amount-ht invo-line)) (format stream "~% ~52@A ~16@A" "" (amount-ht invo-line))))) (format stream " ~%")) ;;let (show-tva (total-ht self) :language language :alt-language :es) (format stream " ~%") (let ((bankref (bank-reference issuer))) (when bankref (format stream "~{ ~A~%~}" (split-lines (format nil (localize *invoice-strings* language "PAYMENT-METHOD") (date-format (+ (* 30 +seconds-in-a-day+) (date-to-universal-time (date self))) :language language)))) (format stream " ~%") (let* ((fields '("Payment Bank" "" "Branch Name" "Account Number (IBAN)" "Beneficiary" "SWIFT Code")) (slots '(bank-name bank-address branch-name account-number beneficiary-name swift-code)) (increment (longest-localized-length *invoice-strings* language fields))) (loop for fname in fields for slot in slots when (slot-value bankref slot) do (format stream " ~A~A : ~A~%" (string-pad "" 8) (string-pad (localize *invoice-strings* language fname) increment) (align-following-lines (slot-value bankref slot) (+ increment 10)))) ))) (format stream " ~%") (format stream " ~%"))) ;;GENERATE (defmethod write-invoice-file ((self invoice) &key (language :en language-p)) (let* ((payer (get-person-with-fiscal-id *invoice-set* (payer-fiscal-id self))) (file-path (make-pathname :directory *invoice-directory-path* :name (format nil "~A-~A-~A" (delete (character "/") (invoice-number self)) (clean-title-for-file-name (object-id payer)) (clean-title-for-file-name (title self))) :type "txt"))) (unless language-p (setf language (or (language payer) :es))) (with-open-file (stream file-path :direction :output :if-does-not-exist :create :if-exists :supersede) (generate self :stream stream :language language)) file-path)) ;;WRITE-INVOICE-FILE ;;;--------------------------------------------------------------------- ;;; INVOICE-SET ;;;--------------------------------------------------------------------- (defmethod get-person-with-fiscal-id ((self invoice-set) fiscal-id) (car (member fiscal-id (persons self) :test (function string-equal) :key (function fiscal-id)))) (defmethod add-person ((self invoice-set) (person fiscal-person) &optional fisc) (let ((old (get-person-with-fiscal-id self (fiscal-id person)))) (if old (substitute person old (persons self) :count 1) (push person (persons self)))) (when (and fisc (not (member (fiscal-id person) (fisc-fiscal-ids self) :test (function string-equal)))) (push (fiscal-id person) (fisc-fiscal-ids self)))) ;;ADD-PERSON (defmethod get-invoice-with-issuer-and-number ((self invoice-set) issuer-fiscal-id invoice-number) (find-if (lambda (i) (and (equal issuer-fiscal-id (issuer-fiscal-id i)) (equal invoice-number (invoice-number i)))) (invoices self))) ;;GET-INVOICE-WITH-ISSUER-AND-NUMBER (defmethod add-invoice ((self invoice-set) (invoice invoice)) (let ((old (get-invoice-with-issuer-and-number self (issuer-fiscal-id invoice) (invoice-number invoice)))) (if old (substitute invoice old (invoices self) :count 1) (push invoice (invoices self))))) ;;ADD-INVOICE ;;;--------------------------------------------------------------------- ;;; MOVEMENT ;;;--------------------------------------------------------------------- (defclass movement (pjb-object) ((date :initform nil :initarg :date :accessor date :type (or null string) :documentation "'YYYY-MM-DD' Date of the movement.") (amount-ttc :initform (amount-zero *default-currency*) :initarg :amount-ttc :accessor amount-ttc :type amount :documentation "(number) The amount paid (including taxes).") (amount-vat :initform 0/100 :initarg :amount-vat :accessor amount-vat :type ratio :documentation "(number) The VAT of the movement.") (description :initform "" :initarg :description :accessor description :type string :documentation "(string) A description of the movement.") (kind :initform nil :initarg :kind :accessor kind :type (or null symbol) :documentation "(symbol) A kind of movement, for tax reporting purpose. PRESTACION-NACIONAL, PRESTACION-INTRACOMUNITARIA, IMPUESTO, INVERSION, GASTO-CORRIENTE, ADQUISICION-INTRACOMUNITARIA") (invoice-fiscal-id :initform nil :initarg :invoice-fiscal-id :accessor invoice-fiscal-id :type (or null string) :documentation "The fiscal id of the common issuer of the following invoices related to this movement.") (invoice-numbers :initform nil :initarg :invoice-numbers :accessor invoice-numbers :type list :documentation "(list of string) The list of invoice numbers related to this entry. Note that one journal entry may relate to several invoices (grouped payment) and one invoice may relate to several movements (part payments, or corrections.") ) (:documentation "An entry in the journal. A movement with a positive amount is a credit, while a movement with a negative amount is a debit.")) ;;MOVEMENT (defmethod initialize-instance ((self movement) &key amount-ttc amount-ht invoice-fiscal-id &allow-other-keys) " DOES: Checks that the values for the fields are within limits. " (declare (ignorable self)) (when *max-movement-amount* (when amount-ttc (when (< *max-movement-amount* (abs amount-ttc)) (error "amount-ttc too big ~S." amount-ttc))) (when amount-ht (if (< *max-movement-amount* (abs amount-ht)) (error "amount-ht too big ~S." amount-ht)))) (when invoice-fiscal-id (unless (get-person-with-fiscal-id *invoice-set* invoice-fiscal-id) (warn "Unknown person (fiscal-id=~S)." invoice-fiscal-id))) INITIALIZE - INSTANCE (defmethod amount-ht ((self movement)) (- (amount-ttc self) (amount-vat self))) (defparameter *movement-kinds* '(:prestacion-nacional :prestacion-intracomunitaria :impuesto :inversion :gasto-corriente :adquisicion-intracomunitaria)) ;;*MOVEMENT-KINDS* (defun make-movement-from-invoice (invoice) " RETURN: A new instance of MOVEMENT filled with data from invoice. " (let (kind amount-sign fiscal-id) (cond ((member (issuer-fiscal-id invoice) (fisc-fiscal-ids *invoice-set*) :test (function string-equal)) (setf kind :impuesto amount-sign -1 fiscal-id (issuer-fiscal-id invoice))) ((equalp (issuer-fiscal-id invoice) (fiscal-id *invoice-set*)) (setf kind (if (zerop (total-vat invoice)) :prestacion-intracomunitaria :prestacion-nacional) amount-sign 1 fiscal-id (payer-fiscal-id invoice))) (t (setf kind :gasto-corriente amount-sign -1 fiscal-id (issuer-fiscal-id invoice)))) (make-instance 'movement :date (date invoice) :amount-ttc (* (total-ttc invoice) amount-sign) :amount-vat (* (total-vat invoice) amount-sign) :description (title invoice) :kind kind :invoice-fiscal-id fiscal-id :invoice-numbers (list (invoice-number invoice))))) ;;MAKE-MOVEMENT-FROM-INVOICE (define-condition movement-error (simple-error) ((date :accessor movement-error-date :initarg :date) (amount-ttc :accessor movement-error-amount-ttc :initarg :amount-ttc) (vat-rate :accessor movement-error-vat-rate :initarg :vat-rate) (nif :accessor movement-error-nif :initarg :nif) (fac-l :accessor movement-error-fac-l :initarg :fac-l) (description :accessor movement-error-description :initarg :description) (kind :accessor movement-error-kind :initarg :kind))) (defun make-movement (date amount-ttc vat-rate nif fac-l description kind) " RETURN: A new instance of MOVEMENT filled with the given data ." (macrolet ((err (ctrl &rest args) `(error 'movement-error :format-control ,ctrl :format-arguments (list ,@args) :date date :amount-ttc amount-ttc :vat-rate vat-rate :nif nif :fac-l fac-l :description description :kind kind))) (unless (member kind *movement-kinds*) (err "Invalid kind ~A." kind)) (when (< vat-rate -2) (err "VAT-RATE must always be >= 0.")) (unless (eq kind :prestacion-intracomunitaria) (when (eq kind :prestacion-nacional) (unless (negativep amount-ttc) (err "AMOUNT-TTC must be > 0 for an entry of kind ~A." kind)))) (cond ((eq kind :prestacion-nacional) (when (<= vat-rate 0) (err "VAT-RATE must be > 0.00 for an entry of kind ~A." kind))) ((member kind '(:prestacion-intracomunitaria :impuesto)) (if (< 0 vat-rate) (err "VAT-RATE must be = 0 for an entry of kind ~A." kind)))) (make-instance 'movement :date date :amount-ttc amount-ttc :amount-vat (/ (* amount-ttc vat-rate) (+ 1 vat-rate)) :description description :kind kind :invoice-fiscal-id nif :invoice-numbers fac-l))) (defmethod is-credit ((self movement)) " RETURN: Whether the SELF is a credit movement. " (positivep (amount-ht self))) ;;IS-CREDIT (defmethod vat-rate ((self movement)) " RETURN: A computed VAT rate for this movement. " (if (zerop (amount-magnitude (amount-ht self))) 0 (/ (round (* 100 (/ (amount-magnitude (amount-vat self)) (amount-magnitude (amount-ht self))))) 100))) (defmethod credit-ht ((self movement)) (if (is-credit self) (amount-ht self) (amount-zero (currency (amount-ht self))))) (defmethod credit-vat ((self movement)) (if (is-credit self) (amount-vat self) (amount-zero (currency (amount-vat self))))) (defmethod debit-ht ((self movement)) (if (is-credit self) (amount-zero (currency (amount-ht self))) (- (amount-ht self)))) (defmethod debit-vat ((self movement)) (if (is-credit self) (amount-zero (currency (amount-vat self))) (- (amount-vat self)))) (defmethod debit-vat-inversion ((self movement)) (if (eq :inversion (kind self)) (debit-vat self) (amount-zero (currency (debit-vat self))))) (defmethod debit-vat-corriente ((self movement)) (if (eq :gasto-corriente (kind self)) (debit-vat self) (amount-zero (currency (debit-vat self))))) (defmethod invoices ((self movement)) " RETURN: A list of INVOICE instances related to this entry. " (let ((fiscal-id (if (and (is-credit self) (not (equal (kind self) :gasto-corriente))) (fiscal-id *invoice-set*) (invoice-fiscal-id self)))) (remove nil (mapcar (lambda (number) (get-invoice-with-issuer-and-number *invoice-set* fiscal-id number)) (invoice-numbers self))))) ;;INVOICES (defun trim-justify-and-split-text (text width) " DOES: Trim spaces on each line. justify each paragraph. RETURN: The justified text. " (let ((lines (split-lines text)) (paragraphs '()) (current-paragraph '())) (dolist (line lines ; group the paragraphs. (when current-paragraph (push (apply (function concatenate) 'string (nreverse current-paragraph)) paragraphs))) (if (string= line "") (when current-paragraph (push (apply (function concatenate) 'string (nreverse current-paragraph)) paragraphs)) (progn (push " " current-paragraph) (push line current-paragraph)))) (or (mapcan (lambda (para) (split-lines (string-justify-left para width 0))) (nreverse paragraphs)) (list " ")))) ;;TRIM-JUSTIFY-AND-SPLIT-TEXT (defmethod generate ((self movement) &key (stream t) (verbose nil) (language :en)) " DOES: format and insert this entry. " (let ((id (invoice-fiscal-id self)) person (name "") name-l (movement-sign (if (is-credit self) 1 -1)) (invoices-sign 1)) (when verbose (format *trace-output* "Generating ~A ~A ~A~%" (class-name (class-of self)) (date self) (amount-ttc self))) first line : (if id (progn (setf person (get-person-with-fiscal-id *invoice-set* id)) (when person (setf name (name person)))) (setf id "")) (setf name-l (trim-justify-and-split-text name 38)) ;; === SEN FECHA IDENTIFICATION NOMBRE ============================= (format stream "~3A ~10A ~23@A ~A~%" (cond ((is-credit self) "ING") ((eq :impuesto (kind self)) "IMP") (t "GAS")) (date self) id (car name-l)) ;; === OPTIONAL NEXT LINES ========================================= ;; NOMBRE (continuación) (dolist (name (cdr name-l)) (format stream "~38A ~A~%" "" name)) ;; === INVOICE LINES =============================================== IMPORTE IVA% + IVA TOTAL NUMERO FACTURA o DESCRIPCION ;; INVOICE TITLE (let* ((zero (amount-zero (currency (amount-ht self)))) (t-ht zero) (t-vat zero) (t-ttc zero)) (let ((t-ttc zero)) ; Let's find the invoices-sign (dolist (invoice (invoices self)) (setf t-ttc (+ t-ttc (total-ttc invoice)))) (setf invoices-sign (* movement-sign (if (negativep t-ttc) -1 1)))) (dolist (invoice (invoices self)) ; Let's print the invoices (let* ((title-l (trim-justify-and-split-text (title invoice) 38)) (i-ht (total-ht invoice)) (i-vat (total-vat invoice)) (i-ttc (total-ttc invoice))) (setf t-ht (+ t-ht i-ht) t-vat (+ t-vat i-vat) t-ttc (+ t-ttc i-ttc)) (format stream " ~2,,9$ ~4,1F% ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude (* i-ht invoices-sign)) (* 100 (vat-rate invoice)) (amount-magnitude (* i-vat invoices-sign)) (amount-magnitude (* i-ttc invoices-sign)) (invoice-number invoice)) (dolist (title title-l) (format stream "~38A ~A~%" "" title)))) ;; === DIFFERNCE LINE ============================================ ;; AMOUNT-HT AMOUNT-VAT AMOUNT-TTC Diferencia (unless (and (zerop t-ht) (zerop t-vat) (zerop t-ttc)) ;; Invoices, let's see if there's a difference. (handler-case (unless (= (amount-ttc self) (* t-ttc invoices-sign)) (let* ((diff-ht (- (amount-ht self) (* t-ht invoices-sign))) (diff-vat (- (amount-vat self) (* t-vat invoices-sign))) (diff-ttc (- (amount-ttc self) (* t-ttc invoices-sign)))) (format stream " ~2,,9$ ~5A ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude diff-ht) "" (amount-magnitude diff-vat) (amount-magnitude diff-ttc) "Diferencia"))) (multi-currency-error () (let ((cambio (if (zerop t-ttc) 0 (/ (amount-ttc self) (* t-ttc invoices-sign))))) (format stream " ~9A ~5A ~8A ~2,,9$ ~A ~A -> ~A~%" "" "" "" cambio (localize *invoice-strings* language "Currency change") (currency-alphabetic-code (currency t-ttc)) (currency-alphabetic-code (currency (amount-ttc self))))))) (format stream " --------- ----- -------- ---------~%"))) ;; === TOTAL ENTRY LINES =========================================== (let* ((desc-l (trim-justify-and-split-text (description self) 38)) (desc (pop desc-l))) (format stream " ~2,,9$ ~4,1F% ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude (amount-ht self)) (* 100 (vat-rate self)) (amount-magnitude (amount-vat self)) (amount-magnitude (amount-ttc self)) desc) (dolist (desc desc-l) (format stream "~38A ~A~%" "" desc)))) (format stream "--- ---------- ----------------------- ~ ----------------------------------------~%")) ;;GENERATE ;;;--------------------------------------------------------------------- JOURNAL - ENTRY ;;;--------------------------------------------------------------------- ;; (defstruct (journal-entry (:type list)) ;; (date (calendar-current-date) :type date) ( amount - ht ( amount - zero * default - currency * ) : type amount ) ;; (vat-rate 16/100 :type ratio) ;; (description "Default journal entry" :type string) ;; (kind :PRESTACION-NACIONAL :type keyword) ( nif " s / n " : type string ) ;; (invoices '() :type list));;journal-entry ;; ( defmethod date ( ( self journal - entry ) ) ( journal - entry - date self ) ) ;; (defmethod amount-ht ((self journal-entry)) (journal-entry-amount-ht self)) ;; (defmethod vat-rate ((self journal-entry)) (journal-entry-vat-rate self)) ;; (defmethod description ((self journal-entry)) (journal-entry-description self)) ;; (defmethod kind ((self journal-entry)) (journal-entry-kind self)) ( defmethod nif ( ( self journal - entry ) ) ( journal - entry - nif self ) ) ( defmethod invoices ( ( self journal - entry ) ) ( journal - entry - invoices self ) ) ;; ;; ( defmethod initialize - instance ( ( self journal - entry ) ;; &key AMOUNT-HT VAT-RATE KIND &allow-other-keys) ;; (unless (MEMBER KIND ' (: - NACIONAL : PRESTACION - INTRACOMUNITARIA : IMPUESTO ;; :INVERSION :GASTO-CORRIENTE : ADQUISICION - INTRACOMUNITARIA ) ) ;; (ERROR "Invalid kind ~A." KIND)) ;; (when (negativep VAT-RATE) ( ERROR " VAT - RATE must always be > = 0.00 . " ) ) ( unless ( EQ KIND : PRESTACION - INTRACOMUNITARIA ) ( unless ( MEMBER KIND ' (: PRESTACION - NACIONAL ) ) ; ; ( when ( > = 0.00 AMOUNT - HT ) ( ERROR " AMOUNT - HT must be > 0.00 for an entry of kind ~A. " KIND ) ) ) ) ;; (COND ;; ((EQ KIND :PRESTACION-NACIONAL) ;; (when (negativep VAT-RATE) ( ERROR " VAT - RATE must be > 0.00 for an entry of kind ~A. " KIND ) ) ) ( ( MEMBER KIND ' (: - INTRACOMUNITARIA : IMPUESTO ) ) ;; (when (positivep VAT-RATE) ( ERROR " VAT - RATE must be = 0.00 for an entry of kind ~A. " KIND ) ) ) ;; (T ;; (IF (zerop VAT-RATE) ( ERROR " VAT - RATE must be > 0.00 for an entry of kind ~A. " KIND ) ) ) ) ;; ());;initialize-instance ;; ;; ( DEFMETHOD IS - CREDIT ( ( SELF JOURNAL - ENTRY ) ) ;; "RETURN: Whether the SELF is a credit." ;; (positivep (AMOUNT-HT SELF))) ;; ;; ( DEFMETHOD CREDIT - HT ( ( SELF JOURNAL - ENTRY ) ) ;; (IF (IS-CREDIT SELF) ;; (AMOUNT-HT SELF) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ) ) ;; ;; ( DEFMETHOD CREDIT - VAT ( ( SELF JOURNAL - ENTRY ) ) ;; (* (CREDIT-HT SELF) (VAT-RATE SELF))) ;; ;; ( DEFMETHOD DEBIT - HT ( ( SELF JOURNAL - ENTRY ) ) ;; (IF (IS-CREDIT SELF) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ;; (- (AMOUNT-HT SELF)))) ;; ;; ( DEFMETHOD DEBIT - VAT ( ( SELF JOURNAL - ENTRY ) ) ;; (* (DEBIT-HT SELF) (VAT-RATE SELF))) ;; ;; ( DEFMETHOD DEBIT - VAT - INVERSION ( ( SELF JOURNAL - ENTRY ) ) ;; (IF (EQ :INVERSION (KIND SELF)) ;; (DEBIT-VAT SELF) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ) ) ;; ;; ( DEFMETHOD DEBIT - VAT - CORRIENTE ( ( SELF JOURNAL - ENTRY ) ) ;; (IF (EQ :GASTO-CORRIENTE (KIND SELF)) ;; (DEBIT-VAT SELF) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ) ) ;;;--------------------------------------------------------------------- JOURNAL ;;;--------------------------------------------------------------------- (defgeneric trimestre (journal) (:documentation "RETURN: The quarter of the journal (1 2 3 or 4).")) (defclass journal () ((sorted :initform nil :accessor sorted :type boolean :documentation "Indicates whether entries are sorted.") (entries :initform '() :initarg :entries :accessor entries :type list) (year :initform (date-year (calendar-current-date)) :initarg :year :accessor year :type (integer 1998 2070)) (trimestre :initform (1+ (truncate (1- (date-month (calendar-current-date))) 3)) :initarg :trimestre :accessor trimestre :type (member 1 2 3 4))) (:documentation "An account journal.")) (defmethod reset ((self journal)) " POST: (null (entries self)) " (setf (entries self) '() (sorted self) nil)) ;;RESET (defmethod add-entry ((self journal) (entry movement)) " DOES: Add the ENTRY into the journal. POST: (AND (MEMBER ENTRY (ENTRIES SELF)) (NOT (SORTED SELF))) " (push entry (entries self)) (setf (sorted self) nil)) ;;ADD-ENTRY (defmethod ensure-sorted ((self journal)) " POST: (sorted *journal*) " (unless (sorted self) (setf (entries self) (sort (entries self) (lambda (a b) (date-after (date b) (date a)))) (defmethod extract ((self journal) year trimestre) " RETURN: The entries of the journal corresponding to the given YEAR and TRIMESTRE. " (ensure-sorted self) (remove-if (lambda (entry) (not (date-in-year-trimestre (date entry) year trimestre))) (entries self))) ;;EXTRACT (defun journal-totals-of-entries (entries) "PRIVATE RETURN: a list containing the totals: credit-ht credit-vat debit-ht debit-vat-inversion debit-vat-corriente. " (if (null entries) (make-list 5 :initial-element (amount-zero *default-currency*)) (let* ((zero (amount-zero (currency (credit-ht (first entries))))) (credit-ht zero) (credit-vat zero) (debit-ht zero) (debit-vat-c zero) (debit-vat-i zero)) (mapcar (lambda (entry) (setf credit-ht (+ credit-ht (credit-ht entry)) credit-vat (+ credit-vat (credit-vat entry)) debit-ht (+ debit-ht (debit-ht entry)) debit-vat-c (+ debit-vat-c (debit-vat-corriente entry)) debit-vat-i (+ debit-vat-i (debit-vat-inversion entry)))) entries) (list credit-ht credit-vat debit-ht debit-vat-i debit-vat-c)))) (defun journal-split-and-justify-description (description width) "PRIVATE" (or (mapcan (lambda (line) (split-lines(string-justify-left line width 0))) (split-lines description)) (list " "))) (defun journal-print-header (year trimestre &key (stream t)) "PRIVATE" (format stream "----------------------------------------~ ---------------------------------------~%") (format stream "~36D - TRIMESTRE ~D~%" year trimestre) (format stream "--- ---------- ----------------------- ~ ----------------------------------------~%") (format stream "SEN FECHA IDENTIFICACION NOMBRE~%") (format stream "TID IMPORTE IVA% +IVA TOTAL ~ NUMERO FACTURA / DESCRIPTION~%") (format stream "--- --------- ----- -------- --------- ~ ---------------------------------------~%") (values)) (defun journal-print-trailer (&key (stream t)) "PRIVATE" (format stream " IMPORTE IVA TOTAL~%") (format stream "--- --------- ----- -------- --------- ~ ---------------------------------------~%") (values)) (defun journal-print-totals (totals &key (stream t)) "PRIVATE" (let ((credit-ht (nth 0 totals)) (credit-vat (nth 1 totals)) (debit-ht (nth 2 totals)) (debit-vat (+ (nth 3 totals) (nth 4 totals)))) (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude credit-ht) "" (amount-magnitude credit-vat) "" "Credito") (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude (- debit-ht)) "" (amount-magnitude (- debit-vat)) "" "Debido") (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude (- credit-ht debit-ht)) "" (amount-magnitude (- credit-vat debit-vat)) "" "Saldo") (values))) (defun kind-to-order (kind) (case kind ((:prestacion-nacional) 1) ((:prestacion-intracomunitaria) 2) ((:impuesto) 3) ((:inversion) 4) ((:gasto-corriente) 5) ((:adquisicion-intracomunitaria) 6) (otherwise 7))) (defmethod generate ((self journal) &key (stream t) (verbose nil) (language :en)) " DOES: Prints the formated entries of the journal onto the stream. " (ensure-sorted self) (let* ((entries (sort (extract self (year self) (trimestre self)) (lambda (a b) (cond ((= (kind-to-order (kind a)) (kind-to-order (kind b))) (not (date-after (date a) (date b)))) (t (< (kind-to-order (kind a)) (kind-to-order (kind b)))))))) (totals (journal-totals-of-entries entries))) (format stream "~2%") (journal-print-header (year self) (trimestre self) :stream stream) (mapcar (lambda (entry) (generate entry :stream stream :verbose verbose :language language)) entries) (journal-print-trailer :stream stream) (journal-print-totals totals :stream stream) (format stream "~2%") (values))) ;;;--------------------------------------------------------------------- ;;; Reading Journal File. ;;;--------------------------------------------------------------------- (defmacro person (&rest args) " DO: Add to the *INVOICE-SET* a new FISCAL-PERSON instance created with the give initargs. " `(add-person *invoice-set* (make-instance 'fiscal-person ,@args))) (defmacro make-bank-reference (&rest args) " RETURN: A new instance of BANK-REFERENCE with the given initargs. " `(make-instance 'bank-reference ,@args)) (defmacro invoice (&rest args) (do ((args args) (attributes '()) (lines '()) (vinst (gensym))) ((null args) `(let ((,vinst (make-instance 'invoice ,@(nreverse attributes)))) ,@(mapcar (lambda (line) `(add-line ,vinst (make-instance 'invoice-line ,@line))) (nreverse lines)) (add-invoice *invoice-set* ,vinst))) (cond ((keywordp (car args)) (push (pop args) attributes) (push (pop args) attributes)) ((atom (car args)) (error "Invalid invoice attribute ~S" (pop args))) ((eql 'line (caar args)) (push (list* :object-id (string (gensym "L")) (cdr (pop args))) lines)) (t (error "Invalid invoice attribute ~S" (pop args)))))) ;;INVOICE (defmacro journal-entry (date amount-ttc vat-rate nif fac description kind) " DOES: Add a new journal entry. AMOUNT-TTC is the total paid (including VAT) expressed in Euros. VAT-RATE is the V.A.T percentage. " `(add-entry *journal* (make-movement (date-from-string ',date) ',amount-ttc ',vat-rate ',nif (if (listp ',fac) ',fac (list ',fac)) JOURNAL - ENTRY (defun load-journal (path &key (verbose *load-verbose*) (print *load-print*)) " DO: Load the journal at PATH. " (let ((*readtable* *currency-readtable*))) (load path :verbose verbose :print print)) ;; (in-package :common-lisp-user) ;; (cd "/home/pascal/jobs/free-lance/accounting/") ;; (load "invoice") ;;;; THE END ;;;;
null
https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/common-lisp/invoice/invoice.lisp
lisp
coding : utf-8 -*- **************************************************************************** LANGUAGE: Common-Lisp SYSTEM: Common-Lisp DESCRIPTION This package exports classes and functions used for accounting: invoices, customers/providers, movements, taxes... Currencies are handled, but multicurrency accounting is not. LEGAL 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 along with this program. If not, see </> **************************************************************************** without even the implied warranty of parameters global variables: invoice-set --------------------------------------------------------------------- --------------------------------------------------------------------- --------------------------------------------------------------------- Since floating point arithmetic is not adapted to accounting, we will use integers for monetary amounts, and In addition monetary amounts are tagged with a currency, and arithmetic operations are type-restricted. The reader syntax is: # [currency-code] m|M [+|-] digit+ [ . digit* ] The currency code must be a numeric code of a currency found in (com.informatimago.common-lisp.cesarum.iso4217:get-currencies), otherwise a read-time error is issued. When the currency-code is not present, the currency designated by *DEFAULT-CURRENCY* is used. The number of digits after the decimal point must not be superior to the minor unit attribute of the currency. The value is converted to an integer number of minor unit and the read result is an AMOUNT structure gathering the currency and the value. The operations defined on AMOUNT values are: c: amount* --> boolean with c in { <, <=, >, >=, =, /= }. +: amount* --> amount -: amount* --> amount /: amount X real* --> amount (not commutatif and not associatif) For now, all these operations work only when the currency of all amount involved is the same. These Common-Lisp operators are shadowed, and functions are defined for them, that extend the normal numeric functions for amounts. The AMOUNT structure has a printer that prints different format depending on the *PRINT-READABLY*. It uses the reader syntax defined the value followed by the alphabetic code of the currency. (:PRINT-OBJECT PRINT-OBJECT) PRINT-OBJECT AMOUNT-ZERO (with-output-to-string (out) both amounts then return a number: cannot take the inverse of an amount! eat the dot (WITH-STANDARD-IO-SYNTAX (CURRENCY-MINOR-UNIT CURRENCY)) currency-syntax eval-when (let ((*readtable* *currency-readtable*)) (mapcar (lambda (s) (let ((cnt 0)) (list s (handler-case (multiple-value-bind (r l) (read-from-string s) (error (err) (apply (function format) nil #||*error-output*||# (simple-condition-format-control err) (simple-condition-format-arguments err)))) (let ((*readtable* *currency-readtable*)) (read-from-string "#M960" )) --------------------------------------------------------------------- DATE --------------------------------------------------------------------- eval-when (:PRINT-OBJECT PRINT-OBJECT) DATE-FROM-STRING DATE-AFTER DATE-IN-YEAR-TRIMESTRE CALENDAR-CURRENT-DATE LOCAL-TIME-ZONE UNIVERSAL-TIME-TO-DATE DATE-TO-UNIVERSAL-TIME --------------------------------------------------------------------- Pjb-Object --------------------------------------------------------------------- --------------------------------------------------------------------- BANK-REFERENCE --------------------------------------------------------------------- BANK-REFERENCE --------------------------------------------------------------------- FISCAL-PERSON --------------------------------------------------------------------- :es :en :fr :de FISCAL-PERSON --------------------------------------------------------------------- --------------------------------------------------------------------- --------------------------------------------------------------------- INVOICE --------------------------------------------------------------------- --------------------------------------------------------------------- INVOICE-SET --------------------------------------------------------------------- INVOICE-SET --------------------------------------------------------------------- INVOICE-LINE --------------------------------------------------------------------- check = ( a-ttc | a-ht ) & ( a-vat | vat-rate ) error = ~check | ( ~a-ttc & ~a-ht ) | ( ~a-vat & ~vat-rate ) ) (insert (carnot '( a-ttc a-ht a-vat vat-rate check) '((check . (lambda (a-ttc a-ht a-vat vat-rate check) (and (or a-ttc a-ht) (or a-vat vat-rate)) )) (error . (lambda (a-ttc a-ht a-vat vat-rate check) (or (not check) (and (not a-ttc) (not a-ht)) (and (not a-vat) (not vat-rate))) ))))) +-------+------+-------+----------+-------+-------+-------+ | a-ttc | a-ht | a-vat | vat-rate | check | check | error | +-------+------+-------+----------+-------+-------+-------+ | OUI | OUI | OUI | NON | OUI | X | . | | OUI | OUI | OUI | NON | NON | X | X | | OUI | OUI | NON | NON | OUI | . | X | | OUI | OUI | NON | NON | NON | . | X | | OUI | NON | OUI | NON | OUI | X | . | | OUI | NON | OUI | NON | NON | X | X | | OUI | NON | NON | NON | OUI | . | X | | OUI | NON | NON | NON | NON | . | X | | NON | OUI | OUI | NON | OUI | X | . | | NON | OUI | OUI | NON | NON | X | X | | NON | OUI | NON | NON | OUI | . | X | | NON | OUI | NON | NON | NON | . | X | | NON | NON | OUI | NON | OUI | . | X | | NON | NON | OUI | NON | NON | . | X | | NON | NON | NON | NON | OUI | . | X | | NON | NON | NON | NON | NON | . | X | +-------+------+-------+----------+-------+-------+-------+ last case should not occur. last case should not occur. (check-vat amount-ttc amount-ht amount-vat vat-rate) --------------------------------------------------------------------- INVOICE --------------------------------------------------------------------- COMPUTE-TOTALS ADD-LINE IS-REFUND *INVOICE-STRINGS* LONGEST-LOCALIZED-LENGTH ALIGN-FOLLOWING-LINES title / name address other fields PRINT-PERSON-ADDRESS (equal (fiscal-id *invoice-set*) (issuer-fiscal-id self)) SHOW-TVA (STRING-REMOVE-ACCENTS CLEAN-TITLE-FOR-FILE-NAME let GENERATE WRITE-INVOICE-FILE --------------------------------------------------------------------- INVOICE-SET --------------------------------------------------------------------- ADD-PERSON GET-INVOICE-WITH-ISSUER-AND-NUMBER ADD-INVOICE --------------------------------------------------------------------- MOVEMENT --------------------------------------------------------------------- MOVEMENT *MOVEMENT-KINDS* MAKE-MOVEMENT-FROM-INVOICE IS-CREDIT INVOICES group the paragraphs. TRIM-JUSTIFY-AND-SPLIT-TEXT === SEN FECHA IDENTIFICATION NOMBRE ============================= === OPTIONAL NEXT LINES ========================================= NOMBRE (continuación) === INVOICE LINES =============================================== INVOICE TITLE Let's find the invoices-sign Let's print the invoices === DIFFERNCE LINE ============================================ AMOUNT-HT AMOUNT-VAT AMOUNT-TTC Diferencia Invoices, let's see if there's a difference. === TOTAL ENTRY LINES =========================================== GENERATE --------------------------------------------------------------------- --------------------------------------------------------------------- (defstruct (journal-entry (:type list)) (date (calendar-current-date) :type date) (vat-rate 16/100 :type ratio) (description "Default journal entry" :type string) (kind :PRESTACION-NACIONAL :type keyword) (invoices '() :type list));;journal-entry (defmethod amount-ht ((self journal-entry)) (journal-entry-amount-ht self)) (defmethod vat-rate ((self journal-entry)) (journal-entry-vat-rate self)) (defmethod description ((self journal-entry)) (journal-entry-description self)) (defmethod kind ((self journal-entry)) (journal-entry-kind self)) &key AMOUNT-HT VAT-RATE KIND &allow-other-keys) (unless (MEMBER KIND :INVERSION :GASTO-CORRIENTE (ERROR "Invalid kind ~A." KIND)) (when (negativep VAT-RATE) ; (COND ((EQ KIND :PRESTACION-NACIONAL) (when (negativep VAT-RATE) (when (positivep VAT-RATE) (T (IF (zerop VAT-RATE) ());;initialize-instance "RETURN: Whether the SELF is a credit." (positivep (AMOUNT-HT SELF))) (IF (IS-CREDIT SELF) (AMOUNT-HT SELF) (* (CREDIT-HT SELF) (VAT-RATE SELF))) (IF (IS-CREDIT SELF) (- (AMOUNT-HT SELF)))) (* (DEBIT-HT SELF) (VAT-RATE SELF))) (IF (EQ :INVERSION (KIND SELF)) (DEBIT-VAT SELF) (IF (EQ :GASTO-CORRIENTE (KIND SELF)) (DEBIT-VAT SELF) --------------------------------------------------------------------- --------------------------------------------------------------------- RESET ADD-ENTRY EXTRACT --------------------------------------------------------------------- Reading Journal File. --------------------------------------------------------------------- INVOICE (in-package :common-lisp-user) (cd "/home/pascal/jobs/free-lance/accounting/") (load "invoice") THE END ;;;;
FILE : invoices.lisp USER - INTERFACE : Common - Lisp < PJB > < > MODIFICATIONS 2004 - 10 - 17 < PJB > Completed conversion to Common - Lisp . 2004 - 10 - 11 < PJB > Converted to Common - Lisp from emacs lisp . 2002 - 09 - 09 < PJB > Added generate - invoice . ? ? < PJB > Creation . AGPL3 Copyright 1990 - 2016 it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.INVOICE.INVOICE" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ISO4217") #+mocl (:shadowing-import-from "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING" "*TRACE-OUTPUT*" "*LOAD-VERBOSE*" "*LOAD-PRINT*" "ARRAY-DISPLACEMENT" "CHANGE-CLASS" "COMPILE" "COMPLEX" "ENSURE-DIRECTORIES-EXIST" "FILE-WRITE-DATE" "INVOKE-DEBUGGER" "*DEBUGGER-HOOK*" "LOAD" "LOGICAL-PATHNAME-TRANSLATIONS" "MACHINE-INSTANCE" "MACHINE-VERSION" "NSET-DIFFERENCE" "RENAME-FILE" "SUBSTITUTE-IF" "TRANSLATE-LOGICAL-PATHNAME" "PRINT-NOT-READABLE" "PRINT-NOT-READABLE-OBJECT") (:export "LOAD-JOURNAL" "JOURNAL-ENTRY" "LINE" "PERSON" "GENERATE" "TRIMESTRE" "MAKE-BANK-REFERENCE" "JOURNAL" "MOVEMENT" "INVOICE-SET" "INVOICE" "INVOICE-LINE" "FISCAL-PERSON" "BANK-REFERENCE" "PJB-OBJECT" "*JOURNAL*" "*INVOICE-SET*" "*CURRENCY-READTABLE*") (:shadow "ABS" "ZEROP" "ROUND" "/=" "=" ">=" ">" "<=" "<" "/" "*" "-" "+") (:documentation " This package exports classes and functions used for accounting: invoices, customers/providers, movements, taxes... License: AGPL3 Copyright Pascal J. Bourguignon 1990 - 2012 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </> ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.INVOICE.INVOICE") (defparameter *vat-rates* '(0/100 4/100 7/100 16/100) "The valid VAT rates in the country of the user.") (defparameter *invoice-directory-path* '(:absolute "HOME""PASCAL""JOBS""FREE-LANCE""INVOICES") "The directory where the generated invoices are stored.") (defparameter *invoice-set-file-path* (make-pathname :directory *invoice-directory-path* :name "INVOICES" :type "DATA") "Path to the file where invoices are stored.") (defparameter *default-currency* (find-currency :eur) "The currency used when no prefix currency code is given to #m") (defparameter *max-movement-amount* nil "The maximum movement amount (ht or ttc, expressed in the currency of the movement (weak, I know).") (defparameter *invoice-set* nil (defparameter *journal* nil "Current Journal (instance of JOURNAL).") (defgeneric abs (self)) (defgeneric add-entry (self entry)) (defgeneric add-invoice (self invoice)) (defgeneric add-line (self line)) (defgeneric add-person (self person &optional fisc)) (defgeneric amount-ht (self)) (defgeneric compute-totals (self)) (defgeneric credit-ht (self)) (defgeneric credit-vat (self)) (defgeneric currency (self)) (defgeneric amount-magnitude (self)) (defgeneric debit-ht (self)) (defgeneric debit-vat (self)) (defgeneric debit-vat-corriente (self)) (defgeneric debit-vat-inversion (self)) (defgeneric ensure-sorted (self)) (defgeneric extract (self year trimestre)) (defgeneric generate (invoice &key stream verbose language &allow-other-keys) (:documentation " DO: Generate this invoice into a file in the directory *INVOICE-DIRECTORY-PATH*. RETURN: The path to the file generated. ")) (defgeneric get-invoice-with-issuer-and-number (self issuer-fiscal-id invoice-number)) (defgeneric get-person-with-fiscal-id (self fiscal-id)) (defgeneric invoices (self)) (defgeneric is-credit (self)) (defgeneric is-refund (self)) (defgeneric negativep (self)) (defgeneric positivep (self)) (defgeneric reset (self)) (defgeneric round (self &optional divisor)) (defgeneric vat-rate (self)) (defgeneric write-invoice-file (self &key language)) (defgeneric zerop (self)) Monetary Amounts & Currency Syntax percentages will be expressed as rationnals : 16 % = 16/100 123.45 ¤ = 12345 ¢ = # 978m123.45 * : amount X real * -- > amount ( commutatif and associatif ) [ set * = closure of the set ] above when * PRINT - READABLY * is true , or a " ~V$ ~3A " format printing (defstruct (amount (:predicate amountp) "An amount of money." currency (value 0 :type integer)) (defmethod print-object ((self amount) stream) (if *print-readably* (format stream "#~DM~V$" (currency-numeric-code (amount-currency self)) (currency-minor-unit (amount-currency self)) (amount-magnitude self)) (format stream "~V$ ~A" (currency-minor-unit (amount-currency self)) (amount-magnitude self) (currency-alphabetic-code (amount-currency self)))) (defmethod currency ((self number)) (declare (ignorable self)) nil) (defmethod currency ((self amount)) (amount-currency self)) (defmethod amount-magnitude ((self number)) self) (defmethod amount-magnitude ((self amount)) " RETURN: A real equal to the value of the amount. " (* (amount-value self) (aref #(1 1/10 1/100 1/1000 1/10000) (currency-minor-unit (amount-currency self))))) (defparameter *zero-amounts* (make-hash-table :test (function eq)) "A cache of 0 amount for the various currencies used.") (defun amount-zero (currency) " RETURN: A null amount of the given currency. " (let ((zero (gethash (find-currency currency) *zero-amounts*))) (unless zero (setf zero (setf (gethash (find-currency currency) *zero-amounts*) (make-amount :currency (find-currency currency) :value 0)))) (defmethod abs ((self number)) (common-lisp:abs self)) (defmethod abs ((self amount)) (make-amount :currency (amount-currency self) :value (common-lisp:abs (amount-value self)))) (defmethod zerop ((self number)) (common-lisp:zerop self)) (defmethod zerop ((self amount)) (common-lisp:zerop (amount-value self))) (defmethod positivep ((self number)) (common-lisp:<= 0 self)) (defmethod positivep ((self amount)) (common-lisp:<= 0 (amount-value self))) (defmethod negativep ((self number)) (common-lisp:> 0 self)) (defmethod negativep ((self amount)) (common-lisp:> 0 (amount-value self))) (defmethod round ((self real) &optional (divisor 1)) (common-lisp:round self divisor)) (defmethod round ((self amount) &optional (divisor 1)) (make-amount :currency (amount-currency self) :value (common-lisp:round (amount-value self) divisor))) (defun euro-round (magnitude currency) " MAGNITUDE: A REAL CURRENCY: The currency of the amount. RETURN: An integer in minor unit rounded according to the Euro rule." (let ((rounder (aref #(1 1/10 1/100 1/1000 1/10000) (currency-minor-unit currency)))) (round (+ magnitude (* (signum magnitude) (/ rounder 10))) rounder))) (defun euro-value-round (value) " VALUE: A REAL CURRENCY: The currency of the amount. RETURN: An integer in minor unit rounded according to the Euro rule." EURO - VALUE - ROUND ( dolist ( * print - readably * ' ( t nil ) ) ( print ( make - amount : currency ( find - currency : EUR ) : value 12345 ) out ) ) ) (define-condition multi-currency-error (error) ((format-control :initarg :format-control :accessor format-control) (format-arguments :initarg :format-arguments :accessor format-arguments) (operation :initarg :operation :accessor multi-currency-error-operation) (amounts :initarg :amounts :accessor multi-currency-error-amounts)) (:report (lambda (self stream) (let ((*print-pretty* nil)) (format stream "~A: (~A ~{~A~^, ~})~%~A" (class-name (class-of self)) (multi-currency-error-operation self) (multi-currency-error-amounts self) (apply (function format) nil (format-control self) (format-arguments self))))))) (defun mcerror (operation amounts format-control &rest format-arguments) (error 'multi-currency-error :operation operation :amounts amounts :format-control format-control :format-arguments format-arguments)) (defun types-of-arguments (args) (labels ((display (item) (cond ((symbolp item) (symbol-name item)) ((atom item) item) (t (mapcar (function display) item))))) (mapcar (lambda (arg) (display (type-of arg))) args))) (defmacro make-comparison-method (name operator) " DO: Generate a comparison method. " `(defun ,name (&rest args) (cond ((every (function numberp) args) (apply (function ,operator) args)) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (apply (function ,operator) (mapcar (function amount-value) args)) (mcerror ',name args "Comparison not implemented yet.")))) (t (mcerror ',name args "Incompatible types: ~A" (types-of-arguments args)))))) (make-comparison-method < common-lisp:<) (make-comparison-method <= common-lisp:<=) (make-comparison-method > common-lisp:>) (make-comparison-method >= common-lisp:>=) (make-comparison-method = common-lisp:=) (make-comparison-method /= common-lisp:/=) (defun + (&rest args) " DO: A Generic addition with numbers or amounts. " (setf args (remove 0 args :key (lambda (x) (if (typep x 'amount) (amount-value x) x)) :test (function equal))) (cond ((every (function numberp) args) (apply (function common-lisp:+) args)) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (make-amount :currency currency :value (apply (function common-lisp:+) (mapcar (function amount-value) args))) (mcerror '+ args "Addtion not implemented yet.")))) (t (mcerror '+ args "Incompatible types: ~A" (types-of-arguments args))))) (defun - (&rest args) " DO: A Generic substraction with numbers or amounts. " (setf args (cons (car args) (remove 0 (cdr args) :key (lambda (x) (if (typep x 'amount) (amount-value x) x)) :test (function equal)))) (cond ((every (function numberp) args) (apply (function common-lisp:-) args)) ((zerop (first args)) (- (apply (function +) (rest args)))) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (make-amount :currency currency :value (apply (function common-lisp:-) (mapcar (function amount-value) args))) (mcerror '- args "Substraction not implemented yet.")))) (t (mcerror '- args "Incompatible types: ~A" (types-of-arguments args))))) (defun * (&rest args) " DO: A Generic multiplication with numbers or amounts. " (if (every (function numberp) args) (apply (function common-lisp:*) args) (let ((p (position-if (function amountp) args))) (cond ((or (null p) (not (every (lambda (x) (or (amountp x)(realp x))) args))) (mcerror '* args "Incompatible types: ~A" (types-of-arguments args))) ((position-if (function amountp) args :start (1+ p)) (mcerror '* args "Cannot multiply moneys.")) (t (make-amount :currency (amount-currency (nth p args)) :value (euro-value-round (apply (function common-lisp:*) (mapcar (lambda (x) (if (amountp x) (amount-value x) x)) args))))))))) (defun / (&rest args) " DO: A Generic division with numbers or amounts. " (cond ((every (function numberp) args) (apply (function common-lisp:/) args)) ((and (cadr args) two arguments (amountp (first args)) (/ (amount-value (first args)) (amount-value (second args)))) ((and (amountp (car args)) (every (function realp) (cdr args))) (make-amount :currency (amount-currency (car args)) :value (euro-value-round (apply (function common-lisp:/) (amount-value (car args)) (cdr args))))) (t (mcerror '/ args "Incompatible types: ~A" (types-of-arguments args))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun currency-syntax (stream char infix) (declare (ignore char)) (let ((currency (or infix *default-currency*))) (setf currency (find-currency currency)) (unless currency (mcerror 'currency-syntax (or infix *default-currency*) "Invalid currency designator ~S" (or infix *default-currency*))) (assert (<= 0 (currency-minor-unit currency) 4) () "Unexpected minor unit for currency: ~S" currency) (let ((left '()) (right '()) (dot nil) (sign 1)) (let ((ch (read-char stream nil nil))) (cond ((null ch)) ((char= ch (character "-" )) (setf sign -1)) ((char= ch (character "+" ))) (t (unread-char ch stream)))) (loop for ch = (peek-char nil stream nil nil) while (and ch (digit-char-p ch)) do (push (read-char stream) left) finally (setf dot (and ch (char= (character ".") ch)))) (when (zerop (length left)) (mcerror 'currency-syntax currency "Missing an amount after #M")) (when dot (when (zerop (currency-minor-unit currency)) (mcerror 'currency-syntax currency "There is no decimal point in ~A" (currency-name currency))) (loop for ch = (peek-char nil stream nil nil) while (and ch (digit-char-p ch)) do (push (read-char stream) right)) (when (< (currency-minor-unit currency) (length right)) (mcerror 'currency-syntax currency "Too many digits after the decimal point for ~A" (currency-name currency)))) (loop for i from (length right) below (currency-minor-unit currency) do (push (character "0") right)) (make-amount :currency currency ( INTERN ( CURRENCY - ALPHABETIC - CODE CURRENCY ) " KEYWORD " ) ) :value (* sign (parse-integer (map 'string (function identity) (nreverse (nconc right left))))) : divisor ( AREF # ( 1 10 100 1000 10000 ) (defparameter *currency-readtable* (copy-readtable *readtable*) "The readtable used to read currencies.") (set-dispatch-macro-character #\# #\M (function currency-syntax) *currency-readtable*) (set-dispatch-macro-character #\# #\M (function currency-syntax) *currency-readtable*) ( setf cnt l ) r ) ( subseq s cnt ) ) ) ) ' ( " # M123.45 " " # 840m123.45 " " # 548m123 " " # 788m123.456 " " # 840m123 " " # 840m123.xyz " " # 840m123.4 " " # 840m123.45 " " # 840m123.456 " " # 197M123.45 " " # 548m123 " " # 548m123.xyz " " # 548m123.4 " " # 548m123.45 " " # 548m123.456 " " # 788m123 " " # 788m123.xyz " " # 788m123.4 " " # 788m123.45 " " # 788m123.456 " " # 788m123.4567 " " # 788m123.45678 " ) ) ) ( let ( ( * readtable * * currency - readtable * ) ) ( read - from - string " # 197M123.45 " ) ) ( let ( ( * readtable * * currency - readtable * ) ) ( read - from - string " # 978M978 " ) ) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +seconds-in-a-day+ (cl:* 24 3600) "Number of seconds in a day.") (defmethod print-object ((self date) stream) (format stream "~4,'0D-~2,'0D-~2,'0D" (date-year self) (date-month self) (date-day self)) self) (defun date-from-string (yyyy-mm-dd) (let ((ymd (split-string yyyy-mm-dd "-"))) (make-date :year (parse-integer (nth 0 ymd)) :month (parse-integer (nth 1 ymd)) (defun date-after (a b) (or (> (date-year a) (date-year b)) (and (= (date-year a) (date-year b)) (or (> (date-month a) (date-month b)) (and (= (date-month a) (date-month b)) (defun date-in-year-trimestre (date year trimestre) " RETURN: Whether the given date is within the given YEAR and TRIMESTRE. " (and (= (date-year date) year) (member (date-month date) (elt '((1 2 3) (4 5 6) (7 8 9) (10 11 12)) (defun calendar-current-date () " RETURN: The date today. " (multiple-value-bind (se mi ho da mo ye dw ds zo) (get-decoded-time) (declare (ignore se mi ho dw ds zo)) (defun local-time-zone () " RETURN: The local time zone, as returned by GET-DECODED-TIME. " (multiple-value-bind (se mi ho da mo ye dw ds zone) (get-decoded-time) (declare (ignore se mi ho da mo ye dw ds)) (defun universal-time-to-date (utime) " RETURN: the given universal time formated in the ISO8601 YYYY-MM-DD format. " (multiple-value-bind (se mi ho da mo ye dw ds zo) (decode-universal-time utime 0) (declare (ignore se mi ho dw ds zo)) (defun date-to-universal-time (date-string) " DATE-STRING: A date in the ISO8601 format 'YYYY-MM-DD'. RETURN: A number of seconds since 1900-01-01 00:00:00 GMT. " (let ((ymd (split-string date-string "-"))) (encode-universal-time 0 0 0 (parse-integer (third ymd)) (parse-integer (second ymd)) (parse-integer (first ymd)) (defun date-format (utime &key (language :en)) (multiple-value-bind (se mi ho day month year dw ds zo) (decode-universal-time utime 0) (declare (ignore se mi ho dw ds zo)) (case language ((:fr) (format nil "~D~A ~A ~D" day (if (= 1 day) "er" "") (aref #("Janvier" "Février" "Mars" "Avril" "Mai" "Juin" "Juillet" "Août" "Septembre" "Octobre" "Novembre" "Décembre") (1- month)) year)) ((:es) (format nil "~D de ~A de ~D" day (aref #("Enero" "Febrero" "Marzo" "Abril" "Mayo" "Junio" "Julio" "Augosto" "Septiembre" "Octobre" "Noviembre" "Diciembre") (1- month)) year)) (otherwise (format nil "~A ~D~A, ~D" (aref #("January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December") (1- month)) day (case (mod day 10) ((1) "st") ((2) "nd") ((3) "rd") (otherwise "th")) year))))) (defclass pjb-object () ((object-id :initform nil :initarg :object-id :accessor object-id :type (or null string) :documentation "The user-level ID of this object.")) (:documentation "This is a root class for my classes.")) (defclass bank-reference (pjb-object) ((bank-name :initform nil :initarg :bank-name :accessor bank-name :type (or null string) :documentation "The name of the bank.") (bank-address :initform nil :initarg :bank-address :accessor bank-address :type (or null string) :documentation "The address of the bank.") (branch-name :initform nil :initarg :branch-name :accessor branch-name :type (or null string) :documentation "The name of the branch.") (swift-code :initform nil :initarg :swift-code :accessor swift-code :type (or null string) :documentation "The swift-code of the bank.") (account-number :initform nil :initarg :account-number :accessor account-number :type (or null string) :documentation "The account number. It should be an IBAN in Europe.") (beneficiary-name :initform nil :initarg :beneficiary-name :accessor beneficiary-name :type (or null string) :documentation "The beneficiary's name.")) (defclass fiscal-person (pjb-object) ((fiscal-id :initform nil :initarg :fiscal-id :accessor fiscal-id :type (or null string) :documentation "The fiscal ID of the person, ie. the European fiscal ID.") (name :initform nil :initarg :name :accessor name :type (or null string) :documentation "The name of the person.") (address :initform nil :initarg :address :accessor address :type (or null string) :documentation "The address of the person.") (phone :initform nil :initarg :phone :accessor phone :type (or null string) :documentation "The phone number of the person.") (fax :initform nil :initarg :fax :accessor fax :type (or null string) :documentation "The fax number of the person.") (web :initform nil :initarg :web :accessor web :type (or null string) :documentation "The URL of the web site of this person.") (email :initform nil :initarg :email :accessor email :type (or null string) :documentation "The fax number of the person.") (bank-reference :initform nil :initarg :bank-reference :accessor bank-reference :type (or null bank-reference) :documentation "The bank reference of the person.") (language :initform :es :initarg :language :accessor language :documentation "The language (two-letter code) used by this person.") (fisc :initform nil :initarg :fisc :accessor fisc :type boolean :documentation "Whether this person is the fiscal administration.")) (:documentation "A person (physical or moral) identified by a fiscal identification number." (defmethod initialize-instance :after ((self fiscal-person) &rest arguments) (unless (getf arguments :object-id) (setf (object-id self) (or (fiscal-id self) (name self)))) self) Invoice - Line (defclass invoice-line (pjb-object) ((description :initform "" :initarg :description :accessor description :type string :documentation "The description of this line.") (currency :initform (find-currency :eur) :initarg :currency :accessor currency :type symbol :documentation "The currency of this line.") (amount-ht :initform (amount-zero *default-currency*) :initarg :amount-ht :accessor amount-ht :type amount :documentation "The amount excluding the taxes of this line.") (vat-rate :initform 0/100 :initarg :vat-rate :accessor vat-rate :type ratio :documentation "The rate of VAT for this line (0.00 <= vat-rate <= 0.50).") (amount-vat :initform (amount-zero *default-currency*) :initarg :amount-vat :accessor amount-vat :type amount :documentation "The amount of VAT for this line. ( = amount-ht * (1+vat-rate) )") (amount-ttc :initform (amount-zero *default-currency*) :initarg :amount-ttc :accessor amount-ttc :type amount :documentation "The amount including the taxes of this line.")) (:documentation "An Invoice Line.")) (defclass invoice (pjb-object) ((date :initform nil :initarg :date :accessor date :type (or null string) :documentation "'YYYY-MM-DD' The date of the invoice.") (issuer-fiscal-id :initform nil :initarg :issuer-fiscal-id :accessor issuer-fiscal-id :type (or null string) :documentation "The fiscal ID of the issuer of this invoice.") (invoice-number :initform nil :initarg :invoice-number :accessor invoice-number :type (or null string) :documentation "The invoice number.") (payer-fiscal-id :initform nil :initarg :payer-fiscal-id :accessor payer-fiscal-id :type (or null string) :documentation "The fiscal ID of the payer of this invoice.") (title :initform "" :initarg :title :accessor title :type (or null string) :documentation "The title of this invoice.") (currency :initform (find-currency :eur) :initarg :currency :accessor currency :type symbol :documentation "The currency of this invoice.") (lines :initform nil :accessor lines :type list :documentation "(list of Invoice-Line) The line items of this invoice.") (total-ht :initform (amount-zero *default-currency*) :accessor total-ht :type amount :documentation "The total excluding taxes of this invoice.") (total-vat :initform (amount-zero *default-currency*) :accessor total-vat :type amount :documentation "The total of VAT.") (total-ttc :initform (amount-zero *default-currency*) :accessor total-ttc :type amount :documentation "The total including taxes of this invoice.") ) (:documentation "An invoice, either outgoing or incoming. The amounts of the invoice may be negative when it's a refund.")) (defmethod initialize-instance :after ((self invoice) &rest arguments) (unless (getf arguments :object-id) (setf (object-id self) (concatenate 'string (issuer-fiscal-id self) ":" (invoice-number self)))) self) (defclass invoice-set (pjb-object) ((fiscal-id :initform nil :initarg :fiscal-id :accessor fiscal-id :type (or null string) :documentation "The fiscal id of the owner of this invoice set.") (fisc-fiscal-ids :initform nil :initarg :fisc-fiscal-ids :accessor fisc-fiscal-ids :type list :documentation "(list of string) List of fiscal-id of fisc entity. An invoice issued by on of these entities is actually a tax.") (persons :initform nil :initarg :persons :accessor persons :type list :documentation "The list of known Fiscal-Person.") (invoices :initform nil :initarg :invoices :accessor invoices :type list :documentation "The list of known Invoices.") ) (:documentation "This class gather all the data sets about invoices and fiscal persons.") | OUI | OUI | OUI | OUI | OUI | X | . | | OUI | OUI | OUI | OUI | NON | X | X | | OUI | OUI | NON | OUI | OUI | X | . | | OUI | OUI | NON | OUI | NON | X | X | | OUI | NON | OUI | OUI | OUI | X | . | | OUI | NON | OUI | OUI | NON | X | X | | OUI | NON | NON | OUI | OUI | X | . | | OUI | NON | NON | OUI | NON | X | X | | NON | OUI | OUI | OUI | OUI | X | . | | NON | OUI | OUI | OUI | NON | X | X | | NON | OUI | NON | OUI | OUI | X | . | | NON | OUI | NON | OUI | NON | X | X | | NON | NON | OUI | OUI | OUI | . | X | | NON | NON | OUI | OUI | NON | . | X | | NON | NON | NON | OUI | OUI | . | X | | NON | NON | NON | OUI | NON | . | X | (defmethod initialize-instance ((self invoice-line) &key object-id description currency amount-ht vat-rate amount-vat amount-ttc &allow-other-keys) " DO: Checks that the values for the fields are within limits. " (when (or (and (not amount-ttc) (not amount-ht)) (and (not amount-vat) (not vat-rate))) (error "Not enought amount data defined for this line ~S." self)) (unless amount-ttc (setf amount-ttc (cond (amount-vat (+ amount-ht amount-vat)) (vat-rate (* amount-ht (+ 1 vat-rate))) (t (if (zerop vat-rate) amount-ht (/ (* amount-vat (+ 1 vat-rate)) vat-rate)))))) (unless amount-ht (setf amount-ht (cond (amount-vat (- amount-ttc amount-vat)) (vat-rate (/ amount-ttc (+ 1 vat-rate))) (t (if (zerop vat-rate) amount-ttc (/ amount-vat vat-rate)))))) (unless amount-vat (setf amount-vat (- amount-ttc amount-ht))) (unless vat-rate (setf vat-rate (if (zerop (amount-magnitude amount-ht)) 0 (/ (round (* (/ (amount-magnitude amount-vat) (amount-magnitude amount-ht)) 100)) 100)))) (when (null currency) (setf currency (currency amount-ttc))) (call-next-method self :object-id object-id :description description :currency currency :amount-ht amount-ht :vat-rate vat-rate :amount-vat amount-vat :amount-ttc amount-ttc)) (defmethod compute-totals ((self invoice)) " DO: Compute the totals. " (let* ((th (amount-zero (currency self))) (tv th) (tt th)) (dolist (line (lines self)) (setf th (+ th (amount-ht line)) tv (+ tv (amount-vat line)) tt (+ tt (amount-ttc line)))) (setf (total-ht self) th (total-vat self) tv (defmethod vat-rate ((self invoice)) " RETURN: A computed VAT rate for this invoice. " (if (zerop (amount-magnitude (total-ht self))) 0 (/ (round (* 100 (/ (amount-magnitude (total-vat self)) (amount-magnitude (total-ht self))))) 100))) (defmethod add-line ((self invoice) (line invoice-line)) " PRE: (eq (find-currency (currency self))(find-currency (currency line))) DO: Add the line. " (assert (eq (find-currency (currency self)) (find-currency (currency line)))) (setf (lines self) (append (lines self) (list line))) (defmethod is-refund ((self invoice)) " RETURN: Whether this invoice is a refund invoice. " (deftranslation *invoice-strings* "Phone:" :en :idem :fr "Téléphone :" :es "Teléfono :") (deftranslation *invoice-strings* "Fax:" :en :idem :fr "Télécopie :" :es "Telécopia :") (deftranslation *invoice-strings* "Email:" :en :idem :fr "Couriel :" :es "Email :") (deftranslation *invoice-strings* "VAT Immatriculation:" :en :idem :fr "TVA Intracommunautaire :" :es "Imatriculación IVA :") (deftranslation *invoice-strings* "INVOICE" :en :idem :fr "FACTURE" :es "FACTURA") (deftranslation *invoice-strings* "Date:" :en :idem :fr "Date :" :es "Fecha :") (deftranslation *invoice-strings* "Invoice no.:" :en :idem :fr "Facture nº :" :es "Nº de factura :") (deftranslation *invoice-strings* "Billing address:" :en :idem :fr "Adresse de facturation :" :es "Dirección de factura :") (deftranslation *invoice-strings* "Description" :en :idem :fr "Description" :es "Descripción") (deftranslation *invoice-strings* "Price" :en :idem :fr "Prix" :es "Precio") (deftranslation *invoice-strings* "Total" :en :idem :fr "Total HT" :es "Base imponible") (deftranslation *invoice-strings* "VAT ~5,1F %" :en :idem :fr "TVA ~5,1F %" :es "IVA ~5,1F %") (deftranslation *invoice-strings* "IRPF ~5,1F %" :en "" :fr "" :es :idem) (deftranslation *invoice-strings* "Total VAT Incl." :en :idem :fr "Total TTC" :es "Total factura") (deftranslation *invoice-strings* "PAYMENT-METHOD" :en "Method of Payment: Bank Transfer Please make your payment using the details below, before ~A." :fr "Mode de règlement : À régler par virement bancaire au compte suivant, avant le ~A." :es "Forma de pago : Transferencia bancaria a la cuenta siguiente, (deftranslation *invoice-strings* "Payment Bank" :en :idem :fr "Banque destinataire" :es "Banco") (deftranslation *invoice-strings* "Branch Name" :en :idem :fr "Agence" :es "Oficina") (deftranslation *invoice-strings* "Account Number (IBAN)" :en :idem :fr "Numéro de compte (IBAN)" :es "Número de cuenta (IBAN)") (deftranslation *invoice-strings* "Beneficiary" :en :idem :fr "Bénéficiaire" :es "Beneficiario") (deftranslation *invoice-strings* "SWIFT Code" :en :idem :fr "Code SWIFT" :es "Código SWIFT") (deftranslation *invoice-strings* "Currency change" :en :idem :fr "Change devises" :es "Cambio devisas") (defmacro longest-localized-length (table language fields) `(loop for fname in ,fields maximize (length (localize ,table ,language fname)) into increment (defparameter +line-chars+ (coerce #(#\LINEFEED #\RETURN #\NEWLINE #\PAGE) 'string) "A string containing the new-line characters.") (defun split-lines (text &key delete-empty-lines) " DELETE-EMPTY-LINES: When true, lines that are stripped empty are removed. RETURN: A list of stripped and splitted lines from the TEXT. " (let ((lines (split-string text +line-chars+))) (map-into lines (lambda (line) (string-trim " " line)) lines) (if delete-empty-lines (delete "" lines :test (function string=)) SPLIT - LINES (defun align-following-lines (text left-margin) " DO: Format the TEXT inserting LEFT-MARGIN spaces before each line but the first. " (format nil (format nil "~~{~~A~~^~~%~VA~~}" left-margin "") (defun print-person-address (title left-margin person &key (language :fr) (stream t)) " DO: Insert into the current buffer at the current point the address and phone, fax and email of the given person, prefixed by the title and with a left-margin of `left-margin' characters. If the length of the title is greater than the `left-margin' then the length of the title is used instead. LANGUAGE: The default language is French (:FR), :EN and :ES are also available for English and Spanish. " (unless title (setf title "")) (when (< left-margin (length title)) (setf left-margin (length title))) (format stream "~A~A~%" (string-pad title left-margin) (name person)) (format stream (format nil "~~{~VA~~A~~%~~}" left-margin "") (split-lines (address person) :delete-empty-lines t)) (let* ((fields '("Phone:" "Fax:" "Email:" "VAT Immatriculation:")) (slots '(phone fax email fiscal-id)) (increment (loop for fname in fields for slot in slots when (slot-value person slot) maximize (length (localize *invoice-strings* language fname)) into increment finally (return increment)))) (loop for fname in fields for slot in slots when (slot-value person slot) do (format stream "~VA~A ~A~%" left-margin "" (string-pad (localize *invoice-strings* language fname) increment) (defun show-tva (montant-ht &key (stream t) (vat-rate 16/100 vat-rate-p) (irpf nil irpf-p) (language :es) (alt-language :es)) "Affiche le montant HT donné, la TVA, le montant TTC. En option le taux de TVA. La facture est dans la devise du montant. Une ou deux langues peuvent aussi être indiquées (:es, :fr, :en). Une option :irpf ou :no-irpf peut être indiquée pour forcer la déduction IRPF, sinon elle est appliquée par défaut uniquement dans le cas où le taux de TVA est 16% et la langue est 'es (sans langue secondaire) et la currency :EUR. (show-tva #978m750.00 :vat-rate 16/100 :language :en :alt-language :es) donne : ---------------------------------------------------- ----------------- (Base imponible ) Total : 750.00 EUR (IVA 16.0 % ) VAT 16.0 % : + 120.00 EUR (Total factura ) Total VAT Incl. : = 870.00 EUR ---------------------------------------------------- ----------------- " (let* ((line-form " ~52A ~17A~%") (desc-line (make-string 52 :initial-element (character "-"))) (pric-line (make-string 17 :initial-element (character "-"))) (base-lab-gau "") (tvat-lab-gau "") (irpf-lab-gau "") (tota-lab-gau "") (base-lab-dro) (tvat-lab-dro) (irpf-lab-dro) (tota-lab-dro) (taux-tva nil) (taux-tva-present nil) empeze la actividad el 2000/07 entonces 2003/07 es -18 % . (taux-irpf (if (date-after (calendar-current-date) (make-date :year 2003 :month 6 :day 30)) -18/100 -9/100)) (show-irpf nil) (force-show-irpf nil) (montant-tva) (montant-irpf) (montant-ttc) (lang-pri nil) (lang-sec nil)) (when irpf-p (if irpf (setf show-irpf t force-show-irpf t) (setf show-irpf nil force-show-irpf t))) (setf lang-pri language lang-sec alt-language) (setf taux-tva vat-rate) (if vat-rate-p (setf taux-tva-present t) (setf taux-tva 0/100 taux-tva-present nil)) (when (equal lang-pri lang-sec) (setf lang-sec nil)) (if (and (null lang-sec) (not taux-tva-present) (string-equal lang-pri :es)) (setf taux-tva 16/100)) (unless force-show-irpf (setf show-irpf (and (eq (find-currency :eur) (currency montant-ht)) (string-equal lang-pri :es) (null lang-sec) (= taux-tva 16/100) ))) (setf montant-tva (* montant-ht taux-tva)) (setf montant-irpf (if show-irpf (* montant-ht taux-irpf) (amount-zero (currency montant-ht)))) (setf montant-ttc (+ montant-ht montant-tva montant-irpf)) (setf base-lab-dro (format nil "~16@A :" (localize *invoice-strings* lang-pri "Total"))) (setf tvat-lab-dro (format nil "~16@A :" (format nil (localize *invoice-strings* lang-pri "VAT ~5,1F %") (* 100 taux-tva)))) (setf irpf-lab-dro (format nil "~16@A :" (format nil (localize *invoice-strings* lang-pri "IRPF ~5,1F %") (* 100 taux-irpf)))) (setf tota-lab-dro (format nil "~16@A :" (localize *invoice-strings* lang-pri "Total VAT Incl."))) (when lang-sec (setf base-lab-gau (format nil "(~16@A) " (localize *invoice-strings* lang-sec "Total"))) (setf tvat-lab-gau (format nil "(~16@A) " (format nil (localize *invoice-strings* lang-sec "VAT ~5,1F %") (* 100 taux-tva)))) (setf irpf-lab-gau (format nil "(~16@A) " (format nil (localize *invoice-strings* lang-sec "IRPF ~5,1F %") (* 100 taux-irpf)))) (setf tota-lab-gau (format nil "(~16@A) " (localize *invoice-strings* lang-sec "Total VAT Incl.")))) (format stream "~%") (format stream line-form desc-line pric-line) (format stream line-form (concatenate 'string base-lab-gau base-lab-dro) (format nil " ~16@A" montant-ht)) (format stream line-form (concatenate 'string tvat-lab-gau tvat-lab-dro) (format nil "+~16@A" montant-tva)) (when show-irpf (format stream line-form (concatenate 'string irpf-lab-gau irpf-lab-dro) (format nil "-~16@A" (- montant-irpf)))) (format stream line-form (concatenate 'string tota-lab-gau tota-lab-dro) (format nil "=~16@A" montant-ttc)) (defun clean-title-for-file-name (title-string) " RETURN: A string containing the first word of title-string as plain ASCII. DO: Remove accents from the returned word. " (string-downcase (subseq title-string 0 (position-if-not (function alphanumericp) (defmethod generate ((self invoice) &key (stream t) (verbose nil) (language :es language-p)) " DO: Generate this invoice into a file in the directory *INVOICE-DIRECTORY-PATH*. RETURN: The path to the file generated. " (let* ((payer (get-person-with-fiscal-id *invoice-set* (payer-fiscal-id self))) (issuer (get-person-with-fiscal-id *invoice-set* (issuer-fiscal-id self)))) (when verbose (format *trace-output* "Generating ~A ~A ~A ~A~%" (class-name (class-of self)) (date self) issuer (invoice-number self))) (unless language-p (setf language (or (language payer) :es))) (print-person-address "" 1 issuer :language language :stream stream) (format stream " ~%") (let* ((title (localize *invoice-strings* language "INVOICE")) (width (+ 8 (length title))) (title-b (concatenate 'string "|" (string-pad title width :justification :center) "|")) (line-b (concatenate 'string "+" (make-string width :initial-element (character "-")) "+"))) (format stream " ~A~%" (string-pad line-b 72 :justification :center)) (format stream " ~A~%" (string-pad title-b 72 :justification :center)) (format stream " ~A~%" (string-pad line-b 72 :justification :center))) (format stream " ~%") (let ((increment (longest-localized-length *invoice-strings* language '("Date:" "Invoice no.:" "Billing address:")))) (format stream " ~A ~A~%" (string-pad (localize *invoice-strings* language "Date:") increment) (date-format (date-to-universal-time (date self)) :language language)) (format stream " ~%") (format stream " ~A ~A~%" (string-pad (localize *invoice-strings* language "Invoice no.:") increment) (invoice-number self)) (format stream " ~%") (print-person-address (concatenate 'string " " (localize *invoice-strings* language "Billing address:")) (+ 2 increment) payer :language language) (format stream " ~%")) (let ((line-form " ~52@A ~17@A~%") (desc-line (make-string 52 :initial-element (character "-"))) (pric-line (make-string 17 :initial-element (character "-")))) (format stream line-form desc-line pric-line) (format stream line-form (localize *invoice-strings* language "Description") (localize *invoice-strings* language "Price")) (format stream line-form desc-line pric-line) (dolist (invo-line (lines self)) (let* ((desc (split-lines (description invo-line))) (last-length (length (car (last desc))))) (format stream "~{~% ~A~}" desc) (if (<= last-length 55) (format stream "~VA ~16@A" (- 55 last-length) "" (amount-ht invo-line)) (format stream "~% ~52@A ~16@A" "" (amount-ht invo-line))))) (show-tva (total-ht self) :language language :alt-language :es) (format stream " ~%") (let ((bankref (bank-reference issuer))) (when bankref (format stream "~{ ~A~%~}" (split-lines (format nil (localize *invoice-strings* language "PAYMENT-METHOD") (date-format (+ (* 30 +seconds-in-a-day+) (date-to-universal-time (date self))) :language language)))) (format stream " ~%") (let* ((fields '("Payment Bank" "" "Branch Name" "Account Number (IBAN)" "Beneficiary" "SWIFT Code")) (slots '(bank-name bank-address branch-name account-number beneficiary-name swift-code)) (increment (longest-localized-length *invoice-strings* language fields))) (loop for fname in fields for slot in slots when (slot-value bankref slot) do (format stream " ~A~A : ~A~%" (string-pad "" 8) (string-pad (localize *invoice-strings* language fname) increment) (align-following-lines (slot-value bankref slot) (+ increment 10)))) ))) (format stream " ~%") (defmethod write-invoice-file ((self invoice) &key (language :en language-p)) (let* ((payer (get-person-with-fiscal-id *invoice-set* (payer-fiscal-id self))) (file-path (make-pathname :directory *invoice-directory-path* :name (format nil "~A-~A-~A" (delete (character "/") (invoice-number self)) (clean-title-for-file-name (object-id payer)) (clean-title-for-file-name (title self))) :type "txt"))) (unless language-p (setf language (or (language payer) :es))) (with-open-file (stream file-path :direction :output :if-does-not-exist :create :if-exists :supersede) (generate self :stream stream :language language)) (defmethod get-person-with-fiscal-id ((self invoice-set) fiscal-id) (car (member fiscal-id (persons self) :test (function string-equal) :key (function fiscal-id)))) (defmethod add-person ((self invoice-set) (person fiscal-person) &optional fisc) (let ((old (get-person-with-fiscal-id self (fiscal-id person)))) (if old (substitute person old (persons self) :count 1) (push person (persons self)))) (when (and fisc (not (member (fiscal-id person) (fisc-fiscal-ids self) :test (function string-equal)))) (defmethod get-invoice-with-issuer-and-number ((self invoice-set) issuer-fiscal-id invoice-number) (find-if (lambda (i) (and (equal issuer-fiscal-id (issuer-fiscal-id i)) (equal invoice-number (invoice-number i)))) (defmethod add-invoice ((self invoice-set) (invoice invoice)) (let ((old (get-invoice-with-issuer-and-number self (issuer-fiscal-id invoice) (invoice-number invoice)))) (if old (substitute invoice old (invoices self) :count 1) (defclass movement (pjb-object) ((date :initform nil :initarg :date :accessor date :type (or null string) :documentation "'YYYY-MM-DD' Date of the movement.") (amount-ttc :initform (amount-zero *default-currency*) :initarg :amount-ttc :accessor amount-ttc :type amount :documentation "(number) The amount paid (including taxes).") (amount-vat :initform 0/100 :initarg :amount-vat :accessor amount-vat :type ratio :documentation "(number) The VAT of the movement.") (description :initform "" :initarg :description :accessor description :type string :documentation "(string) A description of the movement.") (kind :initform nil :initarg :kind :accessor kind :type (or null symbol) :documentation "(symbol) A kind of movement, for tax reporting purpose. PRESTACION-NACIONAL, PRESTACION-INTRACOMUNITARIA, IMPUESTO, INVERSION, GASTO-CORRIENTE, ADQUISICION-INTRACOMUNITARIA") (invoice-fiscal-id :initform nil :initarg :invoice-fiscal-id :accessor invoice-fiscal-id :type (or null string) :documentation "The fiscal id of the common issuer of the following invoices related to this movement.") (invoice-numbers :initform nil :initarg :invoice-numbers :accessor invoice-numbers :type list :documentation "(list of string) The list of invoice numbers related to this entry. Note that one journal entry may relate to several invoices (grouped payment) and one invoice may relate to several movements (part payments, or corrections.") ) (:documentation "An entry in the journal. A movement with a positive amount is a credit, (defmethod initialize-instance ((self movement) &key amount-ttc amount-ht invoice-fiscal-id &allow-other-keys) " DOES: Checks that the values for the fields are within limits. " (declare (ignorable self)) (when *max-movement-amount* (when amount-ttc (when (< *max-movement-amount* (abs amount-ttc)) (error "amount-ttc too big ~S." amount-ttc))) (when amount-ht (if (< *max-movement-amount* (abs amount-ht)) (error "amount-ht too big ~S." amount-ht)))) (when invoice-fiscal-id (unless (get-person-with-fiscal-id *invoice-set* invoice-fiscal-id) (warn "Unknown person (fiscal-id=~S)." invoice-fiscal-id))) INITIALIZE - INSTANCE (defmethod amount-ht ((self movement)) (- (amount-ttc self) (amount-vat self))) (defparameter *movement-kinds* '(:prestacion-nacional :prestacion-intracomunitaria :impuesto :inversion :gasto-corriente (defun make-movement-from-invoice (invoice) " RETURN: A new instance of MOVEMENT filled with data from invoice. " (let (kind amount-sign fiscal-id) (cond ((member (issuer-fiscal-id invoice) (fisc-fiscal-ids *invoice-set*) :test (function string-equal)) (setf kind :impuesto amount-sign -1 fiscal-id (issuer-fiscal-id invoice))) ((equalp (issuer-fiscal-id invoice) (fiscal-id *invoice-set*)) (setf kind (if (zerop (total-vat invoice)) :prestacion-intracomunitaria :prestacion-nacional) amount-sign 1 fiscal-id (payer-fiscal-id invoice))) (t (setf kind :gasto-corriente amount-sign -1 fiscal-id (issuer-fiscal-id invoice)))) (make-instance 'movement :date (date invoice) :amount-ttc (* (total-ttc invoice) amount-sign) :amount-vat (* (total-vat invoice) amount-sign) :description (title invoice) :kind kind :invoice-fiscal-id fiscal-id :invoice-numbers (define-condition movement-error (simple-error) ((date :accessor movement-error-date :initarg :date) (amount-ttc :accessor movement-error-amount-ttc :initarg :amount-ttc) (vat-rate :accessor movement-error-vat-rate :initarg :vat-rate) (nif :accessor movement-error-nif :initarg :nif) (fac-l :accessor movement-error-fac-l :initarg :fac-l) (description :accessor movement-error-description :initarg :description) (kind :accessor movement-error-kind :initarg :kind))) (defun make-movement (date amount-ttc vat-rate nif fac-l description kind) " RETURN: A new instance of MOVEMENT filled with the given data ." (macrolet ((err (ctrl &rest args) `(error 'movement-error :format-control ,ctrl :format-arguments (list ,@args) :date date :amount-ttc amount-ttc :vat-rate vat-rate :nif nif :fac-l fac-l :description description :kind kind))) (unless (member kind *movement-kinds*) (err "Invalid kind ~A." kind)) (when (< vat-rate -2) (err "VAT-RATE must always be >= 0.")) (unless (eq kind :prestacion-intracomunitaria) (when (eq kind :prestacion-nacional) (unless (negativep amount-ttc) (err "AMOUNT-TTC must be > 0 for an entry of kind ~A." kind)))) (cond ((eq kind :prestacion-nacional) (when (<= vat-rate 0) (err "VAT-RATE must be > 0.00 for an entry of kind ~A." kind))) ((member kind '(:prestacion-intracomunitaria :impuesto)) (if (< 0 vat-rate) (err "VAT-RATE must be = 0 for an entry of kind ~A." kind)))) (make-instance 'movement :date date :amount-ttc amount-ttc :amount-vat (/ (* amount-ttc vat-rate) (+ 1 vat-rate)) :description description :kind kind :invoice-fiscal-id nif :invoice-numbers fac-l))) (defmethod is-credit ((self movement)) " RETURN: Whether the SELF is a credit movement. " (defmethod vat-rate ((self movement)) " RETURN: A computed VAT rate for this movement. " (if (zerop (amount-magnitude (amount-ht self))) 0 (/ (round (* 100 (/ (amount-magnitude (amount-vat self)) (amount-magnitude (amount-ht self))))) 100))) (defmethod credit-ht ((self movement)) (if (is-credit self) (amount-ht self) (amount-zero (currency (amount-ht self))))) (defmethod credit-vat ((self movement)) (if (is-credit self) (amount-vat self) (amount-zero (currency (amount-vat self))))) (defmethod debit-ht ((self movement)) (if (is-credit self) (amount-zero (currency (amount-ht self))) (- (amount-ht self)))) (defmethod debit-vat ((self movement)) (if (is-credit self) (amount-zero (currency (amount-vat self))) (- (amount-vat self)))) (defmethod debit-vat-inversion ((self movement)) (if (eq :inversion (kind self)) (debit-vat self) (amount-zero (currency (debit-vat self))))) (defmethod debit-vat-corriente ((self movement)) (if (eq :gasto-corriente (kind self)) (debit-vat self) (amount-zero (currency (debit-vat self))))) (defmethod invoices ((self movement)) " RETURN: A list of INVOICE instances related to this entry. " (let ((fiscal-id (if (and (is-credit self) (not (equal (kind self) :gasto-corriente))) (fiscal-id *invoice-set*) (invoice-fiscal-id self)))) (remove nil (mapcar (lambda (number) (get-invoice-with-issuer-and-number *invoice-set* fiscal-id number)) (defun trim-justify-and-split-text (text width) " DOES: Trim spaces on each line. justify each paragraph. RETURN: The justified text. " (let ((lines (split-lines text)) (paragraphs '()) (current-paragraph '())) (when current-paragraph (push (apply (function concatenate) 'string (nreverse current-paragraph)) paragraphs))) (if (string= line "") (when current-paragraph (push (apply (function concatenate) 'string (nreverse current-paragraph)) paragraphs)) (progn (push " " current-paragraph) (push line current-paragraph)))) (or (mapcan (lambda (para) (split-lines (string-justify-left para width 0))) (nreverse paragraphs)) (defmethod generate ((self movement) &key (stream t) (verbose nil) (language :en)) " DOES: format and insert this entry. " (let ((id (invoice-fiscal-id self)) person (name "") name-l (movement-sign (if (is-credit self) 1 -1)) (invoices-sign 1)) (when verbose (format *trace-output* "Generating ~A ~A ~A~%" (class-name (class-of self)) (date self) (amount-ttc self))) first line : (if id (progn (setf person (get-person-with-fiscal-id *invoice-set* id)) (when person (setf name (name person)))) (setf id "")) (setf name-l (trim-justify-and-split-text name 38)) (format stream "~3A ~10A ~23@A ~A~%" (cond ((is-credit self) "ING") ((eq :impuesto (kind self)) "IMP") (t "GAS")) (date self) id (car name-l)) (dolist (name (cdr name-l)) (format stream "~38A ~A~%" "" name)) IMPORTE IVA% + IVA TOTAL NUMERO FACTURA o DESCRIPCION (let* ((zero (amount-zero (currency (amount-ht self)))) (t-ht zero) (t-vat zero) (t-ttc zero)) (dolist (invoice (invoices self)) (setf t-ttc (+ t-ttc (total-ttc invoice)))) (setf invoices-sign (* movement-sign (if (negativep t-ttc) -1 1)))) (let* ((title-l (trim-justify-and-split-text (title invoice) 38)) (i-ht (total-ht invoice)) (i-vat (total-vat invoice)) (i-ttc (total-ttc invoice))) (setf t-ht (+ t-ht i-ht) t-vat (+ t-vat i-vat) t-ttc (+ t-ttc i-ttc)) (format stream " ~2,,9$ ~4,1F% ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude (* i-ht invoices-sign)) (* 100 (vat-rate invoice)) (amount-magnitude (* i-vat invoices-sign)) (amount-magnitude (* i-ttc invoices-sign)) (invoice-number invoice)) (dolist (title title-l) (format stream "~38A ~A~%" "" title)))) (unless (and (zerop t-ht) (zerop t-vat) (zerop t-ttc)) (handler-case (unless (= (amount-ttc self) (* t-ttc invoices-sign)) (let* ((diff-ht (- (amount-ht self) (* t-ht invoices-sign))) (diff-vat (- (amount-vat self) (* t-vat invoices-sign))) (diff-ttc (- (amount-ttc self) (* t-ttc invoices-sign)))) (format stream " ~2,,9$ ~5A ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude diff-ht) "" (amount-magnitude diff-vat) (amount-magnitude diff-ttc) "Diferencia"))) (multi-currency-error () (let ((cambio (if (zerop t-ttc) 0 (/ (amount-ttc self) (* t-ttc invoices-sign))))) (format stream " ~9A ~5A ~8A ~2,,9$ ~A ~A -> ~A~%" "" "" "" cambio (localize *invoice-strings* language "Currency change") (currency-alphabetic-code (currency t-ttc)) (currency-alphabetic-code (currency (amount-ttc self))))))) (format stream " --------- ----- -------- ---------~%"))) (let* ((desc-l (trim-justify-and-split-text (description self) 38)) (desc (pop desc-l))) (format stream " ~2,,9$ ~4,1F% ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude (amount-ht self)) (* 100 (vat-rate self)) (amount-magnitude (amount-vat self)) (amount-magnitude (amount-ttc self)) desc) (dolist (desc desc-l) (format stream "~38A ~A~%" "" desc)))) (format stream "--- ---------- ----------------------- ~ JOURNAL - ENTRY ( amount - ht ( amount - zero * default - currency * ) : type amount ) ( nif " s / n " : type string ) ( defmethod date ( ( self journal - entry ) ) ( journal - entry - date self ) ) ( defmethod nif ( ( self journal - entry ) ) ( journal - entry - nif self ) ) ( defmethod invoices ( ( self journal - entry ) ) ( journal - entry - invoices self ) ) ( defmethod initialize - instance ( ( self journal - entry ) ' (: - NACIONAL : PRESTACION - INTRACOMUNITARIA : IMPUESTO : ADQUISICION - INTRACOMUNITARIA ) ) ( ERROR " VAT - RATE must always be > = 0.00 . " ) ) ( unless ( EQ KIND : PRESTACION - INTRACOMUNITARIA ) ( when ( > = 0.00 AMOUNT - HT ) ( ERROR " AMOUNT - HT must be > 0.00 for an entry of kind ~A. " KIND ) ) ) ) ( ERROR " VAT - RATE must be > 0.00 for an entry of kind ~A. " KIND ) ) ) ( ( MEMBER KIND ' (: - INTRACOMUNITARIA : IMPUESTO ) ) ( ERROR " VAT - RATE must be = 0.00 for an entry of kind ~A. " KIND ) ) ) ( ERROR " VAT - RATE must be > 0.00 for an entry of kind ~A. " KIND ) ) ) ) ( DEFMETHOD IS - CREDIT ( ( SELF JOURNAL - ENTRY ) ) ( DEFMETHOD CREDIT - HT ( ( SELF JOURNAL - ENTRY ) ) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ) ) ( DEFMETHOD CREDIT - VAT ( ( SELF JOURNAL - ENTRY ) ) ( DEFMETHOD DEBIT - HT ( ( SELF JOURNAL - ENTRY ) ) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ( DEFMETHOD DEBIT - VAT ( ( SELF JOURNAL - ENTRY ) ) ( DEFMETHOD DEBIT - VAT - INVERSION ( ( SELF JOURNAL - ENTRY ) ) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ) ) ( DEFMETHOD DEBIT - VAT - CORRIENTE ( ( SELF JOURNAL - ENTRY ) ) ( amount - zero ( currency ( AMOUNT - HT SELF ) ) ) ) ) JOURNAL (defgeneric trimestre (journal) (:documentation "RETURN: The quarter of the journal (1 2 3 or 4).")) (defclass journal () ((sorted :initform nil :accessor sorted :type boolean :documentation "Indicates whether entries are sorted.") (entries :initform '() :initarg :entries :accessor entries :type list) (year :initform (date-year (calendar-current-date)) :initarg :year :accessor year :type (integer 1998 2070)) (trimestre :initform (1+ (truncate (1- (date-month (calendar-current-date))) 3)) :initarg :trimestre :accessor trimestre :type (member 1 2 3 4))) (:documentation "An account journal.")) (defmethod reset ((self journal)) " POST: (null (entries self)) " (setf (entries self) '() (defmethod add-entry ((self journal) (entry movement)) " DOES: Add the ENTRY into the journal. POST: (AND (MEMBER ENTRY (ENTRIES SELF)) (NOT (SORTED SELF))) " (push entry (entries self)) (defmethod ensure-sorted ((self journal)) " POST: (sorted *journal*) " (unless (sorted self) (setf (entries self) (sort (entries self) (lambda (a b) (date-after (date b) (date a)))) (defmethod extract ((self journal) year trimestre) " RETURN: The entries of the journal corresponding to the given YEAR and TRIMESTRE. " (ensure-sorted self) (remove-if (lambda (entry) (not (date-in-year-trimestre (date entry) year trimestre))) (defun journal-totals-of-entries (entries) "PRIVATE RETURN: a list containing the totals: credit-ht credit-vat debit-ht debit-vat-inversion debit-vat-corriente. " (if (null entries) (make-list 5 :initial-element (amount-zero *default-currency*)) (let* ((zero (amount-zero (currency (credit-ht (first entries))))) (credit-ht zero) (credit-vat zero) (debit-ht zero) (debit-vat-c zero) (debit-vat-i zero)) (mapcar (lambda (entry) (setf credit-ht (+ credit-ht (credit-ht entry)) credit-vat (+ credit-vat (credit-vat entry)) debit-ht (+ debit-ht (debit-ht entry)) debit-vat-c (+ debit-vat-c (debit-vat-corriente entry)) debit-vat-i (+ debit-vat-i (debit-vat-inversion entry)))) entries) (list credit-ht credit-vat debit-ht debit-vat-i debit-vat-c)))) (defun journal-split-and-justify-description (description width) "PRIVATE" (or (mapcan (lambda (line) (split-lines(string-justify-left line width 0))) (split-lines description)) (list " "))) (defun journal-print-header (year trimestre &key (stream t)) "PRIVATE" (format stream "----------------------------------------~ ---------------------------------------~%") (format stream "~36D - TRIMESTRE ~D~%" year trimestre) (format stream "--- ---------- ----------------------- ~ ----------------------------------------~%") (format stream "SEN FECHA IDENTIFICACION NOMBRE~%") (format stream "TID IMPORTE IVA% +IVA TOTAL ~ NUMERO FACTURA / DESCRIPTION~%") (format stream "--- --------- ----- -------- --------- ~ ---------------------------------------~%") (values)) (defun journal-print-trailer (&key (stream t)) "PRIVATE" (format stream " IMPORTE IVA TOTAL~%") (format stream "--- --------- ----- -------- --------- ~ ---------------------------------------~%") (values)) (defun journal-print-totals (totals &key (stream t)) "PRIVATE" (let ((credit-ht (nth 0 totals)) (credit-vat (nth 1 totals)) (debit-ht (nth 2 totals)) (debit-vat (+ (nth 3 totals) (nth 4 totals)))) (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude credit-ht) "" (amount-magnitude credit-vat) "" "Credito") (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude (- debit-ht)) "" (amount-magnitude (- debit-vat)) "" "Debido") (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude (- credit-ht debit-ht)) "" (amount-magnitude (- credit-vat debit-vat)) "" "Saldo") (values))) (defun kind-to-order (kind) (case kind ((:prestacion-nacional) 1) ((:prestacion-intracomunitaria) 2) ((:impuesto) 3) ((:inversion) 4) ((:gasto-corriente) 5) ((:adquisicion-intracomunitaria) 6) (otherwise 7))) (defmethod generate ((self journal) &key (stream t) (verbose nil) (language :en)) " DOES: Prints the formated entries of the journal onto the stream. " (ensure-sorted self) (let* ((entries (sort (extract self (year self) (trimestre self)) (lambda (a b) (cond ((= (kind-to-order (kind a)) (kind-to-order (kind b))) (not (date-after (date a) (date b)))) (t (< (kind-to-order (kind a)) (kind-to-order (kind b)))))))) (totals (journal-totals-of-entries entries))) (format stream "~2%") (journal-print-header (year self) (trimestre self) :stream stream) (mapcar (lambda (entry) (generate entry :stream stream :verbose verbose :language language)) entries) (journal-print-trailer :stream stream) (journal-print-totals totals :stream stream) (format stream "~2%") (values))) (defmacro person (&rest args) " DO: Add to the *INVOICE-SET* a new FISCAL-PERSON instance created with the give initargs. " `(add-person *invoice-set* (make-instance 'fiscal-person ,@args))) (defmacro make-bank-reference (&rest args) " RETURN: A new instance of BANK-REFERENCE with the given initargs. " `(make-instance 'bank-reference ,@args)) (defmacro invoice (&rest args) (do ((args args) (attributes '()) (lines '()) (vinst (gensym))) ((null args) `(let ((,vinst (make-instance 'invoice ,@(nreverse attributes)))) ,@(mapcar (lambda (line) `(add-line ,vinst (make-instance 'invoice-line ,@line))) (nreverse lines)) (add-invoice *invoice-set* ,vinst))) (cond ((keywordp (car args)) (push (pop args) attributes) (push (pop args) attributes)) ((atom (car args)) (error "Invalid invoice attribute ~S" (pop args))) ((eql 'line (caar args)) (push (list* :object-id (string (gensym "L")) (cdr (pop args))) lines)) (defmacro journal-entry (date amount-ttc vat-rate nif fac description kind) " DOES: Add a new journal entry. AMOUNT-TTC is the total paid (including VAT) expressed in Euros. VAT-RATE is the V.A.T percentage. " `(add-entry *journal* (make-movement (date-from-string ',date) ',amount-ttc ',vat-rate ',nif (if (listp ',fac) ',fac (list ',fac)) JOURNAL - ENTRY (defun load-journal (path &key (verbose *load-verbose*) (print *load-print*)) " DO: Load the journal at PATH. " (let ((*readtable* *currency-readtable*))) (load path :verbose verbose :print print))
a10da1c4a5e771a139ec35cdbd3136316ac173fd8c5de225091a9ad043cbc0e2
mhuebert/yawn
env.cljc
(ns yawn.env (:require [clojure.walk :as walk] #?@(:clj [[net.cgrand.macrovich :as macros]] :cljs [[applied-science.js-interop :as j] yawn.react])) #?(:cljs (:require-macros yawn.env [net.cgrand.macrovich :as macros]))) (defn merge-opts [x y] (merge-with (fn [x y] (if (map? x) (merge x y) y)) x y)) (defonce !compile-opts (atom {})) (defn get-opts [sym] (or (@!compile-opts sym) (prn :not-found sym (keys @!compile-opts)) (throw (ex-info "Compile opts not found" {:sym sym :keys (keys @!compile-opts)})))) (defonce defaults (atom nil)) (defn set-defaults! [options] (reset! defaults options)) (defn dequote [x] (if (list? x) (second x) x)) (defn qualified-sym [n] (symbol (name (.-name *ns*)) (name n))) (defmacro def-options [name opts] (assert @defaults "Defaults have not yet been set") (let [opts (merge-opts @defaults opts) quote-it (fn [x] `(quote ~x)) stage (fn [form pick] (walk/postwalk (fn [x] {:pre [(#{:compile :interpret} pick)]} (if (and (map? x) (:compile x)) (get x pick) x)) form)) js-form `(~'applied-science.js-interop/lit ~(-> (dequote opts) (stage :interpret) (dissoc :skip-types :warn-on-interpretation? :rewrite-for?))) qualified-name `(quote ~(qualified-sym name)) clj-form (-> opts (stage :compile) (assoc :js-options-sym qualified-name) (update :skip-types quote-it) (update :custom-elements quote-it))] `(do (swap! !compile-opts assoc ~qualified-name ~clj-form) ~(macros/case :cljs `(def ~name ~js-form) :clj `(def ~name (@!compile-opts ~qualified-name))))))
null
https://raw.githubusercontent.com/mhuebert/yawn/4491c133b12dedd2aaff7c810833a2f7840a5cd2/src/main/yawn/env.cljc
clojure
(ns yawn.env (:require [clojure.walk :as walk] #?@(:clj [[net.cgrand.macrovich :as macros]] :cljs [[applied-science.js-interop :as j] yawn.react])) #?(:cljs (:require-macros yawn.env [net.cgrand.macrovich :as macros]))) (defn merge-opts [x y] (merge-with (fn [x y] (if (map? x) (merge x y) y)) x y)) (defonce !compile-opts (atom {})) (defn get-opts [sym] (or (@!compile-opts sym) (prn :not-found sym (keys @!compile-opts)) (throw (ex-info "Compile opts not found" {:sym sym :keys (keys @!compile-opts)})))) (defonce defaults (atom nil)) (defn set-defaults! [options] (reset! defaults options)) (defn dequote [x] (if (list? x) (second x) x)) (defn qualified-sym [n] (symbol (name (.-name *ns*)) (name n))) (defmacro def-options [name opts] (assert @defaults "Defaults have not yet been set") (let [opts (merge-opts @defaults opts) quote-it (fn [x] `(quote ~x)) stage (fn [form pick] (walk/postwalk (fn [x] {:pre [(#{:compile :interpret} pick)]} (if (and (map? x) (:compile x)) (get x pick) x)) form)) js-form `(~'applied-science.js-interop/lit ~(-> (dequote opts) (stage :interpret) (dissoc :skip-types :warn-on-interpretation? :rewrite-for?))) qualified-name `(quote ~(qualified-sym name)) clj-form (-> opts (stage :compile) (assoc :js-options-sym qualified-name) (update :skip-types quote-it) (update :custom-elements quote-it))] `(do (swap! !compile-opts assoc ~qualified-name ~clj-form) ~(macros/case :cljs `(def ~name ~js-form) :clj `(def ~name (@!compile-opts ~qualified-name))))))
58d0796a5e458f6bd04d5a16d808e78b99cb42d432ce92d9d176f8a74128c3ca
haskell/lsp
Replay.hs
-- | A testing tool for replaying captured client logs back to a server, -- and validating that the server output matches up with another log. module Language.LSP.Test.Replay ( -- replaySession ) where import Prelude hiding (id) import Control.Concurrent import Control.Monad.IO.Class import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.Text as T import Language.LSP.Types import Language.LSP.Types.Lens as LSP import Data.Aeson import Data.Default import Data.List import Data.Maybe import Control.Lens hiding (List) import Control.Monad import System.FilePath import System.IO import Language.LSP.Test import Language.LSP.Test.Compat import Language.LSP.Test.Files import Language.LSP.Test.Decoding import Language.LSP.Test.Server import Language.LSP.Test.Session -- | Replays a captured client output and -- makes sure it matches up with an expected response . -- The session directory should have a captured session file in it -- named " session.log " . -- You can get these capture files from ' Language . Haskell . LSP.resCaptureFile ' in -- . replaySession : : String -- ^ The command to run the server . - > FilePath -- ^ The recorded session directory . - > IO ( ) = do entries < - B.lines < $ > B.readFile ( sessionDir < / > " session.log " ) -- decode session let unswappedEvents = map ( fromJust . decode ) entries \serverIn serverOut serverProc - > do pid < - getProcessID serverProc events < - swapCommands pid < $ > swapFiles sessionDir unswappedEvents let clientEvents = filter isClientMsg events = filter isServerMsg events clientMsgs = map ( \(FromClient _ msg ) - > msg ) clientEvents serverMsgs = filter ( not . shouldSkip ) $ map ( \(FromServer _ msg ) - > msg ) = getRequestMap clientMsgs reqSema < - newEmptyMVar rspSema < - newEmptyMVar passSema < - newEmptyMVar sessionThread < - liftIO $ forkIO $ runSessionWithHandles serverIn serverOut serverProc ( listenServer serverMsgs requestMap reqSema rspSema passSema mainThread ) def fullCaps sessionDir ( return ( ) ) -- No finalizer cleanup ( sendMessages clientMsgs reqSema rspSema ) takeMVar passSema where isClientMsg ( FromClient _ _ ) = True isClientMsg _ = False isServerMsg ( FromServer _ _ ) = True isServerMsg _ = False sendMessages : : [ FromClientMessage ] - > MVar LspId - > MVar LspIdRsp - > Session ( ) sendMessages [ ] _ _ = return ( ) sendMessages ( nextMsg : remainingMsgs ) reqSema = handleClientMessage request response notification nextMsg where -- TODO : May need to prevent premature exit notification being sent notification msg@(NotificationMessage _ Exit _ ) = do liftIO $ putStrLn " Will send exit notification soon " liftIO $ threadDelay 10000000 sendMessage msg liftIO $ error " Done " notification msg@(NotificationMessage _ m _ ) = do sendMessage msg liftIO $ putStrLn $ " Sent a notification " + + show m sendMessages remainingMsgs reqSema rspSema request msg@(RequestMessage _ i d m _ ) = do sendRequestMessage msg liftIO $ putStrLn $ " Sent a request i d " + + show i d + + " : " + + show m + + " \nWaiting for a response " rsp < - liftIO $ takeMVar rspSema when ( responseId i d /= rsp ) $ error $ " Expected i d " + + show i d + + " , got " + + show rsp sendMessages remainingMsgs reqSema rspSema response msg@(ResponseMessage _ i d _ ) = do liftIO $ putStrLn $ " Waiting for request i d " + + show i d + + " from the server " reqId < - liftIO $ takeMVar reqSema if responseId reqId /= i d then error $ " Expected i d " + + show reqId + + " , got " + + show reqId else do sendResponse msg liftIO $ putStrLn $ " Sent response to request i d " + + show i d sendMessages remainingMsgs reqSema sendRequestMessage : : ( ToJSON a , ToJSON b ) = > RequestMessage ClientMethod a b - > Session ( ) sendRequestMessage req = do -- Update the request map reqMap < - requestMap < $ > ask liftIO $ modifyMVar _ reqMap $ \r - > return $ updateRequestMap r ( req ^. LSP.id ) ( req ^. method ) sendMessage req isNotification : : FromServerMessage - > Bool isNotification ( NotPublishDiagnostics _ ) = True isNotification ( NotLogMessage _ ) = True isNotification ( NotShowMessage _ ) = True isNotification ( NotCancelRequestFromServer _ ) = True isNotification _ = False listenServer : : [ FromServerMessage ] - > - > MVar LspId - > MVar MVar ( ) - > ThreadId - > Handle - > SessionContext - > IO ( ) listenServer [ ] _ _ _ passSema _ _ _ = putMVar passSema ( ) listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx = do msgBytes < - getNextMessage serverOut let msg = decodeFromServerMsg reqMap msgBytes handleServerMessage request response notification msg if shouldSkip msg then listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx else if inRightOrder msg expectedMsgs then listenServer ( delete msg expectedMsgs ) reqMap reqSema rspSema passSema mainThreadId serverOut ctx else let remainingMsgs = ( not . isNotification ) expectedMsgs + + [ head $ dropWhile isNotification expectedMsgs ] exc = ReplayOutOfOrder msg remainingMsgs in liftIO $ throwTo mainThreadId exc where response : : ResponseMessage a - > IO ( ) response res = do " Got response for i d " + + show ( res ^. i d ) putMVar ( res ^. i d ) -- unblock the handler waiting to send a request request : : RequestMessage ServerMethod a b - > IO ( ) request req = do putStrLn $ " Got request for i d " + + show ( req ^. i d ) + + " " + + show ( req ^. method ) putMVar reqSema ( req ^. i d ) -- unblock the handler waiting for a response notification : : NotificationMessage ServerMethod a - > IO ( ) notification n = putStrLn $ " Got notification " + + show ( n ^. method ) -- TODO : QuickCheck tests ? -- | Checks wether or not the message appears in the right order -- @ N1 N2 N3 REQ1 N4 N5 REQ2 RES1 @ -- given N2 , notification order does n't matter . -- @ N1 N3 REQ1 N4 N5 REQ2 RES1 @ -- given REQ1 -- @ N1 N3 N4 N5 REQ2 RES1 @ -- given RES1 -- @ N1 N3 N4 N5 XXXX RES1 @ False ! -- Order of requests and responses matter inRightOrder : : FromServerMessage - > [ FromServerMessage ] - > Bool inRightOrder _ [ ] = error " Why is this empty " inRightOrder received ( expected : msgs ) | received = = expected = True | isNotification expected = inRightOrder received msgs | otherwise = False -- | Ignore logging notifications since they vary from session to session shouldSkip : : FromServerMessage - > Bool shouldSkip ( NotLogMessage _ ) = True shouldSkip ( NotShowMessage _ ) = True shouldSkip ( ReqShowMessage _ ) = True shouldSkip _ = False -- | Swaps out any commands uniqued with process IDs to match the specified process ID swapCommands : : Int - > [ Event ] - > [ Event ] swapCommands _ [ ] = [ ] ( FromClient t ( ReqExecuteCommand req):xs ) = FromClient t ( ReqExecuteCommand swapped):swapCommands pid xs where swapped = params . command .~ newCmd $ req newCmd = swapPid pid ( req ^. params . command ) ( FromServer t ( RspInitialize rsp):xs ) = FromServer t ( RspInitialize swapped):swapCommands pid xs where swapped = case newCommands of Just cmds - > result . _ Right . LSP.capabilities . executeCommandProvider . _ Just . commands .~ cmds $ rsp Nothing - > rsp oldCommands = rsp ^ ? result . _ Right . LSP.capabilities . executeCommandProvider . _ Just . commands = fmap ( fmap ( swapPid pid ) ) oldCommands swapCommands pid ( x : xs ) = x : hasPid : : T.Text - > Bool hasPid = ( > = 2 ) . T.length . T.filter ( ' : ' = : Int - > T.Text - > T.Text swapPid pid t | hasPid t = T.append ( T.pack $ show pid ) $ T.dropWhile ( /= ' :') t | otherwise = t -- | Replays a captured client output and -- makes sure it matches up with an expected response. -- The session directory should have a captured session file in it -- named "session.log". -- You can get these capture files from 'Language.Haskell.LSP.resCaptureFile' in -- haskell-lsp. replaySession :: String -- ^ The command to run the server. -> FilePath -- ^ The recorded session directory. -> IO () replaySession serverExe sessionDir = do entries <- B.lines <$> B.readFile (sessionDir </> "session.log") -- decode session let unswappedEvents = map (fromJust . decode) entries withServer serverExe False id $ \serverIn serverOut serverProc -> do pid <- getProcessID serverProc events <- swapCommands pid <$> swapFiles sessionDir unswappedEvents let clientEvents = filter isClientMsg events serverEvents = filter isServerMsg events clientMsgs = map (\(FromClient _ msg) -> msg) clientEvents serverMsgs = filter (not . shouldSkip) $ map (\(FromServer _ msg) -> msg) serverEvents requestMap = getRequestMap clientMsgs reqSema <- newEmptyMVar rspSema <- newEmptyMVar passSema <- newEmptyMVar mainThread <- myThreadId sessionThread <- liftIO $ forkIO $ runSessionWithHandles serverIn serverOut serverProc (listenServer serverMsgs requestMap reqSema rspSema passSema mainThread) def fullCaps sessionDir (return ()) -- No finalizer cleanup (sendMessages clientMsgs reqSema rspSema) takeMVar passSema killThread sessionThread where isClientMsg (FromClient _ _) = True isClientMsg _ = False isServerMsg (FromServer _ _) = True isServerMsg _ = False sendMessages :: [FromClientMessage] -> MVar LspId -> MVar LspIdRsp -> Session () sendMessages [] _ _ = return () sendMessages (nextMsg:remainingMsgs) reqSema rspSema = handleClientMessage request response notification nextMsg where -- TODO: May need to prevent premature exit notification being sent notification msg@(NotificationMessage _ Exit _) = do liftIO $ putStrLn "Will send exit notification soon" liftIO $ threadDelay 10000000 sendMessage msg liftIO $ error "Done" notification msg@(NotificationMessage _ m _) = do sendMessage msg liftIO $ putStrLn $ "Sent a notification " ++ show m sendMessages remainingMsgs reqSema rspSema request msg@(RequestMessage _ id m _) = do sendRequestMessage msg liftIO $ putStrLn $ "Sent a request id " ++ show id ++ ": " ++ show m ++ "\nWaiting for a response" rsp <- liftIO $ takeMVar rspSema when (responseId id /= rsp) $ error $ "Expected id " ++ show id ++ ", got " ++ show rsp sendMessages remainingMsgs reqSema rspSema response msg@(ResponseMessage _ id _) = do liftIO $ putStrLn $ "Waiting for request id " ++ show id ++ " from the server" reqId <- liftIO $ takeMVar reqSema if responseId reqId /= id then error $ "Expected id " ++ show reqId ++ ", got " ++ show reqId else do sendResponse msg liftIO $ putStrLn $ "Sent response to request id " ++ show id sendMessages remainingMsgs reqSema rspSema sendRequestMessage :: (ToJSON a, ToJSON b) => RequestMessage ClientMethod a b -> Session () sendRequestMessage req = do -- Update the request map reqMap <- requestMap <$> ask liftIO $ modifyMVar_ reqMap $ \r -> return $ updateRequestMap r (req ^. LSP.id) (req ^. method) sendMessage req isNotification :: FromServerMessage -> Bool isNotification (NotPublishDiagnostics _) = True isNotification (NotLogMessage _) = True isNotification (NotShowMessage _) = True isNotification (NotCancelRequestFromServer _) = True isNotification _ = False listenServer :: [FromServerMessage] -> RequestMap -> MVar LspId -> MVar LspIdRsp -> MVar () -> ThreadId -> Handle -> SessionContext -> IO () listenServer [] _ _ _ passSema _ _ _ = putMVar passSema () listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx = do msgBytes <- getNextMessage serverOut let msg = decodeFromServerMsg reqMap msgBytes handleServerMessage request response notification msg if shouldSkip msg then listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx else if inRightOrder msg expectedMsgs then listenServer (delete msg expectedMsgs) reqMap reqSema rspSema passSema mainThreadId serverOut ctx else let remainingMsgs = takeWhile (not . isNotification) expectedMsgs ++ [head $ dropWhile isNotification expectedMsgs] exc = ReplayOutOfOrder msg remainingMsgs in liftIO $ throwTo mainThreadId exc where response :: ResponseMessage a -> IO () response res = do putStrLn $ "Got response for id " ++ show (res ^. id) putMVar rspSema (res ^. id) -- unblock the handler waiting to send a request request :: RequestMessage ServerMethod a b -> IO () request req = do putStrLn $ "Got request for id " ++ show (req ^. id) ++ " " ++ show (req ^. method) putMVar reqSema (req ^. id) -- unblock the handler waiting for a response notification :: NotificationMessage ServerMethod a -> IO () notification n = putStrLn $ "Got notification " ++ show (n ^. method) -- TODO: QuickCheck tests? -- | Checks wether or not the message appears in the right order -- @ N1 N2 N3 REQ1 N4 N5 REQ2 RES1 @ -- given N2, notification order doesn't matter. -- @ N1 N3 REQ1 N4 N5 REQ2 RES1 @ -- given REQ1 -- @ N1 N3 N4 N5 REQ2 RES1 @ -- given RES1 -- @ N1 N3 N4 N5 XXXX RES1 @ False! -- Order of requests and responses matter inRightOrder :: FromServerMessage -> [FromServerMessage] -> Bool inRightOrder _ [] = error "Why is this empty" inRightOrder received (expected : msgs) | received == expected = True | isNotification expected = inRightOrder received msgs | otherwise = False -- | Ignore logging notifications since they vary from session to session shouldSkip :: FromServerMessage -> Bool shouldSkip (NotLogMessage _) = True shouldSkip (NotShowMessage _) = True shouldSkip (ReqShowMessage _) = True shouldSkip _ = False -- | Swaps out any commands uniqued with process IDs to match the specified process ID swapCommands :: Int -> [Event] -> [Event] swapCommands _ [] = [] swapCommands pid (FromClient t (ReqExecuteCommand req):xs) = FromClient t (ReqExecuteCommand swapped):swapCommands pid xs where swapped = params . command .~ newCmd $ req newCmd = swapPid pid (req ^. params . command) swapCommands pid (FromServer t (RspInitialize rsp):xs) = FromServer t (RspInitialize swapped):swapCommands pid xs where swapped = case newCommands of Just cmds -> result . _Right . LSP.capabilities . executeCommandProvider . _Just . commands .~ cmds $ rsp Nothing -> rsp oldCommands = rsp ^? result . _Right . LSP.capabilities . executeCommandProvider . _Just . commands newCommands = fmap (fmap (swapPid pid)) oldCommands swapCommands pid (x:xs) = x:swapCommands pid xs hasPid :: T.Text -> Bool hasPid = (>= 2) . T.length . T.filter (':' ==) swapPid :: Int -> T.Text -> T.Text swapPid pid t | hasPid t = T.append (T.pack $ show pid) $ T.dropWhile (/= ':') t | otherwise = t -}
null
https://raw.githubusercontent.com/haskell/lsp/6fbe0669f1b79f3623181d1fc89c156f9f65011d/lsp-test/src/Language/LSP/Test/Replay.hs
haskell
| A testing tool for replaying captured client logs back to a server, and validating that the server output matches up with another log. replaySession | Replays a captured client output and makes sure it matches up with an expected response . The session directory should have a captured session file in it named " session.log " . You can get these capture files from ' Language . Haskell . LSP.resCaptureFile ' in . ^ The command to run the server . ^ The recorded session directory . decode session No finalizer cleanup TODO : May need to prevent premature exit notification being sent Update the request map unblock the handler waiting to send a request unblock the handler waiting for a response TODO : QuickCheck tests ? | Checks wether or not the message appears in the right order @ N1 N2 N3 REQ1 N4 N5 REQ2 RES1 @ given N2 , notification order does n't matter . @ N1 N3 REQ1 N4 N5 REQ2 RES1 @ given REQ1 @ N1 N3 N4 N5 REQ2 RES1 @ given RES1 @ N1 N3 N4 N5 XXXX RES1 @ False ! Order of requests and responses matter | Ignore logging notifications since they vary from session to session | Swaps out any commands uniqued with process IDs to match the specified process ID | Replays a captured client output and makes sure it matches up with an expected response. The session directory should have a captured session file in it named "session.log". You can get these capture files from 'Language.Haskell.LSP.resCaptureFile' in haskell-lsp. ^ The command to run the server. ^ The recorded session directory. decode session No finalizer cleanup TODO: May need to prevent premature exit notification being sent Update the request map unblock the handler waiting to send a request unblock the handler waiting for a response TODO: QuickCheck tests? | Checks wether or not the message appears in the right order @ N1 N2 N3 REQ1 N4 N5 REQ2 RES1 @ given N2, notification order doesn't matter. @ N1 N3 REQ1 N4 N5 REQ2 RES1 @ given REQ1 @ N1 N3 N4 N5 REQ2 RES1 @ given RES1 @ N1 N3 N4 N5 XXXX RES1 @ False! Order of requests and responses matter | Ignore logging notifications since they vary from session to session | Swaps out any commands uniqued with process IDs to match the specified process ID
module Language.LSP.Test.Replay ) where import Prelude hiding (id) import Control.Concurrent import Control.Monad.IO.Class import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.Text as T import Language.LSP.Types import Language.LSP.Types.Lens as LSP import Data.Aeson import Data.Default import Data.List import Data.Maybe import Control.Lens hiding (List) import Control.Monad import System.FilePath import System.IO import Language.LSP.Test import Language.LSP.Test.Compat import Language.LSP.Test.Files import Language.LSP.Test.Decoding import Language.LSP.Test.Server import Language.LSP.Test.Session - > IO ( ) = do entries < - B.lines < $ > B.readFile ( sessionDir < / > " session.log " ) let unswappedEvents = map ( fromJust . decode ) entries \serverIn serverOut serverProc - > do pid < - getProcessID serverProc events < - swapCommands pid < $ > swapFiles sessionDir unswappedEvents let clientEvents = filter isClientMsg events = filter isServerMsg events clientMsgs = map ( \(FromClient _ msg ) - > msg ) clientEvents serverMsgs = filter ( not . shouldSkip ) $ map ( \(FromServer _ msg ) - > msg ) = getRequestMap clientMsgs reqSema < - newEmptyMVar rspSema < - newEmptyMVar passSema < - newEmptyMVar sessionThread < - liftIO $ forkIO $ runSessionWithHandles serverIn serverOut serverProc ( listenServer serverMsgs requestMap reqSema rspSema passSema mainThread ) def fullCaps sessionDir ( sendMessages clientMsgs reqSema rspSema ) takeMVar passSema where isClientMsg ( FromClient _ _ ) = True isClientMsg _ = False isServerMsg ( FromServer _ _ ) = True isServerMsg _ = False sendMessages : : [ FromClientMessage ] - > MVar LspId - > MVar LspIdRsp - > Session ( ) sendMessages [ ] _ _ = return ( ) sendMessages ( nextMsg : remainingMsgs ) reqSema = handleClientMessage request response notification nextMsg where notification msg@(NotificationMessage _ Exit _ ) = do liftIO $ putStrLn " Will send exit notification soon " liftIO $ threadDelay 10000000 sendMessage msg liftIO $ error " Done " notification msg@(NotificationMessage _ m _ ) = do sendMessage msg liftIO $ putStrLn $ " Sent a notification " + + show m sendMessages remainingMsgs reqSema rspSema request msg@(RequestMessage _ i d m _ ) = do sendRequestMessage msg liftIO $ putStrLn $ " Sent a request i d " + + show i d + + " : " + + show m + + " \nWaiting for a response " rsp < - liftIO $ takeMVar rspSema when ( responseId i d /= rsp ) $ error $ " Expected i d " + + show i d + + " , got " + + show rsp sendMessages remainingMsgs reqSema rspSema response msg@(ResponseMessage _ i d _ ) = do liftIO $ putStrLn $ " Waiting for request i d " + + show i d + + " from the server " reqId < - liftIO $ takeMVar reqSema if responseId reqId /= i d then error $ " Expected i d " + + show reqId + + " , got " + + show reqId else do sendResponse msg liftIO $ putStrLn $ " Sent response to request i d " + + show i d sendMessages remainingMsgs reqSema sendRequestMessage : : ( ToJSON a , ToJSON b ) = > RequestMessage ClientMethod a b - > Session ( ) sendRequestMessage req = do reqMap < - requestMap < $ > ask liftIO $ modifyMVar _ reqMap $ \r - > return $ updateRequestMap r ( req ^. LSP.id ) ( req ^. method ) sendMessage req isNotification : : FromServerMessage - > Bool isNotification ( NotPublishDiagnostics _ ) = True isNotification ( NotLogMessage _ ) = True isNotification ( NotShowMessage _ ) = True isNotification ( NotCancelRequestFromServer _ ) = True isNotification _ = False listenServer : : [ FromServerMessage ] - > - > MVar LspId - > MVar MVar ( ) - > ThreadId - > Handle - > SessionContext - > IO ( ) listenServer [ ] _ _ _ passSema _ _ _ = putMVar passSema ( ) listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx = do msgBytes < - getNextMessage serverOut let msg = decodeFromServerMsg reqMap msgBytes handleServerMessage request response notification msg if shouldSkip msg then listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx else if inRightOrder msg expectedMsgs then listenServer ( delete msg expectedMsgs ) reqMap reqSema rspSema passSema mainThreadId serverOut ctx else let remainingMsgs = ( not . isNotification ) expectedMsgs + + [ head $ dropWhile isNotification expectedMsgs ] exc = ReplayOutOfOrder msg remainingMsgs in liftIO $ throwTo mainThreadId exc where response : : ResponseMessage a - > IO ( ) response res = do " Got response for i d " + + show ( res ^. i d ) request : : RequestMessage ServerMethod a b - > IO ( ) request req = do putStrLn $ " Got request for i d " + + show ( req ^. i d ) + + " " + + show ( req ^. method ) notification : : NotificationMessage ServerMethod a - > IO ( ) notification n = putStrLn $ " Got notification " + + show ( n ^. method ) inRightOrder : : FromServerMessage - > [ FromServerMessage ] - > Bool inRightOrder _ [ ] = error " Why is this empty " inRightOrder received ( expected : msgs ) | received = = expected = True | isNotification expected = inRightOrder received msgs | otherwise = False shouldSkip : : FromServerMessage - > Bool shouldSkip ( NotLogMessage _ ) = True shouldSkip ( NotShowMessage _ ) = True shouldSkip ( ReqShowMessage _ ) = True shouldSkip _ = False swapCommands : : Int - > [ Event ] - > [ Event ] swapCommands _ [ ] = [ ] ( FromClient t ( ReqExecuteCommand req):xs ) = FromClient t ( ReqExecuteCommand swapped):swapCommands pid xs where swapped = params . command .~ newCmd $ req newCmd = swapPid pid ( req ^. params . command ) ( FromServer t ( RspInitialize rsp):xs ) = FromServer t ( RspInitialize swapped):swapCommands pid xs where swapped = case newCommands of Just cmds - > result . _ Right . LSP.capabilities . executeCommandProvider . _ Just . commands .~ cmds $ rsp Nothing - > rsp oldCommands = rsp ^ ? result . _ Right . LSP.capabilities . executeCommandProvider . _ Just . commands = fmap ( fmap ( swapPid pid ) ) oldCommands swapCommands pid ( x : xs ) = x : hasPid : : T.Text - > Bool hasPid = ( > = 2 ) . T.length . T.filter ( ' : ' = : Int - > T.Text - > T.Text swapPid pid t | hasPid t = T.append ( T.pack $ show pid ) $ T.dropWhile ( /= ' :') t | otherwise = t -> IO () replaySession serverExe sessionDir = do entries <- B.lines <$> B.readFile (sessionDir </> "session.log") let unswappedEvents = map (fromJust . decode) entries withServer serverExe False id $ \serverIn serverOut serverProc -> do pid <- getProcessID serverProc events <- swapCommands pid <$> swapFiles sessionDir unswappedEvents let clientEvents = filter isClientMsg events serverEvents = filter isServerMsg events clientMsgs = map (\(FromClient _ msg) -> msg) clientEvents serverMsgs = filter (not . shouldSkip) $ map (\(FromServer _ msg) -> msg) serverEvents requestMap = getRequestMap clientMsgs reqSema <- newEmptyMVar rspSema <- newEmptyMVar passSema <- newEmptyMVar mainThread <- myThreadId sessionThread <- liftIO $ forkIO $ runSessionWithHandles serverIn serverOut serverProc (listenServer serverMsgs requestMap reqSema rspSema passSema mainThread) def fullCaps sessionDir (sendMessages clientMsgs reqSema rspSema) takeMVar passSema killThread sessionThread where isClientMsg (FromClient _ _) = True isClientMsg _ = False isServerMsg (FromServer _ _) = True isServerMsg _ = False sendMessages :: [FromClientMessage] -> MVar LspId -> MVar LspIdRsp -> Session () sendMessages [] _ _ = return () sendMessages (nextMsg:remainingMsgs) reqSema rspSema = handleClientMessage request response notification nextMsg where notification msg@(NotificationMessage _ Exit _) = do liftIO $ putStrLn "Will send exit notification soon" liftIO $ threadDelay 10000000 sendMessage msg liftIO $ error "Done" notification msg@(NotificationMessage _ m _) = do sendMessage msg liftIO $ putStrLn $ "Sent a notification " ++ show m sendMessages remainingMsgs reqSema rspSema request msg@(RequestMessage _ id m _) = do sendRequestMessage msg liftIO $ putStrLn $ "Sent a request id " ++ show id ++ ": " ++ show m ++ "\nWaiting for a response" rsp <- liftIO $ takeMVar rspSema when (responseId id /= rsp) $ error $ "Expected id " ++ show id ++ ", got " ++ show rsp sendMessages remainingMsgs reqSema rspSema response msg@(ResponseMessage _ id _) = do liftIO $ putStrLn $ "Waiting for request id " ++ show id ++ " from the server" reqId <- liftIO $ takeMVar reqSema if responseId reqId /= id then error $ "Expected id " ++ show reqId ++ ", got " ++ show reqId else do sendResponse msg liftIO $ putStrLn $ "Sent response to request id " ++ show id sendMessages remainingMsgs reqSema rspSema sendRequestMessage :: (ToJSON a, ToJSON b) => RequestMessage ClientMethod a b -> Session () sendRequestMessage req = do reqMap <- requestMap <$> ask liftIO $ modifyMVar_ reqMap $ \r -> return $ updateRequestMap r (req ^. LSP.id) (req ^. method) sendMessage req isNotification :: FromServerMessage -> Bool isNotification (NotPublishDiagnostics _) = True isNotification (NotLogMessage _) = True isNotification (NotShowMessage _) = True isNotification (NotCancelRequestFromServer _) = True isNotification _ = False listenServer :: [FromServerMessage] -> RequestMap -> MVar LspId -> MVar LspIdRsp -> MVar () -> ThreadId -> Handle -> SessionContext -> IO () listenServer [] _ _ _ passSema _ _ _ = putMVar passSema () listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx = do msgBytes <- getNextMessage serverOut let msg = decodeFromServerMsg reqMap msgBytes handleServerMessage request response notification msg if shouldSkip msg then listenServer expectedMsgs reqMap reqSema rspSema passSema mainThreadId serverOut ctx else if inRightOrder msg expectedMsgs then listenServer (delete msg expectedMsgs) reqMap reqSema rspSema passSema mainThreadId serverOut ctx else let remainingMsgs = takeWhile (not . isNotification) expectedMsgs ++ [head $ dropWhile isNotification expectedMsgs] exc = ReplayOutOfOrder msg remainingMsgs in liftIO $ throwTo mainThreadId exc where response :: ResponseMessage a -> IO () response res = do putStrLn $ "Got response for id " ++ show (res ^. id) request :: RequestMessage ServerMethod a b -> IO () request req = do putStrLn $ "Got request for id " ++ show (req ^. id) ++ " " ++ show (req ^. method) notification :: NotificationMessage ServerMethod a -> IO () notification n = putStrLn $ "Got notification " ++ show (n ^. method) inRightOrder :: FromServerMessage -> [FromServerMessage] -> Bool inRightOrder _ [] = error "Why is this empty" inRightOrder received (expected : msgs) | received == expected = True | isNotification expected = inRightOrder received msgs | otherwise = False shouldSkip :: FromServerMessage -> Bool shouldSkip (NotLogMessage _) = True shouldSkip (NotShowMessage _) = True shouldSkip (ReqShowMessage _) = True shouldSkip _ = False swapCommands :: Int -> [Event] -> [Event] swapCommands _ [] = [] swapCommands pid (FromClient t (ReqExecuteCommand req):xs) = FromClient t (ReqExecuteCommand swapped):swapCommands pid xs where swapped = params . command .~ newCmd $ req newCmd = swapPid pid (req ^. params . command) swapCommands pid (FromServer t (RspInitialize rsp):xs) = FromServer t (RspInitialize swapped):swapCommands pid xs where swapped = case newCommands of Just cmds -> result . _Right . LSP.capabilities . executeCommandProvider . _Just . commands .~ cmds $ rsp Nothing -> rsp oldCommands = rsp ^? result . _Right . LSP.capabilities . executeCommandProvider . _Just . commands newCommands = fmap (fmap (swapPid pid)) oldCommands swapCommands pid (x:xs) = x:swapCommands pid xs hasPid :: T.Text -> Bool hasPid = (>= 2) . T.length . T.filter (':' ==) swapPid :: Int -> T.Text -> T.Text swapPid pid t | hasPid t = T.append (T.pack $ show pid) $ T.dropWhile (/= ':') t | otherwise = t -}
f8e4af1c991b903104c91ee6da969b6cfd0271b7c19f19d97e32a71a600c3ef7
tsloughter/kuberl
kuberl_v1_replica_set_list.erl
-module(kuberl_v1_replica_set_list). -export([encode/1]). -export_type([kuberl_v1_replica_set_list/0]). -type kuberl_v1_replica_set_list() :: #{ 'apiVersion' => binary(), 'items' := list(), 'kind' => binary(), 'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta() }. encode(#{ 'apiVersion' := ApiVersion, 'items' := Items, 'kind' := Kind, 'metadata' := Metadata }) -> #{ 'apiVersion' => ApiVersion, 'items' => Items, 'kind' => Kind, 'metadata' => Metadata }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_replica_set_list.erl
erlang
-module(kuberl_v1_replica_set_list). -export([encode/1]). -export_type([kuberl_v1_replica_set_list/0]). -type kuberl_v1_replica_set_list() :: #{ 'apiVersion' => binary(), 'items' := list(), 'kind' => binary(), 'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta() }. encode(#{ 'apiVersion' := ApiVersion, 'items' := Items, 'kind' := Kind, 'metadata' := Metadata }) -> #{ 'apiVersion' => ApiVersion, 'items' => Items, 'kind' => Kind, 'metadata' => Metadata }.
16ed4b9b98842bbaf9e33296524b5a15da343281cf8375751544e0ed79b6ad3f
GNOME/aisleriot
spiderette.scm
; AisleRiot - spiderette.scm Copyright ( C ) 2001 < > ; ; 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 </>. (use-modules (aisleriot interface) (aisleriot api)) (primitive-load-path "spider") (define stock 0) (define foundation '(1 2 3 4)) (define tableau '(5 6 7 8 9 10 11)) (define winning-score 48) (define (new-game) (initialize-playing-area) (set-ace-low) (make-standard-deck) (shuffle-deck) (add-normal-slot DECK) (add-blank-slot) (add-blank-slot) (add-normal-slot '()) (add-normal-slot '()) (add-normal-slot '()) (add-normal-slot '()) (add-carriage-return-slot) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (deal-cards 0 '(5 6 7 8 9 10 11 6 7 8 9 10 11 7 8 9 10 11 8 9 10 11 9 10 11 10 11 11)) (map flip-top-card '(5 6 7 8 9 10 11)) (give-status-message) (list 7 4)) (define (get-options) #f) (define (apply-options options) #f) (set-lambda! 'new-game new-game) (set-lambda! 'get-options get-options) (set-lambda! 'apply-options apply-options)
null
https://raw.githubusercontent.com/GNOME/aisleriot/5ab7f90d8a196f1fcfe5a552cef4a4c1a4b5ac39/games/spiderette.scm
scheme
AisleRiot - spiderette.scm 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 </>.
Copyright ( C ) 2001 < > 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 (use-modules (aisleriot interface) (aisleriot api)) (primitive-load-path "spider") (define stock 0) (define foundation '(1 2 3 4)) (define tableau '(5 6 7 8 9 10 11)) (define winning-score 48) (define (new-game) (initialize-playing-area) (set-ace-low) (make-standard-deck) (shuffle-deck) (add-normal-slot DECK) (add-blank-slot) (add-blank-slot) (add-normal-slot '()) (add-normal-slot '()) (add-normal-slot '()) (add-normal-slot '()) (add-carriage-return-slot) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (add-extended-slot '() down) (deal-cards 0 '(5 6 7 8 9 10 11 6 7 8 9 10 11 7 8 9 10 11 8 9 10 11 9 10 11 10 11 11)) (map flip-top-card '(5 6 7 8 9 10 11)) (give-status-message) (list 7 4)) (define (get-options) #f) (define (apply-options options) #f) (set-lambda! 'new-game new-game) (set-lambda! 'get-options get-options) (set-lambda! 'apply-options apply-options)
c18587b7be20e5e9548998920c6b23c6c4171c2f39acbd9725f536669c071952
icicle-lang/disorder.hs-ambiata
Property.hs
# LANGUAGE CPP # module Disorder.Core.Property ( (=/=) , (~~~) , (###) , (.^.) , (<=>) , (=\\=) , failWith , neg ) where import Data.AEq (AEq) import qualified Data.AEq as AEQ import Data.List ((\\)) import Data.Text (Text, unpack) import Test.QuickCheck.Gen import Test.QuickCheck.Property #if ! MIN_VERSION_QuickCheck(2, 12, 0) infix 4 =/= (=/=) :: (Eq a, Show a) => a -> a -> Property x =/= y = counterexample (concat [show x, " == ", show y]) $ x /= y #endif infix 4 ~~~ -- | Approximately-equal property for floats and things that look like -- floats. (~~~) :: (AEq a, Show a) => a -> a -> Property x ~~~ y = counterexample cex prop where cex = concat ["|", show x, " - ", show y, "| > ɛ"] prop = x AEQ.~== y infix 4 ### -- | Approximately-equal property for floats, which also verifies that both arguments are real numbers ( i.e. , not NaN or infinity ) . (###) :: (AEq a, Show a, RealFloat a) => a -> a -> Property x ### y = conjoin [counterexample unreal realProp, x ~~~ y] where unreal = unwords ["Argument is not a real number:", show x, show y] realProp = all real [x, y] real z = (not $ isNaN z) && (not $ isInfinite z) failWith :: Text -> Property failWith = flip counterexample False . unpack -- | -- Allows you to negate a property and provide a string to hopefully give some clue as to what -- went wrong. -- neg :: (Testable p) => p -> Property neg x = let genRose :: (Testable p) => p -> Gen (Rose Result) genRose = fmap unProp . unProperty . property checkExpectFailure :: Result -> Rose Result -> Rose Result checkExpectFailure res rose = if expect res then rose else return $ failed { reason = "expectFailure may not occur inside a negation" } negRose :: Rose Result -> Rose Result negRose rose = do res <- rose checkExpectFailure res . return $ case ok res of Nothing -> res Just b -> res { ok = Just $ not b } -- Sorry cant think of a more helpful thing to say... Can't change what will get printed by the negated -- property in a meaningful way.. can only append a "not" to it... -- in counterexample "The following properties are ALL true.... NOT!:" . MkProperty $ do rose <- genRose x return . MkProp $ negRose rose infixr 1 .^. (.^.) :: (Testable p1, Testable p2) => p1 -> p2 -> Property p1 .^. p2 = (p1 .||. p2) .&&. neg (p1 .&&. p2) infixr 1 <=> (<=>) :: (Testable p1, Testable p2) => p1 -> p2 -> Property a <=> b = (a .&&. b) .||. (neg a .&&. neg b) infix 4 =\\= -- | -- Test equivalence of the lists -- i.e. if 'ls' and 'rs' contain the same elements, possible in a different order (=\\=) :: (Eq a, Show a) => [a] -> [a] -> Property ls =\\= rs = let els = ls \\ rs ers = rs \\ ls in flip counterexample (els ++ ers == []) $ "Lists are not equivalent: " ++ "(ls \\\\ rs) == " ++ show els ++ " && " ++ "(rs \\\\ ls) == " ++ show ers
null
https://raw.githubusercontent.com/icicle-lang/disorder.hs-ambiata/0068d9a0dd9aea45e772fb664cf4e7e71636dbe5/disorder-core/src/Disorder/Core/Property.hs
haskell
| Approximately-equal property for floats and things that look like floats. | Approximately-equal property for floats, which also verifies that | Allows you to negate a property and provide a string to hopefully give some clue as to what went wrong. Sorry cant think of a more helpful thing to say... Can't change what will get printed by the negated property in a meaningful way.. can only append a "not" to it... | Test equivalence of the lists i.e. if 'ls' and 'rs' contain the same elements, possible in a different order
# LANGUAGE CPP # module Disorder.Core.Property ( (=/=) , (~~~) , (###) , (.^.) , (<=>) , (=\\=) , failWith , neg ) where import Data.AEq (AEq) import qualified Data.AEq as AEQ import Data.List ((\\)) import Data.Text (Text, unpack) import Test.QuickCheck.Gen import Test.QuickCheck.Property #if ! MIN_VERSION_QuickCheck(2, 12, 0) infix 4 =/= (=/=) :: (Eq a, Show a) => a -> a -> Property x =/= y = counterexample (concat [show x, " == ", show y]) $ x /= y #endif infix 4 ~~~ (~~~) :: (AEq a, Show a) => a -> a -> Property x ~~~ y = counterexample cex prop where cex = concat ["|", show x, " - ", show y, "| > ɛ"] prop = x AEQ.~== y infix 4 ### both arguments are real numbers ( i.e. , not NaN or infinity ) . (###) :: (AEq a, Show a, RealFloat a) => a -> a -> Property x ### y = conjoin [counterexample unreal realProp, x ~~~ y] where unreal = unwords ["Argument is not a real number:", show x, show y] realProp = all real [x, y] real z = (not $ isNaN z) && (not $ isInfinite z) failWith :: Text -> Property failWith = flip counterexample False . unpack neg :: (Testable p) => p -> Property neg x = let genRose :: (Testable p) => p -> Gen (Rose Result) genRose = fmap unProp . unProperty . property checkExpectFailure :: Result -> Rose Result -> Rose Result checkExpectFailure res rose = if expect res then rose else return $ failed { reason = "expectFailure may not occur inside a negation" } negRose :: Rose Result -> Rose Result negRose rose = do res <- rose checkExpectFailure res . return $ case ok res of Nothing -> res Just b -> res { ok = Just $ not b } in counterexample "The following properties are ALL true.... NOT!:" . MkProperty $ do rose <- genRose x return . MkProp $ negRose rose infixr 1 .^. (.^.) :: (Testable p1, Testable p2) => p1 -> p2 -> Property p1 .^. p2 = (p1 .||. p2) .&&. neg (p1 .&&. p2) infixr 1 <=> (<=>) :: (Testable p1, Testable p2) => p1 -> p2 -> Property a <=> b = (a .&&. b) .||. (neg a .&&. neg b) infix 4 =\\= (=\\=) :: (Eq a, Show a) => [a] -> [a] -> Property ls =\\= rs = let els = ls \\ rs ers = rs \\ ls in flip counterexample (els ++ ers == []) $ "Lists are not equivalent: " ++ "(ls \\\\ rs) == " ++ show els ++ " && " ++ "(rs \\\\ ls) == " ++ show ers