_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
85b3ee7ed258ca9d3e0cd5f603983b38730b482a05e350ae6ba271cdcc9149bf
tol/webmine
core.clj
(ns webmine.core (:require [clj-http.client :as client])) ;; From l.core (defn maybe-comp [& fs] (fn [x] (reduce #(if (not %1) %1 (%2 %1)) x (reverse fs)))) ;; From infer.core (defn best-by [compare keyfn coll] (if (empty? coll) nil (let [best-finder (fn [best next-elem] (if (compare (keyfn best) (keyfn next-elem)) best next-elem))] (reduce best-finder coll)))) ;; From infer.core (defn max-by [keyfn coll] (best-by > keyfn coll)) ;; From infer.core (defn min-by [keyfn coll] (best-by < keyfn coll)) ;; From l.fetcher (defn body-str [u] (try (:body (client/get (str u))) (catch java.lang.Exception _ nil))) ;; From l.core (defn min-length [us] (min-by (comp count str) us))
null
https://raw.githubusercontent.com/tol/webmine/10da731028d7b9b65faf957087b0ec6812f60734/src/webmine/core.clj
clojure
From l.core From infer.core From infer.core From infer.core From l.fetcher From l.core
(ns webmine.core (:require [clj-http.client :as client])) (defn maybe-comp [& fs] (fn [x] (reduce #(if (not %1) %1 (%2 %1)) x (reverse fs)))) (defn best-by [compare keyfn coll] (if (empty? coll) nil (let [best-finder (fn [best next-elem] (if (compare (keyfn best) (keyfn next-elem)) best next-elem))] (reduce best-finder coll)))) (defn max-by [keyfn coll] (best-by > keyfn coll)) (defn min-by [keyfn coll] (best-by < keyfn coll)) (defn body-str [u] (try (:body (client/get (str u))) (catch java.lang.Exception _ nil))) (defn min-length [us] (min-by (comp count str) us))
5b04ad7a4b692fc7f89ecdedcad14d872c2e9a50243d195f18d1c74db654b9b6
marcoheisig/sb-simd
packages.lisp
(cl:in-package #:common-lisp-user) (defpackage #:sb-simd-test-suite (:use #:common-lisp #:sb-simd-internals) (:export #:run-test-suite #:define-test #:is #:signals #:all-tests #:check-package #:run-tests #:define-simple-simd-test #:define-horizontal-test #:define-aref-test))
null
https://raw.githubusercontent.com/marcoheisig/sb-simd/6ce4f5aefa7be61f3575e7938c2a9ffae3b272ea/test-suite/packages.lisp
lisp
(cl:in-package #:common-lisp-user) (defpackage #:sb-simd-test-suite (:use #:common-lisp #:sb-simd-internals) (:export #:run-test-suite #:define-test #:is #:signals #:all-tests #:check-package #:run-tests #:define-simple-simd-test #:define-horizontal-test #:define-aref-test))
897c0941b07de8c67953e06b3008d8a93cac6d08e11a1cdde16086264ef3df5b
Th30n/cl-shake
gl.lisp
Copyright ( C ) 2016 ;;;; ;;;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . (in-package #:shake-gl) (eval-when (:compile-toplevel :load-toplevel :execute) (defun foreign-type->lisp-type (foreign-type) "Convert a foreign type to lisp type. This is a convenience for using cffi and is implementation dependant." (ecase foreign-type (:float 'single-float)))) (cffi:defcfun "memcpy" :pointer (dest :pointer) (src :pointer) (n :unsigned-int)) (defmacro with-gl-array ((gl-array ftype arrays) &body body) "Bind GL-ARRAY to a GL:GL-ARRAY containing all the elements from the given list of ARRAYS." (with-gensyms (ltype garrays total-size ptr) `(let* ((,garrays (ensure-list ,arrays)) (,ltype ,(if (constantp ftype) `(quote ,(foreign-type->lisp-type ftype)) `(foreign-type->lisp-type ftype))) (,total-size (reduce #'+ ,garrays :key #'array-total-size))) For some reason , gl : with - gl - array and gl : slow things down . (cffi:with-foreign-object (,ptr ,ftype ,total-size) No need for here as the body is outside the loop . (let ((findex 0)) (dolist (a ,garrays) (dotimes (i (array-total-size a)) (setf (cffi:mem-aref ,ptr ,ftype findex) (coerce (row-major-aref a i) ,ltype)) (incf findex)))) (let ((,gl-array (gl::make-gl-array-from-pointer ,ptr ,ftype ,total-size))) (declare (dynamic-extent ,gl-array)) ,@body))))) (cffi:defcstruct draw-arrays-indirect-command (count :unsigned-int) (prim-count :unsigned-int) (first :unsigned-int) (base-instance :unsigned-int)) (defun set-draw-arrays-command (cmd-ptr count &key (prim-count 1) (first 0) (base-instance 0)) (macrolet ((cmd-slot (slot) `(cffi:foreign-slot-value cmd-ptr '(:struct draw-arrays-indirect-command) ',slot))) (setf (cmd-slot count) count (cmd-slot prim-count) prim-count (cmd-slot first) first (cmd-slot base-instance) base-instance))) (defun clear-buffer-fv (buffer drawbuffer &rest values) (with-gl-array (value-array :float (apply #'vector values)) (%gl:clear-buffer-fv buffer drawbuffer (gl::gl-array-pointer value-array)))) (defmacro map-buffer (target count access &key type (offset 0)) "Maps a part of a buffer bound to TARGET. Foreign TYPE and COUNT elements of that type determine the map length. COUNT can be (:BYTES NUM) if you wish to specify the count in bytes. Optional OFFSET determines the start of the buffer in elements. Also (:BYTES NUM) is accepted. Returns the mapping as a POINTER" (let* ((foreign-size (when type (cffi:foreign-type-size type))) (access-flags (cffi:foreign-bitfield-value '%gl::mapbufferusagemask access)) (count-form (if (and (consp count) (eq :bytes (car count))) (cadr count) (progn (assert type) `(* ,count ,foreign-size)))) (offset-form (cond ((and (consp offset) (eq :bytes (car offset))) (cadr offset)) ((and (numberp offset) (= offset 0) 0)) (t (assert (or type (= offset 0))) `(* ,offset ,foreign-size))))) `(let ((length ,(if (constantp count-form) (eval count-form) count-form)) (byte-offset ,(if (constantp offset-form) (eval offset-form) offset-form))) (declare (dynamic-extent length byte-offset)) (%gl:map-buffer-range ,target byte-offset length ,access-flags)))) (defmacro buffer-data (target usage type arrays) `(with-gl-array (data ,type ,arrays) (gl:buffer-data ,target ,usage data))) (defun load-shader (vs-file fs-file &optional gs-file) "Return shader program, created from given VS-FILE and FS-FILE paths to a vertex shader and fragment shader, respectively. Optional GS-FILE is a path to a geometry shader." (let ((shaders (cons (compile-shader-file vs-file :vertex-shader) (cons (compile-shader-file fs-file :fragment-shader) (when gs-file (list (compile-shader-file gs-file :geometry-shader))))))) (apply #'link-program shaders))) (defun compile-shader (source type) "Create a shader of given TYPE, compiled with given SOURCE string." (let ((shader (gl:create-shader type))) (gl:shader-source shader source) (gl:compile-shader shader) (let ((log (gl:get-shader-info-log shader))) (unless (emptyp log) (print log)) (unless (gl:get-shader shader :compile-status) (gl:delete-shader shader) (error "Error compiling shader.~%~S~%" log))) shader)) (defun compile-shader-file (source-file shader-type) (let ((src (read-file-into-string source-file))) (compile-shader src shader-type))) (defun link-program (shader &rest shaders) "Create a program, linked with given SHADER objects." (let ((program (gl:create-program))) (dolist (sh (cons shader shaders)) (gl:attach-shader program sh)) (gl:link-program program) (let ((log (gl:get-program-info-log program))) (unless (emptyp log) (print log)) (unless (gl:get-program program :link-status) (gl:delete-program program) (error "Error linking program.~%~S~%" log))) program)) (defmacro with-uniform-locations (program names &body body) "Get uniform locations for list of NAMES in PROGRAM and bind them to symbols. Names of uniforms are formatted such that all '-' are replaced with '_' and the characters are lowercased. Bound symbol's name is formatted as uniform name with '-LOC' suffix. Example usage: (with-uniform-locations program (mvp color-tex) ;; mvp-loc is the location of mvp uniform (uniform-matrix-4f mvp-loc (list mvp-matrix)) ;; color-tex-loc is the location of color_tex uniform (gl:uniformi color-tex-loc 0))" (labels ((to-uniform-name (name) (ppcre:regex-replace-all "-" (string-downcase (string name)) "_")) (to-symbol (name) (if (stringp name) ;; User convenience if passed in string. (ppcre:regex-replace-all "_" (string-upcase name) "-") name)) (get-location (name) (let ((uniform-name (to-uniform-name name)) (var-name (symbolicate (to-symbol name) "-LOC"))) `(,var-name (let ((loc (gl:get-uniform-location ,program ,uniform-name))) (declare (type fixnum loc)) (if (= loc -1) (error "Uniform ~S not found" ,uniform-name) loc)))))) (let ((locations (if (consp names) (mapcar #'get-location names) User convenience for one uniform . (list (get-location names))))) `(let ,locations ,@body)))) (defun uniform-matrix-4f (location matrix &key (transpose t)) (declare (optimize (speed 3) (space 3))) (check-type location (signed-byte 64)) (check-type matrix (mat 4)) (check-type transpose boolean) ;; Keep this small and optimized. Unfortunately, sb-profile says this ;; performs a lot of allocations. I cannot tell why, everything should be ;; stack allocated inside. (cffi:with-foreign-object (ptr :float 16) (dotimes (i 16) (setf (cffi:mem-aref ptr :float i) (coerce (row-major-aref matrix i) 'single-float))) (%gl:uniform-matrix-4fv location 1 transpose ptr)))
null
https://raw.githubusercontent.com/Th30n/cl-shake/03753dabe4a8dd3005cfb218eacf251f50073103/shake-gl/gl.lisp
lisp
This program is free software; you can redistribute it and/or modify either version 2 of the License , or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. if not , write to the Free Software Foundation , Inc. , mvp-loc is the location of mvp uniform color-tex-loc is the location of color_tex uniform User convenience if passed in string. Keep this small and optimized. Unfortunately, sb-profile says this performs a lot of allocations. I cannot tell why, everything should be stack allocated inside.
Copyright ( C ) 2016 it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along 51 Franklin Street , Fifth Floor , Boston , USA . (in-package #:shake-gl) (eval-when (:compile-toplevel :load-toplevel :execute) (defun foreign-type->lisp-type (foreign-type) "Convert a foreign type to lisp type. This is a convenience for using cffi and is implementation dependant." (ecase foreign-type (:float 'single-float)))) (cffi:defcfun "memcpy" :pointer (dest :pointer) (src :pointer) (n :unsigned-int)) (defmacro with-gl-array ((gl-array ftype arrays) &body body) "Bind GL-ARRAY to a GL:GL-ARRAY containing all the elements from the given list of ARRAYS." (with-gensyms (ltype garrays total-size ptr) `(let* ((,garrays (ensure-list ,arrays)) (,ltype ,(if (constantp ftype) `(quote ,(foreign-type->lisp-type ftype)) `(foreign-type->lisp-type ftype))) (,total-size (reduce #'+ ,garrays :key #'array-total-size))) For some reason , gl : with - gl - array and gl : slow things down . (cffi:with-foreign-object (,ptr ,ftype ,total-size) No need for here as the body is outside the loop . (let ((findex 0)) (dolist (a ,garrays) (dotimes (i (array-total-size a)) (setf (cffi:mem-aref ,ptr ,ftype findex) (coerce (row-major-aref a i) ,ltype)) (incf findex)))) (let ((,gl-array (gl::make-gl-array-from-pointer ,ptr ,ftype ,total-size))) (declare (dynamic-extent ,gl-array)) ,@body))))) (cffi:defcstruct draw-arrays-indirect-command (count :unsigned-int) (prim-count :unsigned-int) (first :unsigned-int) (base-instance :unsigned-int)) (defun set-draw-arrays-command (cmd-ptr count &key (prim-count 1) (first 0) (base-instance 0)) (macrolet ((cmd-slot (slot) `(cffi:foreign-slot-value cmd-ptr '(:struct draw-arrays-indirect-command) ',slot))) (setf (cmd-slot count) count (cmd-slot prim-count) prim-count (cmd-slot first) first (cmd-slot base-instance) base-instance))) (defun clear-buffer-fv (buffer drawbuffer &rest values) (with-gl-array (value-array :float (apply #'vector values)) (%gl:clear-buffer-fv buffer drawbuffer (gl::gl-array-pointer value-array)))) (defmacro map-buffer (target count access &key type (offset 0)) "Maps a part of a buffer bound to TARGET. Foreign TYPE and COUNT elements of that type determine the map length. COUNT can be (:BYTES NUM) if you wish to specify the count in bytes. Optional OFFSET determines the start of the buffer in elements. Also (:BYTES NUM) is accepted. Returns the mapping as a POINTER" (let* ((foreign-size (when type (cffi:foreign-type-size type))) (access-flags (cffi:foreign-bitfield-value '%gl::mapbufferusagemask access)) (count-form (if (and (consp count) (eq :bytes (car count))) (cadr count) (progn (assert type) `(* ,count ,foreign-size)))) (offset-form (cond ((and (consp offset) (eq :bytes (car offset))) (cadr offset)) ((and (numberp offset) (= offset 0) 0)) (t (assert (or type (= offset 0))) `(* ,offset ,foreign-size))))) `(let ((length ,(if (constantp count-form) (eval count-form) count-form)) (byte-offset ,(if (constantp offset-form) (eval offset-form) offset-form))) (declare (dynamic-extent length byte-offset)) (%gl:map-buffer-range ,target byte-offset length ,access-flags)))) (defmacro buffer-data (target usage type arrays) `(with-gl-array (data ,type ,arrays) (gl:buffer-data ,target ,usage data))) (defun load-shader (vs-file fs-file &optional gs-file) "Return shader program, created from given VS-FILE and FS-FILE paths to a vertex shader and fragment shader, respectively. Optional GS-FILE is a path to a geometry shader." (let ((shaders (cons (compile-shader-file vs-file :vertex-shader) (cons (compile-shader-file fs-file :fragment-shader) (when gs-file (list (compile-shader-file gs-file :geometry-shader))))))) (apply #'link-program shaders))) (defun compile-shader (source type) "Create a shader of given TYPE, compiled with given SOURCE string." (let ((shader (gl:create-shader type))) (gl:shader-source shader source) (gl:compile-shader shader) (let ((log (gl:get-shader-info-log shader))) (unless (emptyp log) (print log)) (unless (gl:get-shader shader :compile-status) (gl:delete-shader shader) (error "Error compiling shader.~%~S~%" log))) shader)) (defun compile-shader-file (source-file shader-type) (let ((src (read-file-into-string source-file))) (compile-shader src shader-type))) (defun link-program (shader &rest shaders) "Create a program, linked with given SHADER objects." (let ((program (gl:create-program))) (dolist (sh (cons shader shaders)) (gl:attach-shader program sh)) (gl:link-program program) (let ((log (gl:get-program-info-log program))) (unless (emptyp log) (print log)) (unless (gl:get-program program :link-status) (gl:delete-program program) (error "Error linking program.~%~S~%" log))) program)) (defmacro with-uniform-locations (program names &body body) "Get uniform locations for list of NAMES in PROGRAM and bind them to symbols. Names of uniforms are formatted such that all '-' are replaced with '_' and the characters are lowercased. Bound symbol's name is formatted as uniform name with '-LOC' suffix. Example usage: (with-uniform-locations program (mvp color-tex) (uniform-matrix-4f mvp-loc (list mvp-matrix)) (gl:uniformi color-tex-loc 0))" (labels ((to-uniform-name (name) (ppcre:regex-replace-all "-" (string-downcase (string name)) "_")) (to-symbol (name) (if (stringp name) (ppcre:regex-replace-all "_" (string-upcase name) "-") name)) (get-location (name) (let ((uniform-name (to-uniform-name name)) (var-name (symbolicate (to-symbol name) "-LOC"))) `(,var-name (let ((loc (gl:get-uniform-location ,program ,uniform-name))) (declare (type fixnum loc)) (if (= loc -1) (error "Uniform ~S not found" ,uniform-name) loc)))))) (let ((locations (if (consp names) (mapcar #'get-location names) User convenience for one uniform . (list (get-location names))))) `(let ,locations ,@body)))) (defun uniform-matrix-4f (location matrix &key (transpose t)) (declare (optimize (speed 3) (space 3))) (check-type location (signed-byte 64)) (check-type matrix (mat 4)) (check-type transpose boolean) (cffi:with-foreign-object (ptr :float 16) (dotimes (i 16) (setf (cffi:mem-aref ptr :float i) (coerce (row-major-aref matrix i) 'single-float))) (%gl:uniform-matrix-4fv location 1 transpose ptr)))
5badfde47db9b8b326e8a1f60b553f71b51392b993d629ac90781f9ff2139546
spurious/sagittarius-scheme-mirror
r7rs.scm
-*- mode : scheme ; coding : utf-8 ; -*- compat.scm : provides R7RS compatible procedures and macros #!core ;; for unbound variable warning (library (compat r7rs helper) (export syntax-rules-transformer ;; we need to export them so that (compat r7rs) sees it. NB : the rename is given from ( compat r7rs ) and renamed ;; identifiers belong to the library. if these are not ;; exported, then it raises unbound variable. length* cons-source error check-length format strip-syntactic-closures er-macro-transformer) (import (rename (except (core) identifier? error) (number->string %number->string)) (rename (sagittarius) (unwrap-syntax strip-syntactic-closures) ;; on chibi-scheme, identifier is either symbol or syntax ;; object. so we need to provide this. (variable? identifier?)) (core base) (only (core macro) er-macro-transformer) (rename (core errors) (error core:error)) (only (sagittarius vm debug) source-info-set!)) allow ' ls ' to be non pair as its extension . ;; syntax-rules depends on this behaviour so we need to allow it (define (any pred ls) (if (pair? ls) (if (null? (cdr ls)) (pred (car ls)) (or (pred (car ls)) (any pred (cdr ls)))) #f)) ;; syntax-violation (define (error msg . irr) (let ((form (if (null? irr) #f (car irr))) (subform (and (not (null? irr)) (not (null? (cdr irr))) (cdr irr)))) (syntax-violation 'syntax-rules msg form subform))) 's length * returns element count of car parts of inproper list e.g ) ( length * ' ( 1 2 3 . 4 ) ) ; ; = > 3 ;; And syntax-rules depends on this behaviour. So provide it. ;; it's a bit awkward way to do it (define (length* ls) (let ((r (length ls))) (cond ((positive? r) r) ; no worry ((= r -2) #f) ; -2 is circular list so return #f (else (let loop ((i 0) (ls ls)) (if (not (pair? ls)) i (loop (+ i 1) (cdr ls)))))))) (define (cons-source kar kdr source) (source-info-set! (cons kar kdr) source)) (define (check-length tmpl . args) (or (apply = (map length args)) (syntax-violation 'syntax-rules "subforms have different size of matched input" `(template ,tmpl) `(input ,args)))) ;; from chibi-scheme (define (syntax-rules-transformer expr rename compare) (let ((ellipsis-specified? (identifier? (cadr expr))) (count 0) (_er-macro-transformer (rename 'er-macro-transformer)) (_lambda (rename 'lambda)) (_let (rename 'let)) (_begin (rename 'begin)) (_if (rename 'if)) (_and (rename 'and)) (_or (rename 'or)) (_eq? (rename 'eq?)) (_equal? (rename 'equal?)) (_car (rename 'car)) (_cdr (rename 'cdr)) (_cons (rename 'cons)) (_pair? (rename 'pair?)) (_null? (rename 'null?)) (_expr (rename 'expr)) (_rename (rename 'rename)) (_compare (rename 'compare)) (_quote (rename 'syntax-quote)) (_apply (rename 'apply)) (_append (rename 'append)) (_map (rename 'map)) (_vector? (rename 'vector?)) (_list? (rename 'list?)) (_len (rename'len)) (_length (rename 'length*)) (_- (rename '-)) (_>= (rename '>=)) (_error (rename 'error)) (_ls (rename 'ls)) (_res (rename 'res)) (_i (rename 'i)) (_reverse (rename 'reverse)) (_vector->list (rename 'vector->list)) (_list->vector (rename 'list->vector)) (_cons3 (rename 'cons-source)) (_underscore (rename '_)) (_check-length (rename 'check-length)) (_format (rename 'format))) (define ellipsis (if ellipsis-specified? (cadr expr) (rename '...))) (define lits (if ellipsis-specified? (car (cddr expr)) (cadr expr))) (define forms (if ellipsis-specified? (cdr (cddr expr)) (cddr expr))) (define (next-symbol s) (set! count (+ count 1)) (rename (string->symbol (string-append s (%number->string count))))) (define (expand-pattern pat tmpl) (let lp ((p (cdr pat)) (x (list _cdr _expr)) (dim 0) (vars '()) (k (lambda (vars) (list _cons (expand-template tmpl vars) #f)))) (let ((v (next-symbol "v."))) (list _let (list (list v x)) (cond ((identifier? p) (cond ((memq p lits) (list _and (list _compare v (list _rename (list _quote p))) (k vars))) ((compare _underscore p) (k vars)) (else (list _let (list (list p v)) (k (cons (cons p dim) vars)))))) ((ellipsis? p) (cond ((not (null? (cddr p))) (cond ((any (lambda (x) (and (identifier? x) (compare x ellipsis))) (cddr p)) (error "multiple ellipses" p)) (else (let ((len (length* (cdr (cdr p)))) (_lp (next-symbol "lp."))) `(,_let ((,_len (,_length ,v))) (,_and (,_>= ,_len ,len) (,_let ,_lp ((,_ls ,v) (,_i (,_- ,_len ,len)) (,_res (,_quote ()))) (,_if (,_>= 0 ,_i) ,(lp `(,(cddr p) (,(car p) ,(car (cdr p)))) `(,_cons ,_ls (,_cons (,_reverse ,_res) (,_quote ()))) dim vars k) (,_lp (,_cdr ,_ls) (,_- ,_i 1) (,_cons3 (,_car ,_ls) ,_res ,_ls)))))))))) ((identifier? (car p)) (list _and (list _list? v) (list _let (list (list (car p) v)) (k (cons (cons (car p) (+ 1 dim)) vars))))) (else (let* ((w (next-symbol "w.")) (_lp (next-symbol "lp.")) (new-vars (all-vars (car p) (+ dim 1))) (ls-vars (map (lambda (x) (next-symbol (string-append (symbol->string (identifier->symbol (car x))) "-ls"))) new-vars)) (once (lp (car p) (list _car w) (+ dim 1) '() (lambda (_) (cons _lp (cons (list _cdr w) (map (lambda (x l) (list _cons (car x) l)) new-vars ls-vars))))))) (list _let _lp (cons (list w v) (map (lambda (x) (list x (list _quote '()))) ls-vars)) (list _if (list _null? w) (list _let (map (lambda (x l) (list (car x) (list _reverse l))) new-vars ls-vars) (k (append new-vars vars))) (list _and (list _pair? w) once))))))) ((pair? p) (list _and (list _pair? v) (lp (car p) (list _car v) dim vars (lambda (vars) (lp (cdr p) (list _cdr v) dim vars k))))) ((vector? p) (list _and (list _vector? v) (lp (vector->list p) (list _vector->list v) dim vars k))) ((null? p) (list _and (list _null? v) (k vars))) (else (list _and (list _equal? v p) (k vars)))))))) (define (ellipsis-escape? x) (and (pair? x) (compare ellipsis (car x)))) (define (ellipsis? x) (and (pair? x) (pair? (cdr x)) (compare ellipsis (cadr x)))) (define (ellipsis-depth x) (if (ellipsis? x) (+ 1 (ellipsis-depth (cdr x))) 0)) (define (ellipsis-tail x) (if (ellipsis? x) (ellipsis-tail (cdr x)) (cdr x))) (define (all-vars x dim) (let lp ((x x) (dim dim) (vars '())) (cond ((identifier? x) (if (or (memq x lits) (compare x _underscore)) vars (cons (cons x dim) vars))) ((ellipsis? x) (lp (car x) (+ dim 1) (lp (cddr x) dim vars))) ((pair? x) (lp (car x) dim (lp (cdr x) dim vars))) ((vector? x) (lp (vector->list x) dim vars)) (else vars)))) (define (free-vars x vars dim) (let lp ((x x) (free '())) (cond ((identifier? x) (if (and (not (memq x free)) (cond ((assq x vars) => (lambda (cell) (>= (cdr cell) dim))) (else #f))) (cons x free) free)) ((pair? x) (lp (car x) (lp (cdr x) free))) ((vector? x) (lp (vector->list x) free)) (else free)))) (define (expand-template tmpl vars) (let lp ((t tmpl) (dim 0) (ell-esc #f)) (cond ((identifier? t) (cond ((find (lambda (v) (eq? t (car v))) vars) => (lambda (cell) (if (<= (cdr cell) dim) t (error "too few ...'s" tmpl)))) (else (list _rename (list _quote t))))) ((pair? t) (cond ((and (ellipsis-escape? t) (not ell-esc)) (lp (if (and (pair? (cdr t)) (null? (cddr t))) (cadr t) (cdr t)) dim #t) #;(list _quote (if (pair? (cdr t)) (if (pair? (cddr t)) (cddr t) (cadr t)) (cdr t)))) ((and (ellipsis? t) (not ell-esc)) (let* ((depth (ellipsis-depth t)) (ell-dim (+ dim depth)) (ell-vars (free-vars (car t) vars ell-dim))) (cond ((null? ell-vars) (error "too many ...'s" tmpl)) ((and (null? (cddr t)) (identifier? (car t))) ;; shortcut for (var ...) (lp (car t) ell-dim ell-esc)) (else (let* ((once (lp (car t) ell-dim ell-dim)) (nest (if (and (null? (cdr ell-vars)) (identifier? once) (eq? once (car vars))) once ;; shortcut ;; call #151 ;; map accepts different length of ;; input this causes different input ;; form acceptible. put some validation ;; here (if (or (null? ell-vars) (null? (cdr ell-vars))) ;; not need to do it (cons _map (cons (list _lambda ell-vars once) ell-vars)) (list _begin (cons* _check-length (list _quote tmpl) ell-vars) (cons _map (cons (list _lambda ell-vars once) ell-vars)))))) (many (do ((d depth (- d 1)) (many nest (list _apply _append many))) ((= d 1) many)))) (if (null? (ellipsis-tail t)) many ;; shortcut (list _append many (lp (ellipsis-tail t) dim ell-esc)))))))) (else (list _cons3 (lp (car t) dim ell-esc) (lp (cdr t) dim ell-esc) (list _quote t))))) ((vector? t) (list _list->vector (lp (vector->list t) dim ell-esc))) ((null? t) (list _quote '())) (else t)))) (list _er-macro-transformer (list _lambda (list _expr _rename _compare) (list _car (cons _or (append (map (lambda (clause) (expand-pattern (car clause) (cadr clause))) forms) (list (list _cons (list _error (list _format "no expansion for ~s" (list (rename 'strip-syntactic-closures) _expr)) (list (rename 'strip-syntactic-closures) _expr)) #f))))))))) ) (library (compat r7rs) (export syntax-rules) (import (core) (core base) (compat r7rs helper)) (define-syntax syntax-rules-aux (er-macro-transformer syntax-rules-transformer)) (define-syntax syntax-rules (er-macro-transformer (lambda (form rename compare) (if (identifier? (cadr form)) `(,(rename 'let) ((,(cadr form) #t)) (,(rename 'syntax-rules-aux) . ,(cdr form))) (syntax-rules-transformer form rename compare))))) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/lib/compat/r7rs.scm
scheme
coding : utf-8 ; -*- for unbound variable warning we need to export them so that (compat r7rs) sees it. identifiers belong to the library. if these are not exported, then it raises unbound variable. on chibi-scheme, identifier is either symbol or syntax object. so we need to provide this. syntax-rules depends on this behaviour so we need to allow it syntax-violation ; = > 3 And syntax-rules depends on this behaviour. So provide it. it's a bit awkward way to do it no worry -2 is circular list so return #f from chibi-scheme (list _quote shortcut for (var ...) shortcut call #151 map accepts different length of input this causes different input form acceptible. put some validation here not need to do it shortcut
compat.scm : provides R7RS compatible procedures and macros #!core (library (compat r7rs helper) (export syntax-rules-transformer NB : the rename is given from ( compat r7rs ) and renamed length* cons-source error check-length format strip-syntactic-closures er-macro-transformer) (import (rename (except (core) identifier? error) (number->string %number->string)) (rename (sagittarius) (unwrap-syntax strip-syntactic-closures) (variable? identifier?)) (core base) (only (core macro) er-macro-transformer) (rename (core errors) (error core:error)) (only (sagittarius vm debug) source-info-set!)) allow ' ls ' to be non pair as its extension . (define (any pred ls) (if (pair? ls) (if (null? (cdr ls)) (pred (car ls)) (or (pred (car ls)) (any pred (cdr ls)))) #f)) (define (error msg . irr) (let ((form (if (null? irr) #f (car irr))) (subform (and (not (null? irr)) (not (null? (cdr irr))) (cdr irr)))) (syntax-violation 'syntax-rules msg form subform))) 's length * returns element count of car parts of inproper list (define (length* ls) (let ((r (length ls))) (else (let loop ((i 0) (ls ls)) (if (not (pair? ls)) i (loop (+ i 1) (cdr ls)))))))) (define (cons-source kar kdr source) (source-info-set! (cons kar kdr) source)) (define (check-length tmpl . args) (or (apply = (map length args)) (syntax-violation 'syntax-rules "subforms have different size of matched input" `(template ,tmpl) `(input ,args)))) (define (syntax-rules-transformer expr rename compare) (let ((ellipsis-specified? (identifier? (cadr expr))) (count 0) (_er-macro-transformer (rename 'er-macro-transformer)) (_lambda (rename 'lambda)) (_let (rename 'let)) (_begin (rename 'begin)) (_if (rename 'if)) (_and (rename 'and)) (_or (rename 'or)) (_eq? (rename 'eq?)) (_equal? (rename 'equal?)) (_car (rename 'car)) (_cdr (rename 'cdr)) (_cons (rename 'cons)) (_pair? (rename 'pair?)) (_null? (rename 'null?)) (_expr (rename 'expr)) (_rename (rename 'rename)) (_compare (rename 'compare)) (_quote (rename 'syntax-quote)) (_apply (rename 'apply)) (_append (rename 'append)) (_map (rename 'map)) (_vector? (rename 'vector?)) (_list? (rename 'list?)) (_len (rename'len)) (_length (rename 'length*)) (_- (rename '-)) (_>= (rename '>=)) (_error (rename 'error)) (_ls (rename 'ls)) (_res (rename 'res)) (_i (rename 'i)) (_reverse (rename 'reverse)) (_vector->list (rename 'vector->list)) (_list->vector (rename 'list->vector)) (_cons3 (rename 'cons-source)) (_underscore (rename '_)) (_check-length (rename 'check-length)) (_format (rename 'format))) (define ellipsis (if ellipsis-specified? (cadr expr) (rename '...))) (define lits (if ellipsis-specified? (car (cddr expr)) (cadr expr))) (define forms (if ellipsis-specified? (cdr (cddr expr)) (cddr expr))) (define (next-symbol s) (set! count (+ count 1)) (rename (string->symbol (string-append s (%number->string count))))) (define (expand-pattern pat tmpl) (let lp ((p (cdr pat)) (x (list _cdr _expr)) (dim 0) (vars '()) (k (lambda (vars) (list _cons (expand-template tmpl vars) #f)))) (let ((v (next-symbol "v."))) (list _let (list (list v x)) (cond ((identifier? p) (cond ((memq p lits) (list _and (list _compare v (list _rename (list _quote p))) (k vars))) ((compare _underscore p) (k vars)) (else (list _let (list (list p v)) (k (cons (cons p dim) vars)))))) ((ellipsis? p) (cond ((not (null? (cddr p))) (cond ((any (lambda (x) (and (identifier? x) (compare x ellipsis))) (cddr p)) (error "multiple ellipses" p)) (else (let ((len (length* (cdr (cdr p)))) (_lp (next-symbol "lp."))) `(,_let ((,_len (,_length ,v))) (,_and (,_>= ,_len ,len) (,_let ,_lp ((,_ls ,v) (,_i (,_- ,_len ,len)) (,_res (,_quote ()))) (,_if (,_>= 0 ,_i) ,(lp `(,(cddr p) (,(car p) ,(car (cdr p)))) `(,_cons ,_ls (,_cons (,_reverse ,_res) (,_quote ()))) dim vars k) (,_lp (,_cdr ,_ls) (,_- ,_i 1) (,_cons3 (,_car ,_ls) ,_res ,_ls)))))))))) ((identifier? (car p)) (list _and (list _list? v) (list _let (list (list (car p) v)) (k (cons (cons (car p) (+ 1 dim)) vars))))) (else (let* ((w (next-symbol "w.")) (_lp (next-symbol "lp.")) (new-vars (all-vars (car p) (+ dim 1))) (ls-vars (map (lambda (x) (next-symbol (string-append (symbol->string (identifier->symbol (car x))) "-ls"))) new-vars)) (once (lp (car p) (list _car w) (+ dim 1) '() (lambda (_) (cons _lp (cons (list _cdr w) (map (lambda (x l) (list _cons (car x) l)) new-vars ls-vars))))))) (list _let _lp (cons (list w v) (map (lambda (x) (list x (list _quote '()))) ls-vars)) (list _if (list _null? w) (list _let (map (lambda (x l) (list (car x) (list _reverse l))) new-vars ls-vars) (k (append new-vars vars))) (list _and (list _pair? w) once))))))) ((pair? p) (list _and (list _pair? v) (lp (car p) (list _car v) dim vars (lambda (vars) (lp (cdr p) (list _cdr v) dim vars k))))) ((vector? p) (list _and (list _vector? v) (lp (vector->list p) (list _vector->list v) dim vars k))) ((null? p) (list _and (list _null? v) (k vars))) (else (list _and (list _equal? v p) (k vars)))))))) (define (ellipsis-escape? x) (and (pair? x) (compare ellipsis (car x)))) (define (ellipsis? x) (and (pair? x) (pair? (cdr x)) (compare ellipsis (cadr x)))) (define (ellipsis-depth x) (if (ellipsis? x) (+ 1 (ellipsis-depth (cdr x))) 0)) (define (ellipsis-tail x) (if (ellipsis? x) (ellipsis-tail (cdr x)) (cdr x))) (define (all-vars x dim) (let lp ((x x) (dim dim) (vars '())) (cond ((identifier? x) (if (or (memq x lits) (compare x _underscore)) vars (cons (cons x dim) vars))) ((ellipsis? x) (lp (car x) (+ dim 1) (lp (cddr x) dim vars))) ((pair? x) (lp (car x) dim (lp (cdr x) dim vars))) ((vector? x) (lp (vector->list x) dim vars)) (else vars)))) (define (free-vars x vars dim) (let lp ((x x) (free '())) (cond ((identifier? x) (if (and (not (memq x free)) (cond ((assq x vars) => (lambda (cell) (>= (cdr cell) dim))) (else #f))) (cons x free) free)) ((pair? x) (lp (car x) (lp (cdr x) free))) ((vector? x) (lp (vector->list x) free)) (else free)))) (define (expand-template tmpl vars) (let lp ((t tmpl) (dim 0) (ell-esc #f)) (cond ((identifier? t) (cond ((find (lambda (v) (eq? t (car v))) vars) => (lambda (cell) (if (<= (cdr cell) dim) t (error "too few ...'s" tmpl)))) (else (list _rename (list _quote t))))) ((pair? t) (cond ((and (ellipsis-escape? t) (not ell-esc)) (lp (if (and (pair? (cdr t)) (null? (cddr t))) (cadr t) (cdr t)) dim #t) (if (pair? (cdr t)) (if (pair? (cddr t)) (cddr t) (cadr t)) (cdr t)))) ((and (ellipsis? t) (not ell-esc)) (let* ((depth (ellipsis-depth t)) (ell-dim (+ dim depth)) (ell-vars (free-vars (car t) vars ell-dim))) (cond ((null? ell-vars) (error "too many ...'s" tmpl)) ((and (null? (cddr t)) (identifier? (car t))) (lp (car t) ell-dim ell-esc)) (else (let* ((once (lp (car t) ell-dim ell-dim)) (nest (if (and (null? (cdr ell-vars)) (identifier? once) (eq? once (car vars))) (if (or (null? ell-vars) (null? (cdr ell-vars))) (cons _map (cons (list _lambda ell-vars once) ell-vars)) (list _begin (cons* _check-length (list _quote tmpl) ell-vars) (cons _map (cons (list _lambda ell-vars once) ell-vars)))))) (many (do ((d depth (- d 1)) (many nest (list _apply _append many))) ((= d 1) many)))) (if (null? (ellipsis-tail t)) (list _append many (lp (ellipsis-tail t) dim ell-esc)))))))) (else (list _cons3 (lp (car t) dim ell-esc) (lp (cdr t) dim ell-esc) (list _quote t))))) ((vector? t) (list _list->vector (lp (vector->list t) dim ell-esc))) ((null? t) (list _quote '())) (else t)))) (list _er-macro-transformer (list _lambda (list _expr _rename _compare) (list _car (cons _or (append (map (lambda (clause) (expand-pattern (car clause) (cadr clause))) forms) (list (list _cons (list _error (list _format "no expansion for ~s" (list (rename 'strip-syntactic-closures) _expr)) (list (rename 'strip-syntactic-closures) _expr)) #f))))))))) ) (library (compat r7rs) (export syntax-rules) (import (core) (core base) (compat r7rs helper)) (define-syntax syntax-rules-aux (er-macro-transformer syntax-rules-transformer)) (define-syntax syntax-rules (er-macro-transformer (lambda (form rename compare) (if (identifier? (cadr form)) `(,(rename 'let) ((,(cadr form) #t)) (,(rename 'syntax-rules-aux) . ,(cdr form))) (syntax-rules-transformer form rename compare))))) )
8bf1269058a862e5e781d060d5f4516994b3d4420ccdcdc10db1583ae524b46c
jrclogic/SMCDEL
DEMO_S5.hs
Note : This is a modified version of DEMO - S5 by . For the original , see module SMCDEL.Explicit.DEMO_S5 where import Control.Arrow (first,second) import Data.List (sortBy) import SMCDEL.Internal.Help (apply,restrict,Erel,bl) newtype Agent = Ag Int deriving (Eq,Ord,Show) data DemoPrp = DemoP Int | DemoQ Int | DemoR Int | DemoS Int deriving (Eq,Ord) instance Show DemoPrp where show (DemoP 0) = "p"; show (DemoP i) = "p" ++ show i show (DemoQ 0) = "q"; show (DemoQ i) = "q" ++ show i show (DemoR 0) = "r"; show (DemoR i) = "r" ++ show i show (DemoS 0) = "s"; show (DemoS i) = "s" ++ show i data EpistM state = Mo [state] [Agent] [(state,[DemoPrp])] [(Agent,Erel state)] [state] deriving (Eq) instance Show state => Show (EpistM state) where show (Mo worlds ags val accs points) = concat [ "Mo\n " , show worlds, "\n " , show ags, "\n " , show val, "\n " , show accs, "\n " , show points, "\n" ] rel :: Show a => Agent -> EpistM a -> Erel a rel ag (Mo _ _ _ rels _) = apply rels ag initM :: (Num state, Enum state) => [Agent] -> [DemoPrp] -> EpistM state initM ags props = Mo worlds ags val accs points where worlds = [0..(2^k-1)] k = length props val = zip worlds (sortL (powerList props)) accs = [ (ag,[worlds]) | ag <- ags ] points = worlds powerList :: [a] -> [[a]] powerList [] = [[]] powerList (x:xs) = powerList xs ++ map (x:) (powerList xs) sortL :: Ord a => [[a]] -> [[a]] sortL = sortBy (\ xs ys -> if length xs < length ys then LT else if length xs > length ys then GT else compare xs ys) data DemoForm a = Top | Info a | Prp DemoPrp | Ng (DemoForm a) | Conj [DemoForm a] | Disj [DemoForm a] | Kn Agent (DemoForm a) | PA (DemoForm a) (DemoForm a) | PAW (DemoForm a) (DemoForm a) deriving (Eq,Ord,Show) impl :: DemoForm a -> DemoForm a -> DemoForm a impl form1 form2 = Disj [Ng form1, form2] -- | semantics: truth at a world in a model isTrueAt :: (Show state, Ord state) => EpistM state -> state -> DemoForm state -> Bool isTrueAt _ _ Top = True isTrueAt _ w (Info x) = w == x isTrueAt (Mo _ _ val _ _) w (Prp p) = p `elem` apply val w isTrueAt m w (Ng f) = not (isTrueAt m w f) isTrueAt m w (Conj fs) = all (isTrueAt m w) fs isTrueAt m w (Disj fs) = any (isTrueAt m w) fs isTrueAt m w (Kn ag f) = all (flip (isTrueAt m) f) (bl (rel ag m) w) isTrueAt m w (PA f g) = not (isTrueAt m w f) || isTrueAt (updPa m f) w g isTrueAt m w (PAW f g) = not (isTrueAt m w f) || isTrueAt (updPaW m f) w g -- | global truth in a model isTrue :: Show a => Ord a => EpistM a -> DemoForm a -> Bool isTrue m@(Mo _ _ _ _ points) f = all (\w -> isTrueAt m w f) points -- | public announcement updPa :: (Show state, Ord state) => EpistM state -> DemoForm state -> EpistM state updPa m@(Mo states agents val rels actual) f = Mo states' agents val' rels' actual' where states' = [ s | s <- states, isTrueAt m s f ] val' = [ (s, ps) | (s,ps) <- val, s `elem` states' ] rels' = [ (ag,restrict states' r) | (ag,r) <- rels ] actual' = [ s | s <- actual, s `elem` states' ] updsPa :: (Show state, Ord state) => EpistM state -> [DemoForm state] -> EpistM state updsPa = foldl updPa -- | public announcement-whether updPaW :: (Show state, Ord state) => EpistM state -> DemoForm state -> EpistM state updPaW m@(Mo states agents val rels actual) f = Mo states agents val rels' actual where rels' = [ (ag, sortL $ concatMap split r) | (ag,r) <- rels ] split ws = filter (/= []) [ filter (\w -> isTrueAt m w f) ws, filter (\w -> not $ isTrueAt m w f) ws ] updsPaW :: (Show state, Ord state) => EpistM state -> [DemoForm state] -> EpistM state updsPaW = foldl updPaW -- | safe substitutions sub :: Show a => [(DemoPrp,DemoForm a)] -> DemoPrp -> DemoForm a sub subst p | p `elem` map fst subst = apply subst p | otherwise = Prp p -- | public factual change updPc :: (Show state, Ord state) => [DemoPrp] -> EpistM state -> [(DemoPrp,DemoForm state)] -> EpistM state updPc ps m@(Mo states agents _ rels actual) sb = Mo states agents val' rels actual where val' = [ (s, [p | p <- ps, isTrueAt m s (sub sb p)]) | s <- states ] updsPc :: Show state => Ord state => [DemoPrp] -> EpistM state -> [[(DemoPrp,DemoForm state)]] -> EpistM state updsPc ps = foldl (updPc ps) updPi :: (state1 -> state2) -> EpistM state1 -> EpistM state2 updPi f (Mo states agents val rels actual) = Mo (map f states) agents (map (first f) val) (map (second (map (map f))) rels) (map f actual) bTables :: Int -> [[Bool]] bTables 0 = [[]] bTables n = map (True:) (bTables (n-1)) ++ map (False:) (bTables (n-1)) initN :: Int -> EpistM [Bool] initN n = Mo states agents [] rels points where states = bTables n agents = map Ag [1..n] rels = [(Ag i, [[tab1++[True]++tab2,tab1++[False]++tab2] | tab1 <- bTables (i-1), tab2 <- bTables (n-i) ]) | i <- [1..n] ] points = [False: replicate (n-1) True] fatherN :: Int -> DemoForm [Bool] fatherN n = Ng (Info (replicate n False)) kn :: Int -> Int -> DemoForm [Bool] kn n i = Disj [Kn (Ag i) (Disj [ Info (tab1++[True]++tab2) | tab1 <- bTables (i-1) , tab2 <- bTables (n-i) ] ), Kn (Ag i) (Disj [ Info (tab1++[False]++tab2) | tab1 <- bTables (i-1) , tab2 <- bTables (n-i) ] ) ] dont :: Int -> DemoForm [Bool] dont n = Conj [Ng (kn n i) | i <- [1..n] ] knowN :: Int -> DemoForm [Bool] knowN n = Conj [kn n i | i <- [2..n] ] solveN :: Int -> EpistM [Bool] solveN n = updsPa (initN n) (f:istatements ++ [knowN n]) where f = fatherN n istatements = replicate (n-2) (dont n)
null
https://raw.githubusercontent.com/jrclogic/SMCDEL/10bd5ba2f1f3cc85e4b0f23d5eddbb26f05df5bf/src/SMCDEL/Explicit/DEMO_S5.hs
haskell
| semantics: truth at a world in a model | global truth in a model | public announcement | public announcement-whether | safe substitutions | public factual change
Note : This is a modified version of DEMO - S5 by . For the original , see module SMCDEL.Explicit.DEMO_S5 where import Control.Arrow (first,second) import Data.List (sortBy) import SMCDEL.Internal.Help (apply,restrict,Erel,bl) newtype Agent = Ag Int deriving (Eq,Ord,Show) data DemoPrp = DemoP Int | DemoQ Int | DemoR Int | DemoS Int deriving (Eq,Ord) instance Show DemoPrp where show (DemoP 0) = "p"; show (DemoP i) = "p" ++ show i show (DemoQ 0) = "q"; show (DemoQ i) = "q" ++ show i show (DemoR 0) = "r"; show (DemoR i) = "r" ++ show i show (DemoS 0) = "s"; show (DemoS i) = "s" ++ show i data EpistM state = Mo [state] [Agent] [(state,[DemoPrp])] [(Agent,Erel state)] [state] deriving (Eq) instance Show state => Show (EpistM state) where show (Mo worlds ags val accs points) = concat [ "Mo\n " , show worlds, "\n " , show ags, "\n " , show val, "\n " , show accs, "\n " , show points, "\n" ] rel :: Show a => Agent -> EpistM a -> Erel a rel ag (Mo _ _ _ rels _) = apply rels ag initM :: (Num state, Enum state) => [Agent] -> [DemoPrp] -> EpistM state initM ags props = Mo worlds ags val accs points where worlds = [0..(2^k-1)] k = length props val = zip worlds (sortL (powerList props)) accs = [ (ag,[worlds]) | ag <- ags ] points = worlds powerList :: [a] -> [[a]] powerList [] = [[]] powerList (x:xs) = powerList xs ++ map (x:) (powerList xs) sortL :: Ord a => [[a]] -> [[a]] sortL = sortBy (\ xs ys -> if length xs < length ys then LT else if length xs > length ys then GT else compare xs ys) data DemoForm a = Top | Info a | Prp DemoPrp | Ng (DemoForm a) | Conj [DemoForm a] | Disj [DemoForm a] | Kn Agent (DemoForm a) | PA (DemoForm a) (DemoForm a) | PAW (DemoForm a) (DemoForm a) deriving (Eq,Ord,Show) impl :: DemoForm a -> DemoForm a -> DemoForm a impl form1 form2 = Disj [Ng form1, form2] isTrueAt :: (Show state, Ord state) => EpistM state -> state -> DemoForm state -> Bool isTrueAt _ _ Top = True isTrueAt _ w (Info x) = w == x isTrueAt (Mo _ _ val _ _) w (Prp p) = p `elem` apply val w isTrueAt m w (Ng f) = not (isTrueAt m w f) isTrueAt m w (Conj fs) = all (isTrueAt m w) fs isTrueAt m w (Disj fs) = any (isTrueAt m w) fs isTrueAt m w (Kn ag f) = all (flip (isTrueAt m) f) (bl (rel ag m) w) isTrueAt m w (PA f g) = not (isTrueAt m w f) || isTrueAt (updPa m f) w g isTrueAt m w (PAW f g) = not (isTrueAt m w f) || isTrueAt (updPaW m f) w g isTrue :: Show a => Ord a => EpistM a -> DemoForm a -> Bool isTrue m@(Mo _ _ _ _ points) f = all (\w -> isTrueAt m w f) points updPa :: (Show state, Ord state) => EpistM state -> DemoForm state -> EpistM state updPa m@(Mo states agents val rels actual) f = Mo states' agents val' rels' actual' where states' = [ s | s <- states, isTrueAt m s f ] val' = [ (s, ps) | (s,ps) <- val, s `elem` states' ] rels' = [ (ag,restrict states' r) | (ag,r) <- rels ] actual' = [ s | s <- actual, s `elem` states' ] updsPa :: (Show state, Ord state) => EpistM state -> [DemoForm state] -> EpistM state updsPa = foldl updPa updPaW :: (Show state, Ord state) => EpistM state -> DemoForm state -> EpistM state updPaW m@(Mo states agents val rels actual) f = Mo states agents val rels' actual where rels' = [ (ag, sortL $ concatMap split r) | (ag,r) <- rels ] split ws = filter (/= []) [ filter (\w -> isTrueAt m w f) ws, filter (\w -> not $ isTrueAt m w f) ws ] updsPaW :: (Show state, Ord state) => EpistM state -> [DemoForm state] -> EpistM state updsPaW = foldl updPaW sub :: Show a => [(DemoPrp,DemoForm a)] -> DemoPrp -> DemoForm a sub subst p | p `elem` map fst subst = apply subst p | otherwise = Prp p updPc :: (Show state, Ord state) => [DemoPrp] -> EpistM state -> [(DemoPrp,DemoForm state)] -> EpistM state updPc ps m@(Mo states agents _ rels actual) sb = Mo states agents val' rels actual where val' = [ (s, [p | p <- ps, isTrueAt m s (sub sb p)]) | s <- states ] updsPc :: Show state => Ord state => [DemoPrp] -> EpistM state -> [[(DemoPrp,DemoForm state)]] -> EpistM state updsPc ps = foldl (updPc ps) updPi :: (state1 -> state2) -> EpistM state1 -> EpistM state2 updPi f (Mo states agents val rels actual) = Mo (map f states) agents (map (first f) val) (map (second (map (map f))) rels) (map f actual) bTables :: Int -> [[Bool]] bTables 0 = [[]] bTables n = map (True:) (bTables (n-1)) ++ map (False:) (bTables (n-1)) initN :: Int -> EpistM [Bool] initN n = Mo states agents [] rels points where states = bTables n agents = map Ag [1..n] rels = [(Ag i, [[tab1++[True]++tab2,tab1++[False]++tab2] | tab1 <- bTables (i-1), tab2 <- bTables (n-i) ]) | i <- [1..n] ] points = [False: replicate (n-1) True] fatherN :: Int -> DemoForm [Bool] fatherN n = Ng (Info (replicate n False)) kn :: Int -> Int -> DemoForm [Bool] kn n i = Disj [Kn (Ag i) (Disj [ Info (tab1++[True]++tab2) | tab1 <- bTables (i-1) , tab2 <- bTables (n-i) ] ), Kn (Ag i) (Disj [ Info (tab1++[False]++tab2) | tab1 <- bTables (i-1) , tab2 <- bTables (n-i) ] ) ] dont :: Int -> DemoForm [Bool] dont n = Conj [Ng (kn n i) | i <- [1..n] ] knowN :: Int -> DemoForm [Bool] knowN n = Conj [kn n i | i <- [2..n] ] solveN :: Int -> EpistM [Bool] solveN n = updsPa (initN n) (f:istatements ++ [knowN n]) where f = fatherN n istatements = replicate (n-2) (dont n)
d9e616878112478d4aba83ec75eb618d492f7b3351e9bfdd02c87cd381ac382d
RefactoringTools/HaRe
SubPatternIn3_TokOut.hs
module SubPatternIn3 where -- takes into account general type variables -- within type implementation. -- here T has its arguments instantiated within g -- selecting 'b' should instantiate list patterns -- selecting 'c' should give an error. -- data T a b = C1 a b | C2 b g :: Int -> T Int [Int] -> Int g z (C1 b c) = b g z (C2 x@[]) = hd x g z (C2 x@(b_1 : b_2)) = hd x g z (C2 x) = hd x f :: [Int] -> Int f x@[] = hd x + hd (tl x) f x@(y:ys) = hd x + hd (tl x) hd x = head x tl x = tail x
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/testing/subIntroPattern/SubPatternIn3_TokOut.hs
haskell
takes into account general type variables within type implementation. here T has its arguments instantiated within g selecting 'b' should instantiate list patterns selecting 'c' should give an error.
module SubPatternIn3 where data T a b = C1 a b | C2 b g :: Int -> T Int [Int] -> Int g z (C1 b c) = b g z (C2 x@[]) = hd x g z (C2 x@(b_1 : b_2)) = hd x g z (C2 x) = hd x f :: [Int] -> Int f x@[] = hd x + hd (tl x) f x@(y:ys) = hd x + hd (tl x) hd x = head x tl x = tail x
f1f269f9eeefe27dc0fe45eb164dc0282a900169e3cbc0c4e380f36bdcd3ae40
dvanhorn/oaam
0cfa-prealloc.rkt
#lang racket (provide aval^ widen) (require "ast.rkt" (except-in "data.rkt" get-cont) "progs.rkt" (for-syntax syntax/parse)) (define-syntax-rule (for/union guards body1 body ...) (for/fold ([res (set)]) guards (set-union res (let () body1 body ...)))) (define-syntax-rule (for*/union guards body1 body ...) (for*/fold ([res (set)]) guards (set-union res (let () body1 body ...)))) 0CFA in the AAM style on some hairy Church numeral churning ;; + compilation phase ;; + lazy non-determinism ;; + specialized step & iterator State = ( cons Conf Store ) ;; State^ = (cons (Set Conf) Store) Comp = Store Env Cont - > State^ ;; Global store (define σ #f) (define unions 0) (define nlabels #f) (define (get-cont σ l) (vector-ref σ l)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; "Compiled" Machine ;; Compile away interpretive overhead of "ev" states ;; Expr -> Comp (define (compile e) (match e [(var l x) (λ (ρ k) (set (co^ k (addr (lookup-env ρ x)))))] [(num l n) (λ (ρ k) (set (co^ k n)))] [(bln l b) (λ (ρ k) (set (co^ k b)))] [(lam l x e) (define c (compile e)) (λ (ρ k) (set (co^ k (clos l x c ρ))))] [(rec f (lam l x e)) (define c (compile e)) (λ (ρ k) (set (co^ k (rlos l f x c ρ))))] [(app l e0 e1) (define c0 (compile e0)) (define c1 (compile e1)) (λ (ρ k) (define a (push l ρ k)) (c0 ρ (ar c1 ρ a)))] [(ife l e0 e1 e2) (define c0 (compile e0)) (define c1 (compile e1)) (define c2 (compile e2)) (λ (ρ k) (define a (push l ρ k)) (c0 ρ (ifk c1 c2 ρ a)))] [(1op l o e) (define c (compile e)) (λ (ρ k) (define a (push l ρ k)) (c ρ (1opk o a)))] [(2op l o e0 e1) (define c0 (compile e0)) (define c1 (compile e1)) (λ (ρ k) (define a (push l ρ k)) (c0 ρ (2opak o c1 ρ a)))] [_ (error 'compile "Bad ~a" e)])) Store ( ) - > Set (define (get-val σ v) (match v [(addr loc) (vector-ref σ loc)] [_ (list v)])) " Bytecode " interpreter ;; State -> State^ (define (step-compiled^ s) (match s [(co^ k v) (match k ['mt (for*/set ([v (get-val σ v)]) (ans^ v))] [(ar c ρ l) (c ρ (fn v l))] [(fn f l) (for*/set ([k (get-cont σ l)] [f (get-val σ f)]) (ap^ f v k))] [(ifk c a ρ l) (for*/union ([k (get-cont σ l)] [v (get-val σ v)]) ((if v c a) ρ k))] [(1opk o l) (for*/set ([k (get-cont σ l)] [v (get-val σ v)]) (ap-op^ o (list v) k))] [(2opak o c ρ l) (c ρ (2opfk o v l))] [(2opfk o u l) (for*/set ([k (get-cont σ l)] [v (get-val σ v)] [u (get-val σ u)]) (ap-op^ o (list v u) k))] [_ (error 'step-compiled^ "Bad ~a" k)])] [(ap^ fun a k) (match fun [(clos l x c ρ) (define ρ* (bind s)) (c ρ* k)] [(rlos l f x c ρ) (define ρ* (bind s)) (c ρ* k)] ;; Anything else is stuck [_ (set s)])] [(ap-op^ o vs k) (match* (o vs) [('zero? (list (? number? n))) (set (co^ k (zero? n)))] [('sub1 (list (? number? n))) (set (co^ k (widen (sub1 n))))] [('add1 (list (? number? n))) (set (co^ k (widen (add1 n))))] [('zero? (list 'number)) (set (co^ k #t) (co^ k #f))] [('sub1 (list 'number)) (set (co^ k 'number))] [('* (list (? number? n) (? number? m))) (set (co^ k (widen (* m n))))] [('* (list (? number? n) 'number)) (set (co^ k 'number))] [('* (list 'number 'number)) (set (co^ k 'number))] ;; Anything else is stuck [(_ _) (set s)])] [s (set s)])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 0CFA - style Abstract semantics (define (widen b) (cond [(number? b) 'number] [else (error "Unknown base value" b)])) (define (bind s) (match s [(ap^ (clos l x e ρ) v k) (join-many! x (get-val σ v)) (extend ρ x x)] [(ap^ (rlos l f x e ρ) v k) (join-one! f (rlos l f x e ρ)) (join-many! x (get-val σ v)) (extend (extend ρ x x) f f)] [_ (error 'bind "Bad ~a" s)])) (define (push l ρ k) (join-one! l k) l) (define (join-one! a v) (define prev (vector-ref σ a)) (unless (member v prev) (vector-set! σ a (cons v prev)) (set! unions (add1 unions)))) (define (join-many! a vs) (define prev (vector-ref σ a)) (define-values (next added?) (for/fold ([res prev] [added? #f]) ([v (in-list vs)] #:unless (member v prev)) (values (cons v res) #t))) (when added? (vector-set! σ a next) (set! unions (add1 unions)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Exp - > Set 0CFA with store widening and specialized iteration (define (aval^ e) (define fst (inj e)) (define seen (make-hash (for/list ([c (in-set fst)]) (cons c unions)))) (time ;; ignore preprocessing (let loop ([todo fst]) (cond [(set-empty? todo) (for*/set ([(c at-unions) (in-hash seen)] #:when (ans^? c)) (ans^-v c))] [else (loop (wide-step-specialized todo seen))])))) Sexp - > Set State (define (inj sexp) (define-values (e nlabels) (parse sexp)) (set! σ (make-vector nlabels '())) ((compile e) #;empty-environment-> (hash) 'mt)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Widening State to State^ ;; State^ -> State^ Specialized from wide - step : State^ - > { State^ } ≈ State^ - > State^ (define (wide-step-specialized cs seen) (for*/fold ([cs* (set)]) ([c (in-set cs)] [s (in-set (step-compiled^ c))] #:unless (= unions (hash-ref seen s -1))) (when (set? s) (error 'wide-step-specialized "Bad step ~a" c)) (hash-set! seen s unions) (set-add cs* s))) (aval^ church)
null
https://raw.githubusercontent.com/dvanhorn/oaam/79bc68ecb79fef45474a948deec1de90d255f307/code/iswim/0cfa-prealloc.rkt
racket
+ compilation phase + lazy non-determinism + specialized step & iterator State^ = (cons (Set Conf) Store) Global store "Compiled" Machine Compile away interpretive overhead of "ev" states Expr -> Comp State -> State^ Anything else is stuck Anything else is stuck ignore preprocessing empty-environment-> (hash) 'mt)) State^ -> State^
#lang racket (provide aval^ widen) (require "ast.rkt" (except-in "data.rkt" get-cont) "progs.rkt" (for-syntax syntax/parse)) (define-syntax-rule (for/union guards body1 body ...) (for/fold ([res (set)]) guards (set-union res (let () body1 body ...)))) (define-syntax-rule (for*/union guards body1 body ...) (for*/fold ([res (set)]) guards (set-union res (let () body1 body ...)))) 0CFA in the AAM style on some hairy Church numeral churning State = ( cons Conf Store ) Comp = Store Env Cont - > State^ (define σ #f) (define unions 0) (define nlabels #f) (define (get-cont σ l) (vector-ref σ l)) (define (compile e) (match e [(var l x) (λ (ρ k) (set (co^ k (addr (lookup-env ρ x)))))] [(num l n) (λ (ρ k) (set (co^ k n)))] [(bln l b) (λ (ρ k) (set (co^ k b)))] [(lam l x e) (define c (compile e)) (λ (ρ k) (set (co^ k (clos l x c ρ))))] [(rec f (lam l x e)) (define c (compile e)) (λ (ρ k) (set (co^ k (rlos l f x c ρ))))] [(app l e0 e1) (define c0 (compile e0)) (define c1 (compile e1)) (λ (ρ k) (define a (push l ρ k)) (c0 ρ (ar c1 ρ a)))] [(ife l e0 e1 e2) (define c0 (compile e0)) (define c1 (compile e1)) (define c2 (compile e2)) (λ (ρ k) (define a (push l ρ k)) (c0 ρ (ifk c1 c2 ρ a)))] [(1op l o e) (define c (compile e)) (λ (ρ k) (define a (push l ρ k)) (c ρ (1opk o a)))] [(2op l o e0 e1) (define c0 (compile e0)) (define c1 (compile e1)) (λ (ρ k) (define a (push l ρ k)) (c0 ρ (2opak o c1 ρ a)))] [_ (error 'compile "Bad ~a" e)])) Store ( ) - > Set (define (get-val σ v) (match v [(addr loc) (vector-ref σ loc)] [_ (list v)])) " Bytecode " interpreter (define (step-compiled^ s) (match s [(co^ k v) (match k ['mt (for*/set ([v (get-val σ v)]) (ans^ v))] [(ar c ρ l) (c ρ (fn v l))] [(fn f l) (for*/set ([k (get-cont σ l)] [f (get-val σ f)]) (ap^ f v k))] [(ifk c a ρ l) (for*/union ([k (get-cont σ l)] [v (get-val σ v)]) ((if v c a) ρ k))] [(1opk o l) (for*/set ([k (get-cont σ l)] [v (get-val σ v)]) (ap-op^ o (list v) k))] [(2opak o c ρ l) (c ρ (2opfk o v l))] [(2opfk o u l) (for*/set ([k (get-cont σ l)] [v (get-val σ v)] [u (get-val σ u)]) (ap-op^ o (list v u) k))] [_ (error 'step-compiled^ "Bad ~a" k)])] [(ap^ fun a k) (match fun [(clos l x c ρ) (define ρ* (bind s)) (c ρ* k)] [(rlos l f x c ρ) (define ρ* (bind s)) (c ρ* k)] [_ (set s)])] [(ap-op^ o vs k) (match* (o vs) [('zero? (list (? number? n))) (set (co^ k (zero? n)))] [('sub1 (list (? number? n))) (set (co^ k (widen (sub1 n))))] [('add1 (list (? number? n))) (set (co^ k (widen (add1 n))))] [('zero? (list 'number)) (set (co^ k #t) (co^ k #f))] [('sub1 (list 'number)) (set (co^ k 'number))] [('* (list (? number? n) (? number? m))) (set (co^ k (widen (* m n))))] [('* (list (? number? n) 'number)) (set (co^ k 'number))] [('* (list 'number 'number)) (set (co^ k 'number))] [(_ _) (set s)])] [s (set s)])) 0CFA - style Abstract semantics (define (widen b) (cond [(number? b) 'number] [else (error "Unknown base value" b)])) (define (bind s) (match s [(ap^ (clos l x e ρ) v k) (join-many! x (get-val σ v)) (extend ρ x x)] [(ap^ (rlos l f x e ρ) v k) (join-one! f (rlos l f x e ρ)) (join-many! x (get-val σ v)) (extend (extend ρ x x) f f)] [_ (error 'bind "Bad ~a" s)])) (define (push l ρ k) (join-one! l k) l) (define (join-one! a v) (define prev (vector-ref σ a)) (unless (member v prev) (vector-set! σ a (cons v prev)) (set! unions (add1 unions)))) (define (join-many! a vs) (define prev (vector-ref σ a)) (define-values (next added?) (for/fold ([res prev] [added? #f]) ([v (in-list vs)] #:unless (member v prev)) (values (cons v res) #t))) (when added? (vector-set! σ a next) (set! unions (add1 unions)))) Exp - > Set 0CFA with store widening and specialized iteration (define (aval^ e) (define fst (inj e)) (define seen (make-hash (for/list ([c (in-set fst)]) (cons c unions)))) (let loop ([todo fst]) (cond [(set-empty? todo) (for*/set ([(c at-unions) (in-hash seen)] #:when (ans^? c)) (ans^-v c))] [else (loop (wide-step-specialized todo seen))])))) Sexp - > Set State (define (inj sexp) (define-values (e nlabels) (parse sexp)) (set! σ (make-vector nlabels '())) Widening State to State^ Specialized from wide - step : State^ - > { State^ } ≈ State^ - > State^ (define (wide-step-specialized cs seen) (for*/fold ([cs* (set)]) ([c (in-set cs)] [s (in-set (step-compiled^ c))] #:unless (= unions (hash-ref seen s -1))) (when (set? s) (error 'wide-step-specialized "Bad step ~a" c)) (hash-set! seen s unions) (set-add cs* s))) (aval^ church)
8e7a44c1ba55ba1ff22ffc60bfe7a073233a9561f6eb092df07da8d2b0ffd3b3
xapi-project/xenopsd
device.mli
* Copyright ( C ) 2006 - 2009 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) 2006-2009 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 Device_common open Xenops_task exception Ioemu_failed of (string * string) exception Device_shutdown exception Device_not_found exception Cdrom * Definition of available qemu profiles , used by the qemu backend implementations implementations *) module Profile : sig type t = | Qemu_trad | Qemu_none | Qemu_upstream_compat | Qemu_upstream * available qemu profiles val typ_of : t Rpc.Types.typ val t : t Rpc.Types.def val fallback : t (** the fallback profile in case an invalid profile string is provided to [of_string] *) val all : t list (** all available profiles *) (** Valid names for a profile, used to define valid values for VM.platform.device-model *) module Name : sig val qemu_trad : string val qemu_upstream_compat : string val qemu_upstream : string end val wrapper_of : t -> string * [ wrapper_of profile ] returns the qemu wrapper script path of a profile val of_string : string -> t (** [of_string profile_name] returns the profile of a profile name, and [fallback] if an invalid name is provided. *) end * Represent an IPC endpoint module Socket : sig type t = Unix of string | Port of int end module Generic : sig val rm_device_state : xs:Xenstore.Xs.xsh -> device -> unit val exists : xs:Xenstore.Xs.xsh -> device -> bool val get_private_key : xs:Xenstore.Xs.xsh -> device -> string -> string end module Vbd : sig type mode = ReadOnly | ReadWrite val string_of_mode : mode -> string val mode_of_string : string -> mode type physty = File | Phys | Qcow | Vhd | Aio val string_of_physty : physty -> string val physty_of_string : string -> physty val uses_blktap : phystype:physty -> bool type devty = CDROM | Disk | Floppy val string_of_devty : devty -> string val devty_of_string : string -> devty type t = { mode: mode ; device_number: Device_number.t option ; phystype: physty ; params: string ; dev_type: devty ; unpluggable: bool ; protocol: protocol option ; kind: Device_common.kind ; extra_backend_keys: (string * string) list ; extra_private_keys: (string * string) list ; backend_domid: int } val add : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> hvm:bool -> t -> Xenctrl.domid -> device val release : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> device -> unit val media_eject : xs:Xenstore.Xs.xsh -> dm:Profile.t -> device -> unit val media_insert : xs:Xenstore.Xs.xsh -> dm:Profile.t -> phystype:physty -> params:string -> device -> unit val media_is_ejected : xs:Xenstore.Xs.xsh -> device -> bool val clean_shutdown_async : xs:Xenstore.Xs.xsh -> device -> unit val clean_shutdown_wait : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> ignore_transients:bool -> device -> unit (* For migration: *) val hard_shutdown_request : xs:Xenstore.Xs.xsh -> device -> unit val hard_shutdown_complete : xs:Xenstore.Xs.xsh -> device -> unit Watch.t val hard_shutdown_wait : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> timeout:float -> device -> unit end module Vif : sig val add : xs:Xenstore.Xs.xsh -> devid:int -> mac:string -> ?mtu:int -> ?rate:(int64 * int64) option -> ?backend_domid:Xenctrl.domid -> ?other_config:(string * string) list -> netty:Netman.netty -> carrier:bool -> ?protocol:protocol -> ?extra_private_keys:(string * string) list -> ?extra_xenserver_keys:(string * string) list -> Xenops_task.task_handle -> Xenctrl.domid -> device val set_carrier : xs:Xenstore.Xs.xsh -> device -> bool -> unit val release : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> device -> unit val move : xs:Xenstore.Xs.xsh -> device -> string -> unit end module NetSriovVf : sig val add : xs:Xenstore.Xs.xsh -> devid:int -> mac:string -> ?mtu:int -> ?rate:(int64 * int64) option -> ?backend_domid:Xenctrl.domid -> ?other_config:(string * string) list -> pci:Xenops_interface.Pci.address -> vlan:int64 option -> carrier:bool -> ?extra_private_keys:(string * string) list -> ?extra_xenserver_keys:(string * string) list -> Xenops_task.task_handle -> Xenctrl.domid -> device end val clean_shutdown : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> device -> unit val hard_shutdown : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> device -> unit val can_surprise_remove : xs:Xenstore.Xs.xsh -> device -> bool module Vcpu : sig val add : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> bool -> unit val del : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> unit val set : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> bool -> unit val status : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> bool end module PV_Vnc : sig exception Failed_to_start val save : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> unit val get_statefile : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> string option val start : ?statefile:string -> xs:Xenstore.Xs.xsh -> ?ip:string -> Xenctrl.domid -> unit val stop : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> unit val get_vnc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> Socket.t option val get_tc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option end module Qemu : sig module SignalMask : sig type t val create : unit -> t val set : t -> int -> unit val unset : t -> int -> unit val has : t -> int -> bool end val signal_mask : SignalMask.t val pid_path_signal : Xenctrl.domid -> string val pid : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option val is_running : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> bool end module Vgpu : sig val pid : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option val is_running : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> bool end module PCI : sig open Xenops_interface.Pci type t = { address: address ; irq: int ; resources: (int64 * int64 * int64) list ; driver: string } type supported_driver = I915 | Nvidia | Pciback type index = int type device' = { host: Xenops_interface.Pci.address ; guest: index * Xenops_interface.Pci.address option ; qmp_add: bool (** false: don't issue Device_add command *) } val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> hvm:bool -> device' list -> Xenctrl.domid -> unit val release : address list -> Xenctrl.domid -> unit val reset : xs:Xenstore.Xs.xsh -> address -> unit val bind : address list -> supported_driver -> unit val list : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> (int * address) list val dequarantine : Xenctrl.handle -> Xenops_interface.Pci.address -> bool end module Vfs : sig val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> ?backend_domid:int -> Xenctrl.domid -> unit end module Vfb : sig val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> ?backend_domid:int -> ?protocol:protocol -> Xenctrl.domid -> unit end module Vkbd : sig val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> ?backend_domid:int -> ?protocol:protocol -> Xenctrl.domid -> unit end module Dm : sig type usb_opt = Enabled of (string * int) list | Disabled type disp_intf_opt = | Std_vga | Cirrus | Vgpu of Xenops_interface.Vgpu.t list | GVT_d type disp_opt = | NONE | VNC of disp_intf_opt * string option * bool * int * string option (* IP address, auto-allocate, port if previous false, keymap *) | SDL of disp_intf_opt * string (* X11 display *) module Media : sig type t = Disk | Cdrom | Floppy end type info = { memory: int64 ; boot: string ; firmware: Xenops_types.Vm.firmware_type ; serial: string option ; monitor: string option ; vcpus: int ; (* vcpus max *) vcpus_current: int ; usb: usb_opt ; parallel: string option ; nics: (string * string * int) list ; disks: (int * string * Media.t) list ; acpi: bool ; disp: disp_opt ; pci_emulations: string list ; pci_passthrough: bool ; video_mib: int ; xen_platform: (int * int) option ; extras: (string * string option) list } type qemu_args = { argv: string list (** command line args *) ; fd_map: (string * Unix.file_descr) list (** open files *) } val get_vnc_port : xs:Xenstore.Xs.xsh -> dm:Profile.t -> Xenctrl.domid -> Socket.t option val get_tc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option val signal : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> qemu_domid:int -> domid:Xenctrl.domid -> ?wait_for:string -> ?param:string -> string -> unit val qemu_args : xs:Xenstore.Xs.xsh -> dm:Profile.t -> info -> bool (** true = restore *) * domid -> qemu_args * computes files and command line arguments to be passed to qemu val start : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> dm:Profile.t -> ?timeout:float -> info -> Xenctrl.domid -> unit val restore : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> dm:Profile.t -> ?timeout:float -> info -> Xenctrl.domid -> unit val assert_can_suspend : xs:Xenstore.Xs.xsh -> dm:Profile.t -> Xenctrl.domid -> unit val suspend : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> qemu_domid:int -> dm:Profile.t -> Xenctrl.domid -> unit val resume : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> qemu_domid:int -> Xenctrl.domid -> unit val stop : xs:Xenstore.Xs.xsh -> qemu_domid:int -> dm:Profile.t -> Xenctrl.domid -> unit val restore_vgpu : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> Xenctrl.domid -> Xenops_interface.Vgpu.t list -> int -> Profile.t -> unit val suspend_varstored : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> Xenctrl.domid -> vm_uuid:string -> string val restore_varstored : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> efivars:string -> Xenctrl.domid -> unit val after_suspend_image : xs:Xenstore.Xs.xsh -> dm:Profile.t -> qemu_domid:int -> int -> unit val pci_assign_guest : xs:Xenstore.Xs.xsh -> dm:Profile.t -> index:int -> host:Xenops_interface.Pci.address -> Xenops_interface.Pci.address option end module Backend : sig val init : unit -> unit end module Serial : sig val update_xenstore : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> unit end module Vusb : sig val vusb_plug : xs:Xenstore.Xs.xsh -> privileged:bool -> domid:Xenctrl.domid -> id:string -> hostbus:string -> hostport:string -> version:string -> speed:float -> unit val vusb_unplug : xs:Xenstore.Xs.xsh -> privileged:bool -> domid:Xenctrl.domid -> id:string -> hostbus:string -> hostport:string -> unit val qom_list : xs:Xenstore.Xs.xsh -> domid:Xenctrl.domid -> string list end val get_vnc_port : xs:Xenstore.Xs.xsh -> dm:Profile.t -> Xenctrl.domid -> Socket.t option val get_tc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option
null
https://raw.githubusercontent.com/xapi-project/xenopsd/f4da21a4ead7c6a7082af5ec32f778faf368cf1c/xc/device.mli
ocaml
* the fallback profile in case an invalid profile string is provided to [of_string] * all available profiles * Valid names for a profile, used to define valid values for VM.platform.device-model * [of_string profile_name] returns the profile of a profile name, and [fallback] if an invalid name is provided. For migration: * false: don't issue Device_add command IP address, auto-allocate, port if previous false, keymap X11 display vcpus max * command line args * open files * true = restore
* Copyright ( C ) 2006 - 2009 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) 2006-2009 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 Device_common open Xenops_task exception Ioemu_failed of (string * string) exception Device_shutdown exception Device_not_found exception Cdrom * Definition of available qemu profiles , used by the qemu backend implementations implementations *) module Profile : sig type t = | Qemu_trad | Qemu_none | Qemu_upstream_compat | Qemu_upstream * available qemu profiles val typ_of : t Rpc.Types.typ val t : t Rpc.Types.def val fallback : t val all : t list module Name : sig val qemu_trad : string val qemu_upstream_compat : string val qemu_upstream : string end val wrapper_of : t -> string * [ wrapper_of profile ] returns the qemu wrapper script path of a profile val of_string : string -> t end * Represent an IPC endpoint module Socket : sig type t = Unix of string | Port of int end module Generic : sig val rm_device_state : xs:Xenstore.Xs.xsh -> device -> unit val exists : xs:Xenstore.Xs.xsh -> device -> bool val get_private_key : xs:Xenstore.Xs.xsh -> device -> string -> string end module Vbd : sig type mode = ReadOnly | ReadWrite val string_of_mode : mode -> string val mode_of_string : string -> mode type physty = File | Phys | Qcow | Vhd | Aio val string_of_physty : physty -> string val physty_of_string : string -> physty val uses_blktap : phystype:physty -> bool type devty = CDROM | Disk | Floppy val string_of_devty : devty -> string val devty_of_string : string -> devty type t = { mode: mode ; device_number: Device_number.t option ; phystype: physty ; params: string ; dev_type: devty ; unpluggable: bool ; protocol: protocol option ; kind: Device_common.kind ; extra_backend_keys: (string * string) list ; extra_private_keys: (string * string) list ; backend_domid: int } val add : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> hvm:bool -> t -> Xenctrl.domid -> device val release : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> device -> unit val media_eject : xs:Xenstore.Xs.xsh -> dm:Profile.t -> device -> unit val media_insert : xs:Xenstore.Xs.xsh -> dm:Profile.t -> phystype:physty -> params:string -> device -> unit val media_is_ejected : xs:Xenstore.Xs.xsh -> device -> bool val clean_shutdown_async : xs:Xenstore.Xs.xsh -> device -> unit val clean_shutdown_wait : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> ignore_transients:bool -> device -> unit val hard_shutdown_request : xs:Xenstore.Xs.xsh -> device -> unit val hard_shutdown_complete : xs:Xenstore.Xs.xsh -> device -> unit Watch.t val hard_shutdown_wait : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> timeout:float -> device -> unit end module Vif : sig val add : xs:Xenstore.Xs.xsh -> devid:int -> mac:string -> ?mtu:int -> ?rate:(int64 * int64) option -> ?backend_domid:Xenctrl.domid -> ?other_config:(string * string) list -> netty:Netman.netty -> carrier:bool -> ?protocol:protocol -> ?extra_private_keys:(string * string) list -> ?extra_xenserver_keys:(string * string) list -> Xenops_task.task_handle -> Xenctrl.domid -> device val set_carrier : xs:Xenstore.Xs.xsh -> device -> bool -> unit val release : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> device -> unit val move : xs:Xenstore.Xs.xsh -> device -> string -> unit end module NetSriovVf : sig val add : xs:Xenstore.Xs.xsh -> devid:int -> mac:string -> ?mtu:int -> ?rate:(int64 * int64) option -> ?backend_domid:Xenctrl.domid -> ?other_config:(string * string) list -> pci:Xenops_interface.Pci.address -> vlan:int64 option -> carrier:bool -> ?extra_private_keys:(string * string) list -> ?extra_xenserver_keys:(string * string) list -> Xenops_task.task_handle -> Xenctrl.domid -> device end val clean_shutdown : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> device -> unit val hard_shutdown : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> device -> unit val can_surprise_remove : xs:Xenstore.Xs.xsh -> device -> bool module Vcpu : sig val add : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> bool -> unit val del : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> unit val set : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> bool -> unit val status : xs:Xenstore.Xs.xsh -> dm:Profile.t -> devid:int -> int -> bool end module PV_Vnc : sig exception Failed_to_start val save : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> unit val get_statefile : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> string option val start : ?statefile:string -> xs:Xenstore.Xs.xsh -> ?ip:string -> Xenctrl.domid -> unit val stop : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> unit val get_vnc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> Socket.t option val get_tc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option end module Qemu : sig module SignalMask : sig type t val create : unit -> t val set : t -> int -> unit val unset : t -> int -> unit val has : t -> int -> bool end val signal_mask : SignalMask.t val pid_path_signal : Xenctrl.domid -> string val pid : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option val is_running : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> bool end module Vgpu : sig val pid : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option val is_running : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> bool end module PCI : sig open Xenops_interface.Pci type t = { address: address ; irq: int ; resources: (int64 * int64 * int64) list ; driver: string } type supported_driver = I915 | Nvidia | Pciback type index = int type device' = { host: Xenops_interface.Pci.address ; guest: index * Xenops_interface.Pci.address option } val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> hvm:bool -> device' list -> Xenctrl.domid -> unit val release : address list -> Xenctrl.domid -> unit val reset : xs:Xenstore.Xs.xsh -> address -> unit val bind : address list -> supported_driver -> unit val list : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> (int * address) list val dequarantine : Xenctrl.handle -> Xenops_interface.Pci.address -> bool end module Vfs : sig val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> ?backend_domid:int -> Xenctrl.domid -> unit end module Vfb : sig val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> ?backend_domid:int -> ?protocol:protocol -> Xenctrl.domid -> unit end module Vkbd : sig val add : xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> ?backend_domid:int -> ?protocol:protocol -> Xenctrl.domid -> unit end module Dm : sig type usb_opt = Enabled of (string * int) list | Disabled type disp_intf_opt = | Std_vga | Cirrus | Vgpu of Xenops_interface.Vgpu.t list | GVT_d type disp_opt = | NONE | VNC of disp_intf_opt * string option * bool * int * string option | SDL of disp_intf_opt * string module Media : sig type t = Disk | Cdrom | Floppy end type info = { memory: int64 ; boot: string ; firmware: Xenops_types.Vm.firmware_type ; serial: string option ; monitor: string option ; vcpus: int vcpus_current: int ; usb: usb_opt ; parallel: string option ; nics: (string * string * int) list ; disks: (int * string * Media.t) list ; acpi: bool ; disp: disp_opt ; pci_emulations: string list ; pci_passthrough: bool ; video_mib: int ; xen_platform: (int * int) option ; extras: (string * string option) list } type qemu_args = { } val get_vnc_port : xs:Xenstore.Xs.xsh -> dm:Profile.t -> Xenctrl.domid -> Socket.t option val get_tc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option val signal : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> qemu_domid:int -> domid:Xenctrl.domid -> ?wait_for:string -> ?param:string -> string -> unit val qemu_args : xs:Xenstore.Xs.xsh -> dm:Profile.t -> info * domid -> qemu_args * computes files and command line arguments to be passed to qemu val start : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> dm:Profile.t -> ?timeout:float -> info -> Xenctrl.domid -> unit val restore : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> dm:Profile.t -> ?timeout:float -> info -> Xenctrl.domid -> unit val assert_can_suspend : xs:Xenstore.Xs.xsh -> dm:Profile.t -> Xenctrl.domid -> unit val suspend : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> qemu_domid:int -> dm:Profile.t -> Xenctrl.domid -> unit val resume : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> qemu_domid:int -> Xenctrl.domid -> unit val stop : xs:Xenstore.Xs.xsh -> qemu_domid:int -> dm:Profile.t -> Xenctrl.domid -> unit val restore_vgpu : Xenops_task.task_handle -> xc:Xenctrl.handle -> xs:Xenstore.Xs.xsh -> Xenctrl.domid -> Xenops_interface.Vgpu.t list -> int -> Profile.t -> unit val suspend_varstored : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> Xenctrl.domid -> vm_uuid:string -> string val restore_varstored : Xenops_task.task_handle -> xs:Xenstore.Xs.xsh -> efivars:string -> Xenctrl.domid -> unit val after_suspend_image : xs:Xenstore.Xs.xsh -> dm:Profile.t -> qemu_domid:int -> int -> unit val pci_assign_guest : xs:Xenstore.Xs.xsh -> dm:Profile.t -> index:int -> host:Xenops_interface.Pci.address -> Xenops_interface.Pci.address option end module Backend : sig val init : unit -> unit end module Serial : sig val update_xenstore : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> unit end module Vusb : sig val vusb_plug : xs:Xenstore.Xs.xsh -> privileged:bool -> domid:Xenctrl.domid -> id:string -> hostbus:string -> hostport:string -> version:string -> speed:float -> unit val vusb_unplug : xs:Xenstore.Xs.xsh -> privileged:bool -> domid:Xenctrl.domid -> id:string -> hostbus:string -> hostport:string -> unit val qom_list : xs:Xenstore.Xs.xsh -> domid:Xenctrl.domid -> string list end val get_vnc_port : xs:Xenstore.Xs.xsh -> dm:Profile.t -> Xenctrl.domid -> Socket.t option val get_tc_port : xs:Xenstore.Xs.xsh -> Xenctrl.domid -> int option
bfbc2026ea08e8d9b457bd68f3933de0bbdcd11edb205fde80b53a5238390748
thheller/shadow-experiments
forms.cljs
(ns shadow.experiments.grove.ui.forms (:require [shadow.experiments.grove.protocols :as gp] [shadow.experiments.arborist.protocols :as ap] [shadow.experiments.grove.components :as comp])) (deftype FormInstance [component-handle config ^:mutable state] gp/IHook (hook-init! [this] (js/console.log ::form-instance-init!)) (hook-ready? [this] true) (hook-value [this] ;; FIXME: return something thats easier to work with and as much data as possible ;; maybe pure data with meta reference to this, fields need this this) (hook-deps-update! [this ^FormInit val] (assert (identical? config (.-config val))) (when-not (= state (.-state val)) (js/console.log ::form-instance-deps-update! this val))) (hook-update! [this] (js/console.log ::form-instance-update! this)) (hook-destroy! [this] (js/console.log ::form-instance-destroy! this)) Object ;; dunno if we actually need to keep a reference ;; should return config, so it doesn't need a separate method (register-field [this field instance] (get-in config [:fields field])) (remove-field [this field]) (get-field-value [this field] (let [v (get state field ::undefined)] (if-not (keyword-identical? ::undefined v) v (get-in config [:fields field :default-value])))) (field-did-change! [this field val] (set! state (assoc state field val)) FIXME : invalidate form to trigger re - render of hosting component ? ;; FIXME: should validation be done by the form or the field? ;; eager-submit as in submit as soon as the form is valid (when (:eager-submit config) (let [submit-fn (:submit config)] (submit-fn (gp/get-component-env component-handle) state))) val)) (deftype FormInit [config state] gp/IBuildHook (hook-build [this ch] (FormInstance. ch config state))) (defn form-has-errors? [form] false) (defn form-has-error? [form field] false) ;; force configuration separately from instantiation ;; saves a bunch of checking if a form config was changed ;; since it may contain function it would otherwise ;; never compare equal (defn configure [config] ;; FIXME: validate config? (fn form-config [state] FIXME : validate state being passed in ? (FormInit. config state))) ;; ===================================================================== ;; SELECT ;; ===================================================================== ;; FIXME: move to separate ns once the structure is cleaner (defn select-find-idx [options current-val] (reduce-kv (fn [_ idx [val label]] (when (= val current-val) (reduced idx))) nil options)) (declare SelectInit) (deftype ManagedSelect [env element ^FormInstance form field ^:mutable options ^:mutable field-config] ap/IManaged (supports? [this ^SelectInit next] (and (instance? SelectInit next) (identical? form (.-form next)) (= field (.-field next)))) (dom-sync! [this ^SelectInit next] (when (not= options (.-options next)) (js/console.warn ::select-options-changed! this next))) (dom-insert [this parent anchor] (.insertBefore parent element anchor)) (dom-first [this] element) (dom-entered! [this]) (destroy! [this dom-remove?] (when dom-remove? (.remove element)) (.remove-field form field)) Object (init! [this] ;; FIXME: should maybe take some config from env or form ;; so that it is easier to keep input styles consistent? (set! field-config (.register-field form field this)) (let [class (or (get field-config :class-empty) (get field-config :class-valid)) init-val (.get-field-value form field) init-idx (select-find-idx options init-val)] (when class (set! element -className class)) (.set-options! this) (when init-idx (set! element -selectedIndex init-idx)) ;; FIXME: any other events we need to listen to for <select>? (.addEventListener element "change" (fn [e] (let [idx (.-selectedIndex element) options should be [ [ 1 " foo " ] ] [val label] (get options idx)] (.field-did-change! form field val)))))) (set-options! [this] ;; FIXME: does this work for reset? ;; (set! (.. element -options -length) 0) (reduce-kv (fn [_ idx [val label]] (let [opt (js/document.createElement "option")] (set! opt -text label) (when (nil? val) (set! opt -disabled true)) (.add element opt nil))) nil options) )) (deftype SelectInit [form field options] ap/IConstruct (as-managed [this env] (doto (ManagedSelect. env (js/document.createElement "select") form field options nil) (.init!)))) not doing fields via attrs since that means ;; none of the related code can ever be DCE'd ;; which is really bad ;; this is out since too much code would be always alive ;; (<< [:select {:form/field [form :thing options]}]) ;; this would be ok since enough select-specific could would still be removable ;; (<< [:select {:form/field (form/select-field form :thing options)}]) this is just the shortest and likely enough , also full control over DOM element ;; (form/select form :thing options) (defn- select-option? [thing] (and (vector? thing) (= 2 (count thing)) (string? (nth thing 1)))) (defn select [form field options] {:pre [(instance? FormInstance form) (keyword? field) (vector? options) (every? select-option? options)]} (SelectInit. form field options)) ;; FIXME: implement something like material-components-web, native select/input feel old and clunky ca n't use it directly because it is loading it via npm means no DCE ;; way too much code if everything is bundled ca n't consume it directly because no clean ESM output is provided ( as of now )
null
https://raw.githubusercontent.com/thheller/shadow-experiments/e4822b8c8fb411b21dcefa39053bd05f60e441d6/src/main/shadow/experiments/grove/ui/forms.cljs
clojure
FIXME: return something thats easier to work with and as much data as possible maybe pure data with meta reference to this, fields need this dunno if we actually need to keep a reference should return config, so it doesn't need a separate method FIXME: should validation be done by the form or the field? eager-submit as in submit as soon as the form is valid force configuration separately from instantiation saves a bunch of checking if a form config was changed since it may contain function it would otherwise never compare equal FIXME: validate config? ===================================================================== SELECT ===================================================================== FIXME: move to separate ns once the structure is cleaner FIXME: should maybe take some config from env or form so that it is easier to keep input styles consistent? FIXME: any other events we need to listen to for <select>? FIXME: does this work for reset? (set! (.. element -options -length) 0) none of the related code can ever be DCE'd which is really bad this is out since too much code would be always alive (<< [:select {:form/field [form :thing options]}]) this would be ok since enough select-specific could would still be removable (<< [:select {:form/field (form/select-field form :thing options)}]) (form/select form :thing options) FIXME: implement something like material-components-web, native select/input feel old and clunky way too much code if everything is bundled
(ns shadow.experiments.grove.ui.forms (:require [shadow.experiments.grove.protocols :as gp] [shadow.experiments.arborist.protocols :as ap] [shadow.experiments.grove.components :as comp])) (deftype FormInstance [component-handle config ^:mutable state] gp/IHook (hook-init! [this] (js/console.log ::form-instance-init!)) (hook-ready? [this] true) (hook-value [this] this) (hook-deps-update! [this ^FormInit val] (assert (identical? config (.-config val))) (when-not (= state (.-state val)) (js/console.log ::form-instance-deps-update! this val))) (hook-update! [this] (js/console.log ::form-instance-update! this)) (hook-destroy! [this] (js/console.log ::form-instance-destroy! this)) Object (register-field [this field instance] (get-in config [:fields field])) (remove-field [this field]) (get-field-value [this field] (let [v (get state field ::undefined)] (if-not (keyword-identical? ::undefined v) v (get-in config [:fields field :default-value])))) (field-did-change! [this field val] (set! state (assoc state field val)) FIXME : invalidate form to trigger re - render of hosting component ? (when (:eager-submit config) (let [submit-fn (:submit config)] (submit-fn (gp/get-component-env component-handle) state))) val)) (deftype FormInit [config state] gp/IBuildHook (hook-build [this ch] (FormInstance. ch config state))) (defn form-has-errors? [form] false) (defn form-has-error? [form field] false) (defn configure [config] (fn form-config [state] FIXME : validate state being passed in ? (FormInit. config state))) (defn select-find-idx [options current-val] (reduce-kv (fn [_ idx [val label]] (when (= val current-val) (reduced idx))) nil options)) (declare SelectInit) (deftype ManagedSelect [env element ^FormInstance form field ^:mutable options ^:mutable field-config] ap/IManaged (supports? [this ^SelectInit next] (and (instance? SelectInit next) (identical? form (.-form next)) (= field (.-field next)))) (dom-sync! [this ^SelectInit next] (when (not= options (.-options next)) (js/console.warn ::select-options-changed! this next))) (dom-insert [this parent anchor] (.insertBefore parent element anchor)) (dom-first [this] element) (dom-entered! [this]) (destroy! [this dom-remove?] (when dom-remove? (.remove element)) (.remove-field form field)) Object (init! [this] (set! field-config (.register-field form field this)) (let [class (or (get field-config :class-empty) (get field-config :class-valid)) init-val (.get-field-value form field) init-idx (select-find-idx options init-val)] (when class (set! element -className class)) (.set-options! this) (when init-idx (set! element -selectedIndex init-idx)) (.addEventListener element "change" (fn [e] (let [idx (.-selectedIndex element) options should be [ [ 1 " foo " ] ] [val label] (get options idx)] (.field-did-change! form field val)))))) (set-options! [this] (reduce-kv (fn [_ idx [val label]] (let [opt (js/document.createElement "option")] (set! opt -text label) (when (nil? val) (set! opt -disabled true)) (.add element opt nil))) nil options) )) (deftype SelectInit [form field options] ap/IConstruct (as-managed [this env] (doto (ManagedSelect. env (js/document.createElement "select") form field options nil) (.init!)))) not doing fields via attrs since that means this is just the shortest and likely enough , also full control over DOM element (defn- select-option? [thing] (and (vector? thing) (= 2 (count thing)) (string? (nth thing 1)))) (defn select [form field options] {:pre [(instance? FormInstance form) (keyword? field) (vector? options) (every? select-option? options)]} (SelectInit. form field options)) ca n't use it directly because it is loading it via npm means no DCE ca n't consume it directly because no clean ESM output is provided ( as of now )
9fb6d80a5a68546ee9ef3e396eba573d891b80affa1c7822a2cf8966a99142ce
xapi-project/xen-api
main.ml
module Xfm = Xenctrlext.Xenforeignmemory let usage_msg = "foreign-mapper <domid>" let domid = ref None let anon_fun param = match !domid with None -> domid := Some (int_of_string param) | _ -> () let defer f = Fun.protect ~finally:f let () = Arg.parse [] anon_fun usage_msg ; let the_domid = Option.get !domid in let handle = Xfm.acquire () in defer (fun () -> Xfm.release handle) @@ fun () -> let prot = {Xfm.read= true; write= true; exec= false} in let tpm_addr = 0x110000L in Xfm.with_mapping handle the_domid prot [tpm_addr] ~on_unmap_failure:(Fun.const ()) @@ fun mapping -> let readable_region = Bigarray.Array1.(create Char C_layout 1024) in for i = 0 to 1023 do readable_region.{i} <- mapping.{i} done ; Hex.(hexdump (of_bigstring readable_region))
null
https://raw.githubusercontent.com/xapi-project/xen-api/15812455c47dd62597d6d4312cdb06fb79bdf844/ocaml/xenforeign/main.ml
ocaml
module Xfm = Xenctrlext.Xenforeignmemory let usage_msg = "foreign-mapper <domid>" let domid = ref None let anon_fun param = match !domid with None -> domid := Some (int_of_string param) | _ -> () let defer f = Fun.protect ~finally:f let () = Arg.parse [] anon_fun usage_msg ; let the_domid = Option.get !domid in let handle = Xfm.acquire () in defer (fun () -> Xfm.release handle) @@ fun () -> let prot = {Xfm.read= true; write= true; exec= false} in let tpm_addr = 0x110000L in Xfm.with_mapping handle the_domid prot [tpm_addr] ~on_unmap_failure:(Fun.const ()) @@ fun mapping -> let readable_region = Bigarray.Array1.(create Char C_layout 1024) in for i = 0 to 1023 do readable_region.{i} <- mapping.{i} done ; Hex.(hexdump (of_bigstring readable_region))
1ba35774fab28350afd0a31d3603093ef209e6f23cc9a7ed271e979ac165b2c8
ygmpkk/house
Pen.hs
module Graphics.HGL.Win32.Pen ( Style(..) , Pen , createPen, deletePen, selectPen ) where import Graphics.HGL.Win32.Types import qualified System.Win32 as Win32 ---------------------------------------------------------------- newtype Pen = Pen Win32.HPEN data Style = Solid | Dash -- "-------" | Dot -- "......." | DashDot -- "_._._._" | DashDotDot -- "_.._.._" | Null | InsideFrame createPen :: Style -> Int -> RGB -> IO Pen deletePen :: Pen -> IO () selectPen :: Pen -> Draw Pen ---------------------------------------------------------------- style :: Style -> Win32.PenStyle style Solid = Win32.pS_SOLID style Dash = Win32.pS_DASH style Dot = Win32.pS_DOT style DashDot = Win32.pS_DASHDOT style DashDotDot = Win32.pS_DASHDOTDOT style Null = Win32.pS_NULL style InsideFrame = Win32.pS_INSIDEFRAME createPen sty width c = Win32.createPen (style sty) (fromIntegral width) (fromRGB c) >>= return . Pen deletePen (Pen pen) = Win32.deletePen pen selectPen (Pen p) = mkDraw (\hdc -> do p' <- Win32.selectPen hdc p return (Pen p')) ---------------------------------------------------------------- -- The end ----------------------------------------------------------------
null
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/HGL/Graphics/HGL/Win32/Pen.hs
haskell
-------------------------------------------------------------- "-------" "......." "_._._._" "_.._.._" -------------------------------------------------------------- -------------------------------------------------------------- The end --------------------------------------------------------------
module Graphics.HGL.Win32.Pen ( Style(..) , Pen , createPen, deletePen, selectPen ) where import Graphics.HGL.Win32.Types import qualified System.Win32 as Win32 newtype Pen = Pen Win32.HPEN data Style = Solid | Null | InsideFrame createPen :: Style -> Int -> RGB -> IO Pen deletePen :: Pen -> IO () selectPen :: Pen -> Draw Pen style :: Style -> Win32.PenStyle style Solid = Win32.pS_SOLID style Dash = Win32.pS_DASH style Dot = Win32.pS_DOT style DashDot = Win32.pS_DASHDOT style DashDotDot = Win32.pS_DASHDOTDOT style Null = Win32.pS_NULL style InsideFrame = Win32.pS_INSIDEFRAME createPen sty width c = Win32.createPen (style sty) (fromIntegral width) (fromRGB c) >>= return . Pen deletePen (Pen pen) = Win32.deletePen pen selectPen (Pen p) = mkDraw (\hdc -> do p' <- Win32.selectPen hdc p return (Pen p'))
6cb0d85e893e20b1652b30b935840ba78b325790b30bcc1e5d527b65e2b8fa54
rootmos/loom
bridge_sup.erl
-module(bridge_sup). -behaviour(gen_server). -export([start_link/1]). -export([init/1, handle_call/3, handle_cast/2]). start_link(Args) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Args], []). init(Port) -> Pid = ar_bridge:start([], [loom:node()], Port), ar_node:add_peers(loom:node(), Pid), erlang:register(http_bridge_node, Pid), error_logger:info_report([{bridge, Pid}]), {ok, {}}. handle_call(_Msg, _From, State) -> {noreply, State}. handle_cast(_Msg, State) -> {noreply, State}.
null
https://raw.githubusercontent.com/rootmos/loom/5f68ef9a9a5350f14d70935bacec3287aca60f1f/apps/loom/src/bridge_sup.erl
erlang
-module(bridge_sup). -behaviour(gen_server). -export([start_link/1]). -export([init/1, handle_call/3, handle_cast/2]). start_link(Args) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Args], []). init(Port) -> Pid = ar_bridge:start([], [loom:node()], Port), ar_node:add_peers(loom:node(), Pid), erlang:register(http_bridge_node, Pid), error_logger:info_report([{bridge, Pid}]), {ok, {}}. handle_call(_Msg, _From, State) -> {noreply, State}. handle_cast(_Msg, State) -> {noreply, State}.
1a5bd9b7fe81becc34559ce6a30e45bdcd043affa26bc36898db2587702d126a
alesaccoia/festival_flinger
toksearch.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; Centre for Speech Technology Research ; ; University of Edinburgh , UK ; ; ;;; Copyright (c) 1996,1997 ;; All Rights Reserved . ; ; ;;; ;; ;;; Permission is hereby granted, free of charge, to use and distribute ;; ;;; this software and its documentation without restriction, including ;; ;;; without limitation the rights to use, copy, modify, merge, publish, ;; ;;; distribute, sublicense, and/or sell copies of this work, and to ;; ;;; permit persons to whom this work is furnished to do so, subject to ;; ;;; the following conditions: ;; ;;; 1. The code must retain the above copyright notice, this list of ;; ;;; conditions and the following disclaimer. ;; ;;; 2. Any modifications must be clearly marked as such. ;; 3 . Original authors ' names are not deleted . ; ; ;;; 4. The authors' names are not used to endorse or promote products ;; ;;; derived from this software without specific prior written ;; ;;; permission. ;; ;;; ;; ;;; THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;; ;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;; ;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;; ;;; SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;; ;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;; WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;; ;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;; ;;; THIS SOFTWARE. ;; ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; A search for token occurrences in buckets of text ;;; ;;; This is only an example to aid you, this actually depends on ;;; the availability of databases we don't have permission to ;;; distribute. (set! text_dir "/home/awb/data/text/") ;;; The databases themselves are identified by a file which names all the files in that databases . e.g. This expects / gutenberg.files ;;; to exists which should contain something like ;;; gutenberg/etext90/bill11.txt ;;; gutenberg/etext90/const11.txt ;;; gutenberg/etext90/getty11.txt (set! db_names books from gutenberg 21906570 books , documents etc 23090463 Time Magazine 1990 - 1994 6770175 "hutch" ;; Hutchinson Encyclopedia 1715268 "dicts" ;; Dictionaries and Encyclopedias 4248109 Standard Reference libraries 3330448 WSJ articles from treebank 1109895 "email" ;; awb's email )) ;;; Identify the tokens you want extracted ;;; Tokens may be regular expressions (set! desired_tokens '(lead wound tear axes Jan bass Nice Begin Chi Colon St Dr III IV V X VII II "[0-9]+")) First pass : to get examples and context for labelling (set! desired_feats '(filepos p.p.p.p.name p.p.p.name p.p.name p.name name n.name nn.name n.n.n.name n.n.n.n.name)) Second : pass to get desried features for tree building ;;; Typically this has to be specific for a particular homograph so you 'll probably want to do multiple second passes one for each ;;; homograph type ;(set! desired_feats ' ( ; lisp_tok_rex ; p.punc ; punc ; n.punc pp.cap p.cap n.cap nn.cap ; )) (define (tok_search_db dbname) "Search through DB for named tokens and save found occurrences." (let ((outfile (string-append text_dir "fullhgs/" dbname ".out"))) (delete-file outfile) (mapcar (lambda (fname) ;; for each file in the database (extract_tokens ;; call internal function to extract tokens (string-append text_dir fname) ;; full pathname to extract from (mapcar ;; list of tokens and features (lambda (t) ;; to extract (cons t desired_feats)) desired_tokens) outfile)) (load (string-append text_dir "bin/" dbname ".files") t)) t)) (define (tok_do_all) "Search all dbs for desired tokens." (mapcar (lambda (db) (print db) (tok_search_db db)) db_names) t)
null
https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/examples/toksearch.scm
scheme
;; ; ; Copyright (c) 1996,1997 ;; ; ;; Permission is hereby granted, free of charge, to use and distribute ;; this software and its documentation without restriction, including ;; without limitation the rights to use, copy, modify, merge, publish, ;; distribute, sublicense, and/or sell copies of this work, and to ;; permit persons to whom this work is furnished to do so, subject to ;; the following conditions: ;; 1. The code must retain the above copyright notice, this list of ;; conditions and the following disclaimer. ;; 2. Any modifications must be clearly marked as such. ;; ; 4. The authors' names are not used to endorse or promote products ;; derived from this software without specific prior written ;; permission. ;; ;; THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;; SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;; ; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;; THIS SOFTWARE. ;; ;; A search for token occurrences in buckets of text This is only an example to aid you, this actually depends on the availability of databases we don't have permission to distribute. The databases themselves are identified by a file which names all to exists which should contain something like gutenberg/etext90/bill11.txt gutenberg/etext90/const11.txt gutenberg/etext90/getty11.txt Hutchinson Encyclopedia 1715268 Dictionaries and Encyclopedias 4248109 awb's email Identify the tokens you want extracted Tokens may be regular expressions Typically this has to be specific for a particular homograph homograph type (set! desired_feats lisp_tok_rex p.punc punc n.punc )) for each file in the database call internal function to extract tokens full pathname to extract from list of tokens and features to extract
(set! text_dir "/home/awb/data/text/") the files in that databases . e.g. This expects / gutenberg.files (set! db_names books from gutenberg 21906570 books , documents etc 23090463 Time Magazine 1990 - 1994 6770175 Standard Reference libraries 3330448 WSJ articles from treebank 1109895 )) (set! desired_tokens '(lead wound tear axes Jan bass Nice Begin Chi Colon St Dr III IV V X VII II "[0-9]+")) First pass : to get examples and context for labelling (set! desired_feats '(filepos p.p.p.p.name p.p.p.name p.p.name p.name name n.name nn.name n.n.n.name n.n.n.n.name)) Second : pass to get desried features for tree building so you 'll probably want to do multiple second passes one for each ' ( pp.cap p.cap n.cap nn.cap (define (tok_search_db dbname) "Search through DB for named tokens and save found occurrences." (let ((outfile (string-append text_dir "fullhgs/" dbname ".out"))) (delete-file outfile) (mapcar (cons t desired_feats)) desired_tokens) outfile)) (load (string-append text_dir "bin/" dbname ".files") t)) t)) (define (tok_do_all) "Search all dbs for desired tokens." (mapcar (lambda (db) (print db) (tok_search_db db)) db_names) t)
88068c6588bcd139e8872377ea6db9ca5c279067f316b384a69b52a08bf60340
tweag/ormolu
lenses-out.hs
lenses = Just $ M.fromList $ "type" .= ("user.connection" :: Text) # "connection" .= uc # "user" .= case name of Just n -> Just $ object ["name" .= n] Nothing -> Nothing # [] foo = a & b .~ 2 & c .~ 3 wreq = let opts = defaults & auth ?~ awsAuth AWSv4 "key" "secret" & header "Accept" .~ ["application/json"] & header "Runscope-Bucket-Auth" .~ ["1example-1111-4yyyy-zzzz-xxxxxxxx"] in getWith opts
null
https://raw.githubusercontent.com/tweag/ormolu/1f63136d047205f95b7d3c0f6aa34c34bb29ac7f/data/examples/declaration/value/function/infix/lenses-out.hs
haskell
lenses = Just $ M.fromList $ "type" .= ("user.connection" :: Text) # "connection" .= uc # "user" .= case name of Just n -> Just $ object ["name" .= n] Nothing -> Nothing # [] foo = a & b .~ 2 & c .~ 3 wreq = let opts = defaults & auth ?~ awsAuth AWSv4 "key" "secret" & header "Accept" .~ ["application/json"] & header "Runscope-Bucket-Auth" .~ ["1example-1111-4yyyy-zzzz-xxxxxxxx"] in getWith opts
1408726426cd91176bb79bbe720e70cb37aa118808e0f6b3e72a120842fb9035
Armael/ocaml-xkbcommon
xkbcommon.ml
type keysym = int type keycode = int module Keysyms = Keysyms module Context = Context module Rule_names = Rule_names module Keymap = Keymap module State = State
null
https://raw.githubusercontent.com/Armael/ocaml-xkbcommon/af0cd8c938938db3e67b65ac13b6444102756ba0/lib/xkbcommon.ml
ocaml
type keysym = int type keycode = int module Keysyms = Keysyms module Context = Context module Rule_names = Rule_names module Keymap = Keymap module State = State
696a4d4427f07f0a958a945d6f9f9d5606428e04c1a5aa35becb0c4f6eb857df
jafingerhut/thalia
core.match-0.2.0-project.clj
(defproject clojure.core.match "0.2.0" :description "core.match 0.2.0" :eval-in :leiningen :source-paths [ "src/main/clojure" ] : dependencies [ [ org.clojure/core.logic " 0.6.5 " ] ] )
null
https://raw.githubusercontent.com/jafingerhut/thalia/20c98eec8168ff72c5b3965cc048b817d34a4583/scripts/core.match-0.2.0-project.clj
clojure
(defproject clojure.core.match "0.2.0" :description "core.match 0.2.0" :eval-in :leiningen :source-paths [ "src/main/clojure" ] : dependencies [ [ org.clojure/core.logic " 0.6.5 " ] ] )
58bdfe731d827ea11b545af4d7f7f4685f7fe3c83c0af5677b4b4e7d6f2d530f
curaai/H-R-Tracing
Sphere.hs
module Hittable.Sphere ( Sphere(Sphere) ) where import Data.Bool (bool) import Data.Maybe (fromJust, isNothing) import Hit (HitRange, HitRecord (HitRecord), Material) import Hittable.Hittable (Hittable (..), isInRange) import Ray (Ray (Ray, direction), at) import Vector (Point, vDot, vLengthSquared) data Sphere = Sphere { sphereCenter :: Point , sphereRadius :: Float , sphereMaterial :: Material } instance Hittable Sphere where hit sp@(Sphere ctr radius mtr) ray hitRange = do t <- findNearestRoot sp ray hitRange let p = at ray t normal = (p - ctr) / pure radius frontFace = 0 > vDot (direction ray) normal return $ HitRecord p (bool negate id frontFace normal) t frontFace mtr findNearestRoot :: Sphere -> Ray -> HitRange -> Maybe Float findNearestRoot sphere ray hitRange | discriminant < 0 = Nothing | otherwise = nearestRoot where (discriminant, halfB, a) = findRoot sphere ray nearestRoot | isInRange rootMinus hitRange = Just rootMinus | isInRange rootPlus hitRange = Just rootPlus | otherwise = Nothing where rootMinus = ((-halfB) - sqrt discriminant) / a rootPlus = ((-halfB) + sqrt discriminant) / a findRoot (Sphere ctr radius _) (Ray ori dir) = (discriminant, halfB, a) where discriminant = halfB * halfB - a * c a = vLengthSquared dir c = vLengthSquared oc - radius * radius oc = ori - ctr halfB = vDot oc dir
null
https://raw.githubusercontent.com/curaai/H-R-Tracing/ad4867763083994c0d482a3e73e5b3de97e20d5c/src/Hittable/Sphere.hs
haskell
module Hittable.Sphere ( Sphere(Sphere) ) where import Data.Bool (bool) import Data.Maybe (fromJust, isNothing) import Hit (HitRange, HitRecord (HitRecord), Material) import Hittable.Hittable (Hittable (..), isInRange) import Ray (Ray (Ray, direction), at) import Vector (Point, vDot, vLengthSquared) data Sphere = Sphere { sphereCenter :: Point , sphereRadius :: Float , sphereMaterial :: Material } instance Hittable Sphere where hit sp@(Sphere ctr radius mtr) ray hitRange = do t <- findNearestRoot sp ray hitRange let p = at ray t normal = (p - ctr) / pure radius frontFace = 0 > vDot (direction ray) normal return $ HitRecord p (bool negate id frontFace normal) t frontFace mtr findNearestRoot :: Sphere -> Ray -> HitRange -> Maybe Float findNearestRoot sphere ray hitRange | discriminant < 0 = Nothing | otherwise = nearestRoot where (discriminant, halfB, a) = findRoot sphere ray nearestRoot | isInRange rootMinus hitRange = Just rootMinus | isInRange rootPlus hitRange = Just rootPlus | otherwise = Nothing where rootMinus = ((-halfB) - sqrt discriminant) / a rootPlus = ((-halfB) + sqrt discriminant) / a findRoot (Sphere ctr radius _) (Ray ori dir) = (discriminant, halfB, a) where discriminant = halfB * halfB - a * c a = vLengthSquared dir c = vLengthSquared oc - radius * radius oc = ori - ctr halfB = vDot oc dir
b7e3492e3e7bc12d1155f0027852d697dc209777c370b64171c614ee89aa8fa1
shirok/Gauche
test.scm
;;; ;;; gauche.test - test framework ;;; Copyright ( c ) 2000 - 2022 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; 3. Neither the name of the authors nor the names of its contributors ;;; may be used to endorse or promote products derived from this ;;; software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!no-fold-case ;; Note for developers: This module intentionally avoids using Gauche 's convenience features and extended libraries ; instead , ;; we stick to the minimal primitives here as much as possible. ;; It's because this module is used to test the convenience ;; features and extended libraries. ;; Writing your own test ;; ;; (use gauche.test) ;; (test-start "my feature") ;; (load "my-feature") ; load your program ;; (select-module my-feature) ; if your program defines a module. ;; ;; (test-module 'my-feature) ; checks if module binding is sane ;; ( test - section " feature group 1 " ) ( test " feature 1 - 1 " EXPECT ( lambda ( ) TEST - BODY ) ) ( test " feature 1 - 2 " EXPECT ( lambda ( ) TEST - BODY ) ) ;; ... ;; ( test - section " feature group 2 " ) ;; (define test-data ...) ( test " feature 2 - 1 " EXPECT ( lambda ( ) TEST - BODY ) ) ;; ... ;; ;; (test-end) ;; ;; To run a test interactively, just load the file. It is also recommended to have a " test " target in your Makefile , so that ;; the user of your program can run a test easily. The rule may look like ;; this: ;; ;; test : gosh my-feature-test.scm > test.log ;; ;; If stdout is redirected to other than tty, all the verbose logs will go ;; there, and only a small amount of messages go to stderr. ;; ;; Some environment variables affect the behavior of the tests. ;; ;; GAUCHE_TEST_REPORT_ERROR If defined, reports stack trace to stderr ;; when the test thunk raises an error (even when it is expected). ;; Useful for diagnosis of unexpected errors. ;; GAUCHE_TEST_RECORD_FILE If defined , names a file the test processes ;; keep the total statistics. Test-end accumulates the stats ;; into the named file instead of reporting it out immediately. (define-module gauche.test (export test test* test-start test-end test-running? test-section test-log test-module test-script test*/diff test-error test-one-of test-none-of test-truthy test-check test-check-diff test-include-r7 test-report-failure test-report-failure-plain test-report-failure-diff test-record-file test-summary-check *test-error* *test-report-error* test-error? prim-test test-count++ test-pass++ test-fail++ test-remove-files test-with-temporary-directory)) (select-module gauche.test) ;; Autoloads to avoid depending other modules (autoload "gauche/test/script" test-script) (autoload "gauche/test/diff" (:macro test*/diff) test-check-diff test-report-failure-diff) (autoload "gauche/test/include" (:macro test-include-r7)) ;; An object to represent error. This class isn't exported; the user ;; must use `test-error' procedure to create an instance. ;; ;; This object is used in both the expected result and the actual result ;; of test expression. For the actual result, this object holds the ;; raised condition in `condition' slot, and its class and message in ;; the `class' and `message' slots. For the expected result , class slot must be set as one of < condition > classes , or # f. If it 's a < condition > class , then it is used to test the actual result condition has the condition type . If it 's # f , ;; then any <test-error> object matches. (define-class <test-error> () ((condition :init-keyword :condition :init-value #f) (class :init-keyword :class :init-value #f) (message :init-keyword :message :init-value #f))) (define-method write-object ((obj <test-error>) out) (let1 cname (if (ref obj'class) (class-name (ref obj'class)) 'error) (if (ref obj 'message) (format out "#<~a ~s>" cname (ref obj 'message)) (format out "#<~a>" cname)))) (define (test-error? obj) (is-a? obj <test-error>)) (define (test-error :optional (class #f) (message #f)) (make <test-error> :class class :message message)) ;; An object to represent "any one of Xs" (define-class <test-one-of> () ((choices :init-keyword :choices))) (define-method write-object ((obj <test-one-of>) out) (format out "#<test-one-of: any one of ~s>" (slot-ref obj'choices))) ;; API (define (test-one-of . choices) (make <test-one-of> :choices choices)) ;; An object to represent "none of Xx" (define-class <test-none-of> () ((choices :init-keyword :choices))) (define-method write-object ((obj <test-none-of>) out) (format out "#<test-none-of: none of ~s>" (slot-ref obj'choices))) ;; API (define (test-none-of . choices) (make <test-none-of> :choices choices)) ;; An object to represent "any true value" (define-class <test-truthy> () ()) (define-method write-object ((obj <test-truthy>) out) (format out "#<test-truthy>")) ;; API (define (test-truthy) (make <test-truthy>)) ;; API ;; We don't use generic function dispatch (at least for the time being), ;; to make it easy to troubleshoot when object system gets messed up. ;; In future we'll make use of generic functions. (define (test-check expected result :optional (fallback equal?)) (cond [(test-error? expected) (and (test-error? result) (let ([c (slot-ref expected'class)] [e (slot-ref result'condition)]) (or (not c) (condition-has-type? e c))) (let ([m (slot-ref expected'message)] [em (slot-ref result'message)]) (cond [(string? m) (and (string? em) (equal? m em))] [(regexp? m) (and (string? em) (m em))] [else #t])))] [(is-a? expected <test-one-of>) (any (lambda (choice) (test-check choice result fallback)) (slot-ref expected 'choices))] [(is-a? expected <test-none-of>) (every (lambda (choice) (not (test-check choice result fallback))) (slot-ref expected 'choices))] [(is-a? expected <test-truthy>) result] [else (fallback expected result)])) (define *test-error* (make <test-error>)) ;DEPRECATED (define *test-report-error* (sys-getenv "GAUCHE_TEST_REPORT_ERROR")) (define *test-record-file* (sys-getenv "GAUCHE_TEST_RECORD_FILE")) ;; API (define (test-record-file file) (set! *test-record-file* file)) ;; List of discrepancies (define *discrepancy-list* '()) (define *test-counts* (vector 0 0 0 0)) ; total/pass/fail/abort (define (test-count++) (vector-set! *test-counts* 0 (+ (vector-ref *test-counts* 0) 1))) (define (test-pass++) (vector-set! *test-counts* 1 (+ (vector-ref *test-counts* 1) 1))) (define (test-fail++ msg expected result :optional (report test-report-failure)) (vector-set! *test-counts* 2 (+ (vector-ref *test-counts* 2) 1)) (set! *discrepancy-list* (cons (list report msg expected result) *discrepancy-list*))) (define (format-summary) (format "Total: ~5d tests, ~5d passed, ~5d failed, ~5d aborted.\n" (vector-ref *test-counts* 0) (vector-ref *test-counts* 1) (vector-ref *test-counts* 2) (vector-ref *test-counts* 3))) (define (read-summary) (when (and (string? *test-record-file*) (sys-access *test-record-file* F_OK)) ; avoid file-exists? to trigger autoload (with-input-from-file *test-record-file* (lambda () (let [(m (rxmatch #/Total:\s+(\d+)\s+tests,\s+(\d+)\s+passed,\s+(\d+)\s+failed,\s+(\d+)\s+aborted/ (read-line)))] (when m (for-each (lambda (i) (vector-set! *test-counts* i (string->number (rxmatch-substring m (+ i 1))))) '(0 1 2 3)))))))) (define (prepare-summary) We write out aborted+1 , in case if the test process fails before test - end ;; For normal case, it will be overwritten by test-end. (let ([orig-abort (vector-ref *test-counts* 3)]) (vector-set! *test-counts* 3 (+ orig-abort 1)) (write-summary) (vector-set! *test-counts* 3 orig-abort))) (define (write-summary) (when (string? *test-record-file*) (receive [p nam] (sys-mkstemp *test-record-file*) (display (format-summary) p) (close-output-port p) (sys-rename nam *test-record-file*)))) ;; Tests ------------------------------------------------------------ ;; test msg expect thunk :optional check report hook ;; check is called (check expected actual-result). default is test-check. ;; report is called (report msg expected actual-result) when failed. ;; The output must end with newline. ;; hook is called (hook 'fail|'pass msg expected actual-result) NB : In 0.9.10 , we have a signature ' : optional check hook ' ( no report ) . ;; We adopted ':optional check report hook', for it makes more sense. To keep the backward compatibility , we check the arity of the second ;; optional argument. ;; Primitive test. This uses neither with-error-handler nor the ;; object system, so it can be used _before_ those constructs are tested. (define (prim-test msg expect thunk . args) (let ([cmp (or (and (pair? args) (car args)) test-check)] [report (or (and (pair? args) (pair? (cdr args)) (cadr args)) test-report-failure)] [hook (and (pair? args) (pair? (cdr args)) (pair? (cddr args)) (caddr args))]) TRANSIENT : Backward compatibility of ' hook ' . Remove by 1.0 . (when (and (not (eq? report test-report-failure)) (not hook) (eqv? (arity report) 4)) (warn "gauche.test: `test' is called with old signature (hook).\n") (set! hook report) (set! report test-report-failure)) ;; End transient code (format/ss #t "test ~a, expects ~s ==> " msg expect) (flush) (test-count++) (let ([r (thunk)]) (cond [(cmp expect r) (format #t "ok\n") (test-pass++) (when hook (hook 'pass msg expect r))] [else (display "ERROR: GOT ") (report msg expect r) (newline) (test-fail++ msg expect r report) (when hook (hook 'fail msg expect r))]) (flush)))) ;; Normal test. (define (test msg expect thunk . args) (apply prim-test msg expect (lambda () (guard (e [else (when *test-report-error* (report-error e)) (make <test-error> :condition e :class (class-of e) :message (condition-message e e))]) (thunk))) args)) ;; A convenient macro version ;; We use er-macro-transformer, so test* should be used after the macro ;; subsystem is tested with more primitive framework. (define-syntax test* (er-macro-transformer (lambda (f r c) (apply (lambda (_ msg expect form . args) `(,(r 'test) ,msg ,expect (,(r 'lambda) () ,form) ,@args)) f)))) Toplevel binding sanity check ---------------------------------- Try to catch careless typos . Suggested by . The toplevel undefined variable screening is suggested by . ;; Keyword argument :allow-undefined takes a list of symbols, which ;; is excluded from undefined variable check. Keyword argument ;; :bypass-arity-check takes a list of symbols that bypasses arity check. (define (test-module module :key (allow-undefined '()) (bypass-arity-check '())) (test-count++) (let1 mod (cond [(module? module) module] [(symbol? module) (or (find-module module) (error "no such module" module))] [else (error "test-module requires module or symbol, but got" module)]) (format #t "testing bindings in ~a ... " mod) (flush) (test-module-common mod allow-undefined bypass-arity-check))) Common op for test - module and test - script . (define (test-module-common mod allow-undefined bypass-arity-check) (define (code-location src-code) (let1 src-info (debug-source-info src-code) (string-append (if src-info (format "~a:" (cadr src-info)) "") (format "~a" src-code)))) (let ([bad-autoload '()] [bad-export '()] [bad-gref '()] [bad-arity '()] [report '()]) 1 . Check if there 's no dangling autoloads . (hash-table-for-each (module-table mod) (lambda (sym val) (guard (_ (else (push! bad-autoload sym))) (global-variable-ref mod sym)))) 2 . Check if all exported symbols are properly defined . ;; We create an anonymous moudle and import the tested module. By this ;; way, we can test renaming export (in which case, the exported name ;; doesn't correspond to the binding in MOD so we can't look up directly in MOD . ) (when (and (module-name mod) (pair? (module-exports mod))) (let ([m (make-module #f)]) (eval `(import ,(module-name mod)) m) (eval `(extend) m) (for-each (lambda (sym) (guard (_ [else (push! bad-export sym)]) (global-variable-ref m sym))) (module-exports mod)))) 3 . Check if all global references are resolvable , and if it is ;; called, gets valid number of arguments. (for-each (lambda (closure) (for-each (lambda (arg) (let ([gref (car arg)] [numargs (cadr arg)] [src-code (caddr arg)]) (cond [(memq (slot-ref gref 'name) allow-undefined)] [(dangling-gref? gref (or src-code (slot-ref closure 'info))) => (lambda (bad) (push! bad-gref bad))] [(memq (slot-ref gref 'name) bypass-arity-check)] [(arity-invalid? gref numargs (or src-code (slot-ref closure 'info))) => (lambda (bad) (push! bad-arity bad))]))) (append-map closure-grefs (cons closure (filter closure? ((with-module gauche.internal %closure-env->list) closure)))))) (toplevel-closures mod)) ;; report discrepancies (unless (null? bad-autoload) (push! report (format "found dangling autoloads: ~a" bad-autoload))) (unless (null? bad-export) (unless (null? report) (push! report " AND ")) (push! report (format "symbols exported but not defined: ~a" bad-export))) (unless (null? bad-gref) (unless (null? report) (push! report " AND ")) (push! report (format "symbols referenced but not defined: ~a" (string-join (map (lambda (z) (format "~a(~a)" (car z) (code-location (cdr z)))) bad-gref) ", ")))) (unless (null? bad-arity) (unless (null? report) (push! report " AND ")) (push! report (format "procedures received wrong number of argument: ~a" (string-join (map (lambda (z) (format "~a(~a) got ~a" (car z) (code-location (cadr z)) (caddr z))) bad-arity) ", ")))) (cond [(null? report) (test-pass++) (format #t "ok\n")] [else (let ([s (apply string-append report)]) (format #t "ERROR: ~a\n" s) (test-fail++ (format #f "bindings in ~a" mod) '() s))]) )) Auxiliary funcs to catch dangling grefs . We use the fact that ;; an identifier embedded within the vm code is almost always an operand of or GSET . ( This is because identifiers are ;; introduced by macro expansion, but quoted identifiers are turned ;; back to ortinary symbols when expansion is done.) However, it ;; may not be impossible to embed identifiers within literals. ;; Eventually we need a builtin procedure that picks identifiers used for / GSET . ;; Note that these identifiers in operands are replaced by GLOCs ;; once the code is executed. We don't need to consider them; since if the identifier has successufully replaced by a GLOC , it could n't ;; be an undefined reference. (define (toplevel-closures module) (filter closure? (map (lambda (sym) (global-variable-ref module sym #f)) (hash-table-keys (module-table module))))) ;; Combs closure's instruction list to extract references for the global ;; identifiers. If it is a call to the global function, we also picks ;; up the number of arguments, so that we can check it against arity. ;; Returns ((<identifier> <num-args> <source-code>|#f) ...) (define (closure-grefs closure) (define code->list (with-module gauche.internal vm-code->list)) (define (gref-numargs code) (cadr code)) (define gref-call-insns '(GREF-CALL PUSH-GREF-CALL GREF-TAIL-CALL PUSH-GREF-TAIL-CALL)) (let loop ([r '()] [code (code->list (closure-code closure))] [i 0] [debug-info (~ (closure-code closure)'debug-info)]) (cond [(null? code) r] [(and (pair? (car code)) (memq (caar code) gref-call-insns)) (if (pair? (cdr code)) (if (wrapped-identifier? (cadr code)) (let* ([src-code (assq-ref (assv-ref debug-info i '()) 'source-info)] ;; If the identifier is in `code' and the source-code ;; field is empty, fill the field with the current ;; `src-code'. [new-r (map (lambda (e) (let ([ident (car e)] [numargs (cadr e)] [orig-src-code (caddr e)]) (if (and (memq (identifier->symbol ident) src-code) (not orig-src-code)) `(,ident ,numargs ,src-code) e))) r)]) (loop `((,(cadr code) ,(gref-numargs (car code)) ,src-code) ,@new-r) (cddr code) (+ i 2) debug-info)) (loop r (cddr code) (+ i 2) debug-info)) ;skip #<gloc> (loop r '() (+ i 1) debug-info))] [(wrapped-identifier? (car code)) (loop `((,(car code) #f #f) ,@r) (cdr code) (+ i 1) debug-info)] [(is-a? (car code) <compiled-code>) (loop (loop r (code->list (car code)) 0 (~ (car code)'debug-info)) (cdr code) (+ i 1) debug-info)] [(list? (car code)) ; for the operand of LOCAL-ENV-CLOSURES (loop (loop r (car code) 0 '()) (cdr code) (+ i 1) debug-info)] [else (loop r (cdr code) (+ i 1) debug-info)]))) (define (arity-invalid? gref numargs src-code) (and-let* ([ numargs ] TODO : What if is nested identifier ? [proc (global-variable-ref (slot-ref gref'module) (unwrap-syntax gref) #f)] ;; We exclude <generic> with no methods. Such "placeholder" ;; generic function may be used in the base module, expecting ;; the other module adds methods to it. [ (not (and (is-a? proc <generic>) (null? (~ proc'methods)))) ] [ (not (apply applicable? proc (make-list numargs <bottom>))) ]) (list (slot-ref gref 'name) src-code numargs))) (define (dangling-gref? ident src-code) (let1 name (unwrap-syntax ident) (and (not ((with-module gauche.internal id->bound-gloc) ident)) (cons name src-code)))) ;; Logging and bookkeeping ----------------------------------------- ;; API: Default report procedure (define (test-report-failure msg expected actual) (write actual)) ;; API: Use ~a instead of ~s (define (test-report-failure-plain msg expected actual) (display actual)) ;; private global flag, true during we're running tests. ;; (we avoid using parameters intentionally.) (define *test-running* #f) (define (test-running?) *test-running*) (define (test-section msg) (let ([msglen (string-length msg)]) (format #t "<~a>~a\n" msg (make-string (max 5 (- 77 msglen)) #\-)))) (define (not-redirected? port) (cond-expand [gauche.os.windows (or (sys-isatty port) for ( mintty ) ((with-module gauche.internal %sys-mintty?) port) ;; for windows console conversion ports (port-attribute-ref port 'windows-console-conversion #f))] [else (sys-isatty port)])) (define (test-start msg) (set! *test-running* #t) (let* ([s (format #f "Testing ~a ... " msg)] [pad (make-string (max 3 (- 65 (string-length s))) #\space)]) (display s (current-error-port)) (display pad (current-error-port)) (flush (current-error-port)) (read-summary) (prepare-summary) (when (and (not-redirected? (current-error-port)) (not-redirected? (current-output-port))) (newline (current-error-port)))) (set! *discrepancy-list* '()) (unless (and (not-redirected? (current-error-port)) (not-redirected? (current-output-port))) (let ([msglen (string-length msg)]) (format #t "Testing ~a ~a\n" msg (make-string (max 5 (- 70 msglen)) #\=))) (flush)) ) ;; test-log fmt arg ... ;; The formatted output, prefixed by ";;", goes to stdout for the logging. (define (test-log fmt . args) (display ";; ") (apply format #t fmt args) (newline) (flush)) ;; test-end :key :exit-on-failure ;; avoid using extended formal list since we need to test it. (define (test-end . args) (let ([e (current-error-port)] [o (current-output-port)] [exit-on-failure (get-keyword :exit-on-failure args #f)]) (define (fmt . args) (if (and (not-redirected? e) (not-redirected? o)) (apply format/ss o args) (begin (apply format/ss e args) (apply format/ss o args)))) (if (null? *discrepancy-list*) (fmt "passed.\n") (begin (fmt "failed.\ndiscrepancies found. Errors are:\n") (for-each (lambda (r) (apply (lambda (report msg expect actual) (fmt "test ~a: expects ~s => got ~a\n" msg expect (with-output-to-string (cut report msg expect actual)))) r)) (reverse *discrepancy-list*)))) (flush) (when *test-record-file* (write-summary)) (set! *test-running* #f) ;; the number of failed tests. (let ([num-failures (length *discrepancy-list*)]) (when (and (> num-failures 0) exit-on-failure) (exit (if (fixnum? exit-on-failure) exit-on-failure 1))) num-failures))) Read the test record file ( if there 's any ) , and exit with 1 ;; if there has been any failure. (define (test-summary-check) (read-summary) (unless (and (zero? (vector-ref *test-counts* 2)) (zero? (vector-ref *test-counts* 3))) (exit 1))) ;; Temporary files and cleanup -------------------------------------- ;; Remove files and directories. Functionally same as 'remove-files' in ;; file.util; but this can be used _before_ we test file.util. (define (test-remove-files . paths) (define (remove-1 path) (if (and (file-is-directory? path) (not (eq? (slot-ref (sys-lstat path)'type) 'symlink))) (begin (for-each (^e (unless (member e '("." "..")) (remove-1 (string-append path "/" e)))) (sys-readdir path)) (sys-rmdir path)) (sys-unlink path))) (for-each remove-1 paths)) Create a fresh DIR , call THUNK ( without cd'ing ) , then remove DIR . (define (test-with-temporary-directory dir thunk) (test-remove-files dir) (sys-mkdir dir #o755) ;; Avoid relying on unwind-protect (dynamic-wind (^[] #f) thunk (^[] (test-remove-files dir))))
null
https://raw.githubusercontent.com/shirok/Gauche/e97efb5e54f9ab97746369b8ac748f338224c746/lib/gauche/test.scm
scheme
gauche.test - test framework Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the authors nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Note for developers: This module intentionally avoids using instead , we stick to the minimal primitives here as much as possible. It's because this module is used to test the convenience features and extended libraries. Writing your own test (use gauche.test) (test-start "my feature") (load "my-feature") ; load your program (select-module my-feature) ; if your program defines a module. (test-module 'my-feature) ; checks if module binding is sane ... (define test-data ...) ... (test-end) To run a test interactively, just load the file. the user of your program can run a test easily. The rule may look like this: test : If stdout is redirected to other than tty, all the verbose logs will go there, and only a small amount of messages go to stderr. Some environment variables affect the behavior of the tests. GAUCHE_TEST_REPORT_ERROR If defined, reports stack trace to stderr when the test thunk raises an error (even when it is expected). Useful for diagnosis of unexpected errors. keep the total statistics. Test-end accumulates the stats into the named file instead of reporting it out immediately. Autoloads to avoid depending other modules An object to represent error. This class isn't exported; the user must use `test-error' procedure to create an instance. This object is used in both the expected result and the actual result of test expression. For the actual result, this object holds the raised condition in `condition' slot, and its class and message in the `class' and `message' slots. then any <test-error> object matches. An object to represent "any one of Xs" API An object to represent "none of Xx" API An object to represent "any true value" API API We don't use generic function dispatch (at least for the time being), to make it easy to troubleshoot when object system gets messed up. In future we'll make use of generic functions. DEPRECATED API List of discrepancies total/pass/fail/abort avoid file-exists? to trigger autoload For normal case, it will be overwritten by test-end. Tests ------------------------------------------------------------ test msg expect thunk :optional check report hook check is called (check expected actual-result). default is test-check. report is called (report msg expected actual-result) when failed. The output must end with newline. hook is called (hook 'fail|'pass msg expected actual-result) We adopted ':optional check report hook', for it makes more sense. optional argument. Primitive test. This uses neither with-error-handler nor the object system, so it can be used _before_ those constructs are tested. End transient code Normal test. A convenient macro version We use er-macro-transformer, so test* should be used after the macro subsystem is tested with more primitive framework. Keyword argument :allow-undefined takes a list of symbols, which is excluded from undefined variable check. Keyword argument :bypass-arity-check takes a list of symbols that bypasses arity check. We create an anonymous moudle and import the tested module. By this way, we can test renaming export (in which case, the exported name doesn't correspond to the binding in MOD so we can't look up directly called, gets valid number of arguments. report discrepancies an identifier embedded within the vm code is almost always an introduced by macro expansion, but quoted identifiers are turned back to ortinary symbols when expansion is done.) However, it may not be impossible to embed identifiers within literals. Eventually we need a builtin procedure that picks identifiers once the code is executed. We don't need to consider them; since be an undefined reference. Combs closure's instruction list to extract references for the global identifiers. If it is a call to the global function, we also picks up the number of arguments, so that we can check it against arity. Returns ((<identifier> <num-args> <source-code>|#f) ...) If the identifier is in `code' and the source-code field is empty, fill the field with the current `src-code'. skip #<gloc> for the operand of LOCAL-ENV-CLOSURES We exclude <generic> with no methods. Such "placeholder" generic function may be used in the base module, expecting the other module adds methods to it. Logging and bookkeeping ----------------------------------------- API: Default report procedure API: Use ~a instead of ~s private global flag, true during we're running tests. (we avoid using parameters intentionally.) for windows console conversion ports test-log fmt arg ... The formatted output, prefixed by ";;", goes to stdout for the logging. test-end :key :exit-on-failure avoid using extended formal list since we need to test it. the number of failed tests. if there has been any failure. Temporary files and cleanup -------------------------------------- Remove files and directories. Functionally same as 'remove-files' in file.util; but this can be used _before_ we test file.util. Avoid relying on unwind-protect
Copyright ( c ) 2000 - 2022 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING #!no-fold-case ( test - section " feature group 1 " ) ( test " feature 1 - 1 " EXPECT ( lambda ( ) TEST - BODY ) ) ( test " feature 1 - 2 " EXPECT ( lambda ( ) TEST - BODY ) ) ( test - section " feature group 2 " ) ( test " feature 2 - 1 " EXPECT ( lambda ( ) TEST - BODY ) ) It is also recommended to have a " test " target in your Makefile , so that gosh my-feature-test.scm > test.log GAUCHE_TEST_RECORD_FILE If defined , names a file the test processes (define-module gauche.test (export test test* test-start test-end test-running? test-section test-log test-module test-script test*/diff test-error test-one-of test-none-of test-truthy test-check test-check-diff test-include-r7 test-report-failure test-report-failure-plain test-report-failure-diff test-record-file test-summary-check *test-error* *test-report-error* test-error? prim-test test-count++ test-pass++ test-fail++ test-remove-files test-with-temporary-directory)) (select-module gauche.test) (autoload "gauche/test/script" test-script) (autoload "gauche/test/diff" (:macro test*/diff) test-check-diff test-report-failure-diff) (autoload "gauche/test/include" (:macro test-include-r7)) For the expected result , class slot must be set as one of < condition > classes , or # f. If it 's a < condition > class , then it is used to test the actual result condition has the condition type . If it 's # f , (define-class <test-error> () ((condition :init-keyword :condition :init-value #f) (class :init-keyword :class :init-value #f) (message :init-keyword :message :init-value #f))) (define-method write-object ((obj <test-error>) out) (let1 cname (if (ref obj'class) (class-name (ref obj'class)) 'error) (if (ref obj 'message) (format out "#<~a ~s>" cname (ref obj 'message)) (format out "#<~a>" cname)))) (define (test-error? obj) (is-a? obj <test-error>)) (define (test-error :optional (class #f) (message #f)) (make <test-error> :class class :message message)) (define-class <test-one-of> () ((choices :init-keyword :choices))) (define-method write-object ((obj <test-one-of>) out) (format out "#<test-one-of: any one of ~s>" (slot-ref obj'choices))) (define (test-one-of . choices) (make <test-one-of> :choices choices)) (define-class <test-none-of> () ((choices :init-keyword :choices))) (define-method write-object ((obj <test-none-of>) out) (format out "#<test-none-of: none of ~s>" (slot-ref obj'choices))) (define (test-none-of . choices) (make <test-none-of> :choices choices)) (define-class <test-truthy> () ()) (define-method write-object ((obj <test-truthy>) out) (format out "#<test-truthy>")) (define (test-truthy) (make <test-truthy>)) (define (test-check expected result :optional (fallback equal?)) (cond [(test-error? expected) (and (test-error? result) (let ([c (slot-ref expected'class)] [e (slot-ref result'condition)]) (or (not c) (condition-has-type? e c))) (let ([m (slot-ref expected'message)] [em (slot-ref result'message)]) (cond [(string? m) (and (string? em) (equal? m em))] [(regexp? m) (and (string? em) (m em))] [else #t])))] [(is-a? expected <test-one-of>) (any (lambda (choice) (test-check choice result fallback)) (slot-ref expected 'choices))] [(is-a? expected <test-none-of>) (every (lambda (choice) (not (test-check choice result fallback))) (slot-ref expected 'choices))] [(is-a? expected <test-truthy>) result] [else (fallback expected result)])) (define *test-report-error* (sys-getenv "GAUCHE_TEST_REPORT_ERROR")) (define *test-record-file* (sys-getenv "GAUCHE_TEST_RECORD_FILE")) (define (test-record-file file) (set! *test-record-file* file)) (define *discrepancy-list* '()) (define (test-count++) (vector-set! *test-counts* 0 (+ (vector-ref *test-counts* 0) 1))) (define (test-pass++) (vector-set! *test-counts* 1 (+ (vector-ref *test-counts* 1) 1))) (define (test-fail++ msg expected result :optional (report test-report-failure)) (vector-set! *test-counts* 2 (+ (vector-ref *test-counts* 2) 1)) (set! *discrepancy-list* (cons (list report msg expected result) *discrepancy-list*))) (define (format-summary) (format "Total: ~5d tests, ~5d passed, ~5d failed, ~5d aborted.\n" (vector-ref *test-counts* 0) (vector-ref *test-counts* 1) (vector-ref *test-counts* 2) (vector-ref *test-counts* 3))) (define (read-summary) (when (and (string? *test-record-file*) (with-input-from-file *test-record-file* (lambda () (let [(m (rxmatch #/Total:\s+(\d+)\s+tests,\s+(\d+)\s+passed,\s+(\d+)\s+failed,\s+(\d+)\s+aborted/ (read-line)))] (when m (for-each (lambda (i) (vector-set! *test-counts* i (string->number (rxmatch-substring m (+ i 1))))) '(0 1 2 3)))))))) (define (prepare-summary) We write out aborted+1 , in case if the test process fails before test - end (let ([orig-abort (vector-ref *test-counts* 3)]) (vector-set! *test-counts* 3 (+ orig-abort 1)) (write-summary) (vector-set! *test-counts* 3 orig-abort))) (define (write-summary) (when (string? *test-record-file*) (receive [p nam] (sys-mkstemp *test-record-file*) (display (format-summary) p) (close-output-port p) (sys-rename nam *test-record-file*)))) NB : In 0.9.10 , we have a signature ' : optional check hook ' ( no report ) . To keep the backward compatibility , we check the arity of the second (define (prim-test msg expect thunk . args) (let ([cmp (or (and (pair? args) (car args)) test-check)] [report (or (and (pair? args) (pair? (cdr args)) (cadr args)) test-report-failure)] [hook (and (pair? args) (pair? (cdr args)) (pair? (cddr args)) (caddr args))]) TRANSIENT : Backward compatibility of ' hook ' . Remove by 1.0 . (when (and (not (eq? report test-report-failure)) (not hook) (eqv? (arity report) 4)) (warn "gauche.test: `test' is called with old signature (hook).\n") (set! hook report) (set! report test-report-failure)) (format/ss #t "test ~a, expects ~s ==> " msg expect) (flush) (test-count++) (let ([r (thunk)]) (cond [(cmp expect r) (format #t "ok\n") (test-pass++) (when hook (hook 'pass msg expect r))] [else (display "ERROR: GOT ") (report msg expect r) (newline) (test-fail++ msg expect r report) (when hook (hook 'fail msg expect r))]) (flush)))) (define (test msg expect thunk . args) (apply prim-test msg expect (lambda () (guard (e [else (when *test-report-error* (report-error e)) (make <test-error> :condition e :class (class-of e) :message (condition-message e e))]) (thunk))) args)) (define-syntax test* (er-macro-transformer (lambda (f r c) (apply (lambda (_ msg expect form . args) `(,(r 'test) ,msg ,expect (,(r 'lambda) () ,form) ,@args)) f)))) Toplevel binding sanity check ---------------------------------- Try to catch careless typos . Suggested by . The toplevel undefined variable screening is suggested by . (define (test-module module :key (allow-undefined '()) (bypass-arity-check '())) (test-count++) (let1 mod (cond [(module? module) module] [(symbol? module) (or (find-module module) (error "no such module" module))] [else (error "test-module requires module or symbol, but got" module)]) (format #t "testing bindings in ~a ... " mod) (flush) (test-module-common mod allow-undefined bypass-arity-check))) Common op for test - module and test - script . (define (test-module-common mod allow-undefined bypass-arity-check) (define (code-location src-code) (let1 src-info (debug-source-info src-code) (string-append (if src-info (format "~a:" (cadr src-info)) "") (format "~a" src-code)))) (let ([bad-autoload '()] [bad-export '()] [bad-gref '()] [bad-arity '()] [report '()]) 1 . Check if there 's no dangling autoloads . (hash-table-for-each (module-table mod) (lambda (sym val) (guard (_ (else (push! bad-autoload sym))) (global-variable-ref mod sym)))) 2 . Check if all exported symbols are properly defined . in MOD . ) (when (and (module-name mod) (pair? (module-exports mod))) (let ([m (make-module #f)]) (eval `(import ,(module-name mod)) m) (eval `(extend) m) (for-each (lambda (sym) (guard (_ [else (push! bad-export sym)]) (global-variable-ref m sym))) (module-exports mod)))) 3 . Check if all global references are resolvable , and if it is (for-each (lambda (closure) (for-each (lambda (arg) (let ([gref (car arg)] [numargs (cadr arg)] [src-code (caddr arg)]) (cond [(memq (slot-ref gref 'name) allow-undefined)] [(dangling-gref? gref (or src-code (slot-ref closure 'info))) => (lambda (bad) (push! bad-gref bad))] [(memq (slot-ref gref 'name) bypass-arity-check)] [(arity-invalid? gref numargs (or src-code (slot-ref closure 'info))) => (lambda (bad) (push! bad-arity bad))]))) (append-map closure-grefs (cons closure (filter closure? ((with-module gauche.internal %closure-env->list) closure)))))) (toplevel-closures mod)) (unless (null? bad-autoload) (push! report (format "found dangling autoloads: ~a" bad-autoload))) (unless (null? bad-export) (unless (null? report) (push! report " AND ")) (push! report (format "symbols exported but not defined: ~a" bad-export))) (unless (null? bad-gref) (unless (null? report) (push! report " AND ")) (push! report (format "symbols referenced but not defined: ~a" (string-join (map (lambda (z) (format "~a(~a)" (car z) (code-location (cdr z)))) bad-gref) ", ")))) (unless (null? bad-arity) (unless (null? report) (push! report " AND ")) (push! report (format "procedures received wrong number of argument: ~a" (string-join (map (lambda (z) (format "~a(~a) got ~a" (car z) (code-location (cadr z)) (caddr z))) bad-arity) ", ")))) (cond [(null? report) (test-pass++) (format #t "ok\n")] [else (let ([s (apply string-append report)]) (format #t "ERROR: ~a\n" s) (test-fail++ (format #f "bindings in ~a" mod) '() s))]) )) Auxiliary funcs to catch dangling grefs . We use the fact that operand of or GSET . ( This is because identifiers are used for / GSET . Note that these identifiers in operands are replaced by GLOCs if the identifier has successufully replaced by a GLOC , it could n't (define (toplevel-closures module) (filter closure? (map (lambda (sym) (global-variable-ref module sym #f)) (hash-table-keys (module-table module))))) (define (closure-grefs closure) (define code->list (with-module gauche.internal vm-code->list)) (define (gref-numargs code) (cadr code)) (define gref-call-insns '(GREF-CALL PUSH-GREF-CALL GREF-TAIL-CALL PUSH-GREF-TAIL-CALL)) (let loop ([r '()] [code (code->list (closure-code closure))] [i 0] [debug-info (~ (closure-code closure)'debug-info)]) (cond [(null? code) r] [(and (pair? (car code)) (memq (caar code) gref-call-insns)) (if (pair? (cdr code)) (if (wrapped-identifier? (cadr code)) (let* ([src-code (assq-ref (assv-ref debug-info i '()) 'source-info)] [new-r (map (lambda (e) (let ([ident (car e)] [numargs (cadr e)] [orig-src-code (caddr e)]) (if (and (memq (identifier->symbol ident) src-code) (not orig-src-code)) `(,ident ,numargs ,src-code) e))) r)]) (loop `((,(cadr code) ,(gref-numargs (car code)) ,src-code) ,@new-r) (cddr code) (+ i 2) debug-info)) (loop r '() (+ i 1) debug-info))] [(wrapped-identifier? (car code)) (loop `((,(car code) #f #f) ,@r) (cdr code) (+ i 1) debug-info)] [(is-a? (car code) <compiled-code>) (loop (loop r (code->list (car code)) 0 (~ (car code)'debug-info)) (cdr code) (+ i 1) debug-info)] (loop (loop r (car code) 0 '()) (cdr code) (+ i 1) debug-info)] [else (loop r (cdr code) (+ i 1) debug-info)]))) (define (arity-invalid? gref numargs src-code) (and-let* ([ numargs ] TODO : What if is nested identifier ? [proc (global-variable-ref (slot-ref gref'module) (unwrap-syntax gref) #f)] [ (not (and (is-a? proc <generic>) (null? (~ proc'methods)))) ] [ (not (apply applicable? proc (make-list numargs <bottom>))) ]) (list (slot-ref gref 'name) src-code numargs))) (define (dangling-gref? ident src-code) (let1 name (unwrap-syntax ident) (and (not ((with-module gauche.internal id->bound-gloc) ident)) (cons name src-code)))) (define (test-report-failure msg expected actual) (write actual)) (define (test-report-failure-plain msg expected actual) (display actual)) (define *test-running* #f) (define (test-running?) *test-running*) (define (test-section msg) (let ([msglen (string-length msg)]) (format #t "<~a>~a\n" msg (make-string (max 5 (- 77 msglen)) #\-)))) (define (not-redirected? port) (cond-expand [gauche.os.windows (or (sys-isatty port) for ( mintty ) ((with-module gauche.internal %sys-mintty?) port) (port-attribute-ref port 'windows-console-conversion #f))] [else (sys-isatty port)])) (define (test-start msg) (set! *test-running* #t) (let* ([s (format #f "Testing ~a ... " msg)] [pad (make-string (max 3 (- 65 (string-length s))) #\space)]) (display s (current-error-port)) (display pad (current-error-port)) (flush (current-error-port)) (read-summary) (prepare-summary) (when (and (not-redirected? (current-error-port)) (not-redirected? (current-output-port))) (newline (current-error-port)))) (set! *discrepancy-list* '()) (unless (and (not-redirected? (current-error-port)) (not-redirected? (current-output-port))) (let ([msglen (string-length msg)]) (format #t "Testing ~a ~a\n" msg (make-string (max 5 (- 70 msglen)) #\=))) (flush)) ) (define (test-log fmt . args) (display ";; ") (apply format #t fmt args) (newline) (flush)) (define (test-end . args) (let ([e (current-error-port)] [o (current-output-port)] [exit-on-failure (get-keyword :exit-on-failure args #f)]) (define (fmt . args) (if (and (not-redirected? e) (not-redirected? o)) (apply format/ss o args) (begin (apply format/ss e args) (apply format/ss o args)))) (if (null? *discrepancy-list*) (fmt "passed.\n") (begin (fmt "failed.\ndiscrepancies found. Errors are:\n") (for-each (lambda (r) (apply (lambda (report msg expect actual) (fmt "test ~a: expects ~s => got ~a\n" msg expect (with-output-to-string (cut report msg expect actual)))) r)) (reverse *discrepancy-list*)))) (flush) (when *test-record-file* (write-summary)) (set! *test-running* #f) (let ([num-failures (length *discrepancy-list*)]) (when (and (> num-failures 0) exit-on-failure) (exit (if (fixnum? exit-on-failure) exit-on-failure 1))) num-failures))) Read the test record file ( if there 's any ) , and exit with 1 (define (test-summary-check) (read-summary) (unless (and (zero? (vector-ref *test-counts* 2)) (zero? (vector-ref *test-counts* 3))) (exit 1))) (define (test-remove-files . paths) (define (remove-1 path) (if (and (file-is-directory? path) (not (eq? (slot-ref (sys-lstat path)'type) 'symlink))) (begin (for-each (^e (unless (member e '("." "..")) (remove-1 (string-append path "/" e)))) (sys-readdir path)) (sys-rmdir path)) (sys-unlink path))) (for-each remove-1 paths)) Create a fresh DIR , call THUNK ( without cd'ing ) , then remove DIR . (define (test-with-temporary-directory dir thunk) (test-remove-files dir) (sys-mkdir dir #o755) (dynamic-wind (^[] #f) thunk (^[] (test-remove-files dir))))
3b003f82e0eb95cd975dd0cd382292e71cb4c41df81b7630259d3abe37fe88e0
Liutos/Project-Euler
pro52.lisp
;;; This is really a ugly program (defun digit-chars (number) (if (< number 10) (list number) (cons (rem number 10) (digit-chars (/ (- number (rem number 10)) 10))))) (defun same-elts (lst1 lst2) (and (every (lambda (elt) (member elt lst2 :test #'=)) lst1) (every (lambda (elt) (member elt lst1 :test #'=)) lst2))) (defun digit-test (number) (let ((org (digit-chars number)) (2org (digit-chars (* 2 number))) (3org (digit-chars (* 3 number))) (4org (digit-chars (* 4 number))) (5org (digit-chars (* 5 number))) (6org (digit-chars (* 6 number)))) (every (lambda (lst) (same-elts org lst)) (list 2org 3org 4org 5org 6org)))) (defun pro52 () (labels ((rec (test-number) (if (> test-number 100000000) nil (if (digit-test test-number) test-number (rec (1+ test-number)))))) (rec 1)))
null
https://raw.githubusercontent.com/Liutos/Project-Euler/dd59940099ae37f971df1d74c4b7c78131fd5470/pro52.lisp
lisp
This is really a ugly program
(defun digit-chars (number) (if (< number 10) (list number) (cons (rem number 10) (digit-chars (/ (- number (rem number 10)) 10))))) (defun same-elts (lst1 lst2) (and (every (lambda (elt) (member elt lst2 :test #'=)) lst1) (every (lambda (elt) (member elt lst1 :test #'=)) lst2))) (defun digit-test (number) (let ((org (digit-chars number)) (2org (digit-chars (* 2 number))) (3org (digit-chars (* 3 number))) (4org (digit-chars (* 4 number))) (5org (digit-chars (* 5 number))) (6org (digit-chars (* 6 number)))) (every (lambda (lst) (same-elts org lst)) (list 2org 3org 4org 5org 6org)))) (defun pro52 () (labels ((rec (test-number) (if (> test-number 100000000) nil (if (digit-test test-number) test-number (rec (1+ test-number)))))) (rec 1)))
469049730f15de830231d3e743bdf3b29ba4343e68c0216828d39c7d3b1dca78
boxuk/trello
util.clj
(ns trello.test.util (:use trello.util midje.sweet)) (facts "about normalising requests" (normalize-http-request "foo/bar") => "foo/bar" (normalize-http-request "/foo/bar") => "foo/bar")
null
https://raw.githubusercontent.com/boxuk/trello/9d9ea29568374d8e026081a0849bfab96ed2001e/test/trello/test/util.clj
clojure
(ns trello.test.util (:use trello.util midje.sweet)) (facts "about normalising requests" (normalize-http-request "foo/bar") => "foo/bar" (normalize-http-request "/foo/bar") => "foo/bar")
27d84aad72812db92208a7429c41eb66b438799c03fdb8196f1d3151b04f4648
csabahruska/jhc-grin
Level.hs
# LANGUAGE TypeOperators , , DeriveFunctor , DeriveTraversable # module Ty.Level where import Util.Std newtype TyLevel = TyLevel Int deriving(Eq,Ord,Enum) -- inhabits constructor level(y ) = level(x ) + 1 data x ::: y = x ::: y deriving(Eq,Ord,Functor,Traversable,Foldable,Show) instance Show TyLevel where showsPrec _ (TyLevel 0) = ('V':) showsPrec _ (TyLevel 1) = ('T':) showsPrec _ (TyLevel 2) = ('*':) showsPrec _ (TyLevel 3) = ('*':) . ('*':) showsPrec _ (TyLevel n) | n > 0 && n <= 10 = f (n - 3) where f 0 s = s f n s = '□':f (n - 1) s showsPrec _ (TyLevel n) = showString "(TyLevel:" . shows n . showChar ')' -- tyLevelOf is possibly not total class HasTyLevel a where getTyLevel :: a -> Maybe TyLevel tyLevelOf :: a -> TyLevel getTyLevel x = Just (tyLevelOf x) tyLevelOf x = case getTyLevel x of Just t -> t Nothing -> error "tyLevelOf: Does not have a TyLevel" instance HasTyLevel TyLevel where tyLevelOf t = t we subtract one from the level of the type as the -- term itself may not carry a level with it. instance HasTyLevel b => HasTyLevel (a ::: b) where getTyLevel (_ ::: y) = fmap pred (getTyLevel y) termLevel = TyLevel 0 typeLevel = TyLevel 1 kindLevel = TyLevel 2
null
https://raw.githubusercontent.com/csabahruska/jhc-grin/30210f659167e357c1ccc52284cf719cfa90d306/src/Ty/Level.hs
haskell
inhabits constructor tyLevelOf is possibly not total term itself may not carry a level with it.
# LANGUAGE TypeOperators , , DeriveFunctor , DeriveTraversable # module Ty.Level where import Util.Std newtype TyLevel = TyLevel Int deriving(Eq,Ord,Enum) level(y ) = level(x ) + 1 data x ::: y = x ::: y deriving(Eq,Ord,Functor,Traversable,Foldable,Show) instance Show TyLevel where showsPrec _ (TyLevel 0) = ('V':) showsPrec _ (TyLevel 1) = ('T':) showsPrec _ (TyLevel 2) = ('*':) showsPrec _ (TyLevel 3) = ('*':) . ('*':) showsPrec _ (TyLevel n) | n > 0 && n <= 10 = f (n - 3) where f 0 s = s f n s = '□':f (n - 1) s showsPrec _ (TyLevel n) = showString "(TyLevel:" . shows n . showChar ')' class HasTyLevel a where getTyLevel :: a -> Maybe TyLevel tyLevelOf :: a -> TyLevel getTyLevel x = Just (tyLevelOf x) tyLevelOf x = case getTyLevel x of Just t -> t Nothing -> error "tyLevelOf: Does not have a TyLevel" instance HasTyLevel TyLevel where tyLevelOf t = t we subtract one from the level of the type as the instance HasTyLevel b => HasTyLevel (a ::: b) where getTyLevel (_ ::: y) = fmap pred (getTyLevel y) termLevel = TyLevel 0 typeLevel = TyLevel 1 kindLevel = TyLevel 2
b484c9d6ee89e5ab4fafae00aa6fde5002d1bb88319b661db8a1cac3f243d3a4
zwizwa/staapl
parse.rkt
#lang racket/base (require "../ns.rkt" (for-syntax racket/base racket/pretty "../ns-tx.rkt" "parse-tx.rkt")) (provide (all-defined-out)) An RPN transformer is a primitive taking arguments ;; W : code stack ;; D : dictionary (parser output) ;; K : parser continuation RPN PARSER ;; (rpn-parse (mk semantics ...) code ...) ;; The rpn syntax is currently implemented as a single transformer to ;; be able to get at the provided semantics macros through lexical ;; scope. (Previous implementation used compile-time paramters, which ;; became hard to understand.) ;; The parser can be parameterized as follows: * semantics for built - in in RPN language constructs . ;; * prefix parsers bound to local syntax ;; * prefix parsers found in the input stream (define-syntax (rpn-parse stx) (let* ((insp (current-code-inspector)) (recertify (lambda (new-stx) (syntax-recertify new-stx stx insp #f))) (args (stx-args stx))) (syntax-case (car args) () ((tx-dict ;; macro continuation <- dictionary output form (ns ...) ;; identifier namespace function ;; semantics macros for different forms immediate immediate-program program: init-dict) (let* ( 1 ) (lambda (id) (ns-prefixed #'(ns ...) id))) (->parse (lambda (it) (and (rpn-transformer? it) (rpn-transformer-tx it)))) (mapped-syntax-value (lambda (stx) ( printf " msv : ~a\n " ( ) ) (and (identifier? stx) (syntax-local-value (map-id stx) (lambda () #f))))) (qq ;; Build a quasiquoted immediate by traverseing an sexp ;; tree and performing proper unquotes. (lambda (unquote-tx) (lambda (atom-stx) (define (uq stx) (syntax-case stx (unquote) ((unquote atom) (unquote-tx #'atom)) ((car . cdr) #`(#,(uq #'car) . #,(uq #'cdr))) (atom #'atom))) #`(immediate (quasiquote #,(uq atom-stx)))))) (quoter All quoters take one arguement . (lambda (fn stx) (syntax-case stx () ((_ atom) (fn #'atom)) (other (raise-syntax-error #f "takes a single argument" stx))))) (quoted ;; Quote supports unquote as a way to introduce ;; arbitrary scheme values into s-expressions. (qq (lambda (atom) #`(unquote #,atom)))) (quasiquoted ;; Quasiquotation is intended to build datastructures ;; containing function objects, not to substitute ;; scheme values. It supports both identifiers and ;; compositions. (qq (lambda (atom) (syntax-case atom () ((e ...) #`(unquote (program: e ...))) (e #`(unquote #,(map-id #'e))))))) (unquoted ;; Unquote takes an expression from the surrounding ;; Scheme environment and uses it as a function. (lambda (atom-stx) #`(function #,atom-stx))) (primitive (lambda (element) (syntax-case element (quote quasiquote unquote) ((quote . e) (quoter quoted element)) ((quasiquote . e) (quoter quasiquoted element)) ((unquote . e) (quoter unquoted element)) ((e ...) #`(immediate-program (program: e ...))) (e (if (identifier? #'e) #`(function (ns ... e)) #`(immediate #,element)))))) (primitive-parse (lambda (element) (lambda (w d next) (next (w-cdr w) (d-compile (primitive element) d)))))) ;; * MAIN LOOP * ;; Read elements from the list of syntax elements, parse ;; and compile. When done, pass the dictionary to the ;; dictionary transformer macro. (recertify (let next ((w (cdr args)) (d (foldl d-compile (d-create) (syntax->list #'init-dict)))) (if (w-null? w) (let ((forms (d->forms d))) ;; (pretty-print (syntax->datum #`( #,@forms ))) #`(tx-dict #,@forms)) (let* ((element (w-car w)) (parse ;; Determine if the element represents a parser ;; extension. Either directly in the input ;; stream, possibly wrapped in a syntax object, ;; or bound to a transformer binding. (or (->parse element) (->parse (syntax->datum element)) (->parse (mapped-syntax-value element)) (primitive-parse element)))) ;; All parsers are invoked in tail position and need ;; to call 'next to continue looping with updated ;; state. (parse w d next)))))))))) Notes ;; ( 1 ) In order to access transformer bindings containing ;; rpn-transformer instances, compile time identifiers specified ;; by the form (namespace ... id) are _interpreted_ : the form ;; which is a valid macro form is _not_ expanded. This is to ;; prevend recursive macro expansion inside the rpn-parse macro, ;; which I've not been able to figure out how to do correctly. ;; (i.e. using 'local-expand ...). However, if this process fails ;; and no transformer binding is found, the identifier is replaced ;; with the form in the output of rpn-parse, which allows for ;; abstract identifier mapping.
null
https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/rpn/parse.rkt
racket
W : code stack D : dictionary (parser output) K : parser continuation (rpn-parse (mk semantics ...) code ...) The rpn syntax is currently implemented as a single transformer to be able to get at the provided semantics macros through lexical scope. (Previous implementation used compile-time paramters, which became hard to understand.) The parser can be parameterized as follows: * prefix parsers bound to local syntax * prefix parsers found in the input stream macro continuation <- dictionary output form identifier namespace semantics macros for different forms Build a quasiquoted immediate by traverseing an sexp tree and performing proper unquotes. Quote supports unquote as a way to introduce arbitrary scheme values into s-expressions. Quasiquotation is intended to build datastructures containing function objects, not to substitute scheme values. It supports both identifiers and compositions. Unquote takes an expression from the surrounding Scheme environment and uses it as a function. * MAIN LOOP * Read elements from the list of syntax elements, parse and compile. When done, pass the dictionary to the dictionary transformer macro. (pretty-print (syntax->datum #`( #,@forms ))) Determine if the element represents a parser extension. Either directly in the input stream, possibly wrapped in a syntax object, or bound to a transformer binding. All parsers are invoked in tail position and need to call 'next to continue looping with updated state. rpn-transformer instances, compile time identifiers specified by the form (namespace ... id) are _interpreted_ : the form which is a valid macro form is _not_ expanded. This is to prevend recursive macro expansion inside the rpn-parse macro, which I've not been able to figure out how to do correctly. (i.e. using 'local-expand ...). However, if this process fails and no transformer binding is found, the identifier is replaced with the form in the output of rpn-parse, which allows for abstract identifier mapping.
#lang racket/base (require "../ns.rkt" (for-syntax racket/base racket/pretty "../ns-tx.rkt" "parse-tx.rkt")) (provide (all-defined-out)) An RPN transformer is a primitive taking arguments RPN PARSER * semantics for built - in in RPN language constructs . (define-syntax (rpn-parse stx) (let* ((insp (current-code-inspector)) (recertify (lambda (new-stx) (syntax-recertify new-stx stx insp #f))) (args (stx-args stx))) (syntax-case (car args) () immediate immediate-program program: init-dict) (let* ( 1 ) (lambda (id) (ns-prefixed #'(ns ...) id))) (->parse (lambda (it) (and (rpn-transformer? it) (rpn-transformer-tx it)))) (mapped-syntax-value (lambda (stx) ( printf " msv : ~a\n " ( ) ) (and (identifier? stx) (syntax-local-value (map-id stx) (lambda () #f))))) (qq (lambda (unquote-tx) (lambda (atom-stx) (define (uq stx) (syntax-case stx (unquote) ((unquote atom) (unquote-tx #'atom)) ((car . cdr) #`(#,(uq #'car) . #,(uq #'cdr))) (atom #'atom))) #`(immediate (quasiquote #,(uq atom-stx)))))) (quoter All quoters take one arguement . (lambda (fn stx) (syntax-case stx () ((_ atom) (fn #'atom)) (other (raise-syntax-error #f "takes a single argument" stx))))) (quoted (qq (lambda (atom) #`(unquote #,atom)))) (quasiquoted (qq (lambda (atom) (syntax-case atom () ((e ...) #`(unquote (program: e ...))) (e #`(unquote #,(map-id #'e))))))) (unquoted (lambda (atom-stx) #`(function #,atom-stx))) (primitive (lambda (element) (syntax-case element (quote quasiquote unquote) ((quote . e) (quoter quoted element)) ((quasiquote . e) (quoter quasiquoted element)) ((unquote . e) (quoter unquoted element)) ((e ...) #`(immediate-program (program: e ...))) (e (if (identifier? #'e) #`(function (ns ... e)) #`(immediate #,element)))))) (primitive-parse (lambda (element) (lambda (w d next) (next (w-cdr w) (d-compile (primitive element) d)))))) (recertify (let next ((w (cdr args)) (d (foldl d-compile (d-create) (syntax->list #'init-dict)))) (if (w-null? w) (let ((forms (d->forms d))) #`(tx-dict #,@forms)) (let* ((element (w-car w)) (parse (or (->parse element) (->parse (syntax->datum element)) (->parse (mapped-syntax-value element)) (primitive-parse element)))) (parse w d next)))))))))) Notes ( 1 ) In order to access transformer bindings containing
fb19271aa2b6dcd0dba1e0c1a0b5d67546617f4ea959ff5177d4358d8b40a160
psilord/option-9
perform-collide.lisp
(in-package :option-9) #+option-9-debug (declaim (optimize (safety 3) (space 0) (speed 0) (debug 3))) ;; Primary method is both entities damage each other and one, both, or ;; neither may die. (defmethod perform-collide ((collider collidable) (collidee collidable)) (damage collider collidee)) (defmethod perform-collide :after ((collider shot) (collidee collidable)) Depending on the charge shoot 1 - 5 shots in random directions (when (> (charge-percentage collider) .25) TODO : Sadly , I would need the MOP to do this elegantly or use ;; an :append method for each class in the hierarchy to rebuild ;; the initialization list using the current values in the object. ;; This should assure I get a deep copy. (loop repeat (lerp 0 5 (charge-percentage collider) :truncp t) do (spawn 'sp-realize (instance-name collider) (world-basis collider) (game-context collider) :parent :universe :orphan-policy :destroy :extra-init (list ;; I should have a powerup such that the ;; charge of a shot can propogate to ;; here, causing a fission-type reaction ;; as each charged shot hits other stuff ;; too. This is a cool effect! : charge - percentage 1.0 :flyingp (flyingp collider) :local-basis (matrix-copy (local-basis collider)) :world-basis (matrix-copy (world-basis collider)) :roles (copy-seq (roles collider)) :dfv (vcopy (dfv collider)) :drv (vcopy (drv collider)) ;; and it goes in a random direction. :dr (pvec 0d0 0d0 (random (* 2d0 pi))) :dtv (vcopy (dtv collider)) :dv (vcopy (dv collider)) :rotatingp (rotatingp collider) :local-basis (mc (local-basis collider)) :previous-world-basis (mc (previous-world-basis collider)) :previous-world-basis-defined-p (previous-world-basis-defined-p collider)))))) ;; Here we handle the processing of a something hitting a ship which might ;; or might not have a shield. (defmethod perform-collide :around ((collider collidable) (collidee ship)) (let ((the-shield (payload (turret collidee :shield-port)))) (when the-shield (multiple-value-bind (absorbedp shield-is-used-up) (absorbs collider the-shield) (when absorbedp (die collider) (when shield-is-used-up (setf (payload (turret collidee :shield-port)) nil) (remove-from-scene (scene-man (game-context collidee)) the-shield)) ;; The :around method consumed the action, so don't continue. (return-from perform-collide nil))))) ;; If I get here, it means we didn't absorb the shot and must continue ;; processing. (call-next-method)) ;; The player gets the new weapon as denoted by the powerup, and the ;; powerup goes immediately stale. NOTE: If I change the collider type ;; to ship here, then ANY ship can get the powerup and its effects (as ;; long as I collide the enemies to the powerups in the main loop of ;; the game. However, I haven't coded the right geometries for the ;; ship shields or a good means to choose between them. So for now, ;; only the player can get powerups. It is actually an interesting game ;; mechanics decision if enemies can get powerups! (defmethod perform-collide ((collider player) (collidee powerup)) ;; A powerup can only be used ONCE (when (not (stalep collidee)) (mark-stale collidee) ;; process all turret powerups contained by this powerup. (dolist (pup (powerup-turrets collidee)) (destructuring-bind (port-name turret-name payload) pup ;; FIXME: Handle passive powerups or incremental powerups. ;; Use a CASE on port-name, maybe? Sounds kinda nasty, but it ;; might work for a bit. ;; For these forms, a port-name must always exist. (assert port-name) (let* ((the-turret (turret collider port-name)) ;; Try and figure out if the possibly generic name ;; this payload has should be specialized to an ;; instance appropriate for this collider. (payload (specialize-generic-instance-name (instance-name collider) payload)) ;; Note payload here would have been specialized! TODO : Ask the current payload , if there is one ;; AND IT IS THE SAME, then increase the power of ;; the payload (payload (cond ((and (payload the-turret) (eq (instance-name (payload the-turret)) payload)) ;; if we already have one and it matches what we ;; just picked up, then see if it wants to ;; increase its power, and return the same ;; payload. (increase-power (payload the-turret)) (payload the-turret)) (payload (let ((the-item (make-entity payload))) ;; Set up its initial location, which is ;; where the turret is on the collider! (at-location the-item the-turret) ;; jam it into the scene-tree. (insert-into-scene (scene-man (game-context collider)) the-item collider) ;; And get rid of the one currently there ;; from the scene tree and turret! (when (payload the-turret) (remove-from-scene (scene-man (game-context collider)) (payload the-turret)) (setf (payload the-turret) nil)) ;; here is the payload we wish to use. the-item)) (t ;; or use the one I already have. (payload the-turret)))) ;; Maybe I have a new turret to use too! (replacement-turret (if turret-name (let ((new-turret (make-entity turret-name))) ;; dump current turret. (remove-from-scene (scene-man (game-context collider)) the-turret) (setf (turret collider port-name) nil) ;; shove new one into scene tree. (insert-into-scene (scene-man (game-context collider)) new-turret collider) ;; and this is out replacement... new-turret) ;; or just use the old one. the-turret))) ;; Ensure the computed payload is assigned into the ;; computed turret. (setf (payload replacement-turret) payload) ;; These turrets use instance names as their payload. (setf (payload-instance-p replacement-turret) (if (keywordp payload) nil t)) ;; ensure the ship's port containes the computed turret (setf (turret collider port-name) replacement-turret)))) TODO , If the powerup affects payload charging in a turret , do ;; the effect here. (dolist (ceff (charging-effects collidee)) (destructuring-bind (port-name mode) ceff (let ((payload (payload (turret collider port-name)))) (when payload ;; When getting the same charging/decaying powerup, we make it ;; twice as fast in an increase-power kind of way. TODO: Consider ;; using an increase-charge or increase-decay verb. (cond ((eq mode :charging) (setf (chargeablep payload) t) (if (null (charge-time payload)) (setf (charge-time payload) (in-usecs 2.0)) (setf (charge-time payload) (/ (charge-time payload) 2.0)))) ((eq mode :decaying) (setf (decayablep payload) t) (if (null (decay-time payload)) (setf (decay-time payload) (in-usecs 2.0)) (setf (decay-time payload) (/ (decay-time payload) 2.0))))))))) ;; If the powerup has a health level, apply it to the player. (incf (hit-points collider) (powerup-health-level collidee)) (when (> (hit-points collider) (max-hit-points collider)) (setf (hit-points collider) (max-hit-points collider))) )) ;; In general, the field damages the thing it touches. (defmethod perform-collide ((f tesla-field) (ent collidable)) First , we cause damage (damage f ent) ;; Then, we emit some sparks during the collision (maphash #'(lambda (eid path-contact) (with-accessors ((pc-path-ids path-ids)) path-contact (dolist (path-index pc-path-ids) (with-accessors ((fp-steps steps) (fp-path path)) (svref (paths f) path-index) (unless (or (equal eid :no-collision) (zerop fp-steps)) (let ((loc (svref fp-path (1- fp-steps)))) (when (zerop (random 10)) (spawn 'sp-sparks :insts/sparks (pvec (x loc) (y loc) (z loc)) *game* :num-sparks 1 :ttl-max (in-usecs .075) :velocity-factor .2d0)))))))) (entity-contacts f))) ;; field mines follow the field back to the generating ship and are ;; NOT damaged by the field, therefore they are a new primary method. (defmethod perform-collide ((f tesla-field) (ent field-mine)) (let ((pc (contacts f ent)) (mx 0d0) (my 0d0) (mz 0d0)) ;; add up the inverse direction vectors from the participating ;; field paths. We're going to be following the field lines ;; back... (dolist (path-index (path-ids pc)) (with-accessors ((fp-steps steps) (fp-path path)) (svref (paths f) path-index) ;; Sum the inverted direction vectors found at the last field ;; path step. XXX It turns out when the last step was computed, it ;; is often past the object (since it was in the collision radius). This messes up the computation of this vector so I use the second ;; to the last step, which should be ok in accordance to the algorithm ;; which produced the path. (when (> fp-steps 1) (let ((loc (svref fp-path (1- (1- fp-steps))))) (incf mx (* (dx loc) -1d0)) (incf my (* (dy loc) -1d0)) (incf mz (* (dz loc) -1d0)))))) ;; Normalize the vector, set some fraction of it to be the ;; direction and speed the mine should translate towards the ship. (let ((invdir (pvec))) (with-pvec-accessors (inv invdir) (multiple-value-bind (nvx nvy) (normalize-vector mx my) (setf invx (* nvx .3d0) invy (* nvy .3d0) invz 0d0))) ;; Set it as a hard translation to move the field-mine towards ;; the player while following the field lines. (setf (dtv ent) invdir))))
null
https://raw.githubusercontent.com/psilord/option-9/44d96cbc5543ee2acbdcf45d300207ef175462bc/perform-collide.lisp
lisp
Primary method is both entities damage each other and one, both, or neither may die. an :append method for each class in the hierarchy to rebuild the initialization list using the current values in the object. This should assure I get a deep copy. I should have a powerup such that the charge of a shot can propogate to here, causing a fission-type reaction as each charged shot hits other stuff too. This is a cool effect! and it goes in a random direction. Here we handle the processing of a something hitting a ship which might or might not have a shield. The :around method consumed the action, so don't continue. If I get here, it means we didn't absorb the shot and must continue processing. The player gets the new weapon as denoted by the powerup, and the powerup goes immediately stale. NOTE: If I change the collider type to ship here, then ANY ship can get the powerup and its effects (as long as I collide the enemies to the powerups in the main loop of the game. However, I haven't coded the right geometries for the ship shields or a good means to choose between them. So for now, only the player can get powerups. It is actually an interesting game mechanics decision if enemies can get powerups! A powerup can only be used ONCE process all turret powerups contained by this powerup. FIXME: Handle passive powerups or incremental powerups. Use a CASE on port-name, maybe? Sounds kinda nasty, but it might work for a bit. For these forms, a port-name must always exist. Try and figure out if the possibly generic name this payload has should be specialized to an instance appropriate for this collider. Note payload here would have been specialized! AND IT IS THE SAME, then increase the power of the payload if we already have one and it matches what we just picked up, then see if it wants to increase its power, and return the same payload. Set up its initial location, which is where the turret is on the collider! jam it into the scene-tree. And get rid of the one currently there from the scene tree and turret! here is the payload we wish to use. or use the one I already have. Maybe I have a new turret to use too! dump current turret. shove new one into scene tree. and this is out replacement... or just use the old one. Ensure the computed payload is assigned into the computed turret. These turrets use instance names as their payload. ensure the ship's port containes the computed turret the effect here. When getting the same charging/decaying powerup, we make it twice as fast in an increase-power kind of way. TODO: Consider using an increase-charge or increase-decay verb. If the powerup has a health level, apply it to the player. In general, the field damages the thing it touches. Then, we emit some sparks during the collision field mines follow the field back to the generating ship and are NOT damaged by the field, therefore they are a new primary method. add up the inverse direction vectors from the participating field paths. We're going to be following the field lines back... Sum the inverted direction vectors found at the last field path step. XXX It turns out when the last step was computed, it is often past the object (since it was in the collision radius). to the last step, which should be ok in accordance to the algorithm which produced the path. Normalize the vector, set some fraction of it to be the direction and speed the mine should translate towards the ship. Set it as a hard translation to move the field-mine towards the player while following the field lines.
(in-package :option-9) #+option-9-debug (declaim (optimize (safety 3) (space 0) (speed 0) (debug 3))) (defmethod perform-collide ((collider collidable) (collidee collidable)) (damage collider collidee)) (defmethod perform-collide :after ((collider shot) (collidee collidable)) Depending on the charge shoot 1 - 5 shots in random directions (when (> (charge-percentage collider) .25) TODO : Sadly , I would need the MOP to do this elegantly or use (loop repeat (lerp 0 5 (charge-percentage collider) :truncp t) do (spawn 'sp-realize (instance-name collider) (world-basis collider) (game-context collider) :parent :universe :orphan-policy :destroy :extra-init (list : charge - percentage 1.0 :flyingp (flyingp collider) :local-basis (matrix-copy (local-basis collider)) :world-basis (matrix-copy (world-basis collider)) :roles (copy-seq (roles collider)) :dfv (vcopy (dfv collider)) :drv (vcopy (drv collider)) :dr (pvec 0d0 0d0 (random (* 2d0 pi))) :dtv (vcopy (dtv collider)) :dv (vcopy (dv collider)) :rotatingp (rotatingp collider) :local-basis (mc (local-basis collider)) :previous-world-basis (mc (previous-world-basis collider)) :previous-world-basis-defined-p (previous-world-basis-defined-p collider)))))) (defmethod perform-collide :around ((collider collidable) (collidee ship)) (let ((the-shield (payload (turret collidee :shield-port)))) (when the-shield (multiple-value-bind (absorbedp shield-is-used-up) (absorbs collider the-shield) (when absorbedp (die collider) (when shield-is-used-up (setf (payload (turret collidee :shield-port)) nil) (remove-from-scene (scene-man (game-context collidee)) the-shield)) (return-from perform-collide nil))))) (call-next-method)) (defmethod perform-collide ((collider player) (collidee powerup)) (when (not (stalep collidee)) (mark-stale collidee) (dolist (pup (powerup-turrets collidee)) (destructuring-bind (port-name turret-name payload) pup (assert port-name) (let* ((the-turret (turret collider port-name)) (payload (specialize-generic-instance-name (instance-name collider) payload)) TODO : Ask the current payload , if there is one (payload (cond ((and (payload the-turret) (eq (instance-name (payload the-turret)) payload)) (increase-power (payload the-turret)) (payload the-turret)) (payload (let ((the-item (make-entity payload))) (at-location the-item the-turret) (insert-into-scene (scene-man (game-context collider)) the-item collider) (when (payload the-turret) (remove-from-scene (scene-man (game-context collider)) (payload the-turret)) (setf (payload the-turret) nil)) the-item)) (t (payload the-turret)))) (replacement-turret (if turret-name (let ((new-turret (make-entity turret-name))) (remove-from-scene (scene-man (game-context collider)) the-turret) (setf (turret collider port-name) nil) (insert-into-scene (scene-man (game-context collider)) new-turret collider) new-turret) the-turret))) (setf (payload replacement-turret) payload) (setf (payload-instance-p replacement-turret) (if (keywordp payload) nil t)) (setf (turret collider port-name) replacement-turret)))) TODO , If the powerup affects payload charging in a turret , do (dolist (ceff (charging-effects collidee)) (destructuring-bind (port-name mode) ceff (let ((payload (payload (turret collider port-name)))) (when payload (cond ((eq mode :charging) (setf (chargeablep payload) t) (if (null (charge-time payload)) (setf (charge-time payload) (in-usecs 2.0)) (setf (charge-time payload) (/ (charge-time payload) 2.0)))) ((eq mode :decaying) (setf (decayablep payload) t) (if (null (decay-time payload)) (setf (decay-time payload) (in-usecs 2.0)) (setf (decay-time payload) (/ (decay-time payload) 2.0))))))))) (incf (hit-points collider) (powerup-health-level collidee)) (when (> (hit-points collider) (max-hit-points collider)) (setf (hit-points collider) (max-hit-points collider))) )) (defmethod perform-collide ((f tesla-field) (ent collidable)) First , we cause damage (damage f ent) (maphash #'(lambda (eid path-contact) (with-accessors ((pc-path-ids path-ids)) path-contact (dolist (path-index pc-path-ids) (with-accessors ((fp-steps steps) (fp-path path)) (svref (paths f) path-index) (unless (or (equal eid :no-collision) (zerop fp-steps)) (let ((loc (svref fp-path (1- fp-steps)))) (when (zerop (random 10)) (spawn 'sp-sparks :insts/sparks (pvec (x loc) (y loc) (z loc)) *game* :num-sparks 1 :ttl-max (in-usecs .075) :velocity-factor .2d0)))))))) (entity-contacts f))) (defmethod perform-collide ((f tesla-field) (ent field-mine)) (let ((pc (contacts f ent)) (mx 0d0) (my 0d0) (mz 0d0)) (dolist (path-index (path-ids pc)) (with-accessors ((fp-steps steps) (fp-path path)) (svref (paths f) path-index) This messes up the computation of this vector so I use the second (when (> fp-steps 1) (let ((loc (svref fp-path (1- (1- fp-steps))))) (incf mx (* (dx loc) -1d0)) (incf my (* (dy loc) -1d0)) (incf mz (* (dz loc) -1d0)))))) (let ((invdir (pvec))) (with-pvec-accessors (inv invdir) (multiple-value-bind (nvx nvy) (normalize-vector mx my) (setf invx (* nvx .3d0) invy (* nvy .3d0) invz 0d0))) (setf (dtv ent) invdir))))
0ea8f7d4ca3f11fbc9dc2cb3b0875d3ce99894bd357efb2a6b0e4424a04eae93
racket/gui
collapsed-snipclass-helpers.rkt
#lang racket/base (require racket/gui/base racket/class) (provide make-sexp-snipclass%) (define (make-sexp-snipclass% sexp-snip%) (class snip-class% (define/override (read in) (define left-bracket (integer->char (bytes-ref (send in get-bytes) 0))) (define right-bracket (integer->char (bytes-ref (send in get-bytes) 0))) (define snip-count (send in get-exact)) (define saved-snips (for/list ([in-range snip-count]) (define classname (bytes->string/utf-8 (send in get-bytes))) (define snipclass (send (get-the-snip-class-list) find classname)) (send snipclass read in))) (new sexp-snip% [left-bracket left-bracket] [right-bracket right-bracket] [saved-snips saved-snips])) (super-new)))
null
https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/framework/private/collapsed-snipclass-helpers.rkt
racket
#lang racket/base (require racket/gui/base racket/class) (provide make-sexp-snipclass%) (define (make-sexp-snipclass% sexp-snip%) (class snip-class% (define/override (read in) (define left-bracket (integer->char (bytes-ref (send in get-bytes) 0))) (define right-bracket (integer->char (bytes-ref (send in get-bytes) 0))) (define snip-count (send in get-exact)) (define saved-snips (for/list ([in-range snip-count]) (define classname (bytes->string/utf-8 (send in get-bytes))) (define snipclass (send (get-the-snip-class-list) find classname)) (send snipclass read in))) (new sexp-snip% [left-bracket left-bracket] [right-bracket right-bracket] [saved-snips saved-snips])) (super-new)))
52129914e6e07ec3fcbbd5700cf4936d9f5dcf84b551bf283c864f26a6050d0e
ocaml/ocaml
lambda.ml
(**************************************************************************) (* *) (* 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. *) (* *) (**************************************************************************) open Misc open Asttypes type compile_time_constant = | Big_endian | Word_size | Int_size | Max_wosize | Ostype_unix | Ostype_win32 | Ostype_cygwin | Backend_type type immediate_or_pointer = | Immediate | Pointer type initialization_or_assignment = | Assignment | Heap_initialization | Root_initialization type is_safe = | Safe | Unsafe type primitive = | Pbytes_to_string | Pbytes_of_string | Pignore (* Globals *) | Pgetglobal of Ident.t | Psetglobal of Ident.t (* Operations on heap blocks *) | Pmakeblock of int * mutable_flag * block_shape | Pfield of int * immediate_or_pointer * mutable_flag | Pfield_computed | Psetfield of int * immediate_or_pointer * initialization_or_assignment | Psetfield_computed of immediate_or_pointer * initialization_or_assignment | Pfloatfield of int | Psetfloatfield of int * initialization_or_assignment | Pduprecord of Types.record_representation * int (* Context switches *) | Prunstack | Pperform | Presume | Preperform (* External call *) | Pccall of Primitive.description (* Exceptions *) | Praise of raise_kind Boolean operations | Psequand | Psequor | Pnot Integer operations | Pnegint | Paddint | Psubint | Pmulint | Pdivint of is_safe | Pmodint of is_safe | Pandint | Porint | Pxorint | Plslint | Plsrint | Pasrint | Pintcomp of integer_comparison | Pcompare_ints | Pcompare_floats | Pcompare_bints of boxed_integer | Poffsetint of int | Poffsetref of int (* Float operations *) | Pintoffloat | Pfloatofint | Pnegfloat | Pabsfloat | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat | Pfloatcomp of float_comparison (* String operations *) | Pstringlength | Pstringrefu | Pstringrefs | Pbyteslength | Pbytesrefu | Pbytessetu | Pbytesrefs | Pbytessets (* Array operations *) | Pmakearray of array_kind * mutable_flag | Pduparray of array_kind * mutable_flag | Parraylength of array_kind | Parrayrefu of array_kind | Parraysetu of array_kind | Parrayrefs of array_kind | Parraysets of array_kind (* Test if the argument is a block or an immediate integer *) | Pisint (* Test if the (integer) argument is outside an interval *) | Pisout Operations on boxed integers ( Nativeint.t , Int32.t , Int64.t ) | Pbintofint of boxed_integer | Pintofbint of boxed_integer | Pcvtbint of boxed_integer (*source*) * boxed_integer (*destination*) | Pnegbint of boxed_integer | Paddbint of boxed_integer | Psubbint of boxed_integer | Pmulbint of boxed_integer | Pdivbint of { size : boxed_integer; is_safe : is_safe } | Pmodbint of { size : boxed_integer; is_safe : is_safe } | Pandbint of boxed_integer | Porbint of boxed_integer | Pxorbint of boxed_integer | Plslbint of boxed_integer | Plsrbint of boxed_integer | Pasrbint of boxed_integer | Pbintcomp of boxed_integer * integer_comparison (* Operations on Bigarrays: (unsafe, #dimensions, kind, layout) *) | Pbigarrayref of bool * int * bigarray_kind * bigarray_layout | Pbigarrayset of bool * int * bigarray_kind * bigarray_layout (* size of the nth dimension of a Bigarray *) | Pbigarraydim of int load / set 16,32,64 bits from a string : ( unsafe ) | Pstring_load_16 of bool | Pstring_load_32 of bool | Pstring_load_64 of bool | Pbytes_load_16 of bool | Pbytes_load_32 of bool | Pbytes_load_64 of bool | Pbytes_set_16 of bool | Pbytes_set_32 of bool | Pbytes_set_64 of bool load / set 16,32,64 bits from a ( char , int8_unsigned_elt , c_layout ) Bigarray . Array1.t : ( unsafe ) (char, int8_unsigned_elt, c_layout) Bigarray.Array1.t : (unsafe) *) | Pbigstring_load_16 of bool | Pbigstring_load_32 of bool | Pbigstring_load_64 of bool | Pbigstring_set_16 of bool | Pbigstring_set_32 of bool | Pbigstring_set_64 of bool (* Compile time constants *) | Pctconst of compile_time_constant (* byte swap *) | Pbswap16 | Pbbswap of boxed_integer Integer to external pointer | Pint_as_pointer (* Atomic operations *) | Patomic_load of {immediate_or_pointer : immediate_or_pointer} | Patomic_exchange | Patomic_cas | Patomic_fetch_add (* Inhibition of optimisation *) | Popaque (* Fetching domain-local state *) | Pdls_get and integer_comparison = Ceq | Cne | Clt | Cgt | Cle | Cge and float_comparison = CFeq | CFneq | CFlt | CFnlt | CFgt | CFngt | CFle | CFnle | CFge | CFnge and value_kind = Pgenval | Pfloatval | Pboxedintval of boxed_integer | Pintval and block_shape = value_kind list option and array_kind = Pgenarray | Paddrarray | Pintarray | Pfloatarray and boxed_integer = Primitive.boxed_integer = Pnativeint | Pint32 | Pint64 and bigarray_kind = Pbigarray_unknown | Pbigarray_float32 | Pbigarray_float64 | Pbigarray_sint8 | Pbigarray_uint8 | Pbigarray_sint16 | Pbigarray_uint16 | Pbigarray_int32 | Pbigarray_int64 | Pbigarray_caml_int | Pbigarray_native_int | Pbigarray_complex32 | Pbigarray_complex64 and bigarray_layout = Pbigarray_unknown_layout | Pbigarray_c_layout | Pbigarray_fortran_layout and raise_kind = | Raise_regular | Raise_reraise | Raise_notrace let equal_boxed_integer = Primitive.equal_boxed_integer let equal_primitive = (* Should be implemented like [equal_value_kind] of [equal_boxed_integer], i.e. by matching over the various constructors but the type has more than 100 constructors... *) (=) let equal_value_kind x y = match x, y with | Pgenval, Pgenval -> true | Pfloatval, Pfloatval -> true | Pboxedintval bi1, Pboxedintval bi2 -> equal_boxed_integer bi1 bi2 | Pintval, Pintval -> true | (Pgenval | Pfloatval | Pboxedintval _ | Pintval), _ -> false type structured_constant = Const_base of constant | Const_block of int * structured_constant list | Const_float_array of string list | Const_immstring of string type tailcall_attribute = | Tailcall_expectation of bool (* [@tailcall] and [@tailcall true] have [true], [@tailcall false] has [false] *) | Default_tailcall (* no [@tailcall] attribute *) type inline_attribute = [ @inline ] or [ @inline always ] [ @inline never ] | Hint_inline (* [@inlined hint] attribute *) [ @unroll x ] no [ @inline ] attribute let equal_inline_attribute x y = match x, y with | Always_inline, Always_inline | Never_inline, Never_inline | Hint_inline, Hint_inline | Default_inline, Default_inline -> true | Unroll u, Unroll v -> u = v | (Always_inline | Never_inline | Hint_inline | Unroll _ | Default_inline), _ -> false type specialise_attribute = | Always_specialise (* [@specialise] or [@specialise always] *) | Never_specialise (* [@specialise never] *) | Default_specialise (* no [@specialise] attribute *) let equal_specialise_attribute x y = match x, y with | Always_specialise, Always_specialise | Never_specialise, Never_specialise | Default_specialise, Default_specialise -> true | (Always_specialise | Never_specialise | Default_specialise), _ -> false type local_attribute = | Always_local (* [@local] or [@local always] *) | Never_local (* [@local never] *) | Default_local (* [@local maybe] or no [@local] attribute *) type poll_attribute = [ @poll error ] no [ @poll ] attribute type function_kind = Curried | Tupled type let_kind = Strict | Alias | StrictOpt type meth_kind = Self | Public | Cached let equal_meth_kind x y = match x, y with | Self, Self -> true | Public, Public -> true | Cached, Cached -> true | (Self | Public | Cached), _ -> false type shared_code = (int * int) list type function_attribute = { inline : inline_attribute; specialise : specialise_attribute; local: local_attribute; poll: poll_attribute; is_a_functor: bool; stub: bool; tmc_candidate: bool; } type scoped_location = Debuginfo.Scoped_location.t type lambda = Lvar of Ident.t | Lmutvar of Ident.t | Lconst of structured_constant | Lapply of lambda_apply | Lfunction of lfunction | Llet of let_kind * value_kind * Ident.t * lambda * lambda | Lmutlet of value_kind * Ident.t * lambda * lambda | Lletrec of (Ident.t * lambda) list * lambda | Lprim of primitive * lambda list * scoped_location | Lswitch of lambda * lambda_switch * scoped_location | Lstringswitch of lambda * (string * lambda) list * lambda option * scoped_location | Lstaticraise of int * lambda list | Lstaticcatch of lambda * (int * (Ident.t * value_kind) list) * lambda | Ltrywith of lambda * Ident.t * lambda | Lifthenelse of lambda * lambda * lambda | Lsequence of lambda * lambda | Lwhile of lambda * lambda | Lfor of Ident.t * lambda * lambda * direction_flag * lambda | Lassign of Ident.t * lambda | Lsend of meth_kind * lambda * lambda * lambda list * scoped_location | Levent of lambda * lambda_event | Lifused of Ident.t * lambda and lfunction = { kind: function_kind; params: (Ident.t * value_kind) list; return: value_kind; body: lambda; specified with [ @inline ] attribute loc: scoped_location; } and lambda_apply = { ap_func : lambda; ap_args : lambda list; ap_loc : scoped_location; ap_tailcall : tailcall_attribute; ap_inlined : inline_attribute; ap_specialised : specialise_attribute; } and lambda_switch = { sw_numconsts: int; sw_consts: (int * lambda) list; sw_numblocks: int; sw_blocks: (int * lambda) list; sw_failaction : lambda option} and lambda_event = { lev_loc: scoped_location; lev_kind: lambda_event_kind; lev_repr: int ref option; lev_env: Env.t } and lambda_event_kind = Lev_before | Lev_after of Types.type_expr | Lev_function | Lev_pseudo | Lev_module_definition of Ident.t type program = { module_ident : Ident.t; main_module_block_size : int; required_globals : Ident.Set.t; code : lambda } let const_int n = Const_base (Const_int n) let const_unit = const_int 0 let max_arity () = if !Clflags.native_code then 126 else max_int 126 = 127 ( the maximal number of parameters supported in C-- ) - 1 ( the hidden parameter containing the environment ) - 1 (the hidden parameter containing the environment) *) let lfunction ~kind ~params ~return ~body ~attr ~loc = assert (List.length params <= max_arity ()); Lfunction { kind; params; return; body; attr; loc } let lambda_unit = Lconst const_unit let default_function_attribute = { inline = Default_inline; specialise = Default_specialise; local = Default_local; poll = Default_poll; is_a_functor = false; stub = false; tmc_candidate = false; } let default_stub_attribute = { default_function_attribute with stub = true } (* Build sharing keys *) (* Those keys are later compared with Stdlib.compare. For that reason, they should not include cycles. *) let max_raw = 32 let make_key e = let exception Not_simple in let count = ref 0 (* Used for controlling size *) and make_key = Ident.make_key_generator () in (* make_key is used for normalizing let-bound variables *) let rec tr_rec env e = incr count ; if !count > max_raw then raise Not_simple ; (* Too big ! *) match e with | Lvar id | Lmutvar id -> begin try Ident.find_same id env with Not_found -> e end | Lconst (Const_base (Const_string _)) -> (* Mutable constants are not shared *) raise Not_simple | Lconst _ -> e | Lapply ap -> Lapply {ap with ap_func = tr_rec env ap.ap_func; ap_args = tr_recs env ap.ap_args; ap_loc = Loc_unknown} | Llet (Alias,_k,x,ex,e) -> (* Ignore aliases -> substitute *) let ex = tr_rec env ex in tr_rec (Ident.add x ex env) e | Llet ((Strict | StrictOpt),_k,x,ex,Lvar v) when Ident.same v x -> tr_rec env ex | Llet (str,k,x,ex,e) -> (* Because of side effects, keep other lets with normalized names *) let ex = tr_rec env ex in let y = make_key x in Llet (str,k,y,ex,tr_rec (Ident.add x (Lvar y) env) e) | Lmutlet (k,x,ex,e) -> let ex = tr_rec env ex in let y = make_key x in Lmutlet (k,y,ex,tr_rec (Ident.add x (Lmutvar y) env) e) | Lprim (p,es,_) -> Lprim (p,tr_recs env es, Loc_unknown) | Lswitch (e,sw,loc) -> Lswitch (tr_rec env e,tr_sw env sw,loc) | Lstringswitch (e,sw,d,_) -> Lstringswitch (tr_rec env e, List.map (fun (s,e) -> s,tr_rec env e) sw, tr_opt env d, Loc_unknown) | Lstaticraise (i,es) -> Lstaticraise (i,tr_recs env es) | Lstaticcatch (e1,xs,e2) -> Lstaticcatch (tr_rec env e1,xs,tr_rec env e2) | Ltrywith (e1,x,e2) -> Ltrywith (tr_rec env e1,x,tr_rec env e2) | Lifthenelse (cond,ifso,ifnot) -> Lifthenelse (tr_rec env cond,tr_rec env ifso,tr_rec env ifnot) | Lsequence (e1,e2) -> Lsequence (tr_rec env e1,tr_rec env e2) | Lassign (x,e) -> Lassign (x,tr_rec env e) | Lsend (m,e1,e2,es,_loc) -> Lsend (m,tr_rec env e1,tr_rec env e2,tr_recs env es,Loc_unknown) | Lifused (id,e) -> Lifused (id,tr_rec env e) | Lletrec _|Lfunction _ | Lfor _ | Lwhile _ Beware : ( PR#6412 ) the event argument to Levent may include cyclic structure of type Type.typexpr may include cyclic structure of type Type.typexpr *) | Levent _ -> raise Not_simple and tr_recs env es = List.map (tr_rec env) es and tr_sw env sw = { sw with sw_consts = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_consts ; sw_blocks = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_blocks ; sw_failaction = tr_opt env sw.sw_failaction ; } and tr_opt env = function | None -> None | Some e -> Some (tr_rec env e) in try Some (tr_rec Ident.empty e) with Not_simple -> None (***************) let name_lambda strict arg fn = match arg with Lvar id -> fn id | _ -> let id = Ident.create_local "let" in Llet(strict, Pgenval, id, arg, fn id) let name_lambda_list args fn = let rec name_list names = function [] -> fn (List.rev names) | (Lvar _ as arg) :: rem -> name_list (arg :: names) rem | arg :: rem -> let id = Ident.create_local "let" in Llet(Strict, Pgenval, id, arg, name_list (Lvar id :: names) rem) in name_list [] args let iter_opt f = function | None -> () | Some e -> f e let shallow_iter ~tail ~non_tail:f = function Lvar _ | Lmutvar _ | Lconst _ -> () | Lapply{ap_func = fn; ap_args = args} -> f fn; List.iter f args | Lfunction{body} -> f body | Llet(_, _k, _id, arg, body) | Lmutlet(_k, _id, arg, body) -> f arg; tail body | Lletrec(decl, body) -> tail body; List.iter (fun (_id, exp) -> f exp) decl | Lprim (Psequand, [l1; l2], _) | Lprim (Psequor, [l1; l2], _) -> f l1; tail l2 | Lprim(_p, args, _loc) -> List.iter f args | Lswitch(arg, sw,_) -> f arg; List.iter (fun (_key, case) -> tail case) sw.sw_consts; List.iter (fun (_key, case) -> tail case) sw.sw_blocks; iter_opt tail sw.sw_failaction | Lstringswitch (arg,cases,default,_) -> f arg ; List.iter (fun (_,act) -> tail act) cases ; iter_opt tail default | Lstaticraise (_,args) -> List.iter f args | Lstaticcatch(e1, _, e2) -> tail e1; tail e2 | Ltrywith(e1, _, e2) -> f e1; tail e2 | Lifthenelse(e1, e2, e3) -> f e1; tail e2; tail e3 | Lsequence(e1, e2) -> f e1; tail e2 | Lwhile(e1, e2) -> f e1; f e2 | Lfor(_v, e1, e2, _dir, e3) -> f e1; f e2; f e3 | Lassign(_, e) -> f e | Lsend (_k, met, obj, args, _) -> List.iter f (met::obj::args) | Levent (e, _evt) -> tail e | Lifused (_v, e) -> tail e let iter_head_constructor f l = shallow_iter ~tail:f ~non_tail:f l let rec free_variables = function | Lvar id | Lmutvar id -> Ident.Set.singleton id | Lconst _ -> Ident.Set.empty | Lapply{ap_func = fn; ap_args = args} -> free_variables_list (free_variables fn) args | Lfunction{body; params} -> Ident.Set.diff (free_variables body) (Ident.Set.of_list (List.map fst params)) | Llet(_, _k, id, arg, body) | Lmutlet(_k, id, arg, body) -> Ident.Set.union (free_variables arg) (Ident.Set.remove id (free_variables body)) | Lletrec(decl, body) -> let set = free_variables_list (free_variables body) (List.map snd decl) in Ident.Set.diff set (Ident.Set.of_list (List.map fst decl)) | Lprim(_p, args, _loc) -> free_variables_list Ident.Set.empty args | Lswitch(arg, sw,_) -> let set = free_variables_list (free_variables_list (free_variables arg) (List.map snd sw.sw_consts)) (List.map snd sw.sw_blocks) in begin match sw.sw_failaction with | None -> set | Some failaction -> Ident.Set.union set (free_variables failaction) end | Lstringswitch (arg,cases,default,_) -> let set = free_variables_list (free_variables arg) (List.map snd cases) in begin match default with | None -> set | Some default -> Ident.Set.union set (free_variables default) end | Lstaticraise (_,args) -> free_variables_list Ident.Set.empty args | Lstaticcatch(body, (_, params), handler) -> Ident.Set.union (Ident.Set.diff (free_variables handler) (Ident.Set.of_list (List.map fst params))) (free_variables body) | Ltrywith(body, param, handler) -> Ident.Set.union (Ident.Set.remove param (free_variables handler)) (free_variables body) | Lifthenelse(e1, e2, e3) -> Ident.Set.union (Ident.Set.union (free_variables e1) (free_variables e2)) (free_variables e3) | Lsequence(e1, e2) -> Ident.Set.union (free_variables e1) (free_variables e2) | Lwhile(e1, e2) -> Ident.Set.union (free_variables e1) (free_variables e2) | Lfor(v, lo, hi, _dir, body) -> let set = Ident.Set.union (free_variables lo) (free_variables hi) in Ident.Set.union set (Ident.Set.remove v (free_variables body)) | Lassign(id, e) -> Ident.Set.add id (free_variables e) | Lsend (_k, met, obj, args, _) -> free_variables_list (Ident.Set.union (free_variables met) (free_variables obj)) args | Levent (lam, _evt) -> free_variables lam | Lifused (_v, e) -> (* Shouldn't v be considered a free variable ? *) free_variables e and free_variables_list set exprs = List.fold_left (fun set expr -> Ident.Set.union (free_variables expr) set) set exprs (* Check if an action has a "when" guard *) let raise_count = ref 0 let next_raise_count () = incr raise_count ; !raise_count (* Anticipated staticraise, for guards *) let staticfail = Lstaticraise (0,[]) let rec is_guarded = function | Lifthenelse(_cond, _body, Lstaticraise (0,[])) -> true | Llet(_str, _k, _id, _lam, body) -> is_guarded body | Levent(lam, _ev) -> is_guarded lam | _ -> false let rec patch_guarded patch = function | Lifthenelse (cond, body, Lstaticraise (0,[])) -> Lifthenelse (cond, body, patch) | Llet(str, k, id, lam, body) -> Llet (str, k, id, lam, patch_guarded patch body) | Levent(lam, ev) -> Levent (patch_guarded patch lam, ev) | _ -> fatal_error "Lambda.patch_guarded" (* Translate an access path *) let rec transl_address loc = function | Env.Aident id -> if Ident.global id then Lprim(Pgetglobal id, [], loc) else Lvar id | Env.Adot(addr, pos) -> Lprim(Pfield(pos, Pointer, Immutable), [transl_address loc addr], loc) let transl_path find loc env path = match find path env with | exception Not_found -> fatal_error ("Cannot find address for: " ^ (Path.name path)) | addr -> transl_address loc addr (* Translation of identifiers *) let transl_module_path loc env path = transl_path Env.find_module_address loc env path let transl_value_path loc env path = transl_path Env.find_value_address loc env path let transl_extension_path loc env path = transl_path Env.find_constructor_address loc env path let transl_class_path loc env path = transl_path Env.find_class_address loc env path let transl_prim mod_name name = let pers = Ident.create_persistent mod_name in let env = Env.add_persistent_structure pers Env.empty in let lid = Longident.Ldot (Longident.Lident mod_name, name) in match Env.find_value_by_name lid env with | path, _ -> transl_value_path Loc_unknown env path | exception Not_found -> fatal_error ("Primitive " ^ name ^ " not found.") (* Compile a sequence of expressions *) let rec make_sequence fn = function [] -> lambda_unit | [x] -> fn x | x::rem -> let lam = fn x in Lsequence(lam, make_sequence fn rem) (* Apply a substitution to a lambda-term. Assumes that the image of the substitution is out of reach of the bound variables of the lambda-term (no capture). *) let subst update_env ?(freshen_bound_variables = false) s input_lam = [ s ] contains a partial substitution for the free variables of the input term [ input_lam ] . During our traversal of the term we maintain a second environment [ l ] with all the bound variables of [ input_lam ] in the current scope , mapped to either themselves or freshened versions of themselves when [ freshen_bound_variables ] is set . input term [input_lam]. During our traversal of the term we maintain a second environment [l] with all the bound variables of [input_lam] in the current scope, mapped to either themselves or freshened versions of themselves when [freshen_bound_variables] is set. *) let bind id l = let id' = if not freshen_bound_variables then id else Ident.rename id in id', Ident.Map.add id id' l in let bind_many ids l = List.fold_right (fun (id, rhs) (ids', l) -> let id', l = bind id l in ((id', rhs) :: ids' , l) ) ids ([], l) in let rec subst s l lam = match lam with | Lvar id as lam -> begin match Ident.Map.find id l with | id' -> Lvar id' | exception Not_found -> (* note: as this point we know [id] is not a bound variable of the input term, otherwise it would belong to [l]; it is a free variable of the input term. *) begin try Ident.Map.find id s with Not_found -> lam end end | Lmutvar id as lam -> begin match Ident.Map.find id l with | id' -> Lmutvar id' | exception Not_found -> Note : a mutable [ i d ] should not appear in [ s ] . Keeping the behavior of Lvar case for now . Keeping the behavior of Lvar case for now. *) begin try Ident.Map.find id s with Not_found -> lam end end | Lconst _ as l -> l | Lapply ap -> Lapply{ap with ap_func = subst s l ap.ap_func; ap_args = subst_list s l ap.ap_args} | Lfunction lf -> let params, l' = bind_many lf.params l in Lfunction {lf with params; body = subst s l' lf.body} | Llet(str, k, id, arg, body) -> let id, l' = bind id l in Llet(str, k, id, subst s l arg, subst s l' body) | Lmutlet(k, id, arg, body) -> let id, l' = bind id l in Lmutlet(k, id, subst s l arg, subst s l' body) | Lletrec(decl, body) -> let decl, l' = bind_many decl l in Lletrec(List.map (subst_decl s l') decl, subst s l' body) | Lprim(p, args, loc) -> Lprim(p, subst_list s l args, loc) | Lswitch(arg, sw, loc) -> Lswitch(subst s l arg, {sw with sw_consts = List.map (subst_case s l) sw.sw_consts; sw_blocks = List.map (subst_case s l) sw.sw_blocks; sw_failaction = subst_opt s l sw.sw_failaction; }, loc) | Lstringswitch (arg,cases,default,loc) -> Lstringswitch (subst s l arg, List.map (subst_strcase s l) cases, subst_opt s l default, loc) | Lstaticraise (i,args) -> Lstaticraise (i, subst_list s l args) | Lstaticcatch(body, (id, params), handler) -> let params, l' = bind_many params l in Lstaticcatch(subst s l body, (id, params), subst s l' handler) | Ltrywith(body, exn, handler) -> let exn, l' = bind exn l in Ltrywith(subst s l body, exn, subst s l' handler) | Lifthenelse(e1, e2, e3) -> Lifthenelse(subst s l e1, subst s l e2, subst s l e3) | Lsequence(e1, e2) -> Lsequence(subst s l e1, subst s l e2) | Lwhile(e1, e2) -> Lwhile(subst s l e1, subst s l e2) | Lfor(v, lo, hi, dir, body) -> let v, l' = bind v l in Lfor(v, subst s l lo, subst s l hi, dir, subst s l' body) | Lassign(id, e) -> assert (not (Ident.Map.mem id s)); let id = try Ident.Map.find id l with Not_found -> id in Lassign(id, subst s l e) | Lsend (k, met, obj, args, loc) -> Lsend (k, subst s l met, subst s l obj, subst_list s l args, loc) | Levent (lam, evt) -> let old_env = evt.lev_env in let env_updates = let find_in_old id = Env.find_value (Path.Pident id) old_env in let rebind id id' new_env = match find_in_old id with | exception Not_found -> new_env | vd -> Env.add_value id' vd new_env in let update_free id new_env = match find_in_old id with | exception Not_found -> new_env | vd -> update_env id vd new_env in Ident.Map.merge (fun id bound free -> match bound, free with | Some id', _ -> if Ident.equal id id' then None else Some (rebind id id') | None, Some _ -> Some (update_free id) | None, None -> None ) l s in let new_env = Ident.Map.fold (fun _id update env -> update env) env_updates old_env in Levent (subst s l lam, { evt with lev_env = new_env }) | Lifused (id, e) -> let id = try Ident.Map.find id l with Not_found -> id in Lifused (id, subst s l e) and subst_list s l li = List.map (subst s l) li and subst_decl s l (id, exp) = (id, subst s l exp) and subst_case s l (key, case) = (key, subst s l case) and subst_strcase s l (key, case) = (key, subst s l case) and subst_opt s l = function | None -> None | Some e -> Some (subst s l e) in subst s Ident.Map.empty input_lam let rename idmap lam = let update_env oldid vd env = let newid = Ident.Map.find oldid idmap in Env.add_value newid vd env in let s = Ident.Map.map (fun new_id -> Lvar new_id) idmap in subst update_env s lam let duplicate lam = subst (fun _ _ env -> env) ~freshen_bound_variables:true Ident.Map.empty lam let shallow_map f = function | Lvar _ | Lmutvar _ | Lconst _ as lam -> lam | Lapply { ap_func; ap_args; ap_loc; ap_tailcall; ap_inlined; ap_specialised } -> Lapply { ap_func = f ap_func; ap_args = List.map f ap_args; ap_loc; ap_tailcall; ap_inlined; ap_specialised; } | Lfunction { kind; params; return; body; attr; loc; } -> Lfunction { kind; params; return; body = f body; attr; loc; } | Llet (str, k, v, e1, e2) -> Llet (str, k, v, f e1, f e2) | Lmutlet (k, v, e1, e2) -> Lmutlet (k, v, f e1, f e2) | Lletrec (idel, e2) -> Lletrec (List.map (fun (v, e) -> (v, f e)) idel, f e2) | Lprim (p, el, loc) -> Lprim (p, List.map f el, loc) | Lswitch (e, sw, loc) -> Lswitch (f e, { sw_numconsts = sw.sw_numconsts; sw_consts = List.map (fun (n, e) -> (n, f e)) sw.sw_consts; sw_numblocks = sw.sw_numblocks; sw_blocks = List.map (fun (n, e) -> (n, f e)) sw.sw_blocks; sw_failaction = Option.map f sw.sw_failaction; }, loc) | Lstringswitch (e, sw, default, loc) -> Lstringswitch ( f e, List.map (fun (s, e) -> (s, f e)) sw, Option.map f default, loc) | Lstaticraise (i, args) -> Lstaticraise (i, List.map f args) | Lstaticcatch (body, id, handler) -> Lstaticcatch (f body, id, f handler) | Ltrywith (e1, v, e2) -> Ltrywith (f e1, v, f e2) | Lifthenelse (e1, e2, e3) -> Lifthenelse (f e1, f e2, f e3) | Lsequence (e1, e2) -> Lsequence (f e1, f e2) | Lwhile (e1, e2) -> Lwhile (f e1, f e2) | Lfor (v, e1, e2, dir, e3) -> Lfor (v, f e1, f e2, dir, f e3) | Lassign (v, e) -> Lassign (v, f e) | Lsend (k, m, o, el, loc) -> Lsend (k, f m, f o, List.map f el, loc) | Levent (l, ev) -> Levent (f l, ev) | Lifused (v, e) -> Lifused (v, f e) let map f = let rec g lam = f (shallow_map g lam) in g (* To let-bind expressions to variables *) let bind_with_value_kind str (var, kind) exp body = match exp with Lvar var' when Ident.same var var' -> body | _ -> Llet(str, kind, var, exp, body) let bind str var exp body = bind_with_value_kind str (var, Pgenval) exp body let negate_integer_comparison = function | Ceq -> Cne | Cne -> Ceq | Clt -> Cge | Cle -> Cgt | Cgt -> Cle | Cge -> Clt let swap_integer_comparison = function | Ceq -> Ceq | Cne -> Cne | Clt -> Cgt | Cle -> Cge | Cgt -> Clt | Cge -> Cle let negate_float_comparison = function | CFeq -> CFneq | CFneq -> CFeq | CFlt -> CFnlt | CFnlt -> CFlt | CFgt -> CFngt | CFngt -> CFgt | CFle -> CFnle | CFnle -> CFle | CFge -> CFnge | CFnge -> CFge let swap_float_comparison = function | CFeq -> CFeq | CFneq -> CFneq | CFlt -> CFgt | CFnlt -> CFngt | CFle -> CFge | CFnle -> CFnge | CFgt -> CFlt | CFngt -> CFnlt | CFge -> CFle | CFnge -> CFnle let raise_kind = function | Raise_regular -> "raise" | Raise_reraise -> "reraise" | Raise_notrace -> "raise_notrace" let merge_inline_attributes attr1 attr2 = match attr1, attr2 with | Default_inline, _ -> Some attr2 | _, Default_inline -> Some attr1 | _, _ -> if attr1 = attr2 then Some attr1 else None let function_is_curried func = match func.kind with | Curried -> true | Tupled -> false let find_exact_application kind ~arity args = match kind with | Curried -> if arity <> List.length args then None else Some args | Tupled -> begin match args with | [Lprim(Pmakeblock _, tupled_args, _)] -> if arity <> List.length tupled_args then None else Some tupled_args | [Lconst(Const_block (_, const_args))] -> if arity <> List.length const_args then None else Some (List.map (fun cst -> Lconst cst) const_args) | _ -> None end let reset () = raise_count := 0
null
https://raw.githubusercontent.com/ocaml/ocaml/ce1a0a50266a9a0dc770967e12e076db055395c1/lambda/lambda.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Globals Operations on heap blocks Context switches External call Exceptions Float operations String operations Array operations Test if the argument is a block or an immediate integer Test if the (integer) argument is outside an interval source destination Operations on Bigarrays: (unsafe, #dimensions, kind, layout) size of the nth dimension of a Bigarray Compile time constants byte swap Atomic operations Inhibition of optimisation Fetching domain-local state Should be implemented like [equal_value_kind] of [equal_boxed_integer], i.e. by matching over the various constructors but the type has more than 100 constructors... [@tailcall] and [@tailcall true] have [true], [@tailcall false] has [false] no [@tailcall] attribute [@inlined hint] attribute [@specialise] or [@specialise always] [@specialise never] no [@specialise] attribute [@local] or [@local always] [@local never] [@local maybe] or no [@local] attribute Build sharing keys Those keys are later compared with Stdlib.compare. For that reason, they should not include cycles. Used for controlling size make_key is used for normalizing let-bound variables Too big ! Mutable constants are not shared Ignore aliases -> substitute Because of side effects, keep other lets with normalized names ************* Shouldn't v be considered a free variable ? Check if an action has a "when" guard Anticipated staticraise, for guards Translate an access path Translation of identifiers Compile a sequence of expressions Apply a substitution to a lambda-term. Assumes that the image of the substitution is out of reach of the bound variables of the lambda-term (no capture). note: as this point we know [id] is not a bound variable of the input term, otherwise it would belong to [l]; it is a free variable of the input term. To let-bind expressions to variables
, 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 Misc open Asttypes type compile_time_constant = | Big_endian | Word_size | Int_size | Max_wosize | Ostype_unix | Ostype_win32 | Ostype_cygwin | Backend_type type immediate_or_pointer = | Immediate | Pointer type initialization_or_assignment = | Assignment | Heap_initialization | Root_initialization type is_safe = | Safe | Unsafe type primitive = | Pbytes_to_string | Pbytes_of_string | Pignore | Pgetglobal of Ident.t | Psetglobal of Ident.t | Pmakeblock of int * mutable_flag * block_shape | Pfield of int * immediate_or_pointer * mutable_flag | Pfield_computed | Psetfield of int * immediate_or_pointer * initialization_or_assignment | Psetfield_computed of immediate_or_pointer * initialization_or_assignment | Pfloatfield of int | Psetfloatfield of int * initialization_or_assignment | Pduprecord of Types.record_representation * int | Prunstack | Pperform | Presume | Preperform | Pccall of Primitive.description | Praise of raise_kind Boolean operations | Psequand | Psequor | Pnot Integer operations | Pnegint | Paddint | Psubint | Pmulint | Pdivint of is_safe | Pmodint of is_safe | Pandint | Porint | Pxorint | Plslint | Plsrint | Pasrint | Pintcomp of integer_comparison | Pcompare_ints | Pcompare_floats | Pcompare_bints of boxed_integer | Poffsetint of int | Poffsetref of int | Pintoffloat | Pfloatofint | Pnegfloat | Pabsfloat | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat | Pfloatcomp of float_comparison | Pstringlength | Pstringrefu | Pstringrefs | Pbyteslength | Pbytesrefu | Pbytessetu | Pbytesrefs | Pbytessets | Pmakearray of array_kind * mutable_flag | Pduparray of array_kind * mutable_flag | Parraylength of array_kind | Parrayrefu of array_kind | Parraysetu of array_kind | Parrayrefs of array_kind | Parraysets of array_kind | Pisint | Pisout Operations on boxed integers ( Nativeint.t , Int32.t , Int64.t ) | Pbintofint of boxed_integer | Pintofbint of boxed_integer | Pnegbint of boxed_integer | Paddbint of boxed_integer | Psubbint of boxed_integer | Pmulbint of boxed_integer | Pdivbint of { size : boxed_integer; is_safe : is_safe } | Pmodbint of { size : boxed_integer; is_safe : is_safe } | Pandbint of boxed_integer | Porbint of boxed_integer | Pxorbint of boxed_integer | Plslbint of boxed_integer | Plsrbint of boxed_integer | Pasrbint of boxed_integer | Pbintcomp of boxed_integer * integer_comparison | Pbigarrayref of bool * int * bigarray_kind * bigarray_layout | Pbigarrayset of bool * int * bigarray_kind * bigarray_layout | Pbigarraydim of int load / set 16,32,64 bits from a string : ( unsafe ) | Pstring_load_16 of bool | Pstring_load_32 of bool | Pstring_load_64 of bool | Pbytes_load_16 of bool | Pbytes_load_32 of bool | Pbytes_load_64 of bool | Pbytes_set_16 of bool | Pbytes_set_32 of bool | Pbytes_set_64 of bool load / set 16,32,64 bits from a ( char , int8_unsigned_elt , c_layout ) Bigarray . Array1.t : ( unsafe ) (char, int8_unsigned_elt, c_layout) Bigarray.Array1.t : (unsafe) *) | Pbigstring_load_16 of bool | Pbigstring_load_32 of bool | Pbigstring_load_64 of bool | Pbigstring_set_16 of bool | Pbigstring_set_32 of bool | Pbigstring_set_64 of bool | Pctconst of compile_time_constant | Pbswap16 | Pbbswap of boxed_integer Integer to external pointer | Pint_as_pointer | Patomic_load of {immediate_or_pointer : immediate_or_pointer} | Patomic_exchange | Patomic_cas | Patomic_fetch_add | Popaque | Pdls_get and integer_comparison = Ceq | Cne | Clt | Cgt | Cle | Cge and float_comparison = CFeq | CFneq | CFlt | CFnlt | CFgt | CFngt | CFle | CFnle | CFge | CFnge and value_kind = Pgenval | Pfloatval | Pboxedintval of boxed_integer | Pintval and block_shape = value_kind list option and array_kind = Pgenarray | Paddrarray | Pintarray | Pfloatarray and boxed_integer = Primitive.boxed_integer = Pnativeint | Pint32 | Pint64 and bigarray_kind = Pbigarray_unknown | Pbigarray_float32 | Pbigarray_float64 | Pbigarray_sint8 | Pbigarray_uint8 | Pbigarray_sint16 | Pbigarray_uint16 | Pbigarray_int32 | Pbigarray_int64 | Pbigarray_caml_int | Pbigarray_native_int | Pbigarray_complex32 | Pbigarray_complex64 and bigarray_layout = Pbigarray_unknown_layout | Pbigarray_c_layout | Pbigarray_fortran_layout and raise_kind = | Raise_regular | Raise_reraise | Raise_notrace let equal_boxed_integer = Primitive.equal_boxed_integer let equal_primitive = (=) let equal_value_kind x y = match x, y with | Pgenval, Pgenval -> true | Pfloatval, Pfloatval -> true | Pboxedintval bi1, Pboxedintval bi2 -> equal_boxed_integer bi1 bi2 | Pintval, Pintval -> true | (Pgenval | Pfloatval | Pboxedintval _ | Pintval), _ -> false type structured_constant = Const_base of constant | Const_block of int * structured_constant list | Const_float_array of string list | Const_immstring of string type tailcall_attribute = | Tailcall_expectation of bool type inline_attribute = [ @inline ] or [ @inline always ] [ @inline never ] [ @unroll x ] no [ @inline ] attribute let equal_inline_attribute x y = match x, y with | Always_inline, Always_inline | Never_inline, Never_inline | Hint_inline, Hint_inline | Default_inline, Default_inline -> true | Unroll u, Unroll v -> u = v | (Always_inline | Never_inline | Hint_inline | Unroll _ | Default_inline), _ -> false type specialise_attribute = let equal_specialise_attribute x y = match x, y with | Always_specialise, Always_specialise | Never_specialise, Never_specialise | Default_specialise, Default_specialise -> true | (Always_specialise | Never_specialise | Default_specialise), _ -> false type local_attribute = type poll_attribute = [ @poll error ] no [ @poll ] attribute type function_kind = Curried | Tupled type let_kind = Strict | Alias | StrictOpt type meth_kind = Self | Public | Cached let equal_meth_kind x y = match x, y with | Self, Self -> true | Public, Public -> true | Cached, Cached -> true | (Self | Public | Cached), _ -> false type shared_code = (int * int) list type function_attribute = { inline : inline_attribute; specialise : specialise_attribute; local: local_attribute; poll: poll_attribute; is_a_functor: bool; stub: bool; tmc_candidate: bool; } type scoped_location = Debuginfo.Scoped_location.t type lambda = Lvar of Ident.t | Lmutvar of Ident.t | Lconst of structured_constant | Lapply of lambda_apply | Lfunction of lfunction | Llet of let_kind * value_kind * Ident.t * lambda * lambda | Lmutlet of value_kind * Ident.t * lambda * lambda | Lletrec of (Ident.t * lambda) list * lambda | Lprim of primitive * lambda list * scoped_location | Lswitch of lambda * lambda_switch * scoped_location | Lstringswitch of lambda * (string * lambda) list * lambda option * scoped_location | Lstaticraise of int * lambda list | Lstaticcatch of lambda * (int * (Ident.t * value_kind) list) * lambda | Ltrywith of lambda * Ident.t * lambda | Lifthenelse of lambda * lambda * lambda | Lsequence of lambda * lambda | Lwhile of lambda * lambda | Lfor of Ident.t * lambda * lambda * direction_flag * lambda | Lassign of Ident.t * lambda | Lsend of meth_kind * lambda * lambda * lambda list * scoped_location | Levent of lambda * lambda_event | Lifused of Ident.t * lambda and lfunction = { kind: function_kind; params: (Ident.t * value_kind) list; return: value_kind; body: lambda; specified with [ @inline ] attribute loc: scoped_location; } and lambda_apply = { ap_func : lambda; ap_args : lambda list; ap_loc : scoped_location; ap_tailcall : tailcall_attribute; ap_inlined : inline_attribute; ap_specialised : specialise_attribute; } and lambda_switch = { sw_numconsts: int; sw_consts: (int * lambda) list; sw_numblocks: int; sw_blocks: (int * lambda) list; sw_failaction : lambda option} and lambda_event = { lev_loc: scoped_location; lev_kind: lambda_event_kind; lev_repr: int ref option; lev_env: Env.t } and lambda_event_kind = Lev_before | Lev_after of Types.type_expr | Lev_function | Lev_pseudo | Lev_module_definition of Ident.t type program = { module_ident : Ident.t; main_module_block_size : int; required_globals : Ident.Set.t; code : lambda } let const_int n = Const_base (Const_int n) let const_unit = const_int 0 let max_arity () = if !Clflags.native_code then 126 else max_int 126 = 127 ( the maximal number of parameters supported in C-- ) - 1 ( the hidden parameter containing the environment ) - 1 (the hidden parameter containing the environment) *) let lfunction ~kind ~params ~return ~body ~attr ~loc = assert (List.length params <= max_arity ()); Lfunction { kind; params; return; body; attr; loc } let lambda_unit = Lconst const_unit let default_function_attribute = { inline = Default_inline; specialise = Default_specialise; local = Default_local; poll = Default_poll; is_a_functor = false; stub = false; tmc_candidate = false; } let default_stub_attribute = { default_function_attribute with stub = true } let max_raw = 32 let make_key e = let exception Not_simple in and make_key = Ident.make_key_generator () in let rec tr_rec env e = incr count ; match e with | Lvar id | Lmutvar id -> begin try Ident.find_same id env with Not_found -> e end | Lconst (Const_base (Const_string _)) -> raise Not_simple | Lconst _ -> e | Lapply ap -> Lapply {ap with ap_func = tr_rec env ap.ap_func; ap_args = tr_recs env ap.ap_args; ap_loc = Loc_unknown} let ex = tr_rec env ex in tr_rec (Ident.add x ex env) e | Llet ((Strict | StrictOpt),_k,x,ex,Lvar v) when Ident.same v x -> tr_rec env ex | Llet (str,k,x,ex,e) -> let ex = tr_rec env ex in let y = make_key x in Llet (str,k,y,ex,tr_rec (Ident.add x (Lvar y) env) e) | Lmutlet (k,x,ex,e) -> let ex = tr_rec env ex in let y = make_key x in Lmutlet (k,y,ex,tr_rec (Ident.add x (Lmutvar y) env) e) | Lprim (p,es,_) -> Lprim (p,tr_recs env es, Loc_unknown) | Lswitch (e,sw,loc) -> Lswitch (tr_rec env e,tr_sw env sw,loc) | Lstringswitch (e,sw,d,_) -> Lstringswitch (tr_rec env e, List.map (fun (s,e) -> s,tr_rec env e) sw, tr_opt env d, Loc_unknown) | Lstaticraise (i,es) -> Lstaticraise (i,tr_recs env es) | Lstaticcatch (e1,xs,e2) -> Lstaticcatch (tr_rec env e1,xs,tr_rec env e2) | Ltrywith (e1,x,e2) -> Ltrywith (tr_rec env e1,x,tr_rec env e2) | Lifthenelse (cond,ifso,ifnot) -> Lifthenelse (tr_rec env cond,tr_rec env ifso,tr_rec env ifnot) | Lsequence (e1,e2) -> Lsequence (tr_rec env e1,tr_rec env e2) | Lassign (x,e) -> Lassign (x,tr_rec env e) | Lsend (m,e1,e2,es,_loc) -> Lsend (m,tr_rec env e1,tr_rec env e2,tr_recs env es,Loc_unknown) | Lifused (id,e) -> Lifused (id,tr_rec env e) | Lletrec _|Lfunction _ | Lfor _ | Lwhile _ Beware : ( PR#6412 ) the event argument to Levent may include cyclic structure of type Type.typexpr may include cyclic structure of type Type.typexpr *) | Levent _ -> raise Not_simple and tr_recs env es = List.map (tr_rec env) es and tr_sw env sw = { sw with sw_consts = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_consts ; sw_blocks = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_blocks ; sw_failaction = tr_opt env sw.sw_failaction ; } and tr_opt env = function | None -> None | Some e -> Some (tr_rec env e) in try Some (tr_rec Ident.empty e) with Not_simple -> None let name_lambda strict arg fn = match arg with Lvar id -> fn id | _ -> let id = Ident.create_local "let" in Llet(strict, Pgenval, id, arg, fn id) let name_lambda_list args fn = let rec name_list names = function [] -> fn (List.rev names) | (Lvar _ as arg) :: rem -> name_list (arg :: names) rem | arg :: rem -> let id = Ident.create_local "let" in Llet(Strict, Pgenval, id, arg, name_list (Lvar id :: names) rem) in name_list [] args let iter_opt f = function | None -> () | Some e -> f e let shallow_iter ~tail ~non_tail:f = function Lvar _ | Lmutvar _ | Lconst _ -> () | Lapply{ap_func = fn; ap_args = args} -> f fn; List.iter f args | Lfunction{body} -> f body | Llet(_, _k, _id, arg, body) | Lmutlet(_k, _id, arg, body) -> f arg; tail body | Lletrec(decl, body) -> tail body; List.iter (fun (_id, exp) -> f exp) decl | Lprim (Psequand, [l1; l2], _) | Lprim (Psequor, [l1; l2], _) -> f l1; tail l2 | Lprim(_p, args, _loc) -> List.iter f args | Lswitch(arg, sw,_) -> f arg; List.iter (fun (_key, case) -> tail case) sw.sw_consts; List.iter (fun (_key, case) -> tail case) sw.sw_blocks; iter_opt tail sw.sw_failaction | Lstringswitch (arg,cases,default,_) -> f arg ; List.iter (fun (_,act) -> tail act) cases ; iter_opt tail default | Lstaticraise (_,args) -> List.iter f args | Lstaticcatch(e1, _, e2) -> tail e1; tail e2 | Ltrywith(e1, _, e2) -> f e1; tail e2 | Lifthenelse(e1, e2, e3) -> f e1; tail e2; tail e3 | Lsequence(e1, e2) -> f e1; tail e2 | Lwhile(e1, e2) -> f e1; f e2 | Lfor(_v, e1, e2, _dir, e3) -> f e1; f e2; f e3 | Lassign(_, e) -> f e | Lsend (_k, met, obj, args, _) -> List.iter f (met::obj::args) | Levent (e, _evt) -> tail e | Lifused (_v, e) -> tail e let iter_head_constructor f l = shallow_iter ~tail:f ~non_tail:f l let rec free_variables = function | Lvar id | Lmutvar id -> Ident.Set.singleton id | Lconst _ -> Ident.Set.empty | Lapply{ap_func = fn; ap_args = args} -> free_variables_list (free_variables fn) args | Lfunction{body; params} -> Ident.Set.diff (free_variables body) (Ident.Set.of_list (List.map fst params)) | Llet(_, _k, id, arg, body) | Lmutlet(_k, id, arg, body) -> Ident.Set.union (free_variables arg) (Ident.Set.remove id (free_variables body)) | Lletrec(decl, body) -> let set = free_variables_list (free_variables body) (List.map snd decl) in Ident.Set.diff set (Ident.Set.of_list (List.map fst decl)) | Lprim(_p, args, _loc) -> free_variables_list Ident.Set.empty args | Lswitch(arg, sw,_) -> let set = free_variables_list (free_variables_list (free_variables arg) (List.map snd sw.sw_consts)) (List.map snd sw.sw_blocks) in begin match sw.sw_failaction with | None -> set | Some failaction -> Ident.Set.union set (free_variables failaction) end | Lstringswitch (arg,cases,default,_) -> let set = free_variables_list (free_variables arg) (List.map snd cases) in begin match default with | None -> set | Some default -> Ident.Set.union set (free_variables default) end | Lstaticraise (_,args) -> free_variables_list Ident.Set.empty args | Lstaticcatch(body, (_, params), handler) -> Ident.Set.union (Ident.Set.diff (free_variables handler) (Ident.Set.of_list (List.map fst params))) (free_variables body) | Ltrywith(body, param, handler) -> Ident.Set.union (Ident.Set.remove param (free_variables handler)) (free_variables body) | Lifthenelse(e1, e2, e3) -> Ident.Set.union (Ident.Set.union (free_variables e1) (free_variables e2)) (free_variables e3) | Lsequence(e1, e2) -> Ident.Set.union (free_variables e1) (free_variables e2) | Lwhile(e1, e2) -> Ident.Set.union (free_variables e1) (free_variables e2) | Lfor(v, lo, hi, _dir, body) -> let set = Ident.Set.union (free_variables lo) (free_variables hi) in Ident.Set.union set (Ident.Set.remove v (free_variables body)) | Lassign(id, e) -> Ident.Set.add id (free_variables e) | Lsend (_k, met, obj, args, _) -> free_variables_list (Ident.Set.union (free_variables met) (free_variables obj)) args | Levent (lam, _evt) -> free_variables lam | Lifused (_v, e) -> free_variables e and free_variables_list set exprs = List.fold_left (fun set expr -> Ident.Set.union (free_variables expr) set) set exprs let raise_count = ref 0 let next_raise_count () = incr raise_count ; !raise_count let staticfail = Lstaticraise (0,[]) let rec is_guarded = function | Lifthenelse(_cond, _body, Lstaticraise (0,[])) -> true | Llet(_str, _k, _id, _lam, body) -> is_guarded body | Levent(lam, _ev) -> is_guarded lam | _ -> false let rec patch_guarded patch = function | Lifthenelse (cond, body, Lstaticraise (0,[])) -> Lifthenelse (cond, body, patch) | Llet(str, k, id, lam, body) -> Llet (str, k, id, lam, patch_guarded patch body) | Levent(lam, ev) -> Levent (patch_guarded patch lam, ev) | _ -> fatal_error "Lambda.patch_guarded" let rec transl_address loc = function | Env.Aident id -> if Ident.global id then Lprim(Pgetglobal id, [], loc) else Lvar id | Env.Adot(addr, pos) -> Lprim(Pfield(pos, Pointer, Immutable), [transl_address loc addr], loc) let transl_path find loc env path = match find path env with | exception Not_found -> fatal_error ("Cannot find address for: " ^ (Path.name path)) | addr -> transl_address loc addr let transl_module_path loc env path = transl_path Env.find_module_address loc env path let transl_value_path loc env path = transl_path Env.find_value_address loc env path let transl_extension_path loc env path = transl_path Env.find_constructor_address loc env path let transl_class_path loc env path = transl_path Env.find_class_address loc env path let transl_prim mod_name name = let pers = Ident.create_persistent mod_name in let env = Env.add_persistent_structure pers Env.empty in let lid = Longident.Ldot (Longident.Lident mod_name, name) in match Env.find_value_by_name lid env with | path, _ -> transl_value_path Loc_unknown env path | exception Not_found -> fatal_error ("Primitive " ^ name ^ " not found.") let rec make_sequence fn = function [] -> lambda_unit | [x] -> fn x | x::rem -> let lam = fn x in Lsequence(lam, make_sequence fn rem) let subst update_env ?(freshen_bound_variables = false) s input_lam = [ s ] contains a partial substitution for the free variables of the input term [ input_lam ] . During our traversal of the term we maintain a second environment [ l ] with all the bound variables of [ input_lam ] in the current scope , mapped to either themselves or freshened versions of themselves when [ freshen_bound_variables ] is set . input term [input_lam]. During our traversal of the term we maintain a second environment [l] with all the bound variables of [input_lam] in the current scope, mapped to either themselves or freshened versions of themselves when [freshen_bound_variables] is set. *) let bind id l = let id' = if not freshen_bound_variables then id else Ident.rename id in id', Ident.Map.add id id' l in let bind_many ids l = List.fold_right (fun (id, rhs) (ids', l) -> let id', l = bind id l in ((id', rhs) :: ids' , l) ) ids ([], l) in let rec subst s l lam = match lam with | Lvar id as lam -> begin match Ident.Map.find id l with | id' -> Lvar id' | exception Not_found -> begin try Ident.Map.find id s with Not_found -> lam end end | Lmutvar id as lam -> begin match Ident.Map.find id l with | id' -> Lmutvar id' | exception Not_found -> Note : a mutable [ i d ] should not appear in [ s ] . Keeping the behavior of Lvar case for now . Keeping the behavior of Lvar case for now. *) begin try Ident.Map.find id s with Not_found -> lam end end | Lconst _ as l -> l | Lapply ap -> Lapply{ap with ap_func = subst s l ap.ap_func; ap_args = subst_list s l ap.ap_args} | Lfunction lf -> let params, l' = bind_many lf.params l in Lfunction {lf with params; body = subst s l' lf.body} | Llet(str, k, id, arg, body) -> let id, l' = bind id l in Llet(str, k, id, subst s l arg, subst s l' body) | Lmutlet(k, id, arg, body) -> let id, l' = bind id l in Lmutlet(k, id, subst s l arg, subst s l' body) | Lletrec(decl, body) -> let decl, l' = bind_many decl l in Lletrec(List.map (subst_decl s l') decl, subst s l' body) | Lprim(p, args, loc) -> Lprim(p, subst_list s l args, loc) | Lswitch(arg, sw, loc) -> Lswitch(subst s l arg, {sw with sw_consts = List.map (subst_case s l) sw.sw_consts; sw_blocks = List.map (subst_case s l) sw.sw_blocks; sw_failaction = subst_opt s l sw.sw_failaction; }, loc) | Lstringswitch (arg,cases,default,loc) -> Lstringswitch (subst s l arg, List.map (subst_strcase s l) cases, subst_opt s l default, loc) | Lstaticraise (i,args) -> Lstaticraise (i, subst_list s l args) | Lstaticcatch(body, (id, params), handler) -> let params, l' = bind_many params l in Lstaticcatch(subst s l body, (id, params), subst s l' handler) | Ltrywith(body, exn, handler) -> let exn, l' = bind exn l in Ltrywith(subst s l body, exn, subst s l' handler) | Lifthenelse(e1, e2, e3) -> Lifthenelse(subst s l e1, subst s l e2, subst s l e3) | Lsequence(e1, e2) -> Lsequence(subst s l e1, subst s l e2) | Lwhile(e1, e2) -> Lwhile(subst s l e1, subst s l e2) | Lfor(v, lo, hi, dir, body) -> let v, l' = bind v l in Lfor(v, subst s l lo, subst s l hi, dir, subst s l' body) | Lassign(id, e) -> assert (not (Ident.Map.mem id s)); let id = try Ident.Map.find id l with Not_found -> id in Lassign(id, subst s l e) | Lsend (k, met, obj, args, loc) -> Lsend (k, subst s l met, subst s l obj, subst_list s l args, loc) | Levent (lam, evt) -> let old_env = evt.lev_env in let env_updates = let find_in_old id = Env.find_value (Path.Pident id) old_env in let rebind id id' new_env = match find_in_old id with | exception Not_found -> new_env | vd -> Env.add_value id' vd new_env in let update_free id new_env = match find_in_old id with | exception Not_found -> new_env | vd -> update_env id vd new_env in Ident.Map.merge (fun id bound free -> match bound, free with | Some id', _ -> if Ident.equal id id' then None else Some (rebind id id') | None, Some _ -> Some (update_free id) | None, None -> None ) l s in let new_env = Ident.Map.fold (fun _id update env -> update env) env_updates old_env in Levent (subst s l lam, { evt with lev_env = new_env }) | Lifused (id, e) -> let id = try Ident.Map.find id l with Not_found -> id in Lifused (id, subst s l e) and subst_list s l li = List.map (subst s l) li and subst_decl s l (id, exp) = (id, subst s l exp) and subst_case s l (key, case) = (key, subst s l case) and subst_strcase s l (key, case) = (key, subst s l case) and subst_opt s l = function | None -> None | Some e -> Some (subst s l e) in subst s Ident.Map.empty input_lam let rename idmap lam = let update_env oldid vd env = let newid = Ident.Map.find oldid idmap in Env.add_value newid vd env in let s = Ident.Map.map (fun new_id -> Lvar new_id) idmap in subst update_env s lam let duplicate lam = subst (fun _ _ env -> env) ~freshen_bound_variables:true Ident.Map.empty lam let shallow_map f = function | Lvar _ | Lmutvar _ | Lconst _ as lam -> lam | Lapply { ap_func; ap_args; ap_loc; ap_tailcall; ap_inlined; ap_specialised } -> Lapply { ap_func = f ap_func; ap_args = List.map f ap_args; ap_loc; ap_tailcall; ap_inlined; ap_specialised; } | Lfunction { kind; params; return; body; attr; loc; } -> Lfunction { kind; params; return; body = f body; attr; loc; } | Llet (str, k, v, e1, e2) -> Llet (str, k, v, f e1, f e2) | Lmutlet (k, v, e1, e2) -> Lmutlet (k, v, f e1, f e2) | Lletrec (idel, e2) -> Lletrec (List.map (fun (v, e) -> (v, f e)) idel, f e2) | Lprim (p, el, loc) -> Lprim (p, List.map f el, loc) | Lswitch (e, sw, loc) -> Lswitch (f e, { sw_numconsts = sw.sw_numconsts; sw_consts = List.map (fun (n, e) -> (n, f e)) sw.sw_consts; sw_numblocks = sw.sw_numblocks; sw_blocks = List.map (fun (n, e) -> (n, f e)) sw.sw_blocks; sw_failaction = Option.map f sw.sw_failaction; }, loc) | Lstringswitch (e, sw, default, loc) -> Lstringswitch ( f e, List.map (fun (s, e) -> (s, f e)) sw, Option.map f default, loc) | Lstaticraise (i, args) -> Lstaticraise (i, List.map f args) | Lstaticcatch (body, id, handler) -> Lstaticcatch (f body, id, f handler) | Ltrywith (e1, v, e2) -> Ltrywith (f e1, v, f e2) | Lifthenelse (e1, e2, e3) -> Lifthenelse (f e1, f e2, f e3) | Lsequence (e1, e2) -> Lsequence (f e1, f e2) | Lwhile (e1, e2) -> Lwhile (f e1, f e2) | Lfor (v, e1, e2, dir, e3) -> Lfor (v, f e1, f e2, dir, f e3) | Lassign (v, e) -> Lassign (v, f e) | Lsend (k, m, o, el, loc) -> Lsend (k, f m, f o, List.map f el, loc) | Levent (l, ev) -> Levent (f l, ev) | Lifused (v, e) -> Lifused (v, f e) let map f = let rec g lam = f (shallow_map g lam) in g let bind_with_value_kind str (var, kind) exp body = match exp with Lvar var' when Ident.same var var' -> body | _ -> Llet(str, kind, var, exp, body) let bind str var exp body = bind_with_value_kind str (var, Pgenval) exp body let negate_integer_comparison = function | Ceq -> Cne | Cne -> Ceq | Clt -> Cge | Cle -> Cgt | Cgt -> Cle | Cge -> Clt let swap_integer_comparison = function | Ceq -> Ceq | Cne -> Cne | Clt -> Cgt | Cle -> Cge | Cgt -> Clt | Cge -> Cle let negate_float_comparison = function | CFeq -> CFneq | CFneq -> CFeq | CFlt -> CFnlt | CFnlt -> CFlt | CFgt -> CFngt | CFngt -> CFgt | CFle -> CFnle | CFnle -> CFle | CFge -> CFnge | CFnge -> CFge let swap_float_comparison = function | CFeq -> CFeq | CFneq -> CFneq | CFlt -> CFgt | CFnlt -> CFngt | CFle -> CFge | CFnle -> CFnge | CFgt -> CFlt | CFngt -> CFnlt | CFge -> CFle | CFnge -> CFnle let raise_kind = function | Raise_regular -> "raise" | Raise_reraise -> "reraise" | Raise_notrace -> "raise_notrace" let merge_inline_attributes attr1 attr2 = match attr1, attr2 with | Default_inline, _ -> Some attr2 | _, Default_inline -> Some attr1 | _, _ -> if attr1 = attr2 then Some attr1 else None let function_is_curried func = match func.kind with | Curried -> true | Tupled -> false let find_exact_application kind ~arity args = match kind with | Curried -> if arity <> List.length args then None else Some args | Tupled -> begin match args with | [Lprim(Pmakeblock _, tupled_args, _)] -> if arity <> List.length tupled_args then None else Some tupled_args | [Lconst(Const_block (_, const_args))] -> if arity <> List.length const_args then None else Some (List.map (fun cst -> Lconst cst) const_args) | _ -> None end let reset () = raise_count := 0
3204704026a90a7ac1cab911fa1323f5ce08e6e2eda912b381efbcf8ccb5d925
hedgehogqa/haskell-hedgehog-classes
Spec.hs
module Main (main) where import Hedgehog.Classes import Spec.Alternative import Spec.Applicative import Spec.Arrow import Spec.Bifoldable import Spec.Bifunctor import Spec.Binary import Spec.Bitraversable import Spec.Bits import Spec.Category import Spec.Comonad import Spec.Contravariant import Spec.Enum import Spec.Eq import Spec.Foldable import Spec.Functor import Spec.Generic import Spec.Integral import Spec . Ix import Spec.Json import Spec.Monad import Spec.Monoid import Spec.MVector import Spec.Ord import Spec.Prim import Spec.Semigroup import Spec.Semiring import Spec.Show import Spec.Storable import Spec.Traversable main :: IO Bool main = lawsCheckMany allLaws allNullaryLaws :: [(String, [Laws])] allNullaryLaws = testBits ++ testEnum ++ testBoundedEnum ++ testBinary ++ testEq ++ testGeneric ++ testIntegral -- ++ testIx ++ testJson ++ testMonoid ++ testCommutativeMonoid ++ testOrd ++ testPrim ++ testSemigroup ++ testCommutativeSemigroup ++ testExponentialSemigroup ++ testIdempotentSemigroup ++ testRectangularBandSemigroup ++ testSemiring ++ testRing ++ testStar ++ testShow ++ testShowRead ++ testStorable ++ testMUVector allUnaryLaws :: [(String, [Laws])] allUnaryLaws = testAlternative ++ testApplicative ++ testComonad ++ testContravariant ++ testFoldable ++ testFunctor ++ testMonad ++ testMonadIO ++ testMonadPlus ++ testMonadZip ++ testTraversable allBinaryLaws :: [(String, [Laws])] allBinaryLaws = testArrow ++ testBifoldable ++ testBifoldableFunctor ++ testBifunctor ++ testBitraversable ++ testCategory ++ testCommutativeCategory allLaws :: [(String, [Laws])] allLaws = allNullaryLaws ++ allUnaryLaws ++ allBinaryLaws
null
https://raw.githubusercontent.com/hedgehogqa/haskell-hedgehog-classes/4d97b000e915de8ba590818f551bce7bd862e7d4/test/Spec.hs
haskell
++ testIx
module Main (main) where import Hedgehog.Classes import Spec.Alternative import Spec.Applicative import Spec.Arrow import Spec.Bifoldable import Spec.Bifunctor import Spec.Binary import Spec.Bitraversable import Spec.Bits import Spec.Category import Spec.Comonad import Spec.Contravariant import Spec.Enum import Spec.Eq import Spec.Foldable import Spec.Functor import Spec.Generic import Spec.Integral import Spec . Ix import Spec.Json import Spec.Monad import Spec.Monoid import Spec.MVector import Spec.Ord import Spec.Prim import Spec.Semigroup import Spec.Semiring import Spec.Show import Spec.Storable import Spec.Traversable main :: IO Bool main = lawsCheckMany allLaws allNullaryLaws :: [(String, [Laws])] allNullaryLaws = testBits ++ testEnum ++ testBoundedEnum ++ testBinary ++ testEq ++ testGeneric ++ testIntegral ++ testJson ++ testMonoid ++ testCommutativeMonoid ++ testOrd ++ testPrim ++ testSemigroup ++ testCommutativeSemigroup ++ testExponentialSemigroup ++ testIdempotentSemigroup ++ testRectangularBandSemigroup ++ testSemiring ++ testRing ++ testStar ++ testShow ++ testShowRead ++ testStorable ++ testMUVector allUnaryLaws :: [(String, [Laws])] allUnaryLaws = testAlternative ++ testApplicative ++ testComonad ++ testContravariant ++ testFoldable ++ testFunctor ++ testMonad ++ testMonadIO ++ testMonadPlus ++ testMonadZip ++ testTraversable allBinaryLaws :: [(String, [Laws])] allBinaryLaws = testArrow ++ testBifoldable ++ testBifoldableFunctor ++ testBifunctor ++ testBitraversable ++ testCategory ++ testCommutativeCategory allLaws :: [(String, [Laws])] allLaws = allNullaryLaws ++ allUnaryLaws ++ allBinaryLaws
0eec9098fd7ebd5c09a4c404f9658d708682f3b5756113d5173f6e6c49d71a2a
fosskers/kanji
Kanji.hs
# LANGUAGE TupleSections # -- | -- Module : Data.Kanji Copyright : ( c ) , 2015 - 2020 -- License : GPL3 Maintainer : < > -- -- A library for analysing the density of Kanji in given texts, -- according to their "Level" classification, as defined by the Japan Kanji Aptitude Testing Foundation ( 日本漢字能力検定協会 ) . module Data.Kanji ( -- * Kanji Kanji , kanji, _kanji , allKanji , isKanji, isHiragana, isKatakana -- * Character Categories , CharCat(..) , category -- * Levels , Level(..) , level -- * Analysis , percentSpread , levelDist , uniques -- ** Densities , densities , elementaryDen , middleDen , highDen ) where import Control.Arrow hiding (second) import Data.Foldable (fold) import Data.Kanji.Levels import Data.Kanji.Types import Data.List (group, sort) import qualified Data.Map.Strict as M import qualified Data.Set as S import qualified Data.Text as T --- | All Japanese ` Kanji ` , grouped by their Level ( 級 ) . allKanji :: M.Map Level (S.Set Kanji) allKanji = M.fromList . zip [ Ten .. ] $ map (S.map Kanji) ks where ks = [ tenth, ninth, eighth, seventh, sixth , fifth, fourth, third, preSecond, second ] | All Japanese ` Kanji ` with their ` Level ` . allKanji' :: M.Map Kanji Level allKanji' = M.fromList . S.toList . fold $ M.mapWithKey (\k v -> S.map (,k) v) allKanji | What ` Level ` does a Kanji belong to ? ` Unknown ` for Kanji above level ` Two ` . level :: Kanji -> Level level k = maybe Unknown id $ M.lookup k allKanji' # INLINE level # -- | Percentage of appearance of each `CharCat` in the source text. The percentages will sum to 1.0 . densities :: T.Text -> M.Map CharCat Float densities t = M.fromList . map (head &&& f) . group . sort . map category $ T.unpack t where f xs = fromIntegral (length xs) / fromIntegral (T.length t) | How much of the Kanji found are learnt in elementary school in Japan ? -- -- > elementaryDen . levelDist :: [Kanji] -> Float elementaryDen :: M.Map Level Float -> Float elementaryDen m = M.foldl' (+) 0 . M.restrictKeys m $ S.fromList [ Five, Six .. ] | How much of the Kanji found are learnt by the end of middle school ? -- -- > middleDen . levelDist :: [Kanji] -> Float middleDen :: M.Map Level Float -> Float middleDen m = M.foldl' (+) 0 . M.restrictKeys m $ S.fromList [ Three, Four .. ] -- | How much of the Kanji found are learnt by the end of high school? -- -- > highDen . levelDist :: [Kanji] -> Float highDen :: M.Map Level Float -> Float highDen m = M.foldl' (+) 0 . M.restrictKeys m $ S.fromList [ Two, PreTwo .. ] | How much of each ` Level ` is represented by a group of Kanji ? The distribution values will sum to 1 . levelDist :: [Kanji] -> M.Map Level Float levelDist ks = M.fromList . map percentPair . group . sort $ map level ks where percentPair qns = (head qns, fromIntegral (length qns) / totalKs) totalKs = fromIntegral $ length ks -- | The distribution of each `Kanji` in a set of them. The distribution values must sum to 1 . percentSpread :: [Kanji] -> M.Map Kanji Float percentSpread ks = getPercent <$> kQuants where getPercent q = fromIntegral q / totalKanji kQuants = kanjiQuantities ks totalKanji = fromIntegral $ M.foldl' (+) 0 kQuants | Determines how many times each ` Kanji ` appears in given set of them . kanjiQuantities :: [Kanji] -> M.Map Kanji Int kanjiQuantities = M.fromList . map (head &&& length) . group . sort -- | Which Kanji appeared from each Level in the text? uniques :: [Kanji] -> M.Map Level (S.Set Kanji) uniques = S.foldl' h M.empty . S.fromList where h a k = (\l -> M.insertWith (<>) l (S.singleton k) a) $ level k
null
https://raw.githubusercontent.com/fosskers/kanji/93dd7d16d1a3690db36ca0ffbeb21e05083c42ea/lib/Data/Kanji.hs
haskell
| Module : Data.Kanji License : GPL3 A library for analysing the density of Kanji in given texts, according to their "Level" classification, as defined by the * Kanji * Character Categories * Levels * Analysis ** Densities - | Percentage of appearance of each `CharCat` in the source text. > elementaryDen . levelDist :: [Kanji] -> Float > middleDen . levelDist :: [Kanji] -> Float | How much of the Kanji found are learnt by the end of high school? > highDen . levelDist :: [Kanji] -> Float | The distribution of each `Kanji` in a set of them. | Which Kanji appeared from each Level in the text?
# LANGUAGE TupleSections # Copyright : ( c ) , 2015 - 2020 Maintainer : < > Japan Kanji Aptitude Testing Foundation ( 日本漢字能力検定協会 ) . module Data.Kanji ( Kanji , kanji, _kanji , allKanji , isKanji, isHiragana, isKatakana , CharCat(..) , category , Level(..) , level , percentSpread , levelDist , uniques , densities , elementaryDen , middleDen , highDen ) where import Control.Arrow hiding (second) import Data.Foldable (fold) import Data.Kanji.Levels import Data.Kanji.Types import Data.List (group, sort) import qualified Data.Map.Strict as M import qualified Data.Set as S import qualified Data.Text as T | All Japanese ` Kanji ` , grouped by their Level ( 級 ) . allKanji :: M.Map Level (S.Set Kanji) allKanji = M.fromList . zip [ Ten .. ] $ map (S.map Kanji) ks where ks = [ tenth, ninth, eighth, seventh, sixth , fifth, fourth, third, preSecond, second ] | All Japanese ` Kanji ` with their ` Level ` . allKanji' :: M.Map Kanji Level allKanji' = M.fromList . S.toList . fold $ M.mapWithKey (\k v -> S.map (,k) v) allKanji | What ` Level ` does a Kanji belong to ? ` Unknown ` for Kanji above level ` Two ` . level :: Kanji -> Level level k = maybe Unknown id $ M.lookup k allKanji' # INLINE level # The percentages will sum to 1.0 . densities :: T.Text -> M.Map CharCat Float densities t = M.fromList . map (head &&& f) . group . sort . map category $ T.unpack t where f xs = fromIntegral (length xs) / fromIntegral (T.length t) | How much of the Kanji found are learnt in elementary school in Japan ? elementaryDen :: M.Map Level Float -> Float elementaryDen m = M.foldl' (+) 0 . M.restrictKeys m $ S.fromList [ Five, Six .. ] | How much of the Kanji found are learnt by the end of middle school ? middleDen :: M.Map Level Float -> Float middleDen m = M.foldl' (+) 0 . M.restrictKeys m $ S.fromList [ Three, Four .. ] highDen :: M.Map Level Float -> Float highDen m = M.foldl' (+) 0 . M.restrictKeys m $ S.fromList [ Two, PreTwo .. ] | How much of each ` Level ` is represented by a group of Kanji ? The distribution values will sum to 1 . levelDist :: [Kanji] -> M.Map Level Float levelDist ks = M.fromList . map percentPair . group . sort $ map level ks where percentPair qns = (head qns, fromIntegral (length qns) / totalKs) totalKs = fromIntegral $ length ks The distribution values must sum to 1 . percentSpread :: [Kanji] -> M.Map Kanji Float percentSpread ks = getPercent <$> kQuants where getPercent q = fromIntegral q / totalKanji kQuants = kanjiQuantities ks totalKanji = fromIntegral $ M.foldl' (+) 0 kQuants | Determines how many times each ` Kanji ` appears in given set of them . kanjiQuantities :: [Kanji] -> M.Map Kanji Int kanjiQuantities = M.fromList . map (head &&& length) . group . sort uniques :: [Kanji] -> M.Map Level (S.Set Kanji) uniques = S.foldl' h M.empty . S.fromList where h a k = (\l -> M.insertWith (<>) l (S.singleton k) a) $ level k
2ed73413fc20dc46101790bcd6b49ba143b7f1481711cb10e4a677ba34149f8a
wireapp/wire-server
Component.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- 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 </>. module Wire.API.Federation.Component ( module Wire.API.Federation.Component, Component (..), ) where import Imports import Wire.API.MakesFederatedCall (Component (..)) parseComponent :: Text -> Maybe Component parseComponent "brig" = Just Brig parseComponent "galley" = Just Galley parseComponent "cargohold" = Just Cargohold parseComponent _ = Nothing componentName :: Component -> Text componentName Brig = "brig" componentName Galley = "galley" componentName Cargohold = "cargohold" class KnownComponent (c :: Component) where componentVal :: Component instance KnownComponent 'Brig where componentVal = Brig instance KnownComponent 'Galley where componentVal = Galley instance KnownComponent 'Cargohold where componentVal = Cargohold
null
https://raw.githubusercontent.com/wireapp/wire-server/d377ffd87066ed286e9cc19ec223190a1c8fd32b/libs/wire-api-federation/src/Wire/API/Federation/Component.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under 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. with this program. If not, see </>.
Copyright ( C ) 2022 Wire Swiss GmbH < > 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 You should have received a copy of the GNU Affero General Public License along module Wire.API.Federation.Component ( module Wire.API.Federation.Component, Component (..), ) where import Imports import Wire.API.MakesFederatedCall (Component (..)) parseComponent :: Text -> Maybe Component parseComponent "brig" = Just Brig parseComponent "galley" = Just Galley parseComponent "cargohold" = Just Cargohold parseComponent _ = Nothing componentName :: Component -> Text componentName Brig = "brig" componentName Galley = "galley" componentName Cargohold = "cargohold" class KnownComponent (c :: Component) where componentVal :: Component instance KnownComponent 'Brig where componentVal = Brig instance KnownComponent 'Galley where componentVal = Galley instance KnownComponent 'Cargohold where componentVal = Cargohold
9ffd22f54d9b58d4d239715db0d8c70ef1e838e68a03ea2a6185934da78e3b4e
acieroid/scala-am
stspaceCODE.scm
(define false #f) (define true #t) (define (create-stack eq-fnct) (let ((content '())) (define (empty?) (null? content)) (define (push element) (set! content (cons element content)) #t) (define (pop) (if (null? content) #f (let ((temp (car content))) (set! content (cdr content)) temp))) (define (top) (if (null? content) #f (car content))) (define (is-in element) (if (member element content) #t #f)) (define (dispatch m) (cond ((eq? m 'empty?) empty?) ((eq? m 'push) push) ((eq? m 'pop) pop) ((eq? m 'top) top) ((eq? m 'is-in) is-in) (else (error "unknown request -- create-stack" m)))) dispatch)) (define (create-set . same) (let ((content '()) (same? (if (null? same) eq? (car same)))) (define (empty?) (null? content)) (define (is-in? item) (define (find-iter current) (cond ((null? current) false) ((same? item (car current)) true) (else (find-iter (cdr current))))) (find-iter content)) (define (insert item) (if (not (is-in? item)) (set! content (cons item content))) true) (define (delete item) (define (remove-iter current prev) (cond ((null? current) false) ((same item (car current)) (if (null? prev) (set! content (cdr content)) (set-cdr! prev (cdr current))) true) (else (remove-iter (cdr current) current)))) (remove-iter content '())) (define (map a-function) (define (map-iter current result) (if (null? current) (reverse result) (map-iter (cdr current) (cons (a-function (car current)) result)))) (map-iter content '())) (define (foreach a-action) (define (foreach-iter current) (cond ((null? current) true) (else (a-action (car current)) (foreach-iter (cdr current))))) (foreach-iter content) true) (define (dispatch m) (cond ((eq? m 'empty?) empty?) ((eq? m 'is-in) is-in?) ((eq? m 'insert) insert) ((eq? m 'delete) delete) ((eq? m 'map) map) ((eq? m 'foreach) foreach) (else (error "unknown request -- create-set" m)))) dispatch)) (define (create-operator pre op) (list pre op)) (define (precondition operator) (car operator)) (define (operation operator) (cadr operator)) (define (depth-first-search start-state operators goal-reached? good-state? eq-state? present-goal open-trace-action closed-trace-action) (let ((open (create-stack eq-state?)) (closed (create-set eq-state?))) (define (expand state) (define (iter rest) (cond ((null? rest) false) (else (let ((operator (car rest))) (if ((precondition operator) state) (let ((new-state ((operation operator) state))) (if (good-state? new-state) (if (goal-reached? new-state) (begin (if open-trace-action (open-trace-action new-state)) (present-goal new-state) true) (begin (if (and (not ((open 'is-in) new-state)) (not ((closed 'is-in) new-state))) (begin ((open 'push) new-state) (if open-trace-action (open-trace-action new-state)))) (iter (cdr rest)))) (iter (cdr rest)))) (iter (cdr rest))))))) (iter operators)) (define (loop) (cond (((open 'empty?)) false) (else (let ((state ((open 'pop)))) ((closed 'insert) state) (if closed-trace-action (closed-trace-action state)) (let ((solution (expand state))) (if solution solution (loop))))))) ((open 'push) start-state) (loop)))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/R5RS/ad/stspaceCODE.scm
scheme
(define false #f) (define true #t) (define (create-stack eq-fnct) (let ((content '())) (define (empty?) (null? content)) (define (push element) (set! content (cons element content)) #t) (define (pop) (if (null? content) #f (let ((temp (car content))) (set! content (cdr content)) temp))) (define (top) (if (null? content) #f (car content))) (define (is-in element) (if (member element content) #t #f)) (define (dispatch m) (cond ((eq? m 'empty?) empty?) ((eq? m 'push) push) ((eq? m 'pop) pop) ((eq? m 'top) top) ((eq? m 'is-in) is-in) (else (error "unknown request -- create-stack" m)))) dispatch)) (define (create-set . same) (let ((content '()) (same? (if (null? same) eq? (car same)))) (define (empty?) (null? content)) (define (is-in? item) (define (find-iter current) (cond ((null? current) false) ((same? item (car current)) true) (else (find-iter (cdr current))))) (find-iter content)) (define (insert item) (if (not (is-in? item)) (set! content (cons item content))) true) (define (delete item) (define (remove-iter current prev) (cond ((null? current) false) ((same item (car current)) (if (null? prev) (set! content (cdr content)) (set-cdr! prev (cdr current))) true) (else (remove-iter (cdr current) current)))) (remove-iter content '())) (define (map a-function) (define (map-iter current result) (if (null? current) (reverse result) (map-iter (cdr current) (cons (a-function (car current)) result)))) (map-iter content '())) (define (foreach a-action) (define (foreach-iter current) (cond ((null? current) true) (else (a-action (car current)) (foreach-iter (cdr current))))) (foreach-iter content) true) (define (dispatch m) (cond ((eq? m 'empty?) empty?) ((eq? m 'is-in) is-in?) ((eq? m 'insert) insert) ((eq? m 'delete) delete) ((eq? m 'map) map) ((eq? m 'foreach) foreach) (else (error "unknown request -- create-set" m)))) dispatch)) (define (create-operator pre op) (list pre op)) (define (precondition operator) (car operator)) (define (operation operator) (cadr operator)) (define (depth-first-search start-state operators goal-reached? good-state? eq-state? present-goal open-trace-action closed-trace-action) (let ((open (create-stack eq-state?)) (closed (create-set eq-state?))) (define (expand state) (define (iter rest) (cond ((null? rest) false) (else (let ((operator (car rest))) (if ((precondition operator) state) (let ((new-state ((operation operator) state))) (if (good-state? new-state) (if (goal-reached? new-state) (begin (if open-trace-action (open-trace-action new-state)) (present-goal new-state) true) (begin (if (and (not ((open 'is-in) new-state)) (not ((closed 'is-in) new-state))) (begin ((open 'push) new-state) (if open-trace-action (open-trace-action new-state)))) (iter (cdr rest)))) (iter (cdr rest)))) (iter (cdr rest))))))) (iter operators)) (define (loop) (cond (((open 'empty?)) false) (else (let ((state ((open 'pop)))) ((closed 'insert) state) (if closed-trace-action (closed-trace-action state)) (let ((solution (expand state))) (if solution solution (loop))))))) ((open 'push) start-state) (loop)))
cfdf5daed81afbaf75689deb267b22a7cc54c269cefdb72c45f90474261a6c55
maacl/websocket-test
form_helpers.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. (ns compojure.html.form-helpers "Functions for generating HTML forms and input fields." (:use compojure.html.gen compojure.control compojure.str-utils clojure.contrib.def clojure.contrib.seq-utils)) ;; Global parameters for easy default values (defvar *params* {} "Parameter map var that form input field functions use to populate their default values.") (defmacro with-params "Bind a map of params to *params*." [params & body] `(binding [*params* ~params] ~@body)) ;; Form input fields (defn- input-field "Creates a form input field." [type name value] (let [name (str* name) attrs {:type type, :name name, :id name} attrs (if value (assoc attrs :value value) attrs)] [:input attrs])) (defn hidden-field "Creates a hidden input field." ([name] (hidden-field name (*params* name))) ([name value] (input-field "hidden" name value))) (defn text-field "Creates a text input field." ([name] (text-field name (*params* name))) ([name value] (input-field "text" name value))) (defn password-field "Creates a password input field." [name] (input-field "password" name "")) (defn check-box "Creates a check box." ([name] (check-box name (*params* name))) ([name checked?] (check-box name checked? "true")) ([name checked? value] [:input {:type "checkbox" :name (str* name) :id (str* name) :value value :checked checked?}])) (defn radio-button "Creates a radio button." ([group] (radio-button group (*params* group))) ([group checked?] (radio-button group checked? "true")) ([group checked? value] [:input {:type "radio" :name (str* group) :id (str* group "_" value) :value value :checked checked?}])) (defn select-options "Turn a collection into a set of option tags." ([options] (select-options options nil)) ([options selected] (let [select (fn [opt attrs] (if (and selected (= opt (str* selected))) (merge attrs {:selected "selected"}) attrs))] (domap [opt options] (if (vector? opt) (let [text (opt 0) value (str* (opt 1))] [:option (select value {:value value}) text]) [:option (select opt {}) opt]))))) (defn drop-down "Creates a drop-down box using the 'select' tag." ([name options] (drop-down name options (*params* name))) ([name options selected] [:select {:name (str* name) :id (str* name)} (select-options options selected)])) (defn text-area "Creates a text area element." ([name] (text-area name (*params* name))) ([name value] [:textarea {:name (str* name) :id (str* name)} value])) (defn file-upload "Creates a file upload input." [name] [:input {:type "file", :name (str* name), :id (str* name)}]) (defn label "Create a label for an input field with the supplied name." [name text] [:label {:for (str* name)} text]) (defn submit-button "Create a submit button." [text] [:input {:type "submit" :value text}]) (defn reset-button "Create a form reset button." [text] [:input {:type "reset" :value text}]) (defn form-to "Create a form that points to a particular method and route. e.g. (form-to [:put \"/post\"] ...)" [[method action] & body] (let [method-str (upcase-name method)] (into [] (concat (if (includes? [:get :post] method) [:form {:method method-str :action action}] [:form {:method "POST" :action action} (hidden-field "_method" method-str)]) body)))) (decorate-with optional-attrs hidden-field text-field check-box drop-down text-area file-upload label submit-button reset-button form-to) (defmacro decorate-fields "Wrap all input field functions in a decorator." [decorator & body] `(decorate-bind ~decorator [text-field password-field check-box drop-down text-area file-upload] (list ~@body)))
null
https://raw.githubusercontent.com/maacl/websocket-test/d79dfdf82762d566cd89b535c3dbede2788bb034/src/compojure/html/form_helpers.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. Global parameters for easy default values Form input fields
Copyright ( c ) . All rights reserved . The use and distribution terms for this software are covered by the Eclipse (ns compojure.html.form-helpers "Functions for generating HTML forms and input fields." (:use compojure.html.gen compojure.control compojure.str-utils clojure.contrib.def clojure.contrib.seq-utils)) (defvar *params* {} "Parameter map var that form input field functions use to populate their default values.") (defmacro with-params "Bind a map of params to *params*." [params & body] `(binding [*params* ~params] ~@body)) (defn- input-field "Creates a form input field." [type name value] (let [name (str* name) attrs {:type type, :name name, :id name} attrs (if value (assoc attrs :value value) attrs)] [:input attrs])) (defn hidden-field "Creates a hidden input field." ([name] (hidden-field name (*params* name))) ([name value] (input-field "hidden" name value))) (defn text-field "Creates a text input field." ([name] (text-field name (*params* name))) ([name value] (input-field "text" name value))) (defn password-field "Creates a password input field." [name] (input-field "password" name "")) (defn check-box "Creates a check box." ([name] (check-box name (*params* name))) ([name checked?] (check-box name checked? "true")) ([name checked? value] [:input {:type "checkbox" :name (str* name) :id (str* name) :value value :checked checked?}])) (defn radio-button "Creates a radio button." ([group] (radio-button group (*params* group))) ([group checked?] (radio-button group checked? "true")) ([group checked? value] [:input {:type "radio" :name (str* group) :id (str* group "_" value) :value value :checked checked?}])) (defn select-options "Turn a collection into a set of option tags." ([options] (select-options options nil)) ([options selected] (let [select (fn [opt attrs] (if (and selected (= opt (str* selected))) (merge attrs {:selected "selected"}) attrs))] (domap [opt options] (if (vector? opt) (let [text (opt 0) value (str* (opt 1))] [:option (select value {:value value}) text]) [:option (select opt {}) opt]))))) (defn drop-down "Creates a drop-down box using the 'select' tag." ([name options] (drop-down name options (*params* name))) ([name options selected] [:select {:name (str* name) :id (str* name)} (select-options options selected)])) (defn text-area "Creates a text area element." ([name] (text-area name (*params* name))) ([name value] [:textarea {:name (str* name) :id (str* name)} value])) (defn file-upload "Creates a file upload input." [name] [:input {:type "file", :name (str* name), :id (str* name)}]) (defn label "Create a label for an input field with the supplied name." [name text] [:label {:for (str* name)} text]) (defn submit-button "Create a submit button." [text] [:input {:type "submit" :value text}]) (defn reset-button "Create a form reset button." [text] [:input {:type "reset" :value text}]) (defn form-to "Create a form that points to a particular method and route. e.g. (form-to [:put \"/post\"] ...)" [[method action] & body] (let [method-str (upcase-name method)] (into [] (concat (if (includes? [:get :post] method) [:form {:method method-str :action action}] [:form {:method "POST" :action action} (hidden-field "_method" method-str)]) body)))) (decorate-with optional-attrs hidden-field text-field check-box drop-down text-area file-upload label submit-button reset-button form-to) (defmacro decorate-fields "Wrap all input field functions in a decorator." [decorator & body] `(decorate-bind ~decorator [text-field password-field check-box drop-down text-area file-upload] (list ~@body)))
be76ca45a817a8464efb24e1a79dc0f79fb47ad96e4664e75497937078046f8d
qnikst/irc-simple
Parser.hs
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} module Test.Protocol.Parser ( tests ) where import Control.Lens import Control.Applicative import Data.Attoparsec.Text import Data.Coerce import Data.Monoid import Data.String import Protocol.Wire (message, toWire) import Protocol.Types import qualified Data.Text as Text import qualified Data.Text.Lazy.Builder as TextL import qualified Data.Text.Lazy as TextL import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.SmallCheck as SC import Test.SmallCheck.Series (Serial(..), decDepth) import qualified Test.SmallCheck.Series as SC tests :: TestTree tests = testGroup "parser" [ testGroup "RFC examples" testsRFC -- , testGroup "properties" testProp ] testsRFC = map (uncurry mkTest) [ ("NICK Wiz", mkTextCommand "NICK" & params .~ ["Wiz"]) --, (":WiZ! NICK Kilroy", -- mkTextCommand "JOIN" & prefix .~ (Just ":WiZ!") & params .~ [ " " ] ) , ("JOIN #foobar", Message Nothing "JOIN" ["#foobar"] Nothing) , ("JOIN &foo fubar", Message Nothing "JOIN" ["&foo", "fubar"] Nothing) , ("JOIN #foo,&bar fubar", Message Nothing "JOIN" ["#foo,&bar", "fubar"] Nothing) , ( " : WiZ! JOIN # Twilight_zone " , Message ( Just " WiZ! " ) " JOIN " [ " # Twilight_zone " ] Nothing ) , ("PART #twilight_zone", Message Nothing "PART" ["#twilight_zone"] Nothing) , (":WiZ PART #playzone :I lost", mkTextCommand "PART" & prefix .~ (Just "WiZ") & params .~ ["#playzone"] & trailing .~ Just "I lost") , (":Angel PRIVMSG Wiz :Are you receiving this message ?", mkTextCommand "PRIVMSG" & prefix .~ (Just "Angel") & params .~ ["Wiz"] & trailing .~ Just "Are you receiving this message ?") , ("PRIVMSG Angel :yes I'm receiving it !", Message Nothing "PRIVMSG" ["Angel"] (Just "yes I'm receiving it !")) ] where mkTest msg pattern = testCase msg $ parseOnly message (fromString msg <> "\r\n") @?= Right pattern testProp = [ SC.testProperty " parse . toWire = = i d " $ \msg - > let s = TextL.toStrict $ TextL.toLazyText $ toWire msg a = parseOnly message s b = Right msg : : Either String Message in if a = = b then Right ( " OK"::String ) else Left $ unlines [ " Request : " < > show msg , " Line : " < > show ( Text.unpack s ) , " Result : " < > show a ] ] instance = > Serial m Channel where series = coerce . Text.pack < $ > series instance = > Serial m Nickname where series = coerce . Text.pack < $ > series instance = > Serial m Command where series = TextCommand . Text.pack . SC.getNonEmpty < $ > series < | > IntCommand < $ > series instance = > Serial m Code instance = > Serial m Message where series = decDepth $ Message < $ > series < * > series < * > series < * > fmap ( fmap Text.pack ) series instance = > Serial m Prefix where series = coerce . Text.pack < $ > series instance = > Serial m Param where series = coerce . Text.pack < $ > series testProp = [ SC.testProperty "parse . toWire == id" $ \msg -> let s = TextL.toStrict $ TextL.toLazyText $ toWire msg a = parseOnly message s b = Right msg :: Either String Message in if a == b then Right ("OK"::String) else Left $ unlines [ "Request: " <> show msg , "Line: " <> show (Text.unpack s) , "Result: " <> show a ] ] instance Monad m => Serial m Channel where series = coerce . Text.pack <$> series instance Monad m => Serial m Nickname where series = coerce . Text.pack <$> series instance Monad m => Serial m Command where series = TextCommand . Text.pack . SC.getNonEmpty <$> series <|> IntCommand <$> series instance Monad m => Serial m Code instance Monad m => Serial m Message where series = decDepth $ Message <$> series <*> series <*> series <*> fmap (fmap Text.pack) series instance Monad m => Serial m Prefix where series = coerce . Text.pack <$> series instance Monad m => Serial m Param where series = coerce . Text.pack <$> series -}
null
https://raw.githubusercontent.com/qnikst/irc-simple/6deaec9c240b0e9023257b96e0328e883e0760a8/tests/Test/Protocol/Parser.hs
haskell
# LANGUAGE OverloadedStrings # , testGroup "properties" testProp , (":WiZ! NICK Kilroy", mkTextCommand "JOIN" & prefix .~ (Just ":WiZ!")
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Test.Protocol.Parser ( tests ) where import Control.Lens import Control.Applicative import Data.Attoparsec.Text import Data.Coerce import Data.Monoid import Data.String import Protocol.Wire (message, toWire) import Protocol.Types import qualified Data.Text as Text import qualified Data.Text.Lazy.Builder as TextL import qualified Data.Text.Lazy as TextL import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.SmallCheck as SC import Test.SmallCheck.Series (Serial(..), decDepth) import qualified Test.SmallCheck.Series as SC tests :: TestTree tests = testGroup "parser" [ testGroup "RFC examples" testsRFC ] testsRFC = map (uncurry mkTest) [ ("NICK Wiz", mkTextCommand "NICK" & params .~ ["Wiz"]) & params .~ [ " " ] ) , ("JOIN #foobar", Message Nothing "JOIN" ["#foobar"] Nothing) , ("JOIN &foo fubar", Message Nothing "JOIN" ["&foo", "fubar"] Nothing) , ("JOIN #foo,&bar fubar", Message Nothing "JOIN" ["#foo,&bar", "fubar"] Nothing) , ( " : WiZ! JOIN # Twilight_zone " , Message ( Just " WiZ! " ) " JOIN " [ " # Twilight_zone " ] Nothing ) , ("PART #twilight_zone", Message Nothing "PART" ["#twilight_zone"] Nothing) , (":WiZ PART #playzone :I lost", mkTextCommand "PART" & prefix .~ (Just "WiZ") & params .~ ["#playzone"] & trailing .~ Just "I lost") , (":Angel PRIVMSG Wiz :Are you receiving this message ?", mkTextCommand "PRIVMSG" & prefix .~ (Just "Angel") & params .~ ["Wiz"] & trailing .~ Just "Are you receiving this message ?") , ("PRIVMSG Angel :yes I'm receiving it !", Message Nothing "PRIVMSG" ["Angel"] (Just "yes I'm receiving it !")) ] where mkTest msg pattern = testCase msg $ parseOnly message (fromString msg <> "\r\n") @?= Right pattern testProp = [ SC.testProperty " parse . toWire = = i d " $ \msg - > let s = TextL.toStrict $ TextL.toLazyText $ toWire msg a = parseOnly message s b = Right msg : : Either String Message in if a = = b then Right ( " OK"::String ) else Left $ unlines [ " Request : " < > show msg , " Line : " < > show ( Text.unpack s ) , " Result : " < > show a ] ] instance = > Serial m Channel where series = coerce . Text.pack < $ > series instance = > Serial m Nickname where series = coerce . Text.pack < $ > series instance = > Serial m Command where series = TextCommand . Text.pack . SC.getNonEmpty < $ > series < | > IntCommand < $ > series instance = > Serial m Code instance = > Serial m Message where series = decDepth $ Message < $ > series < * > series < * > series < * > fmap ( fmap Text.pack ) series instance = > Serial m Prefix where series = coerce . Text.pack < $ > series instance = > Serial m Param where series = coerce . Text.pack < $ > series testProp = [ SC.testProperty "parse . toWire == id" $ \msg -> let s = TextL.toStrict $ TextL.toLazyText $ toWire msg a = parseOnly message s b = Right msg :: Either String Message in if a == b then Right ("OK"::String) else Left $ unlines [ "Request: " <> show msg , "Line: " <> show (Text.unpack s) , "Result: " <> show a ] ] instance Monad m => Serial m Channel where series = coerce . Text.pack <$> series instance Monad m => Serial m Nickname where series = coerce . Text.pack <$> series instance Monad m => Serial m Command where series = TextCommand . Text.pack . SC.getNonEmpty <$> series <|> IntCommand <$> series instance Monad m => Serial m Code instance Monad m => Serial m Message where series = decDepth $ Message <$> series <*> series <*> series <*> fmap (fmap Text.pack) series instance Monad m => Serial m Prefix where series = coerce . Text.pack <$> series instance Monad m => Serial m Param where series = coerce . Text.pack <$> series -}
224ad9f75dca5fd4902c40947848ebf47d1f17b8e4c0cdc980812d952c676ca5
derekslager/advent-of-code-2015
day15.clj
(ns advent-of-code-2015.day15 (:require [clojure.java.io :as io] [clojure.math.combinatorics :refer [selections]])) (defn parse-input [resource] (into [] (for [[_ ingredient props] (re-seq #"(\w+): (.*)" resource)] [ingredient (into {} (for [[_ k v] (re-seq #"(\w+) (-?\d+)" props)] [(keyword k) (Integer/parseInt v)]))]))) (defn score-key [stats recipe key] (max 0 (reduce + (map * recipe (for [[_ stat] stats] (key stat)))))) (defn score [stats recipe] (apply * (for [key [:capacity :durability :flavor :texture] :let [score (score-key stats recipe key)] :while (not= 0 score)] score))) (defn run [] (let [resource (slurp (io/resource "day15.txt")) stats (parse-input resource) ingredients (set (map first stats))] part 1 (apply max (for [recipe (selections (range 1 97) (count ingredients)) :when (= 100 (reduce + recipe)) part 2 :when (= 500 (score-key stats recipe :calories))] (score stats recipe)))))
null
https://raw.githubusercontent.com/derekslager/advent-of-code-2015/bbc589d29613c594178d9305741096f3688b05f2/src/advent_of_code_2015/day15.clj
clojure
(ns advent-of-code-2015.day15 (:require [clojure.java.io :as io] [clojure.math.combinatorics :refer [selections]])) (defn parse-input [resource] (into [] (for [[_ ingredient props] (re-seq #"(\w+): (.*)" resource)] [ingredient (into {} (for [[_ k v] (re-seq #"(\w+) (-?\d+)" props)] [(keyword k) (Integer/parseInt v)]))]))) (defn score-key [stats recipe key] (max 0 (reduce + (map * recipe (for [[_ stat] stats] (key stat)))))) (defn score [stats recipe] (apply * (for [key [:capacity :durability :flavor :texture] :let [score (score-key stats recipe key)] :while (not= 0 score)] score))) (defn run [] (let [resource (slurp (io/resource "day15.txt")) stats (parse-input resource) ingredients (set (map first stats))] part 1 (apply max (for [recipe (selections (range 1 97) (count ingredients)) :when (= 100 (reduce + recipe)) part 2 :when (= 500 (score-key stats recipe :calories))] (score stats recipe)))))
8dd2e440a4d051bd9062b918576b830834b19bda0ec5bde1ad7bb0fc762495a7
mikera/clojure-utils
vectors.clj
(ns mikera.cljutils.vectors "Utility functions for working with Clojure persistent vectors" (:use mikera.cljutils.error) (:import [clojure.lang IPersistentVector])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn find-identical-position "Searches a vector for an identical item and returns the index, or -1 if not found. Mainly used to pick out the position of a thing within a specific location" ^long [item ^IPersistentVector vector] (let [c (count vector)] (loop [i (int 0)] (if (>= i c) -1 (if (identical? item (.nth vector i)) i (recur (inc i))))))) (defn vector-without "Cuts a value from a specific position in a vector" [^IPersistentVector vector ^long i] (let [c (count vector) ni (inc i)] (cond (== c 1) (if (== i 0) [] (error "Index of out range: " i)) (== ni c) (subvec vector 0 i) :else (vec (concat (subvec vector 0 i) (subvec vector ni c)))))) (defn remove-from-vector "Removes a specific object from a vector. Throws an error if the object is not found." [item ^IPersistentVector vector] (let [i (find-identical-position item vector)] (when (< i 0) (error "item not found!")) (vector-without vector i)))
null
https://raw.githubusercontent.com/mikera/clojure-utils/92f7fd7a40c9cf22ab7004a304303e45ea4d4284/src/main/clojure/mikera/cljutils/vectors.clj
clojure
(ns mikera.cljutils.vectors "Utility functions for working with Clojure persistent vectors" (:use mikera.cljutils.error) (:import [clojure.lang IPersistentVector])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn find-identical-position "Searches a vector for an identical item and returns the index, or -1 if not found. Mainly used to pick out the position of a thing within a specific location" ^long [item ^IPersistentVector vector] (let [c (count vector)] (loop [i (int 0)] (if (>= i c) -1 (if (identical? item (.nth vector i)) i (recur (inc i))))))) (defn vector-without "Cuts a value from a specific position in a vector" [^IPersistentVector vector ^long i] (let [c (count vector) ni (inc i)] (cond (== c 1) (if (== i 0) [] (error "Index of out range: " i)) (== ni c) (subvec vector 0 i) :else (vec (concat (subvec vector 0 i) (subvec vector ni c)))))) (defn remove-from-vector "Removes a specific object from a vector. Throws an error if the object is not found." [item ^IPersistentVector vector] (let [i (find-identical-position item vector)] (when (< i 0) (error "item not found!")) (vector-without vector i)))
421fe5e0ab3e62c114b9b63d2ac75b5c19702a8a71d9181e900d37620dc7e77b
hackwaly/ocamlearlybird
value_module.ml
* * Copyright ( C ) 2021 * * 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 < / > . * Copyright (C) 2021 Yuxiang Wen * * 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 </>. *) open Ground open Value_basic let unknown_module_value = object inherit value method to_short_string = "«module»" end class module_value ~scene ~typenv ~obj ~path () = object inherit value method to_short_string = "«module»" method! num_named = -1 method! list_named = let lid = Util.Path.to_longident path in let get_pos addr = match addr with Env.Adot (_, pos) -> Some pos | _ -> None in let%lwt modules = typenv |> Typenv.extract_modules (Some lid) |> List.to_seq |> Seq.map (fun name -> Path.Pdot (path, name)) |> Seq.filter (fun path -> typenv |> Typenv.is_structure_module path) |> Seq.filter_map (fun path -> try let open Option in let addr = typenv |> Typenv.find_module_address path in let* pos = get_pos addr in return (path, pos) with Not_found -> None) |> List.of_seq |> Lwt_list.map_s (fun (path, pos) -> let%lwt obj' = Scene.get_field scene obj pos in Lwt.return ( Path.last path, new module_value ~scene ~typenv ~obj:obj' ~path () )) in let%lwt values = typenv |> Typenv.extract_values (Some lid) |> List.to_seq |> Seq.map (fun name -> Path.Pdot (path, name)) |> Seq.filter_map (fun path -> try let open Option in let valdesc = typenv |> Typenv.find_value path in let addr = typenv |> Typenv.find_value_address path in let* pos = get_pos addr in return (path, valdesc.val_type, pos) with Not_found -> None) |> List.of_seq |> Lwt_list.map_s (fun (path, typ, pos) -> let%lwt obj' = Scene.get_field scene obj pos in let%lwt value = adopt scene typenv obj' typ in Lwt.return (Path.last path, value)) in Lwt.return (modules @ values) end let adopter scene typenv obj typ = match (Ctype.repr typ).desc with | Tpackage (path, [], []) -> ( try let mty = typenv |> Typenv.find_modtype_expansion path in let mid = Ident.create_persistent (Printf.sprintf "M_%04x" (Float.to_int (Sys.time () *. 1e9) mod 0x10000)) in let typenv' = typenv |> Typenv.add_module mid Types.Mp_present mty in Lwt.return (Some (new module_value ~scene ~typenv:typenv' ~obj ~path:(Path.Pident mid) ())) with _ -> Lwt.return (Some unknown_module_value) ) | _ -> Lwt.return None
null
https://raw.githubusercontent.com/hackwaly/ocamlearlybird/165174e3cc749ba416ec7ebfb4b521e5fac744db/src/debugger/inspect/value_module.ml
ocaml
* * Copyright ( C ) 2021 * * 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 < / > . * Copyright (C) 2021 Yuxiang Wen * * 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 </>. *) open Ground open Value_basic let unknown_module_value = object inherit value method to_short_string = "«module»" end class module_value ~scene ~typenv ~obj ~path () = object inherit value method to_short_string = "«module»" method! num_named = -1 method! list_named = let lid = Util.Path.to_longident path in let get_pos addr = match addr with Env.Adot (_, pos) -> Some pos | _ -> None in let%lwt modules = typenv |> Typenv.extract_modules (Some lid) |> List.to_seq |> Seq.map (fun name -> Path.Pdot (path, name)) |> Seq.filter (fun path -> typenv |> Typenv.is_structure_module path) |> Seq.filter_map (fun path -> try let open Option in let addr = typenv |> Typenv.find_module_address path in let* pos = get_pos addr in return (path, pos) with Not_found -> None) |> List.of_seq |> Lwt_list.map_s (fun (path, pos) -> let%lwt obj' = Scene.get_field scene obj pos in Lwt.return ( Path.last path, new module_value ~scene ~typenv ~obj:obj' ~path () )) in let%lwt values = typenv |> Typenv.extract_values (Some lid) |> List.to_seq |> Seq.map (fun name -> Path.Pdot (path, name)) |> Seq.filter_map (fun path -> try let open Option in let valdesc = typenv |> Typenv.find_value path in let addr = typenv |> Typenv.find_value_address path in let* pos = get_pos addr in return (path, valdesc.val_type, pos) with Not_found -> None) |> List.of_seq |> Lwt_list.map_s (fun (path, typ, pos) -> let%lwt obj' = Scene.get_field scene obj pos in let%lwt value = adopt scene typenv obj' typ in Lwt.return (Path.last path, value)) in Lwt.return (modules @ values) end let adopter scene typenv obj typ = match (Ctype.repr typ).desc with | Tpackage (path, [], []) -> ( try let mty = typenv |> Typenv.find_modtype_expansion path in let mid = Ident.create_persistent (Printf.sprintf "M_%04x" (Float.to_int (Sys.time () *. 1e9) mod 0x10000)) in let typenv' = typenv |> Typenv.add_module mid Types.Mp_present mty in Lwt.return (Some (new module_value ~scene ~typenv:typenv' ~obj ~path:(Path.Pident mid) ())) with _ -> Lwt.return (Some unknown_module_value) ) | _ -> Lwt.return None
9e016098e101e37ebfa3ccb7a0af1ea21bfd1983d7e9bd3d3adad6208d7ba38d
stedolan/malfunction
malfunction_compiler.ml
open Lambda open Asttypes open Malfunction open Malfunction_parser open Malfunction_compat List.map , but guarantees left - to - right evaluation let rec lrmap f = function | [] -> [] | (x :: xs) -> let r = f x in r :: lrmap f xs let lprim p args = Lprim (p, args, loc_none) let lbind n exp body = let id = fresh n in Llet (Strict, Pgenval, id, exp, body (Lvar id)) Enforce left - to - right evaluation order by introducing ' let ' bindings let rec reorder = function | Mvar _ | Mnum _ | Mstring _ | Mglobal _ as t -> `Pure, t | Mlambda (params, body) -> `Pure, Mlambda (params, snd (reorder body)) | Mapply (f, xs) -> reorder_sub `Impure (fun ev -> let f = ev f in let xs = lrmap ev xs in Mapply (f, xs)) | Mlet (bindings, body) -> let bindings = reorder_bindings bindings in let _, body = reorder body in `Impure, Mlet (bindings, body) | Mswitch (e, cases) -> `Impure, Mswitch (snd (reorder e), List.map (fun (c, e) -> c, snd (reorder e)) cases) | Mnumop1(op, ty, t) -> reorder_sub `Pure (fun ev -> Mnumop1(op, ty, ev t)) | Mnumop2(op, ty, t1, t2) -> reorder_sub `Pure (fun ev -> let t1 = ev t1 in let t2 = ev t2 in Mnumop2(op, ty, t1, t2)) | Mconvert(src, dst, t) -> reorder_sub `Pure (fun ev -> Mconvert(src, dst, ev t)) | Mvecnew(ty, len, def) -> reorder_sub `Pure (fun ev -> let len = ev len in let def = ev def in Mvecnew(ty, len, def)) | Mvecget(ty, vec, idx) -> reorder_sub `Impure (fun ev -> let vec = ev vec in let idx = ev idx in Mvecget(ty, vec, idx)) | Mvecset(ty, vec, idx, v) -> reorder_sub `Impure (fun ev -> let vec = ev vec in let idx = ev idx in let v = ev v in Mvecset(ty, vec, idx, v)) | Mveclen(ty, vec) -> reorder_sub `Pure (fun ev -> let vec = ev vec in Mveclen(ty, vec)) | Mblock (n, ts) -> reorder_sub `Pure (fun ev -> Mblock(n, lrmap ev ts)) | Mfield (n, t) -> reorder_sub `Impure (fun ev -> Mfield (n, ev t)) | Mlazy e -> `Pure, Mlazy (snd (reorder e)) | Mforce e -> reorder_sub `Impure (fun ev -> Mforce (ev e)) and reorder_bindings bindings = bindings |> lrmap (function | `Unnamed t -> `Unnamed (snd (reorder t)) | `Named (v, t) -> `Named (v, snd (reorder t)) | `Recursive _ as ts -> ts (* must be functions *)) and reorder_sub p f = let bindings = ref [] in let r = f (fun e -> match reorder e with | `Pure, e -> e | `Impure, e -> let id = fresh "tmp" in bindings := (`Named (id, e)) :: !bindings; Mvar id) in match List.rev !bindings with | [] -> p, r | bindings -> `Impure, (Mlet (bindings, r)) module IntSwitch = struct (* Convert a list of possibly-overlapping intervals to a list of disjoint intervals *) type action = int (* lower numbers more important *) cases is a sorted list cases that begin lower appear first when two cases begin together , more important appears first cases that begin lower appear first when two cases begin together, more important appears first *) type case = int * int * action (* start position, end position, priority *) type cases = case list (* sorted by start position then priority *) (* the inactive list is a list of (endpoint, priority) pairs representing intervals that we are currently inside, but are overridden by a more important one. subsequent elements of the list have strictly higher priorities and strictly later endpoints *) type inactive = (int * action) list let rec insert_inactive max act = function | [] -> [(max, act)] | (max', act') as i' :: rest when act' < act -> this interval should appear before the new one i' :: (if max' <= max then (* new interval will never be active *) rest else insert_inactive max act rest) | (max', act') :: rest when max' <= max -> assert (act < act'); (* this interval will is contained by the new one, so never becomes active *) insert_inactive max act rest | ov -> (* new interval both more important and ends sooner, so prepend *) (max, act) :: ov type state = | Hole (* not currently in any interval *) | Interval of (* in an interval... *) int (* since this position *) * int (* until here *) * action (* with this action *) * inactive (* overriding these inactive intervals *) let state_suc = function | Hole -> failwith "state_suc of Hole undefined" | Interval (_, _, _, []) -> Hole | Interval (_, s_max, _, (max', act') :: rest) -> assert (s_max < max'); (* can compute s_max + 1 without overflow, because inactive interval ends later *) Interval (s_max + 1, max', act', rest) type result = case list (* may have duplicate actions, disjoint, sorted by position *) let rec to_disjoint_intervals c_state (c_cases : cases) : result = match c_state, c_cases with | Hole, [] -> [] | Hole, ((min, max, act) :: cases) -> to_disjoint_intervals (Interval (min, max, act, [])) cases | Interval (entered, max, act, _) as state, [] -> (entered, max, act) :: to_disjoint_intervals (state_suc state) [] | Interval (s_entered, s_max, s_act, _) as state, (((min, _max, _act) :: _) as cases) when s_max < min -> (* active interval ends before this case begins *) (s_entered, s_max, s_act) :: to_disjoint_intervals (state_suc state) cases (* below here, we can assume min <= i.s_max: active interval overlaps current case *) | Interval (s_entered, s_max, s_act, s_inactive), ((_min, max, act) :: cases) when s_act < act -> no change to active interval , but this case may become an inactive one to_disjoint_intervals (Interval (s_entered, s_max, s_act, insert_inactive max act s_inactive)) cases | Interval (s_entered, s_max, s_act, s_inactive), ((min, max, act) :: cases) -> (* new active interval, so old one becomes inactive *) assert (s_entered <= min); assert (min <= s_max); assert (act < s_act); let r = if s_entered = min then (* old interval was not active long enough to produce output *) [] else [(s_entered, min - 1, s_act)] in r @ to_disjoint_intervals (Interval (min, max, act, insert_inactive s_max s_act s_inactive)) cases (* unfortunately, this is not exposed from matching.ml, so copy-paste *) module Switcher = Switch.Make (struct type primitive = Lambda.primitive type loc = Location.t let _unused : loc option = None let eqint = Pintcomp Ceq let neint = pintcomp_cne let leint = Pintcomp Cle let ltint = Pintcomp Clt let geint = Pintcomp Cge let gtint = Pintcomp Cgt type arg = Lambda.lambda type test = Lambda.lambda type act = Lambda.lambda let make_is_nonzero arg = (* *) Lprim (pintcomp_cne, [arg; Lconst (Const_base (Const_int 0))], loc_none) let arg_as_test (arg : arg) : test = arg (* these are unused on some OCaml versions *) let _ = make_is_nonzero, arg_as_test let make_prim p args = lprim p args let make_offset arg n = match n with | 0 -> arg | _ -> lprim (Poffsetint n) [arg] let bind arg body = let newvar,newarg = match arg with | Lvar v -> v,arg | _ -> let newvar = fresh "switcher" in newvar,Lvar newvar in bind Alias newvar arg (body newarg) let make_const i = Lconst (Const_base (Const_int i)) let make_isout h arg = lprim Pisout [h ; arg] let make_isin h arg = lprim Pnot [make_isout h arg] let make_if cond ifso ifnot = Lifthenelse (cond, ifso, ifnot) let make_switch arg cases acts = let l = ref [] in for i = Array.length cases-1 downto 0 do l := (i,acts.(cases.(i))) :: !l done ; lswitch arg {sw_numconsts = Array.length cases ; sw_consts = !l ; sw_numblocks = 0 ; sw_blocks = [] ; sw_failaction = None} let make_switch = make_switch_loc make_switch let make_catch d = match d with | Lstaticraise (i, []) -> i, (fun e -> e) | _ -> let i = next_raise_count () in i, fun e -> Lstaticcatch(e, (i, []), d) let make_exit i = Lstaticraise (i,[]) end) let compile_int_switch scr overlapped_cases = assert (overlapped_cases <> []); let actions = Array.of_list (overlapped_cases |> List.map snd) in let cases = overlapped_cases |> List.mapi (fun idx (`Intrange (min, max), _) -> (min, max, idx)) |> List.stable_sort (fun (min, _max, _idx) (min', _max', _idx') -> compare min min') |> to_disjoint_intervals Hole in let occurrences = Array.make (Array.length actions) 0 in let rec count_occurrences = function | [] -> assert false | [(_min, _max, act)] -> occurrences.(act) <- occurrences.(act) + 1 | (_min, max, act) :: (((min', _max', _act') :: _) as rest) -> occurrences.(act) <- occurrences.(act) + 1; begin if max + 1 <> min' then (* When the interval list contains a hole, jump tables generated by switch.ml may contain spurious references to action 0. See PR#6805 *) occurrences.(0) <- occurrences.(0) + 1 end; count_occurrences rest in count_occurrences cases; let open Switch in let store (*: Lambda.lambda t_store*) = { act_get = (fun () -> Array.copy actions); act_get_shared = (fun () -> actions |> Array.mapi (fun i act -> if occurrences.(i) > 1 then Shared act else Single act)); act_store = (fun _ -> failwith "store unimplemented"); act_store_shared = (fun _ -> failwith "store_shared unimplemented") } in let cases = Array.of_list cases in let (low, _, _) = cases.(0) and (_, high, _) = cases.(Array.length cases - 1) in with_loc Switcher.zyva Location.none (low, high) scr cases store end type global_value = | Glob_val of lambda | Glob_prim of Primitive.description let lookup env v = let open Types in let open Primitive in let rec stdlib_compat_hack : Longident.t -> Longident.t = function | Lident "Stdlib" -> Lident (Malfunction_compat.stdlib_module_name) | Ldot (id, s) -> Ldot (stdlib_compat_hack id, s) | l -> l in let v = stdlib_compat_hack v in let (path, descr) = try Env.lookup_value ~loc:Location.none (*parse_loc loc*) v env with Not_found -> let rec try_stdlib = let open Longident in function | Lident s -> Ldot (Lident "Stdlib", s) | Ldot (id, s) -> Ldot (try_stdlib id, s) | Lapply _ as l -> l in try Env.lookup_value ~loc:Location.none (try_stdlib v) env with Not_found -> failwith ("global not found: " ^ String.concat "." (Longident.flatten v)) in match descr.val_kind with | Val_reg -> Glob_val (transl_value_path loc_none env path) | Val_prim(p) -> let p = match p.prim_name with | "%equal" -> Primitive.simple ~name:"caml_equal" ~arity:2 ~alloc:true | "%compare" -> Primitive.simple ~name:"caml_compare" ~arity:2 ~alloc:true | s when s.[0] = '%' -> failwith ("unimplemented primitive " ^ p.prim_name); | _ -> p in Glob_prim p | _ -> failwith "unexpected kind of value" let builtin env path args = let p = match path with | path1 :: pathrest -> List.fold_left (fun id s -> Longident.Ldot (id, s)) (Longident.Lident path1) pathrest | _ -> assert false in match lookup env p with | Glob_val v -> lapply v args | Glob_prim p -> assert (p.prim_arity = List.length args); lprim (Pccall p) args let global_to_lambda = function | Glob_val v -> v | Glob_prim p -> Eta - expand this primitive . See translprim.ml . let rec make_params n = if n <= 0 then [] else fresh "prim" :: make_params (n-1) in let params = make_params p.prim_arity in let body = lprim (Pccall p) (List.map (fun x -> Lvar x) params) in lfunction params body let rec to_lambda env = function | Mvar v -> Lvar v | Mlambda (params, e) -> lfunction params (to_lambda env e) | Mapply (fn, args) -> let ap_func fn = lapply fn (List.map (to_lambda env) args) in (match fn with | Mglobal v -> (match lookup env v with | Glob_prim p when p.prim_arity = List.length args -> lprim (Pccall p) (List.map (to_lambda env) args) | g -> ap_func (global_to_lambda g)) | fn -> ap_func (to_lambda env fn)) | Mlet (bindings, body) -> bindings_to_lambda env bindings (to_lambda env body) | Mnum (`Int n) -> Lconst (Const_base (Const_int n)) | Mnum (`Int32 n) -> Lconst (Const_base (Const_int32 n)) | Mnum (`Int64 n) -> Lconst (Const_base (Const_int64 n)) | Mnum (`Bigint n) -> (match Z.to_int n with | n' -> assert (Obj.repr n = Obj.repr n'); Lconst (Const_base (Const_int n')) | exception Z.Overflow -> builtin env ["Z"; "of_string"] [Lconst (Const_immstring (Z.to_string n))]) | Mnum (`Float64 f) -> Lconst (Const_base (Const_float (string_of_float f))) | Mstring s -> Lconst (Const_immstring s) | Mglobal v -> global_to_lambda (lookup env v) | Mswitch (scr, cases) -> let scr = to_lambda env scr in let rec flatten acc = function | ([], _) :: _ -> assert false | ([sel], e) :: rest -> flatten ((sel, to_lambda env e) :: acc) rest | (sels, e) :: rest -> let i = next_raise_count () in let cases = List.map (fun s -> s, Lstaticraise(i, [])) sels in Lstaticcatch (flatten (cases @ acc) rest, (i, []), to_lambda env e) | [] -> let rec partition (ints, tags, deftag) = function | [] -> (List.rev ints, List.rev tags, deftag) | (`Tag _, _) as c :: cases -> partition (ints, c :: tags, deftag) cases | (`Deftag, _) as c :: cases -> partition (ints, tags, Some c) cases | (`Intrange _, _) as c :: cases -> partition (c :: ints, tags, deftag) cases in let (intcases, tagcases, deftag) = partition ([],[],None) (List.rev acc) in lbind "switch" scr (fun scr -> let tagswitch = match tagcases, deftag with | [], None -> None | [_,e], None | [], Some (_, e) -> Some e | tags, def -> let numtags = match def with | Some _ -> (max_tag :> int) | None -> 1 + List.fold_left (fun s (`Tag i, _) -> max s (i :> int)) (-1) tags in Some (lswitch scr { sw_numconsts = 0; sw_consts = []; sw_numblocks = numtags; sw_blocks = List.map (fun (`Tag i, e) -> i, e) tags; sw_failaction = match def with None -> None | Some (`Deftag,e) -> Some e }) in let intswitch = match intcases with | [] -> None | [_,e] -> Some e | ints -> Some (IntSwitch.compile_int_switch scr ints) in match intswitch, tagswitch with | None, None -> assert false | None, Some e | Some e, None -> e | Some eint, Some etag -> Lifthenelse (lprim Pisint [scr], eint, etag)) in (match cases with | [[`Intrange (0, 0)], ezero; _, enonzero] | [_, enonzero; [`Intrange (0, 0)], ezero] -> special case comparisons with zero Lifthenelse(scr, to_lambda env enonzero, to_lambda env ezero) | cases -> flatten [] cases) | Mnumop1 (op, ty, e) -> let e = to_lambda env e in let ones32 = Const_base (Asttypes.Const_int32 (Int32.of_int (-1))) in let ones64 = Const_base (Asttypes.Const_int64 (Int64.of_int (-1))) in let code = match op, ty with | `Neg, `Int -> lprim Pnegint [e] | `Neg, `Int32 -> lprim (Pnegbint Pint32) [e] | `Neg, `Int64 -> lprim (Pnegbint Pint64) [e] | `Neg, `Bigint -> builtin env ["Z"; "neg"] [e] | `Neg, `Float64 -> lprim Pnegfloat [e] | `Not, `Int -> lprim Pnot [e] | `Not, `Int32 -> lprim (Pxorbint Pint32) [e; Lconst ones32] | `Not, `Int64 -> lprim (Pxorbint Pint64) [e; Lconst ones64] | `Not, `Bigint -> builtin env ["Z"; "lognot"] [e] | `Not, `Float64 -> assert false in code | Mnumop2 (op, ((`Int|`Int32|`Int64) as ty), e1, e2) -> let e1 = to_lambda env e1 in let e2 = to_lambda env e2 in let prim = match ty with | `Int -> (match op with `Add -> Paddint | `Sub -> Psubint | `Mul -> Pmulint | `Div -> Pdivint Safe | `Mod -> Pmodint Safe | `And -> Pandint | `Or -> Porint | `Xor -> Pxorint | `Lsl -> Plslint | `Lsr -> Plsrint | `Asr -> Pasrint | `Lt -> Pintcomp Clt | `Gt -> Pintcomp Cgt | `Lte -> Pintcomp Cle | `Gte -> Pintcomp Cge | `Eq -> Pintcomp Ceq) | (`Int32 | `Int64) as ty -> let t = match ty with `Int32 -> Pint32 | `Int64 -> Pint64 in (match op with `Add -> Paddbint t | `Sub -> Psubbint t | `Mul -> Pmulbint t | `Div -> Pdivbint { size = t; is_safe = Safe } | `Mod -> Pmodbint { size = t; is_safe = Safe } | `And -> Pandbint t | `Or -> Porbint t | `Xor -> Pxorbint t | `Lsl -> Plslbint t | `Lsr -> Plsrbint t | `Asr -> Pasrbint t | `Lt -> Pbintcomp (t, Clt) | `Gt -> Pbintcomp (t, Cgt) | `Lte -> Pbintcomp (t, Cle) | `Gte -> Pbintcomp (t, Cge) | `Eq -> Pbintcomp (t, Ceq)) in lprim prim [e1; e2] | Mnumop2 (op, `Bigint, e1, e2) -> let e1 = to_lambda env e1 in let e2 = to_lambda env e2 in let fn = match op with | `Add -> "add" | `Sub -> "sub" | `Mul -> "mul" | `Div -> "div" | `Mod -> "rem" | `And -> "logand" | `Or -> "logor" | `Xor -> "logxor" | `Lsl -> "shift_left" | `Lsr -> "shift_right" | `Asr -> "shift_right" | `Lt -> "lt" | `Gt -> "gt" | `Lte -> "leq" | `Gte -> "geq" | `Eq -> "equal" in builtin env ["Z"; fn] [e1; e2] | Mnumop2 (op, `Float64, e1, e2) -> let e1 = to_lambda env e1 in let e2 = to_lambda env e2 in begin match op with | #binary_bitwise_op -> assert false | `Add -> lprim Paddfloat [e1; e2] | `Sub -> lprim Psubfloat [e1; e2] | `Mul -> lprim Pmulfloat [e1; e2] | `Div -> lprim Pdivfloat [e1; e2] | `Mod -> builtin env [stdlib_module_name; "mod_float"] [e1; e2] | #binary_comparison as op -> let cmp = cmp_to_float_comparison op in lprim (Pfloatcomp cmp) [e1; e2] end | Mconvert (src, dst, e) -> let e = to_lambda env e in begin match src, dst with | `Bigint, `Bigint | `Int, `Int | `Int32, `Int32 | `Int64, `Int64 | `Float64, `Float64 -> e | `Bigint, ((`Int|`Int32|`Int64) as dst) -> Zarith raises exceptions on overflow , but we truncate conversions . Not fast . let width = match dst with | `Int -> Sys.word_size - 1 | `Int32 -> 32 | `Int64 -> 64 in let range = Z.(shift_left (of_int 1) width) in let truncated = lbind "range" (builtin env ["Z"; "of_string"] [Lconst (Const_immstring (Z.to_string range))]) (fun range -> lbind "masked" (builtin env ["Z"; "logand"] [e; builtin env ["Z"; "sub"] [range; Lconst (Const_base (Const_int 1))]]) (fun masked -> Lifthenelse (builtin env ["Z"; "testbit"] [masked; Lconst (Const_base (Const_int (width - 1)))], builtin env ["Z"; "sub"] [masked; range], masked))) in let fn = match dst with | `Int -> "to_int" | `Int32 -> "to_int32" | `Int64 -> "to_int64" in builtin env ["Z"; fn] [truncated] | ((`Int|`Int32|`Int64) as src), `Bigint -> let fn = match src with | `Int -> "of_int" | `Int32 -> "of_int32" | `Int64 -> "of_int64" in builtin env ["Z"; fn] [e] | `Int, `Int32 -> lprim (Pbintofint Pint32) [e] | `Int, `Int64 -> lprim (Pbintofint Pint64) [e] | `Int32, `Int -> lprim (Pintofbint Pint32) [e] | `Int64, `Int -> lprim (Pintofbint Pint64) [e] | `Int32, `Int64 -> lprim (Pcvtbint(Pint32, Pint64)) [e] | `Int64, `Int32 -> lprim (Pcvtbint(Pint64, Pint32)) [e] | `Int, `Float64 -> lprim Pfloatofint [e] | `Int32, `Float64 -> builtin env ["Int32"; "to_float"] [e] | `Int64, `Float64 -> builtin env ["Int64"; "to_float"] [e] | `Bigint, `Float64 -> builtin env ["Z"; "to_float"] [e] (* FIXME: error handling on overflow *) | `Float64, `Int -> lprim Pintoffloat [e] | `Float64, `Int32 -> builtin env ["Int32"; "of_float"] [e] | `Float64, `Int64 -> builtin env ["Int64"; "of_float"] [e] | `Float64, `Bigint -> builtin env ["Z"; "of_float"] [e] end | Mvecnew (`Array, len, def) -> builtin env ["Array"; "make"] [to_lambda env len; to_lambda env def] | Mvecnew (`Bytevec, len, def) -> builtin env ["String"; "make"] [to_lambda env len; to_lambda env def] | Mvecget (ty, vec, idx) -> let prim = match ty with | `Array -> Parrayrefs Paddrarray | `Bytevec -> Pbytesrefs (* | `Floatvec -> Parrayrefs Pfloatarray *) in lprim prim [to_lambda env vec; to_lambda env idx] | Mvecset (ty, vec, idx, v) -> let prim = match ty with | `Array -> Parraysets Paddrarray | `Bytevec -> Pbytessets (* | `Floatvec -> Parraysets Pfloatarray *) in lprim prim [to_lambda env vec; to_lambda env idx; to_lambda env v] | Mveclen (ty, vec) -> let prim = match ty with | `Array -> Parraylength Paddrarray | `Bytevec -> Pbyteslength | ` Floatvec - > lprim prim [to_lambda env vec] | Mblock (tag, vals) -> lprim (Pmakeblock (tag, Immutable, None)) (List.map (to_lambda env) vals) | Mfield (idx, e) -> lprim (Pfield(idx)) [to_lambda env e] | Mlazy e -> let fn = lfunction [fresh "param"] (to_lambda env e) in lprim (Pmakeblock (Config.lazy_tag, Mutable, None)) [fn] | Mforce e -> Matching.inline_lazy_force (to_lambda env e) loc_none and bindings_to_lambda env bindings body = List.fold_right (fun b rest -> match b with | `Unnamed e -> Lsequence (to_lambda env e, rest) | `Named (n, e) -> Llet (Strict, Pgenval, n, to_lambda env e, rest) | `Recursive bs -> Lletrec (List.map (fun (n, e) -> (n, to_lambda env e)) bs, rest)) bindings body let setup_options options = Clflags.native_code := true; Clflags.flambda_invariant_checks := true; Clflags.nopervasives := false; Clflags.dump_lambda := false; Clflags.dump_cmm := false; Clflags.keep_asm_file := false; Clflags.include_dirs := [Findlib.package_directory "zarith"]; Clflags.inlining_report := false; Clflags.dlcode := true; Clflags.shared := false; Clflags.( default_simplify_rounds := 2; use_inlining_arguments_set o2_arguments; use_inlining_arguments_set ~round:0 o1_arguments); (* FIXME: should we use classic_arguments for non-flambda builds? *) Hack : disable the " no cmx " warning for zarith let _ = Warnings.parse_options false "-58" in assert (not (Warnings.is_active (Warnings.No_cmx_file "asdf"))); (options |> List.iter @@ function | `Verbose -> Clflags.dump_lambda := true; Clflags.dump_cmm := true; (* If anyone wants to keep these, there should probably be another option for where to put them. (rather than leaving stale temporary directories around) Clflags.keep_asm_file := true; Clflags.inlining_report := true *) | `Shared -> Clflags.shared := true); Compenv.(readenv Format.std_formatter (Before_compile "malfunction")); compmisc_init_path () let module_to_lambda ?options ~module_name:_ ~module_id (Mmod (bindings, exports)) = setup_options (match options with Some o -> o | None -> []); let print_if flag printer arg = if !flag then Format.printf "%a@." printer arg; arg in let env = Compmisc.initial_env () in let module_size, code = let bindings = reorder_bindings bindings in let exports = List.map (fun e -> snd (reorder e)) exports in if Config.flambda then List.length exports, bindings_to_lambda env bindings (lprim (Pmakeblock (0, Immutable, None)) (List.map (to_lambda env) exports)) else begin FIXME let num_exports = List.length exports in Compile all of the bindings , store at positions num_exports + i , then compile the exports . See Translmod.transl_store_gen . then compile the exports. See Translmod.transl_store_gen. *) let module_length = ref (-1) in let mod_store pos e = Lprim (Psetfield (pos, Pointer, root_initialization), [Lprim (Pgetglobal module_id, [], loc); e], loc) in let mod_load pos = Lprim (Pfield pos, [Lprim (Pgetglobal module_id, [], loc)], loc) in let transl_exports subst = let exps = List.mapi (fun i e -> mod_store i (Subst.apply subst (to_lambda env e))) exports in List.fold_right (fun x xs -> Lsequence (x, xs)) exps (Lconst Lambda.const_unit) in let rec transl_toplevel_bindings pos subst = function | `Unnamed e :: rest -> Lsequence (Subst.apply subst (to_lambda env e), transl_toplevel_bindings pos subst rest) | `Named (n, e) :: rest -> let lam = Llet (Strict, Pgenval, n, Subst.apply subst (to_lambda env e), mod_store pos (Lvar n)) in Lsequence (lam, transl_toplevel_bindings (pos + 1) (Subst.add n (mod_load pos) subst) rest) | `Recursive bs :: rest -> let ids = List.map fst bs in let stores = ids |> List.mapi (fun i n -> mod_store (pos + i) (Lvar n)) in let stores = List.fold_right (fun x xs -> Lsequence (x, xs)) stores (Lconst Lambda.const_unit) in let lam = Lletrec (bs |> List.map (fun (n, e) -> (n, Subst.apply subst (to_lambda env e))), stores) in let id_load = ids |> List.mapi (fun i n -> (n, mod_load (pos + i))) in let subst = List.fold_left (fun subst (n, l) -> Subst.add n l subst) subst id_load in Lsequence (lam, transl_toplevel_bindings (pos + List.length ids) subst rest) | [] -> module_length := pos; transl_exports subst in let r = transl_toplevel_bindings num_exports Subst.empty bindings in !module_length, r end in let lambda = code |> print_if Clflags.dump_rawlambda Printlambda.lambda |> simplify_lambda |> print_if Clflags.dump_lambda Printlambda.lambda in (module_size, lambda) let backend = (module struct include Compilenv include Import_approx include Arch let max_sensible_number_of_arguments = Proc.max_arguments_for_tailcalls - 1 end : Backend_intf.S) type outfiles = { objfile : string; cmxfile : string; cmifile : string option } let delete_temps { objfile; cmxfile; cmifile } = Misc.remove_file objfile; Misc.remove_file cmxfile; match cmifile with Some f -> Misc.remove_file f | None -> () type options = [`Verbose | `Shared] list let lambda_to_cmx ?(options=[]) ~filename ~prefixname ~module_name ~module_id lmod = let ppf = Format.std_formatter in let outfiles = ref { cmxfile = prefixname ^ ".cmx"; objfile = prefixname ^ Config.ext_obj; cmifile = None } in setup_options options; try let cmi = module_name ^ ".cmi" in Env.set_unit_name module_name; with_source_provenance filename (Compilenv.reset ?packname:!Clflags.for_package module_name); ignore (match load_path_find cmi with | file -> Env.read_signature module_name file | exception Not_found -> let chop_ext = Misc.chop_extensions in let mlifile = chop_ext filename ^ !Config.interface_suffix in if Sys.file_exists mlifile then Typemod.(raise(Error(Location.in_file filename, Env.empty, Interface_not_compiled cmi))) else hackily generate an empty cmi file let cmifile = String.uncapitalize_ascii cmi in outfiles := { !outfiles with cmifile = Some cmifile }; let mlifile = String.uncapitalize_ascii (module_name ^ ".mli") in let ch = open_out mlifile in output_string ch "(* autogenerated mli for malfunction *)\n"; close_out ch; ignore (Sys.command ("ocamlc -c " ^ mlifile)); Misc.remove_file mlifile; if not (Sys.file_exists cmifile) then failwith "Failed to generate empty cmi file"; Env.read_signature module_name cmifile); FIXME : may need to add modules referenced only by " external " to this . See Translmod.primitive_declarations and its use in . See Translmod.primitive_declarations and its use in Asmgen. *) (* FIXME: Translprim.get_used_primitives (see translmod.ml)? *) (* FIXME: Translmod.required_globals? Env.reset_required_globals? Should this be in to_lambda? *) let required_globals = Ident.Set.of_list (Env.get_required_globals ()) in compile_implementation ~prefixname ~filename ~module_id ~backend ~required_globals ~ppf lmod; Compilenv.save_unit_info !outfiles.cmxfile; Warnings.check_fatal (); !outfiles with e -> delete_temps !outfiles; raise e let compile_module ?(options=[]) ~filename modl = FIXME : do we really want to go through Clflags here ? See Compenv.output_prefix let prefixname = Compenv.output_prefix filename in let module_name = prefixname |> Filename.basename |> Filename.remove_extension |> String.capitalize_ascii in if not (Compenv.is_unit_name module_name) then raise (Invalid_argument ("Invalid module name " ^ module_name)); let module_id = Ident.create_persistent module_name in modl |> module_to_lambda ~module_name ~module_id ~options |> lambda_to_cmx ~options ~filename ~prefixname ~module_name ~module_id let compile_cmx ?(options=[]) filename = let lexbuf = Lexing.from_channel (open_in filename) in Lexing.(lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = filename }); let modl = Malfunction_parser.read_module lexbuf in compile_module ~options ~filename modl (* copied from opttoploop.ml *) external ndl_run_toplevel: string -> string -> (Obj.t, string) result = "caml_natdynlink_run_toplevel" external ndl_loadsym: string -> Obj.t = "caml_natdynlink_loadsym" let code_id = ref 0 let compile_and_load ?(options : options =[]) e = if not Dynlink.is_native then failwith "Loading malfunction values works only in native code"; let tmpdir = Filename.temp_file "malfunction" ".tmp" in (* more than a little horrible *) Unix.unlink tmpdir; Unix.mkdir tmpdir 0o700; let old_cwd = Sys.getcwd () in Sys.chdir tmpdir; incr code_id; let modname = "Malfunction_Code_" ^ string_of_int (!code_id) in let modname_uncap = String.uncapitalize_ascii modname in let options = `Shared :: options in let tmpfiles = compile_module ~options ~filename:modname_uncap (Mmod ([], [e])) in setup_options options; (* rescan load path *) begin try with_ppf_dump Format.err_formatter Asmlink.link_shared [tmpfiles.cmxfile] (modname_uncap ^ ".cmxs") with | Asmlink.Error e -> let msg = Format.asprintf "Asmlink error: %a" Asmlink.report_error e in failwith msg end; let cmxs = tmpdir ^ Filename.dir_sep ^ modname_uncap ^ ".cmxs" in (match ndl_run_toplevel cmxs modname with | Ok _ -> () | Error s -> failwith ("loading failed: " ^ s)); let res = Obj.field (ndl_loadsym (Compilenv.symbol_for_global (Ident.create_persistent modname))) 0 in delete_temps tmpfiles; Misc.remove_file cmxs; Sys.chdir old_cwd; Unix.rmdir tmpdir; res let link_executable output tmpfiles = (* urgh *) Sys.command (Printf.sprintf "ocamlfind ocamlopt -package zarith zarith.cmxa '%s' -o '%s'" tmpfiles.cmxfile output)
null
https://raw.githubusercontent.com/stedolan/malfunction/69ec0755d540e0b44c40475d96b57ac27aaa19d0/src/malfunction_compiler.ml
ocaml
must be functions Convert a list of possibly-overlapping intervals to a list of disjoint intervals lower numbers more important start position, end position, priority sorted by start position then priority the inactive list is a list of (endpoint, priority) pairs representing intervals that we are currently inside, but are overridden by a more important one. subsequent elements of the list have strictly higher priorities and strictly later endpoints new interval will never be active this interval will is contained by the new one, so never becomes active new interval both more important and ends sooner, so prepend not currently in any interval in an interval... since this position until here with this action overriding these inactive intervals can compute s_max + 1 without overflow, because inactive interval ends later may have duplicate actions, disjoint, sorted by position active interval ends before this case begins below here, we can assume min <= i.s_max: active interval overlaps current case new active interval, so old one becomes inactive old interval was not active long enough to produce output unfortunately, this is not exposed from matching.ml, so copy-paste these are unused on some OCaml versions When the interval list contains a hole, jump tables generated by switch.ml may contain spurious references to action 0. See PR#6805 : Lambda.lambda t_store parse_loc loc FIXME: error handling on overflow | `Floatvec -> Parrayrefs Pfloatarray | `Floatvec -> Parraysets Pfloatarray FIXME: should we use classic_arguments for non-flambda builds? If anyone wants to keep these, there should probably be another option for where to put them. (rather than leaving stale temporary directories around) Clflags.keep_asm_file := true; Clflags.inlining_report := true FIXME: Translprim.get_used_primitives (see translmod.ml)? FIXME: Translmod.required_globals? Env.reset_required_globals? Should this be in to_lambda? copied from opttoploop.ml more than a little horrible rescan load path urgh
open Lambda open Asttypes open Malfunction open Malfunction_parser open Malfunction_compat List.map , but guarantees left - to - right evaluation let rec lrmap f = function | [] -> [] | (x :: xs) -> let r = f x in r :: lrmap f xs let lprim p args = Lprim (p, args, loc_none) let lbind n exp body = let id = fresh n in Llet (Strict, Pgenval, id, exp, body (Lvar id)) Enforce left - to - right evaluation order by introducing ' let ' bindings let rec reorder = function | Mvar _ | Mnum _ | Mstring _ | Mglobal _ as t -> `Pure, t | Mlambda (params, body) -> `Pure, Mlambda (params, snd (reorder body)) | Mapply (f, xs) -> reorder_sub `Impure (fun ev -> let f = ev f in let xs = lrmap ev xs in Mapply (f, xs)) | Mlet (bindings, body) -> let bindings = reorder_bindings bindings in let _, body = reorder body in `Impure, Mlet (bindings, body) | Mswitch (e, cases) -> `Impure, Mswitch (snd (reorder e), List.map (fun (c, e) -> c, snd (reorder e)) cases) | Mnumop1(op, ty, t) -> reorder_sub `Pure (fun ev -> Mnumop1(op, ty, ev t)) | Mnumop2(op, ty, t1, t2) -> reorder_sub `Pure (fun ev -> let t1 = ev t1 in let t2 = ev t2 in Mnumop2(op, ty, t1, t2)) | Mconvert(src, dst, t) -> reorder_sub `Pure (fun ev -> Mconvert(src, dst, ev t)) | Mvecnew(ty, len, def) -> reorder_sub `Pure (fun ev -> let len = ev len in let def = ev def in Mvecnew(ty, len, def)) | Mvecget(ty, vec, idx) -> reorder_sub `Impure (fun ev -> let vec = ev vec in let idx = ev idx in Mvecget(ty, vec, idx)) | Mvecset(ty, vec, idx, v) -> reorder_sub `Impure (fun ev -> let vec = ev vec in let idx = ev idx in let v = ev v in Mvecset(ty, vec, idx, v)) | Mveclen(ty, vec) -> reorder_sub `Pure (fun ev -> let vec = ev vec in Mveclen(ty, vec)) | Mblock (n, ts) -> reorder_sub `Pure (fun ev -> Mblock(n, lrmap ev ts)) | Mfield (n, t) -> reorder_sub `Impure (fun ev -> Mfield (n, ev t)) | Mlazy e -> `Pure, Mlazy (snd (reorder e)) | Mforce e -> reorder_sub `Impure (fun ev -> Mforce (ev e)) and reorder_bindings bindings = bindings |> lrmap (function | `Unnamed t -> `Unnamed (snd (reorder t)) | `Named (v, t) -> `Named (v, snd (reorder t)) and reorder_sub p f = let bindings = ref [] in let r = f (fun e -> match reorder e with | `Pure, e -> e | `Impure, e -> let id = fresh "tmp" in bindings := (`Named (id, e)) :: !bindings; Mvar id) in match List.rev !bindings with | [] -> p, r | bindings -> `Impure, (Mlet (bindings, r)) module IntSwitch = struct cases is a sorted list cases that begin lower appear first when two cases begin together , more important appears first cases that begin lower appear first when two cases begin together, more important appears first *) type inactive = (int * action) list let rec insert_inactive max act = function | [] -> [(max, act)] | (max', act') as i' :: rest when act' < act -> this interval should appear before the new one i' :: (if max' <= max then rest else insert_inactive max act rest) | (max', act') :: rest when max' <= max -> assert (act < act'); insert_inactive max act rest | ov -> (max, act) :: ov type state = let state_suc = function | Hole -> failwith "state_suc of Hole undefined" | Interval (_, _, _, []) -> Hole | Interval (_, s_max, _, (max', act') :: rest) -> assert (s_max < max'); Interval (s_max + 1, max', act', rest) let rec to_disjoint_intervals c_state (c_cases : cases) : result = match c_state, c_cases with | Hole, [] -> [] | Hole, ((min, max, act) :: cases) -> to_disjoint_intervals (Interval (min, max, act, [])) cases | Interval (entered, max, act, _) as state, [] -> (entered, max, act) :: to_disjoint_intervals (state_suc state) [] | Interval (s_entered, s_max, s_act, _) as state, (((min, _max, _act) :: _) as cases) when s_max < min -> (s_entered, s_max, s_act) :: to_disjoint_intervals (state_suc state) cases | Interval (s_entered, s_max, s_act, s_inactive), ((_min, max, act) :: cases) when s_act < act -> no change to active interval , but this case may become an inactive one to_disjoint_intervals (Interval (s_entered, s_max, s_act, insert_inactive max act s_inactive)) cases | Interval (s_entered, s_max, s_act, s_inactive), ((min, max, act) :: cases) -> assert (s_entered <= min); assert (min <= s_max); assert (act < s_act); let r = if s_entered = min then [] else [(s_entered, min - 1, s_act)] in r @ to_disjoint_intervals (Interval (min, max, act, insert_inactive s_max s_act s_inactive)) cases module Switcher = Switch.Make (struct type primitive = Lambda.primitive type loc = Location.t let _unused : loc option = None let eqint = Pintcomp Ceq let neint = pintcomp_cne let leint = Pintcomp Cle let ltint = Pintcomp Clt let geint = Pintcomp Cge let gtint = Pintcomp Cgt type arg = Lambda.lambda type test = Lambda.lambda type act = Lambda.lambda let make_is_nonzero arg = Lprim (pintcomp_cne, [arg; Lconst (Const_base (Const_int 0))], loc_none) let arg_as_test (arg : arg) : test = arg let _ = make_is_nonzero, arg_as_test let make_prim p args = lprim p args let make_offset arg n = match n with | 0 -> arg | _ -> lprim (Poffsetint n) [arg] let bind arg body = let newvar,newarg = match arg with | Lvar v -> v,arg | _ -> let newvar = fresh "switcher" in newvar,Lvar newvar in bind Alias newvar arg (body newarg) let make_const i = Lconst (Const_base (Const_int i)) let make_isout h arg = lprim Pisout [h ; arg] let make_isin h arg = lprim Pnot [make_isout h arg] let make_if cond ifso ifnot = Lifthenelse (cond, ifso, ifnot) let make_switch arg cases acts = let l = ref [] in for i = Array.length cases-1 downto 0 do l := (i,acts.(cases.(i))) :: !l done ; lswitch arg {sw_numconsts = Array.length cases ; sw_consts = !l ; sw_numblocks = 0 ; sw_blocks = [] ; sw_failaction = None} let make_switch = make_switch_loc make_switch let make_catch d = match d with | Lstaticraise (i, []) -> i, (fun e -> e) | _ -> let i = next_raise_count () in i, fun e -> Lstaticcatch(e, (i, []), d) let make_exit i = Lstaticraise (i,[]) end) let compile_int_switch scr overlapped_cases = assert (overlapped_cases <> []); let actions = Array.of_list (overlapped_cases |> List.map snd) in let cases = overlapped_cases |> List.mapi (fun idx (`Intrange (min, max), _) -> (min, max, idx)) |> List.stable_sort (fun (min, _max, _idx) (min', _max', _idx') -> compare min min') |> to_disjoint_intervals Hole in let occurrences = Array.make (Array.length actions) 0 in let rec count_occurrences = function | [] -> assert false | [(_min, _max, act)] -> occurrences.(act) <- occurrences.(act) + 1 | (_min, max, act) :: (((min', _max', _act') :: _) as rest) -> occurrences.(act) <- occurrences.(act) + 1; begin if max + 1 <> min' then occurrences.(0) <- occurrences.(0) + 1 end; count_occurrences rest in count_occurrences cases; let open Switch in { act_get = (fun () -> Array.copy actions); act_get_shared = (fun () -> actions |> Array.mapi (fun i act -> if occurrences.(i) > 1 then Shared act else Single act)); act_store = (fun _ -> failwith "store unimplemented"); act_store_shared = (fun _ -> failwith "store_shared unimplemented") } in let cases = Array.of_list cases in let (low, _, _) = cases.(0) and (_, high, _) = cases.(Array.length cases - 1) in with_loc Switcher.zyva Location.none (low, high) scr cases store end type global_value = | Glob_val of lambda | Glob_prim of Primitive.description let lookup env v = let open Types in let open Primitive in let rec stdlib_compat_hack : Longident.t -> Longident.t = function | Lident "Stdlib" -> Lident (Malfunction_compat.stdlib_module_name) | Ldot (id, s) -> Ldot (stdlib_compat_hack id, s) | l -> l in let v = stdlib_compat_hack v in let (path, descr) = try with Not_found -> let rec try_stdlib = let open Longident in function | Lident s -> Ldot (Lident "Stdlib", s) | Ldot (id, s) -> Ldot (try_stdlib id, s) | Lapply _ as l -> l in try Env.lookup_value ~loc:Location.none (try_stdlib v) env with Not_found -> failwith ("global not found: " ^ String.concat "." (Longident.flatten v)) in match descr.val_kind with | Val_reg -> Glob_val (transl_value_path loc_none env path) | Val_prim(p) -> let p = match p.prim_name with | "%equal" -> Primitive.simple ~name:"caml_equal" ~arity:2 ~alloc:true | "%compare" -> Primitive.simple ~name:"caml_compare" ~arity:2 ~alloc:true | s when s.[0] = '%' -> failwith ("unimplemented primitive " ^ p.prim_name); | _ -> p in Glob_prim p | _ -> failwith "unexpected kind of value" let builtin env path args = let p = match path with | path1 :: pathrest -> List.fold_left (fun id s -> Longident.Ldot (id, s)) (Longident.Lident path1) pathrest | _ -> assert false in match lookup env p with | Glob_val v -> lapply v args | Glob_prim p -> assert (p.prim_arity = List.length args); lprim (Pccall p) args let global_to_lambda = function | Glob_val v -> v | Glob_prim p -> Eta - expand this primitive . See translprim.ml . let rec make_params n = if n <= 0 then [] else fresh "prim" :: make_params (n-1) in let params = make_params p.prim_arity in let body = lprim (Pccall p) (List.map (fun x -> Lvar x) params) in lfunction params body let rec to_lambda env = function | Mvar v -> Lvar v | Mlambda (params, e) -> lfunction params (to_lambda env e) | Mapply (fn, args) -> let ap_func fn = lapply fn (List.map (to_lambda env) args) in (match fn with | Mglobal v -> (match lookup env v with | Glob_prim p when p.prim_arity = List.length args -> lprim (Pccall p) (List.map (to_lambda env) args) | g -> ap_func (global_to_lambda g)) | fn -> ap_func (to_lambda env fn)) | Mlet (bindings, body) -> bindings_to_lambda env bindings (to_lambda env body) | Mnum (`Int n) -> Lconst (Const_base (Const_int n)) | Mnum (`Int32 n) -> Lconst (Const_base (Const_int32 n)) | Mnum (`Int64 n) -> Lconst (Const_base (Const_int64 n)) | Mnum (`Bigint n) -> (match Z.to_int n with | n' -> assert (Obj.repr n = Obj.repr n'); Lconst (Const_base (Const_int n')) | exception Z.Overflow -> builtin env ["Z"; "of_string"] [Lconst (Const_immstring (Z.to_string n))]) | Mnum (`Float64 f) -> Lconst (Const_base (Const_float (string_of_float f))) | Mstring s -> Lconst (Const_immstring s) | Mglobal v -> global_to_lambda (lookup env v) | Mswitch (scr, cases) -> let scr = to_lambda env scr in let rec flatten acc = function | ([], _) :: _ -> assert false | ([sel], e) :: rest -> flatten ((sel, to_lambda env e) :: acc) rest | (sels, e) :: rest -> let i = next_raise_count () in let cases = List.map (fun s -> s, Lstaticraise(i, [])) sels in Lstaticcatch (flatten (cases @ acc) rest, (i, []), to_lambda env e) | [] -> let rec partition (ints, tags, deftag) = function | [] -> (List.rev ints, List.rev tags, deftag) | (`Tag _, _) as c :: cases -> partition (ints, c :: tags, deftag) cases | (`Deftag, _) as c :: cases -> partition (ints, tags, Some c) cases | (`Intrange _, _) as c :: cases -> partition (c :: ints, tags, deftag) cases in let (intcases, tagcases, deftag) = partition ([],[],None) (List.rev acc) in lbind "switch" scr (fun scr -> let tagswitch = match tagcases, deftag with | [], None -> None | [_,e], None | [], Some (_, e) -> Some e | tags, def -> let numtags = match def with | Some _ -> (max_tag :> int) | None -> 1 + List.fold_left (fun s (`Tag i, _) -> max s (i :> int)) (-1) tags in Some (lswitch scr { sw_numconsts = 0; sw_consts = []; sw_numblocks = numtags; sw_blocks = List.map (fun (`Tag i, e) -> i, e) tags; sw_failaction = match def with None -> None | Some (`Deftag,e) -> Some e }) in let intswitch = match intcases with | [] -> None | [_,e] -> Some e | ints -> Some (IntSwitch.compile_int_switch scr ints) in match intswitch, tagswitch with | None, None -> assert false | None, Some e | Some e, None -> e | Some eint, Some etag -> Lifthenelse (lprim Pisint [scr], eint, etag)) in (match cases with | [[`Intrange (0, 0)], ezero; _, enonzero] | [_, enonzero; [`Intrange (0, 0)], ezero] -> special case comparisons with zero Lifthenelse(scr, to_lambda env enonzero, to_lambda env ezero) | cases -> flatten [] cases) | Mnumop1 (op, ty, e) -> let e = to_lambda env e in let ones32 = Const_base (Asttypes.Const_int32 (Int32.of_int (-1))) in let ones64 = Const_base (Asttypes.Const_int64 (Int64.of_int (-1))) in let code = match op, ty with | `Neg, `Int -> lprim Pnegint [e] | `Neg, `Int32 -> lprim (Pnegbint Pint32) [e] | `Neg, `Int64 -> lprim (Pnegbint Pint64) [e] | `Neg, `Bigint -> builtin env ["Z"; "neg"] [e] | `Neg, `Float64 -> lprim Pnegfloat [e] | `Not, `Int -> lprim Pnot [e] | `Not, `Int32 -> lprim (Pxorbint Pint32) [e; Lconst ones32] | `Not, `Int64 -> lprim (Pxorbint Pint64) [e; Lconst ones64] | `Not, `Bigint -> builtin env ["Z"; "lognot"] [e] | `Not, `Float64 -> assert false in code | Mnumop2 (op, ((`Int|`Int32|`Int64) as ty), e1, e2) -> let e1 = to_lambda env e1 in let e2 = to_lambda env e2 in let prim = match ty with | `Int -> (match op with `Add -> Paddint | `Sub -> Psubint | `Mul -> Pmulint | `Div -> Pdivint Safe | `Mod -> Pmodint Safe | `And -> Pandint | `Or -> Porint | `Xor -> Pxorint | `Lsl -> Plslint | `Lsr -> Plsrint | `Asr -> Pasrint | `Lt -> Pintcomp Clt | `Gt -> Pintcomp Cgt | `Lte -> Pintcomp Cle | `Gte -> Pintcomp Cge | `Eq -> Pintcomp Ceq) | (`Int32 | `Int64) as ty -> let t = match ty with `Int32 -> Pint32 | `Int64 -> Pint64 in (match op with `Add -> Paddbint t | `Sub -> Psubbint t | `Mul -> Pmulbint t | `Div -> Pdivbint { size = t; is_safe = Safe } | `Mod -> Pmodbint { size = t; is_safe = Safe } | `And -> Pandbint t | `Or -> Porbint t | `Xor -> Pxorbint t | `Lsl -> Plslbint t | `Lsr -> Plsrbint t | `Asr -> Pasrbint t | `Lt -> Pbintcomp (t, Clt) | `Gt -> Pbintcomp (t, Cgt) | `Lte -> Pbintcomp (t, Cle) | `Gte -> Pbintcomp (t, Cge) | `Eq -> Pbintcomp (t, Ceq)) in lprim prim [e1; e2] | Mnumop2 (op, `Bigint, e1, e2) -> let e1 = to_lambda env e1 in let e2 = to_lambda env e2 in let fn = match op with | `Add -> "add" | `Sub -> "sub" | `Mul -> "mul" | `Div -> "div" | `Mod -> "rem" | `And -> "logand" | `Or -> "logor" | `Xor -> "logxor" | `Lsl -> "shift_left" | `Lsr -> "shift_right" | `Asr -> "shift_right" | `Lt -> "lt" | `Gt -> "gt" | `Lte -> "leq" | `Gte -> "geq" | `Eq -> "equal" in builtin env ["Z"; fn] [e1; e2] | Mnumop2 (op, `Float64, e1, e2) -> let e1 = to_lambda env e1 in let e2 = to_lambda env e2 in begin match op with | #binary_bitwise_op -> assert false | `Add -> lprim Paddfloat [e1; e2] | `Sub -> lprim Psubfloat [e1; e2] | `Mul -> lprim Pmulfloat [e1; e2] | `Div -> lprim Pdivfloat [e1; e2] | `Mod -> builtin env [stdlib_module_name; "mod_float"] [e1; e2] | #binary_comparison as op -> let cmp = cmp_to_float_comparison op in lprim (Pfloatcomp cmp) [e1; e2] end | Mconvert (src, dst, e) -> let e = to_lambda env e in begin match src, dst with | `Bigint, `Bigint | `Int, `Int | `Int32, `Int32 | `Int64, `Int64 | `Float64, `Float64 -> e | `Bigint, ((`Int|`Int32|`Int64) as dst) -> Zarith raises exceptions on overflow , but we truncate conversions . Not fast . let width = match dst with | `Int -> Sys.word_size - 1 | `Int32 -> 32 | `Int64 -> 64 in let range = Z.(shift_left (of_int 1) width) in let truncated = lbind "range" (builtin env ["Z"; "of_string"] [Lconst (Const_immstring (Z.to_string range))]) (fun range -> lbind "masked" (builtin env ["Z"; "logand"] [e; builtin env ["Z"; "sub"] [range; Lconst (Const_base (Const_int 1))]]) (fun masked -> Lifthenelse (builtin env ["Z"; "testbit"] [masked; Lconst (Const_base (Const_int (width - 1)))], builtin env ["Z"; "sub"] [masked; range], masked))) in let fn = match dst with | `Int -> "to_int" | `Int32 -> "to_int32" | `Int64 -> "to_int64" in builtin env ["Z"; fn] [truncated] | ((`Int|`Int32|`Int64) as src), `Bigint -> let fn = match src with | `Int -> "of_int" | `Int32 -> "of_int32" | `Int64 -> "of_int64" in builtin env ["Z"; fn] [e] | `Int, `Int32 -> lprim (Pbintofint Pint32) [e] | `Int, `Int64 -> lprim (Pbintofint Pint64) [e] | `Int32, `Int -> lprim (Pintofbint Pint32) [e] | `Int64, `Int -> lprim (Pintofbint Pint64) [e] | `Int32, `Int64 -> lprim (Pcvtbint(Pint32, Pint64)) [e] | `Int64, `Int32 -> lprim (Pcvtbint(Pint64, Pint32)) [e] | `Int, `Float64 -> lprim Pfloatofint [e] | `Int32, `Float64 -> builtin env ["Int32"; "to_float"] [e] | `Int64, `Float64 -> builtin env ["Int64"; "to_float"] [e] | `Bigint, `Float64 -> builtin env ["Z"; "to_float"] [e] | `Float64, `Int -> lprim Pintoffloat [e] | `Float64, `Int32 -> builtin env ["Int32"; "of_float"] [e] | `Float64, `Int64 -> builtin env ["Int64"; "of_float"] [e] | `Float64, `Bigint -> builtin env ["Z"; "of_float"] [e] end | Mvecnew (`Array, len, def) -> builtin env ["Array"; "make"] [to_lambda env len; to_lambda env def] | Mvecnew (`Bytevec, len, def) -> builtin env ["String"; "make"] [to_lambda env len; to_lambda env def] | Mvecget (ty, vec, idx) -> let prim = match ty with | `Array -> Parrayrefs Paddrarray | `Bytevec -> Pbytesrefs lprim prim [to_lambda env vec; to_lambda env idx] | Mvecset (ty, vec, idx, v) -> let prim = match ty with | `Array -> Parraysets Paddrarray | `Bytevec -> Pbytessets lprim prim [to_lambda env vec; to_lambda env idx; to_lambda env v] | Mveclen (ty, vec) -> let prim = match ty with | `Array -> Parraylength Paddrarray | `Bytevec -> Pbyteslength | ` Floatvec - > lprim prim [to_lambda env vec] | Mblock (tag, vals) -> lprim (Pmakeblock (tag, Immutable, None)) (List.map (to_lambda env) vals) | Mfield (idx, e) -> lprim (Pfield(idx)) [to_lambda env e] | Mlazy e -> let fn = lfunction [fresh "param"] (to_lambda env e) in lprim (Pmakeblock (Config.lazy_tag, Mutable, None)) [fn] | Mforce e -> Matching.inline_lazy_force (to_lambda env e) loc_none and bindings_to_lambda env bindings body = List.fold_right (fun b rest -> match b with | `Unnamed e -> Lsequence (to_lambda env e, rest) | `Named (n, e) -> Llet (Strict, Pgenval, n, to_lambda env e, rest) | `Recursive bs -> Lletrec (List.map (fun (n, e) -> (n, to_lambda env e)) bs, rest)) bindings body let setup_options options = Clflags.native_code := true; Clflags.flambda_invariant_checks := true; Clflags.nopervasives := false; Clflags.dump_lambda := false; Clflags.dump_cmm := false; Clflags.keep_asm_file := false; Clflags.include_dirs := [Findlib.package_directory "zarith"]; Clflags.inlining_report := false; Clflags.dlcode := true; Clflags.shared := false; Clflags.( default_simplify_rounds := 2; use_inlining_arguments_set o2_arguments; use_inlining_arguments_set ~round:0 o1_arguments); Hack : disable the " no cmx " warning for zarith let _ = Warnings.parse_options false "-58" in assert (not (Warnings.is_active (Warnings.No_cmx_file "asdf"))); (options |> List.iter @@ function | `Verbose -> Clflags.dump_lambda := true; Clflags.dump_cmm := true; | `Shared -> Clflags.shared := true); Compenv.(readenv Format.std_formatter (Before_compile "malfunction")); compmisc_init_path () let module_to_lambda ?options ~module_name:_ ~module_id (Mmod (bindings, exports)) = setup_options (match options with Some o -> o | None -> []); let print_if flag printer arg = if !flag then Format.printf "%a@." printer arg; arg in let env = Compmisc.initial_env () in let module_size, code = let bindings = reorder_bindings bindings in let exports = List.map (fun e -> snd (reorder e)) exports in if Config.flambda then List.length exports, bindings_to_lambda env bindings (lprim (Pmakeblock (0, Immutable, None)) (List.map (to_lambda env) exports)) else begin FIXME let num_exports = List.length exports in Compile all of the bindings , store at positions num_exports + i , then compile the exports . See Translmod.transl_store_gen . then compile the exports. See Translmod.transl_store_gen. *) let module_length = ref (-1) in let mod_store pos e = Lprim (Psetfield (pos, Pointer, root_initialization), [Lprim (Pgetglobal module_id, [], loc); e], loc) in let mod_load pos = Lprim (Pfield pos, [Lprim (Pgetglobal module_id, [], loc)], loc) in let transl_exports subst = let exps = List.mapi (fun i e -> mod_store i (Subst.apply subst (to_lambda env e))) exports in List.fold_right (fun x xs -> Lsequence (x, xs)) exps (Lconst Lambda.const_unit) in let rec transl_toplevel_bindings pos subst = function | `Unnamed e :: rest -> Lsequence (Subst.apply subst (to_lambda env e), transl_toplevel_bindings pos subst rest) | `Named (n, e) :: rest -> let lam = Llet (Strict, Pgenval, n, Subst.apply subst (to_lambda env e), mod_store pos (Lvar n)) in Lsequence (lam, transl_toplevel_bindings (pos + 1) (Subst.add n (mod_load pos) subst) rest) | `Recursive bs :: rest -> let ids = List.map fst bs in let stores = ids |> List.mapi (fun i n -> mod_store (pos + i) (Lvar n)) in let stores = List.fold_right (fun x xs -> Lsequence (x, xs)) stores (Lconst Lambda.const_unit) in let lam = Lletrec (bs |> List.map (fun (n, e) -> (n, Subst.apply subst (to_lambda env e))), stores) in let id_load = ids |> List.mapi (fun i n -> (n, mod_load (pos + i))) in let subst = List.fold_left (fun subst (n, l) -> Subst.add n l subst) subst id_load in Lsequence (lam, transl_toplevel_bindings (pos + List.length ids) subst rest) | [] -> module_length := pos; transl_exports subst in let r = transl_toplevel_bindings num_exports Subst.empty bindings in !module_length, r end in let lambda = code |> print_if Clflags.dump_rawlambda Printlambda.lambda |> simplify_lambda |> print_if Clflags.dump_lambda Printlambda.lambda in (module_size, lambda) let backend = (module struct include Compilenv include Import_approx include Arch let max_sensible_number_of_arguments = Proc.max_arguments_for_tailcalls - 1 end : Backend_intf.S) type outfiles = { objfile : string; cmxfile : string; cmifile : string option } let delete_temps { objfile; cmxfile; cmifile } = Misc.remove_file objfile; Misc.remove_file cmxfile; match cmifile with Some f -> Misc.remove_file f | None -> () type options = [`Verbose | `Shared] list let lambda_to_cmx ?(options=[]) ~filename ~prefixname ~module_name ~module_id lmod = let ppf = Format.std_formatter in let outfiles = ref { cmxfile = prefixname ^ ".cmx"; objfile = prefixname ^ Config.ext_obj; cmifile = None } in setup_options options; try let cmi = module_name ^ ".cmi" in Env.set_unit_name module_name; with_source_provenance filename (Compilenv.reset ?packname:!Clflags.for_package module_name); ignore (match load_path_find cmi with | file -> Env.read_signature module_name file | exception Not_found -> let chop_ext = Misc.chop_extensions in let mlifile = chop_ext filename ^ !Config.interface_suffix in if Sys.file_exists mlifile then Typemod.(raise(Error(Location.in_file filename, Env.empty, Interface_not_compiled cmi))) else hackily generate an empty cmi file let cmifile = String.uncapitalize_ascii cmi in outfiles := { !outfiles with cmifile = Some cmifile }; let mlifile = String.uncapitalize_ascii (module_name ^ ".mli") in let ch = open_out mlifile in output_string ch "(* autogenerated mli for malfunction *)\n"; close_out ch; ignore (Sys.command ("ocamlc -c " ^ mlifile)); Misc.remove_file mlifile; if not (Sys.file_exists cmifile) then failwith "Failed to generate empty cmi file"; Env.read_signature module_name cmifile); FIXME : may need to add modules referenced only by " external " to this . See Translmod.primitive_declarations and its use in . See Translmod.primitive_declarations and its use in Asmgen. *) let required_globals = Ident.Set.of_list (Env.get_required_globals ()) in compile_implementation ~prefixname ~filename ~module_id ~backend ~required_globals ~ppf lmod; Compilenv.save_unit_info !outfiles.cmxfile; Warnings.check_fatal (); !outfiles with e -> delete_temps !outfiles; raise e let compile_module ?(options=[]) ~filename modl = FIXME : do we really want to go through Clflags here ? See Compenv.output_prefix let prefixname = Compenv.output_prefix filename in let module_name = prefixname |> Filename.basename |> Filename.remove_extension |> String.capitalize_ascii in if not (Compenv.is_unit_name module_name) then raise (Invalid_argument ("Invalid module name " ^ module_name)); let module_id = Ident.create_persistent module_name in modl |> module_to_lambda ~module_name ~module_id ~options |> lambda_to_cmx ~options ~filename ~prefixname ~module_name ~module_id let compile_cmx ?(options=[]) filename = let lexbuf = Lexing.from_channel (open_in filename) in Lexing.(lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = filename }); let modl = Malfunction_parser.read_module lexbuf in compile_module ~options ~filename modl external ndl_run_toplevel: string -> string -> (Obj.t, string) result = "caml_natdynlink_run_toplevel" external ndl_loadsym: string -> Obj.t = "caml_natdynlink_loadsym" let code_id = ref 0 let compile_and_load ?(options : options =[]) e = if not Dynlink.is_native then failwith "Loading malfunction values works only in native code"; let tmpdir = Filename.temp_file "malfunction" ".tmp" in Unix.unlink tmpdir; Unix.mkdir tmpdir 0o700; let old_cwd = Sys.getcwd () in Sys.chdir tmpdir; incr code_id; let modname = "Malfunction_Code_" ^ string_of_int (!code_id) in let modname_uncap = String.uncapitalize_ascii modname in let options = `Shared :: options in let tmpfiles = compile_module ~options ~filename:modname_uncap (Mmod ([], [e])) in begin try with_ppf_dump Format.err_formatter Asmlink.link_shared [tmpfiles.cmxfile] (modname_uncap ^ ".cmxs") with | Asmlink.Error e -> let msg = Format.asprintf "Asmlink error: %a" Asmlink.report_error e in failwith msg end; let cmxs = tmpdir ^ Filename.dir_sep ^ modname_uncap ^ ".cmxs" in (match ndl_run_toplevel cmxs modname with | Ok _ -> () | Error s -> failwith ("loading failed: " ^ s)); let res = Obj.field (ndl_loadsym (Compilenv.symbol_for_global (Ident.create_persistent modname))) 0 in delete_temps tmpfiles; Misc.remove_file cmxs; Sys.chdir old_cwd; Unix.rmdir tmpdir; res let link_executable output tmpfiles = Sys.command (Printf.sprintf "ocamlfind ocamlopt -package zarith zarith.cmxa '%s' -o '%s'" tmpfiles.cmxfile output)
de2cda38427421921c26ffec278825883b2e4999b5b89edfad16a5572d1748d7
upenn-cis1xx/camelot
lexical.ml
open Canonical open Check * --------- Checks rules : lines that exceed 80 characters in a given file ------------ module LineLength : LEXICALCHECK = struct type ctxt = Pctxt.file Pctxt.pctxt let fix = "indenting to avoid exceeding the line limit" let violation = "exceeding the 80 character line limit. Only showing (1) such violation of this kind, although there may be others - fix this and re-run the linter to find them." let check st (L {source; pattern = Pctxt.F chan}: ctxt) = let filestream : (int * string) Stream.t = Stream.from 0 indexes file lines , but line numbers start at 1 . Have to increment so that the line numbers are consistent with editors :) Stream.from (fun line -> try (Some (line + 1, input_line chan)) with End_of_file -> None ) in Stream.iter (fun (line_no, line) -> if String.length line > 80 then st := Hint.line_hint source line_no line :: !st ) filestream let name = "LineLength", check end
null
https://raw.githubusercontent.com/upenn-cis1xx/camelot/2d7e8db8abb8c1ad8187bfeb94499fe1746bb664/lib/style/lexical.ml
ocaml
open Canonical open Check * --------- Checks rules : lines that exceed 80 characters in a given file ------------ module LineLength : LEXICALCHECK = struct type ctxt = Pctxt.file Pctxt.pctxt let fix = "indenting to avoid exceeding the line limit" let violation = "exceeding the 80 character line limit. Only showing (1) such violation of this kind, although there may be others - fix this and re-run the linter to find them." let check st (L {source; pattern = Pctxt.F chan}: ctxt) = let filestream : (int * string) Stream.t = Stream.from 0 indexes file lines , but line numbers start at 1 . Have to increment so that the line numbers are consistent with editors :) Stream.from (fun line -> try (Some (line + 1, input_line chan)) with End_of_file -> None ) in Stream.iter (fun (line_no, line) -> if String.length line > 80 then st := Hint.line_hint source line_no line :: !st ) filestream let name = "LineLength", check end
291e0f5c4c6bb6c1df37c8bb7650317a935015fae4edff6134f68bb019712375
TheLortex/mirage-monorepo
migrate_408_407.ml
module From = Ast_408 module To = Ast_407 let migration_error loc missing_feature = Location.raise_errorf ~loc "migration error: %s is not supported before OCaml 4.08" missing_feature let rec copy_toplevel_phrase : From.Parsetree.toplevel_phrase -> To.Parsetree.toplevel_phrase = function | From.Parsetree.Ptop_def x0 -> To.Parsetree.Ptop_def (copy_structure x0) | From.Parsetree.Ptop_dir { From.Parsetree.pdir_name; From.Parsetree.pdir_arg; From.Parsetree.pdir_loc = _; } -> To.Parsetree.Ptop_dir ( pdir_name.Location.txt, match pdir_arg with | None -> To.Parsetree.Pdir_none | Some arg -> copy_directive_argument arg ) and copy_directive_argument : From.Parsetree.directive_argument -> To.Parsetree.directive_argument = fun { From.Parsetree.pdira_desc; From.Parsetree.pdira_loc = _pdira_loc } -> copy_directive_argument_desc pdira_desc and copy_directive_argument_desc : From.Parsetree.directive_argument_desc -> To.Parsetree.directive_argument = function | From.Parsetree.Pdir_string x0 -> To.Parsetree.Pdir_string x0 | From.Parsetree.Pdir_int (x0, x1) -> To.Parsetree.Pdir_int (x0, copy_option (fun x -> x) x1) | From.Parsetree.Pdir_ident x0 -> To.Parsetree.Pdir_ident (copy_longident x0) | From.Parsetree.Pdir_bool x0 -> To.Parsetree.Pdir_bool (copy_bool x0) and copy_expression : From.Parsetree.expression -> To.Parsetree.expression = fun { From.Parsetree.pexp_desc; From.Parsetree.pexp_loc; From.Parsetree.pexp_loc_stack = _; From.Parsetree.pexp_attributes; } -> { To.Parsetree.pexp_desc = copy_expression_desc pexp_desc; To.Parsetree.pexp_loc = copy_location pexp_loc; To.Parsetree.pexp_attributes = copy_attributes pexp_attributes; } and copy_expression_desc : From.Parsetree.expression_desc -> To.Parsetree.expression_desc = function | From.Parsetree.Pexp_ident x0 -> To.Parsetree.Pexp_ident (copy_loc copy_longident x0) | From.Parsetree.Pexp_constant x0 -> To.Parsetree.Pexp_constant (copy_constant x0) | From.Parsetree.Pexp_let (x0, x1, x2) -> To.Parsetree.Pexp_let (copy_rec_flag x0, List.map copy_value_binding x1, copy_expression x2) | From.Parsetree.Pexp_function x0 -> To.Parsetree.Pexp_function (List.map copy_case x0) | From.Parsetree.Pexp_fun (x0, x1, x2, x3) -> To.Parsetree.Pexp_fun ( copy_arg_label x0, copy_option copy_expression x1, copy_pattern x2, copy_expression x3 ) | From.Parsetree.Pexp_apply (x0, x1) -> To.Parsetree.Pexp_apply ( copy_expression x0, List.map (fun x -> let x0, x1 = x in (copy_arg_label x0, copy_expression x1)) x1 ) | From.Parsetree.Pexp_match (x0, x1) -> To.Parsetree.Pexp_match (copy_expression x0, List.map copy_case x1) | From.Parsetree.Pexp_try (x0, x1) -> To.Parsetree.Pexp_try (copy_expression x0, List.map copy_case x1) | From.Parsetree.Pexp_tuple x0 -> To.Parsetree.Pexp_tuple (List.map copy_expression x0) | From.Parsetree.Pexp_construct (x0, x1) -> To.Parsetree.Pexp_construct (copy_loc copy_longident x0, copy_option copy_expression x1) | From.Parsetree.Pexp_variant (x0, x1) -> To.Parsetree.Pexp_variant (copy_label x0, copy_option copy_expression x1) | From.Parsetree.Pexp_record (x0, x1) -> To.Parsetree.Pexp_record ( List.map (fun x -> let x0, x1 = x in (copy_loc copy_longident x0, copy_expression x1)) x0, copy_option copy_expression x1 ) | From.Parsetree.Pexp_field (x0, x1) -> To.Parsetree.Pexp_field (copy_expression x0, copy_loc copy_longident x1) | From.Parsetree.Pexp_setfield (x0, x1, x2) -> To.Parsetree.Pexp_setfield (copy_expression x0, copy_loc copy_longident x1, copy_expression x2) | From.Parsetree.Pexp_array x0 -> To.Parsetree.Pexp_array (List.map copy_expression x0) | From.Parsetree.Pexp_ifthenelse (x0, x1, x2) -> To.Parsetree.Pexp_ifthenelse (copy_expression x0, copy_expression x1, copy_option copy_expression x2) | From.Parsetree.Pexp_sequence (x0, x1) -> To.Parsetree.Pexp_sequence (copy_expression x0, copy_expression x1) | From.Parsetree.Pexp_while (x0, x1) -> To.Parsetree.Pexp_while (copy_expression x0, copy_expression x1) | From.Parsetree.Pexp_for (x0, x1, x2, x3, x4) -> To.Parsetree.Pexp_for ( copy_pattern x0, copy_expression x1, copy_expression x2, copy_direction_flag x3, copy_expression x4 ) | From.Parsetree.Pexp_constraint (x0, x1) -> To.Parsetree.Pexp_constraint (copy_expression x0, copy_core_type x1) | From.Parsetree.Pexp_coerce (x0, x1, x2) -> To.Parsetree.Pexp_coerce (copy_expression x0, copy_option copy_core_type x1, copy_core_type x2) | From.Parsetree.Pexp_send (x0, x1) -> To.Parsetree.Pexp_send (copy_expression x0, copy_loc copy_label x1) | From.Parsetree.Pexp_new x0 -> To.Parsetree.Pexp_new (copy_loc copy_longident x0) | From.Parsetree.Pexp_setinstvar (x0, x1) -> To.Parsetree.Pexp_setinstvar (copy_loc copy_label x0, copy_expression x1) | From.Parsetree.Pexp_override x0 -> To.Parsetree.Pexp_override (List.map (fun x -> let x0, x1 = x in (copy_loc copy_label x0, copy_expression x1)) x0) | From.Parsetree.Pexp_letmodule (x0, x1, x2) -> To.Parsetree.Pexp_letmodule (copy_loc (fun x -> x) x0, copy_module_expr x1, copy_expression x2) | From.Parsetree.Pexp_letexception (x0, x1) -> To.Parsetree.Pexp_letexception (copy_extension_constructor x0, copy_expression x1) | From.Parsetree.Pexp_assert x0 -> To.Parsetree.Pexp_assert (copy_expression x0) | From.Parsetree.Pexp_lazy x0 -> To.Parsetree.Pexp_lazy (copy_expression x0) | From.Parsetree.Pexp_poly (x0, x1) -> To.Parsetree.Pexp_poly (copy_expression x0, copy_option copy_core_type x1) | From.Parsetree.Pexp_object x0 -> To.Parsetree.Pexp_object (copy_class_structure x0) | From.Parsetree.Pexp_newtype (x0, x1) -> To.Parsetree.Pexp_newtype (copy_loc (fun x -> x) x0, copy_expression x1) | From.Parsetree.Pexp_pack x0 -> To.Parsetree.Pexp_pack (copy_module_expr x0) | From.Parsetree.Pexp_open (x0, x1) -> ( match x0.From.Parsetree.popen_expr.From.Parsetree.pmod_desc with | Pmod_ident lid -> To.Parsetree.Pexp_open ( copy_override_flag x0.From.Parsetree.popen_override, copy_loc copy_longident lid, copy_expression x1 ) | Pmod_structure _ | Pmod_functor _ | Pmod_apply _ | Pmod_constraint _ | Pmod_unpack _ | Pmod_extension _ -> migration_error x0.From.Parsetree.popen_loc "complex open") | From.Parsetree.Pexp_letop { let_; ands = _; body = _ } -> migration_error let_.pbop_op.loc "let operators" | From.Parsetree.Pexp_extension x0 -> To.Parsetree.Pexp_extension (copy_extension x0) | From.Parsetree.Pexp_unreachable -> To.Parsetree.Pexp_unreachable and copy_direction_flag : From.Asttypes.direction_flag -> To.Asttypes.direction_flag = function | From.Asttypes.Upto -> To.Asttypes.Upto | From.Asttypes.Downto -> To.Asttypes.Downto and copy_case : From.Parsetree.case -> To.Parsetree.case = fun { From.Parsetree.pc_lhs; From.Parsetree.pc_guard; From.Parsetree.pc_rhs } -> { To.Parsetree.pc_lhs = copy_pattern pc_lhs; To.Parsetree.pc_guard = copy_option copy_expression pc_guard; To.Parsetree.pc_rhs = copy_expression pc_rhs; } and copy_value_binding : From.Parsetree.value_binding -> To.Parsetree.value_binding = fun { From.Parsetree.pvb_pat; From.Parsetree.pvb_expr; From.Parsetree.pvb_attributes; From.Parsetree.pvb_loc; } -> { To.Parsetree.pvb_pat = copy_pattern pvb_pat; To.Parsetree.pvb_expr = copy_expression pvb_expr; To.Parsetree.pvb_attributes = copy_attributes pvb_attributes; To.Parsetree.pvb_loc = copy_location pvb_loc; } and copy_pattern : From.Parsetree.pattern -> To.Parsetree.pattern = fun { From.Parsetree.ppat_desc; From.Parsetree.ppat_loc; From.Parsetree.ppat_loc_stack = _; From.Parsetree.ppat_attributes; } -> { To.Parsetree.ppat_desc = copy_pattern_desc ppat_desc; To.Parsetree.ppat_loc = copy_location ppat_loc; To.Parsetree.ppat_attributes = copy_attributes ppat_attributes; } and copy_pattern_desc : From.Parsetree.pattern_desc -> To.Parsetree.pattern_desc = function | From.Parsetree.Ppat_any -> To.Parsetree.Ppat_any | From.Parsetree.Ppat_var x0 -> To.Parsetree.Ppat_var (copy_loc (fun x -> x) x0) | From.Parsetree.Ppat_alias (x0, x1) -> To.Parsetree.Ppat_alias (copy_pattern x0, copy_loc (fun x -> x) x1) | From.Parsetree.Ppat_constant x0 -> To.Parsetree.Ppat_constant (copy_constant x0) | From.Parsetree.Ppat_interval (x0, x1) -> To.Parsetree.Ppat_interval (copy_constant x0, copy_constant x1) | From.Parsetree.Ppat_tuple x0 -> To.Parsetree.Ppat_tuple (List.map copy_pattern x0) | From.Parsetree.Ppat_construct (x0, x1) -> To.Parsetree.Ppat_construct (copy_loc copy_longident x0, copy_option copy_pattern x1) | From.Parsetree.Ppat_variant (x0, x1) -> To.Parsetree.Ppat_variant (copy_label x0, copy_option copy_pattern x1) | From.Parsetree.Ppat_record (x0, x1) -> To.Parsetree.Ppat_record ( List.map (fun x -> let x0, x1 = x in (copy_loc copy_longident x0, copy_pattern x1)) x0, copy_closed_flag x1 ) | From.Parsetree.Ppat_array x0 -> To.Parsetree.Ppat_array (List.map copy_pattern x0) | From.Parsetree.Ppat_or (x0, x1) -> To.Parsetree.Ppat_or (copy_pattern x0, copy_pattern x1) | From.Parsetree.Ppat_constraint (x0, x1) -> To.Parsetree.Ppat_constraint (copy_pattern x0, copy_core_type x1) | From.Parsetree.Ppat_type x0 -> To.Parsetree.Ppat_type (copy_loc copy_longident x0) | From.Parsetree.Ppat_lazy x0 -> To.Parsetree.Ppat_lazy (copy_pattern x0) | From.Parsetree.Ppat_unpack x0 -> To.Parsetree.Ppat_unpack (copy_loc (fun x -> x) x0) | From.Parsetree.Ppat_exception x0 -> To.Parsetree.Ppat_exception (copy_pattern x0) | From.Parsetree.Ppat_extension x0 -> To.Parsetree.Ppat_extension (copy_extension x0) | From.Parsetree.Ppat_open (x0, x1) -> To.Parsetree.Ppat_open (copy_loc copy_longident x0, copy_pattern x1) and copy_core_type : From.Parsetree.core_type -> To.Parsetree.core_type = fun { From.Parsetree.ptyp_desc; From.Parsetree.ptyp_loc; From.Parsetree.ptyp_loc_stack = _; From.Parsetree.ptyp_attributes; } -> { To.Parsetree.ptyp_desc = copy_core_type_desc ptyp_desc; To.Parsetree.ptyp_loc = copy_location ptyp_loc; To.Parsetree.ptyp_attributes = copy_attributes ptyp_attributes; } and copy_core_type_desc : From.Parsetree.core_type_desc -> To.Parsetree.core_type_desc = function | From.Parsetree.Ptyp_any -> To.Parsetree.Ptyp_any | From.Parsetree.Ptyp_var x0 -> To.Parsetree.Ptyp_var x0 | From.Parsetree.Ptyp_arrow (x0, x1, x2) -> To.Parsetree.Ptyp_arrow (copy_arg_label x0, copy_core_type x1, copy_core_type x2) | From.Parsetree.Ptyp_tuple x0 -> To.Parsetree.Ptyp_tuple (List.map copy_core_type x0) | From.Parsetree.Ptyp_constr (x0, x1) -> To.Parsetree.Ptyp_constr (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Ptyp_object (x0, x1) -> To.Parsetree.Ptyp_object (List.map copy_object_field x0, copy_closed_flag x1) | From.Parsetree.Ptyp_class (x0, x1) -> To.Parsetree.Ptyp_class (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Ptyp_alias (x0, x1) -> To.Parsetree.Ptyp_alias (copy_core_type x0, x1) | From.Parsetree.Ptyp_variant (x0, x1, x2) -> To.Parsetree.Ptyp_variant ( List.map copy_row_field x0, copy_closed_flag x1, copy_option (fun x -> List.map copy_label x) x2 ) | From.Parsetree.Ptyp_poly (x0, x1) -> To.Parsetree.Ptyp_poly (List.map (fun x -> copy_loc (fun x -> x) x) x0, copy_core_type x1) | From.Parsetree.Ptyp_package x0 -> To.Parsetree.Ptyp_package (copy_package_type x0) | From.Parsetree.Ptyp_extension x0 -> To.Parsetree.Ptyp_extension (copy_extension x0) and copy_package_type : From.Parsetree.package_type -> To.Parsetree.package_type = fun x -> let x0, x1 = x in ( copy_loc copy_longident x0, List.map (fun x -> let x0, x1 = x in (copy_loc copy_longident x0, copy_core_type x1)) x1 ) and copy_row_field : From.Parsetree.row_field -> To.Parsetree.row_field = fun { From.Parsetree.prf_desc; From.Parsetree.prf_loc = _; From.Parsetree.prf_attributes; } -> match prf_desc with | From.Parsetree.Rtag (x0, x1, x2) -> To.Parsetree.Rtag ( copy_loc copy_label x0, copy_attributes prf_attributes, copy_bool x1, List.map copy_core_type x2 ) | From.Parsetree.Rinherit x0 -> To.Parsetree.Rinherit (copy_core_type x0) and copy_object_field : From.Parsetree.object_field -> To.Parsetree.object_field = fun { From.Parsetree.pof_desc; From.Parsetree.pof_loc = _; From.Parsetree.pof_attributes; } -> match pof_desc with | From.Parsetree.Otag (x0, x1) -> To.Parsetree.Otag ( copy_loc copy_label x0, copy_attributes pof_attributes, copy_core_type x1 ) | From.Parsetree.Oinherit x0 -> To.Parsetree.Oinherit (copy_core_type x0) and copy_attributes : From.Parsetree.attributes -> To.Parsetree.attributes = fun x -> List.map copy_attribute x and copy_attribute : From.Parsetree.attribute -> To.Parsetree.attribute = fun { From.Parsetree.attr_name; From.Parsetree.attr_payload; From.Parsetree.attr_loc = _; } -> (copy_loc (fun x -> x) attr_name, copy_payload attr_payload) and copy_payload : From.Parsetree.payload -> To.Parsetree.payload = function | From.Parsetree.PStr x0 -> To.Parsetree.PStr (copy_structure x0) | From.Parsetree.PSig x0 -> To.Parsetree.PSig (copy_signature x0) | From.Parsetree.PTyp x0 -> To.Parsetree.PTyp (copy_core_type x0) | From.Parsetree.PPat (x0, x1) -> To.Parsetree.PPat (copy_pattern x0, copy_option copy_expression x1) and copy_structure : From.Parsetree.structure -> To.Parsetree.structure = fun x -> List.map copy_structure_item x and copy_structure_item : From.Parsetree.structure_item -> To.Parsetree.structure_item = fun { From.Parsetree.pstr_desc; From.Parsetree.pstr_loc } -> { To.Parsetree.pstr_desc = copy_structure_item_desc pstr_desc; To.Parsetree.pstr_loc = copy_location pstr_loc; } and copy_structure_item_desc : From.Parsetree.structure_item_desc -> To.Parsetree.structure_item_desc = function | From.Parsetree.Pstr_eval (x0, x1) -> To.Parsetree.Pstr_eval (copy_expression x0, copy_attributes x1) | From.Parsetree.Pstr_value (x0, x1) -> To.Parsetree.Pstr_value (copy_rec_flag x0, List.map copy_value_binding x1) | From.Parsetree.Pstr_primitive x0 -> To.Parsetree.Pstr_primitive (copy_value_description x0) | From.Parsetree.Pstr_type (x0, x1) -> To.Parsetree.Pstr_type (copy_rec_flag x0, List.map copy_type_declaration x1) | From.Parsetree.Pstr_typext x0 -> To.Parsetree.Pstr_typext (copy_type_extension x0) | From.Parsetree.Pstr_exception x0 -> To.Parsetree.Pstr_exception (let e = copy_extension_constructor x0.From.Parsetree.ptyexn_constructor in { e with pext_attributes = e.pext_attributes @ copy_attributes x0.ptyexn_attributes; }) | From.Parsetree.Pstr_module x0 -> To.Parsetree.Pstr_module (copy_module_binding x0) | From.Parsetree.Pstr_recmodule x0 -> To.Parsetree.Pstr_recmodule (List.map copy_module_binding x0) | From.Parsetree.Pstr_modtype x0 -> To.Parsetree.Pstr_modtype (copy_module_type_declaration x0) | From.Parsetree.Pstr_open x0 -> ( match x0.From.Parsetree.popen_expr.From.Parsetree.pmod_desc with | Pmod_ident lid -> To.Parsetree.Pstr_open { To.Parsetree.popen_lid = copy_loc copy_longident lid; To.Parsetree.popen_override = copy_override_flag x0.From.Parsetree.popen_override; To.Parsetree.popen_loc = copy_location x0.From.Parsetree.popen_loc; To.Parsetree.popen_attributes = copy_attributes x0.From.Parsetree.popen_attributes; } | Pmod_structure _ | Pmod_functor _ | Pmod_apply _ | Pmod_constraint _ | Pmod_unpack _ | Pmod_extension _ -> migration_error x0.From.Parsetree.popen_loc "complex open") | From.Parsetree.Pstr_class x0 -> To.Parsetree.Pstr_class (List.map copy_class_declaration x0) | From.Parsetree.Pstr_class_type x0 -> To.Parsetree.Pstr_class_type (List.map copy_class_type_declaration x0) | From.Parsetree.Pstr_include x0 -> To.Parsetree.Pstr_include (copy_include_declaration x0) | From.Parsetree.Pstr_attribute x0 -> To.Parsetree.Pstr_attribute (copy_attribute x0) | From.Parsetree.Pstr_extension (x0, x1) -> To.Parsetree.Pstr_extension (copy_extension x0, copy_attributes x1) and copy_include_declaration : From.Parsetree.include_declaration -> To.Parsetree.include_declaration = fun x -> copy_include_infos copy_module_expr x and copy_class_declaration : From.Parsetree.class_declaration -> To.Parsetree.class_declaration = fun x -> copy_class_infos copy_class_expr x and copy_class_expr : From.Parsetree.class_expr -> To.Parsetree.class_expr = fun { From.Parsetree.pcl_desc; From.Parsetree.pcl_loc; From.Parsetree.pcl_attributes; } -> { To.Parsetree.pcl_desc = copy_class_expr_desc pcl_desc; To.Parsetree.pcl_loc = copy_location pcl_loc; To.Parsetree.pcl_attributes = copy_attributes pcl_attributes; } and copy_class_expr_desc : From.Parsetree.class_expr_desc -> To.Parsetree.class_expr_desc = function | From.Parsetree.Pcl_constr (x0, x1) -> To.Parsetree.Pcl_constr (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Pcl_structure x0 -> To.Parsetree.Pcl_structure (copy_class_structure x0) | From.Parsetree.Pcl_fun (x0, x1, x2, x3) -> To.Parsetree.Pcl_fun ( copy_arg_label x0, copy_option copy_expression x1, copy_pattern x2, copy_class_expr x3 ) | From.Parsetree.Pcl_apply (x0, x1) -> To.Parsetree.Pcl_apply ( copy_class_expr x0, List.map (fun x -> let x0, x1 = x in (copy_arg_label x0, copy_expression x1)) x1 ) | From.Parsetree.Pcl_let (x0, x1, x2) -> To.Parsetree.Pcl_let (copy_rec_flag x0, List.map copy_value_binding x1, copy_class_expr x2) | From.Parsetree.Pcl_constraint (x0, x1) -> To.Parsetree.Pcl_constraint (copy_class_expr x0, copy_class_type x1) | From.Parsetree.Pcl_extension x0 -> To.Parsetree.Pcl_extension (copy_extension x0) | From.Parsetree.Pcl_open (x0, x1) -> To.Parsetree.Pcl_open ( copy_override_flag x0.From.Parsetree.popen_override, copy_loc copy_longident x0.From.Parsetree.popen_expr, copy_class_expr x1 ) and copy_class_structure : From.Parsetree.class_structure -> To.Parsetree.class_structure = fun { From.Parsetree.pcstr_self; From.Parsetree.pcstr_fields } -> { To.Parsetree.pcstr_self = copy_pattern pcstr_self; To.Parsetree.pcstr_fields = List.map copy_class_field pcstr_fields; } and copy_class_field : From.Parsetree.class_field -> To.Parsetree.class_field = fun { From.Parsetree.pcf_desc; From.Parsetree.pcf_loc; From.Parsetree.pcf_attributes; } -> { To.Parsetree.pcf_desc = copy_class_field_desc pcf_desc; To.Parsetree.pcf_loc = copy_location pcf_loc; To.Parsetree.pcf_attributes = copy_attributes pcf_attributes; } and copy_class_field_desc : From.Parsetree.class_field_desc -> To.Parsetree.class_field_desc = function | From.Parsetree.Pcf_inherit (x0, x1, x2) -> To.Parsetree.Pcf_inherit ( copy_override_flag x0, copy_class_expr x1, copy_option (fun x -> copy_loc (fun x -> x) x) x2 ) | From.Parsetree.Pcf_val x0 -> To.Parsetree.Pcf_val (let x0, x1, x2 = x0 in (copy_loc copy_label x0, copy_mutable_flag x1, copy_class_field_kind x2)) | From.Parsetree.Pcf_method x0 -> To.Parsetree.Pcf_method (let x0, x1, x2 = x0 in (copy_loc copy_label x0, copy_private_flag x1, copy_class_field_kind x2)) | From.Parsetree.Pcf_constraint x0 -> To.Parsetree.Pcf_constraint (let x0, x1 = x0 in (copy_core_type x0, copy_core_type x1)) | From.Parsetree.Pcf_initializer x0 -> To.Parsetree.Pcf_initializer (copy_expression x0) | From.Parsetree.Pcf_attribute x0 -> To.Parsetree.Pcf_attribute (copy_attribute x0) | From.Parsetree.Pcf_extension x0 -> To.Parsetree.Pcf_extension (copy_extension x0) and copy_class_field_kind : From.Parsetree.class_field_kind -> To.Parsetree.class_field_kind = function | From.Parsetree.Cfk_virtual x0 -> To.Parsetree.Cfk_virtual (copy_core_type x0) | From.Parsetree.Cfk_concrete (x0, x1) -> To.Parsetree.Cfk_concrete (copy_override_flag x0, copy_expression x1) and copy_module_binding : From.Parsetree.module_binding -> To.Parsetree.module_binding = fun { From.Parsetree.pmb_name; From.Parsetree.pmb_expr; From.Parsetree.pmb_attributes; From.Parsetree.pmb_loc; } -> { To.Parsetree.pmb_name = copy_loc (fun x -> x) pmb_name; To.Parsetree.pmb_expr = copy_module_expr pmb_expr; To.Parsetree.pmb_attributes = copy_attributes pmb_attributes; To.Parsetree.pmb_loc = copy_location pmb_loc; } and copy_module_expr : From.Parsetree.module_expr -> To.Parsetree.module_expr = fun { From.Parsetree.pmod_desc; From.Parsetree.pmod_loc; From.Parsetree.pmod_attributes; } -> { To.Parsetree.pmod_desc = copy_module_expr_desc pmod_desc; To.Parsetree.pmod_loc = copy_location pmod_loc; To.Parsetree.pmod_attributes = copy_attributes pmod_attributes; } and copy_module_expr_desc : From.Parsetree.module_expr_desc -> To.Parsetree.module_expr_desc = function | From.Parsetree.Pmod_ident x0 -> To.Parsetree.Pmod_ident (copy_loc copy_longident x0) | From.Parsetree.Pmod_structure x0 -> To.Parsetree.Pmod_structure (copy_structure x0) | From.Parsetree.Pmod_functor (x0, x1, x2) -> To.Parsetree.Pmod_functor ( copy_loc (fun x -> x) x0, copy_option copy_module_type x1, copy_module_expr x2 ) | From.Parsetree.Pmod_apply (x0, x1) -> To.Parsetree.Pmod_apply (copy_module_expr x0, copy_module_expr x1) | From.Parsetree.Pmod_constraint (x0, x1) -> To.Parsetree.Pmod_constraint (copy_module_expr x0, copy_module_type x1) | From.Parsetree.Pmod_unpack x0 -> To.Parsetree.Pmod_unpack (copy_expression x0) | From.Parsetree.Pmod_extension x0 -> To.Parsetree.Pmod_extension (copy_extension x0) and copy_module_type : From.Parsetree.module_type -> To.Parsetree.module_type = fun { From.Parsetree.pmty_desc; From.Parsetree.pmty_loc; From.Parsetree.pmty_attributes; } -> { To.Parsetree.pmty_desc = copy_module_type_desc pmty_desc; To.Parsetree.pmty_loc = copy_location pmty_loc; To.Parsetree.pmty_attributes = copy_attributes pmty_attributes; } and copy_module_type_desc : From.Parsetree.module_type_desc -> To.Parsetree.module_type_desc = function | From.Parsetree.Pmty_ident x0 -> To.Parsetree.Pmty_ident (copy_loc copy_longident x0) | From.Parsetree.Pmty_signature x0 -> To.Parsetree.Pmty_signature (copy_signature x0) | From.Parsetree.Pmty_functor (x0, x1, x2) -> To.Parsetree.Pmty_functor ( copy_loc (fun x -> x) x0, copy_option copy_module_type x1, copy_module_type x2 ) | From.Parsetree.Pmty_with (x0, x1) -> To.Parsetree.Pmty_with (copy_module_type x0, List.map copy_with_constraint x1) | From.Parsetree.Pmty_typeof x0 -> To.Parsetree.Pmty_typeof (copy_module_expr x0) | From.Parsetree.Pmty_extension x0 -> To.Parsetree.Pmty_extension (copy_extension x0) | From.Parsetree.Pmty_alias x0 -> To.Parsetree.Pmty_alias (copy_loc copy_longident x0) and copy_with_constraint : From.Parsetree.with_constraint -> To.Parsetree.with_constraint = function | From.Parsetree.Pwith_type (x0, x1) -> To.Parsetree.Pwith_type (copy_loc copy_longident x0, copy_type_declaration x1) | From.Parsetree.Pwith_module (x0, x1) -> To.Parsetree.Pwith_module (copy_loc copy_longident x0, copy_loc copy_longident x1) | From.Parsetree.Pwith_typesubst (x0, x1) -> To.Parsetree.Pwith_typesubst (copy_loc copy_longident x0, copy_type_declaration x1) | From.Parsetree.Pwith_modsubst (x0, x1) -> To.Parsetree.Pwith_modsubst (copy_loc copy_longident x0, copy_loc copy_longident x1) and copy_signature : From.Parsetree.signature -> To.Parsetree.signature = fun x -> List.map copy_signature_item x and copy_signature_item : From.Parsetree.signature_item -> To.Parsetree.signature_item = fun { From.Parsetree.psig_desc; From.Parsetree.psig_loc } -> { To.Parsetree.psig_desc = copy_signature_item_desc psig_desc; To.Parsetree.psig_loc = copy_location psig_loc; } and copy_signature_item_desc : From.Parsetree.signature_item_desc -> To.Parsetree.signature_item_desc = function | From.Parsetree.Psig_value x0 -> To.Parsetree.Psig_value (copy_value_description x0) | From.Parsetree.Psig_type (x0, x1) -> To.Parsetree.Psig_type (copy_rec_flag x0, List.map copy_type_declaration x1) | From.Parsetree.Psig_typesubst x0 -> let x0_loc = match x0 with | [] -> Location.none | { From.Parsetree.ptype_loc; _ } :: _ -> ptype_loc in migration_error x0_loc "type substitution in signatures" | From.Parsetree.Psig_typext x0 -> To.Parsetree.Psig_typext (copy_type_extension x0) | From.Parsetree.Psig_exception x0 -> To.Parsetree.Psig_exception (let e = copy_extension_constructor x0.From.Parsetree.ptyexn_constructor in { e with pext_attributes = e.pext_attributes @ copy_attributes x0.ptyexn_attributes; }) | From.Parsetree.Psig_module x0 -> To.Parsetree.Psig_module (copy_module_declaration x0) | From.Parsetree.Psig_modsubst x0 -> migration_error x0.pms_loc "module substitution in signatures" | From.Parsetree.Psig_recmodule x0 -> To.Parsetree.Psig_recmodule (List.map copy_module_declaration x0) | From.Parsetree.Psig_modtype x0 -> To.Parsetree.Psig_modtype (copy_module_type_declaration x0) | From.Parsetree.Psig_open x0 -> To.Parsetree.Psig_open (copy_open_description x0) | From.Parsetree.Psig_include x0 -> To.Parsetree.Psig_include (copy_include_description x0) | From.Parsetree.Psig_class x0 -> To.Parsetree.Psig_class (List.map copy_class_description x0) | From.Parsetree.Psig_class_type x0 -> To.Parsetree.Psig_class_type (List.map copy_class_type_declaration x0) | From.Parsetree.Psig_attribute x0 -> To.Parsetree.Psig_attribute (copy_attribute x0) | From.Parsetree.Psig_extension (x0, x1) -> To.Parsetree.Psig_extension (copy_extension x0, copy_attributes x1) and copy_class_type_declaration : From.Parsetree.class_type_declaration -> To.Parsetree.class_type_declaration = fun x -> copy_class_infos copy_class_type x and copy_class_description : From.Parsetree.class_description -> To.Parsetree.class_description = fun x -> copy_class_infos copy_class_type x and copy_class_type : From.Parsetree.class_type -> To.Parsetree.class_type = fun { From.Parsetree.pcty_desc; From.Parsetree.pcty_loc; From.Parsetree.pcty_attributes; } -> { To.Parsetree.pcty_desc = copy_class_type_desc pcty_desc; To.Parsetree.pcty_loc = copy_location pcty_loc; To.Parsetree.pcty_attributes = copy_attributes pcty_attributes; } and copy_class_type_desc : From.Parsetree.class_type_desc -> To.Parsetree.class_type_desc = function | From.Parsetree.Pcty_constr (x0, x1) -> To.Parsetree.Pcty_constr (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Pcty_signature x0 -> To.Parsetree.Pcty_signature (copy_class_signature x0) | From.Parsetree.Pcty_arrow (x0, x1, x2) -> To.Parsetree.Pcty_arrow (copy_arg_label x0, copy_core_type x1, copy_class_type x2) | From.Parsetree.Pcty_extension x0 -> To.Parsetree.Pcty_extension (copy_extension x0) | From.Parsetree.Pcty_open (x0, x1) -> To.Parsetree.Pcty_open ( copy_override_flag x0.From.Parsetree.popen_override, copy_loc copy_longident x0.From.Parsetree.popen_expr, copy_class_type x1 ) and copy_class_signature : From.Parsetree.class_signature -> To.Parsetree.class_signature = fun { From.Parsetree.pcsig_self; From.Parsetree.pcsig_fields } -> { To.Parsetree.pcsig_self = copy_core_type pcsig_self; To.Parsetree.pcsig_fields = List.map copy_class_type_field pcsig_fields; } and copy_class_type_field : From.Parsetree.class_type_field -> To.Parsetree.class_type_field = fun { From.Parsetree.pctf_desc; From.Parsetree.pctf_loc; From.Parsetree.pctf_attributes; } -> { To.Parsetree.pctf_desc = copy_class_type_field_desc pctf_desc; To.Parsetree.pctf_loc = copy_location pctf_loc; To.Parsetree.pctf_attributes = copy_attributes pctf_attributes; } and copy_class_type_field_desc : From.Parsetree.class_type_field_desc -> To.Parsetree.class_type_field_desc = function | From.Parsetree.Pctf_inherit x0 -> To.Parsetree.Pctf_inherit (copy_class_type x0) | From.Parsetree.Pctf_val x0 -> To.Parsetree.Pctf_val (let x0, x1, x2, x3 = x0 in ( copy_loc copy_label x0, copy_mutable_flag x1, copy_virtual_flag x2, copy_core_type x3 )) | From.Parsetree.Pctf_method x0 -> To.Parsetree.Pctf_method (let x0, x1, x2, x3 = x0 in ( copy_loc copy_label x0, copy_private_flag x1, copy_virtual_flag x2, copy_core_type x3 )) | From.Parsetree.Pctf_constraint x0 -> To.Parsetree.Pctf_constraint (let x0, x1 = x0 in (copy_core_type x0, copy_core_type x1)) | From.Parsetree.Pctf_attribute x0 -> To.Parsetree.Pctf_attribute (copy_attribute x0) | From.Parsetree.Pctf_extension x0 -> To.Parsetree.Pctf_extension (copy_extension x0) and copy_extension : From.Parsetree.extension -> To.Parsetree.extension = fun x -> let x0, x1 = x in let x1 = match x0.txt with | "ocaml.error" | "error" -> ( match x1 with | PStr (hd :: tl) -> From.Parsetree.PStr (hd :: hd :: tl) | _ -> x1) | _ -> x1 in (copy_loc (fun x -> x) x0, copy_payload x1) and copy_class_infos : 'f0 'g0. ('f0 -> 'g0) -> 'f0 From.Parsetree.class_infos -> 'g0 To.Parsetree.class_infos = fun f0 { From.Parsetree.pci_virt; From.Parsetree.pci_params; From.Parsetree.pci_name; From.Parsetree.pci_expr; From.Parsetree.pci_loc; From.Parsetree.pci_attributes; } -> { To.Parsetree.pci_virt = copy_virtual_flag pci_virt; To.Parsetree.pci_params = List.map (fun x -> let x0, x1 = x in (copy_core_type x0, copy_variance x1)) pci_params; To.Parsetree.pci_name = copy_loc (fun x -> x) pci_name; To.Parsetree.pci_expr = f0 pci_expr; To.Parsetree.pci_loc = copy_location pci_loc; To.Parsetree.pci_attributes = copy_attributes pci_attributes; } and copy_virtual_flag : From.Asttypes.virtual_flag -> To.Asttypes.virtual_flag = function | From.Asttypes.Virtual -> To.Asttypes.Virtual | From.Asttypes.Concrete -> To.Asttypes.Concrete and copy_include_description : From.Parsetree.include_description -> To.Parsetree.include_description = fun x -> copy_include_infos copy_module_type x and copy_include_infos : 'f0 'g0. ('f0 -> 'g0) -> 'f0 From.Parsetree.include_infos -> 'g0 To.Parsetree.include_infos = fun f0 { From.Parsetree.pincl_mod; From.Parsetree.pincl_loc; From.Parsetree.pincl_attributes; } -> { To.Parsetree.pincl_mod = f0 pincl_mod; To.Parsetree.pincl_loc = copy_location pincl_loc; To.Parsetree.pincl_attributes = copy_attributes pincl_attributes; } and copy_open_description : From.Parsetree.open_description -> To.Parsetree.open_description = fun { From.Parsetree.popen_expr; From.Parsetree.popen_override; From.Parsetree.popen_loc; From.Parsetree.popen_attributes; } -> { To.Parsetree.popen_lid = copy_loc copy_longident popen_expr; To.Parsetree.popen_override = copy_override_flag popen_override; To.Parsetree.popen_loc = copy_location popen_loc; To.Parsetree.popen_attributes = copy_attributes popen_attributes; } and copy_override_flag : From.Asttypes.override_flag -> To.Asttypes.override_flag = function | From.Asttypes.Override -> To.Asttypes.Override | From.Asttypes.Fresh -> To.Asttypes.Fresh and copy_module_type_declaration : From.Parsetree.module_type_declaration -> To.Parsetree.module_type_declaration = fun { From.Parsetree.pmtd_name; From.Parsetree.pmtd_type; From.Parsetree.pmtd_attributes; From.Parsetree.pmtd_loc; } -> { To.Parsetree.pmtd_name = copy_loc (fun x -> x) pmtd_name; To.Parsetree.pmtd_type = copy_option copy_module_type pmtd_type; To.Parsetree.pmtd_attributes = copy_attributes pmtd_attributes; To.Parsetree.pmtd_loc = copy_location pmtd_loc; } and copy_module_declaration : From.Parsetree.module_declaration -> To.Parsetree.module_declaration = fun { From.Parsetree.pmd_name; From.Parsetree.pmd_type; From.Parsetree.pmd_attributes; From.Parsetree.pmd_loc; } -> { To.Parsetree.pmd_name = copy_loc (fun x -> x) pmd_name; To.Parsetree.pmd_type = copy_module_type pmd_type; To.Parsetree.pmd_attributes = copy_attributes pmd_attributes; To.Parsetree.pmd_loc = copy_location pmd_loc; } (* and copy_type_exception : From.Parsetree.type_exception -> To.Parsetree.type_exception = fun { From.Parsetree.ptyexn_constructor = ptyexn_constructor; From.Parsetree.ptyexn_loc = ptyexn_loc; From.Parsetree.ptyexn_attributes = ptyexn_attributes } -> { To.Parsetree.ptyexn_constructor = (copy_extension_constructor ptyexn_constructor); To.Parsetree.ptyexn_loc = (copy_location ptyexn_loc); To.Parsetree.ptyexn_attributes = (copy_attributes ptyexn_attributes) }*) and copy_type_extension : From.Parsetree.type_extension -> To.Parsetree.type_extension = fun { From.Parsetree.ptyext_path; From.Parsetree.ptyext_params; From.Parsetree.ptyext_constructors; From.Parsetree.ptyext_private; From.Parsetree.ptyext_loc = _; From.Parsetree.ptyext_attributes; } -> { To.Parsetree.ptyext_path = copy_loc copy_longident ptyext_path; To.Parsetree.ptyext_params = List.map (fun x -> let x0, x1 = x in (copy_core_type x0, copy_variance x1)) ptyext_params; To.Parsetree.ptyext_constructors = List.map copy_extension_constructor ptyext_constructors; To.Parsetree.ptyext_private = copy_private_flag ptyext_private; To.Parsetree.ptyext_attributes = copy_attributes ptyext_attributes; } and copy_extension_constructor : From.Parsetree.extension_constructor -> To.Parsetree.extension_constructor = fun { From.Parsetree.pext_name; From.Parsetree.pext_kind; From.Parsetree.pext_loc; From.Parsetree.pext_attributes; } -> { To.Parsetree.pext_name = copy_loc (fun x -> x) pext_name; To.Parsetree.pext_kind = copy_extension_constructor_kind pext_kind; To.Parsetree.pext_loc = copy_location pext_loc; To.Parsetree.pext_attributes = copy_attributes pext_attributes; } and copy_extension_constructor_kind : From.Parsetree.extension_constructor_kind -> To.Parsetree.extension_constructor_kind = function | From.Parsetree.Pext_decl (x0, x1) -> To.Parsetree.Pext_decl (copy_constructor_arguments x0, copy_option copy_core_type x1) | From.Parsetree.Pext_rebind x0 -> To.Parsetree.Pext_rebind (copy_loc copy_longident x0) and copy_type_declaration : From.Parsetree.type_declaration -> To.Parsetree.type_declaration = fun { From.Parsetree.ptype_name; From.Parsetree.ptype_params; From.Parsetree.ptype_cstrs; From.Parsetree.ptype_kind; From.Parsetree.ptype_private; From.Parsetree.ptype_manifest; From.Parsetree.ptype_attributes; From.Parsetree.ptype_loc; } -> { To.Parsetree.ptype_name = copy_loc (fun x -> x) ptype_name; To.Parsetree.ptype_params = List.map (fun x -> let x0, x1 = x in (copy_core_type x0, copy_variance x1)) ptype_params; To.Parsetree.ptype_cstrs = List.map (fun x -> let x0, x1, x2 = x in (copy_core_type x0, copy_core_type x1, copy_location x2)) ptype_cstrs; To.Parsetree.ptype_kind = copy_type_kind ptype_kind; To.Parsetree.ptype_private = copy_private_flag ptype_private; To.Parsetree.ptype_manifest = copy_option copy_core_type ptype_manifest; To.Parsetree.ptype_attributes = copy_attributes ptype_attributes; To.Parsetree.ptype_loc = copy_location ptype_loc; } and copy_private_flag : From.Asttypes.private_flag -> To.Asttypes.private_flag = function | From.Asttypes.Private -> To.Asttypes.Private | From.Asttypes.Public -> To.Asttypes.Public and copy_type_kind : From.Parsetree.type_kind -> To.Parsetree.type_kind = function | From.Parsetree.Ptype_abstract -> To.Parsetree.Ptype_abstract | From.Parsetree.Ptype_variant x0 -> To.Parsetree.Ptype_variant (List.map copy_constructor_declaration x0) | From.Parsetree.Ptype_record x0 -> To.Parsetree.Ptype_record (List.map copy_label_declaration x0) | From.Parsetree.Ptype_open -> To.Parsetree.Ptype_open and copy_constructor_declaration : From.Parsetree.constructor_declaration -> To.Parsetree.constructor_declaration = fun { From.Parsetree.pcd_name; From.Parsetree.pcd_args; From.Parsetree.pcd_res; From.Parsetree.pcd_loc; From.Parsetree.pcd_attributes; } -> { To.Parsetree.pcd_name = copy_loc (fun x -> x) pcd_name; To.Parsetree.pcd_args = copy_constructor_arguments pcd_args; To.Parsetree.pcd_res = copy_option copy_core_type pcd_res; To.Parsetree.pcd_loc = copy_location pcd_loc; To.Parsetree.pcd_attributes = copy_attributes pcd_attributes; } and copy_constructor_arguments : From.Parsetree.constructor_arguments -> To.Parsetree.constructor_arguments = function | From.Parsetree.Pcstr_tuple x0 -> To.Parsetree.Pcstr_tuple (List.map copy_core_type x0) | From.Parsetree.Pcstr_record x0 -> To.Parsetree.Pcstr_record (List.map copy_label_declaration x0) and copy_label_declaration : From.Parsetree.label_declaration -> To.Parsetree.label_declaration = fun { From.Parsetree.pld_name; From.Parsetree.pld_mutable; From.Parsetree.pld_type; From.Parsetree.pld_loc; From.Parsetree.pld_attributes; } -> { To.Parsetree.pld_name = copy_loc (fun x -> x) pld_name; To.Parsetree.pld_mutable = copy_mutable_flag pld_mutable; To.Parsetree.pld_type = copy_core_type pld_type; To.Parsetree.pld_loc = copy_location pld_loc; To.Parsetree.pld_attributes = copy_attributes pld_attributes; } and copy_mutable_flag : From.Asttypes.mutable_flag -> To.Asttypes.mutable_flag = function | From.Asttypes.Immutable -> To.Asttypes.Immutable | From.Asttypes.Mutable -> To.Asttypes.Mutable and copy_variance : From.Asttypes.variance -> To.Asttypes.variance = function | From.Asttypes.Covariant -> To.Asttypes.Covariant | From.Asttypes.Contravariant -> To.Asttypes.Contravariant | From.Asttypes.Invariant -> To.Asttypes.Invariant and copy_value_description : From.Parsetree.value_description -> To.Parsetree.value_description = fun { From.Parsetree.pval_name; From.Parsetree.pval_type; From.Parsetree.pval_prim; From.Parsetree.pval_attributes; From.Parsetree.pval_loc; } -> { To.Parsetree.pval_name = copy_loc (fun x -> x) pval_name; To.Parsetree.pval_type = copy_core_type pval_type; To.Parsetree.pval_prim = List.map (fun x -> x) pval_prim; To.Parsetree.pval_attributes = copy_attributes pval_attributes; To.Parsetree.pval_loc = copy_location pval_loc; } and copy_arg_label : From.Asttypes.arg_label -> To.Asttypes.arg_label = function | From.Asttypes.Nolabel -> To.Asttypes.Nolabel | From.Asttypes.Labelled x0 -> To.Asttypes.Labelled x0 | From.Asttypes.Optional x0 -> To.Asttypes.Optional x0 and copy_closed_flag : From.Asttypes.closed_flag -> To.Asttypes.closed_flag = function | From.Asttypes.Closed -> To.Asttypes.Closed | From.Asttypes.Open -> To.Asttypes.Open and copy_label : From.Asttypes.label -> To.Asttypes.label = fun x -> x and copy_rec_flag : From.Asttypes.rec_flag -> To.Asttypes.rec_flag = function | From.Asttypes.Nonrecursive -> To.Asttypes.Nonrecursive | From.Asttypes.Recursive -> To.Asttypes.Recursive and copy_constant : From.Parsetree.constant -> To.Parsetree.constant = function | From.Parsetree.Pconst_integer (x0, x1) -> To.Parsetree.Pconst_integer (x0, copy_option (fun x -> x) x1) | From.Parsetree.Pconst_char x0 -> To.Parsetree.Pconst_char x0 | From.Parsetree.Pconst_string (x0, x1) -> To.Parsetree.Pconst_string (x0, copy_option (fun x -> x) x1) | From.Parsetree.Pconst_float (x0, x1) -> To.Parsetree.Pconst_float (x0, copy_option (fun x -> x) x1) and copy_option : 'f0 'g0. ('f0 -> 'g0) -> 'f0 option -> 'g0 option = fun f0 -> function None -> None | Some x0 -> Some (f0 x0) and copy_longident : Longident.t -> Longident.t = fun x -> x and copy_loc : 'f0 'g0. ('f0 -> 'g0) -> 'f0 From.Asttypes.loc -> 'g0 To.Asttypes.loc = fun f0 { From.Asttypes.txt; From.Asttypes.loc } -> { To.Asttypes.txt = f0 txt; To.Asttypes.loc = copy_location loc } and copy_location : Location.t -> Location.t = fun x -> x and copy_bool : bool -> bool = function false -> false | true -> true let copy_cases x = List.map copy_case x let copy_pat = copy_pattern let copy_expr = copy_expression let copy_typ = copy_core_type
null
https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/ppxlib/astlib/migrate_408_407.ml
ocaml
and copy_type_exception : From.Parsetree.type_exception -> To.Parsetree.type_exception = fun { From.Parsetree.ptyexn_constructor = ptyexn_constructor; From.Parsetree.ptyexn_loc = ptyexn_loc; From.Parsetree.ptyexn_attributes = ptyexn_attributes } -> { To.Parsetree.ptyexn_constructor = (copy_extension_constructor ptyexn_constructor); To.Parsetree.ptyexn_loc = (copy_location ptyexn_loc); To.Parsetree.ptyexn_attributes = (copy_attributes ptyexn_attributes) }
module From = Ast_408 module To = Ast_407 let migration_error loc missing_feature = Location.raise_errorf ~loc "migration error: %s is not supported before OCaml 4.08" missing_feature let rec copy_toplevel_phrase : From.Parsetree.toplevel_phrase -> To.Parsetree.toplevel_phrase = function | From.Parsetree.Ptop_def x0 -> To.Parsetree.Ptop_def (copy_structure x0) | From.Parsetree.Ptop_dir { From.Parsetree.pdir_name; From.Parsetree.pdir_arg; From.Parsetree.pdir_loc = _; } -> To.Parsetree.Ptop_dir ( pdir_name.Location.txt, match pdir_arg with | None -> To.Parsetree.Pdir_none | Some arg -> copy_directive_argument arg ) and copy_directive_argument : From.Parsetree.directive_argument -> To.Parsetree.directive_argument = fun { From.Parsetree.pdira_desc; From.Parsetree.pdira_loc = _pdira_loc } -> copy_directive_argument_desc pdira_desc and copy_directive_argument_desc : From.Parsetree.directive_argument_desc -> To.Parsetree.directive_argument = function | From.Parsetree.Pdir_string x0 -> To.Parsetree.Pdir_string x0 | From.Parsetree.Pdir_int (x0, x1) -> To.Parsetree.Pdir_int (x0, copy_option (fun x -> x) x1) | From.Parsetree.Pdir_ident x0 -> To.Parsetree.Pdir_ident (copy_longident x0) | From.Parsetree.Pdir_bool x0 -> To.Parsetree.Pdir_bool (copy_bool x0) and copy_expression : From.Parsetree.expression -> To.Parsetree.expression = fun { From.Parsetree.pexp_desc; From.Parsetree.pexp_loc; From.Parsetree.pexp_loc_stack = _; From.Parsetree.pexp_attributes; } -> { To.Parsetree.pexp_desc = copy_expression_desc pexp_desc; To.Parsetree.pexp_loc = copy_location pexp_loc; To.Parsetree.pexp_attributes = copy_attributes pexp_attributes; } and copy_expression_desc : From.Parsetree.expression_desc -> To.Parsetree.expression_desc = function | From.Parsetree.Pexp_ident x0 -> To.Parsetree.Pexp_ident (copy_loc copy_longident x0) | From.Parsetree.Pexp_constant x0 -> To.Parsetree.Pexp_constant (copy_constant x0) | From.Parsetree.Pexp_let (x0, x1, x2) -> To.Parsetree.Pexp_let (copy_rec_flag x0, List.map copy_value_binding x1, copy_expression x2) | From.Parsetree.Pexp_function x0 -> To.Parsetree.Pexp_function (List.map copy_case x0) | From.Parsetree.Pexp_fun (x0, x1, x2, x3) -> To.Parsetree.Pexp_fun ( copy_arg_label x0, copy_option copy_expression x1, copy_pattern x2, copy_expression x3 ) | From.Parsetree.Pexp_apply (x0, x1) -> To.Parsetree.Pexp_apply ( copy_expression x0, List.map (fun x -> let x0, x1 = x in (copy_arg_label x0, copy_expression x1)) x1 ) | From.Parsetree.Pexp_match (x0, x1) -> To.Parsetree.Pexp_match (copy_expression x0, List.map copy_case x1) | From.Parsetree.Pexp_try (x0, x1) -> To.Parsetree.Pexp_try (copy_expression x0, List.map copy_case x1) | From.Parsetree.Pexp_tuple x0 -> To.Parsetree.Pexp_tuple (List.map copy_expression x0) | From.Parsetree.Pexp_construct (x0, x1) -> To.Parsetree.Pexp_construct (copy_loc copy_longident x0, copy_option copy_expression x1) | From.Parsetree.Pexp_variant (x0, x1) -> To.Parsetree.Pexp_variant (copy_label x0, copy_option copy_expression x1) | From.Parsetree.Pexp_record (x0, x1) -> To.Parsetree.Pexp_record ( List.map (fun x -> let x0, x1 = x in (copy_loc copy_longident x0, copy_expression x1)) x0, copy_option copy_expression x1 ) | From.Parsetree.Pexp_field (x0, x1) -> To.Parsetree.Pexp_field (copy_expression x0, copy_loc copy_longident x1) | From.Parsetree.Pexp_setfield (x0, x1, x2) -> To.Parsetree.Pexp_setfield (copy_expression x0, copy_loc copy_longident x1, copy_expression x2) | From.Parsetree.Pexp_array x0 -> To.Parsetree.Pexp_array (List.map copy_expression x0) | From.Parsetree.Pexp_ifthenelse (x0, x1, x2) -> To.Parsetree.Pexp_ifthenelse (copy_expression x0, copy_expression x1, copy_option copy_expression x2) | From.Parsetree.Pexp_sequence (x0, x1) -> To.Parsetree.Pexp_sequence (copy_expression x0, copy_expression x1) | From.Parsetree.Pexp_while (x0, x1) -> To.Parsetree.Pexp_while (copy_expression x0, copy_expression x1) | From.Parsetree.Pexp_for (x0, x1, x2, x3, x4) -> To.Parsetree.Pexp_for ( copy_pattern x0, copy_expression x1, copy_expression x2, copy_direction_flag x3, copy_expression x4 ) | From.Parsetree.Pexp_constraint (x0, x1) -> To.Parsetree.Pexp_constraint (copy_expression x0, copy_core_type x1) | From.Parsetree.Pexp_coerce (x0, x1, x2) -> To.Parsetree.Pexp_coerce (copy_expression x0, copy_option copy_core_type x1, copy_core_type x2) | From.Parsetree.Pexp_send (x0, x1) -> To.Parsetree.Pexp_send (copy_expression x0, copy_loc copy_label x1) | From.Parsetree.Pexp_new x0 -> To.Parsetree.Pexp_new (copy_loc copy_longident x0) | From.Parsetree.Pexp_setinstvar (x0, x1) -> To.Parsetree.Pexp_setinstvar (copy_loc copy_label x0, copy_expression x1) | From.Parsetree.Pexp_override x0 -> To.Parsetree.Pexp_override (List.map (fun x -> let x0, x1 = x in (copy_loc copy_label x0, copy_expression x1)) x0) | From.Parsetree.Pexp_letmodule (x0, x1, x2) -> To.Parsetree.Pexp_letmodule (copy_loc (fun x -> x) x0, copy_module_expr x1, copy_expression x2) | From.Parsetree.Pexp_letexception (x0, x1) -> To.Parsetree.Pexp_letexception (copy_extension_constructor x0, copy_expression x1) | From.Parsetree.Pexp_assert x0 -> To.Parsetree.Pexp_assert (copy_expression x0) | From.Parsetree.Pexp_lazy x0 -> To.Parsetree.Pexp_lazy (copy_expression x0) | From.Parsetree.Pexp_poly (x0, x1) -> To.Parsetree.Pexp_poly (copy_expression x0, copy_option copy_core_type x1) | From.Parsetree.Pexp_object x0 -> To.Parsetree.Pexp_object (copy_class_structure x0) | From.Parsetree.Pexp_newtype (x0, x1) -> To.Parsetree.Pexp_newtype (copy_loc (fun x -> x) x0, copy_expression x1) | From.Parsetree.Pexp_pack x0 -> To.Parsetree.Pexp_pack (copy_module_expr x0) | From.Parsetree.Pexp_open (x0, x1) -> ( match x0.From.Parsetree.popen_expr.From.Parsetree.pmod_desc with | Pmod_ident lid -> To.Parsetree.Pexp_open ( copy_override_flag x0.From.Parsetree.popen_override, copy_loc copy_longident lid, copy_expression x1 ) | Pmod_structure _ | Pmod_functor _ | Pmod_apply _ | Pmod_constraint _ | Pmod_unpack _ | Pmod_extension _ -> migration_error x0.From.Parsetree.popen_loc "complex open") | From.Parsetree.Pexp_letop { let_; ands = _; body = _ } -> migration_error let_.pbop_op.loc "let operators" | From.Parsetree.Pexp_extension x0 -> To.Parsetree.Pexp_extension (copy_extension x0) | From.Parsetree.Pexp_unreachable -> To.Parsetree.Pexp_unreachable and copy_direction_flag : From.Asttypes.direction_flag -> To.Asttypes.direction_flag = function | From.Asttypes.Upto -> To.Asttypes.Upto | From.Asttypes.Downto -> To.Asttypes.Downto and copy_case : From.Parsetree.case -> To.Parsetree.case = fun { From.Parsetree.pc_lhs; From.Parsetree.pc_guard; From.Parsetree.pc_rhs } -> { To.Parsetree.pc_lhs = copy_pattern pc_lhs; To.Parsetree.pc_guard = copy_option copy_expression pc_guard; To.Parsetree.pc_rhs = copy_expression pc_rhs; } and copy_value_binding : From.Parsetree.value_binding -> To.Parsetree.value_binding = fun { From.Parsetree.pvb_pat; From.Parsetree.pvb_expr; From.Parsetree.pvb_attributes; From.Parsetree.pvb_loc; } -> { To.Parsetree.pvb_pat = copy_pattern pvb_pat; To.Parsetree.pvb_expr = copy_expression pvb_expr; To.Parsetree.pvb_attributes = copy_attributes pvb_attributes; To.Parsetree.pvb_loc = copy_location pvb_loc; } and copy_pattern : From.Parsetree.pattern -> To.Parsetree.pattern = fun { From.Parsetree.ppat_desc; From.Parsetree.ppat_loc; From.Parsetree.ppat_loc_stack = _; From.Parsetree.ppat_attributes; } -> { To.Parsetree.ppat_desc = copy_pattern_desc ppat_desc; To.Parsetree.ppat_loc = copy_location ppat_loc; To.Parsetree.ppat_attributes = copy_attributes ppat_attributes; } and copy_pattern_desc : From.Parsetree.pattern_desc -> To.Parsetree.pattern_desc = function | From.Parsetree.Ppat_any -> To.Parsetree.Ppat_any | From.Parsetree.Ppat_var x0 -> To.Parsetree.Ppat_var (copy_loc (fun x -> x) x0) | From.Parsetree.Ppat_alias (x0, x1) -> To.Parsetree.Ppat_alias (copy_pattern x0, copy_loc (fun x -> x) x1) | From.Parsetree.Ppat_constant x0 -> To.Parsetree.Ppat_constant (copy_constant x0) | From.Parsetree.Ppat_interval (x0, x1) -> To.Parsetree.Ppat_interval (copy_constant x0, copy_constant x1) | From.Parsetree.Ppat_tuple x0 -> To.Parsetree.Ppat_tuple (List.map copy_pattern x0) | From.Parsetree.Ppat_construct (x0, x1) -> To.Parsetree.Ppat_construct (copy_loc copy_longident x0, copy_option copy_pattern x1) | From.Parsetree.Ppat_variant (x0, x1) -> To.Parsetree.Ppat_variant (copy_label x0, copy_option copy_pattern x1) | From.Parsetree.Ppat_record (x0, x1) -> To.Parsetree.Ppat_record ( List.map (fun x -> let x0, x1 = x in (copy_loc copy_longident x0, copy_pattern x1)) x0, copy_closed_flag x1 ) | From.Parsetree.Ppat_array x0 -> To.Parsetree.Ppat_array (List.map copy_pattern x0) | From.Parsetree.Ppat_or (x0, x1) -> To.Parsetree.Ppat_or (copy_pattern x0, copy_pattern x1) | From.Parsetree.Ppat_constraint (x0, x1) -> To.Parsetree.Ppat_constraint (copy_pattern x0, copy_core_type x1) | From.Parsetree.Ppat_type x0 -> To.Parsetree.Ppat_type (copy_loc copy_longident x0) | From.Parsetree.Ppat_lazy x0 -> To.Parsetree.Ppat_lazy (copy_pattern x0) | From.Parsetree.Ppat_unpack x0 -> To.Parsetree.Ppat_unpack (copy_loc (fun x -> x) x0) | From.Parsetree.Ppat_exception x0 -> To.Parsetree.Ppat_exception (copy_pattern x0) | From.Parsetree.Ppat_extension x0 -> To.Parsetree.Ppat_extension (copy_extension x0) | From.Parsetree.Ppat_open (x0, x1) -> To.Parsetree.Ppat_open (copy_loc copy_longident x0, copy_pattern x1) and copy_core_type : From.Parsetree.core_type -> To.Parsetree.core_type = fun { From.Parsetree.ptyp_desc; From.Parsetree.ptyp_loc; From.Parsetree.ptyp_loc_stack = _; From.Parsetree.ptyp_attributes; } -> { To.Parsetree.ptyp_desc = copy_core_type_desc ptyp_desc; To.Parsetree.ptyp_loc = copy_location ptyp_loc; To.Parsetree.ptyp_attributes = copy_attributes ptyp_attributes; } and copy_core_type_desc : From.Parsetree.core_type_desc -> To.Parsetree.core_type_desc = function | From.Parsetree.Ptyp_any -> To.Parsetree.Ptyp_any | From.Parsetree.Ptyp_var x0 -> To.Parsetree.Ptyp_var x0 | From.Parsetree.Ptyp_arrow (x0, x1, x2) -> To.Parsetree.Ptyp_arrow (copy_arg_label x0, copy_core_type x1, copy_core_type x2) | From.Parsetree.Ptyp_tuple x0 -> To.Parsetree.Ptyp_tuple (List.map copy_core_type x0) | From.Parsetree.Ptyp_constr (x0, x1) -> To.Parsetree.Ptyp_constr (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Ptyp_object (x0, x1) -> To.Parsetree.Ptyp_object (List.map copy_object_field x0, copy_closed_flag x1) | From.Parsetree.Ptyp_class (x0, x1) -> To.Parsetree.Ptyp_class (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Ptyp_alias (x0, x1) -> To.Parsetree.Ptyp_alias (copy_core_type x0, x1) | From.Parsetree.Ptyp_variant (x0, x1, x2) -> To.Parsetree.Ptyp_variant ( List.map copy_row_field x0, copy_closed_flag x1, copy_option (fun x -> List.map copy_label x) x2 ) | From.Parsetree.Ptyp_poly (x0, x1) -> To.Parsetree.Ptyp_poly (List.map (fun x -> copy_loc (fun x -> x) x) x0, copy_core_type x1) | From.Parsetree.Ptyp_package x0 -> To.Parsetree.Ptyp_package (copy_package_type x0) | From.Parsetree.Ptyp_extension x0 -> To.Parsetree.Ptyp_extension (copy_extension x0) and copy_package_type : From.Parsetree.package_type -> To.Parsetree.package_type = fun x -> let x0, x1 = x in ( copy_loc copy_longident x0, List.map (fun x -> let x0, x1 = x in (copy_loc copy_longident x0, copy_core_type x1)) x1 ) and copy_row_field : From.Parsetree.row_field -> To.Parsetree.row_field = fun { From.Parsetree.prf_desc; From.Parsetree.prf_loc = _; From.Parsetree.prf_attributes; } -> match prf_desc with | From.Parsetree.Rtag (x0, x1, x2) -> To.Parsetree.Rtag ( copy_loc copy_label x0, copy_attributes prf_attributes, copy_bool x1, List.map copy_core_type x2 ) | From.Parsetree.Rinherit x0 -> To.Parsetree.Rinherit (copy_core_type x0) and copy_object_field : From.Parsetree.object_field -> To.Parsetree.object_field = fun { From.Parsetree.pof_desc; From.Parsetree.pof_loc = _; From.Parsetree.pof_attributes; } -> match pof_desc with | From.Parsetree.Otag (x0, x1) -> To.Parsetree.Otag ( copy_loc copy_label x0, copy_attributes pof_attributes, copy_core_type x1 ) | From.Parsetree.Oinherit x0 -> To.Parsetree.Oinherit (copy_core_type x0) and copy_attributes : From.Parsetree.attributes -> To.Parsetree.attributes = fun x -> List.map copy_attribute x and copy_attribute : From.Parsetree.attribute -> To.Parsetree.attribute = fun { From.Parsetree.attr_name; From.Parsetree.attr_payload; From.Parsetree.attr_loc = _; } -> (copy_loc (fun x -> x) attr_name, copy_payload attr_payload) and copy_payload : From.Parsetree.payload -> To.Parsetree.payload = function | From.Parsetree.PStr x0 -> To.Parsetree.PStr (copy_structure x0) | From.Parsetree.PSig x0 -> To.Parsetree.PSig (copy_signature x0) | From.Parsetree.PTyp x0 -> To.Parsetree.PTyp (copy_core_type x0) | From.Parsetree.PPat (x0, x1) -> To.Parsetree.PPat (copy_pattern x0, copy_option copy_expression x1) and copy_structure : From.Parsetree.structure -> To.Parsetree.structure = fun x -> List.map copy_structure_item x and copy_structure_item : From.Parsetree.structure_item -> To.Parsetree.structure_item = fun { From.Parsetree.pstr_desc; From.Parsetree.pstr_loc } -> { To.Parsetree.pstr_desc = copy_structure_item_desc pstr_desc; To.Parsetree.pstr_loc = copy_location pstr_loc; } and copy_structure_item_desc : From.Parsetree.structure_item_desc -> To.Parsetree.structure_item_desc = function | From.Parsetree.Pstr_eval (x0, x1) -> To.Parsetree.Pstr_eval (copy_expression x0, copy_attributes x1) | From.Parsetree.Pstr_value (x0, x1) -> To.Parsetree.Pstr_value (copy_rec_flag x0, List.map copy_value_binding x1) | From.Parsetree.Pstr_primitive x0 -> To.Parsetree.Pstr_primitive (copy_value_description x0) | From.Parsetree.Pstr_type (x0, x1) -> To.Parsetree.Pstr_type (copy_rec_flag x0, List.map copy_type_declaration x1) | From.Parsetree.Pstr_typext x0 -> To.Parsetree.Pstr_typext (copy_type_extension x0) | From.Parsetree.Pstr_exception x0 -> To.Parsetree.Pstr_exception (let e = copy_extension_constructor x0.From.Parsetree.ptyexn_constructor in { e with pext_attributes = e.pext_attributes @ copy_attributes x0.ptyexn_attributes; }) | From.Parsetree.Pstr_module x0 -> To.Parsetree.Pstr_module (copy_module_binding x0) | From.Parsetree.Pstr_recmodule x0 -> To.Parsetree.Pstr_recmodule (List.map copy_module_binding x0) | From.Parsetree.Pstr_modtype x0 -> To.Parsetree.Pstr_modtype (copy_module_type_declaration x0) | From.Parsetree.Pstr_open x0 -> ( match x0.From.Parsetree.popen_expr.From.Parsetree.pmod_desc with | Pmod_ident lid -> To.Parsetree.Pstr_open { To.Parsetree.popen_lid = copy_loc copy_longident lid; To.Parsetree.popen_override = copy_override_flag x0.From.Parsetree.popen_override; To.Parsetree.popen_loc = copy_location x0.From.Parsetree.popen_loc; To.Parsetree.popen_attributes = copy_attributes x0.From.Parsetree.popen_attributes; } | Pmod_structure _ | Pmod_functor _ | Pmod_apply _ | Pmod_constraint _ | Pmod_unpack _ | Pmod_extension _ -> migration_error x0.From.Parsetree.popen_loc "complex open") | From.Parsetree.Pstr_class x0 -> To.Parsetree.Pstr_class (List.map copy_class_declaration x0) | From.Parsetree.Pstr_class_type x0 -> To.Parsetree.Pstr_class_type (List.map copy_class_type_declaration x0) | From.Parsetree.Pstr_include x0 -> To.Parsetree.Pstr_include (copy_include_declaration x0) | From.Parsetree.Pstr_attribute x0 -> To.Parsetree.Pstr_attribute (copy_attribute x0) | From.Parsetree.Pstr_extension (x0, x1) -> To.Parsetree.Pstr_extension (copy_extension x0, copy_attributes x1) and copy_include_declaration : From.Parsetree.include_declaration -> To.Parsetree.include_declaration = fun x -> copy_include_infos copy_module_expr x and copy_class_declaration : From.Parsetree.class_declaration -> To.Parsetree.class_declaration = fun x -> copy_class_infos copy_class_expr x and copy_class_expr : From.Parsetree.class_expr -> To.Parsetree.class_expr = fun { From.Parsetree.pcl_desc; From.Parsetree.pcl_loc; From.Parsetree.pcl_attributes; } -> { To.Parsetree.pcl_desc = copy_class_expr_desc pcl_desc; To.Parsetree.pcl_loc = copy_location pcl_loc; To.Parsetree.pcl_attributes = copy_attributes pcl_attributes; } and copy_class_expr_desc : From.Parsetree.class_expr_desc -> To.Parsetree.class_expr_desc = function | From.Parsetree.Pcl_constr (x0, x1) -> To.Parsetree.Pcl_constr (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Pcl_structure x0 -> To.Parsetree.Pcl_structure (copy_class_structure x0) | From.Parsetree.Pcl_fun (x0, x1, x2, x3) -> To.Parsetree.Pcl_fun ( copy_arg_label x0, copy_option copy_expression x1, copy_pattern x2, copy_class_expr x3 ) | From.Parsetree.Pcl_apply (x0, x1) -> To.Parsetree.Pcl_apply ( copy_class_expr x0, List.map (fun x -> let x0, x1 = x in (copy_arg_label x0, copy_expression x1)) x1 ) | From.Parsetree.Pcl_let (x0, x1, x2) -> To.Parsetree.Pcl_let (copy_rec_flag x0, List.map copy_value_binding x1, copy_class_expr x2) | From.Parsetree.Pcl_constraint (x0, x1) -> To.Parsetree.Pcl_constraint (copy_class_expr x0, copy_class_type x1) | From.Parsetree.Pcl_extension x0 -> To.Parsetree.Pcl_extension (copy_extension x0) | From.Parsetree.Pcl_open (x0, x1) -> To.Parsetree.Pcl_open ( copy_override_flag x0.From.Parsetree.popen_override, copy_loc copy_longident x0.From.Parsetree.popen_expr, copy_class_expr x1 ) and copy_class_structure : From.Parsetree.class_structure -> To.Parsetree.class_structure = fun { From.Parsetree.pcstr_self; From.Parsetree.pcstr_fields } -> { To.Parsetree.pcstr_self = copy_pattern pcstr_self; To.Parsetree.pcstr_fields = List.map copy_class_field pcstr_fields; } and copy_class_field : From.Parsetree.class_field -> To.Parsetree.class_field = fun { From.Parsetree.pcf_desc; From.Parsetree.pcf_loc; From.Parsetree.pcf_attributes; } -> { To.Parsetree.pcf_desc = copy_class_field_desc pcf_desc; To.Parsetree.pcf_loc = copy_location pcf_loc; To.Parsetree.pcf_attributes = copy_attributes pcf_attributes; } and copy_class_field_desc : From.Parsetree.class_field_desc -> To.Parsetree.class_field_desc = function | From.Parsetree.Pcf_inherit (x0, x1, x2) -> To.Parsetree.Pcf_inherit ( copy_override_flag x0, copy_class_expr x1, copy_option (fun x -> copy_loc (fun x -> x) x) x2 ) | From.Parsetree.Pcf_val x0 -> To.Parsetree.Pcf_val (let x0, x1, x2 = x0 in (copy_loc copy_label x0, copy_mutable_flag x1, copy_class_field_kind x2)) | From.Parsetree.Pcf_method x0 -> To.Parsetree.Pcf_method (let x0, x1, x2 = x0 in (copy_loc copy_label x0, copy_private_flag x1, copy_class_field_kind x2)) | From.Parsetree.Pcf_constraint x0 -> To.Parsetree.Pcf_constraint (let x0, x1 = x0 in (copy_core_type x0, copy_core_type x1)) | From.Parsetree.Pcf_initializer x0 -> To.Parsetree.Pcf_initializer (copy_expression x0) | From.Parsetree.Pcf_attribute x0 -> To.Parsetree.Pcf_attribute (copy_attribute x0) | From.Parsetree.Pcf_extension x0 -> To.Parsetree.Pcf_extension (copy_extension x0) and copy_class_field_kind : From.Parsetree.class_field_kind -> To.Parsetree.class_field_kind = function | From.Parsetree.Cfk_virtual x0 -> To.Parsetree.Cfk_virtual (copy_core_type x0) | From.Parsetree.Cfk_concrete (x0, x1) -> To.Parsetree.Cfk_concrete (copy_override_flag x0, copy_expression x1) and copy_module_binding : From.Parsetree.module_binding -> To.Parsetree.module_binding = fun { From.Parsetree.pmb_name; From.Parsetree.pmb_expr; From.Parsetree.pmb_attributes; From.Parsetree.pmb_loc; } -> { To.Parsetree.pmb_name = copy_loc (fun x -> x) pmb_name; To.Parsetree.pmb_expr = copy_module_expr pmb_expr; To.Parsetree.pmb_attributes = copy_attributes pmb_attributes; To.Parsetree.pmb_loc = copy_location pmb_loc; } and copy_module_expr : From.Parsetree.module_expr -> To.Parsetree.module_expr = fun { From.Parsetree.pmod_desc; From.Parsetree.pmod_loc; From.Parsetree.pmod_attributes; } -> { To.Parsetree.pmod_desc = copy_module_expr_desc pmod_desc; To.Parsetree.pmod_loc = copy_location pmod_loc; To.Parsetree.pmod_attributes = copy_attributes pmod_attributes; } and copy_module_expr_desc : From.Parsetree.module_expr_desc -> To.Parsetree.module_expr_desc = function | From.Parsetree.Pmod_ident x0 -> To.Parsetree.Pmod_ident (copy_loc copy_longident x0) | From.Parsetree.Pmod_structure x0 -> To.Parsetree.Pmod_structure (copy_structure x0) | From.Parsetree.Pmod_functor (x0, x1, x2) -> To.Parsetree.Pmod_functor ( copy_loc (fun x -> x) x0, copy_option copy_module_type x1, copy_module_expr x2 ) | From.Parsetree.Pmod_apply (x0, x1) -> To.Parsetree.Pmod_apply (copy_module_expr x0, copy_module_expr x1) | From.Parsetree.Pmod_constraint (x0, x1) -> To.Parsetree.Pmod_constraint (copy_module_expr x0, copy_module_type x1) | From.Parsetree.Pmod_unpack x0 -> To.Parsetree.Pmod_unpack (copy_expression x0) | From.Parsetree.Pmod_extension x0 -> To.Parsetree.Pmod_extension (copy_extension x0) and copy_module_type : From.Parsetree.module_type -> To.Parsetree.module_type = fun { From.Parsetree.pmty_desc; From.Parsetree.pmty_loc; From.Parsetree.pmty_attributes; } -> { To.Parsetree.pmty_desc = copy_module_type_desc pmty_desc; To.Parsetree.pmty_loc = copy_location pmty_loc; To.Parsetree.pmty_attributes = copy_attributes pmty_attributes; } and copy_module_type_desc : From.Parsetree.module_type_desc -> To.Parsetree.module_type_desc = function | From.Parsetree.Pmty_ident x0 -> To.Parsetree.Pmty_ident (copy_loc copy_longident x0) | From.Parsetree.Pmty_signature x0 -> To.Parsetree.Pmty_signature (copy_signature x0) | From.Parsetree.Pmty_functor (x0, x1, x2) -> To.Parsetree.Pmty_functor ( copy_loc (fun x -> x) x0, copy_option copy_module_type x1, copy_module_type x2 ) | From.Parsetree.Pmty_with (x0, x1) -> To.Parsetree.Pmty_with (copy_module_type x0, List.map copy_with_constraint x1) | From.Parsetree.Pmty_typeof x0 -> To.Parsetree.Pmty_typeof (copy_module_expr x0) | From.Parsetree.Pmty_extension x0 -> To.Parsetree.Pmty_extension (copy_extension x0) | From.Parsetree.Pmty_alias x0 -> To.Parsetree.Pmty_alias (copy_loc copy_longident x0) and copy_with_constraint : From.Parsetree.with_constraint -> To.Parsetree.with_constraint = function | From.Parsetree.Pwith_type (x0, x1) -> To.Parsetree.Pwith_type (copy_loc copy_longident x0, copy_type_declaration x1) | From.Parsetree.Pwith_module (x0, x1) -> To.Parsetree.Pwith_module (copy_loc copy_longident x0, copy_loc copy_longident x1) | From.Parsetree.Pwith_typesubst (x0, x1) -> To.Parsetree.Pwith_typesubst (copy_loc copy_longident x0, copy_type_declaration x1) | From.Parsetree.Pwith_modsubst (x0, x1) -> To.Parsetree.Pwith_modsubst (copy_loc copy_longident x0, copy_loc copy_longident x1) and copy_signature : From.Parsetree.signature -> To.Parsetree.signature = fun x -> List.map copy_signature_item x and copy_signature_item : From.Parsetree.signature_item -> To.Parsetree.signature_item = fun { From.Parsetree.psig_desc; From.Parsetree.psig_loc } -> { To.Parsetree.psig_desc = copy_signature_item_desc psig_desc; To.Parsetree.psig_loc = copy_location psig_loc; } and copy_signature_item_desc : From.Parsetree.signature_item_desc -> To.Parsetree.signature_item_desc = function | From.Parsetree.Psig_value x0 -> To.Parsetree.Psig_value (copy_value_description x0) | From.Parsetree.Psig_type (x0, x1) -> To.Parsetree.Psig_type (copy_rec_flag x0, List.map copy_type_declaration x1) | From.Parsetree.Psig_typesubst x0 -> let x0_loc = match x0 with | [] -> Location.none | { From.Parsetree.ptype_loc; _ } :: _ -> ptype_loc in migration_error x0_loc "type substitution in signatures" | From.Parsetree.Psig_typext x0 -> To.Parsetree.Psig_typext (copy_type_extension x0) | From.Parsetree.Psig_exception x0 -> To.Parsetree.Psig_exception (let e = copy_extension_constructor x0.From.Parsetree.ptyexn_constructor in { e with pext_attributes = e.pext_attributes @ copy_attributes x0.ptyexn_attributes; }) | From.Parsetree.Psig_module x0 -> To.Parsetree.Psig_module (copy_module_declaration x0) | From.Parsetree.Psig_modsubst x0 -> migration_error x0.pms_loc "module substitution in signatures" | From.Parsetree.Psig_recmodule x0 -> To.Parsetree.Psig_recmodule (List.map copy_module_declaration x0) | From.Parsetree.Psig_modtype x0 -> To.Parsetree.Psig_modtype (copy_module_type_declaration x0) | From.Parsetree.Psig_open x0 -> To.Parsetree.Psig_open (copy_open_description x0) | From.Parsetree.Psig_include x0 -> To.Parsetree.Psig_include (copy_include_description x0) | From.Parsetree.Psig_class x0 -> To.Parsetree.Psig_class (List.map copy_class_description x0) | From.Parsetree.Psig_class_type x0 -> To.Parsetree.Psig_class_type (List.map copy_class_type_declaration x0) | From.Parsetree.Psig_attribute x0 -> To.Parsetree.Psig_attribute (copy_attribute x0) | From.Parsetree.Psig_extension (x0, x1) -> To.Parsetree.Psig_extension (copy_extension x0, copy_attributes x1) and copy_class_type_declaration : From.Parsetree.class_type_declaration -> To.Parsetree.class_type_declaration = fun x -> copy_class_infos copy_class_type x and copy_class_description : From.Parsetree.class_description -> To.Parsetree.class_description = fun x -> copy_class_infos copy_class_type x and copy_class_type : From.Parsetree.class_type -> To.Parsetree.class_type = fun { From.Parsetree.pcty_desc; From.Parsetree.pcty_loc; From.Parsetree.pcty_attributes; } -> { To.Parsetree.pcty_desc = copy_class_type_desc pcty_desc; To.Parsetree.pcty_loc = copy_location pcty_loc; To.Parsetree.pcty_attributes = copy_attributes pcty_attributes; } and copy_class_type_desc : From.Parsetree.class_type_desc -> To.Parsetree.class_type_desc = function | From.Parsetree.Pcty_constr (x0, x1) -> To.Parsetree.Pcty_constr (copy_loc copy_longident x0, List.map copy_core_type x1) | From.Parsetree.Pcty_signature x0 -> To.Parsetree.Pcty_signature (copy_class_signature x0) | From.Parsetree.Pcty_arrow (x0, x1, x2) -> To.Parsetree.Pcty_arrow (copy_arg_label x0, copy_core_type x1, copy_class_type x2) | From.Parsetree.Pcty_extension x0 -> To.Parsetree.Pcty_extension (copy_extension x0) | From.Parsetree.Pcty_open (x0, x1) -> To.Parsetree.Pcty_open ( copy_override_flag x0.From.Parsetree.popen_override, copy_loc copy_longident x0.From.Parsetree.popen_expr, copy_class_type x1 ) and copy_class_signature : From.Parsetree.class_signature -> To.Parsetree.class_signature = fun { From.Parsetree.pcsig_self; From.Parsetree.pcsig_fields } -> { To.Parsetree.pcsig_self = copy_core_type pcsig_self; To.Parsetree.pcsig_fields = List.map copy_class_type_field pcsig_fields; } and copy_class_type_field : From.Parsetree.class_type_field -> To.Parsetree.class_type_field = fun { From.Parsetree.pctf_desc; From.Parsetree.pctf_loc; From.Parsetree.pctf_attributes; } -> { To.Parsetree.pctf_desc = copy_class_type_field_desc pctf_desc; To.Parsetree.pctf_loc = copy_location pctf_loc; To.Parsetree.pctf_attributes = copy_attributes pctf_attributes; } and copy_class_type_field_desc : From.Parsetree.class_type_field_desc -> To.Parsetree.class_type_field_desc = function | From.Parsetree.Pctf_inherit x0 -> To.Parsetree.Pctf_inherit (copy_class_type x0) | From.Parsetree.Pctf_val x0 -> To.Parsetree.Pctf_val (let x0, x1, x2, x3 = x0 in ( copy_loc copy_label x0, copy_mutable_flag x1, copy_virtual_flag x2, copy_core_type x3 )) | From.Parsetree.Pctf_method x0 -> To.Parsetree.Pctf_method (let x0, x1, x2, x3 = x0 in ( copy_loc copy_label x0, copy_private_flag x1, copy_virtual_flag x2, copy_core_type x3 )) | From.Parsetree.Pctf_constraint x0 -> To.Parsetree.Pctf_constraint (let x0, x1 = x0 in (copy_core_type x0, copy_core_type x1)) | From.Parsetree.Pctf_attribute x0 -> To.Parsetree.Pctf_attribute (copy_attribute x0) | From.Parsetree.Pctf_extension x0 -> To.Parsetree.Pctf_extension (copy_extension x0) and copy_extension : From.Parsetree.extension -> To.Parsetree.extension = fun x -> let x0, x1 = x in let x1 = match x0.txt with | "ocaml.error" | "error" -> ( match x1 with | PStr (hd :: tl) -> From.Parsetree.PStr (hd :: hd :: tl) | _ -> x1) | _ -> x1 in (copy_loc (fun x -> x) x0, copy_payload x1) and copy_class_infos : 'f0 'g0. ('f0 -> 'g0) -> 'f0 From.Parsetree.class_infos -> 'g0 To.Parsetree.class_infos = fun f0 { From.Parsetree.pci_virt; From.Parsetree.pci_params; From.Parsetree.pci_name; From.Parsetree.pci_expr; From.Parsetree.pci_loc; From.Parsetree.pci_attributes; } -> { To.Parsetree.pci_virt = copy_virtual_flag pci_virt; To.Parsetree.pci_params = List.map (fun x -> let x0, x1 = x in (copy_core_type x0, copy_variance x1)) pci_params; To.Parsetree.pci_name = copy_loc (fun x -> x) pci_name; To.Parsetree.pci_expr = f0 pci_expr; To.Parsetree.pci_loc = copy_location pci_loc; To.Parsetree.pci_attributes = copy_attributes pci_attributes; } and copy_virtual_flag : From.Asttypes.virtual_flag -> To.Asttypes.virtual_flag = function | From.Asttypes.Virtual -> To.Asttypes.Virtual | From.Asttypes.Concrete -> To.Asttypes.Concrete and copy_include_description : From.Parsetree.include_description -> To.Parsetree.include_description = fun x -> copy_include_infos copy_module_type x and copy_include_infos : 'f0 'g0. ('f0 -> 'g0) -> 'f0 From.Parsetree.include_infos -> 'g0 To.Parsetree.include_infos = fun f0 { From.Parsetree.pincl_mod; From.Parsetree.pincl_loc; From.Parsetree.pincl_attributes; } -> { To.Parsetree.pincl_mod = f0 pincl_mod; To.Parsetree.pincl_loc = copy_location pincl_loc; To.Parsetree.pincl_attributes = copy_attributes pincl_attributes; } and copy_open_description : From.Parsetree.open_description -> To.Parsetree.open_description = fun { From.Parsetree.popen_expr; From.Parsetree.popen_override; From.Parsetree.popen_loc; From.Parsetree.popen_attributes; } -> { To.Parsetree.popen_lid = copy_loc copy_longident popen_expr; To.Parsetree.popen_override = copy_override_flag popen_override; To.Parsetree.popen_loc = copy_location popen_loc; To.Parsetree.popen_attributes = copy_attributes popen_attributes; } and copy_override_flag : From.Asttypes.override_flag -> To.Asttypes.override_flag = function | From.Asttypes.Override -> To.Asttypes.Override | From.Asttypes.Fresh -> To.Asttypes.Fresh and copy_module_type_declaration : From.Parsetree.module_type_declaration -> To.Parsetree.module_type_declaration = fun { From.Parsetree.pmtd_name; From.Parsetree.pmtd_type; From.Parsetree.pmtd_attributes; From.Parsetree.pmtd_loc; } -> { To.Parsetree.pmtd_name = copy_loc (fun x -> x) pmtd_name; To.Parsetree.pmtd_type = copy_option copy_module_type pmtd_type; To.Parsetree.pmtd_attributes = copy_attributes pmtd_attributes; To.Parsetree.pmtd_loc = copy_location pmtd_loc; } and copy_module_declaration : From.Parsetree.module_declaration -> To.Parsetree.module_declaration = fun { From.Parsetree.pmd_name; From.Parsetree.pmd_type; From.Parsetree.pmd_attributes; From.Parsetree.pmd_loc; } -> { To.Parsetree.pmd_name = copy_loc (fun x -> x) pmd_name; To.Parsetree.pmd_type = copy_module_type pmd_type; To.Parsetree.pmd_attributes = copy_attributes pmd_attributes; To.Parsetree.pmd_loc = copy_location pmd_loc; } and copy_type_extension : From.Parsetree.type_extension -> To.Parsetree.type_extension = fun { From.Parsetree.ptyext_path; From.Parsetree.ptyext_params; From.Parsetree.ptyext_constructors; From.Parsetree.ptyext_private; From.Parsetree.ptyext_loc = _; From.Parsetree.ptyext_attributes; } -> { To.Parsetree.ptyext_path = copy_loc copy_longident ptyext_path; To.Parsetree.ptyext_params = List.map (fun x -> let x0, x1 = x in (copy_core_type x0, copy_variance x1)) ptyext_params; To.Parsetree.ptyext_constructors = List.map copy_extension_constructor ptyext_constructors; To.Parsetree.ptyext_private = copy_private_flag ptyext_private; To.Parsetree.ptyext_attributes = copy_attributes ptyext_attributes; } and copy_extension_constructor : From.Parsetree.extension_constructor -> To.Parsetree.extension_constructor = fun { From.Parsetree.pext_name; From.Parsetree.pext_kind; From.Parsetree.pext_loc; From.Parsetree.pext_attributes; } -> { To.Parsetree.pext_name = copy_loc (fun x -> x) pext_name; To.Parsetree.pext_kind = copy_extension_constructor_kind pext_kind; To.Parsetree.pext_loc = copy_location pext_loc; To.Parsetree.pext_attributes = copy_attributes pext_attributes; } and copy_extension_constructor_kind : From.Parsetree.extension_constructor_kind -> To.Parsetree.extension_constructor_kind = function | From.Parsetree.Pext_decl (x0, x1) -> To.Parsetree.Pext_decl (copy_constructor_arguments x0, copy_option copy_core_type x1) | From.Parsetree.Pext_rebind x0 -> To.Parsetree.Pext_rebind (copy_loc copy_longident x0) and copy_type_declaration : From.Parsetree.type_declaration -> To.Parsetree.type_declaration = fun { From.Parsetree.ptype_name; From.Parsetree.ptype_params; From.Parsetree.ptype_cstrs; From.Parsetree.ptype_kind; From.Parsetree.ptype_private; From.Parsetree.ptype_manifest; From.Parsetree.ptype_attributes; From.Parsetree.ptype_loc; } -> { To.Parsetree.ptype_name = copy_loc (fun x -> x) ptype_name; To.Parsetree.ptype_params = List.map (fun x -> let x0, x1 = x in (copy_core_type x0, copy_variance x1)) ptype_params; To.Parsetree.ptype_cstrs = List.map (fun x -> let x0, x1, x2 = x in (copy_core_type x0, copy_core_type x1, copy_location x2)) ptype_cstrs; To.Parsetree.ptype_kind = copy_type_kind ptype_kind; To.Parsetree.ptype_private = copy_private_flag ptype_private; To.Parsetree.ptype_manifest = copy_option copy_core_type ptype_manifest; To.Parsetree.ptype_attributes = copy_attributes ptype_attributes; To.Parsetree.ptype_loc = copy_location ptype_loc; } and copy_private_flag : From.Asttypes.private_flag -> To.Asttypes.private_flag = function | From.Asttypes.Private -> To.Asttypes.Private | From.Asttypes.Public -> To.Asttypes.Public and copy_type_kind : From.Parsetree.type_kind -> To.Parsetree.type_kind = function | From.Parsetree.Ptype_abstract -> To.Parsetree.Ptype_abstract | From.Parsetree.Ptype_variant x0 -> To.Parsetree.Ptype_variant (List.map copy_constructor_declaration x0) | From.Parsetree.Ptype_record x0 -> To.Parsetree.Ptype_record (List.map copy_label_declaration x0) | From.Parsetree.Ptype_open -> To.Parsetree.Ptype_open and copy_constructor_declaration : From.Parsetree.constructor_declaration -> To.Parsetree.constructor_declaration = fun { From.Parsetree.pcd_name; From.Parsetree.pcd_args; From.Parsetree.pcd_res; From.Parsetree.pcd_loc; From.Parsetree.pcd_attributes; } -> { To.Parsetree.pcd_name = copy_loc (fun x -> x) pcd_name; To.Parsetree.pcd_args = copy_constructor_arguments pcd_args; To.Parsetree.pcd_res = copy_option copy_core_type pcd_res; To.Parsetree.pcd_loc = copy_location pcd_loc; To.Parsetree.pcd_attributes = copy_attributes pcd_attributes; } and copy_constructor_arguments : From.Parsetree.constructor_arguments -> To.Parsetree.constructor_arguments = function | From.Parsetree.Pcstr_tuple x0 -> To.Parsetree.Pcstr_tuple (List.map copy_core_type x0) | From.Parsetree.Pcstr_record x0 -> To.Parsetree.Pcstr_record (List.map copy_label_declaration x0) and copy_label_declaration : From.Parsetree.label_declaration -> To.Parsetree.label_declaration = fun { From.Parsetree.pld_name; From.Parsetree.pld_mutable; From.Parsetree.pld_type; From.Parsetree.pld_loc; From.Parsetree.pld_attributes; } -> { To.Parsetree.pld_name = copy_loc (fun x -> x) pld_name; To.Parsetree.pld_mutable = copy_mutable_flag pld_mutable; To.Parsetree.pld_type = copy_core_type pld_type; To.Parsetree.pld_loc = copy_location pld_loc; To.Parsetree.pld_attributes = copy_attributes pld_attributes; } and copy_mutable_flag : From.Asttypes.mutable_flag -> To.Asttypes.mutable_flag = function | From.Asttypes.Immutable -> To.Asttypes.Immutable | From.Asttypes.Mutable -> To.Asttypes.Mutable and copy_variance : From.Asttypes.variance -> To.Asttypes.variance = function | From.Asttypes.Covariant -> To.Asttypes.Covariant | From.Asttypes.Contravariant -> To.Asttypes.Contravariant | From.Asttypes.Invariant -> To.Asttypes.Invariant and copy_value_description : From.Parsetree.value_description -> To.Parsetree.value_description = fun { From.Parsetree.pval_name; From.Parsetree.pval_type; From.Parsetree.pval_prim; From.Parsetree.pval_attributes; From.Parsetree.pval_loc; } -> { To.Parsetree.pval_name = copy_loc (fun x -> x) pval_name; To.Parsetree.pval_type = copy_core_type pval_type; To.Parsetree.pval_prim = List.map (fun x -> x) pval_prim; To.Parsetree.pval_attributes = copy_attributes pval_attributes; To.Parsetree.pval_loc = copy_location pval_loc; } and copy_arg_label : From.Asttypes.arg_label -> To.Asttypes.arg_label = function | From.Asttypes.Nolabel -> To.Asttypes.Nolabel | From.Asttypes.Labelled x0 -> To.Asttypes.Labelled x0 | From.Asttypes.Optional x0 -> To.Asttypes.Optional x0 and copy_closed_flag : From.Asttypes.closed_flag -> To.Asttypes.closed_flag = function | From.Asttypes.Closed -> To.Asttypes.Closed | From.Asttypes.Open -> To.Asttypes.Open and copy_label : From.Asttypes.label -> To.Asttypes.label = fun x -> x and copy_rec_flag : From.Asttypes.rec_flag -> To.Asttypes.rec_flag = function | From.Asttypes.Nonrecursive -> To.Asttypes.Nonrecursive | From.Asttypes.Recursive -> To.Asttypes.Recursive and copy_constant : From.Parsetree.constant -> To.Parsetree.constant = function | From.Parsetree.Pconst_integer (x0, x1) -> To.Parsetree.Pconst_integer (x0, copy_option (fun x -> x) x1) | From.Parsetree.Pconst_char x0 -> To.Parsetree.Pconst_char x0 | From.Parsetree.Pconst_string (x0, x1) -> To.Parsetree.Pconst_string (x0, copy_option (fun x -> x) x1) | From.Parsetree.Pconst_float (x0, x1) -> To.Parsetree.Pconst_float (x0, copy_option (fun x -> x) x1) and copy_option : 'f0 'g0. ('f0 -> 'g0) -> 'f0 option -> 'g0 option = fun f0 -> function None -> None | Some x0 -> Some (f0 x0) and copy_longident : Longident.t -> Longident.t = fun x -> x and copy_loc : 'f0 'g0. ('f0 -> 'g0) -> 'f0 From.Asttypes.loc -> 'g0 To.Asttypes.loc = fun f0 { From.Asttypes.txt; From.Asttypes.loc } -> { To.Asttypes.txt = f0 txt; To.Asttypes.loc = copy_location loc } and copy_location : Location.t -> Location.t = fun x -> x and copy_bool : bool -> bool = function false -> false | true -> true let copy_cases x = List.map copy_case x let copy_pat = copy_pattern let copy_expr = copy_expression let copy_typ = copy_core_type
e29ac1ec0b0796208066c742e7d18e8e982b886cfb7862e4883fc61648187882
AbstractMachinesLab/caramel
browse_misc.ml
{ { { COPYING * ( This file is part of Merlin , an helper for ocaml editors Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net > refis.thomas(_)gmail.com > < simon.castellan(_)iuwt.fr > Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . The Software is provided " as is " , without warranty of any kind , express or implied , including but not limited to the warranties of merchantability , fitness for a particular purpose and noninfringement . In no event shall the authors or copyright holders be liable for any claim , damages or other liability , whether in an action of contract , tort or otherwise , arising from , out of or in connection with the software or the use or other dealings in the Software . ) * } } } This file is part of Merlin, an helper for ocaml editors Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net> Thomas Refis <refis.thomas(_)gmail.com> Simon Castellan <simon.castellan(_)iuwt.fr> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software. )* }}} *) open Std let print_constructor c = let open Types in match c.cstr_args with | [] -> Printtyp.tree_of_type_scheme (Raw_compat.dummy_type_scheme c.cstr_res.desc) | args -> let desc = Tarrow (Ast_helper.no_label, Raw_compat.dummy_type_scheme (Ttuple args), c.cstr_res, Cok) in Printtyp.tree_of_type_scheme (Raw_compat.dummy_type_scheme desc) let signature_of_env ?(ignore_extensions=true) env = let sg = ref [] in let append item = sg := item :: !sg in let rec aux summary = let open Raw_compat in match summary_module_ident_opt summary with | Some i when ignore_extensions && i = Extension.ident -> () | _ -> Option.iter ~f:append (signature_of_summary summary); Option.iter ~f:aux (summary_prev summary) in aux (Env.summary env); Since 4.08 one ca n't simply call [ simplify ] . (* Typemod.simplify_signature *) (!sg) let dump_browse node = let attr attr = let ({Location . txt; loc},payload) = Ast_helper.Attr.as_tuple attr in `Assoc [ "start" , Lexing.json_of_position loc.Location.loc_start; "end" , Lexing.json_of_position loc.Location.loc_end; "name" , `String (txt ^ if payload = Parsetree.PStr [] then "" else " _") ] in let rec append env node acc = let loc = Mbrowse.node_loc node in `Assoc [ "filename" , `String loc.Location.loc_start.Lexing.pos_fname; "start" , Lexing.json_of_position loc.Location.loc_start; "end" , Lexing.json_of_position loc.Location.loc_end; "ghost" , `Bool loc.Location.loc_ghost; "attrs" , `List (List.map ~f:attr (Browse_raw.node_attributes node)); "kind" , `String (Browse_raw.string_of_node node); "children" , dump_list env node ] :: acc and dump_list env node = `List (List.sort ~cmp:compare @@ Mbrowse.fold_node append env node []) in `List (append Env.empty node []) let annotate_tail_calls (ts : Mbrowse.t) : (Env.t * Browse_raw.node * Query_protocol.is_tail_position) list = let is_one_of candidates node = List.mem node ~set:candidates in let find_entry_points candidates (env, node) = Tail_analysis.entry_points node, (env, node, is_one_of candidates node) in let _, entry_points = List.fold_n_map ts ~f:find_entry_points ~init:[] in let propagate candidates (env, node, entry) = let is_in_tail = entry || is_one_of candidates node in (if is_in_tail then Tail_analysis.tail_positions node else []), (env, node, is_in_tail) in let _, tail_positions = List.fold_n_map entry_points ~f:propagate ~init:[] in List.map ~f:(fun (env, node, tail) -> env, node, if not tail then `No else if Tail_analysis.is_call node then `Tail_call else `Tail_position) tail_positions
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/analysis/browse_misc.ml
ocaml
Typemod.simplify_signature
{ { { COPYING * ( This file is part of Merlin , an helper for ocaml editors Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net > refis.thomas(_)gmail.com > < simon.castellan(_)iuwt.fr > Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . The Software is provided " as is " , without warranty of any kind , express or implied , including but not limited to the warranties of merchantability , fitness for a particular purpose and noninfringement . In no event shall the authors or copyright holders be liable for any claim , damages or other liability , whether in an action of contract , tort or otherwise , arising from , out of or in connection with the software or the use or other dealings in the Software . ) * } } } This file is part of Merlin, an helper for ocaml editors Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net> Thomas Refis <refis.thomas(_)gmail.com> Simon Castellan <simon.castellan(_)iuwt.fr> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software. )* }}} *) open Std let print_constructor c = let open Types in match c.cstr_args with | [] -> Printtyp.tree_of_type_scheme (Raw_compat.dummy_type_scheme c.cstr_res.desc) | args -> let desc = Tarrow (Ast_helper.no_label, Raw_compat.dummy_type_scheme (Ttuple args), c.cstr_res, Cok) in Printtyp.tree_of_type_scheme (Raw_compat.dummy_type_scheme desc) let signature_of_env ?(ignore_extensions=true) env = let sg = ref [] in let append item = sg := item :: !sg in let rec aux summary = let open Raw_compat in match summary_module_ident_opt summary with | Some i when ignore_extensions && i = Extension.ident -> () | _ -> Option.iter ~f:append (signature_of_summary summary); Option.iter ~f:aux (summary_prev summary) in aux (Env.summary env); Since 4.08 one ca n't simply call [ simplify ] . let dump_browse node = let attr attr = let ({Location . txt; loc},payload) = Ast_helper.Attr.as_tuple attr in `Assoc [ "start" , Lexing.json_of_position loc.Location.loc_start; "end" , Lexing.json_of_position loc.Location.loc_end; "name" , `String (txt ^ if payload = Parsetree.PStr [] then "" else " _") ] in let rec append env node acc = let loc = Mbrowse.node_loc node in `Assoc [ "filename" , `String loc.Location.loc_start.Lexing.pos_fname; "start" , Lexing.json_of_position loc.Location.loc_start; "end" , Lexing.json_of_position loc.Location.loc_end; "ghost" , `Bool loc.Location.loc_ghost; "attrs" , `List (List.map ~f:attr (Browse_raw.node_attributes node)); "kind" , `String (Browse_raw.string_of_node node); "children" , dump_list env node ] :: acc and dump_list env node = `List (List.sort ~cmp:compare @@ Mbrowse.fold_node append env node []) in `List (append Env.empty node []) let annotate_tail_calls (ts : Mbrowse.t) : (Env.t * Browse_raw.node * Query_protocol.is_tail_position) list = let is_one_of candidates node = List.mem node ~set:candidates in let find_entry_points candidates (env, node) = Tail_analysis.entry_points node, (env, node, is_one_of candidates node) in let _, entry_points = List.fold_n_map ts ~f:find_entry_points ~init:[] in let propagate candidates (env, node, entry) = let is_in_tail = entry || is_one_of candidates node in (if is_in_tail then Tail_analysis.tail_positions node else []), (env, node, is_in_tail) in let _, tail_positions = List.fold_n_map entry_points ~f:propagate ~init:[] in List.map ~f:(fun (env, node, tail) -> env, node, if not tail then `No else if Tail_analysis.is_call node then `Tail_call else `Tail_position) tail_positions
67d21fe1ca78d5f4d3802a2bdac98580c3af82d7ca3f867e18b542e976be6bb2
coccinelle/herodotos
engineTypes.ml
(**************************************************************************) (* *) Menhir (* *) , INRIA Rocquencourt , PPS , Université Paris Diderot (* *) Copyright 2005 - 2008 Institut National de Recherche en Informatique (* et en Automatique. All rights reserved. This file is distributed *) under the terms of the GNU Library General Public License , with the (* special exception on linking described in file LICENSE. *) (* *) (**************************************************************************) (* This file defines several types and module types that are used in the specification of module [Engine]. *) (* --------------------------------------------------------------------------- *) (* It would be nice if we could keep the structure of stacks and environments hidden. However, stacks and environments must be accessible to semantic actions, so the following data structure definitions must be public. *) (* --------------------------------------------------------------------------- *) (* A stack is a linked list of cells. A sentinel cell -- which is its own successor is used to mark the bottom of the stack. The sentinel cell itself is not significant -- it contains dummy values. *) type ('state, 'semantic_value) stack = { (* The state that we should go back to if we pop this stack cell. *) (* This convention means that the state contained in the top stack cell is not the current state [env.current]. It also means that the state found within the sentinel is a dummy -- it is never consulted. This convention is the same as that adopted by the code-based back-end. *) state: 'state; (* The semantic value associated with the chunk of input that this cell represents. *) semv: 'semantic_value; (* The start and end positions of the chunk of input that this cell represents. *) startp: Lexing.position; endp: Lexing.position; (* The next cell down in the stack. If this is a self-pointer, then this cell is the sentinel, and the stack is conceptually empty. *) next: ('state, 'semantic_value) stack; } (* --------------------------------------------------------------------------- *) (* A parsing environment contains basically all of the automaton's state. *) type ('state, 'semantic_value, 'token) env = { (* The lexer. *) lexer: Lexing.lexbuf -> 'token; (* The lexing buffer. It is used as an argument to the lexer, and also accessed directly when extracting positions. *) lexbuf: Lexing.lexbuf; (* The last token that was obtained from the lexer. *) mutable token: 'token; (* A count of how many tokens were shifted since the beginning, or since the last [error] token was encountered. By convention, if [shifted] is (-1), then the current lookahead token is [error]. *) mutable shifted: int; (* A copy of the value of [shifted] just before the most recent error was detected. This value is not used by the automaton itself, but is made accessible to semantic actions. *) mutable previouserror: int; (* The stack. In [CodeBackend], it is passed around on its own, whereas, here, it is accessed via the environment. *) mutable stack: ('state, 'semantic_value) stack; (* The current state. In [CodeBackend], it is passed around on its own, whereas, here, it is accessed via the environment. *) mutable current: 'state; } (* --------------------------------------------------------------------------- *) This signature describes the parameters that must be supplied to the LR engine . engine. *) module type TABLE = sig (* The type of automaton states. *) type state (* The type of tokens. These can be thought of as real tokens, that is, tokens returned by the lexer. They carry a semantic value. This type does not include the [error] pseudo-token. *) type token (* The type of terminal symbols. These can be thought of as integer codes. They do not carry a semantic value. This type does include the [error] pseudo-token. *) type terminal (* The type of semantic values. *) type semantic_value A token is conceptually a pair of a ( non-[error ] ) terminal symbol and a semantic value . The following two functions are the pair projections . a semantic value. The following two functions are the pair projections. *) val token2terminal: token -> terminal val token2value: token -> semantic_value (* Even though the [error] pseudo-token is not a real token, it is a terminal symbol. Furthermore, for regularity, it must have a semantic value. *) val error_terminal: terminal val error_value: semantic_value (* The type of productions. *) type production (* If a state [s] has a default reduction on production [prod], then, upon entering [s], the automaton should reduce [prod] without consulting the lookahead token. The following function allows determining which states have default reductions. *) Instead of returning a value of a sum type -- either [ DefRed prod ] , or [ NoDefRed ] -- it accepts two continuations , and invokes just one of them . This mechanism allows avoiding a memory allocation . [NoDefRed] -- it accepts two continuations, and invokes just one of them. This mechanism allows avoiding a memory allocation. *) val default_reduction: state -> ('env -> production -> 'answer) -> ('env -> 'answer) -> 'env -> 'answer An LR automaton can normally take three kinds of actions : shift , reduce , or fail . ( Acceptance is a particular case of reduction : it consists in reducing a start production . ) or fail. (Acceptance is a particular case of reduction: it consists in reducing a start production.) *) There are two variants of the shift action . [ shift / discard s ] instructs the automaton to discard the current token , request a new one from the lexer , and move to state [ s ] . [ shift / nodiscard s ] instructs it to move to state [ s ] without requesting a new token . This instruction should be used when [ s ] has a default reduction on [ # ] . See [ CodeBackend.gettoken ] for details . the automaton to discard the current token, request a new one from the lexer, and move to state [s]. [shift/nodiscard s] instructs it to move to state [s] without requesting a new token. This instruction should be used when [s] has a default reduction on [#]. See [CodeBackend.gettoken] for details. *) (* This is the automaton's action table. It maps a pair of a state and a terminal symbol to an action. *) Instead of returning a value of a sum type -- one of shift / discard , shift / nodiscard , reduce , or fail -- this function accepts three continuations , and invokes just one them . This mechanism allows avoiding a memory allocation . shift/nodiscard, reduce, or fail -- this function accepts three continuations, and invokes just one them. This mechanism allows avoiding a memory allocation. *) In summary , the parameters to [ action ] are as follows : - the first two parameters , a state and a terminal symbol , are used to look up the action table ; - the next parameter is the semantic value associated with the above terminal symbol ; it is not used , only passed along to the shift continuation , as explained below ; - the shift continuation expects an environment ; a flag that tells whether to discard the current token ; the terminal symbol that is being shifted ; its semantic value ; and the target state of the transition ; - the reduce continuation expects an environment and a production ; - the fail continuation expects an environment ; - the last parameter is the environment ; it is not used , only passed along to the selected continuation . - the first two parameters, a state and a terminal symbol, are used to look up the action table; - the next parameter is the semantic value associated with the above terminal symbol; it is not used, only passed along to the shift continuation, as explained below; - the shift continuation expects an environment; a flag that tells whether to discard the current token; the terminal symbol that is being shifted; its semantic value; and the target state of the transition; - the reduce continuation expects an environment and a production; - the fail continuation expects an environment; - the last parameter is the environment; it is not used, only passed along to the selected continuation. *) val action: state -> terminal -> semantic_value -> ('env -> bool -> terminal -> semantic_value -> state -> 'answer) -> ('env -> production -> 'answer) -> ('env -> 'answer) -> 'env -> 'answer (* This is the automaton's goto table. It maps a pair of a state and a production to a new state. This convention is slightly different from the textbook approach. The goto table is usually indexed by a state and a non-terminal symbol. *) val goto: state -> production -> state By convention , a semantic action is responsible for : 1 . fetching whatever semantic values and positions it needs off the stack ; 2 . popping an appropriate number of cells off the stack , as dictated by the length of the right - hand side of the production ; this involves updating [ env.stack ] ; 3 . computing a new semantic value , as well as new start and end positions ; 4 . pushing a new stack cell , which contains the three values computed in step 3 ; this again involves updating [ env.stack ] ( only one update is necessary ) . Point 1 is essentially forced upon us : if semantic values were fetched off the stack by this interpreter , then the calling convention for semantic actions would be variadic : not all semantic actions would have the same number of arguments . The rest follows rather naturally . 1. fetching whatever semantic values and positions it needs off the stack; 2. popping an appropriate number of cells off the stack, as dictated by the length of the right-hand side of the production; this involves updating [env.stack]; 3. computing a new semantic value, as well as new start and end positions; 4. pushing a new stack cell, which contains the three values computed in step 3; this again involves updating [env.stack] (only one update is necessary). Point 1 is essentially forced upon us: if semantic values were fetched off the stack by this interpreter, then the calling convention for semantic actions would be variadic: not all semantic actions would have the same number of arguments. The rest follows rather naturally. *) (* If production [prod] is an accepting production, then the semantic action is responsible for raising exception [Accept], instead of returning normally. This convention allows us to not distinguish between regular productions and accepting productions. All we have to do is catch that exception at top level. *) Semantic actions are allowed to raise [ Error ] . exception Accept of semantic_value exception Error type semantic_action = (state, semantic_value, token) env -> unit val semantic_action: production -> semantic_action The LR engine can attempt error recovery . This consists in discarding tokens , just after an error has been successfully handled , until a token that can be successfully handled is found . This mechanism is optional . The following flag enables it . tokens, just after an error has been successfully handled, until a token that can be successfully handled is found. This mechanism is optional. The following flag enables it. *) val recovery: bool The LR engine requires a number of hooks , which are used for logging . (* The comments below indicate the conventional messages that correspond to these hooks in the code-based back-end; see [CodeBackend]. *) module Log : sig State % d : val state: state -> unit (* Shifting (<terminal>) to state <state> *) val shift: terminal -> state -> unit (* Reducing a production should be logged either as a reduction event (for regular productions) or as an acceptance event (for start productions). *) (* Reducing production <production> / Accepting *) val reduce_or_accept: production -> unit (* Lookahead token is now <terminal> (<pos>-<pos>) *) val lookahead_token: Lexing.lexbuf -> terminal -> unit (* Initiating error handling *) val initiating_error_handling: unit -> unit (* Resuming error handling *) val resuming_error_handling: unit -> unit (* Handling error in state <state> *) val handling_error: state -> unit (* Discarding last token read (<terminal>) *) val discarding_last_token: terminal -> unit end end (* --------------------------------------------------------------------------- *) This signature describes the LR engine . module type ENGINE = sig type state type token type semantic_value (* An entry point to the engine requires a start state, a lexer, and a lexing buffer. It either succeeds and produces a semantic value, or fails and raises [Error]. *) exception Error val entry: state -> (Lexing.lexbuf -> token) -> Lexing.lexbuf -> semantic_value end
null
https://raw.githubusercontent.com/coccinelle/herodotos/5da230a18962ca445ed2368bc21abe0a8402e00f/menhirLib/engineTypes.ml
ocaml
************************************************************************ et en Automatique. All rights reserved. This file is distributed special exception on linking described in file LICENSE. ************************************************************************ This file defines several types and module types that are used in the specification of module [Engine]. --------------------------------------------------------------------------- It would be nice if we could keep the structure of stacks and environments hidden. However, stacks and environments must be accessible to semantic actions, so the following data structure definitions must be public. --------------------------------------------------------------------------- A stack is a linked list of cells. A sentinel cell -- which is its own successor is used to mark the bottom of the stack. The sentinel cell itself is not significant -- it contains dummy values. The state that we should go back to if we pop this stack cell. This convention means that the state contained in the top stack cell is not the current state [env.current]. It also means that the state found within the sentinel is a dummy -- it is never consulted. This convention is the same as that adopted by the code-based back-end. The semantic value associated with the chunk of input that this cell represents. The start and end positions of the chunk of input that this cell represents. The next cell down in the stack. If this is a self-pointer, then this cell is the sentinel, and the stack is conceptually empty. --------------------------------------------------------------------------- A parsing environment contains basically all of the automaton's state. The lexer. The lexing buffer. It is used as an argument to the lexer, and also accessed directly when extracting positions. The last token that was obtained from the lexer. A count of how many tokens were shifted since the beginning, or since the last [error] token was encountered. By convention, if [shifted] is (-1), then the current lookahead token is [error]. A copy of the value of [shifted] just before the most recent error was detected. This value is not used by the automaton itself, but is made accessible to semantic actions. The stack. In [CodeBackend], it is passed around on its own, whereas, here, it is accessed via the environment. The current state. In [CodeBackend], it is passed around on its own, whereas, here, it is accessed via the environment. --------------------------------------------------------------------------- The type of automaton states. The type of tokens. These can be thought of as real tokens, that is, tokens returned by the lexer. They carry a semantic value. This type does not include the [error] pseudo-token. The type of terminal symbols. These can be thought of as integer codes. They do not carry a semantic value. This type does include the [error] pseudo-token. The type of semantic values. Even though the [error] pseudo-token is not a real token, it is a terminal symbol. Furthermore, for regularity, it must have a semantic value. The type of productions. If a state [s] has a default reduction on production [prod], then, upon entering [s], the automaton should reduce [prod] without consulting the lookahead token. The following function allows determining which states have default reductions. This is the automaton's action table. It maps a pair of a state and a terminal symbol to an action. This is the automaton's goto table. It maps a pair of a state and a production to a new state. This convention is slightly different from the textbook approach. The goto table is usually indexed by a state and a non-terminal symbol. If production [prod] is an accepting production, then the semantic action is responsible for raising exception [Accept], instead of returning normally. This convention allows us to not distinguish between regular productions and accepting productions. All we have to do is catch that exception at top level. The comments below indicate the conventional messages that correspond to these hooks in the code-based back-end; see [CodeBackend]. Shifting (<terminal>) to state <state> Reducing a production should be logged either as a reduction event (for regular productions) or as an acceptance event (for start productions). Reducing production <production> / Accepting Lookahead token is now <terminal> (<pos>-<pos>) Initiating error handling Resuming error handling Handling error in state <state> Discarding last token read (<terminal>) --------------------------------------------------------------------------- An entry point to the engine requires a start state, a lexer, and a lexing buffer. It either succeeds and produces a semantic value, or fails and raises [Error].
Menhir , INRIA Rocquencourt , PPS , Université Paris Diderot Copyright 2005 - 2008 Institut National de Recherche en Informatique under the terms of the GNU Library General Public License , with the type ('state, 'semantic_value) stack = { state: 'state; semv: 'semantic_value; startp: Lexing.position; endp: Lexing.position; next: ('state, 'semantic_value) stack; } type ('state, 'semantic_value, 'token) env = { lexer: Lexing.lexbuf -> 'token; lexbuf: Lexing.lexbuf; mutable token: 'token; mutable shifted: int; mutable previouserror: int; mutable stack: ('state, 'semantic_value) stack; mutable current: 'state; } This signature describes the parameters that must be supplied to the LR engine . engine. *) module type TABLE = sig type state type token type terminal type semantic_value A token is conceptually a pair of a ( non-[error ] ) terminal symbol and a semantic value . The following two functions are the pair projections . a semantic value. The following two functions are the pair projections. *) val token2terminal: token -> terminal val token2value: token -> semantic_value val error_terminal: terminal val error_value: semantic_value type production Instead of returning a value of a sum type -- either [ DefRed prod ] , or [ NoDefRed ] -- it accepts two continuations , and invokes just one of them . This mechanism allows avoiding a memory allocation . [NoDefRed] -- it accepts two continuations, and invokes just one of them. This mechanism allows avoiding a memory allocation. *) val default_reduction: state -> ('env -> production -> 'answer) -> ('env -> 'answer) -> 'env -> 'answer An LR automaton can normally take three kinds of actions : shift , reduce , or fail . ( Acceptance is a particular case of reduction : it consists in reducing a start production . ) or fail. (Acceptance is a particular case of reduction: it consists in reducing a start production.) *) There are two variants of the shift action . [ shift / discard s ] instructs the automaton to discard the current token , request a new one from the lexer , and move to state [ s ] . [ shift / nodiscard s ] instructs it to move to state [ s ] without requesting a new token . This instruction should be used when [ s ] has a default reduction on [ # ] . See [ CodeBackend.gettoken ] for details . the automaton to discard the current token, request a new one from the lexer, and move to state [s]. [shift/nodiscard s] instructs it to move to state [s] without requesting a new token. This instruction should be used when [s] has a default reduction on [#]. See [CodeBackend.gettoken] for details. *) Instead of returning a value of a sum type -- one of shift / discard , shift / nodiscard , reduce , or fail -- this function accepts three continuations , and invokes just one them . This mechanism allows avoiding a memory allocation . shift/nodiscard, reduce, or fail -- this function accepts three continuations, and invokes just one them. This mechanism allows avoiding a memory allocation. *) In summary , the parameters to [ action ] are as follows : - the first two parameters , a state and a terminal symbol , are used to look up the action table ; - the next parameter is the semantic value associated with the above terminal symbol ; it is not used , only passed along to the shift continuation , as explained below ; - the shift continuation expects an environment ; a flag that tells whether to discard the current token ; the terminal symbol that is being shifted ; its semantic value ; and the target state of the transition ; - the reduce continuation expects an environment and a production ; - the fail continuation expects an environment ; - the last parameter is the environment ; it is not used , only passed along to the selected continuation . - the first two parameters, a state and a terminal symbol, are used to look up the action table; - the next parameter is the semantic value associated with the above terminal symbol; it is not used, only passed along to the shift continuation, as explained below; - the shift continuation expects an environment; a flag that tells whether to discard the current token; the terminal symbol that is being shifted; its semantic value; and the target state of the transition; - the reduce continuation expects an environment and a production; - the fail continuation expects an environment; - the last parameter is the environment; it is not used, only passed along to the selected continuation. *) val action: state -> terminal -> semantic_value -> ('env -> bool -> terminal -> semantic_value -> state -> 'answer) -> ('env -> production -> 'answer) -> ('env -> 'answer) -> 'env -> 'answer val goto: state -> production -> state By convention , a semantic action is responsible for : 1 . fetching whatever semantic values and positions it needs off the stack ; 2 . popping an appropriate number of cells off the stack , as dictated by the length of the right - hand side of the production ; this involves updating [ env.stack ] ; 3 . computing a new semantic value , as well as new start and end positions ; 4 . pushing a new stack cell , which contains the three values computed in step 3 ; this again involves updating [ env.stack ] ( only one update is necessary ) . Point 1 is essentially forced upon us : if semantic values were fetched off the stack by this interpreter , then the calling convention for semantic actions would be variadic : not all semantic actions would have the same number of arguments . The rest follows rather naturally . 1. fetching whatever semantic values and positions it needs off the stack; 2. popping an appropriate number of cells off the stack, as dictated by the length of the right-hand side of the production; this involves updating [env.stack]; 3. computing a new semantic value, as well as new start and end positions; 4. pushing a new stack cell, which contains the three values computed in step 3; this again involves updating [env.stack] (only one update is necessary). Point 1 is essentially forced upon us: if semantic values were fetched off the stack by this interpreter, then the calling convention for semantic actions would be variadic: not all semantic actions would have the same number of arguments. The rest follows rather naturally. *) Semantic actions are allowed to raise [ Error ] . exception Accept of semantic_value exception Error type semantic_action = (state, semantic_value, token) env -> unit val semantic_action: production -> semantic_action The LR engine can attempt error recovery . This consists in discarding tokens , just after an error has been successfully handled , until a token that can be successfully handled is found . This mechanism is optional . The following flag enables it . tokens, just after an error has been successfully handled, until a token that can be successfully handled is found. This mechanism is optional. The following flag enables it. *) val recovery: bool The LR engine requires a number of hooks , which are used for logging . module Log : sig State % d : val state: state -> unit val shift: terminal -> state -> unit val reduce_or_accept: production -> unit val lookahead_token: Lexing.lexbuf -> terminal -> unit val initiating_error_handling: unit -> unit val resuming_error_handling: unit -> unit val handling_error: state -> unit val discarding_last_token: terminal -> unit end end This signature describes the LR engine . module type ENGINE = sig type state type token type semantic_value exception Error val entry: state -> (Lexing.lexbuf -> token) -> Lexing.lexbuf -> semantic_value end
8dd6e9278ec99a12ab2f7f84d0a1e909848c7b2e4351886e3565e3c5a1924e49
basho/riak_test
ts_cluster_unicode.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2015 Basho Technologies , Inc. %% This file is provided to you 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. %% %% ------------------------------------------------------------------- %% @doc A module to test riak_ts basic create bucket/put/select cycle with UTF-8 values -module(ts_cluster_unicode). -behavior(riak_test). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -define(PVAL_P1, <<"Αισθητήρας"/utf8>>). -define(PVAL_P2, <<"¡™£¢∞§¶•ªº"/utf8>>). confirm() -> ts_cluster_comprehensive:run_tests(?PVAL_P1, ?PVAL_P2).
null
https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/ts_cluster_unicode.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @doc A module to test riak_ts basic create bucket/put/select cycle
Copyright ( c ) 2015 Basho Technologies , Inc. This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY with UTF-8 values -module(ts_cluster_unicode). -behavior(riak_test). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -define(PVAL_P1, <<"Αισθητήρας"/utf8>>). -define(PVAL_P2, <<"¡™£¢∞§¶•ªº"/utf8>>). confirm() -> ts_cluster_comprehensive:run_tests(?PVAL_P1, ?PVAL_P2).
05e2006ee6173fbfddf982014cf0b289d73b6984a54d0e6919da9268bf06d6a4
clojure/core.typed
eval.clj
(ns clojure.core.typed.test.typed-load.eval {:lang :core.typed} (:require [clojure.core.typed :as t])) (t/cast t/Int nil)
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/resources/clojure/core/typed/test/typed_load/eval.clj
clojure
(ns clojure.core.typed.test.typed-load.eval {:lang :core.typed} (:require [clojure.core.typed :as t])) (t/cast t/Int nil)
7fdef097ee259bb37b137077d162ba028f753cb1a2f98c7f7efb8052e92db7f0
xapi-project/xen-api
main.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. *) let project_url = "-project/xenops-cli" open Cmdliner (* Help sections common to all commands *) let _common_options = "COMMON OPTIONS" let help = [ `S _common_options ; `P "These options are common to all commands." ; `S "MORE HELP" ; `P "Use `$(mname) $(i,COMMAND) --help' for help on a single command." ; `Noblank ; `S "BUGS" ; `P (Printf.sprintf "Check bug reports at %s" project_url) ] (* Options common to all commands *) let common_options_t = let docs = _common_options in let debug = let doc = "Give only debug output." in Arg.(value & flag & info ["debug"] ~docs ~doc) in let verb = let doc = "Give verbose output." in let verbose = (true, Arg.info ["v"; "verbose"] ~docs ~doc) in Arg.(last & vflag_all [false] [verbose]) in let socket = let doc = Printf.sprintf "Specify path to the server Unix domain socket." in Arg.( value & opt file !Xenops_interface.default_path & info ["socket"] ~docs ~doc ) in let queue = let default = Some "org.xen.xapi.xenops.classic" in let doc = Printf.sprintf "Specify queue name in message switch." in Arg.(value & opt (some string) default & info ["queue"] ~docs ~doc) in Term.(const Common.make $ debug $ verb $ socket $ queue) (* Commands *) let events_cmd = let doc = "display a live stream of events" in let man = [ `S "DESCRIPTION" ; `P "Displays a live stream of events received from xenopsd. These events \ include VM powercycle events and VM configuration changes." ] @ help in ( Term.(ret (const Xn.events $ common_options_t)) , Cmd.info "events" ~sdocs:_common_options ~doc ~man ) let create_cmd = let doc = "register a VM and start it immediately" in let man = [ `S "DESCRIPTION" ; `P "Registers a new VM with the xenopsd service and starts it immediately." ] @ help in let filename = let doc = Printf.sprintf "Path to the VM metadata." in Arg.(value & pos 0 (some file) None & info [] ~doc) in let console = let doc = "Connect to the VM's console." in Arg.(value & flag & info ["console"] ~doc) in ( Term.(ret (const Xn.create $ common_options_t $ filename $ console)) , Cmd.info "create" ~sdocs:_common_options ~doc ~man ) let add_cmd = let doc = "register a new VM with xenopsd" in let man = [`S "DESCRIPTION"; `P "Registers a new VM with the xenopsd service."] @ help in let filename = let doc = Printf.sprintf "Path to the VM metadata to be registered." in Arg.(value & pos 0 (some file) None & info [] ~doc) in ( Term.(ret (const Xn.add $ common_options_t $ filename)) , Cmd.info "add" ~sdocs:_common_options ~doc ~man ) let list_cmd = let doc = "list the VMs registered with xenopsd" in let man = [ `S "DESCRIPTION" ; `P "Lists the VMs registered with the xenopsd service." ; `P "VMs are registered with xenospd via the \"add\" command and\n\ \ will be monitored until the corresponding \"remove\" command." ; `P "xenopsd will not touch any VMs (and domains) which have not\n\ \ been explicitly registered." ] @ help in ( Term.(const Xn.list $ common_options_t) , Cmd.info "list" ~sdocs:_common_options ~doc ~man ) let vm_arg verb = let doc = Printf.sprintf "The name or UUID of the VM to be %s." verb in Arg.(value & pos 0 (some string) None & info [] ~docv:"VM" ~doc) let remove_cmd = let vm = vm_arg "unregistered" in let doc = "unregister a VM" in let man = [ `S "DESCRIPTION" ; `P "Unregister a VM." ; `P "The xenopsd service will only manipulate VMs if they are\n\ \ explicitly registered with it. You should unregister a VM if \ either:" ; `P "1. the VM is not needed any more; or" ; `P "2. you intend to manage the VM on another host or using another \ toolstack." ; `P "Note: before attempting to use multiple toolstacks simultaneously on \ a single host,\n\ \ check all the relevant documentation to see whether this is a \ sensible thing to do." ; `P "Only Halted VMs may be unregistered." ; `S "ERRORS" ; `P "Something about power state exceptions" ] in ( Term.(ret (const Xn.remove $ common_options_t $ vm)) , Cmd.info "remove" ~sdocs:_common_options ~doc ~man ) let start_cmd = let vm = vm_arg "started" in let paused = let doc = "Leave the VM in a Paused state." in Arg.(value & flag & info ["paused"] ~doc) in let console = let doc = "Connect to the VM's console." in Arg.(value & flag & info ["console"] ~doc) in let doc = "start a VM" in let man = [ `S "DESCRIPTION" ; `P "Start a VM.\n\n\ \ If no additional arguments are provided then this command\n\ \ will return when the VM is in the \"Running\" state.\n\ \ If the --paused argument is specified then the VM will\n\ \ be left in the \"Paused\" state." ; `S "ERRORS" ; `P "Something about memory." ; `P "Something about disks." ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.start $ common_options_t $ paused $ console $ vm)) , Cmd.info "start" ~sdocs:_common_options ~doc ~man ) let console_cmd = let vm = let doc = "The name or UUID of the VM whose console to be accessed." in Arg.(value & pos 0 (some string) None & info [] ~docv:"VM" ~doc) in let doc = "attach to the console of a VM" in let man = [ `S "DESCRIPTION" ; `P "Attach to the console of a VM." ; `S "ERRORS" ; `P "Something about memory." ; `P "Something about disks." ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.console_connect $ common_options_t $ vm)) , Cmd.info "console" ~sdocs:_common_options ~doc ~man ) let shutdown_cmd = let vm = vm_arg "shutdown and powered off" in let timeout = let doc = "Amount of time to wait for the VM to cleanly shut itself down, before \ we power it off." in Arg.(value & opt (some float) None & info ["timeout"] ~doc) in let doc = "shutdown a VM" in let man = [ `S "DESCRIPTION" ; `P "Shutdown a VM." ; `P "If the specified VM is running, it will be asked to shutdown.\n\ \ If a <timeout> is specified then we will wait. If no <timeout>\n\ \ is specified or if the timeout expires, the VM will be powered \ off." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.shutdown $ common_options_t $ timeout $ vm)) , Cmd.info "shutdown" ~sdocs:_common_options ~doc ~man ) let reboot_cmd = let vm = vm_arg "rebooted" in let timeout = let doc = "Amount of time to wait for the VM to cleanly shut itself down, before \ we power it off and then on." in Arg.(value & opt (some float) None & info ["timeout"] ~doc) in let doc = "reboot a VM" in let man = [ `S "DESCRIPTION" ; `P "Reboot a VM." ; `P "If the specified VM is running, it will be asked to reboot.\n\ \ If a <timeout> is specified then we will wait. If no <timeout>\n\ \ is specified or if the timeout expires, the VM will be powered \ off.\n\ \ We will then power the VM back on again." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.reboot $ common_options_t $ timeout $ vm)) , Cmd.info "reboot" ~sdocs:_common_options ~doc ~man ) let suspend_cmd = let vm = vm_arg "suspended" in let device = let doc = "Block device to write the suspend image to" in Arg.(value & opt (some file) None & info ["block-device"] ~doc) in let doc = "suspend a VM" in let man = [ `S "DESCRIPTION" ; `P "Suspend a VM." ; `P "If the specified VM is running, it will be asked to suspend.\n\ \ The memory image will be saved to the specified block device." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.suspend $ common_options_t $ device $ vm)) , Cmd.info "suspend" ~sdocs:_common_options ~doc ~man ) let resume_cmd = let vm = vm_arg "resumed" in let device = let doc = "Block device to read the suspend image from" in Arg.(value & opt (some file) None & info ["block-device"] ~doc) in let doc = "resume a VM" in let man = [ `S "DESCRIPTION" ; `P "Resume a VM." ; `P "The VM memory image will be reloaded from the specified block device\n\ \ and the VM will be left in a Running state." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.resume $ common_options_t $ device $ vm)) , Cmd.info "resume" ~sdocs:_common_options ~doc ~man ) let pause_cmd = let vm = vm_arg "paused" in let doc = "pause a VM" in let man = [ `S "DESCRIPTION" ; `P "Pause a VM." ; `P "The running VM will be marked as Paused: although it will\n\ \ still consume memory on the host, all of its virtual CPUs will\n\ \ be taken offline so the VM will stop executing." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.pause $ common_options_t $ vm)) , Cmd.info "pause" ~sdocs:_common_options ~doc ~man ) let unpause_cmd = let vm = vm_arg "unpaused" in let doc = "unpause a VM" in let man = [ `S "DESCRIPTION" ; `P "Unpause a VM." ; `P "A paused VM will be marked as Running: all of its virtual CPUs\n\ \ will be brought back online so the VM will start executing." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.unpause $ common_options_t $ vm)) , Cmd.info "unpause" ~sdocs:_common_options ~doc ~man ) let import_cmd = let filename = let doc = "Path of a previously-exported VM" in Arg.(value & opt (some file) None & info ["filename"] ~doc) in let metadata = let doc = "Import the VM metadata only." in Arg.(value & flag & info ["metadata-only"] ~doc) in let doc = "import a VM" in let man = [ `S "DESCRIPTION" ; `P "Import a VM from a filesystem" ; `P "A previously exported VM is reloaded from the filesystem." ; `P "The VM should have been exported in native (not xm/xl) format\n\ \ by \"export\". If you have an xm/xl format metadata file, it\n\ \ can be imported using \"add\"." ; `S "ERRORS" ; `P "Something about duplicate uuids." ] @ help in ( Term.(ret (const Xn.import $ common_options_t $ metadata $ filename)) , Cmd.info "import" ~sdocs:_common_options ~doc ~man ) let export_cmd = let vm = vm_arg "exported" in let filename = let doc = "Path to create in the filesystem" in Arg.(value & opt (some string) None & info ["filename"] ~doc) in let metadata = let doc = "Export the VM metadata only" in Arg.(value & flag & info ["metadata-only"] ~doc) in let xm = let doc = "Export in xm/xl format, instead of native" in Arg.(value & flag & info ["xm"] ~doc) in let doc = "export a VM" in let man = [ `S "DESCRIPTION" ; `P "Export a VM to the filesystem" ; `P "A currently registered VM is exported to the filesystem." ; `S "ERRORS" ; `P "Something about power states." ] @ help in ( Term.( ret (const Xn.export $ common_options_t $ metadata $ xm $ filename $ vm) ) , Cmd.info "export" ~sdocs:_common_options ~doc ~man ) let diagnostics_cmd = let doc = "retrieve diagnostic information" in let man = [ `S "DESCRIPTION" ; `P "Retrieve diagnostic information from the xenopsd service." ] @ help in ( Term.(ret (const Xn.diagnostics $ common_options_t)) , Cmd.info "diagnostics" ~sdocs:_common_options ~doc ~man ) let tasks_cmd = let doc = "List in-progress tasks" in let man = [`S "DESCRIPTION"; `P "Describe the set of in-progress tasks."] @ help in ( Term.(ret (const Xn.task_list $ common_options_t)) , Cmd.info "tasks" ~sdocs:_common_options ~doc ~man ) let task_cancel_cmd = let doc = "Cancel an in-progress task" in let man = [ `S "DESCRIPTION" ; `P "Attempt to cancel an in-progress task. The task should either \ complete, fail within a short amount of time." ] @ help in let task = let doc = "Task id to cancel" in Arg.(value & pos 0 (some string) None & info [] ~doc) in ( Term.(ret (const Xn.task_cancel $ common_options_t $ task)) , Cmd.info "task-cancel" ~sdocs:_common_options ~doc ~man ) let cd_eject_cmd = let doc = "Eject a CDROM" in let man = [`S "DESCRIPTION"; `P "Eject a CDROM from a CDROM drive"] @ help in let vbd = let doc = "VBD id" in Arg.(value & pos 0 (some string) None & info [] ~doc) in ( Term.(ret (const Xn.cd_eject $ common_options_t $ vbd)) , Cmd.info "cd-eject" ~sdocs:_common_options ~doc ~man ) let stat_vm_cmd = let doc = "Query the runtime status of a running VM." in let man = [`S "DESCRIPTION"; `P "Query the runtime status of a running VM."] @ help in let vm = let doc = "The uuid of the VM to stat." in Arg.(required & pos 0 (some string) None & info [] ~doc ~docv:"uuid") in ( Term.(ret (const Xn.stat_vm $ common_options_t $ vm)) , Cmd.info "vm-stat" ~sdocs:_common_options ~doc ~man ) let cmds = [ list_cmd ; create_cmd ; add_cmd ; remove_cmd ; start_cmd ; shutdown_cmd ; reboot_cmd ; suspend_cmd ; resume_cmd ; pause_cmd ; unpause_cmd ; import_cmd ; export_cmd ; console_cmd ; diagnostics_cmd ; events_cmd ; tasks_cmd ; task_cancel_cmd ; cd_eject_cmd ; stat_vm_cmd ] |> List.map (fun (t, i) -> Cmd.v i t) let default = Term.(ret (const (fun _ -> `Help (`Pager, None)) $ common_options_t)) let info = let doc = "interact with the XCP xenopsd VM management service" in let man = help in Cmd.info "xenops-cli" ~version:"1.0.0" ~sdocs:_common_options ~doc ~man let () = Xcp_client.use_switch := false ; let cmd = Cmd.group ~default info cmds in exit (Cmd.eval cmd)
null
https://raw.githubusercontent.com/xapi-project/xen-api/8d17b53bc236e23aa1ec455137773f7367665d83/ocaml/xenopsd/cli/main.ml
ocaml
Help sections common to all commands Options common to all commands Commands
* 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. *) let project_url = "-project/xenops-cli" open Cmdliner let _common_options = "COMMON OPTIONS" let help = [ `S _common_options ; `P "These options are common to all commands." ; `S "MORE HELP" ; `P "Use `$(mname) $(i,COMMAND) --help' for help on a single command." ; `Noblank ; `S "BUGS" ; `P (Printf.sprintf "Check bug reports at %s" project_url) ] let common_options_t = let docs = _common_options in let debug = let doc = "Give only debug output." in Arg.(value & flag & info ["debug"] ~docs ~doc) in let verb = let doc = "Give verbose output." in let verbose = (true, Arg.info ["v"; "verbose"] ~docs ~doc) in Arg.(last & vflag_all [false] [verbose]) in let socket = let doc = Printf.sprintf "Specify path to the server Unix domain socket." in Arg.( value & opt file !Xenops_interface.default_path & info ["socket"] ~docs ~doc ) in let queue = let default = Some "org.xen.xapi.xenops.classic" in let doc = Printf.sprintf "Specify queue name in message switch." in Arg.(value & opt (some string) default & info ["queue"] ~docs ~doc) in Term.(const Common.make $ debug $ verb $ socket $ queue) let events_cmd = let doc = "display a live stream of events" in let man = [ `S "DESCRIPTION" ; `P "Displays a live stream of events received from xenopsd. These events \ include VM powercycle events and VM configuration changes." ] @ help in ( Term.(ret (const Xn.events $ common_options_t)) , Cmd.info "events" ~sdocs:_common_options ~doc ~man ) let create_cmd = let doc = "register a VM and start it immediately" in let man = [ `S "DESCRIPTION" ; `P "Registers a new VM with the xenopsd service and starts it immediately." ] @ help in let filename = let doc = Printf.sprintf "Path to the VM metadata." in Arg.(value & pos 0 (some file) None & info [] ~doc) in let console = let doc = "Connect to the VM's console." in Arg.(value & flag & info ["console"] ~doc) in ( Term.(ret (const Xn.create $ common_options_t $ filename $ console)) , Cmd.info "create" ~sdocs:_common_options ~doc ~man ) let add_cmd = let doc = "register a new VM with xenopsd" in let man = [`S "DESCRIPTION"; `P "Registers a new VM with the xenopsd service."] @ help in let filename = let doc = Printf.sprintf "Path to the VM metadata to be registered." in Arg.(value & pos 0 (some file) None & info [] ~doc) in ( Term.(ret (const Xn.add $ common_options_t $ filename)) , Cmd.info "add" ~sdocs:_common_options ~doc ~man ) let list_cmd = let doc = "list the VMs registered with xenopsd" in let man = [ `S "DESCRIPTION" ; `P "Lists the VMs registered with the xenopsd service." ; `P "VMs are registered with xenospd via the \"add\" command and\n\ \ will be monitored until the corresponding \"remove\" command." ; `P "xenopsd will not touch any VMs (and domains) which have not\n\ \ been explicitly registered." ] @ help in ( Term.(const Xn.list $ common_options_t) , Cmd.info "list" ~sdocs:_common_options ~doc ~man ) let vm_arg verb = let doc = Printf.sprintf "The name or UUID of the VM to be %s." verb in Arg.(value & pos 0 (some string) None & info [] ~docv:"VM" ~doc) let remove_cmd = let vm = vm_arg "unregistered" in let doc = "unregister a VM" in let man = [ `S "DESCRIPTION" ; `P "Unregister a VM." ; `P "The xenopsd service will only manipulate VMs if they are\n\ \ explicitly registered with it. You should unregister a VM if \ either:" ; `P "1. the VM is not needed any more; or" ; `P "2. you intend to manage the VM on another host or using another \ toolstack." ; `P "Note: before attempting to use multiple toolstacks simultaneously on \ a single host,\n\ \ check all the relevant documentation to see whether this is a \ sensible thing to do." ; `P "Only Halted VMs may be unregistered." ; `S "ERRORS" ; `P "Something about power state exceptions" ] in ( Term.(ret (const Xn.remove $ common_options_t $ vm)) , Cmd.info "remove" ~sdocs:_common_options ~doc ~man ) let start_cmd = let vm = vm_arg "started" in let paused = let doc = "Leave the VM in a Paused state." in Arg.(value & flag & info ["paused"] ~doc) in let console = let doc = "Connect to the VM's console." in Arg.(value & flag & info ["console"] ~doc) in let doc = "start a VM" in let man = [ `S "DESCRIPTION" ; `P "Start a VM.\n\n\ \ If no additional arguments are provided then this command\n\ \ will return when the VM is in the \"Running\" state.\n\ \ If the --paused argument is specified then the VM will\n\ \ be left in the \"Paused\" state." ; `S "ERRORS" ; `P "Something about memory." ; `P "Something about disks." ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.start $ common_options_t $ paused $ console $ vm)) , Cmd.info "start" ~sdocs:_common_options ~doc ~man ) let console_cmd = let vm = let doc = "The name or UUID of the VM whose console to be accessed." in Arg.(value & pos 0 (some string) None & info [] ~docv:"VM" ~doc) in let doc = "attach to the console of a VM" in let man = [ `S "DESCRIPTION" ; `P "Attach to the console of a VM." ; `S "ERRORS" ; `P "Something about memory." ; `P "Something about disks." ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.console_connect $ common_options_t $ vm)) , Cmd.info "console" ~sdocs:_common_options ~doc ~man ) let shutdown_cmd = let vm = vm_arg "shutdown and powered off" in let timeout = let doc = "Amount of time to wait for the VM to cleanly shut itself down, before \ we power it off." in Arg.(value & opt (some float) None & info ["timeout"] ~doc) in let doc = "shutdown a VM" in let man = [ `S "DESCRIPTION" ; `P "Shutdown a VM." ; `P "If the specified VM is running, it will be asked to shutdown.\n\ \ If a <timeout> is specified then we will wait. If no <timeout>\n\ \ is specified or if the timeout expires, the VM will be powered \ off." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.shutdown $ common_options_t $ timeout $ vm)) , Cmd.info "shutdown" ~sdocs:_common_options ~doc ~man ) let reboot_cmd = let vm = vm_arg "rebooted" in let timeout = let doc = "Amount of time to wait for the VM to cleanly shut itself down, before \ we power it off and then on." in Arg.(value & opt (some float) None & info ["timeout"] ~doc) in let doc = "reboot a VM" in let man = [ `S "DESCRIPTION" ; `P "Reboot a VM." ; `P "If the specified VM is running, it will be asked to reboot.\n\ \ If a <timeout> is specified then we will wait. If no <timeout>\n\ \ is specified or if the timeout expires, the VM will be powered \ off.\n\ \ We will then power the VM back on again." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.reboot $ common_options_t $ timeout $ vm)) , Cmd.info "reboot" ~sdocs:_common_options ~doc ~man ) let suspend_cmd = let vm = vm_arg "suspended" in let device = let doc = "Block device to write the suspend image to" in Arg.(value & opt (some file) None & info ["block-device"] ~doc) in let doc = "suspend a VM" in let man = [ `S "DESCRIPTION" ; `P "Suspend a VM." ; `P "If the specified VM is running, it will be asked to suspend.\n\ \ The memory image will be saved to the specified block device." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.suspend $ common_options_t $ device $ vm)) , Cmd.info "suspend" ~sdocs:_common_options ~doc ~man ) let resume_cmd = let vm = vm_arg "resumed" in let device = let doc = "Block device to read the suspend image from" in Arg.(value & opt (some file) None & info ["block-device"] ~doc) in let doc = "resume a VM" in let man = [ `S "DESCRIPTION" ; `P "Resume a VM." ; `P "The VM memory image will be reloaded from the specified block device\n\ \ and the VM will be left in a Running state." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.resume $ common_options_t $ device $ vm)) , Cmd.info "resume" ~sdocs:_common_options ~doc ~man ) let pause_cmd = let vm = vm_arg "paused" in let doc = "pause a VM" in let man = [ `S "DESCRIPTION" ; `P "Pause a VM." ; `P "The running VM will be marked as Paused: although it will\n\ \ still consume memory on the host, all of its virtual CPUs will\n\ \ be taken offline so the VM will stop executing." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.pause $ common_options_t $ vm)) , Cmd.info "pause" ~sdocs:_common_options ~doc ~man ) let unpause_cmd = let vm = vm_arg "unpaused" in let doc = "unpause a VM" in let man = [ `S "DESCRIPTION" ; `P "Unpause a VM." ; `P "A paused VM will be marked as Running: all of its virtual CPUs\n\ \ will be brought back online so the VM will start executing." ; `S "ERRORS" ; `P "Something about the current power state." ] @ help in ( Term.(ret (const Xn.unpause $ common_options_t $ vm)) , Cmd.info "unpause" ~sdocs:_common_options ~doc ~man ) let import_cmd = let filename = let doc = "Path of a previously-exported VM" in Arg.(value & opt (some file) None & info ["filename"] ~doc) in let metadata = let doc = "Import the VM metadata only." in Arg.(value & flag & info ["metadata-only"] ~doc) in let doc = "import a VM" in let man = [ `S "DESCRIPTION" ; `P "Import a VM from a filesystem" ; `P "A previously exported VM is reloaded from the filesystem." ; `P "The VM should have been exported in native (not xm/xl) format\n\ \ by \"export\". If you have an xm/xl format metadata file, it\n\ \ can be imported using \"add\"." ; `S "ERRORS" ; `P "Something about duplicate uuids." ] @ help in ( Term.(ret (const Xn.import $ common_options_t $ metadata $ filename)) , Cmd.info "import" ~sdocs:_common_options ~doc ~man ) let export_cmd = let vm = vm_arg "exported" in let filename = let doc = "Path to create in the filesystem" in Arg.(value & opt (some string) None & info ["filename"] ~doc) in let metadata = let doc = "Export the VM metadata only" in Arg.(value & flag & info ["metadata-only"] ~doc) in let xm = let doc = "Export in xm/xl format, instead of native" in Arg.(value & flag & info ["xm"] ~doc) in let doc = "export a VM" in let man = [ `S "DESCRIPTION" ; `P "Export a VM to the filesystem" ; `P "A currently registered VM is exported to the filesystem." ; `S "ERRORS" ; `P "Something about power states." ] @ help in ( Term.( ret (const Xn.export $ common_options_t $ metadata $ xm $ filename $ vm) ) , Cmd.info "export" ~sdocs:_common_options ~doc ~man ) let diagnostics_cmd = let doc = "retrieve diagnostic information" in let man = [ `S "DESCRIPTION" ; `P "Retrieve diagnostic information from the xenopsd service." ] @ help in ( Term.(ret (const Xn.diagnostics $ common_options_t)) , Cmd.info "diagnostics" ~sdocs:_common_options ~doc ~man ) let tasks_cmd = let doc = "List in-progress tasks" in let man = [`S "DESCRIPTION"; `P "Describe the set of in-progress tasks."] @ help in ( Term.(ret (const Xn.task_list $ common_options_t)) , Cmd.info "tasks" ~sdocs:_common_options ~doc ~man ) let task_cancel_cmd = let doc = "Cancel an in-progress task" in let man = [ `S "DESCRIPTION" ; `P "Attempt to cancel an in-progress task. The task should either \ complete, fail within a short amount of time." ] @ help in let task = let doc = "Task id to cancel" in Arg.(value & pos 0 (some string) None & info [] ~doc) in ( Term.(ret (const Xn.task_cancel $ common_options_t $ task)) , Cmd.info "task-cancel" ~sdocs:_common_options ~doc ~man ) let cd_eject_cmd = let doc = "Eject a CDROM" in let man = [`S "DESCRIPTION"; `P "Eject a CDROM from a CDROM drive"] @ help in let vbd = let doc = "VBD id" in Arg.(value & pos 0 (some string) None & info [] ~doc) in ( Term.(ret (const Xn.cd_eject $ common_options_t $ vbd)) , Cmd.info "cd-eject" ~sdocs:_common_options ~doc ~man ) let stat_vm_cmd = let doc = "Query the runtime status of a running VM." in let man = [`S "DESCRIPTION"; `P "Query the runtime status of a running VM."] @ help in let vm = let doc = "The uuid of the VM to stat." in Arg.(required & pos 0 (some string) None & info [] ~doc ~docv:"uuid") in ( Term.(ret (const Xn.stat_vm $ common_options_t $ vm)) , Cmd.info "vm-stat" ~sdocs:_common_options ~doc ~man ) let cmds = [ list_cmd ; create_cmd ; add_cmd ; remove_cmd ; start_cmd ; shutdown_cmd ; reboot_cmd ; suspend_cmd ; resume_cmd ; pause_cmd ; unpause_cmd ; import_cmd ; export_cmd ; console_cmd ; diagnostics_cmd ; events_cmd ; tasks_cmd ; task_cancel_cmd ; cd_eject_cmd ; stat_vm_cmd ] |> List.map (fun (t, i) -> Cmd.v i t) let default = Term.(ret (const (fun _ -> `Help (`Pager, None)) $ common_options_t)) let info = let doc = "interact with the XCP xenopsd VM management service" in let man = help in Cmd.info "xenops-cli" ~version:"1.0.0" ~sdocs:_common_options ~doc ~man let () = Xcp_client.use_switch := false ; let cmd = Cmd.group ~default info cmds in exit (Cmd.eval cmd)
89d8b5f5802aa9615d06d5eec2e6462a59b3fcfd5d1fde9d7228eeb476a3de32
discus-lang/salt
Nat.hs
module Salt.Core.Prim.Ops.Nat where import Salt.Core.Prim.Ops.Base import qualified Data.Text as T primOpsNat = [ PP { name = "nat'show" , tsig = [TNat] :-> [TText] , step = \[NVs [VNat n]] -> [VText $ T.pack $ show n] , docs = "Convert nat to text." } , PP { name = "nat'add" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 + n2] , docs = "Natural number addition." } , PP { name = "nat'sub" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 - n2] , docs = "Natural number subtraction." } , PP { name = "nat'mul" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 * n2] , docs = "Natural number multiplication." } , PP { name = "nat'div" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 `div` n2] , docs = "Natural number division." } , PP { name = "nat'rem" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 `rem` n2] , docs = "Natural number remainder." } , PP { name = "nat'eq" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 == n2] , docs = "Natural number equality." } , PP { name = "nat'neq" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 /= n2] , docs = "Natural number negated equality." } , PP { name = "nat'lt" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 < n2] , docs = "Natural number less-than." } , PP { name = "nat'le" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 <= n2] , docs = "Natural number less-than or equal." } , PP { name = "nat'gt" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 > n2] , docs = "Natural number greater-than." } , PP { name = "nat'ge" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 >= n2] , docs = "Natural number greater-than or equal." } ]
null
https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/Core/Prim/Ops/Nat.hs
haskell
module Salt.Core.Prim.Ops.Nat where import Salt.Core.Prim.Ops.Base import qualified Data.Text as T primOpsNat = [ PP { name = "nat'show" , tsig = [TNat] :-> [TText] , step = \[NVs [VNat n]] -> [VText $ T.pack $ show n] , docs = "Convert nat to text." } , PP { name = "nat'add" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 + n2] , docs = "Natural number addition." } , PP { name = "nat'sub" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 - n2] , docs = "Natural number subtraction." } , PP { name = "nat'mul" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 * n2] , docs = "Natural number multiplication." } , PP { name = "nat'div" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 `div` n2] , docs = "Natural number division." } , PP { name = "nat'rem" , tsig = [TNat, TNat] :-> [TNat] , step = \[NVs [VNat n1, VNat n2]] -> [VNat $ n1 `rem` n2] , docs = "Natural number remainder." } , PP { name = "nat'eq" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 == n2] , docs = "Natural number equality." } , PP { name = "nat'neq" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 /= n2] , docs = "Natural number negated equality." } , PP { name = "nat'lt" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 < n2] , docs = "Natural number less-than." } , PP { name = "nat'le" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 <= n2] , docs = "Natural number less-than or equal." } , PP { name = "nat'gt" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 > n2] , docs = "Natural number greater-than." } , PP { name = "nat'ge" , tsig = [TNat, TNat] :-> [TBool] , step = \[NVs [VNat n1, VNat n2]] -> [VBool $ n1 >= n2] , docs = "Natural number greater-than or equal." } ]
7335447bee25693cc970acdc579de61f146e8075948e5d1f9cb7bd4f2df5fe04
vgeddes/scheme-compiler
munch-syntax.scm
(import-for-syntax matchable) (import-for-syntax srfi-1) ;; convenience constructors (used in pattern match rules) (define-syntax define-munch-rules (lambda (e r c) (let ((%let* (r 'let*)) (%let (r 'let)) (%if (r 'if)) (%cond (r 'cond)) (%else (r 'else)) (%define (r 'define)) (%match (r 'match)) (%gensym (r 'gensym)) (%block (r 'block)) (%tree (r 'tree)) (%t1 (gensym 't)) (%mc-block-append (r 'mc-block-append)) (%mc-context-allocate-vreg (r 'mc-context-allocate-vreg)) (%mc-block-cxt (r 'mc-block-cxt))) (define renamed '()) (define (rename name) (cond ((assq name renamed) => cdr) (else (let ((x (gensym))) (set! renamed (cons (cons name x) renamed)) x)))) ;; select-names ;; ;; Find names (which are bound to nodes by 'match) which need to be expanded next by the maximal-munch algorithm ;; ( add ( i32 x ) op2 ) ;; => (op2) (define (select-names pat) (match pat ((? symbol? x) (list x)) ((or ('const _ _) ('mode _) ('op _) ('label _) ('temp _)) '()) ((opcode operand* ...) (apply append (map select-names operand*))))) ;; compile-pattern ;; ;; Transform high-level patterns into low-level 'match patterns ;; ( add ( i32 x ) op2 ) = > ( $ tree - instr ' add ( ' mode ' i32 ) ( ? i32 ? x ) ( ? symbol ? ) ) ;; (define (compile-pattern pat) (define (walk pat) (match pat ;; assign (('assign ('temp x) op) `($ tree-instr 'assign _ (? symbol? ,x) ,(walk op) _ _ _ _ _)) ;; binops (('add mode op1 op2) `($ tree-instr 'add ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('sub mode op1 op2) `($ tree-instr 'sub ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('and mode op1 op2) `($ tree-instr 'and ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('ior mode op1 op2) `($ tree-instr 'ior ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('xor mode op1 op2) `($ tree-instr 'xor ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('shl mode op1 op2) `($ tree-instr 'shl ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('shr mode op1 op2) `($ tree-instr 'shr ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) ;; load (('load mode addr) `($ tree-instr 'load ',(walk mode) ,(walk addr) _ _ _ _ _ _)) ;; store (('store mode value addr) `($ tree-instr 'store ',(walk mode) ,(walk value) ,(walk addr) _ _ _ _ _)) brc (('brc cond label1 label2) `($ tree-instr 'brc _ ,(walk cond) ,(walk label1) ,(walk label2) _ _ _ _)) ;; br (('br label) `($ tree-instr 'br _ ,(walk label) _ _ _ _ _ _)) ;; cmp (('cmp mode ('op test) op1 op2) `($ tree-instr 'cmp ',(walk mode) ',test ,(walk op1) ,(walk op2) _ _ _ _)) ;; atoms (('const size x) `($ tree-constant ',size ,x)) (('label x) `($ tree-label ,x)) (('temp x) `($ tree-temp ,x)) ((? symbol? x) (rename x)) ;; mode (('mode x) x) ;;(_ (print pat)) )) (walk pat)) (define (gen-bindings arch bindings) (let ((function-name (string->symbol (format "munch-~s" arch)))) (match bindings (() '()) ((expr . rest) (cons `(,expr (,function-name ,%block ,(rename expr))) (gen-bindings arch rest)))))) (define (parse-temp-cls out) (match out (('temps t* ...) t*) (else (assert-not-reached)))) (define (parse-out-cls out) (match out (('out x) x) (('out) #f) (else (assert-not-reached)))) (define (gen-code arch pat temps out tmpl*) (let* ((nodes-to-expand (select-names pat)) (pat-compiled (compile-pattern pat)) (bindings (append ;; Bind names to expanded nodes (gen-bindings arch nodes-to-expand) (cond ;; bind the name 'out' to a gensym if this production requires a return value (in which case out != #f) ;; AND the user-specified return value is not already listed in nodes-to-expand. ((and out (not (memq out nodes-to-expand))) `((,out (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) (,%gensym 't))))) (else '())) ;; bind temps to unique symbols (remembering not to bind 'out again if it is declared as a temp) (map (lambda (temp) `(,temp (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) (,%gensym 't)))) (lset-difference eq? temps (list out)))))) `(,pat-compiled (,%let* ,bindings (arch-emit-code ,arch ,%block ,@tmpl*) ,out)))) (define (compile arch rule) (match rule ((pat temp-cls out-cls (tmpl* ...)) (gen-code arch pat (parse-temp-cls temp-cls) (parse-out-cls out-cls) tmpl*)))) (define (compile-rules arch rule*) (reverse (fold (lambda (rule x) (cons (compile arch rule) x)) '() rule*))) (match e (('define-munch-rules arch rule* ...) (let* ((rule-compiled* (compile-rules arch rule*)) (function-name (string->symbol (format "munch-~s" arch)))) ;; (pretty-print ;; `(,%define (,function-name ,%block ,%tree) ;; (,%match ,%tree ;; (($ tree-temp ,%t1) ;; (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) ,%t1)) ;; ,@rule-compiled* ;; (_ (tree-instr-print ,%tree (current-output-port)) (error "no matching pattern"))))) `(,%define (,function-name ,%block ,%tree) (,%match ,%tree (($ tree-temp ,%t1) (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) ,%t1)) ,@rule-compiled* (_ (tree-instr-print ,%tree (current-output-port)) (error "no matching pattern"))))))))))
null
https://raw.githubusercontent.com/vgeddes/scheme-compiler/a2ac2d15e96a06d6d50133f516f424856e055cab/munch-syntax.scm
scheme
convenience constructors (used in pattern match rules) select-names Find names (which are bound to nodes by 'match) which need to be expanded next by the maximal-munch algorithm => (op2) compile-pattern Transform high-level patterns into low-level 'match patterns assign binops load store br cmp atoms mode (_ (print pat)) Bind names to expanded nodes bind the name 'out' to a gensym if this production requires a return value (in which case out != #f) AND the user-specified return value is not already listed in nodes-to-expand. bind temps to unique symbols (remembering not to bind 'out again if it is declared as a temp) (pretty-print `(,%define (,function-name ,%block ,%tree) (,%match ,%tree (($ tree-temp ,%t1) (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) ,%t1)) ,@rule-compiled* (_ (tree-instr-print ,%tree (current-output-port)) (error "no matching pattern")))))
(import-for-syntax matchable) (import-for-syntax srfi-1) (define-syntax define-munch-rules (lambda (e r c) (let ((%let* (r 'let*)) (%let (r 'let)) (%if (r 'if)) (%cond (r 'cond)) (%else (r 'else)) (%define (r 'define)) (%match (r 'match)) (%gensym (r 'gensym)) (%block (r 'block)) (%tree (r 'tree)) (%t1 (gensym 't)) (%mc-block-append (r 'mc-block-append)) (%mc-context-allocate-vreg (r 'mc-context-allocate-vreg)) (%mc-block-cxt (r 'mc-block-cxt))) (define renamed '()) (define (rename name) (cond ((assq name renamed) => cdr) (else (let ((x (gensym))) (set! renamed (cons (cons name x) renamed)) x)))) ( add ( i32 x ) op2 ) (define (select-names pat) (match pat ((? symbol? x) (list x)) ((or ('const _ _) ('mode _) ('op _) ('label _) ('temp _)) '()) ((opcode operand* ...) (apply append (map select-names operand*))))) ( add ( i32 x ) op2 ) = > ( $ tree - instr ' add ( ' mode ' i32 ) ( ? i32 ? x ) ( ? symbol ? ) ) (define (compile-pattern pat) (define (walk pat) (match pat (('assign ('temp x) op) `($ tree-instr 'assign _ (? symbol? ,x) ,(walk op) _ _ _ _ _)) (('add mode op1 op2) `($ tree-instr 'add ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('sub mode op1 op2) `($ tree-instr 'sub ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('and mode op1 op2) `($ tree-instr 'and ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('ior mode op1 op2) `($ tree-instr 'ior ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('xor mode op1 op2) `($ tree-instr 'xor ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('shl mode op1 op2) `($ tree-instr 'shl ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('shr mode op1 op2) `($ tree-instr 'shr ',(walk mode) ,(walk op1) ,(walk op2) _ _ _ _ _)) (('load mode addr) `($ tree-instr 'load ',(walk mode) ,(walk addr) _ _ _ _ _ _)) (('store mode value addr) `($ tree-instr 'store ',(walk mode) ,(walk value) ,(walk addr) _ _ _ _ _)) brc (('brc cond label1 label2) `($ tree-instr 'brc _ ,(walk cond) ,(walk label1) ,(walk label2) _ _ _ _)) (('br label) `($ tree-instr 'br _ ,(walk label) _ _ _ _ _ _)) (('cmp mode ('op test) op1 op2) `($ tree-instr 'cmp ',(walk mode) ',test ,(walk op1) ,(walk op2) _ _ _ _)) (('const size x) `($ tree-constant ',size ,x)) (('label x) `($ tree-label ,x)) (('temp x) `($ tree-temp ,x)) ((? symbol? x) (rename x)) (('mode x) x) )) (walk pat)) (define (gen-bindings arch bindings) (let ((function-name (string->symbol (format "munch-~s" arch)))) (match bindings (() '()) ((expr . rest) (cons `(,expr (,function-name ,%block ,(rename expr))) (gen-bindings arch rest)))))) (define (parse-temp-cls out) (match out (('temps t* ...) t*) (else (assert-not-reached)))) (define (parse-out-cls out) (match out (('out x) x) (('out) #f) (else (assert-not-reached)))) (define (gen-code arch pat temps out tmpl*) (let* ((nodes-to-expand (select-names pat)) (pat-compiled (compile-pattern pat)) (bindings (append (gen-bindings arch nodes-to-expand) (cond ((and out (not (memq out nodes-to-expand))) `((,out (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) (,%gensym 't))))) (else '())) (map (lambda (temp) `(,temp (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) (,%gensym 't)))) (lset-difference eq? temps (list out)))))) `(,pat-compiled (,%let* ,bindings (arch-emit-code ,arch ,%block ,@tmpl*) ,out)))) (define (compile arch rule) (match rule ((pat temp-cls out-cls (tmpl* ...)) (gen-code arch pat (parse-temp-cls temp-cls) (parse-out-cls out-cls) tmpl*)))) (define (compile-rules arch rule*) (reverse (fold (lambda (rule x) (cons (compile arch rule) x)) '() rule*))) (match e (('define-munch-rules arch rule* ...) (let* ((rule-compiled* (compile-rules arch rule*)) (function-name (string->symbol (format "munch-~s" arch)))) `(,%define (,function-name ,%block ,%tree) (,%match ,%tree (($ tree-temp ,%t1) (,%mc-context-allocate-vreg (,%mc-block-cxt ,%block) ,%t1)) ,@rule-compiled* (_ (tree-instr-print ,%tree (current-output-port)) (error "no matching pattern"))))))))))
7a5a3a37753ffcff3a5f84b6f36c680358d009303eb1dc7d7f7fd4e889ec2c09
4clojure/4clojure
messages.clj
(ns foreclojure.messages) (defn load-props [file] (into {} (doto (java.util.Properties.) (.load (-> (Thread/currentThread) (.getContextClassLoader) (.getResourceAsStream file)))))) (def err-msg-map (load-props "error-messages.properties")) (defn err-msg [key & args] (apply format (cons (get err-msg-map key) args)))
null
https://raw.githubusercontent.com/4clojure/4clojure/25dec057d9d6871ce52aee9e2c3de7efdab14373/src/foreclojure/messages.clj
clojure
(ns foreclojure.messages) (defn load-props [file] (into {} (doto (java.util.Properties.) (.load (-> (Thread/currentThread) (.getContextClassLoader) (.getResourceAsStream file)))))) (def err-msg-map (load-props "error-messages.properties")) (defn err-msg [key & args] (apply format (cons (get err-msg-map key) args)))
f9d0aa53c8bc44fa024b20bb576d82053c99b42f20dd5b17638653b561a9c696
FranklinChen/hugs98-plus-Sep2006
Trans.hs
----------------------------------------------------------------------------- -- | Module : Control . . Trans Copyright : ( c ) 2001 , ( c ) Oregon Graduate Institute of Science and Technology , 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- -- The MonadTrans class. -- -- Inspired by the paper -- /Functional Programming with Overloading and -- Higher-Order Polymorphism/, ( < /~mpj/ > ) Advanced School of Functional Programming , 1995 . ----------------------------------------------------------------------------- module Control.Monad.Trans ( MonadTrans(..), MonadIO(..), ) where import Prelude import System.IO -- --------------------------------------------------------------------------- -- MonadTrans class -- Monad to facilitate stackable Monads . -- Provides a way of digging into an outer -- monad, giving access to (lifting) the inner monad. class MonadTrans t where lift :: Monad m => m a -> t m a class (Monad m) => MonadIO m where liftIO :: IO a -> m a instance MonadIO IO where liftIO = id
null
https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/mtl/Control/Monad/Trans.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : portable The MonadTrans class. Inspired by the paper /Functional Programming with Overloading and Higher-Order Polymorphism/, --------------------------------------------------------------------------- --------------------------------------------------------------------------- MonadTrans class Provides a way of digging into an outer monad, giving access to (lifting) the inner monad.
Module : Control . . Trans Copyright : ( c ) 2001 , ( c ) Oregon Graduate Institute of Science and Technology , 2001 ( < /~mpj/ > ) Advanced School of Functional Programming , 1995 . module Control.Monad.Trans ( MonadTrans(..), MonadIO(..), ) where import Prelude import System.IO Monad to facilitate stackable Monads . class MonadTrans t where lift :: Monad m => m a -> t m a class (Monad m) => MonadIO m where liftIO :: IO a -> m a instance MonadIO IO where liftIO = id
21afa77906027ac5fd2797d04cb2652bf799efabc2054ebf9b7be1ee71096a5e
wdhowe/clojure-snippets
factorial.clj
;; using iterative recursion to solve factorials (defn factorial-iter [count total] (if (= count 1) total (factorial-iter (- count 1) (* total (- count 1))))) (defn factorial [num] (factorial-iter num num)) (println (factorial 4))
null
https://raw.githubusercontent.com/wdhowe/clojure-snippets/0c3247ce99a563312b549d03f080b8cf449b541d/iter_recur/factorial.clj
clojure
using iterative recursion to solve factorials
(defn factorial-iter [count total] (if (= count 1) total (factorial-iter (- count 1) (* total (- count 1))))) (defn factorial [num] (factorial-iter num num)) (println (factorial 4))
def3cbd79745111183f6f18b5fc0684c45459bb370620f686cd767bbb72700e8
mgeorgoulopoulos/TetrisHaskellWeekend
Renderer.hs
-- Renderer - module that maps a game state into a gloss picture module Renderer(render) where import State import Playfield import Graphics.Gloss -- Let's start with rendering an empty well. -- Playfield dimensions cellSize = 35 padding = (768 - (20 * cellSize)) `quot` 2 wellWidth = 10 * cellSize wellHeight = 20 * cellSize wallWidth = wellWidth + 2 * padding wallHeight = wellHeight + 2 * padding -- Colors wellColor = black wallColor = dark (dark blue) -- Convert from playfield coordinate to screen coordinate playfieldToScreen :: (Int, Int) -> (Int, Int) playfieldToScreen (px, py) = (sx, sy) where sx = (px * cellSize) `quot` 2 sy = (11 * cellSize) + (py * cellSize) `quot` 2 -- Function that renders a single cell renderCell :: (Int, Int) -> Color -> Picture renderCell (px, py) col = translate (fromIntegral sx) (fromIntegral sy) (color col (rectangleSolid sz sz)) where sx = fst transformed sy = snd transformed sz = 0.9 * (fromIntegral cellSize) transformed = playfieldToScreen (px, py) -- Renders Well playfield to Picture renderWell :: Well -> Picture renderWell well = pictures (map cellToPicture (coordCells well)) where cellToPicture (px,py,c) | py > (-3) = pictures [] | c == Empty = pictures [] | otherwise = renderCell (px, py) (cellColor c) -- Game State renderer render :: State -> Picture render gameState = pictures [ walls, playfield, activePiece, guiStuff ] where walls = color wallColor (rectangleSolid (fromIntegral wallWidth) (fromIntegral wallHeight)) playfield = pictures [ color wellColor (rectangleSolid (fromIntegral wellWidth) (fromIntegral wellHeight)) , renderWell (well gameState) ] activePiece = renderWell (renderPiece (piece gameState) (piecePos gameState) emptyWell) guiStuff = translate (-600.0) (200.0) (scale 0.4 0.4 (pictures [playerScore])) where playerScore = color white (Text scoreText) scoreText = "SCORE: " ++ (show (score gameState))
null
https://raw.githubusercontent.com/mgeorgoulopoulos/TetrisHaskellWeekend/7dc406852e7578fb009434de54e3d3eb5b4f90f0/Renderer.hs
haskell
Renderer - module that maps a game state into a gloss picture Let's start with rendering an empty well. Playfield dimensions Colors Convert from playfield coordinate to screen coordinate Function that renders a single cell Renders Well playfield to Picture Game State renderer
module Renderer(render) where import State import Playfield import Graphics.Gloss cellSize = 35 padding = (768 - (20 * cellSize)) `quot` 2 wellWidth = 10 * cellSize wellHeight = 20 * cellSize wallWidth = wellWidth + 2 * padding wallHeight = wellHeight + 2 * padding wellColor = black wallColor = dark (dark blue) playfieldToScreen :: (Int, Int) -> (Int, Int) playfieldToScreen (px, py) = (sx, sy) where sx = (px * cellSize) `quot` 2 sy = (11 * cellSize) + (py * cellSize) `quot` 2 renderCell :: (Int, Int) -> Color -> Picture renderCell (px, py) col = translate (fromIntegral sx) (fromIntegral sy) (color col (rectangleSolid sz sz)) where sx = fst transformed sy = snd transformed sz = 0.9 * (fromIntegral cellSize) transformed = playfieldToScreen (px, py) renderWell :: Well -> Picture renderWell well = pictures (map cellToPicture (coordCells well)) where cellToPicture (px,py,c) | py > (-3) = pictures [] | c == Empty = pictures [] | otherwise = renderCell (px, py) (cellColor c) render :: State -> Picture render gameState = pictures [ walls, playfield, activePiece, guiStuff ] where walls = color wallColor (rectangleSolid (fromIntegral wallWidth) (fromIntegral wallHeight)) playfield = pictures [ color wellColor (rectangleSolid (fromIntegral wellWidth) (fromIntegral wellHeight)) , renderWell (well gameState) ] activePiece = renderWell (renderPiece (piece gameState) (piecePos gameState) emptyWell) guiStuff = translate (-600.0) (200.0) (scale 0.4 0.4 (pictures [playerScore])) where playerScore = color white (Text scoreText) scoreText = "SCORE: " ++ (show (score gameState))
9f4f454147af780483ee8f1cd882f341eebebbf2a3f977ca60524a000b734b85
GaloisInc/what4
SMTLib2.hs
------------------------------------------------------------------------ -- | -- Module : What4.Protocol.SMTLib2 Description : Interface for solvers that consume SMTLib2 Copyright : ( c ) Galois , Inc 2014 - 2020 -- License : BSD3 Maintainer : < > -- Stability : provisional -- This module defines operations for producing SMTLib2 - compatible queries useful for interfacing with solvers that accecpt SMTLib2 as -- an input language. ------------------------------------------------------------------------ # LANGUAGE AllowAmbiguousTypes # # LANGUAGE CPP # # LANGUAGE DataKinds # {-# LANGUAGE GADTs #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE MultiWayIf #-} # LANGUAGE OverloadedLists # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternGuards # # LANGUAGE PatternSynonyms # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - orphans # module What4.Protocol.SMTLib2 ( -- SMTLib special purpose exports Writer , SMTLib2Tweaks(..) , newWriter , writeCheckSat , writeExit , writeGetValue , writeGetAbduct , writeGetAbductNext , writeCheckSynth , runCheckSat , runGetAbducts , asSMT2Type , setOption , getVersion , versionResult , getName , nameResult , setProduceModels , smtLibEvalFuns , smtlib2Options , parseFnModel , parseFnValues -- * Logic , SMT2.Logic(..) , SMT2.qf_bv , SMT2.allSupported , SMT2.hornLogic , all_supported , setLogic -- * Type , SMT2.Sort(..) , SMT2.arraySort -- * Term , Term(..) , arrayConst , What4.Protocol.SMTLib2.arraySelect , arrayStore -- * Solvers and External interface , Session(..) , SMTLib2GenericSolver(..) , writeDefaultSMT2 , defaultFileWriter , startSolver , shutdownSolver , smtAckResult , SMTLib2Exception(..) -- * Solver version , ppSolverVersionCheckError , ppSolverVersionError , checkSolverVersion , checkSolverVersion' , queryErrorBehavior , defaultSolverBounds -- * Re-exports , SMTWriter.WriterConn , SMTWriter.assume , SMTWriter.supportedFeatures , SMTWriter.nullAcknowledgementAction ) where #if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail( MonadFail ) #endif import Control.Applicative import Control.Exception import Control.Monad.Except import Control.Monad.Reader import qualified Data.Bimap as Bimap import qualified Data.BitVector.Sized as BV import Data.Char (digitToInt, isAscii) import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as HashMap import Data.IORef import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Monoid import Data.Parameterized.Classes import qualified Data.Parameterized.Context as Ctx import Data.Parameterized.Map (MapF) import qualified Data.Parameterized.Map as MapF import Data.Parameterized.NatRepr import Data.Parameterized.Pair import Data.Parameterized.Some import Data.Parameterized.TraversableFC import Data.Ratio import Data.Set (Set) import qualified Data.Set as Set import Data.String import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as Lazy import Data.Text.Lazy.Builder (Builder) import qualified Data.Text.Lazy.Builder as Builder import qualified Data.Text.Lazy.Builder.Int as Builder import Numeric (readDec, readHex, readInt, showHex) import Numeric.Natural import qualified System.Exit as Exit import qualified System.IO as IO import qualified System.IO.Streams as Streams import Data.Versions (Version(..)) import qualified Data.Versions as Versions import qualified Prettyprinter as PP import Text.Printf (printf) import LibBF( bfToBits ) import Prelude hiding (writeFile) import What4.BaseTypes import qualified What4.Config as CFG import qualified What4.Expr.Builder as B import What4.Expr.GroundEval import qualified What4.Interface as I import What4.ProblemFeatures import What4.Protocol.Online import What4.Protocol.ReadDecimal import What4.Protocol.SExp import What4.Protocol.SMTLib2.Syntax (Term, term_app, un_app, bin_app) import What4.Protocol.SMTLib2.Response import qualified What4.Protocol.SMTLib2.Syntax as SMT2 hiding (Term) import qualified What4.Protocol.SMTWriter as SMTWriter import What4.Protocol.SMTWriter hiding (assume, Term) import What4.SatResult import What4.Utils.FloatHelpers (fppOpts) import What4.Utils.HandleReader import What4.Utils.Process import What4.Utils.Versions import What4.Solver.Adapter -- | Set the logic to all supported logics. all_supported :: SMT2.Logic all_supported = SMT2.allLogic # DEPRECATED all_supported " Use instead " # smtlib2Options :: [CFG.ConfigDesc] smtlib2Options = smtParseOptions ------------------------------------------------------------------------ -- Floating point data SMTFloatPrecision = SMTFloatPrecision { smtFloatExponentBits :: !Natural -- ^ Number of bits in exponent , smtFloatSignificandBits :: !Natural -- ^ Number of bits in the significand. } deriving (Eq, Ord) asSMTFloatPrecision :: FloatPrecisionRepr fpp -> SMTFloatPrecision asSMTFloatPrecision (FloatingPointPrecisionRepr eb sb) = SMTFloatPrecision { smtFloatExponentBits = natValue eb , smtFloatSignificandBits = natValue sb } mkFloatSymbol :: Builder -> SMTFloatPrecision -> Builder mkFloatSymbol nm (SMTFloatPrecision eb sb) = "(_ " <> nm <> " " <> fromString (show eb) <> " " <> fromString (show sb) <> ")" ------------------------------------------------------------------------ SMTLib2Tweaks -- | Select a valued from a nested array nestedArrayUpdate :: Term -> (Term, [Term]) -> Term -> Term nestedArrayUpdate a (h,[]) v = SMT2.store a h v nestedArrayUpdate a (h,i:l) v = SMT2.store a h sub_a' where sub_a' = nestedArrayUpdate (SMT2.select a h) (i,l) v arrayConst :: SMT2.Sort -> SMT2.Sort -> Term -> Term arrayConst = SMT2.arrayConst arraySelect :: Term -> Term -> Term arraySelect = SMT2.select arrayStore :: Term -> Term -> Term -> Term arrayStore = SMT2.store ------------------------------------------------------------------------------------ -- String Escaping functions -- -- The following functions implement the escaping and escape parsing rules from SMTLib 2.6 . Documentation -- regarding this format is pasted below from the -- specification document. -- -- String literals All double - quote - delimited string literals consisting of printable US ASCII characters , i.e. , those with Unicode code point from 0x00020 to 0x0007E. -- We refer to these literals as _string constants_. -- The restriction to printable US ASCII characters in string constants is for -- simplicity since that set is universally supported. Arbitrary Unicode characters can be represented with _ escape sequences _ which can have one of the following -- forms -- \ud₃d₂d₁d₀ -- \u{d₀} -- \u{d₁d₀} -- \u{d₂d₁d₀} -- \u{d₃d₂d₁d₀} -- \u{d₄d₃d₂d₁d₀} where each dᵢ is a hexadecimal digit and is restricted to the range 0 - 2 . -- These are the **only escape sequences** in this theory. See later. -- In a later version, the restrictions above on the digits may be extended to allow characters from all 17 Unicode planes . -- Observe that the first form , \ud₃d₂d₁d₀ , has exactly 4 hexadecimal digit , -- following the common use of this form in some programming languages. -- Unicode characters outside the range covered by \ud₃d₂d₁d₀ can be -- represented with the long form \u{d₄d₃d₂d₁d₀}. -- -- Also observe that programming language-specific escape sequences, such as \n , \b , \r and so on , are _ not _ escape sequences in this theory as they -- are not fully standard across languages. -- | Apply the SMTLib2.6 string escaping rules to a string literal. textToTerm :: Text -> Term textToTerm bs = SMT2.T ("\"" <> Text.foldr f "\"" bs) where inLiteralRange c = 0x20 <= fromEnum c && fromEnum c <= 0x7E f c x -- special case: the `"` character has a special case escaping mode which -- is encoded as `""` | '\"' == c = "\"\"" <> x -- special case: always escape the `\` character as an explicit code point, -- so we don't have to do lookahead to discover if it is followed by a `u` | '\\' == c = "\\u{5c}" <> x -- others characters in the "normal" ASCII range require no escaping | inLiteralRange c = Builder.singleton c <> x -- characters outside that range require escaping | otherwise = "\\u{" <> Builder.fromString (showHex (fromEnum c) "}") <> x -- | Parse SMTLIb2.6 escaping rules for strings. -- Note ! The escaping rule that uses the @\"\"@ sequence -- to encode a double quote has already been resolved -- by @parseSMTLIb2String@, so here we just need to parse the @\\u@ escape forms . unescapeText :: Text -> Maybe Text unescapeText = go mempty where go str t = case Text.uncons t of Nothing -> Just str Just (c, t') | not (isAscii c) -> Nothing | c == '\\' -> readEscape str t' | otherwise -> continue str c t' continue str c t = go (Text.snoc str c) t readEscape str t = case Text.uncons t of Nothing -> Just (Text.snoc str '\\') Just (c, t') Note : the \u forms are the _ only _ escape forms | c == 'u' -> readHexEscape str t' | otherwise -> continue (Text.snoc str '\\') c t' readHexEscape str t = case Text.uncons t of Just (c, t') -- take until the closing brace | c == '{' , (ds, t'') <- Text.breakOn "}" t' , Just ('}',t''') <- Text.uncons t'' -> readDigits str ds t''' take exactly four digits | (ds, t'') <- Text.splitAt 4 t' , Text.length ds == 4 -> readDigits str ds t'' _ -> Nothing readDigits str ds t = case readHex (Text.unpack ds) of (n, []):_ -> continue str (toEnum n) t _ -> Nothing | This class exists so that solvers supporting the SMTLib2 format can support -- features that go slightly beyond the standard. -- -- In particular, there is no standardized syntax for constant arrays (arrays -- which map every index to the same value). Solvers that support the theory of -- arrays and have custom syntax for constant arrays should implement -- `smtlib2arrayConstant`. In addition, solvers may override the default -- representation of complex numbers if necessary. The default is to represent -- complex numbers as "(Array Bool Real)" and to build instances by updating a -- constant array. class Show a => SMTLib2Tweaks a where smtlib2tweaks :: a smtlib2exitCommand :: Maybe SMT2.Command smtlib2exitCommand = Just SMT2.exit -- | Return a representation of the type associated with a (multi-dimensional) symbolic -- array. -- -- By default, we encode symbolic arrays using a nested representation. If the solver, -- supports tuples/structs it may wish to change this. smtlib2arrayType :: [SMT2.Sort] -> SMT2.Sort -> SMT2.Sort smtlib2arrayType l r = foldr (\i v -> SMT2.arraySort i v) r l smtlib2arrayConstant :: Maybe ([SMT2.Sort] -> SMT2.Sort -> Term -> Term) smtlib2arrayConstant = Nothing smtlib2arraySelect :: Term -> [Term] -> Term smtlib2arraySelect a [] = a smtlib2arraySelect a (h:l) = smtlib2arraySelect @a (What4.Protocol.SMTLib2.arraySelect a h) l smtlib2arrayUpdate :: Term -> [Term] -> Term -> Term smtlib2arrayUpdate a i v = case i of [] -> error "arrayUpdate given empty list" i1:ir -> nestedArrayUpdate a (i1, ir) v smtlib2StringSort :: SMT2.Sort smtlib2StringSort = SMT2.Sort "String" smtlib2StringTerm :: Text -> Term smtlib2StringTerm = textToTerm smtlib2StringLength :: Term -> Term smtlib2StringLength = SMT2.un_app "str.len" smtlib2StringAppend :: [Term] -> Term smtlib2StringAppend = SMT2.term_app "str.++" smtlib2StringContains :: Term -> Term -> Term smtlib2StringContains = SMT2.bin_app "str.contains" smtlib2StringIndexOf :: Term -> Term -> Term -> Term smtlib2StringIndexOf s t i = SMT2.term_app "str.indexof" [s,t,i] smtlib2StringIsPrefixOf :: Term -> Term -> Term smtlib2StringIsPrefixOf = SMT2.bin_app "str.prefixof" smtlib2StringIsSuffixOf :: Term -> Term -> Term smtlib2StringIsSuffixOf = SMT2.bin_app "str.suffixof" smtlib2StringSubstring :: Term -> Term -> Term -> Term smtlib2StringSubstring x off len = SMT2.term_app "str.substr" [x,off,len] -- | The sort of structs with the given field types. -- By default , this uses SMTLIB2 datatypes and are not primitive to the language . smtlib2StructSort :: [SMT2.Sort] -> SMT2.Sort smtlib2StructSort [] = SMT2.Sort "Struct0" smtlib2StructSort flds = SMT2.Sort $ "(Struct" <> Builder.decimal n <> foldMap f flds <> ")" where f :: SMT2.Sort -> Builder f (SMT2.Sort s) = " " <> s n = length flds -- | Construct a struct value from the given field values smtlib2StructCtor :: [Term] -> Term smtlib2StructCtor args = term_app nm args where nm = "mk-struct" <> Builder.decimal (length args) -- | Construct a struct field projection term smtlib2StructProj :: Int {- ^ number of fields in the struct -} -> Int {- ^ 0-based index of the struct field -} -> Term {- ^ struct term to project from -} -> Term smtlib2StructProj n i a = term_app nm [a] where nm = "struct" <> Builder.decimal n <> "-proj" <> Builder.decimal i By default , this uses the SMTLib 2.6 standard version of the declare - datatype command . smtlib2declareStructCmd :: Int -> Maybe SMT2.Command smtlib2declareStructCmd 0 = Just $ SMT2.Cmd $ app "declare-datatype" [ fromString "Struct0", builder_list [ builder_list ["mk-struct0"]]] smtlib2declareStructCmd n = Just $ let n_str = fromString (show n) tp = "Struct" <> n_str cnstr = "mk-struct" <> n_str idxes = map (fromString . show) [0 .. n-1] tp_names = [ "T" <> i_str | i_str <- idxes ] flds = [ app ("struct" <> n_str <> "-proj" <> i_str) [ "T" <> i_str ] | i_str <- idxes ] in SMT2.Cmd $ app "declare-datatype" [ tp, app "par" [ builder_list tp_names, builder_list [app cnstr flds]]] asSMT2Type :: forall a tp . SMTLib2Tweaks a => TypeMap tp -> SMT2.Sort asSMT2Type BoolTypeMap = SMT2.boolSort asSMT2Type IntegerTypeMap = SMT2.intSort asSMT2Type RealTypeMap = SMT2.realSort asSMT2Type (BVTypeMap w) = SMT2.bvSort (natValue w) asSMT2Type (FloatTypeMap fpp) = SMT2.Sort $ mkFloatSymbol "FloatingPoint" (asSMTFloatPrecision fpp) asSMT2Type UnicodeTypeMap = smtlib2StringSort @a asSMT2Type ComplexToStructTypeMap = smtlib2StructSort @a [ SMT2.realSort, SMT2.realSort ] asSMT2Type ComplexToArrayTypeMap = smtlib2arrayType @a [SMT2.boolSort] SMT2.realSort asSMT2Type (PrimArrayTypeMap i r) = smtlib2arrayType @a (toListFC (asSMT2Type @a) i) (asSMT2Type @a r) asSMT2Type (FnArrayTypeMap _ _) = error "SMTLIB backend does not support function types as first class." asSMT2Type (StructTypeMap f) = smtlib2StructSort @a (toListFC (asSMT2Type @a) f) -- Default instance. instance SMTLib2Tweaks () where smtlib2tweaks = () ------------------------------------------------------------------------ readBin :: Num a => ReadS a readBin = readInt 2 (`elem` ("01" :: String)) digitToInt ------------------------------------------------------------------------ -- Type mkRoundingOp :: Builder -> RoundingMode -> Builder mkRoundingOp op r = op <> " " <> fromString (show r) ------------------------------------------------------------------------ -- Writer newtype Writer a = Writer { declaredTuples :: IORef (Set Int) } type instance SMTWriter.Term (Writer a) = Term instance Num Term where x + y = SMT2.add [x, y] x - y = SMT2.sub x [y] x * y = SMT2.mul [x, y] negate x = SMT2.negate x abs x = SMT2.ite (SMT2.ge [x, SMT2.numeral 0]) x (SMT2.negate x) signum x = SMT2.ite (SMT2.ge [x, SMT2.numeral 0]) (SMT2.ite (SMT2.eq [x, SMT2.numeral 0]) (SMT2.numeral 0) (SMT2.numeral 1)) (SMT2.negate (SMT2.numeral 1)) fromInteger = SMT2.numeral varBinding :: forall a . SMTLib2Tweaks a => (Text, Some TypeMap) -> (Text, SMT2.Sort) varBinding (nm, Some tp) = (nm, asSMT2Type @a tp) The SMTLIB2 exporter uses the datatypes theory for representing structures . -- -- Note about structs: -- -- For each length XX associated to some structure with that length in the formula , the SMTLIB2 backend defines a datatype " StructXX " with the -- constructor "mk-structXX", and projection operations "structXX-projII" for II an natural number less than XX . instance SupportTermOps Term where boolExpr b = if b then SMT2.true else SMT2.false notExpr = SMT2.not andAll = SMT2.and orAll = SMT2.or x .== y = SMT2.eq [x,y] x ./= y = SMT2.distinct [x,y] -- NB: SMT2.letBinder defines a "parallel" let, and -- we want the semantics of a "sequential" let, so expand -- to a series of nested lets. letExpr vs t = foldr (\v -> SMT2.letBinder [v]) t vs ite = SMT2.ite sumExpr = SMT2.add termIntegerToReal = SMT2.toReal termRealToInteger = SMT2.toInt integerTerm = SMT2.numeral intDiv x y = SMT2.div x [y] intMod = SMT2.mod intAbs = SMT2.abs intDivisible x 0 = x .== integerTerm 0 intDivisible x k = intMod x (integerTerm (toInteger k)) .== 0 rationalTerm r | d == 1 = SMT2.decimal n | otherwise = (SMT2.decimal n) SMT2../ [SMT2.decimal d] where n = numerator r d = denominator r x .< y = SMT2.lt [x,y] x .<= y = SMT2.le [x,y] x .> y = SMT2.gt [x,y] x .>= y = SMT2.ge [x,y] bvTerm w u = case isZeroOrGT1 w of Left Refl -> error "Cannot construct BV term with 0 width" Right LeqProof -> SMT2.bvdecimal w u bvNeg = SMT2.bvneg bvAdd x y = SMT2.bvadd x [y] bvSub = SMT2.bvsub bvMul x y = SMT2.bvmul x [y] bvSLe = SMT2.bvsle bvULe = SMT2.bvule bvSLt = SMT2.bvslt bvULt = SMT2.bvult bvUDiv = SMT2.bvudiv bvURem = SMT2.bvurem bvSDiv = SMT2.bvsdiv bvSRem = SMT2.bvsrem bvNot = SMT2.bvnot bvAnd x y = SMT2.bvand x [y] bvOr x y = SMT2.bvor x [y] bvXor x y = SMT2.bvxor x [y] bvShl = SMT2.bvshl bvLshr = SMT2.bvlshr bvAshr = SMT2.bvashr bvConcat = SMT2.concat bvExtract _ b n x | n > 0 = SMT2.extract (b+n-1) b x | otherwise = error $ "bvExtract given non-positive width " ++ show n floatNeg = un_app "fp.neg" floatAbs = un_app "fp.abs" floatSqrt r = un_app $ mkRoundingOp "fp.sqrt " r floatAdd r = bin_app $ mkRoundingOp "fp.add" r floatSub r = bin_app $ mkRoundingOp "fp.sub" r floatMul r = bin_app $ mkRoundingOp "fp.mul" r floatDiv r = bin_app $ mkRoundingOp "fp.div" r floatRem = bin_app "fp.rem" floatFMA r x y z = term_app (mkRoundingOp "fp.fma" r) [x, y, z] floatEq x y = SMT2.eq [x,y] floatFpEq = bin_app "fp.eq" floatLe = bin_app "fp.leq" floatLt = bin_app "fp.lt" floatIsNaN = un_app "fp.isNaN" floatIsInf = un_app "fp.isInfinite" floatIsZero = un_app "fp.isZero" floatIsPos = un_app "fp.isPositive" floatIsNeg = un_app "fp.isNegative" floatIsSubnorm = un_app "fp.isSubnormal" floatIsNorm = un_app "fp.isNormal" floatTerm fpp@(FloatingPointPrecisionRepr eb sb) bf = un_app (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) (bvTerm w bv) where w = addNat eb sb bv = BV.mkBV w (bfToBits (fppOpts fpp RNE) bf) floatCast fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) r floatRound r = un_app $ mkRoundingOp "fp.roundToIntegral" r floatFromBinary fpp = un_app $ mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp) bvToFloat fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp_unsigned" (asSMTFloatPrecision fpp)) r sbvToFloat fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) r realToFloat fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) r floatToBV w r = un_app $ mkRoundingOp ("(_ fp.to_ubv " <> fromString (show w) <> ")") r floatToSBV w r = un_app $ mkRoundingOp ("(_ fp.to_sbv " <> fromString (show w) <> ")") r floatToReal = un_app "fp.to_real" realIsInteger = SMT2.isInt realDiv x y = x SMT2../ [y] realSin = un_app "sin" realCos = un_app "cos" realTan = un_app "tan" realATan2 = bin_app "atan2" realSinh = un_app "sinh" realCosh = un_app "cosh" realTanh = un_app "tanh" realExp = un_app "exp" realLog = un_app "log" smtFnApp nm args = term_app (SMT2.renderTerm nm) args fromText t = SMT2.T (Builder.fromText t) ------------------------------------------------------------------------ -- Writer newWriter :: a -> Streams.OutputStream Text -- ^ Stream to write queries onto -> Streams.InputStream Text -- ^ Input stream to read responses from -- (may be the @nullInput@ stream if no responses are expected) -> AcknowledgementAction t (Writer a) -- ^ Action to run for consuming acknowledgement messages -> ResponseStrictness ^ Be strict in parsing SMT solver responses ? -> String -- ^ Name of solver for reporting purposes. -> Bool -- ^ Flag indicating if it is permitted to use " define - fun " when generating SMTLIB -> ProblemFeatures -- ^ Indicates what features are supported by the solver -> Bool -- ^ Indicates if quantifiers are supported. -> B.SymbolVarBimap t -- ^ Variable bindings for names. -> IO (WriterConn t (Writer a)) newWriter _ h in_h ack isStrict solver_name permitDefineFun arithOption quantSupport bindings = do r <- newIORef Set.empty let initWriter = Writer { declaredTuples = r } conn <- newWriterConn h in_h ack solver_name isStrict arithOption bindings initWriter return $! conn { supportFunctionDefs = permitDefineFun , supportQuantifiers = quantSupport } type instance Command (Writer a) = SMT2.Command instance SMTLib2Tweaks a => SMTWriter (Writer a) where forallExpr vars t = SMT2.forall_ (varBinding @a <$> vars) t existsExpr vars t = SMT2.exists_ (varBinding @a <$> vars) t arrayConstant = case smtlib2arrayConstant @a of Just f -> Just $ \idxTypes (Some retType) c -> f ((\(Some itp) -> asSMT2Type @a itp) <$> idxTypes) (asSMT2Type @a retType) c Nothing -> Nothing arraySelect = smtlib2arraySelect @a arrayUpdate = smtlib2arrayUpdate @a commentCommand _ b = SMT2.Cmd ("; " <> b) assertCommand _ e = SMT2.assert e assertNamedCommand _ e nm = SMT2.assertNamed e nm pushCommand _ = SMT2.push 1 popCommand _ = SMT2.pop 1 push2Command _ = SMT2.push 2 pop2Command _ = SMT2.pop 2 resetCommand _ = SMT2.resetAssertions popManyCommands _ n = [SMT2.pop (toInteger n)] checkCommands _ = [SMT2.checkSat] checkWithAssumptionsCommands _ nms = [SMT2.checkSatWithAssumptions nms] getUnsatAssumptionsCommand _ = SMT2.getUnsatAssumptions getUnsatCoreCommand _ = SMT2.getUnsatCore getAbductCommand _ nm e = SMT2.getAbduct nm e getAbductNextCommand _ = SMT2.getAbductNext setOptCommand _ = SMT2.setOption declareCommand _proxy v argTypes retType = SMT2.declareFun v (toListFC (asSMT2Type @a) argTypes) (asSMT2Type @a retType) defineCommand _proxy f args return_type e = let resolveArg (var, Some tp) = (var, asSMT2Type @a tp) in SMT2.defineFun f (resolveArg <$> args) (asSMT2Type @a return_type) e synthFunCommand _proxy f args ret_tp = SMT2.synthFun f (map (\(var, Some tp) -> (var, asSMT2Type @a tp)) args) (asSMT2Type @a ret_tp) declareVarCommand _proxy v tp = SMT2.declareVar v (asSMT2Type @a tp) constraintCommand _proxy e = SMT2.constraint e stringTerm str = smtlib2StringTerm @a str stringLength x = smtlib2StringLength @a x stringAppend xs = smtlib2StringAppend @a xs stringContains x y = smtlib2StringContains @a x y stringIsPrefixOf x y = smtlib2StringIsPrefixOf @a x y stringIsSuffixOf x y = smtlib2StringIsSuffixOf @a x y stringIndexOf x y k = smtlib2StringIndexOf @a x y k stringSubstring x off len = smtlib2StringSubstring @a x off len structCtor _tps vals = smtlib2StructCtor @a vals structProj tps idx v = let n = Ctx.sizeInt (Ctx.size tps) i = Ctx.indexVal idx in smtlib2StructProj @a n i v resetDeclaredStructs conn = do let r = declaredTuples (connState conn) writeIORef r mempty declareStructDatatype conn flds = do let n = Ctx.sizeInt (Ctx.size flds) let r = declaredTuples (connState conn) s <- readIORef r when (Set.notMember n s) $ do case smtlib2declareStructCmd @a n of Nothing -> return () Just cmd -> addCommand conn cmd writeIORef r $! Set.insert n s writeCommand conn (SMT2.Cmd cmd) = do let cmdout = Lazy.toStrict (Builder.toLazyText cmd) Streams.write (Just (cmdout <> "\n")) (connHandle conn) -- force a flush Streams.write (Just "") (connHandle conn) -- | Write check sat command writeCheckSat :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeCheckSat w = addCommandNoAck w SMT2.checkSat writeExit :: forall a t. SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeExit w = mapM_ (addCommand w) (smtlib2exitCommand @a) setLogic :: SMTLib2Tweaks a => WriterConn t (Writer a) -> SMT2.Logic -> IO () setLogic w l = addCommand w $ SMT2.setLogic l setOption :: SMTLib2Tweaks a => WriterConn t (Writer a) -> Text -> Text -> IO () setOption w nm val = addCommand w $ SMT2.setOption nm val getVersion :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () getVersion w = writeCommand w $ SMT2.getVersion getName :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () getName w = writeCommand w $ SMT2.getName -- | Set the produce models option (We typically want this) setProduceModels :: SMTLib2Tweaks a => WriterConn t (Writer a) -> Bool -> IO () setProduceModels w b = addCommand w $ SMT2.setProduceModels b writeGetValue :: SMTLib2Tweaks a => WriterConn t (Writer a) -> [Term] -> IO () writeGetValue w l = addCommandNoAck w $ SMT2.getValue l writeGetAbduct :: SMTLib2Tweaks a => WriterConn t (Writer a) -> Text -> Term -> IO () writeGetAbduct w nm p = addCommandNoAck w $ SMT2.getAbduct nm p writeGetAbductNext :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeGetAbductNext w = addCommandNoAck w SMT2.getAbductNext -- | Write check-synth command writeCheckSynth :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeCheckSynth w = addCommandNoAck w SMT2.checkSynth parseBoolSolverValue :: MonadFail m => SExp -> m Bool parseBoolSolverValue (SAtom "true") = return True parseBoolSolverValue (SAtom "false") = return False parseBoolSolverValue s = do v <- parseBvSolverValue (knownNat @1) s return (if v == BV.zero knownNat then False else True) parseIntSolverValue :: MonadFail m => SExp -> m Integer parseIntSolverValue = \case SAtom v | [(i, "")] <- readDec (Text.unpack v) -> return i SApp ["-", x] -> negate <$> parseIntSolverValue x s -> fail $ "Could not parse solver value: " ++ show s parseRealSolverValue :: MonadFail m => SExp -> m Rational parseRealSolverValue (SAtom v) | Just (r,"") <- readDecimal (Text.unpack v) = return r parseRealSolverValue (SApp ["-", x]) = do negate <$> parseRealSolverValue x parseRealSolverValue (SApp ["/", x , y]) = do (/) <$> parseRealSolverValue x <*> parseRealSolverValue y parseRealSolverValue s = fail $ "Could not parse solver value: " ++ show s -- | Parse a bitvector value returned by a solver. Most solvers give results of the right size , but ABC always gives hex results without leading zeros , so they may be larger or smaller than the actual size -- of the variable. parseBvSolverValue :: MonadFail m => NatRepr w -> SExp -> m (BV.BV w) parseBvSolverValue w s | Just (Pair w' bv) <- parseBVLitHelper s = case w' `compareNat` w of NatLT zw -> return (BV.zext (addNat w' (addNat zw knownNat)) bv) NatEQ -> return bv NatGT _ -> return (BV.trunc w bv) | otherwise = fail $ "Could not parse bitvector solver value: " ++ show s natBV :: Natural -- ^ width -> Integer -- ^ BV value -> Pair NatRepr BV.BV natBV wNatural x = case mkNatRepr wNatural of Some w -> Pair w (BV.mkBV w x) -- | Parse an s-expression and return a bitvector and its width parseBVLitHelper :: SExp -> Maybe (Pair NatRepr BV.BV) parseBVLitHelper (SAtom (Text.unpack -> ('#' : 'b' : n_str))) | [(n, "")] <- readBin n_str = Just $ natBV (fromIntegral (length n_str)) n parseBVLitHelper (SAtom (Text.unpack -> ('#' : 'x' : n_str))) | [(n, "")] <- readHex n_str = Just $ natBV (fromIntegral (length n_str * 4)) n parseBVLitHelper (SApp ["_", SAtom (Text.unpack -> ('b' : 'v' : n_str)), SAtom (Text.unpack -> w_str)]) | [(n, "")] <- readDec n_str, [(w, "")] <- readDec w_str = Just $ natBV w n parseBVLitHelper _ = Nothing parseStringSolverValue :: MonadFail m => SExp -> m Text parseStringSolverValue (SString t) | Just t' <- unescapeText t = return t' parseStringSolverValue x = fail ("Could not parse string solver value:\n " ++ show x) parseFloatSolverValue :: MonadFail m => FloatPrecisionRepr fpp -> SExp -> m (BV.BV (FloatPrecisionBits fpp)) parseFloatSolverValue (FloatingPointPrecisionRepr eb sb) s = do ParsedFloatResult sgn eb' expt sb' sig <- parseFloatLitHelper s case (eb `testEquality` eb', sb `testEquality` ((knownNat @1) `addNat` sb')) of (Just Refl, Just Refl) -> do -- eb' + 1 ~ 1 + eb' Refl <- return $ plusComm eb' (knownNat @1) ( eb ' + 1 ) + sb ' ~ eb ' + ( 1 + sb ' ) Refl <- return $ plusAssoc eb' (knownNat @1) sb' return bv where bv = BV.concat (addNat (knownNat @1) eb) sb' (BV.concat knownNat eb sgn expt) sig _ -> fail $ "Unexpected float precision: " <> show eb' <> ", " <> show sb' data ParsedFloatResult = forall eb sb . ParsedFloatResult (BV.BV 1) -- sign (NatRepr eb) -- exponent width (BV.BV eb) -- exponent (NatRepr sb) -- significand bit width (BV.BV sb) -- significand bit parseFloatLitHelper :: MonadFail m => SExp -> m ParsedFloatResult parseFloatLitHelper (SApp ["fp", sign_s, expt_s, scand_s]) | Just (Pair sign_w sign) <- parseBVLitHelper sign_s , Just Refl <- sign_w `testEquality` (knownNat @1) , Just (Pair eb expt) <- parseBVLitHelper expt_s , Just (Pair sb scand) <- parseBVLitHelper scand_s = return $ ParsedFloatResult sign eb expt sb scand parseFloatLitHelper s@(SApp ["_", SAtom (Text.unpack -> nm), SAtom (Text.unpack -> eb_s), SAtom (Text.unpack -> sb_s)]) | [(eb_n, "")] <- readDec eb_s, [(sb_n, "")] <- readDec sb_s , Some eb <- mkNatRepr eb_n , Some sb <- mkNatRepr (sb_n-1) = case nm of "+oo" -> return $ ParsedFloatResult (BV.zero knownNat) eb (BV.maxUnsigned eb) sb (BV.zero sb) "-oo" -> return $ ParsedFloatResult (BV.one knownNat) eb (BV.maxUnsigned eb) sb (BV.zero sb) "+zero" -> return $ ParsedFloatResult (BV.zero knownNat) eb (BV.zero eb) sb (BV.zero sb) "-zero" -> return $ ParsedFloatResult (BV.one knownNat) eb (BV.zero eb) sb (BV.zero sb) "NaN" -> return $ ParsedFloatResult (BV.zero knownNat) eb (BV.maxUnsigned eb) sb (BV.maxUnsigned sb) _ -> fail $ "Could not parse float solver value: " ++ show s parseFloatLitHelper s = fail $ "Could not parse float solver value: " ++ show s parseBvArraySolverValue :: (MonadFail m, 1 <= w, 1 <= v) => NatRepr w -> NatRepr v -> SExp -> m (Maybe (GroundArray (Ctx.SingleCtx (BaseBVType w)) (BaseBVType v))) parseBvArraySolverValue _ v (SApp [SApp ["as", "const", _], c]) = do c' <- parseBvSolverValue v c return . Just $ ArrayConcrete c' Map.empty parseBvArraySolverValue w v (SApp ["store", arr, idx, val]) = do arr' <- parseBvArraySolverValue w v arr case arr' of Just (ArrayConcrete base m) -> do idx' <- B.BVIndexLit w <$> parseBvSolverValue w idx val' <- parseBvSolverValue v val return . Just $ ArrayConcrete base (Map.insert (Ctx.empty Ctx.:> idx') val' m) _ -> return Nothing parseBvArraySolverValue _ _ _ = return Nothing parseFnModel :: sym ~ B.ExprBuilder t st fs => sym -> WriterConn t h -> [I.SomeSymFn sym] -> SExp -> IO (MapF (I.SymFnWrapper sym) (I.SymFnWrapper sym)) parseFnModel = parseFns parseDefineFun parseFnValues :: sym ~ B.ExprBuilder t st fs => sym -> WriterConn t h -> [I.SomeSymFn sym] -> SExp -> IO (MapF (I.SymFnWrapper sym) (I.SymFnWrapper sym)) parseFnValues = parseFns parseLambda parseFns :: sym ~ B.ExprBuilder t st fs => (sym -> SExp -> IO (Text, I.SomeSymFn sym)) -> sym -> WriterConn t h -> [I.SomeSymFn sym] -> SExp -> IO (MapF (I.SymFnWrapper sym) (I.SymFnWrapper sym)) parseFns parse_model_fn sym conn uninterp_fns sexp = do fn_name_bimap <- cacheLookupFnNameBimap conn $ map (\(I.SomeSymFn fn) -> B.SomeExprSymFn fn) uninterp_fns defined_fns <- case sexp of SApp sexps -> Map.fromList <$> mapM (parse_model_fn sym) sexps _ -> fail $ "Could not parse model response: " ++ show sexp MapF.fromList <$> mapM (\(I.SomeSymFn uninterp_fn) -> if | Just nm <- Bimap.lookup (B.SomeExprSymFn uninterp_fn) fn_name_bimap , Just (I.SomeSymFn defined_fn) <- Map.lookup nm defined_fns , Just Refl <- testEquality (I.fnArgTypes uninterp_fn) (I.fnArgTypes defined_fn) , Just Refl <- testEquality (I.fnReturnType uninterp_fn) (I.fnReturnType defined_fn) -> return $ MapF.Pair (I.SymFnWrapper uninterp_fn) (I.SymFnWrapper defined_fn) | otherwise -> fail $ "Could not find model for function: " ++ show uninterp_fn) uninterp_fns parseDefineFun :: I.IsSymExprBuilder sym => sym -> SExp -> IO (Text, I.SomeSymFn sym) parseDefineFun sym sexp = case sexp of SApp ["define-fun", SAtom nm, SApp params_sexp, _ret_type_sexp , body_sexp] -> do fn <- parseFn sym nm params_sexp body_sexp return (nm, fn) _ -> fail $ "unexpected sexp, expected define-fun, found " ++ show sexp parseLambda :: I.IsSymExprBuilder sym => sym -> SExp -> IO (Text, I.SomeSymFn sym) parseLambda sym sexp = case sexp of SApp [SAtom nm, SApp ["lambda", SApp params_sexp, body_sexp]] -> do fn <- parseFn sym nm params_sexp body_sexp return (nm, fn) _ -> fail $ "unexpected sexp, expected lambda, found " ++ show sexp parseFn :: I.IsSymExprBuilder sym => sym -> Text -> [SExp] -> SExp -> IO (I.SomeSymFn sym) parseFn sym nm params_sexp body_sexp = do (nms, vars) <- unzip <$> mapM (parseVar sym) params_sexp case Ctx.fromList vars of Some vars_assign -> do let let_env = HashMap.fromList $ zip nms $ map (mapSome $ I.varExpr sym) vars proc_res <- runProcessor (ProcessorEnv { procSym = sym, procLetEnv = let_env }) $ parseExpr sym body_sexp Some body_expr <- either fail return proc_res I.SomeSymFn <$> I.definedFn sym (I.safeSymbol $ Text.unpack nm) vars_assign body_expr I.NeverUnfold parseVar :: I.IsSymExprBuilder sym => sym -> SExp -> IO (Text, Some (I.BoundVar sym)) parseVar sym sexp = case sexp of SApp [SAtom nm, tp_sexp] -> do Some tp <- parseType tp_sexp var <- liftIO $ I.freshBoundVar sym (I.safeSymbol $ Text.unpack nm) tp return (nm, Some var) _ -> fail $ "unexpected variable " ++ show sexp parseType :: SExp -> IO (Some BaseTypeRepr) parseType sexp = case sexp of "Bool" -> return $ Some BaseBoolRepr "Int" -> return $ Some BaseIntegerRepr "Real" -> return $ Some BaseRealRepr SApp ["_", "BitVec", SAtom (Text.unpack -> m_str)] | [(m_n, "")] <- readDec m_str , Some m <- mkNatRepr m_n , Just LeqProof <- testLeq (knownNat @1) m -> return $ Some $ BaseBVRepr m SApp ["_", "FloatingPoint", SAtom (Text.unpack -> eb_str), SAtom (Text.unpack -> sb_str)] | [(eb_n, "")] <- readDec eb_str , Some eb <- mkNatRepr eb_n , Just LeqProof <- testLeq (knownNat @2) eb , [(sb_n, "")] <- readDec sb_str , Some sb <- mkNatRepr sb_n , Just LeqProof <- testLeq (knownNat @2) sb -> return $ Some $ BaseFloatRepr $ FloatingPointPrecisionRepr eb sb SApp ["Array", idx_tp_sexp, val_tp_sexp] -> do Some idx_tp <- parseType idx_tp_sexp Some val_tp <- parseType val_tp_sexp return $ Some $ BaseArrayRepr (Ctx.singleton idx_tp) val_tp _ -> fail $ "unexpected type " ++ show sexp | Stores a NatRepr along with proof that its type parameter is a bitvector of that length . Used for easy pattern matching on the LHS of a binding in a -- do-expression to extract the proof. data BVProof tp where BVProof :: forall n . (1 <= n) => NatRepr n -> BVProof (BaseBVType n) -- | Given an expression, monadically either returns proof that it is a -- bitvector or throws an error. getBVProof :: (I.IsExpr ex, MonadError String m) => ex tp -> m (BVProof tp) getBVProof expr = case I.exprType expr of BaseBVRepr n -> return $ BVProof n t -> throwError $ "expected BV, found " ++ show t -- | Operator type descriptions for parsing s-expression of -- the form @(operator operands ...)@. -- Code is copy - pasted and adapted from ` What4.Serialize . ` , see -- <> data Op sym where -- | Generic unary operator description. Op1 :: Ctx.Assignment BaseTypeRepr (Ctx.EmptyCtx Ctx.::> arg1) -> (sym -> I.SymExpr sym arg1 -> IO (I.SymExpr sym ret)) -> Op sym -- | Generic binary operator description. Op2 :: Ctx.Assignment BaseTypeRepr (Ctx.EmptyCtx Ctx.::> arg1 Ctx.::> arg2) -> Maybe Assoc -> (sym -> I.SymExpr sym arg1 -> I.SymExpr sym arg2 -> IO (I.SymExpr sym ret)) -> Op sym | Encapsulating type for a unary operation that takes one bitvector and returns another ( in IO ) . BVOp1 :: (forall w . (1 <= w) => sym -> I.SymBV sym w -> IO (I.SymBV sym w)) -> Op sym | with a bitvector return type , e.g. , addition or bitwise operations . BVOp2 :: Maybe Assoc -> (forall w . (1 <= w) => sym -> I.SymBV sym w -> I.SymBV sym w -> IO (I.SymBV sym w)) -> Op sym -- | Bitvector binop with a boolean return type, i.e., comparison operators. BVComp2 :: (forall w . (1 <= w) => sym -> I.SymBV sym w -> I.SymBV sym w -> IO (I.Pred sym)) -> Op sym data Assoc = RightAssoc | LeftAssoc newtype Processor sym a = Processor (ExceptT String (ReaderT (ProcessorEnv sym) IO) a) deriving (Functor, Applicative, Monad, MonadIO, MonadError String, MonadReader (ProcessorEnv sym)) data ProcessorEnv sym = ProcessorEnv { procSym :: sym , procLetEnv :: HashMap Text (Some (I.SymExpr sym)) } runProcessor :: ProcessorEnv sym -> Processor sym a -> IO (Either String a) runProcessor env (Processor action) = runReaderT (runExceptT action) env opTable :: I.IsSymExprBuilder sym => HashMap Text (Op sym) opTable = HashMap.fromList Boolean ops [ ("not", Op1 knownRepr I.notPred) , ("=>", Op2 knownRepr (Just RightAssoc) I.impliesPred) , ("and", Op2 knownRepr (Just LeftAssoc) I.andPred) , ("or", Op2 knownRepr (Just LeftAssoc) I.orPred) , ("xor", Op2 knownRepr (Just LeftAssoc) I.xorPred) Integer ops , ("-", Op2 knownRepr (Just LeftAssoc) I.intSub) , ("+", Op2 knownRepr (Just LeftAssoc) I.intAdd) , ("*", Op2 knownRepr (Just LeftAssoc) I.intMul) , ("div", Op2 knownRepr (Just LeftAssoc) I.intDiv) , ("mod", Op2 knownRepr Nothing I.intMod) , ("abs", Op1 knownRepr I.intAbs) , ("<=", Op2 knownRepr Nothing I.intLe) , ("<", Op2 knownRepr Nothing I.intLt) , (">=", Op2 knownRepr Nothing $ \sym arg1 arg2 -> I.intLe sym arg2 arg1) , (">", Op2 knownRepr Nothing $ \sym arg1 arg2 -> I.intLt sym arg2 arg1) Bitvector ops , ("bvnot", BVOp1 I.bvNotBits) , ("bvneg", BVOp1 I.bvNeg) , ("bvand", BVOp2 (Just LeftAssoc) I.bvAndBits) , ("bvor", BVOp2 (Just LeftAssoc) I.bvOrBits) , ("bvxor", BVOp2 (Just LeftAssoc) I.bvXorBits) , ("bvadd", BVOp2 (Just LeftAssoc) I.bvAdd) , ("bvsub", BVOp2 (Just LeftAssoc) I.bvSub) , ("bvmul", BVOp2 (Just LeftAssoc) I.bvMul) , ("bvudiv", BVOp2 Nothing I.bvUdiv) , ("bvurem", BVOp2 Nothing I.bvUrem) , ("bvshl", BVOp2 Nothing I.bvShl) , ("bvlshr", BVOp2 Nothing I.bvLshr) , ("bvsdiv", BVOp2 Nothing I.bvSdiv) , ("bvsrem", BVOp2 Nothing I.bvSrem) , ("bvashr", BVOp2 Nothing I.bvAshr) , ("bvult", BVComp2 I.bvUlt) , ("bvule", BVComp2 I.bvUle) , ("bvugt", BVComp2 I.bvUgt) , ("bvuge", BVComp2 I.bvUge) , ("bvslt", BVComp2 I.bvSlt) , ("bvsle", BVComp2 I.bvSle) , ("bvsgt", BVComp2 I.bvSgt) , ("bvsge", BVComp2 I.bvSge) ] parseExpr :: forall sym . I.IsSymExprBuilder sym => sym -> SExp -> Processor sym (Some (I.SymExpr sym)) parseExpr sym sexp = case sexp of "true" -> return $ Some $ I.truePred sym "false" -> return $ Some $ I.falsePred sym _ | Just i <- parseIntSolverValue sexp -> liftIO $ Some <$> I.intLit sym i | Just (Pair w bv) <- parseBVLitHelper sexp , Just LeqProof <- testLeq (knownNat @1) w -> liftIO $ Some <$> I.bvLit sym w bv SAtom nm -> do env <- asks procLetEnv case HashMap.lookup nm env of Just expr -> return $ expr Nothing -> throwError "" SApp ["let", SApp bindings_sexp, body_sexp] -> do let_env <- HashMap.fromList <$> mapM (\case SApp [SAtom nm, expr_sexp] -> do Some expr <- parseExpr sym expr_sexp return (nm, Some expr) _ -> throwError "") bindings_sexp local (\prov_env -> prov_env { procLetEnv = HashMap.union let_env (procLetEnv prov_env) }) $ parseExpr sym body_sexp SApp ["=", arg1, arg2] -> do Some arg1_expr <- parseExpr sym arg1 Some arg2_expr <- parseExpr sym arg2 case testEquality (I.exprType arg1_expr) (I.exprType arg2_expr) of Just Refl -> liftIO (Some <$> I.isEq sym arg1_expr arg2_expr) Nothing -> throwError "" SApp ["ite", arg1, arg2, arg3] -> do Some arg1_expr <- parseExpr sym arg1 Some arg2_expr <- parseExpr sym arg2 Some arg3_expr <- parseExpr sym arg3 case I.exprType arg1_expr of I.BaseBoolRepr -> case testEquality (I.exprType arg2_expr) (I.exprType arg3_expr) of Just Refl -> liftIO (Some <$> I.baseTypeIte sym arg1_expr arg2_expr arg3_expr) Nothing -> throwError "" _ -> throwError "" SApp ["concat", arg1, arg2] -> do Some arg1_expr <- parseExpr sym arg1 Some arg2_expr <- parseExpr sym arg2 BVProof{} <- getBVProof arg1_expr BVProof{} <- getBVProof arg2_expr liftIO $ Some <$> I.bvConcat sym arg1_expr arg2_expr SApp ((SAtom operator) : operands) -> case HashMap.lookup operator (opTable @sym) of Just (Op1 arg_types fn) -> do args <- mapM (parseExpr sym) operands exprAssignment arg_types args >>= \case Ctx.Empty Ctx.:> arg1 -> liftIO (Some <$> fn sym arg1) Just (Op2 arg_types _ fn) -> do args <- mapM (parseExpr sym) operands exprAssignment arg_types args >>= \case Ctx.Empty Ctx.:> arg1 Ctx.:> arg2 -> liftIO (Some <$> fn sym arg1 arg2) Just (BVOp1 op) -> do Some arg_expr <- readOneArg sym operands BVProof{} <- getBVProof arg_expr liftIO $ Some <$> op sym arg_expr Just (BVOp2 _ op) -> do (Some arg1, Some arg2) <- readTwoArgs sym operands BVProof m <- prefixError "in arg 1: " $ getBVProof arg1 BVProof n <- prefixError "in arg 2: " $ getBVProof arg2 case testEquality m n of Just Refl -> liftIO (Some <$> op sym arg1 arg2) Nothing -> throwError $ printf "arguments to %s must be the same length, \ \but arg 1 has length %s \ \and arg 2 has length %s" operator (show m) (show n) Just (BVComp2 op) -> do (Some arg1, Some arg2) <- readTwoArgs sym operands BVProof m <- prefixError "in arg 1: " $ getBVProof arg1 BVProof n <- prefixError "in arg 2: " $ getBVProof arg2 case testEquality m n of Just Refl -> liftIO (Some <$> op sym arg1 arg2) Nothing -> throwError $ printf "arguments to %s must be the same length, \ \but arg 1 has length %s \ \and arg 2 has length %s" operator (show m) (show n) _ -> throwError "" _ -> throwError "" -- | Verify a list of arguments has a single argument and -- return it, else raise an error. readOneArg :: I.IsSymExprBuilder sym => sym -> [SExp] -> Processor sym (Some (I.SymExpr sym)) readOneArg sym operands = do args <- mapM (parseExpr sym) operands case args of [arg] -> return arg _ -> throwError $ printf "expecting 1 argument, got %d" (length args) | Verify a list of arguments has two arguments and return -- it, else raise an error. readTwoArgs :: I.IsSymExprBuilder sym => sym ->[SExp] -> Processor sym (Some (I.SymExpr sym), Some (I.SymExpr sym)) readTwoArgs sym operands = do args <- mapM (parseExpr sym) operands case args of [arg1, arg2] -> return (arg1, arg2) _ -> throwError $ printf "expecting 2 arguments, got %d" (length args) exprAssignment :: forall sym ctx ex . (I.IsSymExprBuilder sym, I.IsExpr ex) => Ctx.Assignment BaseTypeRepr ctx -> [Some ex] -> Processor sym (Ctx.Assignment ex ctx) exprAssignment tpAssns exs = do Some exsAsn <- return $ Ctx.fromList exs exsRepr <- return $ fmapFC I.exprType exsAsn case testEquality exsRepr tpAssns of Just Refl -> return exsAsn Nothing -> throwError $ "Unexpected expression types for " -- ++ show exsAsn ++ "\nExpected: " ++ show tpAssns ++ "\nGot: " ++ show exsRepr -- | Utility function for contextualizing errors. Prepends the given prefix -- whenever an error is thrown. prefixError :: (Monoid e, MonadError e m) => e -> m a -> m a prefixError prefix act = catchError act (throwError . mappend prefix) ------------------------------------------------------------------------ -- Session | This is an interactive session with an SMT solver data Session t a = Session { sessionWriter :: !(WriterConn t (Writer a)) , sessionResponse :: !(Streams.InputStream Text) } -- | Get a value from a solver (must be called after checkSat) runGetValue :: SMTLib2Tweaks a => Session t a -> Term -> IO SExp runGetValue s e = do writeGetValue (sessionWriter s) [ e ] let valRsp = \case AckSuccessSExp (SApp [SApp [_, b]]) -> Just b _ -> Nothing getLimitedSolverResponse "get value" valRsp (sessionWriter s) (SMT2.getValue [e]) | runGetAbducts s nm p n , returns n formulas ( as strings ) the disjunction of which entails p ( along with all -- the assertions in the context) runGetAbducts :: SMTLib2Tweaks a => Session t a -> Int -> Text -> Term -> IO [String] runGetAbducts s n nm p = if (n > 0) then do writeGetAbduct (sessionWriter s) nm p let valRsp = \x -> case x of SMT solver returns ` ( define - fun nm ( ) ) ` where X is the abduct , we discard everything but the abduct AckSuccessSExp (SApp (_ : _ : _ : _ : abduct)) -> Just $ Data.String.unwords (map sExpToString abduct) _ -> Nothing get first abduct using the get - abduct command abd1 <- getLimitedSolverResponse "get abduct" valRsp (sessionWriter s) (SMT2.getAbduct nm p) if (n > 1) then do let rest = n - 1 replicateM_ rest $ writeGetAbductNext (sessionWriter s) -- get the rest of the abducts using the get-abduct-next command abdRest <- forM [1..rest] $ \_ -> getLimitedSolverResponse "get abduct next" valRsp (sessionWriter s) (SMT2.getAbduct nm p) return (abd1:abdRest) else return [abd1] else return [] -- | This function runs a check sat command runCheckSat :: forall b t a. SMTLib2Tweaks b => Session t b -> (SatResult (GroundEvalFn t, Maybe (ExprRangeBindings t)) () -> IO a) -- ^ Function for evaluating model. -- The evaluation should be complete before -> IO a runCheckSat s doEval = do let w = sessionWriter s r = sessionResponse s addCommands w (checkCommands w) res <- smtSatResult w w case res of Unsat x -> doEval (Unsat x) Unknown -> doEval Unknown Sat _ -> do evalFn <- smtExprGroundEvalFn w (smtEvalFuns w r) doEval (Sat (evalFn, Nothing)) instance SMTLib2Tweaks a => SMTReadWriter (Writer a) where smtEvalFuns w s = smtLibEvalFuns Session { sessionWriter = w , sessionResponse = s } smtSatResult p s = let satRsp = \case AckSat -> Just $ Sat () AckUnsat -> Just $ Unsat () AckUnknown -> Just Unknown _ -> Nothing in getLimitedSolverResponse "sat result" satRsp s (head $ reverse $ checkCommands p) smtUnsatAssumptionsResult p s = let unsatAssumpRsp = \case AckSuccessSExp (asNegAtomList -> Just as) -> Just as _ -> Nothing cmd = getUnsatAssumptionsCommand p in getLimitedSolverResponse "unsat assumptions" unsatAssumpRsp s cmd smtUnsatCoreResult p s = let unsatCoreRsp = \case AckSuccessSExp (asAtomList -> Just nms) -> Just nms _ -> Nothing cmd = getUnsatCoreCommand p in getLimitedSolverResponse "unsat core" unsatCoreRsp s cmd smtAbductResult p s nm t = let abductRsp = \case AckSuccessSExp (SApp (_ : _ : _ : _ : abduct)) -> Just $ Data.String.unwords (map sExpToString abduct) _ -> Nothing cmd = getAbductCommand p nm t in getLimitedSolverResponse "get abduct" abductRsp s cmd smtAbductNextResult p s = let abductRsp = \case AckSuccessSExp (SApp (_ : _ : _ : _ : abduct)) -> Just $ Data.String.unwords (map sExpToString abduct) _ -> Nothing cmd = getAbductNextCommand p in getLimitedSolverResponse "get abduct next" abductRsp s cmd smtAckResult :: AcknowledgementAction t (Writer a) smtAckResult = AckAction $ getLimitedSolverResponse "get ack" $ \case AckSuccess -> Just () _ -> Nothing smtLibEvalFuns :: forall t a. SMTLib2Tweaks a => Session t a -> SMTEvalFunctions (Writer a) smtLibEvalFuns s = SMTEvalFunctions { smtEvalBool = evalBool , smtEvalBV = evalBV , smtEvalReal = evalReal , smtEvalFloat = evalFloat , smtEvalBvArray = Just (SMTEvalBVArrayWrapper evalBvArray) , smtEvalString = evalStr } where evalBool tm = parseBoolSolverValue =<< runGetValue s tm evalReal tm = parseRealSolverValue =<< runGetValue s tm evalStr tm = parseStringSolverValue =<< runGetValue s tm evalBV :: NatRepr w -> Term -> IO (BV.BV w) evalBV w tm = parseBvSolverValue w =<< runGetValue s tm evalFloat :: FloatPrecisionRepr fpp -> Term -> IO (BV.BV (FloatPrecisionBits fpp)) evalFloat fpp tm = parseFloatSolverValue fpp =<< runGetValue s tm evalBvArray :: SMTEvalBVArrayFn (Writer a) w v evalBvArray w v tm = parseBvArraySolverValue w v =<< runGetValue s tm class (SMTLib2Tweaks a, Show a) => SMTLib2GenericSolver a where defaultSolverPath :: a -> B.ExprBuilder t st fs -> IO FilePath defaultSolverArgs :: a -> B.ExprBuilder t st fs -> IO [String] defaultFeatures :: a -> ProblemFeatures getErrorBehavior :: a -> WriterConn t (Writer a) -> IO ErrorBehavior getErrorBehavior _ _ = return ImmediateExit supportsResetAssertions :: a -> Bool supportsResetAssertions _ = False setDefaultLogicAndOptions :: WriterConn t (Writer a) -> IO() newDefaultWriter :: a -> AcknowledgementAction t (Writer a) -> ProblemFeatures -> -- | strictness override configuration Maybe (CFG.ConfigOption I.BaseBoolType) -> B.ExprBuilder t st fs -> Streams.OutputStream Text -> Streams.InputStream Text -> IO (WriterConn t (Writer a)) newDefaultWriter solver ack feats strictOpt sym h in_h = do let cfg = I.getConfiguration sym strictness <- parserStrictness strictOpt strictSMTParsing cfg newWriter solver h in_h ack strictness (show solver) True feats True =<< B.getSymbolVarBimap sym -- | Run the solver in a session. withSolver :: a -> AcknowledgementAction t (Writer a) -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -- ^ strictness override configuration -> B.ExprBuilder t st fs -> FilePath -- ^ Path to solver executable -> LogData -> (Session t a -> IO b) -- ^ Action to run -> IO b withSolver solver ack feats strictOpt sym path logData action = do args <- defaultSolverArgs solver sym withProcessHandles path args Nothing $ \hdls@(in_h, out_h, err_h, _ph) -> do (in_stream, out_stream, err_reader) <- demuxProcessHandles in_h out_h err_h (fmap (\x -> ("; ", x)) $ logHandle logData) writer <- newDefaultWriter solver ack feats strictOpt sym in_stream out_stream let s = Session { sessionWriter = writer , sessionResponse = out_stream } -- Set solver logic and solver-specific options setDefaultLogicAndOptions writer -- Run action with session. r <- action s -- Tell solver to exit writeExit writer stopHandleReader err_reader ec <- cleanupProcess hdls case ec of Exit.ExitSuccess -> return r Exit.ExitFailure exit_code -> fail $ show solver ++ " exited with unexpected code: " ++ show exit_code runSolverInOverride :: a -> AcknowledgementAction t (Writer a) -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -- ^ strictness override configuration -> B.ExprBuilder t st fs -> LogData -> [B.BoolExpr t] -> (SatResult (GroundEvalFn t, Maybe (ExprRangeBindings t)) () -> IO b) -> IO b runSolverInOverride solver ack feats strictOpt sym logData predicates cont = do I.logSolverEvent sym (I.SolverStartSATQuery $ I.SolverStartSATQueryRec { I.satQuerySolverName = show solver , I.satQueryReason = logReason logData }) path <- defaultSolverPath solver sym withSolver solver ack feats strictOpt sym path (logData{logVerbosity=2}) $ \session -> do -- Assume the predicates hold. forM_ predicates (SMTWriter.assume (sessionWriter session)) Run check SAT and get the model back . runCheckSat session $ \result -> do I.logSolverEvent sym (I.SolverEndSATQuery $ I.SolverEndSATQueryRec { I.satQueryResult = forgetModelAndCore result , I.satQueryError = Nothing }) cont result | A default method for writing SMTLib2 problems without any -- solver-specific tweaks. writeDefaultSMT2 :: SMTLib2Tweaks a => a -> String -- ^ Name of solver for reporting. -> ProblemFeatures -- ^ Features supported by solver -> Maybe (CFG.ConfigOption I.BaseBoolType) -- ^ strictness override configuration -> B.ExprBuilder t st fs -> IO.Handle -> [B.BoolExpr t] -> IO () writeDefaultSMT2 a nm feat strictOpt sym h ps = do c <- defaultFileWriter a nm feat strictOpt sym h setProduceModels c True forM_ ps (SMTWriter.assume c) writeCheckSat c writeExit c defaultFileWriter :: SMTLib2Tweaks a => a -> String -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -> B.ExprBuilder t st fs -> IO.Handle -> IO (WriterConn t (Writer a)) defaultFileWriter a nm feat strictOpt sym h = do bindings <- B.getSymbolVarBimap sym str <- Streams.encodeUtf8 =<< Streams.handleToOutputStream h null_in <- Streams.nullInput let cfg = I.getConfiguration sym strictness <- parserStrictness strictOpt strictSMTParsing cfg newWriter a str null_in nullAcknowledgementAction strictness nm True feat True bindings -- n.b. commonly used for the startSolverProcess method of the -- OnlineSolver class, so it's helpful for the type suffixes to align startSolver :: SMTLib2GenericSolver a => a -> AcknowledgementAction t (Writer a) -- ^ Action for acknowledging command responses -> (WriterConn t (Writer a) -> IO ()) -- ^ Action for setting start-up-time options and logic -> SolverGoalTimeout -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -- ^ strictness override configuration -> Maybe IO.Handle -> B.ExprBuilder t st fs -> IO (SolverProcess t (Writer a)) startSolver solver ack setup tmout feats strictOpt auxOutput sym = do path <- defaultSolverPath solver sym args <- defaultSolverArgs solver sym hdls@(in_h, out_h, err_h, ph) <- startProcess path args Nothing (in_stream, out_stream, err_reader) <- demuxProcessHandles in_h out_h err_h (fmap (\x -> ("; ", x)) auxOutput) -- Create writer writer <- newDefaultWriter solver ack feats strictOpt sym in_stream out_stream -- Set solver logic and solver-specific options setup writer -- Query the solver for it's error behavior errBeh <- getErrorBehavior solver writer earlyUnsatRef <- newIORef Nothing -- push an initial frame for solvers that don't support reset unless (supportsResetAssertions solver) (addCommand writer (SMT2.push 1)) return $! SolverProcess { solverConn = writer , solverCleanupCallback = cleanupProcess hdls , solverStderr = err_reader , solverHandle = ph , solverErrorBehavior = errBeh , solverEvalFuns = smtEvalFuns writer out_stream , solverLogFn = I.logSolverEvent sym , solverName = show solver , solverEarlyUnsat = earlyUnsatRef , solverSupportsResetAssertions = supportsResetAssertions solver , solverGoalTimeout = tmout } shutdownSolver :: SMTLib2GenericSolver a => a -> SolverProcess t (Writer a) -> IO (Exit.ExitCode, Lazy.Text) shutdownSolver _solver p = do -- Tell solver to exit writeExit (solverConn p) txt <- readAllLines (solverStderr p) stopHandleReader (solverStderr p) ec <- solverCleanupCallback p return (ec,txt) ----------------------------------------------------------------- -- Checking solver version bounds -- | Solver version bounds computed from \"solverBounds.config\" defaultSolverBounds :: Map Text SolverBounds defaultSolverBounds = Map.fromList $(computeDefaultSolverBounds) -- | Things that can go wrong while checking which solver version we've got data SolverVersionCheckError = UnparseableVersion Versions.ParsingError ppSolverVersionCheckError :: SolverVersionCheckError -> PP.Doc ann ppSolverVersionCheckError err = PP.vsep [ "Unexpected error while checking solver version:" , case err of UnparseableVersion parseErr -> PP.hsep [ "Couldn't parse solver version number:" , PP.viaShow parseErr ] ] data SolverVersionError = SolverVersionError { vBounds :: SolverBounds , vActual :: Version } ppSolverVersionError :: SolverVersionError -> PP.Doc ann ppSolverVersionError err = PP.vsep [ "Solver did not meet version bound restrictions:" , "Lower bound (inclusive):" PP.<+> na (lower (vBounds err)) , "Upper bound (non-inclusive):" PP.<+> na (upper (vBounds err)) , "Actual version:" PP.<+> PP.viaShow (vActual err) ] where na (Just s) = PP.viaShow s na Nothing = "n/a" -- | Get the result of a version query nameResult :: WriterConn t a -> IO Text nameResult conn = getLimitedSolverResponse "solver name" (\case RspName nm -> Just nm _ -> Nothing ) conn SMT2.getName -- | Query the solver's error behavior setting queryErrorBehavior :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO ErrorBehavior queryErrorBehavior conn = do let cmd = SMT2.getErrorBehavior writeCommand conn cmd getLimitedSolverResponse "error behavior" (\case RspErrBehavior bh -> case bh of "continued-execution" -> return ContinueOnError "immediate-exit" -> return ImmediateExit _ -> throw $ SMTLib2ResponseUnrecognized cmd bh _ -> Nothing ) conn cmd -- | Get the result of a version query versionResult :: WriterConn t a -> IO Text versionResult conn = getLimitedSolverResponse "solver version" (\case RspVersion v -> Just v _ -> Nothing ) conn SMT2.getVersion -- | Ensure the solver's version falls within a known-good range. checkSolverVersion' :: SMTLib2Tweaks solver => Map Text SolverBounds -> SolverProcess scope (Writer solver) -> IO (Either SolverVersionCheckError (Maybe SolverVersionError)) checkSolverVersion' boundsMap proc = let conn = solverConn proc name = smtWriterName conn done = pure (Right Nothing) verr bnds actual = pure (Right (Just (SolverVersionError bnds actual))) in case Map.lookup (Text.pack name) boundsMap of Nothing -> done Just bnds -> do getVersion conn res <- versionResult $ solverConn proc case Versions.version res of Left e -> pure (Left (UnparseableVersion e)) Right actualVer -> case (lower bnds, upper bnds) of (Nothing, Nothing) -> done (Nothing, Just maxVer) -> if actualVer < maxVer then done else verr bnds actualVer (Just minVer, Nothing) -> if minVer <= actualVer then done else verr bnds actualVer (Just minVer, Just maxVer) -> if minVer <= actualVer && actualVer < maxVer then done else verr bnds actualVer -- | Ensure the solver's version falls within a known-good range. checkSolverVersion :: SMTLib2Tweaks solver => SolverProcess scope (Writer solver) -> IO (Either SolverVersionCheckError (Maybe SolverVersionError)) checkSolverVersion = checkSolverVersion' defaultSolverBounds
null
https://raw.githubusercontent.com/GaloisInc/what4/98ae759128a5c3de947b59730806b110ec8c005d/what4/src/What4/Protocol/SMTLib2.hs
haskell
---------------------------------------------------------------------- | Module : What4.Protocol.SMTLib2 License : BSD3 Stability : provisional an input language. ---------------------------------------------------------------------- # LANGUAGE GADTs # # LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # SMTLib special purpose exports * Logic * Type * Term * Solvers and External interface * Solver version * Re-exports | Set the logic to all supported logics. ---------------------------------------------------------------------- Floating point ^ Number of bits in exponent ^ Number of bits in the significand. ---------------------------------------------------------------------- | Select a valued from a nested array ---------------------------------------------------------------------------------- String Escaping functions The following functions implement the escaping and regarding this format is pasted below from the specification document. String literals We refer to these literals as _string constants_. simplicity since that set is universally supported. Arbitrary Unicode characters forms \ud₃d₂d₁d₀ \u{d₀} \u{d₁d₀} \u{d₂d₁d₀} \u{d₃d₂d₁d₀} \u{d₄d₃d₂d₁d₀} These are the **only escape sequences** in this theory. See later. In a later version, the restrictions above on the digits may be extended following the common use of this form in some programming languages. Unicode characters outside the range covered by \ud₃d₂d₁d₀ can be represented with the long form \u{d₄d₃d₂d₁d₀}. Also observe that programming language-specific escape sequences, such as are not fully standard across languages. | Apply the SMTLib2.6 string escaping rules to a string literal. special case: the `"` character has a special case escaping mode which is encoded as `""` special case: always escape the `\` character as an explicit code point, so we don't have to do lookahead to discover if it is followed by a `u` others characters in the "normal" ASCII range require no escaping characters outside that range require escaping | Parse SMTLIb2.6 escaping rules for strings. to encode a double quote has already been resolved by @parseSMTLIb2String@, so here we just need to take until the closing brace features that go slightly beyond the standard. In particular, there is no standardized syntax for constant arrays (arrays which map every index to the same value). Solvers that support the theory of arrays and have custom syntax for constant arrays should implement `smtlib2arrayConstant`. In addition, solvers may override the default representation of complex numbers if necessary. The default is to represent complex numbers as "(Array Bool Real)" and to build instances by updating a constant array. | Return a representation of the type associated with a (multi-dimensional) symbolic array. By default, we encode symbolic arrays using a nested representation. If the solver, supports tuples/structs it may wish to change this. | The sort of structs with the given field types. | Construct a struct value from the given field values | Construct a struct field projection term ^ number of fields in the struct ^ 0-based index of the struct field ^ struct term to project from Default instance. ---------------------------------------------------------------------- ---------------------------------------------------------------------- Type ---------------------------------------------------------------------- Writer Note about structs: For each length XX associated to some structure with that length in the constructor "mk-structXX", and projection operations "structXX-projII" NB: SMT2.letBinder defines a "parallel" let, and we want the semantics of a "sequential" let, so expand to a series of nested lets. ---------------------------------------------------------------------- Writer ^ Stream to write queries onto ^ Input stream to read responses from (may be the @nullInput@ stream if no responses are expected) ^ Action to run for consuming acknowledgement messages ^ Name of solver for reporting purposes. ^ Flag indicating if it is permitted to use ^ Indicates what features are supported by the solver ^ Indicates if quantifiers are supported. ^ Variable bindings for names. force a flush | Write check sat command | Set the produce models option (We typically want this) | Write check-synth command | Parse a bitvector value returned by a solver. Most solvers give of the variable. ^ width ^ BV value | Parse an s-expression and return a bitvector and its width eb' + 1 ~ 1 + eb' sign exponent width exponent significand bit width significand bit do-expression to extract the proof. | Given an expression, monadically either returns proof that it is a bitvector or throws an error. | Operator type descriptions for parsing s-expression of the form @(operator operands ...)@. <> | Generic unary operator description. | Generic binary operator description. | Bitvector binop with a boolean return type, i.e., comparison operators. | Verify a list of arguments has a single argument and return it, else raise an error. it, else raise an error. ++ show exsAsn | Utility function for contextualizing errors. Prepends the given prefix whenever an error is thrown. ---------------------------------------------------------------------- Session | Get a value from a solver (must be called after checkSat) the assertions in the context) get the rest of the abducts using the get-abduct-next command | This function runs a check sat command ^ Function for evaluating model. The evaluation should be complete before | strictness override configuration | Run the solver in a session. ^ strictness override configuration ^ Path to solver executable ^ Action to run Set solver logic and solver-specific options Run action with session. Tell solver to exit ^ strictness override configuration Assume the predicates hold. solver-specific tweaks. ^ Name of solver for reporting. ^ Features supported by solver ^ strictness override configuration n.b. commonly used for the startSolverProcess method of the OnlineSolver class, so it's helpful for the type suffixes to align ^ Action for acknowledging command responses ^ Action for setting start-up-time options and logic ^ strictness override configuration Create writer Set solver logic and solver-specific options Query the solver for it's error behavior push an initial frame for solvers that don't support reset Tell solver to exit --------------------------------------------------------------- Checking solver version bounds | Solver version bounds computed from \"solverBounds.config\" | Things that can go wrong while checking which solver version we've got | Get the result of a version query | Query the solver's error behavior setting | Get the result of a version query | Ensure the solver's version falls within a known-good range. | Ensure the solver's version falls within a known-good range.
Description : Interface for solvers that consume SMTLib2 Copyright : ( c ) Galois , Inc 2014 - 2020 Maintainer : < > This module defines operations for producing SMTLib2 - compatible queries useful for interfacing with solvers that accecpt SMTLib2 as # LANGUAGE AllowAmbiguousTypes # # LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedLists # # LANGUAGE PatternGuards # # LANGUAGE PatternSynonyms # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - orphans # module What4.Protocol.SMTLib2 Writer , SMTLib2Tweaks(..) , newWriter , writeCheckSat , writeExit , writeGetValue , writeGetAbduct , writeGetAbductNext , writeCheckSynth , runCheckSat , runGetAbducts , asSMT2Type , setOption , getVersion , versionResult , getName , nameResult , setProduceModels , smtLibEvalFuns , smtlib2Options , parseFnModel , parseFnValues , SMT2.Logic(..) , SMT2.qf_bv , SMT2.allSupported , SMT2.hornLogic , all_supported , setLogic , SMT2.Sort(..) , SMT2.arraySort , Term(..) , arrayConst , What4.Protocol.SMTLib2.arraySelect , arrayStore , Session(..) , SMTLib2GenericSolver(..) , writeDefaultSMT2 , defaultFileWriter , startSolver , shutdownSolver , smtAckResult , SMTLib2Exception(..) , ppSolverVersionCheckError , ppSolverVersionError , checkSolverVersion , checkSolverVersion' , queryErrorBehavior , defaultSolverBounds , SMTWriter.WriterConn , SMTWriter.assume , SMTWriter.supportedFeatures , SMTWriter.nullAcknowledgementAction ) where #if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail( MonadFail ) #endif import Control.Applicative import Control.Exception import Control.Monad.Except import Control.Monad.Reader import qualified Data.Bimap as Bimap import qualified Data.BitVector.Sized as BV import Data.Char (digitToInt, isAscii) import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as HashMap import Data.IORef import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Monoid import Data.Parameterized.Classes import qualified Data.Parameterized.Context as Ctx import Data.Parameterized.Map (MapF) import qualified Data.Parameterized.Map as MapF import Data.Parameterized.NatRepr import Data.Parameterized.Pair import Data.Parameterized.Some import Data.Parameterized.TraversableFC import Data.Ratio import Data.Set (Set) import qualified Data.Set as Set import Data.String import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as Lazy import Data.Text.Lazy.Builder (Builder) import qualified Data.Text.Lazy.Builder as Builder import qualified Data.Text.Lazy.Builder.Int as Builder import Numeric (readDec, readHex, readInt, showHex) import Numeric.Natural import qualified System.Exit as Exit import qualified System.IO as IO import qualified System.IO.Streams as Streams import Data.Versions (Version(..)) import qualified Data.Versions as Versions import qualified Prettyprinter as PP import Text.Printf (printf) import LibBF( bfToBits ) import Prelude hiding (writeFile) import What4.BaseTypes import qualified What4.Config as CFG import qualified What4.Expr.Builder as B import What4.Expr.GroundEval import qualified What4.Interface as I import What4.ProblemFeatures import What4.Protocol.Online import What4.Protocol.ReadDecimal import What4.Protocol.SExp import What4.Protocol.SMTLib2.Syntax (Term, term_app, un_app, bin_app) import What4.Protocol.SMTLib2.Response import qualified What4.Protocol.SMTLib2.Syntax as SMT2 hiding (Term) import qualified What4.Protocol.SMTWriter as SMTWriter import What4.Protocol.SMTWriter hiding (assume, Term) import What4.SatResult import What4.Utils.FloatHelpers (fppOpts) import What4.Utils.HandleReader import What4.Utils.Process import What4.Utils.Versions import What4.Solver.Adapter all_supported :: SMT2.Logic all_supported = SMT2.allLogic # DEPRECATED all_supported " Use instead " # smtlib2Options :: [CFG.ConfigDesc] smtlib2Options = smtParseOptions data SMTFloatPrecision = SMTFloatPrecision { smtFloatExponentBits :: !Natural , smtFloatSignificandBits :: !Natural } deriving (Eq, Ord) asSMTFloatPrecision :: FloatPrecisionRepr fpp -> SMTFloatPrecision asSMTFloatPrecision (FloatingPointPrecisionRepr eb sb) = SMTFloatPrecision { smtFloatExponentBits = natValue eb , smtFloatSignificandBits = natValue sb } mkFloatSymbol :: Builder -> SMTFloatPrecision -> Builder mkFloatSymbol nm (SMTFloatPrecision eb sb) = "(_ " <> nm <> " " <> fromString (show eb) <> " " <> fromString (show sb) <> ")" SMTLib2Tweaks nestedArrayUpdate :: Term -> (Term, [Term]) -> Term -> Term nestedArrayUpdate a (h,[]) v = SMT2.store a h v nestedArrayUpdate a (h,i:l) v = SMT2.store a h sub_a' where sub_a' = nestedArrayUpdate (SMT2.select a h) (i,l) v arrayConst :: SMT2.Sort -> SMT2.Sort -> Term -> Term arrayConst = SMT2.arrayConst arraySelect :: Term -> Term -> Term arraySelect = SMT2.select arrayStore :: Term -> Term -> Term -> Term arrayStore = SMT2.store escape parsing rules from SMTLib 2.6 . Documentation All double - quote - delimited string literals consisting of printable US ASCII characters , i.e. , those with Unicode code point from 0x00020 to 0x0007E. The restriction to printable US ASCII characters in string constants is for can be represented with _ escape sequences _ which can have one of the following where each dᵢ is a hexadecimal digit and is restricted to the range 0 - 2 . to allow characters from all 17 Unicode planes . Observe that the first form , \ud₃d₂d₁d₀ , has exactly 4 hexadecimal digit , \n , \b , \r and so on , are _ not _ escape sequences in this theory as they textToTerm :: Text -> Term textToTerm bs = SMT2.T ("\"" <> Text.foldr f "\"" bs) where inLiteralRange c = 0x20 <= fromEnum c && fromEnum c <= 0x7E f c x | '\"' == c = "\"\"" <> x | '\\' == c = "\\u{5c}" <> x | inLiteralRange c = Builder.singleton c <> x | otherwise = "\\u{" <> Builder.fromString (showHex (fromEnum c) "}") <> x Note ! The escaping rule that uses the @\"\"@ sequence parse the @\\u@ escape forms . unescapeText :: Text -> Maybe Text unescapeText = go mempty where go str t = case Text.uncons t of Nothing -> Just str Just (c, t') | not (isAscii c) -> Nothing | c == '\\' -> readEscape str t' | otherwise -> continue str c t' continue str c t = go (Text.snoc str c) t readEscape str t = case Text.uncons t of Nothing -> Just (Text.snoc str '\\') Just (c, t') Note : the \u forms are the _ only _ escape forms | c == 'u' -> readHexEscape str t' | otherwise -> continue (Text.snoc str '\\') c t' readHexEscape str t = case Text.uncons t of Just (c, t') | c == '{' , (ds, t'') <- Text.breakOn "}" t' , Just ('}',t''') <- Text.uncons t'' -> readDigits str ds t''' take exactly four digits | (ds, t'') <- Text.splitAt 4 t' , Text.length ds == 4 -> readDigits str ds t'' _ -> Nothing readDigits str ds t = case readHex (Text.unpack ds) of (n, []):_ -> continue str (toEnum n) t _ -> Nothing | This class exists so that solvers supporting the SMTLib2 format can support class Show a => SMTLib2Tweaks a where smtlib2tweaks :: a smtlib2exitCommand :: Maybe SMT2.Command smtlib2exitCommand = Just SMT2.exit smtlib2arrayType :: [SMT2.Sort] -> SMT2.Sort -> SMT2.Sort smtlib2arrayType l r = foldr (\i v -> SMT2.arraySort i v) r l smtlib2arrayConstant :: Maybe ([SMT2.Sort] -> SMT2.Sort -> Term -> Term) smtlib2arrayConstant = Nothing smtlib2arraySelect :: Term -> [Term] -> Term smtlib2arraySelect a [] = a smtlib2arraySelect a (h:l) = smtlib2arraySelect @a (What4.Protocol.SMTLib2.arraySelect a h) l smtlib2arrayUpdate :: Term -> [Term] -> Term -> Term smtlib2arrayUpdate a i v = case i of [] -> error "arrayUpdate given empty list" i1:ir -> nestedArrayUpdate a (i1, ir) v smtlib2StringSort :: SMT2.Sort smtlib2StringSort = SMT2.Sort "String" smtlib2StringTerm :: Text -> Term smtlib2StringTerm = textToTerm smtlib2StringLength :: Term -> Term smtlib2StringLength = SMT2.un_app "str.len" smtlib2StringAppend :: [Term] -> Term smtlib2StringAppend = SMT2.term_app "str.++" smtlib2StringContains :: Term -> Term -> Term smtlib2StringContains = SMT2.bin_app "str.contains" smtlib2StringIndexOf :: Term -> Term -> Term -> Term smtlib2StringIndexOf s t i = SMT2.term_app "str.indexof" [s,t,i] smtlib2StringIsPrefixOf :: Term -> Term -> Term smtlib2StringIsPrefixOf = SMT2.bin_app "str.prefixof" smtlib2StringIsSuffixOf :: Term -> Term -> Term smtlib2StringIsSuffixOf = SMT2.bin_app "str.suffixof" smtlib2StringSubstring :: Term -> Term -> Term -> Term smtlib2StringSubstring x off len = SMT2.term_app "str.substr" [x,off,len] By default , this uses SMTLIB2 datatypes and are not primitive to the language . smtlib2StructSort :: [SMT2.Sort] -> SMT2.Sort smtlib2StructSort [] = SMT2.Sort "Struct0" smtlib2StructSort flds = SMT2.Sort $ "(Struct" <> Builder.decimal n <> foldMap f flds <> ")" where f :: SMT2.Sort -> Builder f (SMT2.Sort s) = " " <> s n = length flds smtlib2StructCtor :: [Term] -> Term smtlib2StructCtor args = term_app nm args where nm = "mk-struct" <> Builder.decimal (length args) smtlib2StructProj :: Term smtlib2StructProj n i a = term_app nm [a] where nm = "struct" <> Builder.decimal n <> "-proj" <> Builder.decimal i By default , this uses the SMTLib 2.6 standard version of the declare - datatype command . smtlib2declareStructCmd :: Int -> Maybe SMT2.Command smtlib2declareStructCmd 0 = Just $ SMT2.Cmd $ app "declare-datatype" [ fromString "Struct0", builder_list [ builder_list ["mk-struct0"]]] smtlib2declareStructCmd n = Just $ let n_str = fromString (show n) tp = "Struct" <> n_str cnstr = "mk-struct" <> n_str idxes = map (fromString . show) [0 .. n-1] tp_names = [ "T" <> i_str | i_str <- idxes ] flds = [ app ("struct" <> n_str <> "-proj" <> i_str) [ "T" <> i_str ] | i_str <- idxes ] in SMT2.Cmd $ app "declare-datatype" [ tp, app "par" [ builder_list tp_names, builder_list [app cnstr flds]]] asSMT2Type :: forall a tp . SMTLib2Tweaks a => TypeMap tp -> SMT2.Sort asSMT2Type BoolTypeMap = SMT2.boolSort asSMT2Type IntegerTypeMap = SMT2.intSort asSMT2Type RealTypeMap = SMT2.realSort asSMT2Type (BVTypeMap w) = SMT2.bvSort (natValue w) asSMT2Type (FloatTypeMap fpp) = SMT2.Sort $ mkFloatSymbol "FloatingPoint" (asSMTFloatPrecision fpp) asSMT2Type UnicodeTypeMap = smtlib2StringSort @a asSMT2Type ComplexToStructTypeMap = smtlib2StructSort @a [ SMT2.realSort, SMT2.realSort ] asSMT2Type ComplexToArrayTypeMap = smtlib2arrayType @a [SMT2.boolSort] SMT2.realSort asSMT2Type (PrimArrayTypeMap i r) = smtlib2arrayType @a (toListFC (asSMT2Type @a) i) (asSMT2Type @a r) asSMT2Type (FnArrayTypeMap _ _) = error "SMTLIB backend does not support function types as first class." asSMT2Type (StructTypeMap f) = smtlib2StructSort @a (toListFC (asSMT2Type @a) f) instance SMTLib2Tweaks () where smtlib2tweaks = () readBin :: Num a => ReadS a readBin = readInt 2 (`elem` ("01" :: String)) digitToInt mkRoundingOp :: Builder -> RoundingMode -> Builder mkRoundingOp op r = op <> " " <> fromString (show r) newtype Writer a = Writer { declaredTuples :: IORef (Set Int) } type instance SMTWriter.Term (Writer a) = Term instance Num Term where x + y = SMT2.add [x, y] x - y = SMT2.sub x [y] x * y = SMT2.mul [x, y] negate x = SMT2.negate x abs x = SMT2.ite (SMT2.ge [x, SMT2.numeral 0]) x (SMT2.negate x) signum x = SMT2.ite (SMT2.ge [x, SMT2.numeral 0]) (SMT2.ite (SMT2.eq [x, SMT2.numeral 0]) (SMT2.numeral 0) (SMT2.numeral 1)) (SMT2.negate (SMT2.numeral 1)) fromInteger = SMT2.numeral varBinding :: forall a . SMTLib2Tweaks a => (Text, Some TypeMap) -> (Text, SMT2.Sort) varBinding (nm, Some tp) = (nm, asSMT2Type @a tp) The SMTLIB2 exporter uses the datatypes theory for representing structures . formula , the SMTLIB2 backend defines a datatype " StructXX " with the for II an natural number less than XX . instance SupportTermOps Term where boolExpr b = if b then SMT2.true else SMT2.false notExpr = SMT2.not andAll = SMT2.and orAll = SMT2.or x .== y = SMT2.eq [x,y] x ./= y = SMT2.distinct [x,y] letExpr vs t = foldr (\v -> SMT2.letBinder [v]) t vs ite = SMT2.ite sumExpr = SMT2.add termIntegerToReal = SMT2.toReal termRealToInteger = SMT2.toInt integerTerm = SMT2.numeral intDiv x y = SMT2.div x [y] intMod = SMT2.mod intAbs = SMT2.abs intDivisible x 0 = x .== integerTerm 0 intDivisible x k = intMod x (integerTerm (toInteger k)) .== 0 rationalTerm r | d == 1 = SMT2.decimal n | otherwise = (SMT2.decimal n) SMT2../ [SMT2.decimal d] where n = numerator r d = denominator r x .< y = SMT2.lt [x,y] x .<= y = SMT2.le [x,y] x .> y = SMT2.gt [x,y] x .>= y = SMT2.ge [x,y] bvTerm w u = case isZeroOrGT1 w of Left Refl -> error "Cannot construct BV term with 0 width" Right LeqProof -> SMT2.bvdecimal w u bvNeg = SMT2.bvneg bvAdd x y = SMT2.bvadd x [y] bvSub = SMT2.bvsub bvMul x y = SMT2.bvmul x [y] bvSLe = SMT2.bvsle bvULe = SMT2.bvule bvSLt = SMT2.bvslt bvULt = SMT2.bvult bvUDiv = SMT2.bvudiv bvURem = SMT2.bvurem bvSDiv = SMT2.bvsdiv bvSRem = SMT2.bvsrem bvNot = SMT2.bvnot bvAnd x y = SMT2.bvand x [y] bvOr x y = SMT2.bvor x [y] bvXor x y = SMT2.bvxor x [y] bvShl = SMT2.bvshl bvLshr = SMT2.bvlshr bvAshr = SMT2.bvashr bvConcat = SMT2.concat bvExtract _ b n x | n > 0 = SMT2.extract (b+n-1) b x | otherwise = error $ "bvExtract given non-positive width " ++ show n floatNeg = un_app "fp.neg" floatAbs = un_app "fp.abs" floatSqrt r = un_app $ mkRoundingOp "fp.sqrt " r floatAdd r = bin_app $ mkRoundingOp "fp.add" r floatSub r = bin_app $ mkRoundingOp "fp.sub" r floatMul r = bin_app $ mkRoundingOp "fp.mul" r floatDiv r = bin_app $ mkRoundingOp "fp.div" r floatRem = bin_app "fp.rem" floatFMA r x y z = term_app (mkRoundingOp "fp.fma" r) [x, y, z] floatEq x y = SMT2.eq [x,y] floatFpEq = bin_app "fp.eq" floatLe = bin_app "fp.leq" floatLt = bin_app "fp.lt" floatIsNaN = un_app "fp.isNaN" floatIsInf = un_app "fp.isInfinite" floatIsZero = un_app "fp.isZero" floatIsPos = un_app "fp.isPositive" floatIsNeg = un_app "fp.isNegative" floatIsSubnorm = un_app "fp.isSubnormal" floatIsNorm = un_app "fp.isNormal" floatTerm fpp@(FloatingPointPrecisionRepr eb sb) bf = un_app (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) (bvTerm w bv) where w = addNat eb sb bv = BV.mkBV w (bfToBits (fppOpts fpp RNE) bf) floatCast fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) r floatRound r = un_app $ mkRoundingOp "fp.roundToIntegral" r floatFromBinary fpp = un_app $ mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp) bvToFloat fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp_unsigned" (asSMTFloatPrecision fpp)) r sbvToFloat fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) r realToFloat fpp r = un_app $ mkRoundingOp (mkFloatSymbol "to_fp" (asSMTFloatPrecision fpp)) r floatToBV w r = un_app $ mkRoundingOp ("(_ fp.to_ubv " <> fromString (show w) <> ")") r floatToSBV w r = un_app $ mkRoundingOp ("(_ fp.to_sbv " <> fromString (show w) <> ")") r floatToReal = un_app "fp.to_real" realIsInteger = SMT2.isInt realDiv x y = x SMT2../ [y] realSin = un_app "sin" realCos = un_app "cos" realTan = un_app "tan" realATan2 = bin_app "atan2" realSinh = un_app "sinh" realCosh = un_app "cosh" realTanh = un_app "tanh" realExp = un_app "exp" realLog = un_app "log" smtFnApp nm args = term_app (SMT2.renderTerm nm) args fromText t = SMT2.T (Builder.fromText t) newWriter :: a -> Streams.OutputStream Text -> Streams.InputStream Text -> AcknowledgementAction t (Writer a) -> ResponseStrictness ^ Be strict in parsing SMT solver responses ? -> String -> Bool " define - fun " when generating SMTLIB -> ProblemFeatures -> Bool -> B.SymbolVarBimap t -> IO (WriterConn t (Writer a)) newWriter _ h in_h ack isStrict solver_name permitDefineFun arithOption quantSupport bindings = do r <- newIORef Set.empty let initWriter = Writer { declaredTuples = r } conn <- newWriterConn h in_h ack solver_name isStrict arithOption bindings initWriter return $! conn { supportFunctionDefs = permitDefineFun , supportQuantifiers = quantSupport } type instance Command (Writer a) = SMT2.Command instance SMTLib2Tweaks a => SMTWriter (Writer a) where forallExpr vars t = SMT2.forall_ (varBinding @a <$> vars) t existsExpr vars t = SMT2.exists_ (varBinding @a <$> vars) t arrayConstant = case smtlib2arrayConstant @a of Just f -> Just $ \idxTypes (Some retType) c -> f ((\(Some itp) -> asSMT2Type @a itp) <$> idxTypes) (asSMT2Type @a retType) c Nothing -> Nothing arraySelect = smtlib2arraySelect @a arrayUpdate = smtlib2arrayUpdate @a commentCommand _ b = SMT2.Cmd ("; " <> b) assertCommand _ e = SMT2.assert e assertNamedCommand _ e nm = SMT2.assertNamed e nm pushCommand _ = SMT2.push 1 popCommand _ = SMT2.pop 1 push2Command _ = SMT2.push 2 pop2Command _ = SMT2.pop 2 resetCommand _ = SMT2.resetAssertions popManyCommands _ n = [SMT2.pop (toInteger n)] checkCommands _ = [SMT2.checkSat] checkWithAssumptionsCommands _ nms = [SMT2.checkSatWithAssumptions nms] getUnsatAssumptionsCommand _ = SMT2.getUnsatAssumptions getUnsatCoreCommand _ = SMT2.getUnsatCore getAbductCommand _ nm e = SMT2.getAbduct nm e getAbductNextCommand _ = SMT2.getAbductNext setOptCommand _ = SMT2.setOption declareCommand _proxy v argTypes retType = SMT2.declareFun v (toListFC (asSMT2Type @a) argTypes) (asSMT2Type @a retType) defineCommand _proxy f args return_type e = let resolveArg (var, Some tp) = (var, asSMT2Type @a tp) in SMT2.defineFun f (resolveArg <$> args) (asSMT2Type @a return_type) e synthFunCommand _proxy f args ret_tp = SMT2.synthFun f (map (\(var, Some tp) -> (var, asSMT2Type @a tp)) args) (asSMT2Type @a ret_tp) declareVarCommand _proxy v tp = SMT2.declareVar v (asSMT2Type @a tp) constraintCommand _proxy e = SMT2.constraint e stringTerm str = smtlib2StringTerm @a str stringLength x = smtlib2StringLength @a x stringAppend xs = smtlib2StringAppend @a xs stringContains x y = smtlib2StringContains @a x y stringIsPrefixOf x y = smtlib2StringIsPrefixOf @a x y stringIsSuffixOf x y = smtlib2StringIsSuffixOf @a x y stringIndexOf x y k = smtlib2StringIndexOf @a x y k stringSubstring x off len = smtlib2StringSubstring @a x off len structCtor _tps vals = smtlib2StructCtor @a vals structProj tps idx v = let n = Ctx.sizeInt (Ctx.size tps) i = Ctx.indexVal idx in smtlib2StructProj @a n i v resetDeclaredStructs conn = do let r = declaredTuples (connState conn) writeIORef r mempty declareStructDatatype conn flds = do let n = Ctx.sizeInt (Ctx.size flds) let r = declaredTuples (connState conn) s <- readIORef r when (Set.notMember n s) $ do case smtlib2declareStructCmd @a n of Nothing -> return () Just cmd -> addCommand conn cmd writeIORef r $! Set.insert n s writeCommand conn (SMT2.Cmd cmd) = do let cmdout = Lazy.toStrict (Builder.toLazyText cmd) Streams.write (Just (cmdout <> "\n")) (connHandle conn) Streams.write (Just "") (connHandle conn) writeCheckSat :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeCheckSat w = addCommandNoAck w SMT2.checkSat writeExit :: forall a t. SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeExit w = mapM_ (addCommand w) (smtlib2exitCommand @a) setLogic :: SMTLib2Tweaks a => WriterConn t (Writer a) -> SMT2.Logic -> IO () setLogic w l = addCommand w $ SMT2.setLogic l setOption :: SMTLib2Tweaks a => WriterConn t (Writer a) -> Text -> Text -> IO () setOption w nm val = addCommand w $ SMT2.setOption nm val getVersion :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () getVersion w = writeCommand w $ SMT2.getVersion getName :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () getName w = writeCommand w $ SMT2.getName setProduceModels :: SMTLib2Tweaks a => WriterConn t (Writer a) -> Bool -> IO () setProduceModels w b = addCommand w $ SMT2.setProduceModels b writeGetValue :: SMTLib2Tweaks a => WriterConn t (Writer a) -> [Term] -> IO () writeGetValue w l = addCommandNoAck w $ SMT2.getValue l writeGetAbduct :: SMTLib2Tweaks a => WriterConn t (Writer a) -> Text -> Term -> IO () writeGetAbduct w nm p = addCommandNoAck w $ SMT2.getAbduct nm p writeGetAbductNext :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeGetAbductNext w = addCommandNoAck w SMT2.getAbductNext writeCheckSynth :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO () writeCheckSynth w = addCommandNoAck w SMT2.checkSynth parseBoolSolverValue :: MonadFail m => SExp -> m Bool parseBoolSolverValue (SAtom "true") = return True parseBoolSolverValue (SAtom "false") = return False parseBoolSolverValue s = do v <- parseBvSolverValue (knownNat @1) s return (if v == BV.zero knownNat then False else True) parseIntSolverValue :: MonadFail m => SExp -> m Integer parseIntSolverValue = \case SAtom v | [(i, "")] <- readDec (Text.unpack v) -> return i SApp ["-", x] -> negate <$> parseIntSolverValue x s -> fail $ "Could not parse solver value: " ++ show s parseRealSolverValue :: MonadFail m => SExp -> m Rational parseRealSolverValue (SAtom v) | Just (r,"") <- readDecimal (Text.unpack v) = return r parseRealSolverValue (SApp ["-", x]) = do negate <$> parseRealSolverValue x parseRealSolverValue (SApp ["/", x , y]) = do (/) <$> parseRealSolverValue x <*> parseRealSolverValue y parseRealSolverValue s = fail $ "Could not parse solver value: " ++ show s results of the right size , but ABC always gives hex results without leading zeros , so they may be larger or smaller than the actual size parseBvSolverValue :: MonadFail m => NatRepr w -> SExp -> m (BV.BV w) parseBvSolverValue w s | Just (Pair w' bv) <- parseBVLitHelper s = case w' `compareNat` w of NatLT zw -> return (BV.zext (addNat w' (addNat zw knownNat)) bv) NatEQ -> return bv NatGT _ -> return (BV.trunc w bv) | otherwise = fail $ "Could not parse bitvector solver value: " ++ show s natBV :: Natural -> Integer -> Pair NatRepr BV.BV natBV wNatural x = case mkNatRepr wNatural of Some w -> Pair w (BV.mkBV w x) parseBVLitHelper :: SExp -> Maybe (Pair NatRepr BV.BV) parseBVLitHelper (SAtom (Text.unpack -> ('#' : 'b' : n_str))) | [(n, "")] <- readBin n_str = Just $ natBV (fromIntegral (length n_str)) n parseBVLitHelper (SAtom (Text.unpack -> ('#' : 'x' : n_str))) | [(n, "")] <- readHex n_str = Just $ natBV (fromIntegral (length n_str * 4)) n parseBVLitHelper (SApp ["_", SAtom (Text.unpack -> ('b' : 'v' : n_str)), SAtom (Text.unpack -> w_str)]) | [(n, "")] <- readDec n_str, [(w, "")] <- readDec w_str = Just $ natBV w n parseBVLitHelper _ = Nothing parseStringSolverValue :: MonadFail m => SExp -> m Text parseStringSolverValue (SString t) | Just t' <- unescapeText t = return t' parseStringSolverValue x = fail ("Could not parse string solver value:\n " ++ show x) parseFloatSolverValue :: MonadFail m => FloatPrecisionRepr fpp -> SExp -> m (BV.BV (FloatPrecisionBits fpp)) parseFloatSolverValue (FloatingPointPrecisionRepr eb sb) s = do ParsedFloatResult sgn eb' expt sb' sig <- parseFloatLitHelper s case (eb `testEquality` eb', sb `testEquality` ((knownNat @1) `addNat` sb')) of (Just Refl, Just Refl) -> do Refl <- return $ plusComm eb' (knownNat @1) ( eb ' + 1 ) + sb ' ~ eb ' + ( 1 + sb ' ) Refl <- return $ plusAssoc eb' (knownNat @1) sb' return bv where bv = BV.concat (addNat (knownNat @1) eb) sb' (BV.concat knownNat eb sgn expt) sig _ -> fail $ "Unexpected float precision: " <> show eb' <> ", " <> show sb' data ParsedFloatResult = forall eb sb . ParsedFloatResult parseFloatLitHelper :: MonadFail m => SExp -> m ParsedFloatResult parseFloatLitHelper (SApp ["fp", sign_s, expt_s, scand_s]) | Just (Pair sign_w sign) <- parseBVLitHelper sign_s , Just Refl <- sign_w `testEquality` (knownNat @1) , Just (Pair eb expt) <- parseBVLitHelper expt_s , Just (Pair sb scand) <- parseBVLitHelper scand_s = return $ ParsedFloatResult sign eb expt sb scand parseFloatLitHelper s@(SApp ["_", SAtom (Text.unpack -> nm), SAtom (Text.unpack -> eb_s), SAtom (Text.unpack -> sb_s)]) | [(eb_n, "")] <- readDec eb_s, [(sb_n, "")] <- readDec sb_s , Some eb <- mkNatRepr eb_n , Some sb <- mkNatRepr (sb_n-1) = case nm of "+oo" -> return $ ParsedFloatResult (BV.zero knownNat) eb (BV.maxUnsigned eb) sb (BV.zero sb) "-oo" -> return $ ParsedFloatResult (BV.one knownNat) eb (BV.maxUnsigned eb) sb (BV.zero sb) "+zero" -> return $ ParsedFloatResult (BV.zero knownNat) eb (BV.zero eb) sb (BV.zero sb) "-zero" -> return $ ParsedFloatResult (BV.one knownNat) eb (BV.zero eb) sb (BV.zero sb) "NaN" -> return $ ParsedFloatResult (BV.zero knownNat) eb (BV.maxUnsigned eb) sb (BV.maxUnsigned sb) _ -> fail $ "Could not parse float solver value: " ++ show s parseFloatLitHelper s = fail $ "Could not parse float solver value: " ++ show s parseBvArraySolverValue :: (MonadFail m, 1 <= w, 1 <= v) => NatRepr w -> NatRepr v -> SExp -> m (Maybe (GroundArray (Ctx.SingleCtx (BaseBVType w)) (BaseBVType v))) parseBvArraySolverValue _ v (SApp [SApp ["as", "const", _], c]) = do c' <- parseBvSolverValue v c return . Just $ ArrayConcrete c' Map.empty parseBvArraySolverValue w v (SApp ["store", arr, idx, val]) = do arr' <- parseBvArraySolverValue w v arr case arr' of Just (ArrayConcrete base m) -> do idx' <- B.BVIndexLit w <$> parseBvSolverValue w idx val' <- parseBvSolverValue v val return . Just $ ArrayConcrete base (Map.insert (Ctx.empty Ctx.:> idx') val' m) _ -> return Nothing parseBvArraySolverValue _ _ _ = return Nothing parseFnModel :: sym ~ B.ExprBuilder t st fs => sym -> WriterConn t h -> [I.SomeSymFn sym] -> SExp -> IO (MapF (I.SymFnWrapper sym) (I.SymFnWrapper sym)) parseFnModel = parseFns parseDefineFun parseFnValues :: sym ~ B.ExprBuilder t st fs => sym -> WriterConn t h -> [I.SomeSymFn sym] -> SExp -> IO (MapF (I.SymFnWrapper sym) (I.SymFnWrapper sym)) parseFnValues = parseFns parseLambda parseFns :: sym ~ B.ExprBuilder t st fs => (sym -> SExp -> IO (Text, I.SomeSymFn sym)) -> sym -> WriterConn t h -> [I.SomeSymFn sym] -> SExp -> IO (MapF (I.SymFnWrapper sym) (I.SymFnWrapper sym)) parseFns parse_model_fn sym conn uninterp_fns sexp = do fn_name_bimap <- cacheLookupFnNameBimap conn $ map (\(I.SomeSymFn fn) -> B.SomeExprSymFn fn) uninterp_fns defined_fns <- case sexp of SApp sexps -> Map.fromList <$> mapM (parse_model_fn sym) sexps _ -> fail $ "Could not parse model response: " ++ show sexp MapF.fromList <$> mapM (\(I.SomeSymFn uninterp_fn) -> if | Just nm <- Bimap.lookup (B.SomeExprSymFn uninterp_fn) fn_name_bimap , Just (I.SomeSymFn defined_fn) <- Map.lookup nm defined_fns , Just Refl <- testEquality (I.fnArgTypes uninterp_fn) (I.fnArgTypes defined_fn) , Just Refl <- testEquality (I.fnReturnType uninterp_fn) (I.fnReturnType defined_fn) -> return $ MapF.Pair (I.SymFnWrapper uninterp_fn) (I.SymFnWrapper defined_fn) | otherwise -> fail $ "Could not find model for function: " ++ show uninterp_fn) uninterp_fns parseDefineFun :: I.IsSymExprBuilder sym => sym -> SExp -> IO (Text, I.SomeSymFn sym) parseDefineFun sym sexp = case sexp of SApp ["define-fun", SAtom nm, SApp params_sexp, _ret_type_sexp , body_sexp] -> do fn <- parseFn sym nm params_sexp body_sexp return (nm, fn) _ -> fail $ "unexpected sexp, expected define-fun, found " ++ show sexp parseLambda :: I.IsSymExprBuilder sym => sym -> SExp -> IO (Text, I.SomeSymFn sym) parseLambda sym sexp = case sexp of SApp [SAtom nm, SApp ["lambda", SApp params_sexp, body_sexp]] -> do fn <- parseFn sym nm params_sexp body_sexp return (nm, fn) _ -> fail $ "unexpected sexp, expected lambda, found " ++ show sexp parseFn :: I.IsSymExprBuilder sym => sym -> Text -> [SExp] -> SExp -> IO (I.SomeSymFn sym) parseFn sym nm params_sexp body_sexp = do (nms, vars) <- unzip <$> mapM (parseVar sym) params_sexp case Ctx.fromList vars of Some vars_assign -> do let let_env = HashMap.fromList $ zip nms $ map (mapSome $ I.varExpr sym) vars proc_res <- runProcessor (ProcessorEnv { procSym = sym, procLetEnv = let_env }) $ parseExpr sym body_sexp Some body_expr <- either fail return proc_res I.SomeSymFn <$> I.definedFn sym (I.safeSymbol $ Text.unpack nm) vars_assign body_expr I.NeverUnfold parseVar :: I.IsSymExprBuilder sym => sym -> SExp -> IO (Text, Some (I.BoundVar sym)) parseVar sym sexp = case sexp of SApp [SAtom nm, tp_sexp] -> do Some tp <- parseType tp_sexp var <- liftIO $ I.freshBoundVar sym (I.safeSymbol $ Text.unpack nm) tp return (nm, Some var) _ -> fail $ "unexpected variable " ++ show sexp parseType :: SExp -> IO (Some BaseTypeRepr) parseType sexp = case sexp of "Bool" -> return $ Some BaseBoolRepr "Int" -> return $ Some BaseIntegerRepr "Real" -> return $ Some BaseRealRepr SApp ["_", "BitVec", SAtom (Text.unpack -> m_str)] | [(m_n, "")] <- readDec m_str , Some m <- mkNatRepr m_n , Just LeqProof <- testLeq (knownNat @1) m -> return $ Some $ BaseBVRepr m SApp ["_", "FloatingPoint", SAtom (Text.unpack -> eb_str), SAtom (Text.unpack -> sb_str)] | [(eb_n, "")] <- readDec eb_str , Some eb <- mkNatRepr eb_n , Just LeqProof <- testLeq (knownNat @2) eb , [(sb_n, "")] <- readDec sb_str , Some sb <- mkNatRepr sb_n , Just LeqProof <- testLeq (knownNat @2) sb -> return $ Some $ BaseFloatRepr $ FloatingPointPrecisionRepr eb sb SApp ["Array", idx_tp_sexp, val_tp_sexp] -> do Some idx_tp <- parseType idx_tp_sexp Some val_tp <- parseType val_tp_sexp return $ Some $ BaseArrayRepr (Ctx.singleton idx_tp) val_tp _ -> fail $ "unexpected type " ++ show sexp | Stores a NatRepr along with proof that its type parameter is a bitvector of that length . Used for easy pattern matching on the LHS of a binding in a data BVProof tp where BVProof :: forall n . (1 <= n) => NatRepr n -> BVProof (BaseBVType n) getBVProof :: (I.IsExpr ex, MonadError String m) => ex tp -> m (BVProof tp) getBVProof expr = case I.exprType expr of BaseBVRepr n -> return $ BVProof n t -> throwError $ "expected BV, found " ++ show t Code is copy - pasted and adapted from ` What4.Serialize . ` , see data Op sym where Op1 :: Ctx.Assignment BaseTypeRepr (Ctx.EmptyCtx Ctx.::> arg1) -> (sym -> I.SymExpr sym arg1 -> IO (I.SymExpr sym ret)) -> Op sym Op2 :: Ctx.Assignment BaseTypeRepr (Ctx.EmptyCtx Ctx.::> arg1 Ctx.::> arg2) -> Maybe Assoc -> (sym -> I.SymExpr sym arg1 -> I.SymExpr sym arg2 -> IO (I.SymExpr sym ret)) -> Op sym | Encapsulating type for a unary operation that takes one bitvector and returns another ( in IO ) . BVOp1 :: (forall w . (1 <= w) => sym -> I.SymBV sym w -> IO (I.SymBV sym w)) -> Op sym | with a bitvector return type , e.g. , addition or bitwise operations . BVOp2 :: Maybe Assoc -> (forall w . (1 <= w) => sym -> I.SymBV sym w -> I.SymBV sym w -> IO (I.SymBV sym w)) -> Op sym BVComp2 :: (forall w . (1 <= w) => sym -> I.SymBV sym w -> I.SymBV sym w -> IO (I.Pred sym)) -> Op sym data Assoc = RightAssoc | LeftAssoc newtype Processor sym a = Processor (ExceptT String (ReaderT (ProcessorEnv sym) IO) a) deriving (Functor, Applicative, Monad, MonadIO, MonadError String, MonadReader (ProcessorEnv sym)) data ProcessorEnv sym = ProcessorEnv { procSym :: sym , procLetEnv :: HashMap Text (Some (I.SymExpr sym)) } runProcessor :: ProcessorEnv sym -> Processor sym a -> IO (Either String a) runProcessor env (Processor action) = runReaderT (runExceptT action) env opTable :: I.IsSymExprBuilder sym => HashMap Text (Op sym) opTable = HashMap.fromList Boolean ops [ ("not", Op1 knownRepr I.notPred) , ("=>", Op2 knownRepr (Just RightAssoc) I.impliesPred) , ("and", Op2 knownRepr (Just LeftAssoc) I.andPred) , ("or", Op2 knownRepr (Just LeftAssoc) I.orPred) , ("xor", Op2 knownRepr (Just LeftAssoc) I.xorPred) Integer ops , ("-", Op2 knownRepr (Just LeftAssoc) I.intSub) , ("+", Op2 knownRepr (Just LeftAssoc) I.intAdd) , ("*", Op2 knownRepr (Just LeftAssoc) I.intMul) , ("div", Op2 knownRepr (Just LeftAssoc) I.intDiv) , ("mod", Op2 knownRepr Nothing I.intMod) , ("abs", Op1 knownRepr I.intAbs) , ("<=", Op2 knownRepr Nothing I.intLe) , ("<", Op2 knownRepr Nothing I.intLt) , (">=", Op2 knownRepr Nothing $ \sym arg1 arg2 -> I.intLe sym arg2 arg1) , (">", Op2 knownRepr Nothing $ \sym arg1 arg2 -> I.intLt sym arg2 arg1) Bitvector ops , ("bvnot", BVOp1 I.bvNotBits) , ("bvneg", BVOp1 I.bvNeg) , ("bvand", BVOp2 (Just LeftAssoc) I.bvAndBits) , ("bvor", BVOp2 (Just LeftAssoc) I.bvOrBits) , ("bvxor", BVOp2 (Just LeftAssoc) I.bvXorBits) , ("bvadd", BVOp2 (Just LeftAssoc) I.bvAdd) , ("bvsub", BVOp2 (Just LeftAssoc) I.bvSub) , ("bvmul", BVOp2 (Just LeftAssoc) I.bvMul) , ("bvudiv", BVOp2 Nothing I.bvUdiv) , ("bvurem", BVOp2 Nothing I.bvUrem) , ("bvshl", BVOp2 Nothing I.bvShl) , ("bvlshr", BVOp2 Nothing I.bvLshr) , ("bvsdiv", BVOp2 Nothing I.bvSdiv) , ("bvsrem", BVOp2 Nothing I.bvSrem) , ("bvashr", BVOp2 Nothing I.bvAshr) , ("bvult", BVComp2 I.bvUlt) , ("bvule", BVComp2 I.bvUle) , ("bvugt", BVComp2 I.bvUgt) , ("bvuge", BVComp2 I.bvUge) , ("bvslt", BVComp2 I.bvSlt) , ("bvsle", BVComp2 I.bvSle) , ("bvsgt", BVComp2 I.bvSgt) , ("bvsge", BVComp2 I.bvSge) ] parseExpr :: forall sym . I.IsSymExprBuilder sym => sym -> SExp -> Processor sym (Some (I.SymExpr sym)) parseExpr sym sexp = case sexp of "true" -> return $ Some $ I.truePred sym "false" -> return $ Some $ I.falsePred sym _ | Just i <- parseIntSolverValue sexp -> liftIO $ Some <$> I.intLit sym i | Just (Pair w bv) <- parseBVLitHelper sexp , Just LeqProof <- testLeq (knownNat @1) w -> liftIO $ Some <$> I.bvLit sym w bv SAtom nm -> do env <- asks procLetEnv case HashMap.lookup nm env of Just expr -> return $ expr Nothing -> throwError "" SApp ["let", SApp bindings_sexp, body_sexp] -> do let_env <- HashMap.fromList <$> mapM (\case SApp [SAtom nm, expr_sexp] -> do Some expr <- parseExpr sym expr_sexp return (nm, Some expr) _ -> throwError "") bindings_sexp local (\prov_env -> prov_env { procLetEnv = HashMap.union let_env (procLetEnv prov_env) }) $ parseExpr sym body_sexp SApp ["=", arg1, arg2] -> do Some arg1_expr <- parseExpr sym arg1 Some arg2_expr <- parseExpr sym arg2 case testEquality (I.exprType arg1_expr) (I.exprType arg2_expr) of Just Refl -> liftIO (Some <$> I.isEq sym arg1_expr arg2_expr) Nothing -> throwError "" SApp ["ite", arg1, arg2, arg3] -> do Some arg1_expr <- parseExpr sym arg1 Some arg2_expr <- parseExpr sym arg2 Some arg3_expr <- parseExpr sym arg3 case I.exprType arg1_expr of I.BaseBoolRepr -> case testEquality (I.exprType arg2_expr) (I.exprType arg3_expr) of Just Refl -> liftIO (Some <$> I.baseTypeIte sym arg1_expr arg2_expr arg3_expr) Nothing -> throwError "" _ -> throwError "" SApp ["concat", arg1, arg2] -> do Some arg1_expr <- parseExpr sym arg1 Some arg2_expr <- parseExpr sym arg2 BVProof{} <- getBVProof arg1_expr BVProof{} <- getBVProof arg2_expr liftIO $ Some <$> I.bvConcat sym arg1_expr arg2_expr SApp ((SAtom operator) : operands) -> case HashMap.lookup operator (opTable @sym) of Just (Op1 arg_types fn) -> do args <- mapM (parseExpr sym) operands exprAssignment arg_types args >>= \case Ctx.Empty Ctx.:> arg1 -> liftIO (Some <$> fn sym arg1) Just (Op2 arg_types _ fn) -> do args <- mapM (parseExpr sym) operands exprAssignment arg_types args >>= \case Ctx.Empty Ctx.:> arg1 Ctx.:> arg2 -> liftIO (Some <$> fn sym arg1 arg2) Just (BVOp1 op) -> do Some arg_expr <- readOneArg sym operands BVProof{} <- getBVProof arg_expr liftIO $ Some <$> op sym arg_expr Just (BVOp2 _ op) -> do (Some arg1, Some arg2) <- readTwoArgs sym operands BVProof m <- prefixError "in arg 1: " $ getBVProof arg1 BVProof n <- prefixError "in arg 2: " $ getBVProof arg2 case testEquality m n of Just Refl -> liftIO (Some <$> op sym arg1 arg2) Nothing -> throwError $ printf "arguments to %s must be the same length, \ \but arg 1 has length %s \ \and arg 2 has length %s" operator (show m) (show n) Just (BVComp2 op) -> do (Some arg1, Some arg2) <- readTwoArgs sym operands BVProof m <- prefixError "in arg 1: " $ getBVProof arg1 BVProof n <- prefixError "in arg 2: " $ getBVProof arg2 case testEquality m n of Just Refl -> liftIO (Some <$> op sym arg1 arg2) Nothing -> throwError $ printf "arguments to %s must be the same length, \ \but arg 1 has length %s \ \and arg 2 has length %s" operator (show m) (show n) _ -> throwError "" _ -> throwError "" readOneArg :: I.IsSymExprBuilder sym => sym -> [SExp] -> Processor sym (Some (I.SymExpr sym)) readOneArg sym operands = do args <- mapM (parseExpr sym) operands case args of [arg] -> return arg _ -> throwError $ printf "expecting 1 argument, got %d" (length args) | Verify a list of arguments has two arguments and return readTwoArgs :: I.IsSymExprBuilder sym => sym ->[SExp] -> Processor sym (Some (I.SymExpr sym), Some (I.SymExpr sym)) readTwoArgs sym operands = do args <- mapM (parseExpr sym) operands case args of [arg1, arg2] -> return (arg1, arg2) _ -> throwError $ printf "expecting 2 arguments, got %d" (length args) exprAssignment :: forall sym ctx ex . (I.IsSymExprBuilder sym, I.IsExpr ex) => Ctx.Assignment BaseTypeRepr ctx -> [Some ex] -> Processor sym (Ctx.Assignment ex ctx) exprAssignment tpAssns exs = do Some exsAsn <- return $ Ctx.fromList exs exsRepr <- return $ fmapFC I.exprType exsAsn case testEquality exsRepr tpAssns of Just Refl -> return exsAsn Nothing -> throwError $ ++ "\nExpected: " ++ show tpAssns ++ "\nGot: " ++ show exsRepr prefixError :: (Monoid e, MonadError e m) => e -> m a -> m a prefixError prefix act = catchError act (throwError . mappend prefix) | This is an interactive session with an SMT solver data Session t a = Session { sessionWriter :: !(WriterConn t (Writer a)) , sessionResponse :: !(Streams.InputStream Text) } runGetValue :: SMTLib2Tweaks a => Session t a -> Term -> IO SExp runGetValue s e = do writeGetValue (sessionWriter s) [ e ] let valRsp = \case AckSuccessSExp (SApp [SApp [_, b]]) -> Just b _ -> Nothing getLimitedSolverResponse "get value" valRsp (sessionWriter s) (SMT2.getValue [e]) | runGetAbducts s nm p n , returns n formulas ( as strings ) the disjunction of which entails p ( along with all runGetAbducts :: SMTLib2Tweaks a => Session t a -> Int -> Text -> Term -> IO [String] runGetAbducts s n nm p = if (n > 0) then do writeGetAbduct (sessionWriter s) nm p let valRsp = \x -> case x of SMT solver returns ` ( define - fun nm ( ) ) ` where X is the abduct , we discard everything but the abduct AckSuccessSExp (SApp (_ : _ : _ : _ : abduct)) -> Just $ Data.String.unwords (map sExpToString abduct) _ -> Nothing get first abduct using the get - abduct command abd1 <- getLimitedSolverResponse "get abduct" valRsp (sessionWriter s) (SMT2.getAbduct nm p) if (n > 1) then do let rest = n - 1 replicateM_ rest $ writeGetAbductNext (sessionWriter s) abdRest <- forM [1..rest] $ \_ -> getLimitedSolverResponse "get abduct next" valRsp (sessionWriter s) (SMT2.getAbduct nm p) return (abd1:abdRest) else return [abd1] else return [] runCheckSat :: forall b t a. SMTLib2Tweaks b => Session t b -> (SatResult (GroundEvalFn t, Maybe (ExprRangeBindings t)) () -> IO a) -> IO a runCheckSat s doEval = do let w = sessionWriter s r = sessionResponse s addCommands w (checkCommands w) res <- smtSatResult w w case res of Unsat x -> doEval (Unsat x) Unknown -> doEval Unknown Sat _ -> do evalFn <- smtExprGroundEvalFn w (smtEvalFuns w r) doEval (Sat (evalFn, Nothing)) instance SMTLib2Tweaks a => SMTReadWriter (Writer a) where smtEvalFuns w s = smtLibEvalFuns Session { sessionWriter = w , sessionResponse = s } smtSatResult p s = let satRsp = \case AckSat -> Just $ Sat () AckUnsat -> Just $ Unsat () AckUnknown -> Just Unknown _ -> Nothing in getLimitedSolverResponse "sat result" satRsp s (head $ reverse $ checkCommands p) smtUnsatAssumptionsResult p s = let unsatAssumpRsp = \case AckSuccessSExp (asNegAtomList -> Just as) -> Just as _ -> Nothing cmd = getUnsatAssumptionsCommand p in getLimitedSolverResponse "unsat assumptions" unsatAssumpRsp s cmd smtUnsatCoreResult p s = let unsatCoreRsp = \case AckSuccessSExp (asAtomList -> Just nms) -> Just nms _ -> Nothing cmd = getUnsatCoreCommand p in getLimitedSolverResponse "unsat core" unsatCoreRsp s cmd smtAbductResult p s nm t = let abductRsp = \case AckSuccessSExp (SApp (_ : _ : _ : _ : abduct)) -> Just $ Data.String.unwords (map sExpToString abduct) _ -> Nothing cmd = getAbductCommand p nm t in getLimitedSolverResponse "get abduct" abductRsp s cmd smtAbductNextResult p s = let abductRsp = \case AckSuccessSExp (SApp (_ : _ : _ : _ : abduct)) -> Just $ Data.String.unwords (map sExpToString abduct) _ -> Nothing cmd = getAbductNextCommand p in getLimitedSolverResponse "get abduct next" abductRsp s cmd smtAckResult :: AcknowledgementAction t (Writer a) smtAckResult = AckAction $ getLimitedSolverResponse "get ack" $ \case AckSuccess -> Just () _ -> Nothing smtLibEvalFuns :: forall t a. SMTLib2Tweaks a => Session t a -> SMTEvalFunctions (Writer a) smtLibEvalFuns s = SMTEvalFunctions { smtEvalBool = evalBool , smtEvalBV = evalBV , smtEvalReal = evalReal , smtEvalFloat = evalFloat , smtEvalBvArray = Just (SMTEvalBVArrayWrapper evalBvArray) , smtEvalString = evalStr } where evalBool tm = parseBoolSolverValue =<< runGetValue s tm evalReal tm = parseRealSolverValue =<< runGetValue s tm evalStr tm = parseStringSolverValue =<< runGetValue s tm evalBV :: NatRepr w -> Term -> IO (BV.BV w) evalBV w tm = parseBvSolverValue w =<< runGetValue s tm evalFloat :: FloatPrecisionRepr fpp -> Term -> IO (BV.BV (FloatPrecisionBits fpp)) evalFloat fpp tm = parseFloatSolverValue fpp =<< runGetValue s tm evalBvArray :: SMTEvalBVArrayFn (Writer a) w v evalBvArray w v tm = parseBvArraySolverValue w v =<< runGetValue s tm class (SMTLib2Tweaks a, Show a) => SMTLib2GenericSolver a where defaultSolverPath :: a -> B.ExprBuilder t st fs -> IO FilePath defaultSolverArgs :: a -> B.ExprBuilder t st fs -> IO [String] defaultFeatures :: a -> ProblemFeatures getErrorBehavior :: a -> WriterConn t (Writer a) -> IO ErrorBehavior getErrorBehavior _ _ = return ImmediateExit supportsResetAssertions :: a -> Bool supportsResetAssertions _ = False setDefaultLogicAndOptions :: WriterConn t (Writer a) -> IO() newDefaultWriter :: a -> AcknowledgementAction t (Writer a) -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -> B.ExprBuilder t st fs -> Streams.OutputStream Text -> Streams.InputStream Text -> IO (WriterConn t (Writer a)) newDefaultWriter solver ack feats strictOpt sym h in_h = do let cfg = I.getConfiguration sym strictness <- parserStrictness strictOpt strictSMTParsing cfg newWriter solver h in_h ack strictness (show solver) True feats True =<< B.getSymbolVarBimap sym withSolver :: a -> AcknowledgementAction t (Writer a) -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -> B.ExprBuilder t st fs -> FilePath -> LogData -> (Session t a -> IO b) -> IO b withSolver solver ack feats strictOpt sym path logData action = do args <- defaultSolverArgs solver sym withProcessHandles path args Nothing $ \hdls@(in_h, out_h, err_h, _ph) -> do (in_stream, out_stream, err_reader) <- demuxProcessHandles in_h out_h err_h (fmap (\x -> ("; ", x)) $ logHandle logData) writer <- newDefaultWriter solver ack feats strictOpt sym in_stream out_stream let s = Session { sessionWriter = writer , sessionResponse = out_stream } setDefaultLogicAndOptions writer r <- action s writeExit writer stopHandleReader err_reader ec <- cleanupProcess hdls case ec of Exit.ExitSuccess -> return r Exit.ExitFailure exit_code -> fail $ show solver ++ " exited with unexpected code: " ++ show exit_code runSolverInOverride :: a -> AcknowledgementAction t (Writer a) -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -> B.ExprBuilder t st fs -> LogData -> [B.BoolExpr t] -> (SatResult (GroundEvalFn t, Maybe (ExprRangeBindings t)) () -> IO b) -> IO b runSolverInOverride solver ack feats strictOpt sym logData predicates cont = do I.logSolverEvent sym (I.SolverStartSATQuery $ I.SolverStartSATQueryRec { I.satQuerySolverName = show solver , I.satQueryReason = logReason logData }) path <- defaultSolverPath solver sym withSolver solver ack feats strictOpt sym path (logData{logVerbosity=2}) $ \session -> do forM_ predicates (SMTWriter.assume (sessionWriter session)) Run check SAT and get the model back . runCheckSat session $ \result -> do I.logSolverEvent sym (I.SolverEndSATQuery $ I.SolverEndSATQueryRec { I.satQueryResult = forgetModelAndCore result , I.satQueryError = Nothing }) cont result | A default method for writing SMTLib2 problems without any writeDefaultSMT2 :: SMTLib2Tweaks a => a -> String -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -> B.ExprBuilder t st fs -> IO.Handle -> [B.BoolExpr t] -> IO () writeDefaultSMT2 a nm feat strictOpt sym h ps = do c <- defaultFileWriter a nm feat strictOpt sym h setProduceModels c True forM_ ps (SMTWriter.assume c) writeCheckSat c writeExit c defaultFileWriter :: SMTLib2Tweaks a => a -> String -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -> B.ExprBuilder t st fs -> IO.Handle -> IO (WriterConn t (Writer a)) defaultFileWriter a nm feat strictOpt sym h = do bindings <- B.getSymbolVarBimap sym str <- Streams.encodeUtf8 =<< Streams.handleToOutputStream h null_in <- Streams.nullInput let cfg = I.getConfiguration sym strictness <- parserStrictness strictOpt strictSMTParsing cfg newWriter a str null_in nullAcknowledgementAction strictness nm True feat True bindings startSolver :: SMTLib2GenericSolver a => a -> AcknowledgementAction t (Writer a) -> SolverGoalTimeout -> ProblemFeatures -> Maybe (CFG.ConfigOption I.BaseBoolType) -> Maybe IO.Handle -> B.ExprBuilder t st fs -> IO (SolverProcess t (Writer a)) startSolver solver ack setup tmout feats strictOpt auxOutput sym = do path <- defaultSolverPath solver sym args <- defaultSolverArgs solver sym hdls@(in_h, out_h, err_h, ph) <- startProcess path args Nothing (in_stream, out_stream, err_reader) <- demuxProcessHandles in_h out_h err_h (fmap (\x -> ("; ", x)) auxOutput) writer <- newDefaultWriter solver ack feats strictOpt sym in_stream out_stream setup writer errBeh <- getErrorBehavior solver writer earlyUnsatRef <- newIORef Nothing unless (supportsResetAssertions solver) (addCommand writer (SMT2.push 1)) return $! SolverProcess { solverConn = writer , solverCleanupCallback = cleanupProcess hdls , solverStderr = err_reader , solverHandle = ph , solverErrorBehavior = errBeh , solverEvalFuns = smtEvalFuns writer out_stream , solverLogFn = I.logSolverEvent sym , solverName = show solver , solverEarlyUnsat = earlyUnsatRef , solverSupportsResetAssertions = supportsResetAssertions solver , solverGoalTimeout = tmout } shutdownSolver :: SMTLib2GenericSolver a => a -> SolverProcess t (Writer a) -> IO (Exit.ExitCode, Lazy.Text) shutdownSolver _solver p = do writeExit (solverConn p) txt <- readAllLines (solverStderr p) stopHandleReader (solverStderr p) ec <- solverCleanupCallback p return (ec,txt) defaultSolverBounds :: Map Text SolverBounds defaultSolverBounds = Map.fromList $(computeDefaultSolverBounds) data SolverVersionCheckError = UnparseableVersion Versions.ParsingError ppSolverVersionCheckError :: SolverVersionCheckError -> PP.Doc ann ppSolverVersionCheckError err = PP.vsep [ "Unexpected error while checking solver version:" , case err of UnparseableVersion parseErr -> PP.hsep [ "Couldn't parse solver version number:" , PP.viaShow parseErr ] ] data SolverVersionError = SolverVersionError { vBounds :: SolverBounds , vActual :: Version } ppSolverVersionError :: SolverVersionError -> PP.Doc ann ppSolverVersionError err = PP.vsep [ "Solver did not meet version bound restrictions:" , "Lower bound (inclusive):" PP.<+> na (lower (vBounds err)) , "Upper bound (non-inclusive):" PP.<+> na (upper (vBounds err)) , "Actual version:" PP.<+> PP.viaShow (vActual err) ] where na (Just s) = PP.viaShow s na Nothing = "n/a" nameResult :: WriterConn t a -> IO Text nameResult conn = getLimitedSolverResponse "solver name" (\case RspName nm -> Just nm _ -> Nothing ) conn SMT2.getName queryErrorBehavior :: SMTLib2Tweaks a => WriterConn t (Writer a) -> IO ErrorBehavior queryErrorBehavior conn = do let cmd = SMT2.getErrorBehavior writeCommand conn cmd getLimitedSolverResponse "error behavior" (\case RspErrBehavior bh -> case bh of "continued-execution" -> return ContinueOnError "immediate-exit" -> return ImmediateExit _ -> throw $ SMTLib2ResponseUnrecognized cmd bh _ -> Nothing ) conn cmd versionResult :: WriterConn t a -> IO Text versionResult conn = getLimitedSolverResponse "solver version" (\case RspVersion v -> Just v _ -> Nothing ) conn SMT2.getVersion checkSolverVersion' :: SMTLib2Tweaks solver => Map Text SolverBounds -> SolverProcess scope (Writer solver) -> IO (Either SolverVersionCheckError (Maybe SolverVersionError)) checkSolverVersion' boundsMap proc = let conn = solverConn proc name = smtWriterName conn done = pure (Right Nothing) verr bnds actual = pure (Right (Just (SolverVersionError bnds actual))) in case Map.lookup (Text.pack name) boundsMap of Nothing -> done Just bnds -> do getVersion conn res <- versionResult $ solverConn proc case Versions.version res of Left e -> pure (Left (UnparseableVersion e)) Right actualVer -> case (lower bnds, upper bnds) of (Nothing, Nothing) -> done (Nothing, Just maxVer) -> if actualVer < maxVer then done else verr bnds actualVer (Just minVer, Nothing) -> if minVer <= actualVer then done else verr bnds actualVer (Just minVer, Just maxVer) -> if minVer <= actualVer && actualVer < maxVer then done else verr bnds actualVer checkSolverVersion :: SMTLib2Tweaks solver => SolverProcess scope (Writer solver) -> IO (Either SolverVersionCheckError (Maybe SolverVersionError)) checkSolverVersion = checkSolverVersion' defaultSolverBounds
3df1d42eb1a973ecca09133a7d2d282ecc8375aa1fbeaf887e3dbeb5c2277ca3
xtdb/core2
tpch_sql_test.clj
(ns core2.sql.tpch-sql-test (:require [clojure.java.io :as io] [clojure.test :as t] [core2.sql :as sql] core2.sql-test))
null
https://raw.githubusercontent.com/xtdb/core2/3adeb391ca4dd73a3f79faba8024289376597d23/src/test/clojure/core2/sql/tpch_sql_test.clj
clojure
(ns core2.sql.tpch-sql-test (:require [clojure.java.io :as io] [clojure.test :as t] [core2.sql :as sql] core2.sql-test))
ee868aebb7edfd0bdeb507e27393e628b22d8a2d15f83c702f7bccb1360e3439
sbcl/sbcl
simd-pack.pure.lisp
;;;; Potentially side-effectful tests of the simd-pack infrastructure. This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; While most of SBCL is derived from the CMU CL system , the test ;;;; files (like this one) were written from scratch after the fork from CMU CL . ;;;; ;;;; This software is in the public domain and is provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for ;;;; more information. #-sb-simd-pack (invoke-restart 'run-tests::skip-file) (defun make-constant-packs () (values (sb-kernel:%make-simd-pack-ub64 1 2) (sb-kernel:%make-simd-pack-ub32 0 0 0 0) (sb-kernel:%make-simd-pack-ub64 (ldb (byte 64 0) -1) (ldb (byte 64 0) -1)) (sb-kernel:%make-simd-pack-single 1f0 2f0 3f0 4f0) (sb-kernel:%make-simd-pack-single 0f0 0f0 0f0 0f0) (sb-kernel:%make-simd-pack-single (sb-kernel:make-single-float -1) (sb-kernel:make-single-float -1) (sb-kernel:make-single-float -1) (sb-kernel:make-single-float -1)) (sb-kernel:%make-simd-pack-double 1d0 2d0) (sb-kernel:%make-simd-pack-double 0d0 0d0) (sb-kernel:%make-simd-pack-double (sb-kernel:make-double-float -1 (ldb (byte 32 0) -1)) (sb-kernel:make-double-float -1 (ldb (byte 32 0) -1))))) (with-test (:name :compile-simd-pack) (multiple-value-bind (i i0 i-1 f f0 f-1 d d0 d-1) (make-constant-packs) (loop for (lo hi) in (list '(1 2) '(0 0) (list (ldb (byte 64 0) -1) (ldb (byte 64 0) -1))) for pack in (list i i0 i-1) do (assert (eql lo (sb-kernel:%simd-pack-low pack))) (assert (eql hi (sb-kernel:%simd-pack-high pack)))) (loop for expected in (list '(1f0 2f0 3f0 4f0) '(0f0 0f0 0f0 0f0) (make-list 4 :initial-element (sb-kernel:make-single-float -1))) for pack in (list f f0 f-1) do (assert (every #'eql expected (multiple-value-list (sb-kernel:%simd-pack-singles pack))))) (loop for expected in (list '(1d0 2d0) '(0d0 0d0) (make-list 2 :initial-element (sb-kernel:make-double-float -1 (ldb (byte 32 0) -1)))) for pack in (list d d0 d-1) do (assert (every #'eql expected (multiple-value-list (sb-kernel:%simd-pack-doubles pack))))))) (with-test (:name (simd-pack print :smoke)) (let ((packs (multiple-value-list (make-constant-packs)))) (flet ((print-them (expect) (dolist (pack packs) (flet ((do-it () (with-output-to-string (stream) (write pack :stream stream :pretty t :escape nil)))) (case expect (print-not-readable (assert-error (do-it) print-not-readable)) (t (do-it))))))) ;; Default (print-them t) Readably (let ((*print-readably* t) (*read-eval* t)) (print-them t)) ;; Want readably but can't without *READ-EVAL*. (let ((*print-readably* t) (*read-eval* nil)) (print-them 'print-not-readable))))) (defvar *tmp-filename* (scratch-file-name)) (defvar *pack*) (with-test (:name :load-simd-pack-int) (with-open-file (s *tmp-filename* :direction :output :if-exists :supersede :if-does-not-exist :create) (print '(setq *pack* (sb-kernel:%make-simd-pack-ub64 2 4)) s)) (let (tmp-fasl) (unwind-protect (progn (setq tmp-fasl (compile-file *tmp-filename*)) (let ((*pack* nil)) (load tmp-fasl) (assert (typep *pack* '(sb-kernel:simd-pack (unsigned-byte 64)))) (assert (= 2 (sb-kernel:%simd-pack-low *pack*))) (assert (= 4 (sb-kernel:%simd-pack-high *pack*))))) (when tmp-fasl (delete-file tmp-fasl)) (delete-file *tmp-filename*)))) (with-test (:name :load-simd-pack-single) (with-open-file (s *tmp-filename* :direction :output :if-exists :supersede :if-does-not-exist :create) (print '(setq *pack* (sb-kernel:%make-simd-pack-single 1f0 2f0 3f0 4f0)) s)) (let (tmp-fasl) (unwind-protect (progn (setq tmp-fasl (compile-file *tmp-filename*)) (let ((*pack* nil)) (load tmp-fasl) (assert (typep *pack* '(sb-kernel:simd-pack single-float))) (assert (equal (multiple-value-list (sb-kernel:%simd-pack-singles *pack*)) '(1f0 2f0 3f0 4f0))))) (when tmp-fasl (delete-file tmp-fasl)) (delete-file *tmp-filename*)))) (with-test (:name :load-simd-pack-double) (with-open-file (s *tmp-filename* :direction :output :if-exists :supersede :if-does-not-exist :create) (print '(setq *pack* (sb-kernel:%make-simd-pack-double 1d0 2d0)) s)) (let (tmp-fasl) (unwind-protect (progn (setq tmp-fasl (compile-file *tmp-filename*)) (let ((*pack* nil)) (load tmp-fasl) (assert (typep *pack* '(sb-kernel:simd-pack double-float))) (assert (equal (multiple-value-list (sb-kernel:%simd-pack-doubles *pack*)) '(1d0 2d0))))) (when tmp-fasl (delete-file tmp-fasl)) (delete-file *tmp-filename*)))) (with-test (:name (simd-pack subtypep :smoke)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 8)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 16)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 32)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 64)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 8)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 16)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 32)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 64)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack single-float) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack double-float) 'simd-pack)) (assert-tri-eq nil t (subtypep 'simd-pack '(simd-pack (unsigned-byte 64)))) (assert-tri-eq nil t (subtypep 'simd-pack '(simd-pack single-float))) (assert-tri-eq nil t (subtypep 'simd-pack '(simd-pack double-float))) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 64)) '(or (simd-pack (unsigned-byte 64)) (simd-pack single-float)))) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 64)) '(or (simd-pack (unsigned-byte 64)) (simd-pack double-float)))) (assert-tri-eq nil t (subtypep '(simd-pack (unsigned-byte 64)) '(or (simd-pack single-float) (simd-pack double-float)))) (assert-tri-eq nil t (subtypep '(or (simd-pack (unsigned-byte 64)) (simd-pack single-float)) '(simd-pack (unsigned-byte 64)))) (assert-tri-eq nil t (subtypep '(or (simd-pack (unsigned-byte 64)) (simd-pack double-float)) '(simd-pack (unsigned-byte 64)))) (assert-tri-eq nil t (subtypep '(or (simd-pack single-float) (simd-pack double-float)) '(simd-pack (unsigned-byte 64))))) (with-test (:name (simd-pack :ctype-unparse :smoke)) (flet ((unparsed (s) (sb-kernel:type-specifier (sb-kernel:specifier-type s)))) (assert (equal (unparsed 'simd-pack) 'simd-pack)) (assert (equal (unparsed '(simd-pack (unsigned-byte 8))) '(simd-pack (unsigned-byte 8)))) (assert (equal (unparsed '(simd-pack (unsigned-byte 16))) '(simd-pack (unsigned-byte 16)))) (assert (equal (unparsed '(simd-pack (unsigned-byte 32))) '(simd-pack (unsigned-byte 32)))) (assert (equal (unparsed '(simd-pack (unsigned-byte 64))) '(simd-pack (unsigned-byte 64)))) (assert (equal (unparsed '(simd-pack (signed-byte 8))) '(simd-pack (signed-byte 8)))) (assert (equal (unparsed '(simd-pack (signed-byte 16))) '(simd-pack (signed-byte 16)))) (assert (equal (unparsed '(simd-pack (signed-byte 32))) '(simd-pack (signed-byte 32)))) (assert (equal (unparsed '(simd-pack (signed-byte 64))) '(simd-pack (signed-byte 64)))) (assert (equal (unparsed '(simd-pack single-float)) '(simd-pack single-float))) (assert (equal (unparsed '(simd-pack double-float)) '(simd-pack double-float))) (assert (equal (unparsed '(or (simd-pack (unsigned-byte 64)) (simd-pack double-float))) ;; depends on *SIMD-PACK-ELEMENT-TYPES* order '(or (simd-pack double-float) (simd-pack (unsigned-byte 64))))) (assert (equal (unparsed '(or (simd-pack (unsigned-byte 8)) (simd-pack (unsigned-byte 16)) (simd-pack (unsigned-byte 32)) (simd-pack (unsigned-byte 64)) (simd-pack (signed-byte 8)) (simd-pack (signed-byte 16)) (simd-pack (signed-byte 32)) (simd-pack (signed-byte 64)) (simd-pack single-float) (simd-pack double-float))) 'simd-pack))))
null
https://raw.githubusercontent.com/sbcl/sbcl/968b251365ec6e2b0cee3e97df1145074e3a0980/tests/simd-pack.pure.lisp
lisp
Potentially side-effectful tests of the simd-pack infrastructure. more information. files (like this one) were written from scratch after the fork This software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. Default Want readably but can't without *READ-EVAL*. depends on *SIMD-PACK-ELEMENT-TYPES* order
This software is part of the SBCL system . See the README file for While most of SBCL is derived from the CMU CL system , the test from CMU CL . #-sb-simd-pack (invoke-restart 'run-tests::skip-file) (defun make-constant-packs () (values (sb-kernel:%make-simd-pack-ub64 1 2) (sb-kernel:%make-simd-pack-ub32 0 0 0 0) (sb-kernel:%make-simd-pack-ub64 (ldb (byte 64 0) -1) (ldb (byte 64 0) -1)) (sb-kernel:%make-simd-pack-single 1f0 2f0 3f0 4f0) (sb-kernel:%make-simd-pack-single 0f0 0f0 0f0 0f0) (sb-kernel:%make-simd-pack-single (sb-kernel:make-single-float -1) (sb-kernel:make-single-float -1) (sb-kernel:make-single-float -1) (sb-kernel:make-single-float -1)) (sb-kernel:%make-simd-pack-double 1d0 2d0) (sb-kernel:%make-simd-pack-double 0d0 0d0) (sb-kernel:%make-simd-pack-double (sb-kernel:make-double-float -1 (ldb (byte 32 0) -1)) (sb-kernel:make-double-float -1 (ldb (byte 32 0) -1))))) (with-test (:name :compile-simd-pack) (multiple-value-bind (i i0 i-1 f f0 f-1 d d0 d-1) (make-constant-packs) (loop for (lo hi) in (list '(1 2) '(0 0) (list (ldb (byte 64 0) -1) (ldb (byte 64 0) -1))) for pack in (list i i0 i-1) do (assert (eql lo (sb-kernel:%simd-pack-low pack))) (assert (eql hi (sb-kernel:%simd-pack-high pack)))) (loop for expected in (list '(1f0 2f0 3f0 4f0) '(0f0 0f0 0f0 0f0) (make-list 4 :initial-element (sb-kernel:make-single-float -1))) for pack in (list f f0 f-1) do (assert (every #'eql expected (multiple-value-list (sb-kernel:%simd-pack-singles pack))))) (loop for expected in (list '(1d0 2d0) '(0d0 0d0) (make-list 2 :initial-element (sb-kernel:make-double-float -1 (ldb (byte 32 0) -1)))) for pack in (list d d0 d-1) do (assert (every #'eql expected (multiple-value-list (sb-kernel:%simd-pack-doubles pack))))))) (with-test (:name (simd-pack print :smoke)) (let ((packs (multiple-value-list (make-constant-packs)))) (flet ((print-them (expect) (dolist (pack packs) (flet ((do-it () (with-output-to-string (stream) (write pack :stream stream :pretty t :escape nil)))) (case expect (print-not-readable (assert-error (do-it) print-not-readable)) (t (do-it))))))) (print-them t) Readably (let ((*print-readably* t) (*read-eval* t)) (print-them t)) (let ((*print-readably* t) (*read-eval* nil)) (print-them 'print-not-readable))))) (defvar *tmp-filename* (scratch-file-name)) (defvar *pack*) (with-test (:name :load-simd-pack-int) (with-open-file (s *tmp-filename* :direction :output :if-exists :supersede :if-does-not-exist :create) (print '(setq *pack* (sb-kernel:%make-simd-pack-ub64 2 4)) s)) (let (tmp-fasl) (unwind-protect (progn (setq tmp-fasl (compile-file *tmp-filename*)) (let ((*pack* nil)) (load tmp-fasl) (assert (typep *pack* '(sb-kernel:simd-pack (unsigned-byte 64)))) (assert (= 2 (sb-kernel:%simd-pack-low *pack*))) (assert (= 4 (sb-kernel:%simd-pack-high *pack*))))) (when tmp-fasl (delete-file tmp-fasl)) (delete-file *tmp-filename*)))) (with-test (:name :load-simd-pack-single) (with-open-file (s *tmp-filename* :direction :output :if-exists :supersede :if-does-not-exist :create) (print '(setq *pack* (sb-kernel:%make-simd-pack-single 1f0 2f0 3f0 4f0)) s)) (let (tmp-fasl) (unwind-protect (progn (setq tmp-fasl (compile-file *tmp-filename*)) (let ((*pack* nil)) (load tmp-fasl) (assert (typep *pack* '(sb-kernel:simd-pack single-float))) (assert (equal (multiple-value-list (sb-kernel:%simd-pack-singles *pack*)) '(1f0 2f0 3f0 4f0))))) (when tmp-fasl (delete-file tmp-fasl)) (delete-file *tmp-filename*)))) (with-test (:name :load-simd-pack-double) (with-open-file (s *tmp-filename* :direction :output :if-exists :supersede :if-does-not-exist :create) (print '(setq *pack* (sb-kernel:%make-simd-pack-double 1d0 2d0)) s)) (let (tmp-fasl) (unwind-protect (progn (setq tmp-fasl (compile-file *tmp-filename*)) (let ((*pack* nil)) (load tmp-fasl) (assert (typep *pack* '(sb-kernel:simd-pack double-float))) (assert (equal (multiple-value-list (sb-kernel:%simd-pack-doubles *pack*)) '(1d0 2d0))))) (when tmp-fasl (delete-file tmp-fasl)) (delete-file *tmp-filename*)))) (with-test (:name (simd-pack subtypep :smoke)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 8)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 16)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 32)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 64)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 8)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 16)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 32)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack (signed-byte 64)) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack single-float) 'simd-pack)) (assert-tri-eq t t (subtypep '(simd-pack double-float) 'simd-pack)) (assert-tri-eq nil t (subtypep 'simd-pack '(simd-pack (unsigned-byte 64)))) (assert-tri-eq nil t (subtypep 'simd-pack '(simd-pack single-float))) (assert-tri-eq nil t (subtypep 'simd-pack '(simd-pack double-float))) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 64)) '(or (simd-pack (unsigned-byte 64)) (simd-pack single-float)))) (assert-tri-eq t t (subtypep '(simd-pack (unsigned-byte 64)) '(or (simd-pack (unsigned-byte 64)) (simd-pack double-float)))) (assert-tri-eq nil t (subtypep '(simd-pack (unsigned-byte 64)) '(or (simd-pack single-float) (simd-pack double-float)))) (assert-tri-eq nil t (subtypep '(or (simd-pack (unsigned-byte 64)) (simd-pack single-float)) '(simd-pack (unsigned-byte 64)))) (assert-tri-eq nil t (subtypep '(or (simd-pack (unsigned-byte 64)) (simd-pack double-float)) '(simd-pack (unsigned-byte 64)))) (assert-tri-eq nil t (subtypep '(or (simd-pack single-float) (simd-pack double-float)) '(simd-pack (unsigned-byte 64))))) (with-test (:name (simd-pack :ctype-unparse :smoke)) (flet ((unparsed (s) (sb-kernel:type-specifier (sb-kernel:specifier-type s)))) (assert (equal (unparsed 'simd-pack) 'simd-pack)) (assert (equal (unparsed '(simd-pack (unsigned-byte 8))) '(simd-pack (unsigned-byte 8)))) (assert (equal (unparsed '(simd-pack (unsigned-byte 16))) '(simd-pack (unsigned-byte 16)))) (assert (equal (unparsed '(simd-pack (unsigned-byte 32))) '(simd-pack (unsigned-byte 32)))) (assert (equal (unparsed '(simd-pack (unsigned-byte 64))) '(simd-pack (unsigned-byte 64)))) (assert (equal (unparsed '(simd-pack (signed-byte 8))) '(simd-pack (signed-byte 8)))) (assert (equal (unparsed '(simd-pack (signed-byte 16))) '(simd-pack (signed-byte 16)))) (assert (equal (unparsed '(simd-pack (signed-byte 32))) '(simd-pack (signed-byte 32)))) (assert (equal (unparsed '(simd-pack (signed-byte 64))) '(simd-pack (signed-byte 64)))) (assert (equal (unparsed '(simd-pack single-float)) '(simd-pack single-float))) (assert (equal (unparsed '(simd-pack double-float)) '(simd-pack double-float))) (assert (equal (unparsed '(or (simd-pack (unsigned-byte 64)) (simd-pack double-float))) '(or (simd-pack double-float) (simd-pack (unsigned-byte 64))))) (assert (equal (unparsed '(or (simd-pack (unsigned-byte 8)) (simd-pack (unsigned-byte 16)) (simd-pack (unsigned-byte 32)) (simd-pack (unsigned-byte 64)) (simd-pack (signed-byte 8)) (simd-pack (signed-byte 16)) (simd-pack (signed-byte 32)) (simd-pack (signed-byte 64)) (simd-pack single-float) (simd-pack double-float))) 'simd-pack))))
85a8da46e76ba188040359362c5cc5015da798a1f599e37a6711358519e2c434
pietervdvn/ALGT
ManualPreprocessor.hs
module Utils.ManualPreprocessor where {- Takes variables, substitutes them in the manual -} import System.Directory import System.Process import System.IO.Unsafe import Control.Exception (evaluate) import Utils.Utils import Utils.Version import Utils.ArgumentParser import Utils.ToString import Utils.PureIO hiding (writeFile, readFile, putStrLn) import Data.Map (Map) import qualified Data.Map as M import Data.List import Data.Maybe import Data.Char import Data.Time.Clock import Data.Time.Calendar import Data.Either import Utils.CreateAssets import Assets import AssetsHelper import PureMain import Text.Parsec import TypeSystem import TypeSystem.Parser.TargetLanguageParser import qualified TypeSystem.BNF as BNFParser import qualified TypeSystem.Parser.ParsingUtils as ParsingUtils import qualified SyntaxHighlighting.AsLatexPt as Latex import qualified SyntaxHighlighting.Renderers as Renderers import Text.PrettyPrint.ANSI.Leijen (text, ondullred, blue, putDoc) import ParseTreeInterpreter.FunctionInterpreter as FuncInp import Control.Arrow import Control.Monad import Control.Concurrent import System.Random import Lens.Micro hiding ((&)) buildVariables :: Map String String buildVariables = [ ("version", version & fst |> show & intercalate ".") , ("versionmsg", version & snd) , ("builtinEscapes", ParsingUtils.builtinEscapes |> over (_1 . _1) (\c -> '\\':[c]) & makeTable) , ("wsModeInfo", BNFParser.wsModeInfo & makeTable) , ("whitespace", ParsingUtils.whitespace |> (:[]) |> show |> verbatim & intercalate ",") , ("builtinSyntax", BNFParser.builtinSyntax |> over _1 fst3 |> unmerge3r |> (\(bnf, expl, regex) -> verbatim bnf ++ "|" ++ expl ++ "|" ++ verbatim regex) & unlines) , ("bnfKeywords", BNFParser.builtinSyntax |> fst |> fst3 & unlines) , ("regexIdentifier", BNFParser.builtinSyntax |> over _1 fst3 & lookup "Identifier" & fromMaybe (error "BUG in manualpreprocessor: no Identifier regex for builtin") & snd) , ("expressionExamples", TypeSystem.expressionExamples |> (\(e, n, pat, expr) -> [verbatim (toParsable e), n, expr] & intercalate " | " ) & unlines) , ("patternExamples", TypeSystem.expressionExamples |> (\(e, n, pat, expr) -> [verbatim (toParsable e), pat] & intercalate " | " ) & unlines) , ("builtinFunctions", builtinFunctions & advancedTable (\bif -> [verbatim $ get bifName bif, get bifDescr bif , verbatim $ argText (get bifInArgs bif) (get bifResultType bif) ])) , ("styles", AssetsHelper.knownStyles & M.keys |> (\str -> str & reverse & drop 6 & reverse) & list) , ("stylesSupport", AssetsHelper.minimalStyleTypes |> (" - "++) & unlines) , ("styleMatrix", styleMatrix) , ("styleSupported", Renderers.allRenderers |> dropTrd3 & supportedTable) ] & M.fromList supportedTable :: [(String, [String])] -> String supportedTable props = let renderNames = props |> fst header = ("| Attribute":renderNames) & intercalate "\t|" header' = "|:--------------" ++ concat (replicate (length renderNames) "|:-----:") possible = props & unmerge |> swap & merge & M.fromList row renderers = [ if known `elem` renderers then "✓" else "" | known <- renderNames ] & intercalate " | " :: String possible' = possible |> row & M.toList |> (\(k, v) -> verbatim k ++ "\t|" ++ v) :: [String] in ([header, header'] ++ possible') & unlines list :: [String] -> String list strs = strs |> (" - "++) & unlines argText :: Either (TypeName, Int) [TypeName] -> TypeName -> String argText (Left (inTp, nr)) resT = (inTp++" -> " >>= replicate nr) ++ inTp ++ "* -> " ++ resT argText (Right tps) resT = (tps++[resT]) & intercalate " -> " advancedTable :: (a -> [String]) -> [a] -> String advancedTable f as = as |> f |> intercalate "\t | " & unlines makeTable :: [((String, a), String)] -> String makeTable vals = vals |> over _1 fst |> escapedTable & unlines escapedTable :: (String, String) -> String escapedTable (inp, expl) = padR 16 ' ' (verbatim inp) ++ expl latexTable :: [String] -> [[String]] -> String latexTable headers contents = let header = "\\begin{longtable}[c]{@{}"++replicate (length headers) 'l' ++ "@{}}\n\\toprule\n" ++ intercalate " & " headers ++ "\\tabularnewline\n\\midrule\\endhead" :: String contents' = contents |> intercalate " & " |> (++" \\\\\n") & concat :: String bottom = "\\bottomrule\n\\end{longtable}" in [header, contents', bottom] & unlines styleMatrix :: String styleMatrix = let matrix = AssetsHelper.minimalStyleTypes |> (\styleN -> styleN:renderStyleRow styleN) known = AssetsHelper.knownStyles & M.keys |> reverse |> drop 6 |> reverse & ("Style":) in latexTable known matrix renderStyleRow :: Name -> [String] renderStyleRow styleN = do fc <- AssetsHelper.knownStyles & M.elems return $ Latex.renderWithStyle fc styleN styleN manualAssets :: IO (Map String String) manualAssets = do let files0 = allAssets |> fst & filter ("Manual/Files/" `isPrefixOf`) let files1 = allAssets |> fst & filter ("Manual/Thesis/" `isPrefixOf`) let files = files0 ++ files1 contents <- files |> ((\pth -> pth & reverse & takeWhile (/= '/') & reverse) &&& Assets.readFile' . ("src/Assets/"++)) |+> sndEffect contents & M.fromList & return buildVariablesIO :: IO (Map String String) buildVariablesIO = do (y,m,d) <- getCurrentTime |> (toGregorian . utctDay) let date = show y ++ "-"++show m ++ "-" ++ show d let dict' = [("date", date)] & M.fromList assets <- manualAssets let vars = M.unions [dict', assets, buildVariables] let allVarNames = vars & M.keys |> ("\n - "++) & unlines & ("Variables in the manual preprocessor are: "++) return $ M.insert "variables" allVarNames vars verbatim :: String -> String verbatim str = "`" ++ str ++ "`" genArg :: Map String String -> String -> IO (String, Map String String) genArg vars ('$':'$':'$':str) = do let (name, (action, _)) = break (\c -> not (isAlpha c || c `elem` "/.-")) str |> options value <- checkExists name vars ("No variable $$"++name) & either fail return return (name, M.singleton name $ action value) genArg _ str = return (str, M.empty) genArgs :: Map String String -> String -> IO ([String], Map String String) genArgs vars str = str & words |+> genArg vars |> unzip ||>> M.unions runIsolated = runIsolated' (++ " --plain --style WhiteFlat") runIsolated' :: (String -> String) -> (String, Int) -> (FilePath -> FilePath) -> Map String String -> Char -> String -> IO (Output, String -> String, String) runIsolated' argEdit line target vars closing str = do let (args, (action, rest)) = break (==closing) str |> tail |> options putStr $ show line ++ " Running with input args "++show args (args', input) <- genArgs vars (argEdit args) (_, Just parsedArgs) <- parseArgs ([-1::Int], "ManualPreprocessor run") args' let output = mainPure parsedArgs & isolateFailure & runPureOutput defaultConfig (mkStdGen 0) input & removeCarriageReturns & removeUnchanged putStrLn $ "Done! " ++ show (length $ show output) rest' <- preprocess line target vars rest return (output, action, rest') preprocess :: (String, Int) -> (FilePath -> FilePath) -> Map String String -> String -> IO String preprocess _ _ _ [] = return "" preprocess line target vars ('$':'$':'$':'m':'a':'t':'h':str) = do let (math, rest) = break (=='\n') str rest' <- preprocess line target vars rest return ("$$$" ++ math ++ "$$$" ++ rest') preprocess line target vars ('%':'%':str) = do let (comment, rest) = break (=='\n') str print line putDoc $ blue $ text comment putStrLn "" preprocess line target vars $ tail rest preprocess line target vars ('$':'$':'$':'!':'(':str) = do (output', action, rest) <- runIsolated' id line target vars ')' str let output = get stdOut output' & unlines return (output & action ++ rest) preprocess line target vars ('$':'$':'$':'(':str) = do (output', action, rest) <- runIsolated line target vars ')' str let output = get stdOut output' & unlines let wrapFile str = "\\begin{lstlisting}[style=terminal]\n"++str++"\n\n\\end{lstlisting}" return (output & action & wrapFile ++ rest) preprocess line target vars ('$':'$':'$':'[':str) = do (output', action, rest) <- runIsolated line target vars ']' str let output = get stdOut output' & unlines let wrapFile str = "\\begin{lstlisting}[style=terminal]\n"++str++"\n\n\\end{lstlisting}" return (output & action & wrapFile ++ rest) preprocess line destination vars ('$':'$':'$':'s':'v':'g':'(':str) = do (output, action, rest) <- runIsolated line destination vars ')' str let svgs = output & changedFiles & M.toList svgs |+> (\(n, v) -> do fileExists <- doesFileExist n unless fileExists $ writeFile (destination n) v putStrLn $ if fileExists then "Already exists " ++ destination n else "Saved "++destination n ) let dropExt s = if ".svg" `isSuffixOf` s then s & reverse & drop 4 & reverse else error $ "File without svg extension: "++s let named = svgs |> fst |> (\n -> "("++ dropExt n++".png)") & concat rest' <- preprocess line destination vars rest return (action named ++ rest') preprocess line target vars ('$':'$':'$':str) = do let (name, (action, rest)) = break (\c -> not (isAlpha c || c `elem` "/.-")) str |> options value <- checkExists name vars ("No variable $$"++name) & either error return rest' <- preprocess line target vars rest return (action value ++ rest') preprocess (file, line) target vars ('\n':str) = do rest <- preprocess (file, line + 1) target vars str return $ '\n':rest preprocess line target vars (ch:str) = do rest <- preprocess line target vars str return $ ch:rest options :: String -> (String -> String, String) options('!':'k':'e':'y':'w':'o':'r':'d':rest) = let (action, rest') = options rest in (\str -> " <keyword>" ++ str ++ "</keyword>", rest') options ('!':'i':'n':'d':'e':'n':'t':rest) = let (action, rest') = options rest in (\str -> str & action & lines |> (" "++) & intercalate "\n", rest') options('!':'f':'i':'l':'e':rest) = let (action, rest') = options rest wrapFile str = "\\begin{lstlisting}\n"++str++"\\end{lstlisting}\n" in (\str -> str & wrapFile & action, rest') options ('!':rest) = let (option, str) = span (`elem` "0123456789[].,") rest pt = parseTargetLang optionsSyntax "option" "Assets/Manual/Options.language" option & either error id action = matchOptionBody pt (action', str') = options str in (action' . action, str') options str = (id, str) matchOptionBody :: ParseTree -> String -> String matchOptionBody (PtSeq _ _ [body, MLiteral _ _ ",", body']) str = let action = matchOptionBody body action' = matchOptionBody body' in action str ++ "\n" ++ action' str matchOptionBody (PtSeq _ _ [parO, MInt _ _ i, MLiteral _ _ "..", MInt _ _ j, parC]) str = let i' = if inclusivePar parO then i-1 else i j' = if not $ inclusivePar parC then j else j-1 in str & lines & take j' & drop i' & unlines matchOptionBody (PtSeq _ _ [parO, MInt _ _ i, MLiteral _ _ "..", parC]) str = let i' = if inclusivePar parO then i-1 else i action = if not $ inclusivePar parC then id else init in str & lines & action & drop i' & intercalate "\n" matchOptionBody (MInt _ _ i) str = let lined = lines str in if i <= length lined then lined !! (i-1) else error $ "To little lines to get nr "++show i++" out of\n"++(str & lines & mapi |> (\(i, l) -> padR 3 ' ' (show $ 1 + i) ++ l) & unlines) matchOptionBody pt str = error $ "Can't handle option "++toParsable pt inclusivePar :: ParseTree -> Bool inclusivePar (MLiteral _ _ "[") = True inclusivePar (MLiteral _ _ "]") = False preprocessTo :: Map FilePath UTCTime -> FilePath -> (FilePath -> FilePath) -> (FilePath -> FilePath) -> IO () preprocessTo changes inp destination svgDestination = do str <- readFile' inp vars <- buildVariablesIO lastChange <- getModificationTime inp unless (M.lookup inp changes |> (lastChange ==) & fromMaybe False) $ do putStrLn $ "Processing "++inp++"..." str' <- preprocess (inp, 1) svgDestination vars str writeFile (destination inp) str' putStrLn $ "\rProcessed "++inp++" and saved it as "++destination inp preprocessDir :: Map FilePath UTCTime -> FilePath -> (FilePath -> FilePath) -> (FilePath -> FilePath) -> IO () preprocessDir changes fp destination svgDestination = do contents <- dirConts fp let contents' = contents & filter (".md" `isSuffixOf`) contents' |+> (\fp -> preprocessTo changes fp destination svgDestination) pass outputFile' :: FilePath -> FilePath -> FilePath outputFile' path name = path++".bin/"++name outputFile :: FilePath -> FilePath outputFile fp = let (name, path) = fp & reverse & break (=='/') & mapBoth reverse in path++".bin/"++name autoPreprocess :: IO () autoPreprocess = autoPreprocess' M.empty autoPreprocess' :: Map FilePath UTCTime -> IO () autoPreprocess' changes = do let path = "src/Assets/Manual/" runCommand "src/Assets/Manual/prebuild.sh" preprocessDir changes path (\nm -> outputFile path ++ (reverse nm & takeWhile (/= '/') & reverse )) (outputFile' path) runCommand "src/Assets/Manual/build.sh" pass contentsChanged :: FilePath -> IO (Map FilePath UTCTime) contentsChanged fp = do files <- dirConts fp files & filter (not . (".bin" `isInfixOf`)) & filter (not . ("/Output/" `isInfixOf`)) |> (id &&& getModificationTime) |+> sndEffect |> M.fromList diff :: (Ord k, Eq v) => Map k v -> Map k v -> Map k (v, v) diff m0 m1 = M.intersectionWith (,) m0 m1 & M.filter (uncurry (/=)) autoRecreate' :: Map FilePath UTCTime -> IO () autoRecreate' lastEdits = do lastEdits' <- contentsChanged "src/Assets/Manual" let millisecs = 750 -- let animation = ["|","/","-","\\"] let animations = ["|","/","-","\\"] let animation = animations -- ++ reverse animations let animation' = animation |> ("\r "++) let frameLength = 1000 `div` length animation' if lastEdits == lastEdits' then do animation' |+> (\frame -> threadDelay (frameLength*millisecs) >> putStr frame) pass else do putStrLn $ "CHANGED: "++ show (M.toList $ diff lastEdits lastEdits') autoPreprocess' lastEdits autoRecreate' lastEdits' autoRecreate = do lastEdits <- contentsChanged "src/Assets/Manual" putStrLn "Waiting for changes... Run 'autoPreprocess' to process all files" autoRecreate' lastEdits
null
https://raw.githubusercontent.com/pietervdvn/ALGT/43a2811931be6daf1362f37cb16f99375ca4999e/src/Utils/ManualPreprocessor.hs
haskell
Takes variables, substitutes them in the manual let animation = ["|","/","-","\\"] ++ reverse animations
module Utils.ManualPreprocessor where import System.Directory import System.Process import System.IO.Unsafe import Control.Exception (evaluate) import Utils.Utils import Utils.Version import Utils.ArgumentParser import Utils.ToString import Utils.PureIO hiding (writeFile, readFile, putStrLn) import Data.Map (Map) import qualified Data.Map as M import Data.List import Data.Maybe import Data.Char import Data.Time.Clock import Data.Time.Calendar import Data.Either import Utils.CreateAssets import Assets import AssetsHelper import PureMain import Text.Parsec import TypeSystem import TypeSystem.Parser.TargetLanguageParser import qualified TypeSystem.BNF as BNFParser import qualified TypeSystem.Parser.ParsingUtils as ParsingUtils import qualified SyntaxHighlighting.AsLatexPt as Latex import qualified SyntaxHighlighting.Renderers as Renderers import Text.PrettyPrint.ANSI.Leijen (text, ondullred, blue, putDoc) import ParseTreeInterpreter.FunctionInterpreter as FuncInp import Control.Arrow import Control.Monad import Control.Concurrent import System.Random import Lens.Micro hiding ((&)) buildVariables :: Map String String buildVariables = [ ("version", version & fst |> show & intercalate ".") , ("versionmsg", version & snd) , ("builtinEscapes", ParsingUtils.builtinEscapes |> over (_1 . _1) (\c -> '\\':[c]) & makeTable) , ("wsModeInfo", BNFParser.wsModeInfo & makeTable) , ("whitespace", ParsingUtils.whitespace |> (:[]) |> show |> verbatim & intercalate ",") , ("builtinSyntax", BNFParser.builtinSyntax |> over _1 fst3 |> unmerge3r |> (\(bnf, expl, regex) -> verbatim bnf ++ "|" ++ expl ++ "|" ++ verbatim regex) & unlines) , ("bnfKeywords", BNFParser.builtinSyntax |> fst |> fst3 & unlines) , ("regexIdentifier", BNFParser.builtinSyntax |> over _1 fst3 & lookup "Identifier" & fromMaybe (error "BUG in manualpreprocessor: no Identifier regex for builtin") & snd) , ("expressionExamples", TypeSystem.expressionExamples |> (\(e, n, pat, expr) -> [verbatim (toParsable e), n, expr] & intercalate " | " ) & unlines) , ("patternExamples", TypeSystem.expressionExamples |> (\(e, n, pat, expr) -> [verbatim (toParsable e), pat] & intercalate " | " ) & unlines) , ("builtinFunctions", builtinFunctions & advancedTable (\bif -> [verbatim $ get bifName bif, get bifDescr bif , verbatim $ argText (get bifInArgs bif) (get bifResultType bif) ])) , ("styles", AssetsHelper.knownStyles & M.keys |> (\str -> str & reverse & drop 6 & reverse) & list) , ("stylesSupport", AssetsHelper.minimalStyleTypes |> (" - "++) & unlines) , ("styleMatrix", styleMatrix) , ("styleSupported", Renderers.allRenderers |> dropTrd3 & supportedTable) ] & M.fromList supportedTable :: [(String, [String])] -> String supportedTable props = let renderNames = props |> fst header = ("| Attribute":renderNames) & intercalate "\t|" header' = "|:--------------" ++ concat (replicate (length renderNames) "|:-----:") possible = props & unmerge |> swap & merge & M.fromList row renderers = [ if known `elem` renderers then "✓" else "" | known <- renderNames ] & intercalate " | " :: String possible' = possible |> row & M.toList |> (\(k, v) -> verbatim k ++ "\t|" ++ v) :: [String] in ([header, header'] ++ possible') & unlines list :: [String] -> String list strs = strs |> (" - "++) & unlines argText :: Either (TypeName, Int) [TypeName] -> TypeName -> String argText (Left (inTp, nr)) resT = (inTp++" -> " >>= replicate nr) ++ inTp ++ "* -> " ++ resT argText (Right tps) resT = (tps++[resT]) & intercalate " -> " advancedTable :: (a -> [String]) -> [a] -> String advancedTable f as = as |> f |> intercalate "\t | " & unlines makeTable :: [((String, a), String)] -> String makeTable vals = vals |> over _1 fst |> escapedTable & unlines escapedTable :: (String, String) -> String escapedTable (inp, expl) = padR 16 ' ' (verbatim inp) ++ expl latexTable :: [String] -> [[String]] -> String latexTable headers contents = let header = "\\begin{longtable}[c]{@{}"++replicate (length headers) 'l' ++ "@{}}\n\\toprule\n" ++ intercalate " & " headers ++ "\\tabularnewline\n\\midrule\\endhead" :: String contents' = contents |> intercalate " & " |> (++" \\\\\n") & concat :: String bottom = "\\bottomrule\n\\end{longtable}" in [header, contents', bottom] & unlines styleMatrix :: String styleMatrix = let matrix = AssetsHelper.minimalStyleTypes |> (\styleN -> styleN:renderStyleRow styleN) known = AssetsHelper.knownStyles & M.keys |> reverse |> drop 6 |> reverse & ("Style":) in latexTable known matrix renderStyleRow :: Name -> [String] renderStyleRow styleN = do fc <- AssetsHelper.knownStyles & M.elems return $ Latex.renderWithStyle fc styleN styleN manualAssets :: IO (Map String String) manualAssets = do let files0 = allAssets |> fst & filter ("Manual/Files/" `isPrefixOf`) let files1 = allAssets |> fst & filter ("Manual/Thesis/" `isPrefixOf`) let files = files0 ++ files1 contents <- files |> ((\pth -> pth & reverse & takeWhile (/= '/') & reverse) &&& Assets.readFile' . ("src/Assets/"++)) |+> sndEffect contents & M.fromList & return buildVariablesIO :: IO (Map String String) buildVariablesIO = do (y,m,d) <- getCurrentTime |> (toGregorian . utctDay) let date = show y ++ "-"++show m ++ "-" ++ show d let dict' = [("date", date)] & M.fromList assets <- manualAssets let vars = M.unions [dict', assets, buildVariables] let allVarNames = vars & M.keys |> ("\n - "++) & unlines & ("Variables in the manual preprocessor are: "++) return $ M.insert "variables" allVarNames vars verbatim :: String -> String verbatim str = "`" ++ str ++ "`" genArg :: Map String String -> String -> IO (String, Map String String) genArg vars ('$':'$':'$':str) = do let (name, (action, _)) = break (\c -> not (isAlpha c || c `elem` "/.-")) str |> options value <- checkExists name vars ("No variable $$"++name) & either fail return return (name, M.singleton name $ action value) genArg _ str = return (str, M.empty) genArgs :: Map String String -> String -> IO ([String], Map String String) genArgs vars str = str & words |+> genArg vars |> unzip ||>> M.unions runIsolated = runIsolated' (++ " --plain --style WhiteFlat") runIsolated' :: (String -> String) -> (String, Int) -> (FilePath -> FilePath) -> Map String String -> Char -> String -> IO (Output, String -> String, String) runIsolated' argEdit line target vars closing str = do let (args, (action, rest)) = break (==closing) str |> tail |> options putStr $ show line ++ " Running with input args "++show args (args', input) <- genArgs vars (argEdit args) (_, Just parsedArgs) <- parseArgs ([-1::Int], "ManualPreprocessor run") args' let output = mainPure parsedArgs & isolateFailure & runPureOutput defaultConfig (mkStdGen 0) input & removeCarriageReturns & removeUnchanged putStrLn $ "Done! " ++ show (length $ show output) rest' <- preprocess line target vars rest return (output, action, rest') preprocess :: (String, Int) -> (FilePath -> FilePath) -> Map String String -> String -> IO String preprocess _ _ _ [] = return "" preprocess line target vars ('$':'$':'$':'m':'a':'t':'h':str) = do let (math, rest) = break (=='\n') str rest' <- preprocess line target vars rest return ("$$$" ++ math ++ "$$$" ++ rest') preprocess line target vars ('%':'%':str) = do let (comment, rest) = break (=='\n') str print line putDoc $ blue $ text comment putStrLn "" preprocess line target vars $ tail rest preprocess line target vars ('$':'$':'$':'!':'(':str) = do (output', action, rest) <- runIsolated' id line target vars ')' str let output = get stdOut output' & unlines return (output & action ++ rest) preprocess line target vars ('$':'$':'$':'(':str) = do (output', action, rest) <- runIsolated line target vars ')' str let output = get stdOut output' & unlines let wrapFile str = "\\begin{lstlisting}[style=terminal]\n"++str++"\n\n\\end{lstlisting}" return (output & action & wrapFile ++ rest) preprocess line target vars ('$':'$':'$':'[':str) = do (output', action, rest) <- runIsolated line target vars ']' str let output = get stdOut output' & unlines let wrapFile str = "\\begin{lstlisting}[style=terminal]\n"++str++"\n\n\\end{lstlisting}" return (output & action & wrapFile ++ rest) preprocess line destination vars ('$':'$':'$':'s':'v':'g':'(':str) = do (output, action, rest) <- runIsolated line destination vars ')' str let svgs = output & changedFiles & M.toList svgs |+> (\(n, v) -> do fileExists <- doesFileExist n unless fileExists $ writeFile (destination n) v putStrLn $ if fileExists then "Already exists " ++ destination n else "Saved "++destination n ) let dropExt s = if ".svg" `isSuffixOf` s then s & reverse & drop 4 & reverse else error $ "File without svg extension: "++s let named = svgs |> fst |> (\n -> "("++ dropExt n++".png)") & concat rest' <- preprocess line destination vars rest return (action named ++ rest') preprocess line target vars ('$':'$':'$':str) = do let (name, (action, rest)) = break (\c -> not (isAlpha c || c `elem` "/.-")) str |> options value <- checkExists name vars ("No variable $$"++name) & either error return rest' <- preprocess line target vars rest return (action value ++ rest') preprocess (file, line) target vars ('\n':str) = do rest <- preprocess (file, line + 1) target vars str return $ '\n':rest preprocess line target vars (ch:str) = do rest <- preprocess line target vars str return $ ch:rest options :: String -> (String -> String, String) options('!':'k':'e':'y':'w':'o':'r':'d':rest) = let (action, rest') = options rest in (\str -> " <keyword>" ++ str ++ "</keyword>", rest') options ('!':'i':'n':'d':'e':'n':'t':rest) = let (action, rest') = options rest in (\str -> str & action & lines |> (" "++) & intercalate "\n", rest') options('!':'f':'i':'l':'e':rest) = let (action, rest') = options rest wrapFile str = "\\begin{lstlisting}\n"++str++"\\end{lstlisting}\n" in (\str -> str & wrapFile & action, rest') options ('!':rest) = let (option, str) = span (`elem` "0123456789[].,") rest pt = parseTargetLang optionsSyntax "option" "Assets/Manual/Options.language" option & either error id action = matchOptionBody pt (action', str') = options str in (action' . action, str') options str = (id, str) matchOptionBody :: ParseTree -> String -> String matchOptionBody (PtSeq _ _ [body, MLiteral _ _ ",", body']) str = let action = matchOptionBody body action' = matchOptionBody body' in action str ++ "\n" ++ action' str matchOptionBody (PtSeq _ _ [parO, MInt _ _ i, MLiteral _ _ "..", MInt _ _ j, parC]) str = let i' = if inclusivePar parO then i-1 else i j' = if not $ inclusivePar parC then j else j-1 in str & lines & take j' & drop i' & unlines matchOptionBody (PtSeq _ _ [parO, MInt _ _ i, MLiteral _ _ "..", parC]) str = let i' = if inclusivePar parO then i-1 else i action = if not $ inclusivePar parC then id else init in str & lines & action & drop i' & intercalate "\n" matchOptionBody (MInt _ _ i) str = let lined = lines str in if i <= length lined then lined !! (i-1) else error $ "To little lines to get nr "++show i++" out of\n"++(str & lines & mapi |> (\(i, l) -> padR 3 ' ' (show $ 1 + i) ++ l) & unlines) matchOptionBody pt str = error $ "Can't handle option "++toParsable pt inclusivePar :: ParseTree -> Bool inclusivePar (MLiteral _ _ "[") = True inclusivePar (MLiteral _ _ "]") = False preprocessTo :: Map FilePath UTCTime -> FilePath -> (FilePath -> FilePath) -> (FilePath -> FilePath) -> IO () preprocessTo changes inp destination svgDestination = do str <- readFile' inp vars <- buildVariablesIO lastChange <- getModificationTime inp unless (M.lookup inp changes |> (lastChange ==) & fromMaybe False) $ do putStrLn $ "Processing "++inp++"..." str' <- preprocess (inp, 1) svgDestination vars str writeFile (destination inp) str' putStrLn $ "\rProcessed "++inp++" and saved it as "++destination inp preprocessDir :: Map FilePath UTCTime -> FilePath -> (FilePath -> FilePath) -> (FilePath -> FilePath) -> IO () preprocessDir changes fp destination svgDestination = do contents <- dirConts fp let contents' = contents & filter (".md" `isSuffixOf`) contents' |+> (\fp -> preprocessTo changes fp destination svgDestination) pass outputFile' :: FilePath -> FilePath -> FilePath outputFile' path name = path++".bin/"++name outputFile :: FilePath -> FilePath outputFile fp = let (name, path) = fp & reverse & break (=='/') & mapBoth reverse in path++".bin/"++name autoPreprocess :: IO () autoPreprocess = autoPreprocess' M.empty autoPreprocess' :: Map FilePath UTCTime -> IO () autoPreprocess' changes = do let path = "src/Assets/Manual/" runCommand "src/Assets/Manual/prebuild.sh" preprocessDir changes path (\nm -> outputFile path ++ (reverse nm & takeWhile (/= '/') & reverse )) (outputFile' path) runCommand "src/Assets/Manual/build.sh" pass contentsChanged :: FilePath -> IO (Map FilePath UTCTime) contentsChanged fp = do files <- dirConts fp files & filter (not . (".bin" `isInfixOf`)) & filter (not . ("/Output/" `isInfixOf`)) |> (id &&& getModificationTime) |+> sndEffect |> M.fromList diff :: (Ord k, Eq v) => Map k v -> Map k v -> Map k (v, v) diff m0 m1 = M.intersectionWith (,) m0 m1 & M.filter (uncurry (/=)) autoRecreate' :: Map FilePath UTCTime -> IO () autoRecreate' lastEdits = do lastEdits' <- contentsChanged "src/Assets/Manual" let millisecs = 750 let animations = ["|","/","-","\\"] let animation' = animation |> ("\r "++) let frameLength = 1000 `div` length animation' if lastEdits == lastEdits' then do animation' |+> (\frame -> threadDelay (frameLength*millisecs) >> putStr frame) pass else do putStrLn $ "CHANGED: "++ show (M.toList $ diff lastEdits lastEdits') autoPreprocess' lastEdits autoRecreate' lastEdits' autoRecreate = do lastEdits <- contentsChanged "src/Assets/Manual" putStrLn "Waiting for changes... Run 'autoPreprocess' to process all files" autoRecreate' lastEdits
df857e3dcd0c0de115ab70b638734d8174eb8d3cc063c760df73142efd347cc4
fetburner/Coq2SML
big.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 *) (************************************************************************) * [ Big ] : a wrapper around ocaml [ Big_int ] with nicer names , and a few extraction - specific constructions and a few extraction-specific constructions *) (** To be linked with [nums.(cma|cmxa)] *) open Big_int type big_int = Big_int.big_int (** The type of big integers. *) let zero = zero_big_int (** The big integer [0]. *) let one = unit_big_int * The big integer [ 1 ] . let two = big_int_of_int 2 * The big integer [ 2 ] . * { 6 Arithmetic operations } let opp = minus_big_int (** Unary negation. *) let abs = abs_big_int (** Absolute value. *) let add = add_big_int (** Addition. *) let succ = succ_big_int * Successor ( add 1 ) . let add_int = add_int_big_int (** Addition of a small integer to a big integer. *) let sub = sub_big_int (** Subtraction. *) let pred = pred_big_int * Predecessor ( subtract 1 ) . let mult = mult_big_int * Multiplication of two big integers . let mult_int = mult_int_big_int (** Multiplication of a big integer by a small integer *) let square = square_big_int (** Return the square of the given big integer *) let sqrt = sqrt_big_int (** [sqrt_big_int a] returns the integer square root of [a], that is, the largest big integer [r] such that [r * r <= a]. Raise [Invalid_argument] if [a] is negative. *) let quomod = quomod_big_int * Euclidean division of two big integers . The first part of the result is the quotient , the second part is the remainder . Writing [ ( q , r ) = quomod_big_int a b ] , we have [ a = q * b + r ] and [ 0 < = r < |b| ] . Raise [ Division_by_zero ] if the divisor is zero . The first part of the result is the quotient, the second part is the remainder. Writing [(q,r) = quomod_big_int a b], we have [a = q * b + r] and [0 <= r < |b|]. Raise [Division_by_zero] if the divisor is zero. *) let div = div_big_int * Euclidean quotient of two big integers . This is the first result [ q ] of [ quomod_big_int ] ( see above ) . This is the first result [q] of [quomod_big_int] (see above). *) let modulo = mod_big_int * Euclidean modulus of two big integers . This is the second result [ r ] of [ quomod_big_int ] ( see above ) . This is the second result [r] of [quomod_big_int] (see above). *) let gcd = gcd_big_int * Greatest common divisor of two big integers . let power = power_big_int_positive_big_int * Exponentiation functions . Return the big integer representing the first argument [ a ] raised to the power [ b ] ( the second argument ) . Depending on the function , [ a ] and [ b ] can be either small integers or big integers . Raise [ Invalid_argument ] if [ b ] is negative . representing the first argument [a] raised to the power [b] (the second argument). Depending on the function, [a] and [b] can be either small integers or big integers. Raise [Invalid_argument] if [b] is negative. *) * { 6 Comparisons and tests } let sign = sign_big_int * Return [ 0 ] if the given big integer is zero , [ 1 ] if it is positive , and [ -1 ] if it is negative . [1] if it is positive, and [-1] if it is negative. *) let compare = compare_big_int * [ compare_big_int a b ] returns [ 0 ] if [ a ] and [ b ] are equal , [ 1 ] if [ a ] is greater than [ b ] , and [ -1 ] if [ a ] is smaller than [ b ] . [1] if [a] is greater than [b], and [-1] if [a] is smaller than [b]. *) let eq = eq_big_int let le = le_big_int let ge = ge_big_int let lt = lt_big_int let gt = gt_big_int * Usual boolean comparisons between two big integers . let max = max_big_int * Return the greater of its two arguments . let min = min_big_int * Return the smaller of its two arguments . * { 6 Conversions to and from strings } let to_string = string_of_big_int * Return the string representation of the given big integer , in decimal ( base 10 ) . in decimal (base 10). *) let of_string = big_int_of_string * Convert a string to a big integer , in decimal . The string consists of an optional [ - ] or [ + ] sign , followed by one or several decimal digits . The string consists of an optional [-] or [+] sign, followed by one or several decimal digits. *) * { 6 Conversions to and from other numerical types } let of_int = big_int_of_int (** Convert a small integer to a big integer. *) let is_int = is_int_big_int * Test whether the given big integer is small enough to be representable as a small integer ( type [ int ] ) without loss of precision . On a 32 - bit platform , [ is_int_big_int a ] returns [ true ] if and only if [ a ] is between 2{^30 } and 2{^30}-1 . On a 64 - bit platform , [ is_int_big_int a ] returns [ true ] if and only if [ a ] is between -2{^62 } and 2{^62}-1 . be representable as a small integer (type [int]) without loss of precision. On a 32-bit platform, [is_int_big_int a] returns [true] if and only if [a] is between 2{^30} and 2{^30}-1. On a 64-bit platform, [is_int_big_int a] returns [true] if and only if [a] is between -2{^62} and 2{^62}-1. *) let to_int = int_of_big_int (** Convert a big integer to a small integer (type [int]). Raises [Failure "int_of_big_int"] if the big integer is not representable as a small integer. *) (** Functions used by extraction *) let double x = mult_int 2 x let doubleplusone x = succ (double x) let nat_case fO fS n = if sign n <= 0 then fO () else fS (pred n) let positive_case f2p1 f2p f1 p = if le p one then f1 () else let (q,r) = quomod p two in if eq r zero then f2p q else f2p1 q let n_case fO fp n = if sign n <= 0 then fO () else fp n let z_case fO fp fn z = let s = sign z in if s = 0 then fO () else if s > 0 then fp z else fn (opp z) let compare_case e l g x y = let s = compare x y in if s = 0 then e else if s<0 then l else g let nat_rec fO fS = let rec loop acc n = if sign n <= 0 then acc else loop (fS acc) (pred n) in loop fO let positive_rec f2p1 f2p f1 = let rec loop n = if le n one then f1 else let (q,r) = quomod n two in if eq r zero then f2p (loop q) else f2p1 (loop q) in loop let z_rec fO fp fn = z_case (fun _ -> fO) fp fn
null
https://raw.githubusercontent.com/fetburner/Coq2SML/322d613619edbb62edafa999bff24b1993f37612/coq-8.4pl4/plugins/extraction/big.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * To be linked with [nums.(cma|cmxa)] * The type of big integers. * The big integer [0]. * Unary negation. * Absolute value. * Addition. * Addition of a small integer to a big integer. * Subtraction. * Multiplication of a big integer by a small integer * Return the square of the given big integer * [sqrt_big_int a] returns the integer square root of [a], that is, the largest big integer [r] such that [r * r <= a]. Raise [Invalid_argument] if [a] is negative. * Convert a small integer to a big integer. * Convert a big integer to a small integer (type [int]). Raises [Failure "int_of_big_int"] if the big integer is not representable as a small integer. * Functions used by extraction
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * [ Big ] : a wrapper around ocaml [ Big_int ] with nicer names , and a few extraction - specific constructions and a few extraction-specific constructions *) open Big_int type big_int = Big_int.big_int let zero = zero_big_int let one = unit_big_int * The big integer [ 1 ] . let two = big_int_of_int 2 * The big integer [ 2 ] . * { 6 Arithmetic operations } let opp = minus_big_int let abs = abs_big_int let add = add_big_int let succ = succ_big_int * Successor ( add 1 ) . let add_int = add_int_big_int let sub = sub_big_int let pred = pred_big_int * Predecessor ( subtract 1 ) . let mult = mult_big_int * Multiplication of two big integers . let mult_int = mult_int_big_int let square = square_big_int let sqrt = sqrt_big_int let quomod = quomod_big_int * Euclidean division of two big integers . The first part of the result is the quotient , the second part is the remainder . Writing [ ( q , r ) = quomod_big_int a b ] , we have [ a = q * b + r ] and [ 0 < = r < |b| ] . Raise [ Division_by_zero ] if the divisor is zero . The first part of the result is the quotient, the second part is the remainder. Writing [(q,r) = quomod_big_int a b], we have [a = q * b + r] and [0 <= r < |b|]. Raise [Division_by_zero] if the divisor is zero. *) let div = div_big_int * Euclidean quotient of two big integers . This is the first result [ q ] of [ quomod_big_int ] ( see above ) . This is the first result [q] of [quomod_big_int] (see above). *) let modulo = mod_big_int * Euclidean modulus of two big integers . This is the second result [ r ] of [ quomod_big_int ] ( see above ) . This is the second result [r] of [quomod_big_int] (see above). *) let gcd = gcd_big_int * Greatest common divisor of two big integers . let power = power_big_int_positive_big_int * Exponentiation functions . Return the big integer representing the first argument [ a ] raised to the power [ b ] ( the second argument ) . Depending on the function , [ a ] and [ b ] can be either small integers or big integers . Raise [ Invalid_argument ] if [ b ] is negative . representing the first argument [a] raised to the power [b] (the second argument). Depending on the function, [a] and [b] can be either small integers or big integers. Raise [Invalid_argument] if [b] is negative. *) * { 6 Comparisons and tests } let sign = sign_big_int * Return [ 0 ] if the given big integer is zero , [ 1 ] if it is positive , and [ -1 ] if it is negative . [1] if it is positive, and [-1] if it is negative. *) let compare = compare_big_int * [ compare_big_int a b ] returns [ 0 ] if [ a ] and [ b ] are equal , [ 1 ] if [ a ] is greater than [ b ] , and [ -1 ] if [ a ] is smaller than [ b ] . [1] if [a] is greater than [b], and [-1] if [a] is smaller than [b]. *) let eq = eq_big_int let le = le_big_int let ge = ge_big_int let lt = lt_big_int let gt = gt_big_int * Usual boolean comparisons between two big integers . let max = max_big_int * Return the greater of its two arguments . let min = min_big_int * Return the smaller of its two arguments . * { 6 Conversions to and from strings } let to_string = string_of_big_int * Return the string representation of the given big integer , in decimal ( base 10 ) . in decimal (base 10). *) let of_string = big_int_of_string * Convert a string to a big integer , in decimal . The string consists of an optional [ - ] or [ + ] sign , followed by one or several decimal digits . The string consists of an optional [-] or [+] sign, followed by one or several decimal digits. *) * { 6 Conversions to and from other numerical types } let of_int = big_int_of_int let is_int = is_int_big_int * Test whether the given big integer is small enough to be representable as a small integer ( type [ int ] ) without loss of precision . On a 32 - bit platform , [ is_int_big_int a ] returns [ true ] if and only if [ a ] is between 2{^30 } and 2{^30}-1 . On a 64 - bit platform , [ is_int_big_int a ] returns [ true ] if and only if [ a ] is between -2{^62 } and 2{^62}-1 . be representable as a small integer (type [int]) without loss of precision. On a 32-bit platform, [is_int_big_int a] returns [true] if and only if [a] is between 2{^30} and 2{^30}-1. On a 64-bit platform, [is_int_big_int a] returns [true] if and only if [a] is between -2{^62} and 2{^62}-1. *) let to_int = int_of_big_int let double x = mult_int 2 x let doubleplusone x = succ (double x) let nat_case fO fS n = if sign n <= 0 then fO () else fS (pred n) let positive_case f2p1 f2p f1 p = if le p one then f1 () else let (q,r) = quomod p two in if eq r zero then f2p q else f2p1 q let n_case fO fp n = if sign n <= 0 then fO () else fp n let z_case fO fp fn z = let s = sign z in if s = 0 then fO () else if s > 0 then fp z else fn (opp z) let compare_case e l g x y = let s = compare x y in if s = 0 then e else if s<0 then l else g let nat_rec fO fS = let rec loop acc n = if sign n <= 0 then acc else loop (fS acc) (pred n) in loop fO let positive_rec f2p1 f2p f1 = let rec loop n = if le n one then f1 else let (q,r) = quomod n two in if eq r zero then f2p (loop q) else f2p1 (loop q) in loop let z_rec fO fp fn = z_case (fun _ -> fO) fp fn
376071ee762e0db07393a4c22eadc699c94978e9cda841167ff46bd9a6493d90
racehub/liberator-friend
core.clj
(ns liberator-friend.core "Core namespace for the liberator-friend post." (:gen-class) (:require [cemerick.friend.credentials :as creds] [compojure.handler :refer [api]] [compojure.core :as compojure :refer (GET defroutes)] [liberator-friend.middleware.auth :as auth] [liberator-friend.resources :as r :refer [defresource]] [org.httpkit.server :refer [run-server]] [ring.middleware.reload :as rl])) # # " The Database " (def users "dummy in-memory user database." {"root" {:username "root" :password (creds/hash-bcrypt "admin_password") :roles #{:admin}} "jane" {:username "jane" :password (creds/hash-bcrypt "user_password") :roles #{:user}}}) # # Site Resources (defresource admin-resource :base (r/role-auth #{:admin}) :allowed-methods [:get] :available-media-types ["text/plain"] :handle-ok "Welcome, admin!") (defresource user-resource :base (r/role-auth #{:user}) :allowed-methods [:get] :available-media-types ["text/plain"] :handle-ok "Welcome, user!") (defresource authenticated-resource :base r/authenticated-base :allowed-methods [:get] :available-media-types ["text/plain"] :handle-ok "Come on in. You're authenticated.") ;; ## Compojure Routes (defroutes site-routes (GET "/" [] "Welcome to the liberator-friend demo site!") (GET "/admin" [] admin-resource) (GET "/authenticated" [] authenticated-resource) (GET "/user" [] user-resource)) (def site "Main handler for the example Compojure site." (-> site-routes (auth/friend-middleware users) (api))) ;; ## Server Lifecycle (defonce server (atom nil)) (defn kill! [] (swap! server (fn [s] (when s (s) nil)))) (defn -main [] (swap! server (fn [s] (if s (do (println "Server already running!") s) (do (println "Booting server on port 8090.") (run-server (rl/wrap-reload #'site) {})))))) (defn running? "Returns true if the server is currently running, false otherwise." [] (identity @server)) (defn cycle! "Cycles the existing server - shut down the relaunch." [] (kill!) (-main))
null
https://raw.githubusercontent.com/racehub/liberator-friend/ab096f94928ac7b12b4541bd840df678a1f746aa/src/liberator_friend/core.clj
clojure
## Compojure Routes ## Server Lifecycle
(ns liberator-friend.core "Core namespace for the liberator-friend post." (:gen-class) (:require [cemerick.friend.credentials :as creds] [compojure.handler :refer [api]] [compojure.core :as compojure :refer (GET defroutes)] [liberator-friend.middleware.auth :as auth] [liberator-friend.resources :as r :refer [defresource]] [org.httpkit.server :refer [run-server]] [ring.middleware.reload :as rl])) # # " The Database " (def users "dummy in-memory user database." {"root" {:username "root" :password (creds/hash-bcrypt "admin_password") :roles #{:admin}} "jane" {:username "jane" :password (creds/hash-bcrypt "user_password") :roles #{:user}}}) # # Site Resources (defresource admin-resource :base (r/role-auth #{:admin}) :allowed-methods [:get] :available-media-types ["text/plain"] :handle-ok "Welcome, admin!") (defresource user-resource :base (r/role-auth #{:user}) :allowed-methods [:get] :available-media-types ["text/plain"] :handle-ok "Welcome, user!") (defresource authenticated-resource :base r/authenticated-base :allowed-methods [:get] :available-media-types ["text/plain"] :handle-ok "Come on in. You're authenticated.") (defroutes site-routes (GET "/" [] "Welcome to the liberator-friend demo site!") (GET "/admin" [] admin-resource) (GET "/authenticated" [] authenticated-resource) (GET "/user" [] user-resource)) (def site "Main handler for the example Compojure site." (-> site-routes (auth/friend-middleware users) (api))) (defonce server (atom nil)) (defn kill! [] (swap! server (fn [s] (when s (s) nil)))) (defn -main [] (swap! server (fn [s] (if s (do (println "Server already running!") s) (do (println "Booting server on port 8090.") (run-server (rl/wrap-reload #'site) {})))))) (defn running? "Returns true if the server is currently running, false otherwise." [] (identity @server)) (defn cycle! "Cycles the existing server - shut down the relaunch." [] (kill!) (-main))
68e03755607687414c071b170f99fb632291f2c145ae4ac05ac87514640aaa9e
nlsandler/nqcc
lex.mli
(* Convert C program into a list of tokens *) val lex : string -> Tok.token list (* Get string representation of a token *) val tok_to_string: Tok.token -> string
null
https://raw.githubusercontent.com/nlsandler/nqcc/c30e4c33ec7adfe9710edb948cda380b1fc01715/src/lex.mli
ocaml
Convert C program into a list of tokens Get string representation of a token
val lex : string -> Tok.token list val tok_to_string: Tok.token -> string
f51b07fc66774d2741f8ed6c3a302ad750cd72ded01b32f81e0a861d7a914d5c
PESchoenberg/g2q
example15.scm
#! /usr/local/bin/guile -s !# ;; ============================================================================= ;; ;; example15.scm ;; ;; swap fast ladder test. ;; ;; ============================================================================= ;; Copyright ( C ) 2018 - 2022 Pablo Edronkin ( pablo.edronkin at yahoo.com ) ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public ;; License for more details. ;; You should have received a copy of the GNU Lesser General Public License ;; along with this program. If not, see </>. ;; ;; ============================================================================= ;;;; General notes: ;; ;; - Read sources for limitations on function parameters. ;; ;; Compilation (if you have g2q and qre in your system path): ;; ;; - cd to your /examples folder. ;; ;; - Enter the following: ;; ;; guile example15.scm ;; ;; Notice that you will need to have g2q and qre (see README.md for details) ;; installed on your system and your system path variable set to point to both ;; in order for this program to work properly. Alternatively, you can: ;; ;; - copy example15.scm to the main folder of your qre installation. ;; ;; - Enter the following: ;; ;; guile example15.scm ;; Required modules. (use-modules (g2q g2q0) (g2q g2q1) (g2q g2q2) (g2q g2q3) (grsp grsp0)) Vars and initial stuff . These are editable . (define fname "example15") ; File name (define qpu "qlib_simulator") Clean the json files created in ddir after use . (define qver 2.0) ; OpenQASM version (define qn 5) ; Length of the quantum register. (define cn 5) ; Length of the conventional register (define v "y") ; Verbosity. Vars and initial stuff . Do not edit these . (define ddir (car (g2q-qre-config))) ; Obtain this value from configuration list. (define fnameo (strings-append (list fname ".qasm") 0)) (define q "q") (define c "c") (define mc 0) (define qx 1) (define res 0) ;; qf - Notice that qf is a function that contains the actual code to be compiled ;; into QASM2. The function itself is passed as an argument (higher order ;; function) to function main-loop. Also take in account that the arguments ;; to functions such as this one must match the arguments passed to the functions ;; to which this one is passed as an argument. ;; ;; Arguments: - p_i : counter for qcalls . ;; - p_q: value of q variable. ;; - p_c: c. ;; - p_qnl: p_qn lowest. ;; - p_qnh: p_qn highest. ;; - p_cnl: p_cn lowest. ;; - p_cnh: p_cn highest. ;; (define (qf p_i p_q p_c p_qnl p_qnh p_cnl p_cnh) ;; Prep. (g1y "h" p_q p_qnl p_qnh) ;; cswap "wave"; this doesn't do anything special quantum-mechanically but shows four different ladder variants available . For details , see the ;; documentation for this function (comments on file g2q2.scm.) (swap-fast-ladder p_q p_qnl p_qnh 1) (g1y "barrier" p_q p_qnl p_qnh) (swap-fast-ladder p_q p_qnh p_qnl 2) (g1y "barrier" p_q p_qnl p_qnh) (swap-ladder p_q p_qnl p_qnh 1) (g1y "barrier" p_q p_qnl p_qnh) (swap-ladder p_q p_qnh p_qnl 2) (g1y "barrier" p_q p_qnl p_qnh) ;; Measurement. (qmeasy p_q p_c 0 4) ;; Declarations for internal simulators available on qre. (qdeclare "qx-simulator" "error_model depolarizing_channel,0.001") (qdeclare "qlib-simulator" "// Hello qlib-simulator")) rf - results function . In this case , extract the value . ;; ;; Arguments: ;; - p_b: b. list of results to process. ;; (define (rf p_b) (let ((res 0)) (set! res (car (cdr (qfres p_b "#max")))) res)) ;; qpresent - This is a presentation for the program and what it intends to ;; do. ;; ;; Arguments: ;; - p_ti: title. ;; - p_te: text. ;; - p_en: if you want an <ENT> message to appear. ;; - "y" for yes. ;; - "n" for no. ;; (define (qpresent p_ti p_te p_en) (let ((n 0)) (ptit "=" 60 2 p_ti) (ptit " " 60 0 p_te) (display " ") (newline) (if (eq? p_en "y")(begin (qcomm "Press <ENT> to continue.") (set! n (read)))))) ;; And this is the main program. It gives as a result the decimal absolute and non - probabilistic summation of the values obtained on the execution of ;; each quantum circuit created on each qcall. (qpresent "swap fast ladder" "See g2q2.scm for details" "n") (set! qpu (g2q-select-qpu)) (cond ((equal? qpu "none")(display "\nBye!\n")) (else (begin (newline) (display "Running. Wait...") (newline) (set! res (qmain-loop clean fname fnameo qver ddir qpu qf q c qn cn mc qx v rf)) (newlines 2) (display "Result = ") (display res) (newlines 1))))
null
https://raw.githubusercontent.com/PESchoenberg/g2q/8b971d9e5073ab9f1ccd1b7bbce07e95eb4fefee/examples/example15.scm
scheme
============================================================================= example15.scm swap fast ladder test. ============================================================================= This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. along with this program. If not, see </>. ============================================================================= General notes: - Read sources for limitations on function parameters. Compilation (if you have g2q and qre in your system path): - cd to your /examples folder. - Enter the following: guile example15.scm Notice that you will need to have g2q and qre (see README.md for details) installed on your system and your system path variable set to point to both in order for this program to work properly. Alternatively, you can: - copy example15.scm to the main folder of your qre installation. - Enter the following: guile example15.scm Required modules. File name OpenQASM version Length of the quantum register. Length of the conventional register Verbosity. Obtain this value from configuration list. qf - Notice that qf is a function that contains the actual code to be compiled into QASM2. The function itself is passed as an argument (higher order function) to function main-loop. Also take in account that the arguments to functions such as this one must match the arguments passed to the functions to which this one is passed as an argument. Arguments: - p_q: value of q variable. - p_c: c. - p_qnl: p_qn lowest. - p_qnh: p_qn highest. - p_cnl: p_cn lowest. - p_cnh: p_cn highest. Prep. cswap "wave"; this doesn't do anything special quantum-mechanically but documentation for this function (comments on file g2q2.scm.) Measurement. Declarations for internal simulators available on qre. Arguments: - p_b: b. list of results to process. qpresent - This is a presentation for the program and what it intends to do. Arguments: - p_ti: title. - p_te: text. - p_en: if you want an <ENT> message to appear. - "y" for yes. - "n" for no. And this is the main program. It gives as a result the decimal absolute and each quantum circuit created on each qcall.
#! /usr/local/bin/guile -s !# Copyright ( C ) 2018 - 2022 Pablo Edronkin ( pablo.edronkin at yahoo.com ) the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU Lesser General Public License (use-modules (g2q g2q0) (g2q g2q1) (g2q g2q2) (g2q g2q3) (grsp grsp0)) Vars and initial stuff . These are editable . (define qpu "qlib_simulator") Clean the json files created in ddir after use . Vars and initial stuff . Do not edit these . (define fnameo (strings-append (list fname ".qasm") 0)) (define q "q") (define c "c") (define mc 0) (define qx 1) (define res 0) - p_i : counter for qcalls . (define (qf p_i p_q p_c p_qnl p_qnh p_cnl p_cnh) (g1y "h" p_q p_qnl p_qnh) shows four different ladder variants available . For details , see the (swap-fast-ladder p_q p_qnl p_qnh 1) (g1y "barrier" p_q p_qnl p_qnh) (swap-fast-ladder p_q p_qnh p_qnl 2) (g1y "barrier" p_q p_qnl p_qnh) (swap-ladder p_q p_qnl p_qnh 1) (g1y "barrier" p_q p_qnl p_qnh) (swap-ladder p_q p_qnh p_qnl 2) (g1y "barrier" p_q p_qnl p_qnh) (qmeasy p_q p_c 0 4) (qdeclare "qx-simulator" "error_model depolarizing_channel,0.001") (qdeclare "qlib-simulator" "// Hello qlib-simulator")) rf - results function . In this case , extract the value . (define (rf p_b) (let ((res 0)) (set! res (car (cdr (qfres p_b "#max")))) res)) (define (qpresent p_ti p_te p_en) (let ((n 0)) (ptit "=" 60 2 p_ti) (ptit " " 60 0 p_te) (display " ") (newline) (if (eq? p_en "y")(begin (qcomm "Press <ENT> to continue.") (set! n (read)))))) non - probabilistic summation of the values obtained on the execution of (qpresent "swap fast ladder" "See g2q2.scm for details" "n") (set! qpu (g2q-select-qpu)) (cond ((equal? qpu "none")(display "\nBye!\n")) (else (begin (newline) (display "Running. Wait...") (newline) (set! res (qmain-loop clean fname fnameo qver ddir qpu qf q c qn cn mc qx v rf)) (newlines 2) (display "Result = ") (display res) (newlines 1))))
59f132d10b6a81c471019970dde2194aec3a044ef557e080437f6cf3862b89f8
active-group/active-clojure
figwheel_test_runner.cljs
(ns active.clojure.figwheel-test-runner (:require [figwheel.main.testing :refer-macros [run-tests-async]] [active.clojure.test-deps])) (defn -main [& args] (run-tests-async 10000))
null
https://raw.githubusercontent.com/active-group/active-clojure/44050a1292fa610dde732d5fbfc42c37ad976d3a/dev/active/clojure/figwheel_test_runner.cljs
clojure
(ns active.clojure.figwheel-test-runner (:require [figwheel.main.testing :refer-macros [run-tests-async]] [active.clojure.test-deps])) (defn -main [& args] (run-tests-async 10000))
39a346a399a581034ad58dc1d9e9ef4fe3f711fb24bb8a21815f2d1ad1524fa0
NorfairKing/the-notes
ComputationalProblems.hs
module Cryptography.ComputationalProblems where import Notes hiding (cyclic, inverse) import Functions.Application.Macro import Groups.Macro import Groups.Terms import Logic.PropositionalLogic.Macro import NumberTheory.Macro import NumberTheory.Terms import Probability.ProbabilityMeasure.Terms import Probability.RandomVariable.Terms import Rings.Macro import Rings.Terms import Sets.Basics.Terms import Cryptography.SystemAlgebra.AbstractSystems.Terms import Cryptography.SystemAlgebra.DiscreteSystems.Terms import Cryptography.ComputationalProblems.Abstract import Cryptography.ComputationalProblems.Abstract.Macro import Cryptography.ComputationalProblems.Abstract.Terms import Cryptography.ComputationalProblems.Games import Cryptography.ComputationalProblems.Games.DistinctionProblems.Macro import Cryptography.ComputationalProblems.Games.Macro import Cryptography.ComputationalProblems.Games.Terms import Cryptography.ComputationalProblems.Reductions import Cryptography.ComputationalProblems.Reductions.Terms import Cryptography.ComputationalProblems.Macro import Cryptography.ComputationalProblems.Terms computationalProblemsS :: Note computationalProblemsS = section "Computational Problems" $ do abstractSS reductionsSS gamesSS subsection "Discrete Logarithms" $ do discreteLogarithmProblemDefinition additiveDLEasy dlReducable dlModTwoInEvenOrderGroup dlModTwoToTheKInDivGroup dlNotation lsbProbNotation dlLSBHardness dlRepetitionBoosting subsection "Diffie Hellman" $ do diffieHellmanTripleDefinition computationalDHProblemDefinition decisionalDHProblemDefinition reductionDlToCDH dlNotation :: Note dlNotation = de $ do s ["We use", m $ dlp dlgrp_, "to denote the", discreteLogarithm, searchProblem, "in the", group, m dlgrp_] lsbProbNotation :: Note lsbProbNotation = de $ do let x = "x" y = "y" s ["We use", m $ lsbp dlgrp_, "to denote the", searchProblem, "of finding the", leastSignificantBit, m $ x `mod` 2, "of the", discreteLogarithm, m x, "of a", group, element, m y, "in the", group, m dlgrp_, "chosen uniformly at random"] dlLSBHardness :: Note dlLSBHardness = do thm $ do let h = "h" let grps_ = "H" grp_ = grp "H" grpop_ o = "m" s ["Let", m $ grp_ =: grp (genby h) grpop_, "be a", finite, cyclic, group, "generated by", m $ h ∈ grps_, "of", odd, order, m o] let d = delta e = epsilon sol = "S" lp = lsbp grp_ lpa = spac lp lpw = spwc lp dp = dlpw grp_ q = "Q" center $ s [m dp, is, reducible, to, m lpa] s ["More formally: For any", m $ cs [d, e] ∈ ccint 0 1, "and for any", solver, m sol, for, m lpa, with, performance, "greater than", m e <> ",", "there exists a solver", m q, "for", m dp, with, performance, "at least", m $ 1 - d, "which invokes", m sol, "a polynomial number of times (with respect to", csa [m $ log (1 / d), m $ 1 / e, m $ log o] <> ")", "and otherwise performs only a few simple operations"] newline newline s ["In other words: If, for some", m (d < 1) <> ", there exists no polynomial-time algorithm for solving", m dp, with, performance, "at least", m (1 - d) <> ", then there exists no algorithm for solving", m lpa, "with non-negligible", performance] proof $ do s ["We prove this via a", reduction, from, m dp, to, m lpa] s ["In fact, we will use multiple", reductions] s ["The composition of these", reductions, "will complete the reduction from", m dp, to, m lpa, ref compositionOfReductionsTheoremLabel] newline let n = "n" s ["Let", m n, "be a fixed", integer, "parameter"] s ["We divide the", integer, "interval", m $ ccint 0 (o - 1), "into segments of length", m $ roundu (o / n), "( where the last segment can be shorter)"] let i = "I" s ["Let", m i, "be the interval of", elements, "generated by powers of", m h, "that are in the first segment"] let i_ = setlist (h ^ 0) (h ^ 1) (h ^ (roundu (o / n) - 1)) ma $ i =: i_ ⊆ grps_ let t = "t" s ["Let", m t, "be the number of bits necessary to represent the", discreteLogarithm, "of an", element, "of", m i] ma $ (t =:) $ roundu $ logn 2 $ (roundd $ o / n) + 1 let p = "p" s ["Define", m (p `restrictedTo` i), "as the problem", m p, "where the", instanceSpace, "is restricted to", m i] s ["We complete the proof with the following five reductions"] let reduced = "reduced" let dpi = dp `restrictedTo` i let liw = lpw `restrictedTo` i let j_ = "J" j = fn j_ x = "x" let lsbjx = lpa `restrictedTo` (j x) let a = alpha (<-.) = binop $ comm0 "mapsfrom" hereFigure $ linedTable ["from", "to", "performance", "calls"] [ [dp , dpi , a <-. a , n ] , [dpi , liw , ("" >= 1 - 2 * t * a) <-. (1 - a) , t ] , [liw , liw , "TODO" , "TODO"] , [liw , lsbjx, "TODO" , "TODO"] , [lsbjx, lpa , "TODO" , "TODO"] ] s ["We construct each", reduction, "separately as follows"] enumerate $ do item $ do s ["In the first", reduction, m dp, is, reduced, to, m dpi] newline let sl = "S" si = sl !: i sh = sl !: grps_ s ["Let", m si, "be a", solver, for, m dpi, with, performance, m a] s ["We construct a", solver, m sh, for, m dp, "as follows"] newline let x = "x" y = "y" s ["Let", m $ y =: h ^ x, "be a query where", m $ y ∈ i, "holds"] let l = "l" y' = ((y <> "'") .!:) s ["For each", m l, "in", m (setlist 0 1 (n - 1)) <> ",", m sh, "first computes", m $ y' l, "as follows"] ma $ y' l =: y ** h ^ (- l * roundu (o / n)) =: h ^ (x - l * roundu (o / n)) let x' = ((x <> "'") .!:) s [m sh, "then invokes", m sl, on, m $ y' l, "to obtain", m $ x' l] s ["Note that for one of the values of", m l <> ",", m $ y' l, "will be in", m i] s [m sh, "checkes that", m $ x' l, "is a correct solution by checking the following equation"] ma $ y' l =: h ^ (x' l) s ["If", m $ x' l, "is a valid solution, then the solution for the query", m y, "is calculated as follows"] ma $ x =: x' l + l * roundu (o / n) s ["This means that", m sh, "needs to invoke", m si, "at most", m n, "times and has", performance, m a] item $ do s ["In the second", reduction, m dpi, is, reduced, to, m liw] let sl = "S" sli = sl !: "L" sdi = sl !: "D" newline s ["Let", m sli, "be a", solver, for, m liw, with, performance, m $ 1 - alpha] s ["We construct a", solver, m sdi, for, m dpi, "as follows"] newline let x = "x" y = "y" s ["Let", m $ y =: h ^ x, "be a query"] let b = "b" s [m sdi, "determines (guess for) the", leastSignificantBit, m b, "of", m x, "by invoking", m sli] s [m sdi, "does check whether (or do anything different if)", m b, "is incorrect"] let y' = y <> "'" s ["It then computes", m y', "as follows", ref finiteOddGroupRootComputationTheoremLabel] ma $ (y' =:) $ cases $ do y ** h ^ (-1) & text "if " <> m b =: 1 lnbk y & text "otherwise" let x' = x <> "'" s ["Now the power", m x', "of", m h, "that", m y', "represents is", even] let z = "z" s ["Because", m o, is, odd, "we can compute the (unique)" <> ref squareRootUniqueInFiniteOddGroupTheoremLabel, squareRoot, m z, "of", m y', "as follows", ref finiteOddGroupRootComputationTheoremLabel] ma $ z =: y' ^ ((o + 1) / 2) =: h ^ (x' / 2) =: h ^ (roundd $ x / 2) s ["We then repeat this process with", m z, "instead of", m y, "to compute the next", leastSignificantBit, "of", m x] s ["After", m $ roundu $ logn 2 x, "invocations of", m sli <> ",", m sdi, "has computed all the bits of", m x, "and therefore", m x] s ["Because", m y, "is in", m i <> ",", m x, "must be in", m $ setlist 0 1 (roundu (o / n) - 1), "and therefore", m $ roundu $ log2 x, "will be smaller than", m t] clarify "How does it exactly compute x? make a reference, don't show it here." s [the, performance, "of", m sdi, "is then at least", m $ 1 - 2 * t * a, ref unionBoundTheoremLabel] why_ "exactly? union bound doesn't help as much as it should" toprove nte $ do s ["We assert that the", order, is, odd, "because otherwise guessing the LSB is easy", ref dLModTwoInEvenOrderGroupTheoremLabel] discreteLogarithmProblemDefinition :: Note discreteLogarithmProblemDefinition = do de $ do lab discreteLogarithmDefinitionLabel lab dLDefinitionLabel let aa = "A" a = "a" g = "g" s [the, discreteLogarithm', "(" <> dL' <> ")", searchProblem, "for a", cyclic_, group, m $ grp_ =: grp (genby g) grpop_, "is the problem of computing, for a given", group, element, m $ aa ∈ grps_, "the exponent", m $ int a, " such that", m $ aa =: g ^ a, "holds"] s ["Formally: let", m grps_, "be the", instanceSpace, "of a", searchProblem, "with", witnessSpace, m $ setsize grps_ <> ",", "the following", predicate, m spred_, "and the uniform instance distribution of", group, elements] let x = "x" w = "w" ma $ (sol x w) ⇔ (g ^ w =: x) nte $ do s ["Note that the", discreteLogarithm, "for a given", group, and, base, "is also a", functionInversion, searchProblem] additiveDLEasy :: Note additiveDLEasy = thm $ do let n = "n" s [the, discreteLogarithm, "problem is trivially solvable in the", group, m $ intagrp n] proof $ do let z = "z" a = "a" g = "g" s ["Recall that, for any element", m (z ∈ intmod n) <> ", we are looking for the integer", m $ int a, "such that", m $ z =: g * a, "where", m g, "is a", generator, "of", m $ intagrp n] s ["Luckily, ", m $ intagrp n, "gives rise to a", ring, m $ intring n, "as well"] s ["This allows us to find", m a, "by dividing", m z, by, m g] s ["More precicely: because", m g, "is a", generator, "means that", m g, "must have a multiplicative inverse in", m $ intring n, "otherwise no multiple of", m g, "would be equal to", m 1] s ["Now the only thing we need to do is go through the", elements, "of", m $ intmod n, "multiply each of them by", m g, "in", m $ intring n, "and check if the result equals", m 1, "to find the multiplicative inverse", m $ rinv g, "of", m g, "in", m $ intring n] s ["We then compute", m a, "by evaluating", m $ rinv g * z =: rinv g * g * a =: a] s ["We could also use the extended Euclidean algorithm to find", m $ rinv g, "even more efficiently"] refneeded "Extended Euclidean algorithm" dlReducable :: Note dlReducable = thm $ do let g = "g" h = "h" s [the, discreteLogarithm, "problem in a", group, m grp_, "for a", generator, m g, "is reducable to the", discreteLogarithm, "problem in that same", group, "but for a different", generator] proof $ do let a = "A" s ["Let", m a, "be an algorithm that solves the", discreteLogarithm, "problem for a", generator, m g] s ["We construct an algorithm that solves the", discreteLogarithm, "problem for another", generator, m h, "of", m grp_, "as follows"] let z = "z" b = "b" c = "c" s ["Let", m z, "be the", group, element, "that we want the", discreteLogarithm, m b, "base", m h, "in", m grp_, "of"] s ["There then exists a", m $ int c, "such that", m c, "is the", discreteLogarithm, "base", m g, "in", m grp_, "of", m z] ma $ z =: h ^ b =: g ^ c let d = "d" s ["Because", m h, "is an", element, "of", m grps_ <> ",", "there exists a", m $ int d, "such that", m $ h =: g ^ d, "holds"] ma $ z =: (pars $ g ^ d) ^ b =: g ^ c s ["This means that we have the following equation for", m c, "in", m $ intring $ ord grps_] ma $ d * b =: c s ["The algorithm now uses", m a, "to find", m c, from, m z, and, m d, from, m h] s ["It then computes the multiplicative inverse of", m d, "in", m $ intring $ ord grps_, "with the extended Euclidean algorithm and finally computes", m b, "by evaluating", m $ rinv d * c =: rinv d * d * b =: b] dlModTwoInEvenOrderGroup :: Note dlModTwoInEvenOrderGroup = thm $ do lab dLModTwoInEvenOrderGroupTheoremLabel let n = "n" s ["Let", m grp_, beA, group, with, "an", even, order, m $ ord grp_ =: 2 * n] s ["There exists an efficient algorithm to compute whether the", discreteLogarithm, "of an", element, "is even or not"] proof $ do let x = "x" s ["Let", m x, beAn, element, "of", m grps_] let g = "g" a = "a" s ["For a given base", m g, "the task is to compute", m $ a `mod` 2, "such that", m $ x =: g ^ a, "holds"] let q = "q" r = "r" s ["Define", m q, and, m r, "as the quotient and rest after division by", m 2, "of", m a] s ["Observe first the following"] ma $ x ^ n =: g ^ (a * n) =: g ^ ((pars $ 2 * q + r) * n) =: g ^ (2 * n * q) ** (g ^ (r * n) =: g ^ (r * n)) s ["This means that", m $ x ^ n, "will be equal to the", neutralElement, "if", m a, "is even and", m $ g ^ n, "(which cannot be the", neutralElement, "because", m g, "is a", generator, and, m grp_, "has", order, m (2 * n) <> ") if", m a, "is odd"] s ["We only have to compare", m $ x ^ n, "to the", neutralElement, "to determine", m $ a `mod` 2] dlModTwoToTheKInDivGroup :: Note dlModTwoToTheKInDivGroup = thm $ do let n = "n" k = "k" s ["Let", m grp_, beA, group, with, "an", order, m $ ord grp_ =: 2^k * n, "for some", m k] s ["There exists an efficient algorithm to compute the", discreteLogarithm, "of an", element, "modulo", m $ 2^k] toprove dlRepetitionBoosting :: Note dlRepetitionBoosting = do thm $ do let g = "g" grp_ = grp (genby g) grpop_ q = "q" s ["Let", m grp_, "be a", cyclic, group, "of order", m q] let sl = "S" sl' = "S'" a = alpha s ["If there exists a", deterministicSearchProblemSolver, m sl, for, m $ dlp grp_, with, successProbability, m a <> ",", "then it can be used to build a", deterministicSearchProblemSolver, m sl', with, successProbability, "strictly greater than", m a] s ["That is", m sl, "outputs the same result for the same arguments, but a randomly chosen", element, "will yield a correct result with", probability, m a] proof $ do s ["For a given result, it can be checked whether that result is correct, but since", m sl, "is deterministic, that will not get us any farther as-is"] s ["The idea is to repeat the invocation of", m sl, on, elements, "of", m grps_, "that are different from, but related to the query in such a way that the would-be result for the original query can be derived from the results of the new elements"] newline let h = "h" x = "x" c = "c" s ["Let", m $ h =: g ^ x ∈ grps_, "be an input for", m sl', and, m $ nat c, "a constant"] s [m sl', "will operate as follows"] let r = "r" itemize $ do item $ do s [m sl', "chooses", m $ r ∈ intmod q, "uniformly at random and invokes", m sl, "on", m $ h ** g ^ r =: g ^ (x + r)] let y = "y" z = "z" item $ do s [the, "output", m y, from, m sl, "is checked for correctness by checking that", m $ g ^ y, "equals", m $ h ** g ^ r] item $ do s ["If the ouput from", m sl, "is correct for input", m $ h ** g ^ r, "then", m sl', "computes", m $ z =: y - r] s ["This must then equal", m x, "so", m sl', "outputs it"] item $ do s ["If the output from", m sl, "is not correct, it tries again with another randomly chosen", element, from, m $ intmod q, "for at most", m c, "times, after which it will just output the last gotten output from", m a] s ["Note that", m sl, "succeeds with", probability, m a, "because", m $ h ** g ^ r, "is a uniformly random element"] s ["Hence, the success", probability, "of", m sl', "is bigger than that of", m sl] ma $ 1 - (pars $ 1 - a) ^ c > a nte $ do s ["The crucial property of the above algorithm is that it invokes its subroutine each time on a uniformly random instance such that the output can be used to construct an output for the given query"] s ["In general the output for an other uniformly random instance cannot be transformed back to a solution to the original instance."] s ["Problems that allow this are called random self-reducible"] todo "Defined random self-reducible formally and separately" diffieHellmanTripleDefinition :: Note diffieHellmanTripleDefinition = de $ do lab diffieHellmanTripleDefinitionLabel let a = "a" b = "b" g = "g" s ["A", diffieHellmanTriple', "in a given", cyclic, group, m $ grp_ =: grp (genby g) grpop_, "is a triple of the form", m $ triple (g ^ a) (g ^ b) (g ^ (a * b)), "where", m a, and, m b, "are whole numbers"] computationalDHProblemDefinition :: Note computationalDHProblemDefinition = de $ do lab computationalDiffieHellmanDefinitionLabel lab cDHDefinitionLabel let a = "a" b = "b" g = "g" grp_ = grp (genby g) grpop_ ga = g ^ a gb = g ^ b gab = g ^ (a * b) s [the, computationalDiffieHellman, "(" <> cDH' <> ")", "problem for a given", cyclic, group, m grp_, "is the problem of computing, for given group elements", m ga, and, m gb, "the group element", m gab] newline s ["More formally,", m $ cdhp grp_, "is the", nS 2, "that outputs", m $ triple g ga gb, "at its inside", interface, "and outputs", m 1, "at its outside", interface, "if it subsequently receives", m gab, "at that", interface] decisionalDHProblemDefinition :: Note decisionalDHProblemDefinition = de $ do lab computationalDiffieHellmanDefinitionLabel lab cDHDefinitionLabel let a = "a" b = "b" c = "c" g = "g" grp_ = grp (genby g) grpop_ ga = g ^ a gb = g ^ b gc = g ^ c gab = g ^ (a * b) s [the, decisionalDiffieHellman', "(" <> dDH' <> ")", "problem for a given", cyclic, group, m grp_, "is the problem of determining whether, for given group elements", (m ga) <> ",", m gb, and, m gc, "whether they are chosen randomly and independently from", m grps_, "or form a", diffieHellmanTriple] newline let t = "T" !: grp_ r = "R" !: grp_ s ["More formally,", m $ ddhp grp_, "is the", distinctionProblem, m $ dprob t r, "between two", nPSs 1, m t, and, m r] itemize $ do item $ do let tab = t !: cs [a, b] s [m t, "is the", nPS 1, "that is the", randomVariable, "with uniform distribution over the", nDSs 1, m tab, "that output", m $ triple ga gb gab, "and at their", interface, "and do nothing else"] s ["Here", m a, and, m b, "are", elements, "of", m $ intmod $ setsize grps_] item $ do let rabc = r !: cs [a, b, c] s [m r, "is the", nPS 1, "that is the", randomVariable, "with uniform distribution over the", nDSs 1, m rabc, "that output", m $ triple a b c, "at their", interface, "and do nothing else"] s ["Here", csa [m a, m b, m c], "are", elements, "of", m grps_] reductionDlToCDH :: Note reductionDlToCDH = thm $ do let g = "g" grp_ = grp (genby g) grpop_ s ["For a given", cyclic, group, m grp_ <> ",", "the", discreteLogarithm, problem, m $ dlp grp_, is, reducible, "to the", computationalDiffieHellman, problem, m $ cdhp grp_] toprove
null
https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Cryptography/ComputationalProblems.hs
haskell
module Cryptography.ComputationalProblems where import Notes hiding (cyclic, inverse) import Functions.Application.Macro import Groups.Macro import Groups.Terms import Logic.PropositionalLogic.Macro import NumberTheory.Macro import NumberTheory.Terms import Probability.ProbabilityMeasure.Terms import Probability.RandomVariable.Terms import Rings.Macro import Rings.Terms import Sets.Basics.Terms import Cryptography.SystemAlgebra.AbstractSystems.Terms import Cryptography.SystemAlgebra.DiscreteSystems.Terms import Cryptography.ComputationalProblems.Abstract import Cryptography.ComputationalProblems.Abstract.Macro import Cryptography.ComputationalProblems.Abstract.Terms import Cryptography.ComputationalProblems.Games import Cryptography.ComputationalProblems.Games.DistinctionProblems.Macro import Cryptography.ComputationalProblems.Games.Macro import Cryptography.ComputationalProblems.Games.Terms import Cryptography.ComputationalProblems.Reductions import Cryptography.ComputationalProblems.Reductions.Terms import Cryptography.ComputationalProblems.Macro import Cryptography.ComputationalProblems.Terms computationalProblemsS :: Note computationalProblemsS = section "Computational Problems" $ do abstractSS reductionsSS gamesSS subsection "Discrete Logarithms" $ do discreteLogarithmProblemDefinition additiveDLEasy dlReducable dlModTwoInEvenOrderGroup dlModTwoToTheKInDivGroup dlNotation lsbProbNotation dlLSBHardness dlRepetitionBoosting subsection "Diffie Hellman" $ do diffieHellmanTripleDefinition computationalDHProblemDefinition decisionalDHProblemDefinition reductionDlToCDH dlNotation :: Note dlNotation = de $ do s ["We use", m $ dlp dlgrp_, "to denote the", discreteLogarithm, searchProblem, "in the", group, m dlgrp_] lsbProbNotation :: Note lsbProbNotation = de $ do let x = "x" y = "y" s ["We use", m $ lsbp dlgrp_, "to denote the", searchProblem, "of finding the", leastSignificantBit, m $ x `mod` 2, "of the", discreteLogarithm, m x, "of a", group, element, m y, "in the", group, m dlgrp_, "chosen uniformly at random"] dlLSBHardness :: Note dlLSBHardness = do thm $ do let h = "h" let grps_ = "H" grp_ = grp "H" grpop_ o = "m" s ["Let", m $ grp_ =: grp (genby h) grpop_, "be a", finite, cyclic, group, "generated by", m $ h ∈ grps_, "of", odd, order, m o] let d = delta e = epsilon sol = "S" lp = lsbp grp_ lpa = spac lp lpw = spwc lp dp = dlpw grp_ q = "Q" center $ s [m dp, is, reducible, to, m lpa] s ["More formally: For any", m $ cs [d, e] ∈ ccint 0 1, "and for any", solver, m sol, for, m lpa, with, performance, "greater than", m e <> ",", "there exists a solver", m q, "for", m dp, with, performance, "at least", m $ 1 - d, "which invokes", m sol, "a polynomial number of times (with respect to", csa [m $ log (1 / d), m $ 1 / e, m $ log o] <> ")", "and otherwise performs only a few simple operations"] newline newline s ["In other words: If, for some", m (d < 1) <> ", there exists no polynomial-time algorithm for solving", m dp, with, performance, "at least", m (1 - d) <> ", then there exists no algorithm for solving", m lpa, "with non-negligible", performance] proof $ do s ["We prove this via a", reduction, from, m dp, to, m lpa] s ["In fact, we will use multiple", reductions] s ["The composition of these", reductions, "will complete the reduction from", m dp, to, m lpa, ref compositionOfReductionsTheoremLabel] newline let n = "n" s ["Let", m n, "be a fixed", integer, "parameter"] s ["We divide the", integer, "interval", m $ ccint 0 (o - 1), "into segments of length", m $ roundu (o / n), "( where the last segment can be shorter)"] let i = "I" s ["Let", m i, "be the interval of", elements, "generated by powers of", m h, "that are in the first segment"] let i_ = setlist (h ^ 0) (h ^ 1) (h ^ (roundu (o / n) - 1)) ma $ i =: i_ ⊆ grps_ let t = "t" s ["Let", m t, "be the number of bits necessary to represent the", discreteLogarithm, "of an", element, "of", m i] ma $ (t =:) $ roundu $ logn 2 $ (roundd $ o / n) + 1 let p = "p" s ["Define", m (p `restrictedTo` i), "as the problem", m p, "where the", instanceSpace, "is restricted to", m i] s ["We complete the proof with the following five reductions"] let reduced = "reduced" let dpi = dp `restrictedTo` i let liw = lpw `restrictedTo` i let j_ = "J" j = fn j_ x = "x" let lsbjx = lpa `restrictedTo` (j x) let a = alpha (<-.) = binop $ comm0 "mapsfrom" hereFigure $ linedTable ["from", "to", "performance", "calls"] [ [dp , dpi , a <-. a , n ] , [dpi , liw , ("" >= 1 - 2 * t * a) <-. (1 - a) , t ] , [liw , liw , "TODO" , "TODO"] , [liw , lsbjx, "TODO" , "TODO"] , [lsbjx, lpa , "TODO" , "TODO"] ] s ["We construct each", reduction, "separately as follows"] enumerate $ do item $ do s ["In the first", reduction, m dp, is, reduced, to, m dpi] newline let sl = "S" si = sl !: i sh = sl !: grps_ s ["Let", m si, "be a", solver, for, m dpi, with, performance, m a] s ["We construct a", solver, m sh, for, m dp, "as follows"] newline let x = "x" y = "y" s ["Let", m $ y =: h ^ x, "be a query where", m $ y ∈ i, "holds"] let l = "l" y' = ((y <> "'") .!:) s ["For each", m l, "in", m (setlist 0 1 (n - 1)) <> ",", m sh, "first computes", m $ y' l, "as follows"] ma $ y' l =: y ** h ^ (- l * roundu (o / n)) =: h ^ (x - l * roundu (o / n)) let x' = ((x <> "'") .!:) s [m sh, "then invokes", m sl, on, m $ y' l, "to obtain", m $ x' l] s ["Note that for one of the values of", m l <> ",", m $ y' l, "will be in", m i] s [m sh, "checkes that", m $ x' l, "is a correct solution by checking the following equation"] ma $ y' l =: h ^ (x' l) s ["If", m $ x' l, "is a valid solution, then the solution for the query", m y, "is calculated as follows"] ma $ x =: x' l + l * roundu (o / n) s ["This means that", m sh, "needs to invoke", m si, "at most", m n, "times and has", performance, m a] item $ do s ["In the second", reduction, m dpi, is, reduced, to, m liw] let sl = "S" sli = sl !: "L" sdi = sl !: "D" newline s ["Let", m sli, "be a", solver, for, m liw, with, performance, m $ 1 - alpha] s ["We construct a", solver, m sdi, for, m dpi, "as follows"] newline let x = "x" y = "y" s ["Let", m $ y =: h ^ x, "be a query"] let b = "b" s [m sdi, "determines (guess for) the", leastSignificantBit, m b, "of", m x, "by invoking", m sli] s [m sdi, "does check whether (or do anything different if)", m b, "is incorrect"] let y' = y <> "'" s ["It then computes", m y', "as follows", ref finiteOddGroupRootComputationTheoremLabel] ma $ (y' =:) $ cases $ do y ** h ^ (-1) & text "if " <> m b =: 1 lnbk y & text "otherwise" let x' = x <> "'" s ["Now the power", m x', "of", m h, "that", m y', "represents is", even] let z = "z" s ["Because", m o, is, odd, "we can compute the (unique)" <> ref squareRootUniqueInFiniteOddGroupTheoremLabel, squareRoot, m z, "of", m y', "as follows", ref finiteOddGroupRootComputationTheoremLabel] ma $ z =: y' ^ ((o + 1) / 2) =: h ^ (x' / 2) =: h ^ (roundd $ x / 2) s ["We then repeat this process with", m z, "instead of", m y, "to compute the next", leastSignificantBit, "of", m x] s ["After", m $ roundu $ logn 2 x, "invocations of", m sli <> ",", m sdi, "has computed all the bits of", m x, "and therefore", m x] s ["Because", m y, "is in", m i <> ",", m x, "must be in", m $ setlist 0 1 (roundu (o / n) - 1), "and therefore", m $ roundu $ log2 x, "will be smaller than", m t] clarify "How does it exactly compute x? make a reference, don't show it here." s [the, performance, "of", m sdi, "is then at least", m $ 1 - 2 * t * a, ref unionBoundTheoremLabel] why_ "exactly? union bound doesn't help as much as it should" toprove nte $ do s ["We assert that the", order, is, odd, "because otherwise guessing the LSB is easy", ref dLModTwoInEvenOrderGroupTheoremLabel] discreteLogarithmProblemDefinition :: Note discreteLogarithmProblemDefinition = do de $ do lab discreteLogarithmDefinitionLabel lab dLDefinitionLabel let aa = "A" a = "a" g = "g" s [the, discreteLogarithm', "(" <> dL' <> ")", searchProblem, "for a", cyclic_, group, m $ grp_ =: grp (genby g) grpop_, "is the problem of computing, for a given", group, element, m $ aa ∈ grps_, "the exponent", m $ int a, " such that", m $ aa =: g ^ a, "holds"] s ["Formally: let", m grps_, "be the", instanceSpace, "of a", searchProblem, "with", witnessSpace, m $ setsize grps_ <> ",", "the following", predicate, m spred_, "and the uniform instance distribution of", group, elements] let x = "x" w = "w" ma $ (sol x w) ⇔ (g ^ w =: x) nte $ do s ["Note that the", discreteLogarithm, "for a given", group, and, base, "is also a", functionInversion, searchProblem] additiveDLEasy :: Note additiveDLEasy = thm $ do let n = "n" s [the, discreteLogarithm, "problem is trivially solvable in the", group, m $ intagrp n] proof $ do let z = "z" a = "a" g = "g" s ["Recall that, for any element", m (z ∈ intmod n) <> ", we are looking for the integer", m $ int a, "such that", m $ z =: g * a, "where", m g, "is a", generator, "of", m $ intagrp n] s ["Luckily, ", m $ intagrp n, "gives rise to a", ring, m $ intring n, "as well"] s ["This allows us to find", m a, "by dividing", m z, by, m g] s ["More precicely: because", m g, "is a", generator, "means that", m g, "must have a multiplicative inverse in", m $ intring n, "otherwise no multiple of", m g, "would be equal to", m 1] s ["Now the only thing we need to do is go through the", elements, "of", m $ intmod n, "multiply each of them by", m g, "in", m $ intring n, "and check if the result equals", m 1, "to find the multiplicative inverse", m $ rinv g, "of", m g, "in", m $ intring n] s ["We then compute", m a, "by evaluating", m $ rinv g * z =: rinv g * g * a =: a] s ["We could also use the extended Euclidean algorithm to find", m $ rinv g, "even more efficiently"] refneeded "Extended Euclidean algorithm" dlReducable :: Note dlReducable = thm $ do let g = "g" h = "h" s [the, discreteLogarithm, "problem in a", group, m grp_, "for a", generator, m g, "is reducable to the", discreteLogarithm, "problem in that same", group, "but for a different", generator] proof $ do let a = "A" s ["Let", m a, "be an algorithm that solves the", discreteLogarithm, "problem for a", generator, m g] s ["We construct an algorithm that solves the", discreteLogarithm, "problem for another", generator, m h, "of", m grp_, "as follows"] let z = "z" b = "b" c = "c" s ["Let", m z, "be the", group, element, "that we want the", discreteLogarithm, m b, "base", m h, "in", m grp_, "of"] s ["There then exists a", m $ int c, "such that", m c, "is the", discreteLogarithm, "base", m g, "in", m grp_, "of", m z] ma $ z =: h ^ b =: g ^ c let d = "d" s ["Because", m h, "is an", element, "of", m grps_ <> ",", "there exists a", m $ int d, "such that", m $ h =: g ^ d, "holds"] ma $ z =: (pars $ g ^ d) ^ b =: g ^ c s ["This means that we have the following equation for", m c, "in", m $ intring $ ord grps_] ma $ d * b =: c s ["The algorithm now uses", m a, "to find", m c, from, m z, and, m d, from, m h] s ["It then computes the multiplicative inverse of", m d, "in", m $ intring $ ord grps_, "with the extended Euclidean algorithm and finally computes", m b, "by evaluating", m $ rinv d * c =: rinv d * d * b =: b] dlModTwoInEvenOrderGroup :: Note dlModTwoInEvenOrderGroup = thm $ do lab dLModTwoInEvenOrderGroupTheoremLabel let n = "n" s ["Let", m grp_, beA, group, with, "an", even, order, m $ ord grp_ =: 2 * n] s ["There exists an efficient algorithm to compute whether the", discreteLogarithm, "of an", element, "is even or not"] proof $ do let x = "x" s ["Let", m x, beAn, element, "of", m grps_] let g = "g" a = "a" s ["For a given base", m g, "the task is to compute", m $ a `mod` 2, "such that", m $ x =: g ^ a, "holds"] let q = "q" r = "r" s ["Define", m q, and, m r, "as the quotient and rest after division by", m 2, "of", m a] s ["Observe first the following"] ma $ x ^ n =: g ^ (a * n) =: g ^ ((pars $ 2 * q + r) * n) =: g ^ (2 * n * q) ** (g ^ (r * n) =: g ^ (r * n)) s ["This means that", m $ x ^ n, "will be equal to the", neutralElement, "if", m a, "is even and", m $ g ^ n, "(which cannot be the", neutralElement, "because", m g, "is a", generator, and, m grp_, "has", order, m (2 * n) <> ") if", m a, "is odd"] s ["We only have to compare", m $ x ^ n, "to the", neutralElement, "to determine", m $ a `mod` 2] dlModTwoToTheKInDivGroup :: Note dlModTwoToTheKInDivGroup = thm $ do let n = "n" k = "k" s ["Let", m grp_, beA, group, with, "an", order, m $ ord grp_ =: 2^k * n, "for some", m k] s ["There exists an efficient algorithm to compute the", discreteLogarithm, "of an", element, "modulo", m $ 2^k] toprove dlRepetitionBoosting :: Note dlRepetitionBoosting = do thm $ do let g = "g" grp_ = grp (genby g) grpop_ q = "q" s ["Let", m grp_, "be a", cyclic, group, "of order", m q] let sl = "S" sl' = "S'" a = alpha s ["If there exists a", deterministicSearchProblemSolver, m sl, for, m $ dlp grp_, with, successProbability, m a <> ",", "then it can be used to build a", deterministicSearchProblemSolver, m sl', with, successProbability, "strictly greater than", m a] s ["That is", m sl, "outputs the same result for the same arguments, but a randomly chosen", element, "will yield a correct result with", probability, m a] proof $ do s ["For a given result, it can be checked whether that result is correct, but since", m sl, "is deterministic, that will not get us any farther as-is"] s ["The idea is to repeat the invocation of", m sl, on, elements, "of", m grps_, "that are different from, but related to the query in such a way that the would-be result for the original query can be derived from the results of the new elements"] newline let h = "h" x = "x" c = "c" s ["Let", m $ h =: g ^ x ∈ grps_, "be an input for", m sl', and, m $ nat c, "a constant"] s [m sl', "will operate as follows"] let r = "r" itemize $ do item $ do s [m sl', "chooses", m $ r ∈ intmod q, "uniformly at random and invokes", m sl, "on", m $ h ** g ^ r =: g ^ (x + r)] let y = "y" z = "z" item $ do s [the, "output", m y, from, m sl, "is checked for correctness by checking that", m $ g ^ y, "equals", m $ h ** g ^ r] item $ do s ["If the ouput from", m sl, "is correct for input", m $ h ** g ^ r, "then", m sl', "computes", m $ z =: y - r] s ["This must then equal", m x, "so", m sl', "outputs it"] item $ do s ["If the output from", m sl, "is not correct, it tries again with another randomly chosen", element, from, m $ intmod q, "for at most", m c, "times, after which it will just output the last gotten output from", m a] s ["Note that", m sl, "succeeds with", probability, m a, "because", m $ h ** g ^ r, "is a uniformly random element"] s ["Hence, the success", probability, "of", m sl', "is bigger than that of", m sl] ma $ 1 - (pars $ 1 - a) ^ c > a nte $ do s ["The crucial property of the above algorithm is that it invokes its subroutine each time on a uniformly random instance such that the output can be used to construct an output for the given query"] s ["In general the output for an other uniformly random instance cannot be transformed back to a solution to the original instance."] s ["Problems that allow this are called random self-reducible"] todo "Defined random self-reducible formally and separately" diffieHellmanTripleDefinition :: Note diffieHellmanTripleDefinition = de $ do lab diffieHellmanTripleDefinitionLabel let a = "a" b = "b" g = "g" s ["A", diffieHellmanTriple', "in a given", cyclic, group, m $ grp_ =: grp (genby g) grpop_, "is a triple of the form", m $ triple (g ^ a) (g ^ b) (g ^ (a * b)), "where", m a, and, m b, "are whole numbers"] computationalDHProblemDefinition :: Note computationalDHProblemDefinition = de $ do lab computationalDiffieHellmanDefinitionLabel lab cDHDefinitionLabel let a = "a" b = "b" g = "g" grp_ = grp (genby g) grpop_ ga = g ^ a gb = g ^ b gab = g ^ (a * b) s [the, computationalDiffieHellman, "(" <> cDH' <> ")", "problem for a given", cyclic, group, m grp_, "is the problem of computing, for given group elements", m ga, and, m gb, "the group element", m gab] newline s ["More formally,", m $ cdhp grp_, "is the", nS 2, "that outputs", m $ triple g ga gb, "at its inside", interface, "and outputs", m 1, "at its outside", interface, "if it subsequently receives", m gab, "at that", interface] decisionalDHProblemDefinition :: Note decisionalDHProblemDefinition = de $ do lab computationalDiffieHellmanDefinitionLabel lab cDHDefinitionLabel let a = "a" b = "b" c = "c" g = "g" grp_ = grp (genby g) grpop_ ga = g ^ a gb = g ^ b gc = g ^ c gab = g ^ (a * b) s [the, decisionalDiffieHellman', "(" <> dDH' <> ")", "problem for a given", cyclic, group, m grp_, "is the problem of determining whether, for given group elements", (m ga) <> ",", m gb, and, m gc, "whether they are chosen randomly and independently from", m grps_, "or form a", diffieHellmanTriple] newline let t = "T" !: grp_ r = "R" !: grp_ s ["More formally,", m $ ddhp grp_, "is the", distinctionProblem, m $ dprob t r, "between two", nPSs 1, m t, and, m r] itemize $ do item $ do let tab = t !: cs [a, b] s [m t, "is the", nPS 1, "that is the", randomVariable, "with uniform distribution over the", nDSs 1, m tab, "that output", m $ triple ga gb gab, "and at their", interface, "and do nothing else"] s ["Here", m a, and, m b, "are", elements, "of", m $ intmod $ setsize grps_] item $ do let rabc = r !: cs [a, b, c] s [m r, "is the", nPS 1, "that is the", randomVariable, "with uniform distribution over the", nDSs 1, m rabc, "that output", m $ triple a b c, "at their", interface, "and do nothing else"] s ["Here", csa [m a, m b, m c], "are", elements, "of", m grps_] reductionDlToCDH :: Note reductionDlToCDH = thm $ do let g = "g" grp_ = grp (genby g) grpop_ s ["For a given", cyclic, group, m grp_ <> ",", "the", discreteLogarithm, problem, m $ dlp grp_, is, reducible, "to the", computationalDiffieHellman, problem, m $ cdhp grp_] toprove
5cdea1942f2c6c8630686621f61d40c44d5f6793d47c960eb9e14a7a909e0031
clash-lang/clash-compiler
T895.hs
module T895 where import Clash.Prelude topEntity :: Maybe (Vec 2 (Signed 8), Index 1) topEntity = Just (pure 0, 0)
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldwork/Vector/T895.hs
haskell
module T895 where import Clash.Prelude topEntity :: Maybe (Vec 2 (Signed 8), Index 1) topEntity = Just (pure 0, 0)
c17c142dddfd2cb067875097af24141f497ce4feadb02549288a5dc5a23af39e
TrustInSoft/tis-interpreter
non_linear_evaluation.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Cil_types module Ki = Cil_datatype.Kinstr open Cvalue open Eval let dkey = Value_parameters.register_category "nonlin" let (>>=) (t, a) f = match t with | `Bottom -> `Bottom, a | `Value t -> f t a let (>>=:) (t, a) f = match t with | `Bottom -> `Bottom, a | `Value t -> f t, a let (>>-) t f = match t with | `Bottom -> `Bottom | `Value t -> f t let (>>-:) t f = match t with | `Bottom -> `Bottom | `Value t -> `Value (f t) module LvalList = Datatype.List (Cil_datatype.LvalStructEq) module LvalHTbl = Cil_datatype.LvalStructEq.Hashtbl module Non_linear_expressions = State_builder.Hashtbl (Cil_datatype.Exp.Hashtbl) (LvalList) (struct let name = "Non_linear_evaluation" let size = 16 let dependencies = [ Ast.self ] end) class do_non_linear_assignments = object(self) inherit Visitor.frama_c_inplace val found = LvalHTbl.create 16 method private store_non_linear e = let flatten lval count acc = if count > 1 then lval :: acc else acc in let list = LvalHTbl.fold flatten found [] in List.iter (fun lval -> Value_parameters.result ~current:true ~once:true ~dkey "non-linear '%a', lv '%a'" Printer.pp_exp e Printer.pp_lval lval) list; LvalHTbl.clear found; Non_linear_expressions.replace e list; list method! vlval lv = let cur = try LvalHTbl.find found lv with Not_found -> 0 in LvalHTbl.replace found lv (cur+1); Cil.DoChildren (* visit the l-values inside e.g. t[i] *) method! vexpr exp = match exp.enode with | Lval _ | UnOp _ | BinOp _ | CastE _ | Info _ -> Cil.DoChildren | _ -> (* None other expr contain a dereferenced l-value *) Cil.SkipChildren method! vtype _ = Cil.SkipChildren method v_full_exp exp = LvalHTbl.clear found; ignore (Visitor.visitFramacExpr (self:>Visitor.frama_c_inplace) exp); self#store_non_linear exp end let compute_non_linear exp = try Non_linear_expressions.find exp with Not_found -> let c = new do_non_linear_assignments in c#v_full_exp exp exception Too_linear let min_and_max_float v = try let i = V.project_ival v in let f1, f2 = Ival.min_and_max_float i in V.inject_float f1, V.inject_float f2 with V.Not_based_on_null -> assert false let subdiv_float ~size v = try let v_ival = V.project_ival v in let ival1, ival2 = Ival.subdiv_float_interval ~size v_ival in V.inject_ival ival1, V.inject_ival ival2 with V.Not_based_on_null -> assert false let min_and_max_int v = try let i = V.project_ival v in match Ival.min_and_max i with | None, _ | _, None -> raise Too_linear | Some i1, Some i2 -> V.inject_int i1, V.inject_int i2 with V.Not_based_on_null -> assert false let subdiv_int ~size:_ v = try let i = V.project_ival v in let l, h = Ival.subdiv_int i in V.inject_ival l, V.inject_ival h with V.Not_based_on_null -> assert false (* [make_split lval loc value] makes a split function for the lval [lval] with location [loc] and abstract value [value]. Raise Too_linear if the value contains pointer. *) let make_split _lval size value = let size = if Value_parameters.AllRoundingModes.get () then 0 else Integer.to_int size in if V.is_included value V.top_float then subdiv_float ~size else if V.is_included value V.top_int then subdiv_int ~size else raise Too_linear (* pointers *) module Make (Value : Abstract_value.External) (Eva: Evaluation.S with type value = Value.t) = struct Values are converted to { ! . V.t } , because those are currently the only values on which we can split . currently the only values on which we can split. *) let get_cval = match Value.get Main_values.cvalue_key with | Some get -> get | None -> fun _ -> Cvalue.V.top let set_cval = let set = Value.set Main_values.cvalue_key in fun cval v -> set cval v (* A subdivision of the evaluation of an expression according to an lvalue [lval] is stored by an association list, where each disjunct of the abstract value for [lval] is associated to the result of the evaluation for this disjunct. The set of abstract values for [lval] are a partition of the initial abstract value computed for [lval]. The results of the evaluations are pairs of a value and the emitted alarms. *) type result = Value.t evaluated type subdiv = (Cvalue.V.t * result) list let join_or_bottom join a b = match a with | `Bottom -> `Value b | `Value a -> `Value (join a b) (* Flatten a subdivision by joining the values and the alarms. For the subdivided lvalue, the initial values that lead to Bottom are removed (but the alarms of the evaluation are kept). *) let flatten (list: subdiv) = List.fold_left (fun (var, value, alarms) (var', (value', alarms')) -> match value' with | `Bottom -> var, value, Alarmset.union alarms alarms' | `Value v -> join_or_bottom Cvalue.V.join var var', join_or_bottom Value.join value v, Alarmset.union alarms alarms') (`Bottom, `Bottom, Alarmset.none) list let rec insert_in_sorted_list cmp elt list = match list with | [] -> [elt] | hd :: tail -> if cmp elt hd > 0 then hd :: (insert_in_sorted_list cmp elt tail) else elt :: list [ list ] must be a list representing a subdivision ( an association list between values and the results of evaluations for them , as explained above ) . [ has_better_bound ] is an order over the parts of a subdivision ( the elements of the [ list ] . [ subdiv_lval subdivnb list has_better_bound bound split compute ] takes the smallest element of [ list ] according to [ has_better_bound ] , [ split ] its value in two smaller values , and [ compute ] the result for each . The process is repeated [ subdivnb ] times , or until the smallest element of the [ list ] is greater or equal to [ bound ] . values and the results of evaluations for them, as explained above). [has_better_bound] is an order over the parts of a subdivision (the elements of the [list]. [subdiv_lval subdivnb list has_better_bound bound split compute] takes the smallest element of [list] according to [has_better_bound], [split] its value in two smaller values, and [compute] the result for each. The process is repeated [subdivnb] times, or until the smallest element of the [list] is greater or equal to [bound]. *) let subdiv subdivnb (list: subdiv) has_better_bound bound split compute = let working_list = ref (List.sort has_better_bound list) in let subdiv_for_bound has_better_bound bound = let compute_subvalue subvalue list = let res = compute subvalue in insert_in_sorted_list has_better_bound (subvalue, res) list in let subdiv = function | [] -> assert false | (value, _ as v) :: tail -> let subvalue1, subvalue2 = split value in if has_better_bound v bound >= 0 then raise Abstract_interp.Can_not_subdiv; let s = compute_subvalue subvalue1 tail in compute_subvalue subvalue2 s in try for _i = 1 to subdivnb do working_list := subdiv !working_list; done with Abstract_interp.Can_not_subdiv -> () in subdiv_for_bound has_better_bound bound; !working_list (* This function makes orders over elements of a subdiv list. We try to reduce the infimum and the supremum of the result value of the evaluation. The initial [result_value] is needed to know the type of the comparison (float or int). *) let better_bound result_value = let result_value = get_cval result_value in let compare_min, compare_max = if V.is_included result_value V.top_float then V.compare_min_float, V.compare_max_float else V.compare_min_int, V.compare_max_int in let better_bound compare_bound (_, (e1, _)) (_, (e2, _)) = match e1, e2 with | `Bottom, `Bottom -> 0 | `Bottom, _ -> 1 | _, `Bottom -> -1 | `Value v1, `Value v2 -> compare_bound (get_cval v1) (get_cval v2) in better_bound compare_min, better_bound compare_max module Clear = Clear_Valuation (Eva.Valuation) These two functions assume that the given expression or lvalue have been evaluated in the valuation . evaluated in the valuation. *) let find_val valuation expr = match Eva.Valuation.find valuation expr with | `Value record -> record | `Top -> assert false let find_loc valuation lval = match Eva.Valuation.find_loc valuation lval with | `Value record -> record | `Top -> assert false (* Subdivision of the evaluation of the expression [expr], according to the lvalue [lval], in the state [state]. [valuation] is the cache resulting from a previous evaluation of [expr] without subdivision, [value] and [alarms] are the result of the evaluation of [expr]. *) let subdiv_lval ~indeterminate subdivnb state valuation expr value alarms lval = (* Abstract value of [lval]. *) let lv_exp = Cil.new_exp ~loc:expr.Cil_types.eloc (Cil_types.Lval lval) in let lv_record = find_val valuation lv_exp in match lv_record.value.v with | `Bottom -> raise Too_linear | `Value lv_value -> let lv_cval = get_cval lv_value in (* Split function for this abstract value. *) let record = find_loc valuation lval in (* The size is defined, as [lv] is a scalar *) let size = Int_Base.project (Eval_typ.sizeof_lval_typ record.typ) in let split = make_split lval size lv_cval in let cleared_valuation = Clear.clear_expr valuation lv_exp in (* Computes the value of [expr] when [lval] has the value [subvalue]. *) let compute sub_cval = let subvalue = set_cval sub_cval lv_value in let value = { lv_record.value with v = `Value subvalue } in let record = { lv_record with value = value } in let valuation = Eva.Valuation.(add cleared_valuation lv_exp record) in Eva.evaluate ~valuation ~indeterminate state expr >>=: fun (_valuation, value) -> `Value value in (* Evaluation for the bounds of [lv_value]. *) let bound1, bound2 = if V.is_included lv_cval V.top_float then min_and_max_float lv_cval else if V.is_included lv_cval V.top_int then min_and_max_int lv_cval else raise Too_linear (* pointers *) in (* As [bound1] and [bound2] are singleton included in [lv_value], we cannot obtain smaller parts of the subdivision of the evaluation according to [lval]. Thus, [r1] and [r2] will be our limits for the subdivision. *) let r1 = let res1, alarms1 = compute bound1 in bound1, (res1, alarms1) and r2 = let res2, alarms2 = compute bound2 in bound2, (res2, alarms2) in The initial subdivision , with one disjunct . let subdiv_list = [ lv_cval, (`Value value, alarms) ] in let has_better_min_bound, has_better_max_bound = better_bound value in (* Subdivision to reduce the infimum of the result value. *) let min_bound = if has_better_min_bound r2 r1 > 0 then r1 else r2 in let subdiv_list = subdiv subdivnb subdiv_list has_better_min_bound min_bound split compute in (* Subdivision to reduce the supremum of the result value. *) let max_bound = if has_better_max_bound r2 r1 > 0 then r1 else r2 in let subdiv_list = subdiv subdivnb subdiv_list has_better_max_bound max_bound split compute in (* Results of the subdivision *) let reduced_var, result_value, alarms = flatten subdiv_list in (* If [reduced_var] and [result_value] are not bottom, then reduce the valuation by their new value records. *) let eval = reduced_var >>- fun reduced_var -> result_value >>-: fun result_value -> let v = set_cval reduced_var lv_value in let valuation = Eva.Valuation.add valuation lv_exp {lv_record with value = { lv_record.value with v = `Value v }; reductness = Reduced} in let record = find_val valuation expr in let record = { record with value = { record.value with v = `Value result_value }; val_alarms = alarms } in let valuation = Eva.Valuation.add valuation expr record in valuation, result_value in eval, alarms Evaluation of [ expr ] in state [ state ] , with at most ( 2 * [ subdivnb ] ) subdivisions . with at most (2 * [subdivnb]) subdivisions.*) let subdivides_evaluation ~indeterminate subdivnb valuation state expr = (* Evaluation of [expr] without subdivision. *) let default = Eva.evaluate ~valuation ~indeterminate state expr in default >>= fun (valuation, value) alarms -> if not (Value.is_included value Value.top_int) then begin Value_parameters.debug ~level:2 "subdivfloatvar: expression evaluates to an address"; default end else List of that appear multiple times in [ expr ] , candidates for the subdivision . candidates for the subdivision. *) let vars = List.rev (compute_non_linear expr) in (* Comparison function between disjuncts. *) let rec try_sub vars = match vars with | [] -> default | lval :: tail -> try subdiv_lval ~indeterminate subdivnb state valuation expr value alarms lval with Too_linear -> try_sub tail in try_sub vars let evaluate ?(valuation=Eva.Valuation.empty) ?(indeterminate=false) ?(reduction=true) state expr = let subdivnb = Value_parameters.LinearLevel.get () in if subdivnb = 0 || not reduction || not (Value.mem Main_values.cvalue_key) then Eva.evaluate ~valuation ~indeterminate ~reduction state expr else subdivides_evaluation ~indeterminate subdivnb valuation state expr end (* Local Variables: compile-command: "make -C ../../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/value/engine/non_linear_evaluation.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ visit the l-values inside e.g. t[i] None other expr contain a dereferenced l-value [make_split lval loc value] makes a split function for the lval [lval] with location [loc] and abstract value [value]. Raise Too_linear if the value contains pointer. pointers A subdivision of the evaluation of an expression according to an lvalue [lval] is stored by an association list, where each disjunct of the abstract value for [lval] is associated to the result of the evaluation for this disjunct. The set of abstract values for [lval] are a partition of the initial abstract value computed for [lval]. The results of the evaluations are pairs of a value and the emitted alarms. Flatten a subdivision by joining the values and the alarms. For the subdivided lvalue, the initial values that lead to Bottom are removed (but the alarms of the evaluation are kept). This function makes orders over elements of a subdiv list. We try to reduce the infimum and the supremum of the result value of the evaluation. The initial [result_value] is needed to know the type of the comparison (float or int). Subdivision of the evaluation of the expression [expr], according to the lvalue [lval], in the state [state]. [valuation] is the cache resulting from a previous evaluation of [expr] without subdivision, [value] and [alarms] are the result of the evaluation of [expr]. Abstract value of [lval]. Split function for this abstract value. The size is defined, as [lv] is a scalar Computes the value of [expr] when [lval] has the value [subvalue]. Evaluation for the bounds of [lv_value]. pointers As [bound1] and [bound2] are singleton included in [lv_value], we cannot obtain smaller parts of the subdivision of the evaluation according to [lval]. Thus, [r1] and [r2] will be our limits for the subdivision. Subdivision to reduce the infimum of the result value. Subdivision to reduce the supremum of the result value. Results of the subdivision If [reduced_var] and [result_value] are not bottom, then reduce the valuation by their new value records. Evaluation of [expr] without subdivision. Comparison function between disjuncts. Local Variables: compile-command: "make -C ../../../.." End:
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types module Ki = Cil_datatype.Kinstr open Cvalue open Eval let dkey = Value_parameters.register_category "nonlin" let (>>=) (t, a) f = match t with | `Bottom -> `Bottom, a | `Value t -> f t a let (>>=:) (t, a) f = match t with | `Bottom -> `Bottom, a | `Value t -> f t, a let (>>-) t f = match t with | `Bottom -> `Bottom | `Value t -> f t let (>>-:) t f = match t with | `Bottom -> `Bottom | `Value t -> `Value (f t) module LvalList = Datatype.List (Cil_datatype.LvalStructEq) module LvalHTbl = Cil_datatype.LvalStructEq.Hashtbl module Non_linear_expressions = State_builder.Hashtbl (Cil_datatype.Exp.Hashtbl) (LvalList) (struct let name = "Non_linear_evaluation" let size = 16 let dependencies = [ Ast.self ] end) class do_non_linear_assignments = object(self) inherit Visitor.frama_c_inplace val found = LvalHTbl.create 16 method private store_non_linear e = let flatten lval count acc = if count > 1 then lval :: acc else acc in let list = LvalHTbl.fold flatten found [] in List.iter (fun lval -> Value_parameters.result ~current:true ~once:true ~dkey "non-linear '%a', lv '%a'" Printer.pp_exp e Printer.pp_lval lval) list; LvalHTbl.clear found; Non_linear_expressions.replace e list; list method! vlval lv = let cur = try LvalHTbl.find found lv with Not_found -> 0 in LvalHTbl.replace found lv (cur+1); method! vexpr exp = match exp.enode with | Lval _ | UnOp _ | BinOp _ | CastE _ | Info _ -> Cil.DoChildren Cil.SkipChildren method! vtype _ = Cil.SkipChildren method v_full_exp exp = LvalHTbl.clear found; ignore (Visitor.visitFramacExpr (self:>Visitor.frama_c_inplace) exp); self#store_non_linear exp end let compute_non_linear exp = try Non_linear_expressions.find exp with Not_found -> let c = new do_non_linear_assignments in c#v_full_exp exp exception Too_linear let min_and_max_float v = try let i = V.project_ival v in let f1, f2 = Ival.min_and_max_float i in V.inject_float f1, V.inject_float f2 with V.Not_based_on_null -> assert false let subdiv_float ~size v = try let v_ival = V.project_ival v in let ival1, ival2 = Ival.subdiv_float_interval ~size v_ival in V.inject_ival ival1, V.inject_ival ival2 with V.Not_based_on_null -> assert false let min_and_max_int v = try let i = V.project_ival v in match Ival.min_and_max i with | None, _ | _, None -> raise Too_linear | Some i1, Some i2 -> V.inject_int i1, V.inject_int i2 with V.Not_based_on_null -> assert false let subdiv_int ~size:_ v = try let i = V.project_ival v in let l, h = Ival.subdiv_int i in V.inject_ival l, V.inject_ival h with V.Not_based_on_null -> assert false let make_split _lval size value = let size = if Value_parameters.AllRoundingModes.get () then 0 else Integer.to_int size in if V.is_included value V.top_float then subdiv_float ~size else if V.is_included value V.top_int then subdiv_int ~size module Make (Value : Abstract_value.External) (Eva: Evaluation.S with type value = Value.t) = struct Values are converted to { ! . V.t } , because those are currently the only values on which we can split . currently the only values on which we can split. *) let get_cval = match Value.get Main_values.cvalue_key with | Some get -> get | None -> fun _ -> Cvalue.V.top let set_cval = let set = Value.set Main_values.cvalue_key in fun cval v -> set cval v type result = Value.t evaluated type subdiv = (Cvalue.V.t * result) list let join_or_bottom join a b = match a with | `Bottom -> `Value b | `Value a -> `Value (join a b) let flatten (list: subdiv) = List.fold_left (fun (var, value, alarms) (var', (value', alarms')) -> match value' with | `Bottom -> var, value, Alarmset.union alarms alarms' | `Value v -> join_or_bottom Cvalue.V.join var var', join_or_bottom Value.join value v, Alarmset.union alarms alarms') (`Bottom, `Bottom, Alarmset.none) list let rec insert_in_sorted_list cmp elt list = match list with | [] -> [elt] | hd :: tail -> if cmp elt hd > 0 then hd :: (insert_in_sorted_list cmp elt tail) else elt :: list [ list ] must be a list representing a subdivision ( an association list between values and the results of evaluations for them , as explained above ) . [ has_better_bound ] is an order over the parts of a subdivision ( the elements of the [ list ] . [ subdiv_lval subdivnb list has_better_bound bound split compute ] takes the smallest element of [ list ] according to [ has_better_bound ] , [ split ] its value in two smaller values , and [ compute ] the result for each . The process is repeated [ subdivnb ] times , or until the smallest element of the [ list ] is greater or equal to [ bound ] . values and the results of evaluations for them, as explained above). [has_better_bound] is an order over the parts of a subdivision (the elements of the [list]. [subdiv_lval subdivnb list has_better_bound bound split compute] takes the smallest element of [list] according to [has_better_bound], [split] its value in two smaller values, and [compute] the result for each. The process is repeated [subdivnb] times, or until the smallest element of the [list] is greater or equal to [bound]. *) let subdiv subdivnb (list: subdiv) has_better_bound bound split compute = let working_list = ref (List.sort has_better_bound list) in let subdiv_for_bound has_better_bound bound = let compute_subvalue subvalue list = let res = compute subvalue in insert_in_sorted_list has_better_bound (subvalue, res) list in let subdiv = function | [] -> assert false | (value, _ as v) :: tail -> let subvalue1, subvalue2 = split value in if has_better_bound v bound >= 0 then raise Abstract_interp.Can_not_subdiv; let s = compute_subvalue subvalue1 tail in compute_subvalue subvalue2 s in try for _i = 1 to subdivnb do working_list := subdiv !working_list; done with Abstract_interp.Can_not_subdiv -> () in subdiv_for_bound has_better_bound bound; !working_list let better_bound result_value = let result_value = get_cval result_value in let compare_min, compare_max = if V.is_included result_value V.top_float then V.compare_min_float, V.compare_max_float else V.compare_min_int, V.compare_max_int in let better_bound compare_bound (_, (e1, _)) (_, (e2, _)) = match e1, e2 with | `Bottom, `Bottom -> 0 | `Bottom, _ -> 1 | _, `Bottom -> -1 | `Value v1, `Value v2 -> compare_bound (get_cval v1) (get_cval v2) in better_bound compare_min, better_bound compare_max module Clear = Clear_Valuation (Eva.Valuation) These two functions assume that the given expression or lvalue have been evaluated in the valuation . evaluated in the valuation. *) let find_val valuation expr = match Eva.Valuation.find valuation expr with | `Value record -> record | `Top -> assert false let find_loc valuation lval = match Eva.Valuation.find_loc valuation lval with | `Value record -> record | `Top -> assert false let subdiv_lval ~indeterminate subdivnb state valuation expr value alarms lval = let lv_exp = Cil.new_exp ~loc:expr.Cil_types.eloc (Cil_types.Lval lval) in let lv_record = find_val valuation lv_exp in match lv_record.value.v with | `Bottom -> raise Too_linear | `Value lv_value -> let lv_cval = get_cval lv_value in let record = find_loc valuation lval in let size = Int_Base.project (Eval_typ.sizeof_lval_typ record.typ) in let split = make_split lval size lv_cval in let cleared_valuation = Clear.clear_expr valuation lv_exp in let compute sub_cval = let subvalue = set_cval sub_cval lv_value in let value = { lv_record.value with v = `Value subvalue } in let record = { lv_record with value = value } in let valuation = Eva.Valuation.(add cleared_valuation lv_exp record) in Eva.evaluate ~valuation ~indeterminate state expr >>=: fun (_valuation, value) -> `Value value in let bound1, bound2 = if V.is_included lv_cval V.top_float then min_and_max_float lv_cval else if V.is_included lv_cval V.top_int then min_and_max_int lv_cval in let r1 = let res1, alarms1 = compute bound1 in bound1, (res1, alarms1) and r2 = let res2, alarms2 = compute bound2 in bound2, (res2, alarms2) in The initial subdivision , with one disjunct . let subdiv_list = [ lv_cval, (`Value value, alarms) ] in let has_better_min_bound, has_better_max_bound = better_bound value in let min_bound = if has_better_min_bound r2 r1 > 0 then r1 else r2 in let subdiv_list = subdiv subdivnb subdiv_list has_better_min_bound min_bound split compute in let max_bound = if has_better_max_bound r2 r1 > 0 then r1 else r2 in let subdiv_list = subdiv subdivnb subdiv_list has_better_max_bound max_bound split compute in let reduced_var, result_value, alarms = flatten subdiv_list in let eval = reduced_var >>- fun reduced_var -> result_value >>-: fun result_value -> let v = set_cval reduced_var lv_value in let valuation = Eva.Valuation.add valuation lv_exp {lv_record with value = { lv_record.value with v = `Value v }; reductness = Reduced} in let record = find_val valuation expr in let record = { record with value = { record.value with v = `Value result_value }; val_alarms = alarms } in let valuation = Eva.Valuation.add valuation expr record in valuation, result_value in eval, alarms Evaluation of [ expr ] in state [ state ] , with at most ( 2 * [ subdivnb ] ) subdivisions . with at most (2 * [subdivnb]) subdivisions.*) let subdivides_evaluation ~indeterminate subdivnb valuation state expr = let default = Eva.evaluate ~valuation ~indeterminate state expr in default >>= fun (valuation, value) alarms -> if not (Value.is_included value Value.top_int) then begin Value_parameters.debug ~level:2 "subdivfloatvar: expression evaluates to an address"; default end else List of that appear multiple times in [ expr ] , candidates for the subdivision . candidates for the subdivision. *) let vars = List.rev (compute_non_linear expr) in let rec try_sub vars = match vars with | [] -> default | lval :: tail -> try subdiv_lval ~indeterminate subdivnb state valuation expr value alarms lval with Too_linear -> try_sub tail in try_sub vars let evaluate ?(valuation=Eva.Valuation.empty) ?(indeterminate=false) ?(reduction=true) state expr = let subdivnb = Value_parameters.LinearLevel.get () in if subdivnb = 0 || not reduction || not (Value.mem Main_values.cvalue_key) then Eva.evaluate ~valuation ~indeterminate ~reduction state expr else subdivides_evaluation ~indeterminate subdivnb valuation state expr end
cfaffcfc1c17819d19653e520b111d66841da2fc0b566cd16b3d82ccc0616984
tweag/asterius
T10296a.hs
-- A reduced version of the original test case # LANGUAGE ForeignFunctionInterface # import Control.Concurrent import Control.Monad import Foreign.C.Types import Foreign.Ptr main :: IO () main = do mv <- newEmptyMVar -- Fork a thread to continually dereference a stable pointer... void $ forkIO $ f 1 1000000 >> putMVar mv () -- ...while we keep enlarging the stable pointer table f 65536 1 void $ takeMVar mv where f nWraps nApplies = replicateM_ nWraps $ do -- Each call to wrap creates a stable pointer wrappedPlus <- wrap (+) c_applyFun nApplies wrappedPlus 1 2 type CIntFun = CInt -> CInt -> CInt foreign import ccall "wrapper" wrap :: CIntFun -> IO (FunPtr CIntFun) foreign import ccall "apply_fun" c_applyFun :: CInt -> FunPtr CIntFun -> CInt -> CInt -> IO CInt
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/rts/T10296a.hs
haskell
A reduced version of the original test case Fork a thread to continually dereference a stable pointer... ...while we keep enlarging the stable pointer table Each call to wrap creates a stable pointer
# LANGUAGE ForeignFunctionInterface # import Control.Concurrent import Control.Monad import Foreign.C.Types import Foreign.Ptr main :: IO () main = do mv <- newEmptyMVar void $ forkIO $ f 1 1000000 >> putMVar mv () f 65536 1 void $ takeMVar mv where f nWraps nApplies = replicateM_ nWraps $ do wrappedPlus <- wrap (+) c_applyFun nApplies wrappedPlus 1 2 type CIntFun = CInt -> CInt -> CInt foreign import ccall "wrapper" wrap :: CIntFun -> IO (FunPtr CIntFun) foreign import ccall "apply_fun" c_applyFun :: CInt -> FunPtr CIntFun -> CInt -> CInt -> IO CInt
843b4dc2646c3bc17e25f7c3ec875d717bfb86f4bc65bdef1947c885e9063559
dakk/caravand-fullnode
helper.mli
open Yojson open Unix val send : Unix.file_descr -> string -> unit val recv : Unix.file_descr -> string val shutdown : Unix.file_descr -> unit val listen : Unix.file_descr -> int -> int -> unit module HTTP : sig type met = GET | POST | DELETE | PUT type req = { uri : string list; body : string; body_json : Yojson.Basic.json option; rmethod : met; socket : Unix.file_descr; } val reply_json : req -> int -> Yojson.Basic.json -> unit val reply : req -> int -> string -> unit val parse_request : Unix.file_descr -> req option end module JSONRPC : sig type req = { methodn : string; params : Yojson.Basic.json list; id : string; socket : Unix.file_descr; } val parse_request : Unix.file_descr -> req option val reply : req -> Yojson.Basic.json -> unit end
null
https://raw.githubusercontent.com/dakk/caravand-fullnode/72735bf380812aea32ba0d3d4aa671f741cdaecb/src/api/helper.mli
ocaml
open Yojson open Unix val send : Unix.file_descr -> string -> unit val recv : Unix.file_descr -> string val shutdown : Unix.file_descr -> unit val listen : Unix.file_descr -> int -> int -> unit module HTTP : sig type met = GET | POST | DELETE | PUT type req = { uri : string list; body : string; body_json : Yojson.Basic.json option; rmethod : met; socket : Unix.file_descr; } val reply_json : req -> int -> Yojson.Basic.json -> unit val reply : req -> int -> string -> unit val parse_request : Unix.file_descr -> req option end module JSONRPC : sig type req = { methodn : string; params : Yojson.Basic.json list; id : string; socket : Unix.file_descr; } val parse_request : Unix.file_descr -> req option val reply : req -> Yojson.Basic.json -> unit end
064de12e9e3af7c7151cebb0a74a97070f2eff80e870ab23c40436f312a96411
racketscript/racketscript
ident-normalize.rkt
#lang racketscript/base (define 0x 42) (displayln 0x)
null
https://raw.githubusercontent.com/racketscript/racketscript/f94006d11338a674ae10f6bd83fc53e6806d07d8/tests/basic/ident-normalize.rkt
racket
#lang racketscript/base (define 0x 42) (displayln 0x)
673d2297c53c5df41908f21de60556091068a102ac1fa7c4f7ea0b624edb8485
input-output-hk/project-icarus-importer
Common.hs
module Pos.Binary.Core.Common () where import Universum import Pos.Binary.Class (Bi (..), Cons (..), Field (..), deriveSimpleBi) import Pos.Core.Common.Types (Coin (..), unsafeGetCoin) import qualified Pos.Core.Common.Types as T import qualified Pos.Data.Attributes as A import Pos.Util.Orphans () -- kind of boilerplate, but anyway that's what it was made for -- -- verbosity and clarity instance Bi (A.Attributes ()) where encode = A.encodeAttributes [] decode = A.decodeAttributes () $ \_ _ _ -> pure Nothing instance Bi T.BlockCount where encode = encode . T.getBlockCount decode = T.BlockCount <$> decode deriveSimpleBi ''T.SharedSeed [ Cons 'T.SharedSeed [ Field [| T.getSharedSeed :: ByteString |] ]] deriveSimpleBi ''T.ChainDifficulty [ Cons 'T.ChainDifficulty [ Field [| T.getChainDifficulty :: T.BlockCount |] ]] ---------------------------------------------------------------------------- -- Coin ---------------------------------------------------------------------------- number of total coins is 45 * 10 ^ 9 * 10 ^ 6 -- -- Input | Bits to represent | ------------------------------| ----------------- | 0 - 9 | 8 bits | 0 - 99 | 16 bits | 0 - 999 | 24 bits | 0 - 9999 | 24 bits | -- 0-99999 | 40 bits | 0 - 999999 | 40 bits | 45 * 10 ^ 15 | 72 bits | 45 * 10 ^ 9 | 72 bits | 45 * 10 ^ 9 * 10 ^ 6 ( maxbound ) | 72 bits | -- maxbound - 1 | 72 bits | instance Bi Coin where encode = encode . unsafeGetCoin decode = Coin <$> decode
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/core/src/Pos/Binary/Core/Common.hs
haskell
kind of boilerplate, but anyway that's what it was made for -- verbosity and clarity -------------------------------------------------------------------------- Coin -------------------------------------------------------------------------- Input | Bits to represent | ----------------------------| ----------------- | 0-99999 | 40 bits | maxbound - 1 | 72 bits |
module Pos.Binary.Core.Common () where import Universum import Pos.Binary.Class (Bi (..), Cons (..), Field (..), deriveSimpleBi) import Pos.Core.Common.Types (Coin (..), unsafeGetCoin) import qualified Pos.Core.Common.Types as T import qualified Pos.Data.Attributes as A import Pos.Util.Orphans () instance Bi (A.Attributes ()) where encode = A.encodeAttributes [] decode = A.decodeAttributes () $ \_ _ _ -> pure Nothing instance Bi T.BlockCount where encode = encode . T.getBlockCount decode = T.BlockCount <$> decode deriveSimpleBi ''T.SharedSeed [ Cons 'T.SharedSeed [ Field [| T.getSharedSeed :: ByteString |] ]] deriveSimpleBi ''T.ChainDifficulty [ Cons 'T.ChainDifficulty [ Field [| T.getChainDifficulty :: T.BlockCount |] ]] number of total coins is 45 * 10 ^ 9 * 10 ^ 6 0 - 9 | 8 bits | 0 - 99 | 16 bits | 0 - 999 | 24 bits | 0 - 9999 | 24 bits | 0 - 999999 | 40 bits | 45 * 10 ^ 15 | 72 bits | 45 * 10 ^ 9 | 72 bits | 45 * 10 ^ 9 * 10 ^ 6 ( maxbound ) | 72 bits | instance Bi Coin where encode = encode . unsafeGetCoin decode = Coin <$> decode
4641434e371860536cdc3948b2894b6fb5a43978ee0fe6987e270af8fe49b16c
tweag/inline-java
Streaming.hs
-- | Expose Java iterators as streams from the -- < streaming> package. # LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE ExistentialQuantification # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE StaticPointers # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE RecordWildCards # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - orphans # # OPTIONS_GHC -fno - warn - unused - top - binds # module Language.Java.Streaming ( reifyStreamWithBatching , reflectStreamWithBatching ) where import Control.Distributed.Closure.TH import Control.Monad.IO.Class (liftIO) import qualified Data.Coerce as Coerce import Data.IORef (newIORef, readIORef, writeIORef) import Data.Int (Int32, Int64) import Data.Proxy import qualified Data.Vector as V import Data.Singletons (SomeSing(..)) import Foreign.Ptr (FunPtr, Ptr, intPtrToPtr, ptrToIntPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import qualified Foreign.JNI as JNI import qualified Foreign.JNI.Types as JNI import GHC.Stable ( castPtrToStablePtr , castStablePtrToPtr , deRefStablePtr , freeStablePtr , newStablePtr ) import Language.Java import Language.Java.Batching import Language.Java.Inline import Streaming (Bifunctor(first), Stream, Of) import qualified Streaming as Streaming import qualified Streaming.Prelude as Streaming import System.IO.Unsafe (unsafePerformIO) imports "io.tweag.jvm.batching.*" imports "java.util.Iterator" type JNIFun a = JNIEnv -> Ptr JObject -> Int64 -> IO a foreign import ccall "wrapper" wrapObjectFun :: JNIFun (Ptr (J ty)) -> IO (FunPtr (JNIFun (Ptr (J ty)))) -- Export only to get a FunPtr. foreign export ccall "jvm_streaming_freeIterator" freeIterator :: JNIEnv -> Ptr JObject -> Int64 -> IO () foreign import ccall "&jvm_streaming_freeIterator" freeIteratorPtr :: FunPtr (JNIEnv -> Ptr JObject -> Int64 -> IO ()) data FunPtrTable = FunPtrTable { refPtr :: Int64 } freeIterator :: JNIEnv -> Ptr JObject -> Int64 -> IO () freeIterator _ _ ptr = do let sptr = castPtrToStablePtr $ intPtrToPtr $ fromIntegral ptr FunPtrTable{..} <- deRefStablePtr sptr freeStablePtr $ castPtrToStablePtr $ intPtrToPtr $ fromIntegral refPtr freeStablePtr sptr -- | Reflects a stream with no batching. newIterator :: forall ty. Stream (Of (J ty)) IO () -> IO (J ('Iface "java.util.Iterator" <> '[ty])) newIterator stream0 = do ioStreamRef <- newIORef stream0 refPtr :: Int64 <- fromIntegral . ptrToIntPtr . castStablePtrToPtr <$> newStablePtr ioStreamRef Keep FunPtr 's in a table that can be referenced from the Java side , so -- that they can be freed. tblPtr :: Int64 <- fromIntegral . ptrToIntPtr . castStablePtrToPtr <$> newStablePtr FunPtrTable{..} iterator <- [java| new Iterator() { /// A field that the Haskell side sets to true when it reaches the end. private boolean end = false; /// Lookahead element - it always points to a valid element unless /// end is true. There is no constructor, so in order to initialize // it, next() must be invoked once. private Object lookahead; @Override public boolean hasNext() { return !end; } @Override public Object next() { if (hasNext()) { final Object temp = lookahead; lookahead = hsNext($refPtr); return temp; } else throw new java.util.NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException(); } private native void hsFinalize(long tblPtr); private native Object hsNext(long refPtr); @Override public void finalize() { hsFinalize($tblPtr); } } |] runOnce $ do klass <- JNI.getObjectClass iterator registerNativesForIterator klass <* JNI.deleteLocalRef klass -- Call next once to initialize the iterator. () <- [java| { $iterator.next(); } |] return $ generic iterator where -- Given that we always register natives on the same class, -- there is no point in registering natives more than once. runOnce :: IO a -> IO a runOnce action = do # NOINLINE ref # ref = unsafePerformIO $ newIORef Nothing readIORef ref >>= \case Nothing -> do a <- action writeIORef ref (Just a) return a Just a -> return a -- | Registers functions for the native methods of the inner class created in ' newIterator ' . -- -- We keep this helper as a top-level function to ensure that no state tied -- to a particular iterator leaks in the registered functions. The methods -- registered here affect all the instances of the inner class. registerNativesForIterator :: JClass -> IO () registerNativesForIterator klass = do fieldEndId <- JNI.getFieldID klass "end" (JNI.signature (sing :: Sing ('Prim "boolean"))) nextPtr <- wrapObjectFun $ \_ jthis streamRef -> -- Conversion is safe, because result is always a reflected object. unsafeForeignPtrToPtr . Coerce.coerce <$> popStream fieldEndId jthis streamRef JNI.registerNatives klass [ JNI.JNINativeMethod "hsNext" (methodSignature [SomeSing (sing :: Sing ('Prim "long"))] (sing :: Sing ('Class "java.lang.Object")) ) nextPtr , JNI.JNINativeMethod "hsFinalize" (methodSignature [SomeSing (sing :: Sing ('Prim "long"))] (sing :: Sing 'Void)) freeIteratorPtr ] where popStream :: JFieldID -> Ptr JObject -> Int64 -> IO (J ty) popStream fieldEndId ptrThis streamRef = do let stableRef = castPtrToStablePtr $ intPtrToPtr $ fromIntegral streamRef ref <- deRefStablePtr stableRef stream <- readIORef ref Streaming.uncons stream >>= \case Nothing -> do jthis <- JNI.objectFromPtr ptrThis -- When the stream ends, set the end field to True so the Iterator knows not to call hsNext again . JNI.setBooleanField jthis fieldEndId 1 return jnull Just (x, stream') -> do writeIORef ref stream' return x -- | Reifies streams from iterators in batches of the given size. reifyStreamWithBatching :: forall a. BatchReify a => Int32 -- ^ The batch size -> J ('Iface "java.util.Iterator" <> '[Interp a]) -> IO (Stream (Of a) IO ()) reifyStreamWithBatching batchSize jiterator0 = do let jiterator1 = unsafeUngeneric jiterator0 jbatcher <- unsafeUngeneric <$> newBatchWriter (Proxy :: Proxy a) jiterator <- [java| new Iterator() { private final int batchSize = $batchSize; private final Iterator it = $jiterator1; private final BatchWriter batcher = $jbatcher; public int count = 0; @Override public boolean hasNext() { return it.hasNext(); } @Override public Object next() { int i = 0; batcher.start(batchSize); while (it.hasNext() && i < batchSize) { batcher.set(i, it.next()); i++; } count = i; return batcher.getBatch(); } @Override public void remove() { throw new UnsupportedOperationException(); } } |] >>= JNI.newGlobalRef :: IO (J ('Iface "java.util.Iterator")) cls <- JNI.getObjectClass jiterator >>= JNI.newGlobalRef fieldId <- JNI.getFieldID cls "count" (JNI.signature (sing :: Sing ('Prim "int"))) let go :: Int -- next element to return from the batch -> V.Vector a -- current batch of elements -> Stream (Of a) IO () go i v = if V.length v == i then do hasNext <- liftIO [java| $jiterator.hasNext() |] if hasNext then do v' <- liftIO $ [java| $jiterator.next() |] `withLocalRef` \jbatch -> JNI.getIntField jiterator fieldId >>= \sz -> reifyBatch (unsafeCast (jbatch :: JObject) :: J (Batch a)) sz (const True) go 0 v' else liftIO $ do JNI.deleteGlobalRef jiterator JNI.deleteGlobalRef cls else do Streaming.yield $ v V.! i go (i + 1) v return $ go 0 V.empty -- | Reflects streams to iterators in batches of the given size. reflectStreamWithBatching :: forall a. BatchReflect a => Int -- ^ The batch size -> Stream (Of a) IO () -> IO (J ('Iface "java.util.Iterator" <> '[Interp a])) reflectStreamWithBatching batchSize s0 = do jiterator <- unsafeUngeneric <$> (reflectStream $ Streaming.mapsM (\s -> first V.fromList <$> Streaming.toList s) $ Streaming.chunksOf batchSize s0 ) jbatchReader <- unsafeUngeneric <$> newBatchReader (Proxy :: Proxy a) generic <$> [java| new Iterator() { private final Iterator it = $jiterator; private final BatchReader batchReader = $jbatchReader; private int count = 0; @Override public boolean hasNext() { return count < batchReader.getSize() || it.hasNext(); } @Override public Object next() { if (count == batchReader.getSize()) { batchReader.setBatch(it.next()); count = 0; } Object o = batchReader.get(count); count++; return o; } @Override public void remove() { throw new UnsupportedOperationException(); } } |] where reflectStream :: Stream (Of (V.Vector a)) IO () -> IO (J ('Iface "java.util.Iterator" <> '[Batch a])) reflectStream = newIterator . Streaming.mapM reflectBatch withStatic [d| instance Interpretation (Stream (Of a) m r) where type Interp (Stream (Of a) m r) = 'Iface "java.util.Iterator" instance BatchReify a => Reify (Stream (Of a) IO ()) where reify = reifyStreamWithBatching 1024 . generic instance BatchReflect a => Reflect (Stream (Of a) IO ()) where reflect = fmap unsafeUngeneric . reflectStreamWithBatching 1024 |]
null
https://raw.githubusercontent.com/tweag/inline-java/a2daaa3cfc5cb172b6334bf5904d1a57025e709a/jvm-streaming/src/main/haskell/Language/Java/Streaming.hs
haskell
| Expose Java iterators as streams from the < streaming> package. # LANGUAGE OverloadedStrings # Export only to get a FunPtr. | Reflects a stream with no batching. that they can be freed. Call next once to initialize the iterator. Given that we always register natives on the same class, there is no point in registering natives more than once. | Registers functions for the native methods of the inner class created in We keep this helper as a top-level function to ensure that no state tied to a particular iterator leaks in the registered functions. The methods registered here affect all the instances of the inner class. Conversion is safe, because result is always a reflected object. When the stream ends, set the end field to True | Reifies streams from iterators in batches of the given size. ^ The batch size next element to return from the batch current batch of elements | Reflects streams to iterators in batches of the given size. ^ The batch size
# LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE ExistentialQuantification # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE QuasiQuotes # # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE StaticPointers # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE RecordWildCards # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - orphans # # OPTIONS_GHC -fno - warn - unused - top - binds # module Language.Java.Streaming ( reifyStreamWithBatching , reflectStreamWithBatching ) where import Control.Distributed.Closure.TH import Control.Monad.IO.Class (liftIO) import qualified Data.Coerce as Coerce import Data.IORef (newIORef, readIORef, writeIORef) import Data.Int (Int32, Int64) import Data.Proxy import qualified Data.Vector as V import Data.Singletons (SomeSing(..)) import Foreign.Ptr (FunPtr, Ptr, intPtrToPtr, ptrToIntPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import qualified Foreign.JNI as JNI import qualified Foreign.JNI.Types as JNI import GHC.Stable ( castPtrToStablePtr , castStablePtrToPtr , deRefStablePtr , freeStablePtr , newStablePtr ) import Language.Java import Language.Java.Batching import Language.Java.Inline import Streaming (Bifunctor(first), Stream, Of) import qualified Streaming as Streaming import qualified Streaming.Prelude as Streaming import System.IO.Unsafe (unsafePerformIO) imports "io.tweag.jvm.batching.*" imports "java.util.Iterator" type JNIFun a = JNIEnv -> Ptr JObject -> Int64 -> IO a foreign import ccall "wrapper" wrapObjectFun :: JNIFun (Ptr (J ty)) -> IO (FunPtr (JNIFun (Ptr (J ty)))) foreign export ccall "jvm_streaming_freeIterator" freeIterator :: JNIEnv -> Ptr JObject -> Int64 -> IO () foreign import ccall "&jvm_streaming_freeIterator" freeIteratorPtr :: FunPtr (JNIEnv -> Ptr JObject -> Int64 -> IO ()) data FunPtrTable = FunPtrTable { refPtr :: Int64 } freeIterator :: JNIEnv -> Ptr JObject -> Int64 -> IO () freeIterator _ _ ptr = do let sptr = castPtrToStablePtr $ intPtrToPtr $ fromIntegral ptr FunPtrTable{..} <- deRefStablePtr sptr freeStablePtr $ castPtrToStablePtr $ intPtrToPtr $ fromIntegral refPtr freeStablePtr sptr newIterator :: forall ty. Stream (Of (J ty)) IO () -> IO (J ('Iface "java.util.Iterator" <> '[ty])) newIterator stream0 = do ioStreamRef <- newIORef stream0 refPtr :: Int64 <- fromIntegral . ptrToIntPtr . castStablePtrToPtr <$> newStablePtr ioStreamRef Keep FunPtr 's in a table that can be referenced from the Java side , so tblPtr :: Int64 <- fromIntegral . ptrToIntPtr . castStablePtrToPtr <$> newStablePtr FunPtrTable{..} iterator <- [java| new Iterator() { /// A field that the Haskell side sets to true when it reaches the end. private boolean end = false; /// Lookahead element - it always points to a valid element unless /// end is true. There is no constructor, so in order to initialize // it, next() must be invoked once. private Object lookahead; @Override public boolean hasNext() { return !end; } @Override public Object next() { if (hasNext()) { final Object temp = lookahead; lookahead = hsNext($refPtr); return temp; } else throw new java.util.NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException(); } private native void hsFinalize(long tblPtr); private native Object hsNext(long refPtr); @Override public void finalize() { hsFinalize($tblPtr); } } |] runOnce $ do klass <- JNI.getObjectClass iterator registerNativesForIterator klass <* JNI.deleteLocalRef klass () <- [java| { $iterator.next(); } |] return $ generic iterator where runOnce :: IO a -> IO a runOnce action = do # NOINLINE ref # ref = unsafePerformIO $ newIORef Nothing readIORef ref >>= \case Nothing -> do a <- action writeIORef ref (Just a) return a Just a -> return a ' newIterator ' . registerNativesForIterator :: JClass -> IO () registerNativesForIterator klass = do fieldEndId <- JNI.getFieldID klass "end" (JNI.signature (sing :: Sing ('Prim "boolean"))) nextPtr <- wrapObjectFun $ \_ jthis streamRef -> unsafeForeignPtrToPtr . Coerce.coerce <$> popStream fieldEndId jthis streamRef JNI.registerNatives klass [ JNI.JNINativeMethod "hsNext" (methodSignature [SomeSing (sing :: Sing ('Prim "long"))] (sing :: Sing ('Class "java.lang.Object")) ) nextPtr , JNI.JNINativeMethod "hsFinalize" (methodSignature [SomeSing (sing :: Sing ('Prim "long"))] (sing :: Sing 'Void)) freeIteratorPtr ] where popStream :: JFieldID -> Ptr JObject -> Int64 -> IO (J ty) popStream fieldEndId ptrThis streamRef = do let stableRef = castPtrToStablePtr $ intPtrToPtr $ fromIntegral streamRef ref <- deRefStablePtr stableRef stream <- readIORef ref Streaming.uncons stream >>= \case Nothing -> do jthis <- JNI.objectFromPtr ptrThis so the Iterator knows not to call hsNext again . JNI.setBooleanField jthis fieldEndId 1 return jnull Just (x, stream') -> do writeIORef ref stream' return x reifyStreamWithBatching :: forall a. BatchReify a -> J ('Iface "java.util.Iterator" <> '[Interp a]) -> IO (Stream (Of a) IO ()) reifyStreamWithBatching batchSize jiterator0 = do let jiterator1 = unsafeUngeneric jiterator0 jbatcher <- unsafeUngeneric <$> newBatchWriter (Proxy :: Proxy a) jiterator <- [java| new Iterator() { private final int batchSize = $batchSize; private final Iterator it = $jiterator1; private final BatchWriter batcher = $jbatcher; public int count = 0; @Override public boolean hasNext() { return it.hasNext(); } @Override public Object next() { int i = 0; batcher.start(batchSize); while (it.hasNext() && i < batchSize) { batcher.set(i, it.next()); i++; } count = i; return batcher.getBatch(); } @Override public void remove() { throw new UnsupportedOperationException(); } } |] >>= JNI.newGlobalRef :: IO (J ('Iface "java.util.Iterator")) cls <- JNI.getObjectClass jiterator >>= JNI.newGlobalRef fieldId <- JNI.getFieldID cls "count" (JNI.signature (sing :: Sing ('Prim "int"))) -> Stream (Of a) IO () go i v = if V.length v == i then do hasNext <- liftIO [java| $jiterator.hasNext() |] if hasNext then do v' <- liftIO $ [java| $jiterator.next() |] `withLocalRef` \jbatch -> JNI.getIntField jiterator fieldId >>= \sz -> reifyBatch (unsafeCast (jbatch :: JObject) :: J (Batch a)) sz (const True) go 0 v' else liftIO $ do JNI.deleteGlobalRef jiterator JNI.deleteGlobalRef cls else do Streaming.yield $ v V.! i go (i + 1) v return $ go 0 V.empty reflectStreamWithBatching :: forall a. BatchReflect a -> Stream (Of a) IO () -> IO (J ('Iface "java.util.Iterator" <> '[Interp a])) reflectStreamWithBatching batchSize s0 = do jiterator <- unsafeUngeneric <$> (reflectStream $ Streaming.mapsM (\s -> first V.fromList <$> Streaming.toList s) $ Streaming.chunksOf batchSize s0 ) jbatchReader <- unsafeUngeneric <$> newBatchReader (Proxy :: Proxy a) generic <$> [java| new Iterator() { private final Iterator it = $jiterator; private final BatchReader batchReader = $jbatchReader; private int count = 0; @Override public boolean hasNext() { return count < batchReader.getSize() || it.hasNext(); } @Override public Object next() { if (count == batchReader.getSize()) { batchReader.setBatch(it.next()); count = 0; } Object o = batchReader.get(count); count++; return o; } @Override public void remove() { throw new UnsupportedOperationException(); } } |] where reflectStream :: Stream (Of (V.Vector a)) IO () -> IO (J ('Iface "java.util.Iterator" <> '[Batch a])) reflectStream = newIterator . Streaming.mapM reflectBatch withStatic [d| instance Interpretation (Stream (Of a) m r) where type Interp (Stream (Of a) m r) = 'Iface "java.util.Iterator" instance BatchReify a => Reify (Stream (Of a) IO ()) where reify = reifyStreamWithBatching 1024 . generic instance BatchReflect a => Reflect (Stream (Of a) IO ()) where reflect = fmap unsafeUngeneric . reflectStreamWithBatching 1024 |]
3a121cf9b9bd18caa6a38c482a7abf8fa3f54c58c0b5ad416e160c600a99624e
tmattio/js-bindings
vscode_test_download.ml
[@@@js.dummy "!! This code has been generated by gen_js_api !!"] [@@@ocaml.warning "-7-32-39"] [@@@ocaml.warning "-7-11-32-33-39"] open Es5 module AnonymousInterface0 = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2 and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1 end module StringLiteralUnion = struct type ('T, 'U) t = 'T let rec t_of_js : 'T 'U . (Ojs.t -> 'T) -> (Ojs.t -> 'U) -> Ojs.t -> ('T, 'U) t = fun (type __T) -> fun (type __U) -> fun (__T_of_js : Ojs.t -> __T) -> fun (__U_of_js : Ojs.t -> __U) -> fun (x4 : Ojs.t) -> __T_of_js x4 and t_to_js : 'T 'U . ('T -> Ojs.t) -> ('U -> Ojs.t) -> ('T, 'U) t -> Ojs.t = fun (type __T) -> fun (type __U) -> fun (__T_to_js : __T -> Ojs.t) -> fun (__U_to_js : __U -> Ojs.t) -> fun (x3 : __T) -> __T_to_js x3 end module DownloadVersion = struct type t = ([ `L_s1_insiders | `L_s3_stable ], string) StringLiteralUnion.t let rec t_of_js : Ojs.t -> t = fun (x8 : Ojs.t) -> StringLiteralUnion.t_of_js (fun (x9 : Ojs.t) -> let x10 = x9 in match Ojs.string_of_js x10 with | "insiders" -> `L_s1_insiders | "stable" -> `L_s3_stable | _ -> assert false) Ojs.string_of_js x8 and t_to_js : t -> Ojs.t = fun (x5 : ([ `L_s1_insiders | `L_s3_stable ], string) StringLiteralUnion.t) -> StringLiteralUnion.t_to_js (fun (x6 : [ `L_s1_insiders | `L_s3_stable ]) -> match x6 with | `L_s1_insiders -> Ojs.string_to_js "insiders" | `L_s3_stable -> Ojs.string_to_js "stable") Ojs.string_to_js x5 end module DownloadPlatform = struct type t = ([ `L_s0_darwin | `L_s2_linux_x64 | `L_s4_win32_archive | `L_s5_win32_x64_archive ], string) StringLiteralUnion.t let rec t_of_js : Ojs.t -> t = fun (x15 : Ojs.t) -> StringLiteralUnion.t_of_js (fun (x16 : Ojs.t) -> let x17 = x16 in match Ojs.string_of_js x17 with | "darwin" -> `L_s0_darwin | "linux-x64" -> `L_s2_linux_x64 | "win32-archive" -> `L_s4_win32_archive | "win32-x64-archive" -> `L_s5_win32_x64_archive | _ -> assert false) Ojs.string_of_js x15 and t_to_js : t -> Ojs.t = fun (x12 : ([ `L_s0_darwin | `L_s2_linux_x64 | `L_s4_win32_archive | `L_s5_win32_x64_archive ], string) StringLiteralUnion.t) -> StringLiteralUnion.t_to_js (fun (x13 : [ `L_s0_darwin | `L_s2_linux_x64 | `L_s4_win32_archive | `L_s5_win32_x64_archive ]) -> match x13 with | `L_s0_darwin -> Ojs.string_to_js "darwin" | `L_s2_linux_x64 -> Ojs.string_to_js "linux-x64" | `L_s4_win32_archive -> Ojs.string_to_js "win32-archive" | `L_s5_win32_x64_archive -> Ojs.string_to_js "win32-x64-archive") Ojs.string_to_js x12 end let (download_and_unzip_vs_code : ?version:DownloadVersion.t -> ?platform:DownloadPlatform.t -> unit -> string Promise.t) = fun ?version:(x19 : DownloadVersion.t option) -> fun ?platform:(x20 : DownloadPlatform.t option) -> fun () -> Promise.t_of_js Ojs.string_of_js (let x24 = Ojs.global in Ojs.call (Ojs.get_prop_ascii x24 "downloadAndUnzipVSCode") "apply" [|x24;((let x21 = Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array") [||] in (match x19 with | Some x23 -> ignore (Ojs.call x21 "push" [|(DownloadVersion.t_to_js x23)|]) | None -> ()); (match x20 with | Some x22 -> ignore (Ojs.call x21 "push" [|(DownloadPlatform.t_to_js x22)|]) | None -> ()); x21))|])
null
https://raw.githubusercontent.com/tmattio/js-bindings/f1d36bba378e4ecd5310542a0244dce9258b6496/lib/vscode-test/vscode_test_download.ml
ocaml
[@@@js.dummy "!! This code has been generated by gen_js_api !!"] [@@@ocaml.warning "-7-32-39"] [@@@ocaml.warning "-7-11-32-33-39"] open Es5 module AnonymousInterface0 = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2 and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1 end module StringLiteralUnion = struct type ('T, 'U) t = 'T let rec t_of_js : 'T 'U . (Ojs.t -> 'T) -> (Ojs.t -> 'U) -> Ojs.t -> ('T, 'U) t = fun (type __T) -> fun (type __U) -> fun (__T_of_js : Ojs.t -> __T) -> fun (__U_of_js : Ojs.t -> __U) -> fun (x4 : Ojs.t) -> __T_of_js x4 and t_to_js : 'T 'U . ('T -> Ojs.t) -> ('U -> Ojs.t) -> ('T, 'U) t -> Ojs.t = fun (type __T) -> fun (type __U) -> fun (__T_to_js : __T -> Ojs.t) -> fun (__U_to_js : __U -> Ojs.t) -> fun (x3 : __T) -> __T_to_js x3 end module DownloadVersion = struct type t = ([ `L_s1_insiders | `L_s3_stable ], string) StringLiteralUnion.t let rec t_of_js : Ojs.t -> t = fun (x8 : Ojs.t) -> StringLiteralUnion.t_of_js (fun (x9 : Ojs.t) -> let x10 = x9 in match Ojs.string_of_js x10 with | "insiders" -> `L_s1_insiders | "stable" -> `L_s3_stable | _ -> assert false) Ojs.string_of_js x8 and t_to_js : t -> Ojs.t = fun (x5 : ([ `L_s1_insiders | `L_s3_stable ], string) StringLiteralUnion.t) -> StringLiteralUnion.t_to_js (fun (x6 : [ `L_s1_insiders | `L_s3_stable ]) -> match x6 with | `L_s1_insiders -> Ojs.string_to_js "insiders" | `L_s3_stable -> Ojs.string_to_js "stable") Ojs.string_to_js x5 end module DownloadPlatform = struct type t = ([ `L_s0_darwin | `L_s2_linux_x64 | `L_s4_win32_archive | `L_s5_win32_x64_archive ], string) StringLiteralUnion.t let rec t_of_js : Ojs.t -> t = fun (x15 : Ojs.t) -> StringLiteralUnion.t_of_js (fun (x16 : Ojs.t) -> let x17 = x16 in match Ojs.string_of_js x17 with | "darwin" -> `L_s0_darwin | "linux-x64" -> `L_s2_linux_x64 | "win32-archive" -> `L_s4_win32_archive | "win32-x64-archive" -> `L_s5_win32_x64_archive | _ -> assert false) Ojs.string_of_js x15 and t_to_js : t -> Ojs.t = fun (x12 : ([ `L_s0_darwin | `L_s2_linux_x64 | `L_s4_win32_archive | `L_s5_win32_x64_archive ], string) StringLiteralUnion.t) -> StringLiteralUnion.t_to_js (fun (x13 : [ `L_s0_darwin | `L_s2_linux_x64 | `L_s4_win32_archive | `L_s5_win32_x64_archive ]) -> match x13 with | `L_s0_darwin -> Ojs.string_to_js "darwin" | `L_s2_linux_x64 -> Ojs.string_to_js "linux-x64" | `L_s4_win32_archive -> Ojs.string_to_js "win32-archive" | `L_s5_win32_x64_archive -> Ojs.string_to_js "win32-x64-archive") Ojs.string_to_js x12 end let (download_and_unzip_vs_code : ?version:DownloadVersion.t -> ?platform:DownloadPlatform.t -> unit -> string Promise.t) = fun ?version:(x19 : DownloadVersion.t option) -> fun ?platform:(x20 : DownloadPlatform.t option) -> fun () -> Promise.t_of_js Ojs.string_of_js (let x24 = Ojs.global in Ojs.call (Ojs.get_prop_ascii x24 "downloadAndUnzipVSCode") "apply" [|x24;((let x21 = Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array") [||] in (match x19 with | Some x23 -> ignore (Ojs.call x21 "push" [|(DownloadVersion.t_to_js x23)|]) | None -> ()); (match x20 with | Some x22 -> ignore (Ojs.call x21 "push" [|(DownloadPlatform.t_to_js x22)|]) | None -> ()); x21))|])
235ac3997409503a9564e1bf4a01f2ee0558dd323fbe9b3c900a0b653af4041c
janestreet/core_profiler
reader.mli
open! Core open Core_profiler.Std_offline open Core_profiler module Header : sig (** A [Header.Item.t] is anything that is uniquely identified by a [Probe_id.t]. *) module Item : sig type single = { name : string ; spec : Probe_type.t } type group = { name : string ; points_spec : Probe_type.t ; children : Probe_id.t list } type group_point = { name : string ; parent : Probe_id.t ; sources : Probe_id.t list } type t = | Single of single | Group of group | Group_point of group_point val name : t -> string end type t = (Item.t, read) Id_table.t val find_exn : t -> Probe_id.t -> Item.t val find_single_exn : t -> Probe_id.t -> Item.single val find_group_exn : t -> Probe_id.t -> Item.group val find_group_point_exn : t -> Probe_id.t -> Item.group_point (** Get a group point's parent *) val get_parent_id_exn : t -> Probe_id.t -> Probe_id.t val get_parent_exn : t -> Probe_id.t -> Item.group (** If [add_group] is specified and the id refers to a group point, [group_name ^ add_group ^ group_point_name] is returned *) val get_name_exn : t -> ?with_group:string -> Probe_id.t -> string val get_spec_exn : t -> Probe_id.t -> Probe_type.t val get_units_exn : t -> Probe_id.t -> Profiler_units.t (** Conditions are ANDed, and default to true *) val create_table : t -> ?singles:bool -> ?groups:bool -> ?group_points:bool -> ?timers:bool -> ?probes:bool -> 'a -> ('a, _) Id_table.t end val consume_header : ([> read ], Iobuf.seek) Iobuf.t -> Profiler_epoch.t * Header.t module Short_message : sig module Header : module type of Core_profiler.Protocol.Short_header type t = | Timer of Probe_id.t * Time_ns.t | Probe of Probe_id.t * Time_ns.t * int | Group_reset of Probe_id.t * Time_ns.t val id : t -> Probe_id.t val time : t -> Time_ns.t end val consume_short_message : ([> read ], Iobuf.seek) Iobuf.t -> Profiler_epoch.t -> Header.t -> Short_message.t val fold_short_messages : ([> read ], _) Iobuf.t -> Profiler_epoch.t -> Header.t -> init:'accum -> f:('accum -> Short_message.t -> 'accum) -> 'accum val iter_short_messages : ([> read ], _) Iobuf.t -> Profiler_epoch.t -> Header.t -> f:(Short_message.t -> unit) -> unit val iteri_short_messages : ([> read ], _) Iobuf.t -> Profiler_epoch.t -> Header.t -> f:(int -> Short_message.t -> unit) -> unit val map_file : string -> (read, _) Iobuf.t
null
https://raw.githubusercontent.com/janestreet/core_profiler/3d1c0e61df848f5f25f78d64beea92b619b6d5d9/offline_tool/lib/reader.mli
ocaml
* A [Header.Item.t] is anything that is uniquely identified by a [Probe_id.t]. * Get a group point's parent * If [add_group] is specified and the id refers to a group point, [group_name ^ add_group ^ group_point_name] is returned * Conditions are ANDed, and default to true
open! Core open Core_profiler.Std_offline open Core_profiler module Header : sig module Item : sig type single = { name : string ; spec : Probe_type.t } type group = { name : string ; points_spec : Probe_type.t ; children : Probe_id.t list } type group_point = { name : string ; parent : Probe_id.t ; sources : Probe_id.t list } type t = | Single of single | Group of group | Group_point of group_point val name : t -> string end type t = (Item.t, read) Id_table.t val find_exn : t -> Probe_id.t -> Item.t val find_single_exn : t -> Probe_id.t -> Item.single val find_group_exn : t -> Probe_id.t -> Item.group val find_group_point_exn : t -> Probe_id.t -> Item.group_point val get_parent_id_exn : t -> Probe_id.t -> Probe_id.t val get_parent_exn : t -> Probe_id.t -> Item.group val get_name_exn : t -> ?with_group:string -> Probe_id.t -> string val get_spec_exn : t -> Probe_id.t -> Probe_type.t val get_units_exn : t -> Probe_id.t -> Profiler_units.t val create_table : t -> ?singles:bool -> ?groups:bool -> ?group_points:bool -> ?timers:bool -> ?probes:bool -> 'a -> ('a, _) Id_table.t end val consume_header : ([> read ], Iobuf.seek) Iobuf.t -> Profiler_epoch.t * Header.t module Short_message : sig module Header : module type of Core_profiler.Protocol.Short_header type t = | Timer of Probe_id.t * Time_ns.t | Probe of Probe_id.t * Time_ns.t * int | Group_reset of Probe_id.t * Time_ns.t val id : t -> Probe_id.t val time : t -> Time_ns.t end val consume_short_message : ([> read ], Iobuf.seek) Iobuf.t -> Profiler_epoch.t -> Header.t -> Short_message.t val fold_short_messages : ([> read ], _) Iobuf.t -> Profiler_epoch.t -> Header.t -> init:'accum -> f:('accum -> Short_message.t -> 'accum) -> 'accum val iter_short_messages : ([> read ], _) Iobuf.t -> Profiler_epoch.t -> Header.t -> f:(Short_message.t -> unit) -> unit val iteri_short_messages : ([> read ], _) Iobuf.t -> Profiler_epoch.t -> Header.t -> f:(int -> Short_message.t -> unit) -> unit val map_file : string -> (read, _) Iobuf.t
907f828800e6922851b977ce1394941d7601a6dbc68889afe7fe2601c16b0e5d
clj-kafka/franzy
core_test.clj
(ns franzy.serialization.json.core-test (:require [midje.sweet :refer :all]))
null
https://raw.githubusercontent.com/clj-kafka/franzy/6c2e2e65ad137d2bcbc04ff6e671f97ea8c0e380/json/test/franzy/serialization/json/core_test.clj
clojure
(ns franzy.serialization.json.core-test (:require [midje.sweet :refer :all]))
8fb779a9a97a4320315d53f740667c3769dee4dc3fffe13395b0cd1237ea7eef
DanielG/ghc-mod
File_Redir_Lint.hs
# LANGUAGE CPP # #ifndef NOTHING module File where func :: Num a => a -> a -> a func a b = (*) a b #else INVALID #endif
null
https://raw.githubusercontent.com/DanielG/ghc-mod/391e187a5dfef4421aab2508fa6ff7875cc8259d/test/data/file-mapping/preprocessor/File_Redir_Lint.hs
haskell
# LANGUAGE CPP # #ifndef NOTHING module File where func :: Num a => a -> a -> a func a b = (*) a b #else INVALID #endif
38703c87e813b4d2fa29dbe0fc3f50b0d61a7ba113ee07ac0f0abd4ccac87309
janestreet/core
comparator.ml
open! Import module Comparator = Base.Comparator type ('a, 'witness) t = ('a, 'witness) Comparator.t = private { compare : 'a -> 'a -> int ; sexp_of_t : 'a -> Base.Sexp.t } module type Base_mask = module type of Comparator with type ('a, 'b) t := ('a, 'b) t include (Comparator : Base_mask) module Stable = struct module V1 = struct type nonrec ('a, 'witness) t = ('a, 'witness) t = private { compare : 'a -> 'a -> int ; sexp_of_t : 'a -> Base.Sexp.t } type ('a, 'b) comparator = ('a, 'b) t module type S = S module type S1 = S1 let make = make module Make = Make module Make1 = Make1 end end
null
https://raw.githubusercontent.com/janestreet/core/b0be1daa71b662bd38ef2bb406f7b3e70d63d05f/core/src/comparator.ml
ocaml
open! Import module Comparator = Base.Comparator type ('a, 'witness) t = ('a, 'witness) Comparator.t = private { compare : 'a -> 'a -> int ; sexp_of_t : 'a -> Base.Sexp.t } module type Base_mask = module type of Comparator with type ('a, 'b) t := ('a, 'b) t include (Comparator : Base_mask) module Stable = struct module V1 = struct type nonrec ('a, 'witness) t = ('a, 'witness) t = private { compare : 'a -> 'a -> int ; sexp_of_t : 'a -> Base.Sexp.t } type ('a, 'b) comparator = ('a, 'b) t module type S = S module type S1 = S1 let make = make module Make = Make module Make1 = Make1 end end
3550863632ab2ec4bdd2b25a2651c6e2440ebd5ef4987ebf460f54e7b528ade5
kapok-lang/kapok
kapok_dispatch.erl
%% Helper module for dispatching names(module/function/macro/var) and their references. -module(kapok_dispatch). -export([default_requires/0, default_uses/0, find_module/3, find_local_macro/5, find_remote_macro/6, find_local_function/2, find_imported_local_function/3, find_remote_function/4, is_macro_loaded/3, filter_fa/2, format_error/1]). -import(kapok_ctx, [metadata_check_remote_call/1]). -include("kapok.hrl"). default_requires() -> L = [{'kapok_macro', 'kapok_macro'}], orddict:from_list(L). default_uses() -> [{'kapok.core', 'core'}, {'kapok.protocol', 'protocol'}]. %% get the original module name in case module is an alias or rename. find_module(_Meta, Module, Ctx) -> Requires = ?m(Ctx, requires), case orddict:find(Module, Requires) of {ok, M1} -> M1; error -> Module end. %% find local/remote macro/function find_local_macro(Meta, FunArity, FunMeta, Args, #{namespace := Namespace} = Ctx) -> check whether the FunArity refers to a macro in current namespace %% which is defined previously. Macros = kapok_symbol_table:namespace_macros(Namespace), case filter_fa(FunArity, Macros) of [{F, A, P}] -> {{local, {F, A, P}}, Ctx}; [] -> find_import_macro(Meta, FunArity, FunMeta, Args, Ctx) end. find_import_macro(Meta, FunArity, FunMeta, Args, Ctx) -> {D, Ctx1} = find_dispatch(Meta, FunArity, Ctx), R = case D of {macro, MFAP} -> {remote, MFAP}; {function, {M, F, A, P}} -> rewrite_function(Meta, M, F, FunMeta, A, P, Args); false -> false end, {R, Ctx1}. find_remote_macro(Meta, Module, FunArity, FunMeta, Args, Ctx) -> Original = find_module(Meta, Module, Ctx), Uses = ?m(Ctx, uses), case orddict:find(Original, Uses) of {ok, _} -> %% Original is declared in ns use clause. %% Load all the import macros/functions from the specified module if necessary, and then find the specified FunArity . {D, Ctx1} = find_dispatch(Meta, Original, FunArity, Ctx), case D of {macro, MFAP} -> {{remote, MFAP}, Ctx1}; {function, {M, F, A, P}} -> {rewrite_function(Meta, M, F, FunMeta, A, P, Args), Ctx1}; false -> find_optional_remote_macro(Meta, Original, FunArity, FunMeta, Args, Ctx1) end; error -> find_optional_remote_macro(Meta, Original, FunArity, FunMeta, Args, Ctx) end. find_optional_remote_macro(Meta, Module, FunArity, FunMeta, Args, Ctx) -> {D, Ctx1} = find_optional_dispatch(Meta, Module, FunArity, Ctx), R = case D of {macro, MFAP} -> {remote, MFAP}; {function, {M, F, A, P}} -> rewrite_function(Meta, M, F, FunMeta, A, P, Args); unknown_module -> false; false -> false end, {R, Ctx1}. find_local_function(FunArity, #{def_fap := FAP} = Ctx) -> case filter_fa(FunArity, [FAP]) of [{F, A, P}] -> %% match current function definition {F, A, P}; [] -> %% find in macros/functions of current namespace Namespace = maps:get(namespace, Ctx), Locals = kapok_symbol_table:namespace_locals(Namespace), case filter_fa(FunArity, Locals) of [{F, A, P}] -> {F, A, P}; [] -> false end end. find_imported_local_function(Meta, FunArity, Ctx) -> {D, Ctx1} = find_dispatch(Meta, FunArity, Ctx), R = case D of {Tag, MFAP} when Tag == macro; Tag == function -> MFAP; false -> false end, {R, Ctx1}. find_remote_function(Meta, Module, FunArity, Ctx) -> Original = find_module(Meta, Module, Ctx), Uses = ?m(Ctx, uses), case orddict:find(Original, Uses) of {ok, _} -> {D, Ctx1} = find_dispatch(Meta, Original, FunArity, Ctx), case D of {Tag, MFAP} when Tag == macro; Tag == function -> {MFAP, Ctx1}; false -> find_optional_remote_function(Meta, Original, FunArity, Ctx1) end; error -> find_optional_remote_function(Meta, Original, FunArity, Ctx) end. find_optional_remote_function(Meta, Module, {Fun, Arity} = FunArity, Ctx) -> {D, Ctx1} = find_optional_dispatch(Meta, Module, FunArity, Ctx), R = case D of {Tag, MFAP} when Tag == macro; Tag == function -> MFAP; unknown_module -> case metadata_check_remote_call(Ctx) of true -> false; _ -> {Module, Fun, Arity, 'normal'} end; Atom when is_atom(Atom) -> Atom end, {R, Ctx1}. is_macro_loaded(Module, FAP, Ctx) -> lists:member(FAP, get_macros([], Module, Ctx)). find_optional_dispatch(Meta, Module, FunArity, Ctx) -> case code:ensure_loaded(Module) of {module, Module} -> FunImports = orddict:from_list([{Module, get_optional_functions(Module)}]), MacroImports = orddict:from_list([{Module, get_optional_macros(Module)}]), do_find_dispatch(Meta, FunArity, FunImports, MacroImports, Ctx); {error, _} -> {unknown_module, Ctx} end. find_dispatch(Meta, Module, FunArity, Ctx) -> Ctx1 = ensure_uses_imported(Ctx), %% TODO check whether module is a require alias FunList = case orddict:find(Module, ?m(Ctx1, functions)) of {ok, L1} -> L1; error -> [] end, FunImports = orddict:from_list([{Module, FunList}]), MacroList = case orddict:find(Module, ?m(Ctx1, macros)) of {ok, L2} -> L2; error -> [] end, MacroImports = orddict:from_list([{Module, MacroList}]), do_find_dispatch(Meta, FunArity, FunImports, MacroImports, Ctx1). find_dispatch(Meta, FunArity, Ctx) -> Ctx1 = ensure_uses_imported(Ctx), do_find_dispatch(Meta, FunArity, ?m(Ctx1, functions), ?m(Ctx1, macros), Ctx1). do_find_dispatch(Meta, {Fun, Arity} = FunArity, FunImports, MacroImports, Ctx) -> FunMatch = filter_import(FunArity, FunImports), MacroMatch = filter_import({Fun, Arity}, MacroImports), case {FunMatch, MacroMatch} of {[], [Match]} -> {M, [{F, A, P}]} = Match, {{macro, {M, F, A, P}}, Ctx}; {[Match], []} -> {M, [{F, A, P}]} = Match, {{function, {M, F, A, P}}, Ctx}; {[], []} -> {false, Ctx}; _ -> [First, Second | _T] = FunMatch ++ MacroMatch, Error = {ambiguous_call, {Fun, Arity, First, Second}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error) end. filter_import(FunArity, List) when is_list(List) -> lists:foldl(fun({Module, Imports}, Acc) -> case filter_fa(FunArity, Imports) of [] -> Acc; R -> orddict:store(Module, R, Acc) end end, [], List). filter_fa({Fun, Arity} = FunArity, FAList) when is_list(FAList) -> ordsets:fold( fun({F, A} = FA, Acc) when is_number(A) andalso FA == FunArity -> [{F, A, 'normal'} | Acc]; ({Alias, {F, A, P}}, Acc) when (P == 'normal' orelse P == 'key'), {Alias, A} == FunArity -> [{F, A, P} | Acc]; ({Alias, {F, A, 'rest'}}, Acc) when (Alias == Fun) andalso (A =< Arity) -> [{F, A, 'rest'} | Acc]; ({F, A, P} = FAP, Acc) when (P == 'normal' orelse P == 'key'), {F, A} == FunArity -> [FAP | Acc]; ({F, A, 'rest'} = FAP, Acc) when (F == Fun) andalso (A =< Arity) -> [FAP | Acc]; (_, Acc) -> Acc end, [], FAList). ensure_uses_imported(#{uses := Uses} = Ctx) -> lists:foldl(fun({Module, Args}, C) -> {ok, Meta} = orddict:find(meta, Args), case module_is_imported(Module, C) of true -> C; false -> import_module(Meta, Module, Args, C) end end, Ctx, Uses). module_is_imported(Module, #{functions := Functions, macros := Macros}) -> orddict:is_key(Module, Functions) orelse orddict:is_key(Module, Macros). import_module(Meta, Module, Args, Ctx) -> {Functions, Macros} = get_exports(Meta, Module, Args, Ctx), Ctx1 = case Functions of [] -> Ctx; _ -> kapok_ctx:add_function(Meta, Ctx, Module, Functions) end, Ctx2 = case Macros of [] -> Ctx1; _ -> kapok_ctx:add_macro(Meta, Ctx1, Module, Macros) end, Ctx2. get_exports(Meta, Module, Args, Ctx) -> Functions = get_functions(Meta, Module, Ctx), Macros = get_macros(Meta, Module, Ctx), {filter_exports(Functions, Args), filter_exports(Macros, Args)}. ensure_loaded(Meta, Module, Ctx) -> case code:ensure_loaded(Module) of {module, Module} -> ok; {error, What} -> kapok_error:compile_error(Meta, ?m(Ctx, file), "fail to load module: ~p due to load error: ~p", [Module, What]) end. get_optional_functions(Module) -> Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, try L = Module:'__info__'(functions), ordsets:from_list(lists:map(Fun, L)) catch error:undef -> try L1 = Module:module_info(exports), ordsets:from_list(lists:map(Fun, L1)) catch error:undef -> [] end end. get_functions(Meta, Module, Ctx) -> ensure_loaded(Meta, Module, Ctx), Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, try L = Module:'__info__'(functions), ordsets:from_list(lists:map(Fun, L)) catch error:undef -> try L1 = Module:module_info(exports), ordsets:from_list(lists:map(Fun, L1)) catch error:undef -> kapok_error:compile_error(Meta, ?m(Ctx, file), "fail to get exports for unloaded module: ~p", [Module]) end end. get_optional_macros(Module) -> try L = Module:'__info__'(macros), Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, ordsets:from_list(lists:map(Fun, L)) catch error:undef -> [] end. get_macros(Meta, Module, Ctx) -> ensure_loaded(Meta, Module, Ctx), try L = Module:'__info__'(macros), Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, ordsets:from_list(lists:map(Fun, L)) catch error:undef -> [] end. filter_exports(Exports, Args) -> ordsets:from_list(lists:foldl(fun filter_exports_by/2, Exports, Args)). filter_exports_by({'only', Includes}, Exports) -> lists:filter(fun(FAP) -> Match = lists:filter(fun(E) -> match_fa(E, FAP) end, Includes), case Match of [] -> false; _ -> true end end, Exports); filter_exports_by({'exclude', Excludes}, Exports) -> lists:filter(fun(FAP) -> Match = lists:filter(fun(E) -> match_fa(E, FAP) end, Excludes), case Match of [] -> true; _ -> false end end, Exports); filter_exports_by({'rename', Renames}, Exports) -> lists:foldl(fun({Fun, Arity, ParaType} = FAP, Acc) -> New = lists:foldl(fun({Alias, {F, A}}, Acc0) -> case (F == Fun) andalso (A == Arity) of true -> [{Alias, {Fun, Arity, ParaType}} | Acc0]; _ -> Acc0 end; ({Alias, F}, Acc0) -> case (F == Fun) of true -> [{Alias, {Fun, Arity, ParaType}} | Acc0]; _ -> Acc0 end end, [], Renames), case New of [] -> [FAP | Acc]; _ -> New ++ [FAP | Acc] end end, [], Exports); filter_exports_by(_, Exports) -> Exports. match_fa({F, A}, {Fun, Arity, _ParaType}) -> (F == Fun) andalso (A == Arity); match_fa(Name, {Fun, _Arity, _ParaType}) when is_atom(Name) -> Name == Fun. rewrite_function(Meta, Module, Fun, FunMeta, Arity, ParaType, Args) -> case kapok_rewrite:inline(Module, Fun, Arity, ParaType) of {M, F, _A, _P} -> Dot = {dot, FunMeta, {{identifier, FunMeta, M}, {identifier, FunMeta, F}}}, Ast = {list, Meta, [Dot | Args]}, {rewrite, Ast}; false -> case kapok_rewrite:rewrite(Meta, Module, Fun, FunMeta, Arity, ParaType, Args) of false -> false; Ast -> {rewrite, Ast} end end. %% ERROR HANDLING format_error({ambiguous_call, {M, F, A, FAP1, FAP2}}) -> io_lib:format("find function ~ts:~ts/~B duplicates in ~p and ~p", [M, F, A, FAP1, FAP2]); format_error({ambiguous_call, {F, A, FAP1, FAP2}}) -> io_lib:format("function ~ts/~B imported from both ~p and ~p, call in ambiguous", [F, A, FAP1, FAP2]).
null
https://raw.githubusercontent.com/kapok-lang/kapok/4272f990fe495e595d2afe38605dbca560bbe072/lib/kapok/src/kapok_dispatch.erl
erlang
Helper module for dispatching names(module/function/macro/var) and their references. get the original module name in case module is an alias or rename. find local/remote macro/function which is defined previously. Original is declared in ns use clause. Load all the import macros/functions from the specified module if necessary, match current function definition find in macros/functions of current namespace TODO check whether module is a require alias ERROR HANDLING
-module(kapok_dispatch). -export([default_requires/0, default_uses/0, find_module/3, find_local_macro/5, find_remote_macro/6, find_local_function/2, find_imported_local_function/3, find_remote_function/4, is_macro_loaded/3, filter_fa/2, format_error/1]). -import(kapok_ctx, [metadata_check_remote_call/1]). -include("kapok.hrl"). default_requires() -> L = [{'kapok_macro', 'kapok_macro'}], orddict:from_list(L). default_uses() -> [{'kapok.core', 'core'}, {'kapok.protocol', 'protocol'}]. find_module(_Meta, Module, Ctx) -> Requires = ?m(Ctx, requires), case orddict:find(Module, Requires) of {ok, M1} -> M1; error -> Module end. find_local_macro(Meta, FunArity, FunMeta, Args, #{namespace := Namespace} = Ctx) -> check whether the FunArity refers to a macro in current namespace Macros = kapok_symbol_table:namespace_macros(Namespace), case filter_fa(FunArity, Macros) of [{F, A, P}] -> {{local, {F, A, P}}, Ctx}; [] -> find_import_macro(Meta, FunArity, FunMeta, Args, Ctx) end. find_import_macro(Meta, FunArity, FunMeta, Args, Ctx) -> {D, Ctx1} = find_dispatch(Meta, FunArity, Ctx), R = case D of {macro, MFAP} -> {remote, MFAP}; {function, {M, F, A, P}} -> rewrite_function(Meta, M, F, FunMeta, A, P, Args); false -> false end, {R, Ctx1}. find_remote_macro(Meta, Module, FunArity, FunMeta, Args, Ctx) -> Original = find_module(Meta, Module, Ctx), Uses = ?m(Ctx, uses), case orddict:find(Original, Uses) of {ok, _} -> and then find the specified FunArity . {D, Ctx1} = find_dispatch(Meta, Original, FunArity, Ctx), case D of {macro, MFAP} -> {{remote, MFAP}, Ctx1}; {function, {M, F, A, P}} -> {rewrite_function(Meta, M, F, FunMeta, A, P, Args), Ctx1}; false -> find_optional_remote_macro(Meta, Original, FunArity, FunMeta, Args, Ctx1) end; error -> find_optional_remote_macro(Meta, Original, FunArity, FunMeta, Args, Ctx) end. find_optional_remote_macro(Meta, Module, FunArity, FunMeta, Args, Ctx) -> {D, Ctx1} = find_optional_dispatch(Meta, Module, FunArity, Ctx), R = case D of {macro, MFAP} -> {remote, MFAP}; {function, {M, F, A, P}} -> rewrite_function(Meta, M, F, FunMeta, A, P, Args); unknown_module -> false; false -> false end, {R, Ctx1}. find_local_function(FunArity, #{def_fap := FAP} = Ctx) -> case filter_fa(FunArity, [FAP]) of [{F, A, P}] -> {F, A, P}; [] -> Namespace = maps:get(namespace, Ctx), Locals = kapok_symbol_table:namespace_locals(Namespace), case filter_fa(FunArity, Locals) of [{F, A, P}] -> {F, A, P}; [] -> false end end. find_imported_local_function(Meta, FunArity, Ctx) -> {D, Ctx1} = find_dispatch(Meta, FunArity, Ctx), R = case D of {Tag, MFAP} when Tag == macro; Tag == function -> MFAP; false -> false end, {R, Ctx1}. find_remote_function(Meta, Module, FunArity, Ctx) -> Original = find_module(Meta, Module, Ctx), Uses = ?m(Ctx, uses), case orddict:find(Original, Uses) of {ok, _} -> {D, Ctx1} = find_dispatch(Meta, Original, FunArity, Ctx), case D of {Tag, MFAP} when Tag == macro; Tag == function -> {MFAP, Ctx1}; false -> find_optional_remote_function(Meta, Original, FunArity, Ctx1) end; error -> find_optional_remote_function(Meta, Original, FunArity, Ctx) end. find_optional_remote_function(Meta, Module, {Fun, Arity} = FunArity, Ctx) -> {D, Ctx1} = find_optional_dispatch(Meta, Module, FunArity, Ctx), R = case D of {Tag, MFAP} when Tag == macro; Tag == function -> MFAP; unknown_module -> case metadata_check_remote_call(Ctx) of true -> false; _ -> {Module, Fun, Arity, 'normal'} end; Atom when is_atom(Atom) -> Atom end, {R, Ctx1}. is_macro_loaded(Module, FAP, Ctx) -> lists:member(FAP, get_macros([], Module, Ctx)). find_optional_dispatch(Meta, Module, FunArity, Ctx) -> case code:ensure_loaded(Module) of {module, Module} -> FunImports = orddict:from_list([{Module, get_optional_functions(Module)}]), MacroImports = orddict:from_list([{Module, get_optional_macros(Module)}]), do_find_dispatch(Meta, FunArity, FunImports, MacroImports, Ctx); {error, _} -> {unknown_module, Ctx} end. find_dispatch(Meta, Module, FunArity, Ctx) -> Ctx1 = ensure_uses_imported(Ctx), FunList = case orddict:find(Module, ?m(Ctx1, functions)) of {ok, L1} -> L1; error -> [] end, FunImports = orddict:from_list([{Module, FunList}]), MacroList = case orddict:find(Module, ?m(Ctx1, macros)) of {ok, L2} -> L2; error -> [] end, MacroImports = orddict:from_list([{Module, MacroList}]), do_find_dispatch(Meta, FunArity, FunImports, MacroImports, Ctx1). find_dispatch(Meta, FunArity, Ctx) -> Ctx1 = ensure_uses_imported(Ctx), do_find_dispatch(Meta, FunArity, ?m(Ctx1, functions), ?m(Ctx1, macros), Ctx1). do_find_dispatch(Meta, {Fun, Arity} = FunArity, FunImports, MacroImports, Ctx) -> FunMatch = filter_import(FunArity, FunImports), MacroMatch = filter_import({Fun, Arity}, MacroImports), case {FunMatch, MacroMatch} of {[], [Match]} -> {M, [{F, A, P}]} = Match, {{macro, {M, F, A, P}}, Ctx}; {[Match], []} -> {M, [{F, A, P}]} = Match, {{function, {M, F, A, P}}, Ctx}; {[], []} -> {false, Ctx}; _ -> [First, Second | _T] = FunMatch ++ MacroMatch, Error = {ambiguous_call, {Fun, Arity, First, Second}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error) end. filter_import(FunArity, List) when is_list(List) -> lists:foldl(fun({Module, Imports}, Acc) -> case filter_fa(FunArity, Imports) of [] -> Acc; R -> orddict:store(Module, R, Acc) end end, [], List). filter_fa({Fun, Arity} = FunArity, FAList) when is_list(FAList) -> ordsets:fold( fun({F, A} = FA, Acc) when is_number(A) andalso FA == FunArity -> [{F, A, 'normal'} | Acc]; ({Alias, {F, A, P}}, Acc) when (P == 'normal' orelse P == 'key'), {Alias, A} == FunArity -> [{F, A, P} | Acc]; ({Alias, {F, A, 'rest'}}, Acc) when (Alias == Fun) andalso (A =< Arity) -> [{F, A, 'rest'} | Acc]; ({F, A, P} = FAP, Acc) when (P == 'normal' orelse P == 'key'), {F, A} == FunArity -> [FAP | Acc]; ({F, A, 'rest'} = FAP, Acc) when (F == Fun) andalso (A =< Arity) -> [FAP | Acc]; (_, Acc) -> Acc end, [], FAList). ensure_uses_imported(#{uses := Uses} = Ctx) -> lists:foldl(fun({Module, Args}, C) -> {ok, Meta} = orddict:find(meta, Args), case module_is_imported(Module, C) of true -> C; false -> import_module(Meta, Module, Args, C) end end, Ctx, Uses). module_is_imported(Module, #{functions := Functions, macros := Macros}) -> orddict:is_key(Module, Functions) orelse orddict:is_key(Module, Macros). import_module(Meta, Module, Args, Ctx) -> {Functions, Macros} = get_exports(Meta, Module, Args, Ctx), Ctx1 = case Functions of [] -> Ctx; _ -> kapok_ctx:add_function(Meta, Ctx, Module, Functions) end, Ctx2 = case Macros of [] -> Ctx1; _ -> kapok_ctx:add_macro(Meta, Ctx1, Module, Macros) end, Ctx2. get_exports(Meta, Module, Args, Ctx) -> Functions = get_functions(Meta, Module, Ctx), Macros = get_macros(Meta, Module, Ctx), {filter_exports(Functions, Args), filter_exports(Macros, Args)}. ensure_loaded(Meta, Module, Ctx) -> case code:ensure_loaded(Module) of {module, Module} -> ok; {error, What} -> kapok_error:compile_error(Meta, ?m(Ctx, file), "fail to load module: ~p due to load error: ~p", [Module, What]) end. get_optional_functions(Module) -> Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, try L = Module:'__info__'(functions), ordsets:from_list(lists:map(Fun, L)) catch error:undef -> try L1 = Module:module_info(exports), ordsets:from_list(lists:map(Fun, L1)) catch error:undef -> [] end end. get_functions(Meta, Module, Ctx) -> ensure_loaded(Meta, Module, Ctx), Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, try L = Module:'__info__'(functions), ordsets:from_list(lists:map(Fun, L)) catch error:undef -> try L1 = Module:module_info(exports), ordsets:from_list(lists:map(Fun, L1)) catch error:undef -> kapok_error:compile_error(Meta, ?m(Ctx, file), "fail to get exports for unloaded module: ~p", [Module]) end end. get_optional_macros(Module) -> try L = Module:'__info__'(macros), Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, ordsets:from_list(lists:map(Fun, L)) catch error:undef -> [] end. get_macros(Meta, Module, Ctx) -> ensure_loaded(Meta, Module, Ctx), try L = Module:'__info__'(macros), Fun = fun({F, A}) -> {F, A, 'normal'}; ({_F, _A, _P} = FAP) -> FAP end, ordsets:from_list(lists:map(Fun, L)) catch error:undef -> [] end. filter_exports(Exports, Args) -> ordsets:from_list(lists:foldl(fun filter_exports_by/2, Exports, Args)). filter_exports_by({'only', Includes}, Exports) -> lists:filter(fun(FAP) -> Match = lists:filter(fun(E) -> match_fa(E, FAP) end, Includes), case Match of [] -> false; _ -> true end end, Exports); filter_exports_by({'exclude', Excludes}, Exports) -> lists:filter(fun(FAP) -> Match = lists:filter(fun(E) -> match_fa(E, FAP) end, Excludes), case Match of [] -> true; _ -> false end end, Exports); filter_exports_by({'rename', Renames}, Exports) -> lists:foldl(fun({Fun, Arity, ParaType} = FAP, Acc) -> New = lists:foldl(fun({Alias, {F, A}}, Acc0) -> case (F == Fun) andalso (A == Arity) of true -> [{Alias, {Fun, Arity, ParaType}} | Acc0]; _ -> Acc0 end; ({Alias, F}, Acc0) -> case (F == Fun) of true -> [{Alias, {Fun, Arity, ParaType}} | Acc0]; _ -> Acc0 end end, [], Renames), case New of [] -> [FAP | Acc]; _ -> New ++ [FAP | Acc] end end, [], Exports); filter_exports_by(_, Exports) -> Exports. match_fa({F, A}, {Fun, Arity, _ParaType}) -> (F == Fun) andalso (A == Arity); match_fa(Name, {Fun, _Arity, _ParaType}) when is_atom(Name) -> Name == Fun. rewrite_function(Meta, Module, Fun, FunMeta, Arity, ParaType, Args) -> case kapok_rewrite:inline(Module, Fun, Arity, ParaType) of {M, F, _A, _P} -> Dot = {dot, FunMeta, {{identifier, FunMeta, M}, {identifier, FunMeta, F}}}, Ast = {list, Meta, [Dot | Args]}, {rewrite, Ast}; false -> case kapok_rewrite:rewrite(Meta, Module, Fun, FunMeta, Arity, ParaType, Args) of false -> false; Ast -> {rewrite, Ast} end end. format_error({ambiguous_call, {M, F, A, FAP1, FAP2}}) -> io_lib:format("find function ~ts:~ts/~B duplicates in ~p and ~p", [M, F, A, FAP1, FAP2]); format_error({ambiguous_call, {F, A, FAP1, FAP2}}) -> io_lib:format("function ~ts/~B imported from both ~p and ~p, call in ambiguous", [F, A, FAP1, FAP2]).
49cad82b43e4ca0eeba3f4ed3def58e8ebfe1b8f835fcc59b2d480413c49248c
vbmithr/ocaml-thrift-lib
TServerSocket.ml
Licensed to the Apache Software Foundation ( ASF ) under one or more contributor license agreements . See the NOTICE file distributed with this work for additional information regarding copyright ownership . The ASF licenses this file to you 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 . Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. *) open Thrift class t port = object inherit Transport.server_t val mutable sock = None method listen = let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in sock <- Some s; Unix.bind s (Unix.ADDR_INET (Unix.inet_addr_any, port)); Unix.listen s 256 method close = match sock with Some s -> Unix.shutdown s Unix.SHUTDOWN_ALL; Unix.close s; sock <- None | _ -> () method acceptImpl = match sock with Some s -> let (fd,_) = Unix.accept s in new TChannelTransport.t (Unix.in_channel_of_descr fd,Unix.out_channel_of_descr fd) | _ -> raise (Transport.E (Transport.NOT_OPEN,"TServerSocket: Not listening but tried to accept")) end
null
https://raw.githubusercontent.com/vbmithr/ocaml-thrift-lib/70669ce410e99389975384b46492f9a55281ca10/src/TServerSocket.ml
ocaml
Licensed to the Apache Software Foundation ( ASF ) under one or more contributor license agreements . See the NOTICE file distributed with this work for additional information regarding copyright ownership . The ASF licenses this file to you 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 . Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. *) open Thrift class t port = object inherit Transport.server_t val mutable sock = None method listen = let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in sock <- Some s; Unix.bind s (Unix.ADDR_INET (Unix.inet_addr_any, port)); Unix.listen s 256 method close = match sock with Some s -> Unix.shutdown s Unix.SHUTDOWN_ALL; Unix.close s; sock <- None | _ -> () method acceptImpl = match sock with Some s -> let (fd,_) = Unix.accept s in new TChannelTransport.t (Unix.in_channel_of_descr fd,Unix.out_channel_of_descr fd) | _ -> raise (Transport.E (Transport.NOT_OPEN,"TServerSocket: Not listening but tried to accept")) end
39660822cf8a4e538b0ffb1a5c0379aa2de14be8192f8bcbffc84dd324b7c5b1
gregtatcam/imaplet-lwt
email_parse.ml
* Copyright ( c ) 2013 - 2015 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2015 Gregory Tsipenyuk <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Lwt open Nocrypto open Imap_crypto open Server_config open Regex open Lightparsemail open Sexplib open Sexplib.Conv exception EmptyPrivateKey let crlf = "\n" keep two blocks of data in the storage : * headers , content , each compressed / encrypted individually * Headers are stored as sexp of headers list ( n*v list ) , * data_descr : * offset points to the start of header / content in each block , * length is the length of the data in the block , * part_descr : * size is the size of the original data as it appears in the email * lines is the number of lines in the original email * Attachment are stored as individual blocks compressed / convergent encrypted * for deduplication * headers, content, each compressed/encrypted individually * Headers are stored as sexp of headers list (n*v list), * data_descr: * offset points to the start of header/content in each block, * length is the length of the data in the block, * part_descr: * size is the size of the original data as it appears in the email * lines is the number of lines in the original email * Attachment are stored as individual blocks compressed/convergent encrypted * for deduplication *) type data_descr = {offset: int; length: int} [@@deriving sexp] type part_descr = {size: int; lines: int} [@@deriving sexp] type email_map = {part: part_descr; header:data_descr; content: [ `Data_map of data_descr | `Message_map of email_map | `Multipart_map of string(*boundary*) * email_map list ] } [@@deriving sexp] let sexp_of t = sexp_of_email_map t let t_of_sexp t = email_map_of_sexp t let add_boundary buffer ~boundary ~suffix = Buffer.add_string buffer (boundary ^ suffix) let get_hdr_attrs headers = List.fold_left (fun (boundary,attach,rfc822) (n,v) -> if match_regex ~case:false n ~regx:"Content-Type" then ( let rfc822 = if match_regex ~case:false v ~regx:"message/rfc822" then true else false in let attach = if match_regex ~case:false v ~regx:"image\\|application\\|audio\\|video" then true else attach in let boundary = if match_regex ~case:false v ~regx:"multipart" then ( if match_regex ~case:false v ~regx:"boundary=\"\\([^\"]+\\)\"" then ("--" ^ Str.matched_group 1 v) else ( let l = Str.split (Str.regexp ";") v in let b = List.fold_left (fun b i -> let i = String.trim i in if match_regex ~case:false i ~regx:"^boundary=\\(.+\\)$" then ("--" ^ Str.matched_group 1 i) else b ) "" l in if b <> "" then b else boundary ) ) else boundary in boundary,attach,rfc822 ) else boundary,attach,rfc822 ) ("",false,false) headers let headers_str_of_list headers transform = transform (`Headers (List.fold_left (fun acc (n,v) -> acc ^ n ^ ":" ^ v ^ crlf ) "" headers)) let email_content pub_key config attachment content transform = let content = if attachment then transform (`Attachment content) else transform (`Body content) in let size = Bytes.length content in let lines = Utils.lines content in if config.encrypt && attachment then ( return (content,size,lines) ) else if config.compress_attach && attachment then ( (*content compressed separately *) return (do_compress content, size, lines) ) else ( return (content,size,lines) ) let do_encrypt pub_key config data = if config.encrypt then ( return (encrypt ~compress:config.compress data pub_key) ) else if config.compress then ( return (do_compress data) ) else ( return data ) let get_header_descr headers headers_buff transform = let headers_str = headers_str_of_list headers transform in let headers_sexp_str = Sexp.to_string (sexp_of_list (fun (n,v) -> sexp_of_pair sexp_of_string sexp_of_string (n,v) ) headers) in let descr = { offset = Buffer.length headers_buff; length = Bytes.length headers_sexp_str; } in let part = { size = Bytes.length headers_str; lines = Utils.lines headers_str } in Buffer.add_string headers_buff headers_sexp_str; (part,descr) (* parse the email message into MIME parts * all headers are concat together and saved as a separate blob. * attachments are saved each into a separate blob. * all other content is concat together, along with a map that references * all parts, their storage location, and their location inside the message, * and all saved into a separate blob. all blobs are saved under * user/Storage/hash key where the hash is the hash of the whole message *) let do_encrypt_content pub_key config email save_attachment hash transform = let content_buff = Buffer.create 100 in let headers_buff = Buffer.create 100 in let rec walk email multipart last_crlf totsize totlines attachments = let headers = Headers.to_list (Email.headers email) in let (header_part,header_descr) = get_header_descr headers headers_buff transform in let boundary,attach,rfc822 = get_hdr_attrs headers in match Content.content (Email.body email) with | `Data data -> do n't need to key attachments or other parts by the content hash * all parts have the root key - message hash , then the subkeys are * the count , 0 - postmark , 1 - headers , 2 - content , 3 + - attachments * just need to keep the number of attachments * all parts have the root key - message hash, then the subkeys are * the count, 0 - postmark, 1 - headers, 2 - content, 3+ - attachments * just need to keep the number of attachments *) email_content pub_key config attach (Content.to_string data) transform >>= fun (content,size,lines) -> if attach then ( (* consider adding Content-type: message/external-body... *) let attach_contid = (string_of_int (3 + attachments)) in save_attachment hash attach_contid content >>= fun () -> (* +1 for crlf - header crlf content *) let part = if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content=`Attach_map attach_contid },totsize+part.size,totlines+part.lines,1 + attachments) ) else ( let offset = Buffer.length content_buff in let length = Bytes.length content in Buffer.add_string content_buff content; let part = if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content = `Data_map {offset;length}; },totsize+part.size,totlines+part.lines,attachments) ) | `Message email -> walk email multipart 2 0 0 attachments >>= fun (content,size,lines,attachments) -> let part = if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content = `Message_map content; },totsize+part.size,totlines+part.lines,attachments) | `Multipart elist -> assert (boundary <> ""); Lwt_list.fold_left_s (fun (map,size,lines,attachments) email -> let size_ = size + (Bytes.length boundary) + 1 in let lines_ = lines + 1 in walk email true 2 0 0 attachments >>= fun (email_map,size,lines,attachments) -> return (email_map :: map,size_+size,lines_+lines,attachments) 1 because first boundary starts with crlf boundary ends with 2 crlf , last outermost with 1 with 2 crlf, last outermost with 1 *) let lines = lines + 2 in let part= if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content = `Multipart_map (boundary,(List.rev map)) },totsize+part.size,totlines+part.lines,attachments) in walk email false 1 0 0 0 >>= fun (map,_,_,attachments) -> let map_sexp_str = Sexp.to_string (sexp_of_email_map map) in let content = Buffer.contents content_buff in let headers = Printf.sprintf "%07d%s%s" (Bytes.length map_sexp_str) map_sexp_str (Buffer.contents headers_buff) in do_encrypt pub_key config headers >>= fun headers -> do_encrypt pub_key config content >>= fun content -> return (headers,content,attachments) let default_transform = function | `Postmark p -> p | `Headers h -> h | `Body b -> b | `Attachment a -> a let parse ?(transform=default_transform) pub_key config message ~save_message ~save_attachment = let hash = Imap_crypto.get_hash message in Message.parse message >>= fun message -> do_encrypt pub_key config (transform (`Postmark (Postmark.to_string (Message.postmark message)))) >>= fun postmark -> do_encrypt_content pub_key config (Message.email message) save_attachment hash transform >>= fun (headers,content, attachments) -> save_message hash postmark headers content attachments >> return hash (* there must be a better way to do it TBD *) let rec printable buffer str = if Bytes.length str >= 76 then ( Buffer.add_string buffer (Bytes.sub str 0 76); Buffer.add_string buffer crlf; printable buffer (Bytes.sub str 76 (Bytes.length str - 76)) ) else ( Buffer.add_string buffer str; Buffer.add_string buffer crlf; Buffer.contents buffer ) let get_decrypt_attachment priv_key config get_attachment contid = get_attachment contid >>= fun attachment -> if config.encrypt then ( return (conv_decrypt ~compressed:config.compress_attach attachment priv_key) ) else if config.compress_attach then ( return (do_uncompress attachment) ) else ( return attachment ) let header_of_sexp_str str = let sexp = Sexp.of_string str in let headers = list_of_sexp (fun sexp -> pair_of_sexp string_of_sexp string_of_sexp sexp) sexp in headers_str_of_list headers (function | `Headers h -> h) let reassemble_email priv_key config ~headers ~content ~map ~get_attachment = let buffer = Buffer.create 100 in let rec walk map = let header = header_of_sexp_str (Bytes.sub headers map.header.offset map.header.length) in Buffer.add_string buffer header; Buffer.add_string buffer crlf; match map.content with | `Data_map descr -> Buffer.add_string buffer (Bytes.sub content descr.offset descr.length); Buffer.add_string buffer crlf; return () | `Attach_map contid -> get_decrypt_attachment priv_key config get_attachment contid >>= fun cont -> Buffer.add_string buffer cont; Buffer.add_string buffer crlf; return () | `Message_map emap -> walk emap | `Multipart_map (boundary,lmap) -> Buffer.add_string buffer crlf; Lwt_list.iter_s (fun map -> add_boundary buffer ~boundary ~suffix:crlf; walk map ) lmap >>= fun () -> add_boundary buffer ~boundary ~suffix:("--" ^ crlf ^ crlf); return () in walk map >> return (Buffer.contents buffer) let do_decrypt priv_key config data = if config.encrypt then ( return (decrypt ~compressed:config.compress data priv_key) ) else if config.compress then ( return (do_uncompress data) ) else return data let do_decrypt_content priv_key config content = do_decrypt priv_key config content let do_decrypt_headers priv_key config headers = do_decrypt priv_key config headers >>= fun headers -> let len = int_of_string (Bytes.sub headers 0 7) in let map_sexp_str = Bytes.sub headers 7 len in let map = email_map_of_sexp (Sexp.of_string map_sexp_str) in return (map,Bytes.sub headers (7 + len) (Bytes.length headers - 7 - len)) let restore priv_key config ~get_message ~get_attachment = catch (fun () -> get_message () >>= fun (postmark,headers,content) -> do_decrypt priv_key config postmark >>= fun postmark -> do_decrypt_headers priv_key config headers >>= fun (map,headers) -> do_decrypt_content priv_key config content >>= fun content -> reassemble_email priv_key config ~headers ~content ~map ~get_attachment >>= fun email -> Message.parse (String.concat "" [postmark;email]) ) (fun ex -> Printf.printf "restore exception %s\n%!" (Printexc.to_string ex); raise ex) let message_to_blob config keys message = let add buffer content (offset,acc) = Buffer.add_string buffer content; let len = String.length content in (offset+len,(offset,len) :: acc) in let (pub_key,_) = keys in let strm_attach,push_attach = Lwt_stream.create () in let buffer = Buffer.create 100 in let buffer_out = Buffer.create 100 in parse pub_key config message ~save_message:(fun msg_hash postmark headers content attachments -> push_attach None; let acc = add buffer postmark (0,[]) in let acc = add buffer headers acc in let acc = add buffer content acc in Lwt_stream.fold (fun attach acc -> add buffer attach acc ) strm_attach acc >>= fun (_,acc) -> let acc = List.rev acc in let open Sexplib.Conv in let header = Sexplib.Sexp.to_string (sexp_of_list (fun a -> sexp_of_pair sexp_of_int sexp_of_int a) acc) in Buffer.add_string buffer_out (Printf.sprintf "%06d" (String.length header)); Buffer.add_string buffer_out header; Buffer.add_buffer buffer_out buffer; return () ) ~save_attachment:(fun msg_hash contid attachment -> push_attach (Some attachment); return () ) >>= fun hash -> return (hash,(Buffer.contents buffer_out)) let message_unparsed_to_blob config keys message = let hash = Imap_crypto.get_hash message in let (pub_key,_) = keys in do_encrypt pub_key config message >>= fun content -> return (hash,content) let message_unparsed_from_blob config keys message = let (_,priv) = keys in let priv = Utils.option_value_exn ~ex:EmptyPrivateKey priv in do_decrypt priv config message (* lazy_read_message lazily reads the message from the storage * lazy_read_metadata - same for metadata *) let message_from_blob config keys lazy_read_message f = let open Sexplib in let open Sexplib.Conv in let (_,priv) = keys in let priv = Utils.option_value_exn ~ex:EmptyPrivateKey priv in let lazy_header = Lazy.from_fun (fun () -> (* if reading headers then makes sense to read the whole message, no * benefit to do random access *) Lazy.force lazy_read_message >>= fun message -> let len = int_of_string (String.sub message 0 6) in let chunk = String.sub message 6 len in let header = list_of_sexp (fun s -> pair_of_sexp int_of_sexp int_of_sexp s) (Sexp.of_string chunk) in return (6+len,header,message) ) in let get_chunk n = Lazy.force lazy_header >>= fun (base,header,message) -> let (offset,len) = List.nth header n in return (String.sub message (base + offset) len) in let get_chunk_str str = get_chunk (int_of_string str) in let postmark () = get_chunk 0 >>= fun _postmark -> do_decrypt priv config _postmark in let headers () = get_chunk 1 >>= fun _headers -> do_decrypt_headers priv config _headers in let content () = get_chunk 2 >>= fun _content -> do_decrypt_content priv config _content in let attachment = get_decrypt_attachment priv config get_chunk_str in f postmark headers content attachment
null
https://raw.githubusercontent.com/gregtatcam/imaplet-lwt/d7b51253e79cffa97e98ab899ed833cd7cb44bb6/lib/commands/email_parse.ml
ocaml
boundary content compressed separately parse the email message into MIME parts * all headers are concat together and saved as a separate blob. * attachments are saved each into a separate blob. * all other content is concat together, along with a map that references * all parts, their storage location, and their location inside the message, * and all saved into a separate blob. all blobs are saved under * user/Storage/hash key where the hash is the hash of the whole message consider adding Content-type: message/external-body... +1 for crlf - header crlf content there must be a better way to do it TBD lazy_read_message lazily reads the message from the storage * lazy_read_metadata - same for metadata if reading headers then makes sense to read the whole message, no * benefit to do random access
* Copyright ( c ) 2013 - 2015 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2015 Gregory Tsipenyuk <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Lwt open Nocrypto open Imap_crypto open Server_config open Regex open Lightparsemail open Sexplib open Sexplib.Conv exception EmptyPrivateKey let crlf = "\n" keep two blocks of data in the storage : * headers , content , each compressed / encrypted individually * Headers are stored as sexp of headers list ( n*v list ) , * data_descr : * offset points to the start of header / content in each block , * length is the length of the data in the block , * part_descr : * size is the size of the original data as it appears in the email * lines is the number of lines in the original email * Attachment are stored as individual blocks compressed / convergent encrypted * for deduplication * headers, content, each compressed/encrypted individually * Headers are stored as sexp of headers list (n*v list), * data_descr: * offset points to the start of header/content in each block, * length is the length of the data in the block, * part_descr: * size is the size of the original data as it appears in the email * lines is the number of lines in the original email * Attachment are stored as individual blocks compressed/convergent encrypted * for deduplication *) type data_descr = {offset: int; length: int} [@@deriving sexp] type part_descr = {size: int; lines: int} [@@deriving sexp] type email_map = {part: part_descr; header:data_descr; content: [ `Data_map of data_descr | `Message_map of email_map | ] } [@@deriving sexp] let sexp_of t = sexp_of_email_map t let t_of_sexp t = email_map_of_sexp t let add_boundary buffer ~boundary ~suffix = Buffer.add_string buffer (boundary ^ suffix) let get_hdr_attrs headers = List.fold_left (fun (boundary,attach,rfc822) (n,v) -> if match_regex ~case:false n ~regx:"Content-Type" then ( let rfc822 = if match_regex ~case:false v ~regx:"message/rfc822" then true else false in let attach = if match_regex ~case:false v ~regx:"image\\|application\\|audio\\|video" then true else attach in let boundary = if match_regex ~case:false v ~regx:"multipart" then ( if match_regex ~case:false v ~regx:"boundary=\"\\([^\"]+\\)\"" then ("--" ^ Str.matched_group 1 v) else ( let l = Str.split (Str.regexp ";") v in let b = List.fold_left (fun b i -> let i = String.trim i in if match_regex ~case:false i ~regx:"^boundary=\\(.+\\)$" then ("--" ^ Str.matched_group 1 i) else b ) "" l in if b <> "" then b else boundary ) ) else boundary in boundary,attach,rfc822 ) else boundary,attach,rfc822 ) ("",false,false) headers let headers_str_of_list headers transform = transform (`Headers (List.fold_left (fun acc (n,v) -> acc ^ n ^ ":" ^ v ^ crlf ) "" headers)) let email_content pub_key config attachment content transform = let content = if attachment then transform (`Attachment content) else transform (`Body content) in let size = Bytes.length content in let lines = Utils.lines content in if config.encrypt && attachment then ( return (content,size,lines) return (do_compress content, size, lines) ) else ( return (content,size,lines) ) let do_encrypt pub_key config data = if config.encrypt then ( return (encrypt ~compress:config.compress data pub_key) ) else if config.compress then ( return (do_compress data) ) else ( return data ) let get_header_descr headers headers_buff transform = let headers_str = headers_str_of_list headers transform in let headers_sexp_str = Sexp.to_string (sexp_of_list (fun (n,v) -> sexp_of_pair sexp_of_string sexp_of_string (n,v) ) headers) in let descr = { offset = Buffer.length headers_buff; length = Bytes.length headers_sexp_str; } in let part = { size = Bytes.length headers_str; lines = Utils.lines headers_str } in Buffer.add_string headers_buff headers_sexp_str; (part,descr) let do_encrypt_content pub_key config email save_attachment hash transform = let content_buff = Buffer.create 100 in let headers_buff = Buffer.create 100 in let rec walk email multipart last_crlf totsize totlines attachments = let headers = Headers.to_list (Email.headers email) in let (header_part,header_descr) = get_header_descr headers headers_buff transform in let boundary,attach,rfc822 = get_hdr_attrs headers in match Content.content (Email.body email) with | `Data data -> do n't need to key attachments or other parts by the content hash * all parts have the root key - message hash , then the subkeys are * the count , 0 - postmark , 1 - headers , 2 - content , 3 + - attachments * just need to keep the number of attachments * all parts have the root key - message hash, then the subkeys are * the count, 0 - postmark, 1 - headers, 2 - content, 3+ - attachments * just need to keep the number of attachments *) email_content pub_key config attach (Content.to_string data) transform >>= fun (content,size,lines) -> let attach_contid = (string_of_int (3 + attachments)) in save_attachment hash attach_contid content >>= fun () -> let part = if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content=`Attach_map attach_contid },totsize+part.size,totlines+part.lines,1 + attachments) ) else ( let offset = Buffer.length content_buff in let length = Bytes.length content in Buffer.add_string content_buff content; let part = if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content = `Data_map {offset;length}; },totsize+part.size,totlines+part.lines,attachments) ) | `Message email -> walk email multipart 2 0 0 attachments >>= fun (content,size,lines,attachments) -> let part = if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content = `Message_map content; },totsize+part.size,totlines+part.lines,attachments) | `Multipart elist -> assert (boundary <> ""); Lwt_list.fold_left_s (fun (map,size,lines,attachments) email -> let size_ = size + (Bytes.length boundary) + 1 in let lines_ = lines + 1 in walk email true 2 0 0 attachments >>= fun (email_map,size,lines,attachments) -> return (email_map :: map,size_+size,lines_+lines,attachments) 1 because first boundary starts with crlf boundary ends with 2 crlf , last outermost with 1 with 2 crlf, last outermost with 1 *) let lines = lines + 2 in let part= if multipart then {size=size;lines=lines} else {size=header_part.size+size+1;lines=header_part.lines+lines+1} in return ( { part; header=header_descr; content = `Multipart_map (boundary,(List.rev map)) },totsize+part.size,totlines+part.lines,attachments) in walk email false 1 0 0 0 >>= fun (map,_,_,attachments) -> let map_sexp_str = Sexp.to_string (sexp_of_email_map map) in let content = Buffer.contents content_buff in let headers = Printf.sprintf "%07d%s%s" (Bytes.length map_sexp_str) map_sexp_str (Buffer.contents headers_buff) in do_encrypt pub_key config headers >>= fun headers -> do_encrypt pub_key config content >>= fun content -> return (headers,content,attachments) let default_transform = function | `Postmark p -> p | `Headers h -> h | `Body b -> b | `Attachment a -> a let parse ?(transform=default_transform) pub_key config message ~save_message ~save_attachment = let hash = Imap_crypto.get_hash message in Message.parse message >>= fun message -> do_encrypt pub_key config (transform (`Postmark (Postmark.to_string (Message.postmark message)))) >>= fun postmark -> do_encrypt_content pub_key config (Message.email message) save_attachment hash transform >>= fun (headers,content, attachments) -> save_message hash postmark headers content attachments >> return hash let rec printable buffer str = if Bytes.length str >= 76 then ( Buffer.add_string buffer (Bytes.sub str 0 76); Buffer.add_string buffer crlf; printable buffer (Bytes.sub str 76 (Bytes.length str - 76)) ) else ( Buffer.add_string buffer str; Buffer.add_string buffer crlf; Buffer.contents buffer ) let get_decrypt_attachment priv_key config get_attachment contid = get_attachment contid >>= fun attachment -> if config.encrypt then ( return (conv_decrypt ~compressed:config.compress_attach attachment priv_key) ) else if config.compress_attach then ( return (do_uncompress attachment) ) else ( return attachment ) let header_of_sexp_str str = let sexp = Sexp.of_string str in let headers = list_of_sexp (fun sexp -> pair_of_sexp string_of_sexp string_of_sexp sexp) sexp in headers_str_of_list headers (function | `Headers h -> h) let reassemble_email priv_key config ~headers ~content ~map ~get_attachment = let buffer = Buffer.create 100 in let rec walk map = let header = header_of_sexp_str (Bytes.sub headers map.header.offset map.header.length) in Buffer.add_string buffer header; Buffer.add_string buffer crlf; match map.content with | `Data_map descr -> Buffer.add_string buffer (Bytes.sub content descr.offset descr.length); Buffer.add_string buffer crlf; return () | `Attach_map contid -> get_decrypt_attachment priv_key config get_attachment contid >>= fun cont -> Buffer.add_string buffer cont; Buffer.add_string buffer crlf; return () | `Message_map emap -> walk emap | `Multipart_map (boundary,lmap) -> Buffer.add_string buffer crlf; Lwt_list.iter_s (fun map -> add_boundary buffer ~boundary ~suffix:crlf; walk map ) lmap >>= fun () -> add_boundary buffer ~boundary ~suffix:("--" ^ crlf ^ crlf); return () in walk map >> return (Buffer.contents buffer) let do_decrypt priv_key config data = if config.encrypt then ( return (decrypt ~compressed:config.compress data priv_key) ) else if config.compress then ( return (do_uncompress data) ) else return data let do_decrypt_content priv_key config content = do_decrypt priv_key config content let do_decrypt_headers priv_key config headers = do_decrypt priv_key config headers >>= fun headers -> let len = int_of_string (Bytes.sub headers 0 7) in let map_sexp_str = Bytes.sub headers 7 len in let map = email_map_of_sexp (Sexp.of_string map_sexp_str) in return (map,Bytes.sub headers (7 + len) (Bytes.length headers - 7 - len)) let restore priv_key config ~get_message ~get_attachment = catch (fun () -> get_message () >>= fun (postmark,headers,content) -> do_decrypt priv_key config postmark >>= fun postmark -> do_decrypt_headers priv_key config headers >>= fun (map,headers) -> do_decrypt_content priv_key config content >>= fun content -> reassemble_email priv_key config ~headers ~content ~map ~get_attachment >>= fun email -> Message.parse (String.concat "" [postmark;email]) ) (fun ex -> Printf.printf "restore exception %s\n%!" (Printexc.to_string ex); raise ex) let message_to_blob config keys message = let add buffer content (offset,acc) = Buffer.add_string buffer content; let len = String.length content in (offset+len,(offset,len) :: acc) in let (pub_key,_) = keys in let strm_attach,push_attach = Lwt_stream.create () in let buffer = Buffer.create 100 in let buffer_out = Buffer.create 100 in parse pub_key config message ~save_message:(fun msg_hash postmark headers content attachments -> push_attach None; let acc = add buffer postmark (0,[]) in let acc = add buffer headers acc in let acc = add buffer content acc in Lwt_stream.fold (fun attach acc -> add buffer attach acc ) strm_attach acc >>= fun (_,acc) -> let acc = List.rev acc in let open Sexplib.Conv in let header = Sexplib.Sexp.to_string (sexp_of_list (fun a -> sexp_of_pair sexp_of_int sexp_of_int a) acc) in Buffer.add_string buffer_out (Printf.sprintf "%06d" (String.length header)); Buffer.add_string buffer_out header; Buffer.add_buffer buffer_out buffer; return () ) ~save_attachment:(fun msg_hash contid attachment -> push_attach (Some attachment); return () ) >>= fun hash -> return (hash,(Buffer.contents buffer_out)) let message_unparsed_to_blob config keys message = let hash = Imap_crypto.get_hash message in let (pub_key,_) = keys in do_encrypt pub_key config message >>= fun content -> return (hash,content) let message_unparsed_from_blob config keys message = let (_,priv) = keys in let priv = Utils.option_value_exn ~ex:EmptyPrivateKey priv in do_decrypt priv config message let message_from_blob config keys lazy_read_message f = let open Sexplib in let open Sexplib.Conv in let (_,priv) = keys in let priv = Utils.option_value_exn ~ex:EmptyPrivateKey priv in let lazy_header = Lazy.from_fun (fun () -> Lazy.force lazy_read_message >>= fun message -> let len = int_of_string (String.sub message 0 6) in let chunk = String.sub message 6 len in let header = list_of_sexp (fun s -> pair_of_sexp int_of_sexp int_of_sexp s) (Sexp.of_string chunk) in return (6+len,header,message) ) in let get_chunk n = Lazy.force lazy_header >>= fun (base,header,message) -> let (offset,len) = List.nth header n in return (String.sub message (base + offset) len) in let get_chunk_str str = get_chunk (int_of_string str) in let postmark () = get_chunk 0 >>= fun _postmark -> do_decrypt priv config _postmark in let headers () = get_chunk 1 >>= fun _headers -> do_decrypt_headers priv config _headers in let content () = get_chunk 2 >>= fun _content -> do_decrypt_content priv config _content in let attachment = get_decrypt_attachment priv config get_chunk_str in f postmark headers content attachment
a68a8af607b3f0fd63f404f7023b7191dd20d08b9fce8841c98baf6074d7b93d
kit-ty-kate/labrys
pretyper.ml
Copyright ( c ) 2013 - 2017 The Labrys developers . (* See the LICENSE file at the top-level directory. *) open PretypedTree module ForbiddenEnv = Ident.Name.Set let ty_to_effects ty = (fst ty, [ty]) let rec get_rec_ty ~name (loc, t) = match t with | Annot (_, ty) -> ty | Let (_, _, t) | LetRec (_, _, _, t) -> get_rec_ty ~name t | Abs ((name, ty), t) -> let (ty', eff) = get_rec_ty ~name t in let eff = Option.map ty_to_effects eff in ((loc, Fun (ty, eff, ty')), None) | TAbs ((tname, k), t) -> let (ty', eff) = get_rec_ty ~name t in ((loc, Forall ((tname, k), ty')), eff) | CAbs ((_, cl), t) -> let (ty', eff) = get_rec_ty ~name t in let eff = Option.map ty_to_effects eff in ((loc, TyClass (cl, eff, ty')), None) | App _ | TApp _ | CApp _ | Val _ | Var _ | Const _ | PatternMatching _ | Fail _ | Try _ -> let loc = Ident.Name.loc name in Err.fail ~loc "Recursive functions must have explicit return types" let rec pretype_abs ~last_let forbidden_env t = let forbidden_env = match last_let with | Some last_let -> ForbiddenEnv.remove last_let forbidden_env | None -> forbidden_env in pretype_term forbidden_env t and pretype_term ?last_let forbidden_env = function | (loc, DesugaredTree.Abs (arg, t)) -> let t = pretype_abs ~last_let forbidden_env t in (loc, Abs (arg, t)) | (loc, DesugaredTree.TAbs (arg, t)) -> let t = pretype_term forbidden_env t in (loc, TAbs (arg, t)) | (loc, DesugaredTree.CAbs (arg, t)) -> let t = pretype_abs ~last_let forbidden_env t in (loc, CAbs (arg, t)) | (loc, DesugaredTree.App (f, x)) -> let f = pretype_term forbidden_env f in let x = pretype_term forbidden_env x in (loc, App (f, x)) | (loc, DesugaredTree.TApp (f, ty_x)) -> let f = pretype_term forbidden_env f in (loc, TApp (f, ty_x)) | (loc, DesugaredTree.CApp (f, x)) -> let f = pretype_term forbidden_env f in (loc, CApp (f, x)) | (loc, DesugaredTree.Val name) -> if ForbiddenEnv.mem name forbidden_env then Err.fail ~loc "This recursive value cannot be used here" else (loc, Val name) | (loc, DesugaredTree.Var name) -> (loc, Var name) | (loc, DesugaredTree.PatternMatching (t, patterns)) -> let t = pretype_term forbidden_env t in let patterns = let aux (pat, b) = (pat, pretype_term forbidden_env b) in List.map aux patterns in (loc, PatternMatching (t, patterns)) | (loc, DesugaredTree.Let (name, t, xs)) -> let t = pretype_term forbidden_env t in let xs = pretype_term ?last_let forbidden_env xs in (loc, Let (name, t, xs)) | (loc, DesugaredTree.LetRec (name, t, xs)) -> let t = let forbidden_env = ForbiddenEnv.add name forbidden_env in pretype_term ~last_let:name forbidden_env t in let ty = get_rec_ty ~name t in let xs = pretype_term ?last_let forbidden_env xs in (loc, LetRec (name, fst ty, (loc, Annot (t, ty)), xs)) | (loc, DesugaredTree.Fail (ty, t)) -> let t = pretype_term forbidden_env t in (loc, Fail (ty, t)) | (loc, DesugaredTree.Try (e, branches)) -> let e = pretype_term forbidden_env e in let branches = let aux (arg, b) = (arg, pretype_term forbidden_env b) in List.map aux branches in (loc, Try (e, branches)) | (loc, DesugaredTree.Annot (t, ty)) -> let t = pretype_term ?last_let forbidden_env t in (loc, Annot (t, ty)) | (loc, DesugaredTree.Const const) -> (loc, Const const) let forbidden_env = ForbiddenEnv.empty let pretype_top = function | DesugaredTree.Value (name, t) -> let t = pretype_term forbidden_env t in Value (name, t) | DesugaredTree.Type ty -> Type ty | DesugaredTree.Foreign foreign -> Foreign foreign | DesugaredTree.Datatype dtype -> Datatype dtype | DesugaredTree.Exception exn -> Exception exn | DesugaredTree.Class cl -> Class cl | DesugaredTree.Instance (tyclass, name, values) -> let values = let aux (name, t) = (name, pretype_term forbidden_env t) in List.map aux values in Instance (tyclass, name, values) let pretype top = List.map pretype_top top let pretype_interface = Fun.id
null
https://raw.githubusercontent.com/kit-ty-kate/labrys/4a3e0c5dd45343b4de2e22051095b49d05772608/src/pre-typing/pretyper.ml
ocaml
See the LICENSE file at the top-level directory.
Copyright ( c ) 2013 - 2017 The Labrys developers . open PretypedTree module ForbiddenEnv = Ident.Name.Set let ty_to_effects ty = (fst ty, [ty]) let rec get_rec_ty ~name (loc, t) = match t with | Annot (_, ty) -> ty | Let (_, _, t) | LetRec (_, _, _, t) -> get_rec_ty ~name t | Abs ((name, ty), t) -> let (ty', eff) = get_rec_ty ~name t in let eff = Option.map ty_to_effects eff in ((loc, Fun (ty, eff, ty')), None) | TAbs ((tname, k), t) -> let (ty', eff) = get_rec_ty ~name t in ((loc, Forall ((tname, k), ty')), eff) | CAbs ((_, cl), t) -> let (ty', eff) = get_rec_ty ~name t in let eff = Option.map ty_to_effects eff in ((loc, TyClass (cl, eff, ty')), None) | App _ | TApp _ | CApp _ | Val _ | Var _ | Const _ | PatternMatching _ | Fail _ | Try _ -> let loc = Ident.Name.loc name in Err.fail ~loc "Recursive functions must have explicit return types" let rec pretype_abs ~last_let forbidden_env t = let forbidden_env = match last_let with | Some last_let -> ForbiddenEnv.remove last_let forbidden_env | None -> forbidden_env in pretype_term forbidden_env t and pretype_term ?last_let forbidden_env = function | (loc, DesugaredTree.Abs (arg, t)) -> let t = pretype_abs ~last_let forbidden_env t in (loc, Abs (arg, t)) | (loc, DesugaredTree.TAbs (arg, t)) -> let t = pretype_term forbidden_env t in (loc, TAbs (arg, t)) | (loc, DesugaredTree.CAbs (arg, t)) -> let t = pretype_abs ~last_let forbidden_env t in (loc, CAbs (arg, t)) | (loc, DesugaredTree.App (f, x)) -> let f = pretype_term forbidden_env f in let x = pretype_term forbidden_env x in (loc, App (f, x)) | (loc, DesugaredTree.TApp (f, ty_x)) -> let f = pretype_term forbidden_env f in (loc, TApp (f, ty_x)) | (loc, DesugaredTree.CApp (f, x)) -> let f = pretype_term forbidden_env f in (loc, CApp (f, x)) | (loc, DesugaredTree.Val name) -> if ForbiddenEnv.mem name forbidden_env then Err.fail ~loc "This recursive value cannot be used here" else (loc, Val name) | (loc, DesugaredTree.Var name) -> (loc, Var name) | (loc, DesugaredTree.PatternMatching (t, patterns)) -> let t = pretype_term forbidden_env t in let patterns = let aux (pat, b) = (pat, pretype_term forbidden_env b) in List.map aux patterns in (loc, PatternMatching (t, patterns)) | (loc, DesugaredTree.Let (name, t, xs)) -> let t = pretype_term forbidden_env t in let xs = pretype_term ?last_let forbidden_env xs in (loc, Let (name, t, xs)) | (loc, DesugaredTree.LetRec (name, t, xs)) -> let t = let forbidden_env = ForbiddenEnv.add name forbidden_env in pretype_term ~last_let:name forbidden_env t in let ty = get_rec_ty ~name t in let xs = pretype_term ?last_let forbidden_env xs in (loc, LetRec (name, fst ty, (loc, Annot (t, ty)), xs)) | (loc, DesugaredTree.Fail (ty, t)) -> let t = pretype_term forbidden_env t in (loc, Fail (ty, t)) | (loc, DesugaredTree.Try (e, branches)) -> let e = pretype_term forbidden_env e in let branches = let aux (arg, b) = (arg, pretype_term forbidden_env b) in List.map aux branches in (loc, Try (e, branches)) | (loc, DesugaredTree.Annot (t, ty)) -> let t = pretype_term ?last_let forbidden_env t in (loc, Annot (t, ty)) | (loc, DesugaredTree.Const const) -> (loc, Const const) let forbidden_env = ForbiddenEnv.empty let pretype_top = function | DesugaredTree.Value (name, t) -> let t = pretype_term forbidden_env t in Value (name, t) | DesugaredTree.Type ty -> Type ty | DesugaredTree.Foreign foreign -> Foreign foreign | DesugaredTree.Datatype dtype -> Datatype dtype | DesugaredTree.Exception exn -> Exception exn | DesugaredTree.Class cl -> Class cl | DesugaredTree.Instance (tyclass, name, values) -> let values = let aux (name, t) = (name, pretype_term forbidden_env t) in List.map aux values in Instance (tyclass, name, values) let pretype top = List.map pretype_top top let pretype_interface = Fun.id
c350d1ec89ca7255f1f7059c36d263efce25d9bdd724bbfa35da0cfe90692414
ocsigen/obrowser
inline_img.ml
open Js ;; open Html ;; let body = get_element_by_id "body" ;; let h2 = ref 0 and h3 = ref 0 and h4 = ref 0 ;; let imgs = ref [||] let display_img idx = let nb = Array.length !imgs in let current = ref idx in let vimg = img ~src:("pictures/" ^ (!imgs).(!current)) () in let mask = div ~style:"position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; \ background-color: black; opacity: .8;" [] and pdiv = div ~style:"position: fixed; right: 10px; top: 10px; -moz-border-radius: 5px; \ padding: 10px; background-color: white; text-align: center;" [vimg ; br ()] in let time = int_input ~size:3 ~value:30 () in let diapo = span [] in let rec start_diapo () = Node.replace_all diapo (span [a ~onclick:(fun () -> let rec play t = current := (!current + 1) mod nb ; Node.set_attribute vimg "src" ("pictures/" ^ (!imgs).(!current)) ; Thread.delay (float_of_int t) ; play t in let t = Thread.create play (time.get ()) in stop_diapo t) [string "[PLAY]"] ; string " (" ; time.node ; string " secs)"]) and stop_diapo t = Node.replace_all diapo (span [a ~onclick:(fun () -> Thread.kill t ; start_diapo () ) [string "[STOP]"]]) in start_diapo () ; Node.append pdiv (div [a ~onclick:(fun () -> Node.remove body mask ; Node.remove body pdiv) [string "[CLOSE]"] ; string " - " ; a ~onclick:(fun () -> current := (!current + nb - 1) mod nb ; Node.set_attribute vimg "src" ("pictures/" ^ (!imgs).(!current))) [string "[< PREV]"] ; string " - " ; a ~onclick:(fun () -> current := (!current + 1) mod nb ; Node.set_attribute vimg "src" ("pictures/" ^ (!imgs).(!current))) [string "[NEXT >]"] ; string " - " ; diapo]) ; Node.append body mask ; Node.append body pdiv ;; let browse node = let rec browse (idx : int) (node : Node.t) = match try Node.get_attribute node "tagName" with _ -> "" with | "A" -> (match decode_id (Node.get_attribute node "id") with | _ :: "viewer" :: picture :: [] -> Node.set_attribute node "id" ("picture_" ^ string_of_int idx) ; Node.set_attribute node "href" "javascript:;" ; Node.register_event node "onclick" display_img idx ; (succ idx, [picture]) | _ -> (idx,[])) | _ -> Node.fold_left (fun (idx,r) c -> let (idx',r') = browse idx c in (idx', r@r')) (idx, []) node in snd (browse 0 node) ;; imgs := Array.of_list (browse body) ;;
null
https://raw.githubusercontent.com/ocsigen/obrowser/977c09029ea1e4fde4fb0bf92b4d893835bd9504/tutorial/inline_img.ml
ocaml
open Js ;; open Html ;; let body = get_element_by_id "body" ;; let h2 = ref 0 and h3 = ref 0 and h4 = ref 0 ;; let imgs = ref [||] let display_img idx = let nb = Array.length !imgs in let current = ref idx in let vimg = img ~src:("pictures/" ^ (!imgs).(!current)) () in let mask = div ~style:"position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; \ background-color: black; opacity: .8;" [] and pdiv = div ~style:"position: fixed; right: 10px; top: 10px; -moz-border-radius: 5px; \ padding: 10px; background-color: white; text-align: center;" [vimg ; br ()] in let time = int_input ~size:3 ~value:30 () in let diapo = span [] in let rec start_diapo () = Node.replace_all diapo (span [a ~onclick:(fun () -> let rec play t = current := (!current + 1) mod nb ; Node.set_attribute vimg "src" ("pictures/" ^ (!imgs).(!current)) ; Thread.delay (float_of_int t) ; play t in let t = Thread.create play (time.get ()) in stop_diapo t) [string "[PLAY]"] ; string " (" ; time.node ; string " secs)"]) and stop_diapo t = Node.replace_all diapo (span [a ~onclick:(fun () -> Thread.kill t ; start_diapo () ) [string "[STOP]"]]) in start_diapo () ; Node.append pdiv (div [a ~onclick:(fun () -> Node.remove body mask ; Node.remove body pdiv) [string "[CLOSE]"] ; string " - " ; a ~onclick:(fun () -> current := (!current + nb - 1) mod nb ; Node.set_attribute vimg "src" ("pictures/" ^ (!imgs).(!current))) [string "[< PREV]"] ; string " - " ; a ~onclick:(fun () -> current := (!current + 1) mod nb ; Node.set_attribute vimg "src" ("pictures/" ^ (!imgs).(!current))) [string "[NEXT >]"] ; string " - " ; diapo]) ; Node.append body mask ; Node.append body pdiv ;; let browse node = let rec browse (idx : int) (node : Node.t) = match try Node.get_attribute node "tagName" with _ -> "" with | "A" -> (match decode_id (Node.get_attribute node "id") with | _ :: "viewer" :: picture :: [] -> Node.set_attribute node "id" ("picture_" ^ string_of_int idx) ; Node.set_attribute node "href" "javascript:;" ; Node.register_event node "onclick" display_img idx ; (succ idx, [picture]) | _ -> (idx,[])) | _ -> Node.fold_left (fun (idx,r) c -> let (idx',r') = browse idx c in (idx', r@r')) (idx, []) node in snd (browse 0 node) ;; imgs := Array.of_list (browse body) ;;
d7db473fa7138d325f69b261837d1ad0f60defa01fef513d8b0eb8055a7e9dbf
evilbinary/scheme-lib
subarray.scm
;;;;"subarray.scm" Scheme array accessory procedures. Copyright ( C ) 2002 and ; ;Permission to copy this software, to modify it, to redistribute it, ;to distribute modified versions, and to use it for any purpose is ;granted, subject to the following restrictions and understandings. ; 1 . Any copy made of this software must include this copyright notice ;in full. ; 2 . I have made no warranty or representation that the operation of ;this software will be error-free, and I am under no obligation to ;provide any services, by way of maintenance, update, or otherwise. ; 3 . In conjunction with products arising from the use of this ;material, there shall be no use of my name in any advertising, ;promotional, or sales literature without prior written consent in ;each case. (require 'array) (require 'multiarg-apply) ;;@code{(require 'subarray)} ;;@ftindex subarray @args array select @dots { } ;;selects a subset of an array. For 0 <= @i{j} < n, @2@i{j} is either an integer , a list of two integers within the range for the @i{j}th index , or # f. ;; When @2@i{j } is a list of two integers , then the @i{j}th index is ;;restricted to that subrange in the returned array. ;; ;;When @2@i{j} is #f, then the full range of the @i{j}th index is accessible in the returned array . An elided argument is equivalent to # f. ;; ;;When @2@i{j} is an integer, then the rank of the returned array is ;;less than @1, and only elements whose @i{j}th index equals @2@i{j} are ;;shared. ;; ;;@example ;;> (define ra '#2A((a b c) (d e f))) ;;#<unspecified> ;;> (subarray ra 0 #f) # 1A(a b c ) ;;> (subarray ra 1 #f) # 1A(d e f ) > ( subarray ra # f 1 ) ;;#1A(b e) > ( subarray ra ' ( 0 1 ) # f ) ;;#2A((a b c) (d e f)) > ( subarray ra # f ' ( 0 1 ) ) ;;#2A((a b) (d e)) > ( subarray ra # f ' ( 1 2 ) ) # 2A((b c ) ( e f ) ) > ( subarray ra # f ' ( 2 1 ) ) # 2A((c b ) ( f e ) ) ;;@end example ;; Arrays can be reflected ( reversed ) using @0 : ;; ;;@example > ( subarray ' # 1A(a b c d e ) ' ( 4 0 ) ) # 1A(e d c b a ) ;;@end example (define (subarray array . selects) (apply make-shared-array array (lambda args (let loop ((sels selects) (args args) (lst '())) (cond ((null? sels) (if (null? args) (reverse lst) (loop sels (cdr args) (cons (car args) lst)))) ((number? (car sels)) (loop (cdr sels) args (cons (car sels) lst))) ((list? (car sels)) (loop (cdr sels) (cdr args) (cons (if (< (cadar sels) (caar sels)) (+ (- (caar sels) (car args))) (+ (caar sels) (car args))) lst))) (else (loop (cdr sels) (cdr args) (cons (car args) lst)))))) (let loop ((sels selects) (dims (array-dimensions array)) (ndims '())) (cond ((null? dims) (if (null? sels) (reverse ndims) (slib:error 'subarray 'rank (array-rank array) 'mismatch selects))) ((null? sels) (loop sels (cdr dims) (cons (car dims) ndims))) ((number? (car sels)) (loop (cdr sels) (cdr dims) ndims)) ((not (car sels)) (loop (cdr sels) (cdr dims) (cons (car dims) ndims))) ((list? (car sels)) (loop (cdr sels) (cdr dims) (cons (list 0 (abs (- (cadar sels) (caar sels)))) ndims))) (else (loop (cdr sels) (cdr dims) (cons (car sels) ndims))))))) ;;@body ;; ;;Returns a subarray sharing contents with @1 except for slices removed from either side of each dimension . Each of the @2 is an exact ;;integer indicating how much to trim. A positive @var{s} trims the ;;data from the lower end and reduces the upper bound of the result; a ;;negative @var{s} trims from the upper end and increases the lower ;;bound. ;; ;;For example: ;;@example ( array - trim ' # ( 0 1 2 3 4 ) 1 ) @result { } # 1A(1 2 3 4 ) ( array - trim ' # ( 0 1 2 3 4 ) -1 ) @result { } # 1A(0 1 2 3 ) ;; ;;(require 'array-for-each) ;;(define (centered-difference ra) ( array - map ra - ( array - trim ra 1 ) ( array - trim ra -1 ) ) ) ;; ;;(centered-difference '#(0 1 3 5 9 22)) ;; @result{} #(1 2 2 4 13) ;;@end example (define (array-trim array . trims) (define (loop dims trims shps) (cond ((null? trims) (if (null? dims) (reverse shps) (loop (cdr dims) '() (cons (list 0 (+ -1 (car dims))) shps)))) ((null? dims) (slib:error 'array-trim 'too 'many 'trims trims)) ((negative? (car trims)) (loop (cdr dims) (cdr trims) (cons (list 0 (+ (car trims) (car dims) -1)) shps))) (else (loop (cdr dims) (cdr trims) (cons (list (car trims) (+ -1 (car dims))) shps))))) (apply subarray array (loop (array-dimensions array) trims '())))
null
https://raw.githubusercontent.com/evilbinary/scheme-lib/6df491c1f616929caa4e6569fa44e04df7a356a7/packages/slib/subarray.scm
scheme
"subarray.scm" Scheme array accessory procedures. Permission to copy this software, to modify it, to redistribute it, to distribute modified versions, and to use it for any purpose is granted, subject to the following restrictions and understandings. in full. this software will be error-free, and I am under no obligation to provide any services, by way of maintenance, update, or otherwise. material, there shall be no use of my name in any advertising, promotional, or sales literature without prior written consent in each case. @code{(require 'subarray)} @ftindex subarray selects a subset of an array. For 0 <= @i{j} < n, @2@i{j} is either restricted to that subrange in the returned array. When @2@i{j} is #f, then the full range of the @i{j}th index is When @2@i{j} is an integer, then the rank of the returned array is less than @1, and only elements whose @i{j}th index equals @2@i{j} are shared. @example > (define ra '#2A((a b c) (d e f))) #<unspecified> > (subarray ra 0 #f) > (subarray ra 1 #f) #1A(b e) #2A((a b c) (d e f)) #2A((a b) (d e)) @end example @example @end example @body Returns a subarray sharing contents with @1 except for slices removed integer indicating how much to trim. A positive @var{s} trims the data from the lower end and reduces the upper bound of the result; a negative @var{s} trims from the upper end and increases the lower bound. For example: @example (require 'array-for-each) (define (centered-difference ra) (centered-difference '#(0 1 3 5 9 22)) @result{} #(1 2 2 4 13) @end example
Copyright ( C ) 2002 and 1 . Any copy made of this software must include this copyright notice 2 . I have made no warranty or representation that the operation of 3 . In conjunction with products arising from the use of this (require 'array) (require 'multiarg-apply) @args array select @dots { } an integer , a list of two integers within the range for the @i{j}th index , or # f. When @2@i{j } is a list of two integers , then the @i{j}th index is accessible in the returned array . An elided argument is equivalent to # f. # 1A(a b c ) # 1A(d e f ) > ( subarray ra # f 1 ) > ( subarray ra ' ( 0 1 ) # f ) > ( subarray ra # f ' ( 0 1 ) ) > ( subarray ra # f ' ( 1 2 ) ) # 2A((b c ) ( e f ) ) > ( subarray ra # f ' ( 2 1 ) ) # 2A((c b ) ( f e ) ) Arrays can be reflected ( reversed ) using @0 : > ( subarray ' # 1A(a b c d e ) ' ( 4 0 ) ) # 1A(e d c b a ) (define (subarray array . selects) (apply make-shared-array array (lambda args (let loop ((sels selects) (args args) (lst '())) (cond ((null? sels) (if (null? args) (reverse lst) (loop sels (cdr args) (cons (car args) lst)))) ((number? (car sels)) (loop (cdr sels) args (cons (car sels) lst))) ((list? (car sels)) (loop (cdr sels) (cdr args) (cons (if (< (cadar sels) (caar sels)) (+ (- (caar sels) (car args))) (+ (caar sels) (car args))) lst))) (else (loop (cdr sels) (cdr args) (cons (car args) lst)))))) (let loop ((sels selects) (dims (array-dimensions array)) (ndims '())) (cond ((null? dims) (if (null? sels) (reverse ndims) (slib:error 'subarray 'rank (array-rank array) 'mismatch selects))) ((null? sels) (loop sels (cdr dims) (cons (car dims) ndims))) ((number? (car sels)) (loop (cdr sels) (cdr dims) ndims)) ((not (car sels)) (loop (cdr sels) (cdr dims) (cons (car dims) ndims))) ((list? (car sels)) (loop (cdr sels) (cdr dims) (cons (list 0 (abs (- (cadar sels) (caar sels)))) ndims))) (else (loop (cdr sels) (cdr dims) (cons (car sels) ndims))))))) from either side of each dimension . Each of the @2 is an exact ( array - trim ' # ( 0 1 2 3 4 ) 1 ) @result { } # 1A(1 2 3 4 ) ( array - trim ' # ( 0 1 2 3 4 ) -1 ) @result { } # 1A(0 1 2 3 ) ( array - map ra - ( array - trim ra 1 ) ( array - trim ra -1 ) ) ) (define (array-trim array . trims) (define (loop dims trims shps) (cond ((null? trims) (if (null? dims) (reverse shps) (loop (cdr dims) '() (cons (list 0 (+ -1 (car dims))) shps)))) ((null? dims) (slib:error 'array-trim 'too 'many 'trims trims)) ((negative? (car trims)) (loop (cdr dims) (cdr trims) (cons (list 0 (+ (car trims) (car dims) -1)) shps))) (else (loop (cdr dims) (cdr trims) (cons (list (car trims) (+ -1 (car dims))) shps))))) (apply subarray array (loop (array-dimensions array) trims '())))
3348b2c4499a6c4bce6a688adaccda800232e4fcf6d390e72e67dd0d2908d820
ocurrent/ocaml-docs-ci
solver_pool.ml
let spawn_local ~jobs ?solver_dir () : Solver_api.Solver.t = let p, c = Unix.(socketpair PF_UNIX SOCK_STREAM 0 ~cloexec:true) in Unix.clear_close_on_exec c; let solver_dir = match solver_dir with None -> Fpath.to_string (Current.state_dir "solver") | Some x -> x in let cmd = ("", [| "ocaml-docs-ci-solver"; "--jobs"; string_of_int jobs |]) in let _child = Lwt_process.open_process_none ~cwd:solver_dir ~stdin:(`FD_move c) cmd in let switch = Lwt_switch.create () in let p = Lwt_unix.of_unix_file_descr p |> Capnp_rpc_unix.Unix_flow.connect ~switch |> Capnp_rpc_net.Endpoint.of_flow (module Capnp_rpc_unix.Unix_flow) ~peer_id:Capnp_rpc_net.Auth.Digest.insecure ~switch in let conn = Capnp_rpc_unix.CapTP.connect ~restore:Capnp_rpc_net.Restorer.none p in let solver = Capnp_rpc_unix.CapTP.bootstrap conn (Capnp_rpc_net.Restorer.Id.public "solver") in solver |> Capnp_rpc_lwt.Capability.when_broken (fun ex -> Fmt.failwith "Solver process failed: %a" Capnp_rpc.Exception.pp ex); solver
null
https://raw.githubusercontent.com/ocurrent/ocaml-docs-ci/02fc49bf690ea298cbb034c1bd8c96c7a4c2e8d0/src/lib/solver_pool.ml
ocaml
let spawn_local ~jobs ?solver_dir () : Solver_api.Solver.t = let p, c = Unix.(socketpair PF_UNIX SOCK_STREAM 0 ~cloexec:true) in Unix.clear_close_on_exec c; let solver_dir = match solver_dir with None -> Fpath.to_string (Current.state_dir "solver") | Some x -> x in let cmd = ("", [| "ocaml-docs-ci-solver"; "--jobs"; string_of_int jobs |]) in let _child = Lwt_process.open_process_none ~cwd:solver_dir ~stdin:(`FD_move c) cmd in let switch = Lwt_switch.create () in let p = Lwt_unix.of_unix_file_descr p |> Capnp_rpc_unix.Unix_flow.connect ~switch |> Capnp_rpc_net.Endpoint.of_flow (module Capnp_rpc_unix.Unix_flow) ~peer_id:Capnp_rpc_net.Auth.Digest.insecure ~switch in let conn = Capnp_rpc_unix.CapTP.connect ~restore:Capnp_rpc_net.Restorer.none p in let solver = Capnp_rpc_unix.CapTP.bootstrap conn (Capnp_rpc_net.Restorer.Id.public "solver") in solver |> Capnp_rpc_lwt.Capability.when_broken (fun ex -> Fmt.failwith "Solver process failed: %a" Capnp_rpc.Exception.pp ex); solver
c7178277ca8874275816af93156f7eb8885dafc5a35fad8a4ebbcb6ad24d690e
elastic/eui-cljs
icon_ml_create_advanced_job.cljs
(ns eui.icon-ml-create-advanced-job (:require ["@elastic/eui/lib/components/icon/assets/ml_create_advanced_job.js" :as eui])) (def mlCreateAdvancedJob eui/icon)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_ml_create_advanced_job.cljs
clojure
(ns eui.icon-ml-create-advanced-job (:require ["@elastic/eui/lib/components/icon/assets/ml_create_advanced_job.js" :as eui])) (def mlCreateAdvancedJob eui/icon)
c2aa33b0691af6864ed4ecd21f21160c2ae9f69ddaaf63d7af0c04e5b45a361a
brunjlar/protop
Transitivities.hs
# LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # {-# LANGUAGE GADTs #-} # LANGUAGE TypeOperators # module Protop.Core.Transitivities ( (:>)(..) ) where import Data.Proxy (Proxy(..)) import Protop.Core.Proofs import Protop.Core.Setoids infixl 9 :> data (:>) :: * -> * -> * where (:>) :: ( IsProof a , IsProof b , Rhs a ~ Lhs b ) => a -> b -> a :> b instance Show (a :> b) where show (p :> q) = "(" ++ show p ++ " > " ++ show q ++ ")" instance ( IsProof a , IsProof b , Rhs a ~ Lhs b ) => IsProof (a :> b) where type Lhs (a :> b) = Lhs a type Rhs (a :> b) = Rhs b proof (p :> q) x = transitivity (Proxy :: Proxy (DTARGET a)) (proof p x) (proof q x) proxy'' _ = proxy'' Proxy :> proxy'' Proxy
null
https://raw.githubusercontent.com/brunjlar/protop/9f520aeb4dd9baf9ebed8751584e33e3a3e23df6/src/Protop/Core/Transitivities.hs
haskell
# LANGUAGE GADTs #
# LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # module Protop.Core.Transitivities ( (:>)(..) ) where import Data.Proxy (Proxy(..)) import Protop.Core.Proofs import Protop.Core.Setoids infixl 9 :> data (:>) :: * -> * -> * where (:>) :: ( IsProof a , IsProof b , Rhs a ~ Lhs b ) => a -> b -> a :> b instance Show (a :> b) where show (p :> q) = "(" ++ show p ++ " > " ++ show q ++ ")" instance ( IsProof a , IsProof b , Rhs a ~ Lhs b ) => IsProof (a :> b) where type Lhs (a :> b) = Lhs a type Rhs (a :> b) = Rhs b proof (p :> q) x = transitivity (Proxy :: Proxy (DTARGET a)) (proof p x) (proof q x) proxy'' _ = proxy'' Proxy :> proxy'' Proxy
1af1b97f6f5d21fbafa13cdbb57be67aeb0497ac7821970a2068dd217387fc28
borgeby/jarl
http_client.cljs
(ns jarl.http-client) (def request-fn #(throw (ex-info "not implemented yet" {}))) (defn send-request [_] (throw (ex-info "not implemented yet" {})))
null
https://raw.githubusercontent.com/borgeby/jarl/2659afc6c72afb961cb1e98b779beb2b0b5d79c6/core/src/main/cljs/jarl/http_client.cljs
clojure
(ns jarl.http-client) (def request-fn #(throw (ex-info "not implemented yet" {}))) (defn send-request [_] (throw (ex-info "not implemented yet" {})))
cb9eb71013f31025c912751c82245ee24bf56fde0f8bfa715fb64e246f099555
facebook/pyre-check
interface.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) This module implements the logic to call out to buck as needed for classic Pyre daemons . The primary action we take is to build source - db targets , which produces a json map from source paths ( mostly user - controlled source code , but also some buck - built generated code , for example thrift stubs ) to artifact paths . primary action we take is to build source-db targets, which produces a json map from source paths (mostly user-controlled source code, but also some buck-built generated code, for example thrift stubs) to artifact paths. *) open Base exception JsonError of string module BuckOptions = struct type 'raw t = { raw: 'raw; mode: string option; isolation_prefix: string option; } end module BuildResult = struct type t = { build_map: BuildMap.t; targets: Target.t list; } end module V1 = struct module IncompatibleMergeItem = struct type t = { key: string; left_value: string; right_value: string; } [@@deriving sexp, compare] end exception FoundIncompatibleMergeItem of IncompatibleMergeItem.t let resolve_merge_conflict_by_name ~key left_value right_value = if String.equal left_value right_value then left_value else raise (FoundIncompatibleMergeItem { IncompatibleMergeItem.key; left_value; right_value }) module BuckChangedTargetsQueryOutput = struct type t = { source_base_path: string; artifact_base_path: string; artifacts_to_sources: (string * string) list; } [@@deriving sexp, compare] let to_partial_build_map { source_base_path; artifact_base_path; artifacts_to_sources } = let to_build_mapping (artifact, source) = Filename.concat artifact_base_path artifact, Filename.concat source_base_path source in match BuildMap.Partial.of_alist (List.map artifacts_to_sources ~f:to_build_mapping) with | `Duplicate_key artifact -> let message = Format.sprintf "Overlapping artifact file detected: %s" artifact in Result.Error message | `Ok partial_build_map -> Result.Ok partial_build_map let to_build_map_batch outputs = let rec merge ~sofar = function | [] -> Result.Ok (BuildMap.create sofar) | output :: rest -> ( match to_partial_build_map output with | Result.Error _ as error -> error | Result.Ok next_build_map -> ( try let sofar = BuildMap.Partial.merge sofar next_build_map ~resolve_conflict:resolve_merge_conflict_by_name in merge ~sofar rest with | FoundIncompatibleMergeItem { IncompatibleMergeItem.key; _ } -> let message = Format.sprintf "Overlapping artifact file detected: %s" key in Result.Error message)) in merge ~sofar:BuildMap.Partial.empty outputs end type t = { normalize_targets: string list -> Target.t list Lwt.t; query_owner_targets: targets:Target.t list -> PyrePath.t list -> BuckChangedTargetsQueryOutput.t list Lwt.t; construct_build_map: Target.t list -> BuildResult.t Lwt.t; } let create_for_testing ~normalize_targets ~construct_build_map ~query_owner_targets () = { normalize_targets; construct_build_map; query_owner_targets } let source_database_suffix = "#source-db" let query_buck_for_normalized_targets { BuckOptions.raw; mode; isolation_prefix } target_specifications = match target_specifications with | [] -> Lwt.return "{}" | _ -> List.concat [ (* Force `buck` to hand back structured JSON output instead of plain text. *) ["--json"]; (* Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier. *) ["--config"; "client.id=pyre"]; [ (* Build all python-related rules. *) "kind(\"python_binary|python_library|python_test\", %s)" (* Certain Python-related rules are exposed as `configured_alias` which cannot be picked up by the preceding query. *) ^ " + kind(\"python_binary|python_test\", deps(kind(configured_alias, %s), 1))" (* Don't bother with generated rules. *) ^ " - attrfilter(labels, generated, %s)" (* `python_unittest()` sources are separated into a macro-generated library, so make sure we include those. *) ^ " + attrfilter(labels, unittest-library, %s)" ^ (* Provide an opt-out label so that rules can avoid type-checking (e.g. some libraries wrap generated sources which are expensive to build and therefore typecheck). *) " - attrfilter(labels, no_pyre, %s)"; ]; target_specifications; ] |> Raw.V1.query ?mode ?isolation_prefix raw let query_buck_for_changed_targets ~targets { BuckOptions.raw; mode; isolation_prefix } source_paths = match targets with | [] -> Lwt.return "{}" | targets -> ( match source_paths with | [] -> Lwt.return "{}" | source_paths -> let target_string = (* Targets need to be quoted since `buck query` can fail with syntax errors if target name contains special characters like `=`. *) let quote_string value = Format.sprintf "\"%s\"" value in let quote_target target = Target.show target |> quote_string in List.map targets ~f:quote_target |> String.concat ~sep:" " in List.concat [ ["--json"]; ["--config"; "client.id=pyre"]; [ (* This will get only those owner targets that are beneath our targets or the dependencies of our targets. *) Format.sprintf "owner(%%s) ^ deps(set(%s))" target_string; ]; List.map source_paths ~f:PyrePath.show; (* These attributes are all we need to locate the source and artifact relative paths. *) ["--output-attributes"; "srcs"; "buck.base_path"; "buck.base_module"; "base_module"]; ] |> Raw.V1.query ?mode ?isolation_prefix raw) let run_buck_build_for_targets { BuckOptions.raw; mode; isolation_prefix } targets = match targets with | [] -> Lwt.return "{}" | _ -> List.concat [ (* Force `buck` to hand back structured JSON output instead of plain text. *) ["--show-full-json-output"]; (* Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier. *) ["--config"; "client.id=pyre"]; List.map targets ~f:(fun target -> Format.sprintf "%s%s" (Target.show target) source_database_suffix); ] |> Raw.V1.build ?mode ?isolation_prefix raw let parse_buck_normalized_targets_query_output query_output = let open Yojson.Safe in try from_string ~fname:"buck query output" query_output |> Util.to_assoc |> List.map ~f:(fun (_, targets_json) -> Util.to_list targets_json |> List.map ~f:Util.to_string) |> List.concat_no_order |> List.dedup_and_sort ~compare:String.compare with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_buck_changed_targets_query_output query_output = let open Yojson.Safe in try let parse_target_json target_json = let source_base_path = Util.member "buck.base_path" target_json |> Util.to_string in let artifact_base_path = match Util.member "buck.base_module" target_json with | `String base_module -> String.tr ~target:'.' ~replacement:'/' base_module | _ -> source_base_path in let artifact_base_path = match Util.member "base_module" target_json with | `String base_module -> String.tr ~target:'.' ~replacement:'/' base_module | _ -> artifact_base_path in let artifacts_to_sources = match Util.member "srcs" target_json with | `Assoc targets_to_sources -> List.map targets_to_sources ~f:(fun (target, source_json) -> target, Util.to_string source_json) |> List.filter ~f:(function | _, source when String.is_prefix ~prefix:"//" source -> (* This can happen for custom rules. *) false | _ -> true) | _ -> [] in { BuckChangedTargetsQueryOutput.source_base_path; artifact_base_path; artifacts_to_sources } in from_string ~fname:"buck changed paths query output" query_output |> Util.to_assoc |> List.map ~f:(fun (_, target_json) -> parse_target_json target_json) with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_buck_build_output query_output = let open Yojson.Safe in try from_string ~fname:"buck build output" query_output |> Util.to_assoc |> List.map ~f:(fun (target, path_json) -> target, Util.to_string path_json) with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let load_partial_build_map_from_json json = let filter_mapping ~key ~data:_ = match key with | "__manifest__.py" | "__test_main__.py" | "__test_modules__.py" -> (* These files are not useful for type checking but create many conflicts when merging different targets. *) false | _ -> true in BuildMap.Partial.of_json_exn_ignoring_duplicates json |> BuildMap.Partial.filter ~f:filter_mapping let load_partial_build_map path = let open Lwt.Infix in let path = PyrePath.absolute path in Lwt_io.(with_file ~mode:Input path read) >>= fun content -> try Yojson.Safe.from_string ~fname:path content |> load_partial_build_map_from_json |> Lwt.return with | Yojson.Safe.Util.Type_error (message, _) | Yojson.Safe.Util.Undefined (message, _) -> raise (JsonError message) | Yojson.Json_error message -> raise (JsonError message) let normalize_targets_with_options buck_options target_specifications = let open Lwt.Infix in Log.info "Collecting buck targets to build..."; query_buck_for_normalized_targets buck_options target_specifications >>= fun query_output -> let targets = parse_buck_normalized_targets_query_output query_output |> List.map ~f:Target.of_string in Log.info "Collected %d targets" (List.length targets); Lwt.return targets let query_owner_targets_with_options buck_options ~targets changed_paths = let open Lwt.Infix in Log.info "Running `buck query`..."; query_buck_for_changed_targets ~targets buck_options changed_paths >>= fun query_output -> Lwt.return (parse_buck_changed_targets_query_output query_output) Run ` buck build ` on the given target with the ` # source - db ` flavor . This will make ` buck ` construct its link tree and for each target , dump a source - db JSON file containing how files in the link tree corresponds to the final Python artifacts . Return a list containing the input targets as well as the corresponding location of the source - db JSON file . Note that targets in the returned list is not guaranteed to be in the same order as the input list . May raise [ . Raw . BuckError ] when ` buck ` invocation fails , or [ . Builder . JsonError ] when ` buck ` itself succeeds but its output can not be parsed . construct its link tree and for each target, dump a source-db JSON file containing how files in the link tree corresponds to the final Python artifacts. Return a list containing the input targets as well as the corresponding location of the source-db JSON file. Note that targets in the returned list is not guaranteed to be in the same order as the input list. May raise [Buck.Raw.BuckError] when `buck` invocation fails, or [Buck.Builder.JsonError] when `buck` itself succeeds but its output cannot be parsed. *) let build_source_databases buck_options targets = let open Lwt.Infix in Log.info "Building Buck source databases..."; run_buck_build_for_targets buck_options targets >>= fun build_output -> let source_database_suffix_length = String.length source_database_suffix in parse_buck_build_output build_output |> List.map ~f:(fun (target, path) -> ( String.drop_suffix target source_database_suffix_length |> Target.of_string, PyrePath.create_absolute path )) |> Lwt.return let merge_target_and_build_map (target_and_build_maps_sofar, build_map_sofar) (next_target, next_build_map) = let open BuildMap.Partial in try let merged_build_map = merge build_map_sofar next_build_map ~resolve_conflict:resolve_merge_conflict_by_name in (next_target, next_build_map) :: target_and_build_maps_sofar, merged_build_map with | FoundIncompatibleMergeItem { IncompatibleMergeItem.key; left_value; right_value } -> Log.warning "Cannot include target for type checking: %s" (Target.show next_target); (* For better error message, try to figure out which target casued the conflict. *) let conflicting_target = let match_target ~key (target, build_map) = if contains ~key build_map then Some target else None in List.find_map target_and_build_maps_sofar ~f:(match_target ~key) in Log.info "... file `%s` has already been mapped to `%s`%s but the target maps it to `%s` instead. " key left_value (Option.value_map conflicting_target ~default:"" ~f:(Format.sprintf " by `%s`")) right_value; target_and_build_maps_sofar, build_map_sofar let load_and_merge_build_maps target_and_source_database_paths = let open Lwt.Infix in let number_of_targets_to_load = List.length target_and_source_database_paths in Log.info "Loading source databases for %d targets..." number_of_targets_to_load; let rec fold ~sofar = function | [] -> Lwt.return sofar | (next_target, next_build_map_path) :: rest -> load_partial_build_map next_build_map_path >>= fun next_build_map -> let sofar = merge_target_and_build_map sofar (next_target, next_build_map) in fold ~sofar rest in fold target_and_source_database_paths ~sofar:([], BuildMap.Partial.empty) >>= fun (reversed_target_and_build_maps, merged_build_map) -> let targets = List.rev_map reversed_target_and_build_maps ~f:fst in if List.length targets < number_of_targets_to_load then Log.warning "One or more targets get dropped by Pyre due to potential conflicts. For more details, see \ -target-conflict"; Lwt.return { BuildResult.targets; build_map = BuildMap.create merged_build_map } (* Unlike [load_and_merge_build_maps], this function assumes build maps are already loaded into memory and just try to merge them synchronously. Its main purpose is to facilitate testing of the [merge_target_and_build_map] function. *) let merge_build_maps target_and_build_maps = let reversed_target_and_build_maps, merged_build_map = List.fold target_and_build_maps ~init:([], BuildMap.Partial.empty) ~f:merge_target_and_build_map in let targets = List.rev_map reversed_target_and_build_maps ~f:fst in targets, BuildMap.create merged_build_map let load_and_merge_source_databases target_and_source_database_paths = Make sure the targets are in a determinstic order . This is important to make the merging process deterministic later . Note that our dependency on the ordering of the target also implies that the loading process is non - parallelizable . process deterministic later. Note that our dependency on the ordering of the target also implies that the loading process is non-parallelizable. *) List.sort target_and_source_database_paths ~compare:(fun (left_target, _) (right_target, _) -> Target.compare left_target right_target) |> load_and_merge_build_maps let construct_build_map_with_options buck_options normalized_targets = let open Lwt.Infix in build_source_databases buck_options normalized_targets >>= fun target_and_source_database_paths -> load_and_merge_source_databases target_and_source_database_paths let create ?mode ?isolation_prefix raw = let buck_options = { BuckOptions.mode; isolation_prefix; raw } in { normalize_targets = normalize_targets_with_options buck_options; query_owner_targets = query_owner_targets_with_options buck_options; construct_build_map = construct_build_map_with_options buck_options; } let normalize_targets { normalize_targets; _ } target_specifications = normalize_targets target_specifications let query_owner_targets { query_owner_targets; _ } ~targets paths = query_owner_targets ~targets paths let construct_build_map { construct_build_map; _ } normalized_targets = construct_build_map normalized_targets end module V2 = struct type t = { construct_build_map: string list -> BuildMap.t Lwt.t } let create_for_testing ~construct_build_map () = { construct_build_map } let build_map_key = "build_map" let built_targets_count_key = "built_targets_count" let dropped_targets_key = "dropped_targets" module BuckBxlBuilderOutput = struct module Conflict = struct type t = { conflict_with: string; artifact_path: string; preserved_source_path: string; dropped_source_path: string; } [@@deriving sexp, compare, of_yojson { strict = false }] end type t = { build_map: BuildMap.t; target_count: int; conflicts: (Target.t * Conflict.t) list; } end let parse_merged_sourcedb merged_sourcedb : BuckBxlBuilderOutput.t = let open Yojson.Safe in try let build_map = Util.member build_map_key merged_sourcedb |> BuildMap.Partial.of_json_exn_ignoring_duplicates_no_dependency |> BuildMap.create in let target_count = Util.member built_targets_count_key merged_sourcedb |> Util.to_int in let conflicts = let conflict_of_yojson json = match BuckBxlBuilderOutput.Conflict.of_yojson json with | Result.Ok conflict -> conflict | Result.Error message -> let message = Format.sprintf "Cannot parse conflict item: %s" message in raise (JsonError message) in Util.member dropped_targets_key merged_sourcedb |> Util.to_assoc |> List.map ~f:(fun (target, conflict_json) -> Target.of_string target, conflict_of_yojson conflict_json) in { BuckBxlBuilderOutput.build_map; target_count; conflicts } with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_bxl_output bxl_output = let open Yojson.Safe in try let merged_sourcedb_path = from_string ~fname:"buck bxl output" bxl_output |> Util.member "db" |> Util.to_string in from_file merged_sourcedb_path |> parse_merged_sourcedb with | Yojson.Json_error message | Util.Type_error (message, _) | Sys_error message -> raise (JsonError message) let run_bxl_for_targets ~bxl_builder ~buck_options:{ BuckOptions.raw; mode; isolation_prefix; _ } target_patterns = match target_patterns with | [] -> `Assoc [ build_map_key, `Assoc []; built_targets_count_key, `Assoc []; dropped_targets_key, `Assoc []; ] |> Yojson.Safe.to_string |> Lwt.return | _ -> List.concat [ Location of the BXL builder . [bxl_builder]; Force ` buck ` to opt - out fancy tui logging . ["--console=simple"]; (* Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier. *) ["--config"; "client.id=pyre"]; ["--"]; List.bind target_patterns ~f:(fun target -> ["--target"; Format.sprintf "%s" target]); ] |> Raw.V2.bxl ?mode ?isolation_prefix raw let warn_on_conflict ~target { BuckBxlBuilderOutput.Conflict.conflict_with; artifact_path; preserved_source_path; dropped_source_path; } = Log.warning "Cannot include target for type checking: %s" (Target.show target); Log.info "... file `%s` has already been mapped to `%s` by `%s` but the target maps it to `%s` \ instead. " artifact_path preserved_source_path (Target.show conflict_with) dropped_source_path; () let warn_on_conflicts = function | [] -> () | conflicts -> List.iter conflicts ~f:(fun (target, conflict) -> warn_on_conflict ~target conflict); Log.warning "One or more targets get dropped by Pyre due to potential conflicts. For more details, \ see -target-conflict" let construct_build_map_with_options ~bxl_builder ~buck_options target_patterns = let open Lwt.Infix in Log.info "Building Buck source databases..."; run_bxl_for_targets ~bxl_builder ~buck_options target_patterns >>= fun output -> let { BuckBxlBuilderOutput.build_map; target_count; conflicts } = parse_bxl_output output in warn_on_conflicts conflicts; Log.info "Loaded source databases for %d targets" target_count; Lwt.return build_map let create ?mode ?isolation_prefix ?bxl_builder raw = let buck_options = { BuckOptions.mode; isolation_prefix; raw } in match bxl_builder with | None -> failwith "BXL path is not set but it is required when using Buck2" | Some bxl_builder -> { construct_build_map = construct_build_map_with_options ~bxl_builder ~buck_options } let construct_build_map { construct_build_map; _ } target_patterns = construct_build_map target_patterns end module Lazy = struct type t = { construct_build_map: string list -> BuildMap.t Lwt.t } let create_for_testing ~construct_build_map () = { construct_build_map } let parse_merged_sourcedb merged_sourcedb : BuildMap.t = let open Yojson.Safe in try BuildMap.Partial.of_json_exn_ignoring_duplicates_no_dependency merged_sourcedb |> BuildMap.create with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_bxl_output bxl_output = let open Yojson.Safe in try let merged_sourcedb_path = from_string ~fname:"buck bxl output" bxl_output |> Util.member "db" |> Util.to_string in from_file merged_sourcedb_path |> parse_merged_sourcedb with | Yojson.Json_error message | Util.Type_error (message, _) | Sys_error message -> raise (JsonError message) let run_bxl_for_targets ~bxl_builder ~buck_options:{ BuckOptions.raw; mode; isolation_prefix; _ } target_patterns = match target_patterns with | [] -> Lwt.return BuildMap.(Partial.empty |> create) | _ -> let open Lwt.Infix in List.concat [ Location of the BXL builder . [bxl_builder]; Force ` buck ` to opt - out fancy tui logging . ["--console=simple"]; (* Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier. *) ["--config"; "client.id=pyre"]; ["--"]; List.bind target_patterns ~f:(fun source_path -> ["--source"; source_path]); ] |> Raw.V2.bxl ?mode ?isolation_prefix raw >>= fun output -> Lwt.return (parse_bxl_output output) let construct_build_map_with_options ~bxl_builder ~buck_options source_paths = let open Lwt.Infix in Log.info "Building Buck source databases for %d sources..." (List.length source_paths); run_bxl_for_targets ~bxl_builder ~buck_options source_paths >>= fun build_map -> Log.info "Loaded source databases"; Lwt.return build_map let create ?mode ?isolation_prefix ~bxl_builder raw = let buck_options = { BuckOptions.mode; isolation_prefix; raw } in { construct_build_map = construct_build_map_with_options ~bxl_builder ~buck_options } let construct_build_map { construct_build_map; _ } source_paths = construct_build_map source_paths end
null
https://raw.githubusercontent.com/facebook/pyre-check/fa38aa1180d4bb7d1c334c2846aca0ed14e22399/source/buck/interface.ml
ocaml
Force `buck` to hand back structured JSON output instead of plain text. Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier. Build all python-related rules. Certain Python-related rules are exposed as `configured_alias` which cannot be picked up by the preceding query. Don't bother with generated rules. `python_unittest()` sources are separated into a macro-generated library, so make sure we include those. Provide an opt-out label so that rules can avoid type-checking (e.g. some libraries wrap generated sources which are expensive to build and therefore typecheck). Targets need to be quoted since `buck query` can fail with syntax errors if target name contains special characters like `=`. This will get only those owner targets that are beneath our targets or the dependencies of our targets. These attributes are all we need to locate the source and artifact relative paths. Force `buck` to hand back structured JSON output instead of plain text. Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier. This can happen for custom rules. These files are not useful for type checking but create many conflicts when merging different targets. For better error message, try to figure out which target casued the conflict. Unlike [load_and_merge_build_maps], this function assumes build maps are already loaded into memory and just try to merge them synchronously. Its main purpose is to facilitate testing of the [merge_target_and_build_map] function. Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier. Mark the query as coming from `pyre` for `buck`, to make troubleshooting easier.
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) This module implements the logic to call out to buck as needed for classic Pyre daemons . The primary action we take is to build source - db targets , which produces a json map from source paths ( mostly user - controlled source code , but also some buck - built generated code , for example thrift stubs ) to artifact paths . primary action we take is to build source-db targets, which produces a json map from source paths (mostly user-controlled source code, but also some buck-built generated code, for example thrift stubs) to artifact paths. *) open Base exception JsonError of string module BuckOptions = struct type 'raw t = { raw: 'raw; mode: string option; isolation_prefix: string option; } end module BuildResult = struct type t = { build_map: BuildMap.t; targets: Target.t list; } end module V1 = struct module IncompatibleMergeItem = struct type t = { key: string; left_value: string; right_value: string; } [@@deriving sexp, compare] end exception FoundIncompatibleMergeItem of IncompatibleMergeItem.t let resolve_merge_conflict_by_name ~key left_value right_value = if String.equal left_value right_value then left_value else raise (FoundIncompatibleMergeItem { IncompatibleMergeItem.key; left_value; right_value }) module BuckChangedTargetsQueryOutput = struct type t = { source_base_path: string; artifact_base_path: string; artifacts_to_sources: (string * string) list; } [@@deriving sexp, compare] let to_partial_build_map { source_base_path; artifact_base_path; artifacts_to_sources } = let to_build_mapping (artifact, source) = Filename.concat artifact_base_path artifact, Filename.concat source_base_path source in match BuildMap.Partial.of_alist (List.map artifacts_to_sources ~f:to_build_mapping) with | `Duplicate_key artifact -> let message = Format.sprintf "Overlapping artifact file detected: %s" artifact in Result.Error message | `Ok partial_build_map -> Result.Ok partial_build_map let to_build_map_batch outputs = let rec merge ~sofar = function | [] -> Result.Ok (BuildMap.create sofar) | output :: rest -> ( match to_partial_build_map output with | Result.Error _ as error -> error | Result.Ok next_build_map -> ( try let sofar = BuildMap.Partial.merge sofar next_build_map ~resolve_conflict:resolve_merge_conflict_by_name in merge ~sofar rest with | FoundIncompatibleMergeItem { IncompatibleMergeItem.key; _ } -> let message = Format.sprintf "Overlapping artifact file detected: %s" key in Result.Error message)) in merge ~sofar:BuildMap.Partial.empty outputs end type t = { normalize_targets: string list -> Target.t list Lwt.t; query_owner_targets: targets:Target.t list -> PyrePath.t list -> BuckChangedTargetsQueryOutput.t list Lwt.t; construct_build_map: Target.t list -> BuildResult.t Lwt.t; } let create_for_testing ~normalize_targets ~construct_build_map ~query_owner_targets () = { normalize_targets; construct_build_map; query_owner_targets } let source_database_suffix = "#source-db" let query_buck_for_normalized_targets { BuckOptions.raw; mode; isolation_prefix } target_specifications = match target_specifications with | [] -> Lwt.return "{}" | _ -> List.concat [ ["--json"]; ["--config"; "client.id=pyre"]; [ "kind(\"python_binary|python_library|python_test\", %s)" ^ " + kind(\"python_binary|python_test\", deps(kind(configured_alias, %s), 1))" ^ " - attrfilter(labels, generated, %s)" ^ " + attrfilter(labels, unittest-library, %s)" " - attrfilter(labels, no_pyre, %s)"; ]; target_specifications; ] |> Raw.V1.query ?mode ?isolation_prefix raw let query_buck_for_changed_targets ~targets { BuckOptions.raw; mode; isolation_prefix } source_paths = match targets with | [] -> Lwt.return "{}" | targets -> ( match source_paths with | [] -> Lwt.return "{}" | source_paths -> let target_string = let quote_string value = Format.sprintf "\"%s\"" value in let quote_target target = Target.show target |> quote_string in List.map targets ~f:quote_target |> String.concat ~sep:" " in List.concat [ ["--json"]; ["--config"; "client.id=pyre"]; [ Format.sprintf "owner(%%s) ^ deps(set(%s))" target_string; ]; List.map source_paths ~f:PyrePath.show; ["--output-attributes"; "srcs"; "buck.base_path"; "buck.base_module"; "base_module"]; ] |> Raw.V1.query ?mode ?isolation_prefix raw) let run_buck_build_for_targets { BuckOptions.raw; mode; isolation_prefix } targets = match targets with | [] -> Lwt.return "{}" | _ -> List.concat [ ["--show-full-json-output"]; ["--config"; "client.id=pyre"]; List.map targets ~f:(fun target -> Format.sprintf "%s%s" (Target.show target) source_database_suffix); ] |> Raw.V1.build ?mode ?isolation_prefix raw let parse_buck_normalized_targets_query_output query_output = let open Yojson.Safe in try from_string ~fname:"buck query output" query_output |> Util.to_assoc |> List.map ~f:(fun (_, targets_json) -> Util.to_list targets_json |> List.map ~f:Util.to_string) |> List.concat_no_order |> List.dedup_and_sort ~compare:String.compare with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_buck_changed_targets_query_output query_output = let open Yojson.Safe in try let parse_target_json target_json = let source_base_path = Util.member "buck.base_path" target_json |> Util.to_string in let artifact_base_path = match Util.member "buck.base_module" target_json with | `String base_module -> String.tr ~target:'.' ~replacement:'/' base_module | _ -> source_base_path in let artifact_base_path = match Util.member "base_module" target_json with | `String base_module -> String.tr ~target:'.' ~replacement:'/' base_module | _ -> artifact_base_path in let artifacts_to_sources = match Util.member "srcs" target_json with | `Assoc targets_to_sources -> List.map targets_to_sources ~f:(fun (target, source_json) -> target, Util.to_string source_json) |> List.filter ~f:(function | _, source when String.is_prefix ~prefix:"//" source -> false | _ -> true) | _ -> [] in { BuckChangedTargetsQueryOutput.source_base_path; artifact_base_path; artifacts_to_sources } in from_string ~fname:"buck changed paths query output" query_output |> Util.to_assoc |> List.map ~f:(fun (_, target_json) -> parse_target_json target_json) with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_buck_build_output query_output = let open Yojson.Safe in try from_string ~fname:"buck build output" query_output |> Util.to_assoc |> List.map ~f:(fun (target, path_json) -> target, Util.to_string path_json) with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let load_partial_build_map_from_json json = let filter_mapping ~key ~data:_ = match key with | "__manifest__.py" | "__test_main__.py" | "__test_modules__.py" -> false | _ -> true in BuildMap.Partial.of_json_exn_ignoring_duplicates json |> BuildMap.Partial.filter ~f:filter_mapping let load_partial_build_map path = let open Lwt.Infix in let path = PyrePath.absolute path in Lwt_io.(with_file ~mode:Input path read) >>= fun content -> try Yojson.Safe.from_string ~fname:path content |> load_partial_build_map_from_json |> Lwt.return with | Yojson.Safe.Util.Type_error (message, _) | Yojson.Safe.Util.Undefined (message, _) -> raise (JsonError message) | Yojson.Json_error message -> raise (JsonError message) let normalize_targets_with_options buck_options target_specifications = let open Lwt.Infix in Log.info "Collecting buck targets to build..."; query_buck_for_normalized_targets buck_options target_specifications >>= fun query_output -> let targets = parse_buck_normalized_targets_query_output query_output |> List.map ~f:Target.of_string in Log.info "Collected %d targets" (List.length targets); Lwt.return targets let query_owner_targets_with_options buck_options ~targets changed_paths = let open Lwt.Infix in Log.info "Running `buck query`..."; query_buck_for_changed_targets ~targets buck_options changed_paths >>= fun query_output -> Lwt.return (parse_buck_changed_targets_query_output query_output) Run ` buck build ` on the given target with the ` # source - db ` flavor . This will make ` buck ` construct its link tree and for each target , dump a source - db JSON file containing how files in the link tree corresponds to the final Python artifacts . Return a list containing the input targets as well as the corresponding location of the source - db JSON file . Note that targets in the returned list is not guaranteed to be in the same order as the input list . May raise [ . Raw . BuckError ] when ` buck ` invocation fails , or [ . Builder . JsonError ] when ` buck ` itself succeeds but its output can not be parsed . construct its link tree and for each target, dump a source-db JSON file containing how files in the link tree corresponds to the final Python artifacts. Return a list containing the input targets as well as the corresponding location of the source-db JSON file. Note that targets in the returned list is not guaranteed to be in the same order as the input list. May raise [Buck.Raw.BuckError] when `buck` invocation fails, or [Buck.Builder.JsonError] when `buck` itself succeeds but its output cannot be parsed. *) let build_source_databases buck_options targets = let open Lwt.Infix in Log.info "Building Buck source databases..."; run_buck_build_for_targets buck_options targets >>= fun build_output -> let source_database_suffix_length = String.length source_database_suffix in parse_buck_build_output build_output |> List.map ~f:(fun (target, path) -> ( String.drop_suffix target source_database_suffix_length |> Target.of_string, PyrePath.create_absolute path )) |> Lwt.return let merge_target_and_build_map (target_and_build_maps_sofar, build_map_sofar) (next_target, next_build_map) = let open BuildMap.Partial in try let merged_build_map = merge build_map_sofar next_build_map ~resolve_conflict:resolve_merge_conflict_by_name in (next_target, next_build_map) :: target_and_build_maps_sofar, merged_build_map with | FoundIncompatibleMergeItem { IncompatibleMergeItem.key; left_value; right_value } -> Log.warning "Cannot include target for type checking: %s" (Target.show next_target); let conflicting_target = let match_target ~key (target, build_map) = if contains ~key build_map then Some target else None in List.find_map target_and_build_maps_sofar ~f:(match_target ~key) in Log.info "... file `%s` has already been mapped to `%s`%s but the target maps it to `%s` instead. " key left_value (Option.value_map conflicting_target ~default:"" ~f:(Format.sprintf " by `%s`")) right_value; target_and_build_maps_sofar, build_map_sofar let load_and_merge_build_maps target_and_source_database_paths = let open Lwt.Infix in let number_of_targets_to_load = List.length target_and_source_database_paths in Log.info "Loading source databases for %d targets..." number_of_targets_to_load; let rec fold ~sofar = function | [] -> Lwt.return sofar | (next_target, next_build_map_path) :: rest -> load_partial_build_map next_build_map_path >>= fun next_build_map -> let sofar = merge_target_and_build_map sofar (next_target, next_build_map) in fold ~sofar rest in fold target_and_source_database_paths ~sofar:([], BuildMap.Partial.empty) >>= fun (reversed_target_and_build_maps, merged_build_map) -> let targets = List.rev_map reversed_target_and_build_maps ~f:fst in if List.length targets < number_of_targets_to_load then Log.warning "One or more targets get dropped by Pyre due to potential conflicts. For more details, see \ -target-conflict"; Lwt.return { BuildResult.targets; build_map = BuildMap.create merged_build_map } let merge_build_maps target_and_build_maps = let reversed_target_and_build_maps, merged_build_map = List.fold target_and_build_maps ~init:([], BuildMap.Partial.empty) ~f:merge_target_and_build_map in let targets = List.rev_map reversed_target_and_build_maps ~f:fst in targets, BuildMap.create merged_build_map let load_and_merge_source_databases target_and_source_database_paths = Make sure the targets are in a determinstic order . This is important to make the merging process deterministic later . Note that our dependency on the ordering of the target also implies that the loading process is non - parallelizable . process deterministic later. Note that our dependency on the ordering of the target also implies that the loading process is non-parallelizable. *) List.sort target_and_source_database_paths ~compare:(fun (left_target, _) (right_target, _) -> Target.compare left_target right_target) |> load_and_merge_build_maps let construct_build_map_with_options buck_options normalized_targets = let open Lwt.Infix in build_source_databases buck_options normalized_targets >>= fun target_and_source_database_paths -> load_and_merge_source_databases target_and_source_database_paths let create ?mode ?isolation_prefix raw = let buck_options = { BuckOptions.mode; isolation_prefix; raw } in { normalize_targets = normalize_targets_with_options buck_options; query_owner_targets = query_owner_targets_with_options buck_options; construct_build_map = construct_build_map_with_options buck_options; } let normalize_targets { normalize_targets; _ } target_specifications = normalize_targets target_specifications let query_owner_targets { query_owner_targets; _ } ~targets paths = query_owner_targets ~targets paths let construct_build_map { construct_build_map; _ } normalized_targets = construct_build_map normalized_targets end module V2 = struct type t = { construct_build_map: string list -> BuildMap.t Lwt.t } let create_for_testing ~construct_build_map () = { construct_build_map } let build_map_key = "build_map" let built_targets_count_key = "built_targets_count" let dropped_targets_key = "dropped_targets" module BuckBxlBuilderOutput = struct module Conflict = struct type t = { conflict_with: string; artifact_path: string; preserved_source_path: string; dropped_source_path: string; } [@@deriving sexp, compare, of_yojson { strict = false }] end type t = { build_map: BuildMap.t; target_count: int; conflicts: (Target.t * Conflict.t) list; } end let parse_merged_sourcedb merged_sourcedb : BuckBxlBuilderOutput.t = let open Yojson.Safe in try let build_map = Util.member build_map_key merged_sourcedb |> BuildMap.Partial.of_json_exn_ignoring_duplicates_no_dependency |> BuildMap.create in let target_count = Util.member built_targets_count_key merged_sourcedb |> Util.to_int in let conflicts = let conflict_of_yojson json = match BuckBxlBuilderOutput.Conflict.of_yojson json with | Result.Ok conflict -> conflict | Result.Error message -> let message = Format.sprintf "Cannot parse conflict item: %s" message in raise (JsonError message) in Util.member dropped_targets_key merged_sourcedb |> Util.to_assoc |> List.map ~f:(fun (target, conflict_json) -> Target.of_string target, conflict_of_yojson conflict_json) in { BuckBxlBuilderOutput.build_map; target_count; conflicts } with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_bxl_output bxl_output = let open Yojson.Safe in try let merged_sourcedb_path = from_string ~fname:"buck bxl output" bxl_output |> Util.member "db" |> Util.to_string in from_file merged_sourcedb_path |> parse_merged_sourcedb with | Yojson.Json_error message | Util.Type_error (message, _) | Sys_error message -> raise (JsonError message) let run_bxl_for_targets ~bxl_builder ~buck_options:{ BuckOptions.raw; mode; isolation_prefix; _ } target_patterns = match target_patterns with | [] -> `Assoc [ build_map_key, `Assoc []; built_targets_count_key, `Assoc []; dropped_targets_key, `Assoc []; ] |> Yojson.Safe.to_string |> Lwt.return | _ -> List.concat [ Location of the BXL builder . [bxl_builder]; Force ` buck ` to opt - out fancy tui logging . ["--console=simple"]; ["--config"; "client.id=pyre"]; ["--"]; List.bind target_patterns ~f:(fun target -> ["--target"; Format.sprintf "%s" target]); ] |> Raw.V2.bxl ?mode ?isolation_prefix raw let warn_on_conflict ~target { BuckBxlBuilderOutput.Conflict.conflict_with; artifact_path; preserved_source_path; dropped_source_path; } = Log.warning "Cannot include target for type checking: %s" (Target.show target); Log.info "... file `%s` has already been mapped to `%s` by `%s` but the target maps it to `%s` \ instead. " artifact_path preserved_source_path (Target.show conflict_with) dropped_source_path; () let warn_on_conflicts = function | [] -> () | conflicts -> List.iter conflicts ~f:(fun (target, conflict) -> warn_on_conflict ~target conflict); Log.warning "One or more targets get dropped by Pyre due to potential conflicts. For more details, \ see -target-conflict" let construct_build_map_with_options ~bxl_builder ~buck_options target_patterns = let open Lwt.Infix in Log.info "Building Buck source databases..."; run_bxl_for_targets ~bxl_builder ~buck_options target_patterns >>= fun output -> let { BuckBxlBuilderOutput.build_map; target_count; conflicts } = parse_bxl_output output in warn_on_conflicts conflicts; Log.info "Loaded source databases for %d targets" target_count; Lwt.return build_map let create ?mode ?isolation_prefix ?bxl_builder raw = let buck_options = { BuckOptions.mode; isolation_prefix; raw } in match bxl_builder with | None -> failwith "BXL path is not set but it is required when using Buck2" | Some bxl_builder -> { construct_build_map = construct_build_map_with_options ~bxl_builder ~buck_options } let construct_build_map { construct_build_map; _ } target_patterns = construct_build_map target_patterns end module Lazy = struct type t = { construct_build_map: string list -> BuildMap.t Lwt.t } let create_for_testing ~construct_build_map () = { construct_build_map } let parse_merged_sourcedb merged_sourcedb : BuildMap.t = let open Yojson.Safe in try BuildMap.Partial.of_json_exn_ignoring_duplicates_no_dependency merged_sourcedb |> BuildMap.create with | Yojson.Json_error message | Util.Type_error (message, _) -> raise (JsonError message) let parse_bxl_output bxl_output = let open Yojson.Safe in try let merged_sourcedb_path = from_string ~fname:"buck bxl output" bxl_output |> Util.member "db" |> Util.to_string in from_file merged_sourcedb_path |> parse_merged_sourcedb with | Yojson.Json_error message | Util.Type_error (message, _) | Sys_error message -> raise (JsonError message) let run_bxl_for_targets ~bxl_builder ~buck_options:{ BuckOptions.raw; mode; isolation_prefix; _ } target_patterns = match target_patterns with | [] -> Lwt.return BuildMap.(Partial.empty |> create) | _ -> let open Lwt.Infix in List.concat [ Location of the BXL builder . [bxl_builder]; Force ` buck ` to opt - out fancy tui logging . ["--console=simple"]; ["--config"; "client.id=pyre"]; ["--"]; List.bind target_patterns ~f:(fun source_path -> ["--source"; source_path]); ] |> Raw.V2.bxl ?mode ?isolation_prefix raw >>= fun output -> Lwt.return (parse_bxl_output output) let construct_build_map_with_options ~bxl_builder ~buck_options source_paths = let open Lwt.Infix in Log.info "Building Buck source databases for %d sources..." (List.length source_paths); run_bxl_for_targets ~bxl_builder ~buck_options source_paths >>= fun build_map -> Log.info "Loaded source databases"; Lwt.return build_map let create ?mode ?isolation_prefix ~bxl_builder raw = let buck_options = { BuckOptions.mode; isolation_prefix; raw } in { construct_build_map = construct_build_map_with_options ~bxl_builder ~buck_options } let construct_build_map { construct_build_map; _ } source_paths = construct_build_map source_paths end
e929586906e0e73762459c5380cbd185258245173e9cb627e48ef6e533e81ccd
BitGameEN/bitgamex
mod_kernel.erl
%%%------------------------------------ %%% @Module : mod_kernel %%% @Description: 核心服务 %%%------------------------------------ -module(mod_kernel). -behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("common.hrl"). -include("record.hrl"). start_link() -> gen_server:start_link({local,?MODULE}, ?MODULE, [], []). init([]) -> process_flag(trap_exit, true), %%初始ets表 util:launch_log("====> \tinit_ets...~n", []), ok = init_ets(), %%初始dets表 util:launch_log("====> \tinit_dets...~n", []), ok = init_dets(), {ok, 1}. handle_cast(_R, Status) -> {noreply, Status}. handle_call(_R, _FROM, Status) -> {reply, ok, Status}. handle_info(_Reason, Status) -> {noreply, Status}. terminate(_Reason, Status) -> close_dets(), {ok, Status}. code_change(_OldVsn, Status, _Extra) -> {ok, Status}. %% ================== 私有函数 ================= 初始ETS表 init_ets() -> run_role:init(), run_role_gold:init(), run_role_gold_to_draw:init(), ok. 初始DETS表 init_dets() -> 开辟此表完全是为了简单方便,脱离数据库存取的繁琐,主要用于存储全局key - value形式的存盘数据,既然是存盘的,就不能清空 SvrId = mod_disperse:server_id(), GlobalRunFile = "global_run_data_"++integer_to_list(SvrId), dets:open_file(?DETS_GLOBAL_RUN_DATA, [{type, set}, {file, GlobalRunFile}]), ok. %%关闭DETS表 close_dets() -> SvrId = mod_disperse:server_id(), dets:close(?DETS_GLOBAL_RUN_DATA), ok.
null
https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/mod/mod_kernel.erl
erlang
------------------------------------ @Module : mod_kernel @Description: 核心服务 ------------------------------------ 初始ets表 初始dets表 ================== 私有函数 ================= 关闭DETS表
-module(mod_kernel). -behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("common.hrl"). -include("record.hrl"). start_link() -> gen_server:start_link({local,?MODULE}, ?MODULE, [], []). init([]) -> process_flag(trap_exit, true), util:launch_log("====> \tinit_ets...~n", []), ok = init_ets(), util:launch_log("====> \tinit_dets...~n", []), ok = init_dets(), {ok, 1}. handle_cast(_R, Status) -> {noreply, Status}. handle_call(_R, _FROM, Status) -> {reply, ok, Status}. handle_info(_Reason, Status) -> {noreply, Status}. terminate(_Reason, Status) -> close_dets(), {ok, Status}. code_change(_OldVsn, Status, _Extra) -> {ok, Status}. 初始ETS表 init_ets() -> run_role:init(), run_role_gold:init(), run_role_gold_to_draw:init(), ok. 初始DETS表 init_dets() -> 开辟此表完全是为了简单方便,脱离数据库存取的繁琐,主要用于存储全局key - value形式的存盘数据,既然是存盘的,就不能清空 SvrId = mod_disperse:server_id(), GlobalRunFile = "global_run_data_"++integer_to_list(SvrId), dets:open_file(?DETS_GLOBAL_RUN_DATA, [{type, set}, {file, GlobalRunFile}]), ok. close_dets() -> SvrId = mod_disperse:server_id(), dets:close(?DETS_GLOBAL_RUN_DATA), ok.
2e62c44338585a514ef705403e8f82d351904404420c6166b190f424fc0c5d62
sydow/ireal
Auxiliary.hs
module Data.Number.IReal.Auxiliary where import GHC.Float infix 1 `atDecimals` -- Auxiliary functions and constants -------------------------------------------- -- | Base 2 logarithm of argument, rounded downwards. lg2 :: Integer -> Int lg2 = GHC.Float.integerLogBase 2 -- | Converts precisions from decimal to binary. dec2bits :: Int -> Int dec2bits d = ceiling (fromIntegral d * logBase 2 10 :: Double) -- | Operator allowing function expecting binary precision to be applied to decimal ditto. atDecimals :: (Int -> a) -> Int -> a atDecimals f = f . dec2bits
null
https://raw.githubusercontent.com/sydow/ireal/c06438544c711169baac7960540202379f9294b1/Data/Number/IReal/Auxiliary.hs
haskell
Auxiliary functions and constants -------------------------------------------- | Base 2 logarithm of argument, rounded downwards. | Converts precisions from decimal to binary. | Operator allowing function expecting binary precision to be applied to decimal ditto.
module Data.Number.IReal.Auxiliary where import GHC.Float infix 1 `atDecimals` lg2 :: Integer -> Int lg2 = GHC.Float.integerLogBase 2 dec2bits :: Int -> Int dec2bits d = ceiling (fromIntegral d * logBase 2 10 :: Double) atDecimals :: (Int -> a) -> Int -> a atDecimals f = f . dec2bits
f7870dfa759b3ce7c6c22f62bf1b65ca5705c0fd615146edd5adb106b4dc7008
ocaml/dune
log.ml
open Stdune module Console = Dune_console module File = struct type t = | Default | No_log_file | This of Path.t | Out_channel of out_channel end type real = { oc : out_channel option } let t = Fdecl.create Dyn.opaque let verbose = ref false let init ?(file = File.Default) () = let oc = match file with | No_log_file -> None | Out_channel s -> Some s | This path -> Path.mkdir_p (Path.parent_exn path); Some (Io.open_out path) | Default -> Path.ensure_build_dir_exists (); Some (Io.open_out (Path.relative Path.build_dir "log")) in Option.iter oc ~f:(fun oc -> Printf.fprintf oc "# %s\n# OCAMLPARAM: %s\n%!" (String.concat (List.map (Array.to_list Sys.argv) ~f:String.quote_for_shell) ~sep:" ") (match Env.get Env.initial "OCAMLPARAM" with | Some s -> Printf.sprintf "%S" s | None -> "unset")); Fdecl.set t (Some { oc }) let init_disabled () = Fdecl.set t None let t () = Fdecl.get t let info_user_message msg = match t () with | None -> () | Some { oc; _ } -> Option.iter oc ~f:(fun oc -> let s = Format.asprintf "%a@?" Pp.to_fmt (User_message.pp msg) in List.iter (String.split_lines s) ~f:(function | "" -> output_string oc "#\n" | s -> Printf.fprintf oc "# %s\n" s); flush oc); if !verbose then Console.print_user_message msg let info paragraphs = info_user_message (User_message.make paragraphs) let command ~command_line ~output ~exit_status = match t () with | None | Some { oc = None; _ } -> () | Some { oc = Some oc; _ } -> Printf.fprintf oc "$ %s\n" (Ansi_color.strip command_line); List.iter (String.split_lines output) ~f:(fun s -> match Ansi_color.strip s with | "" -> output_string oc ">\n" | s -> Printf.fprintf oc "> %s\n" s); (match (exit_status : Unix.process_status) with | WEXITED 0 -> () | WEXITED n -> Printf.fprintf oc "[%d]\n" n | WSIGNALED n -> let name = Signal.of_int n |> Signal.name in Printf.fprintf oc "[got signal %s]\n" name | WSTOPPED _ -> assert false); flush oc
null
https://raw.githubusercontent.com/ocaml/dune/b8fd9dffecfd1a102720ca2ab485e80fcee2cb65/src/dune_util/log.ml
ocaml
open Stdune module Console = Dune_console module File = struct type t = | Default | No_log_file | This of Path.t | Out_channel of out_channel end type real = { oc : out_channel option } let t = Fdecl.create Dyn.opaque let verbose = ref false let init ?(file = File.Default) () = let oc = match file with | No_log_file -> None | Out_channel s -> Some s | This path -> Path.mkdir_p (Path.parent_exn path); Some (Io.open_out path) | Default -> Path.ensure_build_dir_exists (); Some (Io.open_out (Path.relative Path.build_dir "log")) in Option.iter oc ~f:(fun oc -> Printf.fprintf oc "# %s\n# OCAMLPARAM: %s\n%!" (String.concat (List.map (Array.to_list Sys.argv) ~f:String.quote_for_shell) ~sep:" ") (match Env.get Env.initial "OCAMLPARAM" with | Some s -> Printf.sprintf "%S" s | None -> "unset")); Fdecl.set t (Some { oc }) let init_disabled () = Fdecl.set t None let t () = Fdecl.get t let info_user_message msg = match t () with | None -> () | Some { oc; _ } -> Option.iter oc ~f:(fun oc -> let s = Format.asprintf "%a@?" Pp.to_fmt (User_message.pp msg) in List.iter (String.split_lines s) ~f:(function | "" -> output_string oc "#\n" | s -> Printf.fprintf oc "# %s\n" s); flush oc); if !verbose then Console.print_user_message msg let info paragraphs = info_user_message (User_message.make paragraphs) let command ~command_line ~output ~exit_status = match t () with | None | Some { oc = None; _ } -> () | Some { oc = Some oc; _ } -> Printf.fprintf oc "$ %s\n" (Ansi_color.strip command_line); List.iter (String.split_lines output) ~f:(fun s -> match Ansi_color.strip s with | "" -> output_string oc ">\n" | s -> Printf.fprintf oc "> %s\n" s); (match (exit_status : Unix.process_status) with | WEXITED 0 -> () | WEXITED n -> Printf.fprintf oc "[%d]\n" n | WSIGNALED n -> let name = Signal.of_int n |> Signal.name in Printf.fprintf oc "[got signal %s]\n" name | WSTOPPED _ -> assert false); flush oc
c2369e4efb621c462c56a6a91003193f77c2599d8ec5c4fea6280bf838e5ba59
montelibero-org/veche
User.hs
# LANGUAGE BlockArguments # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DisambiguateRecordFields # # LANGUAGE ImportQualifiedPost # {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} module Handler.User (getUserR, putUserR) where import Import import Data.Aeson (Value (Null, String)) import Data.Char (isAscii, isPrint) import Data.Text qualified as Text import Model.User qualified as User import Templates.User (userPage) getUserR :: Handler Html getUserR = userPage newtype UserEditRequest = UserEditRequest{name :: Text} deriving anyclass (FromJSON) deriving stock (Generic) newtype UserEditResponse = UserEditResponse{editError :: Maybe Text} deriving anyclass (ToJSON) deriving stock (Generic) putUserR :: Handler Value putUserR = do -- input UserEditRequest{name = nameInput} <- requireCheckJsonBody let nameFixed = Text.strip nameInput userId <- requireAuthId if | Text.null nameFixed -> User.setName userId Nothing | isValid nameFixed -> User.setName userId $ Just nameFixed | otherwise -> sendResponseStatus status400 $ object ["error" .= String "Name must be ASCII only"] returnJson Null where isValid = Text.all \c -> isAscii c && isPrint c
null
https://raw.githubusercontent.com/montelibero-org/veche/f9104057c940880fd68bbbd5c752f6ca9118ff94/veche-web/src/Handler/User.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # input
# LANGUAGE BlockArguments # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DisambiguateRecordFields # # LANGUAGE ImportQualifiedPost # module Handler.User (getUserR, putUserR) where import Import import Data.Aeson (Value (Null, String)) import Data.Char (isAscii, isPrint) import Data.Text qualified as Text import Model.User qualified as User import Templates.User (userPage) getUserR :: Handler Html getUserR = userPage newtype UserEditRequest = UserEditRequest{name :: Text} deriving anyclass (FromJSON) deriving stock (Generic) newtype UserEditResponse = UserEditResponse{editError :: Maybe Text} deriving anyclass (ToJSON) deriving stock (Generic) putUserR :: Handler Value putUserR = do UserEditRequest{name = nameInput} <- requireCheckJsonBody let nameFixed = Text.strip nameInput userId <- requireAuthId if | Text.null nameFixed -> User.setName userId Nothing | isValid nameFixed -> User.setName userId $ Just nameFixed | otherwise -> sendResponseStatus status400 $ object ["error" .= String "Name must be ASCII only"] returnJson Null where isValid = Text.all \c -> isAscii c && isPrint c
155f0960e0695b22f9e3a2c37def5a7bbf4980105e57455fd7b31c175c32bb65
spurious/sagittarius-scheme-mirror
websocket.scm
-*- mode : scheme ; coding : utf-8 ; -*- ;;; ;;; rfc/websocket.scm - RFC 6455 Websocket ;;; Copyright ( c ) 2010 - 2016 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; Websocket client library. Server library may come in (rfc websocket server) ;; but not promised. (library (rfc websocket) (export ;; User level APIs make-websocket websocket? websocket-reconnectable? websocket-open websocket-close websocket-send websocket-ping websocket-on-text-message websocket-on-binary-message websocket-on-open websocket-on-error websocket-on-close ;; Low APIs make-websocket-connection websocket-connection? websocket-connection-handshake! websocket-connection-close! websocket-connection-closed? websocket-connection-pong-queue websocket-send-text websocket-send-binary websocket-send-close websocket-send-ping websocket-send-pong websocket-receive websocket-receive-fragments websocket-compose-close-status websocket-parse-close-status +websocket-text-frame+ +websocket-binary-frame+ +websocket-close-frame+ +websocket-ping-frame+ +websocket-pong-frame+ ;; conditions websocket-error? websocket-engine-error? websocket-engine-not-found-error? websocket-error-engine websocket-error-reason websocket-closed-error? websocket-error-status websocket-error-message websocket-pong-error? websocket-error-pong-data websocket-scheme-error? websocket-error-scheme websocket-connection-error? websocket-error-host websocket-error-port websocket-close-timeout-error? *websocket-mask-data?* ) (import (rnrs) (srfi :18) (sagittarius control) (rfc websocket conditions) (rfc websocket connection) (rfc websocket messages) (util concurrent shared-queue)) (define-record-type websocket (fields protocols extensions connection dispatchers (mutable thread) mutex) (protocol (lambda (p) (lambda (uri :key (protocols '()) (extensions '()) (engine 'http)) (p protocols extensions (make-websocket-connection uri engine) (make-eq-hashtable) #f (make-mutex)))))) (define (websocket-reconnectable? websocket) (websocket-reconnectable-connection? (websocket-connection websocket))) (define-condition-type &websocket-pong &websocket make-websocket-pong-error websocket-pong-error? (pong-data websocket-error-pong-data)) (define-condition-type &websocket-close-timeout &websocket make-websocket-close-timeout-error websocket-close-timeout-error?) (define (invoke-event websocket event . opt) (define dispatchers (websocket-dispatchers websocket)) (cond ((hashtable-ref dispatchers event #f) => (lambda (handler) (apply handler websocket opt)))) websocket) ;; if it's &websocket, then let on-error handle it. ;; others just go though. (define-syntax with-error-handling (syntax-rules () ((_ websocket exprs ...) ;; engine error can not be recoverable so re-raise. (guard (e ((or (websocket-engine-error? e) (websocket-connection-error? e)) (invoke-event websocket 'error e) (raise e)) ((websocket-error? e) (invoke-event websocket 'error e) websocket)) exprs ...)))) (define-syntax define-websocket (syntax-rules () ((_ (name websocket . args) exprs ...) (define (name websocket . args) (with-error-handling websocket exprs ...))))) (define (start-dispatch-thread websocket) (define (dispatch) (define conn (websocket-connection websocket)) (define finish? #f) (let restart () (guard (e ((websocket-closed-error? e) (raise e)) ((websocket-error? e) (invoke-event websocket 'error e))) (let loop () (let-values (((opcode data) (websocket-receive conn :push-pong? #t))) (if (eqv? opcode +websocket-close-frame+) (set! finish? #t) (begin (cond ((eqv? opcode +websocket-text-frame+) (invoke-event websocket 'text data)) ((eqv? opcode +websocket-binary-frame+) (invoke-event websocket 'binary data)) (else ;; TODO should we raise an error? (websocket-send-close conn (websocket-compose-close-status 1002) #f))) (loop)))))) (unless finish? (restart)))) (let ((t (make-thread dispatch))) (websocket-thread-set! websocket t) (thread-start! t))) Opens given websocket iff it 's not opened yet (define-websocket (websocket-open websocket . headers) (define conn (websocket-connection websocket)) (if (websocket-connection-closed? conn) (begin (apply websocket-connection-handshake! conn (websocket-protocols websocket) (websocket-extensions websocket) headers) (start-dispatch-thread websocket) (invoke-event websocket 'open)) websocket)) ;; Closes given websocket iff it's open (define-websocket (websocket-close websocket :key (status #f) (message "") (timeout #f)) (define conn (websocket-connection websocket)) (if (websocket-connection-closed? conn) websocket (let ((data (if status (websocket-compose-close-status status message) #vu8()))) ;; we don't wait, let dispatch thread handle it (websocket-send-close conn data #f) (guard (e ((uncaught-exception? e) ;; make sure it's closed... should we? (websocket-connection-close! conn) (websocket-thread-set! websocket #f) (raise (uncaught-exception-reason e))) ((join-timeout-exception? e) close it first , then terminate thread (websocket-connection-close! conn) ;; sorry then die (thread-terminate! (websocket-thread websocket)) (websocket-thread-set! websocket #f) (raise (condition (make-websocket-close-timeout-error) (make-who-condition 'websocket-close) (make-message-condition "timeout!"))))) (thread-join! (websocket-thread websocket) timeout) (websocket-thread-set! websocket #f) ;; close connection. NB: dispatcher thread doesn't close (websocket-connection-close! conn)) (invoke-event websocket 'close)))) (define-websocket (websocket-send websocket data . opt) (define conn (websocket-connection websocket)) (define mutex (websocket-mutex websocket)) (mutex-lock! mutex) (unwind-protect (cond ((string? data) (apply websocket-send-text conn data opt)) ((bytevector? data) (apply websocket-send-binary conn data opt)) (else (assertion-violation 'websocket-send "invalid data" data))) (mutex-unlock! mutex)) websocket) (define-websocket (websocket-ping websocket data . opt) (define mutex (websocket-mutex websocket)) (define conn (websocket-connection websocket)) (mutex-lock! mutex) (unwind-protect (begin (websocket-send-ping conn data) (let ((r (apply shared-queue-get! (websocket-connection-pong-queue conn) opt))) ;; Should we raise an exception? ;; if so, what kind of exception? &websocket would be caught (unless (and (bytevector? r) (bytevector=? data r)) (raise (condition (make-websocket-pong-error r) (make-who-condition 'websocket-ping) (make-message-condition "unknown pong")))))) (mutex-unlock! mutex)) websocket) (define (set-event-handler websocket event handler) (define dispatchers (websocket-dispatchers websocket)) (hashtable-set! dispatchers event handler) websocket) (define (websocket-on-text-message websocket handler) (set-event-handler websocket 'text handler)) (define (websocket-on-binary-message websocket handler) (set-event-handler websocket 'binary handler)) (define (websocket-on-open websocket handler) (set-event-handler websocket 'open handler)) (define (websocket-on-error websocket handler) (set-event-handler websocket 'error handler)) (define (websocket-on-close websocket handler) (set-event-handler websocket 'close handler)) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/rfc/websocket.scm
scheme
coding : utf-8 ; -*- rfc/websocket.scm - RFC 6455 Websocket Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Websocket client library. Server library may come in (rfc websocket server) but not promised. User level APIs Low APIs conditions if it's &websocket, then let on-error handle it. others just go though. engine error can not be recoverable so re-raise. TODO should we raise an error? Closes given websocket iff it's open we don't wait, let dispatch thread handle it make sure it's closed... should we? sorry then die close connection. NB: dispatcher thread doesn't close Should we raise an exception? if so, what kind of exception? &websocket would be caught
Copyright ( c ) 2010 - 2016 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING (library (rfc websocket) make-websocket websocket? websocket-reconnectable? websocket-open websocket-close websocket-send websocket-ping websocket-on-text-message websocket-on-binary-message websocket-on-open websocket-on-error websocket-on-close make-websocket-connection websocket-connection? websocket-connection-handshake! websocket-connection-close! websocket-connection-closed? websocket-connection-pong-queue websocket-send-text websocket-send-binary websocket-send-close websocket-send-ping websocket-send-pong websocket-receive websocket-receive-fragments websocket-compose-close-status websocket-parse-close-status +websocket-text-frame+ +websocket-binary-frame+ +websocket-close-frame+ +websocket-ping-frame+ +websocket-pong-frame+ websocket-error? websocket-engine-error? websocket-engine-not-found-error? websocket-error-engine websocket-error-reason websocket-closed-error? websocket-error-status websocket-error-message websocket-pong-error? websocket-error-pong-data websocket-scheme-error? websocket-error-scheme websocket-connection-error? websocket-error-host websocket-error-port websocket-close-timeout-error? *websocket-mask-data?* ) (import (rnrs) (srfi :18) (sagittarius control) (rfc websocket conditions) (rfc websocket connection) (rfc websocket messages) (util concurrent shared-queue)) (define-record-type websocket (fields protocols extensions connection dispatchers (mutable thread) mutex) (protocol (lambda (p) (lambda (uri :key (protocols '()) (extensions '()) (engine 'http)) (p protocols extensions (make-websocket-connection uri engine) (make-eq-hashtable) #f (make-mutex)))))) (define (websocket-reconnectable? websocket) (websocket-reconnectable-connection? (websocket-connection websocket))) (define-condition-type &websocket-pong &websocket make-websocket-pong-error websocket-pong-error? (pong-data websocket-error-pong-data)) (define-condition-type &websocket-close-timeout &websocket make-websocket-close-timeout-error websocket-close-timeout-error?) (define (invoke-event websocket event . opt) (define dispatchers (websocket-dispatchers websocket)) (cond ((hashtable-ref dispatchers event #f) => (lambda (handler) (apply handler websocket opt)))) websocket) (define-syntax with-error-handling (syntax-rules () ((_ websocket exprs ...) (guard (e ((or (websocket-engine-error? e) (websocket-connection-error? e)) (invoke-event websocket 'error e) (raise e)) ((websocket-error? e) (invoke-event websocket 'error e) websocket)) exprs ...)))) (define-syntax define-websocket (syntax-rules () ((_ (name websocket . args) exprs ...) (define (name websocket . args) (with-error-handling websocket exprs ...))))) (define (start-dispatch-thread websocket) (define (dispatch) (define conn (websocket-connection websocket)) (define finish? #f) (let restart () (guard (e ((websocket-closed-error? e) (raise e)) ((websocket-error? e) (invoke-event websocket 'error e))) (let loop () (let-values (((opcode data) (websocket-receive conn :push-pong? #t))) (if (eqv? opcode +websocket-close-frame+) (set! finish? #t) (begin (cond ((eqv? opcode +websocket-text-frame+) (invoke-event websocket 'text data)) ((eqv? opcode +websocket-binary-frame+) (invoke-event websocket 'binary data)) (else (websocket-send-close conn (websocket-compose-close-status 1002) #f))) (loop)))))) (unless finish? (restart)))) (let ((t (make-thread dispatch))) (websocket-thread-set! websocket t) (thread-start! t))) Opens given websocket iff it 's not opened yet (define-websocket (websocket-open websocket . headers) (define conn (websocket-connection websocket)) (if (websocket-connection-closed? conn) (begin (apply websocket-connection-handshake! conn (websocket-protocols websocket) (websocket-extensions websocket) headers) (start-dispatch-thread websocket) (invoke-event websocket 'open)) websocket)) (define-websocket (websocket-close websocket :key (status #f) (message "") (timeout #f)) (define conn (websocket-connection websocket)) (if (websocket-connection-closed? conn) websocket (let ((data (if status (websocket-compose-close-status status message) #vu8()))) (websocket-send-close conn data #f) (guard (e ((uncaught-exception? e) (websocket-connection-close! conn) (websocket-thread-set! websocket #f) (raise (uncaught-exception-reason e))) ((join-timeout-exception? e) close it first , then terminate thread (websocket-connection-close! conn) (thread-terminate! (websocket-thread websocket)) (websocket-thread-set! websocket #f) (raise (condition (make-websocket-close-timeout-error) (make-who-condition 'websocket-close) (make-message-condition "timeout!"))))) (thread-join! (websocket-thread websocket) timeout) (websocket-thread-set! websocket #f) (websocket-connection-close! conn)) (invoke-event websocket 'close)))) (define-websocket (websocket-send websocket data . opt) (define conn (websocket-connection websocket)) (define mutex (websocket-mutex websocket)) (mutex-lock! mutex) (unwind-protect (cond ((string? data) (apply websocket-send-text conn data opt)) ((bytevector? data) (apply websocket-send-binary conn data opt)) (else (assertion-violation 'websocket-send "invalid data" data))) (mutex-unlock! mutex)) websocket) (define-websocket (websocket-ping websocket data . opt) (define mutex (websocket-mutex websocket)) (define conn (websocket-connection websocket)) (mutex-lock! mutex) (unwind-protect (begin (websocket-send-ping conn data) (let ((r (apply shared-queue-get! (websocket-connection-pong-queue conn) opt))) (unless (and (bytevector? r) (bytevector=? data r)) (raise (condition (make-websocket-pong-error r) (make-who-condition 'websocket-ping) (make-message-condition "unknown pong")))))) (mutex-unlock! mutex)) websocket) (define (set-event-handler websocket event handler) (define dispatchers (websocket-dispatchers websocket)) (hashtable-set! dispatchers event handler) websocket) (define (websocket-on-text-message websocket handler) (set-event-handler websocket 'text handler)) (define (websocket-on-binary-message websocket handler) (set-event-handler websocket 'binary handler)) (define (websocket-on-open websocket handler) (set-event-handler websocket 'open handler)) (define (websocket-on-error websocket handler) (set-event-handler websocket 'error handler)) (define (websocket-on-close websocket handler) (set-event-handler websocket 'close handler)) )
335c96835e5df9b44754291b2b571448dc6f11440ae694c5ca5363ffd83a8f13
OCamlPro/scilint
tyxml_js_manip.ml
let doc = Dom_html.document let window = Dom_html.window let loc = Js.Unsafe.variable "location" let alert s = window##alert (Js.string s) let confirm s = Js.to_bool (window##confirm (Js.string s)) let js_log obj = Firebug.console##log (obj) let js_debug obj = Firebug.console##debug (obj) let js_error obj = Firebug.console##error (obj) let log fmt = Format.ksprintf (fun s -> Firebug.console##log (Js.string s)) fmt let debug fmt = Format.ksprintf (fun s -> Firebug.console##debug (Js.string s)) fmt let error fmt = Format.ksprintf (fun s -> Firebug.console##error (Js.string s)) fmt let is_hidden div = div##style##display = Js.string "none" let hide div = div##style##display <- Js.string "none" let display div = div##style##display <- Js.string "block" let reload () = window##location##reload () module Manip = struct let option_map f = function None -> None | Some x -> Some (f x) exception Error of string let manip_error fmt = Format.ksprintf (fun s -> debug "%s" s; raise (Error s)) fmt open Tyxml_js let id x = x let get_node = Html5.toelt let get_elt name elt : Dom_html.element Js.t = Js.Opt.case (Dom_html.CoerceTo.element (Html5.toelt elt)) (fun () -> manip_error "Cannot call %s on a node which is not an element" name) id let setInnerHtml elt s = let elt = get_elt "setInnerHtml" elt in elt##innerHTML <- Js.string s let raw_appendChild ?before node elt2 = match before with | None -> ignore(node##appendChild(get_node elt2)) | Some elt3 -> let node3 = get_node elt3 in ignore(node##insertBefore(get_node elt2, Js.some node3)) let raw_appendChildren ?before node elts = match before with | None -> List.iter (fun elt2 -> ignore(node##appendChild(get_node elt2))) elts | Some elt3 -> let node3 = get_node elt3 in List.iter (fun elt2 -> ignore(node##insertBefore(get_node elt2, Js.some node3))) elts let raw_removeChild node1 elt2 = let node2 = get_node elt2 in ignore(node1##removeChild(node2)) let raw_replaceChild node1 elt2 elt3 = let node2 = get_node elt2 in ignore(node1##replaceChild(node2, get_node elt3)) let raw_removeChildren node = let childrens = Dom.list_of_nodeList (node##childNodes) in List.iter (fun c -> ignore(node##removeChild(c))) childrens let raw_replaceChildren node elts = raw_removeChildren node; List.iter (fun elt -> ignore(node##appendChild(get_node elt))) elts let nth elt n = let node = get_node elt in let res = Js.Opt.bind (node##childNodes##item (n)) (fun node -> Js.Opt.map (Dom.CoerceTo.element node) (fun node -> Of_dom.of_element (Dom_html.element node) ) ) in Js.Opt.to_option res let childLength elt = let node = get_node elt in node##childNodes##length let appendChild ?before elt1 elt2 = let node = get_node elt1 in raw_appendChild ?before node elt2 let appendChildren ?before elt1 elts = let node = get_node elt1 in raw_appendChildren ?before node elts let removeChild elt1 elt2 = let node1 = get_node elt1 in raw_removeChild node1 elt2 let removeSelf elt = let node = get_node elt in let res = Js.Opt.bind (node##parentNode) (fun node -> Js.Opt.map (Dom.CoerceTo.element node) (fun node -> Of_dom.of_element (Dom_html.element node) ) ) in Js.Opt.iter res (fun p -> removeChild p elt) let appendChildFirst p c = let before = nth p 0 in appendChild ?before p c let replaceChild elt1 elt2 elt3 = let node1 = get_node elt1 in raw_replaceChild node1 elt2 elt3 let removeChildren elt = let node = get_node elt in raw_removeChildren node let replaceChildren elt elts = let node = get_node elt in raw_replaceChildren node elts let childNodes elt = let node = get_node elt in Dom.list_of_nodeList (node##childNodes) let rec filterElements nodes = match nodes with | [] -> [] | node :: nodes -> let elts = filterElements nodes in Js.Opt.case (Dom.CoerceTo.element node) (fun () -> elts) (fun elt -> elt :: elts) let childElements elt = let node = get_node elt in filterElements (Dom.list_of_nodeList (node##childNodes)) let appendToBody ?before elt2 = let body = (Of_dom.of_body Dom_html.window##document##body) in appendChild ?before body elt2 let get_elt_input name elt : Dom_html.inputElement Js.t = Js.Opt.case (Dom_html.CoerceTo.input (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non 'input' node (%s)" name)) id let get_elt_select name elt : Dom_html.selectElement Js.t = Js.Opt.case (Dom_html.CoerceTo.select (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non 'select' node (%s)" name)) id let get_elt_textarea name elt : Dom_html.textAreaElement Js.t = Js.Opt.case (Dom_html.CoerceTo.textarea (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non element node (%s)" name)) id let get_elt_img name elt : Dom_html.imageElement Js.t = Js.Opt.case (Dom_html.CoerceTo.img (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non element node (%s)" name)) id let scrollIntoView ?(bottom = false) elt = let elt = get_elt "Css.background" elt in elt##scrollIntoView(Js.bool (not bottom)) type disable = < disabled: bool Js.t Js.prop > let get_disable_elt name elt : disable Js.t = if Js.undefined == (Js.Unsafe.coerce @@ Html5.toelt elt)##disabled then manip_error "Cannot call %s on a node without a 'disable' property" name; Js.Unsafe.coerce @@ Html5.toelt elt let disable elt = let elt = get_disable_elt "disable" elt in elt##disabled <- Js._true let enable elt = let elt = get_disable_elt "enable" elt in elt##disabled <- Js._false type value = < value: Js.js_string Js.t Js.prop > let get_value_elt name elt : value Js.t = if Js.undefined == (Js.Unsafe.coerce @@ Html5.toelt elt)##value then manip_error "Cannot call %s on a node without a 'value' property" name; Js.Unsafe.coerce @@ Html5.toelt elt let value elt = let elt = get_value_elt "value" elt in Js.to_string elt##value let html_elt_of_elt elt = let node = Html5.toelt elt in match Dom.nodeType node with | Dom.Element elt -> let html_elt = Dom_html.CoerceTo.element elt in Js.Opt.case html_elt (fun () -> manip_error "%s" "non-html element node don't have classes") (fun elt -> elt) | _ -> manip_error "%s" "non-element node don't have classes" let addClass elt cls = let elt = html_elt_of_elt elt in elt##classList##add (Js.string cls) let removeClass elt cls = let elt = html_elt_of_elt elt in elt##classList##remove (Js.string cls) module Elt = struct let body = try Of_dom.of_body (Dom_html.window##document##body) with _ -> Obj.magic Js.undefined (* For workers... *) end module Ev = struct type ('a, 'b) ev = 'a Html5.elt -> ('b Js.t -> bool) -> unit type ('a,'b) ev_unit = 'a Html5.elt -> ('b Js.t -> unit) -> unit let bool_cb f = Dom_html.handler (fun e -> Js.bool (f e)) let onkeyup elt f = let elt = get_elt "Ev.onkeyup" elt in elt##onkeyup <- (bool_cb f) let onkeydown elt f = let elt = get_elt "Ev.onkeydown" elt in elt##onkeydown <- (bool_cb f) let onmouseup elt f = let elt = get_elt "Ev.onmouseup" elt in elt##onmouseup <- (bool_cb f) let onmousedown elt f = let elt = get_elt "Ev.onmousedown" elt in elt##onmousedown <- (bool_cb f) let onmouseout elt f = let elt = get_elt "Ev.onmouseout" elt in elt##onmouseout <- (bool_cb f) let onmouseover elt f = let elt = get_elt "Ev.onmouseover" elt in elt##onmouseover <- (bool_cb f) let onclick elt f = let elt = get_elt "Ev.onclick" elt in elt##onclick <- (bool_cb f) let ondblclick elt f = let elt = get_elt "Ev.ondblclick" elt in elt##ondblclick <- (bool_cb f) let onload elt f = let elt = get_elt_img "Ev.onload" elt in elt##onload <- (bool_cb f) let onerror elt f = let elt = get_elt_img "Ev.onerror" elt in elt##onerror <- (bool_cb f) let onabort elt f = let elt = get_elt_img "Ev.onabort" elt in elt##onabort <- (bool_cb f) let onfocus elt f = let elt = get_elt_input "Ev.onfocus" elt in elt##onfocus <- (bool_cb f) let onblur elt f = let elt = get_elt_input "Ev.onblur" elt in elt##onblur <- (bool_cb f) let onfocus_textarea elt f = let elt = get_elt_textarea "Ev.onfocus" elt in elt##onfocus <- (bool_cb f) let onblur_textarea elt f = let elt = get_elt_textarea "Ev.onblur" elt in elt##onblur <- (bool_cb f) let onscroll elt f = let elt = get_elt "Ev.onscroll" elt in elt##onscroll <- (bool_cb f) let onreturn elt f = let f ev = let key = ev##keyCode in if key = Keycode.return then f ev; true in onkeydown elt f let onchange elt f = let elt = get_elt_input "Ev.onchange" elt in elt##onchange <- (bool_cb f) let onchange_select elt f = let elt = get_elt_select "Ev.onchange_select" elt in elt##onchange <- (bool_cb f) let onchange_textarea elt f = let elt = get_elt_textarea "Ev.onchange_textarea" elt in elt##onchange <- (bool_cb f) end module Attr = struct let clientWidth elt = let elt = get_elt "Attr.clientWidth" elt in elt##clientWidth let clientHeight elt = let elt = get_elt "Attr.clientHeight" elt in elt##clientHeight let offsetWidth elt = let elt = get_elt "Attr.offsetWidth" elt in elt##offsetWidth let offsetHeight elt = let elt = get_elt "Attr.offsetHeight" elt in elt##offsetHeight let clientLeft elt = let elt = get_elt "Attr.clientLeft" elt in elt##clientLeft let clientTop elt = let elt = get_elt "Attr.clientTop" elt in elt##clientTop end module Css = struct let background elt = let elt = get_elt "Css.background" elt in Js.to_bytestring (elt##style##background) let backgroundAttachment elt = let elt = get_elt "Css.backgroundAttachment" elt in Js.to_bytestring (elt##style##backgroundAttachment) let backgroundColor elt = let elt = get_elt "Css.backgroundColor" elt in Js.to_bytestring (elt##style##backgroundColor) let backgroundImage elt = let elt = get_elt "Css.backgroundImage" elt in Js.to_bytestring (elt##style##backgroundImage) let backgroundPosition elt = let elt = get_elt "Css.backgroundPosition" elt in Js.to_bytestring (elt##style##backgroundPosition) let backgroundRepeat elt = let elt = get_elt "Css.backgroundRepeat" elt in Js.to_bytestring (elt##style##backgroundRepeat) let border elt = let elt = get_elt "Css.border" elt in Js.to_bytestring (elt##style##border) let borderBottom elt = let elt = get_elt "Css.borderBottom" elt in Js.to_bytestring (elt##style##borderBottom) let borderBottomColor elt = let elt = get_elt "Css.borderBottomColor" elt in Js.to_bytestring (elt##style##borderBottomColor) let borderBottomStyle elt = let elt = get_elt "Css.borderBottomStyle" elt in Js.to_bytestring (elt##style##borderBottomStyle) let borderBottomWidth elt = let elt = get_elt "Css.borderBottomWidth" elt in Js.to_bytestring (elt##style##borderBottomWidth) let borderBottomWidthPx elt = let elt = get_elt "Css.borderBottomWidthPx" elt in Js.parseInt (elt##style##borderBottomWidth) let borderCollapse elt = let elt = get_elt "Css.borderCollapse" elt in Js.to_bytestring (elt##style##borderCollapse) let borderColor elt = let elt = get_elt "Css.borderColor" elt in Js.to_bytestring (elt##style##borderColor) let borderLeft elt = let elt = get_elt "Css.borderLeft" elt in Js.to_bytestring (elt##style##borderLeft) let borderLeftColor elt = let elt = get_elt "Css.borderLeftColor" elt in Js.to_bytestring (elt##style##borderLeftColor) let borderLeftStyle elt = let elt = get_elt "Css.borderLeftStyle" elt in Js.to_bytestring (elt##style##borderLeftStyle) let borderLeftWidth elt = let elt = get_elt "Css.borderLeftWidth" elt in Js.to_bytestring (elt##style##borderLeftWidth) let borderLeftWidthPx elt = let elt = get_elt "Css.borderLeftWidthPx" elt in Js.parseInt (elt##style##borderLeftWidth) let borderRight elt = let elt = get_elt "Css.borderRight" elt in Js.to_bytestring (elt##style##borderRight) let borderRightColor elt = let elt = get_elt "Css.borderRightColor" elt in Js.to_bytestring (elt##style##borderRightColor) let borderRightStyle elt = let elt = get_elt "Css.borderRightStyle" elt in Js.to_bytestring (elt##style##borderRightStyle) let borderRightWidth elt = let elt = get_elt "Css.borderRightWidth" elt in Js.to_bytestring (elt##style##borderRightWidth) let borderRightWidthPx elt = let elt = get_elt "Css.borderRightWidthPx" elt in Js.parseInt (elt##style##borderRightWidth) let borderSpacing elt = let elt = get_elt "Css.borderSpacing" elt in Js.to_bytestring (elt##style##borderSpacing) let borderStyle elt = let elt = get_elt "Css.borderStyle" elt in Js.to_bytestring (elt##style##borderStyle) let borderTop elt = let elt = get_elt "Css.borderTop" elt in Js.to_bytestring (elt##style##borderTop) let borderTopColor elt = let elt = get_elt "Css.borderTopColor" elt in Js.to_bytestring (elt##style##borderTopColor) let borderTopStyle elt = let elt = get_elt "Css.borderTopStyle" elt in Js.to_bytestring (elt##style##borderTopStyle) let borderTopWidth elt = let elt = get_elt "Css.borderTopWidth" elt in Js.to_bytestring (elt##style##borderTopWidth) let borderTopWidthPx elt = let elt = get_elt "Css.borderTopWidthPx" elt in Js.parseInt (elt##style##borderTopWidth) let borderWidth elt = let elt = get_elt "Css.borderWidth" elt in Js.to_bytestring (elt##style##borderWidth) let borderWidthPx elt = let elt = get_elt "Css.borderWidthPx" elt in Js.parseInt (elt##style##borderWidth) let bottom elt = let elt = get_elt "Css.bottom" elt in Js.to_bytestring (elt##style##bottom) let captionSide elt = let elt = get_elt "Css.captionSide" elt in Js.to_bytestring (elt##style##captionSide) let clear elt = let elt = get_elt "Css.clear" elt in Js.to_bytestring (elt##style##clear) let clip elt = let elt = get_elt "Css.clip" elt in Js.to_bytestring (elt##style##clip) let color elt = let elt = get_elt "Css.color" elt in Js.to_bytestring (elt##style##color) let content elt = let elt = get_elt "Css.content" elt in Js.to_bytestring (elt##style##content) let counterIncrement elt = let elt = get_elt "Css.counterIncrement" elt in Js.to_bytestring (elt##style##counterIncrement) let counterReset elt = let elt = get_elt "Css.counterReset" elt in Js.to_bytestring (elt##style##counterReset) let cssFloat elt = let elt = get_elt "Css.cssFloat" elt in Js.to_bytestring (elt##style##cssFloat) let cssText elt = let elt = get_elt "Css.cssText" elt in Js.to_bytestring (elt##style##cssText) let cursor elt = let elt = get_elt "Css.cursor" elt in Js.to_bytestring (elt##style##cursor) let direction elt = let elt = get_elt "Css.direction" elt in Js.to_bytestring (elt##style##direction) let display elt = let elt = get_elt "Css.display" elt in Js.to_bytestring (elt##style##display) let emptyCells elt = let elt = get_elt "Css.emptyCells" elt in Js.to_bytestring (elt##style##emptyCells) let font elt = let elt = get_elt "Css.font" elt in Js.to_bytestring (elt##style##font) let fontFamily elt = let elt = get_elt "Css.fontFamily" elt in Js.to_bytestring (elt##style##fontFamily) let fontSize elt = let elt = get_elt "Css.fontSize" elt in Js.to_bytestring (elt##style##fontSize) let fontStyle elt = let elt = get_elt "Css.fontStyle" elt in Js.to_bytestring (elt##style##fontStyle) let fontVariant elt = let elt = get_elt "Css.fontVariant" elt in Js.to_bytestring (elt##style##fontVariant) let fontWeight elt = let elt = get_elt "Css.fontWeight" elt in Js.to_bytestring (elt##style##fontWeight) let height elt = let elt = get_elt "Css.height" elt in Js.to_bytestring (elt##style##height) let heightPx elt = let elt = get_elt "Css.heightPx" elt in Js.parseInt (elt##style##height) let left elt = let elt = get_elt "Css.left" elt in Js.to_bytestring (elt##style##left) let leftPx elt = let elt = get_elt "Css.leftPx" elt in Js.parseInt (elt##style##left) let letterSpacing elt = let elt = get_elt "Css.letterSpacing" elt in Js.to_bytestring (elt##style##letterSpacing) let lineHeight elt = let elt = get_elt "Css.lineHeight" elt in Js.to_bytestring (elt##style##lineHeight) let listStyle elt = let elt = get_elt "Css.listStyle" elt in Js.to_bytestring (elt##style##listStyle) let listStyleImage elt = let elt = get_elt "Css.listStyleImage" elt in Js.to_bytestring (elt##style##listStyleImage) let listStylePosition elt = let elt = get_elt "Css.listStylePosition" elt in Js.to_bytestring (elt##style##listStylePosition) let listStyleType elt = let elt = get_elt "Css.listStyleType" elt in Js.to_bytestring (elt##style##listStyleType) let margin elt = let elt = get_elt "Css.margin" elt in Js.to_bytestring (elt##style##margin) let marginBottom elt = let elt = get_elt "Css.marginBottom" elt in Js.to_bytestring (elt##style##marginBottom) let marginBottomPx elt = let elt = get_elt "Css.marginBottomPx" elt in Js.parseInt (elt##style##marginBottom) let marginLeft elt = let elt = get_elt "Css.marginLeft" elt in Js.to_bytestring (elt##style##marginLeft) let marginLeftPx elt = let elt = get_elt "Css.marginLeftPx" elt in Js.parseInt (elt##style##marginLeft) let marginRight elt = let elt = get_elt "Css.marginRight" elt in Js.to_bytestring (elt##style##marginRight) let marginRightPx elt = let elt = get_elt "Css.marginRightPx" elt in Js.parseInt (elt##style##marginRight) let marginTop elt = let elt = get_elt "Css.marginTop" elt in Js.to_bytestring (elt##style##marginTop) let marginTopPx elt = let elt = get_elt "Css.marginTopPx" elt in Js.parseInt (elt##style##marginTop) let maxHeight elt = let elt = get_elt "Css.maxHeight" elt in Js.to_bytestring (elt##style##maxHeight) let maxHeightPx elt = let elt = get_elt "Css.maxHeightPx" elt in Js.parseInt (elt##style##maxHeight) let maxWidth elt = let elt = get_elt "Css.maxWidth" elt in Js.to_bytestring (elt##style##maxWidth) let maxWidthPx elt = let elt = get_elt "Css.maxWidthPx" elt in Js.parseInt (elt##style##maxWidth) let minHeight elt = let elt = get_elt "Css.minHeight" elt in Js.to_bytestring (elt##style##minHeight) let minHeightPx elt = let elt = get_elt "Css.minHeightPx" elt in Js.parseInt (elt##style##minHeight) let minWidth elt = let elt = get_elt "Css.minWidth" elt in Js.to_bytestring (elt##style##minWidth) let minWidthPx elt = let elt = get_elt "Css.minWidthPx" elt in Js.parseInt (elt##style##minWidth) let opacity elt = let elt = get_elt "Css.opacity" elt in option_map Js.to_bytestring (Js.Optdef.to_option (elt##style##opacity)) let outline elt = let elt = get_elt "Css.outline" elt in Js.to_bytestring (elt##style##outline) let outlineColor elt = let elt = get_elt "Css.outlineColor" elt in Js.to_bytestring (elt##style##outlineColor) let outlineOffset elt = let elt = get_elt "Css.outlineOffset" elt in Js.to_bytestring (elt##style##outlineOffset) let outlineStyle elt = let elt = get_elt "Css.outlineStyle" elt in Js.to_bytestring (elt##style##outlineStyle) let outlineWidth elt = let elt = get_elt "Css.outlineWidth" elt in Js.to_bytestring (elt##style##outlineWidth) let overflow elt = let elt = get_elt "Css.overflow" elt in Js.to_bytestring (elt##style##overflow) let overflowX elt = let elt = get_elt "Css.overflowX" elt in Js.to_bytestring (elt##style##overflowX) let overflowY elt = let elt = get_elt "Css.overflowY" elt in Js.to_bytestring (elt##style##overflowY) let padding elt = let elt = get_elt "Css.padding" elt in Js.to_bytestring (elt##style##padding) let paddingBottom elt = let elt = get_elt "Css.paddingBottom" elt in Js.to_bytestring (elt##style##paddingBottom) let paddingBottomPx elt = let elt = get_elt "Css.paddingBottomPx" elt in Js.parseInt (elt##style##paddingBottom) let paddingLeft elt = let elt = get_elt "Css.paddingLeft" elt in Js.to_bytestring (elt##style##paddingLeft) let paddingLeftPx elt = let elt = get_elt "Css.paddingLeftPx" elt in Js.parseInt (elt##style##paddingLeft) let paddingRight elt = let elt = get_elt "Css.paddingRight" elt in Js.to_bytestring (elt##style##paddingRight) let paddingRightPx elt = let elt = get_elt "Css.paddingRightPx" elt in Js.parseInt (elt##style##paddingRight) let paddingTop elt = let elt = get_elt "Css.paddingTop" elt in Js.to_bytestring (elt##style##paddingTop) let paddingTopPx elt = let elt = get_elt "Css.paddingTopPx" elt in Js.parseInt (elt##style##paddingTop) let pageBreakAfter elt = let elt = get_elt "Css.pageBreakAfter" elt in Js.to_bytestring (elt##style##pageBreakAfter) let pageBreakBefore elt = let elt = get_elt "Css.pageBreakBefore" elt in Js.to_bytestring (elt##style##pageBreakBefore) let position elt = let elt = get_elt "Css.position" elt in Js.to_bytestring (elt##style##position) let right elt = let elt = get_elt "Css.right" elt in Js.to_bytestring (elt##style##right) let rightPx elt = let elt = get_elt "Css.rightPx" elt in Js.parseInt (elt##style##right) let tableLayout elt = let elt = get_elt "Css.tableLayout" elt in Js.to_bytestring (elt##style##tableLayout) let textAlign elt = let elt = get_elt "Css.textAlign" elt in Js.to_bytestring (elt##style##textAlign) let textDecoration elt = let elt = get_elt "Css.textDecoration" elt in Js.to_bytestring (elt##style##textDecoration) let textIndent elt = let elt = get_elt "Css.textIndent" elt in Js.to_bytestring (elt##style##textIndent) let textTransform elt = let elt = get_elt "Css.textTransform" elt in Js.to_bytestring (elt##style##textTransform) let top elt = let elt = get_elt "Css.top" elt in Js.to_bytestring (elt##style##top) let topPx elt = let elt = get_elt "Css.topPx" elt in Js.parseInt (elt##style##top) let verticalAlign elt = let elt = get_elt "Css.verticalAlign" elt in Js.to_bytestring (elt##style##verticalAlign) let visibility elt = let elt = get_elt "Css.visibility" elt in Js.to_bytestring (elt##style##visibility) let whiteSpace elt = let elt = get_elt "Css.whiteSpace" elt in Js.to_bytestring (elt##style##whiteSpace) let width elt = let elt = get_elt "Css.width" elt in Js.to_bytestring (elt##style##width) let widthPx elt = let elt = get_elt "Css.widthPx" elt in Js.parseInt (elt##style##width) let wordSpacing elt = let elt = get_elt "Css.wordSpacing" elt in Js.to_bytestring (elt##style##wordSpacing) let zIndex elt = let elt = get_elt "Css.zIndex" elt in Js.to_bytestring (elt##style##zIndex) end module SetCss = struct let background elt v = let elt = get_elt "SetCss.background" elt in elt##style##background <- Js.bytestring v let backgroundAttachment elt v = let elt = get_elt "SetCss.backgroundAttachment" elt in elt##style##backgroundAttachment <- Js.bytestring v let backgroundColor elt v = let elt = get_elt "SetCss.backgroundColor" elt in elt##style##backgroundColor <- Js.bytestring v let backgroundImage elt v = let elt = get_elt "SetCss.backgroundImage" elt in elt##style##backgroundImage <- Js.bytestring v let backgroundPosition elt v = let elt = get_elt "SetCss.backgroundPosition" elt in elt##style##backgroundPosition <- Js.bytestring v let backgroundRepeat elt v = let elt = get_elt "SetCss.backgroundRepeat" elt in elt##style##backgroundRepeat <- Js.bytestring v let border elt v = let elt = get_elt "SetCss.border" elt in elt##style##border <- Js.bytestring v let borderBottom elt v = let elt = get_elt "SetCss.borderBottom" elt in elt##style##borderBottom <- Js.bytestring v let borderBottomColor elt v = let elt = get_elt "SetCss.borderBottomColor" elt in elt##style##borderBottomColor <- Js.bytestring v let borderBottomStyle elt v = let elt = get_elt "SetCss.borderBottomStyle" elt in elt##style##borderBottomStyle <- Js.bytestring v let borderBottomWidth elt v = let elt = get_elt "SetCss.borderBottomWidth" elt in elt##style##borderBottomWidth <- Js.bytestring v let borderBottomWidthPx elt v = borderBottomWidth elt (Printf.sprintf "%dpx" v) let borderCollapse elt v = let elt = get_elt "SetCss.borderCollapse" elt in elt##style##borderCollapse <- Js.bytestring v let borderColor elt v = let elt = get_elt "SetCss.borderColor" elt in elt##style##borderColor <- Js.bytestring v let borderLeft elt v = let elt = get_elt "SetCss.borderLeft" elt in elt##style##borderLeft <- Js.bytestring v let borderLeftColor elt v = let elt = get_elt "SetCss.borderLeftColor" elt in elt##style##borderLeftColor <- Js.bytestring v let borderLeftStyle elt v = let elt = get_elt "SetCss.borderLeftStyle" elt in elt##style##borderLeftStyle <- Js.bytestring v let borderLeftWidth elt v = let elt = get_elt "SetCss.borderLeftWidth" elt in elt##style##borderLeftWidth <- Js.bytestring v let borderLeftWidthPx elt v = borderLeftWidth elt (Printf.sprintf "%dpx" v) let borderRight elt v = let elt = get_elt "SetCss.borderRight" elt in elt##style##borderRight <- Js.bytestring v let borderRightColor elt v = let elt = get_elt "SetCss.borderRightColor" elt in elt##style##borderRightColor <- Js.bytestring v let borderRightStyle elt v = let elt = get_elt "SetCss.borderRightStyle" elt in elt##style##borderRightStyle <- Js.bytestring v let borderRightWidth elt v = let elt = get_elt "SetCss.borderRightWidth" elt in elt##style##borderRightWidth <- Js.bytestring v let borderRightWidthPx elt v = borderRightWidth elt (Printf.sprintf "%dpx" v) let borderSpacing elt v = let elt = get_elt "SetCss.borderSpacing" elt in elt##style##borderSpacing <- Js.bytestring v let borderStyle elt v = let elt = get_elt "SetCss.borderStyle" elt in elt##style##borderStyle <- Js.bytestring v let borderTop elt v = let elt = get_elt "SetCss.borderTop" elt in elt##style##borderTop <- Js.bytestring v let borderTopColor elt v = let elt = get_elt "SetCss.borderTopColor" elt in elt##style##borderTopColor <- Js.bytestring v let borderTopStyle elt v = let elt = get_elt "SetCss.borderTopStyle" elt in elt##style##borderTopStyle <- Js.bytestring v let borderTopWidth elt v = let elt = get_elt "SetCss.borderTopWidth" elt in elt##style##borderTopWidth <- Js.bytestring v let borderTopWidthPx elt v = borderTopWidth elt (Printf.sprintf "%dpx" v) let borderWidth elt v = let elt = get_elt "SetCss.borderWidth" elt in elt##style##borderWidth <- Js.bytestring v let bottom elt v = let elt = get_elt "SetCss.bottom" elt in elt##style##bottom <- Js.bytestring v let bottomPx elt v = bottom elt (Printf.sprintf "%dpx" v) let captionSide elt v = let elt = get_elt "SetCss.captionSide" elt in elt##style##captionSide <- Js.bytestring v let clear elt v = let elt = get_elt "SetCss.clear" elt in elt##style##clear <- Js.bytestring v let clip elt v = let elt = get_elt "SetCss.clip" elt in elt##style##clip <- Js.bytestring v let color elt v = let elt = get_elt "SetCss.color" elt in elt##style##color <- Js.bytestring v let content elt v = let elt = get_elt "SetCss.content" elt in elt##style##content <- Js.bytestring v let counterIncrement elt v = let elt = get_elt "SetCss.counterIncrement" elt in elt##style##counterIncrement <- Js.bytestring v let counterReset elt v = let elt = get_elt "SetCss.counterReset" elt in elt##style##counterReset <- Js.bytestring v let cssFloat elt v = let elt = get_elt "SetCss.cssFloat" elt in elt##style##cssFloat <- Js.bytestring v let cssText elt v = let elt = get_elt "SetCss.cssText" elt in elt##style##cssText <- Js.bytestring v let cursor elt v = let elt = get_elt "SetCss.cursor" elt in elt##style##cursor <- Js.bytestring v let direction elt v = let elt = get_elt "SetCss.direction" elt in elt##style##direction <- Js.bytestring v let display elt v = let elt = get_elt "SetCss.display" elt in elt##style##display <- Js.bytestring v let emptyCells elt v = let elt = get_elt "SetCss.emptyCells" elt in elt##style##emptyCells <- Js.bytestring v let font elt v = let elt = get_elt "SetCss.font" elt in elt##style##font <- Js.bytestring v let fontFamily elt v = let elt = get_elt "SetCss.fontFamily" elt in elt##style##fontFamily <- Js.bytestring v let fontSize elt v = let elt = get_elt "SetCss.fontSize" elt in elt##style##fontSize <- Js.bytestring v let fontStyle elt v = let elt = get_elt "SetCss.fontStyle" elt in elt##style##fontStyle <- Js.bytestring v let fontVariant elt v = let elt = get_elt "SetCss.fontVariant" elt in elt##style##fontVariant <- Js.bytestring v let fontWeight elt v = let elt = get_elt "SetCss.fontWeight" elt in elt##style##fontWeight <- Js.bytestring v let height elt v = let elt = get_elt "SetCss.height" elt in elt##style##height <- Js.bytestring v let heightPx elt v = height elt (Printf.sprintf "%dpx" v) let left elt v = let elt = get_elt "SetCss.left" elt in elt##style##left <- Js.bytestring v let leftPx elt v = left elt (Printf.sprintf "%dpx" v) let letterSpacing elt v = let elt = get_elt "SetCss.letterSpacing" elt in elt##style##letterSpacing <- Js.bytestring v let lineHeight elt v = let elt = get_elt "SetCss.lineHeight" elt in elt##style##lineHeight <- Js.bytestring v let listStyle elt v = let elt = get_elt "SetCss.listStyle" elt in elt##style##listStyle <- Js.bytestring v let listStyleImage elt v = let elt = get_elt "SetCss.listStyleImage" elt in elt##style##listStyleImage <- Js.bytestring v let listStylePosition elt v = let elt = get_elt "SetCss.listStylePosition" elt in elt##style##listStylePosition <- Js.bytestring v let listStyleType elt v = let elt = get_elt "SetCss.listStyleType" elt in elt##style##listStyleType <- Js.bytestring v let margin elt v = let elt = get_elt "SetCss.margin" elt in elt##style##margin <- Js.bytestring v let marginBottom elt v = let elt = get_elt "SetCss.marginBottom" elt in elt##style##marginBottom <- Js.bytestring v let marginBottomPx elt v = marginBottom elt (Printf.sprintf "%dpx" v) let marginLeft elt v = let elt = get_elt "SetCss.marginLeft" elt in elt##style##marginLeft <- Js.bytestring v let marginLeftPx elt v = marginLeft elt (Printf.sprintf "%dpx" v) let marginRight elt v = let elt = get_elt "SetCss.marginRight" elt in elt##style##marginRight <- Js.bytestring v let marginRightPx elt v = marginRight elt (Printf.sprintf "%dpx" v) let marginTop elt v = let elt = get_elt "SetCss.marginTop" elt in elt##style##marginTop <- Js.bytestring v let marginTopPx elt v = marginTop elt (Printf.sprintf "%dpx" v) let maxHeight elt v = let elt = get_elt "SetCss.maxHeight" elt in elt##style##maxHeight <- Js.bytestring v let maxHeightPx elt v = maxHeight elt (Printf.sprintf "%dpx" v) let maxWidth elt v = let elt = get_elt "SetCss.maxWidth" elt in elt##style##maxWidth <- Js.bytestring v let maxWidthPx elt v = maxWidth elt (Printf.sprintf "%dpx" v) let minHeight elt v = let elt = get_elt "SetCss.minHeight" elt in elt##style##minHeight <- Js.bytestring v let minHeightPx elt v = minHeight elt (Printf.sprintf "%dpx" v) let minWidth elt v = let elt = get_elt "SetCss.minWidth" elt in elt##style##minWidth <- Js.bytestring v let minWidthPx elt v = minWidth elt (Printf.sprintf "%dpx" v) let opacity elt v = let elt = get_elt "SetCss.opacity" elt in elt##style##opacity <- match v with None -> Js.undefined | Some v -> Js.def (Js.bytestring v) let outline elt v = let elt = get_elt "SetCss.outline" elt in elt##style##outline <- Js.bytestring v let outlineColor elt v = let elt = get_elt "SetCss.outlineColor" elt in elt##style##outlineColor <- Js.bytestring v let outlineOffset elt v = let elt = get_elt "SetCss.outlineOffset" elt in elt##style##outlineOffset <- Js.bytestring v let outlineStyle elt v = let elt = get_elt "SetCss.outlineStyle" elt in elt##style##outlineStyle <- Js.bytestring v let outlineWidth elt v = let elt = get_elt "SetCss.outlineWidth" elt in elt##style##outlineWidth <- Js.bytestring v let overflow elt v = let elt = get_elt "SetCss.overflow" elt in elt##style##overflow <- Js.bytestring v let overflowX elt v = let elt = get_elt "SetCss.overflowX" elt in elt##style##overflowX <- Js.bytestring v let overflowY elt v = let elt = get_elt "SetCss.overflowY" elt in elt##style##overflowY <- Js.bytestring v let padding elt v = let elt = get_elt "SetCss.padding" elt in elt##style##padding <- Js.bytestring v let paddingBottom elt v = let elt = get_elt "SetCss.paddingBottom" elt in elt##style##paddingBottom <- Js.bytestring v let paddingBottomPx elt v = paddingBottom elt (Printf.sprintf "%dpx" v) let paddingLeft elt v = let elt = get_elt "SetCss.paddingLeft" elt in elt##style##paddingLeft <- Js.bytestring v let paddingLeftPx elt v = paddingLeft elt (Printf.sprintf "%dpx" v) let paddingRight elt v = let elt = get_elt "SetCss.paddingRight" elt in elt##style##paddingRight <- Js.bytestring v let paddingRightPx elt v = paddingRight elt (Printf.sprintf "%dpx" v) let paddingTop elt v = let elt = get_elt "SetCss.paddingTop" elt in elt##style##paddingTop <- Js.bytestring v let paddingTopPx elt v = paddingTop elt (Printf.sprintf "%dpx" v) let pageBreakAfter elt v = let elt = get_elt "SetCss.pageBreakAfter" elt in elt##style##pageBreakAfter <- Js.bytestring v let pageBreakBefore elt v = let elt = get_elt "SetCss.pageBreakBefore" elt in elt##style##pageBreakBefore <- Js.bytestring v let position elt v = let elt = get_elt "SetCss.position" elt in elt##style##position <- Js.bytestring v let right elt v = let elt = get_elt "SetCss.right" elt in elt##style##right <- Js.bytestring v let rightPx elt v = right elt (Printf.sprintf "%dpx" v) let tableLayout elt v = let elt = get_elt "SetCss.tableLayout" elt in elt##style##tableLayout <- Js.bytestring v let textAlign elt v = let elt = get_elt "SetCss.textAlign" elt in elt##style##textAlign <- Js.bytestring v let textDecoration elt v = let elt = get_elt "SetCss.textDecoration" elt in elt##style##textDecoration <- Js.bytestring v let textIndent elt v = let elt = get_elt "SetCss.textIndent" elt in elt##style##textIndent <- Js.bytestring v let textTransform elt v = let elt = get_elt "SetCss.textTransform" elt in elt##style##textTransform <- Js.bytestring v let top elt v = let elt = get_elt "SetCss.top" elt in elt##style##top <- Js.bytestring v let topPx elt v = top elt (Printf.sprintf "%dpx" v) let verticalAlign elt v = let elt = get_elt "SetCss.verticalAlign" elt in elt##style##verticalAlign <- Js.bytestring v let visibility elt v = let elt = get_elt "SetCss.visibility" elt in elt##style##visibility <- Js.bytestring v let whiteSpace elt v = let elt = get_elt "SetCss.whiteSpace" elt in elt##style##whiteSpace <- Js.bytestring v let width elt v = let elt = get_elt "SetCss.width" elt in elt##style##width <- Js.bytestring v let widthPx elt v = width elt (Printf.sprintf "%dpx" v) let wordSpacing elt v = let elt = get_elt "SetCss.wordSpacing" elt in elt##style##wordSpacing <- Js.bytestring v let zIndex elt v = let elt = get_elt "SetCss.zIndex" elt in elt##style##zIndex <- Js.bytestring v end end
null
https://raw.githubusercontent.com/OCamlPro/scilint/9d9ddd8e1630ddeae7f4f875bce62b2f65ec17d8/src/common/tyxml_js_manip.ml
ocaml
For workers...
let doc = Dom_html.document let window = Dom_html.window let loc = Js.Unsafe.variable "location" let alert s = window##alert (Js.string s) let confirm s = Js.to_bool (window##confirm (Js.string s)) let js_log obj = Firebug.console##log (obj) let js_debug obj = Firebug.console##debug (obj) let js_error obj = Firebug.console##error (obj) let log fmt = Format.ksprintf (fun s -> Firebug.console##log (Js.string s)) fmt let debug fmt = Format.ksprintf (fun s -> Firebug.console##debug (Js.string s)) fmt let error fmt = Format.ksprintf (fun s -> Firebug.console##error (Js.string s)) fmt let is_hidden div = div##style##display = Js.string "none" let hide div = div##style##display <- Js.string "none" let display div = div##style##display <- Js.string "block" let reload () = window##location##reload () module Manip = struct let option_map f = function None -> None | Some x -> Some (f x) exception Error of string let manip_error fmt = Format.ksprintf (fun s -> debug "%s" s; raise (Error s)) fmt open Tyxml_js let id x = x let get_node = Html5.toelt let get_elt name elt : Dom_html.element Js.t = Js.Opt.case (Dom_html.CoerceTo.element (Html5.toelt elt)) (fun () -> manip_error "Cannot call %s on a node which is not an element" name) id let setInnerHtml elt s = let elt = get_elt "setInnerHtml" elt in elt##innerHTML <- Js.string s let raw_appendChild ?before node elt2 = match before with | None -> ignore(node##appendChild(get_node elt2)) | Some elt3 -> let node3 = get_node elt3 in ignore(node##insertBefore(get_node elt2, Js.some node3)) let raw_appendChildren ?before node elts = match before with | None -> List.iter (fun elt2 -> ignore(node##appendChild(get_node elt2))) elts | Some elt3 -> let node3 = get_node elt3 in List.iter (fun elt2 -> ignore(node##insertBefore(get_node elt2, Js.some node3))) elts let raw_removeChild node1 elt2 = let node2 = get_node elt2 in ignore(node1##removeChild(node2)) let raw_replaceChild node1 elt2 elt3 = let node2 = get_node elt2 in ignore(node1##replaceChild(node2, get_node elt3)) let raw_removeChildren node = let childrens = Dom.list_of_nodeList (node##childNodes) in List.iter (fun c -> ignore(node##removeChild(c))) childrens let raw_replaceChildren node elts = raw_removeChildren node; List.iter (fun elt -> ignore(node##appendChild(get_node elt))) elts let nth elt n = let node = get_node elt in let res = Js.Opt.bind (node##childNodes##item (n)) (fun node -> Js.Opt.map (Dom.CoerceTo.element node) (fun node -> Of_dom.of_element (Dom_html.element node) ) ) in Js.Opt.to_option res let childLength elt = let node = get_node elt in node##childNodes##length let appendChild ?before elt1 elt2 = let node = get_node elt1 in raw_appendChild ?before node elt2 let appendChildren ?before elt1 elts = let node = get_node elt1 in raw_appendChildren ?before node elts let removeChild elt1 elt2 = let node1 = get_node elt1 in raw_removeChild node1 elt2 let removeSelf elt = let node = get_node elt in let res = Js.Opt.bind (node##parentNode) (fun node -> Js.Opt.map (Dom.CoerceTo.element node) (fun node -> Of_dom.of_element (Dom_html.element node) ) ) in Js.Opt.iter res (fun p -> removeChild p elt) let appendChildFirst p c = let before = nth p 0 in appendChild ?before p c let replaceChild elt1 elt2 elt3 = let node1 = get_node elt1 in raw_replaceChild node1 elt2 elt3 let removeChildren elt = let node = get_node elt in raw_removeChildren node let replaceChildren elt elts = let node = get_node elt in raw_replaceChildren node elts let childNodes elt = let node = get_node elt in Dom.list_of_nodeList (node##childNodes) let rec filterElements nodes = match nodes with | [] -> [] | node :: nodes -> let elts = filterElements nodes in Js.Opt.case (Dom.CoerceTo.element node) (fun () -> elts) (fun elt -> elt :: elts) let childElements elt = let node = get_node elt in filterElements (Dom.list_of_nodeList (node##childNodes)) let appendToBody ?before elt2 = let body = (Of_dom.of_body Dom_html.window##document##body) in appendChild ?before body elt2 let get_elt_input name elt : Dom_html.inputElement Js.t = Js.Opt.case (Dom_html.CoerceTo.input (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non 'input' node (%s)" name)) id let get_elt_select name elt : Dom_html.selectElement Js.t = Js.Opt.case (Dom_html.CoerceTo.select (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non 'select' node (%s)" name)) id let get_elt_textarea name elt : Dom_html.textAreaElement Js.t = Js.Opt.case (Dom_html.CoerceTo.textarea (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non element node (%s)" name)) id let get_elt_img name elt : Dom_html.imageElement Js.t = Js.Opt.case (Dom_html.CoerceTo.img (get_elt name elt)) (fun () -> failwith (Printf.sprintf "Non element node (%s)" name)) id let scrollIntoView ?(bottom = false) elt = let elt = get_elt "Css.background" elt in elt##scrollIntoView(Js.bool (not bottom)) type disable = < disabled: bool Js.t Js.prop > let get_disable_elt name elt : disable Js.t = if Js.undefined == (Js.Unsafe.coerce @@ Html5.toelt elt)##disabled then manip_error "Cannot call %s on a node without a 'disable' property" name; Js.Unsafe.coerce @@ Html5.toelt elt let disable elt = let elt = get_disable_elt "disable" elt in elt##disabled <- Js._true let enable elt = let elt = get_disable_elt "enable" elt in elt##disabled <- Js._false type value = < value: Js.js_string Js.t Js.prop > let get_value_elt name elt : value Js.t = if Js.undefined == (Js.Unsafe.coerce @@ Html5.toelt elt)##value then manip_error "Cannot call %s on a node without a 'value' property" name; Js.Unsafe.coerce @@ Html5.toelt elt let value elt = let elt = get_value_elt "value" elt in Js.to_string elt##value let html_elt_of_elt elt = let node = Html5.toelt elt in match Dom.nodeType node with | Dom.Element elt -> let html_elt = Dom_html.CoerceTo.element elt in Js.Opt.case html_elt (fun () -> manip_error "%s" "non-html element node don't have classes") (fun elt -> elt) | _ -> manip_error "%s" "non-element node don't have classes" let addClass elt cls = let elt = html_elt_of_elt elt in elt##classList##add (Js.string cls) let removeClass elt cls = let elt = html_elt_of_elt elt in elt##classList##remove (Js.string cls) module Elt = struct let body = try Of_dom.of_body (Dom_html.window##document##body) end module Ev = struct type ('a, 'b) ev = 'a Html5.elt -> ('b Js.t -> bool) -> unit type ('a,'b) ev_unit = 'a Html5.elt -> ('b Js.t -> unit) -> unit let bool_cb f = Dom_html.handler (fun e -> Js.bool (f e)) let onkeyup elt f = let elt = get_elt "Ev.onkeyup" elt in elt##onkeyup <- (bool_cb f) let onkeydown elt f = let elt = get_elt "Ev.onkeydown" elt in elt##onkeydown <- (bool_cb f) let onmouseup elt f = let elt = get_elt "Ev.onmouseup" elt in elt##onmouseup <- (bool_cb f) let onmousedown elt f = let elt = get_elt "Ev.onmousedown" elt in elt##onmousedown <- (bool_cb f) let onmouseout elt f = let elt = get_elt "Ev.onmouseout" elt in elt##onmouseout <- (bool_cb f) let onmouseover elt f = let elt = get_elt "Ev.onmouseover" elt in elt##onmouseover <- (bool_cb f) let onclick elt f = let elt = get_elt "Ev.onclick" elt in elt##onclick <- (bool_cb f) let ondblclick elt f = let elt = get_elt "Ev.ondblclick" elt in elt##ondblclick <- (bool_cb f) let onload elt f = let elt = get_elt_img "Ev.onload" elt in elt##onload <- (bool_cb f) let onerror elt f = let elt = get_elt_img "Ev.onerror" elt in elt##onerror <- (bool_cb f) let onabort elt f = let elt = get_elt_img "Ev.onabort" elt in elt##onabort <- (bool_cb f) let onfocus elt f = let elt = get_elt_input "Ev.onfocus" elt in elt##onfocus <- (bool_cb f) let onblur elt f = let elt = get_elt_input "Ev.onblur" elt in elt##onblur <- (bool_cb f) let onfocus_textarea elt f = let elt = get_elt_textarea "Ev.onfocus" elt in elt##onfocus <- (bool_cb f) let onblur_textarea elt f = let elt = get_elt_textarea "Ev.onblur" elt in elt##onblur <- (bool_cb f) let onscroll elt f = let elt = get_elt "Ev.onscroll" elt in elt##onscroll <- (bool_cb f) let onreturn elt f = let f ev = let key = ev##keyCode in if key = Keycode.return then f ev; true in onkeydown elt f let onchange elt f = let elt = get_elt_input "Ev.onchange" elt in elt##onchange <- (bool_cb f) let onchange_select elt f = let elt = get_elt_select "Ev.onchange_select" elt in elt##onchange <- (bool_cb f) let onchange_textarea elt f = let elt = get_elt_textarea "Ev.onchange_textarea" elt in elt##onchange <- (bool_cb f) end module Attr = struct let clientWidth elt = let elt = get_elt "Attr.clientWidth" elt in elt##clientWidth let clientHeight elt = let elt = get_elt "Attr.clientHeight" elt in elt##clientHeight let offsetWidth elt = let elt = get_elt "Attr.offsetWidth" elt in elt##offsetWidth let offsetHeight elt = let elt = get_elt "Attr.offsetHeight" elt in elt##offsetHeight let clientLeft elt = let elt = get_elt "Attr.clientLeft" elt in elt##clientLeft let clientTop elt = let elt = get_elt "Attr.clientTop" elt in elt##clientTop end module Css = struct let background elt = let elt = get_elt "Css.background" elt in Js.to_bytestring (elt##style##background) let backgroundAttachment elt = let elt = get_elt "Css.backgroundAttachment" elt in Js.to_bytestring (elt##style##backgroundAttachment) let backgroundColor elt = let elt = get_elt "Css.backgroundColor" elt in Js.to_bytestring (elt##style##backgroundColor) let backgroundImage elt = let elt = get_elt "Css.backgroundImage" elt in Js.to_bytestring (elt##style##backgroundImage) let backgroundPosition elt = let elt = get_elt "Css.backgroundPosition" elt in Js.to_bytestring (elt##style##backgroundPosition) let backgroundRepeat elt = let elt = get_elt "Css.backgroundRepeat" elt in Js.to_bytestring (elt##style##backgroundRepeat) let border elt = let elt = get_elt "Css.border" elt in Js.to_bytestring (elt##style##border) let borderBottom elt = let elt = get_elt "Css.borderBottom" elt in Js.to_bytestring (elt##style##borderBottom) let borderBottomColor elt = let elt = get_elt "Css.borderBottomColor" elt in Js.to_bytestring (elt##style##borderBottomColor) let borderBottomStyle elt = let elt = get_elt "Css.borderBottomStyle" elt in Js.to_bytestring (elt##style##borderBottomStyle) let borderBottomWidth elt = let elt = get_elt "Css.borderBottomWidth" elt in Js.to_bytestring (elt##style##borderBottomWidth) let borderBottomWidthPx elt = let elt = get_elt "Css.borderBottomWidthPx" elt in Js.parseInt (elt##style##borderBottomWidth) let borderCollapse elt = let elt = get_elt "Css.borderCollapse" elt in Js.to_bytestring (elt##style##borderCollapse) let borderColor elt = let elt = get_elt "Css.borderColor" elt in Js.to_bytestring (elt##style##borderColor) let borderLeft elt = let elt = get_elt "Css.borderLeft" elt in Js.to_bytestring (elt##style##borderLeft) let borderLeftColor elt = let elt = get_elt "Css.borderLeftColor" elt in Js.to_bytestring (elt##style##borderLeftColor) let borderLeftStyle elt = let elt = get_elt "Css.borderLeftStyle" elt in Js.to_bytestring (elt##style##borderLeftStyle) let borderLeftWidth elt = let elt = get_elt "Css.borderLeftWidth" elt in Js.to_bytestring (elt##style##borderLeftWidth) let borderLeftWidthPx elt = let elt = get_elt "Css.borderLeftWidthPx" elt in Js.parseInt (elt##style##borderLeftWidth) let borderRight elt = let elt = get_elt "Css.borderRight" elt in Js.to_bytestring (elt##style##borderRight) let borderRightColor elt = let elt = get_elt "Css.borderRightColor" elt in Js.to_bytestring (elt##style##borderRightColor) let borderRightStyle elt = let elt = get_elt "Css.borderRightStyle" elt in Js.to_bytestring (elt##style##borderRightStyle) let borderRightWidth elt = let elt = get_elt "Css.borderRightWidth" elt in Js.to_bytestring (elt##style##borderRightWidth) let borderRightWidthPx elt = let elt = get_elt "Css.borderRightWidthPx" elt in Js.parseInt (elt##style##borderRightWidth) let borderSpacing elt = let elt = get_elt "Css.borderSpacing" elt in Js.to_bytestring (elt##style##borderSpacing) let borderStyle elt = let elt = get_elt "Css.borderStyle" elt in Js.to_bytestring (elt##style##borderStyle) let borderTop elt = let elt = get_elt "Css.borderTop" elt in Js.to_bytestring (elt##style##borderTop) let borderTopColor elt = let elt = get_elt "Css.borderTopColor" elt in Js.to_bytestring (elt##style##borderTopColor) let borderTopStyle elt = let elt = get_elt "Css.borderTopStyle" elt in Js.to_bytestring (elt##style##borderTopStyle) let borderTopWidth elt = let elt = get_elt "Css.borderTopWidth" elt in Js.to_bytestring (elt##style##borderTopWidth) let borderTopWidthPx elt = let elt = get_elt "Css.borderTopWidthPx" elt in Js.parseInt (elt##style##borderTopWidth) let borderWidth elt = let elt = get_elt "Css.borderWidth" elt in Js.to_bytestring (elt##style##borderWidth) let borderWidthPx elt = let elt = get_elt "Css.borderWidthPx" elt in Js.parseInt (elt##style##borderWidth) let bottom elt = let elt = get_elt "Css.bottom" elt in Js.to_bytestring (elt##style##bottom) let captionSide elt = let elt = get_elt "Css.captionSide" elt in Js.to_bytestring (elt##style##captionSide) let clear elt = let elt = get_elt "Css.clear" elt in Js.to_bytestring (elt##style##clear) let clip elt = let elt = get_elt "Css.clip" elt in Js.to_bytestring (elt##style##clip) let color elt = let elt = get_elt "Css.color" elt in Js.to_bytestring (elt##style##color) let content elt = let elt = get_elt "Css.content" elt in Js.to_bytestring (elt##style##content) let counterIncrement elt = let elt = get_elt "Css.counterIncrement" elt in Js.to_bytestring (elt##style##counterIncrement) let counterReset elt = let elt = get_elt "Css.counterReset" elt in Js.to_bytestring (elt##style##counterReset) let cssFloat elt = let elt = get_elt "Css.cssFloat" elt in Js.to_bytestring (elt##style##cssFloat) let cssText elt = let elt = get_elt "Css.cssText" elt in Js.to_bytestring (elt##style##cssText) let cursor elt = let elt = get_elt "Css.cursor" elt in Js.to_bytestring (elt##style##cursor) let direction elt = let elt = get_elt "Css.direction" elt in Js.to_bytestring (elt##style##direction) let display elt = let elt = get_elt "Css.display" elt in Js.to_bytestring (elt##style##display) let emptyCells elt = let elt = get_elt "Css.emptyCells" elt in Js.to_bytestring (elt##style##emptyCells) let font elt = let elt = get_elt "Css.font" elt in Js.to_bytestring (elt##style##font) let fontFamily elt = let elt = get_elt "Css.fontFamily" elt in Js.to_bytestring (elt##style##fontFamily) let fontSize elt = let elt = get_elt "Css.fontSize" elt in Js.to_bytestring (elt##style##fontSize) let fontStyle elt = let elt = get_elt "Css.fontStyle" elt in Js.to_bytestring (elt##style##fontStyle) let fontVariant elt = let elt = get_elt "Css.fontVariant" elt in Js.to_bytestring (elt##style##fontVariant) let fontWeight elt = let elt = get_elt "Css.fontWeight" elt in Js.to_bytestring (elt##style##fontWeight) let height elt = let elt = get_elt "Css.height" elt in Js.to_bytestring (elt##style##height) let heightPx elt = let elt = get_elt "Css.heightPx" elt in Js.parseInt (elt##style##height) let left elt = let elt = get_elt "Css.left" elt in Js.to_bytestring (elt##style##left) let leftPx elt = let elt = get_elt "Css.leftPx" elt in Js.parseInt (elt##style##left) let letterSpacing elt = let elt = get_elt "Css.letterSpacing" elt in Js.to_bytestring (elt##style##letterSpacing) let lineHeight elt = let elt = get_elt "Css.lineHeight" elt in Js.to_bytestring (elt##style##lineHeight) let listStyle elt = let elt = get_elt "Css.listStyle" elt in Js.to_bytestring (elt##style##listStyle) let listStyleImage elt = let elt = get_elt "Css.listStyleImage" elt in Js.to_bytestring (elt##style##listStyleImage) let listStylePosition elt = let elt = get_elt "Css.listStylePosition" elt in Js.to_bytestring (elt##style##listStylePosition) let listStyleType elt = let elt = get_elt "Css.listStyleType" elt in Js.to_bytestring (elt##style##listStyleType) let margin elt = let elt = get_elt "Css.margin" elt in Js.to_bytestring (elt##style##margin) let marginBottom elt = let elt = get_elt "Css.marginBottom" elt in Js.to_bytestring (elt##style##marginBottom) let marginBottomPx elt = let elt = get_elt "Css.marginBottomPx" elt in Js.parseInt (elt##style##marginBottom) let marginLeft elt = let elt = get_elt "Css.marginLeft" elt in Js.to_bytestring (elt##style##marginLeft) let marginLeftPx elt = let elt = get_elt "Css.marginLeftPx" elt in Js.parseInt (elt##style##marginLeft) let marginRight elt = let elt = get_elt "Css.marginRight" elt in Js.to_bytestring (elt##style##marginRight) let marginRightPx elt = let elt = get_elt "Css.marginRightPx" elt in Js.parseInt (elt##style##marginRight) let marginTop elt = let elt = get_elt "Css.marginTop" elt in Js.to_bytestring (elt##style##marginTop) let marginTopPx elt = let elt = get_elt "Css.marginTopPx" elt in Js.parseInt (elt##style##marginTop) let maxHeight elt = let elt = get_elt "Css.maxHeight" elt in Js.to_bytestring (elt##style##maxHeight) let maxHeightPx elt = let elt = get_elt "Css.maxHeightPx" elt in Js.parseInt (elt##style##maxHeight) let maxWidth elt = let elt = get_elt "Css.maxWidth" elt in Js.to_bytestring (elt##style##maxWidth) let maxWidthPx elt = let elt = get_elt "Css.maxWidthPx" elt in Js.parseInt (elt##style##maxWidth) let minHeight elt = let elt = get_elt "Css.minHeight" elt in Js.to_bytestring (elt##style##minHeight) let minHeightPx elt = let elt = get_elt "Css.minHeightPx" elt in Js.parseInt (elt##style##minHeight) let minWidth elt = let elt = get_elt "Css.minWidth" elt in Js.to_bytestring (elt##style##minWidth) let minWidthPx elt = let elt = get_elt "Css.minWidthPx" elt in Js.parseInt (elt##style##minWidth) let opacity elt = let elt = get_elt "Css.opacity" elt in option_map Js.to_bytestring (Js.Optdef.to_option (elt##style##opacity)) let outline elt = let elt = get_elt "Css.outline" elt in Js.to_bytestring (elt##style##outline) let outlineColor elt = let elt = get_elt "Css.outlineColor" elt in Js.to_bytestring (elt##style##outlineColor) let outlineOffset elt = let elt = get_elt "Css.outlineOffset" elt in Js.to_bytestring (elt##style##outlineOffset) let outlineStyle elt = let elt = get_elt "Css.outlineStyle" elt in Js.to_bytestring (elt##style##outlineStyle) let outlineWidth elt = let elt = get_elt "Css.outlineWidth" elt in Js.to_bytestring (elt##style##outlineWidth) let overflow elt = let elt = get_elt "Css.overflow" elt in Js.to_bytestring (elt##style##overflow) let overflowX elt = let elt = get_elt "Css.overflowX" elt in Js.to_bytestring (elt##style##overflowX) let overflowY elt = let elt = get_elt "Css.overflowY" elt in Js.to_bytestring (elt##style##overflowY) let padding elt = let elt = get_elt "Css.padding" elt in Js.to_bytestring (elt##style##padding) let paddingBottom elt = let elt = get_elt "Css.paddingBottom" elt in Js.to_bytestring (elt##style##paddingBottom) let paddingBottomPx elt = let elt = get_elt "Css.paddingBottomPx" elt in Js.parseInt (elt##style##paddingBottom) let paddingLeft elt = let elt = get_elt "Css.paddingLeft" elt in Js.to_bytestring (elt##style##paddingLeft) let paddingLeftPx elt = let elt = get_elt "Css.paddingLeftPx" elt in Js.parseInt (elt##style##paddingLeft) let paddingRight elt = let elt = get_elt "Css.paddingRight" elt in Js.to_bytestring (elt##style##paddingRight) let paddingRightPx elt = let elt = get_elt "Css.paddingRightPx" elt in Js.parseInt (elt##style##paddingRight) let paddingTop elt = let elt = get_elt "Css.paddingTop" elt in Js.to_bytestring (elt##style##paddingTop) let paddingTopPx elt = let elt = get_elt "Css.paddingTopPx" elt in Js.parseInt (elt##style##paddingTop) let pageBreakAfter elt = let elt = get_elt "Css.pageBreakAfter" elt in Js.to_bytestring (elt##style##pageBreakAfter) let pageBreakBefore elt = let elt = get_elt "Css.pageBreakBefore" elt in Js.to_bytestring (elt##style##pageBreakBefore) let position elt = let elt = get_elt "Css.position" elt in Js.to_bytestring (elt##style##position) let right elt = let elt = get_elt "Css.right" elt in Js.to_bytestring (elt##style##right) let rightPx elt = let elt = get_elt "Css.rightPx" elt in Js.parseInt (elt##style##right) let tableLayout elt = let elt = get_elt "Css.tableLayout" elt in Js.to_bytestring (elt##style##tableLayout) let textAlign elt = let elt = get_elt "Css.textAlign" elt in Js.to_bytestring (elt##style##textAlign) let textDecoration elt = let elt = get_elt "Css.textDecoration" elt in Js.to_bytestring (elt##style##textDecoration) let textIndent elt = let elt = get_elt "Css.textIndent" elt in Js.to_bytestring (elt##style##textIndent) let textTransform elt = let elt = get_elt "Css.textTransform" elt in Js.to_bytestring (elt##style##textTransform) let top elt = let elt = get_elt "Css.top" elt in Js.to_bytestring (elt##style##top) let topPx elt = let elt = get_elt "Css.topPx" elt in Js.parseInt (elt##style##top) let verticalAlign elt = let elt = get_elt "Css.verticalAlign" elt in Js.to_bytestring (elt##style##verticalAlign) let visibility elt = let elt = get_elt "Css.visibility" elt in Js.to_bytestring (elt##style##visibility) let whiteSpace elt = let elt = get_elt "Css.whiteSpace" elt in Js.to_bytestring (elt##style##whiteSpace) let width elt = let elt = get_elt "Css.width" elt in Js.to_bytestring (elt##style##width) let widthPx elt = let elt = get_elt "Css.widthPx" elt in Js.parseInt (elt##style##width) let wordSpacing elt = let elt = get_elt "Css.wordSpacing" elt in Js.to_bytestring (elt##style##wordSpacing) let zIndex elt = let elt = get_elt "Css.zIndex" elt in Js.to_bytestring (elt##style##zIndex) end module SetCss = struct let background elt v = let elt = get_elt "SetCss.background" elt in elt##style##background <- Js.bytestring v let backgroundAttachment elt v = let elt = get_elt "SetCss.backgroundAttachment" elt in elt##style##backgroundAttachment <- Js.bytestring v let backgroundColor elt v = let elt = get_elt "SetCss.backgroundColor" elt in elt##style##backgroundColor <- Js.bytestring v let backgroundImage elt v = let elt = get_elt "SetCss.backgroundImage" elt in elt##style##backgroundImage <- Js.bytestring v let backgroundPosition elt v = let elt = get_elt "SetCss.backgroundPosition" elt in elt##style##backgroundPosition <- Js.bytestring v let backgroundRepeat elt v = let elt = get_elt "SetCss.backgroundRepeat" elt in elt##style##backgroundRepeat <- Js.bytestring v let border elt v = let elt = get_elt "SetCss.border" elt in elt##style##border <- Js.bytestring v let borderBottom elt v = let elt = get_elt "SetCss.borderBottom" elt in elt##style##borderBottom <- Js.bytestring v let borderBottomColor elt v = let elt = get_elt "SetCss.borderBottomColor" elt in elt##style##borderBottomColor <- Js.bytestring v let borderBottomStyle elt v = let elt = get_elt "SetCss.borderBottomStyle" elt in elt##style##borderBottomStyle <- Js.bytestring v let borderBottomWidth elt v = let elt = get_elt "SetCss.borderBottomWidth" elt in elt##style##borderBottomWidth <- Js.bytestring v let borderBottomWidthPx elt v = borderBottomWidth elt (Printf.sprintf "%dpx" v) let borderCollapse elt v = let elt = get_elt "SetCss.borderCollapse" elt in elt##style##borderCollapse <- Js.bytestring v let borderColor elt v = let elt = get_elt "SetCss.borderColor" elt in elt##style##borderColor <- Js.bytestring v let borderLeft elt v = let elt = get_elt "SetCss.borderLeft" elt in elt##style##borderLeft <- Js.bytestring v let borderLeftColor elt v = let elt = get_elt "SetCss.borderLeftColor" elt in elt##style##borderLeftColor <- Js.bytestring v let borderLeftStyle elt v = let elt = get_elt "SetCss.borderLeftStyle" elt in elt##style##borderLeftStyle <- Js.bytestring v let borderLeftWidth elt v = let elt = get_elt "SetCss.borderLeftWidth" elt in elt##style##borderLeftWidth <- Js.bytestring v let borderLeftWidthPx elt v = borderLeftWidth elt (Printf.sprintf "%dpx" v) let borderRight elt v = let elt = get_elt "SetCss.borderRight" elt in elt##style##borderRight <- Js.bytestring v let borderRightColor elt v = let elt = get_elt "SetCss.borderRightColor" elt in elt##style##borderRightColor <- Js.bytestring v let borderRightStyle elt v = let elt = get_elt "SetCss.borderRightStyle" elt in elt##style##borderRightStyle <- Js.bytestring v let borderRightWidth elt v = let elt = get_elt "SetCss.borderRightWidth" elt in elt##style##borderRightWidth <- Js.bytestring v let borderRightWidthPx elt v = borderRightWidth elt (Printf.sprintf "%dpx" v) let borderSpacing elt v = let elt = get_elt "SetCss.borderSpacing" elt in elt##style##borderSpacing <- Js.bytestring v let borderStyle elt v = let elt = get_elt "SetCss.borderStyle" elt in elt##style##borderStyle <- Js.bytestring v let borderTop elt v = let elt = get_elt "SetCss.borderTop" elt in elt##style##borderTop <- Js.bytestring v let borderTopColor elt v = let elt = get_elt "SetCss.borderTopColor" elt in elt##style##borderTopColor <- Js.bytestring v let borderTopStyle elt v = let elt = get_elt "SetCss.borderTopStyle" elt in elt##style##borderTopStyle <- Js.bytestring v let borderTopWidth elt v = let elt = get_elt "SetCss.borderTopWidth" elt in elt##style##borderTopWidth <- Js.bytestring v let borderTopWidthPx elt v = borderTopWidth elt (Printf.sprintf "%dpx" v) let borderWidth elt v = let elt = get_elt "SetCss.borderWidth" elt in elt##style##borderWidth <- Js.bytestring v let bottom elt v = let elt = get_elt "SetCss.bottom" elt in elt##style##bottom <- Js.bytestring v let bottomPx elt v = bottom elt (Printf.sprintf "%dpx" v) let captionSide elt v = let elt = get_elt "SetCss.captionSide" elt in elt##style##captionSide <- Js.bytestring v let clear elt v = let elt = get_elt "SetCss.clear" elt in elt##style##clear <- Js.bytestring v let clip elt v = let elt = get_elt "SetCss.clip" elt in elt##style##clip <- Js.bytestring v let color elt v = let elt = get_elt "SetCss.color" elt in elt##style##color <- Js.bytestring v let content elt v = let elt = get_elt "SetCss.content" elt in elt##style##content <- Js.bytestring v let counterIncrement elt v = let elt = get_elt "SetCss.counterIncrement" elt in elt##style##counterIncrement <- Js.bytestring v let counterReset elt v = let elt = get_elt "SetCss.counterReset" elt in elt##style##counterReset <- Js.bytestring v let cssFloat elt v = let elt = get_elt "SetCss.cssFloat" elt in elt##style##cssFloat <- Js.bytestring v let cssText elt v = let elt = get_elt "SetCss.cssText" elt in elt##style##cssText <- Js.bytestring v let cursor elt v = let elt = get_elt "SetCss.cursor" elt in elt##style##cursor <- Js.bytestring v let direction elt v = let elt = get_elt "SetCss.direction" elt in elt##style##direction <- Js.bytestring v let display elt v = let elt = get_elt "SetCss.display" elt in elt##style##display <- Js.bytestring v let emptyCells elt v = let elt = get_elt "SetCss.emptyCells" elt in elt##style##emptyCells <- Js.bytestring v let font elt v = let elt = get_elt "SetCss.font" elt in elt##style##font <- Js.bytestring v let fontFamily elt v = let elt = get_elt "SetCss.fontFamily" elt in elt##style##fontFamily <- Js.bytestring v let fontSize elt v = let elt = get_elt "SetCss.fontSize" elt in elt##style##fontSize <- Js.bytestring v let fontStyle elt v = let elt = get_elt "SetCss.fontStyle" elt in elt##style##fontStyle <- Js.bytestring v let fontVariant elt v = let elt = get_elt "SetCss.fontVariant" elt in elt##style##fontVariant <- Js.bytestring v let fontWeight elt v = let elt = get_elt "SetCss.fontWeight" elt in elt##style##fontWeight <- Js.bytestring v let height elt v = let elt = get_elt "SetCss.height" elt in elt##style##height <- Js.bytestring v let heightPx elt v = height elt (Printf.sprintf "%dpx" v) let left elt v = let elt = get_elt "SetCss.left" elt in elt##style##left <- Js.bytestring v let leftPx elt v = left elt (Printf.sprintf "%dpx" v) let letterSpacing elt v = let elt = get_elt "SetCss.letterSpacing" elt in elt##style##letterSpacing <- Js.bytestring v let lineHeight elt v = let elt = get_elt "SetCss.lineHeight" elt in elt##style##lineHeight <- Js.bytestring v let listStyle elt v = let elt = get_elt "SetCss.listStyle" elt in elt##style##listStyle <- Js.bytestring v let listStyleImage elt v = let elt = get_elt "SetCss.listStyleImage" elt in elt##style##listStyleImage <- Js.bytestring v let listStylePosition elt v = let elt = get_elt "SetCss.listStylePosition" elt in elt##style##listStylePosition <- Js.bytestring v let listStyleType elt v = let elt = get_elt "SetCss.listStyleType" elt in elt##style##listStyleType <- Js.bytestring v let margin elt v = let elt = get_elt "SetCss.margin" elt in elt##style##margin <- Js.bytestring v let marginBottom elt v = let elt = get_elt "SetCss.marginBottom" elt in elt##style##marginBottom <- Js.bytestring v let marginBottomPx elt v = marginBottom elt (Printf.sprintf "%dpx" v) let marginLeft elt v = let elt = get_elt "SetCss.marginLeft" elt in elt##style##marginLeft <- Js.bytestring v let marginLeftPx elt v = marginLeft elt (Printf.sprintf "%dpx" v) let marginRight elt v = let elt = get_elt "SetCss.marginRight" elt in elt##style##marginRight <- Js.bytestring v let marginRightPx elt v = marginRight elt (Printf.sprintf "%dpx" v) let marginTop elt v = let elt = get_elt "SetCss.marginTop" elt in elt##style##marginTop <- Js.bytestring v let marginTopPx elt v = marginTop elt (Printf.sprintf "%dpx" v) let maxHeight elt v = let elt = get_elt "SetCss.maxHeight" elt in elt##style##maxHeight <- Js.bytestring v let maxHeightPx elt v = maxHeight elt (Printf.sprintf "%dpx" v) let maxWidth elt v = let elt = get_elt "SetCss.maxWidth" elt in elt##style##maxWidth <- Js.bytestring v let maxWidthPx elt v = maxWidth elt (Printf.sprintf "%dpx" v) let minHeight elt v = let elt = get_elt "SetCss.minHeight" elt in elt##style##minHeight <- Js.bytestring v let minHeightPx elt v = minHeight elt (Printf.sprintf "%dpx" v) let minWidth elt v = let elt = get_elt "SetCss.minWidth" elt in elt##style##minWidth <- Js.bytestring v let minWidthPx elt v = minWidth elt (Printf.sprintf "%dpx" v) let opacity elt v = let elt = get_elt "SetCss.opacity" elt in elt##style##opacity <- match v with None -> Js.undefined | Some v -> Js.def (Js.bytestring v) let outline elt v = let elt = get_elt "SetCss.outline" elt in elt##style##outline <- Js.bytestring v let outlineColor elt v = let elt = get_elt "SetCss.outlineColor" elt in elt##style##outlineColor <- Js.bytestring v let outlineOffset elt v = let elt = get_elt "SetCss.outlineOffset" elt in elt##style##outlineOffset <- Js.bytestring v let outlineStyle elt v = let elt = get_elt "SetCss.outlineStyle" elt in elt##style##outlineStyle <- Js.bytestring v let outlineWidth elt v = let elt = get_elt "SetCss.outlineWidth" elt in elt##style##outlineWidth <- Js.bytestring v let overflow elt v = let elt = get_elt "SetCss.overflow" elt in elt##style##overflow <- Js.bytestring v let overflowX elt v = let elt = get_elt "SetCss.overflowX" elt in elt##style##overflowX <- Js.bytestring v let overflowY elt v = let elt = get_elt "SetCss.overflowY" elt in elt##style##overflowY <- Js.bytestring v let padding elt v = let elt = get_elt "SetCss.padding" elt in elt##style##padding <- Js.bytestring v let paddingBottom elt v = let elt = get_elt "SetCss.paddingBottom" elt in elt##style##paddingBottom <- Js.bytestring v let paddingBottomPx elt v = paddingBottom elt (Printf.sprintf "%dpx" v) let paddingLeft elt v = let elt = get_elt "SetCss.paddingLeft" elt in elt##style##paddingLeft <- Js.bytestring v let paddingLeftPx elt v = paddingLeft elt (Printf.sprintf "%dpx" v) let paddingRight elt v = let elt = get_elt "SetCss.paddingRight" elt in elt##style##paddingRight <- Js.bytestring v let paddingRightPx elt v = paddingRight elt (Printf.sprintf "%dpx" v) let paddingTop elt v = let elt = get_elt "SetCss.paddingTop" elt in elt##style##paddingTop <- Js.bytestring v let paddingTopPx elt v = paddingTop elt (Printf.sprintf "%dpx" v) let pageBreakAfter elt v = let elt = get_elt "SetCss.pageBreakAfter" elt in elt##style##pageBreakAfter <- Js.bytestring v let pageBreakBefore elt v = let elt = get_elt "SetCss.pageBreakBefore" elt in elt##style##pageBreakBefore <- Js.bytestring v let position elt v = let elt = get_elt "SetCss.position" elt in elt##style##position <- Js.bytestring v let right elt v = let elt = get_elt "SetCss.right" elt in elt##style##right <- Js.bytestring v let rightPx elt v = right elt (Printf.sprintf "%dpx" v) let tableLayout elt v = let elt = get_elt "SetCss.tableLayout" elt in elt##style##tableLayout <- Js.bytestring v let textAlign elt v = let elt = get_elt "SetCss.textAlign" elt in elt##style##textAlign <- Js.bytestring v let textDecoration elt v = let elt = get_elt "SetCss.textDecoration" elt in elt##style##textDecoration <- Js.bytestring v let textIndent elt v = let elt = get_elt "SetCss.textIndent" elt in elt##style##textIndent <- Js.bytestring v let textTransform elt v = let elt = get_elt "SetCss.textTransform" elt in elt##style##textTransform <- Js.bytestring v let top elt v = let elt = get_elt "SetCss.top" elt in elt##style##top <- Js.bytestring v let topPx elt v = top elt (Printf.sprintf "%dpx" v) let verticalAlign elt v = let elt = get_elt "SetCss.verticalAlign" elt in elt##style##verticalAlign <- Js.bytestring v let visibility elt v = let elt = get_elt "SetCss.visibility" elt in elt##style##visibility <- Js.bytestring v let whiteSpace elt v = let elt = get_elt "SetCss.whiteSpace" elt in elt##style##whiteSpace <- Js.bytestring v let width elt v = let elt = get_elt "SetCss.width" elt in elt##style##width <- Js.bytestring v let widthPx elt v = width elt (Printf.sprintf "%dpx" v) let wordSpacing elt v = let elt = get_elt "SetCss.wordSpacing" elt in elt##style##wordSpacing <- Js.bytestring v let zIndex elt v = let elt = get_elt "SetCss.zIndex" elt in elt##style##zIndex <- Js.bytestring v end end
e657688824521b72b35e52a359852be9f836764461b79cc995d5fe7179917dc8
MrEbbinghaus/fulcro-material-ui-wrapper
data_display.cljc
(ns ^:deprecated material-ui.data-display (:refer-clojure :exclude [list]) (:require [com.fulcrologic.fulcro.algorithms.react-interop :as interop] #?@(:cljs [["@mui/material/Typography" :default Typography] ["@mui/material/Divider" :default Divider] ["@mui/material/Chip" :default Chip] ["@mui/material/Badge" :default Badge] ["@mui/material/Avatar" :default Avatar] ["@mui/material/AvatarGroup" :default AvatarGroup] ["@mui/material/Tooltip" :default Tooltip]]))) (def typography (interop/react-factory #?(:cljs Typography :clj nil))) (def divider (interop/react-factory #?(:cljs Divider :clj nil))) (def chip (interop/react-factory #?(:cljs Chip :clj nil))) (def badge (interop/react-factory #?(:cljs Badge :clj nil))) (def avatar (interop/react-factory #?(:cljs Avatar :clj nil))) (def avatar-group (interop/react-factory #?(:cljs AvatarGroup :clj nil))) (def tooltip (interop/react-factory #?(:cljs Tooltip :clj nil)))
null
https://raw.githubusercontent.com/MrEbbinghaus/fulcro-material-ui-wrapper/058f1dd4b85542914f92f48a4010ea9ad497e48f/src/material_ui/data_display.cljc
clojure
(ns ^:deprecated material-ui.data-display (:refer-clojure :exclude [list]) (:require [com.fulcrologic.fulcro.algorithms.react-interop :as interop] #?@(:cljs [["@mui/material/Typography" :default Typography] ["@mui/material/Divider" :default Divider] ["@mui/material/Chip" :default Chip] ["@mui/material/Badge" :default Badge] ["@mui/material/Avatar" :default Avatar] ["@mui/material/AvatarGroup" :default AvatarGroup] ["@mui/material/Tooltip" :default Tooltip]]))) (def typography (interop/react-factory #?(:cljs Typography :clj nil))) (def divider (interop/react-factory #?(:cljs Divider :clj nil))) (def chip (interop/react-factory #?(:cljs Chip :clj nil))) (def badge (interop/react-factory #?(:cljs Badge :clj nil))) (def avatar (interop/react-factory #?(:cljs Avatar :clj nil))) (def avatar-group (interop/react-factory #?(:cljs AvatarGroup :clj nil))) (def tooltip (interop/react-factory #?(:cljs Tooltip :clj nil)))
651dd6127fb5df258b97ce3e9c2b732c53bd7e7ae481676c44addde01e96ef16
aprell/compiler-potpourri
optim.mli
open Control_flow val optimize : ?dump:bool -> Cfg.t -> Ssa.Graph.t -> Cfg.t
null
https://raw.githubusercontent.com/aprell/compiler-potpourri/a668b71f392abf1810a1f33f362a1d96bc5eebce/ssa/optim.mli
ocaml
open Control_flow val optimize : ?dump:bool -> Cfg.t -> Ssa.Graph.t -> Cfg.t
0d45fcf621c800ada9f813aede08e449fd8721c5b4958650669926986714b4be
anoma/juvix
Closure.hs
module Juvix.Compiler.Backend.C.Data.Closure where import Juvix.Compiler.Backend.C.Data.Base import Juvix.Compiler.Backend.C.Language import Juvix.Compiler.Concrete.Data.Builtins (IsBuiltin (toBuiltinPrim)) import Juvix.Compiler.Internal.Extra (mkPolyType') import Juvix.Compiler.Internal.Extra qualified as Micro import Juvix.Compiler.Internal.Translation.Extra qualified as Micro import Juvix.Compiler.Internal.Translation.FromInternal.Analysis.TypeChecking.Data.Context qualified as Micro import Juvix.Prelude genClosures :: forall r. (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable] r) => Micro.Module -> Sem r [CCode] genClosures Micro.Module {..} = do closureInfos <- concatMapM (applyOnFunStatement functionDefClosures) (_moduleBody ^. Micro.moduleStatements) return (genCClosure =<< nub closureInfos) genCClosure :: ClosureInfo -> [CCode] genCClosure c = [ ExternalDecl (genClosureEnv c), ExternalFunc (genClosureApply c), ExternalFunc (genClosureEval c) ] functionDefClosures :: (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable] r) => Micro.FunctionDef -> Sem r [ClosureInfo] functionDefClosures Micro.FunctionDef {..} = concatMapM (clauseClosures (fst (unfoldFunType (mkPolyType' _funDefType)))) (toList _funDefClauses) lookupBuiltinIden :: (Members '[Reader Micro.InfoTable] r) => Micro.Iden -> Sem r (Maybe Micro.BuiltinPrim) lookupBuiltinIden = \case Micro.IdenFunction f -> fmap toBuiltinPrim . (^. Micro.functionInfoDef . Micro.funDefBuiltin) <$> Micro.lookupFunction f Micro.IdenConstructor c -> fmap toBuiltinPrim . (^. Micro.constructorInfoBuiltin) <$> Micro.lookupConstructor c Micro.IdenAxiom a -> fmap toBuiltinPrim . (^. Micro.axiomInfoBuiltin) <$> Micro.lookupAxiom a Micro.IdenVar {} -> return Nothing Micro.IdenInductive {} -> impossible genClosureExpression :: forall r. (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable, Reader PatternInfoTable] r) => [Micro.PolyType] -> Micro.Expression -> Sem r [ClosureInfo] genClosureExpression funArgTyps = \case Micro.ExpressionLet {} -> error "To be implemented" Micro.ExpressionIden i -> do let rootFunMicroName = Micro.getName i rootFunNameId = rootFunMicroName ^. Micro.nameId rootFunName = mkName rootFunMicroName builtin <- lookupBuiltinIden i case i of Micro.IdenVar {} -> return [] _ -> do (t, patterns) <- getType i let argTyps = t ^. cFunArgTypes if | null argTyps -> return [] | otherwise -> return [ ClosureInfo { _closureNameId = rootFunNameId, _closureRootName = rootFunName, _closureBuiltin = builtin, _closureMembers = [], _closureFunType = t, _closureCArity = patterns } ] Micro.ExpressionApplication a -> exprApplication a Micro.ExpressionLiteral {} -> return [] Micro.ExpressionFunction {} -> impossible Micro.ExpressionHole {} -> impossible Micro.ExpressionUniverse {} -> impossible Micro.ExpressionSimpleLambda {} -> impossible Micro.ExpressionLambda {} -> impossible Micro.ExpressionCase {} -> impossible where exprApplication :: Micro.Application -> Sem r [ClosureInfo] exprApplication a = do (f0, appArgs) <- Micro.unfoldPolyApplication a if | null appArgs -> genClosureExpression funArgTyps f0 | otherwise -> case f0 of Micro.ExpressionLiteral {} -> return [] Micro.ExpressionIden f -> do let rootFunMicroName = Micro.getName f rootFunNameId = rootFunMicroName ^. Micro.nameId rootFunName = mkName rootFunMicroName builtin <- lookupBuiltinIden f (fType, patterns) <- getType f closureArgs <- concatMapM (genClosureExpression funArgTyps) (toList appArgs) if | length appArgs < length (fType ^. cFunArgTypes) -> return ( [ ClosureInfo { _closureNameId = rootFunNameId, _closureRootName = rootFunName, _closureBuiltin = builtin, _closureMembers = take (length appArgs) (fType ^. cFunArgTypes), _closureFunType = fType, _closureCArity = patterns } ] <> closureArgs ) | otherwise -> return closureArgs _ -> impossible genClosureEnv :: ClosureInfo -> Declaration genClosureEnv c = typeDefWrap (asTypeDef name) ( DeclStructUnion ( StructUnion { _structUnionTag = StructTag, _structUnionName = Just name, _structMembers = Just (funDecl : members) } ) ) where name :: Text name = asEnv (closureNamedId c) funDecl :: Declaration funDecl = namedDeclType funField uIntPtrType members :: [Declaration] members = uncurry cDeclToNamedDecl <$> zip envArgs (c ^. closureMembers) genClosureApplySig :: ClosureInfo -> FunctionSig genClosureApplySig c = cFunTypeToFunSig (asApply (closureNamedId c)) applyFunType where nonEnvTyps :: [CDeclType] nonEnvTyps = drop (length (c ^. closureMembers)) (c ^. closureFunType . cFunArgTypes) allFunTyps :: [CDeclType] allFunTyps = declFunctionPtrType : nonEnvTyps applyFunType :: CFunType applyFunType = (c ^. closureFunType) {_cFunArgTypes = allFunTyps} genClosureApply :: ClosureInfo -> Function genClosureApply c = let localName :: Text localName = "env" localFunName :: Text localFunName = "f" name :: Text name = closureNamedId c envName :: Text envName = asTypeDef (asEnv name) closureEnvArgs :: [Text] closureEnvArgs = take (length (c ^. closureMembers)) envArgs closureEnvAccess :: [Expression] closureEnvAccess = memberAccess Pointer (ExpressionVar localName) <$> closureEnvArgs args :: [Expression] args = take (length (c ^. closureFunType . cFunArgTypes)) (closureEnvAccess <> drop 1 (ExpressionVar <$> funArgs)) nPatterns :: Int nPatterns = c ^. closureCArity patternArgs :: [Expression] patternArgs = take nPatterns args funType :: CFunType funType = (c ^. closureFunType) { _cFunArgTypes = drop nPatterns (c ^. closureFunType . cFunArgTypes) } localFunType :: CFunType localFunType = (c ^. closureFunType) { _cFunArgTypes = take nPatterns (c ^. closureFunType . cFunArgTypes) } funName :: Expression funName = ExpressionVar (c ^. closureRootName) funCall :: Expression funCall = if | null patternArgs -> funName | otherwise -> functionCallCasted localFunType funName patternArgs juvixFunCall :: [BodyItem] juvixFunCall = if | nPatterns < length args -> [ BodyDecl ( Declaration { _declType = declFunctionType, _declIsPtr = True, _declName = Just localFunName, _declInitializer = Just (ExprInitializer funCall) } ), BodyStatement . StatementReturn . Just $ juvixFunctionCall funType (ExpressionVar localFunName) (drop nPatterns args) ] | otherwise -> [ BodyStatement . StatementReturn . Just $ functionCallCasted (c ^. closureFunType) (ExpressionVar (closureRootFunction c)) args ] envArg :: BodyItem envArg = BodyDecl ( Declaration { _declType = DeclTypeDefType envName, _declIsPtr = True, _declName = Just localName, _declInitializer = Just $ ExprInitializer ( castToType ( CDeclType { _typeDeclType = DeclTypeDefType envName, _typeIsPtr = True } ) (ExpressionVar "fa0") ) } ) in Function { _funcSig = genClosureApplySig c, _funcBody = envArg : juvixFunCall } genClosureEval :: ClosureInfo -> Function genClosureEval c = let localName :: Text localName = "f" name :: Text name = closureNamedId c envName :: Text envName = asTypeDef (asEnv name) envArgToFunArg :: [(Text, Text)] envArgToFunArg = take (length (c ^. closureMembers)) (zip envArgs funArgs) assignments :: [Assign] assignments = mkAssign <$> envArgToFunArg mkAssign :: (Text, Text) -> Assign mkAssign (envArg, funArg) = Assign { _assignLeft = memberAccess Pointer (ExpressionVar localName) envArg, _assignRight = ExpressionVar funArg } in Function { _funcSig = FunctionSig { _funcReturnType = declFunctionType, _funcIsPtr = True, _funcQualifier = None, _funcName = asEval name, _funcArgs = namedArgs asFunArg (c ^. closureMembers) }, _funcBody = [ BodyDecl ( Declaration { _declType = DeclTypeDefType envName, _declIsPtr = True, _declName = Just localName, _declInitializer = Just $ ExprInitializer (mallocSizeOf envName) } ), BodyStatement ( StatementExpr ( ExpressionAssign ( Assign { _assignLeft = memberAccess Pointer (ExpressionVar localName) funField, _assignRight = castToType ( CDeclType { _typeDeclType = uIntPtrType, _typeIsPtr = False } ) (ExpressionVar (asApply name)) } ) ) ) ] <> (BodyStatement . StatementExpr . ExpressionAssign <$> assignments) <> [ returnStatement (castToType declFunctionPtrType (ExpressionVar localName)) ] } clauseClosures :: (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable] r) => [Micro.PolyType] -> Micro.FunctionClause -> Sem r [ClosureInfo] clauseClosures argTyps clause = do bindings <- buildPatternInfoTable argTyps clause runReader bindings (genClosureExpression argTyps (clause ^. Micro.clauseBody))
null
https://raw.githubusercontent.com/anoma/juvix/58a0f196da301ccf56e280ca4bd28abd35e0a75a/src/Juvix/Compiler/Backend/C/Data/Closure.hs
haskell
module Juvix.Compiler.Backend.C.Data.Closure where import Juvix.Compiler.Backend.C.Data.Base import Juvix.Compiler.Backend.C.Language import Juvix.Compiler.Concrete.Data.Builtins (IsBuiltin (toBuiltinPrim)) import Juvix.Compiler.Internal.Extra (mkPolyType') import Juvix.Compiler.Internal.Extra qualified as Micro import Juvix.Compiler.Internal.Translation.Extra qualified as Micro import Juvix.Compiler.Internal.Translation.FromInternal.Analysis.TypeChecking.Data.Context qualified as Micro import Juvix.Prelude genClosures :: forall r. (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable] r) => Micro.Module -> Sem r [CCode] genClosures Micro.Module {..} = do closureInfos <- concatMapM (applyOnFunStatement functionDefClosures) (_moduleBody ^. Micro.moduleStatements) return (genCClosure =<< nub closureInfos) genCClosure :: ClosureInfo -> [CCode] genCClosure c = [ ExternalDecl (genClosureEnv c), ExternalFunc (genClosureApply c), ExternalFunc (genClosureEval c) ] functionDefClosures :: (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable] r) => Micro.FunctionDef -> Sem r [ClosureInfo] functionDefClosures Micro.FunctionDef {..} = concatMapM (clauseClosures (fst (unfoldFunType (mkPolyType' _funDefType)))) (toList _funDefClauses) lookupBuiltinIden :: (Members '[Reader Micro.InfoTable] r) => Micro.Iden -> Sem r (Maybe Micro.BuiltinPrim) lookupBuiltinIden = \case Micro.IdenFunction f -> fmap toBuiltinPrim . (^. Micro.functionInfoDef . Micro.funDefBuiltin) <$> Micro.lookupFunction f Micro.IdenConstructor c -> fmap toBuiltinPrim . (^. Micro.constructorInfoBuiltin) <$> Micro.lookupConstructor c Micro.IdenAxiom a -> fmap toBuiltinPrim . (^. Micro.axiomInfoBuiltin) <$> Micro.lookupAxiom a Micro.IdenVar {} -> return Nothing Micro.IdenInductive {} -> impossible genClosureExpression :: forall r. (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable, Reader PatternInfoTable] r) => [Micro.PolyType] -> Micro.Expression -> Sem r [ClosureInfo] genClosureExpression funArgTyps = \case Micro.ExpressionLet {} -> error "To be implemented" Micro.ExpressionIden i -> do let rootFunMicroName = Micro.getName i rootFunNameId = rootFunMicroName ^. Micro.nameId rootFunName = mkName rootFunMicroName builtin <- lookupBuiltinIden i case i of Micro.IdenVar {} -> return [] _ -> do (t, patterns) <- getType i let argTyps = t ^. cFunArgTypes if | null argTyps -> return [] | otherwise -> return [ ClosureInfo { _closureNameId = rootFunNameId, _closureRootName = rootFunName, _closureBuiltin = builtin, _closureMembers = [], _closureFunType = t, _closureCArity = patterns } ] Micro.ExpressionApplication a -> exprApplication a Micro.ExpressionLiteral {} -> return [] Micro.ExpressionFunction {} -> impossible Micro.ExpressionHole {} -> impossible Micro.ExpressionUniverse {} -> impossible Micro.ExpressionSimpleLambda {} -> impossible Micro.ExpressionLambda {} -> impossible Micro.ExpressionCase {} -> impossible where exprApplication :: Micro.Application -> Sem r [ClosureInfo] exprApplication a = do (f0, appArgs) <- Micro.unfoldPolyApplication a if | null appArgs -> genClosureExpression funArgTyps f0 | otherwise -> case f0 of Micro.ExpressionLiteral {} -> return [] Micro.ExpressionIden f -> do let rootFunMicroName = Micro.getName f rootFunNameId = rootFunMicroName ^. Micro.nameId rootFunName = mkName rootFunMicroName builtin <- lookupBuiltinIden f (fType, patterns) <- getType f closureArgs <- concatMapM (genClosureExpression funArgTyps) (toList appArgs) if | length appArgs < length (fType ^. cFunArgTypes) -> return ( [ ClosureInfo { _closureNameId = rootFunNameId, _closureRootName = rootFunName, _closureBuiltin = builtin, _closureMembers = take (length appArgs) (fType ^. cFunArgTypes), _closureFunType = fType, _closureCArity = patterns } ] <> closureArgs ) | otherwise -> return closureArgs _ -> impossible genClosureEnv :: ClosureInfo -> Declaration genClosureEnv c = typeDefWrap (asTypeDef name) ( DeclStructUnion ( StructUnion { _structUnionTag = StructTag, _structUnionName = Just name, _structMembers = Just (funDecl : members) } ) ) where name :: Text name = asEnv (closureNamedId c) funDecl :: Declaration funDecl = namedDeclType funField uIntPtrType members :: [Declaration] members = uncurry cDeclToNamedDecl <$> zip envArgs (c ^. closureMembers) genClosureApplySig :: ClosureInfo -> FunctionSig genClosureApplySig c = cFunTypeToFunSig (asApply (closureNamedId c)) applyFunType where nonEnvTyps :: [CDeclType] nonEnvTyps = drop (length (c ^. closureMembers)) (c ^. closureFunType . cFunArgTypes) allFunTyps :: [CDeclType] allFunTyps = declFunctionPtrType : nonEnvTyps applyFunType :: CFunType applyFunType = (c ^. closureFunType) {_cFunArgTypes = allFunTyps} genClosureApply :: ClosureInfo -> Function genClosureApply c = let localName :: Text localName = "env" localFunName :: Text localFunName = "f" name :: Text name = closureNamedId c envName :: Text envName = asTypeDef (asEnv name) closureEnvArgs :: [Text] closureEnvArgs = take (length (c ^. closureMembers)) envArgs closureEnvAccess :: [Expression] closureEnvAccess = memberAccess Pointer (ExpressionVar localName) <$> closureEnvArgs args :: [Expression] args = take (length (c ^. closureFunType . cFunArgTypes)) (closureEnvAccess <> drop 1 (ExpressionVar <$> funArgs)) nPatterns :: Int nPatterns = c ^. closureCArity patternArgs :: [Expression] patternArgs = take nPatterns args funType :: CFunType funType = (c ^. closureFunType) { _cFunArgTypes = drop nPatterns (c ^. closureFunType . cFunArgTypes) } localFunType :: CFunType localFunType = (c ^. closureFunType) { _cFunArgTypes = take nPatterns (c ^. closureFunType . cFunArgTypes) } funName :: Expression funName = ExpressionVar (c ^. closureRootName) funCall :: Expression funCall = if | null patternArgs -> funName | otherwise -> functionCallCasted localFunType funName patternArgs juvixFunCall :: [BodyItem] juvixFunCall = if | nPatterns < length args -> [ BodyDecl ( Declaration { _declType = declFunctionType, _declIsPtr = True, _declName = Just localFunName, _declInitializer = Just (ExprInitializer funCall) } ), BodyStatement . StatementReturn . Just $ juvixFunctionCall funType (ExpressionVar localFunName) (drop nPatterns args) ] | otherwise -> [ BodyStatement . StatementReturn . Just $ functionCallCasted (c ^. closureFunType) (ExpressionVar (closureRootFunction c)) args ] envArg :: BodyItem envArg = BodyDecl ( Declaration { _declType = DeclTypeDefType envName, _declIsPtr = True, _declName = Just localName, _declInitializer = Just $ ExprInitializer ( castToType ( CDeclType { _typeDeclType = DeclTypeDefType envName, _typeIsPtr = True } ) (ExpressionVar "fa0") ) } ) in Function { _funcSig = genClosureApplySig c, _funcBody = envArg : juvixFunCall } genClosureEval :: ClosureInfo -> Function genClosureEval c = let localName :: Text localName = "f" name :: Text name = closureNamedId c envName :: Text envName = asTypeDef (asEnv name) envArgToFunArg :: [(Text, Text)] envArgToFunArg = take (length (c ^. closureMembers)) (zip envArgs funArgs) assignments :: [Assign] assignments = mkAssign <$> envArgToFunArg mkAssign :: (Text, Text) -> Assign mkAssign (envArg, funArg) = Assign { _assignLeft = memberAccess Pointer (ExpressionVar localName) envArg, _assignRight = ExpressionVar funArg } in Function { _funcSig = FunctionSig { _funcReturnType = declFunctionType, _funcIsPtr = True, _funcQualifier = None, _funcName = asEval name, _funcArgs = namedArgs asFunArg (c ^. closureMembers) }, _funcBody = [ BodyDecl ( Declaration { _declType = DeclTypeDefType envName, _declIsPtr = True, _declName = Just localName, _declInitializer = Just $ ExprInitializer (mallocSizeOf envName) } ), BodyStatement ( StatementExpr ( ExpressionAssign ( Assign { _assignLeft = memberAccess Pointer (ExpressionVar localName) funField, _assignRight = castToType ( CDeclType { _typeDeclType = uIntPtrType, _typeIsPtr = False } ) (ExpressionVar (asApply name)) } ) ) ) ] <> (BodyStatement . StatementExpr . ExpressionAssign <$> assignments) <> [ returnStatement (castToType declFunctionPtrType (ExpressionVar localName)) ] } clauseClosures :: (Members '[Reader Micro.InfoTable, Reader Micro.TypesTable] r) => [Micro.PolyType] -> Micro.FunctionClause -> Sem r [ClosureInfo] clauseClosures argTyps clause = do bindings <- buildPatternInfoTable argTyps clause runReader bindings (genClosureExpression argTyps (clause ^. Micro.clauseBody))
db442fe71a7b4b1fd5a8f1634699da30b285212ec2764f2c61feb5c103758772
thepower/tpnode
tpic2.erl
-module(tpic2). -export([childspec/0,certificate/0,cert/2,extract_cert_info/1, verfun/3, node_addresses/0, alloc_id/0]). -export([peers/0,peerstreams/0,cast/2,cast/3,call/2,call/3,cast_prepare/1]). -include_lib("public_key/include/public_key.hrl"). -include("include/tplog.hrl"). alloc_id() -> Node=nodekey:node_id(), N=erlang:phash2(Node,16#ffff), Req=case get(tpic_req) of undefined -> 0; I when is_integer(I) -> I end, PID=erlang:phash2({self(),Req bsr 24},16#ffffff), put(tpic_req,Req+1), <<N:16/big,PID:24/big,Req:24/big>>. broadcast(ReqID, Stream, Srv, Data, Opts) -> case whereis(tpic2_cmgr) of undefined -> tpic_not_started; _ -> tpic2_cmgr:inc_usage(Stream, Srv), maps:fold( fun(PubKey,Pid,Acc) -> Avail=lists:keysort(2,gen_server:call(Pid, {get_stream, Stream})), case Avail of [{_,_,ConnPID}|_] when is_pid(ConnPID) -> case lists:member(async, Opts) of true -> case erlang:is_process_alive(ConnPID) of true -> gen_server:cast(ConnPID,{send, Srv, ReqID, Data}), [PubKey|Acc]; false -> Acc end; false -> case gen_server:call(ConnPID,{send, Srv, ReqID, Data}) of ok -> [PubKey|Acc]; _ -> Acc end end; _ -> Acc end end, [], tpic2_cmgr:peers()) end. unicast(ReqID, Peer, Stream, Srv, Data, Opts) -> case whereis(tpic2_cmgr) of undefined -> tpic_not_started; _ -> tpic2_cmgr:inc_usage(Stream, Srv), Avail=lists:keysort(2,tpic2_cmgr:send(Peer,{get_stream, Stream})), case Avail of [{_,_,ConnPID}|_] when is_pid(ConnPID) -> case lists:member(async, Opts) of true -> case erlang:is_process_alive(ConnPID) of true -> gen_server:cast(ConnPID,{send, Srv, ReqID, Data}), tpic2_cmgr:add_trans(ReqID, self()), [Peer]; false -> [] end; false -> case gen_server:call(ConnPID,{send, Srv, ReqID, Data}) of ok -> tpic2_cmgr:add_trans(ReqID, self()), [Peer]; _ -> [] end end; _ -> [] end end. cast_prepare(Stream) -> ReqID=alloc_id(), maps:fold( fun(PubKey,Pid,Acc) -> Avail=lists:keysort(2,gen_server:call(Pid, {get_stream, Stream})), case Avail of [{_,_,ConnPID}|_] when is_pid(ConnPID) -> case erlang:is_process_alive(ConnPID) of true -> [{PubKey,Stream,ReqID}|Acc]; false -> Acc end; _ -> Acc end end, [], tpic2_cmgr:peers()). cast(Dat, Data) -> cast(Dat, Data, []). cast({Peer,Stream,ReqID}, Data, Opts) when is_atom(Stream) -> cast({Peer,atom_to_binary(Stream,latin1),ReqID}, Data, Opts); cast({Peer,Stream,ReqID}, Data, Opts) -> {Srv, Msg} = case Data of {S1,M1} when is_binary(S1), is_binary(M1) -> {S1, M1}; M when is_binary(M) -> {<<>>, M} end, unicast(ReqID, Peer, Stream, Srv, Msg, Opts); cast(Service, Data, Opts) when is_binary(Service); Service==0 -> {Srv, Msg} = case Data of {S1,M1} when is_binary(S1), is_binary(M1) -> {S1, M1}; M when is_binary(M) -> {<<>>, M} end, ReqID=alloc_id(), SentTo=broadcast(ReqID, Service, Srv, Msg, Opts), if SentTo==[] -> SentTo; true -> case whereis(tpic2_cmgr) of undefined -> tpic_not_started; _ -> tpic2_cmgr:add_trans(ReqID, self()) end, SentTo end. call(Conn, Request) -> call(Conn, Request, 2000). call(Service, Request, Timeout) when is_binary(Service); Service==0 -> R=cast(Service, Request), T2=erlang:system_time(millisecond)+Timeout, lists:reverse(wait_response(T2,R,[])); call(Conn, Request, Timeout) when is_tuple(Conn) -> R=cast(Conn, Request), T2=erlang:system_time(millisecond)+Timeout, lists:reverse(wait_response(T2,R,[])). wait_response(_Until,[],Acc) -> Acc; wait_response(Until,[NodeID|RR],Acc) -> ?LOG_DEBUG("Waiting for reply",[]), T1=Until-erlang:system_time(millisecond), T=if(T1>0) -> T1; true -> 0 end, receive {'$gen_cast',{tpic,{NodeID,_,_}=R1,A}} -> ?LOG_DEBUG("Got reply from ~p",[R1]), wait_response(Until,RR,[{R1,A}|Acc]) after T -> wait_response(Until,RR,Acc) end. peers() -> Raw=gen_server:call(tpic2_cmgr,peers), maps:fold( fun(_,V,Acc) -> [gen_server:call(V,info)|Acc] end, [], Raw). peerstreams() -> Raw=gen_server:call(tpic2_cmgr,peers), maps:fold( fun(_,V,Acc) -> [begin PI=gen_server:call(V,info), maps:put( streams, [ {SID, Dir, Pid, gen_server:call(Pid, peer)} || {SID, Dir, Pid} <- maps:get(streams,PI), is_pid(Pid), is_process_alive(Pid) ], maps:with([authdata],PI) ) end|Acc] end, [], Raw). certificate() -> Priv=nodekey:get_priv(), DERKey=tpecdsa:export(Priv,der), Cert=cert(Priv, nodekey:node_name(iolist_to_binary(net_adm:localhost())) ), [{'Certificate',DerCert,not_encrypted}]=public_key:pem_decode(Cert), [ {verify, verify_peer}, {cert, DerCert}, {cacerts, [DerCert]}, {verify_fun, {fun tpic2:verfun/3, []}}, {fail_if_no_peer_cert, true}, % {key, {'ECPrivateKey', DERKey}} {key, {'PrivateKeyInfo', DERKey}} ]. childspec() -> Cfg=application:get_env(tpnode,tpic,#{}), Port=maps:get(port,Cfg,40000), HTTPOpts = fun(E) -> #{ connection_type => supervisor, socket_opts => [{port,Port}, {next_protocols_advertised, [<<"tpic2">>]}, {alpn_preferred_protocols, [<<"tpic2">>]} ] ++ E ++ certificate() } end, tpic2_client:childspec() ++ [ {tpic2_cmgr, {tpic2_cmgr,start_link, []}, permanent,20000,worker,[] }, ranch:child_spec( tpic_tls, ranch_ssl, HTTPOpts([]), tpic2_tls, #{} ), ranch:child_spec( tpic_tls6, ranch_ssl, HTTPOpts([inet6, {ipv6_v6only, true}]), tpic2_tls, #{} ) ]. node_addresses() -> {ok,IA}=inet:getifaddrs(), AllowLocal=maps:get(allow_localip,application:get_env(tpnode,tpic,#{}),false)==true, TPICAddr=[ list_to_binary(A) || #{address:=A,proto:=tpic} <- maps:get(addresses,application:get_env(tpnode,discovery,#{}),[]) ], lists:foldl( fun({_IFName,Attrs},Acc) -> Flags=proplists:get_value(flags,Attrs,[]), case not lists:member(loopback,Flags) andalso lists:member(running,Flags) of false -> Acc; true -> lists:foldl( fun({addr, {65152,_,_,_,_,_,_,_}}, Acc1) -> Acc1; ({addr, {192,168,_,_}}, Acc1) when (not AllowLocal) -> Acc1; ({addr, {172,SixTeenToThirdtyOne,_,_}}, Acc1) when (not AllowLocal) andalso SixTeenToThirdtyOne >= 16 andalso SixTeenToThirdtyOne < 31 -> Acc1; ({addr, {10,_,_,_}}, Acc1) when not AllowLocal -> Acc1; ({addr, ADDR}, Acc1) -> [list_to_binary(inet:ntoa(ADDR)) | Acc1]; (_,Acc1) -> Acc1 end, Acc, Attrs) end end, TPICAddr, IA). cert(Key, Subject) -> Env=application:get_env(tpnode,tpic,#{}), OpenSSL=maps:get(openssl,Env,os:find_executable("openssl")), H=erlang:open_port( {spawn_executable, OpenSSL}, [{args, [ "req", "-new", "-x509", "-key", "/dev/stdin", "-days", "366", "-nodes", "-subj", "/CN="++binary_to_list(Subject) ]}, eof, binary, stderr_to_stdout ]), PrivKey=tpecdsa:export(Key,pem), H ! {self(), {command, <<PrivKey/binary,"\n">>}}, Res=cert_loop(H), erlang:port_close(H), Res. cert_loop(Handle) -> receive {Handle, {data, Msg}} -> <<Msg/binary,(cert_loop(Handle))/binary>>; {Handle, eof} -> <<>> after 10000 -> throw("Cant get certificate from openssl") end. extract_cert_info( #'OTPCertificate'{ tbsCertificate=#'OTPTBSCertificate'{ % version = asn1_DEFAULT, % serialNumber, % signature, % issuer, % validity, subject={rdnSequence,[Subj|_]}, subjectPublicKeyInfo=#'OTPSubjectPublicKeyInfo'{ algorithm=PubKeyAlgo, subjectPublicKey={'ECPoint',RawPK}=_PubKey } issuerUniqueID = asn1_NOVALUE , subjectUniqueID = asn1_NOVALUE , extensions = asn1_NOVALUE }=_CertBody signatureAlgorithm = SigAlgo , % signature=Signature }) -> #'PublicKeyAlgorithm'{algorithm = Algo} = PubKeyAlgo, #{ subj=>lists:keyfind(?'id-at-commonName',2,Subj), pubkey=>tpecdsa:wrap_pubkey(RawPK, Algo), keyalgo=>PubKeyAlgo }. verfun(PCert,{bad_cert, _} = Reason, _) -> ?LOG_DEBUG("Peer Cert ~p: ~p~n",[Reason,extract_cert_info(PCert)]), {valid, Reason}; verfun(_, Reason, _) -> ?LOG_NOTICE("Bad cert. Reason ~p~n",[Reason]), {fail, unknown}.
null
https://raw.githubusercontent.com/thepower/tpnode/211eab8b35253057f69db3d1e10e68c2aa92aac8/apps/tpic2/src/tpic2.erl
erlang
{key, {'ECPrivateKey', DERKey}} version = asn1_DEFAULT, serialNumber, signature, issuer, validity, signature=Signature
-module(tpic2). -export([childspec/0,certificate/0,cert/2,extract_cert_info/1, verfun/3, node_addresses/0, alloc_id/0]). -export([peers/0,peerstreams/0,cast/2,cast/3,call/2,call/3,cast_prepare/1]). -include_lib("public_key/include/public_key.hrl"). -include("include/tplog.hrl"). alloc_id() -> Node=nodekey:node_id(), N=erlang:phash2(Node,16#ffff), Req=case get(tpic_req) of undefined -> 0; I when is_integer(I) -> I end, PID=erlang:phash2({self(),Req bsr 24},16#ffffff), put(tpic_req,Req+1), <<N:16/big,PID:24/big,Req:24/big>>. broadcast(ReqID, Stream, Srv, Data, Opts) -> case whereis(tpic2_cmgr) of undefined -> tpic_not_started; _ -> tpic2_cmgr:inc_usage(Stream, Srv), maps:fold( fun(PubKey,Pid,Acc) -> Avail=lists:keysort(2,gen_server:call(Pid, {get_stream, Stream})), case Avail of [{_,_,ConnPID}|_] when is_pid(ConnPID) -> case lists:member(async, Opts) of true -> case erlang:is_process_alive(ConnPID) of true -> gen_server:cast(ConnPID,{send, Srv, ReqID, Data}), [PubKey|Acc]; false -> Acc end; false -> case gen_server:call(ConnPID,{send, Srv, ReqID, Data}) of ok -> [PubKey|Acc]; _ -> Acc end end; _ -> Acc end end, [], tpic2_cmgr:peers()) end. unicast(ReqID, Peer, Stream, Srv, Data, Opts) -> case whereis(tpic2_cmgr) of undefined -> tpic_not_started; _ -> tpic2_cmgr:inc_usage(Stream, Srv), Avail=lists:keysort(2,tpic2_cmgr:send(Peer,{get_stream, Stream})), case Avail of [{_,_,ConnPID}|_] when is_pid(ConnPID) -> case lists:member(async, Opts) of true -> case erlang:is_process_alive(ConnPID) of true -> gen_server:cast(ConnPID,{send, Srv, ReqID, Data}), tpic2_cmgr:add_trans(ReqID, self()), [Peer]; false -> [] end; false -> case gen_server:call(ConnPID,{send, Srv, ReqID, Data}) of ok -> tpic2_cmgr:add_trans(ReqID, self()), [Peer]; _ -> [] end end; _ -> [] end end. cast_prepare(Stream) -> ReqID=alloc_id(), maps:fold( fun(PubKey,Pid,Acc) -> Avail=lists:keysort(2,gen_server:call(Pid, {get_stream, Stream})), case Avail of [{_,_,ConnPID}|_] when is_pid(ConnPID) -> case erlang:is_process_alive(ConnPID) of true -> [{PubKey,Stream,ReqID}|Acc]; false -> Acc end; _ -> Acc end end, [], tpic2_cmgr:peers()). cast(Dat, Data) -> cast(Dat, Data, []). cast({Peer,Stream,ReqID}, Data, Opts) when is_atom(Stream) -> cast({Peer,atom_to_binary(Stream,latin1),ReqID}, Data, Opts); cast({Peer,Stream,ReqID}, Data, Opts) -> {Srv, Msg} = case Data of {S1,M1} when is_binary(S1), is_binary(M1) -> {S1, M1}; M when is_binary(M) -> {<<>>, M} end, unicast(ReqID, Peer, Stream, Srv, Msg, Opts); cast(Service, Data, Opts) when is_binary(Service); Service==0 -> {Srv, Msg} = case Data of {S1,M1} when is_binary(S1), is_binary(M1) -> {S1, M1}; M when is_binary(M) -> {<<>>, M} end, ReqID=alloc_id(), SentTo=broadcast(ReqID, Service, Srv, Msg, Opts), if SentTo==[] -> SentTo; true -> case whereis(tpic2_cmgr) of undefined -> tpic_not_started; _ -> tpic2_cmgr:add_trans(ReqID, self()) end, SentTo end. call(Conn, Request) -> call(Conn, Request, 2000). call(Service, Request, Timeout) when is_binary(Service); Service==0 -> R=cast(Service, Request), T2=erlang:system_time(millisecond)+Timeout, lists:reverse(wait_response(T2,R,[])); call(Conn, Request, Timeout) when is_tuple(Conn) -> R=cast(Conn, Request), T2=erlang:system_time(millisecond)+Timeout, lists:reverse(wait_response(T2,R,[])). wait_response(_Until,[],Acc) -> Acc; wait_response(Until,[NodeID|RR],Acc) -> ?LOG_DEBUG("Waiting for reply",[]), T1=Until-erlang:system_time(millisecond), T=if(T1>0) -> T1; true -> 0 end, receive {'$gen_cast',{tpic,{NodeID,_,_}=R1,A}} -> ?LOG_DEBUG("Got reply from ~p",[R1]), wait_response(Until,RR,[{R1,A}|Acc]) after T -> wait_response(Until,RR,Acc) end. peers() -> Raw=gen_server:call(tpic2_cmgr,peers), maps:fold( fun(_,V,Acc) -> [gen_server:call(V,info)|Acc] end, [], Raw). peerstreams() -> Raw=gen_server:call(tpic2_cmgr,peers), maps:fold( fun(_,V,Acc) -> [begin PI=gen_server:call(V,info), maps:put( streams, [ {SID, Dir, Pid, gen_server:call(Pid, peer)} || {SID, Dir, Pid} <- maps:get(streams,PI), is_pid(Pid), is_process_alive(Pid) ], maps:with([authdata],PI) ) end|Acc] end, [], Raw). certificate() -> Priv=nodekey:get_priv(), DERKey=tpecdsa:export(Priv,der), Cert=cert(Priv, nodekey:node_name(iolist_to_binary(net_adm:localhost())) ), [{'Certificate',DerCert,not_encrypted}]=public_key:pem_decode(Cert), [ {verify, verify_peer}, {cert, DerCert}, {cacerts, [DerCert]}, {verify_fun, {fun tpic2:verfun/3, []}}, {fail_if_no_peer_cert, true}, {key, {'PrivateKeyInfo', DERKey}} ]. childspec() -> Cfg=application:get_env(tpnode,tpic,#{}), Port=maps:get(port,Cfg,40000), HTTPOpts = fun(E) -> #{ connection_type => supervisor, socket_opts => [{port,Port}, {next_protocols_advertised, [<<"tpic2">>]}, {alpn_preferred_protocols, [<<"tpic2">>]} ] ++ E ++ certificate() } end, tpic2_client:childspec() ++ [ {tpic2_cmgr, {tpic2_cmgr,start_link, []}, permanent,20000,worker,[] }, ranch:child_spec( tpic_tls, ranch_ssl, HTTPOpts([]), tpic2_tls, #{} ), ranch:child_spec( tpic_tls6, ranch_ssl, HTTPOpts([inet6, {ipv6_v6only, true}]), tpic2_tls, #{} ) ]. node_addresses() -> {ok,IA}=inet:getifaddrs(), AllowLocal=maps:get(allow_localip,application:get_env(tpnode,tpic,#{}),false)==true, TPICAddr=[ list_to_binary(A) || #{address:=A,proto:=tpic} <- maps:get(addresses,application:get_env(tpnode,discovery,#{}),[]) ], lists:foldl( fun({_IFName,Attrs},Acc) -> Flags=proplists:get_value(flags,Attrs,[]), case not lists:member(loopback,Flags) andalso lists:member(running,Flags) of false -> Acc; true -> lists:foldl( fun({addr, {65152,_,_,_,_,_,_,_}}, Acc1) -> Acc1; ({addr, {192,168,_,_}}, Acc1) when (not AllowLocal) -> Acc1; ({addr, {172,SixTeenToThirdtyOne,_,_}}, Acc1) when (not AllowLocal) andalso SixTeenToThirdtyOne >= 16 andalso SixTeenToThirdtyOne < 31 -> Acc1; ({addr, {10,_,_,_}}, Acc1) when not AllowLocal -> Acc1; ({addr, ADDR}, Acc1) -> [list_to_binary(inet:ntoa(ADDR)) | Acc1]; (_,Acc1) -> Acc1 end, Acc, Attrs) end end, TPICAddr, IA). cert(Key, Subject) -> Env=application:get_env(tpnode,tpic,#{}), OpenSSL=maps:get(openssl,Env,os:find_executable("openssl")), H=erlang:open_port( {spawn_executable, OpenSSL}, [{args, [ "req", "-new", "-x509", "-key", "/dev/stdin", "-days", "366", "-nodes", "-subj", "/CN="++binary_to_list(Subject) ]}, eof, binary, stderr_to_stdout ]), PrivKey=tpecdsa:export(Key,pem), H ! {self(), {command, <<PrivKey/binary,"\n">>}}, Res=cert_loop(H), erlang:port_close(H), Res. cert_loop(Handle) -> receive {Handle, {data, Msg}} -> <<Msg/binary,(cert_loop(Handle))/binary>>; {Handle, eof} -> <<>> after 10000 -> throw("Cant get certificate from openssl") end. extract_cert_info( #'OTPCertificate'{ tbsCertificate=#'OTPTBSCertificate'{ subject={rdnSequence,[Subj|_]}, subjectPublicKeyInfo=#'OTPSubjectPublicKeyInfo'{ algorithm=PubKeyAlgo, subjectPublicKey={'ECPoint',RawPK}=_PubKey } issuerUniqueID = asn1_NOVALUE , subjectUniqueID = asn1_NOVALUE , extensions = asn1_NOVALUE }=_CertBody signatureAlgorithm = SigAlgo , }) -> #'PublicKeyAlgorithm'{algorithm = Algo} = PubKeyAlgo, #{ subj=>lists:keyfind(?'id-at-commonName',2,Subj), pubkey=>tpecdsa:wrap_pubkey(RawPK, Algo), keyalgo=>PubKeyAlgo }. verfun(PCert,{bad_cert, _} = Reason, _) -> ?LOG_DEBUG("Peer Cert ~p: ~p~n",[Reason,extract_cert_info(PCert)]), {valid, Reason}; verfun(_, Reason, _) -> ?LOG_NOTICE("Bad cert. Reason ~p~n",[Reason]), {fail, unknown}.
15a6afde8fd035b089db48e2654f4718f68fd0e9795fed80d2a9bfaf310e8169
mcna/usocket
usocket.lisp
$ I d : usocket.lisp 680 2012 - 01 - 20 23:38:00Z hhubner $ ;;;; $URL: svn-lisp.net/project/usocket/svn/usocket/tags/0.6.0.1/usocket.lisp $ ;;;; See LICENSE for licensing information. (in-package :usocket) (defparameter *wildcard-host* #(0 0 0 0) "Hostname to pass when all interfaces in the current system are to be bound.") (defparameter *auto-port* 0 "Port number to pass when an auto-assigned port number is wanted.") (defconstant +max-datagram-packet-size+ 65507 "The theoretical maximum amount of data in a UDP datagram. The IPv4 UDP packets have a 16-bit length constraint, and IP+UDP header has 28-byte. IP_MAXPACKET = 65535, /* netinet/ip.h */ sizeof(struct ip) = 20, /* netinet/ip.h */ sizeof(struct udphdr) = 8, /* netinet/udp.h */ 65535 - 20 - 8 = 65507 (But for UDP broadcast, the maximum message size is limited by the MTU size of the underlying link)") (defclass usocket () ((socket :initarg :socket :accessor socket :documentation "Implementation specific socket object instance.'") (wait-list :initform nil :accessor wait-list :documentation "WAIT-LIST the object is associated with.") (state :initform nil :accessor state :documentation "Per-socket return value for the `wait-for-input' function. The value stored in this slot can be any of NIL - not ready :READ - ready to read :READ-WRITE - ready to read and write :WRITE - ready to write The last two remain unused in the current version. ") #+(and win32 (or sbcl ecl lispworks)) (%ready-p :initform nil :accessor %ready-p :documentation "Indicates whether the socket has been signalled as ready for reading a new connection. The value will be set to T by `wait-for-input-internal' (given the right conditions) and reset to NIL by `socket-accept'. Don't modify this slot or depend on it as it is really intended to be internal only. Note: Accessed, but not used for 'stream-usocket'. " )) (:documentation "The main socket class. Sockets should be closed using the `socket-close' method.")) (defclass stream-usocket (usocket) ((stream :initarg :stream :accessor socket-stream :documentation "Stream instance associated with the socket." ;; ;;Iff an external-format was passed to `socket-connect' or `socket-listen' ;;the stream is a flexi-stream. Otherwise the stream is implementation ;;specific." )) (:documentation "Stream socket class. ' Contrary to other sockets, these sockets may be closed either with the `socket-close' method or by closing the associated stream (which can be retrieved with the `socket-stream' accessor).")) (defclass stream-server-usocket (usocket) ((element-type :initarg :element-type :initform #-lispworks 'character #+lispworks 'base-char :reader element-type :documentation "Default element type for streams created by `socket-accept'.")) (:documentation "Socket which listens for stream connections to be initiated from remote sockets.")) (defclass datagram-usocket (usocket) ((connected-p :type boolean :accessor connected-p :initarg :connected-p) #+(or cmu scl lispworks (and clisp ffi (not rawsock))) (%open-p :type boolean :accessor %open-p :initform t :documentation "Flag to indicate if usocket is open, for GC on implementions operate on raw socket fd.") #+(or lispworks (and clisp ffi (not rawsock))) (recv-buffer :documentation "Private RECV buffer.") #+lispworks (send-buffer :documentation "Private SEND buffer.")) (:documentation "UDP (inet-datagram) socket")) (defun usocket-p (socket) (typep socket 'usocket)) (defun stream-usocket-p (socket) (typep socket 'stream-usocket)) (defun stream-server-usocket-p (socket) (typep socket 'stream-server-usocket)) (defun datagram-usocket-p (socket) (typep socket 'datagram-usocket)) (defun make-socket (&key socket) "Create a usocket socket type from implementation specific socket." (unless socket (error 'invalid-socket)) (make-stream-socket :socket socket)) (defun make-stream-socket (&key socket stream) "Create a usocket socket type from implementation specific socket and stream objects. Sockets returned should be closed using the `socket-close' method or by closing the stream associated with the socket. " (unless socket (error 'invalid-socket-error)) (unless stream (error 'invalid-socket-stream-error)) (make-instance 'stream-usocket :socket socket :stream stream)) (defun make-stream-server-socket (socket &key (element-type #-lispworks 'character #+lispworks 'base-char)) "Create a usocket-server socket type from an implementation-specific socket object. The returned value is a subtype of `stream-server-usocket'. " (unless socket (error 'invalid-socket-error)) (make-instance 'stream-server-usocket :socket socket :element-type element-type)) (defun make-datagram-socket (socket &key connected-p) (unless socket (error 'invalid-socket-error)) (make-instance 'datagram-usocket :socket socket :connected-p connected-p)) (defgeneric socket-accept (socket &key element-type) (:documentation "Accepts a connection from `socket', returning a `stream-socket'. The stream associated with the socket returned has `element-type' when explicitly specified, or the element-type passed to `socket-listen' otherwise.")) (defgeneric socket-close (usocket) (:documentation "Close a previously opened `usocket'.")) (defgeneric socket-send (usocket buffer length &key host port) (:documentation "Send packets through a previously opend `usocket'.")) (defgeneric socket-receive (usocket buffer length &key) (:documentation "Receive packets from a previously opend `usocket'. Returns 4 values: (values buffer size host port)")) (defgeneric get-local-address (socket) (:documentation "Returns the IP address of the socket.")) (defgeneric get-peer-address (socket) (:documentation "Returns the IP address of the peer the socket is connected to.")) (defgeneric get-local-port (socket) (:documentation "Returns the IP port of the socket. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-port (socket) (:documentation "Returns the IP port of the peer the socket to.")) (defgeneric get-local-name (socket) (:documentation "Returns the IP address and port of the socket as values. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-name (socket) (:documentation "Returns the IP address and port of the peer the socket is connected to as values.")) (defmacro with-connected-socket ((var socket) &body body) "Bind `socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(let ((,var ,socket)) (unwind-protect (when ,var (with-mapped-conditions (,var) ,@body)) (when ,var (socket-close ,var))))) (defmacro with-client-socket ((socket-var stream-var &rest socket-connect-args) &body body) "Bind the socket resulting from a call to `socket-connect' with the arguments `socket-connect-args' to `socket-var' and if `stream-var' is non-nil, bind the associated socket stream to it." `(with-connected-socket (,socket-var (socket-connect ,@socket-connect-args)) ,(if (null stream-var) `(progn ,@body) `(let ((,stream-var (socket-stream ,socket-var))) ,@body)))) (defmacro with-server-socket ((var server-socket) &body body) "Bind `server-socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(with-connected-socket (,var ,server-socket) ,@body)) (defmacro with-socket-listener ((socket-var &rest socket-listen-args) &body body) "Bind the socket resulting from a call to `socket-listen' with arguments `socket-listen-args' to `socket-var'." `(with-server-socket (,socket-var (socket-listen ,@socket-listen-args)) ,@body)) (defstruct (wait-list (:constructor %make-wait-list)) %wait ;; implementation specific waiters ;; the list of all usockets map) ;; maps implementation sockets to usockets ;; Implementation specific: ;; ;; %setup-wait-list ;; %add-waiter ;; %remove-waiter (defun make-wait-list (waiters) (let ((wl (%make-wait-list))) (setf (wait-list-map wl) (make-hash-table)) (%setup-wait-list wl) (dolist (x waiters wl) (add-waiter wl x)))) (defun add-waiter (wait-list input) (setf (gethash (socket input) (wait-list-map wait-list)) input (wait-list input) wait-list) (pushnew input (wait-list-waiters wait-list)) (%add-waiter wait-list input)) (defun remove-waiter (wait-list input) (%remove-waiter wait-list input) (setf (wait-list-waiters wait-list) (remove input (wait-list-waiters wait-list)) (wait-list input) nil) (remhash (socket input) (wait-list-map wait-list))) (defun remove-all-waiters (wait-list) (dolist (waiter (wait-list-waiters wait-list)) (%remove-waiter wait-list waiter)) (setf (wait-list-waiters wait-list) nil) (clrhash (wait-list-map wait-list))) (defun wait-for-input (socket-or-sockets &key timeout ready-only) "Waits for one or more streams to become ready for reading from the socket. When `timeout' (a non-negative real number) is specified, wait `timeout' seconds, or wait indefinitely when it isn't specified. A `timeout' value of 0 (zero) means polling. Returns two values: the first value is the list of streams which are readable (or in case of server streams acceptable). NIL may be returned for this value either when waiting timed out or when it was interrupted (EINTR). The second value is a real number indicating the time remaining within the timeout period or NIL if none. Without the READY-ONLY arg, WAIT-FOR-INPUT will return all sockets in the original list you passed it. This prevents a new list from being consed up. Some users of USOCKET were reluctant to use it if it wouldn't behave that way, expecting it to cost significant performance to do the associated garbage collection. Without the READY-ONLY arg, you need to check the socket STATE slot for the values documented in usocket.lisp in the usocket class." (unless (wait-list-p socket-or-sockets) (let ((wl (make-wait-list (if (listp socket-or-sockets) socket-or-sockets (list socket-or-sockets))))) (multiple-value-bind (socks to) (wait-for-input wl :timeout timeout :ready-only ready-only) (return-from wait-for-input (values (if ready-only socks socket-or-sockets) to))))) (let* ((start (get-internal-real-time)) (sockets-ready 0)) (dolist (x (wait-list-waiters socket-or-sockets)) (when (setf (state x) #+(and win32 (or sbcl ecl)) nil ; they cannot rely on LISTEN #-(and win32 (or sbcl ecl)) (if (and (stream-usocket-p x) (listen (socket-stream x))) :read nil)) (incf sockets-ready))) ;; the internal routine is responsibe for ;; making sure the wait doesn't block on socket-streams of ;; which theready- socket isn't ready, but there's space left in the ;; buffer (wait-for-input-internal socket-or-sockets :timeout (if (zerop sockets-ready) timeout 0)) (let ((to-result (when timeout (let ((elapsed (/ (- (get-internal-real-time) start) internal-time-units-per-second))) (when (< elapsed timeout) (- timeout elapsed)))))) (values (if ready-only (remove-if #'null (wait-list-waiters socket-or-sockets) :key #'state) socket-or-sockets) to-result)))) ;; ;; Data utility functions ;; (defun integer-to-octet-buffer (integer buffer octets &key (start 0)) (do ((b start (1+ b)) * 8 (- i 8))) ((> 0 i) buffer) (setf (aref buffer b) (ldb (byte 8 i) integer)))) (defun octet-buffer-to-integer (buffer octets &key (start 0)) (let ((integer 0)) (do ((b start (1+ b)) * 8 (- i 8))) ((> 0 i) integer) (setf (ldb (byte 8 i) integer) (aref buffer b))))) (defmacro port-to-octet-buffer (port buffer &key (start 0)) `(integer-to-octet-buffer ,port ,buffer 2 :start ,start)) (defmacro ip-to-octet-buffer (ip buffer &key (start 0)) `(integer-to-octet-buffer (host-byte-order ,ip) ,buffer 4 :start ,start)) (defmacro port-from-octet-buffer (buffer &key (start 0)) `(octet-buffer-to-integer ,buffer 2 :start ,start)) (defmacro ip-from-octet-buffer (buffer &key (start 0)) `(octet-buffer-to-integer ,buffer 4 :start ,start)) ;; IP(v4 ) utility functions ;; (defun list-of-strings-to-integers (list) "Take a list of strings and return a new list of integers (from parse-integer) on each of the string elements." (let ((new-list nil)) (dolist (element (reverse list)) (push (parse-integer element) new-list)) new-list)) (defun ip-address-string-p (string) "Return a true value if the given string could be an IP address." (every (lambda (char) (or (digit-char-p char) (eql char #\.))) string)) (defun hbo-to-dotted-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (format nil "~A.~A.~A.~A" first second third fourth))) (defun hbo-to-vector-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (vector first second third fourth))) (defun vector-quad-to-dotted-quad (vector) (format nil "~A.~A.~A.~A" (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3))) (defun dotted-quad-to-vector-quad (string) (let ((list (list-of-strings-to-integers (split-sequence #\. string)))) (vector (first list) (second list) (third list) (fourth list)))) (defgeneric host-byte-order (address)) (defmethod host-byte-order ((string string)) "Convert a string, such as 192.168.1.1, to host-byte-order, such as 3232235777." (let ((list (list-of-strings-to-integers (split-sequence #\. string)))) (+ (* (first list) 256 256 256) (* (second list) 256 256) (* (third list) 256) (fourth list)))) (defmethod host-byte-order ((vector vector)) "Convert a vector, such as #(192 168 1 1), to host-byte-order, such as 3232235777." (+ (* (aref vector 0) 256 256 256) (* (aref vector 1) 256 256) (* (aref vector 2) 256) (aref vector 3))) (defmethod host-byte-order ((int integer)) int) (defun host-to-hostname (host) "Translate a string or vector quad to a stringified hostname." (etypecase host (string host) ((or (vector t 4) (array (unsigned-byte 8) (4))) (vector-quad-to-dotted-quad host)) (integer (hbo-to-dotted-quad host)) (null "0.0.0.0"))) (defun ip= (ip1 ip2) (etypecase ip1 (string (string= ip1 (host-to-hostname ip2))) ((or (vector t 4) (array (unsigned-byte 8) (4))) (or (eq ip1 ip2) (and (= (aref ip1 0) (aref ip2 0)) (= (aref ip1 1) (aref ip2 1)) (= (aref ip1 2) (aref ip2 2)) (= (aref ip1 3) (aref ip2 3))))) (integer (= ip1 (host-byte-order ip2))))) (defun ip/= (ip1 ip2) (not (ip= ip1 ip2))) ;; ;; DNS helper functions ;; (defun get-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (car hosts))) (defun get-random-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (when hosts (elt hosts (random (length hosts)))))) (defun host-to-vector-quad (host) "Translate a host specification (vector quad, dotted quad or domain name) to a vector quad." (etypecase host (string (let* ((ip (when (ip-address-string-p host) (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) ;; valid IP dotted quad? ip (get-random-host-by-name host)))) ((or (vector t 4) (array (unsigned-byte 8) (4))) host) (integer (hbo-to-vector-quad host)))) (defun host-to-hbo (host) (etypecase host (string (let ((ip (when (ip-address-string-p host) (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) (host-byte-order ip) (host-to-hbo (get-host-by-name host))))) ((or (vector t 4) (array (unsigned-byte 8) (4))) (host-byte-order host)) (integer host))) ;; ;; Other utility functions ;; (defun split-timeout (timeout &optional (fractional 1000000)) "Split real value timeout into seconds and microseconds. Optionally, a different fractional part can be specified." (multiple-value-bind (secs sec-frac) (truncate timeout 1) (values secs (truncate (* fractional sec-frac) 1)))) ;; ;; Setting of documentation for backend defined functions ;; ;; Documentation for the function ;; ;; (defun SOCKET-CONNECT (host port &key element-type nodelay some-other-keys...) ..) ;; (setf (documentation 'socket-connect 'function) "Connect to `host' on `port'. `host' is assumed to be a string or an IP address represented in vector notation, such as #(192 168 1 1). `port' is assumed to be an integer. `element-type' specifies the element type to use when constructing the stream associated with the socket. The default is 'character. `nodelay' Allows to disable/enable Nagle's algorithm (). If this parameter is omitted, the behaviour is inherited from the CL implementation (in most cases, Nagle's algorithm is enabled by default, but for example in ACL it is disabled). If the parmeter is specified, one of these three values is possible: signals an UNSUPPORTED condition if the implementation does not support explicit manipulation with that option. NIL - Leave Nagle's algorithm enabled on the socket; signals an UNSUPPORTED condition if the implementation does not support explicit manipulation with that option. :IF-SUPPORTED - Disables Nagle's algorithm if the implementation allows this, otherwises just ignore this option. Returns a usocket object.") ;; Documentation for the function ;; ;; (defun SOCKET-LISTEN (host port &key reuseaddress backlog element-type) ..) # # # FIXME : extend with default - element - type (setf (documentation 'socket-listen 'function) "Bind to interface `host' on `port'. `host' should be the representation of an ready-interface address. The implementation is not required to do an address lookup, making no guarantees that hostnames will be correctly resolved. If `*wildcard-host*' is passed for `host', the socket will be bound to all available interfaces for the IPv4 protocol in the system. `port' can be selected by the IP stack by passing `*auto-port*'. Returns an object of type `stream-server-usocket'. `reuse-address' and `backlog' are advisory parameters for setting socket options at creation time. `element-type' is the element type of the streams to be created by `socket-accept'. `reuseaddress' is supported for backward compatibility (but deprecated); when both `reuseaddress' and `reuse-address' have been specified, the latter takes precedence. ")
null
https://raw.githubusercontent.com/mcna/usocket/187e0ecd58ec0b2093d972e0eb607a50182a3efd/usocket.lisp
lisp
$URL: svn-lisp.net/project/usocket/svn/usocket/tags/0.6.0.1/usocket.lisp $ See LICENSE for licensing information. Iff an external-format was passed to `socket-connect' or `socket-listen' the stream is a flexi-stream. Otherwise the stream is implementation specific." implementation specific the list of all usockets maps implementation sockets to usockets Implementation specific: %setup-wait-list %add-waiter %remove-waiter they cannot rely on LISTEN the internal routine is responsibe for making sure the wait doesn't block on socket-streams of which theready- socket isn't ready, but there's space left in the buffer Data utility functions DNS helper functions valid IP dotted quad? Other utility functions Setting of documentation for backend defined functions Documentation for the function (defun SOCKET-CONNECT (host port &key element-type nodelay some-other-keys...) ..) Documentation for the function (defun SOCKET-LISTEN (host port &key reuseaddress backlog element-type) ..) when both `reuseaddress' and
$ I d : usocket.lisp 680 2012 - 01 - 20 23:38:00Z hhubner $ (in-package :usocket) (defparameter *wildcard-host* #(0 0 0 0) "Hostname to pass when all interfaces in the current system are to be bound.") (defparameter *auto-port* 0 "Port number to pass when an auto-assigned port number is wanted.") (defconstant +max-datagram-packet-size+ 65507 "The theoretical maximum amount of data in a UDP datagram. The IPv4 UDP packets have a 16-bit length constraint, and IP+UDP header has 28-byte. IP_MAXPACKET = 65535, /* netinet/ip.h */ sizeof(struct ip) = 20, /* netinet/ip.h */ sizeof(struct udphdr) = 8, /* netinet/udp.h */ 65535 - 20 - 8 = 65507 (But for UDP broadcast, the maximum message size is limited by the MTU size of the underlying link)") (defclass usocket () ((socket :initarg :socket :accessor socket :documentation "Implementation specific socket object instance.'") (wait-list :initform nil :accessor wait-list :documentation "WAIT-LIST the object is associated with.") (state :initform nil :accessor state :documentation "Per-socket return value for the `wait-for-input' function. The value stored in this slot can be any of NIL - not ready :READ - ready to read :READ-WRITE - ready to read and write :WRITE - ready to write The last two remain unused in the current version. ") #+(and win32 (or sbcl ecl lispworks)) (%ready-p :initform nil :accessor %ready-p :documentation "Indicates whether the socket has been signalled as ready for reading a new connection. The value will be set to T by `wait-for-input-internal' (given the right conditions) and reset to NIL by `socket-accept'. Don't modify this slot or depend on it as it is really intended to be internal only. Note: Accessed, but not used for 'stream-usocket'. " )) (:documentation "The main socket class. Sockets should be closed using the `socket-close' method.")) (defclass stream-usocket (usocket) ((stream :initarg :stream :accessor socket-stream :documentation "Stream instance associated with the socket." )) (:documentation "Stream socket class. ' Contrary to other sockets, these sockets may be closed either with the `socket-close' method or by closing the associated stream (which can be retrieved with the `socket-stream' accessor).")) (defclass stream-server-usocket (usocket) ((element-type :initarg :element-type :initform #-lispworks 'character #+lispworks 'base-char :reader element-type :documentation "Default element type for streams created by `socket-accept'.")) (:documentation "Socket which listens for stream connections to be initiated from remote sockets.")) (defclass datagram-usocket (usocket) ((connected-p :type boolean :accessor connected-p :initarg :connected-p) #+(or cmu scl lispworks (and clisp ffi (not rawsock))) (%open-p :type boolean :accessor %open-p :initform t :documentation "Flag to indicate if usocket is open, for GC on implementions operate on raw socket fd.") #+(or lispworks (and clisp ffi (not rawsock))) (recv-buffer :documentation "Private RECV buffer.") #+lispworks (send-buffer :documentation "Private SEND buffer.")) (:documentation "UDP (inet-datagram) socket")) (defun usocket-p (socket) (typep socket 'usocket)) (defun stream-usocket-p (socket) (typep socket 'stream-usocket)) (defun stream-server-usocket-p (socket) (typep socket 'stream-server-usocket)) (defun datagram-usocket-p (socket) (typep socket 'datagram-usocket)) (defun make-socket (&key socket) "Create a usocket socket type from implementation specific socket." (unless socket (error 'invalid-socket)) (make-stream-socket :socket socket)) (defun make-stream-socket (&key socket stream) "Create a usocket socket type from implementation specific socket and stream objects. Sockets returned should be closed using the `socket-close' method or by closing the stream associated with the socket. " (unless socket (error 'invalid-socket-error)) (unless stream (error 'invalid-socket-stream-error)) (make-instance 'stream-usocket :socket socket :stream stream)) (defun make-stream-server-socket (socket &key (element-type #-lispworks 'character #+lispworks 'base-char)) "Create a usocket-server socket type from an implementation-specific socket object. The returned value is a subtype of `stream-server-usocket'. " (unless socket (error 'invalid-socket-error)) (make-instance 'stream-server-usocket :socket socket :element-type element-type)) (defun make-datagram-socket (socket &key connected-p) (unless socket (error 'invalid-socket-error)) (make-instance 'datagram-usocket :socket socket :connected-p connected-p)) (defgeneric socket-accept (socket &key element-type) (:documentation "Accepts a connection from `socket', returning a `stream-socket'. The stream associated with the socket returned has `element-type' when explicitly specified, or the element-type passed to `socket-listen' otherwise.")) (defgeneric socket-close (usocket) (:documentation "Close a previously opened `usocket'.")) (defgeneric socket-send (usocket buffer length &key host port) (:documentation "Send packets through a previously opend `usocket'.")) (defgeneric socket-receive (usocket buffer length &key) (:documentation "Receive packets from a previously opend `usocket'. Returns 4 values: (values buffer size host port)")) (defgeneric get-local-address (socket) (:documentation "Returns the IP address of the socket.")) (defgeneric get-peer-address (socket) (:documentation "Returns the IP address of the peer the socket is connected to.")) (defgeneric get-local-port (socket) (:documentation "Returns the IP port of the socket. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-port (socket) (:documentation "Returns the IP port of the peer the socket to.")) (defgeneric get-local-name (socket) (:documentation "Returns the IP address and port of the socket as values. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-name (socket) (:documentation "Returns the IP address and port of the peer the socket is connected to as values.")) (defmacro with-connected-socket ((var socket) &body body) "Bind `socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(let ((,var ,socket)) (unwind-protect (when ,var (with-mapped-conditions (,var) ,@body)) (when ,var (socket-close ,var))))) (defmacro with-client-socket ((socket-var stream-var &rest socket-connect-args) &body body) "Bind the socket resulting from a call to `socket-connect' with the arguments `socket-connect-args' to `socket-var' and if `stream-var' is non-nil, bind the associated socket stream to it." `(with-connected-socket (,socket-var (socket-connect ,@socket-connect-args)) ,(if (null stream-var) `(progn ,@body) `(let ((,stream-var (socket-stream ,socket-var))) ,@body)))) (defmacro with-server-socket ((var server-socket) &body body) "Bind `server-socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(with-connected-socket (,var ,server-socket) ,@body)) (defmacro with-socket-listener ((socket-var &rest socket-listen-args) &body body) "Bind the socket resulting from a call to `socket-listen' with arguments `socket-listen-args' to `socket-var'." `(with-server-socket (,socket-var (socket-listen ,@socket-listen-args)) ,@body)) (defstruct (wait-list (:constructor %make-wait-list)) (defun make-wait-list (waiters) (let ((wl (%make-wait-list))) (setf (wait-list-map wl) (make-hash-table)) (%setup-wait-list wl) (dolist (x waiters wl) (add-waiter wl x)))) (defun add-waiter (wait-list input) (setf (gethash (socket input) (wait-list-map wait-list)) input (wait-list input) wait-list) (pushnew input (wait-list-waiters wait-list)) (%add-waiter wait-list input)) (defun remove-waiter (wait-list input) (%remove-waiter wait-list input) (setf (wait-list-waiters wait-list) (remove input (wait-list-waiters wait-list)) (wait-list input) nil) (remhash (socket input) (wait-list-map wait-list))) (defun remove-all-waiters (wait-list) (dolist (waiter (wait-list-waiters wait-list)) (%remove-waiter wait-list waiter)) (setf (wait-list-waiters wait-list) nil) (clrhash (wait-list-map wait-list))) (defun wait-for-input (socket-or-sockets &key timeout ready-only) "Waits for one or more streams to become ready for reading from the socket. When `timeout' (a non-negative real number) is specified, wait `timeout' seconds, or wait indefinitely when it isn't specified. A `timeout' value of 0 (zero) means polling. Returns two values: the first value is the list of streams which are readable (or in case of server streams acceptable). NIL may be returned for this value either when waiting timed out or when it was interrupted (EINTR). The second value is a real number indicating the time remaining within the timeout period or NIL if none. Without the READY-ONLY arg, WAIT-FOR-INPUT will return all sockets in the original list you passed it. This prevents a new list from being consed up. Some users of USOCKET were reluctant to use it if it wouldn't behave that way, expecting it to cost significant performance to do the associated garbage collection. Without the READY-ONLY arg, you need to check the socket STATE slot for the values documented in usocket.lisp in the usocket class." (unless (wait-list-p socket-or-sockets) (let ((wl (make-wait-list (if (listp socket-or-sockets) socket-or-sockets (list socket-or-sockets))))) (multiple-value-bind (socks to) (wait-for-input wl :timeout timeout :ready-only ready-only) (return-from wait-for-input (values (if ready-only socks socket-or-sockets) to))))) (let* ((start (get-internal-real-time)) (sockets-ready 0)) (dolist (x (wait-list-waiters socket-or-sockets)) (when (setf (state x) #-(and win32 (or sbcl ecl)) (if (and (stream-usocket-p x) (listen (socket-stream x))) :read nil)) (incf sockets-ready))) (wait-for-input-internal socket-or-sockets :timeout (if (zerop sockets-ready) timeout 0)) (let ((to-result (when timeout (let ((elapsed (/ (- (get-internal-real-time) start) internal-time-units-per-second))) (when (< elapsed timeout) (- timeout elapsed)))))) (values (if ready-only (remove-if #'null (wait-list-waiters socket-or-sockets) :key #'state) socket-or-sockets) to-result)))) (defun integer-to-octet-buffer (integer buffer octets &key (start 0)) (do ((b start (1+ b)) * 8 (- i 8))) ((> 0 i) buffer) (setf (aref buffer b) (ldb (byte 8 i) integer)))) (defun octet-buffer-to-integer (buffer octets &key (start 0)) (let ((integer 0)) (do ((b start (1+ b)) * 8 (- i 8))) ((> 0 i) integer) (setf (ldb (byte 8 i) integer) (aref buffer b))))) (defmacro port-to-octet-buffer (port buffer &key (start 0)) `(integer-to-octet-buffer ,port ,buffer 2 :start ,start)) (defmacro ip-to-octet-buffer (ip buffer &key (start 0)) `(integer-to-octet-buffer (host-byte-order ,ip) ,buffer 4 :start ,start)) (defmacro port-from-octet-buffer (buffer &key (start 0)) `(octet-buffer-to-integer ,buffer 2 :start ,start)) (defmacro ip-from-octet-buffer (buffer &key (start 0)) `(octet-buffer-to-integer ,buffer 4 :start ,start)) IP(v4 ) utility functions (defun list-of-strings-to-integers (list) "Take a list of strings and return a new list of integers (from parse-integer) on each of the string elements." (let ((new-list nil)) (dolist (element (reverse list)) (push (parse-integer element) new-list)) new-list)) (defun ip-address-string-p (string) "Return a true value if the given string could be an IP address." (every (lambda (char) (or (digit-char-p char) (eql char #\.))) string)) (defun hbo-to-dotted-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (format nil "~A.~A.~A.~A" first second third fourth))) (defun hbo-to-vector-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (vector first second third fourth))) (defun vector-quad-to-dotted-quad (vector) (format nil "~A.~A.~A.~A" (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3))) (defun dotted-quad-to-vector-quad (string) (let ((list (list-of-strings-to-integers (split-sequence #\. string)))) (vector (first list) (second list) (third list) (fourth list)))) (defgeneric host-byte-order (address)) (defmethod host-byte-order ((string string)) "Convert a string, such as 192.168.1.1, to host-byte-order, such as 3232235777." (let ((list (list-of-strings-to-integers (split-sequence #\. string)))) (+ (* (first list) 256 256 256) (* (second list) 256 256) (* (third list) 256) (fourth list)))) (defmethod host-byte-order ((vector vector)) "Convert a vector, such as #(192 168 1 1), to host-byte-order, such as 3232235777." (+ (* (aref vector 0) 256 256 256) (* (aref vector 1) 256 256) (* (aref vector 2) 256) (aref vector 3))) (defmethod host-byte-order ((int integer)) int) (defun host-to-hostname (host) "Translate a string or vector quad to a stringified hostname." (etypecase host (string host) ((or (vector t 4) (array (unsigned-byte 8) (4))) (vector-quad-to-dotted-quad host)) (integer (hbo-to-dotted-quad host)) (null "0.0.0.0"))) (defun ip= (ip1 ip2) (etypecase ip1 (string (string= ip1 (host-to-hostname ip2))) ((or (vector t 4) (array (unsigned-byte 8) (4))) (or (eq ip1 ip2) (and (= (aref ip1 0) (aref ip2 0)) (= (aref ip1 1) (aref ip2 1)) (= (aref ip1 2) (aref ip2 2)) (= (aref ip1 3) (aref ip2 3))))) (integer (= ip1 (host-byte-order ip2))))) (defun ip/= (ip1 ip2) (not (ip= ip1 ip2))) (defun get-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (car hosts))) (defun get-random-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (when hosts (elt hosts (random (length hosts)))))) (defun host-to-vector-quad (host) "Translate a host specification (vector quad, dotted quad or domain name) to a vector quad." (etypecase host (string (let* ((ip (when (ip-address-string-p host) (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) ip (get-random-host-by-name host)))) ((or (vector t 4) (array (unsigned-byte 8) (4))) host) (integer (hbo-to-vector-quad host)))) (defun host-to-hbo (host) (etypecase host (string (let ((ip (when (ip-address-string-p host) (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) (host-byte-order ip) (host-to-hbo (get-host-by-name host))))) ((or (vector t 4) (array (unsigned-byte 8) (4))) (host-byte-order host)) (integer host))) (defun split-timeout (timeout &optional (fractional 1000000)) "Split real value timeout into seconds and microseconds. Optionally, a different fractional part can be specified." (multiple-value-bind (secs sec-frac) (truncate timeout 1) (values secs (truncate (* fractional sec-frac) 1)))) (setf (documentation 'socket-connect 'function) "Connect to `host' on `port'. `host' is assumed to be a string or an IP address represented in vector notation, such as #(192 168 1 1). `port' is assumed to be an integer. `element-type' specifies the element type to use when constructing the stream associated with the socket. The default is 'character. `nodelay' Allows to disable/enable Nagle's algorithm (). If this parameter is omitted, the behaviour is inherited from the CL implementation (in most cases, Nagle's algorithm is enabled by default, but for example in ACL it is disabled). If the parmeter is specified, one of these three values is possible: signals an UNSUPPORTED condition if the implementation does not support explicit manipulation with that option. signals an UNSUPPORTED condition if the implementation does not support explicit manipulation with that option. :IF-SUPPORTED - Disables Nagle's algorithm if the implementation allows this, otherwises just ignore this option. Returns a usocket object.") # # # FIXME : extend with default - element - type (setf (documentation 'socket-listen 'function) "Bind to interface `host' on `port'. `host' should be the representation of an ready-interface address. The implementation is not required to do an address lookup, making no guarantees that hostnames will be correctly resolved. If `*wildcard-host*' is passed for `host', the socket will be bound to all available interfaces for the IPv4 protocol in the system. `port' can be selected by the IP stack by passing `*auto-port*'. Returns an object of type `stream-server-usocket'. `reuse-address' and `backlog' are advisory parameters for setting socket options at creation time. `element-type' is the element type of the streams to be created by `socket-accept'. `reuseaddress' is supported for `reuse-address' have been specified, the latter takes precedence. ")
28e3aacceeb1519871ff8cb9e137901aa2a19c8b2e8a71e7d6d76313b3d88833
haroldcarr/learn-haskell-coq-ml-etc
Lib.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RankNTypes # # LANGUAGE TypeApplications # # LANGUAGE ScopedTypeVariables # module Lib where import qualified Crypto.Sodium.Hash import qualified Crypto.Sodium.Init import qualified Crypto.Sodium.Key import qualified Crypto.Sodium.Mac import qualified Crypto.Sodium.Nonce import qualified Crypto.Sodium.Encrypt.Public import qualified Crypto.Sodium.Encrypt.Symmetric -- import qualified Crypto.Sodium.Encrypt.Symmetric.Stream import qualified Crypto.Sodium.Random import qualified Crypto.Sodium.Sign import qualified Data.ByteArray import qualified Data.ByteArray.Sized import qualified Data.ByteString ------------------------------------------------------------------------------ libInit :: IO () libInit = Crypto.Sodium.Init.sodiumInit dbab :: Data.ByteArray.Bytes dbab = Data.ByteArray.pack [0 .. 87] dbasba :: Data.ByteArray.Sized.SizedByteArray 32 Data.ByteArray.Bytes dbasba = Data.ByteArray.Sized.unsafeSizedByteArray (Data.ByteArray.pack [0 .. 31]) -------------------------------------------------- -- Crypto.Sodium.Encrypt.Public keypairSK :: IO ( Crypto.Sodium.Encrypt.Public.PublicKey Data.ByteString.ByteString , Crypto.Sodium.Encrypt.Public.SecretKey Data.ByteArray.ScrubbedBytes ) keypairSK = Crypto.Sodium.Encrypt.Public.keypair deEncrypted :: IO ( Crypto.Sodium.Encrypt.Public.Nonce Data.ByteString.ByteString , Data.ByteString.ByteString , Maybe Data.ByteString.ByteString ) deEncrypted = do (pk, sk) <- keypairSK case Crypto.Sodium.Encrypt.Public.toNonce ("012345678901234567890123" :: Data.ByteString.ByteString) of Nothing -> error "HC: deEncrypted toNonce" Just nonce -> do let encrypted :: Data.ByteString.ByteString = Crypto.Sodium.Encrypt.Public.encrypt pk sk nonce ("message to be encrypted for privacy privacy privacy privacy privacy" :: Data.ByteString.ByteString) -- NOTE: if sk/pk reversed, compiler does not complain, but decrypt returns Nothing let decrypted = Crypto.Sodium.Encrypt.Public.decrypt sk pk nonce encrypted pure (nonce, encrypted, decrypted) -------------------------------------------------- -- Crypto.Sodium.Encrypt.Symmetric keyS :: Data.ByteString.ByteString -> Maybe (Crypto.Sodium.Encrypt.Symmetric.Key Data.ByteString.ByteString) keyS = Crypto.Sodium.Encrypt.Symmetric.toKey deEncryptedS :: IO ( Crypto.Sodium.Encrypt.Symmetric.Key Data.ByteString.ByteString , Crypto.Sodium.Encrypt.Public.Nonce Data.ByteString.ByteString , Data.ByteString.ByteString , Maybe Data.ByteString.ByteString ) deEncryptedS = do case keyS "01234567890123456789012345678901" of Nothing -> error "HC: deEncryptedS keyS" Just k -> case Crypto.Sodium.Encrypt.Symmetric.toNonce ("012345678901234567890123" :: Data.ByteString.ByteString) of Nothing -> error "HC: deEncryptedS toNonce" Just nonce -> do let encrypted :: Data.ByteString.ByteString = Crypto.Sodium.Encrypt.Symmetric.encrypt k nonce ("message to be encrypted for privacy privacy privacy privacy privacy" :: Data.ByteString.ByteString) let decrypted = Crypto.Sodium.Encrypt.Symmetric.decrypt k nonce encrypted pure (k, nonce, encrypted, decrypted) -------------------------------------------------- -- Crypto.Sodium.Encrypt.Symmetric.Stream TODO ------------------------------------------------------------------------------ -- Crypto.Sodium.Hash hash_blake2b256 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashBlake2b 32 Data.ByteArray.Bytes hash_blake2b256 = Crypto.Sodium.Hash.blake2b @32 dbab_blake2b256 :: Crypto.Sodium.Hash.HashBlake2b 32 Data.ByteArray.Bytes dbab_blake2b256 = hash_blake2b256 dbab hash_blake2b512 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashBlake2b 64 Data.ByteArray.Bytes hash_blake2b512 = Crypto.Sodium.Hash.blake2b @64 dbab_blake2b512 :: Crypto.Sodium.Hash.HashBlake2b 64 Data.ByteArray.Bytes dbab_blake2b512 = hash_blake2b512 dbab hash_sha256 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashSha256 Data.ByteArray.Bytes hash_sha256 = Crypto.Sodium.Hash.sha256 dbab_sha256 :: Crypto.Sodium.Hash.HashSha256 Data.ByteArray.Bytes dbab_sha256 = hash_sha256 dbab hash_sha512 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashSha512 Data.ByteArray.Bytes hash_sha512 = Crypto.Sodium.Hash.sha512 dbab_sha512 :: Crypto.Sodium.Hash.HashSha512 Data.ByteArray.Bytes dbab_sha512 = hash_sha512 dbab ------------------------------------------------------------------------------ -- Crypto.Sodium.Key password :: Data.ByteString.ByteString password = "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" params :: Crypto.Sodium.Key.Params params = Crypto.Sodium.Key.Params 1024 1024 dks :: IO ( Data.ByteArray.Sized.SizedByteArray 64 Data.ByteString.ByteString , Crypto.Sodium.Key.DerivationSlip ) dks = Crypto.Sodium.Key.derive @(Data.ByteArray.Sized.SizedByteArray 64 Data.ByteString.ByteString) (Crypto.Sodium.Key.Params 1024 (2 * 1024 * 1024)) password >>= \case Nothing -> error "HC:dks:Nothing" Just r -> pure r rd :: IO Bool rd = do (key, slip) <- dks case Crypto.Sodium.Key.rederive slip password of Nothing -> error "HC:rd:Nothing" Just k -> pure (k == key) ggg ::IO (Data.ByteArray.Sized.SizedByteArray 64 Data.ByteArray.ScrubbedBytes) ggg = Crypto.Sodium.Key.generate ------------------------------------------------------------------------------ -- Crypto.Sodium.Mac authenticator :: Crypto.Sodium.Mac.Authenticator Data.ByteArray.Bytes -- key msg authenticator = Crypto.Sodium.Mac.create dbasba dbab isValid :: Bool -- key msg isValid = Crypto.Sodium.Mac.verify dbasba dbab authenticator ------------------------------------------------------------------------------ -- Crypto.Sodium.Nonce genN :: IO (Data.ByteArray.Sized.SizedByteArray 32 Data.ByteString.ByteString) genN = Crypto.Sodium.Nonce.generate ------------------------------------------------------------------------------ -- Crypto.Sodium.Random genR :: IO (Data.ByteArray.Sized.SizedByteArray 32 Data.ByteArray.Bytes) genR = Crypto.Sodium.Random.generate ------------------------------------------------------------------------------ -- Crypto.Sodium.Sign keypairSign :: IO ( Crypto.Sodium.Sign.PublicKey Data.ByteString.ByteString , Crypto.Sodium.Sign.SecretKey Data.ByteArray.ScrubbedBytes ) keypairSign = Crypto.Sodium.Sign.keypair deEncryptedSign :: IO ( Data.ByteString.ByteString , Maybe Data.ByteString.ByteString ) deEncryptedSign = do (pk, sk) <- keypairSign let signed :: Data.ByteString.ByteString = Crypto.Sodium.Sign.create sk ("message to be signed" :: Data.ByteString.ByteString) let verified = Crypto.Sodium.Sign.open pk signed pure (signed, verified)
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/76c40f281c3ef873f9cd5ba4ea77a7e9dcfc9664/haskell/topic/cryptography/hc-lib-sodium/src/Lib.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE OverloadedStrings # import qualified Crypto.Sodium.Encrypt.Symmetric.Stream ---------------------------------------------------------------------------- ------------------------------------------------ Crypto.Sodium.Encrypt.Public NOTE: if sk/pk reversed, compiler does not complain, but decrypt returns Nothing ------------------------------------------------ Crypto.Sodium.Encrypt.Symmetric ------------------------------------------------ Crypto.Sodium.Encrypt.Symmetric.Stream ---------------------------------------------------------------------------- Crypto.Sodium.Hash ---------------------------------------------------------------------------- Crypto.Sodium.Key ---------------------------------------------------------------------------- Crypto.Sodium.Mac key msg key msg ---------------------------------------------------------------------------- Crypto.Sodium.Nonce ---------------------------------------------------------------------------- Crypto.Sodium.Random ---------------------------------------------------------------------------- Crypto.Sodium.Sign
# LANGUAGE LambdaCase # # LANGUAGE RankNTypes # # LANGUAGE TypeApplications # # LANGUAGE ScopedTypeVariables # module Lib where import qualified Crypto.Sodium.Hash import qualified Crypto.Sodium.Init import qualified Crypto.Sodium.Key import qualified Crypto.Sodium.Mac import qualified Crypto.Sodium.Nonce import qualified Crypto.Sodium.Encrypt.Public import qualified Crypto.Sodium.Encrypt.Symmetric import qualified Crypto.Sodium.Random import qualified Crypto.Sodium.Sign import qualified Data.ByteArray import qualified Data.ByteArray.Sized import qualified Data.ByteString libInit :: IO () libInit = Crypto.Sodium.Init.sodiumInit dbab :: Data.ByteArray.Bytes dbab = Data.ByteArray.pack [0 .. 87] dbasba :: Data.ByteArray.Sized.SizedByteArray 32 Data.ByteArray.Bytes dbasba = Data.ByteArray.Sized.unsafeSizedByteArray (Data.ByteArray.pack [0 .. 31]) keypairSK :: IO ( Crypto.Sodium.Encrypt.Public.PublicKey Data.ByteString.ByteString , Crypto.Sodium.Encrypt.Public.SecretKey Data.ByteArray.ScrubbedBytes ) keypairSK = Crypto.Sodium.Encrypt.Public.keypair deEncrypted :: IO ( Crypto.Sodium.Encrypt.Public.Nonce Data.ByteString.ByteString , Data.ByteString.ByteString , Maybe Data.ByteString.ByteString ) deEncrypted = do (pk, sk) <- keypairSK case Crypto.Sodium.Encrypt.Public.toNonce ("012345678901234567890123" :: Data.ByteString.ByteString) of Nothing -> error "HC: deEncrypted toNonce" Just nonce -> do let encrypted :: Data.ByteString.ByteString = Crypto.Sodium.Encrypt.Public.encrypt pk sk nonce ("message to be encrypted for privacy privacy privacy privacy privacy" :: Data.ByteString.ByteString) let decrypted = Crypto.Sodium.Encrypt.Public.decrypt sk pk nonce encrypted pure (nonce, encrypted, decrypted) keyS :: Data.ByteString.ByteString -> Maybe (Crypto.Sodium.Encrypt.Symmetric.Key Data.ByteString.ByteString) keyS = Crypto.Sodium.Encrypt.Symmetric.toKey deEncryptedS :: IO ( Crypto.Sodium.Encrypt.Symmetric.Key Data.ByteString.ByteString , Crypto.Sodium.Encrypt.Public.Nonce Data.ByteString.ByteString , Data.ByteString.ByteString , Maybe Data.ByteString.ByteString ) deEncryptedS = do case keyS "01234567890123456789012345678901" of Nothing -> error "HC: deEncryptedS keyS" Just k -> case Crypto.Sodium.Encrypt.Symmetric.toNonce ("012345678901234567890123" :: Data.ByteString.ByteString) of Nothing -> error "HC: deEncryptedS toNonce" Just nonce -> do let encrypted :: Data.ByteString.ByteString = Crypto.Sodium.Encrypt.Symmetric.encrypt k nonce ("message to be encrypted for privacy privacy privacy privacy privacy" :: Data.ByteString.ByteString) let decrypted = Crypto.Sodium.Encrypt.Symmetric.decrypt k nonce encrypted pure (k, nonce, encrypted, decrypted) TODO hash_blake2b256 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashBlake2b 32 Data.ByteArray.Bytes hash_blake2b256 = Crypto.Sodium.Hash.blake2b @32 dbab_blake2b256 :: Crypto.Sodium.Hash.HashBlake2b 32 Data.ByteArray.Bytes dbab_blake2b256 = hash_blake2b256 dbab hash_blake2b512 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashBlake2b 64 Data.ByteArray.Bytes hash_blake2b512 = Crypto.Sodium.Hash.blake2b @64 dbab_blake2b512 :: Crypto.Sodium.Hash.HashBlake2b 64 Data.ByteArray.Bytes dbab_blake2b512 = hash_blake2b512 dbab hash_sha256 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashSha256 Data.ByteArray.Bytes hash_sha256 = Crypto.Sodium.Hash.sha256 dbab_sha256 :: Crypto.Sodium.Hash.HashSha256 Data.ByteArray.Bytes dbab_sha256 = hash_sha256 dbab hash_sha512 :: Data.ByteArray.Bytes -> Crypto.Sodium.Hash.HashSha512 Data.ByteArray.Bytes hash_sha512 = Crypto.Sodium.Hash.sha512 dbab_sha512 :: Crypto.Sodium.Hash.HashSha512 Data.ByteArray.Bytes dbab_sha512 = hash_sha512 dbab password :: Data.ByteString.ByteString password = "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" params :: Crypto.Sodium.Key.Params params = Crypto.Sodium.Key.Params 1024 1024 dks :: IO ( Data.ByteArray.Sized.SizedByteArray 64 Data.ByteString.ByteString , Crypto.Sodium.Key.DerivationSlip ) dks = Crypto.Sodium.Key.derive @(Data.ByteArray.Sized.SizedByteArray 64 Data.ByteString.ByteString) (Crypto.Sodium.Key.Params 1024 (2 * 1024 * 1024)) password >>= \case Nothing -> error "HC:dks:Nothing" Just r -> pure r rd :: IO Bool rd = do (key, slip) <- dks case Crypto.Sodium.Key.rederive slip password of Nothing -> error "HC:rd:Nothing" Just k -> pure (k == key) ggg ::IO (Data.ByteArray.Sized.SizedByteArray 64 Data.ByteArray.ScrubbedBytes) ggg = Crypto.Sodium.Key.generate authenticator :: Crypto.Sodium.Mac.Authenticator Data.ByteArray.Bytes authenticator = Crypto.Sodium.Mac.create dbasba dbab isValid :: Bool isValid = Crypto.Sodium.Mac.verify dbasba dbab authenticator genN :: IO (Data.ByteArray.Sized.SizedByteArray 32 Data.ByteString.ByteString) genN = Crypto.Sodium.Nonce.generate genR :: IO (Data.ByteArray.Sized.SizedByteArray 32 Data.ByteArray.Bytes) genR = Crypto.Sodium.Random.generate keypairSign :: IO ( Crypto.Sodium.Sign.PublicKey Data.ByteString.ByteString , Crypto.Sodium.Sign.SecretKey Data.ByteArray.ScrubbedBytes ) keypairSign = Crypto.Sodium.Sign.keypair deEncryptedSign :: IO ( Data.ByteString.ByteString , Maybe Data.ByteString.ByteString ) deEncryptedSign = do (pk, sk) <- keypairSign let signed :: Data.ByteString.ByteString = Crypto.Sodium.Sign.create sk ("message to be signed" :: Data.ByteString.ByteString) let verified = Crypto.Sodium.Sign.open pk signed pure (signed, verified)
2581cb7af4cf59c97f93500b0efa4427ecd55e47ba9aefb0a460dcacc6e0031a
jaspervdj/patat
Read.hs
-- | Read a presentation from disk. {-# LANGUAGE BangPatterns #-} # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # module Patat.Presentation.Read ( readPresentation -- Exposed for testing mostly. , readMetaSettings ) where -------------------------------------------------------------------------------- import Control.Monad.Except (ExceptT (..), runExceptT, throwError) import Control.Monad.Trans (liftIO) import qualified Data.Aeson as A import qualified Data.Aeson.KeyMap as AKM import Data.Bifunctor (first) import Data.Maybe (fromMaybe) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Yaml as Yaml import Patat.Eval (eval) import Patat.Presentation.Fragment import qualified Patat.Presentation.Instruction as Instruction import Patat.Presentation.Internal import Prelude import System.Directory (doesFileExist, getHomeDirectory) import System.FilePath (splitFileName, takeExtension, (</>)) import qualified Text.Pandoc.Error as Pandoc import qualified Text.Pandoc.Extended as Pandoc -------------------------------------------------------------------------------- readPresentation :: FilePath -> IO (Either String Presentation) readPresentation filePath = runExceptT $ do We need to read the settings first . src <- liftIO $ T.readFile filePath homeSettings <- ExceptT readHomeSettings metaSettings <- ExceptT $ return $ readMetaSettings src let settings = metaSettings <> homeSettings <> defaultPresentationSettings let pexts = fromMaybe defaultExtensionList (psPandocExtensions settings) reader <- case readExtension pexts ext of Nothing -> throwError $ "Unknown file extension: " ++ show ext Just x -> return x doc <- case reader src of Left e -> throwError $ "Could not parse document: " ++ show e Right x -> return x pres <- ExceptT $ pure $ pandocToPresentation filePath settings doc liftIO $ eval pres where ext = takeExtension filePath -------------------------------------------------------------------------------- readExtension :: ExtensionList -> String -> Maybe (T.Text -> Either Pandoc.PandocError Pandoc.Pandoc) readExtension (ExtensionList extensions) fileExt = case fileExt of ".markdown" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".md" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdown" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdtext" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdtxt" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdwn" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mkd" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mkdn" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".lhs" -> Just $ Pandoc.runPure . Pandoc.readMarkdown lhsOpts "" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".org" -> Just $ Pandoc.runPure . Pandoc.readOrg readerOpts _ -> Nothing where readerOpts = Pandoc.def { Pandoc.readerExtensions = extensions <> absolutelyRequiredExtensions } lhsOpts = readerOpts { Pandoc.readerExtensions = Pandoc.readerExtensions readerOpts <> Pandoc.extensionsFromList [Pandoc.Ext_literate_haskell] } absolutelyRequiredExtensions = Pandoc.extensionsFromList [Pandoc.Ext_yaml_metadata_block] -------------------------------------------------------------------------------- pandocToPresentation :: FilePath -> PresentationSettings -> Pandoc.Pandoc -> Either String Presentation pandocToPresentation pFilePath pSettings pandoc@(Pandoc.Pandoc meta _) = do let !pTitle = case Pandoc.docTitle meta of [] -> [Pandoc.Str . T.pack . snd $ splitFileName pFilePath] title -> title !pSlides = pandocToSlides pSettings pandoc !pBreadcrumbs = collectBreadcrumbs pSlides !pActiveFragment = (0, 0) !pAuthor = concat (Pandoc.docAuthors meta) return Presentation {..} -------------------------------------------------------------------------------- -- | This re-parses the pandoc metadata block using the YAML library. This avoids the problems caused by pandoc involving rendering . This -- should only be used for settings though, not things like title / authors -- since those /can/ contain markdown. parseMetadataBlock :: T.Text -> Maybe (Either String A.Value) parseMetadataBlock src = case T.lines src of ("---" : ls) -> case break (`elem` ["---", "..."]) ls of (_, []) -> Nothing (block, (_ : _)) -> Just . first Yaml.prettyPrintParseException . Yaml.decodeEither' . T.encodeUtf8 . T.unlines $! block _ -> Nothing -------------------------------------------------------------------------------- | Read settings from the metadata block in the Pandoc document . readMetaSettings :: T.Text -> Either String PresentationSettings readMetaSettings src = case parseMetadataBlock src of Nothing -> Right mempty Just (Left err) -> Left err Just (Right (A.Object obj)) | Just val <- AKM.lookup "patat" obj -> resultToEither $! A.fromJSON val Just (Right _) -> Right mempty where resultToEither :: A.Result a -> Either String a resultToEither (A.Success x) = Right x resultToEither (A.Error e) = Left $! "Error parsing patat settings from metadata: " ++ e -------------------------------------------------------------------------------- | Read settings from " $ HOME/.patat.yaml " . readHomeSettings :: IO (Either String PresentationSettings) readHomeSettings = do home <- getHomeDirectory let path = home </> ".patat.yaml" exists <- doesFileExist path if not exists then return (Right mempty) else do errOrPs <- Yaml.decodeFileEither path return $! case errOrPs of Left err -> Left (show err) Right ps -> Right ps -------------------------------------------------------------------------------- pandocToSlides :: PresentationSettings -> Pandoc.Pandoc -> [Slide] pandocToSlides settings pandoc = let slideLevel = fromMaybe (detectSlideLevel pandoc) (psSlideLevel settings) unfragmented = splitSlides slideLevel pandoc fragmented = [ case slide of TitleSlide _ _ -> slide ContentSlide instrs0 -> ContentSlide $ fragmentInstructions fragmentSettings instrs0 | slide <- unfragmented ] in fragmented where fragmentSettings = FragmentSettings { fsIncrementalLists = fromMaybe False (psIncrementalLists settings) } -------------------------------------------------------------------------------- -- | Find level of header that starts slides. This is defined as the least -- header that occurs before a non-header in the blocks. detectSlideLevel :: Pandoc.Pandoc -> Int detectSlideLevel (Pandoc.Pandoc _meta blocks0) = go 6 blocks0 where go level (Pandoc.Header n _ _ : x : xs) | n < level && nonHeader x = go n xs | otherwise = go level (x:xs) go level (_ : xs) = go level xs go level [] = level nonHeader (Pandoc.Header _ _ _) = False nonHeader _ = True -------------------------------------------------------------------------------- -- | Split a pandoc document into slides. If the document contains horizonal -- rules, we use those as slide delimiters. If there are no horizontal rules, -- we split using headers, determined by the slide level (see -- 'detectSlideLevel'). splitSlides :: Int -> Pandoc.Pandoc -> [Slide] splitSlides slideLevel (Pandoc.Pandoc _meta blocks0) | any (== Pandoc.HorizontalRule) blocks0 = splitAtRules blocks0 | otherwise = splitAtHeaders [] blocks0 where mkContentSlide :: [Pandoc.Block] -> [Slide] mkContentSlide [] = [] -- Never create empty slides mkContentSlide bs = [ContentSlide $ Instruction.fromList [Instruction.Append bs]] splitAtRules blocks = case break (== Pandoc.HorizontalRule) blocks of (xs, []) -> mkContentSlide xs (xs, (_rule : ys)) -> mkContentSlide xs ++ splitAtRules ys splitAtHeaders acc [] = mkContentSlide (reverse acc) splitAtHeaders acc (b@(Pandoc.Header i _ txt) : bs) | i > slideLevel = splitAtHeaders (b : acc) bs | i == slideLevel = mkContentSlide (reverse acc) ++ splitAtHeaders [b] bs | otherwise = mkContentSlide (reverse acc) ++ [TitleSlide i txt] ++ splitAtHeaders [] bs splitAtHeaders acc (b : bs) = splitAtHeaders (b : acc) bs collectBreadcrumbs :: [Slide] -> [Breadcrumbs] collectBreadcrumbs = go [] where go breadcrumbs = \case [] -> [] ContentSlide _ : slides -> breadcrumbs : go breadcrumbs slides TitleSlide lvl inlines : slides -> let parent = filter ((< lvl) . fst) breadcrumbs in parent : go (parent ++ [(lvl, inlines)]) slides
null
https://raw.githubusercontent.com/jaspervdj/patat/9e0d0ccde9afee07ea23521546c406033afeb4f9/lib/Patat/Presentation/Read.hs
haskell
| Read a presentation from disk. # LANGUAGE BangPatterns # # LANGUAGE OverloadedStrings # Exposed for testing mostly. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | This re-parses the pandoc metadata block using the YAML library. This should only be used for settings though, not things like title / authors since those /can/ contain markdown. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | Find level of header that starts slides. This is defined as the least header that occurs before a non-header in the blocks. ------------------------------------------------------------------------------ | Split a pandoc document into slides. If the document contains horizonal rules, we use those as slide delimiters. If there are no horizontal rules, we split using headers, determined by the slide level (see 'detectSlideLevel'). Never create empty slides
# LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # module Patat.Presentation.Read ( readPresentation , readMetaSettings ) where import Control.Monad.Except (ExceptT (..), runExceptT, throwError) import Control.Monad.Trans (liftIO) import qualified Data.Aeson as A import qualified Data.Aeson.KeyMap as AKM import Data.Bifunctor (first) import Data.Maybe (fromMaybe) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Yaml as Yaml import Patat.Eval (eval) import Patat.Presentation.Fragment import qualified Patat.Presentation.Instruction as Instruction import Patat.Presentation.Internal import Prelude import System.Directory (doesFileExist, getHomeDirectory) import System.FilePath (splitFileName, takeExtension, (</>)) import qualified Text.Pandoc.Error as Pandoc import qualified Text.Pandoc.Extended as Pandoc readPresentation :: FilePath -> IO (Either String Presentation) readPresentation filePath = runExceptT $ do We need to read the settings first . src <- liftIO $ T.readFile filePath homeSettings <- ExceptT readHomeSettings metaSettings <- ExceptT $ return $ readMetaSettings src let settings = metaSettings <> homeSettings <> defaultPresentationSettings let pexts = fromMaybe defaultExtensionList (psPandocExtensions settings) reader <- case readExtension pexts ext of Nothing -> throwError $ "Unknown file extension: " ++ show ext Just x -> return x doc <- case reader src of Left e -> throwError $ "Could not parse document: " ++ show e Right x -> return x pres <- ExceptT $ pure $ pandocToPresentation filePath settings doc liftIO $ eval pres where ext = takeExtension filePath readExtension :: ExtensionList -> String -> Maybe (T.Text -> Either Pandoc.PandocError Pandoc.Pandoc) readExtension (ExtensionList extensions) fileExt = case fileExt of ".markdown" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".md" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdown" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdtext" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdtxt" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mdwn" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mkd" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".mkdn" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".lhs" -> Just $ Pandoc.runPure . Pandoc.readMarkdown lhsOpts "" -> Just $ Pandoc.runPure . Pandoc.readMarkdown readerOpts ".org" -> Just $ Pandoc.runPure . Pandoc.readOrg readerOpts _ -> Nothing where readerOpts = Pandoc.def { Pandoc.readerExtensions = extensions <> absolutelyRequiredExtensions } lhsOpts = readerOpts { Pandoc.readerExtensions = Pandoc.readerExtensions readerOpts <> Pandoc.extensionsFromList [Pandoc.Ext_literate_haskell] } absolutelyRequiredExtensions = Pandoc.extensionsFromList [Pandoc.Ext_yaml_metadata_block] pandocToPresentation :: FilePath -> PresentationSettings -> Pandoc.Pandoc -> Either String Presentation pandocToPresentation pFilePath pSettings pandoc@(Pandoc.Pandoc meta _) = do let !pTitle = case Pandoc.docTitle meta of [] -> [Pandoc.Str . T.pack . snd $ splitFileName pFilePath] title -> title !pSlides = pandocToSlides pSettings pandoc !pBreadcrumbs = collectBreadcrumbs pSlides !pActiveFragment = (0, 0) !pAuthor = concat (Pandoc.docAuthors meta) return Presentation {..} avoids the problems caused by pandoc involving rendering . This parseMetadataBlock :: T.Text -> Maybe (Either String A.Value) parseMetadataBlock src = case T.lines src of ("---" : ls) -> case break (`elem` ["---", "..."]) ls of (_, []) -> Nothing (block, (_ : _)) -> Just . first Yaml.prettyPrintParseException . Yaml.decodeEither' . T.encodeUtf8 . T.unlines $! block _ -> Nothing | Read settings from the metadata block in the Pandoc document . readMetaSettings :: T.Text -> Either String PresentationSettings readMetaSettings src = case parseMetadataBlock src of Nothing -> Right mempty Just (Left err) -> Left err Just (Right (A.Object obj)) | Just val <- AKM.lookup "patat" obj -> resultToEither $! A.fromJSON val Just (Right _) -> Right mempty where resultToEither :: A.Result a -> Either String a resultToEither (A.Success x) = Right x resultToEither (A.Error e) = Left $! "Error parsing patat settings from metadata: " ++ e | Read settings from " $ HOME/.patat.yaml " . readHomeSettings :: IO (Either String PresentationSettings) readHomeSettings = do home <- getHomeDirectory let path = home </> ".patat.yaml" exists <- doesFileExist path if not exists then return (Right mempty) else do errOrPs <- Yaml.decodeFileEither path return $! case errOrPs of Left err -> Left (show err) Right ps -> Right ps pandocToSlides :: PresentationSettings -> Pandoc.Pandoc -> [Slide] pandocToSlides settings pandoc = let slideLevel = fromMaybe (detectSlideLevel pandoc) (psSlideLevel settings) unfragmented = splitSlides slideLevel pandoc fragmented = [ case slide of TitleSlide _ _ -> slide ContentSlide instrs0 -> ContentSlide $ fragmentInstructions fragmentSettings instrs0 | slide <- unfragmented ] in fragmented where fragmentSettings = FragmentSettings { fsIncrementalLists = fromMaybe False (psIncrementalLists settings) } detectSlideLevel :: Pandoc.Pandoc -> Int detectSlideLevel (Pandoc.Pandoc _meta blocks0) = go 6 blocks0 where go level (Pandoc.Header n _ _ : x : xs) | n < level && nonHeader x = go n xs | otherwise = go level (x:xs) go level (_ : xs) = go level xs go level [] = level nonHeader (Pandoc.Header _ _ _) = False nonHeader _ = True splitSlides :: Int -> Pandoc.Pandoc -> [Slide] splitSlides slideLevel (Pandoc.Pandoc _meta blocks0) | any (== Pandoc.HorizontalRule) blocks0 = splitAtRules blocks0 | otherwise = splitAtHeaders [] blocks0 where mkContentSlide :: [Pandoc.Block] -> [Slide] mkContentSlide bs = [ContentSlide $ Instruction.fromList [Instruction.Append bs]] splitAtRules blocks = case break (== Pandoc.HorizontalRule) blocks of (xs, []) -> mkContentSlide xs (xs, (_rule : ys)) -> mkContentSlide xs ++ splitAtRules ys splitAtHeaders acc [] = mkContentSlide (reverse acc) splitAtHeaders acc (b@(Pandoc.Header i _ txt) : bs) | i > slideLevel = splitAtHeaders (b : acc) bs | i == slideLevel = mkContentSlide (reverse acc) ++ splitAtHeaders [b] bs | otherwise = mkContentSlide (reverse acc) ++ [TitleSlide i txt] ++ splitAtHeaders [] bs splitAtHeaders acc (b : bs) = splitAtHeaders (b : acc) bs collectBreadcrumbs :: [Slide] -> [Breadcrumbs] collectBreadcrumbs = go [] where go breadcrumbs = \case [] -> [] ContentSlide _ : slides -> breadcrumbs : go breadcrumbs slides TitleSlide lvl inlines : slides -> let parent = filter ((< lvl) . fst) breadcrumbs in parent : go (parent ++ [(lvl, inlines)]) slides
7b3dff66a66e0c92c467bf6f504df634e3054f0958fd42a46ecd824092ed6efc
brunjlar/simple-plutus
Hash.hs
{-# LANGUAGE DerivingStrategies #-} # LANGUAGE GeneralizedNewtypeDeriving # module Plutus.Hash ( Hash , hash ) where import qualified Crypto.Hash as C import qualified Data.Text as T import qualified Data.Text.Encoding as T newtype Hash = Hash (C.Digest C.MD5) deriving newtype (Show, Eq, Ord) hash :: Show a => a -> Hash hash = Hash . C.hash . T.encodeUtf8 . T.pack . show
null
https://raw.githubusercontent.com/brunjlar/simple-plutus/20fe63533cb5006e4dabce09ef02c3bd960fd3bb/src/Plutus/Hash.hs
haskell
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving # module Plutus.Hash ( Hash , hash ) where import qualified Crypto.Hash as C import qualified Data.Text as T import qualified Data.Text.Encoding as T newtype Hash = Hash (C.Digest C.MD5) deriving newtype (Show, Eq, Ord) hash :: Show a => a -> Hash hash = Hash . C.hash . T.encodeUtf8 . T.pack . show
a42d2297d889022b16e17db8169d1b7bf899f9ef861957b85351df4a5265b441
MyDataFlow/ttalk-server
run_common_test.erl
-module(run_common_test). -export([main/1, analyze/2]). -define(CT_DIR, filename:join([".", "tests"])). -define(CT_REPORT, filename:join([".", "ct_report"])). %% %% Entry %% -record(opts, {test, spec, cover, preset = all}). %% Accepted options formatted as: { opt_name , , fun value_sanitizer/1 } . -spec value_sanitizer(string ( ) ) - > NewValue : : any ( ) . opts() -> [{test, #opts.test, fun quick_or_full/1}, {spec, #opts.spec, fun list_to_atom/1}, {cover, #opts.cover, fun bool_or_module_list/1}, {preset, #opts.preset, fun preset/1}]. Raw args are ' key = val ' atoms . are { key : : atom ( ) , : : string ( ) } pairs . %% "=" is an invalid character in option name or value. main(RawArgs) -> Args = [raw_to_arg(Raw) || Raw <- RawArgs], Opts = args_to_opts(Args), try run(Opts), %% Waiting for messages to be flushed timer:sleep(50), init:stop(0) catch Type:Reason -> Stacktrace = erlang:get_stacktrace(), error_logger:error_msg("TEST CRASHED~n Error type: ~p~n Reason: ~p~n Stacktrace:~n~p~n", [Type, Reason, Stacktrace]), %% Waiting for messages to be flushed timer:sleep(50), init:stop("Test failed") end. run(#opts{test = quick, cover = Cover, spec = Spec}) -> do_run_quick_test(tests_to_run(Spec), Cover); run(#opts{test = full, spec = Spec, preset = Preset, cover = Cover}) -> run_test(tests_to_run(Spec), case Preset of all -> all; undefined -> all; _ -> [Preset] end, Cover). %% %% Helpers %% args_to_opts(Args) -> {Args, Opts} = lists:foldl(fun set_opt/2, {Args, #opts{}}, opts()), Opts. raw_to_arg(RawArg) -> ArgVal = atom_to_list(RawArg), [Arg, Val] = string:tokens(ArgVal, "="), {list_to_atom(Arg), Val}. set_opt({Opt, Index, Sanitizer}, {Args, Opts}) -> Value = Sanitizer(proplists:get_value(Opt, Args)), {Args, setelement(Index, Opts, Value)}. quick_or_full("quick") -> quick; quick_or_full("full") -> full. preset(undefined) -> undefined; preset(Preset) -> list_to_atom(Preset). read_file(ConfigFile) when is_list(ConfigFile) -> {ok, CWD} = file:get_cwd(), filename:join([CWD, ConfigFile]), {ok, Props} = file:consult(ConfigFile), Props. tests_to_run(TestSpec) -> TestSpecFile = atom_to_list(TestSpec), [ {spec, TestSpecFile} ]. save_count(Test, Configs) -> Repeat = case proplists:get_value(repeat, Test) of undefined -> 1; Other -> Other end, Times = case length(Configs) of 0 -> 1; N -> N end, file:write_file("/tmp/ct_count", integer_to_list(Repeat*Times)). run_test(Test, PresetsToRun, CoverOpts) -> prepare_cover(Test, CoverOpts), error_logger:info_msg("Presets to run ~p", [PresetsToRun]), {ConfigFile, Props} = get_ct_config(Test), case proplists:lookup(ejabberd_presets, Props) of {ejabberd_presets, Presets} -> Presets1 = case PresetsToRun of all -> Presets; _ -> error_logger:info_msg("Skip presets ~p", [ preset_names(Presets) -- PresetsToRun ]), lists:filter(fun({Preset,_}) -> lists:member(Preset, PresetsToRun) end, Presets) end, Length = length(Presets1), Names = preset_names(Presets), error_logger:info_msg("Starting test of ~p configurations: ~n~p~n", [Length, Names]), Zip = lists:zip(lists:seq(1, Length), Presets1), [run_config_test(Preset, Test, N, Length) || {N, Preset} <- Zip], save_count(Test, Presets1); _ -> error_logger:info_msg("Presets were not found in the config file ~ts", [ConfigFile]), do_run_quick_test(Test, CoverOpts) end, analyze_coverage(Test, CoverOpts). get_ct_config([{spec, Spec}]) -> Props = read_file(Spec), ConfigFile = case proplists:lookup(config, Props) of {config, [Config]} -> Config; _ -> "test.config" end, {ok, ConfigProps} = file:consult(ConfigFile), {ConfigFile, ConfigProps}. preset_names(Presets) -> [Preset||{Preset, _} <- Presets]. do_run_quick_test(Test, CoverOpts) -> prepare_cover(Test, CoverOpts), Result = ct:run_test(Test), case Result of {error, Reason} -> throw({ct_error, Reason}); _ -> ok end, analyze_coverage(Test, CoverOpts), save_count(Test, []). run_config_test({Name, Variables}, Test, N, Tests) -> Node = get_ejabberd_node(Test), {ok, Cwd} = call(Node, file, get_cwd, []), Cfg = filename:join([Cwd, "..", "..", "rel", "files", "ejabberd.cfg"]), Vars = filename:join([Cwd, "..", "..", "rel", "reltool_vars", "node1_vars.config"]), CfgFile = filename:join([Cwd, "etc", "ejabberd.cfg"]), {ok, Template} = call(Node, file, read_file, [Cfg]), {ok, Default} = call(Node, file, consult, [Vars]), NewVars = lists:foldl(fun({Var,Val}, Acc) -> lists:keystore(Var, 1, Acc, {Var,Val}) end, Default, Variables), LTemplate = binary_to_list(Template), NewCfgFile = mustache:render(LTemplate, dict:from_list(NewVars)), ok = call(Node, file, write_file, [CfgFile, NewCfgFile]), call(Node, application, stop, [ejabberd]), call(Node, application, start, [ejabberd]), error_logger:info_msg("Configuration ~p of ~p: ~p started.~n", [N, Tests, Name]), Result = ct:run_test([{label, Name} | Test]), case Result of {error, Reason} -> throw({ct_error, Reason}); _ -> ok end. call(Node, M, F, A) -> case rpc:call(Node, M, F, A) of {badrpc, Reason} -> error_logger:error_msg("RPC call ~p:~p/~p to node ~p failed because ~p", [M, F, length(A), Node, Reason]), {badrpc, Reason}; Result -> Result end. get_apps() -> case file:list_dir("../../apps/") of {ok, Filenames} -> lists:map(fun list_to_atom/1, Filenames); {error, _Reason} -> error("ejabberd parent project not found (expected apps in ../../apps)") end. prepare_cover(Test, true) -> io:format("Preparing cover~n"), prepare(Test); prepare_cover(_, _) -> ok. analyze_coverage(Test, true) -> analyze(Test, true); analyze_coverage(Test, ModuleList) when is_list(ModuleList) -> analyze(Test, ModuleList); analyze_coverage(_, _) -> ok. prepare(Test) -> Apps = get_apps(), Compiled = rpc:call(get_ejabberd_node(Test), mongoose_cover_helper, start, [Apps]), io:format("Compiled modules ~p~n", [Compiled]). analyze(Test, CoverOpts) -> io:format("Coverage analyzing~n"), rpc:call(get_ejabberd_node(Test), mongoose_cover_helper, analyze, []), Files = filelib:wildcard("/tmp/*.coverdata"), [cover:import(File) || File <- Files], cover:export("/tmp/mongoose_combined.coverdata"), case os:getenv("TRAVIS_JOB_ID") of false -> make_html(modules_to_analyze(CoverOpts)); _ -> ok end. make_html(Modules) -> {ok, Root} = file:get_cwd(), SortScript = Root ++ "/priv/sorttable.js", os:cmd("cp " ++ SortScript ++ " " ++ ?CT_REPORT), FilePath = case file:read_file(?CT_REPORT++"/index.html") of {ok, IndexFileData} -> R = re:replace(IndexFileData, "<a href=\"all_runs.html\">ALL RUNS</a>", "& <a href=\"cover.html\" style=\"margin-right:5px\">COVER</a>"), file:write_file(?CT_REPORT++"/index.html", R), ?CT_REPORT++"/cover.html"; _ -> skip end, CoverageDir = filename:dirname(FilePath)++"/coverage", file:make_dir(CoverageDir), {ok, File} = file:open(FilePath, [write]), file:write(File, get_cover_header()), Fun = fun(Module, {CAcc, NCAcc}) -> FileName = lists:flatten(io_lib:format("~s.COVER.html",[Module])), case cover:analyse(Module, module) of {ok, {Module, {C, NC}}} -> file:write(File, row(atom_to_list(Module), C, NC, percent(C,NC),"coverage/"++FileName)), FilePathC = filename:join([CoverageDir, FileName]), catch cover:analyse_to_file(Module, FilePathC, [html]), {CAcc + C, NCAcc + NC}; _ -> {CAcc, NCAcc} end end, {CSum, NCSum} = lists:foldl(Fun, {0, 0}, Modules), file:write(File, row("Summary", CSum, NCSum, percent(CSum, NCSum), "#")), file:close(File). get_ejabberd_node(Test) -> {_File, Props} = get_ct_config(Test), {ejabberd_node, Node} = proplists:lookup(ejabberd_node, Props), Node. percent(0, _) -> 0; percent(C, NC) when C /= 0; NC /= 0 -> round(C / (NC+C) * 100); percent(_, _) -> 100. row(Row, C, NC, Percent, Path) -> [ "<tr>", "<td><a href='", Path, "'>", Row, "</a></td>", "<td>", integer_to_list(Percent), "%</td>", "<td>", integer_to_list(C), "</td>", "<td>", integer_to_list(NC), "</td>", "<td>", integer_to_list(C+NC), "</td>", "</tr>\n" ]. get_cover_header() -> "<html>\n<head></head>\n<body bgcolor=\"white\" text=\"black\" link=\"blue\" vlink=\"purple\" alink=\"red\">\n" "<head><script src='sorttable.js'></script></head>" "<h1>Coverage for application 'MongooseIM'</h1>\n" "<table class='sortable' border=3 cellpadding=5>\n" "<tr><th>Module</th><th>Covered (%)</th><th>Covered (Lines)</th><th>Not covered (Lines)</th><th>Total (Lines)</th></tr>". bool_or_module_list("true") -> true; bool_or_module_list(ModuleList) when is_list(ModuleList) -> [ list_to_atom(L) || L <- string:tokens("asd,qwe,zxc", ",") ]; bool_or_module_list(_) -> false. modules_to_analyze(true) -> cover:imported_modules(); modules_to_analyze(ModuleList) when is_list(ModuleList) -> ModuleList.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/test/ejabberd_tests/run_common_test.erl
erlang
Entry Accepted options formatted as: "=" is an invalid character in option name or value. Waiting for messages to be flushed Waiting for messages to be flushed Helpers
-module(run_common_test). -export([main/1, analyze/2]). -define(CT_DIR, filename:join([".", "tests"])). -define(CT_REPORT, filename:join([".", "ct_report"])). -record(opts, {test, spec, cover, preset = all}). { opt_name , , fun value_sanitizer/1 } . -spec value_sanitizer(string ( ) ) - > NewValue : : any ( ) . opts() -> [{test, #opts.test, fun quick_or_full/1}, {spec, #opts.spec, fun list_to_atom/1}, {cover, #opts.cover, fun bool_or_module_list/1}, {preset, #opts.preset, fun preset/1}]. Raw args are ' key = val ' atoms . are { key : : atom ( ) , : : string ( ) } pairs . main(RawArgs) -> Args = [raw_to_arg(Raw) || Raw <- RawArgs], Opts = args_to_opts(Args), try run(Opts), timer:sleep(50), init:stop(0) catch Type:Reason -> Stacktrace = erlang:get_stacktrace(), error_logger:error_msg("TEST CRASHED~n Error type: ~p~n Reason: ~p~n Stacktrace:~n~p~n", [Type, Reason, Stacktrace]), timer:sleep(50), init:stop("Test failed") end. run(#opts{test = quick, cover = Cover, spec = Spec}) -> do_run_quick_test(tests_to_run(Spec), Cover); run(#opts{test = full, spec = Spec, preset = Preset, cover = Cover}) -> run_test(tests_to_run(Spec), case Preset of all -> all; undefined -> all; _ -> [Preset] end, Cover). args_to_opts(Args) -> {Args, Opts} = lists:foldl(fun set_opt/2, {Args, #opts{}}, opts()), Opts. raw_to_arg(RawArg) -> ArgVal = atom_to_list(RawArg), [Arg, Val] = string:tokens(ArgVal, "="), {list_to_atom(Arg), Val}. set_opt({Opt, Index, Sanitizer}, {Args, Opts}) -> Value = Sanitizer(proplists:get_value(Opt, Args)), {Args, setelement(Index, Opts, Value)}. quick_or_full("quick") -> quick; quick_or_full("full") -> full. preset(undefined) -> undefined; preset(Preset) -> list_to_atom(Preset). read_file(ConfigFile) when is_list(ConfigFile) -> {ok, CWD} = file:get_cwd(), filename:join([CWD, ConfigFile]), {ok, Props} = file:consult(ConfigFile), Props. tests_to_run(TestSpec) -> TestSpecFile = atom_to_list(TestSpec), [ {spec, TestSpecFile} ]. save_count(Test, Configs) -> Repeat = case proplists:get_value(repeat, Test) of undefined -> 1; Other -> Other end, Times = case length(Configs) of 0 -> 1; N -> N end, file:write_file("/tmp/ct_count", integer_to_list(Repeat*Times)). run_test(Test, PresetsToRun, CoverOpts) -> prepare_cover(Test, CoverOpts), error_logger:info_msg("Presets to run ~p", [PresetsToRun]), {ConfigFile, Props} = get_ct_config(Test), case proplists:lookup(ejabberd_presets, Props) of {ejabberd_presets, Presets} -> Presets1 = case PresetsToRun of all -> Presets; _ -> error_logger:info_msg("Skip presets ~p", [ preset_names(Presets) -- PresetsToRun ]), lists:filter(fun({Preset,_}) -> lists:member(Preset, PresetsToRun) end, Presets) end, Length = length(Presets1), Names = preset_names(Presets), error_logger:info_msg("Starting test of ~p configurations: ~n~p~n", [Length, Names]), Zip = lists:zip(lists:seq(1, Length), Presets1), [run_config_test(Preset, Test, N, Length) || {N, Preset} <- Zip], save_count(Test, Presets1); _ -> error_logger:info_msg("Presets were not found in the config file ~ts", [ConfigFile]), do_run_quick_test(Test, CoverOpts) end, analyze_coverage(Test, CoverOpts). get_ct_config([{spec, Spec}]) -> Props = read_file(Spec), ConfigFile = case proplists:lookup(config, Props) of {config, [Config]} -> Config; _ -> "test.config" end, {ok, ConfigProps} = file:consult(ConfigFile), {ConfigFile, ConfigProps}. preset_names(Presets) -> [Preset||{Preset, _} <- Presets]. do_run_quick_test(Test, CoverOpts) -> prepare_cover(Test, CoverOpts), Result = ct:run_test(Test), case Result of {error, Reason} -> throw({ct_error, Reason}); _ -> ok end, analyze_coverage(Test, CoverOpts), save_count(Test, []). run_config_test({Name, Variables}, Test, N, Tests) -> Node = get_ejabberd_node(Test), {ok, Cwd} = call(Node, file, get_cwd, []), Cfg = filename:join([Cwd, "..", "..", "rel", "files", "ejabberd.cfg"]), Vars = filename:join([Cwd, "..", "..", "rel", "reltool_vars", "node1_vars.config"]), CfgFile = filename:join([Cwd, "etc", "ejabberd.cfg"]), {ok, Template} = call(Node, file, read_file, [Cfg]), {ok, Default} = call(Node, file, consult, [Vars]), NewVars = lists:foldl(fun({Var,Val}, Acc) -> lists:keystore(Var, 1, Acc, {Var,Val}) end, Default, Variables), LTemplate = binary_to_list(Template), NewCfgFile = mustache:render(LTemplate, dict:from_list(NewVars)), ok = call(Node, file, write_file, [CfgFile, NewCfgFile]), call(Node, application, stop, [ejabberd]), call(Node, application, start, [ejabberd]), error_logger:info_msg("Configuration ~p of ~p: ~p started.~n", [N, Tests, Name]), Result = ct:run_test([{label, Name} | Test]), case Result of {error, Reason} -> throw({ct_error, Reason}); _ -> ok end. call(Node, M, F, A) -> case rpc:call(Node, M, F, A) of {badrpc, Reason} -> error_logger:error_msg("RPC call ~p:~p/~p to node ~p failed because ~p", [M, F, length(A), Node, Reason]), {badrpc, Reason}; Result -> Result end. get_apps() -> case file:list_dir("../../apps/") of {ok, Filenames} -> lists:map(fun list_to_atom/1, Filenames); {error, _Reason} -> error("ejabberd parent project not found (expected apps in ../../apps)") end. prepare_cover(Test, true) -> io:format("Preparing cover~n"), prepare(Test); prepare_cover(_, _) -> ok. analyze_coverage(Test, true) -> analyze(Test, true); analyze_coverage(Test, ModuleList) when is_list(ModuleList) -> analyze(Test, ModuleList); analyze_coverage(_, _) -> ok. prepare(Test) -> Apps = get_apps(), Compiled = rpc:call(get_ejabberd_node(Test), mongoose_cover_helper, start, [Apps]), io:format("Compiled modules ~p~n", [Compiled]). analyze(Test, CoverOpts) -> io:format("Coverage analyzing~n"), rpc:call(get_ejabberd_node(Test), mongoose_cover_helper, analyze, []), Files = filelib:wildcard("/tmp/*.coverdata"), [cover:import(File) || File <- Files], cover:export("/tmp/mongoose_combined.coverdata"), case os:getenv("TRAVIS_JOB_ID") of false -> make_html(modules_to_analyze(CoverOpts)); _ -> ok end. make_html(Modules) -> {ok, Root} = file:get_cwd(), SortScript = Root ++ "/priv/sorttable.js", os:cmd("cp " ++ SortScript ++ " " ++ ?CT_REPORT), FilePath = case file:read_file(?CT_REPORT++"/index.html") of {ok, IndexFileData} -> R = re:replace(IndexFileData, "<a href=\"all_runs.html\">ALL RUNS</a>", "& <a href=\"cover.html\" style=\"margin-right:5px\">COVER</a>"), file:write_file(?CT_REPORT++"/index.html", R), ?CT_REPORT++"/cover.html"; _ -> skip end, CoverageDir = filename:dirname(FilePath)++"/coverage", file:make_dir(CoverageDir), {ok, File} = file:open(FilePath, [write]), file:write(File, get_cover_header()), Fun = fun(Module, {CAcc, NCAcc}) -> FileName = lists:flatten(io_lib:format("~s.COVER.html",[Module])), case cover:analyse(Module, module) of {ok, {Module, {C, NC}}} -> file:write(File, row(atom_to_list(Module), C, NC, percent(C,NC),"coverage/"++FileName)), FilePathC = filename:join([CoverageDir, FileName]), catch cover:analyse_to_file(Module, FilePathC, [html]), {CAcc + C, NCAcc + NC}; _ -> {CAcc, NCAcc} end end, {CSum, NCSum} = lists:foldl(Fun, {0, 0}, Modules), file:write(File, row("Summary", CSum, NCSum, percent(CSum, NCSum), "#")), file:close(File). get_ejabberd_node(Test) -> {_File, Props} = get_ct_config(Test), {ejabberd_node, Node} = proplists:lookup(ejabberd_node, Props), Node. percent(0, _) -> 0; percent(C, NC) when C /= 0; NC /= 0 -> round(C / (NC+C) * 100); percent(_, _) -> 100. row(Row, C, NC, Percent, Path) -> [ "<tr>", "<td><a href='", Path, "'>", Row, "</a></td>", "<td>", integer_to_list(Percent), "%</td>", "<td>", integer_to_list(C), "</td>", "<td>", integer_to_list(NC), "</td>", "<td>", integer_to_list(C+NC), "</td>", "</tr>\n" ]. get_cover_header() -> "<html>\n<head></head>\n<body bgcolor=\"white\" text=\"black\" link=\"blue\" vlink=\"purple\" alink=\"red\">\n" "<head><script src='sorttable.js'></script></head>" "<h1>Coverage for application 'MongooseIM'</h1>\n" "<table class='sortable' border=3 cellpadding=5>\n" "<tr><th>Module</th><th>Covered (%)</th><th>Covered (Lines)</th><th>Not covered (Lines)</th><th>Total (Lines)</th></tr>". bool_or_module_list("true") -> true; bool_or_module_list(ModuleList) when is_list(ModuleList) -> [ list_to_atom(L) || L <- string:tokens("asd,qwe,zxc", ",") ]; bool_or_module_list(_) -> false. modules_to_analyze(true) -> cover:imported_modules(); modules_to_analyze(ModuleList) when is_list(ModuleList) -> ModuleList.
430e1ced0233c8cff50761a356c4aa17947580238aed1b863455c5021eed304b
thosmos/riverdb
dnd.cljs
(ns theta.ui.dnd (:require [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.algorithms.react-interop :as interop])) [ " react - beautiful - dnd " : refer [ DragDropContext ] ] ) ) ;import * as React from 'react'; ;import { Droppable } from 'react-beautiful-dnd'; ; ;export default (props: any) => ;<Droppable droppableId={props.droppableId}> ;{(provided: any) => ( ; <div className={props.className} ; ref={provided.innerRef} ; {...provided.droppableProps} ; {...provided.droppablePlaceholder}> ; {props.children} ; </div>)} ; ;</Droppable> ( def factory ( interop / react - factory ) ) ( def ui - droppable ( interop / react - factory ) ) ( defn ui - droppable [ { : keys [ droppableId className children ] : as props } ] ; (factory {:droppableId droppableId} ; (fn [jsprops] ; (dom/div {:className className ; :ref (js->clj (comp/isoget jsprops "innerRef")) ; :droppableProps (js->clj (comp/isoget jsprops "droppableProps")) : ( js->clj ( comp / isoget jsprops " " ) ) } ; children))))
null
https://raw.githubusercontent.com/thosmos/riverdb/b47f01a938da26298ee7924c8b2b3a2be5371927/src/main/theta/ui/dnd.cljs
clojure
import * as React from 'react'; import { Droppable } from 'react-beautiful-dnd'; export default (props: any) => <Droppable droppableId={props.droppableId}> {(provided: any) => ( <div className={props.className} ref={provided.innerRef} {...provided.droppableProps} {...provided.droppablePlaceholder}> {props.children} </div>)} </Droppable> (factory {:droppableId droppableId} (fn [jsprops] (dom/div {:className className :ref (js->clj (comp/isoget jsprops "innerRef")) :droppableProps (js->clj (comp/isoget jsprops "droppableProps")) children))))
(ns theta.ui.dnd (:require [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.algorithms.react-interop :as interop])) [ " react - beautiful - dnd " : refer [ DragDropContext ] ] ) ) ( def factory ( interop / react - factory ) ) ( def ui - droppable ( interop / react - factory ) ) ( defn ui - droppable [ { : keys [ droppableId className children ] : as props } ] : ( js->clj ( comp / isoget jsprops " " ) ) }
8d7c49e3b446d4311ad8dbeb3e8813ec125b0cc7a53a726c2a264bd71fe9e736
jerrypnz/clj.tr069
schema_test.clj
(ns clj.tr069.schema-test (:use clojure.test clj.tr069.schema clj.tr069.databinding) (:import (clj.tr069.schema Inform Device DeviceId ParameterValueStruct))) (def test-inform-object {:device-id {:oui "09cafe" :product-class "TEST" :manufacturer "MOBICLOUD" :serial-number "0xcafebabe"} :parameter-list [{:name "InternetGatewayDevice.DeviceSummary" :value {:type :string :value "test device"}} {:name "InternetGatewayDevice.DeviceInfo.SpecVersion" :value {:type :string :value "1.0a"}} {:name "InternetGatewayDevice.DeviceInfo.HardwareVersion" :value {:type :string :value "1.0"}} {:name "InternetGatewayDevice.DeviceInfo.SoftwareVersion" :value {:type :string :value "1.1"}} {:name "InternetGatewayDevice.DeviceInfo.ProvisioningCode" :value {:type :string :value "cloud"}} {:name "InternetGatewayDevice.ManagementServer.ConnectionRequestURL" :value {:type :string :value ":1234"}} {:name "InternetGatewayDevice.ManagementServer.ParameterKey" :value {:type :string :value "4321"}} {:name "InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.ExternalIPAddress" :value {:type :string :value "201.101.101.101"}}]}) (deftest inform->device-success (testing "Failure: incorrect device object created from inform" (is (= (Device. "09cafe_0xcafebabe" "09cafe" "TEST" "0xcafebabe" "MOBICLOUD" "201.101.101.101" ":1234" nil nil "4321" "cloud" "1.0a" "1.0" "1.1" "test device" "InternetGatewayDevice" "WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1." ) (inform->device test-inform-object)))))
null
https://raw.githubusercontent.com/jerrypnz/clj.tr069/5f3361490b3c69d43842e68f74cd92b6b90cd7cd/test/clj/tr069/schema_test.clj
clojure
(ns clj.tr069.schema-test (:use clojure.test clj.tr069.schema clj.tr069.databinding) (:import (clj.tr069.schema Inform Device DeviceId ParameterValueStruct))) (def test-inform-object {:device-id {:oui "09cafe" :product-class "TEST" :manufacturer "MOBICLOUD" :serial-number "0xcafebabe"} :parameter-list [{:name "InternetGatewayDevice.DeviceSummary" :value {:type :string :value "test device"}} {:name "InternetGatewayDevice.DeviceInfo.SpecVersion" :value {:type :string :value "1.0a"}} {:name "InternetGatewayDevice.DeviceInfo.HardwareVersion" :value {:type :string :value "1.0"}} {:name "InternetGatewayDevice.DeviceInfo.SoftwareVersion" :value {:type :string :value "1.1"}} {:name "InternetGatewayDevice.DeviceInfo.ProvisioningCode" :value {:type :string :value "cloud"}} {:name "InternetGatewayDevice.ManagementServer.ConnectionRequestURL" :value {:type :string :value ":1234"}} {:name "InternetGatewayDevice.ManagementServer.ParameterKey" :value {:type :string :value "4321"}} {:name "InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.ExternalIPAddress" :value {:type :string :value "201.101.101.101"}}]}) (deftest inform->device-success (testing "Failure: incorrect device object created from inform" (is (= (Device. "09cafe_0xcafebabe" "09cafe" "TEST" "0xcafebabe" "MOBICLOUD" "201.101.101.101" ":1234" nil nil "4321" "cloud" "1.0a" "1.0" "1.1" "test device" "InternetGatewayDevice" "WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1." ) (inform->device test-inform-object)))))
cd75dcf8a27869dbad8f207078720d3bc8412f8c08030d3ab9fc13227b14447c
stofel/ecldb
ecldb_ring.erl
%% %% Hash ring module %% -module(ecldb_ring). -include("../include/ecldb.hrl"). -export([ new/0, ring_size/1, add_domain/2, %% Add domain to ring add_domain/3, del_domain/2, %% Del domain from ring del_domain/3, list_domains/1, list_nodes/1, route/2, route/3, , route_second/2 , route_thrid/2 , % % TODO r/2, r/3 ]). -compile({no_auto_import, [size/1]}). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Bisect exports { { { %-export([new/2, new/3, insert/3, bulk_insert/2, append/3, find/2, foldl/3]). %-export([next/2, next_nth/3, first/1, last/1, delete/2, compact/1, cas/4, update/4]). -export([serialize/1 , deserialize/1 , from_orddict/2 , , find_many/2 ] ) . %-export([merge/2, intersection/1, intersection/2]). -export([expected_size/2 , expected_size_mb/2 , num_keys/1 , size/1 ] ) . %% }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% new() -> new(32,32). ring_size(Ring) -> size(Ring). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% ADD & DEL {{{ %% add N domains to ring, return count domains in ring add_domain(DomainKey, Ring) -> add_domain(DomainKey, Ring, 16). add_domain(DomainKey, Ring, N) when N > 0 -> Key = ecldb_misc:md5_hex(ecldb_misc:random_bin(16)), NewRing = insert(Ring, Key, DomainKey), add_domain(DomainKey, NewRing, N-1); add_domain(DomainKey, Ring, _N) -> DomainsCount = proplists:get_value(DomainKey, list_domains(Ring), 0), {ok, Ring, DomainsCount}. Del N damains from ring , return count domains in ring del_domain(DomainKey, Ring) -> del_domain(DomainKey, Ring, 1). del_domain(DomainKey, Ring, Num) -> KFun = fun (K, V, Acc) when V == DomainKey -> [K|Acc]; (_, _, Acc) -> Acc end, Keys = ecldb_misc:shuffle_list(foldl(Ring, KFun, [])), DFun = fun (Fu, [K|RestK], R, N) when N > 0 -> Fu(Fu, RestK, delete(R, K), N - 1); (_F, _, R, _N) -> R end, NewRing = DFun(DFun, Keys, Ring, Num), DomainsCount = proplists:get_value(DomainKey, list_domains(NewRing), 0), {ok, NewRing, DomainsCount}. %% }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% list_domains(Ring) -> F = fun(_Key, Value, Acc) -> Counter = proplists:get_value(Value, Acc, 0), lists:keystore(Value, 1, Acc, {Value, Counter+1}) end, foldl(Ring, F, []). %% list_nodes(Ring) -> List = list_domains(Ring), F = fun ({{ok, #{node := Node}}, Len}, Acc) -> Counter = proplists:get_value(Node, Acc, 0), lists:keystore(Node, 1, Acc, {Node, Counter + Len}); (_, Acc) -> Acc end, lists:foldl(F, [], List). r(A, B) -> {A, B}. r(A, B, C) -> {A, B, C}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% ROUTING {{{ Route thru the rings 1 . use dynamic compiling beam with name same as name 2 . In dynamic compiling module : %-define(MODE, proxy). route(KeyHash ) - > ecldb_ring : route(?MODULE , ) . %mode() -> ?MODE. first ( ) - > ring1 . second ( ) - > ring2 . %domains() -> domains. %% -define(ZERO_HASH, <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>). % Module = ClusterName route(Module, Key) -> route(Module, Module:mode(), ecldb_misc:md5_hex(Key)). route(Module, norma, KeyHash) -> case get_domain(Module, first, KeyHash) of {ok, Domain} -> {ok, {norma, Domain}}; Else -> Else end; route(Module, Mode, KeyHash) -> case [get_domain(Module, Ring, KeyHash) || Ring <- [first, second]] of [{ok,V1}, {ok,V2}] when V1 == V2 -> {ok, {norma, V1}}; [{ok,V1}, {ok,V2}] -> {ok, {Mode, V1, V2}}; Else -> ?e(cluster_rings_error, ?p(Else)) end. % get_domain(Module, Ring, KeyHash) -> case get_value_from_ring(Module, Ring, KeyHash) of {ok, ValueKey} -> case Module:domains() of #{ValueKey := Domain} -> {ok, Domain}; error -> ?e(domain_not_found) end; Else -> Else end. % get_value_from_ring(Module, Ring, KeyHash) -> case next(Module:Ring(), KeyHash) of {_Next, V} -> {ok, V}; TODO optimize this case next(Module:Ring(), ?ZERO_HASH) of {_Next, V} -> {ok, V}; not_found -> ?e(domain_not_found) end end. %% }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Bisect { { { %% @doc: Space-efficient dictionary implemented using a binary %% %% This module implements a space-efficient dictionary with no overhead per entry . Read and write access is O(log n ) . %% %% Keys and values are fixed size binaries stored ordered in a larger %% binary which acts as a sparse array. All operations are implemented %% using a binary search. %% %% As large binaries can be shared among processes, there can be %% multiple concurrent readers of an instance of this structure. %% %% serialize/1 and deserialize/1 %-module(ecl_bisect). -author('Knut Nesheim < > ' ) . %-compile({no_auto_import, [size/1]}). %% TYPES %% -type key_size() :: pos_integer(). -type value_size() :: pos_integer(). -type block_size() :: pos_integer(). -type key() :: binary(). -type value() :: binary(). -type index() :: pos_integer(). -record(bindict, { key_size :: key_size(), value_size :: value_size(), block_size :: block_size(), b :: binary() }). -type bindict() :: #bindict{}. %% %% API %% -spec new(key_size(), value_size()) -> bindict(). %% @doc: Returns a new empty dictionary where where the keys and %% values will always be of the given size. new(KeySize, ValueSize) when is_integer(KeySize) andalso is_integer(ValueSize) -> new(KeySize, ValueSize, <<>>). -spec new(key_size(), value_size(), binary()) -> bindict(). %% @doc: Returns a new dictionary with the given data new(KeySize, ValueSize, Data) when is_integer(KeySize) andalso is_integer(ValueSize) andalso is_binary(Data) -> #bindict{key_size = KeySize, value_size = ValueSize, block_size = KeySize + ValueSize, b = Data}. -spec insert(bindict(), key(), value()) -> bindict(). %% @doc: Inserts the key and value into the dictionary. If the size of %% key and value is wrong, throws badarg. If the key is already in the %% array, the value is updated. insert(B, K, V) when byte_size(K) =/= B#bindict.key_size orelse byte_size(V) =/= B#bindict.value_size -> erlang:error(badarg); insert(#bindict{b = <<>>} = B, K, V) -> B#bindict{b = <<K/binary, V/binary>>}; insert(B, K, V) -> Index = index(B, K), LeftOffset = Index * B#bindict.block_size, RightOffset = byte_size(B#bindict.b) - LeftOffset, KeySize = B#bindict.key_size, ValueSize = B#bindict.value_size, case B#bindict.b of <<Left:LeftOffset/binary, K:KeySize/binary, _:ValueSize/binary, Right/binary>> -> B#bindict{b = iolist_to_binary([Left, K, V, Right])}; <<Left:LeftOffset/binary, Right:RightOffset/binary>> -> B#bindict{b = iolist_to_binary([Left, K, V, Right])} end. -spec delete(bindict(), key()) -> bindict(). delete(B, K) -> LeftOffset = index2offset(B, index(B, K)), KeySize = B#bindict.key_size, ValueSize = B#bindict.value_size, case B#bindict.b of <<Left:LeftOffset/binary, K:KeySize/binary, _:ValueSize/binary, Right/binary>> -> B#bindict{b = <<Left/binary, Right/binary>>}; _ -> erlang:error(badarg) end. -spec next(bindict(), key()) -> {key(), value()} | not_found. %% @doc: Returns the next larger key and value associated with it or %% 'not_found' if no larger key exists. next(B, K) -> next_nth(B, K, 1). %% @doc: Returns the nth next larger key and value associated with it %% or 'not_found' if it does not exist. -spec next_nth(bindict(), key(), non_neg_integer()) -> value() | not_found. next_nth(B, K, Steps) -> at(B, index(B, inc(K)) + Steps - 1). -spec first(bindict()) -> {key(), value()} | not_found. @doc : Returns the first key - value pair or ' not_found ' if the dict is empty first(B) -> at(B, 0). -spec foldl(bindict(), fun(), any()) -> any(). foldl(B, F, Acc) -> case first(B) of {Key, Value} -> do_foldl(B, F, Key, F(Key, Value, Acc)); not_found -> Acc end. do_foldl(B, F, PrevKey, Acc) -> case next(B, PrevKey) of {Key, Value} -> do_foldl(B, F, Key, F(Key, Value, Acc)); not_found -> Acc end. size(#bindict{b = B}) -> erlang:byte_size(B). at(B, I) -> Offset = index2offset(B, I), KeySize = B#bindict.key_size, ValueSize = B#bindict.value_size, case B#bindict.b of <<_:Offset/binary, Key:KeySize/binary, Value:ValueSize/binary, _/binary>> -> {Key, Value}; _ -> not_found end. %% INTERNAL HELPERS %% index2offset(_, 0) -> 0; index2offset(B, I) -> I * B#bindict.block_size. %% @doc: Uses binary search to find the index of the given key. If the %% key does not exist, the index where it should be inserted is %% returned. -spec index(bindict(), key()) -> index(). index(<<>>, _) -> 0; index(B, K) -> N = byte_size(B#bindict.b) div B#bindict.block_size, index(B, 0, N, K). index(_B, Low, High, _K) when High =:= Low -> Low; index(_B, Low, High, _K) when High < Low -> -1; index(B, Low, High, K) -> Mid = (Low + High) div 2, MidOffset = index2offset(B, Mid), KeySize = B#bindict.key_size, case byte_size(B#bindict.b) > MidOffset of true -> <<_:MidOffset/binary, MidKey:KeySize/binary, _/binary>> = B#bindict.b, if MidKey > K -> index(B, Low, Mid, K); MidKey < K -> index(B, Mid + 1, High, K); MidKey =:= K -> Mid end; false -> Mid end. inc(B) -> IncInt = binary:decode_unsigned(B) + 1, SizeBits = erlang:size(B) * 8, <<IncInt:SizeBits>>. %% }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
null
https://raw.githubusercontent.com/stofel/ecldb/2d707b3dad0212c417594c2f93cf1beefc5ee342/src/ecldb_ring.erl
erlang
Hash ring module Add domain to ring Del domain from ring % TODO -export([new/2, new/3, insert/3, bulk_insert/2, append/3, find/2, foldl/3]). -export([next/2, next_nth/3, first/1, last/1, delete/2, compact/1, cas/4, update/4]). -export([merge/2, intersection/1, intersection/2]). }}} ADD & DEL {{{ add N domains to ring, return count domains in ring }}} ROUTING {{{ -define(MODE, proxy). mode() -> ?MODE. domains() -> domains. Module = ClusterName }}} @doc: Space-efficient dictionary implemented using a binary This module implements a space-efficient dictionary with no Keys and values are fixed size binaries stored ordered in a larger binary which acts as a sparse array. All operations are implemented using a binary search. As large binaries can be shared among processes, there can be multiple concurrent readers of an instance of this structure. serialize/1 and deserialize/1 -module(ecl_bisect). -compile({no_auto_import, [size/1]}). API @doc: Returns a new empty dictionary where where the keys and values will always be of the given size. @doc: Returns a new dictionary with the given data @doc: Inserts the key and value into the dictionary. If the size of key and value is wrong, throws badarg. If the key is already in the array, the value is updated. @doc: Returns the next larger key and value associated with it or 'not_found' if no larger key exists. @doc: Returns the nth next larger key and value associated with it or 'not_found' if it does not exist. @doc: Uses binary search to find the index of the given key. If the key does not exist, the index where it should be inserted is returned. }}}
-module(ecldb_ring). -include("../include/ecldb.hrl"). -export([ new/0, ring_size/1, add_domain/3, del_domain/3, list_domains/1, list_nodes/1, route/2, route/3, r/2, r/3 ]). -compile({no_auto_import, [size/1]}). Bisect exports { { { -export([serialize/1 , deserialize/1 , from_orddict/2 , , find_many/2 ] ) . -export([expected_size/2 , expected_size_mb/2 , num_keys/1 , size/1 ] ) . new() -> new(32,32). ring_size(Ring) -> size(Ring). add_domain(DomainKey, Ring) -> add_domain(DomainKey, Ring, 16). add_domain(DomainKey, Ring, N) when N > 0 -> Key = ecldb_misc:md5_hex(ecldb_misc:random_bin(16)), NewRing = insert(Ring, Key, DomainKey), add_domain(DomainKey, NewRing, N-1); add_domain(DomainKey, Ring, _N) -> DomainsCount = proplists:get_value(DomainKey, list_domains(Ring), 0), {ok, Ring, DomainsCount}. Del N damains from ring , return count domains in ring del_domain(DomainKey, Ring) -> del_domain(DomainKey, Ring, 1). del_domain(DomainKey, Ring, Num) -> KFun = fun (K, V, Acc) when V == DomainKey -> [K|Acc]; (_, _, Acc) -> Acc end, Keys = ecldb_misc:shuffle_list(foldl(Ring, KFun, [])), DFun = fun (Fu, [K|RestK], R, N) when N > 0 -> Fu(Fu, RestK, delete(R, K), N - 1); (_F, _, R, _N) -> R end, NewRing = DFun(DFun, Keys, Ring, Num), DomainsCount = proplists:get_value(DomainKey, list_domains(NewRing), 0), {ok, NewRing, DomainsCount}. list_domains(Ring) -> F = fun(_Key, Value, Acc) -> Counter = proplists:get_value(Value, Acc, 0), lists:keystore(Value, 1, Acc, {Value, Counter+1}) end, foldl(Ring, F, []). list_nodes(Ring) -> List = list_domains(Ring), F = fun ({{ok, #{node := Node}}, Len}, Acc) -> Counter = proplists:get_value(Node, Acc, 0), lists:keystore(Node, 1, Acc, {Node, Counter + Len}); (_, Acc) -> Acc end, lists:foldl(F, [], List). r(A, B) -> {A, B}. r(A, B, C) -> {A, B, C}. Route thru the rings 1 . use dynamic compiling beam with name same as name 2 . In dynamic compiling module : route(KeyHash ) - > ecldb_ring : route(?MODULE , ) . first ( ) - > ring1 . second ( ) - > ring2 . -define(ZERO_HASH, <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>). route(Module, Key) -> route(Module, Module:mode(), ecldb_misc:md5_hex(Key)). route(Module, norma, KeyHash) -> case get_domain(Module, first, KeyHash) of {ok, Domain} -> {ok, {norma, Domain}}; Else -> Else end; route(Module, Mode, KeyHash) -> case [get_domain(Module, Ring, KeyHash) || Ring <- [first, second]] of [{ok,V1}, {ok,V2}] when V1 == V2 -> {ok, {norma, V1}}; [{ok,V1}, {ok,V2}] -> {ok, {Mode, V1, V2}}; Else -> ?e(cluster_rings_error, ?p(Else)) end. get_domain(Module, Ring, KeyHash) -> case get_value_from_ring(Module, Ring, KeyHash) of {ok, ValueKey} -> case Module:domains() of #{ValueKey := Domain} -> {ok, Domain}; error -> ?e(domain_not_found) end; Else -> Else end. get_value_from_ring(Module, Ring, KeyHash) -> case next(Module:Ring(), KeyHash) of {_Next, V} -> {ok, V}; TODO optimize this case next(Module:Ring(), ?ZERO_HASH) of {_Next, V} -> {ok, V}; not_found -> ?e(domain_not_found) end end. Bisect { { { overhead per entry . Read and write access is O(log n ) . -author('Knut Nesheim < > ' ) . TYPES -type key_size() :: pos_integer(). -type value_size() :: pos_integer(). -type block_size() :: pos_integer(). -type key() :: binary(). -type value() :: binary(). -type index() :: pos_integer(). -record(bindict, { key_size :: key_size(), value_size :: value_size(), block_size :: block_size(), b :: binary() }). -type bindict() :: #bindict{}. -spec new(key_size(), value_size()) -> bindict(). new(KeySize, ValueSize) when is_integer(KeySize) andalso is_integer(ValueSize) -> new(KeySize, ValueSize, <<>>). -spec new(key_size(), value_size(), binary()) -> bindict(). new(KeySize, ValueSize, Data) when is_integer(KeySize) andalso is_integer(ValueSize) andalso is_binary(Data) -> #bindict{key_size = KeySize, value_size = ValueSize, block_size = KeySize + ValueSize, b = Data}. -spec insert(bindict(), key(), value()) -> bindict(). insert(B, K, V) when byte_size(K) =/= B#bindict.key_size orelse byte_size(V) =/= B#bindict.value_size -> erlang:error(badarg); insert(#bindict{b = <<>>} = B, K, V) -> B#bindict{b = <<K/binary, V/binary>>}; insert(B, K, V) -> Index = index(B, K), LeftOffset = Index * B#bindict.block_size, RightOffset = byte_size(B#bindict.b) - LeftOffset, KeySize = B#bindict.key_size, ValueSize = B#bindict.value_size, case B#bindict.b of <<Left:LeftOffset/binary, K:KeySize/binary, _:ValueSize/binary, Right/binary>> -> B#bindict{b = iolist_to_binary([Left, K, V, Right])}; <<Left:LeftOffset/binary, Right:RightOffset/binary>> -> B#bindict{b = iolist_to_binary([Left, K, V, Right])} end. -spec delete(bindict(), key()) -> bindict(). delete(B, K) -> LeftOffset = index2offset(B, index(B, K)), KeySize = B#bindict.key_size, ValueSize = B#bindict.value_size, case B#bindict.b of <<Left:LeftOffset/binary, K:KeySize/binary, _:ValueSize/binary, Right/binary>> -> B#bindict{b = <<Left/binary, Right/binary>>}; _ -> erlang:error(badarg) end. -spec next(bindict(), key()) -> {key(), value()} | not_found. next(B, K) -> next_nth(B, K, 1). -spec next_nth(bindict(), key(), non_neg_integer()) -> value() | not_found. next_nth(B, K, Steps) -> at(B, index(B, inc(K)) + Steps - 1). -spec first(bindict()) -> {key(), value()} | not_found. @doc : Returns the first key - value pair or ' not_found ' if the dict is empty first(B) -> at(B, 0). -spec foldl(bindict(), fun(), any()) -> any(). foldl(B, F, Acc) -> case first(B) of {Key, Value} -> do_foldl(B, F, Key, F(Key, Value, Acc)); not_found -> Acc end. do_foldl(B, F, PrevKey, Acc) -> case next(B, PrevKey) of {Key, Value} -> do_foldl(B, F, Key, F(Key, Value, Acc)); not_found -> Acc end. size(#bindict{b = B}) -> erlang:byte_size(B). at(B, I) -> Offset = index2offset(B, I), KeySize = B#bindict.key_size, ValueSize = B#bindict.value_size, case B#bindict.b of <<_:Offset/binary, Key:KeySize/binary, Value:ValueSize/binary, _/binary>> -> {Key, Value}; _ -> not_found end. INTERNAL HELPERS index2offset(_, 0) -> 0; index2offset(B, I) -> I * B#bindict.block_size. -spec index(bindict(), key()) -> index(). index(<<>>, _) -> 0; index(B, K) -> N = byte_size(B#bindict.b) div B#bindict.block_size, index(B, 0, N, K). index(_B, Low, High, _K) when High =:= Low -> Low; index(_B, Low, High, _K) when High < Low -> -1; index(B, Low, High, K) -> Mid = (Low + High) div 2, MidOffset = index2offset(B, Mid), KeySize = B#bindict.key_size, case byte_size(B#bindict.b) > MidOffset of true -> <<_:MidOffset/binary, MidKey:KeySize/binary, _/binary>> = B#bindict.b, if MidKey > K -> index(B, Low, Mid, K); MidKey < K -> index(B, Mid + 1, High, K); MidKey =:= K -> Mid end; false -> Mid end. inc(B) -> IncInt = binary:decode_unsigned(B) + 1, SizeBits = erlang:size(B) * 8, <<IncInt:SizeBits>>.
f22d12376b286a6d3e9c0be8a8f1afe1eb5a9812eca08c9174cae0073615217f
astampoulis/makam
myocamlbuild.ml
OASIS_START OASIS_STOP open Ocamlbuild_plugin;; open Command;; dispatch begin function | After_rules -> Ocamlbuild_js_of_ocaml.dispatcher After_rules ; let parsers = [ A"-I"; A"+camlp4/Camlp4Parsers"] in flag ["ocaml"; "compile"; "parsers"] (S parsers); rule "Bootstrap PEG parser generation (Stage 1)" ~prod:"bootPegParser.ml" ~deps:["bootstrap/dumpBootParser.byte"] begin fun env _build -> let ml = env "bootPegParser.ml" in let dump = env "bootstrap/dumpBootParser.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; Px ml]) end; rule "Bootstrap PEG parser generation (Stage 2)" ~prod:"boot2PegParser.ml" ~deps:["grammars/pegGrammar.peg"; "bootstrap/bootPegParserGen.byte"] begin fun env _build -> let ml = env "boot2PegParser.ml" in let peg = env "grammars/pegGrammar.peg" in let dump = env "bootstrap/bootPegParserGen.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; P peg; Px ml]) end; rule "Bootstrap PEG parser generation (Stage 3)" ~prod:"pegGrammar.ml" ~deps:["grammars/pegGrammar.peg"; "bootstrap/boot2PegParserGen.byte"] begin fun env _build -> let ml = env "pegGrammar.ml" in let peg = env "grammars/pegGrammar.peg" in let dump = env "bootstrap/boot2PegParserGen.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; P peg; Px ml]) end; rule "PEG parser generation" ~prod:"%.ml" ~deps:["%.peg";"parsing/pegParserGen.byte"] begin fun env _build -> let peg = env "%.peg" in let ml = env "%.ml" in let dump = env "parsing/pegParserGen.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; P peg; Px ml]) end; | hook -> Ocamlbuild_js_of_ocaml.dispatcher hook end;;
null
https://raw.githubusercontent.com/astampoulis/makam/bf7ed7592c21e0439484d7464e659eca5be3b2f9/myocamlbuild.ml
ocaml
OASIS_START OASIS_STOP open Ocamlbuild_plugin;; open Command;; dispatch begin function | After_rules -> Ocamlbuild_js_of_ocaml.dispatcher After_rules ; let parsers = [ A"-I"; A"+camlp4/Camlp4Parsers"] in flag ["ocaml"; "compile"; "parsers"] (S parsers); rule "Bootstrap PEG parser generation (Stage 1)" ~prod:"bootPegParser.ml" ~deps:["bootstrap/dumpBootParser.byte"] begin fun env _build -> let ml = env "bootPegParser.ml" in let dump = env "bootstrap/dumpBootParser.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; Px ml]) end; rule "Bootstrap PEG parser generation (Stage 2)" ~prod:"boot2PegParser.ml" ~deps:["grammars/pegGrammar.peg"; "bootstrap/bootPegParserGen.byte"] begin fun env _build -> let ml = env "boot2PegParser.ml" in let peg = env "grammars/pegGrammar.peg" in let dump = env "bootstrap/bootPegParserGen.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; P peg; Px ml]) end; rule "Bootstrap PEG parser generation (Stage 3)" ~prod:"pegGrammar.ml" ~deps:["grammars/pegGrammar.peg"; "bootstrap/boot2PegParserGen.byte"] begin fun env _build -> let ml = env "pegGrammar.ml" in let peg = env "grammars/pegGrammar.peg" in let dump = env "bootstrap/boot2PegParserGen.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; P peg; Px ml]) end; rule "PEG parser generation" ~prod:"%.ml" ~deps:["%.peg";"parsing/pegParserGen.byte"] begin fun env _build -> let peg = env "%.peg" in let ml = env "%.ml" in let dump = env "parsing/pegParserGen.byte" in let tags = tags_of_pathname ml in Cmd(S[A dump; T tags; P peg; Px ml]) end; | hook -> Ocamlbuild_js_of_ocaml.dispatcher hook end;;