_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
e3f2878616376fbc96f8266fa54dfbb754a15e9309e0e02b9509378b5951bb78
kpreid/e-on-cl
jar.lisp
Copyright 2005 - 2007 , under the terms of the MIT X license found at ................ (defpackage :e.jar (:use :cl :e.elib :zip) (:documentation "Access to jar/zip files, so that we can borrow Java E's emakers.") (:export)) (in-package :e.jar) (defun open-jar (pathname) (let ((zipfile (open-zipfile pathname))) ; XXX finalizer to close zip file (e-lambda "org.cubik.cle.prim.open-jar$jar" () (:|getOpt| ((subpath 'string)) "Return a file from the jar file, or null if it does not exist. Does not yet support getting directories." (let ((zip-entry (get-zipfile-entry subpath zipfile))) (when zip-entry (e-lambda |entry| () (:|_clFileWriteDate| () "XXX this interface to be revised. The modification date of an item in a jar is that of the jar itself, for our purposes." (file-write-date pathname)) (:|getText| () (let ((data (zipfile-entry-contents zip-entry))) use sbcl 's if it 's available , because it 's exported , ;; otherwise borrow zip's internals ;; XXX use flexi-streams directly instead #+sbcl (sb-ext:octets-to-string data :external-format :ascii) #-sbcl (zip::octets-to-string data :us-ascii))) (:|getTwine| () XXX imitating EoJ jar uris ; review (e. (e. |entry| |getText|) |asFrom| (format nil "jar:~A!~A" pathname subpath))))))))))
null
https://raw.githubusercontent.com/kpreid/e-on-cl/f93d188051c66db0ad4ff150bd73b838f7bc25ed/lisp/jar.lisp
lisp
XXX finalizer to close zip file otherwise borrow zip's internals XXX use flexi-streams directly instead review
Copyright 2005 - 2007 , under the terms of the MIT X license found at ................ (defpackage :e.jar (:use :cl :e.elib :zip) (:documentation "Access to jar/zip files, so that we can borrow Java E's emakers.") (:export)) (in-package :e.jar) (defun open-jar (pathname) (let ((zipfile (open-zipfile pathname))) (e-lambda "org.cubik.cle.prim.open-jar$jar" () (:|getOpt| ((subpath 'string)) "Return a file from the jar file, or null if it does not exist. Does not yet support getting directories." (let ((zip-entry (get-zipfile-entry subpath zipfile))) (when zip-entry (e-lambda |entry| () (:|_clFileWriteDate| () "XXX this interface to be revised. The modification date of an item in a jar is that of the jar itself, for our purposes." (file-write-date pathname)) (:|getText| () (let ((data (zipfile-entry-contents zip-entry))) use sbcl 's if it 's available , because it 's exported , #+sbcl (sb-ext:octets-to-string data :external-format :ascii) #-sbcl (zip::octets-to-string data :us-ascii))) (:|getTwine| () (e. (e. |entry| |getText|) |asFrom| (format nil "jar:~A!~A" pathname subpath))))))))))
8955663e05021a1c78da234aefa63b00ba71327f0aac8fbab64de00ec21456a2
Javran/advent-of-code
Uldr.hs
module Javran.AdventOfCode.GridSystem.RowThenCol.Uldr ( Dir (..), Coord, applyDir, oppositeDir, turnLeft, turnRight, uldrOfCoord, allDirs, ) where import Data.Bifunctor type Coord = (Int, Int) -- row then col data Dir = U | L | D | R deriving (Eq, Ord, Enum, Show) applyDir :: Dir -> Coord -> Coord applyDir = \case U -> first (\r -> r - 1) D -> first (\r -> r + 1) L -> second (\c -> c - 1) R -> second (\c -> c + 1) # INLINEABLE applyDir # oppositeDir :: Dir -> Dir oppositeDir = \case U -> D D -> U L -> R R -> L {-# INLINEABLE oppositeDir #-} turnLeft :: Dir -> Dir turnLeft = \case U -> L L -> D D -> R R -> U # INLINEABLE turnLeft # turnRight :: Dir -> Dir turnRight = \case U -> R R -> D D -> L L -> U # INLINEABLE turnRight # uldrOfCoord :: Coord -> [Coord] uldrOfCoord (r, c) = [(r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)] {-# INLINEABLE uldrOfCoord #-} allDirs :: [Dir] allDirs = [U, L, D, R] # INLINEABLE allDirs #
null
https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/GridSystem/RowThenCol/Uldr.hs
haskell
row then col # INLINEABLE oppositeDir # # INLINEABLE uldrOfCoord #
module Javran.AdventOfCode.GridSystem.RowThenCol.Uldr ( Dir (..), Coord, applyDir, oppositeDir, turnLeft, turnRight, uldrOfCoord, allDirs, ) where import Data.Bifunctor data Dir = U | L | D | R deriving (Eq, Ord, Enum, Show) applyDir :: Dir -> Coord -> Coord applyDir = \case U -> first (\r -> r - 1) D -> first (\r -> r + 1) L -> second (\c -> c - 1) R -> second (\c -> c + 1) # INLINEABLE applyDir # oppositeDir :: Dir -> Dir oppositeDir = \case U -> D D -> U L -> R R -> L turnLeft :: Dir -> Dir turnLeft = \case U -> L L -> D D -> R R -> U # INLINEABLE turnLeft # turnRight :: Dir -> Dir turnRight = \case U -> R R -> D D -> L L -> U # INLINEABLE turnRight # uldrOfCoord :: Coord -> [Coord] uldrOfCoord (r, c) = [(r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)] allDirs :: [Dir] allDirs = [U, L, D, R] # INLINEABLE allDirs #
f0248446f8ea25d55c5361045d6bc6c8cc0e5d82198185f44b039df07d823cd1
SonarQubeCommunity/sonar-erlang
linelength.erl
-module(linelength). it is 100 chars long , so it is fine , the question is what shall I write here to ex % it only has comments, so I have to write more than previously, which is hard a little bit but I c % this is a long line, but only contains comments, this should be marked as well, because it is a hard rule, without exceptions B = {world, A}, C = {{a, b, [1,2,4,5]},{[{a, b, c, [12, 12, 34]},{[A, B], [1, 2]}], [error, error, stg, error]}}, this line is bigger than one hundred because of the comments , so it should be marked as ? {A}.
null
https://raw.githubusercontent.com/SonarQubeCommunity/sonar-erlang/279eb7ccd84787c1c0cfd34b9a07981eb20183e3/erlang-checks/src/test/resources/checks/linelength.erl
erlang
it only has comments, so I have to write more than previously, which is hard a little bit but I c this is a long line, but only contains comments, this should be marked as well, because it is a hard rule, without exceptions
-module(linelength). it is 100 chars long , so it is fine , the question is what shall I write here to ex B = {world, A}, C = {{a, b, [1,2,4,5]},{[{a, b, c, [12, 12, 34]},{[A, B], [1, 2]}], [error, error, stg, error]}}, this line is bigger than one hundred because of the comments , so it should be marked as ? {A}.
63f0a1c9737ae47e3289281600b3438a020a3603e77a68504ddd3db880e6dd1d
coco-team/lustrec
machine_code_common.mli
val pp_val: Format.formatter -> Machine_code_types.value_t -> unit val is_memory: Machine_code_types.machine_t -> Lustre_types.var_decl -> bool val is_output: Machine_code_types.machine_t -> Lustre_types.var_decl -> bool val is_const_value: Machine_code_types.value_t -> bool val get_const_assign: Machine_code_types.machine_t -> Lustre_types.var_decl -> Machine_code_types.value_t val get_stateless_status: Machine_code_types.machine_t -> bool * bool val mk_val: Machine_code_types.value_t_desc -> Types.type_expr -> Machine_code_types.value_t val mk_conditional: ?lustre_eq:Lustre_types.eq -> Machine_code_types.value_t -> Machine_code_types.instr_t list -> Machine_code_types.instr_t list -> Machine_code_types.instr_t val empty_machine: Machine_code_types.machine_t val arrow_machine: Machine_code_types.machine_t val new_instance: Lustre_types.node_desc -> Lustre_types.top_decl -> Lustre_types.tag -> Lustre_types.ident val value_of_dimension: Machine_code_types.machine_t -> Dimension.dim_expr -> Machine_code_types.value_t val dimension_of_value:Machine_code_types.value_t -> Dimension.dim_expr val pp_instr: Format.formatter -> Machine_code_types.instr_t -> unit val pp_instrs: Format.formatter -> Machine_code_types.instr_t list -> unit val pp_machines: Format.formatter -> Machine_code_types.machine_t list -> unit val get_machine_opt: string -> Machine_code_types.machine_t list -> Machine_code_types.machine_t option val get_node_def: string -> Machine_code_types.machine_t -> Lustre_types.node_desc val join_guards_list: Machine_code_types.instr_t list -> Machine_code_types.instr_t list
null
https://raw.githubusercontent.com/coco-team/lustrec/b21f9820df97e661633cd4418fdab68a6c6ca67d/src/machine_code_common.mli
ocaml
val pp_val: Format.formatter -> Machine_code_types.value_t -> unit val is_memory: Machine_code_types.machine_t -> Lustre_types.var_decl -> bool val is_output: Machine_code_types.machine_t -> Lustre_types.var_decl -> bool val is_const_value: Machine_code_types.value_t -> bool val get_const_assign: Machine_code_types.machine_t -> Lustre_types.var_decl -> Machine_code_types.value_t val get_stateless_status: Machine_code_types.machine_t -> bool * bool val mk_val: Machine_code_types.value_t_desc -> Types.type_expr -> Machine_code_types.value_t val mk_conditional: ?lustre_eq:Lustre_types.eq -> Machine_code_types.value_t -> Machine_code_types.instr_t list -> Machine_code_types.instr_t list -> Machine_code_types.instr_t val empty_machine: Machine_code_types.machine_t val arrow_machine: Machine_code_types.machine_t val new_instance: Lustre_types.node_desc -> Lustre_types.top_decl -> Lustre_types.tag -> Lustre_types.ident val value_of_dimension: Machine_code_types.machine_t -> Dimension.dim_expr -> Machine_code_types.value_t val dimension_of_value:Machine_code_types.value_t -> Dimension.dim_expr val pp_instr: Format.formatter -> Machine_code_types.instr_t -> unit val pp_instrs: Format.formatter -> Machine_code_types.instr_t list -> unit val pp_machines: Format.formatter -> Machine_code_types.machine_t list -> unit val get_machine_opt: string -> Machine_code_types.machine_t list -> Machine_code_types.machine_t option val get_node_def: string -> Machine_code_types.machine_t -> Lustre_types.node_desc val join_guards_list: Machine_code_types.instr_t list -> Machine_code_types.instr_t list
74f5dbe1a15b36097876f54e6b1cc9833d88ec88e703add1558d15f1ee24ef08
facebookincubator/hsthrift
HeaderChannelTest.hs
Copyright ( c ) Facebook , Inc. and its affiliates . module HeaderChannelTest where import Control.Exception import Control.Monad.Trans.Class import Data.Proxy import Foreign import Foreign.C import Network (testServerHost) import Test.HUnit import TestRunner import Util.EventBase import Thrift.Api import Thrift.Channel import Thrift.Channel.HeaderChannel import Thrift.Monad import Thrift.Protocol import Thrift.Protocol.Id import Math.Adder.Client import Math.Calculator.Client myRpcOptions :: RpcOptions myRpcOptions = defaultRpcOptions { rpc_timeout = 5000 } mySvcConf :: Int -> HeaderConfig Calculator mySvcConf port = HeaderConfig { headerHost = testServerHost , headerPort = port , headerProtocolId = compactProtocolId , headerConnTimeout = 5000 , headerSendTimeout = 5000 , headerRecvTimeout = 5000 } mkChannelTest :: String -> Thrift Calculator () -> Test mkChannelTest label action = TestLabel label $ TestCase $ withEventBaseDataplane $ \evb -> withMathServer $ \port -> withHeaderChannel evb (mySvcConf port) action addTest :: Test addTest = mkChannelTest "add test" $ do res <- withOptions myRpcOptions $ add 5 2 lift $ assertEqual "5 + 2 = 7" 7 res divideTest :: Test divideTest = mkChannelTest "divide test" $ do res <- withOptions myRpcOptions $ divide 9 3 lift $ assertEqual "9 / 3 = 3" 3 res putAndGetTest :: Test putAndGetTest = mkChannelTest "Get gets Put" $ do res <- withOptions myRpcOptions $ do put val get lift $ assertEqual "Get is same as Put" res val where val = 1337 Tests for IO variants of the thrift functions ----------------- mkChannelIOTest :: String -> (forall p . Protocol p => Counter -> HeaderWrappedChannel Calculator -> Proxy p -> IO ()) -> Test mkChannelIOTest label action = TestLabel label $ TestCase $ withEventBaseDataplane $ \evb -> withMathServer $ \port -> do counter <- newCounter withHeaderChannelIO evb (mySvcConf port) $ action counter addIOTest :: Test addIOTest = mkChannelIOTest "addIO test" $ \counter c p -> do res <- addIO p c counter myRpcOptions 5 2 assertEqual "5 + 2 = 7" 7 res divideIOTest :: Test divideIOTest = mkChannelIOTest "divideIO test" $ \counter c p -> do res <- divideIO p c counter myRpcOptions 9 3 assertEqual "9 / 3 = 3" 3 res putAndGetIOTest :: Test putAndGetIOTest = mkChannelIOTest "GetIO gets PutIO" $ \counter c p -> do putIO p c counter myRpcOptions val res <- getIO p c counter myRpcOptions assertEqual "Get is same as Put" res val where val = 1337 main :: IO () main = testRunner $ TestList [ addTest , divideTest , putAndGetTest , addIOTest , divideIOTest , putAndGetIOTest ] -- ----------------------------------------------------------------------------- withMathServer :: (Int -> IO a) -> IO a withMathServer action = bracket makeCPPServer destroyCPPServer $ \s -> do p <- getPort s action $ fromIntegral p data Server foreign import ccall safe "make_cpp_server" makeCPPServer :: IO (Ptr Server) foreign import ccall unsafe "get_port_from_server" getPort :: Ptr Server -> IO CInt foreign import ccall safe "destroy_cpp_server" destroyCPPServer :: Ptr Server -> IO ()
null
https://raw.githubusercontent.com/facebookincubator/hsthrift/d3ff75d487e9d0c2904d18327373b603456e7a01/cpp-channel/test/HeaderChannelTest.hs
haskell
--------------- -----------------------------------------------------------------------------
Copyright ( c ) Facebook , Inc. and its affiliates . module HeaderChannelTest where import Control.Exception import Control.Monad.Trans.Class import Data.Proxy import Foreign import Foreign.C import Network (testServerHost) import Test.HUnit import TestRunner import Util.EventBase import Thrift.Api import Thrift.Channel import Thrift.Channel.HeaderChannel import Thrift.Monad import Thrift.Protocol import Thrift.Protocol.Id import Math.Adder.Client import Math.Calculator.Client myRpcOptions :: RpcOptions myRpcOptions = defaultRpcOptions { rpc_timeout = 5000 } mySvcConf :: Int -> HeaderConfig Calculator mySvcConf port = HeaderConfig { headerHost = testServerHost , headerPort = port , headerProtocolId = compactProtocolId , headerConnTimeout = 5000 , headerSendTimeout = 5000 , headerRecvTimeout = 5000 } mkChannelTest :: String -> Thrift Calculator () -> Test mkChannelTest label action = TestLabel label $ TestCase $ withEventBaseDataplane $ \evb -> withMathServer $ \port -> withHeaderChannel evb (mySvcConf port) action addTest :: Test addTest = mkChannelTest "add test" $ do res <- withOptions myRpcOptions $ add 5 2 lift $ assertEqual "5 + 2 = 7" 7 res divideTest :: Test divideTest = mkChannelTest "divide test" $ do res <- withOptions myRpcOptions $ divide 9 3 lift $ assertEqual "9 / 3 = 3" 3 res putAndGetTest :: Test putAndGetTest = mkChannelTest "Get gets Put" $ do res <- withOptions myRpcOptions $ do put val get lift $ assertEqual "Get is same as Put" res val where val = 1337 mkChannelIOTest :: String -> (forall p . Protocol p => Counter -> HeaderWrappedChannel Calculator -> Proxy p -> IO ()) -> Test mkChannelIOTest label action = TestLabel label $ TestCase $ withEventBaseDataplane $ \evb -> withMathServer $ \port -> do counter <- newCounter withHeaderChannelIO evb (mySvcConf port) $ action counter addIOTest :: Test addIOTest = mkChannelIOTest "addIO test" $ \counter c p -> do res <- addIO p c counter myRpcOptions 5 2 assertEqual "5 + 2 = 7" 7 res divideIOTest :: Test divideIOTest = mkChannelIOTest "divideIO test" $ \counter c p -> do res <- divideIO p c counter myRpcOptions 9 3 assertEqual "9 / 3 = 3" 3 res putAndGetIOTest :: Test putAndGetIOTest = mkChannelIOTest "GetIO gets PutIO" $ \counter c p -> do putIO p c counter myRpcOptions val res <- getIO p c counter myRpcOptions assertEqual "Get is same as Put" res val where val = 1337 main :: IO () main = testRunner $ TestList [ addTest , divideTest , putAndGetTest , addIOTest , divideIOTest , putAndGetIOTest ] withMathServer :: (Int -> IO a) -> IO a withMathServer action = bracket makeCPPServer destroyCPPServer $ \s -> do p <- getPort s action $ fromIntegral p data Server foreign import ccall safe "make_cpp_server" makeCPPServer :: IO (Ptr Server) foreign import ccall unsafe "get_port_from_server" getPort :: Ptr Server -> IO CInt foreign import ccall safe "destroy_cpp_server" destroyCPPServer :: Ptr Server -> IO ()
09be551f6f5d8f83050ce740300bab17838aa85448935dade74fa3c22b52630a
nallen05/rw-ut
rw-ut.lisp
; -ut ; TODO ; ; -tests ; -names of months and days of week ; -12 hour clock, a.m./p.m. ; -optimize (defpackage :rw-ut (:use :cl) (:export ; using :read-time-string :write-time-string :*time-zone* ; old [depricated] API :r-ut :w-ut ; compiling fast readers or writers at runtime :read-time-string-pattern->src :write-time-string-pattern->src)) (in-package :rw-ut) ; special BEWARE : assumes GMT / UTC by default (defconstant +default-ut-pattern+ SBCL complains at normal DEFCONSTANT ... (symbol-value '+default-ut-pattern+) "YYYY?/MM?/DD? hh?:mm?:ss")) ; util (defun .get-match (string pattern-table) " (.get-match \"01234\" '((\"0123\" . xx))) -> xx, 4 (.get-match \"abcde\" '((\"0123\" . xx))) -> NIL " (dolist (% pattern-table) (destructuring-bind (pattern . xx) % (let ((pattern-length (length pattern)) (mismatch (mismatch string pattern))) (if (or (null mismatch) (eql mismatch pattern-length)) (return-from .get-match (values xx pattern-length))))))) (defun .parse-string (string pattern-table &optional (accum "")) " (.parse-string \"jjj0123jjjjj012345abc\" '((\"01234\" . |1-4|) (\"0123\" . |1-3|) (\"abc\" . ABC)) -> (\"jjj\" |1-3| \"jjjjj\" |1-4| \"5\" ABC) " (if (zerop (length string)) (if (not (zerop (length accum))) (list accum)) (let ((1st-char (char string 0))) (if (char= 1st-char #\\) (.parse-string (subseq string 2) pattern-table (format nil "~A~A" accum (char string 1))) (multiple-value-bind (fn pattern-length) (.get-match string pattern-table) (if fn (if (zerop (length accum)) (cons fn #1=(.parse-string (subseq string pattern-length) pattern-table)) (list* accum fn #1#)) (.parse-string (subseq string 1) pattern-table (format nil "~A~A" accum (char string 0))))))))) ; READ-TIME-STRING (defparameter *read-ut-pattern-table* `(("?" . ?) ("YYYY" . year) ("YY" . year) ("MM" . month) ("M" . month) ("DD" . date) ("D" . date) ("hh" . hour) ("h" . hour) ("mm" . minute) ("m" . minute) ("ss" . second) ("s" . second))) (defun read-time-string-pattern->src (pattern) `(lambda (string) (let ((string-length (length string)) (n 0) (year 0) (hour 0) (minute 0) (second 0) (date 1) (month 1)) (declare (ignorable string-length)) ,@(labels ((rfn (%s) (when %s (destructuring-bind (1st% . rest%) %s (etypecase 1st% (string (cons `(incf n ,(length 1st%)) (rfn rest%))) (symbol (case 1st% (? (list `(when (> string-length n) ,@(rfn rest%)))) (otherwise (cons `(multiple-value-setq (,1st% n) (parse-integer string :start n :junk-allowed t)) (rfn rest%)))))))))) (rfn (.parse-string pattern *read-ut-pattern-table*))) (encode-universal-time second minute hour date month year *time-zone*)))) (defun read-time-string (string &optional (pattern +default-ut-pattern+)) "reads `STRING' according to the pattern string `PATTERN' and returns a universal time like would be returned by ENCODE-UNIVERSAL-TIME" (funcall (coerce (read-time-string-pattern->src pattern) 'function) string)) (define-compiler-macro read-time-string (&whole whole string &optional (pattern +default-ut-pattern+)) (cond ((stringp pattern) `(funcall ,(read-time-string-pattern->src pattern) ,string)) ((and (symbolp pattern) (constantp pattern)) `(funcall ,(read-time-string-pattern->src (symbol-value pattern)) ,string)) (t (warn "<<<READ-TIME-STRING is a _lot_ faster if `PATTERN' is a constant or a string. see READ-TIME-STRING-PATTERN->SRC if you need to compile a fast reader at runtime>>>") whole))) ; WRITE-TIME-STRING (defparameter *write-ut-pattern-table* `(("?" . ?) ("YYYY" year n) ("YY" year 2) ("MM" month 2) ("M" month n) ("DD" date 2) ("D" date n) ("hh" hour 2) ("h" hour n) ("mm" minute 2) ("m" minute n) ("ss" second 2) ("s" second n))) (defun .parsed-string->ut-parts (parsed-pattern) " (.parsed-string->ut-parts '(\"jjj\" (year n) \"jjjjj\" (date 2) ? \"5\" (month 2))) -> (year date month) " (mapcar 'first (remove-if-not 'listp parsed-pattern))) (defun .ut-part->minimum-value (symbol) (ecase symbol ((second minute hour year) 0) ((date month) 1))) (defun write-time-string-pattern->src (pattern) `(lambda (ut) (multiple-value-bind (second minute hour date month year) (decode-universal-time ut *time-zone*) (declare (ignorable second minute hour date month year)) (with-output-to-string (out) ,@(labels ((rfn (%s) (when %s (destructuring-bind (1st% . rest%) %s (typecase 1st% (string (cons `(write-string ,1st% out) (rfn rest%))) (otherwise (case 1st% (? (list `(unless (and ,@(mapcar (lambda (_) `(= ,_ ,(.ut-part->minimum-value _))) (.parsed-string->ut-parts rest%))) ,@(rfn rest%)))) (otherwise (destructuring-bind (symbol digits) 1st% (cons (ecase digits (n `(princ ,symbol out)) (2 (case symbol (year `(format out "~2,'0d" (mod year 100))) (otherwise `(format out "~2,'0d" ,symbol))))) (rfn rest%))))))))))) (rfn (.parse-string pattern *write-ut-pattern-table*))))))) (defun write-time-string (ut &optional (pattern +default-ut-pattern+)) "write the universal `UT' as a string according to the pattern string `PATTERN'" (funcall (coerce (write-time-string-pattern->src pattern) 'function) ut)) (define-compiler-macro write-time-string (&whole whole ut &optional (pattern +default-ut-pattern+)) (cond ((stringp pattern) `(funcall ,(write-time-string-pattern->src pattern) ,ut)) ((and (symbolp pattern) (constantp pattern)) `(funcall ,(write-time-string-pattern->src (symbol-value pattern)) ,ut)) (t (warn "<<<WRITE-TIME-STRING is a _lot_ faster if `PATTERN' is a constant or a string. see WRITE-TIME-STRING-PATTERN->SRC if you need to compile a fast writer at runtime>>>") whole))) (defun write-time-string* (ut &rest pattern-and-format-args) "like WRITE-TIME-STRING except PATTERN can be followed by N format arguments [like FORMAT] that are plugged in to PATTERN _after_ WRITE-TIME-STRING does it's magic" (apply #'format nil (funcall (coerce (write-time-string-pattern->src (first pattern-and-format-args)) 'function) ut) (rest pattern-and-format-args))) (define-compiler-macro write-time-string* (&whole whole ut &rest pattern-and-format-args) (let ((pattern (or (first pattern-and-format-args) +default-ut-pattern+)) (args (rest pattern-and-format-args))) (cond ((stringp pattern) `(apply #'format nil (funcall ,(write-time-string-pattern->src pattern) ,ut) ,@args)) ((and (symbolp pattern) (constantp pattern)) `(apply #'format nil (funcall ,(write-time-string-pattern->src (symbol-value pattern)) ,ut) ,@args)) (t (warn "<<<WRITE-TIME-STRING* is a _lot_ faster if `PATTERN' is a constant or a string. see WRITE-TIME-STRING-PATTERN->SRC if you need to compile a fast writer at runtime>>>") whole)))) ; old [depricated] API (defmacro r-ut (&rest args) (warn "use of the R-UT macro is depricated. use READ-TIME-STRING instead") `(read-time-string ,@args)) (defmacro w-ut (&rest args) (warn "use of the W-UT macro is depricated. use WRITE-TIME-STRING instead") `(write-time-string ,@args))
null
https://raw.githubusercontent.com/nallen05/rw-ut/7535c3590aa7fe2bfb5c01a282337c100875b3a4/rw-ut.lisp
lisp
-tests -names of months and days of week -12 hour clock, a.m./p.m. -optimize using old [depricated] API compiling fast readers or writers at runtime special util READ-TIME-STRING WRITE-TIME-STRING old [depricated] API
-ut TODO (defpackage :rw-ut (:use :cl) :read-time-string :write-time-string :*time-zone* :r-ut :w-ut :read-time-string-pattern->src :write-time-string-pattern->src)) (in-package :rw-ut) BEWARE : assumes GMT / UTC by default (defconstant +default-ut-pattern+ SBCL complains at normal DEFCONSTANT ... (symbol-value '+default-ut-pattern+) "YYYY?/MM?/DD? hh?:mm?:ss")) (defun .get-match (string pattern-table) " (.get-match \"01234\" '((\"0123\" . xx))) -> xx, 4 (.get-match \"abcde\" '((\"0123\" . xx))) -> NIL " (dolist (% pattern-table) (destructuring-bind (pattern . xx) % (let ((pattern-length (length pattern)) (mismatch (mismatch string pattern))) (if (or (null mismatch) (eql mismatch pattern-length)) (return-from .get-match (values xx pattern-length))))))) (defun .parse-string (string pattern-table &optional (accum "")) " (.parse-string \"jjj0123jjjjj012345abc\" '((\"01234\" . |1-4|) (\"0123\" . |1-3|) (\"abc\" . ABC)) -> (\"jjj\" |1-3| \"jjjjj\" |1-4| \"5\" ABC) " (if (zerop (length string)) (if (not (zerop (length accum))) (list accum)) (let ((1st-char (char string 0))) (if (char= 1st-char #\\) (.parse-string (subseq string 2) pattern-table (format nil "~A~A" accum (char string 1))) (multiple-value-bind (fn pattern-length) (.get-match string pattern-table) (if fn (if (zerop (length accum)) (cons fn #1=(.parse-string (subseq string pattern-length) pattern-table)) (list* accum fn #1#)) (.parse-string (subseq string 1) pattern-table (format nil "~A~A" accum (char string 0))))))))) (defparameter *read-ut-pattern-table* `(("?" . ?) ("YYYY" . year) ("YY" . year) ("MM" . month) ("M" . month) ("DD" . date) ("D" . date) ("hh" . hour) ("h" . hour) ("mm" . minute) ("m" . minute) ("ss" . second) ("s" . second))) (defun read-time-string-pattern->src (pattern) `(lambda (string) (let ((string-length (length string)) (n 0) (year 0) (hour 0) (minute 0) (second 0) (date 1) (month 1)) (declare (ignorable string-length)) ,@(labels ((rfn (%s) (when %s (destructuring-bind (1st% . rest%) %s (etypecase 1st% (string (cons `(incf n ,(length 1st%)) (rfn rest%))) (symbol (case 1st% (? (list `(when (> string-length n) ,@(rfn rest%)))) (otherwise (cons `(multiple-value-setq (,1st% n) (parse-integer string :start n :junk-allowed t)) (rfn rest%)))))))))) (rfn (.parse-string pattern *read-ut-pattern-table*))) (encode-universal-time second minute hour date month year *time-zone*)))) (defun read-time-string (string &optional (pattern +default-ut-pattern+)) "reads `STRING' according to the pattern string `PATTERN' and returns a universal time like would be returned by ENCODE-UNIVERSAL-TIME" (funcall (coerce (read-time-string-pattern->src pattern) 'function) string)) (define-compiler-macro read-time-string (&whole whole string &optional (pattern +default-ut-pattern+)) (cond ((stringp pattern) `(funcall ,(read-time-string-pattern->src pattern) ,string)) ((and (symbolp pattern) (constantp pattern)) `(funcall ,(read-time-string-pattern->src (symbol-value pattern)) ,string)) (t (warn "<<<READ-TIME-STRING is a _lot_ faster if `PATTERN' is a constant or a string. see READ-TIME-STRING-PATTERN->SRC if you need to compile a fast reader at runtime>>>") whole))) (defparameter *write-ut-pattern-table* `(("?" . ?) ("YYYY" year n) ("YY" year 2) ("MM" month 2) ("M" month n) ("DD" date 2) ("D" date n) ("hh" hour 2) ("h" hour n) ("mm" minute 2) ("m" minute n) ("ss" second 2) ("s" second n))) (defun .parsed-string->ut-parts (parsed-pattern) " (.parsed-string->ut-parts '(\"jjj\" (year n) \"jjjjj\" (date 2) ? \"5\" (month 2))) -> (year date month) " (mapcar 'first (remove-if-not 'listp parsed-pattern))) (defun .ut-part->minimum-value (symbol) (ecase symbol ((second minute hour year) 0) ((date month) 1))) (defun write-time-string-pattern->src (pattern) `(lambda (ut) (multiple-value-bind (second minute hour date month year) (decode-universal-time ut *time-zone*) (declare (ignorable second minute hour date month year)) (with-output-to-string (out) ,@(labels ((rfn (%s) (when %s (destructuring-bind (1st% . rest%) %s (typecase 1st% (string (cons `(write-string ,1st% out) (rfn rest%))) (otherwise (case 1st% (? (list `(unless (and ,@(mapcar (lambda (_) `(= ,_ ,(.ut-part->minimum-value _))) (.parsed-string->ut-parts rest%))) ,@(rfn rest%)))) (otherwise (destructuring-bind (symbol digits) 1st% (cons (ecase digits (n `(princ ,symbol out)) (2 (case symbol (year `(format out "~2,'0d" (mod year 100))) (otherwise `(format out "~2,'0d" ,symbol))))) (rfn rest%))))))))))) (rfn (.parse-string pattern *write-ut-pattern-table*))))))) (defun write-time-string (ut &optional (pattern +default-ut-pattern+)) "write the universal `UT' as a string according to the pattern string `PATTERN'" (funcall (coerce (write-time-string-pattern->src pattern) 'function) ut)) (define-compiler-macro write-time-string (&whole whole ut &optional (pattern +default-ut-pattern+)) (cond ((stringp pattern) `(funcall ,(write-time-string-pattern->src pattern) ,ut)) ((and (symbolp pattern) (constantp pattern)) `(funcall ,(write-time-string-pattern->src (symbol-value pattern)) ,ut)) (t (warn "<<<WRITE-TIME-STRING is a _lot_ faster if `PATTERN' is a constant or a string. see WRITE-TIME-STRING-PATTERN->SRC if you need to compile a fast writer at runtime>>>") whole))) (defun write-time-string* (ut &rest pattern-and-format-args) "like WRITE-TIME-STRING except PATTERN can be followed by N format arguments [like FORMAT] that are plugged in to PATTERN _after_ WRITE-TIME-STRING does it's magic" (apply #'format nil (funcall (coerce (write-time-string-pattern->src (first pattern-and-format-args)) 'function) ut) (rest pattern-and-format-args))) (define-compiler-macro write-time-string* (&whole whole ut &rest pattern-and-format-args) (let ((pattern (or (first pattern-and-format-args) +default-ut-pattern+)) (args (rest pattern-and-format-args))) (cond ((stringp pattern) `(apply #'format nil (funcall ,(write-time-string-pattern->src pattern) ,ut) ,@args)) ((and (symbolp pattern) (constantp pattern)) `(apply #'format nil (funcall ,(write-time-string-pattern->src (symbol-value pattern)) ,ut) ,@args)) (t (warn "<<<WRITE-TIME-STRING* is a _lot_ faster if `PATTERN' is a constant or a string. see WRITE-TIME-STRING-PATTERN->SRC if you need to compile a fast writer at runtime>>>") whole)))) (defmacro r-ut (&rest args) (warn "use of the R-UT macro is depricated. use READ-TIME-STRING instead") `(read-time-string ,@args)) (defmacro w-ut (&rest args) (warn "use of the W-UT macro is depricated. use WRITE-TIME-STRING instead") `(write-time-string ,@args))
e15a725b1a4091aa29fd5adf232f025b398a4ab4f7480afe236d207fb5b5bdfe
oubiwann/star-traders
project.clj
(defproject starlanes "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "BSD" :url "-3-Clause"} :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/math.combinatorics "0.0.4"]] :plugins [[lein-exec "0.3.1"]] :aot [starlanes.trader] :main starlanes.trader)
null
https://raw.githubusercontent.com/oubiwann/star-traders/8d7b85ce9ad6446f3b766cced08c120787a82352/clojure/project.clj
clojure
(defproject starlanes "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "BSD" :url "-3-Clause"} :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/math.combinatorics "0.0.4"]] :plugins [[lein-exec "0.3.1"]] :aot [starlanes.trader] :main starlanes.trader)
22e889adf32fb884ecb3a6aee8ed9e7fdf68f62c7da4524e7a72eef5cf4a9dcf
arcusfelis/binary2
binary2.erl
-module(binary2). Bytes -export([ reverse/1 , join/2 , duplicate/2 , suffix/2 , prefix/2 ]). %% Bits -export([ union/2 , subtract/2 , intersection/2 , inverse/1 ]). %% Trimming -export([ rtrim/1 , rtrim/2 , ltrim/1 , ltrim/2 , trim/1 , trim/2 ]). %% Parsing -export([ bin_to_int/1 ]). %% Matching -export([ optimize_patterns/1 ]). trim(B) -> trim(B, 0). ltrim(B) -> ltrim(B, 0). rtrim(B) -> rtrim(B, 0). rtrim(B, X) when is_binary(B), is_integer(X) -> S = byte_size(B), do_rtrim(S, B, X); rtrim(B, [_|_]=Xs) when is_binary(B) -> S = byte_size(B), do_mrtrim(S, B, Xs). ltrim(B, X) when is_binary(B), is_integer(X) -> do_ltrim(B, X); ltrim(B, [_|_]=Xs) when is_binary(B) -> do_mltrim(B, Xs). @doc The second element is a single integer element or an ordset of elements . trim(B, X) when is_binary(B), is_integer(X) -> From = ltrimc(B, X, 0), case byte_size(B) of From -> <<>>; S -> To = do_rtrimc(S, B, X), binary:part(B, From, To - From) end; trim(B, [_|_]=Xs) when is_binary(B) -> From = mltrimc(B, Xs, 0), case byte_size(B) of From -> <<>>; S -> To = do_mrtrimc(S, B, Xs), binary:part(B, From, To - From) end. do_ltrim(<<X, B/binary>>, X) -> do_ltrim(B, X); do_ltrim(B, _X) -> B. %% multi, left trimming. do_mltrim(<<X, B/binary>> = XB, Xs) -> case ordsets:is_element(X, Xs) of true -> do_mltrim(B, Xs); false -> XB end; do_mltrim(<<>>, _Xs) -> <<>>. do_rtrim(0, _B, _X) -> <<>>; do_rtrim(S, B, X) -> S2 = S - 1, case binary:at(B, S2) of X -> do_rtrim(S2, B, X); _ -> binary_part(B, 0, S) end. %% Multiple version of do_rtrim. do_mrtrim(0, _B, _Xs) -> <<>>; do_mrtrim(S, B, Xs) -> S2 = S - 1, X = binary:at(B, S2), case ordsets:is_element(X, Xs) of true -> do_mrtrim(S2, B, Xs); false -> binary_part(B, 0, S) end. ltrimc(<<X, B/binary>>, X, C) -> ltrimc(B, X, C+1); ltrimc(_B, _X, C) -> C. %% multi, left trimming, returns a count of matched bytes from the left. mltrimc(<<X, B/binary>>, Xs, C) -> case ordsets:is_element(X, Xs) of true -> mltrimc(B, Xs, C+1); false -> C end; mltrimc(<<>>, _Xs, C) -> C. % This clause will never be matched. do_rtrimc(0 , _ B , _ X ) - > 0 ; do_rtrimc(S, B, X) -> S2 = S - 1, case binary:at(B, S2) of X -> do_rtrimc(S2, B, X); _ -> S end. do_mrtrimc(S, B, Xs) -> S2 = S - 1, X = binary:at(B, S2), case ordsets:is_element(X, Xs) of true -> do_mrtrimc(S2, B, Xs); false -> S end. %% @doc Reverse the bytes' order. reverse(Bin) when is_binary(Bin) -> S = bit_size(Bin), <<V:S/integer-little>> = Bin, <<V:S/integer-big>>. join([B|Bs], Sep) when is_binary(Sep) -> iolist_to_binary([B|add_separator(Bs, Sep)]); join([], _Sep) -> <<>>. add_separator([B|Bs], Sep) -> [Sep, B | add_separator(Bs, Sep)]; add_separator([], _) -> []. %% @doc Repeat the binary `B' `C' times. duplicate(C, B) -> iolist_to_binary(lists:duplicate(C, B)). prefix(B, L) when is_binary(B), is_integer(L), L > 0 -> binary:part(B, 0, L). suffix(B, L) when is_binary(B), is_integer(L), L > 0 -> S = byte_size(B), binary:part(B, S-L, L). union(B1, B2) -> S = bit_size(B1), <<V1:S>> = B1, <<V2:S>> = B2, V3 = V1 bor V2, <<V3:S>>. subtract(B1, B2) -> S = bit_size(B1), <<V1:S>> = B1, <<V2:S>> = B2, V3 = (V1 bxor V2) band V1, <<V3:S>>. intersection(B1, B2) -> S = bit_size(B1), <<V1:S>> = B1, <<V2:S>> = B2, V3 = V1 band V2, <<V3:S>>. inverse(B1) -> S = bit_size(B1), <<V1:S>> = B1, V2 = bnot V1, <<V2:S>>. %% @doc string:to_integer/1 for binaries bin_to_int(Bin) -> bin_to_int(Bin, 0). bin_to_int(<<H, T/binary>>, X) when $0 =< H, H =< $9 -> bin_to_int(T, (X*10)+(H-$0)); bin_to_int(Bin, X) -> {X, Bin}. %% Remove longer patterns if shorter pattern matches %% Useful to run before binary:compile_pattern/1 optimize_patterns(Patterns) -> Sorted = lists:usort(Patterns), remove_long_duplicates(Sorted). remove_long_duplicates([H|T]) -> %% match(Subject, Pattern) DedupT = [X || X <- T, binary:match(X, H) =:= nomatch], [H|remove_long_duplicates(DedupT)]; remove_long_duplicates([]) -> [].
null
https://raw.githubusercontent.com/arcusfelis/binary2/22f42c7bd8be0334e90b12af61740e5a4448ec9f/src/binary2.erl
erlang
Bits Trimming Parsing Matching multi, left trimming. Multiple version of do_rtrim. multi, left trimming, returns a count of matched bytes from the left. This clause will never be matched. @doc Reverse the bytes' order. @doc Repeat the binary `B' `C' times. @doc string:to_integer/1 for binaries Remove longer patterns if shorter pattern matches Useful to run before binary:compile_pattern/1 match(Subject, Pattern)
-module(binary2). Bytes -export([ reverse/1 , join/2 , duplicate/2 , suffix/2 , prefix/2 ]). -export([ union/2 , subtract/2 , intersection/2 , inverse/1 ]). -export([ rtrim/1 , rtrim/2 , ltrim/1 , ltrim/2 , trim/1 , trim/2 ]). -export([ bin_to_int/1 ]). -export([ optimize_patterns/1 ]). trim(B) -> trim(B, 0). ltrim(B) -> ltrim(B, 0). rtrim(B) -> rtrim(B, 0). rtrim(B, X) when is_binary(B), is_integer(X) -> S = byte_size(B), do_rtrim(S, B, X); rtrim(B, [_|_]=Xs) when is_binary(B) -> S = byte_size(B), do_mrtrim(S, B, Xs). ltrim(B, X) when is_binary(B), is_integer(X) -> do_ltrim(B, X); ltrim(B, [_|_]=Xs) when is_binary(B) -> do_mltrim(B, Xs). @doc The second element is a single integer element or an ordset of elements . trim(B, X) when is_binary(B), is_integer(X) -> From = ltrimc(B, X, 0), case byte_size(B) of From -> <<>>; S -> To = do_rtrimc(S, B, X), binary:part(B, From, To - From) end; trim(B, [_|_]=Xs) when is_binary(B) -> From = mltrimc(B, Xs, 0), case byte_size(B) of From -> <<>>; S -> To = do_mrtrimc(S, B, Xs), binary:part(B, From, To - From) end. do_ltrim(<<X, B/binary>>, X) -> do_ltrim(B, X); do_ltrim(B, _X) -> B. do_mltrim(<<X, B/binary>> = XB, Xs) -> case ordsets:is_element(X, Xs) of true -> do_mltrim(B, Xs); false -> XB end; do_mltrim(<<>>, _Xs) -> <<>>. do_rtrim(0, _B, _X) -> <<>>; do_rtrim(S, B, X) -> S2 = S - 1, case binary:at(B, S2) of X -> do_rtrim(S2, B, X); _ -> binary_part(B, 0, S) end. do_mrtrim(0, _B, _Xs) -> <<>>; do_mrtrim(S, B, Xs) -> S2 = S - 1, X = binary:at(B, S2), case ordsets:is_element(X, Xs) of true -> do_mrtrim(S2, B, Xs); false -> binary_part(B, 0, S) end. ltrimc(<<X, B/binary>>, X, C) -> ltrimc(B, X, C+1); ltrimc(_B, _X, C) -> C. mltrimc(<<X, B/binary>>, Xs, C) -> case ordsets:is_element(X, Xs) of true -> mltrimc(B, Xs, C+1); false -> C end; mltrimc(<<>>, _Xs, C) -> C. do_rtrimc(0 , _ B , _ X ) - > 0 ; do_rtrimc(S, B, X) -> S2 = S - 1, case binary:at(B, S2) of X -> do_rtrimc(S2, B, X); _ -> S end. do_mrtrimc(S, B, Xs) -> S2 = S - 1, X = binary:at(B, S2), case ordsets:is_element(X, Xs) of true -> do_mrtrimc(S2, B, Xs); false -> S end. reverse(Bin) when is_binary(Bin) -> S = bit_size(Bin), <<V:S/integer-little>> = Bin, <<V:S/integer-big>>. join([B|Bs], Sep) when is_binary(Sep) -> iolist_to_binary([B|add_separator(Bs, Sep)]); join([], _Sep) -> <<>>. add_separator([B|Bs], Sep) -> [Sep, B | add_separator(Bs, Sep)]; add_separator([], _) -> []. duplicate(C, B) -> iolist_to_binary(lists:duplicate(C, B)). prefix(B, L) when is_binary(B), is_integer(L), L > 0 -> binary:part(B, 0, L). suffix(B, L) when is_binary(B), is_integer(L), L > 0 -> S = byte_size(B), binary:part(B, S-L, L). union(B1, B2) -> S = bit_size(B1), <<V1:S>> = B1, <<V2:S>> = B2, V3 = V1 bor V2, <<V3:S>>. subtract(B1, B2) -> S = bit_size(B1), <<V1:S>> = B1, <<V2:S>> = B2, V3 = (V1 bxor V2) band V1, <<V3:S>>. intersection(B1, B2) -> S = bit_size(B1), <<V1:S>> = B1, <<V2:S>> = B2, V3 = V1 band V2, <<V3:S>>. inverse(B1) -> S = bit_size(B1), <<V1:S>> = B1, V2 = bnot V1, <<V2:S>>. bin_to_int(Bin) -> bin_to_int(Bin, 0). bin_to_int(<<H, T/binary>>, X) when $0 =< H, H =< $9 -> bin_to_int(T, (X*10)+(H-$0)); bin_to_int(Bin, X) -> {X, Bin}. optimize_patterns(Patterns) -> Sorted = lists:usort(Patterns), remove_long_duplicates(Sorted). remove_long_duplicates([H|T]) -> DedupT = [X || X <- T, binary:match(X, H) =:= nomatch], [H|remove_long_duplicates(DedupT)]; remove_long_duplicates([]) -> [].
4c1da2ef5c9d9ab37fe277b87cb2a8d8bacedf2336fe7aab1282498136a5ed67
spawnfest/eep49ers
ssl_session_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2007 - 2020 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% %% -module(ssl_session_SUITE). -behaviour(ct_suite). -include("tls_handshake.hrl"). -include("ssl_record.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("public_key/include/public_key.hrl"). %% Common test -export([all/0, groups/0, init_per_suite/1, init_per_group/2, init_per_testcase/2, end_per_suite/1, end_per_group/2, end_per_testcase/2 ]). %% Test cases -export([reuse_session/0, reuse_session/1, reuse_session_expired/0, reuse_session_expired/1, server_does_not_want_to_reuse_session/0, server_does_not_want_to_reuse_session/1, explicit_session_reuse/0, explicit_session_reuse/1, explicit_session_reuse_expired/0, explicit_session_reuse_expired/1, no_reuses_session_server_restart_new_cert/0, no_reuses_session_server_restart_new_cert/1, no_reuses_session_server_restart_new_cert_file/0, no_reuses_session_server_restart_new_cert_file/1, client_max_session_table/0, client_max_session_table/1, server_max_session_table/0, server_max_session_table/1, session_table_stable_size_on_tcp_close/0, session_table_stable_size_on_tcp_close/1 ]). -define(SLEEP, 500). -define(EXPIRE, 2). -define(CLIENT_CB, ssl_client_session_cache_db). %%-------------------------------------------------------------------- %% Common Test interface functions ----------------------------------- %%-------------------------------------------------------------------- all() -> [ {group, 'tlsv1.2'}, {group, 'tlsv1.1'}, {group, 'tlsv1'}, {group, 'dtlsv1.2'}, {group, 'dtlsv1'} ]. groups() -> [{'dtlsv1.2', [], session_tests()}, {'dtlsv1', [], session_tests()}, {'tlsv1.3', [], session_tests() ++ tls_session_tests()}, {'tlsv1.2', [], session_tests() ++ tls_session_tests()}, {'tlsv1.1', [], session_tests() ++ tls_session_tests()}, {'tlsv1', [], session_tests() ++ tls_session_tests()} ]. session_tests() -> [reuse_session, reuse_session_expired, server_does_not_want_to_reuse_session, explicit_session_reuse, explicit_session_reuse_expired, no_reuses_session_server_restart_new_cert, no_reuses_session_server_restart_new_cert_file, client_max_session_table, server_max_session_table ]. tls_session_tests() -> [session_table_stable_size_on_tcp_close]. init_per_suite(Config0) -> catch crypto:stop(), try crypto:start() of ok -> ssl_test_lib:clean_start(), Config = ssl_test_lib:make_rsa_cert(Config0), ssl_test_lib:make_rsa_1024_cert(Config) catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> ssl:stop(), application:stop(crypto). init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(TestCase, Config) when TestCase == reuse_session_expired; TestCase == explicit_session_reuse_expired -> Versions = ssl_test_lib:protocol_version(Config), ssl:stop(), application:load(ssl), ssl_test_lib:clean_env(), ssl_test_lib:set_protocol_versions(Versions), application:set_env(ssl, session_lifetime, ?EXPIRE), ssl:start(), ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config; init_per_testcase(client_max_session_table, Config) -> Versions = ssl_test_lib:protocol_version(Config), ssl:stop(), application:load(ssl), ssl_test_lib:clean_env(), ssl_test_lib:set_protocol_versions(Versions), application:set_env(ssl, session_cache_client_max, 2), ssl:start(), ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config; init_per_testcase(server_max_session_table, Config) -> Versions = ssl_test_lib:protocol_version(Config), ssl:stop(), application:load(ssl), ssl_test_lib:clean_env(), ssl_test_lib:set_protocol_versions(Versions), application:set_env(ssl, session_cache_server_max, 2), ssl:start(), ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config; init_per_testcase(_, Config) -> Config. end_per_testcase(reuse_session_expired, Config) -> application:unset_env(ssl, session_lifetime), Config; end_per_testcase(_, Config) -> Config. %%-------------------------------------------------------------------- %% Test Cases -------------------------------------------------------- %%-------------------------------------------------------------------- reuse_session() -> [{doc,"Test reuse of sessions (short handshake)"}]. reuse_session(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), Version = ssl_test_lib:protocol_version(Config), ssl_test_lib:reuse_session([{versions,[Version]} | ClientOpts], [{versions,[Version]} | ServerOpts], Config). %%-------------------------------------------------------------------- reuse_session_expired() -> [{doc,"Test sessions is not reused when it has expired"}]. reuse_session_expired(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server0 = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {tcp_options, [{active, false}]}, {options, ServerOpts}]), Port0 = ssl_test_lib:inet_port(Server0), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, Hostname}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), Server0 ! listen, Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, Hostname}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, ClientOpts}]), SID = receive {Client0, Id0} -> Id0 end, receive {Client1, SID} -> ok after ?SLEEP -> ct:fail(session_not_reused) end, Server0 ! listen, %% Make sure session is unregistered due to expiration ct:sleep({seconds, ?EXPIRE*2}), make_sure_expired(Hostname, Port0, SID), Client2 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, Hostname}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, ClientOpts}]), receive {Client2, SID} -> end_per_testcase(?FUNCTION_NAME, Config), ct:fail(session_reused_when_session_expired); {Client2, _} -> ok end, process_flag(trap_exit, false), ssl_test_lib:close(Server0), ssl_test_lib:close(Client0), ssl_test_lib:close(Client1), ssl_test_lib:close(Client2). make_sure_expired(Host, Port, Id) -> {status, _, _, StatusInfo} = sys:get_status(whereis(ssl_manager)), [_, _,_, _, Prop] = StatusInfo, State = ssl_test_lib:state(Prop), ClientCache = element(2, State), case ssl_client_session_cache_db:lookup(ClientCache, {{Host, Port}, Id}) of undefined -> ok; #session{is_resumable = false} -> ok; _ -> ct:sleep(?SLEEP), make_sure_expired(Host, Port, Id) end. %%-------------------------------------------------------------------- server_does_not_want_to_reuse_session() -> [{doc,"Test reuse of sessions (short handshake)"}]. server_does_not_want_to_reuse_session(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, session_info_result, []}}, {options, [{reuse_session, fun(_,_,_,_) -> false end} | ServerOpts]}]), Port = ssl_test_lib:inet_port(Server), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, ClientOpts}]), SessionInfo = receive {Server, Info} -> Info end, Server ! {listen, {mfa, {ssl_test_lib, no_result, []}}}, %% Make sure session is registered ct:sleep(?SLEEP), Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, session_info_result, []}}, {from, self()}, {options, ClientOpts}]), receive {Client1, SessionInfo} -> ct:fail(session_reused_when_server_does_not_want_to); {Client1, _Other} -> ok end, ssl_test_lib:close(Client0), ssl_test_lib:close(Server), ssl_test_lib:close(Client1). %%-------------------------------------------------------------------- explicit_session_reuse() -> [{doc,"Test {reuse_session, {ID, Data}}} option for explicit reuse of sessions not" " saved in the clients automated session reuse"}]. explicit_session_reuse(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, ServerOpts}]), Port = ssl_test_lib:inet_port(Server), {Client0, Client0Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, false} | ClientOpts]}, return_socket ]), {ok, [{session_id, ID}, {session_data, SessData}]} = ssl:connection_information(Client0Sock, [session_id, session_data]), ssl_test_lib:close(Client0), Server ! listen, {_, Client1Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_session, {ID, SessData}} | ClientOpts]}, return_socket]), {ok, [{session_id, ID}]} = ssl:connection_information(Client1Sock, [session_id]). %%-------------------------------------------------------------------- explicit_session_reuse_expired() -> [{doc,"Test to reuse a session that has expired and make sure server session table is correctly handled"}]. explicit_session_reuse_expired(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, ServerOpts}]), Port = ssl_test_lib:inet_port(Server), {Client0, Client0Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, false} | ClientOpts]}, return_socket ]), %% Retrieve session data {ok, [{session_id, ID0}, {session_data, SessData}]} = ssl:connection_information(Client0Sock, [session_id, session_data]), ssl_test_lib:close(Client0), Server ! listen, SupName = sup_name(ServerOpts), Sup = whereis(SupName), Will only be one process , that is one server , in our test scenario [{_, SessionCachePid, worker,[ssl_server_session_cache]}] = supervisor:which_children(Sup), Start a new connections so there are three sessions {Client1, Client1Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}, return_socket]), Server ! listen, {Client2, Client2Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}, return_socket]), {ok, [{session_id, ID1}]} = ssl:connection_information(Client1Sock, [session_id]), Assert three sessions in server table {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), 3 = SessionCacheCb:size(SessionCacheDb), Server ! listen, {ok, [{session_id, ID2}]} = ssl:connection_information(Client2Sock, [session_id]), ssl_test_lib:close(Client1), ssl_test_lib:close(Client2), %% Make sure session expired ct:sleep({seconds, ?EXPIRE*2}), Try to reuse session one after expiration {_, Client3Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_session, {ID0, SessData}} | ClientOpts]}, return_socket]), %% Verify that we got a new session {ok, [{session_id, ID3}]} = ssl:connection_information(Client3Sock, [session_id]), %% We tried reusing ID0. So ID1 and ID2 should not be possible but assert anyway true = (ID3=/= ID0) andalso (ID3 =/= ID1) andalso (ID3 =/= ID2), %% Server table should have removed the expired session that we tried to reuse. and replaced the second one that expired . Leaving the third and the new {SessionCacheCb1, SessionCacheDb1} = session_cachce_info(SessionCachePid), 2 = SessionCacheCb1:size(SessionCacheDb1), Server ! listen, %% Make sure session expired ct:sleep({seconds, ?EXPIRE*2}), %% Nothing is removed yet {SessionCacheCb2, SessionCacheDb2} = session_cachce_info(SessionCachePid), 2 = SessionCacheCb2:size(SessionCacheDb2), {_, Client4Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, ClientOpts}, return_socket]), %% Expired session is not reused {ok, [{session_id, ID4}]} = ssl:connection_information(Client4Sock, [session_id]), true = (ID4 =/= ID3), One expired session is replaced {SessionCacheCb3, SessionCacheDb3} = session_cachce_info(SessionCachePid), 2 = SessionCacheCb3:size(SessionCacheDb3). %%-------------------------------------------------------------------- no_reuses_session_server_restart_new_cert() -> [{doc,"Check that a session is not reused if the server is restarted with a new cert."}]. no_reuses_session_server_restart_new_cert(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), RSA1024ServerOpts = ssl_test_lib:ssl_options(server_rsa_1024_opts, Config), RSA1024ClientOpts = ssl_test_lib:ssl_options(client_rsa_1024_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, session_info_result, []}}, {options, ServerOpts}]), Port = ssl_test_lib:inet_port(Server), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), SessionInfo = receive {Server, Info} -> Info end, ssl_test_lib:close(Server), ssl_test_lib:close(Client0), Server1 = ssl_test_lib:start_server([{node, ServerNode}, {port, Port}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, [{reuseaddr, true} | RSA1024ServerOpts]}]), Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, session_info_result, []}}, {from, self()}, {options, RSA1024ClientOpts}]), receive {Client1, SessionInfo} -> ct:fail(session_reused_when_server_has_new_cert); {Client1, _Other} -> ok end, ssl_test_lib:close(Server1), ssl_test_lib:close(Client1). %%-------------------------------------------------------------------- no_reuses_session_server_restart_new_cert_file() -> [{doc,"Check that a session is not reused if a server is restarted with a new " "cert contained in a file with the same name as the old cert."}]. no_reuses_session_server_restart_new_cert_file(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), RSA1024ServerOpts = ssl_test_lib:ssl_options(server_rsa_1024_verify_opts, Config), PrivDir = proplists:get_value(priv_dir, Config), NewServerOpts0 = ssl_test_lib:new_config(PrivDir, ServerOpts), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, session_info_result, []}}, {options, NewServerOpts0}]), Port = ssl_test_lib:inet_port(Server), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, ClientOpts}]), SessionInfo = receive {Server, Info} -> Info end, %% Make sure session is registered and we get new file time stamp when calling new_config ! ct:sleep(?SLEEP* 2), ssl_test_lib:close(Server), ssl_test_lib:close(Client0), ssl:clear_pem_cache(), NewServerOpts1 = ssl_test_lib:new_config(PrivDir, RSA1024ServerOpts), Server1 = ssl_test_lib:start_server([{node, ServerNode}, {port, Port}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, [{reuseaddr, true} | NewServerOpts1]}]), Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, session_info_result, []}}, {from, self()}, {options, ClientOpts}]), receive {Client1, SessionInfo} -> ct:fail(session_reused_when_server_has_new_cert); {Client1, _Other} -> ok end, ssl_test_lib:close(Server1), ssl_test_lib:close(Client1). client_max_session_table() -> [{doc, "Check that max session table limit is not exceeded, set max to 2 in init_per_testcase"}]. client_max_session_table(Config) when is_list(Config)-> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, HostName} = ssl_test_lib:run_where(Config), test_max_session_limit(ClientOpts,ServerOpts,ClientNode, ServerNode, HostName), %% Explicit check table size {status, _, _, StatusInfo} = sys:get_status(whereis(ssl_manager)), [_, _,_, _, Prop] = StatusInfo, State = ssl_test_lib:state(Prop), ClientCache = element(2, State), 2 = ?CLIENT_CB:size(ClientCache). server_max_session_table() -> [{doc, "Check that max session table limit exceeded, set max to 2 in init_per_testcase"}]. server_max_session_table(Config) when is_list(Config)-> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, HostName} = ssl_test_lib:run_where(Config), test_max_session_limit(ClientOpts,ServerOpts,ClientNode, ServerNode, HostName), %% Explicit check table size SupName = sup_name(ServerOpts), Sup = whereis(SupName), Will only be one process , that is one server , in our test senario [{_, SessionCachePid, worker,[ssl_server_session_cache]}] = supervisor:which_children(Sup), {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), N = SessionCacheCb:size(SessionCacheDb), true = N == 2. session_table_stable_size_on_tcp_close() -> [{doc, "Check that new sessions are cleanup when connection is closed abruptly during first handshake"}]. session_table_stable_size_on_tcp_close(Config) when is_list(Config)-> ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {_, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, [{reuseaddr, true} | ServerOpts]}]), Port = ssl_test_lib:inet_port(Server), Sup = whereis(ssl_server_session_cache_sup), Will only be one process , that is one server , in our test scenario [{_, SessionCachePid, worker,[ssl_server_session_cache]}] = supervisor:which_children(Sup), {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), N = SessionCacheCb:size(SessionCacheDb), faulty_client(Hostname, Port), check_table_did_not_grow(SessionCachePid, N). %%-------------------------------------------------------------------- Internal functions ------------------------------------------------ %%-------------------------------------------------------------------- session_cachce_info(SessionCache) -> State = sys:get_state(SessionCache), ServerCacheDb = element(4, State), ServerCacheCb = element(2, State), {ServerCacheCb, ServerCacheDb}. check_table_did_not_grow(SessionCachePid, N) -> {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), ct:pal("Run ~p ~p", [SessionCacheCb, SessionCacheDb]), case catch SessionCacheCb:size(SessionCacheDb) of N -> ok; Size -> ct:fail({table_grew, [{expected, N}, {got, Size}]}) end. faulty_client(Host, Port) -> {ok, Sock} = gen_tcp:connect(Host, Port, [], 10000), Random = crypto:strong_rand_bytes(32), CH = client_hello(Random), CHBin = encode_client_hello(CH, Random), gen_tcp:send(Sock, CHBin), ct:sleep(?SLEEP), gen_tcp:close(Sock). encode_client_hello(CH, Random) -> HSBin = tls_handshake:encode_handshake(CH, {3,3}), CS = connection_states(Random), {Encoded, _} = tls_record:encode_handshake(HSBin, {3,3}, CS), Encoded. client_hello(Random) -> CipherSuites = [<<0,255>>, <<"À,">>, <<"À0">>, <<"À$">>, <<"À(">>, <<"À.">>, <<"À2">>, <<"À&">>, <<"À*">>, <<0,159>>, <<0,163>>, <<0,107>>, <<0,106>>, <<"À+">>, <<"À/">>, <<"À#">>, <<"À'">>, <<"À-">>, <<"À1">>, <<"À%">>, <<"À)">>, <<0,158>>, <<0,162>>, <<0,103>>, <<0,64>>, <<"À\n">>, <<192,20>>, <<0,57>>, <<0,56>>, <<192,5>>, <<192,15>>, <<"À\t">>, <<192,19>>, <<0,51>>, <<0,50>>, <<192,4>>, <<192,14>>], Extensions = #{alpn => undefined, ec_point_formats => {ec_point_formats, [0]}, elliptic_curves => {elliptic_curves, [{1,3,132,0,39}, {1,3,132,0,38}, {1,3,132,0,35}, {1,3,36,3,3,2, 8,1,1,13}, {1,3,132,0,36}, {1,3,132,0,37}, {1,3,36,3,3,2, 8,1,1,11}, {1,3,132,0,34}, {1,3,132,0,16}, {1,3,132,0,17}, {1,3,36,3,3,2, 8,1,1,7}, {1,3,132,0,10}, {1,2,840, 10045,3,1,7}, {1,3,132,0,3}, {1,3,132,0,26}, {1,3,132,0,27}, {1,3,132,0,32}, {1,3,132,0,33}, {1,3,132,0,24}, {1,3,132,0,25}, {1,3,132,0,31}, {1,2,840, 10045,3,1,1}, {1,3,132,0,1}, {1,3,132,0,2}, {1,3,132,0,15}, {1,3,132,0,9}, {1,3,132,0,8}, {1,3,132,0, 30}]}, next_protocol_negotiation => undefined, renegotiation_info => {renegotiation_info, undefined}, signature_algs => {hash_sign_algos, [{sha512,ecdsa}, {sha512,rsa}, {sha384,ecdsa}, {sha384,rsa}, {sha256,ecdsa}, {sha256,rsa}, {sha224,ecdsa}, {sha224,rsa}, {sha,ecdsa}, {sha,rsa}, {sha,dsa}]}, sni => {sni, "localhost"}, srp => undefined}, #client_hello{client_version = {3,3}, random = Random, session_id = crypto:strong_rand_bytes(32), cipher_suites = CipherSuites, compression_methods = [0], extensions = Extensions }. connection_states(Random) -> #{current_write => #{beast_mitigation => one_n_minus_one,cipher_state => undefined, client_verify_data => undefined,compression_state => undefined, mac_secret => undefined,secure_renegotiation => undefined, security_parameters => #security_parameters{ cipher_suite = <<0,0>>, connection_end = 1, bulk_cipher_algorithm = 0, cipher_type = 0, iv_size = 0, key_size = 0, key_material_length = 0, expanded_key_material_length = 0, mac_algorithm = 0, prf_algorithm = 0, hash_size = 0, compression_algorithm = 0, master_secret = undefined, resumption_master_secret = undefined, client_random = Random, server_random = undefined, exportable = undefined}, sequence_number => 0,server_verify_data => undefined,max_fragment_length => undefined}}. test_max_session_limit(ClientOpts, ServerOpts, ClientNode, ServerNode, HostName) -> Server0 = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {tcp_options, [{active, false}]}, {options, ServerOpts}]), Port0 = ssl_test_lib:inet_port(Server0), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), SID0 = receive {Client0, Id0} -> Id0 end, Server0 ! listen, Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), SID1 = receive {Client1, Id1} -> Id1 end, false = SID0 == SID1, Server0 ! listen, Client2 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save}| ClientOpts]}]), SID2 = receive {Client2, Id2} -> Id2 end, Server0 ! listen, Client3 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_session, SID2}| ClientOpts]}]), receive {Client3, SID2} -> ok; Other -> ct:fail({{expected, SID2}, {got,Other}}) end. sup_name(Opts) -> case proplists:get_value(protocol, Opts, tls) of tls -> ssl_server_session_cache_sup; dtls -> dtls_server_session_cache_sup end.
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssl/test/ssl_session_SUITE.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% Common test Test cases -------------------------------------------------------------------- Common Test interface functions ----------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Test Cases -------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Make sure session is unregistered due to expiration -------------------------------------------------------------------- Make sure session is registered -------------------------------------------------------------------- -------------------------------------------------------------------- Retrieve session data Make sure session expired Verify that we got a new session We tried reusing ID0. So ID1 and ID2 should not be possible but assert anyway Server table should have removed the expired session that we tried to reuse. Make sure session expired Nothing is removed yet Expired session is not reused -------------------------------------------------------------------- -------------------------------------------------------------------- Make sure session is registered and we get Explicit check table size Explicit check table size -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright Ericsson AB 2007 - 2020 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(ssl_session_SUITE). -behaviour(ct_suite). -include("tls_handshake.hrl"). -include("ssl_record.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("public_key/include/public_key.hrl"). -export([all/0, groups/0, init_per_suite/1, init_per_group/2, init_per_testcase/2, end_per_suite/1, end_per_group/2, end_per_testcase/2 ]). -export([reuse_session/0, reuse_session/1, reuse_session_expired/0, reuse_session_expired/1, server_does_not_want_to_reuse_session/0, server_does_not_want_to_reuse_session/1, explicit_session_reuse/0, explicit_session_reuse/1, explicit_session_reuse_expired/0, explicit_session_reuse_expired/1, no_reuses_session_server_restart_new_cert/0, no_reuses_session_server_restart_new_cert/1, no_reuses_session_server_restart_new_cert_file/0, no_reuses_session_server_restart_new_cert_file/1, client_max_session_table/0, client_max_session_table/1, server_max_session_table/0, server_max_session_table/1, session_table_stable_size_on_tcp_close/0, session_table_stable_size_on_tcp_close/1 ]). -define(SLEEP, 500). -define(EXPIRE, 2). -define(CLIENT_CB, ssl_client_session_cache_db). all() -> [ {group, 'tlsv1.2'}, {group, 'tlsv1.1'}, {group, 'tlsv1'}, {group, 'dtlsv1.2'}, {group, 'dtlsv1'} ]. groups() -> [{'dtlsv1.2', [], session_tests()}, {'dtlsv1', [], session_tests()}, {'tlsv1.3', [], session_tests() ++ tls_session_tests()}, {'tlsv1.2', [], session_tests() ++ tls_session_tests()}, {'tlsv1.1', [], session_tests() ++ tls_session_tests()}, {'tlsv1', [], session_tests() ++ tls_session_tests()} ]. session_tests() -> [reuse_session, reuse_session_expired, server_does_not_want_to_reuse_session, explicit_session_reuse, explicit_session_reuse_expired, no_reuses_session_server_restart_new_cert, no_reuses_session_server_restart_new_cert_file, client_max_session_table, server_max_session_table ]. tls_session_tests() -> [session_table_stable_size_on_tcp_close]. init_per_suite(Config0) -> catch crypto:stop(), try crypto:start() of ok -> ssl_test_lib:clean_start(), Config = ssl_test_lib:make_rsa_cert(Config0), ssl_test_lib:make_rsa_1024_cert(Config) catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> ssl:stop(), application:stop(crypto). init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(TestCase, Config) when TestCase == reuse_session_expired; TestCase == explicit_session_reuse_expired -> Versions = ssl_test_lib:protocol_version(Config), ssl:stop(), application:load(ssl), ssl_test_lib:clean_env(), ssl_test_lib:set_protocol_versions(Versions), application:set_env(ssl, session_lifetime, ?EXPIRE), ssl:start(), ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config; init_per_testcase(client_max_session_table, Config) -> Versions = ssl_test_lib:protocol_version(Config), ssl:stop(), application:load(ssl), ssl_test_lib:clean_env(), ssl_test_lib:set_protocol_versions(Versions), application:set_env(ssl, session_cache_client_max, 2), ssl:start(), ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config; init_per_testcase(server_max_session_table, Config) -> Versions = ssl_test_lib:protocol_version(Config), ssl:stop(), application:load(ssl), ssl_test_lib:clean_env(), ssl_test_lib:set_protocol_versions(Versions), application:set_env(ssl, session_cache_server_max, 2), ssl:start(), ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config; init_per_testcase(_, Config) -> Config. end_per_testcase(reuse_session_expired, Config) -> application:unset_env(ssl, session_lifetime), Config; end_per_testcase(_, Config) -> Config. reuse_session() -> [{doc,"Test reuse of sessions (short handshake)"}]. reuse_session(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), Version = ssl_test_lib:protocol_version(Config), ssl_test_lib:reuse_session([{versions,[Version]} | ClientOpts], [{versions,[Version]} | ServerOpts], Config). reuse_session_expired() -> [{doc,"Test sessions is not reused when it has expired"}]. reuse_session_expired(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server0 = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {tcp_options, [{active, false}]}, {options, ServerOpts}]), Port0 = ssl_test_lib:inet_port(Server0), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, Hostname}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), Server0 ! listen, Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, Hostname}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, ClientOpts}]), SID = receive {Client0, Id0} -> Id0 end, receive {Client1, SID} -> ok after ?SLEEP -> ct:fail(session_not_reused) end, Server0 ! listen, ct:sleep({seconds, ?EXPIRE*2}), make_sure_expired(Hostname, Port0, SID), Client2 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, Hostname}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, ClientOpts}]), receive {Client2, SID} -> end_per_testcase(?FUNCTION_NAME, Config), ct:fail(session_reused_when_session_expired); {Client2, _} -> ok end, process_flag(trap_exit, false), ssl_test_lib:close(Server0), ssl_test_lib:close(Client0), ssl_test_lib:close(Client1), ssl_test_lib:close(Client2). make_sure_expired(Host, Port, Id) -> {status, _, _, StatusInfo} = sys:get_status(whereis(ssl_manager)), [_, _,_, _, Prop] = StatusInfo, State = ssl_test_lib:state(Prop), ClientCache = element(2, State), case ssl_client_session_cache_db:lookup(ClientCache, {{Host, Port}, Id}) of undefined -> ok; #session{is_resumable = false} -> ok; _ -> ct:sleep(?SLEEP), make_sure_expired(Host, Port, Id) end. server_does_not_want_to_reuse_session() -> [{doc,"Test reuse of sessions (short handshake)"}]. server_does_not_want_to_reuse_session(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, session_info_result, []}}, {options, [{reuse_session, fun(_,_,_,_) -> false end} | ServerOpts]}]), Port = ssl_test_lib:inet_port(Server), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, ClientOpts}]), SessionInfo = receive {Server, Info} -> Info end, Server ! {listen, {mfa, {ssl_test_lib, no_result, []}}}, ct:sleep(?SLEEP), Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, session_info_result, []}}, {from, self()}, {options, ClientOpts}]), receive {Client1, SessionInfo} -> ct:fail(session_reused_when_server_does_not_want_to); {Client1, _Other} -> ok end, ssl_test_lib:close(Client0), ssl_test_lib:close(Server), ssl_test_lib:close(Client1). explicit_session_reuse() -> [{doc,"Test {reuse_session, {ID, Data}}} option for explicit reuse of sessions not" " saved in the clients automated session reuse"}]. explicit_session_reuse(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, ServerOpts}]), Port = ssl_test_lib:inet_port(Server), {Client0, Client0Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, false} | ClientOpts]}, return_socket ]), {ok, [{session_id, ID}, {session_data, SessData}]} = ssl:connection_information(Client0Sock, [session_id, session_data]), ssl_test_lib:close(Client0), Server ! listen, {_, Client1Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_session, {ID, SessData}} | ClientOpts]}, return_socket]), {ok, [{session_id, ID}]} = ssl:connection_information(Client1Sock, [session_id]). explicit_session_reuse_expired() -> [{doc,"Test to reuse a session that has expired and make sure server session table is correctly handled"}]. explicit_session_reuse_expired(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, ServerOpts}]), Port = ssl_test_lib:inet_port(Server), {Client0, Client0Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, false} | ClientOpts]}, return_socket ]), {ok, [{session_id, ID0}, {session_data, SessData}]} = ssl:connection_information(Client0Sock, [session_id, session_data]), ssl_test_lib:close(Client0), Server ! listen, SupName = sup_name(ServerOpts), Sup = whereis(SupName), Will only be one process , that is one server , in our test scenario [{_, SessionCachePid, worker,[ssl_server_session_cache]}] = supervisor:which_children(Sup), Start a new connections so there are three sessions {Client1, Client1Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}, return_socket]), Server ! listen, {Client2, Client2Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}, return_socket]), {ok, [{session_id, ID1}]} = ssl:connection_information(Client1Sock, [session_id]), Assert three sessions in server table {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), 3 = SessionCacheCb:size(SessionCacheDb), Server ! listen, {ok, [{session_id, ID2}]} = ssl:connection_information(Client2Sock, [session_id]), ssl_test_lib:close(Client1), ssl_test_lib:close(Client2), ct:sleep({seconds, ?EXPIRE*2}), Try to reuse session one after expiration {_, Client3Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_session, {ID0, SessData}} | ClientOpts]}, return_socket]), {ok, [{session_id, ID3}]} = ssl:connection_information(Client3Sock, [session_id]), true = (ID3=/= ID0) andalso (ID3 =/= ID1) andalso (ID3 =/= ID2), and replaced the second one that expired . Leaving the third and the new {SessionCacheCb1, SessionCacheDb1} = session_cachce_info(SessionCachePid), 2 = SessionCacheCb1:size(SessionCacheDb1), Server ! listen, ct:sleep({seconds, ?EXPIRE*2}), {SessionCacheCb2, SessionCacheDb2} = session_cachce_info(SessionCachePid), 2 = SessionCacheCb2:size(SessionCacheDb2), {_, Client4Sock} = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, ClientOpts}, return_socket]), {ok, [{session_id, ID4}]} = ssl:connection_information(Client4Sock, [session_id]), true = (ID4 =/= ID3), One expired session is replaced {SessionCacheCb3, SessionCacheDb3} = session_cachce_info(SessionCachePid), 2 = SessionCacheCb3:size(SessionCacheDb3). no_reuses_session_server_restart_new_cert() -> [{doc,"Check that a session is not reused if the server is restarted with a new cert."}]. no_reuses_session_server_restart_new_cert(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), RSA1024ServerOpts = ssl_test_lib:ssl_options(server_rsa_1024_opts, Config), RSA1024ClientOpts = ssl_test_lib:ssl_options(client_rsa_1024_opts, Config), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, session_info_result, []}}, {options, ServerOpts}]), Port = ssl_test_lib:inet_port(Server), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), SessionInfo = receive {Server, Info} -> Info end, ssl_test_lib:close(Server), ssl_test_lib:close(Client0), Server1 = ssl_test_lib:start_server([{node, ServerNode}, {port, Port}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, [{reuseaddr, true} | RSA1024ServerOpts]}]), Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, session_info_result, []}}, {from, self()}, {options, RSA1024ClientOpts}]), receive {Client1, SessionInfo} -> ct:fail(session_reused_when_server_has_new_cert); {Client1, _Other} -> ok end, ssl_test_lib:close(Server1), ssl_test_lib:close(Client1). no_reuses_session_server_restart_new_cert_file() -> [{doc,"Check that a session is not reused if a server is restarted with a new " "cert contained in a file with the same name as the old cert."}]. no_reuses_session_server_restart_new_cert_file(Config) when is_list(Config) -> ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), RSA1024ServerOpts = ssl_test_lib:ssl_options(server_rsa_1024_verify_opts, Config), PrivDir = proplists:get_value(priv_dir, Config), NewServerOpts0 = ssl_test_lib:new_config(PrivDir, ServerOpts), {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, session_info_result, []}}, {options, NewServerOpts0}]), Port = ssl_test_lib:inet_port(Server), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, no_result, []}}, {from, self()}, {options, ClientOpts}]), SessionInfo = receive {Server, Info} -> Info end, new file time stamp when calling new_config ! ct:sleep(?SLEEP* 2), ssl_test_lib:close(Server), ssl_test_lib:close(Client0), ssl:clear_pem_cache(), NewServerOpts1 = ssl_test_lib:new_config(PrivDir, RSA1024ServerOpts), Server1 = ssl_test_lib:start_server([{node, ServerNode}, {port, Port}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, [{reuseaddr, true} | NewServerOpts1]}]), Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port}, {host, Hostname}, {mfa, {ssl_test_lib, session_info_result, []}}, {from, self()}, {options, ClientOpts}]), receive {Client1, SessionInfo} -> ct:fail(session_reused_when_server_has_new_cert); {Client1, _Other} -> ok end, ssl_test_lib:close(Server1), ssl_test_lib:close(Client1). client_max_session_table() -> [{doc, "Check that max session table limit is not exceeded, set max to 2 in init_per_testcase"}]. client_max_session_table(Config) when is_list(Config)-> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, HostName} = ssl_test_lib:run_where(Config), test_max_session_limit(ClientOpts,ServerOpts,ClientNode, ServerNode, HostName), {status, _, _, StatusInfo} = sys:get_status(whereis(ssl_manager)), [_, _,_, _, Prop] = StatusInfo, State = ssl_test_lib:state(Prop), ClientCache = element(2, State), 2 = ?CLIENT_CB:size(ClientCache). server_max_session_table() -> [{doc, "Check that max session table limit exceeded, set max to 2 in init_per_testcase"}]. server_max_session_table(Config) when is_list(Config)-> ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config), ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {ClientNode, ServerNode, HostName} = ssl_test_lib:run_where(Config), test_max_session_limit(ClientOpts,ServerOpts,ClientNode, ServerNode, HostName), SupName = sup_name(ServerOpts), Sup = whereis(SupName), Will only be one process , that is one server , in our test senario [{_, SessionCachePid, worker,[ssl_server_session_cache]}] = supervisor:which_children(Sup), {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), N = SessionCacheCb:size(SessionCacheDb), true = N == 2. session_table_stable_size_on_tcp_close() -> [{doc, "Check that new sessions are cleanup when connection is closed abruptly during first handshake"}]. session_table_stable_size_on_tcp_close(Config) when is_list(Config)-> ServerOpts = ssl_test_lib:ssl_options(server_rsa_verify_opts, Config), {_, ServerNode, Hostname} = ssl_test_lib:run_where(Config), Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {options, [{reuseaddr, true} | ServerOpts]}]), Port = ssl_test_lib:inet_port(Server), Sup = whereis(ssl_server_session_cache_sup), Will only be one process , that is one server , in our test scenario [{_, SessionCachePid, worker,[ssl_server_session_cache]}] = supervisor:which_children(Sup), {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), N = SessionCacheCb:size(SessionCacheDb), faulty_client(Hostname, Port), check_table_did_not_grow(SessionCachePid, N). Internal functions ------------------------------------------------ session_cachce_info(SessionCache) -> State = sys:get_state(SessionCache), ServerCacheDb = element(4, State), ServerCacheCb = element(2, State), {ServerCacheCb, ServerCacheDb}. check_table_did_not_grow(SessionCachePid, N) -> {SessionCacheCb, SessionCacheDb} = session_cachce_info(SessionCachePid), ct:pal("Run ~p ~p", [SessionCacheCb, SessionCacheDb]), case catch SessionCacheCb:size(SessionCacheDb) of N -> ok; Size -> ct:fail({table_grew, [{expected, N}, {got, Size}]}) end. faulty_client(Host, Port) -> {ok, Sock} = gen_tcp:connect(Host, Port, [], 10000), Random = crypto:strong_rand_bytes(32), CH = client_hello(Random), CHBin = encode_client_hello(CH, Random), gen_tcp:send(Sock, CHBin), ct:sleep(?SLEEP), gen_tcp:close(Sock). encode_client_hello(CH, Random) -> HSBin = tls_handshake:encode_handshake(CH, {3,3}), CS = connection_states(Random), {Encoded, _} = tls_record:encode_handshake(HSBin, {3,3}, CS), Encoded. client_hello(Random) -> CipherSuites = [<<0,255>>, <<"À,">>, <<"À0">>, <<"À$">>, <<"À(">>, <<"À.">>, <<"À2">>, <<"À&">>, <<"À*">>, <<0,159>>, <<0,163>>, <<0,107>>, <<0,106>>, <<"À+">>, <<"À/">>, <<"À#">>, <<"À'">>, <<"À-">>, <<"À1">>, <<"À%">>, <<"À)">>, <<0,158>>, <<0,162>>, <<0,103>>, <<0,64>>, <<"À\n">>, <<192,20>>, <<0,57>>, <<0,56>>, <<192,5>>, <<192,15>>, <<"À\t">>, <<192,19>>, <<0,51>>, <<0,50>>, <<192,4>>, <<192,14>>], Extensions = #{alpn => undefined, ec_point_formats => {ec_point_formats, [0]}, elliptic_curves => {elliptic_curves, [{1,3,132,0,39}, {1,3,132,0,38}, {1,3,132,0,35}, {1,3,36,3,3,2, 8,1,1,13}, {1,3,132,0,36}, {1,3,132,0,37}, {1,3,36,3,3,2, 8,1,1,11}, {1,3,132,0,34}, {1,3,132,0,16}, {1,3,132,0,17}, {1,3,36,3,3,2, 8,1,1,7}, {1,3,132,0,10}, {1,2,840, 10045,3,1,7}, {1,3,132,0,3}, {1,3,132,0,26}, {1,3,132,0,27}, {1,3,132,0,32}, {1,3,132,0,33}, {1,3,132,0,24}, {1,3,132,0,25}, {1,3,132,0,31}, {1,2,840, 10045,3,1,1}, {1,3,132,0,1}, {1,3,132,0,2}, {1,3,132,0,15}, {1,3,132,0,9}, {1,3,132,0,8}, {1,3,132,0, 30}]}, next_protocol_negotiation => undefined, renegotiation_info => {renegotiation_info, undefined}, signature_algs => {hash_sign_algos, [{sha512,ecdsa}, {sha512,rsa}, {sha384,ecdsa}, {sha384,rsa}, {sha256,ecdsa}, {sha256,rsa}, {sha224,ecdsa}, {sha224,rsa}, {sha,ecdsa}, {sha,rsa}, {sha,dsa}]}, sni => {sni, "localhost"}, srp => undefined}, #client_hello{client_version = {3,3}, random = Random, session_id = crypto:strong_rand_bytes(32), cipher_suites = CipherSuites, compression_methods = [0], extensions = Extensions }. connection_states(Random) -> #{current_write => #{beast_mitigation => one_n_minus_one,cipher_state => undefined, client_verify_data => undefined,compression_state => undefined, mac_secret => undefined,secure_renegotiation => undefined, security_parameters => #security_parameters{ cipher_suite = <<0,0>>, connection_end = 1, bulk_cipher_algorithm = 0, cipher_type = 0, iv_size = 0, key_size = 0, key_material_length = 0, expanded_key_material_length = 0, mac_algorithm = 0, prf_algorithm = 0, hash_size = 0, compression_algorithm = 0, master_secret = undefined, resumption_master_secret = undefined, client_random = Random, server_random = undefined, exportable = undefined}, sequence_number => 0,server_verify_data => undefined,max_fragment_length => undefined}}. test_max_session_limit(ClientOpts, ServerOpts, ClientNode, ServerNode, HostName) -> Server0 = ssl_test_lib:start_server([{node, ServerNode}, {port, 0}, {from, self()}, {mfa, {ssl_test_lib, no_result, []}}, {tcp_options, [{active, false}]}, {options, ServerOpts}]), Port0 = ssl_test_lib:inet_port(Server0), Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), SID0 = receive {Client0, Id0} -> Id0 end, Server0 ! listen, Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save} | ClientOpts]}]), SID1 = receive {Client1, Id1} -> Id1 end, false = SID0 == SID1, Server0 ! listen, Client2 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_sessions, save}| ClientOpts]}]), SID2 = receive {Client2, Id2} -> Id2 end, Server0 ! listen, Client3 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port0}, {host, HostName}, {mfa, {ssl_test_lib, session_id, []}}, {from, self()}, {options, [{reuse_session, SID2}| ClientOpts]}]), receive {Client3, SID2} -> ok; Other -> ct:fail({{expected, SID2}, {got,Other}}) end. sup_name(Opts) -> case proplists:get_value(protocol, Opts, tls) of tls -> ssl_server_session_cache_sup; dtls -> dtls_server_session_cache_sup end.
8c383cf4e4f30f872649647b2e0cfdfaa3636c36dfe91f7de5fba88c7d7f281c
ygmpkk/house
All.hs
For convenience , unites all parts of H in one module . -- Typically, it is better style to import the individual parts separately. -- See the imported modules for details of the H interface. module H.All(module H.All) where -- The H monad and its operations: import H.Monad as H.All import H.PhysicalMemory as H.All import H.VirtualMemory as H.All import H.UserMode as H.All import H.IOPorts as H.All import H.Interrupts as H.All import H.MemRegion as H.All hiding (createRegion) -- hide unsafe function import H.Grub as H.All hiding (moduleStart,moduleEnd) Features inherited from the IO monad : import H.Mutable as H.All import H.Concurrency as H.All -- Things excluded from the main H interface: import H.AdHocMem as H -- Exports unsafe memory operations --import H.MonadImpl as H -- Reveals internal representation import H.Unsafe as H -- Unsafe operations inherited from the IO monad import Control.Monad(liftM) ---------------- PROPERTIES FOLLOW --------------- P : -- A monadic computations returns a given value : property Returns x = { | m | m==={m>>return x } | } -- Two computations are independent in all contexts property Commute = { | f , g | { do x < - f ; y < - g ; return ( x , y ) } = = = { do y ; x < - f ; return ( x , y ) } | } -- Two computations are independent immediately following computation m property PostCommute f g = { | m | { do m ; x < - f ; y < - g ; return ( x , y ) } = = = { do m ; y < - g ; x < - f ; return ( x , y ) } | } property StateGetGet = { | get | { do x < - get ; y < - get ; return x } = = = { do x < - get ; y < - get ; return y } | } property StateSetSet = { | set | All x , x ' . { do set x ; set x ' } = = = { do set x ' } | } property StateSetGet set get = All x. { do set x ; get } : : : Returns x -- Normal stateul operations . property Stateful = { | set , get | StateGetGet get /\ StateSetSet set /\ StateSetGet set get | } ----- property IndependentSetSet = { | set , set ' | All x , x ' . Commute { set x } { set ' x ' } | } property IndependentSetGet = { | set , get | All x . Commute { set x } { get } | } property Independent = { | set , get , set ' , get ' | IndependentSetSet set set ' /\ IndependentSetGet set get ' /\ IndependentSetGet set ' get | } -------------- -- each use of f generates a different result property JustGenerative f = All m. { do Just x < - f ; m ; Just y < - f ; return ( ) } : : : Returns { False } -------------- property ValidVAddr = { | v::VAddr | True { v > = minVAddr & & v < = maxVAddr } | } property OnSamePage = { | v::VAddr , v'::VAddr | { v ` div ` ( fromIntegral pageSize ) } = = = { v ' ` div ` ( fromIntegral pageSize ) } | } -- property AlignedVAddr = -- { | vaddr::VAddr | True { fromIntegral vaddr ` mod ` pageSize = = 0 } | } -- property PageVAddr = ValidVAddr /\ AlignedVAddr -- Following m , is not mapped by any va in pm property NotMapped pm pa = { | m | All va . va : : : ValidVAddr = = > { do m ; isMappedTo pm va pa } : : : Returns { False } | } -- Following m , is not mapped writable by any va in pm property NotMappedWritable pm pa = { | m | All va . va : : : ValidVAddr = = > { do m ; isMappedWritableTo pm va pa } : : : Returns { False } | } -- va is mapped to ppg in pm isMappedTo pm va ( ppg , _ ) = do pme < - getPage pm va case pme of Just PageInfo{physPage = ppg ' } - > return ( ppg = = ppg ' ) Nothing - > return False -- va is mapped writeable to ppg in pm isMappedWritableTo pm va ( ppg , _ ) = do pme < - getPage pm va case pme of Just PageInfo{physPage = ppg',writeable = True } - > return ( ppg = = ppg ' ) _ - > return False -- Paddrs act like distinct stateful locations . assert All pa , pa',x . = = > Stateful { setPAddr pa } { getPAddr pa } /\ Independent { setPAddr pa } { getPAddr pa } { setPAddr pa ' } { getPAddr pa ' } -- page map entries are independent stateful locations assert All pm , pm ' , va , va ' . va : : : ValidVAddr /\ va ' : : : /\ -- ( pm = /= pm ' \/ -/ OnSamePage { va } { va ' } ) = = > Stateful { setPage pm va } { getPage pm va } /\ Independent { setPage pm va } { getPage pm va } { setPage pm ' va ' } { getPage pm ' va ' } -- page maps are initially zero assert All va . va : : : ValidVAddr = = > { do Just pm < - allocPageMap ; getPage pm va } : : : Returns { Nothing } -- page map entries and physical addresses are independent too assert All pm , pa , va . : : : ValidVAddr = = > Independent { setPage pm va } { getPage pm va } { setPAddr pa } { getPAddr pa } -- IO ports are independent from physical pages and page tables : assert All p , pa . Independent { outB p } { inB p } { setPAddr pa } { getPAddr pa } assert All p , pm , va . : : : ValidVAddr = = > Independent { outB p } { inB p } { setPage pm va } { getPage pm va } -- execution can not change the contents of a physical address not mapped writeable assert All pm , pa , m , c . m : : : NotMappedWritable pm pa = = > m : : : PostCommute { getPAddr pa } { execContext pm c } -- changing the contents of an unmapped address can not affect execution assert All pm , pa , m , c , x . m : : : NotMapped pm pa = = > m : : : PostCommute { } { execContext pm c } -- changing one page table has no effect on execution under another page table assert All pm , pm ' , va , c , x . pm = /= pm ' = = > Commute { setPage pm ' va x } { execContext pm c } -- executing under one page table has no effect on the contents of any other page table assert All pm , pm ' , va , c . pm = /= pm ' = = > Commute { getPage pm ' va } { execContext pm c } -- execution under a page table has no effect on the page mapping and writeable status of any entry in that table assert All pm , va , c . Commute { getPageField physPage pm va } { execContext pm c } assert All pm , va , c . Commute { writeable pm va } { execContext pm c } getPageField field pm va = liftM ( fmap field ) ( getPage pm va ) -- if execution under a page table changes some physical address , then there must -- be an entry mapping that address somewhere in the table with its dirty and access bits set -- here 's the best try so far : property Changed pa pm c = { | m | { do m ; x < - getPAddr pa ; execContext pm c ; y < - getPAddr pa ; return ( x = = y ) } : : : Returns { False } | } property Dirty pa pm c = { | m | Exist va . { do m ; execContext pm c ; getPage pm va } : : : Returns { Just PageInfo { physPage = fst pa , writeable = True , dirty = True , accessed = True } } | } assert All pa , pm , c , m . m : : : Changed pa pm c = = > m : : : Dirty pa pm c -- A monadic computations returns a given value: property Returns x = {| m | m==={m>>return x} |} -- Two computations are independent in all contexts property Commute = {| f,g | {do x <- f; y <- g; return (x,y)} === {do y <- g; x <- f; return (x,y)} |} -- Two computations are independent immediately following computation m property PostCommute f g = {| m | { do m; x <- f; y <- g; return (x,y) } === {do m; y <- g; x <- f; return (x,y) } |} property StateGetGet = {| get | {do x <- get; y <- get; return x } === { do x <- get ; y <- get; return y } |} property StateSetSet = {| set | All x, x'. { do set x; set x' } === { do set x' } |} property StateSetGet set get = All x. { do set x; get } ::: Returns x -- Normal stateul operations. property Stateful = {| set, get | StateGetGet get /\ StateSetSet set /\ StateSetGet set get |} ----- property IndependentSetSet = {| set, set' | All x, x'. Commute {set x} {set' x'} |} property IndependentSetGet = {| set, get | All x . Commute {set x} {get} |} property Independent = {| set, get, set', get' | IndependentSetSet set set' /\ IndependentSetGet set get' /\ IndependentSetGet set' get |} -------------- -- each use of f generates a different result property JustGenerative f = All m. {do Just x <- f; m; Just y <- f; return (x==y)} ::: Returns {False} -------------- property ValidVAddr = {| v::VAddr | True {v >= minVAddr && v <= maxVAddr} |} property OnSamePage = {| v::VAddr,v'::VAddr | {v `div` (fromIntegral pageSize)} === {v' `div` (fromIntegral pageSize)} |} -- property AlignedVAddr = -- {| vaddr::VAddr | True {fromIntegral vaddr `mod` pageSize == 0} |} -- property PageVAddr = ValidVAddr /\ AlignedVAddr -- Following m, pa is not mapped by any va in pm property NotMapped pm pa = {| m | All va . va ::: ValidVAddr ==> {do m; isMappedTo pm va pa} ::: Returns {False} |} -- Following m, pa is not mapped writable by any va in pm property NotMappedWritable pm pa = {| m | All va . va ::: ValidVAddr ==> {do m; isMappedWritableTo pm va pa} ::: Returns {False} |} -- va is mapped to ppg in pm isMappedTo pm va (ppg,_) = do pme <- getPage pm va case pme of Just PageInfo{physPage = ppg'} -> return (ppg == ppg') Nothing -> return False -- va is mapped writeable to ppg in pm isMappedWritableTo pm va (ppg,_) = do pme <- getPage pm va case pme of Just PageInfo{physPage = ppg',writeable=True} -> return (ppg == ppg') _ -> return False -- Paddrs act like distinct stateful locations. assert All pa, pa',x . pa =/= pa' ==> Stateful {setPAddr pa} {getPAddr pa} /\ Independent {setPAddr pa} {getPAddr pa} {setPAddr pa'} {getPAddr pa'} -- page map entries are independent stateful locations assert All pm, pm', va, va'. va ::: ValidVAddr /\ va' ::: ValidVAddr /\ -- (pm =/= pm' \/ -/ OnSamePage {va} {va'}) ==> Stateful {setPage pm va} {getPage pm va} /\ Independent {setPage pm va} {getPage pm va} {setPage pm' va'} {getPage pm' va'} -- page maps are initially zero assert All va. va ::: ValidVAddr ==> {do Just pm <- allocPageMap; getPage pm va} ::: Returns {Nothing} -- page map entries and physical addresses are independent too assert All pm, pa, va . va ::: ValidVAddr ==> Independent {setPage pm va} {getPage pm va} {setPAddr pa} {getPAddr pa} -- IO ports are independent from physical pages and page tables: assert All p, pa . Independent {outB p} {inB p} {setPAddr pa} {getPAddr pa} assert All p, pm, va . va ::: ValidVAddr ==> Independent {outB p} {inB p} {setPage pm va} {getPage pm va} -- execution cannot change the contents of a physical address not mapped writeable assert All pm, pa, m, c . m ::: NotMappedWritable pm pa ==> m ::: PostCommute {getPAddr pa} {execContext pm c} -- changing the contents of an unmapped address cannot affect execution assert All pm, pa, m, c, x . m ::: NotMapped pm pa ==> m ::: PostCommute {setPAddr pa x} {execContext pm c} -- changing one page table has no effect on execution under another page table assert All pm, pm', va, c, x . pm =/= pm' ==> Commute {setPage pm' va x} {execContext pm c} -- executing under one page table has no effect on the contents of any other page table assert All pm, pm', va, c . pm =/= pm' ==> Commute {getPage pm' va} {execContext pm c} -- execution under a page table has no effect on the page mapping and writeable status of any entry in that table assert All pm, va, c . Commute {getPageField physPage pm va} {execContext pm c} assert All pm, va, c . Commute {getPageField writeable pm va} {execContext pm c} getPageField field pm va = liftM (fmap field) (getPage pm va) -- if execution under a page table changes some physical address, then there must -- be an entry mapping that address somewhere in the table with its dirty and access bits set -- here's the best try so far: property Changed pa pm c = {| m | {do m; x <- getPAddr pa; execContext pm c; y <- getPAddr pa; return (x == y)} ::: Returns {False} |} property Dirty pa pm c = {| m | Exist va . {do m; execContext pm c; getPage pm va} ::: Returns {Just PageInfo{ physPage = fst pa, writeable = True, dirty = True, accessed = True }} |} assert All pa, pm, c, m . m ::: Changed pa pm c ==> m ::: Dirty pa pm c -}
null
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/kernel/H/All.hs
haskell
Typically, it is better style to import the individual parts separately. See the imported modules for details of the H interface. The H monad and its operations: hide unsafe function Things excluded from the main H interface: Exports unsafe memory operations import H.MonadImpl as H -- Reveals internal representation Unsafe operations inherited from the IO monad -------------- PROPERTIES FOLLOW --------------- A monadic computations returns a given value : Two computations are independent in all contexts Two computations are independent immediately following computation m Normal stateul operations . --- ------------ each use of f generates a different result ------------ property AlignedVAddr = { | vaddr::VAddr | True { fromIntegral vaddr ` mod ` pageSize = = 0 } | } property PageVAddr = ValidVAddr /\ AlignedVAddr Following m , is not mapped by any va in pm Following m , is not mapped writable by any va in pm va is mapped to ppg in pm va is mapped writeable to ppg in pm Paddrs act like distinct stateful locations . page map entries are independent stateful locations page maps are initially zero page map entries and physical addresses are independent too IO ports are independent from physical pages and page tables : execution can not change the contents of a physical address not mapped writeable changing the contents of an unmapped address can not affect execution changing one page table has no effect on execution under another page table executing under one page table has no effect on the contents of any other page table execution under a page table has no effect on the page mapping and writeable status of any entry in that table if execution under a page table changes some physical address , then there must be an entry mapping that address somewhere in the table with its dirty and access bits set here 's the best try so far : A monadic computations returns a given value: Two computations are independent in all contexts Two computations are independent immediately following computation m Normal stateul operations. --- ------------ each use of f generates a different result ------------ property AlignedVAddr = {| vaddr::VAddr | True {fromIntegral vaddr `mod` pageSize == 0} |} property PageVAddr = ValidVAddr /\ AlignedVAddr Following m, pa is not mapped by any va in pm Following m, pa is not mapped writable by any va in pm va is mapped to ppg in pm va is mapped writeable to ppg in pm Paddrs act like distinct stateful locations. page map entries are independent stateful locations page maps are initially zero page map entries and physical addresses are independent too IO ports are independent from physical pages and page tables: execution cannot change the contents of a physical address not mapped writeable changing the contents of an unmapped address cannot affect execution changing one page table has no effect on execution under another page table executing under one page table has no effect on the contents of any other page table execution under a page table has no effect on the page mapping and writeable status of any entry in that table if execution under a page table changes some physical address, then there must be an entry mapping that address somewhere in the table with its dirty and access bits set here's the best try so far:
For convenience , unites all parts of H in one module . module H.All(module H.All) where import H.Monad as H.All import H.PhysicalMemory as H.All import H.VirtualMemory as H.All import H.UserMode as H.All import H.IOPorts as H.All import H.Interrupts as H.All import H.Grub as H.All hiding (moduleStart,moduleEnd) Features inherited from the IO monad : import H.Mutable as H.All import H.Concurrency as H.All import Control.Monad(liftM) P : property Returns x = { | m | m==={m>>return x } | } property Commute = { | f , g | { do x < - f ; y < - g ; return ( x , y ) } = = = { do y ; x < - f ; return ( x , y ) } | } property PostCommute f g = { | m | { do m ; x < - f ; y < - g ; return ( x , y ) } = = = { do m ; y < - g ; x < - f ; return ( x , y ) } | } property StateGetGet = { | get | { do x < - get ; y < - get ; return x } = = = { do x < - get ; y < - get ; return y } | } property StateSetSet = { | set | All x , x ' . { do set x ; set x ' } = = = { do set x ' } | } property StateSetGet set get = All x. { do set x ; get } : : : Returns x property Stateful = { | set , get | StateGetGet get /\ StateSetSet set /\ StateSetGet set get | } property IndependentSetSet = { | set , set ' | All x , x ' . Commute { set x } { set ' x ' } | } property IndependentSetGet = { | set , get | All x . Commute { set x } { get } | } property Independent = { | set , get , set ' , get ' | IndependentSetSet set set ' /\ IndependentSetGet set get ' /\ IndependentSetGet set ' get | } property JustGenerative f = All m. { do Just x < - f ; m ; Just y < - f ; return ( ) } : : : Returns { False } property ValidVAddr = { | v::VAddr | True { v > = minVAddr & & v < = maxVAddr } | } property OnSamePage = { | v::VAddr , v'::VAddr | { v ` div ` ( fromIntegral pageSize ) } = = = { v ' ` div ` ( fromIntegral pageSize ) } | } property NotMapped pm pa = { | m | All va . va : : : ValidVAddr = = > { do m ; isMappedTo pm va pa } : : : Returns { False } | } property NotMappedWritable pm pa = { | m | All va . va : : : ValidVAddr = = > { do m ; isMappedWritableTo pm va pa } : : : Returns { False } | } isMappedTo pm va ( ppg , _ ) = do pme < - getPage pm va case pme of Just PageInfo{physPage = ppg ' } - > return ( ppg = = ppg ' ) Nothing - > return False isMappedWritableTo pm va ( ppg , _ ) = do pme < - getPage pm va case pme of Just PageInfo{physPage = ppg',writeable = True } - > return ( ppg = = ppg ' ) _ - > return False assert All pa , pa',x . = = > Stateful { setPAddr pa } { getPAddr pa } /\ Independent { setPAddr pa } { getPAddr pa } { setPAddr pa ' } { getPAddr pa ' } ( pm = /= pm ' \/ -/ OnSamePage { va } { va ' } ) = = > Stateful { setPage pm va } { getPage pm va } /\ Independent { setPage pm va } { getPage pm va } { setPage pm ' va ' } { getPage pm ' va ' } assert All va . va : : : ValidVAddr = = > { do Just pm < - allocPageMap ; getPage pm va } : : : Returns { Nothing } assert All pm , pa , va . : : : ValidVAddr = = > Independent { setPage pm va } { getPage pm va } { setPAddr pa } { getPAddr pa } assert All p , pa . Independent { outB p } { inB p } { setPAddr pa } { getPAddr pa } assert All p , pm , va . : : : ValidVAddr = = > Independent { outB p } { inB p } { setPage pm va } { getPage pm va } assert All pm , pa , m , c . m : : : NotMappedWritable pm pa = = > m : : : PostCommute { getPAddr pa } { execContext pm c } assert All pm , pa , m , c , x . m : : : NotMapped pm pa = = > m : : : PostCommute { } { execContext pm c } assert All pm , pm ' , va , c , x . pm = /= pm ' = = > Commute { setPage pm ' va x } { execContext pm c } assert All pm , pm ' , va , c . pm = /= pm ' = = > Commute { getPage pm ' va } { execContext pm c } assert All pm , va , c . Commute { getPageField physPage pm va } { execContext pm c } assert All pm , va , c . Commute { writeable pm va } { execContext pm c } getPageField field pm va = liftM ( fmap field ) ( getPage pm va ) property Changed pa pm c = { | m | { do m ; x < - getPAddr pa ; execContext pm c ; y < - getPAddr pa ; return ( x = = y ) } : : : Returns { False } | } property Dirty pa pm c = { | m | Exist va . { do m ; execContext pm c ; getPage pm va } : : : Returns { Just PageInfo { physPage = fst pa , writeable = True , dirty = True , accessed = True } } | } assert All pa , pm , c , m . m : : : Changed pa pm c = = > m : : : Dirty pa pm c property Returns x = {| m | m==={m>>return x} |} property Commute = {| f,g | {do x <- f; y <- g; return (x,y)} === {do y <- g; x <- f; return (x,y)} |} property PostCommute f g = {| m | { do m; x <- f; y <- g; return (x,y) } === {do m; y <- g; x <- f; return (x,y) } |} property StateGetGet = {| get | {do x <- get; y <- get; return x } === { do x <- get ; y <- get; return y } |} property StateSetSet = {| set | All x, x'. { do set x; set x' } === { do set x' } |} property StateSetGet set get = All x. { do set x; get } ::: Returns x property Stateful = {| set, get | StateGetGet get /\ StateSetSet set /\ StateSetGet set get |} property IndependentSetSet = {| set, set' | All x, x'. Commute {set x} {set' x'} |} property IndependentSetGet = {| set, get | All x . Commute {set x} {get} |} property Independent = {| set, get, set', get' | IndependentSetSet set set' /\ IndependentSetGet set get' /\ IndependentSetGet set' get |} property JustGenerative f = All m. {do Just x <- f; m; Just y <- f; return (x==y)} ::: Returns {False} property ValidVAddr = {| v::VAddr | True {v >= minVAddr && v <= maxVAddr} |} property OnSamePage = {| v::VAddr,v'::VAddr | {v `div` (fromIntegral pageSize)} === {v' `div` (fromIntegral pageSize)} |} property NotMapped pm pa = {| m | All va . va ::: ValidVAddr ==> {do m; isMappedTo pm va pa} ::: Returns {False} |} property NotMappedWritable pm pa = {| m | All va . va ::: ValidVAddr ==> {do m; isMappedWritableTo pm va pa} ::: Returns {False} |} isMappedTo pm va (ppg,_) = do pme <- getPage pm va case pme of Just PageInfo{physPage = ppg'} -> return (ppg == ppg') Nothing -> return False isMappedWritableTo pm va (ppg,_) = do pme <- getPage pm va case pme of Just PageInfo{physPage = ppg',writeable=True} -> return (ppg == ppg') _ -> return False assert All pa, pa',x . pa =/= pa' ==> Stateful {setPAddr pa} {getPAddr pa} /\ Independent {setPAddr pa} {getPAddr pa} {setPAddr pa'} {getPAddr pa'} (pm =/= pm' \/ -/ OnSamePage {va} {va'}) ==> Stateful {setPage pm va} {getPage pm va} /\ Independent {setPage pm va} {getPage pm va} {setPage pm' va'} {getPage pm' va'} assert All va. va ::: ValidVAddr ==> {do Just pm <- allocPageMap; getPage pm va} ::: Returns {Nothing} assert All pm, pa, va . va ::: ValidVAddr ==> Independent {setPage pm va} {getPage pm va} {setPAddr pa} {getPAddr pa} assert All p, pa . Independent {outB p} {inB p} {setPAddr pa} {getPAddr pa} assert All p, pm, va . va ::: ValidVAddr ==> Independent {outB p} {inB p} {setPage pm va} {getPage pm va} assert All pm, pa, m, c . m ::: NotMappedWritable pm pa ==> m ::: PostCommute {getPAddr pa} {execContext pm c} assert All pm, pa, m, c, x . m ::: NotMapped pm pa ==> m ::: PostCommute {setPAddr pa x} {execContext pm c} assert All pm, pm', va, c, x . pm =/= pm' ==> Commute {setPage pm' va x} {execContext pm c} assert All pm, pm', va, c . pm =/= pm' ==> Commute {getPage pm' va} {execContext pm c} assert All pm, va, c . Commute {getPageField physPage pm va} {execContext pm c} assert All pm, va, c . Commute {getPageField writeable pm va} {execContext pm c} getPageField field pm va = liftM (fmap field) (getPage pm va) property Changed pa pm c = {| m | {do m; x <- getPAddr pa; execContext pm c; y <- getPAddr pa; return (x == y)} ::: Returns {False} |} property Dirty pa pm c = {| m | Exist va . {do m; execContext pm c; getPage pm va} ::: Returns {Just PageInfo{ physPage = fst pa, writeable = True, dirty = True, accessed = True }} |} assert All pa, pm, c, m . m ::: Changed pa pm c ==> m ::: Dirty pa pm c -}
ae84db47eb7e9eb146a4e4caa897f209392b54ea6c12a14d659421f050d4ec62
sheepduke/silver-brain
packages.lisp
(defpackage silver-brain.config (:nicknames config) (:use #:cl) (:import-from #:chameleon #:defconfig #:defprofile) (:import-from #:find-port #:find-port) (:export #:set-profile)) (defpackage silver-brain.core (:nicknames core) (:use #:cl #:alexandria #:iterate) (:export #:concept #:print-object ;; Accessors. #:concept-uuid #:concept-name #:concept-content-format #:concept-content #:concept-parents #:concept-children #:concept-friends ;; Modifiers. #:concept-childp #:concept-friendp #:become-child #:become-friend #:remove-all-relations-of #:remove-relations-between)) (defpackage silver-brain.db (:nicknames db) (:use #:cl #:alexandria #:iterate) (:import-from #:sxql #:where) (:export #:setup ;; Concept DAO. #:concept #:db-concept-to-core-concept #:concept-uuid #:concept-name #:concept-content #:concept-content-format #:save-concept ;; Concept Relation DAO. #:concept-relation-source #:concept-relation-target ;; Concept. #:read-all-concepts #:read-all-concept-relations #:find-concept-by-name #:create-concept #:update-concept #:delete-concept ;; Concept relation. #:add-relation #:delete-relations-of)) (defpackage silver-brain.service (:nicknames service) (:use #:cl #:alexandria #:iterate #:trivia #:silver-brain.core) (:export #:setup #:get-all-concepts #:get-concept-by-uuid #:find-concept-by-name #:create-concept #:update-concept #:delete-concept #:make-child #:make-friend #:remove-relation)) (defpackage silver-brain.server (:nicknames server) (:use #:cl #:alexandria #:core #:trivia #:silver-brain.core) (:import-from #:serapeum #:~>>) (:import-from #:ningle #:*request* #:*response*) (:import-from #:lack.response #:response-status #:response-headers #:response-body) (:import-from #:trivial-types #:association-list-p) (:export #:start #:stop)) (defpackage silver-brain (:use #:cl #:alexandria) (:export #:main))
null
https://raw.githubusercontent.com/sheepduke/silver-brain/81ef7d0035fadc63e3cfca0be6a6f157e1dbbe05/backend/src/packages.lisp
lisp
Accessors. Modifiers. Concept DAO. Concept Relation DAO. Concept. Concept relation.
(defpackage silver-brain.config (:nicknames config) (:use #:cl) (:import-from #:chameleon #:defconfig #:defprofile) (:import-from #:find-port #:find-port) (:export #:set-profile)) (defpackage silver-brain.core (:nicknames core) (:use #:cl #:alexandria #:iterate) (:export #:concept #:print-object #:concept-uuid #:concept-name #:concept-content-format #:concept-content #:concept-parents #:concept-children #:concept-friends #:concept-childp #:concept-friendp #:become-child #:become-friend #:remove-all-relations-of #:remove-relations-between)) (defpackage silver-brain.db (:nicknames db) (:use #:cl #:alexandria #:iterate) (:import-from #:sxql #:where) (:export #:setup #:concept #:db-concept-to-core-concept #:concept-uuid #:concept-name #:concept-content #:concept-content-format #:save-concept #:concept-relation-source #:concept-relation-target #:read-all-concepts #:read-all-concept-relations #:find-concept-by-name #:create-concept #:update-concept #:delete-concept #:add-relation #:delete-relations-of)) (defpackage silver-brain.service (:nicknames service) (:use #:cl #:alexandria #:iterate #:trivia #:silver-brain.core) (:export #:setup #:get-all-concepts #:get-concept-by-uuid #:find-concept-by-name #:create-concept #:update-concept #:delete-concept #:make-child #:make-friend #:remove-relation)) (defpackage silver-brain.server (:nicknames server) (:use #:cl #:alexandria #:core #:trivia #:silver-brain.core) (:import-from #:serapeum #:~>>) (:import-from #:ningle #:*request* #:*response*) (:import-from #:lack.response #:response-status #:response-headers #:response-body) (:import-from #:trivial-types #:association-list-p) (:export #:start #:stop)) (defpackage silver-brain (:use #:cl #:alexandria) (:export #:main))
d321f88a4f6b7e4db74c8984ca0bd43c0cc88eafae82893b9c99dcaf2bc24877
samrushing/irken-compiler
t28.scm
(include "lib/core.scm") (include "lib/pair.scm") ;; vector and list literals #('(1 2 3 4) '(1 2 3))
null
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t28.scm
scheme
vector and list literals
(include "lib/core.scm") (include "lib/pair.scm") #('(1 2 3 4) '(1 2 3))
5ead6b56a7badc22cb4134c0d7728bbde5829b3980d9878b6130bc813cbe9cfa
stepcut/plugins
Parser.hs
# LANGUAGE CPP # # LANGUAGE PatternGuards # -- Copyright ( C ) 2004 - 5 -- -- 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. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . -- module System.Plugins.Parser ( parse, mergeModules, pretty, parsePragmas, HsModule(..) , replaceModName ) where #include "config.h" import Data.List import Data.Char import Data.Either ( ) #if defined(WITH_HSX) import Language.Haskell.Hsx #else import Language.Haskell.Parser import Language.Haskell.Syntax import Language.Haskell.Pretty #endif -- | parse a file ( as a string ) as src -- parse :: FilePath -- ^ module name ^ -> Either String HsModule -- ^ abstract syntax parse f fsrc = #if defined(WITH_HSX) case parseFileContentsWithMode (ParseMode f) fsrc of #else case parseModuleWithMode (ParseMode f) fsrc of #endif ParseOk src -> Right src ParseFailed loc _ -> Left $ srcmsg loc where srcmsg loc = "parse error in " ++ f ++ "\n" ++ "line: " ++ (show $ srcLine loc) ++ ", col: " ++ (show $ srcColumn loc)++ "\n" -- | pretty print -- -- doesn't handle operators with '#' at the end. i.e. unsafeCoerce# -- pretty :: HsModule -> String pretty code = prettyPrintWithMode (defaultMode { linePragmas = True }) code | mergeModules : generate a full Haskell src file , give a .hs config -- file, and a stub to take default syntax and decls from. Mostly we -- just ensure they don't do anything bad, and that the names are -- correct for the module. -- -- Transformations: -- . Take src location pragmas from the conf file ( 1st file ) . Use the template 's ( 2nd argument ) module name . Only use export list from template ( 2nd arg ) -- . Merge top-level decls -- . need to force the type of the plugin to match the stub, -- overwriting any type they supply. -- mergeModules :: HsModule -> -- Configure module HsModule -> -- Template module A merge of the two mergeModules (HsModule l _ _ is ds ) (HsModule _ m' es' is' ds') = (HsModule l m' es' (mImps m' is is') (mDecl ds ds') ) -- -- | replace Module name with String. -- replaceModName :: HsModule -> String -> HsModule replaceModName (HsModule l _ es is ds) nm = (HsModule l (Module nm) es is ds) -- -- | merge import declarations: -- -- * ensure that the config file doesn't import the stub name -- * merge import lists uniquely, and when they match, merge their decls -- -- TODO * we don't merge imports of the same module from both files. -- We should, and then merge the decls in their import list -- * rename args, too confusing. -- -- quick fix: strip all type signatures from the source. -- mImps :: Module -> -- plugin module name [HsImportDecl] -> -- conf file imports [HsImportDecl] -> -- stub file imports [HsImportDecl] mImps plug_mod cimps timps = case filter (!~ self) cimps of cimps' -> unionBy (=~) cimps' timps where self = ( HsImportDecl undefined plug_mod undefined undefined undefined ) -- -- | merge top-level declarations -- -- Remove decls found in template, using those from the config file. Need to sort decls by types , then decls first , in both . -- -- Could we write a pass to handle editor, foo :: String ? -- We must keep the type from the template. -- mDecl ds es = let ds' = filter (not.typeDecl) ds in sortBy decls $! unionBy (=~) ds' es where decls a b = compare (encoding a) (encoding b) typeDecl :: HsDecl -> Bool typeDecl (HsTypeSig _ _ _) = True typeDecl _ = False encoding :: HsDecl -> Int encoding d = case d of HsFunBind _ -> 1 HsPatBind _ _ _ _ -> 1 _ -> 0 -- syntactic equality over the useful abstract syntax -- this may be extended if we try to merge the files more thoroughly -- class SynEq a where (=~) :: a -> a -> Bool (!~) :: a -> a -> Bool n !~ m = not (n =~ m) instance SynEq HsDecl where (HsPatBind _ (HsPVar n) _ _) =~ (HsPatBind _ (HsPVar m) _ _) = n == m (HsTypeSig _ (n:_) _) =~ (HsTypeSig _ (m:_) _) = n == m _ =~ _ = False instance SynEq HsImportDecl where (HsImportDecl _ m _ _ _) =~ (HsImportDecl _ n _ _ _) = n == m -- -- | Parsing option pragmas. -- -- This is not a type checker. If the user supplies bogus options, -- they'll get slightly mystical error messages. Also, we /want/ to -- handle -package options, and other /static/ flags. This is more than GHC . -- GHC user 's guide : -- -- > OPTIONS pragmas are only looked for at the top of your source > files , up to the first ( non - literate , non - empty ) line not -- > containing OPTIONS. Multiple OPTIONS pragmas are recognised. -- -- based on getOptionsFromSource(), in main\/DriverUtil.hs -- parsePragmas :: String -- ^ input src -> ([String],[String]) -- ^ normal options, global options parsePragmas s = look $ lines s where look [] = ([],[]) look (l':ls) = let l = remove_spaces l' in case () of () | null l -> look ls | prefixMatch "#" l -> look ls | prefixMatch "{-# LINE" l -> look ls | Just (Option o) <- matchPragma l -> let (as,bs) = look ls in (words o ++ as,bs) | Just (Global g) <- matchPragma l -> let (as,bs) = look ls in (as,words g ++ bs) | otherwise -> ([],[]) -- -- based on main\/DriverUtil.hs -- -- extended to handle dynamic options too -- data Pragma = Option !String | Global !String matchPragma :: String -> Maybe Pragma matchPragma s | Just s1 <- maybePrefixMatch "{-#" s, -- -} Just s2 <- maybePrefixMatch "OPTIONS" (remove_spaces s1), Just s3 <- maybePrefixMatch "}-#" (reverse s2) = Just (Option (reverse s3)) | Just s1 <- maybePrefixMatch "{-#" s, -- -} Just s2 <- maybePrefixMatch "GLOBALOPTIONS" (remove_spaces s1), Just s3 <- maybePrefixMatch "}-#" (reverse s2) = Just (Global (reverse s3)) | otherwise = Nothing remove_spaces :: String -> String remove_spaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace -- -- verbatim from utils\/Utils.lhs -- prefixMatch :: Eq a => [a] -> [a] -> Bool prefixMatch [] _str = True prefixMatch _pat [] = False prefixMatch (p:ps) (s:ss) | p == s = prefixMatch ps ss | otherwise = False maybePrefixMatch :: String -> String -> Maybe String maybePrefixMatch [] rest = Just rest maybePrefixMatch (_:_) [] = Nothing maybePrefixMatch (p:pat) (r:rest) | p == r = maybePrefixMatch pat rest | otherwise = Nothing
null
https://raw.githubusercontent.com/stepcut/plugins/52c660b5bc71182627d14c1d333d0234050cac01/src/System/Plugins/Parser.hs
haskell
This program is free software; you can redistribute it and/or This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software ^ module name ^ abstract syntax doesn't handle operators with '#' at the end. i.e. unsafeCoerce# file, and a stub to take default syntax and decls from. Mostly we just ensure they don't do anything bad, and that the names are correct for the module. Transformations: . Merge top-level decls . need to force the type of the plugin to match the stub, overwriting any type they supply. Configure module Template module | replace Module name with String. | merge import declarations: * ensure that the config file doesn't import the stub name * merge import lists uniquely, and when they match, merge their decls TODO * we don't merge imports of the same module from both files. We should, and then merge the decls in their import list * rename args, too confusing. quick fix: strip all type signatures from the source. plugin module name conf file imports stub file imports | merge top-level declarations Remove decls found in template, using those from the config file. Could we write a pass to handle editor, foo :: String ? We must keep the type from the template. this may be extended if we try to merge the files more thoroughly | Parsing option pragmas. This is not a type checker. If the user supplies bogus options, they'll get slightly mystical error messages. Also, we /want/ to handle -package options, and other /static/ flags. This is more than > OPTIONS pragmas are only looked for at the top of your source > containing OPTIONS. Multiple OPTIONS pragmas are recognised. based on getOptionsFromSource(), in main\/DriverUtil.hs ^ input src ^ normal options, global options based on main\/DriverUtil.hs extended to handle dynamic options too -} -} verbatim from utils\/Utils.lhs
# LANGUAGE CPP # # LANGUAGE PatternGuards # Copyright ( C ) 2004 - 5 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 . You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . module System.Plugins.Parser ( parse, mergeModules, pretty, parsePragmas, HsModule(..) , replaceModName ) where #include "config.h" import Data.List import Data.Char import Data.Either ( ) #if defined(WITH_HSX) import Language.Haskell.Hsx #else import Language.Haskell.Parser import Language.Haskell.Syntax import Language.Haskell.Pretty #endif | parse a file ( as a string ) as src ^ parse f fsrc = #if defined(WITH_HSX) case parseFileContentsWithMode (ParseMode f) fsrc of #else case parseModuleWithMode (ParseMode f) fsrc of #endif ParseOk src -> Right src ParseFailed loc _ -> Left $ srcmsg loc where srcmsg loc = "parse error in " ++ f ++ "\n" ++ "line: " ++ (show $ srcLine loc) ++ ", col: " ++ (show $ srcColumn loc)++ "\n" | pretty print pretty :: HsModule -> String pretty code = prettyPrintWithMode (defaultMode { linePragmas = True }) code | mergeModules : generate a full Haskell src file , give a .hs config . Take src location pragmas from the conf file ( 1st file ) . Use the template 's ( 2nd argument ) module name . Only use export list from template ( 2nd arg ) A merge of the two mergeModules (HsModule l _ _ is ds ) (HsModule _ m' es' is' ds') = (HsModule l m' es' (mImps m' is is') (mDecl ds ds') ) replaceModName :: HsModule -> String -> HsModule replaceModName (HsModule l _ es is ds) nm = (HsModule l (Module nm) es is ds) [HsImportDecl] mImps plug_mod cimps timps = case filter (!~ self) cimps of cimps' -> unionBy (=~) cimps' timps where self = ( HsImportDecl undefined plug_mod undefined undefined undefined ) Need to sort decls by types , then decls first , in both . mDecl ds es = let ds' = filter (not.typeDecl) ds in sortBy decls $! unionBy (=~) ds' es where decls a b = compare (encoding a) (encoding b) typeDecl :: HsDecl -> Bool typeDecl (HsTypeSig _ _ _) = True typeDecl _ = False encoding :: HsDecl -> Int encoding d = case d of HsFunBind _ -> 1 HsPatBind _ _ _ _ -> 1 _ -> 0 syntactic equality over the useful abstract syntax class SynEq a where (=~) :: a -> a -> Bool (!~) :: a -> a -> Bool n !~ m = not (n =~ m) instance SynEq HsDecl where (HsPatBind _ (HsPVar n) _ _) =~ (HsPatBind _ (HsPVar m) _ _) = n == m (HsTypeSig _ (n:_) _) =~ (HsTypeSig _ (m:_) _) = n == m _ =~ _ = False instance SynEq HsImportDecl where (HsImportDecl _ m _ _ _) =~ (HsImportDecl _ n _ _ _) = n == m GHC . GHC user 's guide : > files , up to the first ( non - literate , non - empty ) line not parsePragmas s = look $ lines s where look [] = ([],[]) look (l':ls) = let l = remove_spaces l' in case () of () | null l -> look ls | prefixMatch "#" l -> look ls | prefixMatch "{-# LINE" l -> look ls | Just (Option o) <- matchPragma l -> let (as,bs) = look ls in (words o ++ as,bs) | Just (Global g) <- matchPragma l -> let (as,bs) = look ls in (as,words g ++ bs) | otherwise -> ([],[]) data Pragma = Option !String | Global !String matchPragma :: String -> Maybe Pragma matchPragma s Just s2 <- maybePrefixMatch "OPTIONS" (remove_spaces s1), Just s3 <- maybePrefixMatch "}-#" (reverse s2) = Just (Option (reverse s3)) Just s2 <- maybePrefixMatch "GLOBALOPTIONS" (remove_spaces s1), Just s3 <- maybePrefixMatch "}-#" (reverse s2) = Just (Global (reverse s3)) | otherwise = Nothing remove_spaces :: String -> String remove_spaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace prefixMatch :: Eq a => [a] -> [a] -> Bool prefixMatch [] _str = True prefixMatch _pat [] = False prefixMatch (p:ps) (s:ss) | p == s = prefixMatch ps ss | otherwise = False maybePrefixMatch :: String -> String -> Maybe String maybePrefixMatch [] rest = Just rest maybePrefixMatch (_:_) [] = Nothing maybePrefixMatch (p:pat) (r:rest) | p == r = maybePrefixMatch pat rest | otherwise = Nothing
275721226bb48759607f1edb89c9fbb40de5b745c3e987470de291bb4f0ffc0e
Popl7/Bamse
macros.cljc
(ns bamse.macros) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- nodejs-target? [] (= :nodejs (get-in @cljs.env/*compiler* [:options :target]))) (defmacro code-for-nodejs [& body] (when (nodejs-target?) `(do ~@body))) (defmacro code-for-browser [& body] (when-not (nodejs-target?) `(do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro load-readme "Read README.md" [] (slurp (str "README.md"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro load-translation "Read translation file" [edn-file] (slurp (str "resources/gettext/" edn-file)))
null
https://raw.githubusercontent.com/Popl7/Bamse/33f45df2f22ee35344671f11fd0db3dd50331c84/src/clj/bamse/macros.cljc
clojure
(ns bamse.macros) (defn- nodejs-target? [] (= :nodejs (get-in @cljs.env/*compiler* [:options :target]))) (defmacro code-for-nodejs [& body] (when (nodejs-target?) `(do ~@body))) (defmacro code-for-browser [& body] (when-not (nodejs-target?) `(do ~@body))) (defmacro load-readme "Read README.md" [] (slurp (str "README.md"))) (defmacro load-translation "Read translation file" [edn-file] (slurp (str "resources/gettext/" edn-file)))
b77194d00846c09e5b9ced16e50e6540c049c1108b778ea3468e566a5db66d27
spl/ivy
dlocals.mli
* * Copyright ( c ) 2006 , * < > * < > * < > * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are * met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . The names of the contributors may not 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 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 . * * * Copyright (c) 2006, * Jeremy Condit <> * Matthew Harren <> * George C. Necula <> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of the contributors may not 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. * *) val doLiveness : Cil.fundec -> unit val clearLiveness : unit -> unit val liveAtStmtStart : Cil.stmt -> Usedef.VS.t val localDependsOn : Cil.varinfo -> Usedef.VS.t
null
https://raw.githubusercontent.com/spl/ivy/b1b516484fba637eb24e83d27555d273495e622b/src/deputy/dlocals.mli
ocaml
* * Copyright ( c ) 2006 , * < > * < > * < > * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are * met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . The names of the contributors may not 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 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 . * * * Copyright (c) 2006, * Jeremy Condit <> * Matthew Harren <> * George C. Necula <> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of the contributors may not 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. * *) val doLiveness : Cil.fundec -> unit val clearLiveness : unit -> unit val liveAtStmtStart : Cil.stmt -> Usedef.VS.t val localDependsOn : Cil.varinfo -> Usedef.VS.t
36f2026a887ca2a56023836b81f1c7e714a7e6bd936ac0ce20d1935e682a5e38
ndmitchell/build-shootout
unchanged-shake.hs
import Development.Shake main = shakeArgs shakeOptions $ do "output" %> \out -> do need ["source"] cmd "sh unchanged-run source -- output" "source" %> \out -> do need ["input"] cmd "sh unchanged-gen input -- source"
null
https://raw.githubusercontent.com/ndmitchell/build-shootout/40b2fd3804d89f8c7cf0a37b3a9d45a863be04ce/examples/unchanged-shake.hs
haskell
import Development.Shake main = shakeArgs shakeOptions $ do "output" %> \out -> do need ["source"] cmd "sh unchanged-run source -- output" "source" %> \out -> do need ["input"] cmd "sh unchanged-gen input -- source"
6445f09212f261b7a0ebf1cff454558a5bb136861bb503629d2a80c1a41555f3
scotthaleen/clojure-spring-cloud
greeting.clj
(ns spring.cloud.models.greeting (:import [com.fasterxml.jackson.annotation JsonIgnoreProperties]) (:gen-class ignore clojure internal ` .state ` field during serialization :name ^{com.fasterxml.jackson.annotation.JsonIgnoreProperties ["state"]} spring.cloud.models.Greeting :init init :state state :constructors {[long String] []} :methods [[getId [] long] [getContent [] String]])) (defn -init [id content] [[] {:id id :content content}]) (defn -getId [this] (:id (.state this))) (defn -getContent [this] (:content (.state this)))
null
https://raw.githubusercontent.com/scotthaleen/clojure-spring-cloud/56d874c2cd4af616f9b8e62eccd19cbddd47f2fa/src/spring/cloud/models/greeting.clj
clojure
(ns spring.cloud.models.greeting (:import [com.fasterxml.jackson.annotation JsonIgnoreProperties]) (:gen-class ignore clojure internal ` .state ` field during serialization :name ^{com.fasterxml.jackson.annotation.JsonIgnoreProperties ["state"]} spring.cloud.models.Greeting :init init :state state :constructors {[long String] []} :methods [[getId [] long] [getContent [] String]])) (defn -init [id content] [[] {:id id :content content}]) (defn -getId [this] (:id (.state this))) (defn -getContent [this] (:content (.state this)))
ea0cdde29b0c73c9267364b3588684b85d5bfbb6e15d47cdbd482d4a3662a054
SamB/coq
declarations.mli
open Util open Names open Term Bytecode type values type reloc_table type to_patch_substituted (*Retroknowledge *) type action type retroknowledge (* Engagements *) type engagement = ImpredicativeSet (* Constants *) type polymorphic_arity = { poly_param_levels : Univ.universe option list; poly_level : Univ.universe; } type constant_type = | NonPolymorphicType of constr | PolymorphicArity of rel_context * polymorphic_arity type constr_substituted val force_constr : constr_substituted -> constr val from_val : constr -> constr_substituted type constant_body = { const_hyps : section_context; (* New: younger hyp at top *) const_body : constr_substituted option; const_type : constant_type; const_body_code : to_patch_substituted; const_constraints : Univ.constraints; const_opaque : bool; const_inline : bool} Mutual inductives type recarg = | Norec | Mrec of int | Imbr of inductive type wf_paths = recarg Rtree.t val mk_norec : wf_paths val mk_paths : recarg -> wf_paths list array -> wf_paths val dest_subterms : wf_paths -> wf_paths list array type monomorphic_inductive_arity = { mind_user_arity : constr; mind_sort : sorts; } type inductive_arity = | Monomorphic of monomorphic_inductive_arity | Polymorphic of polymorphic_arity type one_inductive_body = { (* Primitive datas *) (* Name of the type: [Ii] *) mind_typename : identifier; (* Arity context of [Ii] with parameters: [forall params, Ui] *) mind_arity_ctxt : rel_context; (* Arity sort, original user arity, and allowed elim sorts, if monomorphic *) mind_arity : inductive_arity; (* Names of the constructors: [cij] *) mind_consnames : identifier array; Types of the constructors with parameters : [ forall params , Tij ] , where the Ik are replaced by de Bruijn index in the context I1 : forall params , U1 .. In : forall params , Un where the Ik are replaced by de Bruijn index in the context I1:forall params, U1 .. In:forall params, Un *) mind_user_lc : constr array; (* Derived datas *) (* Number of expected real arguments of the type (no let, no params) *) mind_nrealargs : int; (* List of allowed elimination sorts *) mind_kelim : sorts_family list; (* Head normalized constructor types so that their conclusion is atomic *) mind_nf_lc : constr array; (* Length of the signature of the constructors (with let, w/o params) *) mind_consnrealdecls : int array; (* Signature of recursive arguments in the constructors *) mind_recargs : wf_paths; (* Datas for bytecode compilation *) (* number of constant constructor *) mind_nb_constant : int; (* number of no constant constructor *) mind_nb_args : int; mind_reloc_tbl : reloc_table; } type mutual_inductive_body = { (* The component of the mutual inductive block *) mind_packets : one_inductive_body array; (* Whether the inductive type has been declared as a record *) mind_record : bool; (* Whether the type is inductive or coinductive *) mind_finite : bool; (* Number of types in the block *) mind_ntypes : int; (* Section hypotheses on which the block depends *) mind_hyps : section_context; (* Number of expected parameters *) mind_nparams : int; (* Number of recursively uniform (i.e. ordinary) parameters *) mind_nparams_rec : int; (* The context of parameters (includes let-in declaration) *) mind_params_ctxt : rel_context; Universes constraints enforced by the inductive declaration mind_constraints : Univ.constraints; (* Source of the inductive block when aliased in a module *) mind_equiv : kernel_name option } (* Modules *) type substitution type structure_field_body = | SFBconst of constant_body | SFBmind of mutual_inductive_body | SFBmodule of module_body | SFBalias of module_path * Univ.constraints option | SFBmodtype of module_type_body and structure_body = (label * structure_field_body) list and struct_expr_body = | SEBident of module_path | SEBfunctor of mod_bound_id * module_type_body * struct_expr_body | SEBstruct of mod_self_id * structure_body | SEBapply of struct_expr_body * struct_expr_body * Univ.constraints | SEBwith of struct_expr_body * with_declaration_body and with_declaration_body = With_module_body of identifier list * module_path * Univ.constraints | With_definition_body of identifier list * constant_body and module_body = { mod_expr : struct_expr_body option; mod_type : struct_expr_body option; mod_constraints : Univ.constraints; mod_alias : substitution; mod_retroknowledge : action list} and module_type_body = { typ_expr : struct_expr_body; typ_strength : module_path option; typ_alias : substitution} (* Substitutions *) val fold_subst : (mod_self_id -> module_path -> 'a -> 'a) -> (mod_bound_id -> module_path -> 'a -> 'a) -> (module_path -> module_path -> 'a -> 'a) -> substitution -> 'a -> 'a type 'a subst_fun = substitution -> 'a -> 'a val empty_subst : substitution val add_msid : mod_self_id -> module_path -> substitution -> substitution val add_mbid : mod_bound_id -> module_path -> substitution -> substitution val add_mp : module_path -> module_path -> substitution -> substitution val map_msid : mod_self_id -> module_path -> substitution val map_mbid : mod_bound_id -> module_path -> substitution val map_mp : module_path -> module_path -> substitution val subst_const_body : constant_body subst_fun val subst_mind : mutual_inductive_body subst_fun val subst_modtype : substitution -> module_type_body -> module_type_body val subst_struct_expr : substitution -> struct_expr_body -> struct_expr_body val subst_structure : substitution -> structure_body -> structure_body val subst_signature_msid : mod_self_id -> module_path -> structure_body -> structure_body val join : substitution -> substitution -> substitution val join_alias : substitution -> substitution -> substitution val update_subst_alias : substitution -> substitution -> substitution val update_subst : substitution -> substitution -> substitution val subst_key : substitution -> substitution -> substitution
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/checker/declarations.mli
ocaml
Retroknowledge Engagements Constants New: younger hyp at top Primitive datas Name of the type: [Ii] Arity context of [Ii] with parameters: [forall params, Ui] Arity sort, original user arity, and allowed elim sorts, if monomorphic Names of the constructors: [cij] Derived datas Number of expected real arguments of the type (no let, no params) List of allowed elimination sorts Head normalized constructor types so that their conclusion is atomic Length of the signature of the constructors (with let, w/o params) Signature of recursive arguments in the constructors Datas for bytecode compilation number of constant constructor number of no constant constructor The component of the mutual inductive block Whether the inductive type has been declared as a record Whether the type is inductive or coinductive Number of types in the block Section hypotheses on which the block depends Number of expected parameters Number of recursively uniform (i.e. ordinary) parameters The context of parameters (includes let-in declaration) Source of the inductive block when aliased in a module Modules Substitutions
open Util open Names open Term Bytecode type values type reloc_table type to_patch_substituted type action type retroknowledge type engagement = ImpredicativeSet type polymorphic_arity = { poly_param_levels : Univ.universe option list; poly_level : Univ.universe; } type constant_type = | NonPolymorphicType of constr | PolymorphicArity of rel_context * polymorphic_arity type constr_substituted val force_constr : constr_substituted -> constr val from_val : constr -> constr_substituted type constant_body = { const_body : constr_substituted option; const_type : constant_type; const_body_code : to_patch_substituted; const_constraints : Univ.constraints; const_opaque : bool; const_inline : bool} Mutual inductives type recarg = | Norec | Mrec of int | Imbr of inductive type wf_paths = recarg Rtree.t val mk_norec : wf_paths val mk_paths : recarg -> wf_paths list array -> wf_paths val dest_subterms : wf_paths -> wf_paths list array type monomorphic_inductive_arity = { mind_user_arity : constr; mind_sort : sorts; } type inductive_arity = | Monomorphic of monomorphic_inductive_arity | Polymorphic of polymorphic_arity type one_inductive_body = { mind_typename : identifier; mind_arity_ctxt : rel_context; mind_arity : inductive_arity; mind_consnames : identifier array; Types of the constructors with parameters : [ forall params , Tij ] , where the Ik are replaced by de Bruijn index in the context I1 : forall params , U1 .. In : forall params , Un where the Ik are replaced by de Bruijn index in the context I1:forall params, U1 .. In:forall params, Un *) mind_user_lc : constr array; mind_nrealargs : int; mind_kelim : sorts_family list; mind_nf_lc : constr array; mind_consnrealdecls : int array; mind_recargs : wf_paths; mind_nb_constant : int; mind_nb_args : int; mind_reloc_tbl : reloc_table; } type mutual_inductive_body = { mind_packets : one_inductive_body array; mind_record : bool; mind_finite : bool; mind_ntypes : int; mind_hyps : section_context; mind_nparams : int; mind_nparams_rec : int; mind_params_ctxt : rel_context; Universes constraints enforced by the inductive declaration mind_constraints : Univ.constraints; mind_equiv : kernel_name option } type substitution type structure_field_body = | SFBconst of constant_body | SFBmind of mutual_inductive_body | SFBmodule of module_body | SFBalias of module_path * Univ.constraints option | SFBmodtype of module_type_body and structure_body = (label * structure_field_body) list and struct_expr_body = | SEBident of module_path | SEBfunctor of mod_bound_id * module_type_body * struct_expr_body | SEBstruct of mod_self_id * structure_body | SEBapply of struct_expr_body * struct_expr_body * Univ.constraints | SEBwith of struct_expr_body * with_declaration_body and with_declaration_body = With_module_body of identifier list * module_path * Univ.constraints | With_definition_body of identifier list * constant_body and module_body = { mod_expr : struct_expr_body option; mod_type : struct_expr_body option; mod_constraints : Univ.constraints; mod_alias : substitution; mod_retroknowledge : action list} and module_type_body = { typ_expr : struct_expr_body; typ_strength : module_path option; typ_alias : substitution} val fold_subst : (mod_self_id -> module_path -> 'a -> 'a) -> (mod_bound_id -> module_path -> 'a -> 'a) -> (module_path -> module_path -> 'a -> 'a) -> substitution -> 'a -> 'a type 'a subst_fun = substitution -> 'a -> 'a val empty_subst : substitution val add_msid : mod_self_id -> module_path -> substitution -> substitution val add_mbid : mod_bound_id -> module_path -> substitution -> substitution val add_mp : module_path -> module_path -> substitution -> substitution val map_msid : mod_self_id -> module_path -> substitution val map_mbid : mod_bound_id -> module_path -> substitution val map_mp : module_path -> module_path -> substitution val subst_const_body : constant_body subst_fun val subst_mind : mutual_inductive_body subst_fun val subst_modtype : substitution -> module_type_body -> module_type_body val subst_struct_expr : substitution -> struct_expr_body -> struct_expr_body val subst_structure : substitution -> structure_body -> structure_body val subst_signature_msid : mod_self_id -> module_path -> structure_body -> structure_body val join : substitution -> substitution -> substitution val join_alias : substitution -> substitution -> substitution val update_subst_alias : substitution -> substitution -> substitution val update_subst : substitution -> substitution -> substitution val subst_key : substitution -> substitution -> substitution
0afd8a8f76c7ef4fddc92f3a80e9340f8cfb517c2471751dc7b9160ceab604ff
cram2/cram
series-acceleration.lisp
Series acceleration . , We d Nov 21 2007 - 18:41 Time - stamp : < 2012 - 01 - 13 12:01:09EST series-acceleration.lisp > ;; Copyright 2007 , 2008 , 2009 , 2011 Distributed under the terms of the GNU General Public License ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. (in-package :gsl) ;;; /usr/include/gsl/gsl_sum.h ;;;;**************************************************************************** Creation and calculation of series acceleration ;;;;**************************************************************************** (defun levin-value (levin slot) (cffi:foreign-slot-value (mpointer levin) '(:struct levin-c) slot)) (defmobject levin "gsl_sum_levin_u" ((order :sizet)) "Levin u-transform" "Make a workspace for a Levin u-transform of n terms. The size of the workspace is O(2n^2 + 3n).") (defmfun accelerate (array levin) "gsl_sum_levin_u_accel" (((grid:foreign-pointer array) :pointer) ((dim0 array) :sizet) ((mpointer levin) :pointer) (accelerated-sum (:pointer :double)) (abserr (:pointer :double))) :inputs (array) "From the terms of a series in array, compute the extrapolated limit of the series using a Levin u-transform. Additional working space must be provided in levin. The extrapolated sum is returned with an estimate of the absolute error. The actual term-by-term sum is returned in w->sum_plain. The algorithm calculates the truncation error (the difference between two successive extrapolations) and round-off error (propagated from the individual terms) to choose an optimal number of terms for the extrapolation.") ;;;;**************************************************************************** ;;;; Acceleration with error estimation from truncation ;;;;**************************************************************************** (defmobject levin-truncated "gsl_sum_levin_utrunc" ((order :sizet)) "truncated Levin u-transform" "Make a workspace for a Levin u-transform of n terms, without error estimation. The size of the workspace is O(3n).") (defmfun accelerate-truncated (array levin) "gsl_sum_levin_utrunc_accel" (((grid:foreign-pointer array) :pointer) ((dim0 array) :sizet) ((mpointer levin) :pointer) (accelerated-sum (:pointer :double)) (abserr (:pointer :double))) :inputs (array) "From the terms of a series in array, compute the extrapolated limit of the series using a Levin u-transform. Additional working space must be provided in levin. The extrapolated sum is returned with an estimate of the absolute error. The actual term-by-term sum is returned in w->sum_plain. The algorithm terminates when the difference between two successive extrapolations reaches a minimum or is sufficiently small. The difference between these two values is used as estimate of the error and is stored in abserr_trunc. To improve the reliability of the algorithm the extrapolated values are replaced by moving averages when calculating the truncation error, smoothing out any fluctuations.") ;;;;**************************************************************************** ;;;; Example ;;;;**************************************************************************** From Sec . 29.3 in the GSL manual . (defun acceleration-example (&optional (print-explanation t)) (let ((maxterms 20) (sum 0.0d0) (zeta2 (/ (expt dpi 2) 6))) (let ((levin (make-levin maxterms)) (array (grid:make-foreign-array 'double-float :dimensions maxterms))) (dotimes (n maxterms) (setf (grid:aref array n) (coerce (/ (expt (1+ n) 2)) 'double-float)) (incf sum (grid:aref array n))) (multiple-value-bind (accelerated-sum error) (accelerate array levin) (when print-explanation (format t "term-by-term sum =~f using ~d terms~&" sum maxterms) (format t "term-by-term sum =~f using ~d terms~&" (levin-value levin 'sum-plain) (levin-value levin 'terms-used)) (format t "exact value = ~f~&" zeta2) (format t "accelerated sum = ~f using ~d terms~&" accelerated-sum (levin-value levin 'terms-used)) (format t "estimated error = ~f~&" error) (format t "actual error = ~f ~&" (- accelerated-sum zeta2))) (values sum maxterms (levin-value levin 'sum-plain) (levin-value levin 'terms-used) accelerated-sum error (- accelerated-sum zeta2)))))) term - by - term sum = 1.5961632439130233 using 20 terms term - by - term sum = 1.5759958390005426 using 13 terms exact value = 1.6449340668482264 accelerated sum = 1.6449340669228176 using 13 terms estimated error = 0.00000000008883604962761638 actual error = 0.00000000007459122208786084 (save-test series-acceleration (acceleration-example nil))
null
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/series-acceleration.lisp
lisp
This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. /usr/include/gsl/gsl_sum.h **************************************************************************** **************************************************************************** **************************************************************************** Acceleration with error estimation from truncation **************************************************************************** **************************************************************************** Example ****************************************************************************
Series acceleration . , We d Nov 21 2007 - 18:41 Time - stamp : < 2012 - 01 - 13 12:01:09EST series-acceleration.lisp > Copyright 2007 , 2008 , 2009 , 2011 Distributed under the terms of the GNU General Public License it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (in-package :gsl) Creation and calculation of series acceleration (defun levin-value (levin slot) (cffi:foreign-slot-value (mpointer levin) '(:struct levin-c) slot)) (defmobject levin "gsl_sum_levin_u" ((order :sizet)) "Levin u-transform" "Make a workspace for a Levin u-transform of n terms. The size of the workspace is O(2n^2 + 3n).") (defmfun accelerate (array levin) "gsl_sum_levin_u_accel" (((grid:foreign-pointer array) :pointer) ((dim0 array) :sizet) ((mpointer levin) :pointer) (accelerated-sum (:pointer :double)) (abserr (:pointer :double))) :inputs (array) "From the terms of a series in array, compute the extrapolated limit of the series using a Levin u-transform. Additional working space must be provided in levin. The extrapolated sum is returned with an estimate of the absolute error. The actual term-by-term sum is returned in w->sum_plain. The algorithm calculates the truncation error (the difference between two successive extrapolations) and round-off error (propagated from the individual terms) to choose an optimal number of terms for the extrapolation.") (defmobject levin-truncated "gsl_sum_levin_utrunc" ((order :sizet)) "truncated Levin u-transform" "Make a workspace for a Levin u-transform of n terms, without error estimation. The size of the workspace is O(3n).") (defmfun accelerate-truncated (array levin) "gsl_sum_levin_utrunc_accel" (((grid:foreign-pointer array) :pointer) ((dim0 array) :sizet) ((mpointer levin) :pointer) (accelerated-sum (:pointer :double)) (abserr (:pointer :double))) :inputs (array) "From the terms of a series in array, compute the extrapolated limit of the series using a Levin u-transform. Additional working space must be provided in levin. The extrapolated sum is returned with an estimate of the absolute error. The actual term-by-term sum is returned in w->sum_plain. The algorithm terminates when the difference between two successive extrapolations reaches a minimum or is sufficiently small. The difference between these two values is used as estimate of the error and is stored in abserr_trunc. To improve the reliability of the algorithm the extrapolated values are replaced by moving averages when calculating the truncation error, smoothing out any fluctuations.") From Sec . 29.3 in the GSL manual . (defun acceleration-example (&optional (print-explanation t)) (let ((maxterms 20) (sum 0.0d0) (zeta2 (/ (expt dpi 2) 6))) (let ((levin (make-levin maxterms)) (array (grid:make-foreign-array 'double-float :dimensions maxterms))) (dotimes (n maxterms) (setf (grid:aref array n) (coerce (/ (expt (1+ n) 2)) 'double-float)) (incf sum (grid:aref array n))) (multiple-value-bind (accelerated-sum error) (accelerate array levin) (when print-explanation (format t "term-by-term sum =~f using ~d terms~&" sum maxterms) (format t "term-by-term sum =~f using ~d terms~&" (levin-value levin 'sum-plain) (levin-value levin 'terms-used)) (format t "exact value = ~f~&" zeta2) (format t "accelerated sum = ~f using ~d terms~&" accelerated-sum (levin-value levin 'terms-used)) (format t "estimated error = ~f~&" error) (format t "actual error = ~f ~&" (- accelerated-sum zeta2))) (values sum maxterms (levin-value levin 'sum-plain) (levin-value levin 'terms-used) accelerated-sum error (- accelerated-sum zeta2)))))) term - by - term sum = 1.5961632439130233 using 20 terms term - by - term sum = 1.5759958390005426 using 13 terms exact value = 1.6449340668482264 accelerated sum = 1.6449340669228176 using 13 terms estimated error = 0.00000000008883604962761638 actual error = 0.00000000007459122208786084 (save-test series-acceleration (acceleration-example nil))
b1468a30f9c436c86a05ceed70741397ca4482037ade0c7af21ac50b5bd86b9b
gonzojive/sbcl
cache.lisp
the basics of the PCL wrapper cache mechanism This software is part of the SBCL system . See the README file for ;;;; more information. This software is derived from software originally released by Xerox ;;;; Corporation. Copyright and release statements follow. Later modifications ;;;; to the software are in the public domain and are provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for more ;;;; information. copyright information from original PCL sources : ;;;; Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . ;;;; All rights reserved. ;;;; ;;;; Use and copying of this software and preparation of derivative works based ;;;; upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United States export ;;;; control laws. ;;;; This software is made available AS IS , and Xerox Corporation makes no ;;;; warranty about the software, its performance or its conformity to any ;;;; specification. Note : as of SBCL 1.0.6.3 it is questionable if cache.lisp can ;;;; anymore be considered to be "derived from software originally released by Xerox Corporation " , as at that time the whole cache ;;;; implementation was essentially redone from scratch. (in-package "SB!PCL") ;;;; Public API: ;;;; ;;;; fill-cache ;;;; probe-cache ;;;; make-cache ;;;; map-cache ;;;; emit-cache-lookup ;;;; copy-cache ;;;; hash-table-to-cache ;;;; ;;;; This is a thread and interrupt safe reimplementation loosely based on the original PCL cache by and Rodrigues , as described in " Efficient Method Dispatch in PCL " . ;;;; ;;;; * Writes to cache are made atomic using compare-and-swap on ;;;; wrappers. Wrappers are never moved or deleted after they have ;;;; been written: to clean them out the cache need to be copied. ;;;; ;;;; * Copying or expanding the cache drops out incomplete and invalid ;;;; lines. ;;;; ;;;; * Since the cache is used for memoization only we don't need to ;;;; worry about which of simultaneous replacements (when expanding ;;;; the cache) takes place: the losing one will have its work ;;;; redone later. This also allows us to drop entries when the ;;;; cache is about to grow insanely huge. ;;;; ;;;; The cache is essentially a specialized hash-table for layouts, used ;;;; for memoization of effective methods, slot locations, and constant ;;;; return values. ;;;; ;;;; Subsequences of the cache vector are called cache lines. ;;;; ;;;; The cache vector uses the symbol SB!PCL::..EMPTY.. as a sentinel value , to allow storing NILs in the vector as well . (def!struct (cache (:constructor %make-cache) (:copier %copy-cache)) ;; Number of keys the cache uses. (key-count 1 :type (integer 1 (#.call-arguments-limit))) ;; True if we store values in the cache. (value) ;; Number of vector elements a single cache line uses in the vector. This is always a power of two , so that the vector length can be both an exact multiple of this and a power of two . (line-size 1 :type (integer 1 #.most-positive-fixnum)) Cache vector , its length is always both a multiple of line - size and a power of two . This is so that we can calculate ;; (mod index (length vector)) ;; using a bitmask. (vector #() :type simple-vector) ;; The bitmask used to calculate ;; (mod (* line-size line-hash) (length vector))). (mask 0 :type fixnum) ;; Current probe-depth needed in the cache. (depth 0 :type index) ;; Maximum allowed probe-depth before the cache needs to expand. (limit 0 :type index)) (defun compute-cache-mask (vector-length line-size) Since both vector - length and line - size are powers of two , we ;; can compute a bitmask such that ;; ;; (logand <mask> <combined-layout-hash>) ;; ;; is "morally equal" to ;; ;; (mod (* <line-size> <combined-layout-hash>) <vector-length>) ;; This is it : ( 1- vector - length ) is # b111 ... of the approriate size to get the MOD , and ( - line - size ) gives right the number of zero ;; bits at the low end. (logand (1- vector-length) (- line-size))) (defun cache-statistics (cache) (let* ((vector (cache-vector cache)) (size (length vector)) (line-size (cache-line-size cache)) (total-lines (/ size line-size)) (free-lines (loop for i from 0 by line-size below size unless (eq (svref vector i) '..empty..) count t))) (values (- total-lines free-lines) total-lines (cache-depth cache) (cache-limit cache)))) Do n't allocate insanely huge caches : this is 4096 lines for a value cache with 8 - 15 keys -- probably " big enough for anyone " , and 16384 lines for a commonplace 2 - key value cache . (defconstant +cache-vector-max-length+ (expt 2 16)) ;;; Compute the maximum allowed probe depth as a function of cache size. ;;; Cache size refers to number of cache lines, not the length of the ;;; cache vector. ;;; ;;; FIXME: It would be nice to take the generic function optimization ;;; policy into account here (speed vs. space.) (declaim (inline compute-limit)) (defun compute-limit (size) (ceiling (sqrt (sqrt size)))) ;;; Returns VALUE if it is not ..EMPTY.., otherwise executes ELSE: (defmacro non-empty-or (value else) (with-unique-names (n-value) `(let ((,n-value ,value)) (if (eq ,n-value '..empty..) ,else ,n-value)))) ;;; Fast way to check if a thing found at the position of a cache key is one: ;;; it is always either a wrapper, or the ..EMPTY.. symbol. (declaim (inline cache-key-p)) (defun cache-key-p (thing) (not (symbolp thing))) ;;; Atomically update the current probe depth of a cache. (defun note-cache-depth (cache depth) (loop for old = (cache-depth cache) while (and (< old depth) (not (eq old (compare-and-swap (cache-depth cache) old depth)))))) ;;; Compute the starting index of the next cache line in the cache vector. (declaim (inline next-cache-index)) (defun next-cache-index (mask index line-size) (declare (type (unsigned-byte #.sb!vm:n-word-bits) index line-size mask)) (logand mask (+ index line-size))) ;;; Returns the hash-value for layout, or executes ELSE if the layout ;;; is invalid. (defmacro hash-layout-or (layout else) (with-unique-names (n-hash) `(let ((,n-hash (layout-clos-hash ,layout))) (if (zerop ,n-hash) ,else ,n-hash)))) ;;; Compute cache index for the cache and a list of layouts. (declaim (inline compute-cache-index)) (defun compute-cache-index (cache layouts) (let ((index (hash-layout-or (car layouts) (return-from compute-cache-index nil)))) (declare (fixnum index)) (dolist (layout (cdr layouts)) (mixf index (hash-layout-or layout (return-from compute-cache-index nil)))) ;; align with cache lines (logand index (cache-mask cache)))) ;;; Emit code that does lookup in cache bound to CACHE-VAR using layouts bound to LAYOUT - VARS . Go to MISS - TAG on event of a miss or invalid layout . Otherwise , if VALUE - VAR is non - nil , set it to the value found . ( VALUE - VAR is non - nil only when CACHE - VALUE is true . ) ;;; ;;; In other words, produces inlined code for COMPUTE-CACHE-INDEX when ;;; number of keys and presence of values in the cache is known ;;; beforehand. (defun emit-cache-lookup (cache-var layout-vars miss-tag value-var) (let ((line-size (power-of-two-ceiling (+ (length layout-vars) (if value-var 1 0))))) (with-unique-names (n-index n-vector n-depth n-pointer n-mask MATCH-WRAPPERS EXIT-WITH-HIT) `(let* ((,n-index (hash-layout-or ,(car layout-vars) (go ,miss-tag))) (,n-vector (cache-vector ,cache-var)) (,n-mask (cache-mask ,cache-var))) (declare (index ,n-index)) ,@(mapcar (lambda (layout-var) `(mixf ,n-index (hash-layout-or ,layout-var (go ,miss-tag)))) (cdr layout-vars)) ;; align with cache lines (setf ,n-index (logand ,n-index ,n-mask)) (let ((,n-depth (cache-depth ,cache-var)) (,n-pointer ,n-index)) (declare (index ,n-depth ,n-pointer)) (tagbody ,MATCH-WRAPPERS (when (and ,@(mapcar (lambda (layout-var) `(prog1 (eq ,layout-var (svref ,n-vector ,n-pointer)) (incf ,n-pointer))) layout-vars)) ,@(when value-var `((setf ,value-var (non-empty-or (svref ,n-vector ,n-pointer) (go ,miss-tag))))) (go ,EXIT-WITH-HIT)) (if (zerop ,n-depth) (go ,miss-tag) (decf ,n-depth)) (setf ,n-index (next-cache-index ,n-mask ,n-index ,line-size) ,n-pointer ,n-index) (go ,MATCH-WRAPPERS) ,EXIT-WITH-HIT)))))) Probes CACHE for LAYOUTS . ;;; Returns two values : a boolean indicating a hit or a miss , and a secondary ;;; value that is the value that was stored in the cache if any. (defun probe-cache (cache layouts) (declare (optimize speed)) (unless (consp layouts) (setf layouts (list layouts))) (let ((vector (cache-vector cache)) (key-count (cache-key-count cache)) (line-size (cache-line-size cache)) (mask (cache-mask cache))) (flet ((probe-line (base) #+sb-xc (declare (optimize (sb!c::type-check 0))) (tagbody (loop for offset of-type index from 0 below key-count for layout in layouts do (unless (eq layout (svref vector (+ base offset))) ;; missed (go :miss))) ;; all layouts match! (let ((value (when (cache-value cache) (non-empty-or (svref vector (+ base key-count)) (go :miss))))) (return-from probe-cache (values t value))) :miss (return-from probe-line (next-cache-index mask base line-size))))) (declare (ftype (function (index) (values index &optional)) probe-line)) (let ((index (compute-cache-index cache layouts))) (when index (loop repeat (1+ (cache-depth cache)) do (setf index (probe-line index))))))) (values nil nil)) Tries to write LAYOUTS and VALUE at the cache line starting at ;;; the index BASE. Returns true on success, and false on failure. (defun try-update-cache-line (cache base layouts value) (declare (index base)) (let ((vector (cache-vector cache)) (new (pop layouts))) ;; If we unwind from here, we will be left with an incomplete ;; cache line, but that is OK: next write using the same layouts ;; will fill it, and reads will treat an incomplete line as a ;; miss -- causing it to be filled. (loop for old = (compare-and-swap (svref vector base) '..empty.. new) do (when (and (cache-key-p old) (not (eq old new))) ;; The place was already taken, and doesn't match our key. (return-from try-update-cache-line nil)) (unless layouts ;; All keys match or succesfully saved, save our value -- just smash it in . Until the first time it is written ;; there is ..EMPTY.. here, which probes look for, so we ;; don't get bogus hits. This is necessary because we want ;; to be able store arbitrary values here for use with ;; constant-value dispatch functions. (when (cache-value cache) (setf (svref vector (1+ base)) value)) (return-from try-update-cache-line t)) (setf new (pop layouts)) (incf base)))) Tries to write LAYOUTS and VALUE somewhere in the cache . Returns ;;; true on success and false on failure, meaning the cache is too ;;; full. (defun try-update-cache (cache layouts value) (let ((index (or (compute-cache-index cache layouts) At least one of the layouts was invalid : just ;; pretend we updated the cache, and let the next ;; read pick up the mess. (return-from try-update-cache t))) (line-size (cache-line-size cache)) (mask (cache-mask cache))) (declare (index index)) (loop for depth from 0 upto (cache-limit cache) do (when (try-update-cache-line cache index layouts value) (note-cache-depth cache depth) (return-from try-update-cache t)) (setf index (next-cache-index mask index line-size))))) Constructs a new cache . (defun make-cache (&key (key-count (missing-arg)) (value (missing-arg)) (size 1)) (let* ((line-size (power-of-two-ceiling (+ key-count (if value 1 0)))) (adjusted-size (power-of-two-ceiling size)) (length (* adjusted-size line-size))) (if (<= length +cache-vector-max-length+) (%make-cache :key-count key-count :line-size line-size :vector (make-array length :initial-element '..empty..) :value value :mask (compute-cache-mask length line-size) :limit (compute-limit adjusted-size)) ;; Make a smaller one, then (make-cache :key-count key-count :value value :size (ceiling size 2))))) ;;;; Copies and expands the cache, dropping any invalidated or ;;;; incomplete lines. (defun copy-and-expand-cache (cache layouts value) (let ((copy (%copy-cache cache)) (length (length (cache-vector cache))) (drop-random-entries nil)) (declare (index length)) (when (< length +cache-vector-max-length+) (setf length (* 2 length))) (tagbody :again Blow way the old vector first , so a GC potentially triggered by ;; MAKE-ARRAY can collect it. (setf (cache-vector copy) #() (cache-vector copy) (make-array length :initial-element '..empty..) (cache-depth copy) 0 (cache-mask copy) (compute-cache-mask length (cache-line-size cache)) (cache-limit copy) (compute-limit (/ length (cache-line-size cache)))) First insert the new one -- if we do n't do this first and ;; the cache has reached its maximum size we may end up looping in FILL - CACHE . (unless (try-update-cache copy layouts value) (bug "Could not insert ~S:~S to supposedly empty ~S." layouts value copy)) (map-cache (if drop-random-entries ;; The cache is at maximum size, and all entries do not fit in . Drop a random ~50 % of entries , ;; to make space for new ones. This needs to be ;; random, since otherwise we might get in a ;; rut: add A causing B to drop, then add B ;; causing A to drop... repeat ad nauseam, ;; spending most of the time here instead of doing real work . 50 % because if we drop too ;; few we need to do this almost right away ;; again, and if we drop too many, we need to ;; recompute more then we'd like. _ Experimentally _ 50 % seems to perform the ;; best, but it would be nice to have a proper ;; analysis... (randomly-punting-lambda (layouts value) (try-update-cache copy layouts value)) (lambda (layouts value) (unless (try-update-cache copy layouts value) ;; Didn't fit -- expand the cache, or drop ;; a few unlucky ones. (if (< length +cache-vector-max-length+) (setf length (* 2 length)) (setf drop-random-entries t)) (go :again)))) cache)) copy)) (defun cache-has-invalid-entries-p (cache) (let ((vector (cache-vector cache)) (line-size (cache-line-size cache)) (key-count (cache-key-count cache)) (mask (cache-mask cache)) (index 0)) (loop ;; Check if the line is in use, and check validity of the keys. (let ((key1 (svref vector index))) (when (cache-key-p key1) (if (zerop (layout-clos-hash key1)) First key invalid . (return-from cache-has-invalid-entries-p t) Line is in use and the first key is valid : check the rest . (loop for offset from 1 below key-count do (let ((thing (svref vector (+ index offset)))) (when (or (not (cache-key-p thing)) (zerop (layout-clos-hash thing))) ;; Incomplete line or invalid layout. (return-from cache-has-invalid-entries-p t))))))) ;; Line empty of valid, onwards. (setf index (next-cache-index mask index line-size)) (when (zerop index) ;; wrapped around (return-from cache-has-invalid-entries-p nil))))) (defun hash-table-to-cache (table &key value key-count) (let ((cache (make-cache :key-count key-count :value value :size (hash-table-count table)))) (maphash (lambda (class value) (setq cache (fill-cache cache (class-wrapper class) value))) table) cache)) Inserts VALUE to by LAYOUTS . Expands the cache if ;;; necessary, and returns the new cache. (defun fill-cache (cache layouts value) (labels ((%fill-cache (cache layouts value expand) (cond ((try-update-cache cache layouts value) cache) ((and (not expand) (cache-has-invalid-entries-p cache)) ;; Don't expand yet: maybe there will be enough space if ;; we just drop the invalid entries. (%fill-cache (copy-cache cache) layouts value t)) (t (copy-and-expand-cache cache layouts value))))) (if (listp layouts) (%fill-cache cache layouts value nil) (%fill-cache cache (list layouts) value nil)))) ;;; Calls FUNCTION with all layouts and values in cache. (defun map-cache (function cache) (let* ((vector (cache-vector cache)) (key-count (cache-key-count cache)) (valuep (cache-value cache)) (line-size (cache-line-size cache)) (mask (cache-mask cache)) (fun (if (functionp function) function (fdefinition function))) (index 0)) (tagbody :map (let ((layouts (loop for offset from 0 below key-count collect (non-empty-or (svref vector (+ offset index)) (go :next))))) (let ((value (when valuep (non-empty-or (svref vector (+ index key-count)) (go :next))))) ;; Let the callee worry about invalid layouts (funcall fun layouts value))) :next (setf index (next-cache-index mask index line-size)) (unless (zerop index) (go :map)))) cache) ;;; Copying a cache without expanding it is very much like mapping it: ;;; we need to be carefull because there may be updates while we are ;;; copying it, and we don't want to copy incomplete entries or invalid ;;; ones. (defun copy-cache (cache) (let* ((vector (cache-vector cache)) (copy (make-array (length vector) :initial-element '..empty..)) (line-size (cache-line-size cache)) (key-count (cache-key-count cache)) (valuep (cache-value cache)) (mask (cache-mask cache)) (size (/ (length vector) line-size)) (index 0) (depth 0)) (tagbody :copy (let ((layouts (loop for offset from 0 below key-count collect (non-empty-or (svref vector (+ index offset)) (go :next))))) ;; Check validity & compute primary index. (let ((primary (or (compute-cache-index cache layouts) (go :next)))) ;; Check & copy value. (when valuep (setf (svref copy (+ index key-count)) (non-empty-or (svref vector (+ index key-count)) (go :next)))) ;; Copy layouts. (loop for offset from 0 below key-count do (setf (svref copy (+ index offset)) (pop layouts))) ;; Update probe depth. (let ((distance (/ (- index primary) line-size))) (setf depth (max depth (if (minusp distance) ;; account for wrap-around (+ distance size) distance)))))) :next (setf index (next-cache-index mask index line-size)) (unless (zerop index) (go :copy))) (%make-cache :vector copy :depth depth :key-count (cache-key-count cache) :line-size line-size :value valuep :mask mask :limit (cache-limit cache)))) ;;;; For debugging & collecting statistics. (defun map-all-caches (function) (dolist (p (list-all-packages)) (do-symbols (s p) (when (eq p (symbol-package s)) (dolist (name (list s `(setf ,s) (slot-reader-name s) (slot-writer-name s) (slot-boundp-name s))) (when (fboundp name) (let ((fun (fdefinition name))) (when (typep fun 'generic-function) (let ((cache (gf-dfun-cache fun))) (when cache (funcall function name cache))))))))))) (defun check-cache-consistency (cache) (let ((table (make-hash-table :test 'equal))) (map-cache (lambda (layouts value) (declare (ignore value)) (if (gethash layouts table) (cerror "Check futher." "Multiple appearances of ~S." layouts) (setf (gethash layouts table) t))) cache)))
null
https://raw.githubusercontent.com/gonzojive/sbcl/3210d8ed721541d5bba85cbf51831238990e33f1/src/pcl/cache.lisp
lisp
more information. Corporation. Copyright and release statements follow. Later modifications to the software are in the public domain and are provided with absolutely no warranty. See the COPYING and CREDITS files for more information. All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this software or control laws. warranty about the software, its performance or its conformity to any specification. anymore be considered to be "derived from software originally implementation was essentially redone from scratch. Public API: fill-cache probe-cache make-cache map-cache emit-cache-lookup copy-cache hash-table-to-cache This is a thread and interrupt safe reimplementation loosely * Writes to cache are made atomic using compare-and-swap on wrappers. Wrappers are never moved or deleted after they have been written: to clean them out the cache need to be copied. * Copying or expanding the cache drops out incomplete and invalid lines. * Since the cache is used for memoization only we don't need to worry about which of simultaneous replacements (when expanding the cache) takes place: the losing one will have its work redone later. This also allows us to drop entries when the cache is about to grow insanely huge. The cache is essentially a specialized hash-table for layouts, used for memoization of effective methods, slot locations, and constant return values. Subsequences of the cache vector are called cache lines. The cache vector uses the symbol SB!PCL::..EMPTY.. as a sentinel Number of keys the cache uses. True if we store values in the cache. Number of vector elements a single cache line uses in the vector. (mod index (length vector)) using a bitmask. The bitmask used to calculate (mod (* line-size line-hash) (length vector))). Current probe-depth needed in the cache. Maximum allowed probe-depth before the cache needs to expand. can compute a bitmask such that (logand <mask> <combined-layout-hash>) is "morally equal" to (mod (* <line-size> <combined-layout-hash>) <vector-length>) bits at the low end. Compute the maximum allowed probe depth as a function of cache size. Cache size refers to number of cache lines, not the length of the cache vector. FIXME: It would be nice to take the generic function optimization policy into account here (speed vs. space.) Returns VALUE if it is not ..EMPTY.., otherwise executes ELSE: Fast way to check if a thing found at the position of a cache key is one: it is always either a wrapper, or the ..EMPTY.. symbol. Atomically update the current probe depth of a cache. Compute the starting index of the next cache line in the cache vector. Returns the hash-value for layout, or executes ELSE if the layout is invalid. Compute cache index for the cache and a list of layouts. align with cache lines Emit code that does lookup in cache bound to CACHE-VAR using In other words, produces inlined code for COMPUTE-CACHE-INDEX when number of keys and presence of values in the cache is known beforehand. align with cache lines value that is the value that was stored in the cache if any. missed all layouts match! the index BASE. Returns true on success, and false on failure. If we unwind from here, we will be left with an incomplete cache line, but that is OK: next write using the same layouts will fill it, and reads will treat an incomplete line as a miss -- causing it to be filled. The place was already taken, and doesn't match our key. All keys match or succesfully saved, save our value -- there is ..EMPTY.. here, which probes look for, so we don't get bogus hits. This is necessary because we want to be able store arbitrary values here for use with constant-value dispatch functions. true on success and false on failure, meaning the cache is too full. pretend we updated the cache, and let the next read pick up the mess. Make a smaller one, then Copies and expands the cache, dropping any invalidated or incomplete lines. MAKE-ARRAY can collect it. the cache has reached its maximum size we may end up looping The cache is at maximum size, and all entries to make space for new ones. This needs to be random, since otherwise we might get in a rut: add A causing B to drop, then add B causing A to drop... repeat ad nauseam, spending most of the time here instead of few we need to do this almost right away again, and if we drop too many, we need to recompute more then we'd like. best, but it would be nice to have a proper analysis... Didn't fit -- expand the cache, or drop a few unlucky ones. Check if the line is in use, and check validity of the keys. Incomplete line or invalid layout. Line empty of valid, onwards. wrapped around necessary, and returns the new cache. Don't expand yet: maybe there will be enough space if we just drop the invalid entries. Calls FUNCTION with all layouts and values in cache. Let the callee worry about invalid layouts Copying a cache without expanding it is very much like mapping it: we need to be carefull because there may be updates while we are copying it, and we don't want to copy incomplete entries or invalid ones. Check validity & compute primary index. Check & copy value. Copy layouts. Update probe depth. account for wrap-around For debugging & collecting statistics.
the basics of the PCL wrapper cache mechanism This software is part of the SBCL system . See the README file for This software is derived from software originally released by Xerox copyright information from original PCL sources : Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . derivative works must comply with all applicable United States export This software is made available AS IS , and Xerox Corporation makes no Note : as of SBCL 1.0.6.3 it is questionable if cache.lisp can released by Xerox Corporation " , as at that time the whole cache (in-package "SB!PCL") based on the original PCL cache by and Rodrigues , as described in " Efficient Method Dispatch in PCL " . value , to allow storing NILs in the vector as well . (def!struct (cache (:constructor %make-cache) (:copier %copy-cache)) (key-count 1 :type (integer 1 (#.call-arguments-limit))) (value) This is always a power of two , so that the vector length can be both an exact multiple of this and a power of two . (line-size 1 :type (integer 1 #.most-positive-fixnum)) Cache vector , its length is always both a multiple of line - size and a power of two . This is so that we can calculate (vector #() :type simple-vector) (mask 0 :type fixnum) (depth 0 :type index) (limit 0 :type index)) (defun compute-cache-mask (vector-length line-size) Since both vector - length and line - size are powers of two , we This is it : ( 1- vector - length ) is # b111 ... of the approriate size to get the MOD , and ( - line - size ) gives right the number of zero (logand (1- vector-length) (- line-size))) (defun cache-statistics (cache) (let* ((vector (cache-vector cache)) (size (length vector)) (line-size (cache-line-size cache)) (total-lines (/ size line-size)) (free-lines (loop for i from 0 by line-size below size unless (eq (svref vector i) '..empty..) count t))) (values (- total-lines free-lines) total-lines (cache-depth cache) (cache-limit cache)))) Do n't allocate insanely huge caches : this is 4096 lines for a value cache with 8 - 15 keys -- probably " big enough for anyone " , and 16384 lines for a commonplace 2 - key value cache . (defconstant +cache-vector-max-length+ (expt 2 16)) (declaim (inline compute-limit)) (defun compute-limit (size) (ceiling (sqrt (sqrt size)))) (defmacro non-empty-or (value else) (with-unique-names (n-value) `(let ((,n-value ,value)) (if (eq ,n-value '..empty..) ,else ,n-value)))) (declaim (inline cache-key-p)) (defun cache-key-p (thing) (not (symbolp thing))) (defun note-cache-depth (cache depth) (loop for old = (cache-depth cache) while (and (< old depth) (not (eq old (compare-and-swap (cache-depth cache) old depth)))))) (declaim (inline next-cache-index)) (defun next-cache-index (mask index line-size) (declare (type (unsigned-byte #.sb!vm:n-word-bits) index line-size mask)) (logand mask (+ index line-size))) (defmacro hash-layout-or (layout else) (with-unique-names (n-hash) `(let ((,n-hash (layout-clos-hash ,layout))) (if (zerop ,n-hash) ,else ,n-hash)))) (declaim (inline compute-cache-index)) (defun compute-cache-index (cache layouts) (let ((index (hash-layout-or (car layouts) (return-from compute-cache-index nil)))) (declare (fixnum index)) (dolist (layout (cdr layouts)) (mixf index (hash-layout-or layout (return-from compute-cache-index nil)))) (logand index (cache-mask cache)))) layouts bound to LAYOUT - VARS . Go to MISS - TAG on event of a miss or invalid layout . Otherwise , if VALUE - VAR is non - nil , set it to the value found . ( VALUE - VAR is non - nil only when CACHE - VALUE is true . ) (defun emit-cache-lookup (cache-var layout-vars miss-tag value-var) (let ((line-size (power-of-two-ceiling (+ (length layout-vars) (if value-var 1 0))))) (with-unique-names (n-index n-vector n-depth n-pointer n-mask MATCH-WRAPPERS EXIT-WITH-HIT) `(let* ((,n-index (hash-layout-or ,(car layout-vars) (go ,miss-tag))) (,n-vector (cache-vector ,cache-var)) (,n-mask (cache-mask ,cache-var))) (declare (index ,n-index)) ,@(mapcar (lambda (layout-var) `(mixf ,n-index (hash-layout-or ,layout-var (go ,miss-tag)))) (cdr layout-vars)) (setf ,n-index (logand ,n-index ,n-mask)) (let ((,n-depth (cache-depth ,cache-var)) (,n-pointer ,n-index)) (declare (index ,n-depth ,n-pointer)) (tagbody ,MATCH-WRAPPERS (when (and ,@(mapcar (lambda (layout-var) `(prog1 (eq ,layout-var (svref ,n-vector ,n-pointer)) (incf ,n-pointer))) layout-vars)) ,@(when value-var `((setf ,value-var (non-empty-or (svref ,n-vector ,n-pointer) (go ,miss-tag))))) (go ,EXIT-WITH-HIT)) (if (zerop ,n-depth) (go ,miss-tag) (decf ,n-depth)) (setf ,n-index (next-cache-index ,n-mask ,n-index ,line-size) ,n-pointer ,n-index) (go ,MATCH-WRAPPERS) ,EXIT-WITH-HIT)))))) Probes CACHE for LAYOUTS . Returns two values : a boolean indicating a hit or a miss , and a secondary (defun probe-cache (cache layouts) (declare (optimize speed)) (unless (consp layouts) (setf layouts (list layouts))) (let ((vector (cache-vector cache)) (key-count (cache-key-count cache)) (line-size (cache-line-size cache)) (mask (cache-mask cache))) (flet ((probe-line (base) #+sb-xc (declare (optimize (sb!c::type-check 0))) (tagbody (loop for offset of-type index from 0 below key-count for layout in layouts do (unless (eq layout (svref vector (+ base offset))) (go :miss))) (let ((value (when (cache-value cache) (non-empty-or (svref vector (+ base key-count)) (go :miss))))) (return-from probe-cache (values t value))) :miss (return-from probe-line (next-cache-index mask base line-size))))) (declare (ftype (function (index) (values index &optional)) probe-line)) (let ((index (compute-cache-index cache layouts))) (when index (loop repeat (1+ (cache-depth cache)) do (setf index (probe-line index))))))) (values nil nil)) Tries to write LAYOUTS and VALUE at the cache line starting at (defun try-update-cache-line (cache base layouts value) (declare (index base)) (let ((vector (cache-vector cache)) (new (pop layouts))) (loop for old = (compare-and-swap (svref vector base) '..empty.. new) do (when (and (cache-key-p old) (not (eq old new))) (return-from try-update-cache-line nil)) (unless layouts just smash it in . Until the first time it is written (when (cache-value cache) (setf (svref vector (1+ base)) value)) (return-from try-update-cache-line t)) (setf new (pop layouts)) (incf base)))) Tries to write LAYOUTS and VALUE somewhere in the cache . Returns (defun try-update-cache (cache layouts value) (let ((index (or (compute-cache-index cache layouts) At least one of the layouts was invalid : just (return-from try-update-cache t))) (line-size (cache-line-size cache)) (mask (cache-mask cache))) (declare (index index)) (loop for depth from 0 upto (cache-limit cache) do (when (try-update-cache-line cache index layouts value) (note-cache-depth cache depth) (return-from try-update-cache t)) (setf index (next-cache-index mask index line-size))))) Constructs a new cache . (defun make-cache (&key (key-count (missing-arg)) (value (missing-arg)) (size 1)) (let* ((line-size (power-of-two-ceiling (+ key-count (if value 1 0)))) (adjusted-size (power-of-two-ceiling size)) (length (* adjusted-size line-size))) (if (<= length +cache-vector-max-length+) (%make-cache :key-count key-count :line-size line-size :vector (make-array length :initial-element '..empty..) :value value :mask (compute-cache-mask length line-size) :limit (compute-limit adjusted-size)) (make-cache :key-count key-count :value value :size (ceiling size 2))))) (defun copy-and-expand-cache (cache layouts value) (let ((copy (%copy-cache cache)) (length (length (cache-vector cache))) (drop-random-entries nil)) (declare (index length)) (when (< length +cache-vector-max-length+) (setf length (* 2 length))) (tagbody :again Blow way the old vector first , so a GC potentially triggered by (setf (cache-vector copy) #() (cache-vector copy) (make-array length :initial-element '..empty..) (cache-depth copy) 0 (cache-mask copy) (compute-cache-mask length (cache-line-size cache)) (cache-limit copy) (compute-limit (/ length (cache-line-size cache)))) First insert the new one -- if we do n't do this first and in FILL - CACHE . (unless (try-update-cache copy layouts value) (bug "Could not insert ~S:~S to supposedly empty ~S." layouts value copy)) (map-cache (if drop-random-entries do not fit in . Drop a random ~50 % of entries , doing real work . 50 % because if we drop too _ Experimentally _ 50 % seems to perform the (randomly-punting-lambda (layouts value) (try-update-cache copy layouts value)) (lambda (layouts value) (unless (try-update-cache copy layouts value) (if (< length +cache-vector-max-length+) (setf length (* 2 length)) (setf drop-random-entries t)) (go :again)))) cache)) copy)) (defun cache-has-invalid-entries-p (cache) (let ((vector (cache-vector cache)) (line-size (cache-line-size cache)) (key-count (cache-key-count cache)) (mask (cache-mask cache)) (index 0)) (loop (let ((key1 (svref vector index))) (when (cache-key-p key1) (if (zerop (layout-clos-hash key1)) First key invalid . (return-from cache-has-invalid-entries-p t) Line is in use and the first key is valid : check the rest . (loop for offset from 1 below key-count do (let ((thing (svref vector (+ index offset)))) (when (or (not (cache-key-p thing)) (zerop (layout-clos-hash thing))) (return-from cache-has-invalid-entries-p t))))))) (setf index (next-cache-index mask index line-size)) (when (zerop index) (return-from cache-has-invalid-entries-p nil))))) (defun hash-table-to-cache (table &key value key-count) (let ((cache (make-cache :key-count key-count :value value :size (hash-table-count table)))) (maphash (lambda (class value) (setq cache (fill-cache cache (class-wrapper class) value))) table) cache)) Inserts VALUE to by LAYOUTS . Expands the cache if (defun fill-cache (cache layouts value) (labels ((%fill-cache (cache layouts value expand) (cond ((try-update-cache cache layouts value) cache) ((and (not expand) (cache-has-invalid-entries-p cache)) (%fill-cache (copy-cache cache) layouts value t)) (t (copy-and-expand-cache cache layouts value))))) (if (listp layouts) (%fill-cache cache layouts value nil) (%fill-cache cache (list layouts) value nil)))) (defun map-cache (function cache) (let* ((vector (cache-vector cache)) (key-count (cache-key-count cache)) (valuep (cache-value cache)) (line-size (cache-line-size cache)) (mask (cache-mask cache)) (fun (if (functionp function) function (fdefinition function))) (index 0)) (tagbody :map (let ((layouts (loop for offset from 0 below key-count collect (non-empty-or (svref vector (+ offset index)) (go :next))))) (let ((value (when valuep (non-empty-or (svref vector (+ index key-count)) (go :next))))) (funcall fun layouts value))) :next (setf index (next-cache-index mask index line-size)) (unless (zerop index) (go :map)))) cache) (defun copy-cache (cache) (let* ((vector (cache-vector cache)) (copy (make-array (length vector) :initial-element '..empty..)) (line-size (cache-line-size cache)) (key-count (cache-key-count cache)) (valuep (cache-value cache)) (mask (cache-mask cache)) (size (/ (length vector) line-size)) (index 0) (depth 0)) (tagbody :copy (let ((layouts (loop for offset from 0 below key-count collect (non-empty-or (svref vector (+ index offset)) (go :next))))) (let ((primary (or (compute-cache-index cache layouts) (go :next)))) (when valuep (setf (svref copy (+ index key-count)) (non-empty-or (svref vector (+ index key-count)) (go :next)))) (loop for offset from 0 below key-count do (setf (svref copy (+ index offset)) (pop layouts))) (let ((distance (/ (- index primary) line-size))) (setf depth (max depth (if (minusp distance) (+ distance size) distance)))))) :next (setf index (next-cache-index mask index line-size)) (unless (zerop index) (go :copy))) (%make-cache :vector copy :depth depth :key-count (cache-key-count cache) :line-size line-size :value valuep :mask mask :limit (cache-limit cache)))) (defun map-all-caches (function) (dolist (p (list-all-packages)) (do-symbols (s p) (when (eq p (symbol-package s)) (dolist (name (list s `(setf ,s) (slot-reader-name s) (slot-writer-name s) (slot-boundp-name s))) (when (fboundp name) (let ((fun (fdefinition name))) (when (typep fun 'generic-function) (let ((cache (gf-dfun-cache fun))) (when cache (funcall function name cache))))))))))) (defun check-cache-consistency (cache) (let ((table (make-hash-table :test 'equal))) (map-cache (lambda (layouts value) (declare (ignore value)) (if (gethash layouts table) (cerror "Check futher." "Multiple appearances of ~S." layouts) (setf (gethash layouts table) t))) cache)))
33203f9cee64bc1bf79844749284a2ba7afacf1dde7c1157834d2d604dc7bd44
restyled-io/restyled.io
Job.hs
# LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # module Restyled.Widgets.Job ( jobCard , jobListItem , jobOutput , jobLogLine ) where import Restyled.Prelude hiding (Key) import Control.Monad.Logger.Aeson (LoggedMessage(..)) import Data.Aeson.Key (Key) import qualified Data.Aeson.Key as Key import Data.Aeson.KeyMap (KeyMap) import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Text as T import qualified Data.Vector as V import Formatting (format) import Formatting.Time (diff) import qualified Network.URI.Encode as URI import Restyled.Foundation import Restyled.Job.Completion import Restyled.Models hiding (jobLogLine) import Restyled.Routes import Restyled.Settings import Restyled.Widgets.ContainsURLs import Restyled.Yesod import Text.Julius (RawJS(..)) import Text.Shakespeare.Text (st) jobCard :: Entity Job -> Widget jobCard jobE@(Entity jobId job) = do now <- liftIO getCurrentTime issueUrl <- jobIssueURL jobE <$> getUrlRender $(widgetFile "widgets/job-card") jobListItem :: Entity Job -> Widget jobListItem (Entity jobId job) = do now <- liftIO getCurrentTime $(widgetFile "widgets/job-list-item") jobIssueURL :: Entity Job -> (Route App -> Text) -> Text jobIssueURL (Entity jobId Job {..}) urlRender = "-io/restyler/issues/new" <> "?title=" <> URI.encodeText title <> "&body=" <> URI.encodeText body where title = "Problem with Restyler Job #" <> toPathPiece jobId body = [st| Please use the below template to report an issue with this Job. **Don't submit sensitive information**, this is a public project. If you'd rather communicate privately, email . --- Hi there- I'm having a problem with a Restyled Job - **Restyled Job**: #{urlRender $ repoP jobOwner jobRepo $ jobR jobId} - **GitHub PR**: #{repoPullPath jobOwner jobRepo jobPullRequest} **What I expected to happen**: **What happened instead**: **Configuration** (if applicable): ```yaml # .restyled.yaml as it was in the commit for the Job ``` |] jobOutput :: Entity Job -> Widget jobOutput (Entity jobId job) = $(widgetFile "widgets/job-output") where streamElementId = "logs-job-id-" <> toPathPiece jobId jobLogLine :: JobLogLine -> Widget jobLogLine ln = $(widgetFile "widgets/log-line") where lm = jobLogLineContentJSON ln level = case loggedMessageLevel lm of LevelDebug -> "debug" LevelInfo -> "info" LevelWarn -> "warn" LevelError -> "error" LevelOther x -> x padTo :: Int -> Text -> Text padTo n t = t <> T.replicate pad " " where pad = max 0 $ n - T.length t renderKeyMap :: KeyMap Value -> Widget renderKeyMap = mconcat . map (uncurry pair) . KeyMap.toList where pair :: Key -> Value -> Widget pair k v = [whamlet|$newline never \ # <span .key-map-key>#{Key.toText k} = <span .key-map-value>#{plainValue v} |] plainValue :: Value -> Text plainValue = \case Object km -> mconcat [ "{" , T.intercalate "," $ map (\(k, v) -> Key.toText k <> ":" <> plainValue v) $ KeyMap.toList km , "}" ] Array vs -> mconcat ["[", T.intercalate "," $ map plainValue $ V.toList vs, "]"] String t -> pack $ show t -- encode escapes and quote Bool b -> if b then "true" else "false" Number n -> dropSuffix ".0" $ show n Null -> "null" dropSuffix :: Text -> Text -> Text dropSuffix suffix x = fromMaybe x $ T.stripSuffix suffix x
null
https://raw.githubusercontent.com/restyled-io/restyled.io/d1dae477a108c3d902030ff159424fbdd7b85d46/src/Restyled/Widgets/Job.hs
haskell
- encode escapes and quote
# LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # module Restyled.Widgets.Job ( jobCard , jobListItem , jobOutput , jobLogLine ) where import Restyled.Prelude hiding (Key) import Control.Monad.Logger.Aeson (LoggedMessage(..)) import Data.Aeson.Key (Key) import qualified Data.Aeson.Key as Key import Data.Aeson.KeyMap (KeyMap) import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Text as T import qualified Data.Vector as V import Formatting (format) import Formatting.Time (diff) import qualified Network.URI.Encode as URI import Restyled.Foundation import Restyled.Job.Completion import Restyled.Models hiding (jobLogLine) import Restyled.Routes import Restyled.Settings import Restyled.Widgets.ContainsURLs import Restyled.Yesod import Text.Julius (RawJS(..)) import Text.Shakespeare.Text (st) jobCard :: Entity Job -> Widget jobCard jobE@(Entity jobId job) = do now <- liftIO getCurrentTime issueUrl <- jobIssueURL jobE <$> getUrlRender $(widgetFile "widgets/job-card") jobListItem :: Entity Job -> Widget jobListItem (Entity jobId job) = do now <- liftIO getCurrentTime $(widgetFile "widgets/job-list-item") jobIssueURL :: Entity Job -> (Route App -> Text) -> Text jobIssueURL (Entity jobId Job {..}) urlRender = "-io/restyler/issues/new" <> "?title=" <> URI.encodeText title <> "&body=" <> URI.encodeText body where title = "Problem with Restyler Job #" <> toPathPiece jobId body = [st| Please use the below template to report an issue with this Job. **Don't submit sensitive information**, this is a public project. If you'd rather communicate privately, email . Hi there- I'm having a problem with a Restyled Job - **Restyled Job**: #{urlRender $ repoP jobOwner jobRepo $ jobR jobId} - **GitHub PR**: #{repoPullPath jobOwner jobRepo jobPullRequest} **What I expected to happen**: **What happened instead**: **Configuration** (if applicable): ```yaml # .restyled.yaml as it was in the commit for the Job ``` |] jobOutput :: Entity Job -> Widget jobOutput (Entity jobId job) = $(widgetFile "widgets/job-output") where streamElementId = "logs-job-id-" <> toPathPiece jobId jobLogLine :: JobLogLine -> Widget jobLogLine ln = $(widgetFile "widgets/log-line") where lm = jobLogLineContentJSON ln level = case loggedMessageLevel lm of LevelDebug -> "debug" LevelInfo -> "info" LevelWarn -> "warn" LevelError -> "error" LevelOther x -> x padTo :: Int -> Text -> Text padTo n t = t <> T.replicate pad " " where pad = max 0 $ n - T.length t renderKeyMap :: KeyMap Value -> Widget renderKeyMap = mconcat . map (uncurry pair) . KeyMap.toList where pair :: Key -> Value -> Widget pair k v = [whamlet|$newline never \ # <span .key-map-key>#{Key.toText k} = <span .key-map-value>#{plainValue v} |] plainValue :: Value -> Text plainValue = \case Object km -> mconcat [ "{" , T.intercalate "," $ map (\(k, v) -> Key.toText k <> ":" <> plainValue v) $ KeyMap.toList km , "}" ] Array vs -> mconcat ["[", T.intercalate "," $ map plainValue $ V.toList vs, "]"] Bool b -> if b then "true" else "false" Number n -> dropSuffix ".0" $ show n Null -> "null" dropSuffix :: Text -> Text -> Text dropSuffix suffix x = fromMaybe x $ T.stripSuffix suffix x
f13d72aee23fae7f169209e088896b7909d9f5401965b9222f9b47f73ad6cd22
tisnik/clojure-examples
project.clj
; ( C ) Copyright 2015 , 2020 , 2021 ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the Eclipse Public License v1.0 ; which accompanies this distribution, and is available at -v10.html ; ; Contributors: ; (defproject webapp6 "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.1"] [ring/ring-core "1.3.2"] [ring/ring-jetty-adapter "1.3.2"]] :plugins [[lein-codox "0.10.7"] [test2junit "1.1.0"] [ lein - test - out " 0.3.1 " ] [lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit "0.1.8"] [lein-clean-m2 "0.1.2"] [lein-project-edn "0.3.0"] [lein-marginalia "0.9.1"]] :project-edn {:output-file "doc/details.clj"} :main ^:skip-aot webapp6.core :target-path "target/%s" :profiles {:uberjar {:aot :all}})
null
https://raw.githubusercontent.com/tisnik/clojure-examples/d0879d8587e58d14dbdd4e2ae1a206eea95c96bf/webapp6/project.clj
clojure
All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at Contributors:
( C ) Copyright 2015 , 2020 , 2021 -v10.html (defproject webapp6 "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.1"] [ring/ring-core "1.3.2"] [ring/ring-jetty-adapter "1.3.2"]] :plugins [[lein-codox "0.10.7"] [test2junit "1.1.0"] [ lein - test - out " 0.3.1 " ] [lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit "0.1.8"] [lein-clean-m2 "0.1.2"] [lein-project-edn "0.3.0"] [lein-marginalia "0.9.1"]] :project-edn {:output-file "doc/details.clj"} :main ^:skip-aot webapp6.core :target-path "target/%s" :profiles {:uberjar {:aot :all}})
6e56794976ee41bc43a3f8f164f9787af77afc7933f8ca3d1018da947f7cb201
ublubu/shapes
Utils.hs
# LANGUAGE TemplateHaskell # {-# LANGUAGE RankNTypes #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE RecordWildCards # {- | A bunch of unrelated utility functions and types. -} module Utils.Utils where import GHC.Generics (Generic) import Control.DeepSeq import Control.Monad.Trans.Maybe import Control.Lens import Data.Maybe import Data.Tuple import qualified Data.IntMap.Strict as IM import qualified Data.Vector.Unboxed as V import Data.Vector.Unboxed.Deriving data SP a b = SP { _spFst :: !a , _spSnd :: !b } deriving (Show, Eq, Generic, NFData, Ord) makeLenses ''SP derivingUnbox "SP" [t| forall a b. (V.Unbox a, V.Unbox b) => SP a b -> (a, b) |] [| \SP{..} -> (_spFst, _spSnd) |] [| uncurry SP |] type SP' a = SP a a toSP :: (a, b) -> SP a b toSP (x, y) = SP x y # INLINE toSP # fromSP :: SP a b -> (a, b) fromSP (SP x y) = (x, y) # INLINE fromSP # spMap :: (a -> b) -> SP a a -> SP b b spMap f (SP x y) = SP (f x) (f y) # INLINE spMap # pairMap :: (a -> b) -> (a, a) -> (b, b) pairMap f (x, y) = (f x, f y) # INLINE pairMap # pairAp :: (a -> b, c -> d) -> (a, c) -> (b, d) pairAp (f, g) (x, y) = (f x, g y) # INLINE pairAp # pairFold :: Monoid m => (m, m) -> m pairFold (a, b) = mappend a b # INLINE pairFold # maybeChange :: a -> (a -> Maybe a) -> a maybeChange x f = fromMaybe x (f x) # INLINE maybeChange # toMaybe :: Bool -> a -> Maybe a toMaybe b x = if b then Just x else Nothing # INLINE toMaybe # eitherToMaybe :: Either a b -> Maybe b eitherToMaybe (Left _) = Nothing eitherToMaybe (Right x) = Just x # INLINE eitherToMaybe # maybeBranch :: (a -> a -> Bool) -> Maybe a -> Maybe a -> Maybe (Either a a) maybeBranch _ Nothing Nothing = Nothing maybeBranch _ Nothing (Just x) = Just $ Right x maybeBranch _ (Just x) Nothing = Just $ Left x maybeBranch useLeft (Just x) (Just y) = if useLeft x y then Just $ Left x else Just $ Right y # INLINE maybeBranch # maybeBranchBoth :: (a -> a -> Bool) -> Maybe a -> Maybe a -> Maybe (Either a a) maybeBranchBoth _ Nothing _ = Nothing maybeBranchBoth _ _ Nothing = Nothing maybeBranchBoth useLeft (Just x) (Just y) = if useLeft x y then Just $ Left x else Just $ Right y # INLINE maybeBranchBoth # takeIfAll :: (a -> Bool) -> [a] -> Maybe [a] takeIfAll _ [] = Just [] takeIfAll p (x:xs) | p x = fmap (x:) (takeIfAll p xs) | otherwise = Nothing # INLINE takeIfAll # cycles :: [a] -> [[a]] cycles xs = folds tail (cycle xs) xs # INLINE cycles # data Loop a = Loop { loopPrev :: Loop a , loopVal :: !a , loopNext :: Loop a } -- TODO: for debugging only instance (Show a, Eq a) => Show (Loop a) where show l = "loopify [" ++ f l [] ++ "]" where f x seen = if loopVal y `elem` seen' then show val else show val ++ ", " ++ f y seen' where y = loopNext x seen' = val:seen val = loopVal x loopify :: [a] -> Loop a loopify [] = error "can't have an empty loop" loopify v = let (first, lst) = f lst v first in first where f :: Loop a -> [a] -> Loop a -> (Loop a, Loop a) f prev [] next = (next, prev) f prev (x:xs) next = let (next', last') = f this xs next this = Loop prev x next' in (this, last') # INLINE loopify # takeNext :: Int -> Loop a -> [Loop a] takeNext = takeDir loopNext # INLINE takeNext # takePrev :: Int -> Loop a -> [Loop a] takePrev = takeDir loopPrev # INLINE takePrev # takeDir :: (Loop a -> Loop a) -> Int -> Loop a -> [Loop a] takeDir dir n x | n > 0 = x : takeDir dir (n - 1) (dir x) | n == 0 = [] | otherwise = error "cannot take fewer than 0" # INLINE takeDir # folds :: (b -> b) -> b -> [a] -> [b] folds _ _ [] = [] folds f a0 (_:xs) = a0 : folds f (f a0) xs # INLINE folds # data Flipping a = Same !a | Flip !a deriving Show flipToTuple :: Flipping a -> (Bool, a) flipToTuple (Same x) = (True, x) flipToTuple (Flip x) = (False, x) # INLINE flipToTuple # derivingUnbox "Flipping" [t| forall a. (V.Unbox a) => Flipping a -> (Bool, a) |] [| flipToTuple |] [| \(isSame, x) -> if isSame then Same x else Flip x |] TODO : write an iso for Flipping and Either flipAsEither :: Flipping a -> Either a a flipAsEither (Same x) = Left x flipAsEither (Flip x) = Right x # INLINE flipAsEither # flipWrap :: Flipping a -> b -> Flipping b flipWrap (Same _) = Same flipWrap (Flip _) = Flip # INLINE flipWrap # flipUnsafe :: (a -> (b, b) -> c) -> Flipping a -> (b, b) -> c flipUnsafe f (Same x) = f x flipUnsafe f (Flip x) = f x . swap # INLINE flipUnsafe # flipMap :: (a -> (b, b) -> c) -> Flipping a -> (b, b) -> Flipping c flipMap f x = flipWrap x . flipUnsafe f x # INLINE flipMap # flipExtractWith :: (a -> b, a -> b) -> Flipping a -> b flipExtractWith (f, _) (Same x) = f x flipExtractWith (_, f) (Flip x) = f x # INLINE flipExtractWith # flipExtractPair :: (a -> (b, b)) -> Flipping a -> (b, b) flipExtractPair f = flipExtractWith (f, swap . f) # INLINE flipExtractPair # flipJoin :: Flipping (Flipping a) -> Flipping a flipJoin (Same (Same x)) = Same x flipJoin (Flip (Same x)) = Flip x flipJoin (Same (Flip x)) = Flip x flipJoin (Flip (Flip x)) = Same x # INLINE flipJoin # instance Functor Flipping where fmap f (Same x) = Same (f x) fmap f (Flip x) = Flip (f x) # INLINE fmap # class Flippable f where flipp :: f -> f instance Flippable (x, x) where flipp = swap # INLINE flipp # instance Flippable (Flipping x) where flipp (Same x) = Flip x flipp (Flip x) = Same x # INLINE flipp # flipExtract :: (Flippable a) => Flipping a -> a flipExtract (Same x) = x flipExtract (Flip x) = flipp x # INLINE flipExtract # flipExtractUnsafe :: Flipping a -> a flipExtractUnsafe (Same x) = x flipExtractUnsafe (Flip x) = x # INLINE flipExtractUnsafe # flipInjectF :: Functor f => Flipping (f a) -> f (Flipping a) flipInjectF x = fmap (flipWrap x) . flipExtractUnsafe $ x # INLINE flipInjectF # | Combine two ' Either 's , using the provided function to choose between two ' Right 's . Always choose the first ' Left ' . Combine two 'Either's, using the provided function to choose between two 'Right's. Always choose the first 'Left'. -} eitherBranchBoth :: (b -> b -> Bool) -> Either a b -> Either a b -> Flipping (Either a b) eitherBranchBoth _ x@(Left _) _ = Same x eitherBranchBoth _ _ x@(Left _) = Flip x eitherBranchBoth useFirst x@(Right a) y@(Right b) = if useFirst a b then Same x else Flip y # INLINE eitherBranchBoth # liftRightMaybe :: Either a (Maybe b) -> Maybe (Either a b) liftRightMaybe (Right Nothing) = Nothing liftRightMaybe (Right (Just x)) = Just $ Right x liftRightMaybe (Left x) = Just $ Left x # INLINE liftRightMaybe # -- TODO: pull out the stuff that depends on lens. ixZipWith :: (Ixed s, TraversableWithIndex (Index s) t) => (a -> Maybe (IxValue s) -> b) -> t a -> s -> t b ixZipWith f xs ys = xs & itraversed %@~ g where g i x = f x (ys ^? ix i) # INLINE ixZipWith # overWith :: Lens' s a -> ((a, a) -> (a, a)) -> (s, s) -> (s, s) overWith l f (x, y) = (x & l .~ a, y & l .~ b) where (a, b) = f (x ^. l, y ^. l) # INLINE overWith # findOrInsert :: IM.Key -> a -> IM.IntMap a -> (Maybe a, IM.IntMap a) findOrInsert = IM.insertLookupWithKey (\_ _ a -> a) {-# INLINE findOrInsert #-} findOrInsert' :: IM.Key -> a -> IM.IntMap a -> (a, IM.IntMap a) findOrInsert' k x t = (fromMaybe x mx, t') where (mx, t') = findOrInsert k x t {-# INLINE findOrInsert' #-} posMod :: (Integral a) => a -> a -> a posMod x n = if res < 0 then res + n else res where res = x `mod` n # INLINE posMod #
null
https://raw.githubusercontent.com/ublubu/shapes/fa5d959c17224a851d517826deeae097f1583392/shapes/src/Utils/Utils.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE DeriveAnyClass # | A bunch of unrelated utility functions and types. TODO: for debugging only TODO: pull out the stuff that depends on lens. # INLINE findOrInsert # # INLINE findOrInsert' #
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE DeriveGeneric # # LANGUAGE RecordWildCards # module Utils.Utils where import GHC.Generics (Generic) import Control.DeepSeq import Control.Monad.Trans.Maybe import Control.Lens import Data.Maybe import Data.Tuple import qualified Data.IntMap.Strict as IM import qualified Data.Vector.Unboxed as V import Data.Vector.Unboxed.Deriving data SP a b = SP { _spFst :: !a , _spSnd :: !b } deriving (Show, Eq, Generic, NFData, Ord) makeLenses ''SP derivingUnbox "SP" [t| forall a b. (V.Unbox a, V.Unbox b) => SP a b -> (a, b) |] [| \SP{..} -> (_spFst, _spSnd) |] [| uncurry SP |] type SP' a = SP a a toSP :: (a, b) -> SP a b toSP (x, y) = SP x y # INLINE toSP # fromSP :: SP a b -> (a, b) fromSP (SP x y) = (x, y) # INLINE fromSP # spMap :: (a -> b) -> SP a a -> SP b b spMap f (SP x y) = SP (f x) (f y) # INLINE spMap # pairMap :: (a -> b) -> (a, a) -> (b, b) pairMap f (x, y) = (f x, f y) # INLINE pairMap # pairAp :: (a -> b, c -> d) -> (a, c) -> (b, d) pairAp (f, g) (x, y) = (f x, g y) # INLINE pairAp # pairFold :: Monoid m => (m, m) -> m pairFold (a, b) = mappend a b # INLINE pairFold # maybeChange :: a -> (a -> Maybe a) -> a maybeChange x f = fromMaybe x (f x) # INLINE maybeChange # toMaybe :: Bool -> a -> Maybe a toMaybe b x = if b then Just x else Nothing # INLINE toMaybe # eitherToMaybe :: Either a b -> Maybe b eitherToMaybe (Left _) = Nothing eitherToMaybe (Right x) = Just x # INLINE eitherToMaybe # maybeBranch :: (a -> a -> Bool) -> Maybe a -> Maybe a -> Maybe (Either a a) maybeBranch _ Nothing Nothing = Nothing maybeBranch _ Nothing (Just x) = Just $ Right x maybeBranch _ (Just x) Nothing = Just $ Left x maybeBranch useLeft (Just x) (Just y) = if useLeft x y then Just $ Left x else Just $ Right y # INLINE maybeBranch # maybeBranchBoth :: (a -> a -> Bool) -> Maybe a -> Maybe a -> Maybe (Either a a) maybeBranchBoth _ Nothing _ = Nothing maybeBranchBoth _ _ Nothing = Nothing maybeBranchBoth useLeft (Just x) (Just y) = if useLeft x y then Just $ Left x else Just $ Right y # INLINE maybeBranchBoth # takeIfAll :: (a -> Bool) -> [a] -> Maybe [a] takeIfAll _ [] = Just [] takeIfAll p (x:xs) | p x = fmap (x:) (takeIfAll p xs) | otherwise = Nothing # INLINE takeIfAll # cycles :: [a] -> [[a]] cycles xs = folds tail (cycle xs) xs # INLINE cycles # data Loop a = Loop { loopPrev :: Loop a , loopVal :: !a , loopNext :: Loop a } instance (Show a, Eq a) => Show (Loop a) where show l = "loopify [" ++ f l [] ++ "]" where f x seen = if loopVal y `elem` seen' then show val else show val ++ ", " ++ f y seen' where y = loopNext x seen' = val:seen val = loopVal x loopify :: [a] -> Loop a loopify [] = error "can't have an empty loop" loopify v = let (first, lst) = f lst v first in first where f :: Loop a -> [a] -> Loop a -> (Loop a, Loop a) f prev [] next = (next, prev) f prev (x:xs) next = let (next', last') = f this xs next this = Loop prev x next' in (this, last') # INLINE loopify # takeNext :: Int -> Loop a -> [Loop a] takeNext = takeDir loopNext # INLINE takeNext # takePrev :: Int -> Loop a -> [Loop a] takePrev = takeDir loopPrev # INLINE takePrev # takeDir :: (Loop a -> Loop a) -> Int -> Loop a -> [Loop a] takeDir dir n x | n > 0 = x : takeDir dir (n - 1) (dir x) | n == 0 = [] | otherwise = error "cannot take fewer than 0" # INLINE takeDir # folds :: (b -> b) -> b -> [a] -> [b] folds _ _ [] = [] folds f a0 (_:xs) = a0 : folds f (f a0) xs # INLINE folds # data Flipping a = Same !a | Flip !a deriving Show flipToTuple :: Flipping a -> (Bool, a) flipToTuple (Same x) = (True, x) flipToTuple (Flip x) = (False, x) # INLINE flipToTuple # derivingUnbox "Flipping" [t| forall a. (V.Unbox a) => Flipping a -> (Bool, a) |] [| flipToTuple |] [| \(isSame, x) -> if isSame then Same x else Flip x |] TODO : write an iso for Flipping and Either flipAsEither :: Flipping a -> Either a a flipAsEither (Same x) = Left x flipAsEither (Flip x) = Right x # INLINE flipAsEither # flipWrap :: Flipping a -> b -> Flipping b flipWrap (Same _) = Same flipWrap (Flip _) = Flip # INLINE flipWrap # flipUnsafe :: (a -> (b, b) -> c) -> Flipping a -> (b, b) -> c flipUnsafe f (Same x) = f x flipUnsafe f (Flip x) = f x . swap # INLINE flipUnsafe # flipMap :: (a -> (b, b) -> c) -> Flipping a -> (b, b) -> Flipping c flipMap f x = flipWrap x . flipUnsafe f x # INLINE flipMap # flipExtractWith :: (a -> b, a -> b) -> Flipping a -> b flipExtractWith (f, _) (Same x) = f x flipExtractWith (_, f) (Flip x) = f x # INLINE flipExtractWith # flipExtractPair :: (a -> (b, b)) -> Flipping a -> (b, b) flipExtractPair f = flipExtractWith (f, swap . f) # INLINE flipExtractPair # flipJoin :: Flipping (Flipping a) -> Flipping a flipJoin (Same (Same x)) = Same x flipJoin (Flip (Same x)) = Flip x flipJoin (Same (Flip x)) = Flip x flipJoin (Flip (Flip x)) = Same x # INLINE flipJoin # instance Functor Flipping where fmap f (Same x) = Same (f x) fmap f (Flip x) = Flip (f x) # INLINE fmap # class Flippable f where flipp :: f -> f instance Flippable (x, x) where flipp = swap # INLINE flipp # instance Flippable (Flipping x) where flipp (Same x) = Flip x flipp (Flip x) = Same x # INLINE flipp # flipExtract :: (Flippable a) => Flipping a -> a flipExtract (Same x) = x flipExtract (Flip x) = flipp x # INLINE flipExtract # flipExtractUnsafe :: Flipping a -> a flipExtractUnsafe (Same x) = x flipExtractUnsafe (Flip x) = x # INLINE flipExtractUnsafe # flipInjectF :: Functor f => Flipping (f a) -> f (Flipping a) flipInjectF x = fmap (flipWrap x) . flipExtractUnsafe $ x # INLINE flipInjectF # | Combine two ' Either 's , using the provided function to choose between two ' Right 's . Always choose the first ' Left ' . Combine two 'Either's, using the provided function to choose between two 'Right's. Always choose the first 'Left'. -} eitherBranchBoth :: (b -> b -> Bool) -> Either a b -> Either a b -> Flipping (Either a b) eitherBranchBoth _ x@(Left _) _ = Same x eitherBranchBoth _ _ x@(Left _) = Flip x eitherBranchBoth useFirst x@(Right a) y@(Right b) = if useFirst a b then Same x else Flip y # INLINE eitherBranchBoth # liftRightMaybe :: Either a (Maybe b) -> Maybe (Either a b) liftRightMaybe (Right Nothing) = Nothing liftRightMaybe (Right (Just x)) = Just $ Right x liftRightMaybe (Left x) = Just $ Left x # INLINE liftRightMaybe # ixZipWith :: (Ixed s, TraversableWithIndex (Index s) t) => (a -> Maybe (IxValue s) -> b) -> t a -> s -> t b ixZipWith f xs ys = xs & itraversed %@~ g where g i x = f x (ys ^? ix i) # INLINE ixZipWith # overWith :: Lens' s a -> ((a, a) -> (a, a)) -> (s, s) -> (s, s) overWith l f (x, y) = (x & l .~ a, y & l .~ b) where (a, b) = f (x ^. l, y ^. l) # INLINE overWith # findOrInsert :: IM.Key -> a -> IM.IntMap a -> (Maybe a, IM.IntMap a) findOrInsert = IM.insertLookupWithKey (\_ _ a -> a) findOrInsert' :: IM.Key -> a -> IM.IntMap a -> (a, IM.IntMap a) findOrInsert' k x t = (fromMaybe x mx, t') where (mx, t') = findOrInsert k x t posMod :: (Integral a) => a -> a -> a posMod x n = if res < 0 then res + n else res where res = x `mod` n # INLINE posMod #
2fef1d58c8357414f5fd7e9cf1f725c94095d27846e16c52a1f27f13e817170f
aenglisc/the_f
prop_f.erl
-module(prop_f). -include_lib("proper/include/proper.hrl"). -include_lib("stdlib/include/assert.hrl"). prop_identity() -> ?FORALL(T, term(), T =:= f:id(T)). prop_curry() -> ?FORALL( {Arity, ReturnType}, {arity(20), term()}, gen_curried_function(Arity, ReturnType) ). prop_is_curried() -> ?FORALL( {Arity, ReturnType}, {arity(20), term()}, is_curried_assertions(Arity, ReturnType) ). prop_ok() -> ?FORALL(T, term(), {ok, T} =:= f:ok(T)). prop_err() -> ?FORALL(T, term(), {error, T} =:= f:err(T)). prop_unwrap() -> ?FORALL(T, f:result(), unwrap_assertions(T)). %%==================================================================== Internal functions %%==================================================================== arity(Limit) -> ?SUCHTHAT(Arity, pos_integer(), Arity =< Limit). gen_curried_function(Arity, ReturnType) -> ?FORALL( F, curried_function(Arity, ReturnType), curry_assertions(F, Arity, ReturnType) ). curried_function(Arity, ReturnType) -> ?LET(F, function(Arity, ReturnType), f:curry(F)). curry_assertions(F, 1 = Arity, ReturnType) -> ReturnType =:= f:partial(F, lists:seq(1, Arity)) andalso is_function(F, 1) andalso f:is_curried(F); curry_assertions(F, Arity, ReturnType) -> ReturnType =:= f:partial(F, lists:seq(1, Arity)) andalso is_function(f:partial(F, lists:seq(1, Arity - 1)), 1) andalso is_function(F, 1) andalso f:is_curried(F). is_curried_assertions(Arity, ReturnType) -> ?FORALL(F, function(Arity, ReturnType), f:is_curried(f:curry(F))). unwrap_assertions({ok, T} = R) -> T =:= f:unwrap(R); unwrap_assertions({error, E} = R) -> ok =:= ?assertThrow(E, f:unwrap(R)).
null
https://raw.githubusercontent.com/aenglisc/the_f/191baf870ad1841c1c35b01bae8db6cce47c81c5/test/prop_f.erl
erlang
==================================================================== ====================================================================
-module(prop_f). -include_lib("proper/include/proper.hrl"). -include_lib("stdlib/include/assert.hrl"). prop_identity() -> ?FORALL(T, term(), T =:= f:id(T)). prop_curry() -> ?FORALL( {Arity, ReturnType}, {arity(20), term()}, gen_curried_function(Arity, ReturnType) ). prop_is_curried() -> ?FORALL( {Arity, ReturnType}, {arity(20), term()}, is_curried_assertions(Arity, ReturnType) ). prop_ok() -> ?FORALL(T, term(), {ok, T} =:= f:ok(T)). prop_err() -> ?FORALL(T, term(), {error, T} =:= f:err(T)). prop_unwrap() -> ?FORALL(T, f:result(), unwrap_assertions(T)). Internal functions arity(Limit) -> ?SUCHTHAT(Arity, pos_integer(), Arity =< Limit). gen_curried_function(Arity, ReturnType) -> ?FORALL( F, curried_function(Arity, ReturnType), curry_assertions(F, Arity, ReturnType) ). curried_function(Arity, ReturnType) -> ?LET(F, function(Arity, ReturnType), f:curry(F)). curry_assertions(F, 1 = Arity, ReturnType) -> ReturnType =:= f:partial(F, lists:seq(1, Arity)) andalso is_function(F, 1) andalso f:is_curried(F); curry_assertions(F, Arity, ReturnType) -> ReturnType =:= f:partial(F, lists:seq(1, Arity)) andalso is_function(f:partial(F, lists:seq(1, Arity - 1)), 1) andalso is_function(F, 1) andalso f:is_curried(F). is_curried_assertions(Arity, ReturnType) -> ?FORALL(F, function(Arity, ReturnType), f:is_curried(f:curry(F))). unwrap_assertions({ok, T} = R) -> T =:= f:unwrap(R); unwrap_assertions({error, E} = R) -> ok =:= ?assertThrow(E, f:unwrap(R)).
8a087b10ad7d011d54f68f4e65c994b528d4c9a58d1b6e143a0ca7906b0ae0c1
facebook/pyre-check
worker.mli
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) (*****************************************************************************) Module building workers . * A worker is a subprocess executing an arbitrary function . * You should first create a fixed amount of workers and then use those * because the amount of workers is limited and to make the load - balancing * of tasks better ( cf multiWorker.ml ) . * A worker is a subprocess executing an arbitrary function. * You should first create a fixed amount of workers and then use those * because the amount of workers is limited and to make the load-balancing * of tasks better (cf multiWorker.ml). *) (*****************************************************************************) exception Worker_exited_abnormally of int * Unix.process_status (** Worker exited with the given exception, as a string (because marshal-ing on * exceptions is not safe). *) exception Worker_exception of string * Printexc.raw_backtrace * Worker killed by Out Of Memory . exception Worker_oomed (** Raise this exception when sending work to a worker that is already busy. * We should never be doing that, and this is an assertion error. *) exception Worker_busy (** Raise this exception when sending work to a worker that is already killed. * We should never be doing that, and this is an assertion error. *) exception Worker_killed type send_job_failure = | Worker_already_exited of Unix.process_status | Other_send_job_failure of exn exception Worker_failed_to_send_job of send_job_failure (* The type of a worker visible to the outside world *) type t (*****************************************************************************) (* The handle is what we get back when we start a job. It's a "future" * (sometimes called a "promise"). The scheduler uses the handle to retrieve * the result of the job when the task is done (cf multiWorker.ml). *) (*****************************************************************************) type 'a handle type 'a entry val register_entry_point: restore:('a -> unit) -> 'a entry (** Creates a pool of workers. *) val make: saved_state : 'a -> entry : 'a entry -> nbr_procs : int -> gc_control : Gc.control -> heap_handle : SharedMemory.handle -> t list Call in a sub - process ( CAREFUL , GLOBALS ARE COPIED ) val call: t -> ('a -> 'b) -> 'a -> 'b handle (* Retrieves the result (once the worker is done) hangs otherwise *) val get_result: 'a handle -> 'a (* Selects among multiple handles those which are ready. *) type 'a selected = { readys: 'a handle list; waiters: 'a handle list; } val select: 'a handle list -> 'a selected (* Returns the worker which produces this handle *) val get_worker: 'a handle -> t (* Kill a worker *) val kill: t -> unit (* Return the id of the worker to which the current process belong. 0 means the master process *) val current_worker_id: unit -> int val exception_backtrace: exn -> Printexc.raw_backtrace
null
https://raw.githubusercontent.com/facebook/pyre-check/254c63580d44c0a547b362b2035fbb82803742c5/source/hack_parallel/hack_parallel/procs/worker.mli
ocaml
*************************************************************************** *************************************************************************** * Worker exited with the given exception, as a string (because marshal-ing on * exceptions is not safe). * Raise this exception when sending work to a worker that is already busy. * We should never be doing that, and this is an assertion error. * Raise this exception when sending work to a worker that is already killed. * We should never be doing that, and this is an assertion error. The type of a worker visible to the outside world *************************************************************************** The handle is what we get back when we start a job. It's a "future" * (sometimes called a "promise"). The scheduler uses the handle to retrieve * the result of the job when the task is done (cf multiWorker.ml). *************************************************************************** * Creates a pool of workers. Retrieves the result (once the worker is done) hangs otherwise Selects among multiple handles those which are ready. Returns the worker which produces this handle Kill a worker Return the id of the worker to which the current process belong. 0 means the master process
* 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. *) Module building workers . * A worker is a subprocess executing an arbitrary function . * You should first create a fixed amount of workers and then use those * because the amount of workers is limited and to make the load - balancing * of tasks better ( cf multiWorker.ml ) . * A worker is a subprocess executing an arbitrary function. * You should first create a fixed amount of workers and then use those * because the amount of workers is limited and to make the load-balancing * of tasks better (cf multiWorker.ml). *) exception Worker_exited_abnormally of int * Unix.process_status exception Worker_exception of string * Printexc.raw_backtrace * Worker killed by Out Of Memory . exception Worker_oomed exception Worker_busy exception Worker_killed type send_job_failure = | Worker_already_exited of Unix.process_status | Other_send_job_failure of exn exception Worker_failed_to_send_job of send_job_failure type t type 'a handle type 'a entry val register_entry_point: restore:('a -> unit) -> 'a entry val make: saved_state : 'a -> entry : 'a entry -> nbr_procs : int -> gc_control : Gc.control -> heap_handle : SharedMemory.handle -> t list Call in a sub - process ( CAREFUL , GLOBALS ARE COPIED ) val call: t -> ('a -> 'b) -> 'a -> 'b handle val get_result: 'a handle -> 'a type 'a selected = { readys: 'a handle list; waiters: 'a handle list; } val select: 'a handle list -> 'a selected val get_worker: 'a handle -> t val kill: t -> unit val current_worker_id: unit -> int val exception_backtrace: exn -> Printexc.raw_backtrace
22dec5198e4eb5b65d71aef6ef087a3d5bcbf4dad08b8eeb0946f3b6a12d230b
IvanRublev/year_progress_bot
telegram.erl
-module(telegram). -export([send_message/2, register_webhook/0]). -compile([{parse_transform, lager_transform}]). send_message(ChatId, ProgressDate) -> case application:get_env(year_progress_bot, tel_integrate) of {ok, true} -> send_message_fun(ChatId, ProgressDate); _ -> ok end. send_message_fun(ChatId, ProgressDate) -> {ok, Host} = application:get_env(year_progress_bot, tel_host), {ok, Conn} = shotgun:open(Host, 443, https), {ok, Token} = application:get_env(year_progress_bot, tel_token), Path = "/bot" ++ Token ++ "/sendMessage", Headers = #{<<"content-type">> => <<"application/json">>}, Msg = formatter:year_progress_bar(ProgressDate), Payload = jiffy:encode({[{chat_id, ChatId}, {text, Msg}]}), {ok, Response} = shotgun:post(Conn, Path, Headers, Payload, #{}), ok = shotgun:close(Conn), #{status_code := Status, body := Body} = Response, if (Status >= 200) and (Status =< 299) -> RespDoc = jiffy:decode(Body, [return_maps]), case maps:get(<<"ok">>, RespDoc) of true -> ok; false -> {error, internal, Body} end; true -> {error, Status, Body} end. register_webhook() -> case application:get_env(year_progress_bot, tel_integrate) of {ok, true} -> register_webhook_fun(); _ -> ok end. register_webhook_fun() -> {ok, Host} = application:get_env(year_progress_bot, tel_host), {ok, Conn} = shotgun:open(Host, 443, https), {ok, SelfHost} = application:get_env(year_progress_bot, host), {ok, HookPath} = application:get_env(year_progress_bot, webhook_path), {ok, Token} = application:get_env(year_progress_bot, tel_token), HookUrl = "https://" ++ SelfHost ++ HookPath, Path = "/bot" ++ Token ++ "/setWebhook?" ++ "url=" ++ url_encode(HookUrl) ++ "&allowed_updates=" ++ url_encode("[\"message\",\"channel_post\"]"), {ok, Response} = shotgun:get(Conn, Path), lager:info("Registered Webhook with status: ~p and body: ~s...", formatter:gun_response_printable(Response)), ok = shotgun:close(Conn). url_encode(Str) -> uri_string:compose_query([{Str, true}]).
null
https://raw.githubusercontent.com/IvanRublev/year_progress_bot/c3e85a5598d768933d5fb676c74d92fa8033cf60/apps/year_progress_bot/src/telegram.erl
erlang
-module(telegram). -export([send_message/2, register_webhook/0]). -compile([{parse_transform, lager_transform}]). send_message(ChatId, ProgressDate) -> case application:get_env(year_progress_bot, tel_integrate) of {ok, true} -> send_message_fun(ChatId, ProgressDate); _ -> ok end. send_message_fun(ChatId, ProgressDate) -> {ok, Host} = application:get_env(year_progress_bot, tel_host), {ok, Conn} = shotgun:open(Host, 443, https), {ok, Token} = application:get_env(year_progress_bot, tel_token), Path = "/bot" ++ Token ++ "/sendMessage", Headers = #{<<"content-type">> => <<"application/json">>}, Msg = formatter:year_progress_bar(ProgressDate), Payload = jiffy:encode({[{chat_id, ChatId}, {text, Msg}]}), {ok, Response} = shotgun:post(Conn, Path, Headers, Payload, #{}), ok = shotgun:close(Conn), #{status_code := Status, body := Body} = Response, if (Status >= 200) and (Status =< 299) -> RespDoc = jiffy:decode(Body, [return_maps]), case maps:get(<<"ok">>, RespDoc) of true -> ok; false -> {error, internal, Body} end; true -> {error, Status, Body} end. register_webhook() -> case application:get_env(year_progress_bot, tel_integrate) of {ok, true} -> register_webhook_fun(); _ -> ok end. register_webhook_fun() -> {ok, Host} = application:get_env(year_progress_bot, tel_host), {ok, Conn} = shotgun:open(Host, 443, https), {ok, SelfHost} = application:get_env(year_progress_bot, host), {ok, HookPath} = application:get_env(year_progress_bot, webhook_path), {ok, Token} = application:get_env(year_progress_bot, tel_token), HookUrl = "https://" ++ SelfHost ++ HookPath, Path = "/bot" ++ Token ++ "/setWebhook?" ++ "url=" ++ url_encode(HookUrl) ++ "&allowed_updates=" ++ url_encode("[\"message\",\"channel_post\"]"), {ok, Response} = shotgun:get(Conn, Path), lager:info("Registered Webhook with status: ~p and body: ~s...", formatter:gun_response_printable(Response)), ok = shotgun:close(Conn). url_encode(Str) -> uri_string:compose_query([{Str, true}]).
c81d91066075ee2f1cf56d8f7837090018a9d2f2c4b15f6507a9faf208ba46e6
caradoc-org/caradoc
type.mli
(*****************************************************************************) (* Caradoc: a PDF parser and validator *) Copyright ( C ) 2015 ANSSI Copyright ( C ) 2015 - 2017 (* *) (* This program is free software; you can redistribute it and/or modify *) it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . (* *) (* 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 . (*****************************************************************************) open Mapkey open Key open Boundedint open Errors module Type : sig type 'a kind = (* TODO : remove Any, that accepts any type *) | Any and class | Alias of string | Class of string | Stream of string (* Basic PDF types *) | Null | Bool | Int | Real | String | Name (* Types based on string *) | Text | Date (* Bool exactly equal to *) | BoolExact of bool Integer within a range | IntRange of (BoundedInt.t option) * (BoundedInt.t option) (* Integer exactly equal to *) | IntExact of BoundedInt.t Integer in a set | IntIn of BoundedInt.t array (* Name exactly equal to *) | NameExact of string (* Name in a set *) | NameIn of (string, unit) Hashtbl.t (* Homogeneous array *) | Array of 'a Array or element ( equivalent to array of length 1 ) | ArrayOrOne of 'a (* Homogeneous array of fixed length *) | ArraySized of 'a * int (* Homogeneous array whose length is in a set *) | ArrayVariantSized of 'a * (int array) (* Array that contains an array of tuples *) | ArrayTuples of 'a array (* Array of differences *) | ArrayDifferences (* Array that contains a tuple *) | Tuple of 'a array (* Variant of types *) | Variant of 'a kind list (* Dictionary with values of a type *) | Dictionary of 'a type t = { (* Actual type *) kind : t kind; (* Allow indirect reference *) allow_ind : bool; } type kind_t = t kind (* Class entry *) type entry_t = { (* Type of entry *) typ : t; (* Entry is optional *) optional : bool; } (* A class is a set of keys associated to value types *) (* The bool parameter is for strictness *) type class_t = ((string, entry_t) Hashtbl.t) * (string list) * bool (* A pool associates names to classes and aliases *) type pool_t = ((string, class_t) Hashtbl.t) * ((string, kind_t) Hashtbl.t) type context = { (* Definitions of aliases and classes *) mutable pool : pool_t; (* Types of objects *) mutable types : kind_t MapKey.t; (* Queue of objects to traverse *) mutable to_check : (Key.t * Errors.error_ctxt) list; (* Incomplete types were encountered *) mutable incomplete : bool; } (* Convert a type to a string Args : - actual type Returns : - string representation *) val kind_to_string : kind_t -> string (* Convert a type to a string Args : - type Returns : - string representation *) val type_to_string : t -> string (* Print a pool of classes and aliases Args : - pool *) val print_pool : pool_t -> unit (* Check that classes and aliases used in a type are declared in a pool Args : - pool - string representation of the type - type to check *) val check_pool_type : pool_t -> string -> kind_t -> unit (* Check that all classes and aliases used in a pool are declared Args : - pool *) val check_pool : pool_t -> unit (* Create an empty context Returns : - a new context *) val create_context : unit -> context Copy a context : - context Returns : - copy of context Args : - context Returns : - copy of context *) val copy_context : context -> context (* Assign a context to another Args : - destination - source *) val assign_context : context -> context -> unit (* Register a class in a pool Args : - class requires strict checking - pool - name of the class - classes included by the class - members of the class *) val register_class : ?strict:bool -> pool_t -> string -> ?includes:(string list) -> (string * entry_t) list -> unit (* Register an alias in a pool Args : - pool - name of the alias - actual type *) val register_alias : pool_t -> string -> kind_t -> unit (* Remove (recursively) the top-level alias of a type Args : - pool of classes and aliases - type Returns : - type that is not an alias *) val remove_alias : pool_t -> kind_t -> kind_t (* Get a sorted list of all variant types contained in a type Args : - pool of classes and aliases - type Returns : - actual type *) val remove_variant : pool_t -> kind_t -> kind_t list Compute the intersection of two types Args : - pool of classes and aliases - type 1 - type 2 - error context Returns : - intersection of the two types , without alias Args : - pool of classes and aliases - type 1 - type 2 - error context Returns : - intersection of the two types, without alias *) val type_intersection : pool_t -> kind_t -> kind_t -> Errors.error_ctxt -> kind_t end
null
https://raw.githubusercontent.com/caradoc-org/caradoc/100f53bc55ef682049e10fabf24869bc019dc6ce/src/type/type.mli
ocaml
*************************************************************************** Caradoc: a PDF parser and validator This program is free software; you can redistribute it and/or modify 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. *************************************************************************** TODO : remove Any, that accepts any type Basic PDF types Types based on string Bool exactly equal to Integer exactly equal to Name exactly equal to Name in a set Homogeneous array Homogeneous array of fixed length Homogeneous array whose length is in a set Array that contains an array of tuples Array of differences Array that contains a tuple Variant of types Dictionary with values of a type Actual type Allow indirect reference Class entry Type of entry Entry is optional A class is a set of keys associated to value types The bool parameter is for strictness A pool associates names to classes and aliases Definitions of aliases and classes Types of objects Queue of objects to traverse Incomplete types were encountered Convert a type to a string Args : - actual type Returns : - string representation Convert a type to a string Args : - type Returns : - string representation Print a pool of classes and aliases Args : - pool Check that classes and aliases used in a type are declared in a pool Args : - pool - string representation of the type - type to check Check that all classes and aliases used in a pool are declared Args : - pool Create an empty context Returns : - a new context Assign a context to another Args : - destination - source Register a class in a pool Args : - class requires strict checking - pool - name of the class - classes included by the class - members of the class Register an alias in a pool Args : - pool - name of the alias - actual type Remove (recursively) the top-level alias of a type Args : - pool of classes and aliases - type Returns : - type that is not an alias Get a sorted list of all variant types contained in a type Args : - pool of classes and aliases - type Returns : - actual type
Copyright ( C ) 2015 ANSSI Copyright ( C ) 2015 - 2017 it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . 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 . open Mapkey open Key open Boundedint open Errors module Type : sig type 'a kind = | Any and class | Alias of string | Class of string | Stream of string | Null | Bool | Int | Real | String | Name | Text | Date | BoolExact of bool Integer within a range | IntRange of (BoundedInt.t option) * (BoundedInt.t option) | IntExact of BoundedInt.t Integer in a set | IntIn of BoundedInt.t array | NameExact of string | NameIn of (string, unit) Hashtbl.t | Array of 'a Array or element ( equivalent to array of length 1 ) | ArrayOrOne of 'a | ArraySized of 'a * int | ArrayVariantSized of 'a * (int array) | ArrayTuples of 'a array | ArrayDifferences | Tuple of 'a array | Variant of 'a kind list | Dictionary of 'a type t = { kind : t kind; allow_ind : bool; } type kind_t = t kind type entry_t = { typ : t; optional : bool; } type class_t = ((string, entry_t) Hashtbl.t) * (string list) * bool type pool_t = ((string, class_t) Hashtbl.t) * ((string, kind_t) Hashtbl.t) type context = { mutable pool : pool_t; mutable types : kind_t MapKey.t; mutable to_check : (Key.t * Errors.error_ctxt) list; mutable incomplete : bool; } val kind_to_string : kind_t -> string val type_to_string : t -> string val print_pool : pool_t -> unit val check_pool_type : pool_t -> string -> kind_t -> unit val check_pool : pool_t -> unit val create_context : unit -> context Copy a context : - context Returns : - copy of context Args : - context Returns : - copy of context *) val copy_context : context -> context val assign_context : context -> context -> unit val register_class : ?strict:bool -> pool_t -> string -> ?includes:(string list) -> (string * entry_t) list -> unit val register_alias : pool_t -> string -> kind_t -> unit val remove_alias : pool_t -> kind_t -> kind_t val remove_variant : pool_t -> kind_t -> kind_t list Compute the intersection of two types Args : - pool of classes and aliases - type 1 - type 2 - error context Returns : - intersection of the two types , without alias Args : - pool of classes and aliases - type 1 - type 2 - error context Returns : - intersection of the two types, without alias *) val type_intersection : pool_t -> kind_t -> kind_t -> Errors.error_ctxt -> kind_t end
5b11bde8f9a6858e4db793253192eadc8efa9022b010c610b4232cf8b7a2d333
fantasytree/fancy_game_server
dev.erl
%%---------------------------------------------------- 开发工具 %%---------------------------------------------------- -module(dev). -export([ info/0 ,mq_info/2 ,mq_info/3 ,mq_info_top/2 ,top/0 ,top/1 ,top/3 ,eprof_start/0 ,eprof_start/2 ,eprof_stop/0 ,m/0 ,m/1 ,u/0 ,u/1 ,u/2 ,u_db/1 ,edoc/0 ,get_all_erl/0 ,file_list/2 ] ). -include_lib("kernel/include/file.hrl"). -include("common.hrl"). %% @doc 查看系统当前的综合信息 -spec info() -> ok. info() -> SchedId = erlang:system_info(scheduler_id), SchedNum = erlang:system_info(schedulers), ProcCount = erlang:system_info(process_count), ProcLimit = erlang:system_info(process_limit), ProcMemUsed = erlang:memory(processes_used), ProcMemAlloc = erlang:memory(processes), MemTot = erlang:memory(total), OnlineNum = ets:info(ets_role_login, size), RoleNum = dets:info(role_data, size), {MaxFDsize,_}= string:to_integer(os:cmd("ulimit -n")), FDsize = length(string:tokens(os:cmd("lsof -d \"0-9999999\" -lna -Ff -p " ++ os:getpid()), "\n")), {CoreSize,_} = string:to_integer(os:cmd("ulimit -c")), DistBufBusyLimit = erlang:system_info(dist_buf_busy_limit), util:cn( " 当前节点名: ~p~n" " Scheduler id: ~p~n" " Num scheduler: ~p~n" " Memory used by erlang processes: ~p~n" " Memory allocated by erlang processes: ~p~n" " The total amount of memory allocated: ~p~n" " 可创建进程数量上限: ~p~n" " 当前节点进程数: ~p~n" " 本节点在线玩家数: ~p~n" " 本节点玩家总数: ~p~n" " 本节点文件描述符上限: ~p~n" " 本节点当前打开PORT数: ~p~n" " 本节点CoreDump文件大小上限: ~p~n" " 本节点RPC通道缓存: ~p Bytes~n" , [node(), SchedId, SchedNum, ProcMemUsed, ProcMemAlloc, MemTot, ProcLimit, ProcCount, OnlineNum, RoleNum, MaxFDsize, FDsize, CoreSize, DistBufBusyLimit]), ok. %% @doc 返回当前及诶单的占用资源最多的列表信息 -spec top() -> ProcList::list(). top() -> ?INFO("显示占用内存最多的10个进程:~n"), top(mem), ?INFO("显示消息队列最多的10个进程:~n"), top(queue), ?INFO("显示CPU占用最多的10个进程:~n"), top(reds), ?INFO("显示bin使用最多的10个进程:~n"), top(bin). @doc 返回当前节点中占用资源最多的N个进程列表 . %% Type = mem | queue | reds -spec top(Type::atom()) -> ProcList::list(). %% Type: 排名类型 %% <ul> %% <li>{@type mem} 返回当前节点中内存占用前N的进程</li> %% <li>{@type queue} 返回当前节点中消息队列长度前N的进程</li> < li>{@type reds } 返回当前节点中reductions值前N的进程</li > %% </ul> top(mem) -> top(mem, 1, 10); top(queue) -> top(queue, 1, 10); top(reds) -> top(reds, 1, 10); top(bin) -> top(bin, 1, 10). @doc 返回当前节点中占用资源最多的N个进程列表 . ProcList = list ( ) -spec top(Type::atom(), Start::integer(), Len::integer()) -> ProcList::list(). top(Type, Start, Len) -> TopType = if Type =:= mem -> memory; Type =:= queue -> message_queue_len; Type =:= reds -> reductions; Type =:= bin -> binary; true -> undefined end, L = do_top(TopType, Start, Len), util:cn( "~10s ~24s ~30s ~30s ~12s ~12s ~10s ~10s~n" , ["Pid", "registered_name", "initial_call", "current_call", "memory", "reductions", "msg_len", "bin"] ), print_top(lists:reverse(L)). %% @doc 打印进程消息队列 -spec mq_info(PidStr, N, Order) -> ok when PidStr :: list(), %% 进程PID N :: integer(), %% 取消息队列前N个 Order :: asc | desc. mq_info(P, N) -> mq_info(P, N, asc). mq_info(P, N, Order) when is_list(P) -> mq_info(list_to_pid(P), N, Order); mq_info(P, N, Order) when node(P) == node() -> L = erlang:process_info(P), case lists:keyfind(messages, 1, L) of {_, Mgs} when is_list(Mgs) -> Mgs1 = case Order of desc -> lists:reverse(Mgs); _ -> Mgs end, Len = length(Mgs1), N1 = if N < 0 -> 0; N > Len -> Len; true -> N end, {L1, _} = lists:split(N1, Mgs1), ?INFO("Pid=~w的消息队列前N=~w个:~w", [P, N, L1]); _ -> ?INFO("错误的参数:P=~w, N=~w", [P, N]) end. %% @doc 打印消息队列最高的几个进程的消息队列 -spec mq_info_top(TopNum, MsgNum) -> ok when TopNum :: integer(), %% 消息队列最高的多少个 MsgNum :: integer(). %% 消息条数 mq_info_top(TopNum, MsgNum) -> case dev:top(queue, 1, TopNum) of L when is_list(L) -> lists:foreach(fun(Args) -> case Args of [Pid, Name, _, Memory, Reds, MsgLen] -> ?INFO("Pid=~w, Name=~ts, Memory=~w, Reds=~w, MsgLen=~w, 消息队列前[~w]个:", [Pid, Name, Memory, Reds, MsgLen, MsgNum]), mq_info(Pid, MsgNum); _ -> ?INFO("top(queue)返回格式错误:~w", [Args]) end end, L); _ -> ?INFO("top(queue)返回格式错误") end. %% @doc 开始对当前进程执行eprof分析程序 -spec eprof_start() -> ok. eprof_start() -> eprof_start(pid, [self()]). %% @doc 开始执行eprof分析程序 -spec eprof_start(pid, Pids) -> ok when Pids :: [pid()]. eprof_start(pid, Pids) -> case eprof:start_profiling(Pids) of profiling -> ?INFO("eprof启动成功"); E -> ?INFO("eprof启动失败: ~w", [E]) end; %% @doc 对指定角色执行eprof分析 eprof_start(role, {Rid, Platform, SrvId}) -> case role_query:pid({Rid, Platform, SrvId}) of {ok, Pid} -> eprof_start(pid, [Pid]); _ -> ?INFO("角色[Rid:~w Platform:~ts SrvId:~w]不在线", [Rid, Platform, SrvId]) end; %% @doc 对联盟进程执行eprof分析 eprof_start(clan, ClanId) -> case clan:pid(ClanId) of {ok, Pid} -> eprof_start(pid, [Pid]); {error, not_found} -> ?INFO("联盟[~w]不存在", [ClanId]); _ -> ?INFO("联盟[~w]不在线", [ClanId]) end. eprof_stop ( ) - > ok %% @doc 停止eprof并输出分析结果到指eprof_analyze.log文件中 eprof_stop() -> eprof_stop("eprof_analyze"). @doc 停止eprof并输出分析结果到指定文件 -spec eprof_stop(FileName) -> ok when FileName :: string(). eprof_stop(FileName) -> File = FileName ++ ".log", eprof:stop_profiling(), eprof:log(File), eprof:analyze(total), ?INFO("eprof分析结果已经输出到了:~ts", [File]). %% @doc 编译并热更新模块(生产模式) -spec m() -> ok. m() -> %% make(main, []). m(main). %% @doc 编译并热更新模块(使用标准调试模式) -spec m(Type::atom()) -> ok. m(main) -> make(main, [{d, debug}, {d, dbg_socket}, {d, disable_auth}, {d, enable_gm}, {d, dbg_lag}]); m(tester) -> make(tester, [{d, dbg_tester}, {d, disable_auth}, {d, enable_gm}]); m(data) -> make(data, []). @doc 编译并更新模块 %% 有效编译参数: %% <ul> %% <li>debug 开启debug模式,打开宏?DEBUG的输出</li> < li > dbg_sql 开启数据库调试模式,打印所有的SQL查询信息</li > %% <li>dbg_socket 开启socket调试模式,打印所有收发的socket数据</li> %% <li>dbg_lag 开启网络延时模拟,波动延时为100~300</li> < li > enable_gm_cmd > %% <li>disable_auth 关闭ticket验证</li> %% </ul> -spec make(atom() | string(), list()) -> ok. make(main, Param) -> make(env:get(code_path), Param); make(data, Param) -> make(env:get(code_path) ++ "/data", Param); make(tester, Param) -> make(env:get(code_path) ++ "/tester", Param); make(Path, Param) -> util:cn("### 正在编译(~ts),参数:~w~n", [Path, Param]), file:set_cwd(Path), case make:all(Param) of up_to_date -> do_up([], false); _ -> ignore end, file:set_cwd(env:get(zone_path)). %% 返回节点目录 %% @doc 热更新所有模块(非强制) -spec u() -> ok. u() -> do_up([], false), ok. %% @doc 热更新所有模块(强制更新) %% <ul> %% <li>force 强制更新所有模块</li> %% <li>[atom()] 非强制更新指定模块</li> %% </ul> -spec u(Options) -> ok when Options :: force | [atom()]. u(force) -> do_up([], true); u(ModList) when is_list(ModList) -> do_up(ModList, false). %% @doc 热更新指定模块(强制更新) -spec u([atom()], F::force) -> ok. u(ModList, force) when is_list(ModList) -> do_up(ModList, true). %% @doc 热更新数据库语句 %% <div>不可逆</div> -spec u_db(DbSql::string()) -> ok | error. u_db(DbSql) -> util:cn("--- 正在热更新节点SQL: ~w ---~n", [node()]), case db:exec(DbSql) of {error, _Why} -> util:cn(">> 热更新节点SQL失败: ~w", [_Why]), error; {ok, _} -> ok end. %% @doc 生成API文档,将源码文件全部放入src同级的doc/目录中 -spec edoc() -> ok. edoc() -> %% edoc:application(main, "./", []), {ok, Path} = file:get_cwd(), CodePath = Path ++ "/src", case file_list(CodePath, ".erl") of {error, _Why} -> ignore; {ok, L} -> edoc:files(do_edoc(L, []), [{new, true}, {dir, Path ++ "/doc"}]) end, ok. %% @doc 获取所有*.erl文件 %% <div>注意:对于没有访问权限的文件将不在出现在此列表中</div> -spec get_all_erl() -> FileList | {error, term()} when FileList :: [{FileName, FilePath}], FileName :: string(), FilePath :: string(). get_all_erl() -> {ok, Cwd} = file:get_cwd(), Dir = Cwd ++ "src", case file:list_dir(Dir) of {ok, L} -> {ok, file_filter(L, Dir, ".erl", [])}; _Other -> {error, _Other} end. %% @doc 获取指定目录下指定类型的文件(包括子目录) -spec file_list(Dir, Ext) -> {ok, FileList} | {error, Why} when Dir :: string(), Ext :: string(), FileList :: [{FilePath, FileName}], Why :: term(), FilePath :: string(), FileName :: string(). file_list(Dir, Ext) -> ?DEBUG("搜索目录[~ts]下的所有\"~ts\"文件", [Dir, Ext]), case file:list_dir(Dir) of {error, Reason} -> {error, Reason}; {ok, L} -> {ok, file_filter(L, Dir, Ext, [])} end. %% ---------------------------------------------------- 私有函数 %% ---------------------------------------------------- %% 执行更新 do_up(L, F) -> util:cn("--- 正在热更新节点: ~w ---~n", [node()]), Args = case {L, F} of {[], false} -> []; {[], true} -> [force]; {[_H | _T], false} -> [L]; {[_H | _T], true} -> [L, force] end, print_up(apply(sys_code, up, Args)). %% 显示更新结果 print_up([]) -> ?P("~n"); print_up([{M, ok} | T]) -> util:cn("# 加载模块成功: ~p~n", [M]), print_up(T); print_up([{M, {error, Reason}} | T]) -> util:cn("* 加载模块失败[~p]: ~p~n", [M, Reason]), print_up(T). %% 格式化打钱top信息 print_top([]) -> ok; print_top([H | T]) -> io:format("~10w ~24w ~30w ~30w ~12w ~12w ~10w ~10w~n", H), print_top(T). 处理edoc使用的文件列表,过滤掉没有必要生成文档的文件 do_edoc([], L) -> L; do_edoc([{M, F} | T], L) -> case util:text_banned(M, ["proto_.*", ".*_data", "sup_.*", ".*_rpc", "mysql.*"]) of true -> do_edoc(T, L); false -> do_edoc(T, [F | L]) end. %% 文件过滤,查找指定目录下的所有文件(包括子目录),返回指定扩展名的文件列表 file_filter([], _Dir, _Ext, List) -> List; file_filter([H | T], Dir, Ext, List) -> F = Dir ++ "/" ++ H, NewList = case file:read_file_info(F) of {ok, I} -> if I#file_info.type =:= directory -> case file:list_dir(F) of {ok, L} -> D = Dir ++ "/" ++ H, List ++ file_filter(L, D, Ext, []); _Err -> io:format("error list in directory:~p~n", [_Err]), List end; I#file_info.type =:= regular -> case filename:extension(F) =:= Ext of true -> List ++ [{filename:basename(filename:rootname(F)), F}]; false -> List end; true -> List end; _Other -> io:format("error in read_file_info:~p ~w~n", [F, _Other]), List end, file_filter(T, Dir, Ext, NewList). %% top辅助函数 do_top(Type, Start, Len) when is_integer(Start), is_integer(Len), Start > 0, Len > 0 -> L = do_top1(Type, erlang:processes(), []), NL = lists:sublist(L, Start, Len), top_detail(NL, []). do_top1(_Type, [], L) -> lists:sort(fun top_sort/2, L); do_top1(Type, [P | Pids], L) -> NL = case process_info(P, Type) of {_, V} when Type =:= binary -> SortedBins = lists:usort(V), {_, SL, _} = lists:unzip3(SortedBins), [{P, lists:sum(SL)} | L]; {_, V} -> [{P, V} | L]; _ -> L end, do_top1(Type, Pids, NL). top_detail([], L) -> L; top_detail([{P, _} | T], L) -> Mem = case process_info(P, memory) of {_, V1} -> V1; _ -> undefined end, Reds = case process_info(P, reductions) of {_, V2} -> V2; _ -> undefined end, InitCall = case process_info(P, initial_call) of {_, V3} -> V3; _ -> undefined end, CurrCall = case process_info(P, current_function) of {_, V4} -> V4; _ -> undefined end, MsgLen = case process_info(P, message_queue_len) of {_, V5} -> V5; _ -> undefined end, RegName = case process_info(P, registered_name) of {_, V6} -> V6; _ -> undefined end, Bin = case process_info(P, binary) of {_, V7} -> SortedBins = lists:usort(V7), {_, SL, _} = lists:unzip3(SortedBins), lists:sum(SL); _ -> undefined end, top_detail(T, [[P, RegName, InitCall, CurrCall, Mem, Reds, MsgLen, Bin] | L]). top_sort({_, A}, {_, B}) when A =< B -> false; top_sort(_, _) -> true.
null
https://raw.githubusercontent.com/fantasytree/fancy_game_server/4ca93486fc0d5b6630170e79b48fb31e9c6e2358/src/sys/dev.erl
erlang
---------------------------------------------------- ---------------------------------------------------- @doc 查看系统当前的综合信息 @doc 返回当前及诶单的占用资源最多的列表信息 Type = mem | queue | reds Type: 排名类型 <ul> <li>{@type mem} 返回当前节点中内存占用前N的进程</li> <li>{@type queue} 返回当前节点中消息队列长度前N的进程</li> </ul> @doc 打印进程消息队列 进程PID 取消息队列前N个 @doc 打印消息队列最高的几个进程的消息队列 消息队列最高的多少个 消息条数 @doc 开始对当前进程执行eprof分析程序 @doc 开始执行eprof分析程序 @doc 对指定角色执行eprof分析 @doc 对联盟进程执行eprof分析 @doc 停止eprof并输出分析结果到指eprof_analyze.log文件中 @doc 编译并热更新模块(生产模式) make(main, []). @doc 编译并热更新模块(使用标准调试模式) 有效编译参数: <ul> <li>debug 开启debug模式,打开宏?DEBUG的输出</li> <li>dbg_socket 开启socket调试模式,打印所有收发的socket数据</li> <li>dbg_lag 开启网络延时模拟,波动延时为100~300</li> <li>disable_auth 关闭ticket验证</li> </ul> 返回节点目录 @doc 热更新所有模块(非强制) @doc 热更新所有模块(强制更新) <ul> <li>force 强制更新所有模块</li> <li>[atom()] 非强制更新指定模块</li> </ul> @doc 热更新指定模块(强制更新) @doc 热更新数据库语句 <div>不可逆</div> @doc 生成API文档,将源码文件全部放入src同级的doc/目录中 edoc:application(main, "./", []), @doc 获取所有*.erl文件 <div>注意:对于没有访问权限的文件将不在出现在此列表中</div> @doc 获取指定目录下指定类型的文件(包括子目录) ---------------------------------------------------- ---------------------------------------------------- 执行更新 显示更新结果 格式化打钱top信息 文件过滤,查找指定目录下的所有文件(包括子目录),返回指定扩展名的文件列表 top辅助函数
开发工具 -module(dev). -export([ info/0 ,mq_info/2 ,mq_info/3 ,mq_info_top/2 ,top/0 ,top/1 ,top/3 ,eprof_start/0 ,eprof_start/2 ,eprof_stop/0 ,m/0 ,m/1 ,u/0 ,u/1 ,u/2 ,u_db/1 ,edoc/0 ,get_all_erl/0 ,file_list/2 ] ). -include_lib("kernel/include/file.hrl"). -include("common.hrl"). -spec info() -> ok. info() -> SchedId = erlang:system_info(scheduler_id), SchedNum = erlang:system_info(schedulers), ProcCount = erlang:system_info(process_count), ProcLimit = erlang:system_info(process_limit), ProcMemUsed = erlang:memory(processes_used), ProcMemAlloc = erlang:memory(processes), MemTot = erlang:memory(total), OnlineNum = ets:info(ets_role_login, size), RoleNum = dets:info(role_data, size), {MaxFDsize,_}= string:to_integer(os:cmd("ulimit -n")), FDsize = length(string:tokens(os:cmd("lsof -d \"0-9999999\" -lna -Ff -p " ++ os:getpid()), "\n")), {CoreSize,_} = string:to_integer(os:cmd("ulimit -c")), DistBufBusyLimit = erlang:system_info(dist_buf_busy_limit), util:cn( " 当前节点名: ~p~n" " Scheduler id: ~p~n" " Num scheduler: ~p~n" " Memory used by erlang processes: ~p~n" " Memory allocated by erlang processes: ~p~n" " The total amount of memory allocated: ~p~n" " 可创建进程数量上限: ~p~n" " 当前节点进程数: ~p~n" " 本节点在线玩家数: ~p~n" " 本节点玩家总数: ~p~n" " 本节点文件描述符上限: ~p~n" " 本节点当前打开PORT数: ~p~n" " 本节点CoreDump文件大小上限: ~p~n" " 本节点RPC通道缓存: ~p Bytes~n" , [node(), SchedId, SchedNum, ProcMemUsed, ProcMemAlloc, MemTot, ProcLimit, ProcCount, OnlineNum, RoleNum, MaxFDsize, FDsize, CoreSize, DistBufBusyLimit]), ok. -spec top() -> ProcList::list(). top() -> ?INFO("显示占用内存最多的10个进程:~n"), top(mem), ?INFO("显示消息队列最多的10个进程:~n"), top(queue), ?INFO("显示CPU占用最多的10个进程:~n"), top(reds), ?INFO("显示bin使用最多的10个进程:~n"), top(bin). @doc 返回当前节点中占用资源最多的N个进程列表 . -spec top(Type::atom()) -> ProcList::list(). < li>{@type reds } 返回当前节点中reductions值前N的进程</li > top(mem) -> top(mem, 1, 10); top(queue) -> top(queue, 1, 10); top(reds) -> top(reds, 1, 10); top(bin) -> top(bin, 1, 10). @doc 返回当前节点中占用资源最多的N个进程列表 . ProcList = list ( ) -spec top(Type::atom(), Start::integer(), Len::integer()) -> ProcList::list(). top(Type, Start, Len) -> TopType = if Type =:= mem -> memory; Type =:= queue -> message_queue_len; Type =:= reds -> reductions; Type =:= bin -> binary; true -> undefined end, L = do_top(TopType, Start, Len), util:cn( "~10s ~24s ~30s ~30s ~12s ~12s ~10s ~10s~n" , ["Pid", "registered_name", "initial_call", "current_call", "memory", "reductions", "msg_len", "bin"] ), print_top(lists:reverse(L)). -spec mq_info(PidStr, N, Order) -> ok when Order :: asc | desc. mq_info(P, N) -> mq_info(P, N, asc). mq_info(P, N, Order) when is_list(P) -> mq_info(list_to_pid(P), N, Order); mq_info(P, N, Order) when node(P) == node() -> L = erlang:process_info(P), case lists:keyfind(messages, 1, L) of {_, Mgs} when is_list(Mgs) -> Mgs1 = case Order of desc -> lists:reverse(Mgs); _ -> Mgs end, Len = length(Mgs1), N1 = if N < 0 -> 0; N > Len -> Len; true -> N end, {L1, _} = lists:split(N1, Mgs1), ?INFO("Pid=~w的消息队列前N=~w个:~w", [P, N, L1]); _ -> ?INFO("错误的参数:P=~w, N=~w", [P, N]) end. -spec mq_info_top(TopNum, MsgNum) -> ok when mq_info_top(TopNum, MsgNum) -> case dev:top(queue, 1, TopNum) of L when is_list(L) -> lists:foreach(fun(Args) -> case Args of [Pid, Name, _, Memory, Reds, MsgLen] -> ?INFO("Pid=~w, Name=~ts, Memory=~w, Reds=~w, MsgLen=~w, 消息队列前[~w]个:", [Pid, Name, Memory, Reds, MsgLen, MsgNum]), mq_info(Pid, MsgNum); _ -> ?INFO("top(queue)返回格式错误:~w", [Args]) end end, L); _ -> ?INFO("top(queue)返回格式错误") end. -spec eprof_start() -> ok. eprof_start() -> eprof_start(pid, [self()]). -spec eprof_start(pid, Pids) -> ok when Pids :: [pid()]. eprof_start(pid, Pids) -> case eprof:start_profiling(Pids) of profiling -> ?INFO("eprof启动成功"); E -> ?INFO("eprof启动失败: ~w", [E]) end; eprof_start(role, {Rid, Platform, SrvId}) -> case role_query:pid({Rid, Platform, SrvId}) of {ok, Pid} -> eprof_start(pid, [Pid]); _ -> ?INFO("角色[Rid:~w Platform:~ts SrvId:~w]不在线", [Rid, Platform, SrvId]) end; eprof_start(clan, ClanId) -> case clan:pid(ClanId) of {ok, Pid} -> eprof_start(pid, [Pid]); {error, not_found} -> ?INFO("联盟[~w]不存在", [ClanId]); _ -> ?INFO("联盟[~w]不在线", [ClanId]) end. eprof_stop ( ) - > ok eprof_stop() -> eprof_stop("eprof_analyze"). @doc 停止eprof并输出分析结果到指定文件 -spec eprof_stop(FileName) -> ok when FileName :: string(). eprof_stop(FileName) -> File = FileName ++ ".log", eprof:stop_profiling(), eprof:log(File), eprof:analyze(total), ?INFO("eprof分析结果已经输出到了:~ts", [File]). -spec m() -> ok. m() -> m(main). -spec m(Type::atom()) -> ok. m(main) -> make(main, [{d, debug}, {d, dbg_socket}, {d, disable_auth}, {d, enable_gm}, {d, dbg_lag}]); m(tester) -> make(tester, [{d, dbg_tester}, {d, disable_auth}, {d, enable_gm}]); m(data) -> make(data, []). @doc 编译并更新模块 < li > dbg_sql 开启数据库调试模式,打印所有的SQL查询信息</li > < li > enable_gm_cmd > -spec make(atom() | string(), list()) -> ok. make(main, Param) -> make(env:get(code_path), Param); make(data, Param) -> make(env:get(code_path) ++ "/data", Param); make(tester, Param) -> make(env:get(code_path) ++ "/tester", Param); make(Path, Param) -> util:cn("### 正在编译(~ts),参数:~w~n", [Path, Param]), file:set_cwd(Path), case make:all(Param) of up_to_date -> do_up([], false); _ -> ignore end, -spec u() -> ok. u() -> do_up([], false), ok. -spec u(Options) -> ok when Options :: force | [atom()]. u(force) -> do_up([], true); u(ModList) when is_list(ModList) -> do_up(ModList, false). -spec u([atom()], F::force) -> ok. u(ModList, force) when is_list(ModList) -> do_up(ModList, true). -spec u_db(DbSql::string()) -> ok | error. u_db(DbSql) -> util:cn("--- 正在热更新节点SQL: ~w ---~n", [node()]), case db:exec(DbSql) of {error, _Why} -> util:cn(">> 热更新节点SQL失败: ~w", [_Why]), error; {ok, _} -> ok end. -spec edoc() -> ok. edoc() -> {ok, Path} = file:get_cwd(), CodePath = Path ++ "/src", case file_list(CodePath, ".erl") of {error, _Why} -> ignore; {ok, L} -> edoc:files(do_edoc(L, []), [{new, true}, {dir, Path ++ "/doc"}]) end, ok. -spec get_all_erl() -> FileList | {error, term()} when FileList :: [{FileName, FilePath}], FileName :: string(), FilePath :: string(). get_all_erl() -> {ok, Cwd} = file:get_cwd(), Dir = Cwd ++ "src", case file:list_dir(Dir) of {ok, L} -> {ok, file_filter(L, Dir, ".erl", [])}; _Other -> {error, _Other} end. -spec file_list(Dir, Ext) -> {ok, FileList} | {error, Why} when Dir :: string(), Ext :: string(), FileList :: [{FilePath, FileName}], Why :: term(), FilePath :: string(), FileName :: string(). file_list(Dir, Ext) -> ?DEBUG("搜索目录[~ts]下的所有\"~ts\"文件", [Dir, Ext]), case file:list_dir(Dir) of {error, Reason} -> {error, Reason}; {ok, L} -> {ok, file_filter(L, Dir, Ext, [])} end. 私有函数 do_up(L, F) -> util:cn("--- 正在热更新节点: ~w ---~n", [node()]), Args = case {L, F} of {[], false} -> []; {[], true} -> [force]; {[_H | _T], false} -> [L]; {[_H | _T], true} -> [L, force] end, print_up(apply(sys_code, up, Args)). print_up([]) -> ?P("~n"); print_up([{M, ok} | T]) -> util:cn("# 加载模块成功: ~p~n", [M]), print_up(T); print_up([{M, {error, Reason}} | T]) -> util:cn("* 加载模块失败[~p]: ~p~n", [M, Reason]), print_up(T). print_top([]) -> ok; print_top([H | T]) -> io:format("~10w ~24w ~30w ~30w ~12w ~12w ~10w ~10w~n", H), print_top(T). 处理edoc使用的文件列表,过滤掉没有必要生成文档的文件 do_edoc([], L) -> L; do_edoc([{M, F} | T], L) -> case util:text_banned(M, ["proto_.*", ".*_data", "sup_.*", ".*_rpc", "mysql.*"]) of true -> do_edoc(T, L); false -> do_edoc(T, [F | L]) end. file_filter([], _Dir, _Ext, List) -> List; file_filter([H | T], Dir, Ext, List) -> F = Dir ++ "/" ++ H, NewList = case file:read_file_info(F) of {ok, I} -> if I#file_info.type =:= directory -> case file:list_dir(F) of {ok, L} -> D = Dir ++ "/" ++ H, List ++ file_filter(L, D, Ext, []); _Err -> io:format("error list in directory:~p~n", [_Err]), List end; I#file_info.type =:= regular -> case filename:extension(F) =:= Ext of true -> List ++ [{filename:basename(filename:rootname(F)), F}]; false -> List end; true -> List end; _Other -> io:format("error in read_file_info:~p ~w~n", [F, _Other]), List end, file_filter(T, Dir, Ext, NewList). do_top(Type, Start, Len) when is_integer(Start), is_integer(Len), Start > 0, Len > 0 -> L = do_top1(Type, erlang:processes(), []), NL = lists:sublist(L, Start, Len), top_detail(NL, []). do_top1(_Type, [], L) -> lists:sort(fun top_sort/2, L); do_top1(Type, [P | Pids], L) -> NL = case process_info(P, Type) of {_, V} when Type =:= binary -> SortedBins = lists:usort(V), {_, SL, _} = lists:unzip3(SortedBins), [{P, lists:sum(SL)} | L]; {_, V} -> [{P, V} | L]; _ -> L end, do_top1(Type, Pids, NL). top_detail([], L) -> L; top_detail([{P, _} | T], L) -> Mem = case process_info(P, memory) of {_, V1} -> V1; _ -> undefined end, Reds = case process_info(P, reductions) of {_, V2} -> V2; _ -> undefined end, InitCall = case process_info(P, initial_call) of {_, V3} -> V3; _ -> undefined end, CurrCall = case process_info(P, current_function) of {_, V4} -> V4; _ -> undefined end, MsgLen = case process_info(P, message_queue_len) of {_, V5} -> V5; _ -> undefined end, RegName = case process_info(P, registered_name) of {_, V6} -> V6; _ -> undefined end, Bin = case process_info(P, binary) of {_, V7} -> SortedBins = lists:usort(V7), {_, SL, _} = lists:unzip3(SortedBins), lists:sum(SL); _ -> undefined end, top_detail(T, [[P, RegName, InitCall, CurrCall, Mem, Reds, MsgLen, Bin] | L]). top_sort({_, A}, {_, B}) when A =< B -> false; top_sort(_, _) -> true.
370ed027d5e28f421cc1dabf24b24a17ffde1544e693f31deeba0448a48604ee
VisionsGlobalEmpowerment/webchange
views.cljs
(ns webchange.admin.widgets.activity-info-form.views (:require [re-frame.core :as re-frame] [webchange.admin.widgets.activity-info-form.state :as state] [webchange.validation.specs.activity :as spec] [webchange.ui.index :as ui] [webchange.utils.languages :refer [language-options]])) (defn- remove-window [{:keys [activity-id]}] (let [{:keys [done? open? in-progress?]} @(re-frame/subscribe [::state/remove-window-state]) remove #(re-frame/dispatch [::state/remove-activity activity-id]) close-window #(re-frame/dispatch [::state/close-remove-window]) confirm-removed #(re-frame/dispatch [::state/handle-removed])] [ui/confirm {:open? open? :loading? in-progress? :confirm-text (if done? "Ok" "Yes") :on-confirm (if done? confirm-removed remove) :on-cancel (when-not done? close-window)} (if done? "Activity successfully deleted" "Are you sure you want to delete activity?")])) (defn activity-info-form [{:keys [activity-id] :as props}] (re-frame/dispatch [::state/init props]) (fn [{:keys [editable? class-name controls on-save on-cancel] :or {editable? true}}] (let [loading? @(re-frame/subscribe [::state/data-loading?]) saving? @(re-frame/subscribe [::state/data-saving?]) data @(re-frame/subscribe [::state/form-data]) locked? (:locked data) model {:group-left {:type :group :class-name "group-left" :fields {:about {:label "About" :type :text-multiline} :short-description {:label "Short Description" :type :text} :remove {:label "Delete Activity" :type (if locked? :empty :action) :icon "trash" :on-click #(re-frame/dispatch [::state/open-remove-window])}}} :group-filler {:type :group :class-name "group-filler"} :group-right {:type :group :class-name "group-right" :fields (cond-> {:name {:label "Name" :type :text} :lang {:label "Language" :type :select :options language-options}} (some? controls) (assoc :controls {:type :custom :label (:label controls) :control (:component controls)}))}} handle-save #(re-frame/dispatch [::state/save % {:on-success on-save}])] [:<> [ui/form {:form-id (-> (str "activity-" activity-id) (keyword)) :data data :model model :spec ::spec/activity-info :on-save handle-save :on-cancel on-cancel :disabled? (not editable?) :loading? loading? :saving? saving? :class-name class-name}] [remove-window {:activity-id activity-id}]])))
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/2097ed3510b4060028232a85956a00c7efbfda68/src/cljs/webchange/admin/widgets/activity_info_form/views.cljs
clojure
(ns webchange.admin.widgets.activity-info-form.views (:require [re-frame.core :as re-frame] [webchange.admin.widgets.activity-info-form.state :as state] [webchange.validation.specs.activity :as spec] [webchange.ui.index :as ui] [webchange.utils.languages :refer [language-options]])) (defn- remove-window [{:keys [activity-id]}] (let [{:keys [done? open? in-progress?]} @(re-frame/subscribe [::state/remove-window-state]) remove #(re-frame/dispatch [::state/remove-activity activity-id]) close-window #(re-frame/dispatch [::state/close-remove-window]) confirm-removed #(re-frame/dispatch [::state/handle-removed])] [ui/confirm {:open? open? :loading? in-progress? :confirm-text (if done? "Ok" "Yes") :on-confirm (if done? confirm-removed remove) :on-cancel (when-not done? close-window)} (if done? "Activity successfully deleted" "Are you sure you want to delete activity?")])) (defn activity-info-form [{:keys [activity-id] :as props}] (re-frame/dispatch [::state/init props]) (fn [{:keys [editable? class-name controls on-save on-cancel] :or {editable? true}}] (let [loading? @(re-frame/subscribe [::state/data-loading?]) saving? @(re-frame/subscribe [::state/data-saving?]) data @(re-frame/subscribe [::state/form-data]) locked? (:locked data) model {:group-left {:type :group :class-name "group-left" :fields {:about {:label "About" :type :text-multiline} :short-description {:label "Short Description" :type :text} :remove {:label "Delete Activity" :type (if locked? :empty :action) :icon "trash" :on-click #(re-frame/dispatch [::state/open-remove-window])}}} :group-filler {:type :group :class-name "group-filler"} :group-right {:type :group :class-name "group-right" :fields (cond-> {:name {:label "Name" :type :text} :lang {:label "Language" :type :select :options language-options}} (some? controls) (assoc :controls {:type :custom :label (:label controls) :control (:component controls)}))}} handle-save #(re-frame/dispatch [::state/save % {:on-success on-save}])] [:<> [ui/form {:form-id (-> (str "activity-" activity-id) (keyword)) :data data :model model :spec ::spec/activity-info :on-save handle-save :on-cancel on-cancel :disabled? (not editable?) :loading? loading? :saving? saving? :class-name class-name}] [remove-window {:activity-id activity-id}]])))
6e985290c64d347c4a463e5e3eb7d253fc5103978448728555fc73cfa47b9812
haskell-opengl/OpenGLRaw
VertexProgram.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.VertexProgram Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.VertexProgram ( -- * Extension Support glGetNVVertexProgram, gl_NV_vertex_program, -- * Enums pattern GL_ATTRIB_ARRAY_POINTER_NV, pattern GL_ATTRIB_ARRAY_SIZE_NV, pattern GL_ATTRIB_ARRAY_STRIDE_NV, pattern GL_ATTRIB_ARRAY_TYPE_NV, pattern GL_CURRENT_ATTRIB_NV, pattern GL_CURRENT_MATRIX_NV, pattern GL_CURRENT_MATRIX_STACK_DEPTH_NV, pattern GL_IDENTITY_NV, pattern GL_INVERSE_NV, pattern GL_INVERSE_TRANSPOSE_NV, pattern GL_MAP1_VERTEX_ATTRIB0_4_NV, pattern GL_MAP1_VERTEX_ATTRIB10_4_NV, pattern GL_MAP1_VERTEX_ATTRIB11_4_NV, pattern GL_MAP1_VERTEX_ATTRIB12_4_NV, pattern GL_MAP1_VERTEX_ATTRIB13_4_NV, pattern GL_MAP1_VERTEX_ATTRIB14_4_NV, pattern GL_MAP1_VERTEX_ATTRIB15_4_NV, pattern GL_MAP1_VERTEX_ATTRIB1_4_NV, pattern GL_MAP1_VERTEX_ATTRIB2_4_NV, pattern GL_MAP1_VERTEX_ATTRIB3_4_NV, pattern GL_MAP1_VERTEX_ATTRIB4_4_NV, pattern GL_MAP1_VERTEX_ATTRIB5_4_NV, pattern GL_MAP1_VERTEX_ATTRIB6_4_NV, pattern GL_MAP1_VERTEX_ATTRIB7_4_NV, pattern GL_MAP1_VERTEX_ATTRIB8_4_NV, pattern GL_MAP1_VERTEX_ATTRIB9_4_NV, pattern GL_MAP2_VERTEX_ATTRIB0_4_NV, pattern GL_MAP2_VERTEX_ATTRIB10_4_NV, pattern GL_MAP2_VERTEX_ATTRIB11_4_NV, pattern GL_MAP2_VERTEX_ATTRIB12_4_NV, pattern GL_MAP2_VERTEX_ATTRIB13_4_NV, pattern GL_MAP2_VERTEX_ATTRIB14_4_NV, pattern GL_MAP2_VERTEX_ATTRIB15_4_NV, pattern GL_MAP2_VERTEX_ATTRIB1_4_NV, pattern GL_MAP2_VERTEX_ATTRIB2_4_NV, pattern GL_MAP2_VERTEX_ATTRIB3_4_NV, pattern GL_MAP2_VERTEX_ATTRIB4_4_NV, pattern GL_MAP2_VERTEX_ATTRIB5_4_NV, pattern GL_MAP2_VERTEX_ATTRIB6_4_NV, pattern GL_MAP2_VERTEX_ATTRIB7_4_NV, pattern GL_MAP2_VERTEX_ATTRIB8_4_NV, pattern GL_MAP2_VERTEX_ATTRIB9_4_NV, pattern GL_MATRIX0_NV, pattern GL_MATRIX1_NV, pattern GL_MATRIX2_NV, pattern GL_MATRIX3_NV, pattern GL_MATRIX4_NV, pattern GL_MATRIX5_NV, pattern GL_MATRIX6_NV, pattern GL_MATRIX7_NV, pattern GL_MAX_TRACK_MATRICES_NV, pattern GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV, pattern GL_MODELVIEW_PROJECTION_NV, pattern GL_PROGRAM_ERROR_POSITION_NV, pattern GL_PROGRAM_LENGTH_NV, pattern GL_PROGRAM_PARAMETER_NV, pattern GL_PROGRAM_RESIDENT_NV, pattern GL_PROGRAM_STRING_NV, pattern GL_PROGRAM_TARGET_NV, pattern GL_TRACK_MATRIX_NV, pattern GL_TRACK_MATRIX_TRANSFORM_NV, pattern GL_TRANSPOSE_NV, pattern GL_VERTEX_ATTRIB_ARRAY0_NV, pattern GL_VERTEX_ATTRIB_ARRAY10_NV, pattern GL_VERTEX_ATTRIB_ARRAY11_NV, pattern GL_VERTEX_ATTRIB_ARRAY12_NV, pattern GL_VERTEX_ATTRIB_ARRAY13_NV, pattern GL_VERTEX_ATTRIB_ARRAY14_NV, pattern GL_VERTEX_ATTRIB_ARRAY15_NV, pattern GL_VERTEX_ATTRIB_ARRAY1_NV, pattern GL_VERTEX_ATTRIB_ARRAY2_NV, pattern GL_VERTEX_ATTRIB_ARRAY3_NV, pattern GL_VERTEX_ATTRIB_ARRAY4_NV, pattern GL_VERTEX_ATTRIB_ARRAY5_NV, pattern GL_VERTEX_ATTRIB_ARRAY6_NV, pattern GL_VERTEX_ATTRIB_ARRAY7_NV, pattern GL_VERTEX_ATTRIB_ARRAY8_NV, pattern GL_VERTEX_ATTRIB_ARRAY9_NV, pattern GL_VERTEX_PROGRAM_BINDING_NV, pattern GL_VERTEX_PROGRAM_NV, pattern GL_VERTEX_PROGRAM_POINT_SIZE_NV, pattern GL_VERTEX_PROGRAM_TWO_SIDE_NV, pattern GL_VERTEX_STATE_PROGRAM_NV, -- * Functions glAreProgramsResidentNV, glBindProgramNV, glDeleteProgramsNV, glExecuteProgramNV, glGenProgramsNV, glGetProgramParameterdvNV, glGetProgramParameterfvNV, glGetProgramStringNV, glGetProgramivNV, glGetTrackMatrixivNV, glGetVertexAttribPointervNV, glGetVertexAttribdvNV, glGetVertexAttribfvNV, glGetVertexAttribivNV, glIsProgramNV, glLoadProgramNV, glProgramParameter4dNV, glProgramParameter4dvNV, glProgramParameter4fNV, glProgramParameter4fvNV, glProgramParameters4dvNV, glProgramParameters4fvNV, glRequestResidentProgramsNV, glTrackMatrixNV, glVertexAttrib1dNV, glVertexAttrib1dvNV, glVertexAttrib1fNV, glVertexAttrib1fvNV, glVertexAttrib1sNV, glVertexAttrib1svNV, glVertexAttrib2dNV, glVertexAttrib2dvNV, glVertexAttrib2fNV, glVertexAttrib2fvNV, glVertexAttrib2sNV, glVertexAttrib2svNV, glVertexAttrib3dNV, glVertexAttrib3dvNV, glVertexAttrib3fNV, glVertexAttrib3fvNV, glVertexAttrib3sNV, glVertexAttrib3svNV, glVertexAttrib4dNV, glVertexAttrib4dvNV, glVertexAttrib4fNV, glVertexAttrib4fvNV, glVertexAttrib4sNV, glVertexAttrib4svNV, glVertexAttrib4ubNV, glVertexAttrib4ubvNV, glVertexAttribPointerNV, glVertexAttribs1dvNV, glVertexAttribs1fvNV, glVertexAttribs1svNV, glVertexAttribs2dvNV, glVertexAttribs2fvNV, glVertexAttribs2svNV, glVertexAttribs3dvNV, glVertexAttribs3fvNV, glVertexAttribs3svNV, glVertexAttribs4dvNV, glVertexAttribs4fvNV, glVertexAttribs4svNV, glVertexAttribs4ubvNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/NV/VertexProgram.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.NV.VertexProgram License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums * Functions
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.NV.VertexProgram ( glGetNVVertexProgram, gl_NV_vertex_program, pattern GL_ATTRIB_ARRAY_POINTER_NV, pattern GL_ATTRIB_ARRAY_SIZE_NV, pattern GL_ATTRIB_ARRAY_STRIDE_NV, pattern GL_ATTRIB_ARRAY_TYPE_NV, pattern GL_CURRENT_ATTRIB_NV, pattern GL_CURRENT_MATRIX_NV, pattern GL_CURRENT_MATRIX_STACK_DEPTH_NV, pattern GL_IDENTITY_NV, pattern GL_INVERSE_NV, pattern GL_INVERSE_TRANSPOSE_NV, pattern GL_MAP1_VERTEX_ATTRIB0_4_NV, pattern GL_MAP1_VERTEX_ATTRIB10_4_NV, pattern GL_MAP1_VERTEX_ATTRIB11_4_NV, pattern GL_MAP1_VERTEX_ATTRIB12_4_NV, pattern GL_MAP1_VERTEX_ATTRIB13_4_NV, pattern GL_MAP1_VERTEX_ATTRIB14_4_NV, pattern GL_MAP1_VERTEX_ATTRIB15_4_NV, pattern GL_MAP1_VERTEX_ATTRIB1_4_NV, pattern GL_MAP1_VERTEX_ATTRIB2_4_NV, pattern GL_MAP1_VERTEX_ATTRIB3_4_NV, pattern GL_MAP1_VERTEX_ATTRIB4_4_NV, pattern GL_MAP1_VERTEX_ATTRIB5_4_NV, pattern GL_MAP1_VERTEX_ATTRIB6_4_NV, pattern GL_MAP1_VERTEX_ATTRIB7_4_NV, pattern GL_MAP1_VERTEX_ATTRIB8_4_NV, pattern GL_MAP1_VERTEX_ATTRIB9_4_NV, pattern GL_MAP2_VERTEX_ATTRIB0_4_NV, pattern GL_MAP2_VERTEX_ATTRIB10_4_NV, pattern GL_MAP2_VERTEX_ATTRIB11_4_NV, pattern GL_MAP2_VERTEX_ATTRIB12_4_NV, pattern GL_MAP2_VERTEX_ATTRIB13_4_NV, pattern GL_MAP2_VERTEX_ATTRIB14_4_NV, pattern GL_MAP2_VERTEX_ATTRIB15_4_NV, pattern GL_MAP2_VERTEX_ATTRIB1_4_NV, pattern GL_MAP2_VERTEX_ATTRIB2_4_NV, pattern GL_MAP2_VERTEX_ATTRIB3_4_NV, pattern GL_MAP2_VERTEX_ATTRIB4_4_NV, pattern GL_MAP2_VERTEX_ATTRIB5_4_NV, pattern GL_MAP2_VERTEX_ATTRIB6_4_NV, pattern GL_MAP2_VERTEX_ATTRIB7_4_NV, pattern GL_MAP2_VERTEX_ATTRIB8_4_NV, pattern GL_MAP2_VERTEX_ATTRIB9_4_NV, pattern GL_MATRIX0_NV, pattern GL_MATRIX1_NV, pattern GL_MATRIX2_NV, pattern GL_MATRIX3_NV, pattern GL_MATRIX4_NV, pattern GL_MATRIX5_NV, pattern GL_MATRIX6_NV, pattern GL_MATRIX7_NV, pattern GL_MAX_TRACK_MATRICES_NV, pattern GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV, pattern GL_MODELVIEW_PROJECTION_NV, pattern GL_PROGRAM_ERROR_POSITION_NV, pattern GL_PROGRAM_LENGTH_NV, pattern GL_PROGRAM_PARAMETER_NV, pattern GL_PROGRAM_RESIDENT_NV, pattern GL_PROGRAM_STRING_NV, pattern GL_PROGRAM_TARGET_NV, pattern GL_TRACK_MATRIX_NV, pattern GL_TRACK_MATRIX_TRANSFORM_NV, pattern GL_TRANSPOSE_NV, pattern GL_VERTEX_ATTRIB_ARRAY0_NV, pattern GL_VERTEX_ATTRIB_ARRAY10_NV, pattern GL_VERTEX_ATTRIB_ARRAY11_NV, pattern GL_VERTEX_ATTRIB_ARRAY12_NV, pattern GL_VERTEX_ATTRIB_ARRAY13_NV, pattern GL_VERTEX_ATTRIB_ARRAY14_NV, pattern GL_VERTEX_ATTRIB_ARRAY15_NV, pattern GL_VERTEX_ATTRIB_ARRAY1_NV, pattern GL_VERTEX_ATTRIB_ARRAY2_NV, pattern GL_VERTEX_ATTRIB_ARRAY3_NV, pattern GL_VERTEX_ATTRIB_ARRAY4_NV, pattern GL_VERTEX_ATTRIB_ARRAY5_NV, pattern GL_VERTEX_ATTRIB_ARRAY6_NV, pattern GL_VERTEX_ATTRIB_ARRAY7_NV, pattern GL_VERTEX_ATTRIB_ARRAY8_NV, pattern GL_VERTEX_ATTRIB_ARRAY9_NV, pattern GL_VERTEX_PROGRAM_BINDING_NV, pattern GL_VERTEX_PROGRAM_NV, pattern GL_VERTEX_PROGRAM_POINT_SIZE_NV, pattern GL_VERTEX_PROGRAM_TWO_SIDE_NV, pattern GL_VERTEX_STATE_PROGRAM_NV, glAreProgramsResidentNV, glBindProgramNV, glDeleteProgramsNV, glExecuteProgramNV, glGenProgramsNV, glGetProgramParameterdvNV, glGetProgramParameterfvNV, glGetProgramStringNV, glGetProgramivNV, glGetTrackMatrixivNV, glGetVertexAttribPointervNV, glGetVertexAttribdvNV, glGetVertexAttribfvNV, glGetVertexAttribivNV, glIsProgramNV, glLoadProgramNV, glProgramParameter4dNV, glProgramParameter4dvNV, glProgramParameter4fNV, glProgramParameter4fvNV, glProgramParameters4dvNV, glProgramParameters4fvNV, glRequestResidentProgramsNV, glTrackMatrixNV, glVertexAttrib1dNV, glVertexAttrib1dvNV, glVertexAttrib1fNV, glVertexAttrib1fvNV, glVertexAttrib1sNV, glVertexAttrib1svNV, glVertexAttrib2dNV, glVertexAttrib2dvNV, glVertexAttrib2fNV, glVertexAttrib2fvNV, glVertexAttrib2sNV, glVertexAttrib2svNV, glVertexAttrib3dNV, glVertexAttrib3dvNV, glVertexAttrib3fNV, glVertexAttrib3fvNV, glVertexAttrib3sNV, glVertexAttrib3svNV, glVertexAttrib4dNV, glVertexAttrib4dvNV, glVertexAttrib4fNV, glVertexAttrib4fvNV, glVertexAttrib4sNV, glVertexAttrib4svNV, glVertexAttrib4ubNV, glVertexAttrib4ubvNV, glVertexAttribPointerNV, glVertexAttribs1dvNV, glVertexAttribs1fvNV, glVertexAttribs1svNV, glVertexAttribs2dvNV, glVertexAttribs2fvNV, glVertexAttribs2svNV, glVertexAttribs3dvNV, glVertexAttribs3fvNV, glVertexAttribs3svNV, glVertexAttribs4dvNV, glVertexAttribs4fvNV, glVertexAttribs4svNV, glVertexAttribs4ubvNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
b67933b772ee19a76745ae2b94a411e76487fc800edbf2b335f24d623dd31cf7
ocaml/dune
dune_rpc_client.ml
module Where = Where module Client = Client module Private = Private
null
https://raw.githubusercontent.com/ocaml/dune/20180d12149343d073cdea5860d01dc181702e6a/src/dune_rpc_client/dune_rpc_client.ml
ocaml
module Where = Where module Client = Client module Private = Private
b40eef149459ead4c39027b3a9c21a08ee153747859d7db435a96344a610d9a3
GaloisInc/gidl
Gidl.hs
module Gidl ( run ) where import Prelude () import Prelude.Compat import Data.Char import Data.Maybe (catMaybes) import Control.Monad (when) import System.Console.GetOpt import System.Directory import System.Environment import System.Exit import System.FilePath import Text.Show.Pretty import Ivory.Artifact import Gidl.Parse import Gidl.Interface import Gidl.Backend.Elm (elmBackend) import Gidl.Backend.Haskell import Gidl.Backend.Ivory import Gidl.Backend.Rpc (rpcBackend) import Gidl.Backend.Tower data OptParser opt = OptParser [String] (opt -> opt) instance Monoid (OptParser opt) where mempty = OptParser [] id OptParser as f `mappend` OptParser bs g = OptParser (as ++ bs) (f . g) success :: (opt -> opt) -> OptParser opt success = OptParser [] invalid :: String -> OptParser opt invalid e = OptParser [e] id parseOptions :: [OptDescr (OptParser opt)] -> [String] -> Either [String] (opt -> opt) parseOptions opts args = case getOpt Permute opts args of (fs,[],[]) -> case mconcat fs of OptParser [] f -> Right f OptParser es _ -> Left es (_,_,es) -> Left es data Backend = HaskellBackend | IvoryBackend | TowerBackend | RpcBackend | ElmBackend deriving (Eq, Show) data Opts = Opts { backend :: Backend , idlpath :: FilePath , outpath :: FilePath , ivoryrepo :: FilePath , towerrepo :: FilePath , ivorytowerstm32repo :: FilePath , packagename :: String , namespace :: String , debug :: Bool , help :: Bool } initialOpts :: Opts initialOpts = Opts { backend = error (usage ["must specify a backend"]) , idlpath = error (usage ["must specify an idl file"]) , outpath = error (usage ["must specify an output path"]) , ivoryrepo = "ivory" , towerrepo = "tower" , ivorytowerstm32repo = "ivory-tower-stm32" , packagename = error (usage ["must specify a package name"]) , namespace = "" , debug = False , help = False } setBackend :: String -> OptParser Opts setBackend b = case map toUpper b of "HASKELL" -> success (\o -> o { backend = HaskellBackend }) "IVORY" -> success (\o -> o { backend = IvoryBackend }) "TOWER" -> success (\o -> o { backend = TowerBackend }) "HASKELL-RPC" -> success (\o -> o { backend = RpcBackend }) "ELM" -> success (\o -> o { backend = ElmBackend }) _ -> invalid e where e = "\"" ++ b ++ "\" is not a valid backend.\n" ++ "Supported backends: haskell, ivory, tower, haskell-rpc" setIdlPath :: String -> OptParser Opts setIdlPath p = success (\o -> o { idlpath = p }) setOutPath :: String -> OptParser Opts setOutPath p = success (\o -> o { outpath = p }) setIvoryRepo :: String -> OptParser Opts setIvoryRepo p = success (\o -> o { ivoryrepo = p }) setTowerRepo :: String -> OptParser Opts setTowerRepo p = success (\o -> o { towerrepo = p }) setIvoryTowerSTM32Repo :: String -> OptParser Opts setIvoryTowerSTM32Repo p = success (\o -> o { ivorytowerstm32repo = p }) setPackageName :: String -> OptParser Opts setPackageName p = success (\o -> o { packagename = p }) setNamespace :: String -> OptParser Opts setNamespace p = success (\o -> o { namespace = p }) setDebug :: OptParser Opts setDebug = success (\o -> o { debug = True }) setHelp :: OptParser Opts setHelp = success (\o -> o { help = True }) options :: [OptDescr (OptParser Opts)] options = [ Option "b" ["backend"] (ReqArg setBackend "BACKEND") "code generator backend" , Option "i" ["idl"] (ReqArg setIdlPath "FILE") "IDL file" , Option "o" ["out"] (ReqArg setOutPath "DIR") "root directory for output" , Option [] ["ivory-repo"] (ReqArg setIvoryRepo "REPO") "root of ivory.git (for Ivory and Tower backends only)" , Option [] ["tower-repo"] (ReqArg setTowerRepo "REPO") "root of tower.git (for Tower backend only)" , Option [] ["ivory-tower-stm32-repo"] (ReqArg setIvoryTowerSTM32Repo "REPO") "root of ivory-tower-stm32.git (for Tower backend only)" , Option "p" ["package"] (ReqArg setPackageName "NAME") "package name for output" , Option "n" ["namespace"] (ReqArg setNamespace "NAME") "namespace for output" , Option "" ["debug"] (NoArg setDebug) "enable debugging output" , Option "h" ["help"] (NoArg setHelp) "display this message and exit" ] parseOpts :: [String] -> IO Opts parseOpts args = case parseOptions options args of Right f -> let opts = f initialOpts in if help opts then putStrLn (usage []) >> exitSuccess else return opts Left errs -> putStrLn (usage errs) >> exitFailure usage :: [String] -> String usage errs = usageInfo banner options where banner = unlines (errs ++ ["", "Usage: gidl OPTIONS"]) run :: IO () run = do args <- getArgs opts <- parseOpts args idl <- readFile (idlpath opts) case parseDecls idl of Left e -> putStrLn ("Error parsing " ++ (idlpath opts) ++ ": " ++ e) >> exitFailure Right (te, ie) -> do when (debug opts) $ do putStrLn (ppShow te) putStrLn (ppShow ie) let InterfaceEnv ie' = ie interfaces = map snd ie' absolutize p name = do pAbs <- fmap normalise $ if isRelative p then fmap (</> p) getCurrentDirectory else return p ex <- doesDirectoryExist pAbs when (not ex) $ error (usage [ "Directory \"" ++ p ++ "\" does not exist." , "Make sure that the " ++ name ++ " repository is checked out." ]) return pAbs b <- case backend opts of HaskellBackend -> return haskellBackend IvoryBackend -> do ivoryAbs <- absolutize (ivoryrepo opts) "Ivory" return (ivoryBackend ivoryAbs) TowerBackend -> do ivoryAbs <- absolutize (ivoryrepo opts) "Ivory" towerAbs <- absolutize (towerrepo opts) "Tower" ivoryTowerSTM32Abs <- absolutize (ivorytowerstm32repo opts) "ivory-tower-stm32" return (towerBackend ivoryAbs towerAbs ivoryTowerSTM32Abs) RpcBackend -> return rpcBackend ElmBackend -> return elmBackend artifactBackend opts (b interfaces (packagename opts) (namespace opts)) where artifactBackend :: Opts -> [Artifact] -> IO () artifactBackend opts as = do when (debug opts) $ mapM_ printArtifact as es <- mapM (putArtifact (outpath opts)) as case catMaybes es of [] -> exitSuccess ees -> putStrLn (unlines ees) >> exitFailure
null
https://raw.githubusercontent.com/GaloisInc/gidl/f7674eeeffca124f8d12272152d29dd0c0ba0c0f/src/Gidl.hs
haskell
module Gidl ( run ) where import Prelude () import Prelude.Compat import Data.Char import Data.Maybe (catMaybes) import Control.Monad (when) import System.Console.GetOpt import System.Directory import System.Environment import System.Exit import System.FilePath import Text.Show.Pretty import Ivory.Artifact import Gidl.Parse import Gidl.Interface import Gidl.Backend.Elm (elmBackend) import Gidl.Backend.Haskell import Gidl.Backend.Ivory import Gidl.Backend.Rpc (rpcBackend) import Gidl.Backend.Tower data OptParser opt = OptParser [String] (opt -> opt) instance Monoid (OptParser opt) where mempty = OptParser [] id OptParser as f `mappend` OptParser bs g = OptParser (as ++ bs) (f . g) success :: (opt -> opt) -> OptParser opt success = OptParser [] invalid :: String -> OptParser opt invalid e = OptParser [e] id parseOptions :: [OptDescr (OptParser opt)] -> [String] -> Either [String] (opt -> opt) parseOptions opts args = case getOpt Permute opts args of (fs,[],[]) -> case mconcat fs of OptParser [] f -> Right f OptParser es _ -> Left es (_,_,es) -> Left es data Backend = HaskellBackend | IvoryBackend | TowerBackend | RpcBackend | ElmBackend deriving (Eq, Show) data Opts = Opts { backend :: Backend , idlpath :: FilePath , outpath :: FilePath , ivoryrepo :: FilePath , towerrepo :: FilePath , ivorytowerstm32repo :: FilePath , packagename :: String , namespace :: String , debug :: Bool , help :: Bool } initialOpts :: Opts initialOpts = Opts { backend = error (usage ["must specify a backend"]) , idlpath = error (usage ["must specify an idl file"]) , outpath = error (usage ["must specify an output path"]) , ivoryrepo = "ivory" , towerrepo = "tower" , ivorytowerstm32repo = "ivory-tower-stm32" , packagename = error (usage ["must specify a package name"]) , namespace = "" , debug = False , help = False } setBackend :: String -> OptParser Opts setBackend b = case map toUpper b of "HASKELL" -> success (\o -> o { backend = HaskellBackend }) "IVORY" -> success (\o -> o { backend = IvoryBackend }) "TOWER" -> success (\o -> o { backend = TowerBackend }) "HASKELL-RPC" -> success (\o -> o { backend = RpcBackend }) "ELM" -> success (\o -> o { backend = ElmBackend }) _ -> invalid e where e = "\"" ++ b ++ "\" is not a valid backend.\n" ++ "Supported backends: haskell, ivory, tower, haskell-rpc" setIdlPath :: String -> OptParser Opts setIdlPath p = success (\o -> o { idlpath = p }) setOutPath :: String -> OptParser Opts setOutPath p = success (\o -> o { outpath = p }) setIvoryRepo :: String -> OptParser Opts setIvoryRepo p = success (\o -> o { ivoryrepo = p }) setTowerRepo :: String -> OptParser Opts setTowerRepo p = success (\o -> o { towerrepo = p }) setIvoryTowerSTM32Repo :: String -> OptParser Opts setIvoryTowerSTM32Repo p = success (\o -> o { ivorytowerstm32repo = p }) setPackageName :: String -> OptParser Opts setPackageName p = success (\o -> o { packagename = p }) setNamespace :: String -> OptParser Opts setNamespace p = success (\o -> o { namespace = p }) setDebug :: OptParser Opts setDebug = success (\o -> o { debug = True }) setHelp :: OptParser Opts setHelp = success (\o -> o { help = True }) options :: [OptDescr (OptParser Opts)] options = [ Option "b" ["backend"] (ReqArg setBackend "BACKEND") "code generator backend" , Option "i" ["idl"] (ReqArg setIdlPath "FILE") "IDL file" , Option "o" ["out"] (ReqArg setOutPath "DIR") "root directory for output" , Option [] ["ivory-repo"] (ReqArg setIvoryRepo "REPO") "root of ivory.git (for Ivory and Tower backends only)" , Option [] ["tower-repo"] (ReqArg setTowerRepo "REPO") "root of tower.git (for Tower backend only)" , Option [] ["ivory-tower-stm32-repo"] (ReqArg setIvoryTowerSTM32Repo "REPO") "root of ivory-tower-stm32.git (for Tower backend only)" , Option "p" ["package"] (ReqArg setPackageName "NAME") "package name for output" , Option "n" ["namespace"] (ReqArg setNamespace "NAME") "namespace for output" , Option "" ["debug"] (NoArg setDebug) "enable debugging output" , Option "h" ["help"] (NoArg setHelp) "display this message and exit" ] parseOpts :: [String] -> IO Opts parseOpts args = case parseOptions options args of Right f -> let opts = f initialOpts in if help opts then putStrLn (usage []) >> exitSuccess else return opts Left errs -> putStrLn (usage errs) >> exitFailure usage :: [String] -> String usage errs = usageInfo banner options where banner = unlines (errs ++ ["", "Usage: gidl OPTIONS"]) run :: IO () run = do args <- getArgs opts <- parseOpts args idl <- readFile (idlpath opts) case parseDecls idl of Left e -> putStrLn ("Error parsing " ++ (idlpath opts) ++ ": " ++ e) >> exitFailure Right (te, ie) -> do when (debug opts) $ do putStrLn (ppShow te) putStrLn (ppShow ie) let InterfaceEnv ie' = ie interfaces = map snd ie' absolutize p name = do pAbs <- fmap normalise $ if isRelative p then fmap (</> p) getCurrentDirectory else return p ex <- doesDirectoryExist pAbs when (not ex) $ error (usage [ "Directory \"" ++ p ++ "\" does not exist." , "Make sure that the " ++ name ++ " repository is checked out." ]) return pAbs b <- case backend opts of HaskellBackend -> return haskellBackend IvoryBackend -> do ivoryAbs <- absolutize (ivoryrepo opts) "Ivory" return (ivoryBackend ivoryAbs) TowerBackend -> do ivoryAbs <- absolutize (ivoryrepo opts) "Ivory" towerAbs <- absolutize (towerrepo opts) "Tower" ivoryTowerSTM32Abs <- absolutize (ivorytowerstm32repo opts) "ivory-tower-stm32" return (towerBackend ivoryAbs towerAbs ivoryTowerSTM32Abs) RpcBackend -> return rpcBackend ElmBackend -> return elmBackend artifactBackend opts (b interfaces (packagename opts) (namespace opts)) where artifactBackend :: Opts -> [Artifact] -> IO () artifactBackend opts as = do when (debug opts) $ mapM_ printArtifact as es <- mapM (putArtifact (outpath opts)) as case catMaybes es of [] -> exitSuccess ees -> putStrLn (unlines ees) >> exitFailure
b33ca9906b5f7272da9143a075b43fd2d8fc17b703fb6e5b051ea8dc74359474
cj1128/sicp-review
2.78.scm
Exercise 2.78 ;; Modify the definition of type-tag, contents and attach-tag so that our generic system takes advantage of scheme's internal type system. That's to say, we can represent oridinary numbers as scheme numbers without adding 'scheme-number tag (define (type-tag datum) (cond ((number? datum) 'scheme-number) ((pair? datum) (car datum)) (else (error "Bad tagged datum: TYPE-TAG" datum)))) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cdr datum)) (else (error "Bad tagged datum: CONTENTS" datum)))) (define (attach-tag tag contents) (if (number? contents) contents (cons tag contents)))
null
https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-2/2.5/2.78.scm
scheme
Modify the definition of type-tag, contents and attach-tag so that our generic system takes advantage of scheme's internal type system. That's to say, we can represent oridinary numbers as scheme numbers without adding 'scheme-number tag
Exercise 2.78 (define (type-tag datum) (cond ((number? datum) 'scheme-number) ((pair? datum) (car datum)) (else (error "Bad tagged datum: TYPE-TAG" datum)))) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cdr datum)) (else (error "Bad tagged datum: CONTENTS" datum)))) (define (attach-tag tag contents) (if (number? contents) contents (cons tag contents)))
5daae59d4721980e9e3fa381e8cc361269bd2b3689c6b78b43bbbad2c6a9cb51
Frozenlock/wacnet
devices.clj
(ns wacnet.api.bacnet.devices (:require [bacure.coerce :as c] [bacure.coerce.type.enumerated :as ce] [bacure.core :as b] [bacure.remote-device :as rd] [clojure.set :as cs] [clojure.string :as string] [ring.swagger.schema :as rs] [schema.core :as s] [wacnet.api.bacnet.common :as co] [yada.resource :refer [resource]])) (def devices-list (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:get {:summary "Devices list" :parameters {:query {(s/optional-key :refresh) (rs/field s/Bool {:description (str "Tries to find new devices on the network" " using a WhoIs broadcast.")})}} :description "The list of all known devices with an optional refresh." :swagger/tags ["BACnet"] :response (fn [ctx] (co/with-bacnet-device ctx nil (when (get-in ctx [:parameters :query :refresh]) (rd/discover-network)) {:href (co/make-link ctx) :devices (for [[k v] (rd/remote-devices-and-names nil)] {:device-id (str k) :device-name v :href (co/make-link ctx (str (:uri (:request ctx)) "/" k))})}))}}})) (defn device-summary [local-device-id device-id] (-> (b/remote-object-properties local-device-id device-id [:device device-id] [:description :vendor-identifier :vendor-name :object-name :model-name]) (first) (dissoc :object-identifier) (cs/rename-keys {:object-name :device-name}) (assoc :device-id (str device-id)))) (def device (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:get {:summary "Device info" :parameters {:path {:device-id Long}} :description "A few properties and values for the given device-id." :swagger/tags ["BACnet"] :response (fn [ctx] (let [device-id (some-> ctx :parameters :path :device-id)] (co/with-bacnet-device ctx nil (assoc (device-summary nil device-id) :href (co/make-link ctx) :objects {:href (co/make-link ctx (str (:uri (:request ctx)) "/objects"))}))))}}})) (defn get-object-quantity [local-device-id device-id] (-> (b/remote-object-properties local-device-id device-id [:device device-id] [[:object-list 0]]) first :object-list)) ; TODO: use co/paginated-object-list instead (defn paginated-object-list "Return a collection of object maps. Each one has, in addition to the given properties, the :object-id, :object-type and :object-instance. If no properties are given, only retrieve the name." ([local-device-id device-id] (paginated-object-list local-device-id device-id nil 20 1)) ([local-device-id device-id desired-properties limit page] (let [obj-qty (get-object-quantity local-device-id device-id) all-array-indexes (range 1 (inc obj-qty)) cursor-pos (* limit (dec page)) after-cursor (drop cursor-pos all-array-indexes) remaining? (> (count after-cursor) limit) desired-array (for [i (take limit after-cursor)] [:object-list i]) get-prop-fn (fn [obj-ids props] (b/remote-object-properties local-device-id device-id obj-ids props)) object-identifiers (-> (if (> obj-qty limit) (get-prop-fn [:device device-id] desired-array) (get-prop-fn [:device device-id] :object-list)) first :object-list)] (when object-identifiers {:objects (for [raw-obj-map (get-prop-fn object-identifiers (or desired-properties :object-name))] (-> raw-obj-map (assoc :device-id (str device-id)) (co/prepare-obj-map))) :limit limit :next-page (when remaining? (inc page)) :current-page page :previous-page (when (> page 1) (dec page))})))) (defn get-object-properties "Get and prepare the object properties." [device-id obj-id properties] (-> (b/remote-object-properties nil device-id (co/obj-id-to-object-identifier obj-id) (or properties :all)) (first) (co/prepare-obj-map) (assoc :device-id (str device-id)))) (defn clean-errors "Remove the objects that can't be transmitted by the API." [b-error] (if (map? b-error) (->> (for [[k v] b-error] [k (dissoc v :apdu-error :timeout-error)]) (into {})) b-error)) (def objects (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:post {:summary "New object" :description (str "Create a new BACnet object. It is possible to give an object ID, but it is " "suggested to rather give the object-type and let the remote device handle " "the object-instance itself.\n\n" "The object-type can be the integer value or the keyword. " "(Ex: \"0\" or \"analog-input\" for an analog input)\n\n" "It is possible to give additional properties (such as object-name).") :swagger/tags ["BACnet"] :parameters {:path {:device-id Long} :body co/BACnetObject} :response (fn [ctx] (let [body (get-in ctx [:parameters :body]) d-id (get-in ctx [:parameters :path :device-id])] (when body (co/with-bacnet-device ctx nil (let [clean-body (co/clean-bacnet-object body) o-id (:object-id clean-body) object-identifier (or (:object-identifier clean-body) (when o-id (co/obj-id-to-object-identifier o-id))) obj-map (-> clean-body (dissoc :object-id) (assoc :object-identifier object-identifier)) result (rd/create-remote-object! nil d-id obj-map)] (if-let [success (:success result)] (let [o-identifier (get success :object-identifier) new-o-id (co/object-identifier-to-obj-id o-identifier)] (-> (get-object-properties d-id new-o-id nil) (assoc :href (co/make-link ctx (str (:uri (:request ctx)) "/" new-o-id))))) (merge (:response ctx) {:status 500 :body (clean-errors result)})))))))} :get {:parameters {:path {:device-id Long} :query {(s/optional-key :limit) (rs/field Long {:description "Maximum number of objects per page."}) (s/optional-key :page) Long (s/optional-key :properties) (rs/field [s/Keyword] {:description "List of wanted properties."})}} :summary "Objects list, optionally with all their properties." :description (str "List of all known objects for a given device." "\n\n" "Unless specified, the page will default to 1 and limit to 50 objects.") :swagger/tags ["BACnet"] :response (fn [ctx] (let [device-id (some-> ctx :parameters :path :device-id) limit (or (some-> ctx :parameters :query :limit) 50) page (or (some-> ctx :parameters :query :page) 1) properties (some-> ctx :parameters :query :properties)] (co/with-bacnet-device ctx nil (let [p-o-l (paginated-object-list nil device-id properties limit page) {:keys [next-page previous-page current-page objects]} p-o-l] (merge {:device {:href (co/make-link ctx (string/replace (:uri (:request ctx)) "/objects" ""))} :objects (for [o objects] (assoc o :href (co/make-link ctx (str (:uri (:request ctx)) "/" (:object-id o))))) :href (co/make-page-link ctx current-page limit)} (when-let [l (co/make-page-link ctx next-page limit)] {:next {:href l :page next-page}}) (when-let [l (co/make-page-link ctx previous-page limit)] {:previous {:href l :page previous-page}}))))))}}})) (def object (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:put {:summary "Update object" :description (str "Update object properties.\n\n The properties expected are of the form :" "\n" "{property-identifier1 property-value1, " "property-identifier2 property-value2}" "\n\n" "WARNING : you can specify the priority, but you should ONLY do so" " if you understand the consequences.") :swagger/tags ["BACnet"] :parameters {:path {:device-id Long :object-id String} :body {:properties co/PropertyValue (s/optional-key :priority) Long}} :response (fn [ctx] (let [device-id (get-in ctx [:parameters :path :device-id]) o-id (get-in ctx [:parameters :path :object-id]) properties (get-in ctx [:parameters :body :properties]) priority (get-in ctx [:parameters :body :priority] nil)] (co/with-bacnet-device ctx nil (let [write-access-spec {(co/obj-id-to-object-identifier o-id) (for [[k v] properties] [k (rd/advanced-property v priority nil)])}] (let [result (try (rd/set-remote-properties! nil device-id write-access-spec) (catch Exception e {:error (.getMessage e)}))] (if (:success result) result (merge (:response ctx) {:status 500 :body (clean-errors result)})))))))} :delete {:summary "Delete object" :description "Delete the given object." :swagger/tags ["BACnet"] :parameters {:path {:device-id Long :object-id String}} :response (fn [ctx] (let [device-id (get-in ctx [:parameters :path :device-id]) o-id (get-in ctx [:parameters :path :object-id])] (co/with-bacnet-device ctx nil (let [result (rd/delete-remote-object! nil device-id (co/obj-id-to-object-identifier o-id))] (if (:success result) result (merge (:response ctx) {:status 500 :body (clean-errors result)}))))))} :get {:parameters {:path {:device-id Long :object-id String} :query {(s/optional-key :properties) (rs/field [s/Keyword] {:description "List of wanted properties."})}} :summary "Object properties." :description (str "Return the object properties specified in the query parameter. " "If none is given, try to return all of them.") :swagger/tags ["BACnet"] :response (fn [ctx] (let [device-id (some-> ctx :parameters :path :device-id) obj-id (some-> ctx :parameters :path :object-id) properties (some-> ctx :parameters :query :properties)] (co/with-bacnet-device ctx nil (-> (get-object-properties device-id obj-id properties) (assoc :href (co/make-link ctx))))))}}})) (defn decode-global-id "Return a map containing useful info from the global-ids." [id] (let [items (string/split id #"\.") [d-id o-type o-inst] (map #(Integer/parseInt %) (take-last 3 items))] {:device-id d-id :object-type o-type :object-instance o-inst :object-identifier (->> [o-type o-inst] (c/clojure->bacnet :object-identifier) (c/bacnet->clojure)) :global-id id})) (defn get-properties "Get the requested properties in parallel for every devices." ([objects-maps] (get-properties objects-maps :all)) ([objects-maps properties] ;; first get retrieve the data from the remote devices... (let [by-devices (group-by :device-id objects-maps) result-map (->> (pmap (fn [[device-id objects]] [device-id (->> (for [result (b/remote-object-properties nil device-id (map :object-identifier objects) properties)] [(:object-identifier result) result]) (into {}))]) by-devices) (into {}))] ;; then we format it back into a map using the global ids as keys. (->> (for [obj objects-maps] [(:global-id obj) (-> (get-in result-map [(:device-id obj) (:object-identifier obj)]) (co/prepare-obj-map))]) (into {}))))) (def multi-objects (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:get {:summary "Multi object properties" :description (str "Retrieve the properties of multiple objects at the same time. " "A subset of properties can be returned by providing them in the optional " "'properties' field.\n\n The 'global-object-id' is the 'object-id' prepended " "with the 'device-id'." "\n\nExample: \"my-awesome.prefix.10122.3.3\"") :swagger/tags ["BACnet"] :parameters {:query {(s/optional-key :properties) (rs/field [s/Keyword] {:description "List of wanted properties."}) :global-object-ids [s/Str]}} :response (fn [ctx] (co/with-bacnet-device ctx nil (let [ids (get-in ctx [:parameters :query :global-object-ids]) properties (or (get-in ctx [:parameters :query :properties]) :all)] (get-properties (map decode-global-id ids) properties))))} }}))
null
https://raw.githubusercontent.com/Frozenlock/wacnet/4a4c21d423a9eeaaa70ec5c0ac4203a6978d3db9/src/clj/wacnet/api/bacnet/devices.clj
clojure
TODO: use co/paginated-object-list instead first get retrieve the data from the remote devices... then we format it back into a map using the global ids as keys.
(ns wacnet.api.bacnet.devices (:require [bacure.coerce :as c] [bacure.coerce.type.enumerated :as ce] [bacure.core :as b] [bacure.remote-device :as rd] [clojure.set :as cs] [clojure.string :as string] [ring.swagger.schema :as rs] [schema.core :as s] [wacnet.api.bacnet.common :as co] [yada.resource :refer [resource]])) (def devices-list (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:get {:summary "Devices list" :parameters {:query {(s/optional-key :refresh) (rs/field s/Bool {:description (str "Tries to find new devices on the network" " using a WhoIs broadcast.")})}} :description "The list of all known devices with an optional refresh." :swagger/tags ["BACnet"] :response (fn [ctx] (co/with-bacnet-device ctx nil (when (get-in ctx [:parameters :query :refresh]) (rd/discover-network)) {:href (co/make-link ctx) :devices (for [[k v] (rd/remote-devices-and-names nil)] {:device-id (str k) :device-name v :href (co/make-link ctx (str (:uri (:request ctx)) "/" k))})}))}}})) (defn device-summary [local-device-id device-id] (-> (b/remote-object-properties local-device-id device-id [:device device-id] [:description :vendor-identifier :vendor-name :object-name :model-name]) (first) (dissoc :object-identifier) (cs/rename-keys {:object-name :device-name}) (assoc :device-id (str device-id)))) (def device (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:get {:summary "Device info" :parameters {:path {:device-id Long}} :description "A few properties and values for the given device-id." :swagger/tags ["BACnet"] :response (fn [ctx] (let [device-id (some-> ctx :parameters :path :device-id)] (co/with-bacnet-device ctx nil (assoc (device-summary nil device-id) :href (co/make-link ctx) :objects {:href (co/make-link ctx (str (:uri (:request ctx)) "/objects"))}))))}}})) (defn get-object-quantity [local-device-id device-id] (-> (b/remote-object-properties local-device-id device-id [:device device-id] [[:object-list 0]]) first :object-list)) (defn paginated-object-list "Return a collection of object maps. Each one has, in addition to the given properties, the :object-id, :object-type and :object-instance. If no properties are given, only retrieve the name." ([local-device-id device-id] (paginated-object-list local-device-id device-id nil 20 1)) ([local-device-id device-id desired-properties limit page] (let [obj-qty (get-object-quantity local-device-id device-id) all-array-indexes (range 1 (inc obj-qty)) cursor-pos (* limit (dec page)) after-cursor (drop cursor-pos all-array-indexes) remaining? (> (count after-cursor) limit) desired-array (for [i (take limit after-cursor)] [:object-list i]) get-prop-fn (fn [obj-ids props] (b/remote-object-properties local-device-id device-id obj-ids props)) object-identifiers (-> (if (> obj-qty limit) (get-prop-fn [:device device-id] desired-array) (get-prop-fn [:device device-id] :object-list)) first :object-list)] (when object-identifiers {:objects (for [raw-obj-map (get-prop-fn object-identifiers (or desired-properties :object-name))] (-> raw-obj-map (assoc :device-id (str device-id)) (co/prepare-obj-map))) :limit limit :next-page (when remaining? (inc page)) :current-page page :previous-page (when (> page 1) (dec page))})))) (defn get-object-properties "Get and prepare the object properties." [device-id obj-id properties] (-> (b/remote-object-properties nil device-id (co/obj-id-to-object-identifier obj-id) (or properties :all)) (first) (co/prepare-obj-map) (assoc :device-id (str device-id)))) (defn clean-errors "Remove the objects that can't be transmitted by the API." [b-error] (if (map? b-error) (->> (for [[k v] b-error] [k (dissoc v :apdu-error :timeout-error)]) (into {})) b-error)) (def objects (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:post {:summary "New object" :description (str "Create a new BACnet object. It is possible to give an object ID, but it is " "suggested to rather give the object-type and let the remote device handle " "the object-instance itself.\n\n" "The object-type can be the integer value or the keyword. " "(Ex: \"0\" or \"analog-input\" for an analog input)\n\n" "It is possible to give additional properties (such as object-name).") :swagger/tags ["BACnet"] :parameters {:path {:device-id Long} :body co/BACnetObject} :response (fn [ctx] (let [body (get-in ctx [:parameters :body]) d-id (get-in ctx [:parameters :path :device-id])] (when body (co/with-bacnet-device ctx nil (let [clean-body (co/clean-bacnet-object body) o-id (:object-id clean-body) object-identifier (or (:object-identifier clean-body) (when o-id (co/obj-id-to-object-identifier o-id))) obj-map (-> clean-body (dissoc :object-id) (assoc :object-identifier object-identifier)) result (rd/create-remote-object! nil d-id obj-map)] (if-let [success (:success result)] (let [o-identifier (get success :object-identifier) new-o-id (co/object-identifier-to-obj-id o-identifier)] (-> (get-object-properties d-id new-o-id nil) (assoc :href (co/make-link ctx (str (:uri (:request ctx)) "/" new-o-id))))) (merge (:response ctx) {:status 500 :body (clean-errors result)})))))))} :get {:parameters {:path {:device-id Long} :query {(s/optional-key :limit) (rs/field Long {:description "Maximum number of objects per page."}) (s/optional-key :page) Long (s/optional-key :properties) (rs/field [s/Keyword] {:description "List of wanted properties."})}} :summary "Objects list, optionally with all their properties." :description (str "List of all known objects for a given device." "\n\n" "Unless specified, the page will default to 1 and limit to 50 objects.") :swagger/tags ["BACnet"] :response (fn [ctx] (let [device-id (some-> ctx :parameters :path :device-id) limit (or (some-> ctx :parameters :query :limit) 50) page (or (some-> ctx :parameters :query :page) 1) properties (some-> ctx :parameters :query :properties)] (co/with-bacnet-device ctx nil (let [p-o-l (paginated-object-list nil device-id properties limit page) {:keys [next-page previous-page current-page objects]} p-o-l] (merge {:device {:href (co/make-link ctx (string/replace (:uri (:request ctx)) "/objects" ""))} :objects (for [o objects] (assoc o :href (co/make-link ctx (str (:uri (:request ctx)) "/" (:object-id o))))) :href (co/make-page-link ctx current-page limit)} (when-let [l (co/make-page-link ctx next-page limit)] {:next {:href l :page next-page}}) (when-let [l (co/make-page-link ctx previous-page limit)] {:previous {:href l :page previous-page}}))))))}}})) (def object (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:put {:summary "Update object" :description (str "Update object properties.\n\n The properties expected are of the form :" "\n" "{property-identifier1 property-value1, " "property-identifier2 property-value2}" "\n\n" "WARNING : you can specify the priority, but you should ONLY do so" " if you understand the consequences.") :swagger/tags ["BACnet"] :parameters {:path {:device-id Long :object-id String} :body {:properties co/PropertyValue (s/optional-key :priority) Long}} :response (fn [ctx] (let [device-id (get-in ctx [:parameters :path :device-id]) o-id (get-in ctx [:parameters :path :object-id]) properties (get-in ctx [:parameters :body :properties]) priority (get-in ctx [:parameters :body :priority] nil)] (co/with-bacnet-device ctx nil (let [write-access-spec {(co/obj-id-to-object-identifier o-id) (for [[k v] properties] [k (rd/advanced-property v priority nil)])}] (let [result (try (rd/set-remote-properties! nil device-id write-access-spec) (catch Exception e {:error (.getMessage e)}))] (if (:success result) result (merge (:response ctx) {:status 500 :body (clean-errors result)})))))))} :delete {:summary "Delete object" :description "Delete the given object." :swagger/tags ["BACnet"] :parameters {:path {:device-id Long :object-id String}} :response (fn [ctx] (let [device-id (get-in ctx [:parameters :path :device-id]) o-id (get-in ctx [:parameters :path :object-id])] (co/with-bacnet-device ctx nil (let [result (rd/delete-remote-object! nil device-id (co/obj-id-to-object-identifier o-id))] (if (:success result) result (merge (:response ctx) {:status 500 :body (clean-errors result)}))))))} :get {:parameters {:path {:device-id Long :object-id String} :query {(s/optional-key :properties) (rs/field [s/Keyword] {:description "List of wanted properties."})}} :summary "Object properties." :description (str "Return the object properties specified in the query parameter. " "If none is given, try to return all of them.") :swagger/tags ["BACnet"] :response (fn [ctx] (let [device-id (some-> ctx :parameters :path :device-id) obj-id (some-> ctx :parameters :path :object-id) properties (some-> ctx :parameters :query :properties)] (co/with-bacnet-device ctx nil (-> (get-object-properties device-id obj-id properties) (assoc :href (co/make-link ctx))))))}}})) (defn decode-global-id "Return a map containing useful info from the global-ids." [id] (let [items (string/split id #"\.") [d-id o-type o-inst] (map #(Integer/parseInt %) (take-last 3 items))] {:device-id d-id :object-type o-type :object-instance o-inst :object-identifier (->> [o-type o-inst] (c/clojure->bacnet :object-identifier) (c/bacnet->clojure)) :global-id id})) (defn get-properties "Get the requested properties in parallel for every devices." ([objects-maps] (get-properties objects-maps :all)) ([objects-maps properties] (let [by-devices (group-by :device-id objects-maps) result-map (->> (pmap (fn [[device-id objects]] [device-id (->> (for [result (b/remote-object-properties nil device-id (map :object-identifier objects) properties)] [(:object-identifier result) result]) (into {}))]) by-devices) (into {}))] (->> (for [obj objects-maps] [(:global-id obj) (-> (get-in result-map [(:device-id obj) (:object-identifier obj)]) (co/prepare-obj-map))]) (into {}))))) (def multi-objects (resource {:produces [{:media-type co/produced-types :charset "UTF-8"}] :consumes [{:media-type co/consumed-types :charset "UTF-8"}] :access-control {:allow-origin "*"} :methods {:get {:summary "Multi object properties" :description (str "Retrieve the properties of multiple objects at the same time. " "A subset of properties can be returned by providing them in the optional " "'properties' field.\n\n The 'global-object-id' is the 'object-id' prepended " "with the 'device-id'." "\n\nExample: \"my-awesome.prefix.10122.3.3\"") :swagger/tags ["BACnet"] :parameters {:query {(s/optional-key :properties) (rs/field [s/Keyword] {:description "List of wanted properties."}) :global-object-ids [s/Str]}} :response (fn [ctx] (co/with-bacnet-device ctx nil (let [ids (get-in ctx [:parameters :query :global-object-ids]) properties (or (get-in ctx [:parameters :query :properties]) :all)] (get-properties (map decode-global-id ids) properties))))} }}))
cb65352a46c7fa07f30192b6b5379b8593f6b28b409c478bac6a69376047c2fa
emilaxelsson/ag-graph
TypeFam.hs
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # module PAG.Projection.TypeFam (pr, (:<),module PAG.Product) where import Prelude hiding (Either (..)) import PAG.Product -- | Path to a node in a binary tree. data Pos = Here | Left Pos | Right Pos -- | Result of searching for a unique occurrence of a node in a binary tree. data RPos = NotFound | Ambiguous | Found Pos | Reconciling search results of two subtrees . -- 'Ambiguous' is the absorptive (dominant) element. ' NotFound ' is the identity ( neutral ) element . -- If element was 'Found' it both subtrees, the result is 'Ambiguous'. type family Ch (l :: RPos) (r :: RPos) :: RPos where Ch (Found x) (Found y) = Ambiguous Ch Ambiguous y = Ambiguous Ch x Ambiguous = Ambiguous Ch (Found x) y = Found (Left x) Ch x (Found y) = Found (Right y) Ch x y = NotFound -- | @Elem e p@ searches for type @e@ in a nested tuple type @p@ -- returning a path to its location if successful. type family Elem (e :: * -> *) p :: RPos where Elem e e = Found Here Elem e (l :*: r) = Ch (Elem e l) (Elem e r) Elem e p = NotFound | @Pointer pos e p@ holds if result @pos@ points to subtree @e@ in @p@. data Pointer (pos :: RPos) (e :: * -> *) (p :: * -> *) where Phere :: Pointer (Found Here) e e Pleft :: Pointer (Found pos) e p -> Pointer (Found (Left pos)) e (p :*: p') Pright :: Pointer (Found pos) e p -> Pointer (Found (Right pos)) e (p' :*: p) -- | @pr' path p@ extracts subtree @e@ pointed to by @path@ in tree @p@. pr' :: Pointer pos e p -> p i -> e i pr' Phere e = e pr' (Pleft p) (x :*: _) = pr' p x pr' (Pright p) (_ :*: y) = pr' p y -- | A class to automatically construct valid pathes. class GetPointer (pos :: RPos) (e :: * -> *) (p :: * -> *) where pointer :: Pointer pos e p instance GetPointer (Found Here) e e where pointer = Phere instance GetPointer (Found pos) e p => GetPointer (Found (Left pos)) e (p :*: p') where pointer = Pleft pointer instance GetPointer (Found pos) e p => GetPointer (Found (Right pos)) e (p' :*: p) where pointer = Pright pointer type (:<) (e :: * -> *) (p :: * -> *) = GetPointer (Elem e p) e p | If @e@ is a part of type @p@ , witnessed by constraint @e : < p@ , -- project out the corresponding value. pr :: forall e p i . (e :< p) => p i -> e i pr p = pr' (pointer :: Pointer (Elem e p) e p) p
null
https://raw.githubusercontent.com/emilaxelsson/ag-graph/50fb1ebb819e1ed0bd3b97e8a9f82bb9310e782f/src/PAG/Projection/TypeFam.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeOperators # | Path to a node in a binary tree. | Result of searching for a unique occurrence of a node in a binary tree. 'Ambiguous' is the absorptive (dominant) element. If element was 'Found' it both subtrees, the result is 'Ambiguous'. | @Elem e p@ searches for type @e@ in a nested tuple type @p@ returning a path to its location if successful. | @pr' path p@ extracts subtree @e@ pointed to by @path@ in tree @p@. | A class to automatically construct valid pathes. project out the corresponding value.
# LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module PAG.Projection.TypeFam (pr, (:<),module PAG.Product) where import Prelude hiding (Either (..)) import PAG.Product data Pos = Here | Left Pos | Right Pos data RPos = NotFound | Ambiguous | Found Pos | Reconciling search results of two subtrees . ' NotFound ' is the identity ( neutral ) element . type family Ch (l :: RPos) (r :: RPos) :: RPos where Ch (Found x) (Found y) = Ambiguous Ch Ambiguous y = Ambiguous Ch x Ambiguous = Ambiguous Ch (Found x) y = Found (Left x) Ch x (Found y) = Found (Right y) Ch x y = NotFound type family Elem (e :: * -> *) p :: RPos where Elem e e = Found Here Elem e (l :*: r) = Ch (Elem e l) (Elem e r) Elem e p = NotFound | @Pointer pos e p@ holds if result @pos@ points to subtree @e@ in @p@. data Pointer (pos :: RPos) (e :: * -> *) (p :: * -> *) where Phere :: Pointer (Found Here) e e Pleft :: Pointer (Found pos) e p -> Pointer (Found (Left pos)) e (p :*: p') Pright :: Pointer (Found pos) e p -> Pointer (Found (Right pos)) e (p' :*: p) pr' :: Pointer pos e p -> p i -> e i pr' Phere e = e pr' (Pleft p) (x :*: _) = pr' p x pr' (Pright p) (_ :*: y) = pr' p y class GetPointer (pos :: RPos) (e :: * -> *) (p :: * -> *) where pointer :: Pointer pos e p instance GetPointer (Found Here) e e where pointer = Phere instance GetPointer (Found pos) e p => GetPointer (Found (Left pos)) e (p :*: p') where pointer = Pleft pointer instance GetPointer (Found pos) e p => GetPointer (Found (Right pos)) e (p' :*: p) where pointer = Pright pointer type (:<) (e :: * -> *) (p :: * -> *) = GetPointer (Elem e p) e p | If @e@ is a part of type @p@ , witnessed by constraint @e : < p@ , pr :: forall e p i . (e :< p) => p i -> e i pr p = pr' (pointer :: Pointer (Elem e p) e p) p
19e5e4491232a56f60ad81c32b6af30f308f2479e11df92d6a51478f46dea32c
Leberwurscht/Diaspora-User-Directory
packet.ml
(************************************************************************) This file is part of SKS . SKS 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (***********************************************************************) * Type definitions and simple functions related to PGP packets open Printf type ptype = | Reserved | Public_Key_Encrypted_Session_Key_Packet | Signature_Packet | Symmetric_Key_Encrypted_Session_Key_Packet | One_Pass_Signature_Packet | Secret_Key_Packet | Public_Key_Packet | Secret_Subkey_Packet | Compressed_Data_Packet | Symmetrically_Encrypted_Data_Packet | Marker_Packet | Literal_Data_Packet | Trust_Packet | User_ID_Packet | User_Attribute_Packet | Sym_Encrypted_and_Integrity_Protected_Data_Packet | Modification_Detection_Code_Packet | Public_Subkey_Packet | Private_or_Experimental_ptype | Unexpected_ptype type packet = { content_tag: int; packet_type: ptype; packet_length: int; packet_body: string; } type sigsubpacket = { ssp_length: int; ssp_type: int; ssp_body: string; } let ssp_type_to_string i = match i with | 2 -> "signature creation time" | 3 -> "signature expiration time" | 4 -> "exportable certification" | 5 -> "trust signature" | 6 -> "regular expression" | 7 -> "revocable" | 9 -> "key expiration time" | 10 -> "placeholder for backward compatibility" | 11 -> "preferred symmetric algorithms" | 12 -> "revocation key" | 16 -> "issuer key ID" | 20 -> "notation data" | 21 -> "preferred hash algorithms" | 22 -> "preferred compression algorithms" | 23 -> "key server preferences" | 24 -> "preferred key server" | 25 -> "primary user id" | 26 -> "policy URL" | 27 -> "key flags" | 28 -> "signer's user id" | 29 -> "reason for revocation" | x when x >= 100 && x <= 110 -> "internal or user-defined" | _ -> failwith "Unexpected sigsubpacket type" type key = packet list let sigtype_to_string sigtype = match sigtype with | 0x00 -> "signature of binary document" | 0x01 -> "signature of canonical text document" | 0x02 -> "Standalone signature" | 0x10 -> "Generic certification of a User ID and Public Key packet" | 0x11 -> "Persona certification of a User ID and Public Key packet" | 0x12 -> "Casual certification of a User ID and Public Key packet" | 0x13 -> "Positive certification of a User ID and Public Key packet" | 0x18 -> "Subkey Binding Signature" | 0x1F -> "Signature directly on a key" | 0x20 -> "Key revocation signature" | 0x28 -> "Subkey revocation signature" | 0x30 -> "Certification revocation signature" | 0x40 -> "Timestamp signature" | _ -> "UNEXPECTED SIGTYPE" let content_tag_to_ptype tag = match tag with | 0 -> Reserved | 1 -> Public_Key_Encrypted_Session_Key_Packet | 2 -> Signature_Packet | 3 -> Symmetric_Key_Encrypted_Session_Key_Packet | 4 -> One_Pass_Signature_Packet | 5 -> Secret_Key_Packet | 6 -> Public_Key_Packet | 7 -> Secret_Subkey_Packet | 8 -> Compressed_Data_Packet | 9 -> Symmetrically_Encrypted_Data_Packet | 10 -> Marker_Packet | 11 -> Literal_Data_Packet | 12 -> Trust_Packet | 13 -> User_ID_Packet | 14 -> Public_Subkey_Packet | 17 -> User_Attribute_Packet | 18 -> Sym_Encrypted_and_Integrity_Protected_Data_Packet | 19 -> Modification_Detection_Code_Packet | 60 | 61 | 62 | 63 -> Private_or_Experimental_ptype | _ -> Unexpected_ptype let ptype_to_string ptype = match ptype with | Reserved -> "Reserved - a packet tag must not have this value" | Public_Key_Encrypted_Session_Key_Packet -> "Public-Key Encrypted Session Key Packet" | Signature_Packet -> "Signature Packet" | Symmetric_Key_Encrypted_Session_Key_Packet -> "Symmetric-Key Encrypted Session Key Packet" | One_Pass_Signature_Packet -> "One-Pass Signature Packet" | Secret_Key_Packet -> "Secret Key Packet" | Public_Key_Packet -> "Public Key Packet" | Secret_Subkey_Packet -> "Secret Subkey Packet" | Compressed_Data_Packet -> "Compressed Data Packet" | Symmetrically_Encrypted_Data_Packet -> "Symmetrically Encrypted Data Packet" | Marker_Packet -> "Marker Packet" | Literal_Data_Packet -> "Literal Data Packet" | Trust_Packet -> "Trust Packet" | User_ID_Packet -> "User ID Packet" | Public_Subkey_Packet -> "Public Subkey Packet" | User_Attribute_Packet -> "User Attribute Packet" | Sym_Encrypted_and_Integrity_Protected_Data_Packet -> "Sym Encrypted and Integrity Protected Data Packet" | Modification_Detection_Code_Packet -> "Modification Detection Code Packet" | Private_or_Experimental_ptype -> "Private or Experimental Values" | Unexpected_ptype -> "Unexpected value" type mpi = { mpi_bits: int; mpi_data: string; } let pubkey_algorithm_string i = match i with | 1 -> "RSA (Encrypt or Sign)" | 2 -> "RSA Encrypt-Only" | 3 -> "RSA Sign-Only" | 16 -> "Elgamal (Encrypt-Only), see [ELGAMAL]" | 17 -> "DSA (Digital Signature Standard)" | 18 -> "Reserved for Elliptic Curve" | 19 -> "Reserved for ECDSA" | 20 -> "Elgamal (Encrypt or Sign)" | 21 -> "Reserved for Diffie-Hellman (X9.42) as defined for IETF-S/MIME" | x when x >= 100 && x <= 110 -> "Private/Experimental algorithm." | _ -> "Unknown Public Key Algorithm" type pubkeyinfo = { pk_version: int; pk_ctime: int64; pk_expiration: int option; pk_alg: int; pk_keylen: int; } type sigtype = | Signature_of_a_binary_document | Signature_of_a_canonical_text_document | Standalone_signature | Generic_certification_of_a_User_ID_and_Public_Key_packet | Persona_certification_of_a_User_ID_and_Public_Key_packet | Casual_certification_of_a_User_ID_and_Public_Key_packet | Positive_certification_of_a_User_ID_and_Public_Key_packet | Subkey_Binding_Signature | Signature_directly_on_a_key | Key_revocation_signature | Subkey_revocation_signature | Certification_revocation_signature | Timestamp_signature | Unexpected_sigtype type v3sig = { v3s_sigtype: int; v3s_ctime: int64; v3s_keyid: string; v3s_pk_alg: int; v3s_hash_alg: int; v3s_hash_value: string; v3s_mpis: mpi list; } type v4sig = { v4s_sigtype: int; v4s_pk_alg: int; v4s_hashed_subpackets: sigsubpacket list; v4s_unhashed_subpackets: sigsubpacket list; v4s_hash_value: string; v4s_mpis: mpi list; } type signature = V3sig of v3sig | V4sig of v4sig let int_to_sigtype byte = match byte with | 0x00 -> Signature_of_a_binary_document | 0x01 -> Signature_of_a_canonical_text_document | 0x02 -> Standalone_signature | 0x10 -> Generic_certification_of_a_User_ID_and_Public_Key_packet | 0x11 -> Persona_certification_of_a_User_ID_and_Public_Key_packet | 0x12 -> Casual_certification_of_a_User_ID_and_Public_Key_packet | 0x13 -> Positive_certification_of_a_User_ID_and_Public_Key_packet | 0x18 -> Subkey_Binding_Signature | 0x1F -> Signature_directly_on_a_key | 0x20 -> Key_revocation_signature | 0x28 -> Subkey_revocation_signature | 0x30 -> Certification_revocation_signature | 0x40 -> Timestamp_signature | _ -> Unexpected_sigtype let content_tag_to_string tag = ptype_to_string (content_tag_to_ptype tag) let print_packet packet = printf "%s\n" (ptype_to_string packet.packet_type); printf "Length: %d\n" packet.packet_length; if packet.packet_type = User_ID_Packet then (print_string packet.packet_body; print_string "\n") (** write out new-style packet *) let write_packet_new packet cout = (* specify new packet format *) cout#write_byte (packet.content_tag lor 0xC0); cout#write_byte 0xFF; cout#write_int packet.packet_length; cout#write_string packet.packet_body let pk_alg_to_ident i = match i with RSA sign and encrypt RSA encrypt RSA sign encrypt sign and encrypt DSA NoClue (** writes out packet, using old-style packets when possible *) let write_packet_old packet cout = if packet.content_tag >= 16 then (* write new-style packet *) write_packet_new packet cout else (* write old-style packet *) begin let length_type = if packet.packet_length < 256 then 0 else if packet.packet_length < 65536 then 1 else 2 in cout#write_byte ((packet.content_tag lsl 2) lor 0x80 lor length_type); (match length_type with 0 -> cout#write_byte packet.packet_length | 1 -> cout#write_byte ((packet.packet_length lsr 8) land 0xFF); cout#write_byte (packet.packet_length land 0xFF); | 2 -> cout#write_byte ((packet.packet_length lsr 24) land 0xFF); cout#write_byte ((packet.packet_length lsr 16) land 0xFF); cout#write_byte ((packet.packet_length lsr 8) land 0xFF); cout#write_byte (packet.packet_length land 0xFF); | _ -> failwith "Packet.write_packet_old: Bug -- bad packet length" ); cout#write_string packet.packet_body end let write_packet = write_packet_old
null
https://raw.githubusercontent.com/Leberwurscht/Diaspora-User-Directory/1ca4a06a67d591760516edffddb0308b86b6314c/trie_manager/packet.ml
ocaml
********************************************************************** ********************************************************************* * write out new-style packet specify new packet format * writes out packet, using old-style packets when possible write new-style packet write old-style packet
This file is part of SKS . SKS 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) * Type definitions and simple functions related to PGP packets open Printf type ptype = | Reserved | Public_Key_Encrypted_Session_Key_Packet | Signature_Packet | Symmetric_Key_Encrypted_Session_Key_Packet | One_Pass_Signature_Packet | Secret_Key_Packet | Public_Key_Packet | Secret_Subkey_Packet | Compressed_Data_Packet | Symmetrically_Encrypted_Data_Packet | Marker_Packet | Literal_Data_Packet | Trust_Packet | User_ID_Packet | User_Attribute_Packet | Sym_Encrypted_and_Integrity_Protected_Data_Packet | Modification_Detection_Code_Packet | Public_Subkey_Packet | Private_or_Experimental_ptype | Unexpected_ptype type packet = { content_tag: int; packet_type: ptype; packet_length: int; packet_body: string; } type sigsubpacket = { ssp_length: int; ssp_type: int; ssp_body: string; } let ssp_type_to_string i = match i with | 2 -> "signature creation time" | 3 -> "signature expiration time" | 4 -> "exportable certification" | 5 -> "trust signature" | 6 -> "regular expression" | 7 -> "revocable" | 9 -> "key expiration time" | 10 -> "placeholder for backward compatibility" | 11 -> "preferred symmetric algorithms" | 12 -> "revocation key" | 16 -> "issuer key ID" | 20 -> "notation data" | 21 -> "preferred hash algorithms" | 22 -> "preferred compression algorithms" | 23 -> "key server preferences" | 24 -> "preferred key server" | 25 -> "primary user id" | 26 -> "policy URL" | 27 -> "key flags" | 28 -> "signer's user id" | 29 -> "reason for revocation" | x when x >= 100 && x <= 110 -> "internal or user-defined" | _ -> failwith "Unexpected sigsubpacket type" type key = packet list let sigtype_to_string sigtype = match sigtype with | 0x00 -> "signature of binary document" | 0x01 -> "signature of canonical text document" | 0x02 -> "Standalone signature" | 0x10 -> "Generic certification of a User ID and Public Key packet" | 0x11 -> "Persona certification of a User ID and Public Key packet" | 0x12 -> "Casual certification of a User ID and Public Key packet" | 0x13 -> "Positive certification of a User ID and Public Key packet" | 0x18 -> "Subkey Binding Signature" | 0x1F -> "Signature directly on a key" | 0x20 -> "Key revocation signature" | 0x28 -> "Subkey revocation signature" | 0x30 -> "Certification revocation signature" | 0x40 -> "Timestamp signature" | _ -> "UNEXPECTED SIGTYPE" let content_tag_to_ptype tag = match tag with | 0 -> Reserved | 1 -> Public_Key_Encrypted_Session_Key_Packet | 2 -> Signature_Packet | 3 -> Symmetric_Key_Encrypted_Session_Key_Packet | 4 -> One_Pass_Signature_Packet | 5 -> Secret_Key_Packet | 6 -> Public_Key_Packet | 7 -> Secret_Subkey_Packet | 8 -> Compressed_Data_Packet | 9 -> Symmetrically_Encrypted_Data_Packet | 10 -> Marker_Packet | 11 -> Literal_Data_Packet | 12 -> Trust_Packet | 13 -> User_ID_Packet | 14 -> Public_Subkey_Packet | 17 -> User_Attribute_Packet | 18 -> Sym_Encrypted_and_Integrity_Protected_Data_Packet | 19 -> Modification_Detection_Code_Packet | 60 | 61 | 62 | 63 -> Private_or_Experimental_ptype | _ -> Unexpected_ptype let ptype_to_string ptype = match ptype with | Reserved -> "Reserved - a packet tag must not have this value" | Public_Key_Encrypted_Session_Key_Packet -> "Public-Key Encrypted Session Key Packet" | Signature_Packet -> "Signature Packet" | Symmetric_Key_Encrypted_Session_Key_Packet -> "Symmetric-Key Encrypted Session Key Packet" | One_Pass_Signature_Packet -> "One-Pass Signature Packet" | Secret_Key_Packet -> "Secret Key Packet" | Public_Key_Packet -> "Public Key Packet" | Secret_Subkey_Packet -> "Secret Subkey Packet" | Compressed_Data_Packet -> "Compressed Data Packet" | Symmetrically_Encrypted_Data_Packet -> "Symmetrically Encrypted Data Packet" | Marker_Packet -> "Marker Packet" | Literal_Data_Packet -> "Literal Data Packet" | Trust_Packet -> "Trust Packet" | User_ID_Packet -> "User ID Packet" | Public_Subkey_Packet -> "Public Subkey Packet" | User_Attribute_Packet -> "User Attribute Packet" | Sym_Encrypted_and_Integrity_Protected_Data_Packet -> "Sym Encrypted and Integrity Protected Data Packet" | Modification_Detection_Code_Packet -> "Modification Detection Code Packet" | Private_or_Experimental_ptype -> "Private or Experimental Values" | Unexpected_ptype -> "Unexpected value" type mpi = { mpi_bits: int; mpi_data: string; } let pubkey_algorithm_string i = match i with | 1 -> "RSA (Encrypt or Sign)" | 2 -> "RSA Encrypt-Only" | 3 -> "RSA Sign-Only" | 16 -> "Elgamal (Encrypt-Only), see [ELGAMAL]" | 17 -> "DSA (Digital Signature Standard)" | 18 -> "Reserved for Elliptic Curve" | 19 -> "Reserved for ECDSA" | 20 -> "Elgamal (Encrypt or Sign)" | 21 -> "Reserved for Diffie-Hellman (X9.42) as defined for IETF-S/MIME" | x when x >= 100 && x <= 110 -> "Private/Experimental algorithm." | _ -> "Unknown Public Key Algorithm" type pubkeyinfo = { pk_version: int; pk_ctime: int64; pk_expiration: int option; pk_alg: int; pk_keylen: int; } type sigtype = | Signature_of_a_binary_document | Signature_of_a_canonical_text_document | Standalone_signature | Generic_certification_of_a_User_ID_and_Public_Key_packet | Persona_certification_of_a_User_ID_and_Public_Key_packet | Casual_certification_of_a_User_ID_and_Public_Key_packet | Positive_certification_of_a_User_ID_and_Public_Key_packet | Subkey_Binding_Signature | Signature_directly_on_a_key | Key_revocation_signature | Subkey_revocation_signature | Certification_revocation_signature | Timestamp_signature | Unexpected_sigtype type v3sig = { v3s_sigtype: int; v3s_ctime: int64; v3s_keyid: string; v3s_pk_alg: int; v3s_hash_alg: int; v3s_hash_value: string; v3s_mpis: mpi list; } type v4sig = { v4s_sigtype: int; v4s_pk_alg: int; v4s_hashed_subpackets: sigsubpacket list; v4s_unhashed_subpackets: sigsubpacket list; v4s_hash_value: string; v4s_mpis: mpi list; } type signature = V3sig of v3sig | V4sig of v4sig let int_to_sigtype byte = match byte with | 0x00 -> Signature_of_a_binary_document | 0x01 -> Signature_of_a_canonical_text_document | 0x02 -> Standalone_signature | 0x10 -> Generic_certification_of_a_User_ID_and_Public_Key_packet | 0x11 -> Persona_certification_of_a_User_ID_and_Public_Key_packet | 0x12 -> Casual_certification_of_a_User_ID_and_Public_Key_packet | 0x13 -> Positive_certification_of_a_User_ID_and_Public_Key_packet | 0x18 -> Subkey_Binding_Signature | 0x1F -> Signature_directly_on_a_key | 0x20 -> Key_revocation_signature | 0x28 -> Subkey_revocation_signature | 0x30 -> Certification_revocation_signature | 0x40 -> Timestamp_signature | _ -> Unexpected_sigtype let content_tag_to_string tag = ptype_to_string (content_tag_to_ptype tag) let print_packet packet = printf "%s\n" (ptype_to_string packet.packet_type); printf "Length: %d\n" packet.packet_length; if packet.packet_type = User_ID_Packet then (print_string packet.packet_body; print_string "\n") let write_packet_new packet cout = cout#write_byte (packet.content_tag lor 0xC0); cout#write_byte 0xFF; cout#write_int packet.packet_length; cout#write_string packet.packet_body let pk_alg_to_ident i = match i with RSA sign and encrypt RSA encrypt RSA sign encrypt sign and encrypt DSA NoClue let write_packet_old packet cout = if packet.content_tag >= 16 write_packet_new packet cout begin let length_type = if packet.packet_length < 256 then 0 else if packet.packet_length < 65536 then 1 else 2 in cout#write_byte ((packet.content_tag lsl 2) lor 0x80 lor length_type); (match length_type with 0 -> cout#write_byte packet.packet_length | 1 -> cout#write_byte ((packet.packet_length lsr 8) land 0xFF); cout#write_byte (packet.packet_length land 0xFF); | 2 -> cout#write_byte ((packet.packet_length lsr 24) land 0xFF); cout#write_byte ((packet.packet_length lsr 16) land 0xFF); cout#write_byte ((packet.packet_length lsr 8) land 0xFF); cout#write_byte (packet.packet_length land 0xFF); | _ -> failwith "Packet.write_packet_old: Bug -- bad packet length" ); cout#write_string packet.packet_body end let write_packet = write_packet_old
58166a48ee3610d74c8652d54622024956fcf59d5304b57e0f437910339638de
liquidz/antq
core_test.clj
(ns antq.core-test (:require [antq.changelog :as changelog] [antq.core :as sut] [antq.record :as r] [antq.util.dep :as u.dep] [antq.util.exception :as u.ex] [antq.util.git :as u.git] [antq.ver :as ver] [clojure.string :as str] [clojure.test :as t] [clojure.tools.cli :as cli])) (defmethod ver/get-sorted-versions :test [_ _] ["3.0.0" "2.0.0" "1.0.0"]) (def ^:private test-parse-opts #(cli/parse-opts % sut/cli-options)) (t/deftest cli-options-test (t/testing "default options" (t/is (= {:exclude [] :focus [] :directory ["."] :skip [] :error-format nil :reporter "table"} (:options (test-parse-opts []))))) (t/testing "--exclude" (t/is (= ["ex/ex1" "ex/ex2" "ex/ex3" "ex/ex4@1.0.0" "ex/ex5@2.0.0" "ex/ex6@3.0.0"] (get-in (test-parse-opts ["--exclude=ex/ex1" "--exclude=ex/ex2:ex/ex3" "--exclude=ex/ex4@1.0.0" "--exclude=ex/ex5@2.0.0:ex/ex6@3.0.0"]) [:options :exclude])))) (t/testing "--focus" (t/is (= ["fo/cus1" "fo/cus2" "fo/cus3"] (get-in (test-parse-opts ["--focus=fo/cus1" "--focus=fo/cus2:fo/cus3"]) [:options :focus])))) (t/testing "--directory" (t/is (= ["." "dir1" "dir2" "dir3" "dir4"] (get-in (test-parse-opts ["-d" "dir1" "--directory=dir2" "--directory" "dir3:dir4"]) [:options :directory])))) (t/testing "--skip" (let [res (test-parse-opts ["--skip" "boot" "--skip=clojure-cli"])] (t/is (= ["boot" "clojure-cli"] (get-in res [:options :skip]))) (t/is (nil? (:errors res)))) (t/testing "validation error" (let [res (test-parse-opts ["--skip=foo"])] (t/is (= [] (get-in res [:options :skip]))) (t/is (some? (:errors res)))))) (t/testing "--error-format" (t/is (= "foo" (get-in (test-parse-opts ["--error-format=foo"]) [:options :error-format])))) (t/testing "--reporter" (let [res (test-parse-opts ["--reporter=edn"])] (t/is (= "edn" (get-in res [:options :reporter]))) (t/is (nil? (:errors res)))) (t/testing "validation error" (let [res (test-parse-opts ["--reporter=foo"])] (t/is (= "table" (get-in res [:options :reporter]))) (t/is (some? (:errors res)))))) (t/testing "--upgrade" (t/is (true? (get-in (test-parse-opts ["--upgrade"]) [:options :upgrade])))) (t/testing "--no-diff" (t/is (true? (get-in (test-parse-opts ["--no-diff"]) [:options :no-diff]))))) (t/deftest skip-artifacts?-test (t/testing "default" (t/are [expected in] (= expected (sut/skip-artifacts? (r/map->Dependency {:name in}) {})) false "org.clojure/clojure" false "org.clojure/foo" false "foo/clojure" false "foo" false "foo/bar")) (t/testing "custom: exclude" (t/are [expected in] (= expected (sut/skip-artifacts? (r/map->Dependency {:name in}) {:exclude ["org.clojure/clojure" "org.clojure/foo" "foo"]})) true "org.clojure/clojure" true "org.clojure/foo" false "foo/clojure" true "foo" false "foo/bar")) (t/testing "custom: focus" (t/are [expected in] (= expected (sut/skip-artifacts? (r/map->Dependency {:name in}) {:focus ["org.clojure/clojure" "foo"]})) false "org.clojure/clojure" true "org.clojure/foo" true "foo/clojure" false "foo" true "foo/bar")) (t/testing "`focus` shoud be prefer than `exclude`" (t/is (false? (sut/skip-artifacts? (r/map->Dependency {:name "org.clojure/clojure"}) {:exclude ["org.clojure/clojure"] :focus ["org.clojure/clojure"]}))))) (t/deftest remove-skipping-versions-test (t/testing "there are no target to remove" (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {}))) (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@4"]})))) (t/testing "only dep's name is matched" (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo"]})))) (t/testing "only version number is matched" (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["bar@2"]})))) (t/testing "dep's name and version number are matched" (t/is (= ["1" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@2"]}))) (t/is (= ["1"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@2" "foo@3"]}))) (t/is (= [] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@1" "foo@2" "foo@3"]}))))) (t/deftest using-release-version?-test (t/are [expected in] (= expected (sut/using-release-version? (r/map->Dependency {:version in}))) true "RELEASE" true "master" true "main" true "latest" false "1.0.0" false "")) (defn- test-dep [m] (r/map->Dependency (merge {:type :test} m))) (t/deftest outdated-deps-test (let [deps [(test-dep {:name "alice" :version "1.0.0"}) (test-dep {:name "bob" :version "2.0.0"}) (test-dep {:name "charlie" :version "3.0.0"})]] (t/is (= [(test-dep {:name "alice" :version "1.0.0" :latest-version "3.0.0"}) (test-dep {:name "bob" :version "2.0.0" :latest-version "3.0.0"})] (sut/outdated-deps deps {}))) (t/testing "alice@3.0.0 should be excluded" (t/is (= [(test-dep {:name "alice" :version "1.0.0" :latest-version "2.0.0"}) (test-dep {:name "bob" :version "2.0.0" :latest-version "3.0.0"})] (sut/outdated-deps deps {:exclude ["alice@3.0.0"]})))))) (t/deftest assoc-changes-url-test (let [dummy-dep {:type :java :name "foo/bar" :version "1" :latest-version "2"}] (t/testing "changelog" (with-redefs [u.dep/get-scm-url (constantly "") u.git/tags-by-ls-remote (constantly ["v1" "v2"]) changelog/get-root-file-names (constantly ["CHANGELOG.md"])] (t/is (= (assoc dummy-dep :changes-url "") (sut/assoc-changes-url dummy-dep))) (t/is (= (assoc dummy-dep :type :test) (sut/assoc-changes-url (assoc dummy-dep :type :test)))))) (t/testing "diff" (with-redefs [u.dep/get-scm-url (constantly "") u.git/tags-by-ls-remote (constantly ["v1" "v2"]) changelog/get-root-file-names (constantly [])] (t/is (= (assoc dummy-dep :changes-url "") (sut/assoc-changes-url dummy-dep))) (t/is (= (assoc dummy-dep :type :test) (sut/assoc-changes-url (assoc dummy-dep :type :test))))))) (t/testing "timed out to fetch diffs" (let [dummy-dep {:type :java :name "foo/bar" :version "1" :latest-version "2"}] (with-redefs [u.dep/get-scm-url (fn [& _] (throw (u.ex/ex-timeout "test")))] (t/is (= dummy-dep (sut/assoc-changes-url dummy-dep)))))) (t/testing "timed out dependencies" (let [timed-out-dep {:type :java :name "foo/bar" :version "1" :latest-version (u.ex/ex-timeout "test")}] (with-redefs [u.dep/get-scm-url (fn [& _] (throw (Exception. "must not be called")))] (t/is (= timed-out-dep (sut/assoc-changes-url timed-out-dep))))))) (t/deftest unverified-deps-test (let [dummy-deps [{:type :java :name "antq/antq"} {:type :java :name "seancorfield/next.jdbc"} {:type :java :name "dummy/dummy"} {:type :UNKNOWN :name "antq/antq"}]] (t/is (= [{:type :java :name "antq/antq" :version "antq/antq" :latest-version nil :latest-name "com.github.liquidz/antq"} {:type :java :name "seancorfield/next.jdbc" :version "seancorfield/next.jdbc" :latest-version nil :latest-name "com.github.seancorfield/next.jdbc"}] (sut/unverified-deps dummy-deps))))) (t/deftest fetch-deps-test (t/is (seq (sut/fetch-deps {:directory ["."]}))) (t/testing "skip" (t/testing "boot" (t/is (nil? (some #(= "test/resources/dep/build.boot" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["boot"]}))))) (t/testing "clojure-cli" (t/is (nil? (some #(= "test/resources/dep/deps.edn" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["clojure-cli"]}))))) (t/testing "github-action" (t/is (nil? (some #(= "test/resources/dep/github_action.yml" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["github-action"]}))))) (t/testing "pom" (t/is (nil? (some #(= "test/resources/dep/pom.xml" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["pom"]}))))) (t/testing "shadow-cljs" (t/is (nil? (some #(#{"test/resources/dep/shadow-cljs.edn" "test/resources/dep/shadow-cljs-env.edn"} (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["shadow-cljs"]}))))) (t/testing "leiningen" (t/is (nil? (some #(= "test/resources/dep/project.clj" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["leiningen"]}))))))) (t/deftest mark-only-newest-version-flag-test (let [deps [(r/map->Dependency {:name "org.clojure/clojure" :version "1"}) (r/map->Dependency {:name "org.clojure/clojure" :version "2"}) (r/map->Dependency {:name "dummy" :version "3"})] res (sut/mark-only-newest-version-flag deps)] (t/is (= 3 (count res))) (t/is (= #{(r/map->Dependency {:name "org.clojure/clojure" :version "1" :only-newest-version? true}) (r/map->Dependency {:name "org.clojure/clojure" :version "2" :only-newest-version? true}) (r/map->Dependency {:name "dummy" :version "3" :only-newest-version? nil})} (set res))))) (t/deftest unify-deps-having-only-newest-version-flag-test (let [deps [(r/map->Dependency {:name "foo" :version "1.8.0" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.9.0" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.10.2" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.8.0" :file "project.clj" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.9.0" :file "project.clj" :only-newest-version? true}) (r/map->Dependency {:name "bar" :version "1.8.0" :file "project.clj" :only-newest-version? false}) (r/map->Dependency {:name "bar" :version "1.9.0" :file "project.clj" :only-newest-version? false})] res (sut/unify-deps-having-only-newest-version-flag deps)] (t/is (= 4 (count res))) (t/is (= #{(r/map->Dependency {:name "foo" :version "1.10.2" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.9.0" :file "project.clj" :only-newest-version? true}) (r/map->Dependency {:name "bar" :version "1.8.0" :file "project.clj" :only-newest-version? false}) (r/map->Dependency {:name "bar" :version "1.9.0" :file "project.clj" :only-newest-version? false})} (set res))))) (t/deftest latest-test (t/is (= "3.0.0" (str/trim (with-out-str (sut/latest {:type :test :name 'foo/bar}))))))
null
https://raw.githubusercontent.com/liquidz/antq/ca8472b28702f5e568492001bc476fb09e5b2e6b/test/antq/core_test.clj
clojure
(ns antq.core-test (:require [antq.changelog :as changelog] [antq.core :as sut] [antq.record :as r] [antq.util.dep :as u.dep] [antq.util.exception :as u.ex] [antq.util.git :as u.git] [antq.ver :as ver] [clojure.string :as str] [clojure.test :as t] [clojure.tools.cli :as cli])) (defmethod ver/get-sorted-versions :test [_ _] ["3.0.0" "2.0.0" "1.0.0"]) (def ^:private test-parse-opts #(cli/parse-opts % sut/cli-options)) (t/deftest cli-options-test (t/testing "default options" (t/is (= {:exclude [] :focus [] :directory ["."] :skip [] :error-format nil :reporter "table"} (:options (test-parse-opts []))))) (t/testing "--exclude" (t/is (= ["ex/ex1" "ex/ex2" "ex/ex3" "ex/ex4@1.0.0" "ex/ex5@2.0.0" "ex/ex6@3.0.0"] (get-in (test-parse-opts ["--exclude=ex/ex1" "--exclude=ex/ex2:ex/ex3" "--exclude=ex/ex4@1.0.0" "--exclude=ex/ex5@2.0.0:ex/ex6@3.0.0"]) [:options :exclude])))) (t/testing "--focus" (t/is (= ["fo/cus1" "fo/cus2" "fo/cus3"] (get-in (test-parse-opts ["--focus=fo/cus1" "--focus=fo/cus2:fo/cus3"]) [:options :focus])))) (t/testing "--directory" (t/is (= ["." "dir1" "dir2" "dir3" "dir4"] (get-in (test-parse-opts ["-d" "dir1" "--directory=dir2" "--directory" "dir3:dir4"]) [:options :directory])))) (t/testing "--skip" (let [res (test-parse-opts ["--skip" "boot" "--skip=clojure-cli"])] (t/is (= ["boot" "clojure-cli"] (get-in res [:options :skip]))) (t/is (nil? (:errors res)))) (t/testing "validation error" (let [res (test-parse-opts ["--skip=foo"])] (t/is (= [] (get-in res [:options :skip]))) (t/is (some? (:errors res)))))) (t/testing "--error-format" (t/is (= "foo" (get-in (test-parse-opts ["--error-format=foo"]) [:options :error-format])))) (t/testing "--reporter" (let [res (test-parse-opts ["--reporter=edn"])] (t/is (= "edn" (get-in res [:options :reporter]))) (t/is (nil? (:errors res)))) (t/testing "validation error" (let [res (test-parse-opts ["--reporter=foo"])] (t/is (= "table" (get-in res [:options :reporter]))) (t/is (some? (:errors res)))))) (t/testing "--upgrade" (t/is (true? (get-in (test-parse-opts ["--upgrade"]) [:options :upgrade])))) (t/testing "--no-diff" (t/is (true? (get-in (test-parse-opts ["--no-diff"]) [:options :no-diff]))))) (t/deftest skip-artifacts?-test (t/testing "default" (t/are [expected in] (= expected (sut/skip-artifacts? (r/map->Dependency {:name in}) {})) false "org.clojure/clojure" false "org.clojure/foo" false "foo/clojure" false "foo" false "foo/bar")) (t/testing "custom: exclude" (t/are [expected in] (= expected (sut/skip-artifacts? (r/map->Dependency {:name in}) {:exclude ["org.clojure/clojure" "org.clojure/foo" "foo"]})) true "org.clojure/clojure" true "org.clojure/foo" false "foo/clojure" true "foo" false "foo/bar")) (t/testing "custom: focus" (t/are [expected in] (= expected (sut/skip-artifacts? (r/map->Dependency {:name in}) {:focus ["org.clojure/clojure" "foo"]})) false "org.clojure/clojure" true "org.clojure/foo" true "foo/clojure" false "foo" true "foo/bar")) (t/testing "`focus` shoud be prefer than `exclude`" (t/is (false? (sut/skip-artifacts? (r/map->Dependency {:name "org.clojure/clojure"}) {:exclude ["org.clojure/clojure"] :focus ["org.clojure/clojure"]}))))) (t/deftest remove-skipping-versions-test (t/testing "there are no target to remove" (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {}))) (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@4"]})))) (t/testing "only dep's name is matched" (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo"]})))) (t/testing "only version number is matched" (t/is (= ["1" "2" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["bar@2"]})))) (t/testing "dep's name and version number are matched" (t/is (= ["1" "3"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@2"]}))) (t/is (= ["1"] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@2" "foo@3"]}))) (t/is (= [] (sut/remove-skipping-versions ["1" "2" "3"] "foo" {:exclude ["foo@1" "foo@2" "foo@3"]}))))) (t/deftest using-release-version?-test (t/are [expected in] (= expected (sut/using-release-version? (r/map->Dependency {:version in}))) true "RELEASE" true "master" true "main" true "latest" false "1.0.0" false "")) (defn- test-dep [m] (r/map->Dependency (merge {:type :test} m))) (t/deftest outdated-deps-test (let [deps [(test-dep {:name "alice" :version "1.0.0"}) (test-dep {:name "bob" :version "2.0.0"}) (test-dep {:name "charlie" :version "3.0.0"})]] (t/is (= [(test-dep {:name "alice" :version "1.0.0" :latest-version "3.0.0"}) (test-dep {:name "bob" :version "2.0.0" :latest-version "3.0.0"})] (sut/outdated-deps deps {}))) (t/testing "alice@3.0.0 should be excluded" (t/is (= [(test-dep {:name "alice" :version "1.0.0" :latest-version "2.0.0"}) (test-dep {:name "bob" :version "2.0.0" :latest-version "3.0.0"})] (sut/outdated-deps deps {:exclude ["alice@3.0.0"]})))))) (t/deftest assoc-changes-url-test (let [dummy-dep {:type :java :name "foo/bar" :version "1" :latest-version "2"}] (t/testing "changelog" (with-redefs [u.dep/get-scm-url (constantly "") u.git/tags-by-ls-remote (constantly ["v1" "v2"]) changelog/get-root-file-names (constantly ["CHANGELOG.md"])] (t/is (= (assoc dummy-dep :changes-url "") (sut/assoc-changes-url dummy-dep))) (t/is (= (assoc dummy-dep :type :test) (sut/assoc-changes-url (assoc dummy-dep :type :test)))))) (t/testing "diff" (with-redefs [u.dep/get-scm-url (constantly "") u.git/tags-by-ls-remote (constantly ["v1" "v2"]) changelog/get-root-file-names (constantly [])] (t/is (= (assoc dummy-dep :changes-url "") (sut/assoc-changes-url dummy-dep))) (t/is (= (assoc dummy-dep :type :test) (sut/assoc-changes-url (assoc dummy-dep :type :test))))))) (t/testing "timed out to fetch diffs" (let [dummy-dep {:type :java :name "foo/bar" :version "1" :latest-version "2"}] (with-redefs [u.dep/get-scm-url (fn [& _] (throw (u.ex/ex-timeout "test")))] (t/is (= dummy-dep (sut/assoc-changes-url dummy-dep)))))) (t/testing "timed out dependencies" (let [timed-out-dep {:type :java :name "foo/bar" :version "1" :latest-version (u.ex/ex-timeout "test")}] (with-redefs [u.dep/get-scm-url (fn [& _] (throw (Exception. "must not be called")))] (t/is (= timed-out-dep (sut/assoc-changes-url timed-out-dep))))))) (t/deftest unverified-deps-test (let [dummy-deps [{:type :java :name "antq/antq"} {:type :java :name "seancorfield/next.jdbc"} {:type :java :name "dummy/dummy"} {:type :UNKNOWN :name "antq/antq"}]] (t/is (= [{:type :java :name "antq/antq" :version "antq/antq" :latest-version nil :latest-name "com.github.liquidz/antq"} {:type :java :name "seancorfield/next.jdbc" :version "seancorfield/next.jdbc" :latest-version nil :latest-name "com.github.seancorfield/next.jdbc"}] (sut/unverified-deps dummy-deps))))) (t/deftest fetch-deps-test (t/is (seq (sut/fetch-deps {:directory ["."]}))) (t/testing "skip" (t/testing "boot" (t/is (nil? (some #(= "test/resources/dep/build.boot" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["boot"]}))))) (t/testing "clojure-cli" (t/is (nil? (some #(= "test/resources/dep/deps.edn" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["clojure-cli"]}))))) (t/testing "github-action" (t/is (nil? (some #(= "test/resources/dep/github_action.yml" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["github-action"]}))))) (t/testing "pom" (t/is (nil? (some #(= "test/resources/dep/pom.xml" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["pom"]}))))) (t/testing "shadow-cljs" (t/is (nil? (some #(#{"test/resources/dep/shadow-cljs.edn" "test/resources/dep/shadow-cljs-env.edn"} (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["shadow-cljs"]}))))) (t/testing "leiningen" (t/is (nil? (some #(= "test/resources/dep/project.clj" (:file %)) (sut/fetch-deps {:directory ["test/resources/dep"] :skip ["leiningen"]}))))))) (t/deftest mark-only-newest-version-flag-test (let [deps [(r/map->Dependency {:name "org.clojure/clojure" :version "1"}) (r/map->Dependency {:name "org.clojure/clojure" :version "2"}) (r/map->Dependency {:name "dummy" :version "3"})] res (sut/mark-only-newest-version-flag deps)] (t/is (= 3 (count res))) (t/is (= #{(r/map->Dependency {:name "org.clojure/clojure" :version "1" :only-newest-version? true}) (r/map->Dependency {:name "org.clojure/clojure" :version "2" :only-newest-version? true}) (r/map->Dependency {:name "dummy" :version "3" :only-newest-version? nil})} (set res))))) (t/deftest unify-deps-having-only-newest-version-flag-test (let [deps [(r/map->Dependency {:name "foo" :version "1.8.0" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.9.0" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.10.2" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.8.0" :file "project.clj" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.9.0" :file "project.clj" :only-newest-version? true}) (r/map->Dependency {:name "bar" :version "1.8.0" :file "project.clj" :only-newest-version? false}) (r/map->Dependency {:name "bar" :version "1.9.0" :file "project.clj" :only-newest-version? false})] res (sut/unify-deps-having-only-newest-version-flag deps)] (t/is (= 4 (count res))) (t/is (= #{(r/map->Dependency {:name "foo" :version "1.10.2" :file "deps.edn" :only-newest-version? true}) (r/map->Dependency {:name "foo" :version "1.9.0" :file "project.clj" :only-newest-version? true}) (r/map->Dependency {:name "bar" :version "1.8.0" :file "project.clj" :only-newest-version? false}) (r/map->Dependency {:name "bar" :version "1.9.0" :file "project.clj" :only-newest-version? false})} (set res))))) (t/deftest latest-test (t/is (= "3.0.0" (str/trim (with-out-str (sut/latest {:type :test :name 'foo/bar}))))))
a36acf0f7859e1d6e0eb34ae6c95092200a23962b8f166f37f32bc55f5732d6f
igorhvr/bedlam
dict.scm
(define (query-dictionary database word) (import srfi-13) (let* ([sock (open-tcp-socket "dict.org" 2628)] [out (open-socket-output-port sock #t)] [def (with-output-to-string (lambda () (with-input-from-port (open-socket-input-port sock) (lambda () (when (= 220 (read)) (read-line) (display (format "DEFINE ~a ~a\r\n" database word) out) (let ([rc (read)]) (cond [(> 200 rc 100) (let ([c (read)]) (read-line) (do [(count c (- count 1))] [(zero? count)] (read-line) (do ([r (read-line) (read-line)]) ((equal? (string-trim-both r) ".")) (display (string-trim-both r)) (newline))))] [(= rc 552) (display "Sorry, I couldn't find that word.")] [else (display (format "Error ~a retriving dictionary entry for '~a'" rc word))])))))))]) (close-output-port out) (close-socket sock) def)) (define (dict source) (lambda (channel message ignore term) (query-dictionary source term)))
null
https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/sisc/sisc-contrib/irc/scheme/sarah/plugins/dict.scm
scheme
(define (query-dictionary database word) (import srfi-13) (let* ([sock (open-tcp-socket "dict.org" 2628)] [out (open-socket-output-port sock #t)] [def (with-output-to-string (lambda () (with-input-from-port (open-socket-input-port sock) (lambda () (when (= 220 (read)) (read-line) (display (format "DEFINE ~a ~a\r\n" database word) out) (let ([rc (read)]) (cond [(> 200 rc 100) (let ([c (read)]) (read-line) (do [(count c (- count 1))] [(zero? count)] (read-line) (do ([r (read-line) (read-line)]) ((equal? (string-trim-both r) ".")) (display (string-trim-both r)) (newline))))] [(= rc 552) (display "Sorry, I couldn't find that word.")] [else (display (format "Error ~a retriving dictionary entry for '~a'" rc word))])))))))]) (close-output-port out) (close-socket sock) def)) (define (dict source) (lambda (channel message ignore term) (query-dictionary source term)))
0516eee47b80a1a788fb21bc93a95329462ebb9255b2b3954046fab39c6f2cff
DavidAlphaFox/RabbitMQ
rabbit_stomp_reader.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_stomp_reader). -export([start_link/3]). -export([init/3]). -export([conserve_resources/3]). -include("rabbit_stomp.hrl"). -include("rabbit_stomp_frame.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -record(reader_state, {socket, parse_state, processor, state, conserve_resources, recv_outstanding}). %%---------------------------------------------------------------------------- start_link(SupHelperPid, ProcessorPid, Configuration) -> {ok, proc_lib:spawn_link(?MODULE, init, [SupHelperPid, ProcessorPid, Configuration])}. log(Level, Fmt, Args) -> rabbit_log:log(connection, Level, Fmt, Args). init(SupHelperPid, ProcessorPid, Configuration) -> Reply = go(SupHelperPid, ProcessorPid, Configuration), rabbit_stomp_processor:flush_and_die(ProcessorPid), Reply. go(SupHelperPid, ProcessorPid, Configuration) -> process_flag(trap_exit, true), receive {go, Sock0, SockTransform} -> case rabbit_net:connection_string(Sock0, inbound) of {ok, ConnStr} -> case SockTransform(Sock0) of {ok, Sock} -> ProcInitArgs = processor_args(SupHelperPid, Configuration, Sock), rabbit_stomp_processor:init_arg(ProcessorPid, ProcInitArgs), log(info, "accepting STOMP connection ~p (~s)~n", [self(), ConnStr]), ParseState = rabbit_stomp_frame:initial_state(), try mainloop( register_resource_alarm( #reader_state{socket = Sock, parse_state = ParseState, processor = ProcessorPid, state = running, conserve_resources = false, recv_outstanding = false})), log(info, "closing STOMP connection ~p (~s)~n", [self(), ConnStr]) catch _:Ex -> log_network_error(ConnStr, Ex), rabbit_net:fast_close(Sock), exit(normal) end, done; {error, enotconn} -> rabbit_net:fast_close(Sock0), exit(normal); {error, Reason} -> log_network_error(ConnStr, Reason), rabbit_net:fast_close(Sock0), exit(normal) end end end. mainloop(State0 = #reader_state{socket = Sock}) -> State = run_socket(control_throttle(State0)), receive {inet_async, Sock, _Ref, {ok, Data}} -> mainloop(process_received_bytes( Data, State#reader_state{recv_outstanding = false})); {inet_async, _Sock, _Ref, {error, closed}} -> ok; {inet_async, _Sock, _Ref, {error, Reason}} -> throw({inet_error, Reason}); {inet_reply, _Sock, {error, closed}} -> ok; {conserve_resources, Conserve} -> mainloop(State#reader_state{conserve_resources = Conserve}); {bump_credit, Msg} -> credit_flow:handle_bump_msg(Msg), mainloop(State); {'EXIT', _From, shutdown} -> ok; Other -> log(warning, "STOMP connection ~p received " "an unexpected message ~p~n", [Other]), ok end. process_received_bytes([], State) -> State; process_received_bytes(Bytes, State = #reader_state{ processor = Processor, parse_state = ParseState, state = S}) -> case rabbit_stomp_frame:parse(Bytes, ParseState) of {more, ParseState1} -> State#reader_state{parse_state = ParseState1}; {ok, Frame, Rest} -> rabbit_stomp_processor:process_frame(Processor, Frame), PS = rabbit_stomp_frame:initial_state(), process_received_bytes(Rest, State#reader_state{ parse_state = PS, state = next_state(S, Frame)}) end. conserve_resources(Pid, _Source, Conserve) -> Pid ! {conserve_resources, Conserve}, ok. register_resource_alarm(State) -> rabbit_alarm:register(self(), {?MODULE, conserve_resources, []}), State. control_throttle(State = #reader_state{state = CS, conserve_resources = Mem}) -> case {CS, Mem orelse credit_flow:blocked()} of {running, true} -> State#reader_state{state = blocking}; {blocking, false} -> State#reader_state{state = running}; {blocked, false} -> State#reader_state{state = running}; {_, _} -> State end. next_state(blocking, #stomp_frame{command = "SEND"}) -> blocked; next_state(S, _) -> S. run_socket(State = #reader_state{state = blocked}) -> State; run_socket(State = #reader_state{recv_outstanding = true}) -> State; run_socket(State = #reader_state{socket = Sock}) -> rabbit_net:async_recv(Sock, 0, infinity), State#reader_state{recv_outstanding = true}. %%---------------------------------------------------------------------------- processor_args(SupPid, Configuration, Sock) -> SendFun = fun (sync, IoData) -> %% no messages emitted catch rabbit_net:send(Sock, IoData); (async, IoData) -> %% {inet_reply, _, _} will appear soon %% We ignore certain errors here, as we will be %% receiving an asynchronous notification of the %% same (or a related) fault shortly anyway. See bug 21365 . catch rabbit_net:port_command(Sock, IoData) end, StartHeartbeatFun = fun (SendTimeout, SendFin, ReceiveTimeout, ReceiveFun) -> rabbit_heartbeat:start(SupPid, Sock, SendTimeout, SendFin, ReceiveTimeout, ReceiveFun) end, {ok, {PeerAddr, _PeerPort}} = rabbit_net:sockname(Sock), [SendFun, adapter_info(Sock), StartHeartbeatFun, ssl_login_name(Sock, Configuration), PeerAddr]. adapter_info(Sock) -> amqp_connection:socket_adapter_info(Sock, {'STOMP', 0}). ssl_login_name(_Sock, #stomp_configuration{ssl_cert_login = false}) -> none; ssl_login_name(Sock, #stomp_configuration{ssl_cert_login = true}) -> case rabbit_net:peercert(Sock) of {ok, C} -> case rabbit_ssl:peer_cert_auth_name(C) of unsafe -> none; not_found -> none; Name -> Name end; {error, no_peercert} -> none; nossl -> none end. %%---------------------------------------------------------------------------- log_network_error(ConnStr, {ssl_upgrade_error, {tls_alert, "handshake failure"}}) -> log(error, "STOMP detected TLS upgrade error on " "~p (~s): handshake failure~n", [self(), ConnStr]); log_network_error(ConnStr, {ssl_upgrade_error, {tls_alert, "unknown ca"}}) -> log(error, "STOMP detected TLS certificate " "verification error on " "~p (~s): alert 'unknown CA'~n", [self(), ConnStr]); log_network_error(ConnStr, {ssl_upgrade_error, {tls_alert, Alert}}) -> log(error, "STOMP detected TLS upgrade error on " "~p (~s): alert ~s~n", [self(), ConnStr, Alert]); log_network_error(ConnStr, {ssl_upgrade_error, closed}) -> log(error, "STOMP detected TLS upgrade error on " "~p (~s): connection closed~n", [self(), ConnStr]); log_network_error(ConnStr, Ex) -> log(error, "STOMP detected network error on " "~p (~s):~n~p~n", [self(), ConnStr, Ex]).
null
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/rabbitmq-stomp/src/rabbit_stomp_reader.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- no messages emitted {inet_reply, _, _} will appear soon We ignore certain errors here, as we will be receiving an asynchronous notification of the same (or a related) fault shortly anyway. See ----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_stomp_reader). -export([start_link/3]). -export([init/3]). -export([conserve_resources/3]). -include("rabbit_stomp.hrl"). -include("rabbit_stomp_frame.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -record(reader_state, {socket, parse_state, processor, state, conserve_resources, recv_outstanding}). start_link(SupHelperPid, ProcessorPid, Configuration) -> {ok, proc_lib:spawn_link(?MODULE, init, [SupHelperPid, ProcessorPid, Configuration])}. log(Level, Fmt, Args) -> rabbit_log:log(connection, Level, Fmt, Args). init(SupHelperPid, ProcessorPid, Configuration) -> Reply = go(SupHelperPid, ProcessorPid, Configuration), rabbit_stomp_processor:flush_and_die(ProcessorPid), Reply. go(SupHelperPid, ProcessorPid, Configuration) -> process_flag(trap_exit, true), receive {go, Sock0, SockTransform} -> case rabbit_net:connection_string(Sock0, inbound) of {ok, ConnStr} -> case SockTransform(Sock0) of {ok, Sock} -> ProcInitArgs = processor_args(SupHelperPid, Configuration, Sock), rabbit_stomp_processor:init_arg(ProcessorPid, ProcInitArgs), log(info, "accepting STOMP connection ~p (~s)~n", [self(), ConnStr]), ParseState = rabbit_stomp_frame:initial_state(), try mainloop( register_resource_alarm( #reader_state{socket = Sock, parse_state = ParseState, processor = ProcessorPid, state = running, conserve_resources = false, recv_outstanding = false})), log(info, "closing STOMP connection ~p (~s)~n", [self(), ConnStr]) catch _:Ex -> log_network_error(ConnStr, Ex), rabbit_net:fast_close(Sock), exit(normal) end, done; {error, enotconn} -> rabbit_net:fast_close(Sock0), exit(normal); {error, Reason} -> log_network_error(ConnStr, Reason), rabbit_net:fast_close(Sock0), exit(normal) end end end. mainloop(State0 = #reader_state{socket = Sock}) -> State = run_socket(control_throttle(State0)), receive {inet_async, Sock, _Ref, {ok, Data}} -> mainloop(process_received_bytes( Data, State#reader_state{recv_outstanding = false})); {inet_async, _Sock, _Ref, {error, closed}} -> ok; {inet_async, _Sock, _Ref, {error, Reason}} -> throw({inet_error, Reason}); {inet_reply, _Sock, {error, closed}} -> ok; {conserve_resources, Conserve} -> mainloop(State#reader_state{conserve_resources = Conserve}); {bump_credit, Msg} -> credit_flow:handle_bump_msg(Msg), mainloop(State); {'EXIT', _From, shutdown} -> ok; Other -> log(warning, "STOMP connection ~p received " "an unexpected message ~p~n", [Other]), ok end. process_received_bytes([], State) -> State; process_received_bytes(Bytes, State = #reader_state{ processor = Processor, parse_state = ParseState, state = S}) -> case rabbit_stomp_frame:parse(Bytes, ParseState) of {more, ParseState1} -> State#reader_state{parse_state = ParseState1}; {ok, Frame, Rest} -> rabbit_stomp_processor:process_frame(Processor, Frame), PS = rabbit_stomp_frame:initial_state(), process_received_bytes(Rest, State#reader_state{ parse_state = PS, state = next_state(S, Frame)}) end. conserve_resources(Pid, _Source, Conserve) -> Pid ! {conserve_resources, Conserve}, ok. register_resource_alarm(State) -> rabbit_alarm:register(self(), {?MODULE, conserve_resources, []}), State. control_throttle(State = #reader_state{state = CS, conserve_resources = Mem}) -> case {CS, Mem orelse credit_flow:blocked()} of {running, true} -> State#reader_state{state = blocking}; {blocking, false} -> State#reader_state{state = running}; {blocked, false} -> State#reader_state{state = running}; {_, _} -> State end. next_state(blocking, #stomp_frame{command = "SEND"}) -> blocked; next_state(S, _) -> S. run_socket(State = #reader_state{state = blocked}) -> State; run_socket(State = #reader_state{recv_outstanding = true}) -> State; run_socket(State = #reader_state{socket = Sock}) -> rabbit_net:async_recv(Sock, 0, infinity), State#reader_state{recv_outstanding = true}. processor_args(SupPid, Configuration, Sock) -> SendFun = fun (sync, IoData) -> catch rabbit_net:send(Sock, IoData); (async, IoData) -> bug 21365 . catch rabbit_net:port_command(Sock, IoData) end, StartHeartbeatFun = fun (SendTimeout, SendFin, ReceiveTimeout, ReceiveFun) -> rabbit_heartbeat:start(SupPid, Sock, SendTimeout, SendFin, ReceiveTimeout, ReceiveFun) end, {ok, {PeerAddr, _PeerPort}} = rabbit_net:sockname(Sock), [SendFun, adapter_info(Sock), StartHeartbeatFun, ssl_login_name(Sock, Configuration), PeerAddr]. adapter_info(Sock) -> amqp_connection:socket_adapter_info(Sock, {'STOMP', 0}). ssl_login_name(_Sock, #stomp_configuration{ssl_cert_login = false}) -> none; ssl_login_name(Sock, #stomp_configuration{ssl_cert_login = true}) -> case rabbit_net:peercert(Sock) of {ok, C} -> case rabbit_ssl:peer_cert_auth_name(C) of unsafe -> none; not_found -> none; Name -> Name end; {error, no_peercert} -> none; nossl -> none end. log_network_error(ConnStr, {ssl_upgrade_error, {tls_alert, "handshake failure"}}) -> log(error, "STOMP detected TLS upgrade error on " "~p (~s): handshake failure~n", [self(), ConnStr]); log_network_error(ConnStr, {ssl_upgrade_error, {tls_alert, "unknown ca"}}) -> log(error, "STOMP detected TLS certificate " "verification error on " "~p (~s): alert 'unknown CA'~n", [self(), ConnStr]); log_network_error(ConnStr, {ssl_upgrade_error, {tls_alert, Alert}}) -> log(error, "STOMP detected TLS upgrade error on " "~p (~s): alert ~s~n", [self(), ConnStr, Alert]); log_network_error(ConnStr, {ssl_upgrade_error, closed}) -> log(error, "STOMP detected TLS upgrade error on " "~p (~s): connection closed~n", [self(), ConnStr]); log_network_error(ConnStr, Ex) -> log(error, "STOMP detected network error on " "~p (~s):~n~p~n", [self(), ConnStr, Ex]).
dac8fb53c97ec45038bdfd45aa23afcb531767cc9d4e7bd98bdbbcac020fd577
yrashk/erlang
snmp_standard_mib.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(snmp_standard_mib). %%%----------------------------------------------------------------- %%% This module implements the configure- and reinit-functions %%% for the STANDARD-MIB and SNMPv2-MIB. %%%----------------------------------------------------------------- -include("snmp_types.hrl"). -include("STANDARD-MIB.hrl"). -define(VMODULE,"STANDARD-MIB"). -include("snmp_verbosity.hrl"). -define(enabled, 1). -define(disabled, 2). %% External exports -export([configure/1, reconfigure/1, reset/0, sys_up_time/0, sys_up_time/1, snmp_enable_authen_traps/1, snmp_enable_authen_traps/2, sys_object_id/1, sys_object_id/2, sys_or_table/3, variable_func/1, variable_func/2, inc/1, inc/2]). -export([dummy/1, snmp_set_serial_no/1, snmp_set_serial_no/2]). -export([add_agent_caps/2, del_agent_caps/1, get_agent_caps/0]). -export([check_standard/1]). %%----------------------------------------------------------------- %% Func: configure/1 : Dir is the directory with trailing dir_separator where %% the configuration files can be found. %% Purpose: Reads the config-files for the standard mib, and %% inserts the data. Persistent data that is already %% present is *not* changed! (use reconfigure for that) %% Returns: ok %% Fails: exit(configuration_error) %%----------------------------------------------------------------- configure(Dir) -> case (catch do_configure(Dir)) of ok -> ok; {error, Reason} -> ?vinfo("configure error: ~p", [Reason]), config_err("configure failed: ~p", [Reason]), exit(configuration_error); Error -> ?vinfo("configure failed: ~p", [Error]), config_err("configure failed: ~p", [Error]), exit(configuration_error) end. do_configure(Dir) -> case snmpa_agent:get_agent_mib_storage() of mnesia -> ok; _ -> Standard = read_standard(Dir), lists:map(fun maybe_create_persistent_var/1, Standard) end, snmpa_local_db:variable_set({next_sys_or_index, volatile}, 1), %% sysORTable is always volatile snmp_generic:table_func(new, {sysORTable, volatile}), ok. %%----------------------------------------------------------------- %% Func: reconfigure/1 : Dir is the directory with trailing dir_separator where %% the configuration files can be found. %% Purpose: Reads the config-files for the standard mib, and %% inserts the data. Persistent data that is already %% present is deleted. Makes sure the config file %% data is used. %% Returns: ok %% Fails: exit(configuration_error) %%----------------------------------------------------------------- reconfigure(Dir) -> set_sname(), case (catch do_reconfigure(Dir)) of ok -> ok; {error, Reason} -> ?vinfo("reconfigure error: ~p", [Reason]), config_err("reconfigure failed: ~p", [Reason]), exit(configuration_error); Error -> ?vinfo("reconfigure failed: ~p", [Error]), config_err("reconfigure failed: ~p", [Error]), exit(configuration_error) end. do_reconfigure(Dir) -> Standard = read_standard(Dir), lists:map(fun create_persistent_var/1, Standard), snmpa_local_db:variable_set({next_sys_or_index, volatile}, 1), snmp_generic:table_func(new, {sysORTable, volatile}), ok. %%----------------------------------------------------------------- %% Func: read_standard/1 : Dir is the directory with trailing dir_separator where %% the configuration files can be found. %% Purpose: Reads th standard configuration file. %% Returns: A list of standard variables %% Fails: If an error occurs, the process will die with Reason %% configuration_error. %%----------------------------------------------------------------- read_standard(Dir) -> ?vdebug("check standard config file",[]), Gen = fun(_) -> ok end, Filter = fun(Standard) -> sort_standard(Standard) end, Check = fun(Entry) -> check_standard(Entry) end, [Standard] = snmp_conf:read_files(Dir, [{Gen, Filter, Check, "standard.conf"}]), Standard. %%----------------------------------------------------------------- %% Make sure that each mandatory standard attribute is present, and %% provide default values for the other non-present attributes. %%----------------------------------------------------------------- sort_standard(L) -> Mand = [{sysContact, {value, ""}}, {sysDescr, {value, ""}}, {sysLocation, {value, ""}}, {sysName, {value, ""}}, {sysObjectID, mandatory}, {sysServices, mandatory}, {snmpEnableAuthenTraps, mandatory}], {ok, L2} = snmp_conf:check_mandatory(L, Mand), lists:keysort(1, L2). %%----------------------------------------------------------------- %% Standard %% {Name, Value}. %%----------------------------------------------------------------- check_standard({sysDescr, Value}) -> snmp_conf:check_string(Value); check_standard({sysObjectID, Value}) -> snmp_conf:check_oid(Value); check_standard({sysContact, Value}) -> snmp_conf:check_string(Value); check_standard({sysName, Value}) -> snmp_conf:check_string(Value); check_standard({sysLocation, Value}) -> snmp_conf:check_string(Value); check_standard({sysServices, Value}) -> snmp_conf:check_integer(Value); check_standard({snmpEnableAuthenTraps, Value}) -> Atoms = [{enabled, ?snmpEnableAuthenTraps_enabled}, {disabled, ?snmpEnableAuthenTraps_disabled}], {ok, Val} = snmp_conf:check_atom(Value, Atoms), {ok, {snmpEnableAuthenTraps, Val}}; check_standard({Attrib, _Value}) -> error({unknown_attribute, Attrib}); check_standard(X) -> error({invalid_standard_specification, X}). %%----------------------------------------------------------------- %% Func: reset/0 %% Purpose: Resets all counters (sets them to 0). %%----------------------------------------------------------------- reset() -> snmpa_mpd:reset(). maybe_create_persistent_var({Var, Val}) -> VarDB = db(Var), case snmp_generic:variable_get(VarDB) of {value, _} -> ok; _ -> snmp_generic:variable_set(VarDB, Val) end. create_persistent_var({Var, Val}) -> snmp_generic:variable_set(db(Var), Val). variable_func(_Op) -> ok. variable_func(get, Name) -> [{_, Val}] = ets:lookup(snmp_agent_table, Name), {value, Val}. %%----------------------------------------------------------------- %% inc(VariableName) increments the variable (Counter) in the local mib . ( e.g. snmpInPkts ) %%----------------------------------------------------------------- inc(Name) -> inc(Name, 1). inc(Name, N) -> ets:update_counter(snmp_agent_table, Name, N). %%----------------------------------------------------------------- This is the instrumentation function for sysUpTime . %%----------------------------------------------------------------- sys_up_time() -> snmpa:sys_up_time(). sys_up_time(get) -> {value, snmpa:sys_up_time()}. %%----------------------------------------------------------------- %% This is the instrumentation function for snmpEnableAuthenTraps %%----------------------------------------------------------------- snmp_enable_authen_traps(new) -> snmp_generic:variable_func(new, db(snmpEnableAuthenTraps)); snmp_enable_authen_traps(delete) -> ok; snmp_enable_authen_traps(get) -> snmp_generic:variable_func(get, db(snmpEnableAuthenTraps)). snmp_enable_authen_traps(set, NewVal) -> snmp_generic:variable_func(set, NewVal, db(snmpEnableAuthenTraps)). %%----------------------------------------------------------------- %% This is the instrumentation function for sysObjectId %%----------------------------------------------------------------- sys_object_id(new) -> snmp_generic:variable_func(new, db(sysObjectID)); sys_object_id(delete) -> ok; sys_object_id(get) -> snmp_generic:variable_func(get, db(sysObjectID)). sys_object_id(set, NewVal) -> snmp_generic:variable_func(set, NewVal, db(sysObjectID)). %%----------------------------------------------------------------- %% This is a dummy instrumentation function for objects like %% snmpTrapOID, that is accessible-for-notify, with different %% values each time. This function will only be called with %% new/delete. %%----------------------------------------------------------------- dummy(_Op) -> ok. %%----------------------------------------------------------------- %% This is the instrumentation function for snmpSetSerialNo. %% It is always volatile. %%----------------------------------------------------------------- snmp_set_serial_no(new) -> snmp_generic:variable_func(new, {snmpSetSerialNo, volatile}), {A1,A2,A3} = erlang:now(), random:seed(A1,A2,A3), Val = random:uniform(2147483648) - 1, snmp_generic:variable_func(set, Val, {snmpSetSerialNo, volatile}); snmp_set_serial_no(delete) -> ok; snmp_set_serial_no(get) -> snmp_generic:variable_func(get, {snmpSetSerialNo, volatile}). snmp_set_serial_no(is_set_ok, NewVal) -> case snmp_generic:variable_func(get, {snmpSetSerialNo, volatile}) of {value, NewVal} -> noError; _ -> inconsistentValue end; snmp_set_serial_no(set, NewVal) -> snmp_generic:variable_func(set, (NewVal + 1) rem 2147483648, {snmpSetSerialNo, volatile}). %%----------------------------------------------------------------- %% This is the instrumentation function for sysOrTable %%----------------------------------------------------------------- sys_or_table(Op, RowIndex, Cols) -> snmp_generic:table_func(Op, RowIndex, Cols, {sysORTable, volatile}). add_agent_caps(Oid, Descr) when list(Oid), list(Descr) -> {value, Next} = snmpa_local_db:variable_get({next_sys_or_index, volatile}), snmpa_local_db:variable_set({next_sys_or_index, volatile}, Next+1), SysUpTime = sys_up_time(), Row = {Next, Oid, Descr, SysUpTime}, snmpa_local_db:table_create_row({sysORTable, volatile}, [Next], Row), snmpa_local_db:variable_set({sysORLastChange, volatile}, SysUpTime), Next. del_agent_caps(Index) -> snmpa_local_db:table_delete_row({sysORTable, volatile}, [Index]), snmpa_local_db:variable_set({sysORLastChange, volatile}, sys_up_time()). get_agent_caps() -> snmpa_local_db:match({sysORTable, volatile}, {'$1', '$2', '$3', '$4'}). db(Var) -> snmpa_agent:db(Var). %% ----- set_sname() -> set_sname(get(sname)). set_sname(undefined) -> put(sname,conf); set_sname(_) -> %% Keep it, if already set. ok. error(Reason) -> throw({error, Reason}). config_err(F, A) -> snmpa_error:config_err("[STANDARD-MIB]: " ++ F, A).
null
https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/snmp/src/agent/snmp_standard_mib.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ----------------------------------------------------------------- This module implements the configure- and reinit-functions for the STANDARD-MIB and SNMPv2-MIB. ----------------------------------------------------------------- External exports ----------------------------------------------------------------- Func: configure/1 the configuration files can be found. Purpose: Reads the config-files for the standard mib, and inserts the data. Persistent data that is already present is *not* changed! (use reconfigure for that) Returns: ok Fails: exit(configuration_error) ----------------------------------------------------------------- sysORTable is always volatile ----------------------------------------------------------------- Func: reconfigure/1 the configuration files can be found. Purpose: Reads the config-files for the standard mib, and inserts the data. Persistent data that is already present is deleted. Makes sure the config file data is used. Returns: ok Fails: exit(configuration_error) ----------------------------------------------------------------- ----------------------------------------------------------------- Func: read_standard/1 the configuration files can be found. Purpose: Reads th standard configuration file. Returns: A list of standard variables Fails: If an error occurs, the process will die with Reason configuration_error. ----------------------------------------------------------------- ----------------------------------------------------------------- Make sure that each mandatory standard attribute is present, and provide default values for the other non-present attributes. ----------------------------------------------------------------- ----------------------------------------------------------------- Standard {Name, Value}. ----------------------------------------------------------------- ----------------------------------------------------------------- Func: reset/0 Purpose: Resets all counters (sets them to 0). ----------------------------------------------------------------- ----------------------------------------------------------------- inc(VariableName) increments the variable (Counter) in ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- This is the instrumentation function for snmpEnableAuthenTraps ----------------------------------------------------------------- ----------------------------------------------------------------- This is the instrumentation function for sysObjectId ----------------------------------------------------------------- ----------------------------------------------------------------- This is a dummy instrumentation function for objects like snmpTrapOID, that is accessible-for-notify, with different values each time. This function will only be called with new/delete. ----------------------------------------------------------------- ----------------------------------------------------------------- This is the instrumentation function for snmpSetSerialNo. It is always volatile. ----------------------------------------------------------------- ----------------------------------------------------------------- This is the instrumentation function for sysOrTable ----------------------------------------------------------------- ----- Keep it, if already set.
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(snmp_standard_mib). -include("snmp_types.hrl"). -include("STANDARD-MIB.hrl"). -define(VMODULE,"STANDARD-MIB"). -include("snmp_verbosity.hrl"). -define(enabled, 1). -define(disabled, 2). -export([configure/1, reconfigure/1, reset/0, sys_up_time/0, sys_up_time/1, snmp_enable_authen_traps/1, snmp_enable_authen_traps/2, sys_object_id/1, sys_object_id/2, sys_or_table/3, variable_func/1, variable_func/2, inc/1, inc/2]). -export([dummy/1, snmp_set_serial_no/1, snmp_set_serial_no/2]). -export([add_agent_caps/2, del_agent_caps/1, get_agent_caps/0]). -export([check_standard/1]). : Dir is the directory with trailing dir_separator where configure(Dir) -> case (catch do_configure(Dir)) of ok -> ok; {error, Reason} -> ?vinfo("configure error: ~p", [Reason]), config_err("configure failed: ~p", [Reason]), exit(configuration_error); Error -> ?vinfo("configure failed: ~p", [Error]), config_err("configure failed: ~p", [Error]), exit(configuration_error) end. do_configure(Dir) -> case snmpa_agent:get_agent_mib_storage() of mnesia -> ok; _ -> Standard = read_standard(Dir), lists:map(fun maybe_create_persistent_var/1, Standard) end, snmpa_local_db:variable_set({next_sys_or_index, volatile}, 1), snmp_generic:table_func(new, {sysORTable, volatile}), ok. : Dir is the directory with trailing dir_separator where reconfigure(Dir) -> set_sname(), case (catch do_reconfigure(Dir)) of ok -> ok; {error, Reason} -> ?vinfo("reconfigure error: ~p", [Reason]), config_err("reconfigure failed: ~p", [Reason]), exit(configuration_error); Error -> ?vinfo("reconfigure failed: ~p", [Error]), config_err("reconfigure failed: ~p", [Error]), exit(configuration_error) end. do_reconfigure(Dir) -> Standard = read_standard(Dir), lists:map(fun create_persistent_var/1, Standard), snmpa_local_db:variable_set({next_sys_or_index, volatile}, 1), snmp_generic:table_func(new, {sysORTable, volatile}), ok. : Dir is the directory with trailing dir_separator where read_standard(Dir) -> ?vdebug("check standard config file",[]), Gen = fun(_) -> ok end, Filter = fun(Standard) -> sort_standard(Standard) end, Check = fun(Entry) -> check_standard(Entry) end, [Standard] = snmp_conf:read_files(Dir, [{Gen, Filter, Check, "standard.conf"}]), Standard. sort_standard(L) -> Mand = [{sysContact, {value, ""}}, {sysDescr, {value, ""}}, {sysLocation, {value, ""}}, {sysName, {value, ""}}, {sysObjectID, mandatory}, {sysServices, mandatory}, {snmpEnableAuthenTraps, mandatory}], {ok, L2} = snmp_conf:check_mandatory(L, Mand), lists:keysort(1, L2). check_standard({sysDescr, Value}) -> snmp_conf:check_string(Value); check_standard({sysObjectID, Value}) -> snmp_conf:check_oid(Value); check_standard({sysContact, Value}) -> snmp_conf:check_string(Value); check_standard({sysName, Value}) -> snmp_conf:check_string(Value); check_standard({sysLocation, Value}) -> snmp_conf:check_string(Value); check_standard({sysServices, Value}) -> snmp_conf:check_integer(Value); check_standard({snmpEnableAuthenTraps, Value}) -> Atoms = [{enabled, ?snmpEnableAuthenTraps_enabled}, {disabled, ?snmpEnableAuthenTraps_disabled}], {ok, Val} = snmp_conf:check_atom(Value, Atoms), {ok, {snmpEnableAuthenTraps, Val}}; check_standard({Attrib, _Value}) -> error({unknown_attribute, Attrib}); check_standard(X) -> error({invalid_standard_specification, X}). reset() -> snmpa_mpd:reset(). maybe_create_persistent_var({Var, Val}) -> VarDB = db(Var), case snmp_generic:variable_get(VarDB) of {value, _} -> ok; _ -> snmp_generic:variable_set(VarDB, Val) end. create_persistent_var({Var, Val}) -> snmp_generic:variable_set(db(Var), Val). variable_func(_Op) -> ok. variable_func(get, Name) -> [{_, Val}] = ets:lookup(snmp_agent_table, Name), {value, Val}. the local mib . ( e.g. snmpInPkts ) inc(Name) -> inc(Name, 1). inc(Name, N) -> ets:update_counter(snmp_agent_table, Name, N). This is the instrumentation function for sysUpTime . sys_up_time() -> snmpa:sys_up_time(). sys_up_time(get) -> {value, snmpa:sys_up_time()}. snmp_enable_authen_traps(new) -> snmp_generic:variable_func(new, db(snmpEnableAuthenTraps)); snmp_enable_authen_traps(delete) -> ok; snmp_enable_authen_traps(get) -> snmp_generic:variable_func(get, db(snmpEnableAuthenTraps)). snmp_enable_authen_traps(set, NewVal) -> snmp_generic:variable_func(set, NewVal, db(snmpEnableAuthenTraps)). sys_object_id(new) -> snmp_generic:variable_func(new, db(sysObjectID)); sys_object_id(delete) -> ok; sys_object_id(get) -> snmp_generic:variable_func(get, db(sysObjectID)). sys_object_id(set, NewVal) -> snmp_generic:variable_func(set, NewVal, db(sysObjectID)). dummy(_Op) -> ok. snmp_set_serial_no(new) -> snmp_generic:variable_func(new, {snmpSetSerialNo, volatile}), {A1,A2,A3} = erlang:now(), random:seed(A1,A2,A3), Val = random:uniform(2147483648) - 1, snmp_generic:variable_func(set, Val, {snmpSetSerialNo, volatile}); snmp_set_serial_no(delete) -> ok; snmp_set_serial_no(get) -> snmp_generic:variable_func(get, {snmpSetSerialNo, volatile}). snmp_set_serial_no(is_set_ok, NewVal) -> case snmp_generic:variable_func(get, {snmpSetSerialNo, volatile}) of {value, NewVal} -> noError; _ -> inconsistentValue end; snmp_set_serial_no(set, NewVal) -> snmp_generic:variable_func(set, (NewVal + 1) rem 2147483648, {snmpSetSerialNo, volatile}). sys_or_table(Op, RowIndex, Cols) -> snmp_generic:table_func(Op, RowIndex, Cols, {sysORTable, volatile}). add_agent_caps(Oid, Descr) when list(Oid), list(Descr) -> {value, Next} = snmpa_local_db:variable_get({next_sys_or_index, volatile}), snmpa_local_db:variable_set({next_sys_or_index, volatile}, Next+1), SysUpTime = sys_up_time(), Row = {Next, Oid, Descr, SysUpTime}, snmpa_local_db:table_create_row({sysORTable, volatile}, [Next], Row), snmpa_local_db:variable_set({sysORLastChange, volatile}, SysUpTime), Next. del_agent_caps(Index) -> snmpa_local_db:table_delete_row({sysORTable, volatile}, [Index]), snmpa_local_db:variable_set({sysORLastChange, volatile}, sys_up_time()). get_agent_caps() -> snmpa_local_db:match({sysORTable, volatile}, {'$1', '$2', '$3', '$4'}). db(Var) -> snmpa_agent:db(Var). set_sname() -> set_sname(get(sname)). set_sname(undefined) -> put(sname,conf); ok. error(Reason) -> throw({error, Reason}). config_err(F, A) -> snmpa_error:config_err("[STANDARD-MIB]: " ++ F, A).
773657d2cabdf6060a2f07f29129eb530570e943dfc4cfcba3aa723ce7303769
madgen/exalog
Helper.hs
module Language.Exalog.Pretty.Helper ( pp , Pretty(..) , PrettyCollection(..) , (<?>) , (<+?>) , ($?$) , ($+?$) , cond , csep ) where import Protolude hiding ((<>), empty, head) import Data.String (fromString) import Data.Text (unpack) import Text.PrettyPrint -- | Render as text pp :: Pretty a => a -> Text pp = fromString . render . pretty class Pretty a where pretty :: a -> Doc class PrettyCollection a where prettyC :: a -> [ Doc ] infixl 7 <?> infix 7 <+?> -- | Same as `<>` but `empty` acts as an annihilator (<?>) :: Doc -> Doc -> Doc d1 <?> d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 <> d2 -- | Same as `<+>` but `empty` acts as an annihilator (<+?>) :: Doc -> Doc -> Doc d1 <+?> d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 <+> d2 -- | Same as `$$` but `empty` acts as an annihilator ($?$) :: Doc -> Doc -> Doc d1 $?$ d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 $$ d2 -- | Same as `$+?$` but `empty` acts as an annihilator ($+?$) :: Doc -> Doc -> Doc d1 $+?$ d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 $+$ d2 | Conditionally return the second argument cond :: Bool -> Doc -> Doc cond True doc = doc cond False _ = empty | Comma separate Docs csep :: [ Doc ] -> Doc csep = hsep . punctuate comma -- Common instances instance {-# OVERLAPPABLE #-} Pretty a => PrettyCollection [ a ] where prettyC = map pretty instance Pretty Text where pretty = text . unpack instance Pretty () where pretty _ = empty instance Pretty Int where pretty = int
null
https://raw.githubusercontent.com/madgen/exalog/7d169b066c5c08f2b8e44f5e078df264731ac177/src/Language/Exalog/Pretty/Helper.hs
haskell
| Render as text | Same as `<>` but `empty` acts as an annihilator | Same as `<+>` but `empty` acts as an annihilator | Same as `$$` but `empty` acts as an annihilator | Same as `$+?$` but `empty` acts as an annihilator Common instances # OVERLAPPABLE #
module Language.Exalog.Pretty.Helper ( pp , Pretty(..) , PrettyCollection(..) , (<?>) , (<+?>) , ($?$) , ($+?$) , cond , csep ) where import Protolude hiding ((<>), empty, head) import Data.String (fromString) import Data.Text (unpack) import Text.PrettyPrint pp :: Pretty a => a -> Text pp = fromString . render . pretty class Pretty a where pretty :: a -> Doc class PrettyCollection a where prettyC :: a -> [ Doc ] infixl 7 <?> infix 7 <+?> (<?>) :: Doc -> Doc -> Doc d1 <?> d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 <> d2 (<+?>) :: Doc -> Doc -> Doc d1 <+?> d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 <+> d2 ($?$) :: Doc -> Doc -> Doc d1 $?$ d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 $$ d2 ($+?$) :: Doc -> Doc -> Doc d1 $+?$ d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 $+$ d2 | Conditionally return the second argument cond :: Bool -> Doc -> Doc cond True doc = doc cond False _ = empty | Comma separate Docs csep :: [ Doc ] -> Doc csep = hsep . punctuate comma prettyC = map pretty instance Pretty Text where pretty = text . unpack instance Pretty () where pretty _ = empty instance Pretty Int where pretty = int
face1891f5037a0d354c8949eb6be72062a7c6a8cefbbf757ff8fc4486fa19a4
yariv/twoorl
twoorl_pol.erl
This file is part of Twoorl . %% %% Twoorl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or %% (at your option) any later version. %% %% Twoorl 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 . If not , see < / > . -module(twoorl_pol). -export([bundle/1]). bundle(Tag) -> case Tag of %% layout login -> <<"zaloguj">>; register -> <<"zajrejstruj">>; logged_in_as -> <<"zalogowany jako">>; settings -> <<"ustawienia">>; logout -> <<"wyloguj">>; get_source -> <<"Pobierz <a href=\"\">" "kod źródłowy</a>">>; %% navbar home -> <<"początek">>; replies -> <<"odpowiedzi">>; me -> <<"ja">>; everyone -> <<"wszyscy">>; %% login page login_cap -> <<"Login">>; username -> <<"nazwa użytkownika">>; password -> <<"hasło">>; not_member -> <<"Nie jesteś członkiem?">>; login_submit -> <<"zaloguj">>; %% register page register_cap -> <<"Zarejstruj">>; username -> <<"nazwa użytkownika">>; email -> <<"adres poczty elektronicznej">>; password -> <<"hasło">>; password2 -> <<"powtórz hasło">>; already_member -> <<"Jesteś już członkiem?">>; login_cap - > < < " " > > ; %% home page upto -> <<"Co teraz robisz?">>; twitter_msg -> <<"Automatyczne wysyłanie do Twittera włączone dla " "'nie-odpowiedzi'">>; %% main page public_timeline -> <<"Publiczna historia">>; %% users page {no_user, Username} -> [<<"Użytkownik '">>, Username, <<"' nie istnieje">>]; {timeline_of, Username} -> [<<"Historia użytkownika ">>, Username]; following -> <<"śledzi">>; followers -> <<"śledzący">>; follow -> <<"śledź">>; unfollow -> <<"przestań śledzić">>; %% friends page {friends_of, Userlink} -> [<<"Użytkownicy których ">>, Userlink, <<" śledzi">>]; {followers_of, Userlink} -> [<<"Śledzący użytkownika ">>, Userlink]; {no_friends, Username} -> [Username, <<" nie śledzi nikogo">>]; {no_followers, Username} -> [<<"Nikt ie śledzi ">>, Username]; %% settings page settings_cap -> <<"Ustawienia">>; use_gravatar -> <<"Użyć <a href=\"\" " "target=\"_blank\">Gravatara</a>?">>; profile_bg -> <<"Tło profilu">>; profile_bg_help -> <<"Wprowadź URL dla obrazu tła Twojego profilu " "(zostaw puste dla domyślnego tła):">>; twitter_help -> <<"Możesz podać szczegóły Twojego konta Twitter aby automatycznie " "wysyłać również do Twittera.<br/><br/>" "Jedynie twoorle które nie zawierają odpowiedzi (np." "\"@tomek\") będą wysyłane do Twittera.">>; twitter_username -> <<"Nazwa użytkownika Twitter:">>; twitter_password -> <<"Hasło Twitter:">>; twitter_auto -> <<"Automatycznie wysyłaj moje Twoorle do Twittera?">>; submit -> <<"wyślij">>; %% error messages {missing_field, Field} -> [<<"Pole ">>, Field, <<" jest wymagane">>]; {username, Val} -> [<<"Nazwa użytkownika '">>, Val, <<"' jest zajęta">>]; {invalid_username, Val} -> [<<"Nazwa użytkownika '">>, Val, <<"' jest nieprawidłowa. Jedynie litery, cyfry oraz znak podkreślenia ('_') " "są dozwolone">>]; invalid_login -> <<"Niepoprawna nazwa użytkownika lub hasło">>; {too_short, Field, Min} -> [<<"Pole ">>, Field, <<" jest zbyt krótkie (minimum ">>, Min, <<" znaków)">>]; password_mismatch -> <<"Podane hasła nie są identyczne">>; twitter_unauthorized -> <<"Twitter odrzucił kombinację nazwy użytkownika oraz hasła " "które podałeś/podałaś">>; twitter_authorization_error -> <<"Nie mogę połączyć się z Twitter. Spróbuj ponownie później.">>; {invalid_url, Field} -> [<<"Pole ">>, Field, <<" z URL musi zaczynać się od 'http://'">>]; %% confirmation messages settings_updated -> [<<"Twoje ustawienia zostały poprawnie zaktualizowane">>] end.
null
https://raw.githubusercontent.com/yariv/twoorl/77b6bea2e29283d09a95d8db131b916e16d2960b/src/bundles/twoorl_pol.erl
erlang
Twoorl is free software: you can redistribute it and/or modify (at your option) any later version. Twoorl 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. layout navbar login page register page home page main page users page friends page settings page error messages confirmation messages
This file is part of Twoorl . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License along with . If not , see < / > . -module(twoorl_pol). -export([bundle/1]). bundle(Tag) -> case Tag of login -> <<"zaloguj">>; register -> <<"zajrejstruj">>; logged_in_as -> <<"zalogowany jako">>; settings -> <<"ustawienia">>; logout -> <<"wyloguj">>; get_source -> <<"Pobierz <a href=\"\">" "kod źródłowy</a>">>; home -> <<"początek">>; replies -> <<"odpowiedzi">>; me -> <<"ja">>; everyone -> <<"wszyscy">>; login_cap -> <<"Login">>; username -> <<"nazwa użytkownika">>; password -> <<"hasło">>; not_member -> <<"Nie jesteś członkiem?">>; login_submit -> <<"zaloguj">>; register_cap -> <<"Zarejstruj">>; username -> <<"nazwa użytkownika">>; email -> <<"adres poczty elektronicznej">>; password -> <<"hasło">>; password2 -> <<"powtórz hasło">>; already_member -> <<"Jesteś już członkiem?">>; login_cap - > < < " " > > ; upto -> <<"Co teraz robisz?">>; twitter_msg -> <<"Automatyczne wysyłanie do Twittera włączone dla " "'nie-odpowiedzi'">>; public_timeline -> <<"Publiczna historia">>; {no_user, Username} -> [<<"Użytkownik '">>, Username, <<"' nie istnieje">>]; {timeline_of, Username} -> [<<"Historia użytkownika ">>, Username]; following -> <<"śledzi">>; followers -> <<"śledzący">>; follow -> <<"śledź">>; unfollow -> <<"przestań śledzić">>; {friends_of, Userlink} -> [<<"Użytkownicy których ">>, Userlink, <<" śledzi">>]; {followers_of, Userlink} -> [<<"Śledzący użytkownika ">>, Userlink]; {no_friends, Username} -> [Username, <<" nie śledzi nikogo">>]; {no_followers, Username} -> [<<"Nikt ie śledzi ">>, Username]; settings_cap -> <<"Ustawienia">>; use_gravatar -> <<"Użyć <a href=\"\" " "target=\"_blank\">Gravatara</a>?">>; profile_bg -> <<"Tło profilu">>; profile_bg_help -> <<"Wprowadź URL dla obrazu tła Twojego profilu " "(zostaw puste dla domyślnego tła):">>; twitter_help -> <<"Możesz podać szczegóły Twojego konta Twitter aby automatycznie " "wysyłać również do Twittera.<br/><br/>" "Jedynie twoorle które nie zawierają odpowiedzi (np." "\"@tomek\") będą wysyłane do Twittera.">>; twitter_username -> <<"Nazwa użytkownika Twitter:">>; twitter_password -> <<"Hasło Twitter:">>; twitter_auto -> <<"Automatycznie wysyłaj moje Twoorle do Twittera?">>; submit -> <<"wyślij">>; {missing_field, Field} -> [<<"Pole ">>, Field, <<" jest wymagane">>]; {username, Val} -> [<<"Nazwa użytkownika '">>, Val, <<"' jest zajęta">>]; {invalid_username, Val} -> [<<"Nazwa użytkownika '">>, Val, <<"' jest nieprawidłowa. Jedynie litery, cyfry oraz znak podkreślenia ('_') " "są dozwolone">>]; invalid_login -> <<"Niepoprawna nazwa użytkownika lub hasło">>; {too_short, Field, Min} -> [<<"Pole ">>, Field, <<" jest zbyt krótkie (minimum ">>, Min, <<" znaków)">>]; password_mismatch -> <<"Podane hasła nie są identyczne">>; twitter_unauthorized -> <<"Twitter odrzucił kombinację nazwy użytkownika oraz hasła " "które podałeś/podałaś">>; twitter_authorization_error -> <<"Nie mogę połączyć się z Twitter. Spróbuj ponownie później.">>; {invalid_url, Field} -> [<<"Pole ">>, Field, <<" z URL musi zaczynać się od 'http://'">>]; settings_updated -> [<<"Twoje ustawienia zostały poprawnie zaktualizowane">>] end.
ff5481fe3caf431eed48e6e09db1b4081f21bbe138cf793e3495151700916209
imdea-software/leap
PosExpression.ml
(***********************************************************************) (* *) LEAP (* *) , IMDEA Software Institute (* *) (* *) Copyright 2011 IMDEA Software Institute (* *) Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . (* You may obtain a copy of the License at *) (* *) (* -2.0 *) (* *) (* Unless required by applicable law or agreed to in writing, *) software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , (* either express or implied. *) (* See the License for the specific language governing permissions *) (* and limitations under the License. *) (* *) (***********************************************************************) open Printf open LeapLib module E = Expression module F = Formula module V = Variable.Make ( struct type sort_t = unit type info_t = unit end ) type tid = | VarTh of V.t | NoTid | CellLockId of V.t type expression = | Eq of tid * tid | InEq of tid * tid | Pred of string | PC of int * V.shared_or_local * bool | PCUpdate of int * tid | PCRange of int * int * V.shared_or_local * bool | True | False | And of expression * expression | Or of expression * expression | Not of expression | Implies of expression * expression | Iff of expression * expression exception Not_tid_var of tid module ThreadSet = Set.Make( struct let compare = Pervasives.compare type t = tid end ) module PredSet = Set.Make( struct let compare = Pervasives.compare type t = string end ) module PosSet = Set.Make( struct let compare = Pervasives.compare type t = int end ) module TermPool = Pool.Make ( struct type t = E.term let compare = Pervasives.compare end) (* Pool of terms *) let term_pool = TermPool.empty (* Configuration *) let abs_cell_id = "abs_cell_lock_" let abs_array_id = "abs_tid_array_" let abs_bucket_id = "abs_bucket_" let abs_lock_id = "abs_lock_" let defPredTableSize = 200 let abs_cell_counter = ref 0 let build_var ?(fresh=false) (id:V.id) (pr:bool) (th:V.shared_or_local) (p:V.procedure_name) : V.t = V.build id () pr th p () ~fresh:fresh let build_fresh (t:E.tid) (abs_id:V.id) : V.t = let new_tag = TermPool.tag term_pool (E.TidT t) in let id = (abs_id ^ string_of_int new_tag) in let var = build_var id false V.Shared V.GlobalScope ~fresh:true in var let rec conv_variable (v:E.V.t) : V.t = build_var (E.V.id v) (E.V.is_primed v) (conv_shared_or_local (E.V.parameter v)) (conv_procedure_name (E.V.scope v)) ~fresh:(E.V.is_fresh v) and conv_shared_or_local (th:E.V.shared_or_local) : V.shared_or_local = match th with | E.V.Shared -> V.Shared | E.V.Local t -> V.Local (conv_variable t) and conv_procedure_name (p:E.V.procedure_name) : V.procedure_name = match p with | E.V.GlobalScope -> V.GlobalScope | E.V.Scope proc -> V.Scope proc and conv_th (th:E.tid) : tid = match th with E.VarTh v -> VarTh (conv_variable v) | E.NoTid -> NoTid | E.CellLockId _ -> VarTh (build_fresh th abs_cell_id) | E.CellLockIdAt _ -> VarTh (build_fresh th abs_cell_id) | E.TidArrayRd _ -> VarTh (build_fresh th abs_array_id) | E.TidArrRd _ -> VarTh (build_fresh th abs_array_id) | E.PairTid _ -> VarTh (build_fresh th abs_array_id) | E.BucketTid _ -> VarTh (build_fresh th abs_bucket_id) | E.LockId _ -> VarTh (build_fresh th abs_lock_id) let rec tid_to_str (expr:tid) : string = match expr with VarTh v -> V.to_str v | NoTid -> "#" | CellLockId v -> V.to_str v ^ ".lockid" and param_tid_to_str (expr:tid) : string = match expr with VarTh v -> begin try sprintf "[%i]" (int_of_string (V.id v)) with _ -> sprintf "(%s)" (V.to_str v) end | NoTid -> sprintf "(#)" | CellLockId _ -> sprintf "(%s)" (tid_to_str expr) and priming_tid (t:tid) : tid = match t with VarTh v -> VarTh (V.prime v) | NoTid -> NoTid | CellLockId v -> CellLockId (V.prime v) and priming_option_tid (expr:V.shared_or_local) : V.shared_or_local = match expr with | V.Shared -> V.Shared | V.Local t -> V.Local (V.prime t) let rec expr_to_str (expr:expression) : string = match expr with Eq (t1,t2) -> sprintf "%s = %s" (tid_to_str t1) (tid_to_str t2) | InEq (t1, t2) -> sprintf "%s != %s" (tid_to_str t1) (tid_to_str t2) | Pred p -> p | PC (pc,t,p) -> let t_str = V.shared_or_local_to_str t in let v_name = if p then Conf.pc_name ^ "'" else Conf.pc_name in sprintf "%s%s=%i" v_name t_str pc | PCUpdate (pc,t) -> sprintf "%s' = %s{%s<-%i}" Conf.pc_name Conf.pc_name (tid_to_str t) pc | PCRange (pc1,pc2,t,p) -> let t_str = if p then V.shared_or_local_to_str (priming_option_tid t) else V.shared_or_local_to_str t in let v_name = if p then Conf.pc_name ^ "'" else Conf.pc_name in sprintf "%i <= %s%s <=%i" pc1 v_name t_str pc2 | True -> sprintf "true" | False -> sprintf "false" | And(f1, f2) -> sprintf "(%s /\\ %s)" (expr_to_str f1) (expr_to_str f2) | Or(f1,f2) -> sprintf "(%s \\/ %s)" (expr_to_str f1) (expr_to_str f2) | Not(f) -> sprintf "(~ %s)" (expr_to_str f) | Implies(f1,f2) -> sprintf "(%s -> %s)" (expr_to_str f1) (expr_to_str f2) | Iff (f1,f2) -> sprintf "(%s <-> %s)" (expr_to_str f1) (expr_to_str f2) let conj_list (es:expression list) : expression = match es with | [] -> True | x::xs -> List.fold_left (fun phi e -> And(e, phi)) x xs let disj_list (es:expression list) : expression = match es with | [] -> False | x::xs -> List.fold_left (fun phi e -> Or(e, phi)) x xs let rec all_preds (expr:expression) : string list = let all_preds_aux expr = match expr with Pred p -> [p] | And (e1,e2) -> all_preds e1 @ all_preds e2 | Or (e1,e2) -> all_preds e1 @ all_preds e2 | Not e -> all_preds e | Implies (e1,e2) -> all_preds e1 @ all_preds e2 | Iff (e1,e2) -> all_preds e1 @ all_preds e2 | _ -> [] in let pred_list = all_preds_aux expr in let pred_set = List.fold_left (fun s p -> PredSet.add p s ) PredSet.empty pred_list in PredSet.elements pred_set let voc (expr:expression) : tid list = let rec voc_aux exp = match exp with Eq (t1,t2) -> [t1;t2] | InEq (t1,t2) -> [t1;t2] | PC (_,th,_) -> begin match th with | V.Shared -> [] | V.Local t -> [VarTh t] end | PCUpdate (_,th) -> [th] | PCRange (_,_,th,_) -> begin match th with | V.Shared -> [] | V.Local t -> [VarTh t] end | And (e1,e2) -> voc_aux e1 @ voc_aux e2 | Or (e1,e2) -> voc_aux e1 @ voc_aux e2 | Not e -> voc_aux e | Implies (e1,e2) -> voc_aux e1 @ voc_aux e2 | Iff (e1,e2) -> voc_aux e1 @ voc_aux e2 | Pred _ -> [] | True -> [] | False -> [] in let voc_list = voc_aux expr in let voc_set = List.fold_left (fun set e -> ThreadSet.add e set) (ThreadSet.empty) (voc_list) in ThreadSet.elements voc_set let pos (expr:expression) : int list = let rec pos_aux exp = match exp with | PC (i,_,_) -> [i] | PCUpdate (i,_) -> [i] | PCRange (i,j,_,_) -> rangeList i j | And (e1,e2) -> pos_aux e1 @ pos_aux e2 | Or (e1,e2) -> pos_aux e1 @ pos_aux e2 | Not e -> pos_aux e | Implies (e1,e2) -> pos_aux e1 @ pos_aux e2 | Iff (e1,e2) -> pos_aux e1 @ pos_aux e2 | _ -> [] in let pos_list = pos_aux expr in let pos_set = List.fold_left (fun set e -> PosSet.add e set ) PosSet.empty pos_list in PosSet.elements pos_set let keep_locations (f:E.formula) : (expression * string list) = let curr_id = ref 0 in let pred_tbl = Hashtbl.create defPredTableSize in let rec apply (f:E.formula) = match f with F.True -> True | F.False -> False | F.And(e1,e2) -> And (apply e1, apply e2) | F.Or (e1, e2) -> Or (apply e1, apply e2) | F.Not e -> Not (apply e) | F.Implies (e1, e2) -> Implies (apply e1, apply e2) | F.Iff (e1, e2) -> apply (F.And (F.Implies (e1,e2), F.Implies (e2,e1))) | F.Literal(F.Atom(E.PC(i,th,pr))) -> PC (i, conv_shared_or_local th, pr) | F.Literal(F.Atom(E.PCUpdate (i,th))) -> PCUpdate (i, conv_th th) | F.Literal(F.Atom(E.PCRange(i,j,th,pr))) -> PCRange (i, j, conv_shared_or_local th, pr) | F.Literal (F.NegAtom (E.Eq (E.TidT t1, E.TidT t2))) -> apply (E.ineq_tid t1 t2) | F.Literal (F.Atom (E.Eq (E.TidT t1, E.TidT t2))) -> let th1 = conv_th t1 in let th2 = conv_th t2 in Eq (th1, th2) | F.Literal (F.NegAtom (E.InEq (E.TidT t1, E.TidT t2))) -> apply (E.eq_tid t1 t2) | F.Literal (F.Atom (E.InEq (E.TidT t1, E.TidT t2))) -> let th1 = conv_th t1 in let th2 = conv_th t2 in InEq (th1, th2) | _ -> begin if Hashtbl.mem pred_tbl f then Pred (Hashtbl.find pred_tbl f) else let new_pred = "pred" ^ (string_of_int !curr_id) in let _ = Hashtbl.add pred_tbl f new_pred in let _ = curr_id := !curr_id + 1 in Pred new_pred end in let new_formula = apply f in (new_formula, Hashtbl.fold (fun _ p xs -> p::xs) pred_tbl []) let rec has_pc (expr:expression) : bool = match expr with | Eq _ -> false | InEq _ -> false | Pred _ -> false | PC _ -> true | PCUpdate _ -> true | PCRange _ -> true | True -> false | False -> false | And (e1,e2) -> (has_pc e1) || (has_pc e2) | Or (e1,e2) -> (has_pc e1) || (has_pc e2) | Not e1 -> (has_pc e1) | Implies (e1,e2) -> (has_pc e1) || (has_pc e2) | Iff (e1,e2) -> (has_pc e1) || (has_pc e2) let rec expand_pc_range (expr:expression) : expression = let expand = expand_pc_range in match expr with And (e1,e2) -> And (expand e1, expand e2) | Or (e1,e2) -> Or (expand e1, expand e2) | Not (e) -> Not (expand e) | Implies (e1,e2) -> Implies (expand e1, expand e2) | Iff (e1,e2) -> Iff (expand e1, expand e2) | PCRange (i,j,th,pr) -> List.fold_left (fun phi k -> Or (phi, PC (k,th,pr)) ) (PC (i,th,pr)) (rangeList (i+1) j) | _ -> expr let rec nnf (expr:expression) : expression = match expr with | False -> False | True -> True | Eq _ | InEq _ | Pred _ | PC _ | PCUpdate _ | PCRange _ -> expr | Iff (e1,e2) -> And (nnf (Implies (e1,e2)),nnf (Implies(e2,e1))) | Implies(e1,e2) -> Or (nnf (Not e1), nnf e2) | And(e1,e2) -> And(nnf e1, nnf e2) | Or(e1,e2) -> Or(nnf e1, nnf e2) | Not (Not e) -> nnf e | Not (And (e1,e2)) -> Or (nnf (Not e1), nnf (Not e2)) | Not (Or (e1, e2)) -> And (nnf (Not e1), nnf (Not e2)) | Not (Implies (e1, e2)) -> And (nnf e1, nnf (Not e2)) | Not (Iff (e1, e2)) -> Or(And(nnf e1, nnf (Not e2)),And (nnf (Not e1), nnf e2)) | Not (Eq (x,y)) -> InEq (x,y) | Not (InEq (x,y)) -> Eq (x,y) | Not True -> False | Not False -> True | Not (Pred _) | Not (PC _) | Not (PCUpdate _) | Not (PCRange _) -> expr let rec dnf (expr:expression) : expression list list = match expr with Iff (e1,e2) -> dnf (Or (And (e1,e2), And (Not e1, Not e2))) | Implies(e1,e2) -> dnf (Or (Not e1, e2)) | Or(e1,e2) -> let e1_dnf = dnf e1 in let e2_dnf = dnf e2 in List.fold_left (fun final_lst x1 -> let lst = List.fold_left (fun l2 x2 -> (x1 @ x2) :: l2 ) [] e2_dnf in lst @ final_lst ) [] e1_dnf | And (e1,e2) -> dnf e1 @ dnf e2 | Not (Not e) -> dnf e | Not (And (e1,e2)) -> dnf (Or (Not e1, Not e2)) | Not (Or (e1, e2)) -> dnf (And (Not e1, Not e2)) | Not (Implies (e1, e2)) -> dnf (And (e1, Not e2)) | Not (Iff (e1, e2)) -> dnf (Or (And (e1, Not e2), And (Not e1, e2))) | e -> [[e]] let rec cnf (expr:expression) : expression list list = match expr with Iff (e1,e2) -> cnf (Or (And (e1,e2), And (Not e1, Not e2))) | Implies(e1,e2) -> cnf (Or (Not e1, e2)) | And(e1,e2) -> let e1_cnf = cnf e1 in let e2_cnf = cnf e2 in List.fold_left (fun final_lst x1 -> let lst = List.fold_left (fun l2 x2 -> (x1 @ x2) :: l2 ) [] e2_cnf in lst @ final_lst ) [] e1_cnf | Or (e1,e2) -> cnf e1 @ cnf e2 | Not (Not e) -> cnf e | Not (And (e1,e2)) -> cnf (Or (Not e1, Not e2)) | Not (Or (e1, e2)) -> cnf (And (Not e1, Not e2)) | Not (Implies (e1, e2)) -> cnf (And (e1, Not e2)) | Not (Iff (e1, e2)) -> cnf (Or (And (e1, Not e2), And (Not e1, e2))) | e -> [[e]] (* Vocabulary to variable conversion *) let voc_to_var (t:tid) : V.t = match t with | VarTh v -> v | _ -> raise(Not_tid_var t)
null
https://raw.githubusercontent.com/imdea-software/leap/5f946163c0f80ff9162db605a75b7ce2e27926ef/src/expression/PosExpression.ml
ocaml
********************************************************************* You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************* Pool of terms Configuration Vocabulary to variable conversion
LEAP , IMDEA Software Institute Copyright 2011 IMDEA Software Institute Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , open Printf open LeapLib module E = Expression module F = Formula module V = Variable.Make ( struct type sort_t = unit type info_t = unit end ) type tid = | VarTh of V.t | NoTid | CellLockId of V.t type expression = | Eq of tid * tid | InEq of tid * tid | Pred of string | PC of int * V.shared_or_local * bool | PCUpdate of int * tid | PCRange of int * int * V.shared_or_local * bool | True | False | And of expression * expression | Or of expression * expression | Not of expression | Implies of expression * expression | Iff of expression * expression exception Not_tid_var of tid module ThreadSet = Set.Make( struct let compare = Pervasives.compare type t = tid end ) module PredSet = Set.Make( struct let compare = Pervasives.compare type t = string end ) module PosSet = Set.Make( struct let compare = Pervasives.compare type t = int end ) module TermPool = Pool.Make ( struct type t = E.term let compare = Pervasives.compare end) let term_pool = TermPool.empty let abs_cell_id = "abs_cell_lock_" let abs_array_id = "abs_tid_array_" let abs_bucket_id = "abs_bucket_" let abs_lock_id = "abs_lock_" let defPredTableSize = 200 let abs_cell_counter = ref 0 let build_var ?(fresh=false) (id:V.id) (pr:bool) (th:V.shared_or_local) (p:V.procedure_name) : V.t = V.build id () pr th p () ~fresh:fresh let build_fresh (t:E.tid) (abs_id:V.id) : V.t = let new_tag = TermPool.tag term_pool (E.TidT t) in let id = (abs_id ^ string_of_int new_tag) in let var = build_var id false V.Shared V.GlobalScope ~fresh:true in var let rec conv_variable (v:E.V.t) : V.t = build_var (E.V.id v) (E.V.is_primed v) (conv_shared_or_local (E.V.parameter v)) (conv_procedure_name (E.V.scope v)) ~fresh:(E.V.is_fresh v) and conv_shared_or_local (th:E.V.shared_or_local) : V.shared_or_local = match th with | E.V.Shared -> V.Shared | E.V.Local t -> V.Local (conv_variable t) and conv_procedure_name (p:E.V.procedure_name) : V.procedure_name = match p with | E.V.GlobalScope -> V.GlobalScope | E.V.Scope proc -> V.Scope proc and conv_th (th:E.tid) : tid = match th with E.VarTh v -> VarTh (conv_variable v) | E.NoTid -> NoTid | E.CellLockId _ -> VarTh (build_fresh th abs_cell_id) | E.CellLockIdAt _ -> VarTh (build_fresh th abs_cell_id) | E.TidArrayRd _ -> VarTh (build_fresh th abs_array_id) | E.TidArrRd _ -> VarTh (build_fresh th abs_array_id) | E.PairTid _ -> VarTh (build_fresh th abs_array_id) | E.BucketTid _ -> VarTh (build_fresh th abs_bucket_id) | E.LockId _ -> VarTh (build_fresh th abs_lock_id) let rec tid_to_str (expr:tid) : string = match expr with VarTh v -> V.to_str v | NoTid -> "#" | CellLockId v -> V.to_str v ^ ".lockid" and param_tid_to_str (expr:tid) : string = match expr with VarTh v -> begin try sprintf "[%i]" (int_of_string (V.id v)) with _ -> sprintf "(%s)" (V.to_str v) end | NoTid -> sprintf "(#)" | CellLockId _ -> sprintf "(%s)" (tid_to_str expr) and priming_tid (t:tid) : tid = match t with VarTh v -> VarTh (V.prime v) | NoTid -> NoTid | CellLockId v -> CellLockId (V.prime v) and priming_option_tid (expr:V.shared_or_local) : V.shared_or_local = match expr with | V.Shared -> V.Shared | V.Local t -> V.Local (V.prime t) let rec expr_to_str (expr:expression) : string = match expr with Eq (t1,t2) -> sprintf "%s = %s" (tid_to_str t1) (tid_to_str t2) | InEq (t1, t2) -> sprintf "%s != %s" (tid_to_str t1) (tid_to_str t2) | Pred p -> p | PC (pc,t,p) -> let t_str = V.shared_or_local_to_str t in let v_name = if p then Conf.pc_name ^ "'" else Conf.pc_name in sprintf "%s%s=%i" v_name t_str pc | PCUpdate (pc,t) -> sprintf "%s' = %s{%s<-%i}" Conf.pc_name Conf.pc_name (tid_to_str t) pc | PCRange (pc1,pc2,t,p) -> let t_str = if p then V.shared_or_local_to_str (priming_option_tid t) else V.shared_or_local_to_str t in let v_name = if p then Conf.pc_name ^ "'" else Conf.pc_name in sprintf "%i <= %s%s <=%i" pc1 v_name t_str pc2 | True -> sprintf "true" | False -> sprintf "false" | And(f1, f2) -> sprintf "(%s /\\ %s)" (expr_to_str f1) (expr_to_str f2) | Or(f1,f2) -> sprintf "(%s \\/ %s)" (expr_to_str f1) (expr_to_str f2) | Not(f) -> sprintf "(~ %s)" (expr_to_str f) | Implies(f1,f2) -> sprintf "(%s -> %s)" (expr_to_str f1) (expr_to_str f2) | Iff (f1,f2) -> sprintf "(%s <-> %s)" (expr_to_str f1) (expr_to_str f2) let conj_list (es:expression list) : expression = match es with | [] -> True | x::xs -> List.fold_left (fun phi e -> And(e, phi)) x xs let disj_list (es:expression list) : expression = match es with | [] -> False | x::xs -> List.fold_left (fun phi e -> Or(e, phi)) x xs let rec all_preds (expr:expression) : string list = let all_preds_aux expr = match expr with Pred p -> [p] | And (e1,e2) -> all_preds e1 @ all_preds e2 | Or (e1,e2) -> all_preds e1 @ all_preds e2 | Not e -> all_preds e | Implies (e1,e2) -> all_preds e1 @ all_preds e2 | Iff (e1,e2) -> all_preds e1 @ all_preds e2 | _ -> [] in let pred_list = all_preds_aux expr in let pred_set = List.fold_left (fun s p -> PredSet.add p s ) PredSet.empty pred_list in PredSet.elements pred_set let voc (expr:expression) : tid list = let rec voc_aux exp = match exp with Eq (t1,t2) -> [t1;t2] | InEq (t1,t2) -> [t1;t2] | PC (_,th,_) -> begin match th with | V.Shared -> [] | V.Local t -> [VarTh t] end | PCUpdate (_,th) -> [th] | PCRange (_,_,th,_) -> begin match th with | V.Shared -> [] | V.Local t -> [VarTh t] end | And (e1,e2) -> voc_aux e1 @ voc_aux e2 | Or (e1,e2) -> voc_aux e1 @ voc_aux e2 | Not e -> voc_aux e | Implies (e1,e2) -> voc_aux e1 @ voc_aux e2 | Iff (e1,e2) -> voc_aux e1 @ voc_aux e2 | Pred _ -> [] | True -> [] | False -> [] in let voc_list = voc_aux expr in let voc_set = List.fold_left (fun set e -> ThreadSet.add e set) (ThreadSet.empty) (voc_list) in ThreadSet.elements voc_set let pos (expr:expression) : int list = let rec pos_aux exp = match exp with | PC (i,_,_) -> [i] | PCUpdate (i,_) -> [i] | PCRange (i,j,_,_) -> rangeList i j | And (e1,e2) -> pos_aux e1 @ pos_aux e2 | Or (e1,e2) -> pos_aux e1 @ pos_aux e2 | Not e -> pos_aux e | Implies (e1,e2) -> pos_aux e1 @ pos_aux e2 | Iff (e1,e2) -> pos_aux e1 @ pos_aux e2 | _ -> [] in let pos_list = pos_aux expr in let pos_set = List.fold_left (fun set e -> PosSet.add e set ) PosSet.empty pos_list in PosSet.elements pos_set let keep_locations (f:E.formula) : (expression * string list) = let curr_id = ref 0 in let pred_tbl = Hashtbl.create defPredTableSize in let rec apply (f:E.formula) = match f with F.True -> True | F.False -> False | F.And(e1,e2) -> And (apply e1, apply e2) | F.Or (e1, e2) -> Or (apply e1, apply e2) | F.Not e -> Not (apply e) | F.Implies (e1, e2) -> Implies (apply e1, apply e2) | F.Iff (e1, e2) -> apply (F.And (F.Implies (e1,e2), F.Implies (e2,e1))) | F.Literal(F.Atom(E.PC(i,th,pr))) -> PC (i, conv_shared_or_local th, pr) | F.Literal(F.Atom(E.PCUpdate (i,th))) -> PCUpdate (i, conv_th th) | F.Literal(F.Atom(E.PCRange(i,j,th,pr))) -> PCRange (i, j, conv_shared_or_local th, pr) | F.Literal (F.NegAtom (E.Eq (E.TidT t1, E.TidT t2))) -> apply (E.ineq_tid t1 t2) | F.Literal (F.Atom (E.Eq (E.TidT t1, E.TidT t2))) -> let th1 = conv_th t1 in let th2 = conv_th t2 in Eq (th1, th2) | F.Literal (F.NegAtom (E.InEq (E.TidT t1, E.TidT t2))) -> apply (E.eq_tid t1 t2) | F.Literal (F.Atom (E.InEq (E.TidT t1, E.TidT t2))) -> let th1 = conv_th t1 in let th2 = conv_th t2 in InEq (th1, th2) | _ -> begin if Hashtbl.mem pred_tbl f then Pred (Hashtbl.find pred_tbl f) else let new_pred = "pred" ^ (string_of_int !curr_id) in let _ = Hashtbl.add pred_tbl f new_pred in let _ = curr_id := !curr_id + 1 in Pred new_pred end in let new_formula = apply f in (new_formula, Hashtbl.fold (fun _ p xs -> p::xs) pred_tbl []) let rec has_pc (expr:expression) : bool = match expr with | Eq _ -> false | InEq _ -> false | Pred _ -> false | PC _ -> true | PCUpdate _ -> true | PCRange _ -> true | True -> false | False -> false | And (e1,e2) -> (has_pc e1) || (has_pc e2) | Or (e1,e2) -> (has_pc e1) || (has_pc e2) | Not e1 -> (has_pc e1) | Implies (e1,e2) -> (has_pc e1) || (has_pc e2) | Iff (e1,e2) -> (has_pc e1) || (has_pc e2) let rec expand_pc_range (expr:expression) : expression = let expand = expand_pc_range in match expr with And (e1,e2) -> And (expand e1, expand e2) | Or (e1,e2) -> Or (expand e1, expand e2) | Not (e) -> Not (expand e) | Implies (e1,e2) -> Implies (expand e1, expand e2) | Iff (e1,e2) -> Iff (expand e1, expand e2) | PCRange (i,j,th,pr) -> List.fold_left (fun phi k -> Or (phi, PC (k,th,pr)) ) (PC (i,th,pr)) (rangeList (i+1) j) | _ -> expr let rec nnf (expr:expression) : expression = match expr with | False -> False | True -> True | Eq _ | InEq _ | Pred _ | PC _ | PCUpdate _ | PCRange _ -> expr | Iff (e1,e2) -> And (nnf (Implies (e1,e2)),nnf (Implies(e2,e1))) | Implies(e1,e2) -> Or (nnf (Not e1), nnf e2) | And(e1,e2) -> And(nnf e1, nnf e2) | Or(e1,e2) -> Or(nnf e1, nnf e2) | Not (Not e) -> nnf e | Not (And (e1,e2)) -> Or (nnf (Not e1), nnf (Not e2)) | Not (Or (e1, e2)) -> And (nnf (Not e1), nnf (Not e2)) | Not (Implies (e1, e2)) -> And (nnf e1, nnf (Not e2)) | Not (Iff (e1, e2)) -> Or(And(nnf e1, nnf (Not e2)),And (nnf (Not e1), nnf e2)) | Not (Eq (x,y)) -> InEq (x,y) | Not (InEq (x,y)) -> Eq (x,y) | Not True -> False | Not False -> True | Not (Pred _) | Not (PC _) | Not (PCUpdate _) | Not (PCRange _) -> expr let rec dnf (expr:expression) : expression list list = match expr with Iff (e1,e2) -> dnf (Or (And (e1,e2), And (Not e1, Not e2))) | Implies(e1,e2) -> dnf (Or (Not e1, e2)) | Or(e1,e2) -> let e1_dnf = dnf e1 in let e2_dnf = dnf e2 in List.fold_left (fun final_lst x1 -> let lst = List.fold_left (fun l2 x2 -> (x1 @ x2) :: l2 ) [] e2_dnf in lst @ final_lst ) [] e1_dnf | And (e1,e2) -> dnf e1 @ dnf e2 | Not (Not e) -> dnf e | Not (And (e1,e2)) -> dnf (Or (Not e1, Not e2)) | Not (Or (e1, e2)) -> dnf (And (Not e1, Not e2)) | Not (Implies (e1, e2)) -> dnf (And (e1, Not e2)) | Not (Iff (e1, e2)) -> dnf (Or (And (e1, Not e2), And (Not e1, e2))) | e -> [[e]] let rec cnf (expr:expression) : expression list list = match expr with Iff (e1,e2) -> cnf (Or (And (e1,e2), And (Not e1, Not e2))) | Implies(e1,e2) -> cnf (Or (Not e1, e2)) | And(e1,e2) -> let e1_cnf = cnf e1 in let e2_cnf = cnf e2 in List.fold_left (fun final_lst x1 -> let lst = List.fold_left (fun l2 x2 -> (x1 @ x2) :: l2 ) [] e2_cnf in lst @ final_lst ) [] e1_cnf | Or (e1,e2) -> cnf e1 @ cnf e2 | Not (Not e) -> cnf e | Not (And (e1,e2)) -> cnf (Or (Not e1, Not e2)) | Not (Or (e1, e2)) -> cnf (And (Not e1, Not e2)) | Not (Implies (e1, e2)) -> cnf (And (e1, Not e2)) | Not (Iff (e1, e2)) -> cnf (Or (And (e1, Not e2), And (Not e1, e2))) | e -> [[e]] let voc_to_var (t:tid) : V.t = match t with | VarTh v -> v | _ -> raise(Not_tid_var t)
b08a738574c9317e7407f2319366a37f75512077c4fe14c388f6c528efd856a4
karamellpelle/grid
Fancy.hs
grid is a game written in Haskell Copyright ( C ) 2018 -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or -- (at your option) any later version. -- -- grid 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 grid. If not, see </>. -- module Game.Run.RunWorld.Scene.Fancy ( Scene (..), makeScene, makeSceneEmpty, remakeScene, makeSceneProj3D, makeSceneProj2D, module Game.Data.Shape, module Game.Run.RunWorld.Scene.Fancy.Noise, module Game.Run.RunWorld.Scene.Fancy.Tweak, ) where import MyPrelude import File import Game import Game.Data.Shape import Game.Grid.GridWorld.Node import Game.Run.RunWorld.Scene.Fancy.Noise import Game.Run.RunWorld.Scene.Fancy.Tweak import System.Random import OpenGL import OpenGL.Helpers data Scene = Scene { GL sceneFBO :: !GLuint, sceneTex :: !GLuint, sceneDepthStencil :: !GLuint, sceneWth :: !UInt, sceneHth :: !UInt, sceneShape :: !Shape, sceneProj3D :: !Mat4, sceneProj2D :: !Mat4, -- Noise sceneNoise :: !Noise, -- Tweak sceneTweak :: !Tweak } makeSceneEmpty :: MEnv' Scene makeSceneEmpty = makeScene 1 1 -- | make a Scene from size makeScene :: UInt -> UInt -> MEnv' Scene makeScene wth hth = io $ do " makeScene begin " fbo debugGLError ' " begin : " fbo <- bindNewFBO debugGLError ' " end : " -- tex --debugGLError' "glFramebufferTexture2D begin: " tex <- bindNewTex gl_TEXTURE_2D glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $ fI gl_LINEAR glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $ fI gl_LINEAR glTexImage2D gl_TEXTURE_2D 0 (fI gl_RGBA) (fI wth) (fI hth) 0 gl_RGBA gl_UNSIGNED_BYTE nullPtr glFramebufferTexture2D gl_FRAMEBUFFER gl_COLOR_ATTACHMENT0 gl_TEXTURE_2D tex 0 --debugGLError' "glFramebufferTexture2D end: " depthstencil --debugGLError' "bindNewRBO begin: " depthstencil <- bindNewRBO --debugGLError' "bindNewRBO end: " --debugGLError' "glRenderBufferStorage begin: " glRenderbufferStorage gl_RENDERBUFFER gl_DEPTH24_STENCIL8_OES (fI wth) (fI hth) --debugGLError' "glRenderBufferStorage end: " --debugGLError' "glFramebufferRenderbuffer DEPTH begin: " glFramebufferRenderbuffer gl_FRAMEBUFFER gl_DEPTH_ATTACHMENT gl_RENDERBUFFER depthstencil --debugGLError' "glFramebufferRenderbuffer DEPTH end: " --debugGLError' "glFramebufferRenderbuffer DEPTH begin: " glFramebufferRenderbuffer gl_FRAMEBUFFER gl_STENCIL_ATTACHMENT gl_RENDERBUFFER depthstencil --debugGLError' "glFramebufferRenderbuffer DEPTH end: " -- check status debugGLError ' " glCheckFramebufferStatus begin : " status <- glCheckFramebufferStatus gl_FRAMEBUFFER debugGLFramebufferStatus ' " : " status unless (status == gl_FRAMEBUFFER_COMPLETE) $ error "makeScene: could not create framebuffer!" debugGLError ' " glCheckFramebufferStatus end : " -- Noise noise <- makeNoise " makeScene end " --putStrLn "" let shape = shapeOfSize wth hth return Scene { sceneFBO = fbo, sceneTex = tex, sceneDepthStencil = depthstencil, sceneWth = wth, sceneHth = hth, sceneShape = shape, sceneProj3D = makeSceneProj3D (fI wth) (fI hth), sceneProj2D = makeSceneProj2D (shapeWth shape) (shapeHth shape), sceneNoise = noise, sceneTweak = makeTweak } -- | remake Scene remakeScene :: Scene -> UInt -> UInt -> MEnv' Scene remakeScene scene wth hth = io $ do " remakeScene begin . wth = " + + show wth + + " , hth = " + + show hth -- destroy --debugGLError' "delDepthStencil begin: " delRBO $ sceneDepthStencil scene --debugGLError' "delDepthStencil end: " --debugGLError' "delTex begin: " delTex $ sceneTex scene --debugGLError' "delTex end: " --debugGLError' "delFBO begin: " delFBO $ sceneFBO scene --debugGLError' "delFBO end: " fbo debugGLError ' " begin : " fbo <- bindNewFBO debugGLError ' " end : " -- tex --debugGLError' "bindNewTex begin: " tex <- bindNewTex gl_TEXTURE_2D --debugGLError' "bindNewTex end: " glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $ fI gl_LINEAR glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $ fI gl_LINEAR --debugGLError' "glTexImage2D begin: " glTexImage2D gl_TEXTURE_2D 0 (fI gl_RGBA) (fI wth) (fI hth) 0 gl_RGBA gl_UNSIGNED_BYTE nullPtr --debugGLError' "glTexImage2D end: " --debugGLError' "glFramebufferTexture2D begin: " glFramebufferTexture2D gl_FRAMEBUFFER gl_COLOR_ATTACHMENT0 gl_TEXTURE_2D tex 0 --debugGLError' "glFramebufferTexture2D end: " depthstencil --debugGLError' "bindNewRBO begin: " depthstencil <- bindNewRBO --debugGLError' "bindNewRBO end: " --debugGLError' "glRenderbufferStorage begin: " glRenderbufferStorage gl_RENDERBUFFER gl_DEPTH24_STENCIL8_OES (fI wth) (fI hth) --debugGLError' "glRenderbufferStorage end: " --debugGLError' "glFramebufferRenderbuffer DEPTH begin: " glFramebufferRenderbuffer gl_FRAMEBUFFER gl_DEPTH_ATTACHMENT gl_RENDERBUFFER depthstencil --debugGLError' "glFramebufferRenderbuffer DEPTH end: " --debugGLError' "glFramebufferRenderbuffer STENCIL begin: " glFramebufferRenderbuffer gl_FRAMEBUFFER gl_STENCIL_ATTACHMENT gl_RENDERBUFFER depthstencil --debugGLError' "glFramebufferRenderbuffer STENCIL end: " status <- glCheckFramebufferStatus gl_FRAMEBUFFER debugGLFramebufferStatus ' " : " status unless (status == gl_FRAMEBUFFER_COMPLETE) $ error "remakeScene: could not create framebuffer!" let shape = shapeOfSize wth hth . " --putStrLn "" return scene { sceneFBO = fbo, sceneTex = tex, sceneDepthStencil = depthstencil, sceneWth = wth, sceneHth = hth, sceneShape = shape, sceneProj3D = makeSceneProj3D (fI wth) (fI hth), sceneProj2D = makeSceneProj2D (shapeWth shape) (shapeHth shape) } makeSceneProj3D :: Float -> Float -> Mat4 makeSceneProj3D wth hth = mat4Perspective valueFOVY (wth / hth) valueNear valueFar where valueFOVY = valuePerspectiveFOVY valueNear = valuePerspectiveNear valueFar = valuePerspectiveFar makeSceneProj2D :: Float -> Float -> Mat4 makeSceneProj2D wth hth = mat4Ortho2D 0 wth hth 0
null
https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/Run/RunWorld/Scene/Fancy.hs
haskell
This file is part of grid. grid is free software: you can redistribute it and/or modify (at your option) any later version. grid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with grid. If not, see </>. Noise Tweak | make a Scene from size tex debugGLError' "glFramebufferTexture2D begin: " debugGLError' "glFramebufferTexture2D end: " debugGLError' "bindNewRBO begin: " debugGLError' "bindNewRBO end: " debugGLError' "glRenderBufferStorage begin: " debugGLError' "glRenderBufferStorage end: " debugGLError' "glFramebufferRenderbuffer DEPTH begin: " debugGLError' "glFramebufferRenderbuffer DEPTH end: " debugGLError' "glFramebufferRenderbuffer DEPTH begin: " debugGLError' "glFramebufferRenderbuffer DEPTH end: " check status Noise putStrLn "" | remake Scene destroy debugGLError' "delDepthStencil begin: " debugGLError' "delDepthStencil end: " debugGLError' "delTex begin: " debugGLError' "delTex end: " debugGLError' "delFBO begin: " debugGLError' "delFBO end: " tex debugGLError' "bindNewTex begin: " debugGLError' "bindNewTex end: " debugGLError' "glTexImage2D begin: " debugGLError' "glTexImage2D end: " debugGLError' "glFramebufferTexture2D begin: " debugGLError' "glFramebufferTexture2D end: " debugGLError' "bindNewRBO begin: " debugGLError' "bindNewRBO end: " debugGLError' "glRenderbufferStorage begin: " debugGLError' "glRenderbufferStorage end: " debugGLError' "glFramebufferRenderbuffer DEPTH begin: " debugGLError' "glFramebufferRenderbuffer DEPTH end: " debugGLError' "glFramebufferRenderbuffer STENCIL begin: " debugGLError' "glFramebufferRenderbuffer STENCIL end: " putStrLn ""
grid is a game written in Haskell Copyright ( C ) 2018 it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License module Game.Run.RunWorld.Scene.Fancy ( Scene (..), makeScene, makeSceneEmpty, remakeScene, makeSceneProj3D, makeSceneProj2D, module Game.Data.Shape, module Game.Run.RunWorld.Scene.Fancy.Noise, module Game.Run.RunWorld.Scene.Fancy.Tweak, ) where import MyPrelude import File import Game import Game.Data.Shape import Game.Grid.GridWorld.Node import Game.Run.RunWorld.Scene.Fancy.Noise import Game.Run.RunWorld.Scene.Fancy.Tweak import System.Random import OpenGL import OpenGL.Helpers data Scene = Scene { GL sceneFBO :: !GLuint, sceneTex :: !GLuint, sceneDepthStencil :: !GLuint, sceneWth :: !UInt, sceneHth :: !UInt, sceneShape :: !Shape, sceneProj3D :: !Mat4, sceneProj2D :: !Mat4, sceneNoise :: !Noise, sceneTweak :: !Tweak } makeSceneEmpty :: MEnv' Scene makeSceneEmpty = makeScene 1 1 makeScene :: UInt -> UInt -> MEnv' Scene makeScene wth hth = io $ do " makeScene begin " fbo debugGLError ' " begin : " fbo <- bindNewFBO debugGLError ' " end : " tex <- bindNewTex gl_TEXTURE_2D glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $ fI gl_LINEAR glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $ fI gl_LINEAR glTexImage2D gl_TEXTURE_2D 0 (fI gl_RGBA) (fI wth) (fI hth) 0 gl_RGBA gl_UNSIGNED_BYTE nullPtr glFramebufferTexture2D gl_FRAMEBUFFER gl_COLOR_ATTACHMENT0 gl_TEXTURE_2D tex 0 depthstencil depthstencil <- bindNewRBO glRenderbufferStorage gl_RENDERBUFFER gl_DEPTH24_STENCIL8_OES (fI wth) (fI hth) glFramebufferRenderbuffer gl_FRAMEBUFFER gl_DEPTH_ATTACHMENT gl_RENDERBUFFER depthstencil glFramebufferRenderbuffer gl_FRAMEBUFFER gl_STENCIL_ATTACHMENT gl_RENDERBUFFER depthstencil debugGLError ' " glCheckFramebufferStatus begin : " status <- glCheckFramebufferStatus gl_FRAMEBUFFER debugGLFramebufferStatus ' " : " status unless (status == gl_FRAMEBUFFER_COMPLETE) $ error "makeScene: could not create framebuffer!" debugGLError ' " glCheckFramebufferStatus end : " noise <- makeNoise " makeScene end " let shape = shapeOfSize wth hth return Scene { sceneFBO = fbo, sceneTex = tex, sceneDepthStencil = depthstencil, sceneWth = wth, sceneHth = hth, sceneShape = shape, sceneProj3D = makeSceneProj3D (fI wth) (fI hth), sceneProj2D = makeSceneProj2D (shapeWth shape) (shapeHth shape), sceneNoise = noise, sceneTweak = makeTweak } remakeScene :: Scene -> UInt -> UInt -> MEnv' Scene remakeScene scene wth hth = io $ do " remakeScene begin . wth = " + + show wth + + " , hth = " + + show hth delRBO $ sceneDepthStencil scene delTex $ sceneTex scene delFBO $ sceneFBO scene fbo debugGLError ' " begin : " fbo <- bindNewFBO debugGLError ' " end : " tex <- bindNewTex gl_TEXTURE_2D glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $ fI gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $ fI gl_LINEAR glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $ fI gl_LINEAR glTexImage2D gl_TEXTURE_2D 0 (fI gl_RGBA) (fI wth) (fI hth) 0 gl_RGBA gl_UNSIGNED_BYTE nullPtr glFramebufferTexture2D gl_FRAMEBUFFER gl_COLOR_ATTACHMENT0 gl_TEXTURE_2D tex 0 depthstencil depthstencil <- bindNewRBO glRenderbufferStorage gl_RENDERBUFFER gl_DEPTH24_STENCIL8_OES (fI wth) (fI hth) glFramebufferRenderbuffer gl_FRAMEBUFFER gl_DEPTH_ATTACHMENT gl_RENDERBUFFER depthstencil glFramebufferRenderbuffer gl_FRAMEBUFFER gl_STENCIL_ATTACHMENT gl_RENDERBUFFER depthstencil status <- glCheckFramebufferStatus gl_FRAMEBUFFER debugGLFramebufferStatus ' " : " status unless (status == gl_FRAMEBUFFER_COMPLETE) $ error "remakeScene: could not create framebuffer!" let shape = shapeOfSize wth hth . " return scene { sceneFBO = fbo, sceneTex = tex, sceneDepthStencil = depthstencil, sceneWth = wth, sceneHth = hth, sceneShape = shape, sceneProj3D = makeSceneProj3D (fI wth) (fI hth), sceneProj2D = makeSceneProj2D (shapeWth shape) (shapeHth shape) } makeSceneProj3D :: Float -> Float -> Mat4 makeSceneProj3D wth hth = mat4Perspective valueFOVY (wth / hth) valueNear valueFar where valueFOVY = valuePerspectiveFOVY valueNear = valuePerspectiveNear valueFar = valuePerspectiveFar makeSceneProj2D :: Float -> Float -> Mat4 makeSceneProj2D wth hth = mat4Ortho2D 0 wth hth 0
6e223e083adb50b03505040a3864dcaf82513ef65cf6060a181b8470738137a3
tolysz/ghcjs-stack
World.hs
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.World Copyright : ( c ) 2009 -- License : BSD-like -- -- Maintainer : -- Stability : provisional -- Portability : portable -- Interface to the world - file that contains a list of explicitly -- requested packages. Meant to be imported qualified. -- -- A world file entry stores the package-name, package-version, and -- user flags. -- For example, the entry generated by -- # cabal install stm-io-hooks --flags="-debug" -- looks like this: # stm - io - hooks -any --flags="-debug " -- To rebuild/upgrade the packages in world (e.g. when updating the compiler) -- use -- # cabal install world -- ----------------------------------------------------------------------------- module Distribution.Client.World ( WorldPkgInfo(..), insert, delete, getContents, ) where import Distribution.Package ( Dependency(..) ) import Distribution.PackageDescription ( FlagAssignment, FlagName(FlagName) ) import Distribution.Verbosity ( Verbosity ) import Distribution.Simple.Utils ( die, info, chattyTry, writeFileAtomic ) import Distribution.Text ( Text(..), display, simpleParse ) import qualified Distribution.Compat.ReadP as Parse import Distribution.Compat.Exception ( catchIO ) import qualified Text.PrettyPrint as Disp import Text.PrettyPrint ( (<>), (<+>) ) import Data.Char as Char import Data.List ( unionBy, deleteFirstsBy, nubBy ) import System.IO.Error ( isDoesNotExistError ) import qualified Data.ByteString.Lazy.Char8 as B import Prelude hiding (getContents) data WorldPkgInfo = WorldPkgInfo Dependency FlagAssignment deriving (Show,Eq) -- | Adds packages to the world file; creates the file if it doesn't -- exist yet. Version constraints and flag assignments for a package are -- updated if already present. IO errors are non-fatal. insert :: Verbosity -> FilePath -> [WorldPkgInfo] -> IO () insert = modifyWorld $ unionBy equalUDep -- | Removes packages from the world file. Note : Currently unused as there is no mechanism in ( yet ) to -- handle uninstalls. IO errors are non-fatal. delete :: Verbosity -> FilePath -> [WorldPkgInfo] -> IO () delete = modifyWorld $ flip (deleteFirstsBy equalUDep) -- | WorldPkgInfo values are considered equal if they refer to -- the same package, i.e., we don't care about differing versions or flags. equalUDep :: WorldPkgInfo -> WorldPkgInfo -> Bool equalUDep (WorldPkgInfo (Dependency pkg1 _) _) (WorldPkgInfo (Dependency pkg2 _) _) = pkg1 == pkg2 -- | Modifies the world file by applying an update-function ('unionBy' -- for 'insert', 'deleteFirstsBy' for 'delete') to the given list of -- packages. IO errors are considered non-fatal. modifyWorld :: ([WorldPkgInfo] -> [WorldPkgInfo] -> [WorldPkgInfo]) -- ^ Function that defines how -- the list of user packages are merged with -- existing world packages. -> Verbosity -> FilePath -- ^ Location of the world file -> [WorldPkgInfo] -- ^ list of user supplied packages -> IO () modifyWorld _ _ _ [] = return () modifyWorld f verbosity world pkgs = chattyTry "Error while updating world-file. " $ do pkgsOldWorld <- getContents world -- Filter out packages that are not in the world file: let pkgsNewWorld = nubBy equalUDep $ f pkgs pkgsOldWorld ' Dependency ' is not an instance , so we need to check for -- equivalence the awkward way: if not (all (`elem` pkgsOldWorld) pkgsNewWorld && all (`elem` pkgsNewWorld) pkgsOldWorld) then do info verbosity "Updating world file..." writeFileAtomic world . B.pack $ unlines [ (display pkg) | pkg <- pkgsNewWorld] else info verbosity "World file is already up to date." -- | Returns the content of the world file as a list getContents :: FilePath -> IO [WorldPkgInfo] getContents world = do content <- safelyReadFile world let result = map simpleParse (lines $ B.unpack content) case sequence result of Nothing -> die "Could not parse world file." Just xs -> return xs where safelyReadFile :: FilePath -> IO B.ByteString safelyReadFile file = B.readFile file `catchIO` handler where handler e | isDoesNotExistError e = return B.empty | otherwise = ioError e instance Text WorldPkgInfo where disp (WorldPkgInfo dep flags) = disp dep <+> dispFlags flags where dispFlags [] = Disp.empty dispFlags fs = Disp.text "--flags=" <> Disp.doubleQuotes (flagAssToDoc fs) flagAssToDoc = foldr (\(FlagName fname,val) flagAssDoc -> (if not val then Disp.char '-' else Disp.empty) Disp.<> Disp.text fname Disp.<+> flagAssDoc) Disp.empty parse = do dep <- parse Parse.skipSpaces flagAss <- Parse.option [] parseFlagAssignment return $ WorldPkgInfo dep flagAss where parseFlagAssignment :: Parse.ReadP r FlagAssignment parseFlagAssignment = do _ <- Parse.string "--flags" Parse.skipSpaces _ <- Parse.char '=' Parse.skipSpaces inDoubleQuotes $ Parse.many1 flag where inDoubleQuotes :: Parse.ReadP r a -> Parse.ReadP r a inDoubleQuotes = Parse.between (Parse.char '"') (Parse.char '"') flag = do Parse.skipSpaces val <- negative Parse.+++ positive name <- ident Parse.skipSpaces return (FlagName name,val) negative = do _ <- Parse.char '-' return False positive = return True ident :: Parse.ReadP r String ident = do First character must be a letter / digit to avoid flags -- like "+-debug": c <- Parse.satisfy Char.isAlphaNum cs <- Parse.munch (\ch -> Char.isAlphaNum ch || ch == '_' || ch == '-') return (c:cs)
null
https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal-next/cabal-install/Distribution/Client/World.hs
haskell
--------------------------------------------------------------------------- | Module : Distribution.Client.World License : BSD-like Maintainer : Stability : provisional Portability : portable requested packages. Meant to be imported qualified. A world file entry stores the package-name, package-version, and user flags. For example, the entry generated by # cabal install stm-io-hooks --flags="-debug" looks like this: flags="-debug " To rebuild/upgrade the packages in world (e.g. when updating the compiler) use # cabal install world --------------------------------------------------------------------------- | Adds packages to the world file; creates the file if it doesn't exist yet. Version constraints and flag assignments for a package are updated if already present. IO errors are non-fatal. | Removes packages from the world file. handle uninstalls. IO errors are non-fatal. | WorldPkgInfo values are considered equal if they refer to the same package, i.e., we don't care about differing versions or flags. | Modifies the world file by applying an update-function ('unionBy' for 'insert', 'deleteFirstsBy' for 'delete') to the given list of packages. IO errors are considered non-fatal. ^ Function that defines how the list of user packages are merged with existing world packages. ^ Location of the world file ^ list of user supplied packages Filter out packages that are not in the world file: equivalence the awkward way: | Returns the content of the world file as a list like "+-debug":
Copyright : ( c ) 2009 Interface to the world - file that contains a list of explicitly module Distribution.Client.World ( WorldPkgInfo(..), insert, delete, getContents, ) where import Distribution.Package ( Dependency(..) ) import Distribution.PackageDescription ( FlagAssignment, FlagName(FlagName) ) import Distribution.Verbosity ( Verbosity ) import Distribution.Simple.Utils ( die, info, chattyTry, writeFileAtomic ) import Distribution.Text ( Text(..), display, simpleParse ) import qualified Distribution.Compat.ReadP as Parse import Distribution.Compat.Exception ( catchIO ) import qualified Text.PrettyPrint as Disp import Text.PrettyPrint ( (<>), (<+>) ) import Data.Char as Char import Data.List ( unionBy, deleteFirstsBy, nubBy ) import System.IO.Error ( isDoesNotExistError ) import qualified Data.ByteString.Lazy.Char8 as B import Prelude hiding (getContents) data WorldPkgInfo = WorldPkgInfo Dependency FlagAssignment deriving (Show,Eq) insert :: Verbosity -> FilePath -> [WorldPkgInfo] -> IO () insert = modifyWorld $ unionBy equalUDep Note : Currently unused as there is no mechanism in ( yet ) to delete :: Verbosity -> FilePath -> [WorldPkgInfo] -> IO () delete = modifyWorld $ flip (deleteFirstsBy equalUDep) equalUDep :: WorldPkgInfo -> WorldPkgInfo -> Bool equalUDep (WorldPkgInfo (Dependency pkg1 _) _) (WorldPkgInfo (Dependency pkg2 _) _) = pkg1 == pkg2 modifyWorld :: ([WorldPkgInfo] -> [WorldPkgInfo] -> [WorldPkgInfo]) -> Verbosity -> IO () modifyWorld _ _ _ [] = return () modifyWorld f verbosity world pkgs = chattyTry "Error while updating world-file. " $ do pkgsOldWorld <- getContents world let pkgsNewWorld = nubBy equalUDep $ f pkgs pkgsOldWorld ' Dependency ' is not an instance , so we need to check for if not (all (`elem` pkgsOldWorld) pkgsNewWorld && all (`elem` pkgsNewWorld) pkgsOldWorld) then do info verbosity "Updating world file..." writeFileAtomic world . B.pack $ unlines [ (display pkg) | pkg <- pkgsNewWorld] else info verbosity "World file is already up to date." getContents :: FilePath -> IO [WorldPkgInfo] getContents world = do content <- safelyReadFile world let result = map simpleParse (lines $ B.unpack content) case sequence result of Nothing -> die "Could not parse world file." Just xs -> return xs where safelyReadFile :: FilePath -> IO B.ByteString safelyReadFile file = B.readFile file `catchIO` handler where handler e | isDoesNotExistError e = return B.empty | otherwise = ioError e instance Text WorldPkgInfo where disp (WorldPkgInfo dep flags) = disp dep <+> dispFlags flags where dispFlags [] = Disp.empty dispFlags fs = Disp.text "--flags=" <> Disp.doubleQuotes (flagAssToDoc fs) flagAssToDoc = foldr (\(FlagName fname,val) flagAssDoc -> (if not val then Disp.char '-' else Disp.empty) Disp.<> Disp.text fname Disp.<+> flagAssDoc) Disp.empty parse = do dep <- parse Parse.skipSpaces flagAss <- Parse.option [] parseFlagAssignment return $ WorldPkgInfo dep flagAss where parseFlagAssignment :: Parse.ReadP r FlagAssignment parseFlagAssignment = do _ <- Parse.string "--flags" Parse.skipSpaces _ <- Parse.char '=' Parse.skipSpaces inDoubleQuotes $ Parse.many1 flag where inDoubleQuotes :: Parse.ReadP r a -> Parse.ReadP r a inDoubleQuotes = Parse.between (Parse.char '"') (Parse.char '"') flag = do Parse.skipSpaces val <- negative Parse.+++ positive name <- ident Parse.skipSpaces return (FlagName name,val) negative = do _ <- Parse.char '-' return False positive = return True ident :: Parse.ReadP r String ident = do First character must be a letter / digit to avoid flags c <- Parse.satisfy Char.isAlphaNum cs <- Parse.munch (\ch -> Char.isAlphaNum ch || ch == '_' || ch == '-') return (c:cs)
93e594338854c5b52f1563df726b3e73cc4da2ffcb86f7348b45c7638746a71d
iconnect/regex
ByteString.hs
# LANGUAGE NoImplicitPrelude # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # OPTIONS_GHC -fno - warn - orphans # # OPTIONS_GHC -fno - warn - duplicate - exports # # LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 # OPTIONS_GHC -fno - warn - redundant - constraints # # OPTIONS_GHC -fno - warn - unused - imports # #endif module Text.RE.PCRE.ByteString ( -- * Tutorial -- $tutorial -- * The 'Matches' and 'Match' Operators (*=~) , (?=~) -- * The 'SearchReplace' Operators , (*=~/) , (?=~/) -- * The 'Matches' Type , Matches , matchesSource , allMatches , anyMatches , countMatches , matches -- * The 'Match' Type , Match , matchSource , matched , matchedText * The Macros and Parsers -- $macros , module Text.RE.TestBench.Parsers -- * The 'RE' Type , RE , reSource -- * Options -- $options , SimpleREOptions(..) -- * Compiling and Escaping REs , SearchReplace(..) , compileRegex , compileRegexWith , compileSearchReplace , compileSearchReplaceWith , escape , escapeWith , escapeREString * The Classic regex - base Match Operators , (=~) , (=~~) -- * The re Quasi Quoters -- $re , re , reMultilineSensitive , reMultilineInsensitive , reBlockSensitive , reBlockInsensitive , reMS , reMI , reBS , reBI , re_ * -- $ed , edMultilineSensitive , edMultilineInsensitive , edBlockSensitive , edBlockInsensitive , ed , edMS , edMI , edBS , edBI , ed_ * The cp Quasi , cp -- * IsRegex $ isregex , module Text.RE.Tools.IsRegex ) where import Control.Monad.Fail import qualified Data.ByteString as B import Data.Typeable import Prelude.Compat import Text.RE.REOptions import Text.RE.Replace import Text.RE.TestBench.Parsers import Text.RE.Tools.IsRegex import Text.RE.ZeInternals import Text.RE.ZeInternals.PCRE import Text.RE.ZeInternals.SearchReplace.PCRE.ByteString import Text.Regex.Base import qualified Text.Regex.PCRE as PCRE NB regex - base instance imports maybe be needed for for some API modules -- | find all the matches in the argument text; e.g., to count the number -- of naturals in s: -- @countMatches $ s * = ~ [ -- (*=~) :: B.ByteString -> RE -> Matches B.ByteString (*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs | find the first match in the argument text ; e.g. , to test if there -- is a natural number in the input text: -- @matched $ s ? = ~ [ -- (?=~) :: B.ByteString -> RE -> Match B.ByteString (?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs -- | search and replace all matches in the argument text; e.g., this section -- will convert every YYYY-MM-DD format date in its argument text into a -- DD\/MM\/YYYY date: -- -- @(*=~\/ [ed|${y}([0-9]{4})-0*${m}([0-9]{2})-0*${d}([0-9]{2})\/\/\/${d}\/${m}\/${y}|])@ -- (*=~/) :: B.ByteString -> SearchReplace RE B.ByteString -> B.ByteString (*=~/) = flip searchReplaceAll | search and replace the first occurrence only ( if any ) in the input text e.g. , to prefix the first string of four hex digits in the input text , -- if any, with @0x@: -- -- @(?=~\/ [ed|[0-9A-Fa-f]{4}\/\/\/0x$0|])@ -- (?=~/) :: B.ByteString -> SearchReplace RE B.ByteString -> B.ByteString (?=~/) = flip searchReplaceFirst -- | the `regex-base` polymorphic match operator (=~) :: ( Typeable a , RegexContext PCRE.Regex B.ByteString a ) => B.ByteString -> RE -> a (=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs -- | the `regex-base` monadic, polymorphic match operator (=~~) :: ( Monad m, MonadFail m , Functor m , Typeable a , RegexContext PCRE.Regex B.ByteString a ) => B.ByteString -> RE -> m a (=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs instance IsRegex RE B.ByteString where matchOnce = flip (?=~) matchMany = flip (*=~) makeRegexWith = \o -> compileRegexWith o . unpackR makeSearchReplaceWith = \o r t -> compileSearchReplaceWith o (unpackR r) (unpackR t) regexSource = packR . reSource -- $tutorial -- We have a regex tutorial at <>. -- $macros There are a number of RE macros and corresponding parsers for parsing the matched text into appropriate types . See -- the [Macros Tables]() for details. -- $options -- You can specify different compilation options by appending a -- to the name of an [re| ... |] or [ed| ... \/\/\/ ... |] quasi quoter -- to select the corresponding compilation option. For example, the -- section, -- @(?=~/ [ edBlockInsensitive|foo$\/\/\/bar|])@ -- -- will replace a @foo@ suffix of the argument text, of any -- capitalisation, with a (lower case) @bar@. If you need to specify the options dynamically , use the @[re_| ... |]@ and @[ed_| ... \/\/\/ ... |]@ -- quasi quoters, which generate functions that take an 'IsOption' option ( e.g. , a ' SimpleReOptions ' value ) and yields a ' RE ' or ' ' -- as appropriate. For example if you have a 'SimpleReOptions' value in @sro@ then -- @(?=~/ [ ed_|foo$\/\/\/bar| ] sro)@ -- will compile the @foo$@ RE according to the value of For more -- on specifying RE options see "Text.RE.REOptions". -- $re -- The @[re|.*|]@ quasi quoters, with variants for specifying different -- options to the RE compiler (see "Text.RE.REOptions"), and the -- specialised back-end types and functions. -- $ed -- The @[ed|.*\/\/\/foo|]@ quasi quoters, with variants for specifying different -- options to the RE compiler (see "Text.RE.REOptions"). -- $ed -- The -- | the @[ed| ... \/\/\/ ... |]@ quasi quoters; for example, -- -- @[ed|${y}([0-9]{4})-0*${m}([0-9]{2})-0*${d}([0-9]{2})\/\/\/${d}\/${m}\/${y}|])@ -- -- represents a @SearchReplace@ that will convert a YYYY-MM-DD format date -- into a DD\/MM\/YYYY format date. -- -- The only difference between these quasi quoters is the RE options that are set, -- using the same conventions as the @[re| ... |]@ quasi quoters. $ isregex The ' IsRegex ' class is used to abstract over the different regex back ends and -- the text types they work with -- see "Text.RE.Tools.IsRegex" for details.
null
https://raw.githubusercontent.com/iconnect/regex/68752790a8f75986b917b71cf0e8e22cd3a28a3d/Text/RE/PCRE/ByteString.hs
haskell
* Tutorial $tutorial * The 'Matches' and 'Match' Operators * The 'SearchReplace' Operators * The 'Matches' Type * The 'Match' Type $macros * The 'RE' Type * Options $options * Compiling and Escaping REs * The re Quasi Quoters $re $ed * IsRegex | find all the matches in the argument text; e.g., to count the number of naturals in s: is a natural number in the input text: | search and replace all matches in the argument text; e.g., this section will convert every YYYY-MM-DD format date in its argument text into a DD\/MM\/YYYY date: @(*=~\/ [ed|${y}([0-9]{4})-0*${m}([0-9]{2})-0*${d}([0-9]{2})\/\/\/${d}\/${m}\/${y}|])@ if any, with @0x@: @(?=~\/ [ed|[0-9A-Fa-f]{4}\/\/\/0x$0|])@ | the `regex-base` polymorphic match operator | the `regex-base` monadic, polymorphic match operator $tutorial We have a regex tutorial at <>. $macros the [Macros Tables]() for details. $options You can specify different compilation options by appending a to the name of an [re| ... |] or [ed| ... \/\/\/ ... |] quasi quoter to select the corresponding compilation option. For example, the section, will replace a @foo@ suffix of the argument text, of any capitalisation, with a (lower case) @bar@. If you need to specify the quasi quoters, which generate functions that take an 'IsOption' option as appropriate. For example if you have a 'SimpleReOptions' value in on specifying RE options see "Text.RE.REOptions". $re The @[re|.*|]@ quasi quoters, with variants for specifying different options to the RE compiler (see "Text.RE.REOptions"), and the specialised back-end types and functions. $ed The @[ed|.*\/\/\/foo|]@ quasi quoters, with variants for specifying different options to the RE compiler (see "Text.RE.REOptions"). $ed The -- | the @[ed| ... \/\/\/ ... |]@ quasi quoters; for example, @[ed|${y}([0-9]{4})-0*${m}([0-9]{2})-0*${d}([0-9]{2})\/\/\/${d}\/${m}\/${y}|])@ represents a @SearchReplace@ that will convert a YYYY-MM-DD format date into a DD\/MM\/YYYY format date. The only difference between these quasi quoters is the RE options that are set, using the same conventions as the @[re| ... |]@ quasi quoters. the text types they work with -- see "Text.RE.Tools.IsRegex" for details.
# LANGUAGE NoImplicitPrelude # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # OPTIONS_GHC -fno - warn - orphans # # OPTIONS_GHC -fno - warn - duplicate - exports # # LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 # OPTIONS_GHC -fno - warn - redundant - constraints # # OPTIONS_GHC -fno - warn - unused - imports # #endif module Text.RE.PCRE.ByteString ( (*=~) , (?=~) , (*=~/) , (?=~/) , Matches , matchesSource , allMatches , anyMatches , countMatches , matches , Match , matchSource , matched , matchedText * The Macros and Parsers , module Text.RE.TestBench.Parsers , RE , reSource , SimpleREOptions(..) , SearchReplace(..) , compileRegex , compileRegexWith , compileSearchReplace , compileSearchReplaceWith , escape , escapeWith , escapeREString * The Classic regex - base Match Operators , (=~) , (=~~) , re , reMultilineSensitive , reMultilineInsensitive , reBlockSensitive , reBlockInsensitive , reMS , reMI , reBS , reBI , re_ * , edMultilineSensitive , edMultilineInsensitive , edBlockSensitive , edBlockInsensitive , ed , edMS , edMI , edBS , edBI , ed_ * The cp Quasi , cp $ isregex , module Text.RE.Tools.IsRegex ) where import Control.Monad.Fail import qualified Data.ByteString as B import Data.Typeable import Prelude.Compat import Text.RE.REOptions import Text.RE.Replace import Text.RE.TestBench.Parsers import Text.RE.Tools.IsRegex import Text.RE.ZeInternals import Text.RE.ZeInternals.PCRE import Text.RE.ZeInternals.SearchReplace.PCRE.ByteString import Text.Regex.Base import qualified Text.Regex.PCRE as PCRE NB regex - base instance imports maybe be needed for for some API modules @countMatches $ s * = ~ [ (*=~) :: B.ByteString -> RE -> Matches B.ByteString (*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs | find the first match in the argument text ; e.g. , to test if there @matched $ s ? = ~ [ (?=~) :: B.ByteString -> RE -> Match B.ByteString (?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs (*=~/) :: B.ByteString -> SearchReplace RE B.ByteString -> B.ByteString (*=~/) = flip searchReplaceAll | search and replace the first occurrence only ( if any ) in the input text e.g. , to prefix the first string of four hex digits in the input text , (?=~/) :: B.ByteString -> SearchReplace RE B.ByteString -> B.ByteString (?=~/) = flip searchReplaceFirst (=~) :: ( Typeable a , RegexContext PCRE.Regex B.ByteString a ) => B.ByteString -> RE -> a (=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs (=~~) :: ( Monad m, MonadFail m , Functor m , Typeable a , RegexContext PCRE.Regex B.ByteString a ) => B.ByteString -> RE -> m a (=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs instance IsRegex RE B.ByteString where matchOnce = flip (?=~) matchMany = flip (*=~) makeRegexWith = \o -> compileRegexWith o . unpackR makeSearchReplaceWith = \o r t -> compileSearchReplaceWith o (unpackR r) (unpackR t) regexSource = packR . reSource There are a number of RE macros and corresponding parsers for parsing the matched text into appropriate types . See @(?=~/ [ edBlockInsensitive|foo$\/\/\/bar|])@ options dynamically , use the @[re_| ... |]@ and @[ed_| ... \/\/\/ ... |]@ ( e.g. , a ' SimpleReOptions ' value ) and yields a ' RE ' or ' ' @sro@ then @(?=~/ [ ed_|foo$\/\/\/bar| ] sro)@ will compile the @foo$@ RE according to the value of For more $ isregex The ' IsRegex ' class is used to abstract over the different regex back ends and
bfc3fb63a5f6a5b19c10d95e688499cfa6db2c78351f1591f0b0efbc8c09f348
smahood/re-frame-conj-2016
snippet4.cljs
(defn on-jsload [] (mount-root)) (defn ^:export run [] (re-frisk/enable-re-frisk! {:x 0 :y 0}) (mount-root))
null
https://raw.githubusercontent.com/smahood/re-frame-conj-2016/51fe544a5f4e95f28c26995c11d64301ba9a2142/show/src/show/snippets/snippet4.cljs
clojure
(defn on-jsload [] (mount-root)) (defn ^:export run [] (re-frisk/enable-re-frisk! {:x 0 :y 0}) (mount-root))
2a671750f5329e33eb5dc8822c802ce4dcbfd677f313973480a74cbe454c6bb0
patzy/glaw
sdl.lisp
(defpackage :glaw-sdl (:use #:cl #:glaw) (:export #:translate-keysym)) (in-package #:glaw-sdl) ;; input (defun translate-keysym (keysym) "Translate a subset of SDL keysym to GLAW compatible keysyms." (case keysym (:sdl-key-up :up) (:sdl-key-down :down) (:sdl-key-left :left) (:sdl-key-right :right) (:sdl-key-tab :tab) (:sdl-key-return :return) (:sdl-key-escape :escape) (:sdl-key-space :space) (:sdl-key-backspace :backspace) (:sdl-key-a :a) (:sdl-key-b :b) (:sdl-key-c :c) (:sdl-key-d :d) (:sdl-key-e :e) (:sdl-key-f :f) (:sdl-key-g :g) (:sdl-key-h :h) (:sdl-key-i :i) (:sdl-key-j :j) (:sdl-key-k :k) (:sdl-key-l :l) (:sdl-key-m :m) (:sdl-key-n :n) (:sdl-key-o :o) (:sdl-key-p :p) (:sdl-key-q :q) (:sdl-key-r :r) (:sdl-key-s :s) (:sdl-key-t :t) (:sdl-key-u :u) (:sdl-key-v :v) (:sdl-key-w :w) (:sdl-key-x :x) (:sdl-key-y :y) (:sdl-key-z :z) (:sdl-key-1 :1) (:sdl-key-2 :2) (:sdl-key-3 :3) (:sdl-key-4 :4) (:sdl-key-5 :5) (:sdl-key-6 :6) (:sdl-key-7 :7) (:sdl-key-8 :8) (:sdl-key-9 :9))) ;; image asset (defasset :image '("png" "jpg" "bmp" "gif" "tga" "pnm" "pbm" "pgm" "ppm" "xpm" "xcf" "pcx" "tif" "lbm") ;; load (lambda (&key filename &allow-other-keys) (sdl:with-init (sdl:sdl-init-video) (let ((img-surf (sdl-image:load-image filename))) (sdl-base::with-pixel (pix (sdl:fp img-surf)) (make-image :data (cffi::foreign-array-to-lisp (sdl-base::pixel-data pix) (list :array :unsigned-char (* (sdl-base::pixel-bpp pix) (sdl:width img-surf) (sdl:height img-surf)))) :bpp (sdl-base::pixel-bpp pix) :width (sdl:width img-surf) :height (sdl:height img-surf)))))) ;; unload ) ;; texture asset (defasset :texture '("png" "jpg" "bmp" "gif" "tga" "pnm" "pbm" "pgm" "ppm" "xpm" "xcf" "pcx" "tif" "lbm") ;; load (lambda (&key filename &allow-other-keys) (sdl:with-init (sdl:sdl-init-video) (let ((img-surf (sdl-image:load-image filename))) (sdl-base::with-pixel (pix (sdl:fp img-surf)) ;; XXX: loaded data is top-left origin while textures are bottom-left (loop with start = 0 with end = (1- (sdl:height img-surf)) with bpp = (sdl-base::pixel-bpp pix) with width = (sdl:width img-surf) while (< start end) do (progn (loop for x below (* width bpp) with color = (random 255) do (let* ((start-index (+ x (* start width bpp))) (end-index (+ x (* end width bpp))) (data (sdl-base::pixel-data pix)) (tmp (cffi:mem-aref data :unsigned-char start-index))) (setf (cffi:mem-aref data :unsigned-char start-index) (cffi:mem-aref data :unsigned-char end-index) (cffi:mem-aref data :unsigned-char end-index) tmp))) (incf start) (decf end))) (create-texture (sdl:width img-surf) (sdl:height img-surf) (sdl-base::pixel-bpp pix) (cffi::foreign-array-to-lisp (sdl-base::pixel-data pix) (list :array :unsigned-char (* (sdl-base::pixel-bpp pix) (sdl:width img-surf) (sdl:height img-surf))))))))) ;; unload 'glaw:destroy-texture) ;; font asset XXX : assumes 256x256 image (defasset :font '("png" "jpg" "bmp" "gif" "tga" "pnm" "pbm" "pgm" "ppm" "xpm" "xcf" "pcx" "tif" "lbm") ;; load (lambda (filename &rest props) (sdl:with-init (sdl:sdl-init-video) (let ((img-surf (sdl-image:load-image filename))) (sdl-base::with-pixel (pix (sdl:fp img-surf)) (let* ((tex (create-texture (sdl:width img-surf) (sdl:height img-surf) (sdl-base::pixel-bpp pix) (sdl-base::pixel-data pix))) (fnt (create-font tex))) (loop for i below 256 for cx = (/ (mod i 16.0) 16.0) for cy = (/ (truncate (/ i 16)) 16.0) do (font-set-glyph-data fnt i cx cy 0.0625 0.0625 16)) (font-build-cache fnt) fnt))))) ;; unload (lambda (font) (glaw:destroy-texture (glaw::font-texture font)) (glaw:destroy-font font)))
null
https://raw.githubusercontent.com/patzy/glaw/e678fc0c107ce4b1e3ff9921a6de7e32fd39bc37/ext/sdl.lisp
lisp
input image asset load unload texture asset load XXX: loaded data is top-left origin while textures are bottom-left unload font asset load unload
(defpackage :glaw-sdl (:use #:cl #:glaw) (:export #:translate-keysym)) (in-package #:glaw-sdl) (defun translate-keysym (keysym) "Translate a subset of SDL keysym to GLAW compatible keysyms." (case keysym (:sdl-key-up :up) (:sdl-key-down :down) (:sdl-key-left :left) (:sdl-key-right :right) (:sdl-key-tab :tab) (:sdl-key-return :return) (:sdl-key-escape :escape) (:sdl-key-space :space) (:sdl-key-backspace :backspace) (:sdl-key-a :a) (:sdl-key-b :b) (:sdl-key-c :c) (:sdl-key-d :d) (:sdl-key-e :e) (:sdl-key-f :f) (:sdl-key-g :g) (:sdl-key-h :h) (:sdl-key-i :i) (:sdl-key-j :j) (:sdl-key-k :k) (:sdl-key-l :l) (:sdl-key-m :m) (:sdl-key-n :n) (:sdl-key-o :o) (:sdl-key-p :p) (:sdl-key-q :q) (:sdl-key-r :r) (:sdl-key-s :s) (:sdl-key-t :t) (:sdl-key-u :u) (:sdl-key-v :v) (:sdl-key-w :w) (:sdl-key-x :x) (:sdl-key-y :y) (:sdl-key-z :z) (:sdl-key-1 :1) (:sdl-key-2 :2) (:sdl-key-3 :3) (:sdl-key-4 :4) (:sdl-key-5 :5) (:sdl-key-6 :6) (:sdl-key-7 :7) (:sdl-key-8 :8) (:sdl-key-9 :9))) (defasset :image '("png" "jpg" "bmp" "gif" "tga" "pnm" "pbm" "pgm" "ppm" "xpm" "xcf" "pcx" "tif" "lbm") (lambda (&key filename &allow-other-keys) (sdl:with-init (sdl:sdl-init-video) (let ((img-surf (sdl-image:load-image filename))) (sdl-base::with-pixel (pix (sdl:fp img-surf)) (make-image :data (cffi::foreign-array-to-lisp (sdl-base::pixel-data pix) (list :array :unsigned-char (* (sdl-base::pixel-bpp pix) (sdl:width img-surf) (sdl:height img-surf)))) :bpp (sdl-base::pixel-bpp pix) :width (sdl:width img-surf) :height (sdl:height img-surf)))))) ) (defasset :texture '("png" "jpg" "bmp" "gif" "tga" "pnm" "pbm" "pgm" "ppm" "xpm" "xcf" "pcx" "tif" "lbm") (lambda (&key filename &allow-other-keys) (sdl:with-init (sdl:sdl-init-video) (let ((img-surf (sdl-image:load-image filename))) (sdl-base::with-pixel (pix (sdl:fp img-surf)) (loop with start = 0 with end = (1- (sdl:height img-surf)) with bpp = (sdl-base::pixel-bpp pix) with width = (sdl:width img-surf) while (< start end) do (progn (loop for x below (* width bpp) with color = (random 255) do (let* ((start-index (+ x (* start width bpp))) (end-index (+ x (* end width bpp))) (data (sdl-base::pixel-data pix)) (tmp (cffi:mem-aref data :unsigned-char start-index))) (setf (cffi:mem-aref data :unsigned-char start-index) (cffi:mem-aref data :unsigned-char end-index) (cffi:mem-aref data :unsigned-char end-index) tmp))) (incf start) (decf end))) (create-texture (sdl:width img-surf) (sdl:height img-surf) (sdl-base::pixel-bpp pix) (cffi::foreign-array-to-lisp (sdl-base::pixel-data pix) (list :array :unsigned-char (* (sdl-base::pixel-bpp pix) (sdl:width img-surf) (sdl:height img-surf))))))))) 'glaw:destroy-texture) XXX : assumes 256x256 image (defasset :font '("png" "jpg" "bmp" "gif" "tga" "pnm" "pbm" "pgm" "ppm" "xpm" "xcf" "pcx" "tif" "lbm") (lambda (filename &rest props) (sdl:with-init (sdl:sdl-init-video) (let ((img-surf (sdl-image:load-image filename))) (sdl-base::with-pixel (pix (sdl:fp img-surf)) (let* ((tex (create-texture (sdl:width img-surf) (sdl:height img-surf) (sdl-base::pixel-bpp pix) (sdl-base::pixel-data pix))) (fnt (create-font tex))) (loop for i below 256 for cx = (/ (mod i 16.0) 16.0) for cy = (/ (truncate (/ i 16)) 16.0) do (font-set-glyph-data fnt i cx cy 0.0625 0.0625 16)) (font-build-cache fnt) fnt))))) (lambda (font) (glaw:destroy-texture (glaw::font-texture font)) (glaw:destroy-font font)))
0212a320f9bfd4dde0e144479ea4c169625eacec5922598be841c120f07b1601
yrashk/erlang
snmpa_general_db.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2000 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(snmpa_general_db). %%%----------------------------------------------------------------- This module implements a very simple " generic " MIB database %%% interface. It contains the most common functions performed. %%% It is generic in the sense that it implements both an interface %%% to mnesia and ets. %%% %%% Note that this module has nothing to do with the snmp_generic and snmp_generic_mnesia modules . %%%----------------------------------------------------------------- -export([open/5, close/1, read/2, write/2, delete/1, delete/2]). -export([sync/1, backup/2]). -export([match_object/2, match_delete/2]). -export([tab2list/1, info/1, info/2]). -define(VMODULE,"GDB"). -include("snmp_verbosity.hrl"). %% --------------------------------------------------------------- open(Info , Name , RecName , , Type ) - > term ( ) Info - > ets | { ets , } | { dets , } | { dets , , Action } | { mnesia , Nodes } | { mnesia , Nodes , Action } %% Name -> atom() %% RecName -> Name of the record to store %% Attr -> Attributes of the record stored in the table %% Type -> set | bag %% Dir -> string() %% Nodes -> [node()] %% Action -> keep | clear %% Open or create a database table . In the / dets case , %% where the table is stored on disc, it could be of interest %% to clear the table. This is controlled by the Action parameter. %% An empty node list ([]), is traslated into a list containing %% only the own node. %% --------------------------------------------------------------- open({mnesia,Nodes,clear}, Name, RecName, Attr, Type) when list(Nodes) -> ?vtrace("[mnesia] open ~p database ~p for ~p on ~p; clear", [Type, Name, RecName, Nodes]), mnesia_open(mnesia_table_check(Name), Nodes, RecName, Attr, Type, clear); open({mnesia,Nodes,_}, Name, RecName, Attr, Type) -> ?vtrace("[mnesia] open ~p database ~p for ~p on ~p; keep", [Type, Name, RecName, Nodes]), open({mnesia,Nodes}, Name, RecName, Attr, Type); open({mnesia,Nodes}, Name, RecName, Attr, Type) when list(Nodes) -> ?vtrace("[mnesia] open ~p database ~p for ~p on ~p", [Type, Name, RecName, Nodes]), mnesia_open(mnesia_table_check(Name), Nodes, RecName, Attr, Type, keep); open({dets, Dir, Action}, Name, _RecName, _Attr, Type) -> dets_open(Name, dets_filename(Name, Dir), Type, Action); open({dets, Dir}, Name, _RecName, _Attr, Type) -> dets_open(Name, dets_filename(Name, Dir), Type, keep); %% This function creates the ets table open(ets, Name, _RecName, _Attr, Type) -> ?vtrace("[ets] open ~p database ~p", [Type, Name]), Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, undefined}; open({ets, Dir}, Name, _RecName, _Attr, Type) -> ets_open(Name, Dir, keep, Type); open({ets, Dir, Action}, Name, _RecName, _Attr, Type) -> ets_open(Name, Dir, Action, Type). ets_open(Name, Dir, keep, Type) -> ?vtrace("[ets] open ~p database ~p", [Type, Name]), File = filename:join(Dir, atom_to_list(Name) ++ ".db"), case file:read_file_info(File) of {ok, _} -> case ets:file2tab(File) of {ok, Tab} -> {ets, Tab, File}; {error, Reason} -> user_err("failed converting file to (ets-) tab: " "File: ~p" "~n~p", [File, Reason]), Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, File} end; {error, _} -> Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, File} end; ets_open(Name, Dir, clear, Type) -> File = filename:join(Dir, atom_to_list(Name) ++ ".db"), Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, File}. mnesia_open({table_exist,Name},_Nodes,_RecName,_Attr,_Type,clear) -> ?vtrace("[mnesia] database ~p already exists; clear content",[Name]), Pattern = '_', F = fun() -> Recs = mnesia:match_object(Name,Pattern,read), lists:foreach(fun(Rec) -> mnesia:delete_object(Name,Rec,write) end, Recs), Recs end, case mnesia:transaction(F) of {aborted,Reason} -> exit({aborted,Reason}); {atomic,_} -> {mnesia,Name} end; mnesia_open({table_exist,Name},_Nodes,_RecName,_Attr,_Type,keep) -> ?vtrace("[mnesia] database ~p already exists; keep content",[Name]), {mnesia,Name}; mnesia_open({no_table,Name},[],Type,RecName,Attr,Action) -> mnesia_open({no_table,Name},[node()],Type,RecName,Attr,Action); mnesia_open({no_table,Name},Nodes,RecName,Attr,Type,_) -> ?vtrace("[mnesia] no database ~p: create for ~p of type ~p", [Name,RecName,Type]), %% Ok, we assume that this means that the table does not exist Args = [{record_name,RecName}, {attributes,Attr}, {type,Type}, {disc_copies,Nodes}], case mnesia:create_table(Name,Args) of {atomic,ok} -> {mnesia,Name}; {aborted,Reason} -> %% ?vinfo("[mnesia] aborted: ~p", [Reason]), exit({failed_create_mnesia_table,Reason}) end. mnesia_table_check(Name) -> ?vtrace("[mnesia] check existens of database ~p",[Name]), case (catch mnesia:table_info(Name,type)) of {'EXIT', _Reason} -> {no_table, Name}; _ -> {table_exist, Name} end. dets_open(Name, File, Type, Action) -> ?vtrace("[dets] open database ~p (~p)", [Name, Action]), N = dets_open1(Name, File, Type), dets_open2(N, Action). dets_open1(Name, File, Type) -> ?vtrace("[dets] open database ~p of type ~p",[Name, Type]), {ok, N} = dets:open_file(Name, [{file, File}, {type, Type}, {keypos, 2}]), N. dets_open2(N, clear) -> dets:match_delete(N,'_'), {dets, N}; dets_open2(N, _) -> {dets, N}. dets_table_check(Name , ) - > Filename = dets_filename(Name , ) , %% ?vtrace("[dets] check existens of database: " %% "~n ~p -> ~s" %% "~n ~p" %% "~n ~p" %% , %% [Name, Filename, file:list_dir(Dir), file:read_file_info(Filename)]), %% case (catch dets:info(Filename, size)) of { ' EXIT ' , Reason } - > %% {no_table, Name, Filename}; undefined - > % % Introduced in R8 %% {no_table, Name, Filename}; %% _ -> %% {table_exist, Name, Filename} %% end. dets_filename(Name, Dir) -> Dir1 = dets_filename1(Dir), Dir2 = string:strip(Dir1, right, $/), io_lib:format("~s/~p.dat", [Dir2, Name]). dets_filename1([]) -> "."; dets_filename1(Dir) -> Dir. %% --------------------------------------------------------------- %% close(DbRef) -> %% DbRef -> term() %% Close the database . This does nothing in the case , but %% deletes the table in the ets case. %% --------------------------------------------------------------- close({mnesia,_}) -> ?vtrace("[mnesia] close database: NO ACTION",[]), ok; close({dets, Name}) -> ?vtrace("[dets] close database ~p",[Name]), dets:close(Name); close({ets, Name, undefined}) -> ?vtrace("[ets] close (delete) table ~p",[Name]), ets:delete(Name); close({ets, Name, File}) -> ?vtrace("[ets] close (delete) table ~p",[Name]), write_ets_file(Name, File), ets:delete(Name). %% --------------------------------------------------------------- %% read(DbRef,Key) -> false | {value,Rec} %% DbRef -> term() %% Rec -> tuple() %% %% Retrieve a record from the database. %% --------------------------------------------------------------- read({mnesia, Name}, Key) -> ?vtrace("[mnesia] read (dirty) from database ~p: ~p",[Name,Key]), case (catch mnesia:dirty_read(Name,Key)) of [Rec|_] -> {value,Rec}; _ -> false end; read({dets, Name}, Key) -> ?vtrace("[dets] read from table ~p: ~p",[Name,Key]), case dets:lookup(Name, Key) of [Rec|_] -> {value, Rec}; _ -> false end; read({ets, Name, _}, Key) -> ?vtrace("[ets] read from table ~p: ~p",[Name,Key]), case ets:lookup(Name, Key) of [Rec|_] -> {value, Rec}; _ -> false end. %% --------------------------------------------------------------- %% write(DbRef,Rec) -> ok %% DbRef -> term() %% Rec -> tuple() %% %% Write a record to the database. %% --------------------------------------------------------------- write({mnesia, Name}, Rec) -> ?vtrace("[mnesia] write to database ~p",[Name]), F = fun() -> mnesia:write(Name, Rec, write) end, case mnesia:transaction(F) of {aborted, Reason} -> exit({aborted, Reason}); {atomic,_} -> ok end; write({dets, Name}, Rec) -> ?vtrace("[dets] write to table ~p",[Name]), dets:insert(Name, Rec); write({ets, Name, _}, Rec) -> ?vtrace("[ets] write to table ~p",[Name]), ets:insert(Name, Rec). %% --------------------------------------------------------------- %% delete(DbRef) -> %% DbRef -> term() %% %% Delete the database. %% --------------------------------------------------------------- delete({mnesia, Name}) -> ?vtrace("[mnesia] delete database: ~p",[Name]), mnesia:delete_table(Name); delete({dets, Name}) -> ?vtrace("[dets] delete database ~p",[Name]), File = dets:info(Name, filename), case dets:close(Name) of ok -> file:delete(File); Error -> Error end; delete({ets, Name, undefined}) -> ?vtrace("[dets] delete table ~p",[Name]), ets:delete(Name); delete({ets, Name, File}) -> ?vtrace("[dets] delete table ~p",[Name]), file:delete(File), ets:delete(Name). %% --------------------------------------------------------------- %% delete(DbRef, Key) -> ok %% DbRef -> term() %% Key -> term() %% %% Delete a record from the database. %% --------------------------------------------------------------- delete({mnesia, Name}, Key) -> ?vtrace("[mnesia] delete from database ~p: ~p", [Name, Key]), F = fun() -> mnesia:delete(Name, Key, write) end, case mnesia:transaction(F) of {aborted,Reason} -> exit({aborted,Reason}); {atomic,_} -> ok end; delete({dets, Name}, Key) -> ?vtrace("[dets] delete from table ~p: ~p", [Name, Key]), dets:delete(Name, Key); delete({ets, Name, _}, Key) -> ?vtrace("[ets] delete from table ~p: ~p", [Name, Key]), ets:delete(Name, Key). %% --------------------------------------------------------------- %% match_object(DbRef,Pattern) -> [tuple()] %% DbRef -> term() %% Pattern -> tuple() %% %% Search the database for records witch matches the pattern. %% --------------------------------------------------------------- match_object({mnesia, Name}, Pattern) -> ?vtrace("[mnesia] match_object in ~p of ~p",[Name, Pattern]), F = fun() -> mnesia:match_object(Name, Pattern, read) end, case mnesia:transaction(F) of {aborted, Reason} -> exit({aborted, Reason}); {atomic, Recs} -> Recs end; match_object({dets, Name}, Pattern) -> ?vtrace("[dets] match_object in ~p of ~p",[Name, Pattern]), dets:match_object(Name, Pattern); match_object({ets, Name, _}, Pattern) -> ?vtrace("[ets] match_object in ~p of ~p",[Name, Pattern]), ets:match_object(Name, Pattern). %% --------------------------------------------------------------- %% match_delete(DbRef,Pattern) -> %% DbRef -> term() %% Pattern -> tuple() %% %% Search the database for records witch matches the pattern and %% deletes them from the database. %% --------------------------------------------------------------- match_delete({mnesia, Name}, Pattern) -> ?vtrace("[mnesia] match_delete in ~p with pattern ~p",[Name,Pattern]), F = fun() -> Recs = mnesia:match_object(Name, Pattern, read), lists:foreach(fun(Rec) -> mnesia:delete_object(Name, Rec, write) end, Recs), Recs end, case mnesia:transaction(F) of {aborted, Reason} -> exit({aborted, Reason}); {atomic,R} -> R end; match_delete({dets, Name}, Pattern) -> ?vtrace("[dets] match_delete in ~p with pattern ~p",[Name,Pattern]), Recs = dets:match_object(Name, Pattern), dets:match_delete(Name, Pattern), Recs; match_delete({ets, Name, _}, Pattern) -> ?vtrace("[ets] match_delete in ~p with pattern ~p",[Name,Pattern]), Recs = ets:match_object(Name, Pattern), ets:match_delete(Name, Pattern), Recs. %% --------------------------------------------------------------- %% tab2list(DbRef) -> [tuple()] %% DbRef -> term() %% %% Return all records in the table in the form of a list. %% --------------------------------------------------------------- tab2list({mnesia, Name}) -> ?vtrace("[mnesia] tab2list -> list of ~p", [Name]), match_object({mnesia, Name}, mnesia:table_info(Name, wild_pattern)); tab2list({dets, Name}) -> ?vtrace("[dets] tab2list -> list of ~p", [Name]), match_object({dets, Name}, '_'); tab2list({ets, Name, _}) -> ?vtrace("[ets] tab2list -> list of ~p", [Name]), ets:tab2list(Name). %% --------------------------------------------------------------- %% info(Db) -> taglist() %% info(Db, Item) -> Info %% Db -> term() %% Item -> atom() %% tablist() -> [{key(),value()}] %% key() -> atom() %% value() -> term() %% %% Retrieve table information. %% --------------------------------------------------------------- info({mnesia, Name}) -> case (catch mnesia:table_info(Name, all)) of Info when list(Info) -> Info; {'EXIT', {aborted, Reason}} -> {error, Reason}; Else -> {error, Else} end; info({dets, Name}) -> dets:info(Name); info({ets, Name, _}) -> case ets:info(Name) of undefined -> []; L -> L end. info({mnesia, Name}, Item) -> case (catch mnesia:table_info(Name, Item)) of {'EXIT', {aborted, Reason}} -> {error, Reason}; Info -> Info end; info({dets, Name}, memory) -> dets:info(Name, file_size); info({dets, Name}, Item) -> dets:info(Name, Item); info({ets, Name, _}, Item) -> ets:info(Name, Item). %% --------------------------------------------------------------- %% sync(Db) -> ok | {error, Reason} %% Db -> term() %% Reason -> term() %% %% Dump table to disc (if possible) %% --------------------------------------------------------------- sync({mnesia, _}) -> ok; sync({dets, Name}) -> dets:sync(Name); sync({ets, _Name, undefined}) -> ok; sync({ets, Name, File}) -> write_ets_file(Name, File). %% --------------------------------------------------------------- %% backup(Db, BackupDir) -> ok | {error, Reason} %% Db -> term() %% Reason -> term() %% Make a backup copy of the DB ( only valid for det and ets ) %% --------------------------------------------------------------- backup({mnesia, _}, _) -> ok; backup({dets, Name}, BackupDir) -> case dets:info(Name, filename) of undefined -> {error, no_file}; Filename -> case filename:dirname(Filename) of BackupDir -> {error, db_dir}; _ -> Type = dets:info(Name, type), KP = dets:info(Name, keypos), dets_backup(Name, filename:basename(Filename), BackupDir, Type, KP) end end; backup({ets, _Name, undefined}, _BackupDir) -> ok; backup({ets, Name, File}, BackupDir) -> Filename = filename:basename(File), case filename:join(BackupDir, Filename) of File -> Oups : backup - dir and the same {error, db_dir}; BackupFile -> write_ets_file(Name, BackupFile) end. dets_backup(Name, Filename, BackupDir, Type, KP) -> ?vtrace("dets_backup -> entry with" "~n Name: ~p" "~n Filename: ~p" "~n BackupDir: ~p" "~n Type: ~p" "~n KP: ~p", [Name, Filename, BackupDir, Type, KP]), BackupFile = filename:join(BackupDir, Filename), ?vtrace("dets_backup -> " "~n BackupFile: ~p", [BackupFile]), Backup = list_to_atom(atom_to_list(Name) ++ "_backup"), Opts = [{file, BackupFile}, {type, Type}, {keypos, KP}], case dets:open_file(Backup, Opts) of {ok, B} -> ?vtrace("dets_backup -> create fun", []), F = fun(Arg) -> dets_backup(Arg, start, Name, B) end, dets:safe_fixtable(Name, true), Res = dets:init_table(Backup, F, [{format, bchunk}]), dets:safe_fixtable(Name, false), ?vtrace("dets_backup -> Res: ~p", [Res]), Res; Error -> ?vinfo("dets_backup -> open_file failed: " "~n ~p", [Error]), Error end. dets_backup(close, _Cont, _Name, B) -> dets:close(B), ok; dets_backup(read, Cont1, Name, B) -> case dets:bchunk(Name, Cont1) of {Cont2, Data} -> F = fun(Arg) -> dets_backup(Arg, Cont2, Name, B) end, {Data, F}; '$end_of_table' -> dets:close(B), end_of_input; Error -> Error end. %%---------------------------------------------------------------------- write_ets_file(Name, File) -> TmpFile = File ++ ".tmp", case ets:tab2file(Name, TmpFile) of ok -> case file:rename(TmpFile, File) of ok -> ok; Else -> user_err("Warning: could not move file ~p" " (~p)", [File, Else]) end; {error, Reason} -> user_err("Warning: could not save file ~p (~p)", [File, Reason]) end. %%---------------------------------------------------------------------- user_err(F, A) -> snmpa_error:user_err(F, A).
null
https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/snmp/src/agent/snmpa_general_db.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ----------------------------------------------------------------- interface. It contains the most common functions performed. It is generic in the sense that it implements both an interface to mnesia and ets. Note that this module has nothing to do with the snmp_generic ----------------------------------------------------------------- --------------------------------------------------------------- Name -> atom() RecName -> Name of the record to store Attr -> Attributes of the record stored in the table Type -> set | bag Dir -> string() Nodes -> [node()] Action -> keep | clear where the table is stored on disc, it could be of interest to clear the table. This is controlled by the Action parameter. An empty node list ([]), is traslated into a list containing only the own node. --------------------------------------------------------------- This function creates the ets table Ok, we assume that this means that the table does not exist ?vinfo("[mnesia] aborted: ~p", [Reason]), ?vtrace("[dets] check existens of database: " "~n ~p -> ~s" "~n ~p" "~n ~p" , [Name, Filename, file:list_dir(Dir), file:read_file_info(Filename)]), case (catch dets:info(Filename, size)) of {no_table, Name, Filename}; % Introduced in R8 {no_table, Name, Filename}; _ -> {table_exist, Name, Filename} end. --------------------------------------------------------------- close(DbRef) -> DbRef -> term() deletes the table in the ets case. --------------------------------------------------------------- --------------------------------------------------------------- read(DbRef,Key) -> false | {value,Rec} DbRef -> term() Rec -> tuple() Retrieve a record from the database. --------------------------------------------------------------- --------------------------------------------------------------- write(DbRef,Rec) -> ok DbRef -> term() Rec -> tuple() Write a record to the database. --------------------------------------------------------------- --------------------------------------------------------------- delete(DbRef) -> DbRef -> term() Delete the database. --------------------------------------------------------------- --------------------------------------------------------------- delete(DbRef, Key) -> ok DbRef -> term() Key -> term() Delete a record from the database. --------------------------------------------------------------- --------------------------------------------------------------- match_object(DbRef,Pattern) -> [tuple()] DbRef -> term() Pattern -> tuple() Search the database for records witch matches the pattern. --------------------------------------------------------------- --------------------------------------------------------------- match_delete(DbRef,Pattern) -> DbRef -> term() Pattern -> tuple() Search the database for records witch matches the pattern and deletes them from the database. --------------------------------------------------------------- --------------------------------------------------------------- tab2list(DbRef) -> [tuple()] DbRef -> term() Return all records in the table in the form of a list. --------------------------------------------------------------- --------------------------------------------------------------- info(Db) -> taglist() info(Db, Item) -> Info Db -> term() Item -> atom() tablist() -> [{key(),value()}] key() -> atom() value() -> term() Retrieve table information. --------------------------------------------------------------- --------------------------------------------------------------- sync(Db) -> ok | {error, Reason} Db -> term() Reason -> term() Dump table to disc (if possible) --------------------------------------------------------------- --------------------------------------------------------------- backup(Db, BackupDir) -> ok | {error, Reason} Db -> term() Reason -> term() --------------------------------------------------------------- ---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright Ericsson AB 2000 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(snmpa_general_db). This module implements a very simple " generic " MIB database and snmp_generic_mnesia modules . -export([open/5, close/1, read/2, write/2, delete/1, delete/2]). -export([sync/1, backup/2]). -export([match_object/2, match_delete/2]). -export([tab2list/1, info/1, info/2]). -define(VMODULE,"GDB"). -include("snmp_verbosity.hrl"). open(Info , Name , RecName , , Type ) - > term ( ) Info - > ets | { ets , } | { dets , } | { dets , , Action } | { mnesia , Nodes } | { mnesia , Nodes , Action } Open or create a database table . In the / dets case , open({mnesia,Nodes,clear}, Name, RecName, Attr, Type) when list(Nodes) -> ?vtrace("[mnesia] open ~p database ~p for ~p on ~p; clear", [Type, Name, RecName, Nodes]), mnesia_open(mnesia_table_check(Name), Nodes, RecName, Attr, Type, clear); open({mnesia,Nodes,_}, Name, RecName, Attr, Type) -> ?vtrace("[mnesia] open ~p database ~p for ~p on ~p; keep", [Type, Name, RecName, Nodes]), open({mnesia,Nodes}, Name, RecName, Attr, Type); open({mnesia,Nodes}, Name, RecName, Attr, Type) when list(Nodes) -> ?vtrace("[mnesia] open ~p database ~p for ~p on ~p", [Type, Name, RecName, Nodes]), mnesia_open(mnesia_table_check(Name), Nodes, RecName, Attr, Type, keep); open({dets, Dir, Action}, Name, _RecName, _Attr, Type) -> dets_open(Name, dets_filename(Name, Dir), Type, Action); open({dets, Dir}, Name, _RecName, _Attr, Type) -> dets_open(Name, dets_filename(Name, Dir), Type, keep); open(ets, Name, _RecName, _Attr, Type) -> ?vtrace("[ets] open ~p database ~p", [Type, Name]), Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, undefined}; open({ets, Dir}, Name, _RecName, _Attr, Type) -> ets_open(Name, Dir, keep, Type); open({ets, Dir, Action}, Name, _RecName, _Attr, Type) -> ets_open(Name, Dir, Action, Type). ets_open(Name, Dir, keep, Type) -> ?vtrace("[ets] open ~p database ~p", [Type, Name]), File = filename:join(Dir, atom_to_list(Name) ++ ".db"), case file:read_file_info(File) of {ok, _} -> case ets:file2tab(File) of {ok, Tab} -> {ets, Tab, File}; {error, Reason} -> user_err("failed converting file to (ets-) tab: " "File: ~p" "~n~p", [File, Reason]), Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, File} end; {error, _} -> Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, File} end; ets_open(Name, Dir, clear, Type) -> File = filename:join(Dir, atom_to_list(Name) ++ ".db"), Ets = ets:new(Name, [Type, protected, {keypos, 2}]), {ets, Ets, File}. mnesia_open({table_exist,Name},_Nodes,_RecName,_Attr,_Type,clear) -> ?vtrace("[mnesia] database ~p already exists; clear content",[Name]), Pattern = '_', F = fun() -> Recs = mnesia:match_object(Name,Pattern,read), lists:foreach(fun(Rec) -> mnesia:delete_object(Name,Rec,write) end, Recs), Recs end, case mnesia:transaction(F) of {aborted,Reason} -> exit({aborted,Reason}); {atomic,_} -> {mnesia,Name} end; mnesia_open({table_exist,Name},_Nodes,_RecName,_Attr,_Type,keep) -> ?vtrace("[mnesia] database ~p already exists; keep content",[Name]), {mnesia,Name}; mnesia_open({no_table,Name},[],Type,RecName,Attr,Action) -> mnesia_open({no_table,Name},[node()],Type,RecName,Attr,Action); mnesia_open({no_table,Name},Nodes,RecName,Attr,Type,_) -> ?vtrace("[mnesia] no database ~p: create for ~p of type ~p", [Name,RecName,Type]), Args = [{record_name,RecName}, {attributes,Attr}, {type,Type}, {disc_copies,Nodes}], case mnesia:create_table(Name,Args) of {atomic,ok} -> {mnesia,Name}; {aborted,Reason} -> exit({failed_create_mnesia_table,Reason}) end. mnesia_table_check(Name) -> ?vtrace("[mnesia] check existens of database ~p",[Name]), case (catch mnesia:table_info(Name,type)) of {'EXIT', _Reason} -> {no_table, Name}; _ -> {table_exist, Name} end. dets_open(Name, File, Type, Action) -> ?vtrace("[dets] open database ~p (~p)", [Name, Action]), N = dets_open1(Name, File, Type), dets_open2(N, Action). dets_open1(Name, File, Type) -> ?vtrace("[dets] open database ~p of type ~p",[Name, Type]), {ok, N} = dets:open_file(Name, [{file, File}, {type, Type}, {keypos, 2}]), N. dets_open2(N, clear) -> dets:match_delete(N,'_'), {dets, N}; dets_open2(N, _) -> {dets, N}. dets_table_check(Name , ) - > Filename = dets_filename(Name , ) , { ' EXIT ' , Reason } - > dets_filename(Name, Dir) -> Dir1 = dets_filename1(Dir), Dir2 = string:strip(Dir1, right, $/), io_lib:format("~s/~p.dat", [Dir2, Name]). dets_filename1([]) -> "."; dets_filename1(Dir) -> Dir. Close the database . This does nothing in the case , but close({mnesia,_}) -> ?vtrace("[mnesia] close database: NO ACTION",[]), ok; close({dets, Name}) -> ?vtrace("[dets] close database ~p",[Name]), dets:close(Name); close({ets, Name, undefined}) -> ?vtrace("[ets] close (delete) table ~p",[Name]), ets:delete(Name); close({ets, Name, File}) -> ?vtrace("[ets] close (delete) table ~p",[Name]), write_ets_file(Name, File), ets:delete(Name). read({mnesia, Name}, Key) -> ?vtrace("[mnesia] read (dirty) from database ~p: ~p",[Name,Key]), case (catch mnesia:dirty_read(Name,Key)) of [Rec|_] -> {value,Rec}; _ -> false end; read({dets, Name}, Key) -> ?vtrace("[dets] read from table ~p: ~p",[Name,Key]), case dets:lookup(Name, Key) of [Rec|_] -> {value, Rec}; _ -> false end; read({ets, Name, _}, Key) -> ?vtrace("[ets] read from table ~p: ~p",[Name,Key]), case ets:lookup(Name, Key) of [Rec|_] -> {value, Rec}; _ -> false end. write({mnesia, Name}, Rec) -> ?vtrace("[mnesia] write to database ~p",[Name]), F = fun() -> mnesia:write(Name, Rec, write) end, case mnesia:transaction(F) of {aborted, Reason} -> exit({aborted, Reason}); {atomic,_} -> ok end; write({dets, Name}, Rec) -> ?vtrace("[dets] write to table ~p",[Name]), dets:insert(Name, Rec); write({ets, Name, _}, Rec) -> ?vtrace("[ets] write to table ~p",[Name]), ets:insert(Name, Rec). delete({mnesia, Name}) -> ?vtrace("[mnesia] delete database: ~p",[Name]), mnesia:delete_table(Name); delete({dets, Name}) -> ?vtrace("[dets] delete database ~p",[Name]), File = dets:info(Name, filename), case dets:close(Name) of ok -> file:delete(File); Error -> Error end; delete({ets, Name, undefined}) -> ?vtrace("[dets] delete table ~p",[Name]), ets:delete(Name); delete({ets, Name, File}) -> ?vtrace("[dets] delete table ~p",[Name]), file:delete(File), ets:delete(Name). delete({mnesia, Name}, Key) -> ?vtrace("[mnesia] delete from database ~p: ~p", [Name, Key]), F = fun() -> mnesia:delete(Name, Key, write) end, case mnesia:transaction(F) of {aborted,Reason} -> exit({aborted,Reason}); {atomic,_} -> ok end; delete({dets, Name}, Key) -> ?vtrace("[dets] delete from table ~p: ~p", [Name, Key]), dets:delete(Name, Key); delete({ets, Name, _}, Key) -> ?vtrace("[ets] delete from table ~p: ~p", [Name, Key]), ets:delete(Name, Key). match_object({mnesia, Name}, Pattern) -> ?vtrace("[mnesia] match_object in ~p of ~p",[Name, Pattern]), F = fun() -> mnesia:match_object(Name, Pattern, read) end, case mnesia:transaction(F) of {aborted, Reason} -> exit({aborted, Reason}); {atomic, Recs} -> Recs end; match_object({dets, Name}, Pattern) -> ?vtrace("[dets] match_object in ~p of ~p",[Name, Pattern]), dets:match_object(Name, Pattern); match_object({ets, Name, _}, Pattern) -> ?vtrace("[ets] match_object in ~p of ~p",[Name, Pattern]), ets:match_object(Name, Pattern). match_delete({mnesia, Name}, Pattern) -> ?vtrace("[mnesia] match_delete in ~p with pattern ~p",[Name,Pattern]), F = fun() -> Recs = mnesia:match_object(Name, Pattern, read), lists:foreach(fun(Rec) -> mnesia:delete_object(Name, Rec, write) end, Recs), Recs end, case mnesia:transaction(F) of {aborted, Reason} -> exit({aborted, Reason}); {atomic,R} -> R end; match_delete({dets, Name}, Pattern) -> ?vtrace("[dets] match_delete in ~p with pattern ~p",[Name,Pattern]), Recs = dets:match_object(Name, Pattern), dets:match_delete(Name, Pattern), Recs; match_delete({ets, Name, _}, Pattern) -> ?vtrace("[ets] match_delete in ~p with pattern ~p",[Name,Pattern]), Recs = ets:match_object(Name, Pattern), ets:match_delete(Name, Pattern), Recs. tab2list({mnesia, Name}) -> ?vtrace("[mnesia] tab2list -> list of ~p", [Name]), match_object({mnesia, Name}, mnesia:table_info(Name, wild_pattern)); tab2list({dets, Name}) -> ?vtrace("[dets] tab2list -> list of ~p", [Name]), match_object({dets, Name}, '_'); tab2list({ets, Name, _}) -> ?vtrace("[ets] tab2list -> list of ~p", [Name]), ets:tab2list(Name). info({mnesia, Name}) -> case (catch mnesia:table_info(Name, all)) of Info when list(Info) -> Info; {'EXIT', {aborted, Reason}} -> {error, Reason}; Else -> {error, Else} end; info({dets, Name}) -> dets:info(Name); info({ets, Name, _}) -> case ets:info(Name) of undefined -> []; L -> L end. info({mnesia, Name}, Item) -> case (catch mnesia:table_info(Name, Item)) of {'EXIT', {aborted, Reason}} -> {error, Reason}; Info -> Info end; info({dets, Name}, memory) -> dets:info(Name, file_size); info({dets, Name}, Item) -> dets:info(Name, Item); info({ets, Name, _}, Item) -> ets:info(Name, Item). sync({mnesia, _}) -> ok; sync({dets, Name}) -> dets:sync(Name); sync({ets, _Name, undefined}) -> ok; sync({ets, Name, File}) -> write_ets_file(Name, File). Make a backup copy of the DB ( only valid for det and ets ) backup({mnesia, _}, _) -> ok; backup({dets, Name}, BackupDir) -> case dets:info(Name, filename) of undefined -> {error, no_file}; Filename -> case filename:dirname(Filename) of BackupDir -> {error, db_dir}; _ -> Type = dets:info(Name, type), KP = dets:info(Name, keypos), dets_backup(Name, filename:basename(Filename), BackupDir, Type, KP) end end; backup({ets, _Name, undefined}, _BackupDir) -> ok; backup({ets, Name, File}, BackupDir) -> Filename = filename:basename(File), case filename:join(BackupDir, Filename) of File -> Oups : backup - dir and the same {error, db_dir}; BackupFile -> write_ets_file(Name, BackupFile) end. dets_backup(Name, Filename, BackupDir, Type, KP) -> ?vtrace("dets_backup -> entry with" "~n Name: ~p" "~n Filename: ~p" "~n BackupDir: ~p" "~n Type: ~p" "~n KP: ~p", [Name, Filename, BackupDir, Type, KP]), BackupFile = filename:join(BackupDir, Filename), ?vtrace("dets_backup -> " "~n BackupFile: ~p", [BackupFile]), Backup = list_to_atom(atom_to_list(Name) ++ "_backup"), Opts = [{file, BackupFile}, {type, Type}, {keypos, KP}], case dets:open_file(Backup, Opts) of {ok, B} -> ?vtrace("dets_backup -> create fun", []), F = fun(Arg) -> dets_backup(Arg, start, Name, B) end, dets:safe_fixtable(Name, true), Res = dets:init_table(Backup, F, [{format, bchunk}]), dets:safe_fixtable(Name, false), ?vtrace("dets_backup -> Res: ~p", [Res]), Res; Error -> ?vinfo("dets_backup -> open_file failed: " "~n ~p", [Error]), Error end. dets_backup(close, _Cont, _Name, B) -> dets:close(B), ok; dets_backup(read, Cont1, Name, B) -> case dets:bchunk(Name, Cont1) of {Cont2, Data} -> F = fun(Arg) -> dets_backup(Arg, Cont2, Name, B) end, {Data, F}; '$end_of_table' -> dets:close(B), end_of_input; Error -> Error end. write_ets_file(Name, File) -> TmpFile = File ++ ".tmp", case ets:tab2file(Name, TmpFile) of ok -> case file:rename(TmpFile, File) of ok -> ok; Else -> user_err("Warning: could not move file ~p" " (~p)", [File, Else]) end; {error, Reason} -> user_err("Warning: could not save file ~p (~p)", [File, Reason]) end. user_err(F, A) -> snmpa_error:user_err(F, A).
a5dc3a6ed92ae08800f5a87ec905cc91ac8c81fd45849eb2370c5a5264f2b9da
sweirich/trellys
BaseTypes.hs
module BaseTypes ( Literal(..) , ppLit ) where import Text.PrettyPrint.HughesPJ (Doc,text) data Literal = LInt Int | LDouble Double | LChar Char | LInteger Integer | LUnit deriving Eq ppLit :: Literal -> Doc ppLit (LInt n) = text(show n) ppLit (LInteger n) = text(show n) ppLit (LDouble d) = text (show d) ppLit (LChar c) = text(show c) ppLit (LUnit) = text "()"
null
https://raw.githubusercontent.com/sweirich/trellys/63ea89d8fa09929c23504665c55a3d909fe047c5/nax/src/BaseTypes.hs
haskell
module BaseTypes ( Literal(..) , ppLit ) where import Text.PrettyPrint.HughesPJ (Doc,text) data Literal = LInt Int | LDouble Double | LChar Char | LInteger Integer | LUnit deriving Eq ppLit :: Literal -> Doc ppLit (LInt n) = text(show n) ppLit (LInteger n) = text(show n) ppLit (LDouble d) = text (show d) ppLit (LChar c) = text(show c) ppLit (LUnit) = text "()"
aa16f933622f59e38b2023f7a9dfcf77ace79709137d21f1606e524dfe4036bc
KeliLanguage/compiler
Package.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE BangPatterns #-} module Package where import GHC.Generics hiding(packageName) import Control.Monad import Control.Concurrent import qualified Data.ByteString.Lazy.Char8 as Char8 import Text.ParserCombinators.Parsec hiding (token) import Data.Either import System.Directory import System.IO import System.Exit import qualified System.Info as SysInfo import System.Process import Data.Aeson.Encode.Pretty import Data.Aeson type Version = String data Purse = Purse { os :: String, arch :: String, compiler :: Version, git :: Version, node :: Version, dependencies :: [Dependency] } deriving (Show, Generic, Eq, Read) instance ToJSON Purse where instance FromJSON Purse where data Dependency = Dependency { url :: String, tag :: String } deriving (Show, Generic, Eq, Read) instance ToJSON Dependency where instance FromJSON Dependency where createNewPackage :: String -> IO() createNewPackage packageName = do putStrLn ("Creating package `" ++ packageName ++ "`") createDirectory packageName putStrLn ("Creating _src folder") createDirectory (packageName ++ "/_src") putStrLn ("Initializing purse.json") purse <- getPurse writeFile (packageName ++ "/_src/purse.json") (Char8.unpack (encodePretty purse)) putStrLn ("Creating _test folder") createDirectory (packageName ++ "/_test") putStrLn ("Creating README file") writeFile (packageName ++ "/README.md") ("# " ++ packageName) putStrLn ("Creating LICENSE file") writeFile (packageName ++ "/LICENSE") "" putStrLn ("Creating .gitignore file") writeFile (packageName ++ "/.gitignore") ( "# ignore all folders\n" ++ "/*\n\n" ++ "# ignore __temp__.keli generated by Keli Language Extension\n" ++ "__temp__.keli\n\n" ++ "# except\n" ++ "!.gitignore\n" ++ "!README.md\n" ++ "!LICENSE\n" ++ "!_src/\n" ++ "!_test/\n") -- initialize git output <- readCreateProcess ((shell "git init") { cwd = Just ("./" ++ packageName) }) "" putStrLn output -- stage and commit auto-generated files putStrLn "Staging and commiting initial files" !_ <- readCreateProcess ((shell "git add .") { cwd = Just ("./" ++ packageName) }) "" !_ <- readCreateProcess ((shell "git commit -m 'Package initialization'") { cwd = Just ("./" ++ packageName) }) "" putStrLn "\n==== Package successfully created! ====\n" putStrLn "Type the following command to go into your package:\n" putStrLn (" cd " ++ packageName ++ "\n") getPurse :: IO Purse getPurse = do compilerVersion' <- readProcess "keli" ["version"] [] gitVersion <- readProcess "git" ["--version"] [] nodeVersion <- readProcess "node" ["--version"] [] return Purse { os = SysInfo.os, arch = SysInfo.arch, compiler = init compilerVersion', -- init is used for removing the last newline character node = init nodeVersion, git = init gitVersion, dependencies = [] } defaultPursePath :: String defaultPursePath = "./_src/purse.json" readPurse :: String -> IO (Maybe Purse) readPurse pursePath = do purseFileExist <- doesPathExist pursePath if purseFileExist then do contents <- readFile pursePath return ((decode (Char8.pack contents)) :: Maybe Purse) else do hPutStrLn stderr ("Cannot locate the file named " ++ pursePath ++ ". Make sure you are in the package root.") return Nothing addDependency :: String -> String -> IO() addDependency gitRepoUrl tag = do let newDep = Dependency gitRepoUrl tag case toGitRepoUrl newDep of Left err -> hPutStrLn stderr (show err) Right{} -> do result <- readPurse defaultPursePath case result of Just purse -> do let prevDeps = dependencies purse if newDep `elem` prevDeps then hPutStrLn stderr $ "The dependency you intended to add is already added previously." else do let newPurse = purse {dependencies = prevDeps ++ [newDep]} putStrLn "Updating `dependencies` of `./_src/purse.json`" writeFile defaultPursePath (Char8.unpack (encodePretty newPurse)) installDeps defaultPursePath Nothing -> hPutStrLn stderr $ "Error:couldn't parse `./_src/purse.json`\n" ++ "Make sure it is in the correct format, " ++ "as defined at -language.gitbook.io/doc/specification/section-8-packages#8-4-manifest-file" installDeps :: String -> IO() installDeps pursePath = do putStrLn ("\nInstalling dependencies, referring: " ++ pursePath) result <- readPurse pursePath case result of Nothing -> return () Just purse -> do let parseResults = map toGitRepoUrl (dependencies purse) let errors = lefts parseResults case errors of -- if no parse errors [] -> do let grurls = rights parseResults !_ <- forM grurls (\u -> do let targetFolderName = authorName u ++ "." ++ repoName u ++ "." ++ tagString u alreadyDownloaded <- doesPathExist targetFolderName if alreadyDownloaded then -- skip the download for this grurl return () else do putStrLn ("\n-- Installing " ++ targetFolderName ++ "\n") !_ <- clonePackage u targetFolderName return()) putStrLn ("Dependencies installation completed for " ++ pursePath) -- if there are parse errors errors' -> do -- display parse errors !_ <- forM errors' (\e -> hPutStrLn stderr (show e)) return () clonePackage :: GitRepoUrl -> String -> IO() clonePackage u targetFolderName = do !_ <- readProcess "git" [ "clone", "-b", tagString u, "--single-branch", "--depth", "1", fullUrl u, targetFolderName, "-c", "advice.detachedHead=false"] -- this line is to silent all the stuff from git clone [] -- restructure the folder luckily , ` mv ` command works on both Windows and Linux sourceFiles <- listDirectory (targetFolderName ++ "/_src") exitCodes <- forM sourceFiles (\name -> do mvHandle <- spawnProcess "mv" [targetFolderName ++ "/_src/" ++ name, targetFolderName] waitForProcess mvHandle) -- if some files cannot be moved if any (\e -> case e of ExitFailure{}->True; _->False) exitCodes then hPutStrLn stderr ("Error unpacking files from _src.") else do -- remove unneeded files removeDirIfExists (targetFolderName ++ "/_src") removeDirIfExists (targetFolderName ++ "/_test") removeDirIfExists (targetFolderName ++ "/_.git") -- install its dependencies installDeps (targetFolderName ++ "/purse.json") return () removeDirIfExists :: FilePath -> IO() removeDirIfExists path = do yes <- doesPathExist path if yes then removeDirectoryRecursive path else return () data GitRepoUrl = GitRepoUrl { fullUrl :: String, authorName :: String, repoName :: String, tagString :: String } toGitRepoUrl :: Dependency -> Either ParseError GitRepoUrl toGitRepoUrl dep = parse parser "" (url dep) where parser :: Parser GitRepoUrl parser = (string "/" <|> string "/") >>= \_ -> manyTill anyChar (char '/') >>= \authorName' -> manyTill anyChar (string ".git") >>= \repoName' -> return (GitRepoUrl (url dep) authorName' repoName' (tag dep))
null
https://raw.githubusercontent.com/KeliLanguage/compiler/5cc5f2314fa0e0863a49c504cdb115d799f382f6/src/Package.hs
haskell
# LANGUAGE BangPatterns # initialize git stage and commit auto-generated files init is used for removing the last newline character if no parse errors skip the download for this grurl if there are parse errors display parse errors this line is to silent all the stuff from git clone restructure the folder if some files cannot be moved remove unneeded files install its dependencies
# LANGUAGE DeriveGeneric # module Package where import GHC.Generics hiding(packageName) import Control.Monad import Control.Concurrent import qualified Data.ByteString.Lazy.Char8 as Char8 import Text.ParserCombinators.Parsec hiding (token) import Data.Either import System.Directory import System.IO import System.Exit import qualified System.Info as SysInfo import System.Process import Data.Aeson.Encode.Pretty import Data.Aeson type Version = String data Purse = Purse { os :: String, arch :: String, compiler :: Version, git :: Version, node :: Version, dependencies :: [Dependency] } deriving (Show, Generic, Eq, Read) instance ToJSON Purse where instance FromJSON Purse where data Dependency = Dependency { url :: String, tag :: String } deriving (Show, Generic, Eq, Read) instance ToJSON Dependency where instance FromJSON Dependency where createNewPackage :: String -> IO() createNewPackage packageName = do putStrLn ("Creating package `" ++ packageName ++ "`") createDirectory packageName putStrLn ("Creating _src folder") createDirectory (packageName ++ "/_src") putStrLn ("Initializing purse.json") purse <- getPurse writeFile (packageName ++ "/_src/purse.json") (Char8.unpack (encodePretty purse)) putStrLn ("Creating _test folder") createDirectory (packageName ++ "/_test") putStrLn ("Creating README file") writeFile (packageName ++ "/README.md") ("# " ++ packageName) putStrLn ("Creating LICENSE file") writeFile (packageName ++ "/LICENSE") "" putStrLn ("Creating .gitignore file") writeFile (packageName ++ "/.gitignore") ( "# ignore all folders\n" ++ "/*\n\n" ++ "# ignore __temp__.keli generated by Keli Language Extension\n" ++ "__temp__.keli\n\n" ++ "# except\n" ++ "!.gitignore\n" ++ "!README.md\n" ++ "!LICENSE\n" ++ "!_src/\n" ++ "!_test/\n") output <- readCreateProcess ((shell "git init") { cwd = Just ("./" ++ packageName) }) "" putStrLn output putStrLn "Staging and commiting initial files" !_ <- readCreateProcess ((shell "git add .") { cwd = Just ("./" ++ packageName) }) "" !_ <- readCreateProcess ((shell "git commit -m 'Package initialization'") { cwd = Just ("./" ++ packageName) }) "" putStrLn "\n==== Package successfully created! ====\n" putStrLn "Type the following command to go into your package:\n" putStrLn (" cd " ++ packageName ++ "\n") getPurse :: IO Purse getPurse = do compilerVersion' <- readProcess "keli" ["version"] [] gitVersion <- readProcess "git" ["--version"] [] nodeVersion <- readProcess "node" ["--version"] [] return Purse { os = SysInfo.os, arch = SysInfo.arch, node = init nodeVersion, git = init gitVersion, dependencies = [] } defaultPursePath :: String defaultPursePath = "./_src/purse.json" readPurse :: String -> IO (Maybe Purse) readPurse pursePath = do purseFileExist <- doesPathExist pursePath if purseFileExist then do contents <- readFile pursePath return ((decode (Char8.pack contents)) :: Maybe Purse) else do hPutStrLn stderr ("Cannot locate the file named " ++ pursePath ++ ". Make sure you are in the package root.") return Nothing addDependency :: String -> String -> IO() addDependency gitRepoUrl tag = do let newDep = Dependency gitRepoUrl tag case toGitRepoUrl newDep of Left err -> hPutStrLn stderr (show err) Right{} -> do result <- readPurse defaultPursePath case result of Just purse -> do let prevDeps = dependencies purse if newDep `elem` prevDeps then hPutStrLn stderr $ "The dependency you intended to add is already added previously." else do let newPurse = purse {dependencies = prevDeps ++ [newDep]} putStrLn "Updating `dependencies` of `./_src/purse.json`" writeFile defaultPursePath (Char8.unpack (encodePretty newPurse)) installDeps defaultPursePath Nothing -> hPutStrLn stderr $ "Error:couldn't parse `./_src/purse.json`\n" ++ "Make sure it is in the correct format, " ++ "as defined at -language.gitbook.io/doc/specification/section-8-packages#8-4-manifest-file" installDeps :: String -> IO() installDeps pursePath = do putStrLn ("\nInstalling dependencies, referring: " ++ pursePath) result <- readPurse pursePath case result of Nothing -> return () Just purse -> do let parseResults = map toGitRepoUrl (dependencies purse) let errors = lefts parseResults case errors of [] -> do let grurls = rights parseResults !_ <- forM grurls (\u -> do let targetFolderName = authorName u ++ "." ++ repoName u ++ "." ++ tagString u alreadyDownloaded <- doesPathExist targetFolderName if alreadyDownloaded then return () else do putStrLn ("\n-- Installing " ++ targetFolderName ++ "\n") !_ <- clonePackage u targetFolderName return()) putStrLn ("Dependencies installation completed for " ++ pursePath) errors' -> do !_ <- forM errors' (\e -> hPutStrLn stderr (show e)) return () clonePackage :: GitRepoUrl -> String -> IO() clonePackage u targetFolderName = do !_ <- readProcess "git" [ "clone", "-b", tagString u, "--single-branch", "--depth", "1", fullUrl u, targetFolderName, [] luckily , ` mv ` command works on both Windows and Linux sourceFiles <- listDirectory (targetFolderName ++ "/_src") exitCodes <- forM sourceFiles (\name -> do mvHandle <- spawnProcess "mv" [targetFolderName ++ "/_src/" ++ name, targetFolderName] waitForProcess mvHandle) if any (\e -> case e of ExitFailure{}->True; _->False) exitCodes then hPutStrLn stderr ("Error unpacking files from _src.") else do removeDirIfExists (targetFolderName ++ "/_src") removeDirIfExists (targetFolderName ++ "/_test") removeDirIfExists (targetFolderName ++ "/_.git") installDeps (targetFolderName ++ "/purse.json") return () removeDirIfExists :: FilePath -> IO() removeDirIfExists path = do yes <- doesPathExist path if yes then removeDirectoryRecursive path else return () data GitRepoUrl = GitRepoUrl { fullUrl :: String, authorName :: String, repoName :: String, tagString :: String } toGitRepoUrl :: Dependency -> Either ParseError GitRepoUrl toGitRepoUrl dep = parse parser "" (url dep) where parser :: Parser GitRepoUrl parser = (string "/" <|> string "/") >>= \_ -> manyTill anyChar (char '/') >>= \authorName' -> manyTill anyChar (string ".git") >>= \repoName' -> return (GitRepoUrl (url dep) authorName' repoName' (tag dep))
8e79b692182b5a996c5c878b702f68ad809f0ed11bf2f12e7b40d7f555a12585
tisnik/clojure-examples
core.clj
; ( C ) Copyright 2016 , 2020 , 2021 ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the Eclipse Public License v1.0 ; which accompanies this distribution, and is available at -v10.html ; ; Contributors: ; (ns stream-pipe-4.core (:require [jackdaw.admin :as ja] [jackdaw.client :as jc] [jackdaw.client.log :as jl] [jackdaw.serdes.json] [jackdaw.streams :as j] [clojure.pprint :as pp] [clojure.tools.logging :as log])) (def topic-config "Konfigurace témat - vstupního i výstupního." {:input {:topic-name "input" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)} :output-1 {:topic-name "output1" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)} :output-2 {:topic-name "output2" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)} :output-3 {:topic-name "output3" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)}}) (def app-config "Konfigurace aplikace (ve smyslu knihovny Jackdaw)." {"application.id" "pipe" "bootstrap.servers" "localhost:9092" "cache.max.bytes.buffering" "0" "default.deserialization.exception.handler" "org.apache.kafka.streams.errors.LogAndContinueExceptionHandler"}) (defn delete-topic "Pomocná funkce pro smazání vybraného tématu." [broker-config topic] (try (log/warn "Deleting topic" (:topic-name topic)) (let [client (ja/->AdminClient broker-config)] (ja/delete-topics! client [topic])) (catch Exception e (str "caught exception: " (.getMessage e))))) (defn new-topic "Pomocná funkce pro vytvoření nového tématu." [broker-config topic] (try (log/warn "Creating topic" (:topic-name topic)) (let [client (ja/->AdminClient broker-config)] (ja/create-topics! client [topic])) (catch Exception e (str "caught exception: " (.getMessage e))))) (defn etl-1 "Transformační funkce." [[k v]] [k {:result (+ (:x v) (:y v))}]) (defn etl-2 "Transformační funkce." [[k v]] [k (assoc v :timestamp (str (new java.util.Date)))]) (defn build-topology "Definice celé pipeliny (kolony) - základ aplikace." [builder topic-config] (-> (j/kstream builder (:input topic-config)) (j/peek (fn [[k v]] (log/warn "Received message with key: " k " and value:" v))) (j/through (:output-1 topic-config)) (j/map etl-1) (j/peek (fn [[k v]] (log/warn "Transformed message with key:" k " and value:" v))) (j/through (:output-2 topic-config)) (j/map etl-2) (j/peek (fn [[k v]] (log/warn "Transformed message with key:" k " and value:" v))) (j/to (:output-3 topic-config))) builder) (defn start-app "Spuštění aplikace." [app-config topic-config] (let [builder (j/streams-builder) topology (build-topology builder topic-config) app (j/kafka-streams topology app-config)] (log/warn "Starting pipe") (j/start app) (log/warn "Pipe is up") app)) (defn stop-app "Zastavení aplikace." [app] (log/warn "Stopping pipe") (j/close app) (log/warn "Pipe is down")) (defn -main [& args] (let [broker-config {"bootstrap.servers" "localhost:9092"}] na začátku pro (delete-topic broker-config (:input topic-config)) (delete-topic broker-config (:output-1 topic-config)) (delete-topic broker-config (:output-2 topic-config)) (delete-topic broker-config (:output-3 topic-config)) vytvoření akceptujících zprávy ve formátu JSON (new-topic broker-config (:input topic-config)) (new-topic broker-config (:output-1 topic-config)) (new-topic broker-config (:output-2 topic-config)) (new-topic broker-config (:output-3 topic-config)) ;; spuštění kolony (log/warn "Starting application") (let [app (start-app app-config topic-config)] (log/warn "App created:" app))))
null
https://raw.githubusercontent.com/tisnik/clojure-examples/a5f9d6119b62520b05da64b7929d07b832b957ab/kafka-stream-pipe-4/src/stream_pipe_4/core.clj
clojure
All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at Contributors: spuštění kolony
( C ) Copyright 2016 , 2020 , 2021 -v10.html (ns stream-pipe-4.core (:require [jackdaw.admin :as ja] [jackdaw.client :as jc] [jackdaw.client.log :as jl] [jackdaw.serdes.json] [jackdaw.streams :as j] [clojure.pprint :as pp] [clojure.tools.logging :as log])) (def topic-config "Konfigurace témat - vstupního i výstupního." {:input {:topic-name "input" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)} :output-1 {:topic-name "output1" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)} :output-2 {:topic-name "output2" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)} :output-3 {:topic-name "output3" :partition-count 1 :replication-factor 1 :key-serde (jackdaw.serdes.json/serde) :value-serde (jackdaw.serdes.json/serde)}}) (def app-config "Konfigurace aplikace (ve smyslu knihovny Jackdaw)." {"application.id" "pipe" "bootstrap.servers" "localhost:9092" "cache.max.bytes.buffering" "0" "default.deserialization.exception.handler" "org.apache.kafka.streams.errors.LogAndContinueExceptionHandler"}) (defn delete-topic "Pomocná funkce pro smazání vybraného tématu." [broker-config topic] (try (log/warn "Deleting topic" (:topic-name topic)) (let [client (ja/->AdminClient broker-config)] (ja/delete-topics! client [topic])) (catch Exception e (str "caught exception: " (.getMessage e))))) (defn new-topic "Pomocná funkce pro vytvoření nového tématu." [broker-config topic] (try (log/warn "Creating topic" (:topic-name topic)) (let [client (ja/->AdminClient broker-config)] (ja/create-topics! client [topic])) (catch Exception e (str "caught exception: " (.getMessage e))))) (defn etl-1 "Transformační funkce." [[k v]] [k {:result (+ (:x v) (:y v))}]) (defn etl-2 "Transformační funkce." [[k v]] [k (assoc v :timestamp (str (new java.util.Date)))]) (defn build-topology "Definice celé pipeliny (kolony) - základ aplikace." [builder topic-config] (-> (j/kstream builder (:input topic-config)) (j/peek (fn [[k v]] (log/warn "Received message with key: " k " and value:" v))) (j/through (:output-1 topic-config)) (j/map etl-1) (j/peek (fn [[k v]] (log/warn "Transformed message with key:" k " and value:" v))) (j/through (:output-2 topic-config)) (j/map etl-2) (j/peek (fn [[k v]] (log/warn "Transformed message with key:" k " and value:" v))) (j/to (:output-3 topic-config))) builder) (defn start-app "Spuštění aplikace." [app-config topic-config] (let [builder (j/streams-builder) topology (build-topology builder topic-config) app (j/kafka-streams topology app-config)] (log/warn "Starting pipe") (j/start app) (log/warn "Pipe is up") app)) (defn stop-app "Zastavení aplikace." [app] (log/warn "Stopping pipe") (j/close app) (log/warn "Pipe is down")) (defn -main [& args] (let [broker-config {"bootstrap.servers" "localhost:9092"}] na začátku pro (delete-topic broker-config (:input topic-config)) (delete-topic broker-config (:output-1 topic-config)) (delete-topic broker-config (:output-2 topic-config)) (delete-topic broker-config (:output-3 topic-config)) vytvoření akceptujících zprávy ve formátu JSON (new-topic broker-config (:input topic-config)) (new-topic broker-config (:output-1 topic-config)) (new-topic broker-config (:output-2 topic-config)) (new-topic broker-config (:output-3 topic-config)) (log/warn "Starting application") (let [app (start-app app-config topic-config)] (log/warn "App created:" app))))
39298a781bb690c25bb79c89d87910087fb4528beee1a5e1234f5b49ec0cfaa5
utdemir/distributed-dataset
Types.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE StaticPointers # # LANGUAGE TemplateHaskell # module Control.Distributed.Dataset.OpenDatasets.GHArchive.Types where import Codec.Serialise (Serialise) import Control.Distributed.Dataset ( Dict (Dict), StaticSerialise (staticSerialise), ) import Control.Lens.TH (makeLenses, makePrisms) import Data.Aeson ((.!=), (.:), (.:?), FromJSON (..), withObject) import Data.Text (Text) import GHC.Generics (Generic) data GHEvent = GHEvent {_gheActor :: GHActor, _gheRepo :: GHRepo, _gheType :: GHEventType} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHEvent where staticSerialise = static Dict instance FromJSON GHEvent where parseJSON val = withObject "GHEvent" ( \obj -> GHEvent <$> obj .: "actor" <*> obj .: "repo" <*> parseJSON val ) val data GHEventType = GHPushEvent GHPushEventPayload | GHOtherEvent Text deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHEventType where staticSerialise = static Dict instance FromJSON GHEventType where parseJSON = withObject "GHEventType" ( \obj -> do ty <- obj .: "type" payload <- obj .: "payload" case ty of "PushEvent" -> GHPushEvent <$> parseJSON payload other -> return $ GHOtherEvent other ) newtype GHPushEventPayload = GHPushEventPayload {_ghpepCommits :: [GHCommit]} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHPushEventPayload where staticSerialise = static Dict instance FromJSON GHPushEventPayload where parseJSON = withObject "GHPushEventPayload" $ \obj -> GHPushEventPayload <$> obj .: "commits" data GHCommit = GHCommit { _ghcAuthor :: GHCommitAuthor, _ghcMessage :: Text, _ghcSha :: Text, _ghcDistinct :: Bool } deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHCommit where staticSerialise = static Dict instance FromJSON GHCommit where parseJSON = withObject "GHCommit" $ \obj -> GHCommit <$> obj .: "author" <*> obj .: "message" <*> obj .: "sha" <*> obj .:? "distinct" .!= True data GHCommitAuthor = GHCommitAuthor {_ghcaEmail :: Text, _ghcaName :: Text} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHCommitAuthor where staticSerialise = static Dict instance FromJSON GHCommitAuthor where parseJSON = withObject "GHCommitAuthor" $ \obj -> GHCommitAuthor <$> obj .: "email" <*> obj .: "name" data GHActor = GHActor {_ghaId :: Maybe Integer, _ghaLogin :: Maybe Text, _ghaUrl :: Text} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHActor where staticSerialise = static Dict instance FromJSON GHActor where parseJSON = withObject "GHActor" $ \obj -> GHActor <$> obj .:? "id" <*> obj .:? "login" <*> obj .: "url" data GHRepo = GHRepo {_ghrId :: Integer, _ghrName :: Text} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHRepo where staticSerialise = static Dict instance FromJSON GHRepo where parseJSON = withObject "GHRepo" $ \obj -> GHRepo <$> obj .: "id" <*> obj .: "name" makeLenses ''GHEvent makePrisms ''GHEventType makeLenses ''GHPushEventPayload makeLenses ''GHCommit makeLenses ''GHCommitAuthor makeLenses ''GHActor makeLenses ''GHRepo
null
https://raw.githubusercontent.com/utdemir/distributed-dataset/a582a96e541884580e66bc5d87b4d498c8d58182/distributed-dataset-opendatasets/src/Control/Distributed/Dataset/OpenDatasets/GHArchive/Types.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveGeneric # # LANGUAGE StaticPointers # # LANGUAGE TemplateHaskell # module Control.Distributed.Dataset.OpenDatasets.GHArchive.Types where import Codec.Serialise (Serialise) import Control.Distributed.Dataset ( Dict (Dict), StaticSerialise (staticSerialise), ) import Control.Lens.TH (makeLenses, makePrisms) import Data.Aeson ((.!=), (.:), (.:?), FromJSON (..), withObject) import Data.Text (Text) import GHC.Generics (Generic) data GHEvent = GHEvent {_gheActor :: GHActor, _gheRepo :: GHRepo, _gheType :: GHEventType} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHEvent where staticSerialise = static Dict instance FromJSON GHEvent where parseJSON val = withObject "GHEvent" ( \obj -> GHEvent <$> obj .: "actor" <*> obj .: "repo" <*> parseJSON val ) val data GHEventType = GHPushEvent GHPushEventPayload | GHOtherEvent Text deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHEventType where staticSerialise = static Dict instance FromJSON GHEventType where parseJSON = withObject "GHEventType" ( \obj -> do ty <- obj .: "type" payload <- obj .: "payload" case ty of "PushEvent" -> GHPushEvent <$> parseJSON payload other -> return $ GHOtherEvent other ) newtype GHPushEventPayload = GHPushEventPayload {_ghpepCommits :: [GHCommit]} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHPushEventPayload where staticSerialise = static Dict instance FromJSON GHPushEventPayload where parseJSON = withObject "GHPushEventPayload" $ \obj -> GHPushEventPayload <$> obj .: "commits" data GHCommit = GHCommit { _ghcAuthor :: GHCommitAuthor, _ghcMessage :: Text, _ghcSha :: Text, _ghcDistinct :: Bool } deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHCommit where staticSerialise = static Dict instance FromJSON GHCommit where parseJSON = withObject "GHCommit" $ \obj -> GHCommit <$> obj .: "author" <*> obj .: "message" <*> obj .: "sha" <*> obj .:? "distinct" .!= True data GHCommitAuthor = GHCommitAuthor {_ghcaEmail :: Text, _ghcaName :: Text} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHCommitAuthor where staticSerialise = static Dict instance FromJSON GHCommitAuthor where parseJSON = withObject "GHCommitAuthor" $ \obj -> GHCommitAuthor <$> obj .: "email" <*> obj .: "name" data GHActor = GHActor {_ghaId :: Maybe Integer, _ghaLogin :: Maybe Text, _ghaUrl :: Text} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHActor where staticSerialise = static Dict instance FromJSON GHActor where parseJSON = withObject "GHActor" $ \obj -> GHActor <$> obj .:? "id" <*> obj .:? "login" <*> obj .: "url" data GHRepo = GHRepo {_ghrId :: Integer, _ghrName :: Text} deriving (Eq, Show, Generic, Serialise) instance StaticSerialise GHRepo where staticSerialise = static Dict instance FromJSON GHRepo where parseJSON = withObject "GHRepo" $ \obj -> GHRepo <$> obj .: "id" <*> obj .: "name" makeLenses ''GHEvent makePrisms ''GHEventType makeLenses ''GHPushEventPayload makeLenses ''GHCommit makeLenses ''GHCommitAuthor makeLenses ''GHActor makeLenses ''GHRepo
65d5d781a2ed67babdfb5679def1cbe406d02af8e5be6be1682e5fd2d5e21ed9
Helium4Haskell/helium
LayoutBad6.hs
module LayoutBad6 where x = id (case x of 3 -> 4)
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/parser/LayoutBad6.hs
haskell
module LayoutBad6 where x = id (case x of 3 -> 4)
c0f771158d54078435e75b819d9c6a408764252275979a2dd320d7f7702d81f3
brownplt/cs173-python
basic.rkt
#lang plai (require racket/match racket/list) (define (pretty-struct s) (pretty-write s)) (define (pretty-store s) (pretty-write s)) (define (pretty-scopedb s) (pretty-write s))
null
https://raw.githubusercontent.com/brownplt/cs173-python/d8ae026172f269282e54366f16ec42e037117cb4/design2/python/basic.rkt
racket
#lang plai (require racket/match racket/list) (define (pretty-struct s) (pretty-write s)) (define (pretty-store s) (pretty-write s)) (define (pretty-scopedb s) (pretty-write s))
5c81c64d9371fe1771fbed60a3a7480c0f4e4ad48074269db66abff1ca394b73
ntoronto/drbayes
arrow-tests.rkt
#lang typed/racket (require typed/rackunit drbayes/private/set drbayes/private/arrow) (check-true (set-equal? (range/pre (run/pre (+/pre) (set-pair (real-set 0.0 1.0 #t #t) (real-set 0.0 1.0 #t #t)))) (real-set 0.0 2.0 #t #t))) (let () (define-values (A A-exact?) (preimage/pre (run/pre (+/pre) (set-pair (real-set 0.0 1.0 #t #t) (real-set 0.0 1.0 #t #t))) (real-set 0.0 0.5 #t #t))) (check-true (set-equal? A (set-pair (real-set 0.0 0.5 #t #t) (real-set 0.0 0.5 #t #t)))))
null
https://raw.githubusercontent.com/ntoronto/drbayes/e59eb7c7867118bf4c77ca903e133c7530e612a3/drbayes/tests/arrow-tests/arrow-tests.rkt
racket
#lang typed/racket (require typed/rackunit drbayes/private/set drbayes/private/arrow) (check-true (set-equal? (range/pre (run/pre (+/pre) (set-pair (real-set 0.0 1.0 #t #t) (real-set 0.0 1.0 #t #t)))) (real-set 0.0 2.0 #t #t))) (let () (define-values (A A-exact?) (preimage/pre (run/pre (+/pre) (set-pair (real-set 0.0 1.0 #t #t) (real-set 0.0 1.0 #t #t))) (real-set 0.0 0.5 #t #t))) (check-true (set-equal? A (set-pair (real-set 0.0 0.5 #t #t) (real-set 0.0 0.5 #t #t)))))
e312f67015024220dc4d17e4f7778695e292068058ed37e3c106f22ee1a7217d
chrisnevers/ocamline
read.ml
open Ocamline let hints = function | "git remote add " -> Some (" <remote name> <remote url>", LNoise.Yellow, true) | _ -> None let completion line_so_far ln_completions = if line_so_far <> "" && line_so_far.[0] = 'h' then ["Hey"; "Howard"; "Hughes"; "Hocus"] |> List.iter (LNoise.add_completion ln_completions) let rec repl () = let str = read ~prompt:"ocamline>" ~brackets:['(', ')'] ~delim:";;" ~hints_callback:hints ~completion_callback:completion () in print_endline str; repl () let _ = repl ()
null
https://raw.githubusercontent.com/chrisnevers/ocamline/6a9c5a190844a3ecbbb0b168372248d10fa184d0/examples/read.ml
ocaml
open Ocamline let hints = function | "git remote add " -> Some (" <remote name> <remote url>", LNoise.Yellow, true) | _ -> None let completion line_so_far ln_completions = if line_so_far <> "" && line_so_far.[0] = 'h' then ["Hey"; "Howard"; "Hughes"; "Hocus"] |> List.iter (LNoise.add_completion ln_completions) let rec repl () = let str = read ~prompt:"ocamline>" ~brackets:['(', ')'] ~delim:";;" ~hints_callback:hints ~completion_callback:completion () in print_endline str; repl () let _ = repl ()
fce597b743ee3f19020c1a6cbb968cb2de1d4b8673b9de7b2bd26ad6074dd3af
malcolmsparks/plugboard
test_accept.clj
Copyright 2010 . ;; This file is part of Plugboard . ;; Plugboard 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. ;; Plugboard 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. ;; Please see the LICENSE file for a copy of the GNU Affero General Public License . (ns plugboard.demos.accept.test-accept (:use clojure.test) (:require plugboard.demos.accept.configuration [clj-http.client :as http] [clojure.data.zip.xml :as zfx] [compojure.core :as compojure] [plugboard.core.conneg :as conneg] [plugboard.demos.accept.webfunctions] [plugboard.demos.jetty-fixture :as jf] [plugboard.webfunction.plugboards :as plugboards] [plugboard.webfunction.webfunction :as web])) ;; TODO: Do more tests to check different content negotiation situations. (use-fixtures :once (jf/make-fixture (compojure/routes (compojure/GET "/test/*" [] (jf/create-handler (plugboard.demos.accept.configuration/create-plugboard)))))) (deftest test-demo (letfn [(get-content-type [response] (:type (conneg/accept-fragment (get-in response [:headers "content-type"]))))] (let [response (http/get (format ":%d/test/index" (jf/get-jetty-port)))] (is (= 200 (:status response))) (is (= ["application" "xhtml+xml"] (get-content-type response))))))
null
https://raw.githubusercontent.com/malcolmsparks/plugboard/c1e78afc5dde60b08b48020c6f3ef800f05d1ada/src/test/clojure/plugboard/demos/accept/test_accept.clj
clojure
later version. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. TODO: Do more tests to check different content negotiation situations.
Copyright 2010 . This file is part of Plugboard . Plugboard 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 Plugboard is distributed in the hope that it will be useful but WITHOUT ANY Please see the LICENSE file for a copy of the GNU Affero General Public License . (ns plugboard.demos.accept.test-accept (:use clojure.test) (:require plugboard.demos.accept.configuration [clj-http.client :as http] [clojure.data.zip.xml :as zfx] [compojure.core :as compojure] [plugboard.core.conneg :as conneg] [plugboard.demos.accept.webfunctions] [plugboard.demos.jetty-fixture :as jf] [plugboard.webfunction.plugboards :as plugboards] [plugboard.webfunction.webfunction :as web])) (use-fixtures :once (jf/make-fixture (compojure/routes (compojure/GET "/test/*" [] (jf/create-handler (plugboard.demos.accept.configuration/create-plugboard)))))) (deftest test-demo (letfn [(get-content-type [response] (:type (conneg/accept-fragment (get-in response [:headers "content-type"]))))] (let [response (http/get (format ":%d/test/index" (jf/get-jetty-port)))] (is (= 200 (:status response))) (is (= ["application" "xhtml+xml"] (get-content-type response))))))
72864587aff3425c9a22e78d382fe63d5922b0be3f3fe60f31c16ece487241df
RefactoringTools/HaRe
M3.hs
module M3 where --Any type/data constructor name declared in this module can be renamed. --Any type variable can be renamed. Rename type Constructor ' BTree ' to ' MyBTree ' data BTree a = Empty | T a (BTree a) (BTree a) deriving Show buildtree :: (Monad m, Ord a) => [a] -> m (BTree a) buildtree [] = return Empty buildtree (x:xs) = do res1 <- buildtree xs res <- insert x res1 return res insert :: (Monad m, Ord a) => a -> BTree a -> m (BTree a) insert val v2 = do case v2 of T val Empty Empty | val == val -> return Empty | otherwise -> return (T val Empty (T val Empty Empty)) T val (T val2 Empty Empty) Empty -> return Empty _ -> return v2 main :: IO () main = do n@(T val Empty Empty) <- buildtree [3, 1, 2] if True then do putStrLn $ (show n) else do putStrLn $ (show (T val Empty n))
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/testing/unfoldAsPatterns/M3.hs
haskell
Any type/data constructor name declared in this module can be renamed. Any type variable can be renamed.
module M3 where Rename type Constructor ' BTree ' to ' MyBTree ' data BTree a = Empty | T a (BTree a) (BTree a) deriving Show buildtree :: (Monad m, Ord a) => [a] -> m (BTree a) buildtree [] = return Empty buildtree (x:xs) = do res1 <- buildtree xs res <- insert x res1 return res insert :: (Monad m, Ord a) => a -> BTree a -> m (BTree a) insert val v2 = do case v2 of T val Empty Empty | val == val -> return Empty | otherwise -> return (T val Empty (T val Empty Empty)) T val (T val2 Empty Empty) Empty -> return Empty _ -> return v2 main :: IO () main = do n@(T val Empty Empty) <- buildtree [3, 1, 2] if True then do putStrLn $ (show n) else do putStrLn $ (show (T val Empty n))
fa8e2988c1fc24fb0aaea415cc270cac1e800809f84fa1284bf5ceba5bf0de55
faylang/fay
C.hs
module ImportList1.C where import Prelude data A = B1 { b1 :: Double } | B2 Double data UnimportedX = UnimportedY unimportedF :: Double unimportedF = 1
null
https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/ImportList1/C.hs
haskell
module ImportList1.C where import Prelude data A = B1 { b1 :: Double } | B2 Double data UnimportedX = UnimportedY unimportedF :: Double unimportedF = 1
435eb05037a60aaae5d833939cde4b20463a473d6afc7e597f05b1875e250f7c
ocaml-ppx/ppx
view_attr.mli
* Helpers to interpret [ [ @view ? ... ] ] attributes open Ppx_ast.V4_07 (** The type for information about an extra record field. *) type field = Longident_loc.t * Pattern.t * Extracts the extra field information from the [ [ @view ? ... ] ] attributes amongst the given pattern attributes . Returns [ None ] if there is no such attribute . amongst the given pattern attributes. Returns [None] if there is no such attribute. *) val extract_fields : Attributes.t -> ((field list) option, Error.t) result
null
https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/ppx_view/lib/view_attr.mli
ocaml
* The type for information about an extra record field.
* Helpers to interpret [ [ @view ? ... ] ] attributes open Ppx_ast.V4_07 type field = Longident_loc.t * Pattern.t * Extracts the extra field information from the [ [ @view ? ... ] ] attributes amongst the given pattern attributes . Returns [ None ] if there is no such attribute . amongst the given pattern attributes. Returns [None] if there is no such attribute. *) val extract_fields : Attributes.t -> ((field list) option, Error.t) result
ec70aeee665528705425615de56e8a6c95a2274b637dad993973351f626294a3
racket/plot
marching-utils.rkt
#lang typed/racket/base (provide (all-defined-out)) ;; Returns the interpolated distance of z from za toward zb Examples : if z = za , this returns 0.0 if z = zb , this returns 1.0 if z = ( za + zb ) / 2 , this returns 0.5 ;; Intuitively, regard a use (solve-t z za zb) as "the point between za and zb". (define-syntax-rule (solve-t z za zb) (/ (- z za) (- zb za))) (define-syntax-rule (unsolve-t za zb t) (cond [(eq? t 0) za] [(eq? t 1) zb] [else (+ (* t zb) (* (- 1 t) za))]))
null
https://raw.githubusercontent.com/racket/plot/c4126001f2c609e36c3aa12f300e9c673ab1a806/plot-lib/plot/private/common/marching-utils.rkt
racket
Returns the interpolated distance of z from za toward zb Intuitively, regard a use (solve-t z za zb) as "the point between za and zb".
#lang typed/racket/base (provide (all-defined-out)) Examples : if z = za , this returns 0.0 if z = zb , this returns 1.0 if z = ( za + zb ) / 2 , this returns 0.5 (define-syntax-rule (solve-t z za zb) (/ (- z za) (- zb za))) (define-syntax-rule (unsolve-t za zb t) (cond [(eq? t 0) za] [(eq? t 1) zb] [else (+ (* t zb) (* (- 1 t) za))]))
4fa0b0a7f50296bc141b906b1878e35bdd30544dbd7181ca9406d2ff45e6e2ec
melange-re/melange-compiler-libs
printtyped.ml
(**************************************************************************) (* *) (* OCaml *) (* *) (* Fabrice Le Fessant, INRIA Saclay *) (* *) Copyright 1999 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 Asttypes;; open Format;; open Lexing;; open Location;; open Typedtree;; let fmt_position f l = if l.pos_lnum = -1 then fprintf f "%s[%d]" l.pos_fname l.pos_cnum else fprintf f "%s[%d,%d+%d]" l.pos_fname l.pos_lnum l.pos_bol (l.pos_cnum - l.pos_bol) ;; let fmt_location f loc = if not !Clflags.locations then () else begin fprintf f "(%a..%a)" fmt_position loc.loc_start fmt_position loc.loc_end; if loc.loc_ghost then fprintf f " ghost"; end ;; let rec fmt_longident_aux f x = match x with | Longident.Lident (s) -> fprintf f "%s" s; | Longident.Ldot (y, s) -> fprintf f "%a.%s" fmt_longident_aux y s; | Longident.Lapply (y, z) -> fprintf f "%a(%a)" fmt_longident_aux y fmt_longident_aux z; ;; let fmt_longident f x = fprintf f "\"%a\"" fmt_longident_aux x.txt;; let fmt_ident = Ident.print let fmt_modname f = function | None -> fprintf f "_"; | Some id -> Ident.print f id let rec fmt_path_aux f x = match x with | Path.Pident (s) -> fprintf f "%a" fmt_ident s; | Path.Pdot (y, s) -> fprintf f "%a.%s" fmt_path_aux y s; | Path.Papply (y, z) -> fprintf f "%a(%a)" fmt_path_aux y fmt_path_aux z; ;; let fmt_path f x = fprintf f "\"%a\"" fmt_path_aux x;; let fmt_constant f x = match x with | Const_int (i) -> fprintf f "Const_int %d" i; | Const_char (c) -> fprintf f "Const_char %02x" (Char.code c); | Const_string (s, strloc, None) -> fprintf f "Const_string(%S,%a,None)" s fmt_location strloc; | Const_string (s, strloc, Some delim) -> fprintf f "Const_string (%S,%a,Some %S)" s fmt_location strloc delim; | Const_float (s) -> fprintf f "Const_float %s" s; | Const_int32 (i) -> fprintf f "Const_int32 %ld" i; | Const_int64 (i) -> fprintf f "Const_int64 %Ld" i; | Const_nativeint (i) -> fprintf f "Const_nativeint %nd" i; ;; let fmt_mutable_flag f x = match x with | Immutable -> fprintf f "Immutable"; | Mutable -> fprintf f "Mutable"; ;; let fmt_virtual_flag f x = match x with | Virtual -> fprintf f "Virtual"; | Concrete -> fprintf f "Concrete"; ;; let fmt_override_flag f x = match x with | Override -> fprintf f "Override"; | Fresh -> fprintf f "Fresh"; ;; let fmt_closed_flag f x = match x with | Closed -> fprintf f "Closed" | Open -> fprintf f "Open" let fmt_rec_flag f x = match x with | Nonrecursive -> fprintf f "Nonrec"; | Recursive -> fprintf f "Rec"; ;; let fmt_direction_flag f x = match x with | Upto -> fprintf f "Up"; | Downto -> fprintf f "Down"; ;; let fmt_private_flag f x = match x with | Public -> fprintf f "Public"; | Private -> fprintf f "Private"; ;; let line i f s (*...*) = fprintf f "%s" (String.make (2*i) ' '); fprintf f s (*...*) ;; let list i f ppf l = match l with | [] -> line i ppf "[]\n"; | _ :: _ -> line i ppf "[\n"; List.iter (f (i+1) ppf) l; line i ppf "]\n"; ;; let array i f ppf a = if Array.length a = 0 then line i ppf "[]\n" else begin line i ppf "[\n"; Array.iter (f (i+1) ppf) a; line i ppf "]\n" end ;; let option i f ppf x = match x with | None -> line i ppf "None\n"; | Some x -> line i ppf "Some\n"; f (i+1) ppf x; ;; let longident i ppf li = line i ppf "%a\n" fmt_longident li;; let string i ppf s = line i ppf "\"%s\"\n" s;; let arg_label i ppf = function | Nolabel -> line i ppf "Nolabel\n" | Optional s -> line i ppf "Optional \"%s\"\n" s | Labelled s -> line i ppf "Labelled \"%s\"\n" s ;; let typevars ppf vs = List.iter (fun x -> fprintf ppf " %a" Pprintast.tyvar x.txt) vs ;; let record_representation i ppf = let open Types in function | Record_regular -> line i ppf "Record_regular\n" | Record_float -> line i ppf "Record_float\n" | Record_unboxed b -> line i ppf "Record_unboxed %b\n" b | Record_inlined {tag = i} -> line i ppf "Record_inlined %d\n" i | Record_extension p -> line i ppf "Record_extension %a\n" fmt_path p let attribute i ppf k a = line i ppf "%s \"%s\"\n" k a.Parsetree.attr_name.txt; Printast.payload i ppf a.Parsetree.attr_payload let attributes i ppf l = let i = i + 1 in List.iter (fun a -> line i ppf "attribute \"%s\"\n" a.Parsetree.attr_name.txt; Printast.payload (i + 1) ppf a.Parsetree.attr_payload ) l let rec core_type i ppf x = line i ppf "core_type %a\n" fmt_location x.ctyp_loc; attributes i ppf x.ctyp_attributes; let i = i+1 in match x.ctyp_desc with | Ttyp_any -> line i ppf "Ttyp_any\n"; | Ttyp_var (s) -> line i ppf "Ttyp_var %s\n" s; | Ttyp_arrow (l, ct1, ct2) -> line i ppf "Ttyp_arrow\n"; arg_label i ppf l; core_type i ppf ct1; core_type i ppf ct2; | Ttyp_tuple l -> line i ppf "Ttyp_tuple\n"; list i core_type ppf l; | Ttyp_constr (li, _, l) -> line i ppf "Ttyp_constr %a\n" fmt_path li; list i core_type ppf l; | Ttyp_variant (l, closed, low) -> line i ppf "Ttyp_variant closed=%a\n" fmt_closed_flag closed; list i label_x_bool_x_core_type_list ppf l; option i (fun i -> list i string) ppf low | Ttyp_object (l, c) -> line i ppf "Ttyp_object %a\n" fmt_closed_flag c; let i = i + 1 in List.iter (fun {of_desc; of_attributes; _} -> match of_desc with | OTtag (s, t) -> line i ppf "method %s\n" s.txt; attributes i ppf of_attributes; core_type (i + 1) ppf t | OTinherit ct -> line i ppf "OTinherit\n"; core_type (i + 1) ppf ct ) l | Ttyp_class (li, _, l) -> line i ppf "Ttyp_class %a\n" fmt_path li; list i core_type ppf l; | Ttyp_alias (ct, s) -> line i ppf "Ttyp_alias \"%s\"\n" s; core_type i ppf ct; | Ttyp_poly (sl, ct) -> line i ppf "Ttyp_poly%a\n" (fun ppf -> List.iter (fun x -> fprintf ppf " '%s" x)) sl; core_type i ppf ct; | Ttyp_package { pack_path = s; pack_fields = l } -> line i ppf "Ttyp_package %a\n" fmt_path s; list i package_with ppf l; and package_with i ppf (s, t) = line i ppf "with type %a\n" fmt_longident s; core_type i ppf t and pattern : type k . _ -> _ -> k general_pattern -> unit = fun i ppf x -> line i ppf "pattern %a\n" fmt_location x.pat_loc; attributes i ppf x.pat_attributes; let i = i+1 in begin match x.pat_extra with | [] -> () | extra -> line i ppf "extra\n"; List.iter (pattern_extra (i+1) ppf) extra; end; match x.pat_desc with | Tpat_any -> line i ppf "Tpat_any\n"; | Tpat_var (s,_) -> line i ppf "Tpat_var \"%a\"\n" fmt_ident s; | Tpat_alias (p, s,_) -> line i ppf "Tpat_alias \"%a\"\n" fmt_ident s; pattern i ppf p; | Tpat_constant (c) -> line i ppf "Tpat_constant %a\n" fmt_constant c; | Tpat_tuple (l) -> line i ppf "Tpat_tuple\n"; list i pattern ppf l; | Tpat_construct (li, _, po, vto) -> line i ppf "Tpat_construct %a\n" fmt_longident li; list i pattern ppf po; option i (fun i ppf (vl,ct) -> let names = List.map (fun {txt} -> "\""^Ident.name txt^"\"") vl in line i ppf "[%s]\n" (String.concat "; " names); core_type i ppf ct) ppf vto | Tpat_variant (l, po, _) -> line i ppf "Tpat_variant \"%s\"\n" l; option i pattern ppf po; | Tpat_record (l, _c) -> line i ppf "Tpat_record\n"; list i longident_x_pattern ppf l; | Tpat_array (l) -> line i ppf "Tpat_array\n"; list i pattern ppf l; | Tpat_lazy p -> line i ppf "Tpat_lazy\n"; pattern i ppf p; | Tpat_exception p -> line i ppf "Tpat_exception\n"; pattern i ppf p; | Tpat_value p -> line i ppf "Tpat_value\n"; pattern i ppf (p :> pattern); | Tpat_or (p1, p2, _) -> line i ppf "Tpat_or\n"; pattern i ppf p1; pattern i ppf p2; and pattern_extra i ppf (extra_pat, _, attrs) = match extra_pat with | Tpat_unpack -> line i ppf "Tpat_extra_unpack\n"; attributes i ppf attrs; | Tpat_constraint cty -> line i ppf "Tpat_extra_constraint\n"; attributes i ppf attrs; core_type i ppf cty; | Tpat_type (id, _) -> line i ppf "Tpat_extra_type %a\n" fmt_path id; attributes i ppf attrs; | Tpat_open (id,_,_) -> line i ppf "Tpat_extra_open %a\n" fmt_path id; attributes i ppf attrs; and expression_extra i ppf (x,_,attrs) = match x with | Texp_constraint ct -> line i ppf "Texp_constraint\n"; attributes i ppf attrs; core_type i ppf ct; | Texp_coerce (cto1, cto2) -> line i ppf "Texp_coerce\n"; attributes i ppf attrs; option i core_type ppf cto1; core_type i ppf cto2; | Texp_poly cto -> line i ppf "Texp_poly\n"; attributes i ppf attrs; option i core_type ppf cto; | Texp_newtype s -> line i ppf "Texp_newtype \"%s\"\n" s; attributes i ppf attrs; and expression i ppf x = line i ppf "expression %a\n" fmt_location x.exp_loc; attributes i ppf x.exp_attributes; let i = i+1 in begin match x.exp_extra with | [] -> () | extra -> line i ppf "extra\n"; List.iter (expression_extra (i+1) ppf) extra; end; match x.exp_desc with | Texp_ident (li,_,_) -> line i ppf "Texp_ident %a\n" fmt_path li; | Texp_instvar (_, li,_) -> line i ppf "Texp_instvar %a\n" fmt_path li; | Texp_constant (c) -> line i ppf "Texp_constant %a\n" fmt_constant c; | Texp_let (rf, l, e) -> line i ppf "Texp_let %a\n" fmt_rec_flag rf; list i value_binding ppf l; expression i ppf e; | Texp_function { arg_label = p; param ; cases; partial = _; } -> line i ppf "Texp_function\n"; line i ppf "%a" Ident.print param; arg_label i ppf p; list i case ppf cases; | Texp_apply (e, l) -> line i ppf "Texp_apply\n"; expression i ppf e; list i label_x_expression ppf l; | Texp_match (e, l, _partial) -> line i ppf "Texp_match\n"; expression i ppf e; list i case ppf l; | Texp_try (e, l) -> line i ppf "Texp_try\n"; expression i ppf e; list i case ppf l; | Texp_tuple (l) -> line i ppf "Texp_tuple\n"; list i expression ppf l; | Texp_construct (li, _, eo) -> line i ppf "Texp_construct %a\n" fmt_longident li; list i expression ppf eo; | Texp_variant (l, eo) -> line i ppf "Texp_variant \"%s\"\n" l; option i expression ppf eo; | Texp_record { fields; representation; extended_expression } -> line i ppf "Texp_record\n"; let i = i+1 in line i ppf "fields =\n"; array (i+1) record_field ppf fields; line i ppf "representation =\n"; record_representation (i+1) ppf representation; line i ppf "extended_expression =\n"; option (i+1) expression ppf extended_expression; | Texp_field (e, li, _) -> line i ppf "Texp_field\n"; expression i ppf e; longident i ppf li; | Texp_setfield (e1, li, _, e2) -> line i ppf "Texp_setfield\n"; expression i ppf e1; longident i ppf li; expression i ppf e2; | Texp_array (l) -> line i ppf "Texp_array\n"; list i expression ppf l; | Texp_ifthenelse (e1, e2, eo) -> line i ppf "Texp_ifthenelse\n"; expression i ppf e1; expression i ppf e2; option i expression ppf eo; | Texp_sequence (e1, e2) -> line i ppf "Texp_sequence\n"; expression i ppf e1; expression i ppf e2; | Texp_while (e1, e2) -> line i ppf "Texp_while\n"; expression i ppf e1; expression i ppf e2; | Texp_for (s, _, e1, e2, df, e3) -> line i ppf "Texp_for \"%a\" %a\n" fmt_ident s fmt_direction_flag df; expression i ppf e1; expression i ppf e2; expression i ppf e3; | Texp_send (e, Tmeth_name s) -> line i ppf "Texp_send \"%s\"\n" s; expression i ppf e | Texp_send (e, Tmeth_val s) -> line i ppf "Texp_send \"%a\"\n" fmt_ident s; expression i ppf e | Texp_send (e, Tmeth_ancestor(s, _)) -> line i ppf "Texp_send \"%a\"\n" fmt_ident s; expression i ppf e | Texp_new (li, _, _) -> line i ppf "Texp_new %a\n" fmt_path li; | Texp_setinstvar (_, s, _, e) -> line i ppf "Texp_setinstvar %a\n" fmt_path s; expression i ppf e; | Texp_override (_, l) -> line i ppf "Texp_override\n"; list i string_x_expression ppf l; | Texp_letmodule (s, _, _, me, e) -> line i ppf "Texp_letmodule \"%a\"\n" fmt_modname s; module_expr i ppf me; expression i ppf e; | Texp_letexception (cd, e) -> line i ppf "Texp_letexception\n"; extension_constructor i ppf cd; expression i ppf e; | Texp_assert (e) -> line i ppf "Texp_assert"; expression i ppf e; | Texp_lazy (e) -> line i ppf "Texp_lazy"; expression i ppf e; | Texp_object (s, _) -> line i ppf "Texp_object"; class_structure i ppf s | Texp_pack me -> line i ppf "Texp_pack"; module_expr i ppf me | Texp_letop {let_; ands; param = _; body; partial = _} -> line i ppf "Texp_letop"; binding_op (i+1) ppf let_; list (i+1) binding_op ppf ands; case i ppf body | Texp_unreachable -> line i ppf "Texp_unreachable" | Texp_extension_constructor (li, _) -> line i ppf "Texp_extension_constructor %a" fmt_longident li | Texp_open (o, e) -> line i ppf "Texp_open %a\n" fmt_override_flag o.open_override; module_expr i ppf o.open_expr; attributes i ppf o.open_attributes; expression i ppf e; and value_description i ppf x = line i ppf "value_description %a %a\n" fmt_ident x.val_id fmt_location x.val_loc; attributes i ppf x.val_attributes; core_type (i+1) ppf x.val_desc; list (i+1) string ppf x.val_prim; and binding_op i ppf x = line i ppf "binding_op %a %a\n" fmt_path x.bop_op_path fmt_location x.bop_loc; expression i ppf x.bop_exp and type_parameter i ppf (x, _variance) = core_type i ppf x and type_declaration i ppf x = line i ppf "type_declaration %a %a\n" fmt_ident x.typ_id fmt_location x.typ_loc; attributes i ppf x.typ_attributes; let i = i+1 in line i ppf "ptype_params =\n"; list (i+1) type_parameter ppf x.typ_params; line i ppf "ptype_cstrs =\n"; list (i+1) core_type_x_core_type_x_location ppf x.typ_cstrs; line i ppf "ptype_kind =\n"; type_kind (i+1) ppf x.typ_kind; line i ppf "ptype_private = %a\n" fmt_private_flag x.typ_private; line i ppf "ptype_manifest =\n"; option (i+1) core_type ppf x.typ_manifest; and type_kind i ppf x = match x with | Ttype_abstract -> line i ppf "Ttype_abstract\n" | Ttype_variant l -> line i ppf "Ttype_variant\n"; list (i+1) constructor_decl ppf l; | Ttype_record l -> line i ppf "Ttype_record\n"; list (i+1) label_decl ppf l; | Ttype_open -> line i ppf "Ttype_open\n" and type_extension i ppf x = line i ppf "type_extension\n"; attributes i ppf x.tyext_attributes; let i = i+1 in line i ppf "ptyext_path = %a\n" fmt_path x.tyext_path; line i ppf "ptyext_params =\n"; list (i+1) type_parameter ppf x.tyext_params; line i ppf "ptyext_constructors =\n"; list (i+1) extension_constructor ppf x.tyext_constructors; line i ppf "ptyext_private = %a\n" fmt_private_flag x.tyext_private; and type_exception i ppf x = line i ppf "type_exception\n"; attributes i ppf x.tyexn_attributes; let i = i+1 in line i ppf "ptyext_constructor =\n"; let i = i+1 in extension_constructor i ppf x.tyexn_constructor and extension_constructor i ppf x = line i ppf "extension_constructor %a\n" fmt_location x.ext_loc; attributes i ppf x.ext_attributes; let i = i + 1 in line i ppf "pext_name = \"%a\"\n" fmt_ident x.ext_id; line i ppf "pext_kind =\n"; extension_constructor_kind (i + 1) ppf x.ext_kind; and extension_constructor_kind i ppf x = match x with Text_decl(v, a, r) -> line i ppf "Text_decl\n"; if v <> [] then line (i+1) ppf "vars%a\n" typevars v; constructor_arguments (i+1) ppf a; option (i+1) core_type ppf r; | Text_rebind(p, _) -> line i ppf "Text_rebind\n"; line (i+1) ppf "%a\n" fmt_path p; and class_type i ppf x = line i ppf "class_type %a\n" fmt_location x.cltyp_loc; attributes i ppf x.cltyp_attributes; let i = i+1 in match x.cltyp_desc with | Tcty_constr (li, _, l) -> line i ppf "Tcty_constr %a\n" fmt_path li; list i core_type ppf l; | Tcty_signature (cs) -> line i ppf "Tcty_signature\n"; class_signature i ppf cs; | Tcty_arrow (l, co, cl) -> line i ppf "Tcty_arrow\n"; arg_label i ppf l; core_type i ppf co; class_type i ppf cl; | Tcty_open (o, e) -> line i ppf "Tcty_open %a %a\n" fmt_override_flag o.open_override fmt_path (fst o.open_expr); class_type i ppf e and class_signature i ppf { csig_self = ct; csig_fields = l } = line i ppf "class_signature\n"; core_type (i+1) ppf ct; list (i+1) class_type_field ppf l; and class_type_field i ppf x = line i ppf "class_type_field %a\n" fmt_location x.ctf_loc; let i = i+1 in attributes i ppf x.ctf_attributes; match x.ctf_desc with | Tctf_inherit (ct) -> line i ppf "Tctf_inherit\n"; class_type i ppf ct; | Tctf_val (s, mf, vf, ct) -> line i ppf "Tctf_val \"%s\" %a %a\n" s fmt_mutable_flag mf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Tctf_method (s, pf, vf, ct) -> line i ppf "Tctf_method \"%s\" %a %a\n" s fmt_private_flag pf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Tctf_constraint (ct1, ct2) -> line i ppf "Tctf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Tctf_attribute a -> attribute i ppf "Tctf_attribute" a and class_description i ppf x = line i ppf "class_description %a\n" fmt_location x.ci_loc; attributes i ppf x.ci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.ci_params; line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.ci_expr; and class_type_declaration i ppf x = line i ppf "class_type_declaration %a\n" fmt_location x.ci_loc; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.ci_params; line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.ci_expr; and class_expr i ppf x = line i ppf "class_expr %a\n" fmt_location x.cl_loc; attributes i ppf x.cl_attributes; let i = i+1 in match x.cl_desc with | Tcl_ident (li, _, l) -> line i ppf "Tcl_ident %a\n" fmt_path li; list i core_type ppf l; | Tcl_structure (cs) -> line i ppf "Tcl_structure\n"; class_structure i ppf cs; | Tcl_fun (l, p, _, ce, _) -> line i ppf "Tcl_fun\n"; arg_label i ppf l; pattern i ppf p; class_expr i ppf ce | Tcl_apply (ce, l) -> line i ppf "Tcl_apply\n"; class_expr i ppf ce; list i label_x_expression ppf l; | Tcl_let (rf, l1, l2, ce) -> line i ppf "Tcl_let %a\n" fmt_rec_flag rf; list i value_binding ppf l1; list i ident_x_expression_def ppf l2; class_expr i ppf ce; | Tcl_constraint (ce, Some ct, _, _, _) -> line i ppf "Tcl_constraint\n"; class_expr i ppf ce; class_type i ppf ct | Tcl_constraint (ce, None, _, _, _) -> class_expr i ppf ce | Tcl_open (o, e) -> line i ppf "Tcl_open %a %a\n" fmt_override_flag o.open_override fmt_path (fst o.open_expr); class_expr i ppf e and class_structure i ppf { cstr_self = p; cstr_fields = l } = line i ppf "class_structure\n"; pattern (i+1) ppf p; list (i+1) class_field ppf l; and class_field i ppf x = line i ppf "class_field %a\n" fmt_location x.cf_loc; let i = i + 1 in attributes i ppf x.cf_attributes; match x.cf_desc with | Tcf_inherit (ovf, ce, so, _, _) -> line i ppf "Tcf_inherit %a\n" fmt_override_flag ovf; class_expr (i+1) ppf ce; option (i+1) string ppf so; | Tcf_val (s, mf, _, k, _) -> line i ppf "Tcf_val \"%s\" %a\n" s.txt fmt_mutable_flag mf; class_field_kind (i+1) ppf k | Tcf_method (s, pf, k) -> line i ppf "Tcf_method \"%s\" %a\n" s.txt fmt_private_flag pf; class_field_kind (i+1) ppf k | Tcf_constraint (ct1, ct2) -> line i ppf "Tcf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Tcf_initializer (e) -> line i ppf "Tcf_initializer\n"; expression (i+1) ppf e; | Tcf_attribute a -> attribute i ppf "Tcf_attribute" a and class_field_kind i ppf = function | Tcfk_concrete (o, e) -> line i ppf "Concrete %a\n" fmt_override_flag o; expression i ppf e | Tcfk_virtual t -> line i ppf "Virtual\n"; core_type i ppf t and class_declaration i ppf x = line i ppf "class_declaration %a\n" fmt_location x.ci_loc; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.ci_params; line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt; line i ppf "pci_expr =\n"; class_expr (i+1) ppf x.ci_expr; and module_type i ppf x = line i ppf "module_type %a\n" fmt_location x.mty_loc; attributes i ppf x.mty_attributes; let i = i+1 in match x.mty_desc with | Tmty_ident (li,_) -> line i ppf "Tmty_ident %a\n" fmt_path li; | Tmty_alias (li,_) -> line i ppf "Tmty_alias %a\n" fmt_path li; | Tmty_signature (s) -> line i ppf "Tmty_signature\n"; signature i ppf s; | Tmty_functor (Unit, mt2) -> line i ppf "Tmty_functor ()\n"; module_type i ppf mt2; | Tmty_functor (Named (s, _, mt1), mt2) -> line i ppf "Tmty_functor \"%a\"\n" fmt_modname s; module_type i ppf mt1; module_type i ppf mt2; | Tmty_with (mt, l) -> line i ppf "Tmty_with\n"; module_type i ppf mt; list i longident_x_with_constraint ppf l; | Tmty_typeof m -> line i ppf "Tmty_typeof\n"; module_expr i ppf m; and signature i ppf x = list i signature_item ppf x.sig_items and signature_item i ppf x = line i ppf "signature_item %a\n" fmt_location x.sig_loc; let i = i+1 in match x.sig_desc with | Tsig_value vd -> line i ppf "Tsig_value\n"; value_description i ppf vd; | Tsig_type (rf, l) -> line i ppf "Tsig_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Tsig_typesubst l -> line i ppf "Tsig_typesubst\n"; list i type_declaration ppf l; | Tsig_typext e -> line i ppf "Tsig_typext\n"; type_extension i ppf e; | Tsig_exception ext -> line i ppf "Tsig_exception\n"; type_exception i ppf ext | Tsig_module md -> line i ppf "Tsig_module \"%a\"\n" fmt_modname md.md_id; attributes i ppf md.md_attributes; module_type i ppf md.md_type | Tsig_modsubst ms -> line i ppf "Tsig_modsubst \"%a\" = %a\n" fmt_ident ms.ms_id fmt_path ms.ms_manifest; attributes i ppf ms.ms_attributes; | Tsig_recmodule decls -> line i ppf "Tsig_recmodule\n"; list i module_declaration ppf decls; | Tsig_modtype x -> line i ppf "Tsig_modtype \"%a\"\n" fmt_ident x.mtd_id; attributes i ppf x.mtd_attributes; modtype_declaration i ppf x.mtd_type | Tsig_modtypesubst x -> line i ppf "Tsig_modtypesubst \"%a\"\n" fmt_ident x.mtd_id; attributes i ppf x.mtd_attributes; modtype_declaration i ppf x.mtd_type | Tsig_open od -> line i ppf "Tsig_open %a %a\n" fmt_override_flag od.open_override fmt_path (fst od.open_expr); attributes i ppf od.open_attributes | Tsig_include incl -> line i ppf "Tsig_include\n"; attributes i ppf incl.incl_attributes; module_type i ppf incl.incl_mod | Tsig_class (l) -> line i ppf "Tsig_class\n"; list i class_description ppf l; | Tsig_class_type (l) -> line i ppf "Tsig_class_type\n"; list i class_type_declaration ppf l; | Tsig_attribute a -> attribute i ppf "Tsig_attribute" a and module_declaration i ppf md = line i ppf "%a" fmt_modname md.md_id; attributes i ppf md.md_attributes; module_type (i+1) ppf md.md_type; and module_binding i ppf x = line i ppf "%a\n" fmt_modname x.mb_id; attributes i ppf x.mb_attributes; module_expr (i+1) ppf x.mb_expr and modtype_declaration i ppf = function | None -> line i ppf "#abstract" | Some mt -> module_type (i + 1) ppf mt and with_constraint i ppf x = match x with | Twith_type (td) -> line i ppf "Twith_type\n"; type_declaration (i+1) ppf td; | Twith_typesubst (td) -> line i ppf "Twith_typesubst\n"; type_declaration (i+1) ppf td; | Twith_module (li,_) -> line i ppf "Twith_module %a\n" fmt_path li; | Twith_modsubst (li,_) -> line i ppf "Twith_modsubst %a\n" fmt_path li; | Twith_modtype mty -> line i ppf "Twith_modtype\n"; module_type (i+1) ppf mty | Twith_modtypesubst mty -> line i ppf "Twith_modtype\n"; module_type (i+1) ppf mty and module_expr i ppf x = line i ppf "module_expr %a\n" fmt_location x.mod_loc; attributes i ppf x.mod_attributes; let i = i+1 in match x.mod_desc with | Tmod_ident (li,_) -> line i ppf "Tmod_ident %a\n" fmt_path li; | Tmod_structure (s) -> line i ppf "Tmod_structure\n"; structure i ppf s; | Tmod_functor (Unit, me) -> line i ppf "Tmod_functor ()\n"; module_expr i ppf me; | Tmod_functor (Named (s, _, mt), me) -> line i ppf "Tmod_functor \"%a\"\n" fmt_modname s; module_type i ppf mt; module_expr i ppf me; | Tmod_apply (me1, me2, _) -> line i ppf "Tmod_apply\n"; module_expr i ppf me1; module_expr i ppf me2; | Tmod_constraint (me, _, Tmodtype_explicit mt, _) -> line i ppf "Tmod_constraint\n"; module_expr i ppf me; module_type i ppf mt; | Tmod_constraint (me, _, Tmodtype_implicit, _) -> module_expr i ppf me | Tmod_unpack (e, _) -> line i ppf "Tmod_unpack\n"; expression i ppf e; and structure i ppf x = list i structure_item ppf x.str_items and structure_item i ppf x = line i ppf "structure_item %a\n" fmt_location x.str_loc; let i = i+1 in match x.str_desc with | Tstr_eval (e, attrs) -> line i ppf "Tstr_eval\n"; attributes i ppf attrs; expression i ppf e; | Tstr_value (rf, l) -> line i ppf "Tstr_value %a\n" fmt_rec_flag rf; list i value_binding ppf l; | Tstr_primitive vd -> line i ppf "Tstr_primitive\n"; value_description i ppf vd; | Tstr_type (rf, l) -> line i ppf "Tstr_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Tstr_typext te -> line i ppf "Tstr_typext\n"; type_extension i ppf te | Tstr_exception ext -> line i ppf "Tstr_exception\n"; type_exception i ppf ext; | Tstr_module x -> line i ppf "Tstr_module\n"; module_binding i ppf x | Tstr_recmodule bindings -> line i ppf "Tstr_recmodule\n"; list i module_binding ppf bindings | Tstr_modtype x -> line i ppf "Tstr_modtype \"%a\"\n" fmt_ident x.mtd_id; attributes i ppf x.mtd_attributes; modtype_declaration i ppf x.mtd_type | Tstr_open od -> line i ppf "Tstr_open %a\n" fmt_override_flag od.open_override; module_expr i ppf od.open_expr; attributes i ppf od.open_attributes | Tstr_class (l) -> line i ppf "Tstr_class\n"; list i class_declaration ppf (List.map (fun (cl, _) -> cl) l); | Tstr_class_type (l) -> line i ppf "Tstr_class_type\n"; list i class_type_declaration ppf (List.map (fun (_, _, cl) -> cl) l); | Tstr_include incl -> line i ppf "Tstr_include"; attributes i ppf incl.incl_attributes; module_expr i ppf incl.incl_mod; | Tstr_attribute a -> attribute i ppf "Tstr_attribute" a and longident_x_with_constraint i ppf (li, _, wc) = line i ppf "%a\n" fmt_path li; with_constraint (i+1) ppf wc; and core_type_x_core_type_x_location i ppf (ct1, ct2, l) = line i ppf "<constraint> %a\n" fmt_location l; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; and constructor_decl i ppf {cd_id; cd_name = _; cd_vars; cd_args; cd_res; cd_loc; cd_attributes} = line i ppf "%a\n" fmt_location cd_loc; line (i+1) ppf "%a\n" fmt_ident cd_id; if cd_vars <> [] then line (i+1) ppf "cd_vars =%a\n" typevars cd_vars; attributes i ppf cd_attributes; constructor_arguments (i+1) ppf cd_args; option (i+1) core_type ppf cd_res and constructor_arguments i ppf = function | Cstr_tuple l -> list i core_type ppf l | Cstr_record l -> list i label_decl ppf l and label_decl i ppf {ld_id; ld_name = _; ld_mutable; ld_type; ld_loc; ld_attributes} = line i ppf "%a\n" fmt_location ld_loc; attributes i ppf ld_attributes; line (i+1) ppf "%a\n" fmt_mutable_flag ld_mutable; line (i+1) ppf "%a" fmt_ident ld_id; core_type (i+1) ppf ld_type and longident_x_pattern i ppf (li, _, p) = line i ppf "%a\n" fmt_longident li; pattern (i+1) ppf p; and case : type k . _ -> _ -> k case -> unit = fun i ppf {c_lhs; c_guard; c_rhs} -> line i ppf "<case>\n"; pattern (i+1) ppf c_lhs; begin match c_guard with | None -> () | Some g -> line (i+1) ppf "<when>\n"; expression (i + 2) ppf g end; expression (i+1) ppf c_rhs; and value_binding i ppf x = line i ppf "<def>\n"; attributes (i+1) ppf x.vb_attributes; pattern (i+1) ppf x.vb_pat; expression (i+1) ppf x.vb_expr and string_x_expression i ppf (s, _, e) = line i ppf "<override> \"%a\"\n" fmt_ident s; expression (i+1) ppf e; and record_field i ppf = function | _, Overridden (li, e) -> line i ppf "%a\n" fmt_longident li; expression (i+1) ppf e; | _, Kept _ -> line i ppf "<kept>" and label_x_expression i ppf (l, e) = line i ppf "<arg>\n"; arg_label (i+1) ppf l; (match e with None -> () | Some e -> expression (i+1) ppf e) and ident_x_expression_def i ppf (l, e) = line i ppf "<def> \"%a\"\n" fmt_ident l; expression (i+1) ppf e; and label_x_bool_x_core_type_list i ppf x = match x.rf_desc with | Ttag (l, b, ctl) -> line i ppf "Ttag \"%s\" %s\n" l.txt (string_of_bool b); attributes (i+1) ppf x.rf_attributes; list (i+1) core_type ppf ctl | Tinherit (ct) -> line i ppf "Tinherit\n"; core_type (i+1) ppf ct ;; let interface ppf x = list 0 signature_item ppf x.sig_items;; let implementation ppf x = list 0 structure_item ppf x.str_items;; let implementation_with_coercion ppf Typedtree.{structure; _} = implementation ppf structure
null
https://raw.githubusercontent.com/melange-re/melange-compiler-libs/2fac95b0ea97fb676240662aeeec8c6f6495dd9c/typing/printtyped.ml
ocaml
************************************************************************ OCaml Fabrice Le Fessant, INRIA Saclay en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ ... ...
Copyright 1999 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Asttypes;; open Format;; open Lexing;; open Location;; open Typedtree;; let fmt_position f l = if l.pos_lnum = -1 then fprintf f "%s[%d]" l.pos_fname l.pos_cnum else fprintf f "%s[%d,%d+%d]" l.pos_fname l.pos_lnum l.pos_bol (l.pos_cnum - l.pos_bol) ;; let fmt_location f loc = if not !Clflags.locations then () else begin fprintf f "(%a..%a)" fmt_position loc.loc_start fmt_position loc.loc_end; if loc.loc_ghost then fprintf f " ghost"; end ;; let rec fmt_longident_aux f x = match x with | Longident.Lident (s) -> fprintf f "%s" s; | Longident.Ldot (y, s) -> fprintf f "%a.%s" fmt_longident_aux y s; | Longident.Lapply (y, z) -> fprintf f "%a(%a)" fmt_longident_aux y fmt_longident_aux z; ;; let fmt_longident f x = fprintf f "\"%a\"" fmt_longident_aux x.txt;; let fmt_ident = Ident.print let fmt_modname f = function | None -> fprintf f "_"; | Some id -> Ident.print f id let rec fmt_path_aux f x = match x with | Path.Pident (s) -> fprintf f "%a" fmt_ident s; | Path.Pdot (y, s) -> fprintf f "%a.%s" fmt_path_aux y s; | Path.Papply (y, z) -> fprintf f "%a(%a)" fmt_path_aux y fmt_path_aux z; ;; let fmt_path f x = fprintf f "\"%a\"" fmt_path_aux x;; let fmt_constant f x = match x with | Const_int (i) -> fprintf f "Const_int %d" i; | Const_char (c) -> fprintf f "Const_char %02x" (Char.code c); | Const_string (s, strloc, None) -> fprintf f "Const_string(%S,%a,None)" s fmt_location strloc; | Const_string (s, strloc, Some delim) -> fprintf f "Const_string (%S,%a,Some %S)" s fmt_location strloc delim; | Const_float (s) -> fprintf f "Const_float %s" s; | Const_int32 (i) -> fprintf f "Const_int32 %ld" i; | Const_int64 (i) -> fprintf f "Const_int64 %Ld" i; | Const_nativeint (i) -> fprintf f "Const_nativeint %nd" i; ;; let fmt_mutable_flag f x = match x with | Immutable -> fprintf f "Immutable"; | Mutable -> fprintf f "Mutable"; ;; let fmt_virtual_flag f x = match x with | Virtual -> fprintf f "Virtual"; | Concrete -> fprintf f "Concrete"; ;; let fmt_override_flag f x = match x with | Override -> fprintf f "Override"; | Fresh -> fprintf f "Fresh"; ;; let fmt_closed_flag f x = match x with | Closed -> fprintf f "Closed" | Open -> fprintf f "Open" let fmt_rec_flag f x = match x with | Nonrecursive -> fprintf f "Nonrec"; | Recursive -> fprintf f "Rec"; ;; let fmt_direction_flag f x = match x with | Upto -> fprintf f "Up"; | Downto -> fprintf f "Down"; ;; let fmt_private_flag f x = match x with | Public -> fprintf f "Public"; | Private -> fprintf f "Private"; ;; fprintf f "%s" (String.make (2*i) ' '); ;; let list i f ppf l = match l with | [] -> line i ppf "[]\n"; | _ :: _ -> line i ppf "[\n"; List.iter (f (i+1) ppf) l; line i ppf "]\n"; ;; let array i f ppf a = if Array.length a = 0 then line i ppf "[]\n" else begin line i ppf "[\n"; Array.iter (f (i+1) ppf) a; line i ppf "]\n" end ;; let option i f ppf x = match x with | None -> line i ppf "None\n"; | Some x -> line i ppf "Some\n"; f (i+1) ppf x; ;; let longident i ppf li = line i ppf "%a\n" fmt_longident li;; let string i ppf s = line i ppf "\"%s\"\n" s;; let arg_label i ppf = function | Nolabel -> line i ppf "Nolabel\n" | Optional s -> line i ppf "Optional \"%s\"\n" s | Labelled s -> line i ppf "Labelled \"%s\"\n" s ;; let typevars ppf vs = List.iter (fun x -> fprintf ppf " %a" Pprintast.tyvar x.txt) vs ;; let record_representation i ppf = let open Types in function | Record_regular -> line i ppf "Record_regular\n" | Record_float -> line i ppf "Record_float\n" | Record_unboxed b -> line i ppf "Record_unboxed %b\n" b | Record_inlined {tag = i} -> line i ppf "Record_inlined %d\n" i | Record_extension p -> line i ppf "Record_extension %a\n" fmt_path p let attribute i ppf k a = line i ppf "%s \"%s\"\n" k a.Parsetree.attr_name.txt; Printast.payload i ppf a.Parsetree.attr_payload let attributes i ppf l = let i = i + 1 in List.iter (fun a -> line i ppf "attribute \"%s\"\n" a.Parsetree.attr_name.txt; Printast.payload (i + 1) ppf a.Parsetree.attr_payload ) l let rec core_type i ppf x = line i ppf "core_type %a\n" fmt_location x.ctyp_loc; attributes i ppf x.ctyp_attributes; let i = i+1 in match x.ctyp_desc with | Ttyp_any -> line i ppf "Ttyp_any\n"; | Ttyp_var (s) -> line i ppf "Ttyp_var %s\n" s; | Ttyp_arrow (l, ct1, ct2) -> line i ppf "Ttyp_arrow\n"; arg_label i ppf l; core_type i ppf ct1; core_type i ppf ct2; | Ttyp_tuple l -> line i ppf "Ttyp_tuple\n"; list i core_type ppf l; | Ttyp_constr (li, _, l) -> line i ppf "Ttyp_constr %a\n" fmt_path li; list i core_type ppf l; | Ttyp_variant (l, closed, low) -> line i ppf "Ttyp_variant closed=%a\n" fmt_closed_flag closed; list i label_x_bool_x_core_type_list ppf l; option i (fun i -> list i string) ppf low | Ttyp_object (l, c) -> line i ppf "Ttyp_object %a\n" fmt_closed_flag c; let i = i + 1 in List.iter (fun {of_desc; of_attributes; _} -> match of_desc with | OTtag (s, t) -> line i ppf "method %s\n" s.txt; attributes i ppf of_attributes; core_type (i + 1) ppf t | OTinherit ct -> line i ppf "OTinherit\n"; core_type (i + 1) ppf ct ) l | Ttyp_class (li, _, l) -> line i ppf "Ttyp_class %a\n" fmt_path li; list i core_type ppf l; | Ttyp_alias (ct, s) -> line i ppf "Ttyp_alias \"%s\"\n" s; core_type i ppf ct; | Ttyp_poly (sl, ct) -> line i ppf "Ttyp_poly%a\n" (fun ppf -> List.iter (fun x -> fprintf ppf " '%s" x)) sl; core_type i ppf ct; | Ttyp_package { pack_path = s; pack_fields = l } -> line i ppf "Ttyp_package %a\n" fmt_path s; list i package_with ppf l; and package_with i ppf (s, t) = line i ppf "with type %a\n" fmt_longident s; core_type i ppf t and pattern : type k . _ -> _ -> k general_pattern -> unit = fun i ppf x -> line i ppf "pattern %a\n" fmt_location x.pat_loc; attributes i ppf x.pat_attributes; let i = i+1 in begin match x.pat_extra with | [] -> () | extra -> line i ppf "extra\n"; List.iter (pattern_extra (i+1) ppf) extra; end; match x.pat_desc with | Tpat_any -> line i ppf "Tpat_any\n"; | Tpat_var (s,_) -> line i ppf "Tpat_var \"%a\"\n" fmt_ident s; | Tpat_alias (p, s,_) -> line i ppf "Tpat_alias \"%a\"\n" fmt_ident s; pattern i ppf p; | Tpat_constant (c) -> line i ppf "Tpat_constant %a\n" fmt_constant c; | Tpat_tuple (l) -> line i ppf "Tpat_tuple\n"; list i pattern ppf l; | Tpat_construct (li, _, po, vto) -> line i ppf "Tpat_construct %a\n" fmt_longident li; list i pattern ppf po; option i (fun i ppf (vl,ct) -> let names = List.map (fun {txt} -> "\""^Ident.name txt^"\"") vl in line i ppf "[%s]\n" (String.concat "; " names); core_type i ppf ct) ppf vto | Tpat_variant (l, po, _) -> line i ppf "Tpat_variant \"%s\"\n" l; option i pattern ppf po; | Tpat_record (l, _c) -> line i ppf "Tpat_record\n"; list i longident_x_pattern ppf l; | Tpat_array (l) -> line i ppf "Tpat_array\n"; list i pattern ppf l; | Tpat_lazy p -> line i ppf "Tpat_lazy\n"; pattern i ppf p; | Tpat_exception p -> line i ppf "Tpat_exception\n"; pattern i ppf p; | Tpat_value p -> line i ppf "Tpat_value\n"; pattern i ppf (p :> pattern); | Tpat_or (p1, p2, _) -> line i ppf "Tpat_or\n"; pattern i ppf p1; pattern i ppf p2; and pattern_extra i ppf (extra_pat, _, attrs) = match extra_pat with | Tpat_unpack -> line i ppf "Tpat_extra_unpack\n"; attributes i ppf attrs; | Tpat_constraint cty -> line i ppf "Tpat_extra_constraint\n"; attributes i ppf attrs; core_type i ppf cty; | Tpat_type (id, _) -> line i ppf "Tpat_extra_type %a\n" fmt_path id; attributes i ppf attrs; | Tpat_open (id,_,_) -> line i ppf "Tpat_extra_open %a\n" fmt_path id; attributes i ppf attrs; and expression_extra i ppf (x,_,attrs) = match x with | Texp_constraint ct -> line i ppf "Texp_constraint\n"; attributes i ppf attrs; core_type i ppf ct; | Texp_coerce (cto1, cto2) -> line i ppf "Texp_coerce\n"; attributes i ppf attrs; option i core_type ppf cto1; core_type i ppf cto2; | Texp_poly cto -> line i ppf "Texp_poly\n"; attributes i ppf attrs; option i core_type ppf cto; | Texp_newtype s -> line i ppf "Texp_newtype \"%s\"\n" s; attributes i ppf attrs; and expression i ppf x = line i ppf "expression %a\n" fmt_location x.exp_loc; attributes i ppf x.exp_attributes; let i = i+1 in begin match x.exp_extra with | [] -> () | extra -> line i ppf "extra\n"; List.iter (expression_extra (i+1) ppf) extra; end; match x.exp_desc with | Texp_ident (li,_,_) -> line i ppf "Texp_ident %a\n" fmt_path li; | Texp_instvar (_, li,_) -> line i ppf "Texp_instvar %a\n" fmt_path li; | Texp_constant (c) -> line i ppf "Texp_constant %a\n" fmt_constant c; | Texp_let (rf, l, e) -> line i ppf "Texp_let %a\n" fmt_rec_flag rf; list i value_binding ppf l; expression i ppf e; | Texp_function { arg_label = p; param ; cases; partial = _; } -> line i ppf "Texp_function\n"; line i ppf "%a" Ident.print param; arg_label i ppf p; list i case ppf cases; | Texp_apply (e, l) -> line i ppf "Texp_apply\n"; expression i ppf e; list i label_x_expression ppf l; | Texp_match (e, l, _partial) -> line i ppf "Texp_match\n"; expression i ppf e; list i case ppf l; | Texp_try (e, l) -> line i ppf "Texp_try\n"; expression i ppf e; list i case ppf l; | Texp_tuple (l) -> line i ppf "Texp_tuple\n"; list i expression ppf l; | Texp_construct (li, _, eo) -> line i ppf "Texp_construct %a\n" fmt_longident li; list i expression ppf eo; | Texp_variant (l, eo) -> line i ppf "Texp_variant \"%s\"\n" l; option i expression ppf eo; | Texp_record { fields; representation; extended_expression } -> line i ppf "Texp_record\n"; let i = i+1 in line i ppf "fields =\n"; array (i+1) record_field ppf fields; line i ppf "representation =\n"; record_representation (i+1) ppf representation; line i ppf "extended_expression =\n"; option (i+1) expression ppf extended_expression; | Texp_field (e, li, _) -> line i ppf "Texp_field\n"; expression i ppf e; longident i ppf li; | Texp_setfield (e1, li, _, e2) -> line i ppf "Texp_setfield\n"; expression i ppf e1; longident i ppf li; expression i ppf e2; | Texp_array (l) -> line i ppf "Texp_array\n"; list i expression ppf l; | Texp_ifthenelse (e1, e2, eo) -> line i ppf "Texp_ifthenelse\n"; expression i ppf e1; expression i ppf e2; option i expression ppf eo; | Texp_sequence (e1, e2) -> line i ppf "Texp_sequence\n"; expression i ppf e1; expression i ppf e2; | Texp_while (e1, e2) -> line i ppf "Texp_while\n"; expression i ppf e1; expression i ppf e2; | Texp_for (s, _, e1, e2, df, e3) -> line i ppf "Texp_for \"%a\" %a\n" fmt_ident s fmt_direction_flag df; expression i ppf e1; expression i ppf e2; expression i ppf e3; | Texp_send (e, Tmeth_name s) -> line i ppf "Texp_send \"%s\"\n" s; expression i ppf e | Texp_send (e, Tmeth_val s) -> line i ppf "Texp_send \"%a\"\n" fmt_ident s; expression i ppf e | Texp_send (e, Tmeth_ancestor(s, _)) -> line i ppf "Texp_send \"%a\"\n" fmt_ident s; expression i ppf e | Texp_new (li, _, _) -> line i ppf "Texp_new %a\n" fmt_path li; | Texp_setinstvar (_, s, _, e) -> line i ppf "Texp_setinstvar %a\n" fmt_path s; expression i ppf e; | Texp_override (_, l) -> line i ppf "Texp_override\n"; list i string_x_expression ppf l; | Texp_letmodule (s, _, _, me, e) -> line i ppf "Texp_letmodule \"%a\"\n" fmt_modname s; module_expr i ppf me; expression i ppf e; | Texp_letexception (cd, e) -> line i ppf "Texp_letexception\n"; extension_constructor i ppf cd; expression i ppf e; | Texp_assert (e) -> line i ppf "Texp_assert"; expression i ppf e; | Texp_lazy (e) -> line i ppf "Texp_lazy"; expression i ppf e; | Texp_object (s, _) -> line i ppf "Texp_object"; class_structure i ppf s | Texp_pack me -> line i ppf "Texp_pack"; module_expr i ppf me | Texp_letop {let_; ands; param = _; body; partial = _} -> line i ppf "Texp_letop"; binding_op (i+1) ppf let_; list (i+1) binding_op ppf ands; case i ppf body | Texp_unreachable -> line i ppf "Texp_unreachable" | Texp_extension_constructor (li, _) -> line i ppf "Texp_extension_constructor %a" fmt_longident li | Texp_open (o, e) -> line i ppf "Texp_open %a\n" fmt_override_flag o.open_override; module_expr i ppf o.open_expr; attributes i ppf o.open_attributes; expression i ppf e; and value_description i ppf x = line i ppf "value_description %a %a\n" fmt_ident x.val_id fmt_location x.val_loc; attributes i ppf x.val_attributes; core_type (i+1) ppf x.val_desc; list (i+1) string ppf x.val_prim; and binding_op i ppf x = line i ppf "binding_op %a %a\n" fmt_path x.bop_op_path fmt_location x.bop_loc; expression i ppf x.bop_exp and type_parameter i ppf (x, _variance) = core_type i ppf x and type_declaration i ppf x = line i ppf "type_declaration %a %a\n" fmt_ident x.typ_id fmt_location x.typ_loc; attributes i ppf x.typ_attributes; let i = i+1 in line i ppf "ptype_params =\n"; list (i+1) type_parameter ppf x.typ_params; line i ppf "ptype_cstrs =\n"; list (i+1) core_type_x_core_type_x_location ppf x.typ_cstrs; line i ppf "ptype_kind =\n"; type_kind (i+1) ppf x.typ_kind; line i ppf "ptype_private = %a\n" fmt_private_flag x.typ_private; line i ppf "ptype_manifest =\n"; option (i+1) core_type ppf x.typ_manifest; and type_kind i ppf x = match x with | Ttype_abstract -> line i ppf "Ttype_abstract\n" | Ttype_variant l -> line i ppf "Ttype_variant\n"; list (i+1) constructor_decl ppf l; | Ttype_record l -> line i ppf "Ttype_record\n"; list (i+1) label_decl ppf l; | Ttype_open -> line i ppf "Ttype_open\n" and type_extension i ppf x = line i ppf "type_extension\n"; attributes i ppf x.tyext_attributes; let i = i+1 in line i ppf "ptyext_path = %a\n" fmt_path x.tyext_path; line i ppf "ptyext_params =\n"; list (i+1) type_parameter ppf x.tyext_params; line i ppf "ptyext_constructors =\n"; list (i+1) extension_constructor ppf x.tyext_constructors; line i ppf "ptyext_private = %a\n" fmt_private_flag x.tyext_private; and type_exception i ppf x = line i ppf "type_exception\n"; attributes i ppf x.tyexn_attributes; let i = i+1 in line i ppf "ptyext_constructor =\n"; let i = i+1 in extension_constructor i ppf x.tyexn_constructor and extension_constructor i ppf x = line i ppf "extension_constructor %a\n" fmt_location x.ext_loc; attributes i ppf x.ext_attributes; let i = i + 1 in line i ppf "pext_name = \"%a\"\n" fmt_ident x.ext_id; line i ppf "pext_kind =\n"; extension_constructor_kind (i + 1) ppf x.ext_kind; and extension_constructor_kind i ppf x = match x with Text_decl(v, a, r) -> line i ppf "Text_decl\n"; if v <> [] then line (i+1) ppf "vars%a\n" typevars v; constructor_arguments (i+1) ppf a; option (i+1) core_type ppf r; | Text_rebind(p, _) -> line i ppf "Text_rebind\n"; line (i+1) ppf "%a\n" fmt_path p; and class_type i ppf x = line i ppf "class_type %a\n" fmt_location x.cltyp_loc; attributes i ppf x.cltyp_attributes; let i = i+1 in match x.cltyp_desc with | Tcty_constr (li, _, l) -> line i ppf "Tcty_constr %a\n" fmt_path li; list i core_type ppf l; | Tcty_signature (cs) -> line i ppf "Tcty_signature\n"; class_signature i ppf cs; | Tcty_arrow (l, co, cl) -> line i ppf "Tcty_arrow\n"; arg_label i ppf l; core_type i ppf co; class_type i ppf cl; | Tcty_open (o, e) -> line i ppf "Tcty_open %a %a\n" fmt_override_flag o.open_override fmt_path (fst o.open_expr); class_type i ppf e and class_signature i ppf { csig_self = ct; csig_fields = l } = line i ppf "class_signature\n"; core_type (i+1) ppf ct; list (i+1) class_type_field ppf l; and class_type_field i ppf x = line i ppf "class_type_field %a\n" fmt_location x.ctf_loc; let i = i+1 in attributes i ppf x.ctf_attributes; match x.ctf_desc with | Tctf_inherit (ct) -> line i ppf "Tctf_inherit\n"; class_type i ppf ct; | Tctf_val (s, mf, vf, ct) -> line i ppf "Tctf_val \"%s\" %a %a\n" s fmt_mutable_flag mf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Tctf_method (s, pf, vf, ct) -> line i ppf "Tctf_method \"%s\" %a %a\n" s fmt_private_flag pf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Tctf_constraint (ct1, ct2) -> line i ppf "Tctf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Tctf_attribute a -> attribute i ppf "Tctf_attribute" a and class_description i ppf x = line i ppf "class_description %a\n" fmt_location x.ci_loc; attributes i ppf x.ci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.ci_params; line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.ci_expr; and class_type_declaration i ppf x = line i ppf "class_type_declaration %a\n" fmt_location x.ci_loc; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.ci_params; line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.ci_expr; and class_expr i ppf x = line i ppf "class_expr %a\n" fmt_location x.cl_loc; attributes i ppf x.cl_attributes; let i = i+1 in match x.cl_desc with | Tcl_ident (li, _, l) -> line i ppf "Tcl_ident %a\n" fmt_path li; list i core_type ppf l; | Tcl_structure (cs) -> line i ppf "Tcl_structure\n"; class_structure i ppf cs; | Tcl_fun (l, p, _, ce, _) -> line i ppf "Tcl_fun\n"; arg_label i ppf l; pattern i ppf p; class_expr i ppf ce | Tcl_apply (ce, l) -> line i ppf "Tcl_apply\n"; class_expr i ppf ce; list i label_x_expression ppf l; | Tcl_let (rf, l1, l2, ce) -> line i ppf "Tcl_let %a\n" fmt_rec_flag rf; list i value_binding ppf l1; list i ident_x_expression_def ppf l2; class_expr i ppf ce; | Tcl_constraint (ce, Some ct, _, _, _) -> line i ppf "Tcl_constraint\n"; class_expr i ppf ce; class_type i ppf ct | Tcl_constraint (ce, None, _, _, _) -> class_expr i ppf ce | Tcl_open (o, e) -> line i ppf "Tcl_open %a %a\n" fmt_override_flag o.open_override fmt_path (fst o.open_expr); class_expr i ppf e and class_structure i ppf { cstr_self = p; cstr_fields = l } = line i ppf "class_structure\n"; pattern (i+1) ppf p; list (i+1) class_field ppf l; and class_field i ppf x = line i ppf "class_field %a\n" fmt_location x.cf_loc; let i = i + 1 in attributes i ppf x.cf_attributes; match x.cf_desc with | Tcf_inherit (ovf, ce, so, _, _) -> line i ppf "Tcf_inherit %a\n" fmt_override_flag ovf; class_expr (i+1) ppf ce; option (i+1) string ppf so; | Tcf_val (s, mf, _, k, _) -> line i ppf "Tcf_val \"%s\" %a\n" s.txt fmt_mutable_flag mf; class_field_kind (i+1) ppf k | Tcf_method (s, pf, k) -> line i ppf "Tcf_method \"%s\" %a\n" s.txt fmt_private_flag pf; class_field_kind (i+1) ppf k | Tcf_constraint (ct1, ct2) -> line i ppf "Tcf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Tcf_initializer (e) -> line i ppf "Tcf_initializer\n"; expression (i+1) ppf e; | Tcf_attribute a -> attribute i ppf "Tcf_attribute" a and class_field_kind i ppf = function | Tcfk_concrete (o, e) -> line i ppf "Concrete %a\n" fmt_override_flag o; expression i ppf e | Tcfk_virtual t -> line i ppf "Virtual\n"; core_type i ppf t and class_declaration i ppf x = line i ppf "class_declaration %a\n" fmt_location x.ci_loc; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.ci_params; line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt; line i ppf "pci_expr =\n"; class_expr (i+1) ppf x.ci_expr; and module_type i ppf x = line i ppf "module_type %a\n" fmt_location x.mty_loc; attributes i ppf x.mty_attributes; let i = i+1 in match x.mty_desc with | Tmty_ident (li,_) -> line i ppf "Tmty_ident %a\n" fmt_path li; | Tmty_alias (li,_) -> line i ppf "Tmty_alias %a\n" fmt_path li; | Tmty_signature (s) -> line i ppf "Tmty_signature\n"; signature i ppf s; | Tmty_functor (Unit, mt2) -> line i ppf "Tmty_functor ()\n"; module_type i ppf mt2; | Tmty_functor (Named (s, _, mt1), mt2) -> line i ppf "Tmty_functor \"%a\"\n" fmt_modname s; module_type i ppf mt1; module_type i ppf mt2; | Tmty_with (mt, l) -> line i ppf "Tmty_with\n"; module_type i ppf mt; list i longident_x_with_constraint ppf l; | Tmty_typeof m -> line i ppf "Tmty_typeof\n"; module_expr i ppf m; and signature i ppf x = list i signature_item ppf x.sig_items and signature_item i ppf x = line i ppf "signature_item %a\n" fmt_location x.sig_loc; let i = i+1 in match x.sig_desc with | Tsig_value vd -> line i ppf "Tsig_value\n"; value_description i ppf vd; | Tsig_type (rf, l) -> line i ppf "Tsig_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Tsig_typesubst l -> line i ppf "Tsig_typesubst\n"; list i type_declaration ppf l; | Tsig_typext e -> line i ppf "Tsig_typext\n"; type_extension i ppf e; | Tsig_exception ext -> line i ppf "Tsig_exception\n"; type_exception i ppf ext | Tsig_module md -> line i ppf "Tsig_module \"%a\"\n" fmt_modname md.md_id; attributes i ppf md.md_attributes; module_type i ppf md.md_type | Tsig_modsubst ms -> line i ppf "Tsig_modsubst \"%a\" = %a\n" fmt_ident ms.ms_id fmt_path ms.ms_manifest; attributes i ppf ms.ms_attributes; | Tsig_recmodule decls -> line i ppf "Tsig_recmodule\n"; list i module_declaration ppf decls; | Tsig_modtype x -> line i ppf "Tsig_modtype \"%a\"\n" fmt_ident x.mtd_id; attributes i ppf x.mtd_attributes; modtype_declaration i ppf x.mtd_type | Tsig_modtypesubst x -> line i ppf "Tsig_modtypesubst \"%a\"\n" fmt_ident x.mtd_id; attributes i ppf x.mtd_attributes; modtype_declaration i ppf x.mtd_type | Tsig_open od -> line i ppf "Tsig_open %a %a\n" fmt_override_flag od.open_override fmt_path (fst od.open_expr); attributes i ppf od.open_attributes | Tsig_include incl -> line i ppf "Tsig_include\n"; attributes i ppf incl.incl_attributes; module_type i ppf incl.incl_mod | Tsig_class (l) -> line i ppf "Tsig_class\n"; list i class_description ppf l; | Tsig_class_type (l) -> line i ppf "Tsig_class_type\n"; list i class_type_declaration ppf l; | Tsig_attribute a -> attribute i ppf "Tsig_attribute" a and module_declaration i ppf md = line i ppf "%a" fmt_modname md.md_id; attributes i ppf md.md_attributes; module_type (i+1) ppf md.md_type; and module_binding i ppf x = line i ppf "%a\n" fmt_modname x.mb_id; attributes i ppf x.mb_attributes; module_expr (i+1) ppf x.mb_expr and modtype_declaration i ppf = function | None -> line i ppf "#abstract" | Some mt -> module_type (i + 1) ppf mt and with_constraint i ppf x = match x with | Twith_type (td) -> line i ppf "Twith_type\n"; type_declaration (i+1) ppf td; | Twith_typesubst (td) -> line i ppf "Twith_typesubst\n"; type_declaration (i+1) ppf td; | Twith_module (li,_) -> line i ppf "Twith_module %a\n" fmt_path li; | Twith_modsubst (li,_) -> line i ppf "Twith_modsubst %a\n" fmt_path li; | Twith_modtype mty -> line i ppf "Twith_modtype\n"; module_type (i+1) ppf mty | Twith_modtypesubst mty -> line i ppf "Twith_modtype\n"; module_type (i+1) ppf mty and module_expr i ppf x = line i ppf "module_expr %a\n" fmt_location x.mod_loc; attributes i ppf x.mod_attributes; let i = i+1 in match x.mod_desc with | Tmod_ident (li,_) -> line i ppf "Tmod_ident %a\n" fmt_path li; | Tmod_structure (s) -> line i ppf "Tmod_structure\n"; structure i ppf s; | Tmod_functor (Unit, me) -> line i ppf "Tmod_functor ()\n"; module_expr i ppf me; | Tmod_functor (Named (s, _, mt), me) -> line i ppf "Tmod_functor \"%a\"\n" fmt_modname s; module_type i ppf mt; module_expr i ppf me; | Tmod_apply (me1, me2, _) -> line i ppf "Tmod_apply\n"; module_expr i ppf me1; module_expr i ppf me2; | Tmod_constraint (me, _, Tmodtype_explicit mt, _) -> line i ppf "Tmod_constraint\n"; module_expr i ppf me; module_type i ppf mt; | Tmod_constraint (me, _, Tmodtype_implicit, _) -> module_expr i ppf me | Tmod_unpack (e, _) -> line i ppf "Tmod_unpack\n"; expression i ppf e; and structure i ppf x = list i structure_item ppf x.str_items and structure_item i ppf x = line i ppf "structure_item %a\n" fmt_location x.str_loc; let i = i+1 in match x.str_desc with | Tstr_eval (e, attrs) -> line i ppf "Tstr_eval\n"; attributes i ppf attrs; expression i ppf e; | Tstr_value (rf, l) -> line i ppf "Tstr_value %a\n" fmt_rec_flag rf; list i value_binding ppf l; | Tstr_primitive vd -> line i ppf "Tstr_primitive\n"; value_description i ppf vd; | Tstr_type (rf, l) -> line i ppf "Tstr_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Tstr_typext te -> line i ppf "Tstr_typext\n"; type_extension i ppf te | Tstr_exception ext -> line i ppf "Tstr_exception\n"; type_exception i ppf ext; | Tstr_module x -> line i ppf "Tstr_module\n"; module_binding i ppf x | Tstr_recmodule bindings -> line i ppf "Tstr_recmodule\n"; list i module_binding ppf bindings | Tstr_modtype x -> line i ppf "Tstr_modtype \"%a\"\n" fmt_ident x.mtd_id; attributes i ppf x.mtd_attributes; modtype_declaration i ppf x.mtd_type | Tstr_open od -> line i ppf "Tstr_open %a\n" fmt_override_flag od.open_override; module_expr i ppf od.open_expr; attributes i ppf od.open_attributes | Tstr_class (l) -> line i ppf "Tstr_class\n"; list i class_declaration ppf (List.map (fun (cl, _) -> cl) l); | Tstr_class_type (l) -> line i ppf "Tstr_class_type\n"; list i class_type_declaration ppf (List.map (fun (_, _, cl) -> cl) l); | Tstr_include incl -> line i ppf "Tstr_include"; attributes i ppf incl.incl_attributes; module_expr i ppf incl.incl_mod; | Tstr_attribute a -> attribute i ppf "Tstr_attribute" a and longident_x_with_constraint i ppf (li, _, wc) = line i ppf "%a\n" fmt_path li; with_constraint (i+1) ppf wc; and core_type_x_core_type_x_location i ppf (ct1, ct2, l) = line i ppf "<constraint> %a\n" fmt_location l; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; and constructor_decl i ppf {cd_id; cd_name = _; cd_vars; cd_args; cd_res; cd_loc; cd_attributes} = line i ppf "%a\n" fmt_location cd_loc; line (i+1) ppf "%a\n" fmt_ident cd_id; if cd_vars <> [] then line (i+1) ppf "cd_vars =%a\n" typevars cd_vars; attributes i ppf cd_attributes; constructor_arguments (i+1) ppf cd_args; option (i+1) core_type ppf cd_res and constructor_arguments i ppf = function | Cstr_tuple l -> list i core_type ppf l | Cstr_record l -> list i label_decl ppf l and label_decl i ppf {ld_id; ld_name = _; ld_mutable; ld_type; ld_loc; ld_attributes} = line i ppf "%a\n" fmt_location ld_loc; attributes i ppf ld_attributes; line (i+1) ppf "%a\n" fmt_mutable_flag ld_mutable; line (i+1) ppf "%a" fmt_ident ld_id; core_type (i+1) ppf ld_type and longident_x_pattern i ppf (li, _, p) = line i ppf "%a\n" fmt_longident li; pattern (i+1) ppf p; and case : type k . _ -> _ -> k case -> unit = fun i ppf {c_lhs; c_guard; c_rhs} -> line i ppf "<case>\n"; pattern (i+1) ppf c_lhs; begin match c_guard with | None -> () | Some g -> line (i+1) ppf "<when>\n"; expression (i + 2) ppf g end; expression (i+1) ppf c_rhs; and value_binding i ppf x = line i ppf "<def>\n"; attributes (i+1) ppf x.vb_attributes; pattern (i+1) ppf x.vb_pat; expression (i+1) ppf x.vb_expr and string_x_expression i ppf (s, _, e) = line i ppf "<override> \"%a\"\n" fmt_ident s; expression (i+1) ppf e; and record_field i ppf = function | _, Overridden (li, e) -> line i ppf "%a\n" fmt_longident li; expression (i+1) ppf e; | _, Kept _ -> line i ppf "<kept>" and label_x_expression i ppf (l, e) = line i ppf "<arg>\n"; arg_label (i+1) ppf l; (match e with None -> () | Some e -> expression (i+1) ppf e) and ident_x_expression_def i ppf (l, e) = line i ppf "<def> \"%a\"\n" fmt_ident l; expression (i+1) ppf e; and label_x_bool_x_core_type_list i ppf x = match x.rf_desc with | Ttag (l, b, ctl) -> line i ppf "Ttag \"%s\" %s\n" l.txt (string_of_bool b); attributes (i+1) ppf x.rf_attributes; list (i+1) core_type ppf ctl | Tinherit (ct) -> line i ppf "Tinherit\n"; core_type (i+1) ppf ct ;; let interface ppf x = list 0 signature_item ppf x.sig_items;; let implementation ppf x = list 0 structure_item ppf x.str_items;; let implementation_with_coercion ppf Typedtree.{structure; _} = implementation ppf structure
0413942677020db573a3eba1ca1a46643d1fbde020afc3bfcd88850b9ad9ac9c
alwx/luno-react-native
handlers.cljs
(ns luno.handlers (:require [re-frame.core :refer [register-handler dispatch after]] [schema.core :as s :include-macros true] [clojure.walk :refer [keywordize-keys]] [ajax.core :refer [GET POST]] [luno.config :refer [openweathermap-appid bing-appid]] [luno.schema :refer [app-db schema]] [luno.db :as db])) -- Middleware ------------------------------------------------------------ (defn check-and-throw "throw an exception if db doesn't match the schema." [a-schema db] (if-let [problems (s/check a-schema db)] (throw (js/Error. (str "schema check failed: " problems))))) (def validate-schema-mw (after (partial check-and-throw schema))) (register-handler :initialize-schema validate-schema-mw (fn [_ _] app-db)) ;; -- DB handlers ------------------------------------------------------------- (register-handler :load-from-db (fn [db [_ model-type]] (db/load model-type (fn [response] (let [handler-name (->> (name model-type) (str "load-from-db-") (keyword))] (dispatch [handler-name response])))) db)) (register-handler :load-from-db-city (fn [db [_ data]] (->> data (map (fn [city] (let [{:keys [name] :as city} (keywordize-keys (js->clj city))] [name city]))) (into {}) (assoc db :data)))) ;; -- Network handlers -------------------------------------------------------- (register-handler :load-weather (fn [db [_ city]] (POST (str "=" city "&appid=" openweathermap-appid) {:response-format :json :handler #(dispatch [:load-weather-success [%1 city]]) :error-handler #(dispatch [:load-weather-failure [%1 city]])}) (assoc db :loading? true))) (register-handler :load-weather-success (fn [db [_ [response city]]] (let [city-object (keywordize-keys response)] (dispatch [:load-city-image city]) (db/upsert! :city {:where {:name {:eq city}}} city-object) (-> db (assoc :error nil) (assoc-in [:data city] city-object) (assoc :loading? false))))) (register-handler :load-weather-failure (fn [db [_ [e city]]] (-> db (assoc-in [:error city] e) (assoc :loading? false)))) (register-handler :load-city-image (fn [db [_ city]] (POST (str "?$format=json&Query=%27" city "%27") {:response-format :json :headers {"Authorization" (str "Basic " bing-appid)} :handler #(dispatch [:load-city-image-success [%1 city]]) :error-handler #(dispatch [:load-city-image-failure [%1 city]])}) db)) (register-handler :load-city-image-success (fn [db [_ [response city]]] (let [result (-> response (keywordize-keys) :d :results (first)) city-object (-> (get-in db [:data city]) (assoc :bing-image result))] (db/upsert! :city {:where {:name {:eq city}}} city-object) (assoc-in db [:data city] city-object)))) (register-handler :load-city-image-failure (fn [db [_ [e city]]] (assoc-in db [:data city :bing-image] nil))) ;; -- Other handlers ---------------------------------------------------------- (register-handler :set-android-drawer validate-schema-mw (fn [db [_ value]] (assoc-in db [:android :drawer] value))) (register-handler :set-shared-tab validate-schema-mw (fn [db [_ value]] (assoc-in db [:shared :tab] value))) (register-handler :delete-city (fn [db [_ city]] (db/remove! :city {:where {:name {:eq city}}}) (update db :data (fn [v] (dissoc v city)))))
null
https://raw.githubusercontent.com/alwx/luno-react-native/34f9f8b01c1248cf64f40be9638e8352fd8fd448/src/luno/handlers.cljs
clojure
-- DB handlers ------------------------------------------------------------- -- Network handlers -------------------------------------------------------- -- Other handlers ----------------------------------------------------------
(ns luno.handlers (:require [re-frame.core :refer [register-handler dispatch after]] [schema.core :as s :include-macros true] [clojure.walk :refer [keywordize-keys]] [ajax.core :refer [GET POST]] [luno.config :refer [openweathermap-appid bing-appid]] [luno.schema :refer [app-db schema]] [luno.db :as db])) -- Middleware ------------------------------------------------------------ (defn check-and-throw "throw an exception if db doesn't match the schema." [a-schema db] (if-let [problems (s/check a-schema db)] (throw (js/Error. (str "schema check failed: " problems))))) (def validate-schema-mw (after (partial check-and-throw schema))) (register-handler :initialize-schema validate-schema-mw (fn [_ _] app-db)) (register-handler :load-from-db (fn [db [_ model-type]] (db/load model-type (fn [response] (let [handler-name (->> (name model-type) (str "load-from-db-") (keyword))] (dispatch [handler-name response])))) db)) (register-handler :load-from-db-city (fn [db [_ data]] (->> data (map (fn [city] (let [{:keys [name] :as city} (keywordize-keys (js->clj city))] [name city]))) (into {}) (assoc db :data)))) (register-handler :load-weather (fn [db [_ city]] (POST (str "=" city "&appid=" openweathermap-appid) {:response-format :json :handler #(dispatch [:load-weather-success [%1 city]]) :error-handler #(dispatch [:load-weather-failure [%1 city]])}) (assoc db :loading? true))) (register-handler :load-weather-success (fn [db [_ [response city]]] (let [city-object (keywordize-keys response)] (dispatch [:load-city-image city]) (db/upsert! :city {:where {:name {:eq city}}} city-object) (-> db (assoc :error nil) (assoc-in [:data city] city-object) (assoc :loading? false))))) (register-handler :load-weather-failure (fn [db [_ [e city]]] (-> db (assoc-in [:error city] e) (assoc :loading? false)))) (register-handler :load-city-image (fn [db [_ city]] (POST (str "?$format=json&Query=%27" city "%27") {:response-format :json :headers {"Authorization" (str "Basic " bing-appid)} :handler #(dispatch [:load-city-image-success [%1 city]]) :error-handler #(dispatch [:load-city-image-failure [%1 city]])}) db)) (register-handler :load-city-image-success (fn [db [_ [response city]]] (let [result (-> response (keywordize-keys) :d :results (first)) city-object (-> (get-in db [:data city]) (assoc :bing-image result))] (db/upsert! :city {:where {:name {:eq city}}} city-object) (assoc-in db [:data city] city-object)))) (register-handler :load-city-image-failure (fn [db [_ [e city]]] (assoc-in db [:data city :bing-image] nil))) (register-handler :set-android-drawer validate-schema-mw (fn [db [_ value]] (assoc-in db [:android :drawer] value))) (register-handler :set-shared-tab validate-schema-mw (fn [db [_ value]] (assoc-in db [:shared :tab] value))) (register-handler :delete-city (fn [db [_ city]] (db/remove! :city {:where {:name {:eq city}}}) (update db :data (fn [v] (dissoc v city)))))
fb710cb35a691d9b52139ff09e2d5ecd35fd479aa95e895019d7afa348ef01fe
Octachron/orec
default.ml
include Namespace.Make()
null
https://raw.githubusercontent.com/Octachron/orec/cc6e6546cf7dbd5b49bf6b6d913f452f2e1c5d89/src/default.ml
ocaml
include Namespace.Make()
0ce8c288f7db8202e11250f68669bdd037ec32764744797aeb8e08a4b6abbc85
tsloughter/kuberl
kuberl_v1_http_header.erl
-module(kuberl_v1_http_header). -export([encode/1]). -export_type([kuberl_v1_http_header/0]). -type kuberl_v1_http_header() :: #{ 'name' := binary(), 'value' := binary() }. encode(#{ 'name' := Name, 'value' := Value }) -> #{ 'name' => Name, 'value' => Value }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_http_header.erl
erlang
-module(kuberl_v1_http_header). -export([encode/1]). -export_type([kuberl_v1_http_header/0]). -type kuberl_v1_http_header() :: #{ 'name' := binary(), 'value' := binary() }. encode(#{ 'name' := Name, 'value' := Value }) -> #{ 'name' => Name, 'value' => Value }.
cf55a7959c1d0adf94fb40be90e11cd295409cdef6254b419e889723fffc5cf4
lpeterse/haskell-terminal
Internal.hs
module System.Terminal.Internal ( -- ** Terminal Terminal (..) , Command (..) , Attribute (..) , Color (..) , Decoder (..) , defaultDecoder , defaultEncode -- ** LocalTerminal , System.Terminal.Platform.LocalTerminal () -- ** VirtualTerminal (for testing) , VirtualTerminal (..) , VirtualTerminalSettings (..) , withVirtualTerminal ) where import System.Terminal.Decoder import System.Terminal.Encoder import System.Terminal.Terminal import System.Terminal.Platform import System.Terminal.Virtual
null
https://raw.githubusercontent.com/lpeterse/haskell-terminal/994602af65e7f038bc387139ec961248760fd6e6/src/System/Terminal/Internal.hs
haskell
** Terminal ** LocalTerminal ** VirtualTerminal (for testing)
module System.Terminal.Internal ( Terminal (..) , Command (..) , Attribute (..) , Color (..) , Decoder (..) , defaultDecoder , defaultEncode , System.Terminal.Platform.LocalTerminal () , VirtualTerminal (..) , VirtualTerminalSettings (..) , withVirtualTerminal ) where import System.Terminal.Decoder import System.Terminal.Encoder import System.Terminal.Terminal import System.Terminal.Platform import System.Terminal.Virtual
e665fe2073e27b2dd717890106ce1e458ab976cf1a1cf8660a3c73ad1e13f636
spurious/sagittarius-scheme-mirror
ffi.scm
-*- mode : scheme ; coding : utf-8 ; -*- #!read-macro=sagittarius/regex (library (sagittarius ffi) (export open-shared-library lookup-shared-library close-shared-library shared-object-suffix c-function issue 83 pointer->c-function c-callback make-c-callback ;; in some cases, we want this as well free-c-callback callback? ;; malloc c-malloc c-free ;; finalizer register-ffi-finalizer unregister-ffi-finalizer c-memcpy ;; pointer pointer? integer->pointer uinteger->pointer pointer->integer pointer->uinteger object->pointer pointer->object allocate-pointer set-pointer-value! ;; c-struct define-c-struct define-c-union c-struct? allocate-c-struct size-of-c-struct c-struct-ref c-struct-set! describe-c-struct ;; typedef define-c-typedef ;; sizes size-of-bool size-of-char size-of-short size-of-unsigned-short size-of-int size-of-unsigned-int size-of-long size-of-unsigned-long size-of-long-long size-of-unsigned-long-long size-of-void* size-of-size_t size-of-float size-of-double size-of-int8_t size-of-int16_t size-of-int32_t size-of-int64_t size-of-uint8_t size-of-uint16_t size-of-uint32_t size-of-uint64_t size-of-intptr_t size-of-uintptr_t size-of-wchar_t ;; address pointer-address address ;for convenience ;; ref pointer-ref-c-uint8 pointer-ref-c-int8 pointer-ref-c-uint16 pointer-ref-c-int16 pointer-ref-c-uint32 pointer-ref-c-int32 pointer-ref-c-uint64 pointer-ref-c-int64 ;; for convenience (rename (pointer-ref-c-uint8 pointer-ref-c-uint8_t) (pointer-ref-c-int8 pointer-ref-c-int8_t) (pointer-ref-c-uint16 pointer-ref-c-uint16_t) (pointer-ref-c-int16 pointer-ref-c-int16_t) (pointer-ref-c-uint32 pointer-ref-c-uint32_t) (pointer-ref-c-int32 pointer-ref-c-int32_t) (pointer-ref-c-uint64 pointer-ref-c-uint64_t) (pointer-ref-c-int64 pointer-ref-c-int64_t)) pointer-ref-c-unsigned-char pointer-ref-c-char pointer-ref-c-unsigned-short pointer-ref-c-short pointer-ref-c-unsigned-int pointer-ref-c-int pointer-ref-c-unsigned-long pointer-ref-c-long pointer-ref-c-unsigned-long-long pointer-ref-c-long-long pointer-ref-c-intptr pointer-ref-c-uintptr ;; for convenience (rename (pointer-ref-c-intptr pointer-ref-c-intptr_t) (pointer-ref-c-uintptr pointer-ref-c-uintptr_t)) pointer-ref-c-float pointer-ref-c-double pointer-ref-c-pointer pointer-ref-c-wchar (rename (pointer-ref-c-wchar pointer-ref-c-wchar_t)) ;; set! pointer-set-c-uint8! pointer-set-c-int8! pointer-set-c-uint16! pointer-set-c-int16! pointer-set-c-uint32! pointer-set-c-int32! pointer-set-c-uint64! pointer-set-c-int64! ;; for convenience (rename (pointer-set-c-uint8! pointer-set-c-uint8_t! ) (pointer-set-c-int8! pointer-set-c-int8_t! ) (pointer-set-c-uint16! pointer-set-c-uint16_t!) (pointer-set-c-int16! pointer-set-c-int16_t! ) (pointer-set-c-uint32! pointer-set-c-uint32_t!) (pointer-set-c-int32! pointer-set-c-int32_t! ) (pointer-set-c-uint64! pointer-set-c-uint64_t!) (pointer-set-c-int64! pointer-set-c-int64_t! )) pointer-set-c-unsigned-char! pointer-set-c-char! pointer-set-c-unsigned-short! pointer-set-c-short! pointer-set-c-unsigned-int! pointer-set-c-int! pointer-set-c-unsigned-long! pointer-set-c-long! pointer-set-c-unsigned-long-long! pointer-set-c-long-long! pointer-set-c-intptr! pointer-set-c-uintptr! (rename (pointer-set-c-intptr! pointer-set-c-intptr_t!) (pointer-set-c-uintptr! pointer-set-c-uintptr_t!)) pointer-set-c-float! pointer-set-c-double! pointer-set-c-pointer! pointer-set-c-wchar! (rename (pointer-set-c-wchar! pointer-set-c-wchar_t!)) ;; alignment align-of-bool align-of-char align-of-short align-of-unsigned-short align-of-int align-of-unsigned-int align-of-long align-of-unsigned-long align-of-long-long align-of-unsigned-long-long align-of-void* align-of-size_t align-of-float align-of-double align-of-int8_t align-of-int16_t align-of-int32_t align-of-int64_t align-of-uint8_t align-of-uint16_t align-of-uint32_t align-of-uint64_t align-of-intptr_t align-of-uintptr_t align-of-wchar_t ffi procedures pointer-ref-c-of pointer-set-c!-of size-of-of align-of-of ;; c-primitives void char short int long ;; for some convenience (rename (short short-int) (char unsigned-char) (char signed-char) (short signed-short) (short signed-short-int) (int signed-int) (long signed-long) (long signed-long-int)) unsigned-short unsigned-int unsigned-long ;; for some convenience (rename (unsigned-short unsigned-short-int) (unsigned-int unsigned) (unsigned-long unsigned-long-int)) int8_t int16_t int32_t uint8_t uint16_t uint32_t size_t int64_t uint64_t long-long unsigned-long-long bool void* char* float double callback struct array intptr_t uintptr_t wchar_t wchar_t* ___ bit-field ;; utility null-pointer null-pointer? empty-pointer pointer->string pointer->bytevector bytevector->pointer wchar-pointer->string deref ;; c-variable c-variable c-variable? ;; clos <pointer> <function-info> <callback> <c-struct>) (import (rnrs) (core base) (clos user) (sagittarius) (sagittarius regex) (sagittarius dynamic-module)) (load-dynamic-module "sagittarius--ffi") (define void 'void) (define char 'char) (define short 'short) (define int 'int) (define long 'long) (define intptr_t 'intptr_t) (define uintptr_t 'uintptr_t) (define unsigned-short 'unsigned-short) (define unsigned-int 'unsigned-int) (define unsigned-long 'unsigned-long) (define int8_t 'int8_t) (define int16_t 'int16_t) (define int32_t 'int32_t) (define uint8_t 'uint8_t) (define uint16_t 'uint16_t) (define uint32_t 'uint32_t) (define size_t 'size_t) (define int64_t 'int64_t) (define uint64_t 'uint64_t) (define long-long 'long-long) (define unsigned-long-long 'unsigned-long-long) (define bool 'bool) (define void* 'void*) (define char* 'char*) (define float 'float) (define double 'double) (define callback 'callback) (define struct 'struct) (define array 'array) (define wchar_t 'wchar_t) (define wchar_t* 'wchar_t*) (define ___ '___) (define bit-field 'bit-field) ;; helper (define (pointer-ref-c-char* p offset) (pointer->string (pointer-ref-c-pointer p offset))) (define (pointer-ref-c-wchar_t* p offset) (wchar-pointer->string (pointer-ref-c-pointer p offset))) (define (pointer-set-c-char*! s/bv offset) (if (string? s/bv) (pointer-set-c-char*! (string->utf8 s/bv)) (pointer-set-c-pointer! s/bv))) (define (pointer-set-c-wchar_t*! s/bv offset) (if (string? s/bv) (pointer-set-c-wchar_t*! (string->utf16 s/bv (endianness native))) (pointer-set-c-pointer! s/bv))) ;; should be either (define pointer-ref-c-size_t (if (= size-of-size_t size-of-int32_t) pointer-ref-c-int32 pointer-ref-c-int64)) (define pointer-set-c-size_t! (if (= size-of-size_t size-of-int32_t) pointer-set-c-int32! pointer-set-c-int64!)) ;; type ref set size-of align-of (define %type-proc-table `((char . #(,pointer-ref-c-char ,pointer-set-c-char! ,size-of-char ,align-of-char )) (short . #(,pointer-ref-c-short ,pointer-set-c-short! ,size-of-short ,align-of-short )) (int . #(,pointer-ref-c-int ,pointer-set-c-int! ,size-of-int ,align-of-int )) (long . #(,pointer-ref-c-long ,pointer-set-c-long! ,size-of-long ,align-of-long )) (intptr_t . #(,pointer-ref-c-intptr ,pointer-set-c-intptr! ,size-of-intptr_t ,align-of-intptr_t )) (uintptr_t . #(,pointer-ref-c-uintptr ,pointer-set-c-uintptr! ,size-of-uintptr_t ,align-of-uintptr_t )) (unsigned-short . #(,pointer-ref-c-unsigned-short ,pointer-set-c-unsigned-short! ,size-of-unsigned-short ,align-of-unsigned-short )) (unsigned-int . #(,pointer-ref-c-unsigned-int ,pointer-set-c-unsigned-int! ,size-of-unsigned-int ,align-of-unsigned-int )) (unsigned-long . #(,pointer-ref-c-unsigned-long ,pointer-set-c-unsigned-long! ,size-of-unsigned-long ,align-of-unsigned-long )) (int8_t . #(,pointer-ref-c-int8 ,pointer-set-c-int8! ,size-of-int8_t ,align-of-int8_t )) (int16_t . #(,pointer-ref-c-int16 ,pointer-set-c-int16! ,size-of-int16_t ,align-of-int16_t )) (int32_t . #(,pointer-ref-c-int32 ,pointer-set-c-int32! ,size-of-int32_t ,align-of-int32_t )) (uint8_t . #(,pointer-ref-c-uint8 ,pointer-set-c-uint8! ,size-of-uint8_t ,align-of-uint8_t )) (uint16_t . #(,pointer-ref-c-uint16 ,pointer-set-c-uint16! ,size-of-uint16_t ,align-of-uint16_t )) (uint32_t . #(,pointer-ref-c-uint32 ,pointer-set-c-uint32! ,size-of-uint32_t ,align-of-uint32_t )) (size_t . #(,pointer-ref-c-size_t ,pointer-set-c-size_t! ,size-of-size_t ,align-of-size_t )) (int64_t . #(,pointer-ref-c-int64 ,pointer-set-c-int64! ,size-of-int64_t ,align-of-int64_t )) (uint64_t . #(,pointer-ref-c-uint64 ,pointer-set-c-uint64! ,size-of-uint64_t ,align-of-uint64_t )) (long-long . #(,pointer-ref-c-long-long ,pointer-set-c-long-long! ,size-of-long-long ,align-of-long-long )) (unsigned-long-long . #(,pointer-ref-c-unsigned-long-long ,pointer-set-c-unsigned-long-long! ,size-of-unsigned-long-long ,align-of-unsigned-long-long)) (bool . #(,pointer-ref-c-uint8 ,pointer-set-c-uint8! ,size-of-bool ,align-of-bool )) (void* . #(,pointer-ref-c-pointer ,pointer-set-c-pointer! ,size-of-void* ,align-of-void* )) (char* . #(,pointer-ref-c-char* ,pointer-set-c-char*! ,size-of-void* ,align-of-void* )) (float . #(,pointer-ref-c-float ,pointer-set-c-float! ,size-of-float ,align-of-float )) (double . #(,pointer-ref-c-double ,pointer-set-c-double! ,size-of-double ,align-of-double )) ;; how should we treat callback? ;;(callback . #(,pointer-ref-c-callback ,pointer-set-c-callback! ,size-of-callback ,align-of-callback )) (wchar_t . #(,pointer-ref-c-wchar ,pointer-set-c-wchar! ,size-of-wchar_t ,align-of-wchar_t )) (wchar_t* . #(,pointer-ref-c-wchar_t* ,pointer-set-c-wchar_t*! ,size-of-void* ,align-of-void* )))) (define (%type-procedure type pos) (cond ((assq type %type-proc-table) => (lambda (v) (vector-ref (cdr v) pos))) ((c-struct? type) (case pos ((0 1 3) (error 'type-procecure "ref/set!/align-of for c-struct is not supported" type)) ((2) (size-of-c-struct type)) (else (error 'type-procecure "invalid position" pos)))) (else (error 'type-procecure "unknown type" type)))) (define (pointer-ref-c-of type) (%type-procedure type 0)) (define (pointer-set-c!-of type) (%type-procedure type 1)) (define (size-of-of type) (%type-procedure type 2)) (define (align-of-of type) (%type-procedure type 3)) (define null-pointer (integer->pointer 0)) (define (null-pointer? p) (and (pointer? p) (= (pointer->integer p) 0))) (define (empty-pointer) (integer->pointer 0)) (define (pointer->string pointer :optional (transcoder (native-transcoder))) (if (null-pointer? pointer) (assertion-violation 'pointer->string "NULL pointer is given") (let-values (((out getter) (open-bytevector-output-port))) (do ((i 0 (+ i 1))) ((zero? (pointer-ref-c-uint8 pointer i)) (bytevector->string (getter) transcoder)) (put-u8 out (pointer-ref-c-uint8 pointer i)))))) (define (wchar-pointer->string pointer) (if (null-pointer? pointer) (assertion-violation 'pointer->string "NULL pointer is given") (let-values (((out getter) (open-bytevector-output-port))) (let ((buf (make-bytevector size-of-wchar_t))) (do ((i 0 (+ i size-of-wchar_t))) ((zero? (pointer-ref-c-wchar pointer i)) (bytevector->string (getter) (make-transcoder (case size-of-wchar_t ((2) (utf-16-codec)) ((4) (utf-32-codec))) (native-eol-style)))) (let ((wc (pointer-ref-c-wchar pointer i))) (case size-of-wchar_t ((2) (bytevector-u16-set! buf 0 wc (endianness big)) (put-bytevector out buf)) ((4) ;; utf-32-codec uses native endian if it's not specified ;; endianness. (bytevector-u32-native-set! buf 0 wc) (put-bytevector out buf))))))))) ;; we can't determine the size of given pointer ;; so trust the user. (define (pointer->bytevector p size :optional (offset 0) (share #t)) (cond ((null-pointer? p) (assertion-violation 'pointer->bytevector "NULL pointer is given")) (share (%pointer->bytevector p size offset)) (else (do ((i 0 (+ i 1)) (bv (make-bytevector size))) ((= i size) bv) (bytevector-u8-set! bv i (pointer-ref-c-uint8 p (+ i offset))))))) (define (bytevector->pointer bv :optional (offset 0) (share #t)) (if share (%bytevector->pointer bv offset) (let ((size (- (bytevector-length bv) offset))) (do ((i 0 (+ i 1)) (p (allocate-pointer size))) ((= i size) p) (pointer-set-c-uint8! p i (bytevector-u8-ref bv (+ i offset))))))) (define (set-pointer-value! p n) (slot-set! p 'value n)) (define (deref pointer offset) (if (null-pointer? pointer) (assertion-violation 'pointer->string "NULL pointer is given") (pointer-ref-c-pointer pointer (* size-of-void* offset)))) (define-syntax define-c-typedef (syntax-rules (* s*) ((_ old (* new) rest ...) (begin (define new void*) (define-c-typedef old rest ...))) ((_ old (s* new) rest ...) (begin (define new char*) (define-c-typedef old rest ...))) ((_ old new rest ...) (begin (define new old) (define-c-typedef old rest ...))) ((_ old) #t))) (define-syntax address (syntax-rules () underling process can handle 2 elements list as well ;; to avoid unnecessary allocation, we do like this. ((_ p) (list 'address p)) ((_ p offset) (if (and (fixnum? offset) (>= offset 0)) (list 'address p offset) (error 'address "offset must be zero or positive fixnum" offset))))) (define (convert-return-type ret-type) (if (and (pair? ret-type) (not (null? (cdr ret-type))) (eq? (cadr ret-type) '*)) (case (car ret-type) ((wchar_t) wchar_t*) ((char) char*) (else void*)) ret-type)) (define (pointer->c-function pointer ret-type name arg-types) (let* ((rtype (convert-return-type ret-type)) (stub-ret-type (assoc rtype c-function-return-type-alist))) (unless stub-ret-type (assertion-violation 'c-function "wrong return type" ret-type)) (let* ((ret-type (cdr stub-ret-type)) (signatures (list->string (make-signatures arg-types))) (function (create-function-info pointer name ret-type signatures (car stub-ret-type) arg-types))) (lambda args (let ((args-length (length args))) (if (memq ___ arg-types) (let-values (((rest required) (partition (lambda (e) (eq? ___ e)) arg-types))) (unless (< (length required) args-length) (assertion-violation name (format "wrong arguments number at least ~d required, but got ~d" (length required) args-length) args))) (unless (= (length arg-types) (length args)) (assertion-violation name (format "wrong arguments number ~d required, but got ~d" (length arg-types) args-length) args)))) (apply %ffi-call ret-type function args))))) (define (make-signatures arg-types) (let loop ((arg-types arg-types) (r '())) (if (null? arg-types) (reverse! r) (loop (cdr arg-types) (cons (case (car arg-types) ((char short int long unsigned-short int8_t int16_t int32_t uint8_t uint16_t) #\i) ((unsigned-int unsigned-long uint32_t size_t) #\u) ((int64_t long-long) #\x) ((uint64_t unsigned-long-long) #\U) ((bool) #\b) ((void* char*) #\p) ((float) #\f) ((double) #\d) ((callback) #\c) ((wchar_t*) #\w) ((intptr_t) (if (= size-of-intptr_t 4) #\i #\x)) ((uintptr_t) (if (= size-of-intptr_t 4) #\u #\U)) ((___) ;; varargs must be the last (unless (null? (cdr arg-types)) (assertion-violation 'make-signatures "___ must be the last" arg-types)) #\v) (else => (lambda (arg-type) (if (and (pair? arg-type) (not (null? (cdr arg-type))) (eq? (cadr arg-type) '*)) (case (car arg-type) ;; there is no wchar_t above but ;; just for convenience ((wchar_t) #\w) (else #\p)) (assertion-violation 'make-signatures "invalid argument type" arg-types))))) r))))) (define-syntax arg-list (syntax-rules (*) ((_ "next" (arg *) args ...) (cons (list arg '*) (arg-list "next" args ...))) ((_ "next" arg args ...) (cons arg (arg-list "next" args ...))) ((_ "next") '()) ((_ args ...) (arg-list "next" args ...)))) (define-syntax c-function (syntax-rules (*) ((_ lib (ret *) func (args ...)) (make-c-function lib (list ret '*) 'func (arg-list args ...))) ((_ lib ret func (args ...)) (make-c-function lib ret 'func (arg-list args ...))))) (define (make-c-function lib ret-type name arg-types) (let ((func (lookup-shared-library lib (symbol->string name)))) (when (null-pointer? func) (assertion-violation 'c-function "c-function not found" name)) (pointer->c-function func ret-type name arg-types))) ;; callback (define (make-callback-signature name ret args) (apply string (map (lambda (a) (let ((a (if (and (pair? a) (not (null? (cdr a))) (eq? (cadr a) '*)) void* a))) (cond ((assq a callback-argument-type-class) => cdr) (else (assertion-violation name (format "invalid argument type ~a" a) (list ret args)))))) args))) (define-syntax c-callback (lambda (x) (syntax-case x (*) ((_ (ret *) (args ...) proc) #'(make-c-callback (ret *) (arg-list args ...) proc)) ((_ ret (args ...) proc) #'(make-c-callback ret (arg-list args ...) proc))))) (define (make-c-callback ret-type args proc) (define ret (convert-return-type ret-type)) (cond ((assq ret c-function-return-type-alist) => (lambda (type) (create-c-callback (cdr type) (make-callback-signature 'make-c-callback ret args) proc))) (else (assertion-violation 'make-c-callback (format "invalid return type ~a" ret) (list ret args proc))))) ;; c-struct (define (make-c-struct name defs packed?) (define (bit-field-check fields) (and (for-all (lambda (field) (and (pair? field) (= (length field) 2))) fields) (or (unique-id-list? (map car fields)) (assertion-violation 'make-c-struct "bit-field contains duplicate field name(s)" fields)))) (let ((layouts (map (lambda (def) (cond ((and (eq? 'struct (car def)) (= (length def) 3)) `(,(caddr def) -1 struct . ,(cadr def))) ((eq? 'callback (car def)) ;; speciall case `(,(cadr def) ,FFI_RETURN_TYPE_CALLBACK . callback)) ((and (eq? 'array (cadr def)) (= (length def) 4) (assq (car def) c-function-return-type-alist)) => (lambda (type) `(,(cadddr def) ,(cdr type) ,(caddr def) . ,(car type)))) ((and (eq? 'bit-field (car def)) (memq (caddr def) '(big little)) (bit-field-check (cdddr def)) (memq (cadr def) c-function-integers) (assq (cadr def) c-function-return-type-alist)) => (lambda (type) `(bit-field ,(cdr type) ,@(cddr def)))) ((assq (convert-return-type (car def)) c-function-return-type-alist) => (lambda (type) `(,(cadr def) ,(cdr type) . ,(car type)))) (else (assertion-violation 'make-c-struct (format "invalid struct declaration ~a" def) (list name defs))))) defs))) (unless (unique-id-list? (filter-map (lambda (layout) (let ((name (car layout))) (and (not (eq? name 'bit-field)) name))) layouts)) (assertion-violation 'make-c-struct "struct declaration contains duplicated member name" (list name defs))) (create-c-struct name layouts packed?))) ;; (define-c-struct name (int x) (int y) (struct st s)) (define (generate-member-name base lst) (string->symbol (string-append (format "~a." base) (string-join (map symbol->string lst) ".")))) ;; handle struct keyword in the define-c-struct. (define-syntax type-list (lambda (x) (define (build type* r) ;; FIXME clean up, it's getting unreadable... (syntax-case type* (struct array bit-field *) (() (reverse! r)) (((struct type member) rest ...) (build #'(rest ...) (cons (cons* #'list 'struct #'type #'('member)) r))) (((bit-field (type endian) (member bit) ...) rest ...) (build #'(rest ...) (cons (cons* #'list 'bit-field #'type #'(endianness endian) #'((list 'member bit) ...)) r))) (((bit-field type (member bit) ...) rest ...) (identifier? #'type) (build #'(rest ...) (cons (cons* #'list 'bit-field #'type #'(native-endianness) #'((list 'member bit) ...)) r))) (((type array n args ...) rest ...) (build #'(rest ...) (cons (cons* #'list #'type 'array #'n #'('args ...)) r))) ((((type *) args ...) rest ...) (build #'(rest ...) (cons (cons* #'list (list #'list #'type #''*) #'('args ...)) r))) (((type args ...) rest ...) (build #'(rest ...) (cons (cons* #'list #'type #'('args ...)) r))))) (syntax-case x () ((_ types ...) (build #'(types ...) (list #'list)))))) (define-syntax define-c-struct (lambda (x) (define (generate-accessors name spec r) ;; the struct members should can't be created at runtime ;; so we can define the accessor here (define (gen m suffix) (datum->syntax name (string->symbol (format "~a-~a-~a" (syntax->datum name) (syntax->datum m) suffix)))) (define (gen-getters members struct?) (let loop ((members members) (r '())) (syntax-case members () (() r) ((member . d) (with-syntax ((name name) (getter (gen #'member "ref")) (struct? (datum->syntax name struct?))) (loop #'d (cons #'(define (getter st . opt) (if (and struct? (not (null? opt))) (let ((m (generate-member-name 'member opt))) (c-struct-ref st name m)) (c-struct-ref st name 'member))) r))))))) (define (gen-setters members struct?) (let loop ((members members) (r '())) (syntax-case members () (() r) ((member . d) (with-syntax ((name name) (setter (gen #'member "set!")) (struct? (datum->syntax name struct?))) (loop #'d (cons #'(define (setter st v . opt) ;; the same trick as above (if (and struct? (not (null? opt))) (let ((m (generate-member-name 'member opt))) (c-struct-set! st name m v)) (c-struct-set! st name 'member v))) r))))))) (define (continue members rest struct?) (with-syntax (((getters ...) (gen-getters members struct?)) ((setters ...) (gen-setters members struct?))) (generate-accessors name rest (cons #'(begin getters ... setters ...) r)))) (syntax-case spec (struct array bit-field) (() (reverse! r)) (((type member) rest ...) (continue #'(member) #'(rest ...) #f)) (((struct type member) rest ...) (continue #'(member) #'(rest ...) #t)) (((type array elements member) rest ...) (continue #'(member) #'(rest ...) #f)) (((bit-field type (member bit) ...) rest ...) (continue #'(member ...) #'(rest ...) #f)))) (syntax-case x () ((_ name (type . rest) ...) #'(define-c-struct name #f (type . rest) ...)) ((_ name packed? (type . rest) ...) ;;(or (eq? #'packed? :packed) (not #'packed?)) ;; disabled for now (not #'packed?) ;; with black magic ... (with-syntax (((accessors ...) (generate-accessors #'name #'((type . rest) ...) '()))) #'(begin (define name (make-c-struct 'name (type-list (type . rest) ...) (eq? packed? :packed))) accessors ...)))))) (define (find-max-size types) (define (find-size type n) (* (size-of-of type) n)) (apply max (map (lambda (spec) (cond ((eq? (car spec) 'struct) (size-of-c-struct (cadr spec))) ((eq? (cadr spec) 'array) (or (find-size (car spec) (caddr spec)) 0)) (else (or (find-size (car spec) 1) 0)))) types))) the union is a type of c - struct which has uninterned symbol ;; member (thus not accessible), and provides bunch of procedures ;; which manipulate the member memory storage. (define-syntax define-c-union (lambda (x) (define (generate-accessors name spec r) ;; the struct members should can't be created at runtime ;; so we can define the accessor here (define (gen m suffix) (datum->syntax name (string->symbol (format "~a-~a-~a" (syntax->datum name) (syntax->datum m) suffix)))) ;; TODO how to solve struct inner members? (define (continue type member n rest struct-type) (with-syntax ((name name) (getter (gen member "ref")) (setter (gen member "set!")) (?t type) (?n n)) (generate-accessors #'name rest (cons (case struct-type ((struct) #'(begin (define (getter p) p) (define (setter p v) (c-memcpy p 0 v 0 (size-of-c-struct ?t))))) ((array) #'(begin (define (getter p) (define sizeof (size-of-of ?t)) (define ref (pointer-ref-c-of ?t)) (let* ((len ?n) (v (make-vector len))) (let loop ((i 0)) (cond ((= i len) v) (else (vector-set! v i (ref p (* sizeof i))) (loop (+ i 1))))))) (define (setter p v) (define sizeof (size-of-of ?t)) (define set (pointer-set-c!-of ?t)) (let* ((len ?n)) (let loop ((i 0)) (cond ((= i len) v) (else (set p (* sizeof i) (vector-ref v i)) (loop (+ i 1))))))))) (else #'(begin (define (getter p) (define ref (pointer-ref-c-of ?t)) (ref p 0)) (define (setter p v) (define set (pointer-set-c!-of ?t)) (set p 0 v))))) r)))) (syntax-case spec (struct array) (() (reverse! r)) (((type member) rest ...) (continue #'type #'member #f #'(rest ...) #f)) (((struct type member) rest ...) (continue #'type #'member #f #'(rest ...) 'struct)) (((type array elements member) rest ...) (continue #'type #'member #'elements #'(rest ...) 'array)))) (syntax-case x () ((_ name (type rest ...) ...) ;; with black magic ... (with-syntax (((accessors ...) (generate-accessors #'name #'((type rest ...) ...) '()))) #'(begin (define name (let* ((types (type-list (type rest ...) ...)) (max (find-max-size types))) (make-c-struct 'name (list (list uint8_t 'array max (gensym))) #f))) accessors ...)))))) (define c-function-integers `(char short int long long-long intptr_t unsigned-short unsigned-int unsigned-long unsigned-long-long uintptr_t size_t int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t)) (define c-function-return-type-alist `((void . ,FFI_RETURN_TYPE_VOID ) (bool . ,FFI_RETURN_TYPE_BOOL ) (char . ,FFI_RETURN_TYPE_INT8_T ) (short . ,FFI_RETURN_TYPE_SHORT ) (int . ,FFI_RETURN_TYPE_INT ) (long . ,FFI_RETURN_TYPE_LONG ) (long-long . ,FFI_RETURN_TYPE_INT64_T ) (intptr_t . ,FFI_RETURN_TYPE_INTPTR ) (unsigned-short . ,FFI_RETURN_TYPE_USHORT ) (unsigned-int . ,FFI_RETURN_TYPE_UINT ) (unsigned-long . ,FFI_RETURN_TYPE_ULONG ) (unsigned-long-long . ,FFI_RETURN_TYPE_UINT64_T) (uintptr_t . ,FFI_RETURN_TYPE_UINTPTR ) (float . ,FFI_RETURN_TYPE_FLOAT ) (double . ,FFI_RETURN_TYPE_DOUBLE ) (void* . ,FFI_RETURN_TYPE_POINTER ) (char* . ,FFI_RETURN_TYPE_STRING ) (size_t . ,FFI_RETURN_TYPE_SIZE_T ) (int8_t . ,FFI_RETURN_TYPE_INT8_T ) (uint8_t . ,FFI_RETURN_TYPE_UINT8_T ) (int16_t . ,FFI_RETURN_TYPE_INT16_T ) (uint16_t . ,FFI_RETURN_TYPE_UINT16_T) (int32_t . ,FFI_RETURN_TYPE_INT32_T ) (uint32_t . ,FFI_RETURN_TYPE_UINT32_T) (int64_t . ,FFI_RETURN_TYPE_INT64_T ) (uint64_t . ,FFI_RETURN_TYPE_UINT64_T) (wchar_t* . ,FFI_RETURN_TYPE_WCHAR_STR) (callback . ,FFI_RETURN_TYPE_CALLBACK))) (define callback-argument-type-class `((bool . #\l) (char . #\b) (short . #\h) (int . ,(if (= size-of-int 4) #\w #\q)) (long . ,(if (= size-of-long 4) #\w #\q)) (long-long . #\q) (intptr_t . ,(if (= size-of-intptr_t 4) #\w #\q)) (unsigned-char . #\B) (unsigned-short . #\H) (unsigned-int . ,(if (= size-of-int 4) #\W #\Q)) (unsigned-long . ,(if (= size-of-long 4) #\W #\Q)) (unsigned-long-long . #\Q) (uintptr_t . ,(if (= size-of-uintptr_t 4) #\W #\Q)) (int8_t . #\b) (int16_t . #\h) (int32_t . #\w) (int64_t . #\Q) (uint8_t . #\B) (uint16_t . #\H) (uint32_t . #\W) (uint64_t . #\Q) (float . #\f) (double . #\d) (size_t . ,(if (= size-of-size_t 4) #\W #\Q)) (void* . #\p))) ;; c-varibale (define-class <c-variable> () ((pointer :init-keyword :pointer) (getter :init-keyword :getter) (setter :init-keyword :setter))) ;; make this work like parameters :) ;; TODO how should we treat with void*? (define-method object-apply ((o <c-variable>)) ((slot-ref o 'getter) (slot-ref o 'pointer))) (define-method object-apply ((o <c-variable>)) ((slot-ref o 'getter) (slot-ref o 'pointer))) (define-method object-apply ((o <c-variable>) v) (let ((setter (slot-ref o 'setter))) (if setter (setter (slot-ref o 'pointer) v) (error 'c-variable "variable is immutable" o)))) (define-method (setter object-apply) ((o <c-variable>) v) (o v)) (define-method write-object ((o <c-variable>) out) (format out "#<c-varible ~a>" (slot-ref o 'pointer))) (define (make-c-variable lib name getter setter) (let ((p (lookup-shared-library lib (symbol->string name)))) (make <c-variable> :pointer p :getter getter :setter setter))) (define (c-variable? o) (is-a? o <c-variable>)) (define-syntax c-variable (lambda (x) (define (get-accessor type) (let ((name (symbol->string (syntax->datum type)))) (regex-match-cond ((#/(.+?)_t$/ name) (#f name) (list (string->symbol (string-append "pointer-ref-c-" name)) (string->symbol (string-append "pointer-set-c-" name "!")))) (else (list (string->symbol (string-append "pointer-ref-c-" name)) (string->symbol (string-append "pointer-set-c-" name "!"))))) )) (syntax-case x (char* void* wchar_t*) ;; We make char* and wchar_t* immutable from Scheme. ((_ lib char* name) #'(c-variable lib name (lambda (p) (pointer->string (deref p 0))) #f)) ((_ lib wchar_t* name) #'(c-variable lib name (lambda (p) (wchar-pointer->string (deref p 0))) #f)) ;; TODO how should we treat this? for now direct pointer access ((_ lib void* name) ;; pointer is not immutable but I don't know the best way to ;; handle set! with setter. So for now make it like this #'(c-variable lib name (lambda (p) p) #f)) ((_ lib type name) (with-syntax (((getter setter) (datum->syntax #'k (get-accessor #'type)))) #'(c-variable lib name (lambda (p) (getter p 0)) (lambda (p v) (setter p 0 v))))) ((_ lib name getter setter) #'(make-c-variable lib 'name getter setter))))) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/ext/ffi/sagittarius/ffi.scm
scheme
coding : utf-8 ; -*- in some cases, we want this as well malloc finalizer pointer c-struct typedef sizes address for convenience ref for convenience for convenience set! for convenience alignment c-primitives for some convenience for some convenience utility c-variable clos helper should be either type ref set size-of align-of how should we treat callback? (callback . #(,pointer-ref-c-callback ,pointer-set-c-callback! ,size-of-callback ,align-of-callback )) utf-32-codec uses native endian if it's not specified endianness. we can't determine the size of given pointer so trust the user. to avoid unnecessary allocation, we do like this. varargs must be the last there is no wchar_t above but just for convenience callback c-struct speciall case (define-c-struct name (int x) (int y) (struct st s)) handle struct keyword in the define-c-struct. FIXME clean up, it's getting unreadable... the struct members should can't be created at runtime so we can define the accessor here the same trick as above (or (eq? #'packed? :packed) (not #'packed?)) disabled for now with black magic ... member (thus not accessible), and provides bunch of procedures which manipulate the member memory storage. the struct members should can't be created at runtime so we can define the accessor here TODO how to solve struct inner members? with black magic ... c-varibale make this work like parameters :) TODO how should we treat with void*? We make char* and wchar_t* immutable from Scheme. TODO how should we treat this? for now direct pointer access pointer is not immutable but I don't know the best way to handle set! with setter. So for now make it like this
#!read-macro=sagittarius/regex (library (sagittarius ffi) (export open-shared-library lookup-shared-library close-shared-library shared-object-suffix c-function issue 83 pointer->c-function c-callback free-c-callback callback? c-malloc c-free register-ffi-finalizer unregister-ffi-finalizer c-memcpy pointer? integer->pointer uinteger->pointer pointer->integer pointer->uinteger object->pointer pointer->object allocate-pointer set-pointer-value! define-c-struct define-c-union c-struct? allocate-c-struct size-of-c-struct c-struct-ref c-struct-set! describe-c-struct define-c-typedef size-of-bool size-of-char size-of-short size-of-unsigned-short size-of-int size-of-unsigned-int size-of-long size-of-unsigned-long size-of-long-long size-of-unsigned-long-long size-of-void* size-of-size_t size-of-float size-of-double size-of-int8_t size-of-int16_t size-of-int32_t size-of-int64_t size-of-uint8_t size-of-uint16_t size-of-uint32_t size-of-uint64_t size-of-intptr_t size-of-uintptr_t size-of-wchar_t pointer-address pointer-ref-c-uint8 pointer-ref-c-int8 pointer-ref-c-uint16 pointer-ref-c-int16 pointer-ref-c-uint32 pointer-ref-c-int32 pointer-ref-c-uint64 pointer-ref-c-int64 (rename (pointer-ref-c-uint8 pointer-ref-c-uint8_t) (pointer-ref-c-int8 pointer-ref-c-int8_t) (pointer-ref-c-uint16 pointer-ref-c-uint16_t) (pointer-ref-c-int16 pointer-ref-c-int16_t) (pointer-ref-c-uint32 pointer-ref-c-uint32_t) (pointer-ref-c-int32 pointer-ref-c-int32_t) (pointer-ref-c-uint64 pointer-ref-c-uint64_t) (pointer-ref-c-int64 pointer-ref-c-int64_t)) pointer-ref-c-unsigned-char pointer-ref-c-char pointer-ref-c-unsigned-short pointer-ref-c-short pointer-ref-c-unsigned-int pointer-ref-c-int pointer-ref-c-unsigned-long pointer-ref-c-long pointer-ref-c-unsigned-long-long pointer-ref-c-long-long pointer-ref-c-intptr pointer-ref-c-uintptr (rename (pointer-ref-c-intptr pointer-ref-c-intptr_t) (pointer-ref-c-uintptr pointer-ref-c-uintptr_t)) pointer-ref-c-float pointer-ref-c-double pointer-ref-c-pointer pointer-ref-c-wchar (rename (pointer-ref-c-wchar pointer-ref-c-wchar_t)) pointer-set-c-uint8! pointer-set-c-int8! pointer-set-c-uint16! pointer-set-c-int16! pointer-set-c-uint32! pointer-set-c-int32! pointer-set-c-uint64! pointer-set-c-int64! (rename (pointer-set-c-uint8! pointer-set-c-uint8_t! ) (pointer-set-c-int8! pointer-set-c-int8_t! ) (pointer-set-c-uint16! pointer-set-c-uint16_t!) (pointer-set-c-int16! pointer-set-c-int16_t! ) (pointer-set-c-uint32! pointer-set-c-uint32_t!) (pointer-set-c-int32! pointer-set-c-int32_t! ) (pointer-set-c-uint64! pointer-set-c-uint64_t!) (pointer-set-c-int64! pointer-set-c-int64_t! )) pointer-set-c-unsigned-char! pointer-set-c-char! pointer-set-c-unsigned-short! pointer-set-c-short! pointer-set-c-unsigned-int! pointer-set-c-int! pointer-set-c-unsigned-long! pointer-set-c-long! pointer-set-c-unsigned-long-long! pointer-set-c-long-long! pointer-set-c-intptr! pointer-set-c-uintptr! (rename (pointer-set-c-intptr! pointer-set-c-intptr_t!) (pointer-set-c-uintptr! pointer-set-c-uintptr_t!)) pointer-set-c-float! pointer-set-c-double! pointer-set-c-pointer! pointer-set-c-wchar! (rename (pointer-set-c-wchar! pointer-set-c-wchar_t!)) align-of-bool align-of-char align-of-short align-of-unsigned-short align-of-int align-of-unsigned-int align-of-long align-of-unsigned-long align-of-long-long align-of-unsigned-long-long align-of-void* align-of-size_t align-of-float align-of-double align-of-int8_t align-of-int16_t align-of-int32_t align-of-int64_t align-of-uint8_t align-of-uint16_t align-of-uint32_t align-of-uint64_t align-of-intptr_t align-of-uintptr_t align-of-wchar_t ffi procedures pointer-ref-c-of pointer-set-c!-of size-of-of align-of-of void char short int long (rename (short short-int) (char unsigned-char) (char signed-char) (short signed-short) (short signed-short-int) (int signed-int) (long signed-long) (long signed-long-int)) unsigned-short unsigned-int unsigned-long (rename (unsigned-short unsigned-short-int) (unsigned-int unsigned) (unsigned-long unsigned-long-int)) int8_t int16_t int32_t uint8_t uint16_t uint32_t size_t int64_t uint64_t long-long unsigned-long-long bool void* char* float double callback struct array intptr_t uintptr_t wchar_t wchar_t* ___ bit-field null-pointer null-pointer? empty-pointer pointer->string pointer->bytevector bytevector->pointer wchar-pointer->string deref c-variable c-variable? <pointer> <function-info> <callback> <c-struct>) (import (rnrs) (core base) (clos user) (sagittarius) (sagittarius regex) (sagittarius dynamic-module)) (load-dynamic-module "sagittarius--ffi") (define void 'void) (define char 'char) (define short 'short) (define int 'int) (define long 'long) (define intptr_t 'intptr_t) (define uintptr_t 'uintptr_t) (define unsigned-short 'unsigned-short) (define unsigned-int 'unsigned-int) (define unsigned-long 'unsigned-long) (define int8_t 'int8_t) (define int16_t 'int16_t) (define int32_t 'int32_t) (define uint8_t 'uint8_t) (define uint16_t 'uint16_t) (define uint32_t 'uint32_t) (define size_t 'size_t) (define int64_t 'int64_t) (define uint64_t 'uint64_t) (define long-long 'long-long) (define unsigned-long-long 'unsigned-long-long) (define bool 'bool) (define void* 'void*) (define char* 'char*) (define float 'float) (define double 'double) (define callback 'callback) (define struct 'struct) (define array 'array) (define wchar_t 'wchar_t) (define wchar_t* 'wchar_t*) (define ___ '___) (define bit-field 'bit-field) (define (pointer-ref-c-char* p offset) (pointer->string (pointer-ref-c-pointer p offset))) (define (pointer-ref-c-wchar_t* p offset) (wchar-pointer->string (pointer-ref-c-pointer p offset))) (define (pointer-set-c-char*! s/bv offset) (if (string? s/bv) (pointer-set-c-char*! (string->utf8 s/bv)) (pointer-set-c-pointer! s/bv))) (define (pointer-set-c-wchar_t*! s/bv offset) (if (string? s/bv) (pointer-set-c-wchar_t*! (string->utf16 s/bv (endianness native))) (pointer-set-c-pointer! s/bv))) (define pointer-ref-c-size_t (if (= size-of-size_t size-of-int32_t) pointer-ref-c-int32 pointer-ref-c-int64)) (define pointer-set-c-size_t! (if (= size-of-size_t size-of-int32_t) pointer-set-c-int32! pointer-set-c-int64!)) (define %type-proc-table `((char . #(,pointer-ref-c-char ,pointer-set-c-char! ,size-of-char ,align-of-char )) (short . #(,pointer-ref-c-short ,pointer-set-c-short! ,size-of-short ,align-of-short )) (int . #(,pointer-ref-c-int ,pointer-set-c-int! ,size-of-int ,align-of-int )) (long . #(,pointer-ref-c-long ,pointer-set-c-long! ,size-of-long ,align-of-long )) (intptr_t . #(,pointer-ref-c-intptr ,pointer-set-c-intptr! ,size-of-intptr_t ,align-of-intptr_t )) (uintptr_t . #(,pointer-ref-c-uintptr ,pointer-set-c-uintptr! ,size-of-uintptr_t ,align-of-uintptr_t )) (unsigned-short . #(,pointer-ref-c-unsigned-short ,pointer-set-c-unsigned-short! ,size-of-unsigned-short ,align-of-unsigned-short )) (unsigned-int . #(,pointer-ref-c-unsigned-int ,pointer-set-c-unsigned-int! ,size-of-unsigned-int ,align-of-unsigned-int )) (unsigned-long . #(,pointer-ref-c-unsigned-long ,pointer-set-c-unsigned-long! ,size-of-unsigned-long ,align-of-unsigned-long )) (int8_t . #(,pointer-ref-c-int8 ,pointer-set-c-int8! ,size-of-int8_t ,align-of-int8_t )) (int16_t . #(,pointer-ref-c-int16 ,pointer-set-c-int16! ,size-of-int16_t ,align-of-int16_t )) (int32_t . #(,pointer-ref-c-int32 ,pointer-set-c-int32! ,size-of-int32_t ,align-of-int32_t )) (uint8_t . #(,pointer-ref-c-uint8 ,pointer-set-c-uint8! ,size-of-uint8_t ,align-of-uint8_t )) (uint16_t . #(,pointer-ref-c-uint16 ,pointer-set-c-uint16! ,size-of-uint16_t ,align-of-uint16_t )) (uint32_t . #(,pointer-ref-c-uint32 ,pointer-set-c-uint32! ,size-of-uint32_t ,align-of-uint32_t )) (size_t . #(,pointer-ref-c-size_t ,pointer-set-c-size_t! ,size-of-size_t ,align-of-size_t )) (int64_t . #(,pointer-ref-c-int64 ,pointer-set-c-int64! ,size-of-int64_t ,align-of-int64_t )) (uint64_t . #(,pointer-ref-c-uint64 ,pointer-set-c-uint64! ,size-of-uint64_t ,align-of-uint64_t )) (long-long . #(,pointer-ref-c-long-long ,pointer-set-c-long-long! ,size-of-long-long ,align-of-long-long )) (unsigned-long-long . #(,pointer-ref-c-unsigned-long-long ,pointer-set-c-unsigned-long-long! ,size-of-unsigned-long-long ,align-of-unsigned-long-long)) (bool . #(,pointer-ref-c-uint8 ,pointer-set-c-uint8! ,size-of-bool ,align-of-bool )) (void* . #(,pointer-ref-c-pointer ,pointer-set-c-pointer! ,size-of-void* ,align-of-void* )) (char* . #(,pointer-ref-c-char* ,pointer-set-c-char*! ,size-of-void* ,align-of-void* )) (float . #(,pointer-ref-c-float ,pointer-set-c-float! ,size-of-float ,align-of-float )) (double . #(,pointer-ref-c-double ,pointer-set-c-double! ,size-of-double ,align-of-double )) (wchar_t . #(,pointer-ref-c-wchar ,pointer-set-c-wchar! ,size-of-wchar_t ,align-of-wchar_t )) (wchar_t* . #(,pointer-ref-c-wchar_t* ,pointer-set-c-wchar_t*! ,size-of-void* ,align-of-void* )))) (define (%type-procedure type pos) (cond ((assq type %type-proc-table) => (lambda (v) (vector-ref (cdr v) pos))) ((c-struct? type) (case pos ((0 1 3) (error 'type-procecure "ref/set!/align-of for c-struct is not supported" type)) ((2) (size-of-c-struct type)) (else (error 'type-procecure "invalid position" pos)))) (else (error 'type-procecure "unknown type" type)))) (define (pointer-ref-c-of type) (%type-procedure type 0)) (define (pointer-set-c!-of type) (%type-procedure type 1)) (define (size-of-of type) (%type-procedure type 2)) (define (align-of-of type) (%type-procedure type 3)) (define null-pointer (integer->pointer 0)) (define (null-pointer? p) (and (pointer? p) (= (pointer->integer p) 0))) (define (empty-pointer) (integer->pointer 0)) (define (pointer->string pointer :optional (transcoder (native-transcoder))) (if (null-pointer? pointer) (assertion-violation 'pointer->string "NULL pointer is given") (let-values (((out getter) (open-bytevector-output-port))) (do ((i 0 (+ i 1))) ((zero? (pointer-ref-c-uint8 pointer i)) (bytevector->string (getter) transcoder)) (put-u8 out (pointer-ref-c-uint8 pointer i)))))) (define (wchar-pointer->string pointer) (if (null-pointer? pointer) (assertion-violation 'pointer->string "NULL pointer is given") (let-values (((out getter) (open-bytevector-output-port))) (let ((buf (make-bytevector size-of-wchar_t))) (do ((i 0 (+ i size-of-wchar_t))) ((zero? (pointer-ref-c-wchar pointer i)) (bytevector->string (getter) (make-transcoder (case size-of-wchar_t ((2) (utf-16-codec)) ((4) (utf-32-codec))) (native-eol-style)))) (let ((wc (pointer-ref-c-wchar pointer i))) (case size-of-wchar_t ((2) (bytevector-u16-set! buf 0 wc (endianness big)) (put-bytevector out buf)) ((4) (bytevector-u32-native-set! buf 0 wc) (put-bytevector out buf))))))))) (define (pointer->bytevector p size :optional (offset 0) (share #t)) (cond ((null-pointer? p) (assertion-violation 'pointer->bytevector "NULL pointer is given")) (share (%pointer->bytevector p size offset)) (else (do ((i 0 (+ i 1)) (bv (make-bytevector size))) ((= i size) bv) (bytevector-u8-set! bv i (pointer-ref-c-uint8 p (+ i offset))))))) (define (bytevector->pointer bv :optional (offset 0) (share #t)) (if share (%bytevector->pointer bv offset) (let ((size (- (bytevector-length bv) offset))) (do ((i 0 (+ i 1)) (p (allocate-pointer size))) ((= i size) p) (pointer-set-c-uint8! p i (bytevector-u8-ref bv (+ i offset))))))) (define (set-pointer-value! p n) (slot-set! p 'value n)) (define (deref pointer offset) (if (null-pointer? pointer) (assertion-violation 'pointer->string "NULL pointer is given") (pointer-ref-c-pointer pointer (* size-of-void* offset)))) (define-syntax define-c-typedef (syntax-rules (* s*) ((_ old (* new) rest ...) (begin (define new void*) (define-c-typedef old rest ...))) ((_ old (s* new) rest ...) (begin (define new char*) (define-c-typedef old rest ...))) ((_ old new rest ...) (begin (define new old) (define-c-typedef old rest ...))) ((_ old) #t))) (define-syntax address (syntax-rules () underling process can handle 2 elements list as well ((_ p) (list 'address p)) ((_ p offset) (if (and (fixnum? offset) (>= offset 0)) (list 'address p offset) (error 'address "offset must be zero or positive fixnum" offset))))) (define (convert-return-type ret-type) (if (and (pair? ret-type) (not (null? (cdr ret-type))) (eq? (cadr ret-type) '*)) (case (car ret-type) ((wchar_t) wchar_t*) ((char) char*) (else void*)) ret-type)) (define (pointer->c-function pointer ret-type name arg-types) (let* ((rtype (convert-return-type ret-type)) (stub-ret-type (assoc rtype c-function-return-type-alist))) (unless stub-ret-type (assertion-violation 'c-function "wrong return type" ret-type)) (let* ((ret-type (cdr stub-ret-type)) (signatures (list->string (make-signatures arg-types))) (function (create-function-info pointer name ret-type signatures (car stub-ret-type) arg-types))) (lambda args (let ((args-length (length args))) (if (memq ___ arg-types) (let-values (((rest required) (partition (lambda (e) (eq? ___ e)) arg-types))) (unless (< (length required) args-length) (assertion-violation name (format "wrong arguments number at least ~d required, but got ~d" (length required) args-length) args))) (unless (= (length arg-types) (length args)) (assertion-violation name (format "wrong arguments number ~d required, but got ~d" (length arg-types) args-length) args)))) (apply %ffi-call ret-type function args))))) (define (make-signatures arg-types) (let loop ((arg-types arg-types) (r '())) (if (null? arg-types) (reverse! r) (loop (cdr arg-types) (cons (case (car arg-types) ((char short int long unsigned-short int8_t int16_t int32_t uint8_t uint16_t) #\i) ((unsigned-int unsigned-long uint32_t size_t) #\u) ((int64_t long-long) #\x) ((uint64_t unsigned-long-long) #\U) ((bool) #\b) ((void* char*) #\p) ((float) #\f) ((double) #\d) ((callback) #\c) ((wchar_t*) #\w) ((intptr_t) (if (= size-of-intptr_t 4) #\i #\x)) ((uintptr_t) (if (= size-of-intptr_t 4) #\u #\U)) ((___) (unless (null? (cdr arg-types)) (assertion-violation 'make-signatures "___ must be the last" arg-types)) #\v) (else => (lambda (arg-type) (if (and (pair? arg-type) (not (null? (cdr arg-type))) (eq? (cadr arg-type) '*)) (case (car arg-type) ((wchar_t) #\w) (else #\p)) (assertion-violation 'make-signatures "invalid argument type" arg-types))))) r))))) (define-syntax arg-list (syntax-rules (*) ((_ "next" (arg *) args ...) (cons (list arg '*) (arg-list "next" args ...))) ((_ "next" arg args ...) (cons arg (arg-list "next" args ...))) ((_ "next") '()) ((_ args ...) (arg-list "next" args ...)))) (define-syntax c-function (syntax-rules (*) ((_ lib (ret *) func (args ...)) (make-c-function lib (list ret '*) 'func (arg-list args ...))) ((_ lib ret func (args ...)) (make-c-function lib ret 'func (arg-list args ...))))) (define (make-c-function lib ret-type name arg-types) (let ((func (lookup-shared-library lib (symbol->string name)))) (when (null-pointer? func) (assertion-violation 'c-function "c-function not found" name)) (pointer->c-function func ret-type name arg-types))) (define (make-callback-signature name ret args) (apply string (map (lambda (a) (let ((a (if (and (pair? a) (not (null? (cdr a))) (eq? (cadr a) '*)) void* a))) (cond ((assq a callback-argument-type-class) => cdr) (else (assertion-violation name (format "invalid argument type ~a" a) (list ret args)))))) args))) (define-syntax c-callback (lambda (x) (syntax-case x (*) ((_ (ret *) (args ...) proc) #'(make-c-callback (ret *) (arg-list args ...) proc)) ((_ ret (args ...) proc) #'(make-c-callback ret (arg-list args ...) proc))))) (define (make-c-callback ret-type args proc) (define ret (convert-return-type ret-type)) (cond ((assq ret c-function-return-type-alist) => (lambda (type) (create-c-callback (cdr type) (make-callback-signature 'make-c-callback ret args) proc))) (else (assertion-violation 'make-c-callback (format "invalid return type ~a" ret) (list ret args proc))))) (define (make-c-struct name defs packed?) (define (bit-field-check fields) (and (for-all (lambda (field) (and (pair? field) (= (length field) 2))) fields) (or (unique-id-list? (map car fields)) (assertion-violation 'make-c-struct "bit-field contains duplicate field name(s)" fields)))) (let ((layouts (map (lambda (def) (cond ((and (eq? 'struct (car def)) (= (length def) 3)) `(,(caddr def) -1 struct . ,(cadr def))) ((eq? 'callback (car def)) `(,(cadr def) ,FFI_RETURN_TYPE_CALLBACK . callback)) ((and (eq? 'array (cadr def)) (= (length def) 4) (assq (car def) c-function-return-type-alist)) => (lambda (type) `(,(cadddr def) ,(cdr type) ,(caddr def) . ,(car type)))) ((and (eq? 'bit-field (car def)) (memq (caddr def) '(big little)) (bit-field-check (cdddr def)) (memq (cadr def) c-function-integers) (assq (cadr def) c-function-return-type-alist)) => (lambda (type) `(bit-field ,(cdr type) ,@(cddr def)))) ((assq (convert-return-type (car def)) c-function-return-type-alist) => (lambda (type) `(,(cadr def) ,(cdr type) . ,(car type)))) (else (assertion-violation 'make-c-struct (format "invalid struct declaration ~a" def) (list name defs))))) defs))) (unless (unique-id-list? (filter-map (lambda (layout) (let ((name (car layout))) (and (not (eq? name 'bit-field)) name))) layouts)) (assertion-violation 'make-c-struct "struct declaration contains duplicated member name" (list name defs))) (create-c-struct name layouts packed?))) (define (generate-member-name base lst) (string->symbol (string-append (format "~a." base) (string-join (map symbol->string lst) ".")))) (define-syntax type-list (lambda (x) (define (build type* r) (syntax-case type* (struct array bit-field *) (() (reverse! r)) (((struct type member) rest ...) (build #'(rest ...) (cons (cons* #'list 'struct #'type #'('member)) r))) (((bit-field (type endian) (member bit) ...) rest ...) (build #'(rest ...) (cons (cons* #'list 'bit-field #'type #'(endianness endian) #'((list 'member bit) ...)) r))) (((bit-field type (member bit) ...) rest ...) (identifier? #'type) (build #'(rest ...) (cons (cons* #'list 'bit-field #'type #'(native-endianness) #'((list 'member bit) ...)) r))) (((type array n args ...) rest ...) (build #'(rest ...) (cons (cons* #'list #'type 'array #'n #'('args ...)) r))) ((((type *) args ...) rest ...) (build #'(rest ...) (cons (cons* #'list (list #'list #'type #''*) #'('args ...)) r))) (((type args ...) rest ...) (build #'(rest ...) (cons (cons* #'list #'type #'('args ...)) r))))) (syntax-case x () ((_ types ...) (build #'(types ...) (list #'list)))))) (define-syntax define-c-struct (lambda (x) (define (generate-accessors name spec r) (define (gen m suffix) (datum->syntax name (string->symbol (format "~a-~a-~a" (syntax->datum name) (syntax->datum m) suffix)))) (define (gen-getters members struct?) (let loop ((members members) (r '())) (syntax-case members () (() r) ((member . d) (with-syntax ((name name) (getter (gen #'member "ref")) (struct? (datum->syntax name struct?))) (loop #'d (cons #'(define (getter st . opt) (if (and struct? (not (null? opt))) (let ((m (generate-member-name 'member opt))) (c-struct-ref st name m)) (c-struct-ref st name 'member))) r))))))) (define (gen-setters members struct?) (let loop ((members members) (r '())) (syntax-case members () (() r) ((member . d) (with-syntax ((name name) (setter (gen #'member "set!")) (struct? (datum->syntax name struct?))) (loop #'d (cons #'(define (setter st v . opt) (if (and struct? (not (null? opt))) (let ((m (generate-member-name 'member opt))) (c-struct-set! st name m v)) (c-struct-set! st name 'member v))) r))))))) (define (continue members rest struct?) (with-syntax (((getters ...) (gen-getters members struct?)) ((setters ...) (gen-setters members struct?))) (generate-accessors name rest (cons #'(begin getters ... setters ...) r)))) (syntax-case spec (struct array bit-field) (() (reverse! r)) (((type member) rest ...) (continue #'(member) #'(rest ...) #f)) (((struct type member) rest ...) (continue #'(member) #'(rest ...) #t)) (((type array elements member) rest ...) (continue #'(member) #'(rest ...) #f)) (((bit-field type (member bit) ...) rest ...) (continue #'(member ...) #'(rest ...) #f)))) (syntax-case x () ((_ name (type . rest) ...) #'(define-c-struct name #f (type . rest) ...)) ((_ name packed? (type . rest) ...) (not #'packed?) (with-syntax (((accessors ...) (generate-accessors #'name #'((type . rest) ...) '()))) #'(begin (define name (make-c-struct 'name (type-list (type . rest) ...) (eq? packed? :packed))) accessors ...)))))) (define (find-max-size types) (define (find-size type n) (* (size-of-of type) n)) (apply max (map (lambda (spec) (cond ((eq? (car spec) 'struct) (size-of-c-struct (cadr spec))) ((eq? (cadr spec) 'array) (or (find-size (car spec) (caddr spec)) 0)) (else (or (find-size (car spec) 1) 0)))) types))) the union is a type of c - struct which has uninterned symbol (define-syntax define-c-union (lambda (x) (define (generate-accessors name spec r) (define (gen m suffix) (datum->syntax name (string->symbol (format "~a-~a-~a" (syntax->datum name) (syntax->datum m) suffix)))) (define (continue type member n rest struct-type) (with-syntax ((name name) (getter (gen member "ref")) (setter (gen member "set!")) (?t type) (?n n)) (generate-accessors #'name rest (cons (case struct-type ((struct) #'(begin (define (getter p) p) (define (setter p v) (c-memcpy p 0 v 0 (size-of-c-struct ?t))))) ((array) #'(begin (define (getter p) (define sizeof (size-of-of ?t)) (define ref (pointer-ref-c-of ?t)) (let* ((len ?n) (v (make-vector len))) (let loop ((i 0)) (cond ((= i len) v) (else (vector-set! v i (ref p (* sizeof i))) (loop (+ i 1))))))) (define (setter p v) (define sizeof (size-of-of ?t)) (define set (pointer-set-c!-of ?t)) (let* ((len ?n)) (let loop ((i 0)) (cond ((= i len) v) (else (set p (* sizeof i) (vector-ref v i)) (loop (+ i 1))))))))) (else #'(begin (define (getter p) (define ref (pointer-ref-c-of ?t)) (ref p 0)) (define (setter p v) (define set (pointer-set-c!-of ?t)) (set p 0 v))))) r)))) (syntax-case spec (struct array) (() (reverse! r)) (((type member) rest ...) (continue #'type #'member #f #'(rest ...) #f)) (((struct type member) rest ...) (continue #'type #'member #f #'(rest ...) 'struct)) (((type array elements member) rest ...) (continue #'type #'member #'elements #'(rest ...) 'array)))) (syntax-case x () ((_ name (type rest ...) ...) (with-syntax (((accessors ...) (generate-accessors #'name #'((type rest ...) ...) '()))) #'(begin (define name (let* ((types (type-list (type rest ...) ...)) (max (find-max-size types))) (make-c-struct 'name (list (list uint8_t 'array max (gensym))) #f))) accessors ...)))))) (define c-function-integers `(char short int long long-long intptr_t unsigned-short unsigned-int unsigned-long unsigned-long-long uintptr_t size_t int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t)) (define c-function-return-type-alist `((void . ,FFI_RETURN_TYPE_VOID ) (bool . ,FFI_RETURN_TYPE_BOOL ) (char . ,FFI_RETURN_TYPE_INT8_T ) (short . ,FFI_RETURN_TYPE_SHORT ) (int . ,FFI_RETURN_TYPE_INT ) (long . ,FFI_RETURN_TYPE_LONG ) (long-long . ,FFI_RETURN_TYPE_INT64_T ) (intptr_t . ,FFI_RETURN_TYPE_INTPTR ) (unsigned-short . ,FFI_RETURN_TYPE_USHORT ) (unsigned-int . ,FFI_RETURN_TYPE_UINT ) (unsigned-long . ,FFI_RETURN_TYPE_ULONG ) (unsigned-long-long . ,FFI_RETURN_TYPE_UINT64_T) (uintptr_t . ,FFI_RETURN_TYPE_UINTPTR ) (float . ,FFI_RETURN_TYPE_FLOAT ) (double . ,FFI_RETURN_TYPE_DOUBLE ) (void* . ,FFI_RETURN_TYPE_POINTER ) (char* . ,FFI_RETURN_TYPE_STRING ) (size_t . ,FFI_RETURN_TYPE_SIZE_T ) (int8_t . ,FFI_RETURN_TYPE_INT8_T ) (uint8_t . ,FFI_RETURN_TYPE_UINT8_T ) (int16_t . ,FFI_RETURN_TYPE_INT16_T ) (uint16_t . ,FFI_RETURN_TYPE_UINT16_T) (int32_t . ,FFI_RETURN_TYPE_INT32_T ) (uint32_t . ,FFI_RETURN_TYPE_UINT32_T) (int64_t . ,FFI_RETURN_TYPE_INT64_T ) (uint64_t . ,FFI_RETURN_TYPE_UINT64_T) (wchar_t* . ,FFI_RETURN_TYPE_WCHAR_STR) (callback . ,FFI_RETURN_TYPE_CALLBACK))) (define callback-argument-type-class `((bool . #\l) (char . #\b) (short . #\h) (int . ,(if (= size-of-int 4) #\w #\q)) (long . ,(if (= size-of-long 4) #\w #\q)) (long-long . #\q) (intptr_t . ,(if (= size-of-intptr_t 4) #\w #\q)) (unsigned-char . #\B) (unsigned-short . #\H) (unsigned-int . ,(if (= size-of-int 4) #\W #\Q)) (unsigned-long . ,(if (= size-of-long 4) #\W #\Q)) (unsigned-long-long . #\Q) (uintptr_t . ,(if (= size-of-uintptr_t 4) #\W #\Q)) (int8_t . #\b) (int16_t . #\h) (int32_t . #\w) (int64_t . #\Q) (uint8_t . #\B) (uint16_t . #\H) (uint32_t . #\W) (uint64_t . #\Q) (float . #\f) (double . #\d) (size_t . ,(if (= size-of-size_t 4) #\W #\Q)) (void* . #\p))) (define-class <c-variable> () ((pointer :init-keyword :pointer) (getter :init-keyword :getter) (setter :init-keyword :setter))) (define-method object-apply ((o <c-variable>)) ((slot-ref o 'getter) (slot-ref o 'pointer))) (define-method object-apply ((o <c-variable>)) ((slot-ref o 'getter) (slot-ref o 'pointer))) (define-method object-apply ((o <c-variable>) v) (let ((setter (slot-ref o 'setter))) (if setter (setter (slot-ref o 'pointer) v) (error 'c-variable "variable is immutable" o)))) (define-method (setter object-apply) ((o <c-variable>) v) (o v)) (define-method write-object ((o <c-variable>) out) (format out "#<c-varible ~a>" (slot-ref o 'pointer))) (define (make-c-variable lib name getter setter) (let ((p (lookup-shared-library lib (symbol->string name)))) (make <c-variable> :pointer p :getter getter :setter setter))) (define (c-variable? o) (is-a? o <c-variable>)) (define-syntax c-variable (lambda (x) (define (get-accessor type) (let ((name (symbol->string (syntax->datum type)))) (regex-match-cond ((#/(.+?)_t$/ name) (#f name) (list (string->symbol (string-append "pointer-ref-c-" name)) (string->symbol (string-append "pointer-set-c-" name "!")))) (else (list (string->symbol (string-append "pointer-ref-c-" name)) (string->symbol (string-append "pointer-set-c-" name "!"))))) )) (syntax-case x (char* void* wchar_t*) ((_ lib char* name) #'(c-variable lib name (lambda (p) (pointer->string (deref p 0))) #f)) ((_ lib wchar_t* name) #'(c-variable lib name (lambda (p) (wchar-pointer->string (deref p 0))) #f)) ((_ lib void* name) #'(c-variable lib name (lambda (p) p) #f)) ((_ lib type name) (with-syntax (((getter setter) (datum->syntax #'k (get-accessor #'type)))) #'(c-variable lib name (lambda (p) (getter p 0)) (lambda (p v) (setter p 0 v))))) ((_ lib name getter setter) #'(make-c-variable lib 'name getter setter))))) )
a009575ff3c40ac38f4aba82c68066f7adf11951ffdbd0c2d42ac78d0f85b3ed
Emmanuel-PLF/facile
fcl_reify.ml
(***********************************************************************) (* *) FaCiLe A Functional Constraint Library (* *) , , LOG , CENA (* *) Copyright 2004 CENA . All rights reserved . This file is distributed (* under the terms of the GNU Lesser General Public License. *) (***********************************************************************) $ I d : , v 1.21 2004/08/12 15:22:07 barnier Exp $ open Fcl_var module C = Fcl_cstr let reification c b on_not = let name = "reification" and fprint s = Printf.fprintf s "reification: "; C.fprint s c and delay x = C.self_delay c x; if on_not then (C.self_delay (C.not c)) x; delay [Fd.on_subst] b x and update _0 = match Fd.value b with Val vb -> Fcl_cstr.post (if vb = 0 then (C.not c) else c); true | Unk _ -> try if C.is_solved c || C.check c then begin Fd.unify b 1 end else begin Fd.unify b 0 end; true with Fcl_cstr.DontKnow -> false in C.create ~name ~fprint update delay let cstr ?(delay_on_negation = true) c b = reification c b delay_on_negation;; let boolean ?delay_on_negation c = let b = Fd.create Fcl_domain.boolean in let r = cstr ?delay_on_negation c b in Fcl_cstr.post r; b;; exception MyDontKnow;; let rec (||~~) c1 c2 = let update _0 = C.is_solved c1 || C.is_solved c2 || try if not (C.check c1) then begin (* if c1 is false, c2 must be true *) Fcl_cstr.post c2 end; true with Fcl_cstr.DontKnow -> try if not (C.check c2) then (* if c2 is false, c1 must be true *) Fcl_cstr.post c1; true with Fcl_cstr.DontKnow -> false and fprint s = Printf.fprintf s "("; C.fprint s c1; Printf.fprintf s ") ||~~ ("; C.fprint s c2; Printf.fprintf s ")" and delay c = C.self_delay c1 c; C.self_delay c2 c; C.self_delay (C.not c1) c; C.self_delay (C.not c2) c and check () = C.is_solved c1 || C.is_solved c2 || try (try C.check c1 with Fcl_cstr.DontKnow -> raise MyDontKnow) || C.check c2 with MyDontKnow -> C.check c2 || raise Fcl_cstr.DontKnow and not () = (&&~~) (C.not c1) (C.not c2) in Fcl_cstr.create ~name:"||~~" ~fprint:fprint ~not:not ~check:check update delay and (&&~~) c1 c2 = let update _ = Fcl_cstr.post c1; Fcl_cstr.post c2; true and fprint s = Printf.fprintf s "("; C.fprint s c1; Printf.fprintf s ") &&~~ ("; C.fprint s c2; Printf.fprintf s ")" and delay c = C.self_delay c1 c; C.self_delay c2 c; C.self_delay (C.not c1) c; C.self_delay (C.not c2) c and check () = (C.is_solved c1 || try C.check c1 with Fcl_cstr.DontKnow -> if C.check c2 then raise Fcl_cstr.DontKnow else false ) && (C.is_solved c2 || C.check c2) and not () = (||~~) (C.not c1) (C.not c2) in Fcl_cstr.create ~name:"&&~~" ~fprint:fprint ~not:not ~check:check update delay;; let (=>~~) c1 c2 = C.not c1 ||~~ c2 let rec eq_or_xor c1 c2 equiv = (* if [equiv] then (<=>~~) else (xor~~) *) let update _0 = try Fcl_cstr.post (if C.check c1 = equiv then c2 else C.not c2); true with Fcl_cstr.DontKnow -> (* c1 unknown *) try Fcl_cstr.post (if C.check c2 = equiv then c1 else C.not c1); true with Fcl_cstr.DontKnow -> (* c1 && c2 unknown *) false and delay c = C.self_delay c1 c; C.self_delay c2 c; C.self_delay (C.not c1) c; C.self_delay (C.not c2) c and check _0 = (C.check c1 = C.check c2) = equiv and not () = eq_or_xor c1 c2 (not equiv) in Fcl_cstr.create ~name:(if equiv then "<=>~~" else "xor~~") ~not:not ~check:check update delay;; let (<=>~~) c1 c2 = eq_or_xor c1 c2 true let xor c1 c2 = eq_or_xor c1 c2 false let not c = C.not c
null
https://raw.githubusercontent.com/Emmanuel-PLF/facile/3b6902e479019c25b582042d9a02152fec145eb0/lib/fcl_reify.ml
ocaml
********************************************************************* under the terms of the GNU Lesser General Public License. ********************************************************************* if c1 is false, c2 must be true if c2 is false, c1 must be true if [equiv] then (<=>~~) else (xor~~) c1 unknown c1 && c2 unknown
FaCiLe A Functional Constraint Library , , LOG , CENA Copyright 2004 CENA . All rights reserved . This file is distributed $ I d : , v 1.21 2004/08/12 15:22:07 barnier Exp $ open Fcl_var module C = Fcl_cstr let reification c b on_not = let name = "reification" and fprint s = Printf.fprintf s "reification: "; C.fprint s c and delay x = C.self_delay c x; if on_not then (C.self_delay (C.not c)) x; delay [Fd.on_subst] b x and update _0 = match Fd.value b with Val vb -> Fcl_cstr.post (if vb = 0 then (C.not c) else c); true | Unk _ -> try if C.is_solved c || C.check c then begin Fd.unify b 1 end else begin Fd.unify b 0 end; true with Fcl_cstr.DontKnow -> false in C.create ~name ~fprint update delay let cstr ?(delay_on_negation = true) c b = reification c b delay_on_negation;; let boolean ?delay_on_negation c = let b = Fd.create Fcl_domain.boolean in let r = cstr ?delay_on_negation c b in Fcl_cstr.post r; b;; exception MyDontKnow;; let rec (||~~) c1 c2 = let update _0 = C.is_solved c1 || C.is_solved c2 || try Fcl_cstr.post c2 end; true with Fcl_cstr.DontKnow -> try Fcl_cstr.post c1; true with Fcl_cstr.DontKnow -> false and fprint s = Printf.fprintf s "("; C.fprint s c1; Printf.fprintf s ") ||~~ ("; C.fprint s c2; Printf.fprintf s ")" and delay c = C.self_delay c1 c; C.self_delay c2 c; C.self_delay (C.not c1) c; C.self_delay (C.not c2) c and check () = C.is_solved c1 || C.is_solved c2 || try (try C.check c1 with Fcl_cstr.DontKnow -> raise MyDontKnow) || C.check c2 with MyDontKnow -> C.check c2 || raise Fcl_cstr.DontKnow and not () = (&&~~) (C.not c1) (C.not c2) in Fcl_cstr.create ~name:"||~~" ~fprint:fprint ~not:not ~check:check update delay and (&&~~) c1 c2 = let update _ = Fcl_cstr.post c1; Fcl_cstr.post c2; true and fprint s = Printf.fprintf s "("; C.fprint s c1; Printf.fprintf s ") &&~~ ("; C.fprint s c2; Printf.fprintf s ")" and delay c = C.self_delay c1 c; C.self_delay c2 c; C.self_delay (C.not c1) c; C.self_delay (C.not c2) c and check () = (C.is_solved c1 || try C.check c1 with Fcl_cstr.DontKnow -> if C.check c2 then raise Fcl_cstr.DontKnow else false ) && (C.is_solved c2 || C.check c2) and not () = (||~~) (C.not c1) (C.not c2) in Fcl_cstr.create ~name:"&&~~" ~fprint:fprint ~not:not ~check:check update delay;; let (=>~~) c1 c2 = C.not c1 ||~~ c2 let update _0 = try Fcl_cstr.post (if C.check c1 = equiv then c2 else C.not c2); true with try Fcl_cstr.post (if C.check c2 = equiv then c1 else C.not c1); true with false and delay c = C.self_delay c1 c; C.self_delay c2 c; C.self_delay (C.not c1) c; C.self_delay (C.not c2) c and check _0 = (C.check c1 = C.check c2) = equiv and not () = eq_or_xor c1 c2 (not equiv) in Fcl_cstr.create ~name:(if equiv then "<=>~~" else "xor~~") ~not:not ~check:check update delay;; let (<=>~~) c1 c2 = eq_or_xor c1 c2 true let xor c1 c2 = eq_or_xor c1 c2 false let not c = C.not c
9d4b4f178e098866983fe8799d44cd2655a6f5410cf8473a23ca65abeeaa9375
sheyll/b9-vm-image-builder
ErlangPropList.hs
| Allow reading , merging and writing Erlang terms . module B9.Artifact.Content.ErlangPropList ( ErlangPropList (..), textToErlangAst, stringToErlangAst, ) where import B9.Artifact.Content import B9.Artifact.Content.AST import B9.Artifact.Content.ErlTerms import B9.Artifact.Content.StringTemplate import B9.Text import Control.Parallel.Strategies import Data.Data import Data.Function import Data.Hashable import Data.List (partition, sortBy) import qualified Data.Text as T import GHC.Generics (Generic) import Test.QuickCheck import Text.Printf | A wrapper type around erlang terms with a Semigroup instance useful for combining sys.config files with OTP - application configurations in a list of -- the form of a proplist. newtype ErlangPropList = ErlangPropList SimpleErlangTerm deriving (Read, Eq, Show, Data, Typeable, Generic) instance Hashable ErlangPropList instance NFData ErlangPropList instance Arbitrary ErlangPropList where arbitrary = ErlangPropList <$> arbitrary instance Semigroup ErlangPropList where (ErlangPropList v1) <> (ErlangPropList v2) = ErlangPropList (combine v1 v2) where combine (ErlList l1) (ErlList l2) = ErlList (l1Only <> merged <> l2Only) where l1Only = l1NonPairs <> l1NotL2 l2Only = l2NonPairs <> l2NotL1 (l1Pairs, l1NonPairs) = partition isPair l1 (l2Pairs, l2NonPairs) = partition isPair l2 merged = zipWith merge il1 il2 where merge (ErlTuple [_k, pv1]) (ErlTuple [k, pv2]) = ErlTuple [k, pv1 `combine` pv2] merge _ _ = error "unreachable" (l1NotL2, il1, il2, l2NotL1) = partitionByKey l1Sorted l2Sorted ([], [], [], []) where partitionByKey [] ys (exs, cxs, cys, eys) = (reverse exs, reverse cxs, reverse cys, reverse eys <> ys) partitionByKey xs [] (exs, cxs, cys, eys) = (reverse exs <> xs, reverse cxs, reverse cys, reverse eys) partitionByKey (x : xs) (y : ys) (exs, cxs, cys, eys) | equalKey x y = partitionByKey xs ys (exs, x : cxs, y : cys, eys) | x `keyLessThan` y = partitionByKey xs (y : ys) (x : exs, cxs, cys, eys) | otherwise = partitionByKey (x : xs) ys (exs, cxs, cys, y : eys) l1Sorted = sortByKey l1Pairs l2Sorted = sortByKey l2Pairs sortByKey = sortBy (compare `on` getKey) keyLessThan = (<) `on` getKey equalKey = (==) `on` getKey getKey (ErlTuple (x : _)) = x getKey x = x isPair (ErlTuple [_, _]) = True isPair _ = False combine (ErlList pl1) t2 = ErlList (pl1 <> [t2]) combine t1 (ErlList pl2) = ErlList ([t1] <> pl2) combine t1 t2 = ErlList [t1, t2] instance Textual ErlangPropList where parseFromText txt = do str <- parseFromText txt t <- parseErlTerm "" str return (ErlangPropList t) renderToText (ErlangPropList t) = renderToText (renderErlTerm t) instance FromAST ErlangPropList where fromAST (AST a) = pure a fromAST (ASTObj pairs) = ErlangPropList . ErlList <$> mapM makePair pairs where makePair (k, ast) = do (ErlangPropList second) <- fromAST ast return $ ErlTuple [ErlAtom k, second] fromAST (ASTArr xs) = ErlangPropList . ErlList <$> mapM ( \x -> do (ErlangPropList x') <- fromAST x return x' ) xs fromAST (ASTString s) = pure $ ErlangPropList $ ErlString s fromAST (ASTInt i) = pure $ ErlangPropList $ ErlString (show i) fromAST (ASTEmbed c) = ErlangPropList . ErlString . T.unpack <$> toContentGenerator c fromAST (ASTMerge []) = error "ASTMerge MUST NOT be used with an empty list!" fromAST (ASTMerge asts) = foldl1 (<>) <$> mapM fromAST asts fromAST (ASTParse src@(Source _ srcPath)) = do c <- readTemplateFile src case parseFromTextWithErrorMessage srcPath c of Right s -> return s Left e -> error (printf "could not parse erlang source file: '%s'\n%s\n" srcPath e) -- * Misc. utilities -- | Parse a text containing an @Erlang@ expression ending with a @.@ and Return -- an 'AST'. -- -- @since 0.5.67 textToErlangAst :: Text -> AST c ErlangPropList textToErlangAst txt = either (error . ((unsafeParseFromText txt ++ "\n: ") ++)) AST (parseFromTextWithErrorMessage "textToErlangAst" txt) -- | Parse a string containing an @Erlang@ expression ending with a @.@ and Return -- an 'AST'. -- -- @since 0.5.67 stringToErlangAst :: String -> AST c ErlangPropList stringToErlangAst = textToErlangAst . unsafeRenderToText
null
https://raw.githubusercontent.com/sheyll/b9-vm-image-builder/4d2af80d3be4decfce6c137ee284c961e3f4a396/src/lib/B9/Artifact/Content/ErlangPropList.hs
haskell
the form of a proplist. * Misc. utilities | Parse a text containing an @Erlang@ expression ending with a @.@ and Return an 'AST'. @since 0.5.67 | Parse a string containing an @Erlang@ expression ending with a @.@ and Return an 'AST'. @since 0.5.67
| Allow reading , merging and writing Erlang terms . module B9.Artifact.Content.ErlangPropList ( ErlangPropList (..), textToErlangAst, stringToErlangAst, ) where import B9.Artifact.Content import B9.Artifact.Content.AST import B9.Artifact.Content.ErlTerms import B9.Artifact.Content.StringTemplate import B9.Text import Control.Parallel.Strategies import Data.Data import Data.Function import Data.Hashable import Data.List (partition, sortBy) import qualified Data.Text as T import GHC.Generics (Generic) import Test.QuickCheck import Text.Printf | A wrapper type around erlang terms with a Semigroup instance useful for combining sys.config files with OTP - application configurations in a list of newtype ErlangPropList = ErlangPropList SimpleErlangTerm deriving (Read, Eq, Show, Data, Typeable, Generic) instance Hashable ErlangPropList instance NFData ErlangPropList instance Arbitrary ErlangPropList where arbitrary = ErlangPropList <$> arbitrary instance Semigroup ErlangPropList where (ErlangPropList v1) <> (ErlangPropList v2) = ErlangPropList (combine v1 v2) where combine (ErlList l1) (ErlList l2) = ErlList (l1Only <> merged <> l2Only) where l1Only = l1NonPairs <> l1NotL2 l2Only = l2NonPairs <> l2NotL1 (l1Pairs, l1NonPairs) = partition isPair l1 (l2Pairs, l2NonPairs) = partition isPair l2 merged = zipWith merge il1 il2 where merge (ErlTuple [_k, pv1]) (ErlTuple [k, pv2]) = ErlTuple [k, pv1 `combine` pv2] merge _ _ = error "unreachable" (l1NotL2, il1, il2, l2NotL1) = partitionByKey l1Sorted l2Sorted ([], [], [], []) where partitionByKey [] ys (exs, cxs, cys, eys) = (reverse exs, reverse cxs, reverse cys, reverse eys <> ys) partitionByKey xs [] (exs, cxs, cys, eys) = (reverse exs <> xs, reverse cxs, reverse cys, reverse eys) partitionByKey (x : xs) (y : ys) (exs, cxs, cys, eys) | equalKey x y = partitionByKey xs ys (exs, x : cxs, y : cys, eys) | x `keyLessThan` y = partitionByKey xs (y : ys) (x : exs, cxs, cys, eys) | otherwise = partitionByKey (x : xs) ys (exs, cxs, cys, y : eys) l1Sorted = sortByKey l1Pairs l2Sorted = sortByKey l2Pairs sortByKey = sortBy (compare `on` getKey) keyLessThan = (<) `on` getKey equalKey = (==) `on` getKey getKey (ErlTuple (x : _)) = x getKey x = x isPair (ErlTuple [_, _]) = True isPair _ = False combine (ErlList pl1) t2 = ErlList (pl1 <> [t2]) combine t1 (ErlList pl2) = ErlList ([t1] <> pl2) combine t1 t2 = ErlList [t1, t2] instance Textual ErlangPropList where parseFromText txt = do str <- parseFromText txt t <- parseErlTerm "" str return (ErlangPropList t) renderToText (ErlangPropList t) = renderToText (renderErlTerm t) instance FromAST ErlangPropList where fromAST (AST a) = pure a fromAST (ASTObj pairs) = ErlangPropList . ErlList <$> mapM makePair pairs where makePair (k, ast) = do (ErlangPropList second) <- fromAST ast return $ ErlTuple [ErlAtom k, second] fromAST (ASTArr xs) = ErlangPropList . ErlList <$> mapM ( \x -> do (ErlangPropList x') <- fromAST x return x' ) xs fromAST (ASTString s) = pure $ ErlangPropList $ ErlString s fromAST (ASTInt i) = pure $ ErlangPropList $ ErlString (show i) fromAST (ASTEmbed c) = ErlangPropList . ErlString . T.unpack <$> toContentGenerator c fromAST (ASTMerge []) = error "ASTMerge MUST NOT be used with an empty list!" fromAST (ASTMerge asts) = foldl1 (<>) <$> mapM fromAST asts fromAST (ASTParse src@(Source _ srcPath)) = do c <- readTemplateFile src case parseFromTextWithErrorMessage srcPath c of Right s -> return s Left e -> error (printf "could not parse erlang source file: '%s'\n%s\n" srcPath e) textToErlangAst :: Text -> AST c ErlangPropList textToErlangAst txt = either (error . ((unsafeParseFromText txt ++ "\n: ") ++)) AST (parseFromTextWithErrorMessage "textToErlangAst" txt) stringToErlangAst :: String -> AST c ErlangPropList stringToErlangAst = textToErlangAst . unsafeRenderToText
ae1b654f0a1951863bbafa3aaeb4bf3fe15324e543f04fd4796c89412fefca81
tomgr/libcspm
Wrapper.hs
# LANGUAGE FlexibleContexts # -- | A wrapper around the types and functions from "Data.Graph" to make programming with them less painful. Also implements some extra useful goodies such as ' successors ' and ' ' , and improves the documentation of -- the behaviour of some functions. -- -- As it wraps "Data.Graph", this module only supports directed graphs with unlabelled edges. -- Incorporates code from the ' containers ' package which is ( c ) The University of Glasgow 2002 and based -- on code described in: -- /Lazy Depth - First Search and Linear Graph Algorithms in Haskell/ , by and module Data.Graph.Wrapper ( Edge, Graph, vertex, fromListSimple, fromList, fromListLenient, fromListBy, fromVerticesEdges, toList, vertices, edges, successors, outdegree, indegree, transpose, reachableVertices, hasPath, topologicalSort, depthNumbering, SCC(..), stronglyConnectedComponents, sccGraph, traverseWithKey ) where import Data.Graph.Wrapper.Internal import Control.Arrow (second) import Control.Monad import Control.Monad.ST import Data.Array import Data.Array.ST import qualified Data.Graph as G import qualified Data.IntSet as IS import Data.List (sortBy, mapAccumL) import Data.Maybe (fromMaybe, fromJust, mapMaybe) import qualified Data.Map as M import Data.Ord import qualified Data.Set as S import qualified Data.Foldable as Foldable import qualified Data.Traversable as Traversable fst3 :: (a, b, c) -> a fst3 (a, _, _) = a snd3 :: (a, b, c) -> b snd3 (_, b, _) = b thd3 :: (a, b, c) -> c thd3 (_, _, c) = c -- amapWithKey :: Ix i => (i -> v -> v') -> Array i v -> Array i v' -- More efficient , but not portable ( uses ): --amapWithKey f arr = unsafeArray ' ( bounds ) ( ) [ ( i , f i ( unsafeAt arr i ) ) | i < - [ 0 .. n - 1 ] ] amapWithKey f arr = array ( bounds ) [ ( i , f i v ) | ( i , v ) < - assocs arr ] amapWithKeyM :: (Monad m, Ix i) => (i -> v -> m v') -> Array i v -> m (Array i v') amapWithKeyM f arr = liftM (array (bounds arr)) $ mapM (\(i, v) -> liftM (\v' -> (i, v')) $ f i v) (assocs arr) -- | Construct a 'Graph' where the vertex data double up as the indices. -- Unlike ' Data . Graph.graphFromEdges ' , vertex data that is listed as edges that are not actually themselves -- present in the input list are reported as an error. fromListSimple :: Ord v => [(v, [v])] -> Graph v v fromListSimple = fromListBy id -- | Construct a 'Graph' that contains the given vertex data, linked up according to the supplied key extraction -- function and edge list. -- Unlike ' Data . Graph.graphFromEdges ' , indexes in the edge list that do not correspond to the index of some item in the -- input list are reported as an error. fromListBy :: Ord i => (v -> i) -> [(v, [i])] -> Graph i v fromListBy f vertices = fromList [(f v, v, is) | (v, is) <- vertices] -- | Construct a 'Graph' directly from a list of vertices (and vertex data). -- -- If either end of an 'Edge' does not correspond to a supplied vertex, an error will be raised. fromVerticesEdges :: Ord i => [(i, v)] -> [Edge i] -> Graph i v fromVerticesEdges vertices edges | M.null final_edges_map = fromList done_vertices | otherwise = error "fromVerticesEdges: some edges originated from non-existant vertices" where (final_edges_map, done_vertices) = mapAccumL accum (M.fromListWith (++) (map (second return) edges)) vertices accum edges_map (i, v) = case M.updateLookupWithKey (\_ _ -> Nothing) i edges_map of (mb_is, edges_map) -> (edges_map, (i, v, fromMaybe [] mb_is)) -- | Construct a 'Graph' that contains the given vertex data, linked up according to the supplied index and edge list. -- Unlike ' Data . Graph.graphFromEdges ' , indexes in the edge list that do not correspond to the index of some item in the -- input list are reported as an error. fromList :: Ord i => [(i, v, [i])] -> Graph i v fromList = fromList' False -- | Construct a 'Graph' that contains the given vertex data, linked up according to the supplied index and edge list. -- -- Like 'Data.Graph.graphFromEdges', indexes in the edge list that do not correspond to the index of some item in the -- input list are silently ignored. fromListLenient :: Ord i => [(i, v, [i])] -> Graph i v fromListLenient = fromList' True {-# INLINE fromList' #-} fromList' :: Ord i => Bool -> [(i, v, [i])] -> Graph i v fromList' lenient vertices = G graph key_map vertex_map where max_v = length vertices - 1 bounds0 = (0, max_v) :: (G.Vertex, G.Vertex) sorted_vertices = sortBy (comparing fst3) vertices index_vertex = if lenient then mapMaybe (indexGVertex'_maybe key_map) else map (indexGVertex' key_map) graph = array bounds0 $ [0..] `zip` map (index_vertex . thd3) sorted_vertices key_map = array bounds0 $ [0..] `zip` map fst3 sorted_vertices vertex_map = array bounds0 $ [0..] `zip` map snd3 sorted_vertices -- | Morally, the inverse of 'fromList'. The order of the elements in the output list is unspecified, as is the order of the edges -- in each node's adjacency list. For this reason, @toList . fromList@ is not necessarily the identity function. toList :: Ord i => Graph i v -> [(i, v, [i])] toList g = [(indexGVertexArray g ! m, gVertexVertexArray g ! m, map (indexGVertexArray g !) ns) | (m, ns) <- assocs (graph g)] | Find the vertices we can reach from a vertex with the given indentity successors :: Ord i => Graph i v -> i -> [i] successors g i = map (gVertexIndex g) (graph g ! indexGVertex g i) -- | Number of edges going out of the vertex. -- -- It is worth sharing a partial application of 'outdegree' to the 'Graph' argument if you intend to query -- for the outdegrees of a number of vertices. outdegree :: Ord i => Graph i v -> i -> Int outdegree g = \i -> outdegrees ! indexGVertex g i where outdegrees = G.outdegree (graph g) -- | Number of edges going in to the vertex. -- -- It is worth sharing a partial application of 'indegree' to the 'Graph' argument if you intend to query -- for the indegrees of a number of vertices. indegree :: Ord i => Graph i v -> i -> Int indegree g = \i -> indegrees ! indexGVertex g i where indegrees = G.indegree (graph g) -- | The graph formed by flipping all the edges, so edges from i to j now go from j to i transpose :: Graph i v -> Graph i v transpose g = g { graph = G.transposeG (graph g) } -- | Topological sort of of the graph (<>). If the graph is acyclic, -- vertices will only appear in the list once all of those vertices with arrows to them have already appeared. -- Vertex /i/ precedes /j/ in the output whenever /j/ is reachable from /i/ but not vice versa . topologicalSort :: Graph i v -> [i] topologicalSort g = map (gVertexIndex g) $ G.topSort (graph g) -- | List all of the vertices reachable from the given starting point reachableVertices :: Ord i => Graph i v -> i -> [i] reachableVertices g = map (gVertexIndex g) . G.reachable (graph g) . indexGVertex g | Is the second vertex reachable by following edges from the first vertex ? -- It is worth sharing a partial application of ' hasPath ' to the first vertex if you are testing for several -- vertices being reachable from it. hasPath :: Ord i => Graph i v -> i -> i -> Bool hasPath g i1 = (`elem` reachableVertices g i1) | Number the vertices in the graph by how far away they are from the given roots . The roots themselves have depth 0 , and every subsequent link we traverse adds 1 to the depth . If a vertex is not reachable it will have a depth of ' Nothing ' . depthNumbering :: Ord i => Graph i v -> [i] -> Graph i (v, Maybe Int) depthNumbering g is = runST $ do -- This array records the minimum known depth for the node at the moment depth_array <- newArray (bounds (graph g)) Nothing :: ST s (STArray s G.Vertex (Maybe Int)) let -- Lets us adjust the known depth given a new observation atDepth gv depth = do mb_old_depth <- readArray depth_array gv let depth' = maybe depth (`min` depth) mb_old_depth depth' `seq` writeArray depth_array gv (Just depth') Do an depth - first search on the graph ( checking for cycles to prevent non - termination ) , -- recording the depth at which any node was seen in that array. let gos seen depth gvs = mapM_ (go seen depth) gvs go seen depth gv | depth `seq` False = error "depthNumbering: unreachable" | gv `IS.member` seen = return () | otherwise = do gv `atDepth` depth gos (IS.insert gv seen) (depth + 1) (graph g ! gv) gos IS.empty 0 (map (indexGVertex g) is) -- let go _ _ [] = return () go seen depth = do let go_one ( seen , ) gv | gv ` IS.member ` seen = return ( seen , ) -- | otherwise = do gv `atDepth` depth return ( IS.insert gv seen , next_gvs + + ( graph g ! gv ) ) ( seen , ) < - foldM go_one ( seen , [ ] ) -- go seen (depth + 1) next_gvs -- go IS.empty 0 ( map ( ) is ) gvva <- amapWithKeyM (\gv v -> liftM (\mb_depth -> (v, mb_depth)) $ readArray depth_array gv) (gVertexVertexArray g) return $ g { gVertexVertexArray = gvva } data SCC i = AcyclicSCC i | CyclicSCC [i] deriving (Show) instance Functor SCC where fmap f (AcyclicSCC v) = AcyclicSCC (f v) fmap f (CyclicSCC vs) = CyclicSCC (map f vs) instance Foldable.Foldable SCC where foldMap f (AcyclicSCC v) = f v foldMap f (CyclicSCC vs) = Foldable.foldMap f vs instance Traversable.Traversable SCC where traverse f (AcyclicSCC v) = fmap AcyclicSCC (f v) traverse f (CyclicSCC vs) = fmap CyclicSCC (Traversable.traverse f vs) -- | Strongly connected components (<>). -- The SCCs are listed in a * reverse topological order * . That is to say , any edges * to * a node in the SCC -- originate either *from*: -- 1 ) Within the SCC itself ( in the case of a ' CyclicSCC ' only ) 2 ) Or from a node in a SCC later on in the list -- Vertex /i/ strictly precedes /j/ in the output whenever /i/ is reachable from /j/ but not vice versa . Vertex /i/ occurs in the same SCC as /j/ whenever both /i/ is reachable from /j/ and /j/ is reachable from /i/. stronglyConnectedComponents :: Graph i v -> [SCC i] stronglyConnectedComponents g = map decode forest where forest = G.scc (graph g) decode (G.Node v []) | mentions_itself v = CyclicSCC [gVertexIndex g v] | otherwise = AcyclicSCC (gVertexIndex g v) decode other = CyclicSCC (dec other []) where dec (G.Node v ts) vs = gVertexIndex g v : foldr dec vs ts mentions_itself v = v `elem` (graph g ! v) -- | The graph formed by the strongly connected components of the input graph. Each node in the resulting -- graph is indexed by the set of vertex indices from the input graph that it contains. sccGraph :: Ord i => Graph i v -> Graph (S.Set i) (M.Map i v) sccGraph g = fromList nodes' where As we consume the SCCs , we accumulate a Map i ( S.Set i ) that tells us which SCC any given index belongs to . -- When we do a lookup, it is sufficient to look in the map accumulated so far because nodes that are successors of a SCC must occur to the * left * of it in the list . (_final_i2scc_i, nodes') = mapAccumL go M.empty (stronglyConnectedComponents g) --go :: M.Map i (S.Set i) -> SCC i -> (M.Map i (S.Set i), (S.Set i, M.Map i v, [S.Set i])) go i2scc_i scc = (i2scc_i', (scc_i, Foldable.foldMap (\i -> M.singleton i (vertex g i)) scc, Foldable.foldMap (\i -> map (fromJust . (`M.lookup` i2scc_i')) (successors g i)) scc)) where -- The mechanism by which we index the new graph -- the set of indexes of its components scc_i = Foldable.foldMap S.singleton scc i2scc_i' = i2scc_i `M.union` Foldable.foldMap (\i -> M.singleton i scc_i) scc
null
https://raw.githubusercontent.com/tomgr/libcspm/24d1b41954191a16e3b5e388e35f5ba0915d671e/src/Data/Graph/Wrapper.hs
haskell
| A wrapper around the types and functions from "Data.Graph" to make programming with them less painful. Also the behaviour of some functions. As it wraps "Data.Graph", this module only supports directed graphs with unlabelled edges. on code described in: amapWithKey :: Ix i => (i -> v -> v') -> Array i v -> Array i v' More efficient , but not portable ( uses ): amapWithKey f arr = unsafeArray ' ( bounds ) ( ) [ ( i , f i ( unsafeAt arr i ) ) | i < - [ 0 .. n - 1 ] ] | Construct a 'Graph' where the vertex data double up as the indices. present in the input list are reported as an error. | Construct a 'Graph' that contains the given vertex data, linked up according to the supplied key extraction function and edge list. input list are reported as an error. | Construct a 'Graph' directly from a list of vertices (and vertex data). If either end of an 'Edge' does not correspond to a supplied vertex, an error will be raised. | Construct a 'Graph' that contains the given vertex data, linked up according to the supplied index and edge list. input list are reported as an error. | Construct a 'Graph' that contains the given vertex data, linked up according to the supplied index and edge list. Like 'Data.Graph.graphFromEdges', indexes in the edge list that do not correspond to the index of some item in the input list are silently ignored. # INLINE fromList' # | Morally, the inverse of 'fromList'. The order of the elements in the output list is unspecified, as is the order of the edges in each node's adjacency list. For this reason, @toList . fromList@ is not necessarily the identity function. | Number of edges going out of the vertex. It is worth sharing a partial application of 'outdegree' to the 'Graph' argument if you intend to query for the outdegrees of a number of vertices. | Number of edges going in to the vertex. It is worth sharing a partial application of 'indegree' to the 'Graph' argument if you intend to query for the indegrees of a number of vertices. | The graph formed by flipping all the edges, so edges from i to j now go from j to i | Topological sort of of the graph (<>). If the graph is acyclic, vertices will only appear in the list once all of those vertices with arrows to them have already appeared. | List all of the vertices reachable from the given starting point vertices being reachable from it. This array records the minimum known depth for the node at the moment Lets us adjust the known depth given a new observation recording the depth at which any node was seen in that array. let go _ _ [] = return () | otherwise = do gv `atDepth` depth go seen (depth + 1) next_gvs | Strongly connected components (<>). originate either *from*: | The graph formed by the strongly connected components of the input graph. Each node in the resulting graph is indexed by the set of vertex indices from the input graph that it contains. When we do a lookup, it is sufficient to look in the map accumulated so far because nodes that are successors go :: M.Map i (S.Set i) -> SCC i -> (M.Map i (S.Set i), (S.Set i, M.Map i v, [S.Set i])) The mechanism by which we index the new graph -- the set of indexes of its components
# LANGUAGE FlexibleContexts # implements some extra useful goodies such as ' successors ' and ' ' , and improves the documentation of Incorporates code from the ' containers ' package which is ( c ) The University of Glasgow 2002 and based /Lazy Depth - First Search and Linear Graph Algorithms in Haskell/ , by and module Data.Graph.Wrapper ( Edge, Graph, vertex, fromListSimple, fromList, fromListLenient, fromListBy, fromVerticesEdges, toList, vertices, edges, successors, outdegree, indegree, transpose, reachableVertices, hasPath, topologicalSort, depthNumbering, SCC(..), stronglyConnectedComponents, sccGraph, traverseWithKey ) where import Data.Graph.Wrapper.Internal import Control.Arrow (second) import Control.Monad import Control.Monad.ST import Data.Array import Data.Array.ST import qualified Data.Graph as G import qualified Data.IntSet as IS import Data.List (sortBy, mapAccumL) import Data.Maybe (fromMaybe, fromJust, mapMaybe) import qualified Data.Map as M import Data.Ord import qualified Data.Set as S import qualified Data.Foldable as Foldable import qualified Data.Traversable as Traversable fst3 :: (a, b, c) -> a fst3 (a, _, _) = a snd3 :: (a, b, c) -> b snd3 (_, b, _) = b thd3 :: (a, b, c) -> c thd3 (_, _, c) = c amapWithKey f arr = array ( bounds ) [ ( i , f i v ) | ( i , v ) < - assocs arr ] amapWithKeyM :: (Monad m, Ix i) => (i -> v -> m v') -> Array i v -> m (Array i v') amapWithKeyM f arr = liftM (array (bounds arr)) $ mapM (\(i, v) -> liftM (\v' -> (i, v')) $ f i v) (assocs arr) Unlike ' Data . Graph.graphFromEdges ' , vertex data that is listed as edges that are not actually themselves fromListSimple :: Ord v => [(v, [v])] -> Graph v v fromListSimple = fromListBy id Unlike ' Data . Graph.graphFromEdges ' , indexes in the edge list that do not correspond to the index of some item in the fromListBy :: Ord i => (v -> i) -> [(v, [i])] -> Graph i v fromListBy f vertices = fromList [(f v, v, is) | (v, is) <- vertices] fromVerticesEdges :: Ord i => [(i, v)] -> [Edge i] -> Graph i v fromVerticesEdges vertices edges | M.null final_edges_map = fromList done_vertices | otherwise = error "fromVerticesEdges: some edges originated from non-existant vertices" where (final_edges_map, done_vertices) = mapAccumL accum (M.fromListWith (++) (map (second return) edges)) vertices accum edges_map (i, v) = case M.updateLookupWithKey (\_ _ -> Nothing) i edges_map of (mb_is, edges_map) -> (edges_map, (i, v, fromMaybe [] mb_is)) Unlike ' Data . Graph.graphFromEdges ' , indexes in the edge list that do not correspond to the index of some item in the fromList :: Ord i => [(i, v, [i])] -> Graph i v fromList = fromList' False fromListLenient :: Ord i => [(i, v, [i])] -> Graph i v fromListLenient = fromList' True fromList' :: Ord i => Bool -> [(i, v, [i])] -> Graph i v fromList' lenient vertices = G graph key_map vertex_map where max_v = length vertices - 1 bounds0 = (0, max_v) :: (G.Vertex, G.Vertex) sorted_vertices = sortBy (comparing fst3) vertices index_vertex = if lenient then mapMaybe (indexGVertex'_maybe key_map) else map (indexGVertex' key_map) graph = array bounds0 $ [0..] `zip` map (index_vertex . thd3) sorted_vertices key_map = array bounds0 $ [0..] `zip` map fst3 sorted_vertices vertex_map = array bounds0 $ [0..] `zip` map snd3 sorted_vertices toList :: Ord i => Graph i v -> [(i, v, [i])] toList g = [(indexGVertexArray g ! m, gVertexVertexArray g ! m, map (indexGVertexArray g !) ns) | (m, ns) <- assocs (graph g)] | Find the vertices we can reach from a vertex with the given indentity successors :: Ord i => Graph i v -> i -> [i] successors g i = map (gVertexIndex g) (graph g ! indexGVertex g i) outdegree :: Ord i => Graph i v -> i -> Int outdegree g = \i -> outdegrees ! indexGVertex g i where outdegrees = G.outdegree (graph g) indegree :: Ord i => Graph i v -> i -> Int indegree g = \i -> indegrees ! indexGVertex g i where indegrees = G.indegree (graph g) transpose :: Graph i v -> Graph i v transpose g = g { graph = G.transposeG (graph g) } Vertex /i/ precedes /j/ in the output whenever /j/ is reachable from /i/ but not vice versa . topologicalSort :: Graph i v -> [i] topologicalSort g = map (gVertexIndex g) $ G.topSort (graph g) reachableVertices :: Ord i => Graph i v -> i -> [i] reachableVertices g = map (gVertexIndex g) . G.reachable (graph g) . indexGVertex g | Is the second vertex reachable by following edges from the first vertex ? It is worth sharing a partial application of ' hasPath ' to the first vertex if you are testing for several hasPath :: Ord i => Graph i v -> i -> i -> Bool hasPath g i1 = (`elem` reachableVertices g i1) | Number the vertices in the graph by how far away they are from the given roots . The roots themselves have depth 0 , and every subsequent link we traverse adds 1 to the depth . If a vertex is not reachable it will have a depth of ' Nothing ' . depthNumbering :: Ord i => Graph i v -> [i] -> Graph i (v, Maybe Int) depthNumbering g is = runST $ do depth_array <- newArray (bounds (graph g)) Nothing :: ST s (STArray s G.Vertex (Maybe Int)) atDepth gv depth = do mb_old_depth <- readArray depth_array gv let depth' = maybe depth (`min` depth) mb_old_depth depth' `seq` writeArray depth_array gv (Just depth') Do an depth - first search on the graph ( checking for cycles to prevent non - termination ) , let gos seen depth gvs = mapM_ (go seen depth) gvs go seen depth gv | depth `seq` False = error "depthNumbering: unreachable" | gv `IS.member` seen = return () | otherwise = do gv `atDepth` depth gos (IS.insert gv seen) (depth + 1) (graph g ! gv) gos IS.empty 0 (map (indexGVertex g) is) go seen depth = do let go_one ( seen , ) gv | gv ` IS.member ` seen = return ( seen , ) return ( IS.insert gv seen , next_gvs + + ( graph g ! gv ) ) ( seen , ) < - foldM go_one ( seen , [ ] ) go IS.empty 0 ( map ( ) is ) gvva <- amapWithKeyM (\gv v -> liftM (\mb_depth -> (v, mb_depth)) $ readArray depth_array gv) (gVertexVertexArray g) return $ g { gVertexVertexArray = gvva } data SCC i = AcyclicSCC i | CyclicSCC [i] deriving (Show) instance Functor SCC where fmap f (AcyclicSCC v) = AcyclicSCC (f v) fmap f (CyclicSCC vs) = CyclicSCC (map f vs) instance Foldable.Foldable SCC where foldMap f (AcyclicSCC v) = f v foldMap f (CyclicSCC vs) = Foldable.foldMap f vs instance Traversable.Traversable SCC where traverse f (AcyclicSCC v) = fmap AcyclicSCC (f v) traverse f (CyclicSCC vs) = fmap CyclicSCC (Traversable.traverse f vs) The SCCs are listed in a * reverse topological order * . That is to say , any edges * to * a node in the SCC 1 ) Within the SCC itself ( in the case of a ' CyclicSCC ' only ) 2 ) Or from a node in a SCC later on in the list Vertex /i/ strictly precedes /j/ in the output whenever /i/ is reachable from /j/ but not vice versa . Vertex /i/ occurs in the same SCC as /j/ whenever both /i/ is reachable from /j/ and /j/ is reachable from /i/. stronglyConnectedComponents :: Graph i v -> [SCC i] stronglyConnectedComponents g = map decode forest where forest = G.scc (graph g) decode (G.Node v []) | mentions_itself v = CyclicSCC [gVertexIndex g v] | otherwise = AcyclicSCC (gVertexIndex g v) decode other = CyclicSCC (dec other []) where dec (G.Node v ts) vs = gVertexIndex g v : foldr dec vs ts mentions_itself v = v `elem` (graph g ! v) sccGraph :: Ord i => Graph i v -> Graph (S.Set i) (M.Map i v) sccGraph g = fromList nodes' where As we consume the SCCs , we accumulate a Map i ( S.Set i ) that tells us which SCC any given index belongs to . of a SCC must occur to the * left * of it in the list . (_final_i2scc_i, nodes') = mapAccumL go M.empty (stronglyConnectedComponents g) go i2scc_i scc = (i2scc_i', (scc_i, Foldable.foldMap (\i -> M.singleton i (vertex g i)) scc, Foldable.foldMap (\i -> map (fromJust . (`M.lookup` i2scc_i')) (successors g i)) scc)) where scc_i = Foldable.foldMap S.singleton scc i2scc_i' = i2scc_i `M.union` Foldable.foldMap (\i -> M.singleton i scc_i) scc
328c0512432a7d71e3618e0822ef7bef19c8a8d393f7411a7d1b41365f362a7a
al3623/rippl
natives.ml
module L = Llvm open Ast open Tast open Structs open Lib let eval_t : L.lltype = L.function_type (L.pointer_type i8_t) [| L.pointer_type struct_thunk_type |] let arith_t : L.lltype = L.function_type (L.pointer_type i32_t) [| L.pointer_type struct_thunk_type ; L.pointer_type struct_thunk_type |] let add : L.llvalue = L.declare_function "add" arith_t the_module let add_eval : L.llvalue = L.declare_function "add_eval" eval_t the_module let sub : L.llvalue = L.declare_function "sub" arith_t the_module let sub_eval : L.llvalue = L.declare_function "sub_eval" eval_t the_module let mult : L.llvalue = L.declare_function "mult" arith_t the_module let mult_eval : L.llvalue = L.declare_function "mult_eval" eval_t the_module let neq : L.llvalue = L.declare_function "neq" arith_t the_module let neq_eval : L.llvalue = L.declare_function "neq_eval" eval_t the_module let addf_eval : L.llvalue = L.declare_function "addf_eval" eval_t the_module let addf : L.llvalue = L.declare_function "addf" arith_t the_module
null
https://raw.githubusercontent.com/al3623/rippl/a7e5c24f67935b3513324148279791042856a1fa/src/natives.ml
ocaml
module L = Llvm open Ast open Tast open Structs open Lib let eval_t : L.lltype = L.function_type (L.pointer_type i8_t) [| L.pointer_type struct_thunk_type |] let arith_t : L.lltype = L.function_type (L.pointer_type i32_t) [| L.pointer_type struct_thunk_type ; L.pointer_type struct_thunk_type |] let add : L.llvalue = L.declare_function "add" arith_t the_module let add_eval : L.llvalue = L.declare_function "add_eval" eval_t the_module let sub : L.llvalue = L.declare_function "sub" arith_t the_module let sub_eval : L.llvalue = L.declare_function "sub_eval" eval_t the_module let mult : L.llvalue = L.declare_function "mult" arith_t the_module let mult_eval : L.llvalue = L.declare_function "mult_eval" eval_t the_module let neq : L.llvalue = L.declare_function "neq" arith_t the_module let neq_eval : L.llvalue = L.declare_function "neq_eval" eval_t the_module let addf_eval : L.llvalue = L.declare_function "addf_eval" eval_t the_module let addf : L.llvalue = L.declare_function "addf" arith_t the_module
10d5ac06d6ee8afc4dc7d5077ba7573c9c6f1cf579060eab58d285bc555ee9af
schani/flickr-clojure
flickr_api.clj
;;; flickr_api.clj flickr - clojure --- Flickr API bindings for Clojure Copyright ( C ) 2009 - 2012 ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. (ns at.ac.tuwien.complang.flickr-api (:import [org.apache.xmlrpc.client XmlRpcClient XmlRpcClientConfigImpl] [java.io ByteArrayInputStream]) (:use at.ac.tuwien.complang.utils clojure.xml)) (defmulti persistence-get (fn [p key] (type p))) (defmulti persistence-put (fn [p key val] (type p))) (def ^{:private true} xml-rpc-client (let [config (XmlRpcClientConfigImpl.) client (XmlRpcClient.) url (java.net.URL. "/")] (. config setServerURL url) (. config setConnectionTimeout 2000) (. config setReplyTimeout 15000) (. client setConfig config) client)) (defn- xml-tag [xml] (:tag xml)) (defn- xml-body [xml] (apply str (:content xml))) (defn- xml-children [xml] (:content xml)) (defn- xml-child [tag xml] (first (filter #(= (:tag %) tag) (xml-children xml)))) (defn- xml-attrib [attrib xml] (attrib (:attrs xml))) (defn- xml-follow-path [xml path] (cond (keyword? path) (xml-attrib path xml) (empty? path) xml true (let [f (first path)] (cond (= f :body) (xml-body xml) (= f :attrib) (xml-attrib (second path) xml) (= f :child) (xml-follow-path (xml-child (second path) xml) (rest (rest path))) true (throw (Exception. (str "Illegal XML Path " path))))))) (defn- convert-type [value type] (cond (string? value) (case type :string value :integer (if (empty? value) :unknown (BigInteger. value)) :boolean (if (empty? value) :unknown (not (zero? (BigInteger. value)))) (throw (Exception. (str "Illegal type " type)))) (nil? value) :unknown true (throw (Exception. (str "Value to be converted (" value ") must be string or nil"))))) (defmacro ^{:private true} defapistruct [name & members] (let [parser-name (symbol (str "make-" name)) xml-arg (gensym) member-inits (mapcat (fn [member] (let [[name path & type-list] member type (or (first type-list) :string) member-keyword (keyword (str name))] (if (and (list? path) (#{'fn 'fn*} (first path))) `(~member-keyword (~path ~xml-arg)) `(~member-keyword (convert-type (xml-follow-path ~xml-arg '~path) ~type))))) members)] `(defn- ~parser-name [~xml-arg] (sorted-map ~@member-inits)))) (defapistruct flickr-comment (id :id) (author :author) (authorname :authorname) (date-create :date_create) (permalink :permalink) (text (:body))) (defapistruct flickr-contact (id :nsid) (username :username) (realname :realname) (isfriend :friend :boolean) (isfamily :family :boolean) (ignored :ignored :boolean)) (defapistruct flickr-context-set (id :id) (title :title)) (defapistruct flickr-context-pool (id :id) (title :title)) (defapistruct flickr-favorite (id :id) (owner :owner) (secret :secret) (server :server) (farm :farm) (title :title) (ispublic :ispublic :boolean) (isfriend :isfriend :boolean) (isfamily :isfamily :boolean)) (defapistruct flickr-group (id :id) (title (:child :name :body)) (description (:child :description :body)) (members (:child :members :body) :integer) (privacy (:child :privacy :body))) (defapistruct flickr-url-group (id :id) (title (:child :groupname :body))) (defapistruct flickr-list-group (id :nsid) (title :name) (admin :admin) (eighteenplus :eighteenplus :boolean)) (defapistruct flickr-note (id :id) (author :author) (authorname :authorname) (x :x :integer) (y :y :integer) (w :w :integer) (h :h :integer) (text (:body))) (defapistruct flickr-person (id :nsid) (isadmin :isadmin :boolean) (ispro :ispro :boolean) (iconserver :iconserver) (username (:child :username :body)) (realname (:child :realname :body)) (location (:child :location :body)) (photosurl (:child :photosurl :body)) (profileurl (:child :profileurl :body)) (mobileurl (:child :mobileurl :body)) (firstdate (:child :photos :child :firstdate :body)) (firstdatetaken (:child :photos :child :firstdatetaken :body)) (count (:child :photos :child :count :body) :integer)) (defapistruct flickr-photoset (id :id) (primary :primary) (photos :photos) (secret :secret) (server :server) (title (:child :title :body)) (description (:child :description :body))) (defapistruct flickr-photoset-info (id :id) (owner :owner) (primary :primary) (photos :photos) (title (:child :title :body)) (description (:child :description :body))) (defapistruct flickr-photoset-photo (id :id) (secret :secret) (server :server) (farm :farm) (title :title) (isprimary :isprimary :boolean)) (defapistruct flickr-public-contact (id :nsid) (username :username) (ignored :ignored :boolean)) (defapistruct flickr-search-photo (id :id) (owner :owner) (secret :secret) (server :server) (farm :farm) (title :title) (ispublic :ispublic :boolean) (isfriend :isfriend :boolean) (isfamily :isfamily :boolean)) (defapistruct flickr-size (label :label) (width :width :integer) (height :height :integer) (source :source) (url :url)) (defapistruct flickr-tag (id :id) (author :author) (raw :raw) (machine-tag :machine_tag :boolean) (text (:body))) (defapistruct flickr-url (type :type) (url (:body))) (defapistruct flickr-user (id :nsid) (username (:child :username :body))) (defapistruct flickr-url-user (id :id) (username (:child :username :body))) ;; Uses flickr-not, flickr-tag and flickr-url, so must come after ;; them. (defapistruct flickr-full-photo (id :id) (secret :secret) (server :server) (farm :farm) (isfavorite :isfavorite :boolean) (license :license) (rotation :rotation) (owner (:child :owner :attrib :nsid)) (title (:child :title :body)) (description (:child :description :body)) (ispublic (:child :visibility :attrib :ispublic) :boolean) (isfriend (:child :visibility :attrib :isfriend) :boolean) (isfamily (:child :visibility :attrib :isfamily) :boolean) (posted (:child :dates :attrib :posted)) (taken (:child :dates :attrib :taken)) (takengranularity (:child :dates :attrib :takengranularity)) (lastupdate (:child :dates :attrib :lastupdate)) (permcomment (:child :permissions :attrib :permcomment) :boolean) (permaddmeta (:child :permissions :attrib :permaddmeta) :boolean) (cancomment (:child :editability :attrib :cancomment) :boolean) (canaddmeta (:child :editability :attrib :canaddmeta) :boolean) (comments (:child :comments :attrib :body) :integer) (notes (fn [xml] (map make-flickr-note (xml-children (xml-child :notes xml))))) (tags (fn [xml] (map make-flickr-tag (xml-children (xml-child :tags xml))))) (urls (fn [xml] (map make-flickr-url (xml-children (xml-child :urls xml)))))) (defn- parse-xml-from-string [string] (let [stream (ByteArrayInputStream. (. string getBytes "UTF-8"))] (parse stream))) (defn- call-args-string [args] (let [keys (sort (keys args))] (reduce str (map (fn [k] (str k (get args k))) keys)))) (defn- arguments-signature-source [api-info args] (str (:shared-secret api-info) (call-args-string args))) (defn- arguments-signature [api-info args] (md5-sum (arguments-signature-source api-info args))) (defn- full-call-args [api-info method args] (let [full-args (reduce into (list {"api_key" (:api-key api-info)} (if-let [auth-token (:token api-info)] {"auth_token" auth-token} {}) args))] (assoc full-args "api_sig" (arguments-signature api-info full-args)))) (defn- lookup-call [api-info method args] (if-let [persistence (:persistence api-info)] (persistence-get persistence (str method (call-args-string args))) nil)) (defn- memoize-call [api-info method args result] (when-let [persistence (:persistence api-info)] (persistence-put persistence (str method (call-args-string args)) result))) (def *print-calls* false) (defn- make-flickr-call [api-info method persistent string-modifier args] (if-let [result (and persistent (lookup-call api-info method args))] (parse-xml-from-string (string-modifier result)) (do (when *print-calls* (printf "making call to %s with args %s\n" method (str args)) (flush)) (let [full-args (full-call-args api-info method args) result (. xml-rpc-client execute method [full-args])] (when persistent (memoize-call api-info method args result)) (parse-xml-from-string (string-modifier result)))))) (defn- lispify-method-name [string] (apply str (mapcat (fn [c] (cond (= c \.) "-" (. Character isUpperCase c) (list \- (. Character toLowerCase c)) true (list c))) string))) (defmacro ^{:private true} defcall [name-string args persistence & body] (let [full-method-name-string (str "flickr." name-string) fun-name (symbol (lispify-method-name name-string)) persistent (= persistence :persistent)] `(defn ~fun-name [~'api-info ~@args] (let [~'call (fn [& args#] (make-flickr-call ~'api-info ~full-method-name-string ~persistent identity (apply sorted-map args#))) ~'call-with-string-modifier (fn [modifier# & args#] (make-flickr-call ~'api-info ~full-method-name-string ~persistent modifier# (apply sorted-map args#)))] ~@body)))) ;; returns a list of the items, the total number of pages, and the ;; total number of items. (defn- multi-page-call [call-fun make-fun per-page page & args] (let [result (apply call-fun "per_page" (str per-page) "page" (str page) args)] {:items (map make-fun (xml-children result)) :pages (convert-type (xml-attrib :pages result) :integer) :total (convert-type (xml-attrib :total result) :integer)})) (defcall "auth.getFrob" [] :not-persistent (xml-body (call))) ;; returns the token, the permission string, and the user (defcall "auth.getToken" [] :not-persistent (let [result (call "frob" (:frob api-info))] {:token (xml-body (xml-child :token result)) :perms (xml-body (xml-child :perms result)) :user (let [child (xml-child :user result)] {:nsid (xml-attrib :nsid child) :username (xml-attrib :username child)})})) (defcall "contacts.getList" [filter per-page page] :persistent (if (nil? filter) (multi-page-call call make-flickr-contact per-page page) (multi-page-call call make-flickr-contact per-page page "filter" filter))) (defcall "contacts.getPublicList" [nsid per-page page] :persistent (multi-page-call call make-flickr-public-contact per-page page "user_id" nsid)) (defcall "favorites.getList" [nsid per-page page] :persistent (multi-page-call call make-flickr-favorite per-page page "user_id" nsid)) (defcall "favorites.getPublicList" [nsid per-page page] :persistent (multi-page-call call make-flickr-favorite per-page page "user_id" nsid)) (defcall "groups.getInfo" [group-id] :persistent (make-flickr-group (call "group_id" group-id))) (defcall "groups.pools.add" [photo-id group-id] :not-persistent (call "photo_id" photo-id "group_id" group-id)) (defcall "groups.pools.getPhotos" [group-id per-page page tags] :persistent (if (nil? tags) (multi-page-call call make-flickr-search-photo per-page page "group_id" group-id) (multi-page-call call make-flickr-search-photo per-page page "group_id" group-id "tags" tags))) (defcall "groups.pools.remove" [photo-id group-id] :not-persistent (call "group_id" group-id "photo_id" photo-id)) (defcall "people.findByUsername" [name] :persistent (make-flickr-user (call "username" name))) (defcall "people.getInfo" [nsid] :persistent (make-flickr-person (call "user_id" nsid))) (defcall "people.getPublicGroups" [nsid] :persistent (let [result (call "user_id" nsid)] (map make-flickr-list-group (xml-children result)))) (defcall "photos.addTags" [photo-id tags] :not-persistent (let [tags-string (apply str (interpose " " (map #(str \" % \") tags)))] (call "photo_id" photo-id "tags" tags-string))) (defcall "photos.comments.getList" [photo-id] :persistent (let [result (call "photo_id" photo-id)] (map make-flickr-comment (xml-children result)))) (defcall "photos.getAllContexts" [photo-id] :persistent (let [result (call-with-string-modifier #(str "<list>" % "</list>") "photo_id" photo-id)] (map (fn [item] (case (xml-tag item) :set (assoc (make-flickr-context-set item) :type :set) :pool (assoc (make-flickr-context-pool item) :type :pool) (throw (Exception. (str "invalid context tag " (xml-tag item)))))) (xml-children result)))) (defcall "photos.getInfo" [photo-id & secret] :persistent (make-flickr-full-photo (if (empty? secret) (call "photo_id" photo-id) (call "photo_id" photo-id "secret" (first secret))))) (defcall "photos.getSizes" [photo-id] :persistent (map make-flickr-size (xml-children (call "photo_id" photo-id)))) (defcall "photos.removeTag" [tag-id] :not-persistent (call "tag_id" tag-id)) (defcall "photos.search" [per-page page & keyvals] :persistent (let [keyvals-map (apply hash-map keyvals) optional-args (mapcat #(if-let [value ((key %) keyvals-map)] (list (val %) value) ()) {:user-id "user_id" :tags "tags" :tag-mode "tag_mode" :text "text" :min-upload-data "min_upload_date" :max-upload-date "max_upload_date" :min-taken-date "min_taken_date" :max-taken-date "max_taken_date" :licence "licence" :sort "sort"})] (apply multi-page-call call make-flickr-search-photo per-page page optional-args))) (defcall "photosets.getInfo" [photoset-id] :persistent (make-flickr-photoset-info (call "photoset_id" photoset-id))) (defcall "photosets.getList" [user-id] :persistent (let [result (call "user_id" user-id)] (map make-flickr-photoset (xml-children result)))) (defcall "photosets.getPhotos" [photoset-id] :persistent (let [result (call "photoset_id" photoset-id)] (map make-flickr-photoset-photo (xml-children result)))) (defcall "test.echo" [] :not-persistent (call-with-string-modifier #(str "<list>" % "</list>"))) (defcall "test.login" [] :not-persistent (call)) (defcall "urls.lookupGroup" [url] :persistent (make-flickr-url-group (call "url" url))) (defcall "urls.lookupUser" [url] :persistent (make-flickr-url-user (call "url" url))) (defn api-request-authorization [api-key shared-secret] (let [api-info {:api-key api-key :shared-secret shared-secret} frob (auth-get-frob api-info) api-info (assoc api-info :frob frob) perms "write" api-sig (arguments-signature api-info {"api_key" api-key "perms" perms "frob" frob}) url (format "" api-key perms frob api-sig)] {:api-info api-info :url url})) (defn api-complete-authorization [api-info persistence] (merge api-info (auth-get-token api-info) {:persistence persistence})) (defn collect-pages [fetcher per-page first] (lazy-seq (let [previous-total (* per-page (dec first)) {items :items pages :pages total :total} (fetcher per-page first)] (if (<= total (+ previous-total (count items))) items (concat items (collect-pages fetcher per-page (inc first)))))))
null
https://raw.githubusercontent.com/schani/flickr-clojure/be4739cc4300a593b4688d56ccebcbab70eb3352/src/at/ac/tuwien/complang/flickr_api.clj
clojure
flickr_api.clj This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. Uses flickr-not, flickr-tag and flickr-url, so must come after them. returns a list of the items, the total number of pages, and the total number of items. returns the token, the permission string, and the user
flickr - clojure --- Flickr API bindings for Clojure Copyright ( C ) 2009 - 2012 it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (ns at.ac.tuwien.complang.flickr-api (:import [org.apache.xmlrpc.client XmlRpcClient XmlRpcClientConfigImpl] [java.io ByteArrayInputStream]) (:use at.ac.tuwien.complang.utils clojure.xml)) (defmulti persistence-get (fn [p key] (type p))) (defmulti persistence-put (fn [p key val] (type p))) (def ^{:private true} xml-rpc-client (let [config (XmlRpcClientConfigImpl.) client (XmlRpcClient.) url (java.net.URL. "/")] (. config setServerURL url) (. config setConnectionTimeout 2000) (. config setReplyTimeout 15000) (. client setConfig config) client)) (defn- xml-tag [xml] (:tag xml)) (defn- xml-body [xml] (apply str (:content xml))) (defn- xml-children [xml] (:content xml)) (defn- xml-child [tag xml] (first (filter #(= (:tag %) tag) (xml-children xml)))) (defn- xml-attrib [attrib xml] (attrib (:attrs xml))) (defn- xml-follow-path [xml path] (cond (keyword? path) (xml-attrib path xml) (empty? path) xml true (let [f (first path)] (cond (= f :body) (xml-body xml) (= f :attrib) (xml-attrib (second path) xml) (= f :child) (xml-follow-path (xml-child (second path) xml) (rest (rest path))) true (throw (Exception. (str "Illegal XML Path " path))))))) (defn- convert-type [value type] (cond (string? value) (case type :string value :integer (if (empty? value) :unknown (BigInteger. value)) :boolean (if (empty? value) :unknown (not (zero? (BigInteger. value)))) (throw (Exception. (str "Illegal type " type)))) (nil? value) :unknown true (throw (Exception. (str "Value to be converted (" value ") must be string or nil"))))) (defmacro ^{:private true} defapistruct [name & members] (let [parser-name (symbol (str "make-" name)) xml-arg (gensym) member-inits (mapcat (fn [member] (let [[name path & type-list] member type (or (first type-list) :string) member-keyword (keyword (str name))] (if (and (list? path) (#{'fn 'fn*} (first path))) `(~member-keyword (~path ~xml-arg)) `(~member-keyword (convert-type (xml-follow-path ~xml-arg '~path) ~type))))) members)] `(defn- ~parser-name [~xml-arg] (sorted-map ~@member-inits)))) (defapistruct flickr-comment (id :id) (author :author) (authorname :authorname) (date-create :date_create) (permalink :permalink) (text (:body))) (defapistruct flickr-contact (id :nsid) (username :username) (realname :realname) (isfriend :friend :boolean) (isfamily :family :boolean) (ignored :ignored :boolean)) (defapistruct flickr-context-set (id :id) (title :title)) (defapistruct flickr-context-pool (id :id) (title :title)) (defapistruct flickr-favorite (id :id) (owner :owner) (secret :secret) (server :server) (farm :farm) (title :title) (ispublic :ispublic :boolean) (isfriend :isfriend :boolean) (isfamily :isfamily :boolean)) (defapistruct flickr-group (id :id) (title (:child :name :body)) (description (:child :description :body)) (members (:child :members :body) :integer) (privacy (:child :privacy :body))) (defapistruct flickr-url-group (id :id) (title (:child :groupname :body))) (defapistruct flickr-list-group (id :nsid) (title :name) (admin :admin) (eighteenplus :eighteenplus :boolean)) (defapistruct flickr-note (id :id) (author :author) (authorname :authorname) (x :x :integer) (y :y :integer) (w :w :integer) (h :h :integer) (text (:body))) (defapistruct flickr-person (id :nsid) (isadmin :isadmin :boolean) (ispro :ispro :boolean) (iconserver :iconserver) (username (:child :username :body)) (realname (:child :realname :body)) (location (:child :location :body)) (photosurl (:child :photosurl :body)) (profileurl (:child :profileurl :body)) (mobileurl (:child :mobileurl :body)) (firstdate (:child :photos :child :firstdate :body)) (firstdatetaken (:child :photos :child :firstdatetaken :body)) (count (:child :photos :child :count :body) :integer)) (defapistruct flickr-photoset (id :id) (primary :primary) (photos :photos) (secret :secret) (server :server) (title (:child :title :body)) (description (:child :description :body))) (defapistruct flickr-photoset-info (id :id) (owner :owner) (primary :primary) (photos :photos) (title (:child :title :body)) (description (:child :description :body))) (defapistruct flickr-photoset-photo (id :id) (secret :secret) (server :server) (farm :farm) (title :title) (isprimary :isprimary :boolean)) (defapistruct flickr-public-contact (id :nsid) (username :username) (ignored :ignored :boolean)) (defapistruct flickr-search-photo (id :id) (owner :owner) (secret :secret) (server :server) (farm :farm) (title :title) (ispublic :ispublic :boolean) (isfriend :isfriend :boolean) (isfamily :isfamily :boolean)) (defapistruct flickr-size (label :label) (width :width :integer) (height :height :integer) (source :source) (url :url)) (defapistruct flickr-tag (id :id) (author :author) (raw :raw) (machine-tag :machine_tag :boolean) (text (:body))) (defapistruct flickr-url (type :type) (url (:body))) (defapistruct flickr-user (id :nsid) (username (:child :username :body))) (defapistruct flickr-url-user (id :id) (username (:child :username :body))) (defapistruct flickr-full-photo (id :id) (secret :secret) (server :server) (farm :farm) (isfavorite :isfavorite :boolean) (license :license) (rotation :rotation) (owner (:child :owner :attrib :nsid)) (title (:child :title :body)) (description (:child :description :body)) (ispublic (:child :visibility :attrib :ispublic) :boolean) (isfriend (:child :visibility :attrib :isfriend) :boolean) (isfamily (:child :visibility :attrib :isfamily) :boolean) (posted (:child :dates :attrib :posted)) (taken (:child :dates :attrib :taken)) (takengranularity (:child :dates :attrib :takengranularity)) (lastupdate (:child :dates :attrib :lastupdate)) (permcomment (:child :permissions :attrib :permcomment) :boolean) (permaddmeta (:child :permissions :attrib :permaddmeta) :boolean) (cancomment (:child :editability :attrib :cancomment) :boolean) (canaddmeta (:child :editability :attrib :canaddmeta) :boolean) (comments (:child :comments :attrib :body) :integer) (notes (fn [xml] (map make-flickr-note (xml-children (xml-child :notes xml))))) (tags (fn [xml] (map make-flickr-tag (xml-children (xml-child :tags xml))))) (urls (fn [xml] (map make-flickr-url (xml-children (xml-child :urls xml)))))) (defn- parse-xml-from-string [string] (let [stream (ByteArrayInputStream. (. string getBytes "UTF-8"))] (parse stream))) (defn- call-args-string [args] (let [keys (sort (keys args))] (reduce str (map (fn [k] (str k (get args k))) keys)))) (defn- arguments-signature-source [api-info args] (str (:shared-secret api-info) (call-args-string args))) (defn- arguments-signature [api-info args] (md5-sum (arguments-signature-source api-info args))) (defn- full-call-args [api-info method args] (let [full-args (reduce into (list {"api_key" (:api-key api-info)} (if-let [auth-token (:token api-info)] {"auth_token" auth-token} {}) args))] (assoc full-args "api_sig" (arguments-signature api-info full-args)))) (defn- lookup-call [api-info method args] (if-let [persistence (:persistence api-info)] (persistence-get persistence (str method (call-args-string args))) nil)) (defn- memoize-call [api-info method args result] (when-let [persistence (:persistence api-info)] (persistence-put persistence (str method (call-args-string args)) result))) (def *print-calls* false) (defn- make-flickr-call [api-info method persistent string-modifier args] (if-let [result (and persistent (lookup-call api-info method args))] (parse-xml-from-string (string-modifier result)) (do (when *print-calls* (printf "making call to %s with args %s\n" method (str args)) (flush)) (let [full-args (full-call-args api-info method args) result (. xml-rpc-client execute method [full-args])] (when persistent (memoize-call api-info method args result)) (parse-xml-from-string (string-modifier result)))))) (defn- lispify-method-name [string] (apply str (mapcat (fn [c] (cond (= c \.) "-" (. Character isUpperCase c) (list \- (. Character toLowerCase c)) true (list c))) string))) (defmacro ^{:private true} defcall [name-string args persistence & body] (let [full-method-name-string (str "flickr." name-string) fun-name (symbol (lispify-method-name name-string)) persistent (= persistence :persistent)] `(defn ~fun-name [~'api-info ~@args] (let [~'call (fn [& args#] (make-flickr-call ~'api-info ~full-method-name-string ~persistent identity (apply sorted-map args#))) ~'call-with-string-modifier (fn [modifier# & args#] (make-flickr-call ~'api-info ~full-method-name-string ~persistent modifier# (apply sorted-map args#)))] ~@body)))) (defn- multi-page-call [call-fun make-fun per-page page & args] (let [result (apply call-fun "per_page" (str per-page) "page" (str page) args)] {:items (map make-fun (xml-children result)) :pages (convert-type (xml-attrib :pages result) :integer) :total (convert-type (xml-attrib :total result) :integer)})) (defcall "auth.getFrob" [] :not-persistent (xml-body (call))) (defcall "auth.getToken" [] :not-persistent (let [result (call "frob" (:frob api-info))] {:token (xml-body (xml-child :token result)) :perms (xml-body (xml-child :perms result)) :user (let [child (xml-child :user result)] {:nsid (xml-attrib :nsid child) :username (xml-attrib :username child)})})) (defcall "contacts.getList" [filter per-page page] :persistent (if (nil? filter) (multi-page-call call make-flickr-contact per-page page) (multi-page-call call make-flickr-contact per-page page "filter" filter))) (defcall "contacts.getPublicList" [nsid per-page page] :persistent (multi-page-call call make-flickr-public-contact per-page page "user_id" nsid)) (defcall "favorites.getList" [nsid per-page page] :persistent (multi-page-call call make-flickr-favorite per-page page "user_id" nsid)) (defcall "favorites.getPublicList" [nsid per-page page] :persistent (multi-page-call call make-flickr-favorite per-page page "user_id" nsid)) (defcall "groups.getInfo" [group-id] :persistent (make-flickr-group (call "group_id" group-id))) (defcall "groups.pools.add" [photo-id group-id] :not-persistent (call "photo_id" photo-id "group_id" group-id)) (defcall "groups.pools.getPhotos" [group-id per-page page tags] :persistent (if (nil? tags) (multi-page-call call make-flickr-search-photo per-page page "group_id" group-id) (multi-page-call call make-flickr-search-photo per-page page "group_id" group-id "tags" tags))) (defcall "groups.pools.remove" [photo-id group-id] :not-persistent (call "group_id" group-id "photo_id" photo-id)) (defcall "people.findByUsername" [name] :persistent (make-flickr-user (call "username" name))) (defcall "people.getInfo" [nsid] :persistent (make-flickr-person (call "user_id" nsid))) (defcall "people.getPublicGroups" [nsid] :persistent (let [result (call "user_id" nsid)] (map make-flickr-list-group (xml-children result)))) (defcall "photos.addTags" [photo-id tags] :not-persistent (let [tags-string (apply str (interpose " " (map #(str \" % \") tags)))] (call "photo_id" photo-id "tags" tags-string))) (defcall "photos.comments.getList" [photo-id] :persistent (let [result (call "photo_id" photo-id)] (map make-flickr-comment (xml-children result)))) (defcall "photos.getAllContexts" [photo-id] :persistent (let [result (call-with-string-modifier #(str "<list>" % "</list>") "photo_id" photo-id)] (map (fn [item] (case (xml-tag item) :set (assoc (make-flickr-context-set item) :type :set) :pool (assoc (make-flickr-context-pool item) :type :pool) (throw (Exception. (str "invalid context tag " (xml-tag item)))))) (xml-children result)))) (defcall "photos.getInfo" [photo-id & secret] :persistent (make-flickr-full-photo (if (empty? secret) (call "photo_id" photo-id) (call "photo_id" photo-id "secret" (first secret))))) (defcall "photos.getSizes" [photo-id] :persistent (map make-flickr-size (xml-children (call "photo_id" photo-id)))) (defcall "photos.removeTag" [tag-id] :not-persistent (call "tag_id" tag-id)) (defcall "photos.search" [per-page page & keyvals] :persistent (let [keyvals-map (apply hash-map keyvals) optional-args (mapcat #(if-let [value ((key %) keyvals-map)] (list (val %) value) ()) {:user-id "user_id" :tags "tags" :tag-mode "tag_mode" :text "text" :min-upload-data "min_upload_date" :max-upload-date "max_upload_date" :min-taken-date "min_taken_date" :max-taken-date "max_taken_date" :licence "licence" :sort "sort"})] (apply multi-page-call call make-flickr-search-photo per-page page optional-args))) (defcall "photosets.getInfo" [photoset-id] :persistent (make-flickr-photoset-info (call "photoset_id" photoset-id))) (defcall "photosets.getList" [user-id] :persistent (let [result (call "user_id" user-id)] (map make-flickr-photoset (xml-children result)))) (defcall "photosets.getPhotos" [photoset-id] :persistent (let [result (call "photoset_id" photoset-id)] (map make-flickr-photoset-photo (xml-children result)))) (defcall "test.echo" [] :not-persistent (call-with-string-modifier #(str "<list>" % "</list>"))) (defcall "test.login" [] :not-persistent (call)) (defcall "urls.lookupGroup" [url] :persistent (make-flickr-url-group (call "url" url))) (defcall "urls.lookupUser" [url] :persistent (make-flickr-url-user (call "url" url))) (defn api-request-authorization [api-key shared-secret] (let [api-info {:api-key api-key :shared-secret shared-secret} frob (auth-get-frob api-info) api-info (assoc api-info :frob frob) perms "write" api-sig (arguments-signature api-info {"api_key" api-key "perms" perms "frob" frob}) url (format "" api-key perms frob api-sig)] {:api-info api-info :url url})) (defn api-complete-authorization [api-info persistence] (merge api-info (auth-get-token api-info) {:persistence persistence})) (defn collect-pages [fetcher per-page first] (lazy-seq (let [previous-total (* per-page (dec first)) {items :items pages :pages total :total} (fetcher per-page first)] (if (<= total (+ previous-total (count items))) items (concat items (collect-pages fetcher per-page (inc first)))))))
30b7ff4cd7a60aa88101f97345ba8f25849b1861b3457e27a66037a6b0a5341f
cram2/cram
higher-moments.lisp
;; Skewness and kurtosis. , Sun Dec 31 2006 - 14:20 Time - stamp : < 2014 - 12 - 26 13:16:00EST higher-moments.lisp > ;; Copyright 2006 , 2007 , 2008 , 2009 , 2011 , 2012 , 2014 Distributed under the terms of the GNU General Public License ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. (in-package :gsl) (named-readtables:in-readtable :antik) To do : stride other than 1 when that information is availble from ;;; the vector. (defmfun skewness ((data vector) &optional mean standard-deviation) (("gsl_stats" :type "_skew") ("gsl_stats" :type "_skew_m_sd")) ((((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :no-complex :c-return :double :inputs (data) "The skewness of data, defined as skew = (1/N) \sum ((x_i - \Hat\mu)/\Hat\sigma)^3 where x_i are the elements of the dataset data. The skewness measures the asymmetry of the tails of a distribution. If mean and standard deviation are supplied, compute skewness of the dataset data using the given values skew = (1/N) \sum ((x_i - mean)/sd)^3. This is useful if you have already computed the mean and standard deviation of data and want to avoid recomputing them.") (defmfun kurtosis ((data vector) &optional mean standard-deviation) (("gsl_stats" :type "_kurtosis") ("gsl_stats" :type "_kurtosis_m_sd")) ((((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :no-complex :c-return :double :inputs (data) "The kurtosis of data defined as kurtosis = ((1/N) \sum ((x_i - \Hat\mu)/\Hat\sigma)^4) - 3 The kurtosis measures how sharply peaked a distribution is, relative to its width. The kurtosis is normalized to zero for a gaussian distribution.") (defmfun weighted-skewness ((data vector) (weights vector) &optional mean standard-deviation) (("gsl_stats" :type "_wskew") ("gsl_stats" :type "_wskew_m_sd")) ((((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :float :c-return :double :inputs (data weights) "The weighted skewness of the dataset. skew = (\sum w_i ((x_i - xbar)/\sigma)^3) / (\sum w_i).") (defmfun weighted-kurtosis ((data vector) (weights vector) &optional mean standard-deviation) (("gsl_stats" :type "_wkurtosis") ("gsl_stats" :type "_wkurtosis_m_sd")) ((((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :float :c-return :double :inputs (data weights) "The weighted kurtosis of the dataset. kurtosis = ((\sum w_i ((x_i - xbar)/sigma)^4) / (\sum w_i)) - 3.") ;;; Examples and unit test (save-test higher-moments (let ((vec #m(-3.21d0 1.0d0 12.8d0))) (let* ((mean (mean vec)) (sd (standard-deviation vec mean))) (list (skewness vec) (skewness vec mean sd) (kurtosis vec) (kurtosis vec mean sd)))))
null
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/statistics/higher-moments.lisp
lisp
Skewness and kurtosis. This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. the vector. Examples and unit test
, Sun Dec 31 2006 - 14:20 Time - stamp : < 2014 - 12 - 26 13:16:00EST higher-moments.lisp > Copyright 2006 , 2007 , 2008 , 2009 , 2011 , 2012 , 2014 Distributed under the terms of the GNU General Public License it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (in-package :gsl) (named-readtables:in-readtable :antik) To do : stride other than 1 when that information is availble from (defmfun skewness ((data vector) &optional mean standard-deviation) (("gsl_stats" :type "_skew") ("gsl_stats" :type "_skew_m_sd")) ((((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :no-complex :c-return :double :inputs (data) "The skewness of data, defined as skew = (1/N) \sum ((x_i - \Hat\mu)/\Hat\sigma)^3 where x_i are the elements of the dataset data. The skewness measures the asymmetry of the tails of a distribution. If mean and standard deviation are supplied, compute skewness of the dataset data using the given values skew = (1/N) \sum ((x_i - mean)/sd)^3. This is useful if you have already computed the mean and standard deviation of data and want to avoid recomputing them.") (defmfun kurtosis ((data vector) &optional mean standard-deviation) (("gsl_stats" :type "_kurtosis") ("gsl_stats" :type "_kurtosis_m_sd")) ((((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :no-complex :c-return :double :inputs (data) "The kurtosis of data defined as kurtosis = ((1/N) \sum ((x_i - \Hat\mu)/\Hat\sigma)^4) - 3 The kurtosis measures how sharply peaked a distribution is, relative to its width. The kurtosis is normalized to zero for a gaussian distribution.") (defmfun weighted-skewness ((data vector) (weights vector) &optional mean standard-deviation) (("gsl_stats" :type "_wskew") ("gsl_stats" :type "_wskew_m_sd")) ((((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :float :c-return :double :inputs (data weights) "The weighted skewness of the dataset. skew = (\sum w_i ((x_i - xbar)/\sigma)^3) / (\sum w_i).") (defmfun weighted-kurtosis ((data vector) (weights vector) &optional mean standard-deviation) (("gsl_stats" :type "_wkurtosis") ("gsl_stats" :type "_wkurtosis_m_sd")) ((((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet)) (((grid:foreign-pointer weights) :pointer) (1 :int) ((grid:foreign-pointer data) :pointer) (1 :int) ((dim0 data) :sizet) (mean :double) (standard-deviation :double))) :definition :generic :element-types :float :c-return :double :inputs (data weights) "The weighted kurtosis of the dataset. kurtosis = ((\sum w_i ((x_i - xbar)/sigma)^4) / (\sum w_i)) - 3.") (save-test higher-moments (let ((vec #m(-3.21d0 1.0d0 12.8d0))) (let* ((mean (mean vec)) (sd (standard-deviation vec mean))) (list (skewness vec) (skewness vec mean sd) (kurtosis vec) (kurtosis vec mean sd)))))
398b6ad63c65d8f0b93d9524d3a2c45bbd469b5d7237a4b0f256c992302944fa
klarna/erlavro
avro_binary_decoder_tests.erl
%% coding: latin-1 %%%------------------------------------------------------------------- Copyright ( c ) 2013 - 2016 Klarna AB %%% 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. %%% %%%------------------------------------------------------------------- -module(avro_binary_decoder_tests). -import(avro_binary_decoder, [ decode/3 , decode/4 , zigzag/1 ]). -include_lib("eunit/include/eunit.hrl"). %% simple types, never reference decode_t(Bin, Type) -> decode(Bin, Type, fun(Name) -> exit({error, Name}) end). decode_null_test() -> ?assertEqual(null, decode_t(<<>>, avro_primitive:null_type())). decode_boolean_test() -> ?assertEqual(true, decode_t([1], avro_primitive:boolean_type())), ?assertEqual(false, decode_t([0], avro_primitive:boolean_type())). zigzag_test() -> ?assertEqual(0, zigzag(0)), ?assertEqual(-1, zigzag(1)), ?assertEqual(1, zigzag(2)), ?assertEqual(-2, zigzag(3)), ?assertEqual(2147483647, zigzag(4294967294)), ?assertEqual(-2147483648, zigzag(4294967295)). encode_int_test() -> Int = avro_primitive:int_type(), Long = avro_primitive:long_type(), ?assertEqual(4, decode_t(<<8>>, Int)), ?assertEqual(-2, decode_t([<<3>>], Long)), ?assertEqual(-64, decode_t(<<127>>, Long)), ?assertEqual(64, decode_t(<<128, 1>>, Int)), ?assertEqual(-127, decode_t(<<253, 1>>, Long)), ?assertEqual(127, decode_t(<<254, 1>>, Int)), ?assertEqual(128, decode_t(<<128, 2>>, Int)). decode_float_test() -> Type = avro_primitive:float_type(), V_orig = 3.14159265358, Typed = avro_primitive:float(V_orig), Bin = avro_binary_encoder:encode_value(Typed), V_dec = decode_t(Bin, Type), ?assert(abs(V_orig - V_dec) < 0.000001). decode_double_test() -> Type = avro_primitive:double_type(), V_orig = 3.14159265358, Typed = avro_primitive:double(V_orig), Bin = avro_binary_encoder:encode_value(Typed), V_dec = decode_t(Bin, Type), ?assert(abs(V_orig - V_dec) < 0.000000000001). decode_empty_bytes_test() -> ?assertEqual(<<>>, decode_t(<<0>>, avro_primitive:bytes_type())). decode_string_test() -> Str = <<"Avro is popular">>, Enc = [30, Str], ?assertEqual(Str, decode_t(Enc, avro_primitive:string_type())). decode_utf8_string_test() -> Str = "Avro är populär", Utf8 = unicode:characters_to_binary(Str, latin1, utf8), Enc = [size(Utf8) * 2, Utf8], ?assertEqual(Utf8, decode_t(Enc, avro_primitive:string_type())), ?assertEqual(Str, unicode:characters_to_list(Utf8, utf8)). decode_empty_array_test() -> Type = avro_array:type(avro_primitive:int_type()), ?assertEqual([], decode_t(<<0>>, Type)). decode_array_test() -> Type = avro_array:type(avro_primitive:int_type()), TypedValue = avro_array:new(Type, [3, 27]), Bin = avro_binary_encoder:encode_value(TypedValue), ?assertEqual([3, 27], decode_t(Bin, Type)). decode_empty_map_test() -> Type = avro_map:type(avro_primitive:int_type()), ?assertEqual([], decode_t([0], Type)). decode_map_test() -> Type = avro_map:type(avro_primitive:int_type()), Data1 = [4, 2, "a", 0, 2, "b", 2, 0], %% Count + Items Data2 = [3, 12, 2, "a", 0, 2, "b", 2, 0], %% -Count + Size + Items ?assertEqual([{<<"a">>, 0}, {<<"b">>, 1}], decode_t(Data1, Type)), ?assertEqual([{<<"a">>, 0}, {<<"b">>, 1}], decode_t(Data2, Type)). decode_union_test() -> Type = avro_union:type([ avro_primitive:null_type() , avro_primitive:string_type()]), Value1 = [0], Value2 = [2, 2, "a"], ?assertEqual(null, decode_t(Value1, Type)), ?assertEqual(<<"a">>, decode_t(Value2, Type)). decode_fixed_test() -> Type = avro_fixed:type("FooBar", 2), ?assertEqual(<<1, 127>>, decode_t(<<1, 127>>, Type)). sample_record_type() -> avro_record:type( "SampleRecord", [ define_field("bool", boolean, [ {doc, "bool f"} , {default, avro_primitive:boolean(false)} ]) , define_field("int", int, [ {doc, "int f"} , {default, avro_primitive:int(0)} ]) , define_field("long", long, [ {doc, "long f"} , {default, avro_primitive:long(42)} ]) , define_field("float", float, [ {doc, "float f"} , {default, avro_primitive:float(3.14)} ]) , define_field("double", double, [ {doc, "double f"} , {default, avro_primitive:double(6.67221937)} ]) , define_field("bytes", bytes, [ {doc, "bytes f"} ]) , define_field("string", string, [ {doc, "string f"} ]) , define_field("array", avro_array:type(long), [ {doc, "array f"} ]) , define_field("map", avro_map:type(long), [ {doc, "map f"} ]) ], [ {namespace, "com.klarna.test.bix"} , {doc, "Record documentation"} ]). sample_record_binary() -> [<<1>>, %% bool <<200,1>>, %% int <<170,252,130,205,245,210,205,182,3>>, % long <<84, 248, 45, 64>>, % float <<244, 214, 67, 84, 251, 33, 9, 64>>, % double [22, <<98, 121, 116, 101, 115, 32, 118, 97, 108, 117, 101>>], % bytes [12, <<115, 116, 114, 105, 110, 103>>], % string [2, 0, 0], %% array [0] %% map ]. decode_record_test() -> Fields = decode_t(sample_record_binary(), sample_record_type()), ?assertMatch([ {<<"bool">>, true} , {<<"int">>, 100} , {<<"long">>, 123456789123456789} , {<<"float">>, _} , {<<"double">>, _} , {<<"bytes">>, <<"bytes value">>} , {<<"string">>, <<"string">>} , {<<"array">>, [0]} , {<<"map">>, []} ], Fields). decode_with_hook_test() -> Binary = sample_record_binary(), Schema = sample_record_type(), Lkup = fun(_) -> exit(error) end, Hook = avro_decoder_hooks:pretty_print_hist(), Fields = decode(Binary, Schema, Lkup, avro:make_decoder_options([{hook, Hook}])), ?assertMatch([ {<<"bool">>, true} , {<<"int">>, 100} , {<<"long">>, 123456789123456789} , {<<"float">>, _} , {<<"double">>, _} , {<<"bytes">>, <<"bytes value">>} , {<<"string">>, <<"string">>} , {<<"array">>, [0]} , {<<"map">>, []} ], Fields). define_field(Name, Type, Opts) -> avro_record:define_field(Name, Type, Opts). %%%_* Emacs ==================================================================== %%% Local Variables: %%% allout-layout: t erlang - indent - level : 2 %%% End:
null
https://raw.githubusercontent.com/klarna/erlavro/c55e55238ed879642c65d00c8105e498b4acc8db/test/avro_binary_decoder_tests.erl
erlang
coding: latin-1 ------------------------------------------------------------------- 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. ------------------------------------------------------------------- simple types, never reference Count + Items -Count + Size + Items bool int long float double bytes string array map _* Emacs ==================================================================== Local Variables: allout-layout: t End:
Copyright ( c ) 2013 - 2016 Klarna AB 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 -module(avro_binary_decoder_tests). -import(avro_binary_decoder, [ decode/3 , decode/4 , zigzag/1 ]). -include_lib("eunit/include/eunit.hrl"). decode_t(Bin, Type) -> decode(Bin, Type, fun(Name) -> exit({error, Name}) end). decode_null_test() -> ?assertEqual(null, decode_t(<<>>, avro_primitive:null_type())). decode_boolean_test() -> ?assertEqual(true, decode_t([1], avro_primitive:boolean_type())), ?assertEqual(false, decode_t([0], avro_primitive:boolean_type())). zigzag_test() -> ?assertEqual(0, zigzag(0)), ?assertEqual(-1, zigzag(1)), ?assertEqual(1, zigzag(2)), ?assertEqual(-2, zigzag(3)), ?assertEqual(2147483647, zigzag(4294967294)), ?assertEqual(-2147483648, zigzag(4294967295)). encode_int_test() -> Int = avro_primitive:int_type(), Long = avro_primitive:long_type(), ?assertEqual(4, decode_t(<<8>>, Int)), ?assertEqual(-2, decode_t([<<3>>], Long)), ?assertEqual(-64, decode_t(<<127>>, Long)), ?assertEqual(64, decode_t(<<128, 1>>, Int)), ?assertEqual(-127, decode_t(<<253, 1>>, Long)), ?assertEqual(127, decode_t(<<254, 1>>, Int)), ?assertEqual(128, decode_t(<<128, 2>>, Int)). decode_float_test() -> Type = avro_primitive:float_type(), V_orig = 3.14159265358, Typed = avro_primitive:float(V_orig), Bin = avro_binary_encoder:encode_value(Typed), V_dec = decode_t(Bin, Type), ?assert(abs(V_orig - V_dec) < 0.000001). decode_double_test() -> Type = avro_primitive:double_type(), V_orig = 3.14159265358, Typed = avro_primitive:double(V_orig), Bin = avro_binary_encoder:encode_value(Typed), V_dec = decode_t(Bin, Type), ?assert(abs(V_orig - V_dec) < 0.000000000001). decode_empty_bytes_test() -> ?assertEqual(<<>>, decode_t(<<0>>, avro_primitive:bytes_type())). decode_string_test() -> Str = <<"Avro is popular">>, Enc = [30, Str], ?assertEqual(Str, decode_t(Enc, avro_primitive:string_type())). decode_utf8_string_test() -> Str = "Avro är populär", Utf8 = unicode:characters_to_binary(Str, latin1, utf8), Enc = [size(Utf8) * 2, Utf8], ?assertEqual(Utf8, decode_t(Enc, avro_primitive:string_type())), ?assertEqual(Str, unicode:characters_to_list(Utf8, utf8)). decode_empty_array_test() -> Type = avro_array:type(avro_primitive:int_type()), ?assertEqual([], decode_t(<<0>>, Type)). decode_array_test() -> Type = avro_array:type(avro_primitive:int_type()), TypedValue = avro_array:new(Type, [3, 27]), Bin = avro_binary_encoder:encode_value(TypedValue), ?assertEqual([3, 27], decode_t(Bin, Type)). decode_empty_map_test() -> Type = avro_map:type(avro_primitive:int_type()), ?assertEqual([], decode_t([0], Type)). decode_map_test() -> Type = avro_map:type(avro_primitive:int_type()), ?assertEqual([{<<"a">>, 0}, {<<"b">>, 1}], decode_t(Data1, Type)), ?assertEqual([{<<"a">>, 0}, {<<"b">>, 1}], decode_t(Data2, Type)). decode_union_test() -> Type = avro_union:type([ avro_primitive:null_type() , avro_primitive:string_type()]), Value1 = [0], Value2 = [2, 2, "a"], ?assertEqual(null, decode_t(Value1, Type)), ?assertEqual(<<"a">>, decode_t(Value2, Type)). decode_fixed_test() -> Type = avro_fixed:type("FooBar", 2), ?assertEqual(<<1, 127>>, decode_t(<<1, 127>>, Type)). sample_record_type() -> avro_record:type( "SampleRecord", [ define_field("bool", boolean, [ {doc, "bool f"} , {default, avro_primitive:boolean(false)} ]) , define_field("int", int, [ {doc, "int f"} , {default, avro_primitive:int(0)} ]) , define_field("long", long, [ {doc, "long f"} , {default, avro_primitive:long(42)} ]) , define_field("float", float, [ {doc, "float f"} , {default, avro_primitive:float(3.14)} ]) , define_field("double", double, [ {doc, "double f"} , {default, avro_primitive:double(6.67221937)} ]) , define_field("bytes", bytes, [ {doc, "bytes f"} ]) , define_field("string", string, [ {doc, "string f"} ]) , define_field("array", avro_array:type(long), [ {doc, "array f"} ]) , define_field("map", avro_map:type(long), [ {doc, "map f"} ]) ], [ {namespace, "com.klarna.test.bix"} , {doc, "Record documentation"} ]). sample_record_binary() -> ]. decode_record_test() -> Fields = decode_t(sample_record_binary(), sample_record_type()), ?assertMatch([ {<<"bool">>, true} , {<<"int">>, 100} , {<<"long">>, 123456789123456789} , {<<"float">>, _} , {<<"double">>, _} , {<<"bytes">>, <<"bytes value">>} , {<<"string">>, <<"string">>} , {<<"array">>, [0]} , {<<"map">>, []} ], Fields). decode_with_hook_test() -> Binary = sample_record_binary(), Schema = sample_record_type(), Lkup = fun(_) -> exit(error) end, Hook = avro_decoder_hooks:pretty_print_hist(), Fields = decode(Binary, Schema, Lkup, avro:make_decoder_options([{hook, Hook}])), ?assertMatch([ {<<"bool">>, true} , {<<"int">>, 100} , {<<"long">>, 123456789123456789} , {<<"float">>, _} , {<<"double">>, _} , {<<"bytes">>, <<"bytes value">>} , {<<"string">>, <<"string">>} , {<<"array">>, [0]} , {<<"map">>, []} ], Fields). define_field(Name, Type, Opts) -> avro_record:define_field(Name, Type, Opts). erlang - indent - level : 2
27ffb32976fe8a1bd6ea947b778ee67aa4ac8fbad47ef21142fa7c039f8e81e8
fleximus/redirect_service
redirect_service_app.erl
%% Feel free to use, reuse and abuse the code in this file. @private -module(redirect_service_app). -behaviour(application). %% API. -export([start/2]). -export([stop/1]). %% API. start(_Type, _Args) -> Dispatch = cowboy_router:compile([ {'_', [ {"/[...]", cowboy_static, [ {directory, {priv_dir, redirect_service, []}}, {mimetypes, {fun mimetypes:path_to_mimes/2, default}} ]} ]} ]), {ok, _} = cowboy:start_http(http, 100, [{port, 80}], [ {env, [{dispatch, Dispatch}]}, {middlewares, [cowboy_router, redirect_lookup, cowboy_handler]} ]), redirect_service_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/fleximus/redirect_service/57b56a3fad3379ca5ae662764594b179c323e251/src/redirect_service_app.erl
erlang
Feel free to use, reuse and abuse the code in this file. API. API.
@private -module(redirect_service_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> Dispatch = cowboy_router:compile([ {'_', [ {"/[...]", cowboy_static, [ {directory, {priv_dir, redirect_service, []}}, {mimetypes, {fun mimetypes:path_to_mimes/2, default}} ]} ]} ]), {ok, _} = cowboy:start_http(http, 100, [{port, 80}], [ {env, [{dispatch, Dispatch}]}, {middlewares, [cowboy_router, redirect_lookup, cowboy_handler]} ]), redirect_service_sup:start_link(). stop(_State) -> ok.
cf0520684a1c7e1866794537a6385bc7f5057f1b6838f302100445ce9cdfd913
expipiplus1/vulkan
Alias.hs
module Render.Alias where import Prettyprinter import Polysemy import Polysemy.Input import Relude import Error import Render.Element import Render.SpecInfo import Spec.Parse renderAlias :: (HasErr r, HasRenderParams r, HasSpecInfo r) => Alias -> Sem r RenderElement renderAlias Alias {..} = context (unCName aName) $ do RenderParams {..} <- input genRe ("alias " <> unCName aName) $ case aType of TypeAlias -> do let t = mkTyName aTarget n = mkTyName aName tellImport t let syn :: forall r . HasRenderElem r => Sem r () syn = do tellDocWithHaddock $ \getDoc -> vsep [ getDoc (TopLevel aName) , "type" <+> pretty n <+> "=" <+> pretty t ] tellExport (EType n) syn tellBoot $ do syn tellSourceImport t TermAlias -> do let n = mkFunName aName t = mkFunName aTarget tellExport (ETerm n) tellImport t tellDocWithHaddock $ \getDoc -> vsep [getDoc (TopLevel aName), pretty n <+> "=" <+> pretty t] PatternAlias -> do let n = mkPatternName aName t = mkPatternName aTarget tellExport (EPat n) tellImport t tellDocWithHaddock $ \getDoc -> vsep [getDoc (TopLevel aName), "pattern" <+> pretty n <+> "=" <+> pretty t]
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/generate-new/src/Render/Alias.hs
haskell
module Render.Alias where import Prettyprinter import Polysemy import Polysemy.Input import Relude import Error import Render.Element import Render.SpecInfo import Spec.Parse renderAlias :: (HasErr r, HasRenderParams r, HasSpecInfo r) => Alias -> Sem r RenderElement renderAlias Alias {..} = context (unCName aName) $ do RenderParams {..} <- input genRe ("alias " <> unCName aName) $ case aType of TypeAlias -> do let t = mkTyName aTarget n = mkTyName aName tellImport t let syn :: forall r . HasRenderElem r => Sem r () syn = do tellDocWithHaddock $ \getDoc -> vsep [ getDoc (TopLevel aName) , "type" <+> pretty n <+> "=" <+> pretty t ] tellExport (EType n) syn tellBoot $ do syn tellSourceImport t TermAlias -> do let n = mkFunName aName t = mkFunName aTarget tellExport (ETerm n) tellImport t tellDocWithHaddock $ \getDoc -> vsep [getDoc (TopLevel aName), pretty n <+> "=" <+> pretty t] PatternAlias -> do let n = mkPatternName aName t = mkPatternName aTarget tellExport (EPat n) tellImport t tellDocWithHaddock $ \getDoc -> vsep [getDoc (TopLevel aName), "pattern" <+> pretty n <+> "=" <+> pretty t]
f90c2c855ac162d69a800744a0f68841a5a885ffd00c498825c3fc760e67948b
emina/rosette
bool.rkt
#lang racket (require "term.rkt" "union.rkt" "exn.rkt" "result.rkt" "reporter.rkt") (provide ;; ---- lifted boolean? operations ---- ;; @boolean? @false? @true? ! && || => <=> @! @&& @|| @=> @<=> @exists @forall and-&& or-|| instance-of? T*->boolean? ;; ---- VC generation ---- ;; @assert @assume $assert $assume (rename-out [get-vc vc]) clear-vc! merge-vc! with-vc vc? vc-assumes vc-asserts vc-true vc-true?) ;; ----------------- Boolean type ----------------- ;; (define-lifted-type @boolean? #:base boolean? #:is-a? (instance-of? boolean? @boolean?) #:methods [(define (solvable-default self) #f) (define (type-eq? self u v) (<=> u v)) (define (type-equal? self u v) (<=> u v)) (define (type-cast self v [caller 'type-cast]) (match v [(? boolean?) v] [(term _ (== self)) v] [(union : [g (and (or (? boolean?) (term _ (== self))) u)] _ ...) ($assert g (argument-error caller "boolean?" v)) u] [_ ($assert #f (argument-error caller "boolean?" v))])) (define (type-compress self force? ps) (match ps [(list _) ps] [(list (cons g v) (cons u w)) (list (cons (|| g u) (|| (&& g v) (&& u w))))] [_ (list (cons (apply || (map car ps)) (apply || (for/list ([p ps]) (&& (car p) (cdr p))))))]))]) ;; ----------------- Lifting utilities ----------------- ;; (define (lift-op op) (define caller (object-name op)) (case (procedure-arity op) [(1) (lambda (x) (op (type-cast @boolean? x caller)))] [(2) (lambda (x y) (op (type-cast @boolean? x caller) (type-cast @boolean? y caller)))] [else (case-lambda [() (op)] [(x) (op (type-cast @boolean? x caller))] [(x y) (op (type-cast @boolean? x caller) (type-cast @boolean? y caller))] [xs (apply op (for/list ([x xs]) (type-cast @boolean? x caller)))])])) ; A generic typing procedure for a lifted operator that takes N >= 0 arguments of type T ; and returns a @boolean?. See term.rkt. (define (T*->boolean? . xs) @boolean?) (define-syntax-rule (define-lifted-operator @op $op) (define-operator @op #:identifier '$op #:range T*->boolean? #:unsafe $op #:safe (lift-op $op))) (define-syntax-rule (define-quantifier $op @op) (begin (define $op (quantifier @op)) (define-operator @op #:identifier '$op #:range T*->boolean? #:unsafe $op #:safe (lambda (@vars @body) (match* (@vars (type-cast @boolean? @body '$op)) [((list (constant _ (? primitive-solvable?)) (... ...)) body) ($op @vars body)] [(_ _) ($assert #f (argument-error '$op "list of symbolic constants of primitive solvable types" @vars))]))))) ;; ----------------- Basic boolean operators ----------------- ;; (define (! x) (match x [(? boolean?) (not x)] [(expression (== @!) y) y] [_ (expression @! x)])) (define && (logical-connective @&& @|| #t #f)) (define || (logical-connective @|| @&& #f #t)) (define (=> x y) ; (|| (! x) y)) (cond [(equal? x y) #t] [(eq? x #f) #t] [(eq? y #t) #t] [(eq? x #t) y] [(eq? y #f) (! x)] [(cancel? x y) y] [else (match y [(expression (== @||) _ ... (== x) _ ...) #t] [(expression (== @&&) (== x) b) (=> x b)] [(expression (== @&&) b (== x)) (=> x b)] [(expression (== @&&) (expression (== @||) _ ... (== x) _ ...) b) (=> x b)] [(expression (== @&&) b (expression (== @||) _ ... (== x) _ ...)) (=> x b)] [(expression (== @<=>) (== x) b) (=> x b)] [(expression (== @<=>) b (== x)) (=> x b)] [_ (|| (! x) y)])])) (define (<=> x y) (cond [(equal? x y) #t] [(boolean? x) (if x y (! y))] [(boolean? y) (if y x (! x))] [(cancel? x y) #f] [(term<? x y) (expression @<=> x y)] [else (expression @<=> y x)])) (define-lifted-operator @! !) (define-lifted-operator @&& &&) (define-lifted-operator @|| ||) (define-lifted-operator @=> =>) (define-lifted-operator @<=> <=>) (define (@false? v) (match v [#f #t] [(term _ (== @boolean?)) (! v)] [(union xs (== @any/c)) (let loop ([xs xs]) (match xs [(list) #f] [(list (cons g (and (or (? boolean?) (term _ (== @boolean?))) u)) _ ...) (&& g (! u))] [_ (loop (cdr xs))]))] [_ #f])) (define (@true? v) (or (eq? #t v) (! (@false? v)))) (define-quantifier exists @exists) (define-quantifier forall @forall) ;; ----------------- Additional operators and utilities ----------------- ;; (define-syntax and-&& (syntax-rules () [(_) #t] [(_ v0) v0] [(_ v0 #:rest (r ...)) (let ([t0 v0]) (and t0 (@&& r ... t0)))] [(_ v0 v ... #:rest (r ...)) (let ([t0 v0]) (and t0 (and-&& v ... #:rest (r ... t0))))] [(_ v0 v ...) (let ([t0 v0]) (and t0 (and-&& v ... #:rest (t0))))])) (define-syntax or-|| (syntax-rules () [(_) #f] [(_ v0) v0] [(_ v0 #:rest (r ...)) (let ([t0 v0]) (or (equal? #t t0) (@|| r ... t0)))] [(_ v0 v ... #:rest (r ...)) (let ([t0 v0]) (or (equal? #t t0) (or-|| v ... #:rest (r ... t0))))] [(_ v0 v ...) (let ([t0 v0]) (or (equal? #t t0) (or-|| v ... #:rest (t0))))])) (define-syntax-rule (instance-of? primitive-type ... symbolic-type) (match-lambda [(? primitive-type) #t] ... [(and (? typed? v) (app get-type t)) (or (and t (subtype? t symbolic-type)) (and (union? v) (apply || (for/list ([g (in-union-guards v symbolic-type)]) g))))] [_ #f])) (define ⊥ (void)) (define-syntax first-term-or-bool (syntax-rules () [(_ e) e] [(_ e0 e ...) (let ([v e0]) (if (void? v) (first-term-or-bool e ...) v))])) ----------------- Partial evaluation rules for and ∃ ----------------- ; ; (define-syntax-rule (quantifier @op) (lambda (vars body) (match* (vars body) [((list) _) body] [(_ (? boolean?)) body] [(_ _) (expression @op vars body)]))) ----------------- Partial evaluation rules for & & and || ----------------- ; ; (define-syntax-rule (logical-connective op co iden !iden) (case-lambda [() iden] [(x) x] [(x y) (match* (x y) [((== iden) _) y] [(_ (== iden)) x] [((== !iden) _) !iden] [(_ (== !iden)) !iden] [(_ _) (first-term-or-bool (simplify-connective op co !iden x y) (if (term<? x y) (expression op x y) (expression op y x)))])] [xs (cond [(member !iden xs) !iden] [else (match (simplify-fp op co !iden (remove-duplicates (filter term? xs))) [(list) iden] [(list x) x] [ys (apply expression op (sort ys term<?))])])])) (define (simplify-connective op co !iden x y) (match* (x y) [(_ (== x)) x] [((? expression?) (? expression?)) (first-term-or-bool (if (term<? y x) (simplify-connective:expr/any op co !iden x y) (simplify-connective:expr/any op co !iden y x)) (simplify-connective:expr/expr op co !iden x y))] [((? expression?) _) (if (term<? y x) (simplify-connective:expr/any op co !iden x y) ⊥)] [(_ (? expression?)) (if (term<? x y) (simplify-connective:expr/any op co !iden y x) ⊥)] [(_ _) ⊥])) (define (simplify-connective:expr/any op co !iden x y) (match x [(expression (== @!) (== y)) !iden] [(expression (== co) _ ... (== y) _ ...) y] [(expression (== op) _ ... (== y) _ ...) x] [(expression (== op) _ ... (expression (== @!) (== y)) _ ...) !iden] [(expression (== @!) (expression (== co) _ ... (== y) _ ...)) !iden] [_ ⊥])) (define (simplify-connective:expr/expr op co !iden a b) (match* (a b) [((expression (== op) _ ... x _ ...) (expression (== @!) x)) !iden] [((expression (== @!) x) (expression (== op) _ ... x _ ...)) !iden] [((expression (== op) xs ...) (expression (== op) ys ...)) (cond [(sublist? xs ys) b] [(sublist? ys xs) a] [(for*/or ([x xs][y ys]) (cancel? x y)) !iden] [else ⊥])] [((expression (== co) xs ...) (expression (== co) ys ...)) (cond [(sublist? xs ys) a] [(sublist? ys xs) b] [else ⊥])] [((expression (== op) xs ...) (expression (== co) ys ...)) (cond [(for*/or ([x xs][y ys]) (equal? x y)) a] [else ⊥])] [((expression (== co) xs ...) (expression (== op) ys ...)) (cond [(for*/or ([y ys][x xs]) (equal? x y)) b] [else ⊥])] [(_ _) ⊥])) (define (simplify-fp op co !iden xs) (or (and (> (length xs) 10) xs) (let-values ([(!ys ys) (for/fold ([!ys '()][ys '()]) ([x xs]) (match x [(expression (== @!) y) (values (cons y !ys) ys)] [_ (values !ys (cons x ys))]))]) (for/first ([!y !ys] #:when (member !y ys)) (list !iden))) (let outer ([xs xs]) (match xs [(list x rest ..1) (let inner ([head rest] [tail '()]) (match head [(list) (match (outer tail) [(and (list (== !iden)) t) t] [t (cons x t)])] [(list y ys ...) (match (simplify-connective op co !iden x y) [(== ⊥) (inner ys (cons y tail))] [(== !iden) (list !iden)] [v (outer (cons v (append ys tail)))])]))] [_ xs])))) (define (cancel? a b) (match* (a b) [(_ (expression (== @!) (== a))) #t] [((expression (== @!) (== b)) _) #t] [(_ _) #f])) ;; ----------------- VC generation ----------------- ;; A verification condition ( VC ) consists of two @boolean ? ; values representing assumptions and assertions issued during execution . A VC is legal if at least one of its ; constituent fields is true under all models. (struct vc (assumes asserts) #:transparent) ; The true verification condition. (define vc-true (vc #t #t)) (define (vc-true? s) (equal? s vc-true)) Returns ( vc ( s.assumes & & ( s.asserts = ) ) s.asserts ) . (define (assuming s g) ; g must be a symbolic or concrete boolean (vc (&& (vc-assumes s) (=> (vc-asserts s) g)) (vc-asserts s))) ; Returns (vc s.assumes (s.asserts && (s.assumes => g))). (define (asserting s g) ; g must be a symbolic or concrete boolean (vc (vc-assumes s) (&& (vc-asserts s) (=> (vc-assumes s) g)))) ; The current-vc parameter keeps track of the current verification condition, ; which is an instance of vc?. The default value for this parameter is vc-true. (define current-vc (make-parameter vc-true (lambda (v) (unless (vc? v) (raise-argument-error 'vc "vc?" v)) v))) ; Returns the current vc, without exposing the parameter outside the module. (define (get-vc) (current-vc)) ; Clears the current vc by setting it to the true spec. (define (clear-vc!) (current-vc vc-true)) ; Returns #t if x && (g => y) is equivalent to x according to the embedded rewrite rules . Otherwise returns # f. (define (merge-absorbs? x g y) (match y [(== x) #t] ; x && (g => x) x & & ( g = > ( x & & g ) ) x & & ( g = > ( x & & g ) ) x & & ( g = > ( x & & ( _ = > g ) ) ) x & & ( g = > ( ( _ = > g ) & & x ) ) [_ #f])) Returns ( field x ) & & ( gs[0 ] = > ( field ys[0 ] ) ) ... & & ( gs[n-1 ] = > ( field gs[n-1 ] ) ) . (define (merge-field field x gs ys) (define xf (field x)) (apply && xf (for*/list ([(g y) (in-parallel gs ys)] [yf (in-value (field y))] #:unless (merge-absorbs? xf g yf)) (=> g yf)))) Returns ( field x ) & & ( gs[0 ] = > ( field ys[0 ] ) ) ... & & ( gs[n-1 ] = > ( field gs[n-1 ] ) ) . ;; Assumes that ys[i] => x for all i, and at most one gs evaluates to true in any model. ;(define (merge-field field x gs ys) ; (define xf (field x)) ( define gs=>ys ( for*/list ( [ ( g y ) ( in - parallel gs ys ) ] ; [yf (in-value (field y))] ; #:unless (merge-absorbs? xf g yf)) ; (=> g yf))) ; (match gs=>ys ; [(list) xf] ; [(list gy) (&& xf gy)] ; [(or (list (expression (== @||) _ ... g _ ...) (expression (== @||) _ ... (expression (== @!) g) _ ...)) ; (list (expression (== @||) _ ... (expression (== @!) g) _ ...) (expression (== @||) _ ... g _ ...))) ; (apply && gs=>ys)] ; [_ (apply && xf gs=>ys)])) Takes as input a list of n guards and n vcs and sets the current vc to ( current - vc ) & & ( vc - guard ) & & ... & & ( vc - guard ) . ; Then, it checks if either the assumes or the asserts of the resulting vc ; are false? and if so, throws either an exn:fail:svm:assume? or ; exn:fail:svm:assert? exception. This procedure makes the following assumptions: ; * at most one of the given guards is true in any model, ; * (vc-assumes vcs[i]) => (vc-assumes (current-vc)) for all i, and ; * (vc-asserts vcs[i]) => (vc-asserts (current-vc)) for all i. (define (merge-vc! guards vcs) (unless (null? vcs) (define vc* (vc (merge-field vc-assumes (current-vc) guards vcs) (merge-field vc-asserts (current-vc) guards vcs))) (current-vc vc*) (when (false? (vc-assumes vc*)) (raise-exn:fail:svm:assume:core "contradiction")) (when (false? (vc-asserts vc*)) (raise-exn:fail:svm:assert:core "contradiction")))) Sets the current vc to ( vc - proc ( current - vc ) g ) where g is ( @true ? ) . If g is # f or the resulting vc 's vc - field value is # f , ; uses raise-exn throws an exn:fail:svm exception. (define-syntax-rule (vc-set! val msg vc-proc vc-field raise-exn) (let* ([guard (@true? val)] [vc* (vc-proc (current-vc) guard)]) (current-vc vc*) (when (false? guard) (raise-exn msg)) (when (false? (vc-field vc*)) (raise-exn "contradiction")))) Sets the current vc to ( asserting ( current - vc ) g ) where g is ( @true ? ) . If g is # f or the resulting vc 's asserts field is # f , throws an ; exn:fail:svm:assert exception of the given kind. (define-syntax-rule (vc-assert! val msg raise-kind) (vc-set! val msg asserting vc-asserts raise-kind)) Sets the current vc to ( assuming ( current - vc ) g ) where g is ( @true ? ) . If g is # f or the resulting vc 's assumes field is # f , throws an ; exn:fail:svm:assume exception of the given kind. (define-syntax-rule (vc-assume! val msg raise-kind) (vc-set! val msg assuming vc-assumes raise-kind)) The $ assert form has three variants : ( $ assert val ) , ( $ assert val msg ) , and ( $ assert val msg kind ) , where is the value being asserted , msg ; is the failure message, and kind is a procedure that returns a subtype of ; exn:fail:svm:assert. Default values for msg and kind are #f and ; raise-exn:fail:svm:assert:core, respectively. The first two variants of this form are used for issuing assertions from within the Rosette core . The third variant is used to implement the @assert ; form that is exposed to user code. An $assert call modifies the current vc to ; reflect the issued assertion. If the issued assertion or the vc-assert of the ; current vc reduce to #f, the call throws an exception of the given kind after ; updating the vc. (define-syntax ($assert stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assert val #f raise-exn:fail:svm:assert:core))] [(_ val msg) (syntax/loc stx ($assert val msg raise-exn:fail:svm:assert:core))] [(_ val msg kind) (syntax/loc stx (vc-assert! val msg kind))])) ; Analogous to the $assert form, except that it modifies the current vc to ; reflect the issued assumption. (define-syntax ($assume stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assume val #f raise-exn:fail:svm:assume:core))] [(_ val msg) (syntax/loc stx ($assume val msg raise-exn:fail:svm:assume:core))] [(_ val msg kind) (syntax/loc stx (vc-assume! val msg kind))])) The @assert form modifies the current vc to reflect the issued assertion . The form has two variants ( @assert val ) and ( @assert val msg ) , where val ; is the value being asserted and msg is the optional error message in case val is This form is exposed to user code . (define-syntax (@assert stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assert val #f raise-exn:fail:svm:assert:user))] [(_ val msg) (syntax/loc stx ($assert val msg raise-exn:fail:svm:assert:user))])) The @assume form modifies the current vc to reflect the issued assumption . The form has two variants ( @assume val ) and ( @assume val msg ) , where val ; is the value being assume and msg is the optional error message in case val is This form is exposed to user code . (define-syntax (@assume stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assume val #f raise-exn:fail:svm:assume:user))] [(_ val msg) (syntax/loc stx ($assume val msg raise-exn:fail:svm:assume:user))])) (define (halt-svm ex) (define result (failed ex (current-vc))) ((current-reporter) 'exception result) result) (define (halt-err ex) ; Treat an exn:fail? error as an assertion failure. (define result (failed (make-exn:fail:svm:assert:err (exn-message ex) (exn-continuation-marks ex)) (asserting (current-vc) #f))) ((current-reporter) 'exception result) result) The with - vc form has two variants , ( with - vc body ) and ( with - vc vc0 body ) . ; The former expands into (with-vc (current-vc) body). The latter sets the current ; vc to vc0, evaluates the given body, returns the result, and reverts current-vc ; to the value it held before the call to with-vc. ; ; If the evaluation of the body terminates normally, (with-vc vc0 body) ; outputs (normal v vc*) where v is the value computed by the body, and vc* is ; the vc (i.e., assumes and asserts) generated during the evaluation, with vc0 as the initial vc . ; ; If the evaluation of the body terminates abnormally with an exn:fail? exception, ; (with-vc vc0 body) outputs (failed v vc*) where v is an exn:fail:svm? exception ; that represents the cause of the abnormal termination, and vc* is the vc ; generated during the evaluation, with vc0 as the initial vc. (define-syntax (with-vc stx) (syntax-case stx () [(_ body) (syntax/loc stx (with-vc (current-vc) body))] [(_ vc0 body) (syntax/loc stx (parameterize ([current-vc vc0]) (with-handlers ([exn:fail:svm? halt-svm] [exn:fail? halt-err]) (normal (let () body) (current-vc)))))]))
null
https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/rosette/base/core/bool.rkt
racket
---- lifted boolean? operations ---- ;; ---- VC generation ---- ;; ----------------- Boolean type ----------------- ;; ----------------- Lifting utilities ----------------- ;; A generic typing procedure for a lifted operator that takes N >= 0 arguments of type T and returns a @boolean?. See term.rkt. ----------------- Basic boolean operators ----------------- ;; (|| (! x) y)) ----------------- Additional operators and utilities ----------------- ;; ; ; ----------------- VC generation ----------------- ;; values representing assumptions and assertions issued constituent fields is true under all models. The true verification condition. g must be a symbolic or concrete boolean Returns (vc s.assumes (s.asserts && (s.assumes => g))). g must be a symbolic or concrete boolean The current-vc parameter keeps track of the current verification condition, which is an instance of vc?. The default value for this parameter is vc-true. Returns the current vc, without exposing the parameter outside the module. Clears the current vc by setting it to the true spec. Returns #t if x && (g => y) is equivalent to x according to the embedded x && (g => x) Assumes that ys[i] => x for all i, and at most one gs evaluates to true in any model. (define (merge-field field x gs ys) (define xf (field x)) [yf (in-value (field y))] #:unless (merge-absorbs? xf g yf)) (=> g yf))) (match gs=>ys [(list) xf] [(list gy) (&& xf gy)] [(or (list (expression (== @||) _ ... g _ ...) (expression (== @||) _ ... (expression (== @!) g) _ ...)) (list (expression (== @||) _ ... (expression (== @!) g) _ ...) (expression (== @||) _ ... g _ ...))) (apply && gs=>ys)] [_ (apply && xf gs=>ys)])) Then, it checks if either the assumes or the asserts of the resulting vc are false? and if so, throws either an exn:fail:svm:assume? or exn:fail:svm:assert? exception. This procedure makes the following assumptions: * at most one of the given guards is true in any model, * (vc-assumes vcs[i]) => (vc-assumes (current-vc)) for all i, and * (vc-asserts vcs[i]) => (vc-asserts (current-vc)) for all i. uses raise-exn throws an exn:fail:svm exception. exn:fail:svm:assert exception of the given kind. exn:fail:svm:assume exception of the given kind. is the failure message, and kind is a procedure that returns a subtype of exn:fail:svm:assert. Default values for msg and kind are #f and raise-exn:fail:svm:assert:core, respectively. form that is exposed to user code. An $assert call modifies the current vc to reflect the issued assertion. If the issued assertion or the vc-assert of the current vc reduce to #f, the call throws an exception of the given kind after updating the vc. Analogous to the $assert form, except that it modifies the current vc to reflect the issued assumption. is the value being asserted and msg is the optional error message in case is the value being assume and msg is the optional error message in case Treat an exn:fail? error as an assertion failure. The former expands into (with-vc (current-vc) body). The latter sets the current vc to vc0, evaluates the given body, returns the result, and reverts current-vc to the value it held before the call to with-vc. If the evaluation of the body terminates normally, (with-vc vc0 body) outputs (normal v vc*) where v is the value computed by the body, and vc* is the vc (i.e., assumes and asserts) generated during the evaluation, If the evaluation of the body terminates abnormally with an exn:fail? exception, (with-vc vc0 body) outputs (failed v vc*) where v is an exn:fail:svm? exception that represents the cause of the abnormal termination, and vc* is the vc generated during the evaluation, with vc0 as the initial vc.
#lang racket (require "term.rkt" "union.rkt" "exn.rkt" "result.rkt" "reporter.rkt") (provide @boolean? @false? @true? ! && || => <=> @! @&& @|| @=> @<=> @exists @forall and-&& or-|| instance-of? T*->boolean? @assert @assume $assert $assume (rename-out [get-vc vc]) clear-vc! merge-vc! with-vc vc? vc-assumes vc-asserts vc-true vc-true?) (define-lifted-type @boolean? #:base boolean? #:is-a? (instance-of? boolean? @boolean?) #:methods [(define (solvable-default self) #f) (define (type-eq? self u v) (<=> u v)) (define (type-equal? self u v) (<=> u v)) (define (type-cast self v [caller 'type-cast]) (match v [(? boolean?) v] [(term _ (== self)) v] [(union : [g (and (or (? boolean?) (term _ (== self))) u)] _ ...) ($assert g (argument-error caller "boolean?" v)) u] [_ ($assert #f (argument-error caller "boolean?" v))])) (define (type-compress self force? ps) (match ps [(list _) ps] [(list (cons g v) (cons u w)) (list (cons (|| g u) (|| (&& g v) (&& u w))))] [_ (list (cons (apply || (map car ps)) (apply || (for/list ([p ps]) (&& (car p) (cdr p))))))]))]) (define (lift-op op) (define caller (object-name op)) (case (procedure-arity op) [(1) (lambda (x) (op (type-cast @boolean? x caller)))] [(2) (lambda (x y) (op (type-cast @boolean? x caller) (type-cast @boolean? y caller)))] [else (case-lambda [() (op)] [(x) (op (type-cast @boolean? x caller))] [(x y) (op (type-cast @boolean? x caller) (type-cast @boolean? y caller))] [xs (apply op (for/list ([x xs]) (type-cast @boolean? x caller)))])])) (define (T*->boolean? . xs) @boolean?) (define-syntax-rule (define-lifted-operator @op $op) (define-operator @op #:identifier '$op #:range T*->boolean? #:unsafe $op #:safe (lift-op $op))) (define-syntax-rule (define-quantifier $op @op) (begin (define $op (quantifier @op)) (define-operator @op #:identifier '$op #:range T*->boolean? #:unsafe $op #:safe (lambda (@vars @body) (match* (@vars (type-cast @boolean? @body '$op)) [((list (constant _ (? primitive-solvable?)) (... ...)) body) ($op @vars body)] [(_ _) ($assert #f (argument-error '$op "list of symbolic constants of primitive solvable types" @vars))]))))) (define (! x) (match x [(? boolean?) (not x)] [(expression (== @!) y) y] [_ (expression @! x)])) (define && (logical-connective @&& @|| #t #f)) (define || (logical-connective @|| @&& #f #t)) (cond [(equal? x y) #t] [(eq? x #f) #t] [(eq? y #t) #t] [(eq? x #t) y] [(eq? y #f) (! x)] [(cancel? x y) y] [else (match y [(expression (== @||) _ ... (== x) _ ...) #t] [(expression (== @&&) (== x) b) (=> x b)] [(expression (== @&&) b (== x)) (=> x b)] [(expression (== @&&) (expression (== @||) _ ... (== x) _ ...) b) (=> x b)] [(expression (== @&&) b (expression (== @||) _ ... (== x) _ ...)) (=> x b)] [(expression (== @<=>) (== x) b) (=> x b)] [(expression (== @<=>) b (== x)) (=> x b)] [_ (|| (! x) y)])])) (define (<=> x y) (cond [(equal? x y) #t] [(boolean? x) (if x y (! y))] [(boolean? y) (if y x (! x))] [(cancel? x y) #f] [(term<? x y) (expression @<=> x y)] [else (expression @<=> y x)])) (define-lifted-operator @! !) (define-lifted-operator @&& &&) (define-lifted-operator @|| ||) (define-lifted-operator @=> =>) (define-lifted-operator @<=> <=>) (define (@false? v) (match v [#f #t] [(term _ (== @boolean?)) (! v)] [(union xs (== @any/c)) (let loop ([xs xs]) (match xs [(list) #f] [(list (cons g (and (or (? boolean?) (term _ (== @boolean?))) u)) _ ...) (&& g (! u))] [_ (loop (cdr xs))]))] [_ #f])) (define (@true? v) (or (eq? #t v) (! (@false? v)))) (define-quantifier exists @exists) (define-quantifier forall @forall) (define-syntax and-&& (syntax-rules () [(_) #t] [(_ v0) v0] [(_ v0 #:rest (r ...)) (let ([t0 v0]) (and t0 (@&& r ... t0)))] [(_ v0 v ... #:rest (r ...)) (let ([t0 v0]) (and t0 (and-&& v ... #:rest (r ... t0))))] [(_ v0 v ...) (let ([t0 v0]) (and t0 (and-&& v ... #:rest (t0))))])) (define-syntax or-|| (syntax-rules () [(_) #f] [(_ v0) v0] [(_ v0 #:rest (r ...)) (let ([t0 v0]) (or (equal? #t t0) (@|| r ... t0)))] [(_ v0 v ... #:rest (r ...)) (let ([t0 v0]) (or (equal? #t t0) (or-|| v ... #:rest (r ... t0))))] [(_ v0 v ...) (let ([t0 v0]) (or (equal? #t t0) (or-|| v ... #:rest (t0))))])) (define-syntax-rule (instance-of? primitive-type ... symbolic-type) (match-lambda [(? primitive-type) #t] ... [(and (? typed? v) (app get-type t)) (or (and t (subtype? t symbolic-type)) (and (union? v) (apply || (for/list ([g (in-union-guards v symbolic-type)]) g))))] [_ #f])) (define ⊥ (void)) (define-syntax first-term-or-bool (syntax-rules () [(_ e) e] [(_ e0 e ...) (let ([v e0]) (if (void? v) (first-term-or-bool e ...) v))])) (define-syntax-rule (quantifier @op) (lambda (vars body) (match* (vars body) [((list) _) body] [(_ (? boolean?)) body] [(_ _) (expression @op vars body)]))) (define-syntax-rule (logical-connective op co iden !iden) (case-lambda [() iden] [(x) x] [(x y) (match* (x y) [((== iden) _) y] [(_ (== iden)) x] [((== !iden) _) !iden] [(_ (== !iden)) !iden] [(_ _) (first-term-or-bool (simplify-connective op co !iden x y) (if (term<? x y) (expression op x y) (expression op y x)))])] [xs (cond [(member !iden xs) !iden] [else (match (simplify-fp op co !iden (remove-duplicates (filter term? xs))) [(list) iden] [(list x) x] [ys (apply expression op (sort ys term<?))])])])) (define (simplify-connective op co !iden x y) (match* (x y) [(_ (== x)) x] [((? expression?) (? expression?)) (first-term-or-bool (if (term<? y x) (simplify-connective:expr/any op co !iden x y) (simplify-connective:expr/any op co !iden y x)) (simplify-connective:expr/expr op co !iden x y))] [((? expression?) _) (if (term<? y x) (simplify-connective:expr/any op co !iden x y) ⊥)] [(_ (? expression?)) (if (term<? x y) (simplify-connective:expr/any op co !iden y x) ⊥)] [(_ _) ⊥])) (define (simplify-connective:expr/any op co !iden x y) (match x [(expression (== @!) (== y)) !iden] [(expression (== co) _ ... (== y) _ ...) y] [(expression (== op) _ ... (== y) _ ...) x] [(expression (== op) _ ... (expression (== @!) (== y)) _ ...) !iden] [(expression (== @!) (expression (== co) _ ... (== y) _ ...)) !iden] [_ ⊥])) (define (simplify-connective:expr/expr op co !iden a b) (match* (a b) [((expression (== op) _ ... x _ ...) (expression (== @!) x)) !iden] [((expression (== @!) x) (expression (== op) _ ... x _ ...)) !iden] [((expression (== op) xs ...) (expression (== op) ys ...)) (cond [(sublist? xs ys) b] [(sublist? ys xs) a] [(for*/or ([x xs][y ys]) (cancel? x y)) !iden] [else ⊥])] [((expression (== co) xs ...) (expression (== co) ys ...)) (cond [(sublist? xs ys) a] [(sublist? ys xs) b] [else ⊥])] [((expression (== op) xs ...) (expression (== co) ys ...)) (cond [(for*/or ([x xs][y ys]) (equal? x y)) a] [else ⊥])] [((expression (== co) xs ...) (expression (== op) ys ...)) (cond [(for*/or ([y ys][x xs]) (equal? x y)) b] [else ⊥])] [(_ _) ⊥])) (define (simplify-fp op co !iden xs) (or (and (> (length xs) 10) xs) (let-values ([(!ys ys) (for/fold ([!ys '()][ys '()]) ([x xs]) (match x [(expression (== @!) y) (values (cons y !ys) ys)] [_ (values !ys (cons x ys))]))]) (for/first ([!y !ys] #:when (member !y ys)) (list !iden))) (let outer ([xs xs]) (match xs [(list x rest ..1) (let inner ([head rest] [tail '()]) (match head [(list) (match (outer tail) [(and (list (== !iden)) t) t] [t (cons x t)])] [(list y ys ...) (match (simplify-connective op co !iden x y) [(== ⊥) (inner ys (cons y tail))] [(== !iden) (list !iden)] [v (outer (cons v (append ys tail)))])]))] [_ xs])))) (define (cancel? a b) (match* (a b) [(_ (expression (== @!) (== a))) #t] [((expression (== @!) (== b)) _) #t] [(_ _) #f])) A verification condition ( VC ) consists of two @boolean ? during execution . A VC is legal if at least one of its (struct vc (assumes asserts) #:transparent) (define vc-true (vc #t #t)) (define (vc-true? s) (equal? s vc-true)) Returns ( vc ( s.assumes & & ( s.asserts = ) ) s.asserts ) . (vc (&& (vc-assumes s) (=> (vc-asserts s) g)) (vc-asserts s))) (vc (vc-assumes s) (&& (vc-asserts s) (=> (vc-assumes s) g)))) (define current-vc (make-parameter vc-true (lambda (v) (unless (vc? v) (raise-argument-error 'vc "vc?" v)) v))) (define (get-vc) (current-vc)) (define (clear-vc!) (current-vc vc-true)) rewrite rules . Otherwise returns # f. (define (merge-absorbs? x g y) (match y x & & ( g = > ( x & & g ) ) x & & ( g = > ( x & & g ) ) x & & ( g = > ( x & & ( _ = > g ) ) ) x & & ( g = > ( ( _ = > g ) & & x ) ) [_ #f])) Returns ( field x ) & & ( gs[0 ] = > ( field ys[0 ] ) ) ... & & ( gs[n-1 ] = > ( field gs[n-1 ] ) ) . (define (merge-field field x gs ys) (define xf (field x)) (apply && xf (for*/list ([(g y) (in-parallel gs ys)] [yf (in-value (field y))] #:unless (merge-absorbs? xf g yf)) (=> g yf)))) Returns ( field x ) & & ( gs[0 ] = > ( field ys[0 ] ) ) ... & & ( gs[n-1 ] = > ( field gs[n-1 ] ) ) . ( define gs=>ys ( for*/list ( [ ( g y ) ( in - parallel gs ys ) ] Takes as input a list of n guards and n vcs and sets the current vc to ( current - vc ) & & ( vc - guard ) & & ... & & ( vc - guard ) . (define (merge-vc! guards vcs) (unless (null? vcs) (define vc* (vc (merge-field vc-assumes (current-vc) guards vcs) (merge-field vc-asserts (current-vc) guards vcs))) (current-vc vc*) (when (false? (vc-assumes vc*)) (raise-exn:fail:svm:assume:core "contradiction")) (when (false? (vc-asserts vc*)) (raise-exn:fail:svm:assert:core "contradiction")))) Sets the current vc to ( vc - proc ( current - vc ) g ) where g is ( @true ? ) . If g is # f or the resulting vc 's vc - field value is # f , (define-syntax-rule (vc-set! val msg vc-proc vc-field raise-exn) (let* ([guard (@true? val)] [vc* (vc-proc (current-vc) guard)]) (current-vc vc*) (when (false? guard) (raise-exn msg)) (when (false? (vc-field vc*)) (raise-exn "contradiction")))) Sets the current vc to ( asserting ( current - vc ) g ) where g is ( @true ? ) . If g is # f or the resulting vc 's asserts field is # f , throws an (define-syntax-rule (vc-assert! val msg raise-kind) (vc-set! val msg asserting vc-asserts raise-kind)) Sets the current vc to ( assuming ( current - vc ) g ) where g is ( @true ? ) . If g is # f or the resulting vc 's assumes field is # f , throws an (define-syntax-rule (vc-assume! val msg raise-kind) (vc-set! val msg assuming vc-assumes raise-kind)) The $ assert form has three variants : ( $ assert val ) , ( $ assert val msg ) , and ( $ assert val msg kind ) , where is the value being asserted , msg The first two variants of this form are used for issuing assertions from within the Rosette core . The third variant is used to implement the @assert (define-syntax ($assert stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assert val #f raise-exn:fail:svm:assert:core))] [(_ val msg) (syntax/loc stx ($assert val msg raise-exn:fail:svm:assert:core))] [(_ val msg kind) (syntax/loc stx (vc-assert! val msg kind))])) (define-syntax ($assume stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assume val #f raise-exn:fail:svm:assume:core))] [(_ val msg) (syntax/loc stx ($assume val msg raise-exn:fail:svm:assume:core))] [(_ val msg kind) (syntax/loc stx (vc-assume! val msg kind))])) The @assert form modifies the current vc to reflect the issued assertion . The form has two variants ( @assert val ) and ( @assert val msg ) , where val val is This form is exposed to user code . (define-syntax (@assert stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assert val #f raise-exn:fail:svm:assert:user))] [(_ val msg) (syntax/loc stx ($assert val msg raise-exn:fail:svm:assert:user))])) The @assume form modifies the current vc to reflect the issued assumption . The form has two variants ( @assume val ) and ( @assume val msg ) , where val val is This form is exposed to user code . (define-syntax (@assume stx) (syntax-case stx () [(_ val) (syntax/loc stx ($assume val #f raise-exn:fail:svm:assume:user))] [(_ val msg) (syntax/loc stx ($assume val msg raise-exn:fail:svm:assume:user))])) (define (halt-svm ex) (define result (failed ex (current-vc))) ((current-reporter) 'exception result) result) (define result (failed (make-exn:fail:svm:assert:err (exn-message ex) (exn-continuation-marks ex)) (asserting (current-vc) #f))) ((current-reporter) 'exception result) result) The with - vc form has two variants , ( with - vc body ) and ( with - vc vc0 body ) . with vc0 as the initial vc . (define-syntax (with-vc stx) (syntax-case stx () [(_ body) (syntax/loc stx (with-vc (current-vc) body))] [(_ vc0 body) (syntax/loc stx (parameterize ([current-vc vc0]) (with-handlers ([exn:fail:svm? halt-svm] [exn:fail? halt-err]) (normal (let () body) (current-vc)))))]))
22bd74bdc2e8d2d7cec3507b30a339fe87cfafffa18c09d6ab0cebe058e8dd0e
GaloisInc/macaw
AbsEval.hs
| Copyright : ( c ) Galois , Inc 2015 - 2017 Maintainer : < > , < > This provides a set of functions for abstract evaluation of statements . Copyright : (c) Galois, Inc 2015-2017 Maintainer : Joe Hendrix <>, Simon Winwood <> This provides a set of functions for abstract evaluation of statements. -} # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE PatternGuards # # LANGUAGE ScopedTypeVariables # module Data.Macaw.Discovery.AbsEval ( absEvalStmt , absEvalStmts , absEvalReadMem ) where import Control.Lens import qualified Data.Map.Strict as Map import Data.Parameterized.Classes import Data.Macaw.AbsDomain.AbsState import Data.Macaw.Architecture.Info import Data.Macaw.CFG -- | Get the abstract value associated with an address. absEvalReadMem :: RegisterInfo (ArchReg a) => AbsProcessorState (ArchReg a) ids -> ArchAddrValue a ids -> MemRepr tp -- ^ Information about the memory layout for the value. -> ArchAbsValue a tp absEvalReadMem r a tp -- If the value is a stack entry, then see if there is a stack -- value associated with it. | StackOffsetAbsVal _ o <- transferValue r a , Just (StackEntry v_tp v) <- Map.lookup o (r^.curAbsStack) , Just Refl <- testEquality tp v_tp = v | otherwise = TopV -- | Get the abstract domain for the right-hand side of an assignment. transferRHS :: ArchitectureInfo a -> AbsProcessorState (ArchReg a) ids -> AssignRhs a (Value a ids) tp -> ArchAbsValue a tp transferRHS info r rhs = case rhs of EvalApp app -> withArchConstraints info $ transferApp r app SetUndefined _ -> TopV ReadMem a tp -> withArchConstraints info $ absEvalReadMem r a tp -- TODO: See if we should build a mux specific version CondReadMem tp _ a d -> withArchConstraints info $ do lub (absEvalReadMem r a tp) (transferValue r d) EvalArchFn f _ -> absEvalArchFn info r f -- | Merge in the value of the assignment. -- -- If we have already seen a value, this will combine with meet. addAssignment :: ArchitectureInfo a -> AbsProcessorState (ArchReg a) ids -> Assignment a ids tp -> AbsProcessorState (ArchReg a) ids addAssignment info s a = withArchConstraints info $ s & (absAssignments . assignLens (assignId a)) %~ (`meet` transferRHS info s (assignRhs a)) -- | Given a statement this modifies the processor state based on the statement. absEvalStmt :: ArchitectureInfo arch -> AbsProcessorState (ArchReg arch) ids -> Stmt arch ids -> AbsProcessorState (ArchReg arch) ids absEvalStmt info s stmt = withArchConstraints info $ case stmt of AssignStmt a -> addAssignment info s a WriteMem addr memRepr v -> do addMemWrite s addr memRepr v CondWriteMem cond addr memRepr v -> addCondMemWrite s cond addr memRepr v InstructionStart _ _ -> s Comment{} -> s ExecArchStmt astmt -> absEvalArchStmt info s astmt ArchState{} -> s -- This takes a processor state and updates it based on executing each statement . absEvalStmts : : Foldable t = > ArchitectureInfo arch - > AbsProcessorState ( arch ) ids - > t ( Stmt arch ids ) - > AbsProcessorState ( arch ) ids absEvalStmts info = foldl ' ( info ) -- This takes a processor state and updates it based on executing each statement. absEvalStmts :: Foldable t => ArchitectureInfo arch -> AbsProcessorState (ArchReg arch) ids -> t (Stmt arch ids) -> AbsProcessorState (ArchReg arch) ids absEvalStmts info = foldl' (absEvalStmt info) -}
null
https://raw.githubusercontent.com/GaloisInc/macaw/ff894f9286f976d0ab131325bea902ef6275aad2/base/src/Data/Macaw/Discovery/AbsEval.hs
haskell
# LANGUAGE GADTs # | Get the abstract value associated with an address. ^ Information about the memory layout for the value. If the value is a stack entry, then see if there is a stack value associated with it. | Get the abstract domain for the right-hand side of an assignment. TODO: See if we should build a mux specific version | Merge in the value of the assignment. If we have already seen a value, this will combine with meet. | Given a statement this modifies the processor state based on the statement. This takes a processor state and updates it based on executing each statement . This takes a processor state and updates it based on executing each statement.
| Copyright : ( c ) Galois , Inc 2015 - 2017 Maintainer : < > , < > This provides a set of functions for abstract evaluation of statements . Copyright : (c) Galois, Inc 2015-2017 Maintainer : Joe Hendrix <>, Simon Winwood <> This provides a set of functions for abstract evaluation of statements. -} # LANGUAGE FlexibleContexts # # LANGUAGE PatternGuards # # LANGUAGE ScopedTypeVariables # module Data.Macaw.Discovery.AbsEval ( absEvalStmt , absEvalStmts , absEvalReadMem ) where import Control.Lens import qualified Data.Map.Strict as Map import Data.Parameterized.Classes import Data.Macaw.AbsDomain.AbsState import Data.Macaw.Architecture.Info import Data.Macaw.CFG absEvalReadMem :: RegisterInfo (ArchReg a) => AbsProcessorState (ArchReg a) ids -> ArchAddrValue a ids -> MemRepr tp -> ArchAbsValue a tp absEvalReadMem r a tp | StackOffsetAbsVal _ o <- transferValue r a , Just (StackEntry v_tp v) <- Map.lookup o (r^.curAbsStack) , Just Refl <- testEquality tp v_tp = v | otherwise = TopV transferRHS :: ArchitectureInfo a -> AbsProcessorState (ArchReg a) ids -> AssignRhs a (Value a ids) tp -> ArchAbsValue a tp transferRHS info r rhs = case rhs of EvalApp app -> withArchConstraints info $ transferApp r app SetUndefined _ -> TopV ReadMem a tp -> withArchConstraints info $ absEvalReadMem r a tp CondReadMem tp _ a d -> withArchConstraints info $ do lub (absEvalReadMem r a tp) (transferValue r d) EvalArchFn f _ -> absEvalArchFn info r f addAssignment :: ArchitectureInfo a -> AbsProcessorState (ArchReg a) ids -> Assignment a ids tp -> AbsProcessorState (ArchReg a) ids addAssignment info s a = withArchConstraints info $ s & (absAssignments . assignLens (assignId a)) %~ (`meet` transferRHS info s (assignRhs a)) absEvalStmt :: ArchitectureInfo arch -> AbsProcessorState (ArchReg arch) ids -> Stmt arch ids -> AbsProcessorState (ArchReg arch) ids absEvalStmt info s stmt = withArchConstraints info $ case stmt of AssignStmt a -> addAssignment info s a WriteMem addr memRepr v -> do addMemWrite s addr memRepr v CondWriteMem cond addr memRepr v -> addCondMemWrite s cond addr memRepr v InstructionStart _ _ -> s Comment{} -> s ExecArchStmt astmt -> absEvalArchStmt info s astmt ArchState{} -> s absEvalStmts : : Foldable t = > ArchitectureInfo arch - > AbsProcessorState ( arch ) ids - > t ( Stmt arch ids ) - > AbsProcessorState ( arch ) ids absEvalStmts info = foldl ' ( info ) absEvalStmts :: Foldable t => ArchitectureInfo arch -> AbsProcessorState (ArchReg arch) ids -> t (Stmt arch ids) -> AbsProcessorState (ArchReg arch) ids absEvalStmts info = foldl' (absEvalStmt info) -}
109e28b4bc1869db2a79ed7732ac79eaecbafe2724e9edf24f923e570e3f6bbd
takikawa/racket-ppa
syntax-local.rkt
#lang racket/base (require "../common/set.rkt" "../common/struct-star.rkt" "../syntax/syntax.rkt" "../common/phase.rkt" "../common/phase+space.rkt" "../syntax/scope.rkt" "../syntax/binding.rkt" "../syntax/taint.rkt" "env.rkt" "context.rkt" "main.rkt" "../namespace/core.rkt" "use-site.rkt" "rename-trans.rkt" "lift-context.rkt" "require.rkt" "require+provide.rkt" "protect.rkt" "log.rkt" "module-path.rkt" "definition-context.rkt" "../common/module-path.rkt" "../namespace/namespace.rkt" "../namespace/module.rkt" "../common/contract.rkt") (provide syntax-transforming? syntax-transforming-with-lifts? syntax-transforming-module-expression? syntax-local-transforming-module-provides? syntax-local-context syntax-local-introduce syntax-local-identifier-as-binding syntax-local-phase-level syntax-local-name make-syntax-introducer make-interned-syntax-introducer make-syntax-delta-introducer syntax-local-make-delta-introducer syntax-local-value syntax-local-value/immediate syntax-local-lift-expression syntax-local-lift-values-expression syntax-local-lift-context syntax-local-lift-module syntax-local-lift-require syntax-local-lift-provide syntax-local-lift-module-end-declaration syntax-local-module-defined-identifiers syntax-local-module-required-identifiers syntax-local-module-exports syntax-local-submodules syntax-local-module-interned-scope-symbols syntax-local-expand-observer syntax-local-get-shadower) ;; ---------------------------------------- (define (syntax-transforming?) (and (get-current-expand-context #:fail-ok? #t) #t)) (define (syntax-transforming-with-lifts?) (define ctx (get-current-expand-context #:fail-ok? #t)) (and ctx (expand-context-lifts ctx) #t)) (define (syntax-transforming-module-expression?) (define ctx (get-current-expand-context #:fail-ok? #t)) (and ctx (expand-context-to-module-lifts ctx) #t)) (define (syntax-local-transforming-module-provides?) (define ctx (get-current-expand-context #:fail-ok? #t)) (and ctx (expand-context-requires+provides ctx) #t)) ;; ---------------------------------------- (define (syntax-local-context) (define ctx (get-current-expand-context 'syntax-local-context)) (expand-context-context ctx)) (define/who (syntax-local-introduce s) (check who syntax? s) (define ctx (get-current-expand-context 'syntax-local-introduce)) (define new-s (flip-introduction-and-use-scopes s ctx)) (log-expand ctx 'track-syntax 'syntax-local-introduce new-s s) new-s) (define/who (syntax-local-identifier-as-binding id [intdef #f]) (check who identifier? id) (when intdef (check who internal-definition-context? intdef)) (define ctx (get-current-expand-context 'syntax-local-identifier-as-binding)) (define new-id (if intdef (remove-intdef-use-site-scopes id intdef) (remove-use-site-scopes id ctx))) (log-expand ctx 'track-syntax 'syntax-local-identifier-as-binding new-id id) new-id) (define (syntax-local-phase-level) (define ctx (get-current-expand-context #:fail-ok? #t)) (if ctx (expand-context-phase ctx) 0)) (define/who (syntax-local-name) (define ctx (get-current-expand-context who)) (define id (expand-context-name ctx)) (and id Strip lexical context , but keep source - location information (datum->syntax #f (syntax-e id) id))) ;; ---------------------------------------- (define (make-syntax-introducer [as-use-site? #f]) (do-make-syntax-introducer (new-scope (if as-use-site? 'use-site 'macro)))) (define/who (make-interned-syntax-introducer sym-key) (check who (lambda (v) (and (symbol? v) (symbol-interned? v))) #:contract "(and/c symbol? symbol-interned?)" sym-key) (do-make-syntax-introducer (make-interned-scope sym-key))) (define (do-make-syntax-introducer sc) (lambda (s [mode 'flip]) (check 'syntax-introducer syntax? s) (define new-s (case mode [(add) (add-scope s sc)] [(remove) (remove-scope s sc)] [(flip) (flip-scope s sc)] [else (raise-argument-error 'syntax-introducer "(or/c 'add 'remove 'flip)" mode)])) (define ctx (get-current-expand-context #:fail-ok? #t)) (when ctx (log-expand ctx 'track-syntax mode new-s s)) new-s)) (define/who (make-syntax-delta-introducer ext-s base-s [phase (syntax-local-phase-level)]) (check who syntax? ext-s) (check who syntax? #:or-false base-s) (check who phase? #:contract phase?-string phase) (define ext-scs (syntax-scope-set ext-s phase)) (define base-scs (syntax-scope-set (or base-s empty-syntax) phase)) (define use-base-scs (if (subset? base-scs ext-scs) base-scs (or (and (identifier? base-s) (resolve base-s phase #:get-scopes? #t)) (seteq)))) (define delta-scs (set->list (set-subtract ext-scs use-base-scs))) (define maybe-taint (if (syntax-clean? ext-s) values syntax-taint)) (define shifts (syntax-mpi-shifts ext-s)) (lambda (s [mode 'add]) (check 'syntax-introducer syntax? s) (define new-s (maybe-taint (case mode [(add) (syntax-add-shifts (add-scopes s delta-scs) shifts #:non-source? #t)] [(remove) (remove-scopes s delta-scs)] [(flip) (syntax-add-shifts (flip-scopes s delta-scs) shifts #:non-source? #t)] [else (raise-argument-error 'syntax-introducer "(or/c 'add 'remove 'flip)" mode)]))) (define ctx (get-current-expand-context #:fail-ok? #t)) (when ctx (log-expand ctx 'track-syntax mode new-s s)) new-s)) (define/who (syntax-local-make-delta-introducer id-stx) (check who identifier? id-stx) (raise (exn:fail:unsupported "syntax-local-make-delta-introducer: not supported anymore" (current-continuation-marks)))) ;; ---------------------------------------- (define (do-syntax-local-value who id intdefs failure-thunk #:immediate? immediate?) (check who identifier? id) (check who #:or-false (procedure-arity-includes/c 0) failure-thunk) (check who intdefs-or-false? #:contract intdefs-or-false?-string intdefs) (define current-ctx (get-current-expand-context who)) (define ctx (if intdefs (struct*-copy expand-context current-ctx [env (add-intdef-bindings (expand-context-env current-ctx) intdefs)]) current-ctx)) (log-expand ctx 'local-value id) (define phase (expand-context-phase ctx)) (let loop ([id (flip-introduction-scopes id ctx)]) (define b (if immediate? (resolve+shift id phase #:immediate? #t) (resolve+shift/extra-inspector id phase (expand-context-namespace ctx)))) (log-expand ctx 'resolve id) (cond [(not b) (log-expand ctx 'local-value-result #f) (if failure-thunk (failure-thunk) (error who "unbound identifier: ~v" id))] [else (define-values (v primitive? insp protected?) (lookup b ctx id #:out-of-context-as-variable? #t)) (cond [(or (variable? v) (core-form? v)) (log-expand ctx 'local-value-result #f) (if failure-thunk (failure-thunk) (error who "identifier is not bound to syntax: ~v" id))] [else (log-expand* ctx #:unless (and (rename-transformer? v) (not immediate?)) ['local-value-result #t]) (cond [(rename-transformer? v) (if immediate? (values v (rename-transformer-target-in-context v ctx)) (loop (rename-transformer-target-in-context v ctx)))] [immediate? (values v #f)] [else v])])]))) (define/who (syntax-local-value id [failure-thunk #f] [intdef #f]) (do-syntax-local-value who #:immediate? #f id intdef failure-thunk)) (define/who (syntax-local-value/immediate id [failure-thunk #f] [intdef #f]) (do-syntax-local-value who #:immediate? #t id intdef failure-thunk)) ;; ---------------------------------------- (define (do-lift-values-expression who n s) (check who syntax? s) (check who exact-nonnegative-integer? n) (define ctx (get-current-expand-context who)) (define lifts (expand-context-lifts ctx)) (unless lifts (raise-arguments-error who "no lift target")) (define counter (root-expand-context-counter ctx)) (define ids (for/list ([i (in-range n)]) (set-box! counter (add1 (unbox counter))) (define name (string->unreadable-symbol (format "lifted/~a" (unbox counter)))) (add-scope (datum->syntax #f name) (new-scope 'macro)))) (define added-s (flip-introduction-scopes s ctx)) (log-expand ctx 'lift-expr ids s added-s) (map (lambda (id) (flip-introduction-scopes id ctx)) ;; returns converted ids: (add-lifted! lifts ids added-s (expand-context-phase ctx)))) (define/who (syntax-local-lift-expression s) (car (do-lift-values-expression who 1 s))) (define/who (syntax-local-lift-values-expression n s) (do-lift-values-expression who n s)) (define/who (syntax-local-lift-context) (define ctx (get-current-expand-context who)) (root-expand-context-lift-key ctx)) ;; ---------------------------------------- (define/who (syntax-local-lift-module s) (check who syntax? s) (define ctx (get-current-expand-context who)) (define phase (expand-context-phase ctx)) (case (core-form-sym s phase) [(module module*) (define lifts (expand-context-module-lifts ctx)) (unless lifts (raise-arguments-error who "not currently transforming within a module declaration or top level" "form to lift" s)) (define added-s (flip-introduction-scopes s ctx)) (add-lifted-module! lifts added-s phase) (log-expand ctx 'lift-module s added-s)] [else (raise-arguments-error who "not a module form" "given form" s)])) ;; ---------------------------------------- (define (do-local-lift-to-module who s #:log-tag [log-tag #f] #:no-target-msg no-target-msg #:intro? [intro? #t] #:more-checks [more-checks void] #:get-lift-ctx get-lift-ctx #:add-lifted! add-lifted! #:get-wrt-phase get-wrt-phase #:pre-wrap [pre-wrap (lambda (s phase lift-ctx) s)] #:shift-wrap [shift-wrap (lambda (s phase lift-ctx) s)] #:post-wrap [post-wrap (lambda (s phase lift-ctx) s)]) (check who syntax? s) (more-checks) (define ctx (get-current-expand-context who)) (define lift-ctx (get-lift-ctx ctx)) (unless lift-ctx (raise-arguments-error who no-target-msg "form to lift" s)) (define phase (expand-context-phase ctx)) ; we're currently at this phase (define wrt-phase (get-wrt-phase lift-ctx)) ; lift context is at this phase (define added-s (if intro? (flip-introduction-scopes s ctx) s)) (define pre-s (pre-wrap added-s phase lift-ctx)) ; add pre-wrap at current phase (define shift-s (for/fold ([s pre-s]) ([phase (in-range phase wrt-phase -1)]) ; shift from lift-context phase (shift-wrap s (sub1 phase) lift-ctx))) (define post-s (post-wrap shift-s wrt-phase lift-ctx)) ; post-wrap at lift-context phase (when log-tag ;; Separate changes in scopes (s -> added-s) from wrapping (added-s -> post-s). (log-expand ctx log-tag s added-s post-s)) (add-lifted! lift-ctx post-s wrt-phase) ; record lift for the target phase (values ctx post-s)) (define/who (syntax-local-lift-require s use-s) (define sc (new-scope 'lifted-require)) (define-values (ctx added-s) (do-local-lift-to-module who (datum->syntax #f s) #:no-target-msg "could not find target context" #:intro? #f #:more-checks (lambda () (check who syntax? use-s)) #:get-lift-ctx expand-context-require-lifts #:get-wrt-phase require-lift-context-wrt-phase #:add-lifted! add-lifted-require! #:shift-wrap (lambda (s phase require-lift-ctx) (require-spec-shift-for-syntax s)) #:post-wrap (lambda (s phase require-lift-ctx) (wrap-form '#%require (add-scope s sc) phase)))) (without-expand-context (namespace-visit-available-modules! (expand-context-namespace ctx) (expand-context-phase ctx))) (define result-s (add-scope use-s sc)) (log-expand ctx 'lift-require added-s use-s result-s) result-s) (define/who (syntax-local-lift-provide s) (define-values (ctx result-s) (do-local-lift-to-module who s #:no-target-msg "not expanding in a module run-time body" #:get-lift-ctx expand-context-to-module-lifts #:get-wrt-phase to-module-lift-context-wrt-phase #:add-lifted! add-lifted-to-module-provide! #:shift-wrap (lambda (s phase to-module-lift-ctx) (wrap-form 'for-syntax s #f)) #:post-wrap (lambda (s phase to-module-lift-ctx) (wrap-form '#%provide s phase)))) (log-expand ctx 'lift-provide result-s)) (define/who (syntax-local-lift-module-end-declaration s) (define-values (ctx also-s) (do-local-lift-to-module who s #:log-tag 'lift-end-decl #:no-target-msg "not currently transforming an expression within a module declaration" #:get-lift-ctx expand-context-to-module-lifts always relative to 0 #:add-lifted! add-lifted-to-module-end! #:pre-wrap (lambda (orig-s phase to-module-lift-ctx) (if (to-module-lift-context-end-as-expressions? to-module-lift-ctx) (wrap-form '#%expression orig-s phase) orig-s)) #:shift-wrap (lambda (s phase to-module-lift-ctx) (wrap-form 'begin-for-syntax s phase)))) (void)) (define (wrap-form sym s phase) (datum->syntax #f (list (datum->syntax (if phase (syntax-shift-phase-level core-stx phase) #f) sym) s))) ;; ---------------------------------------- (define/who (syntax-local-module-defined-identifiers) (unless (syntax-local-transforming-module-provides?) (raise-arguments-error who "not currently transforming module provides")) (define ctx (get-current-expand-context 'syntax-local-module-defined-identifiers)) (requireds->phase-ht (extract-module-definitions (expand-context-requires+provides ctx)))) (define/who (syntax-local-module-required-identifiers mod-path phase+space-shift) (unless (or (not mod-path) (module-path? mod-path)) (raise-argument-error who "(or/c module-path? #f)" mod-path)) (unless (or (eq? phase+space-shift #t) (phase+space-shift? phase+space-shift)) (raise-argument-error who (format "(or/c ~a #t)" phase+space-shift?-string) phase+space-shift)) (unless (syntax-local-transforming-module-provides?) (raise-arguments-error who "not currently transforming module provides")) (define ctx (get-current-expand-context 'syntax-local-module-required-identifiers)) (define requires+provides (expand-context-requires+provides ctx)) (define mpi (and mod-path (module-path->mpi/context mod-path ctx))) (define requireds (extract-all-module-requires requires+provides mpi (if (eq? phase+space-shift #t) 'all (intern-phase+space-shift phase+space-shift)))) (and requireds (for/list ([(phase+space-shift ids) (in-hash (requireds->phase-ht requireds))]) (cons phase+space-shift ids)))) (define (requireds->phase-ht requireds) (for/fold ([ht (hasheqv)]) ([r (in-list requireds)]) (hash-update ht (required-phase+space r) (lambda (l) (cons (required-id r) l)) null))) ;; ---------------------------------------- (define/who (syntax-local-module-exports mod-path) (unless (or (module-path? mod-path) (and (syntax? mod-path) (module-path? (syntax->datum mod-path)))) (raise-argument-error who (string-append "(or/c module-path?\n" " (and/c syntax?\n" " (lambda (stx)\n" " (module-path? (syntax->datum stx)))))") mod-path)) (define ctx (get-current-expand-context 'syntax-local-module-exports)) (define ns (expand-context-namespace ctx)) (define mod-name (module-path-index-resolve (module-path->mpi/context (if (syntax? mod-path) (syntax->datum mod-path) mod-path) ctx) #t)) (define m (namespace->module ns mod-name)) (unless m (raise-unknown-module-error 'syntax-local-module-exports mod-name)) (for/list ([(phase syms) (in-hash (module-provides m))]) (cons phase (for/list ([sym (in-hash-keys syms)]) sym)))) (define/who (syntax-local-submodules) (define ctx (get-current-expand-context who)) (define submods (expand-context-declared-submodule-names ctx)) (for/list ([(name kind) (in-hash submods)] #:when (eq? kind 'module)) name)) (define/who (syntax-local-module-interned-scope-symbols) ;; just returns all interned-scope symbols, but defined ;; relative to a module expansion in case it's necessary to ;; do better in the future (void (get-current-expand-context who)) (interned-scope-symbols)) ;; ---------------------------------------- Exported via # % expobs , not # % kernel (define/who (syntax-local-expand-observer) (define ctx (get-current-expand-context 'syntax-local-expand-observer)) (expand-context-observer ctx)) ;; ---------------------------------------- ;; Works well enough for some backward compatibility: (define/who (syntax-local-get-shadower id [only-generated? #f]) (check who identifier? id) (define ctx (get-current-expand-context who)) (define new-id (add-scopes id (expand-context-scopes ctx))) (if (syntax-clean? id) new-id (syntax-taint new-id)))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/src/expander/expand/syntax-local.rkt
racket
---------------------------------------- ---------------------------------------- ---------------------------------------- ---------------------------------------- ---------------------------------------- returns converted ids: ---------------------------------------- ---------------------------------------- we're currently at this phase lift context is at this phase add pre-wrap at current phase shift from lift-context phase post-wrap at lift-context phase Separate changes in scopes (s -> added-s) from wrapping (added-s -> post-s). record lift for the target phase ---------------------------------------- ---------------------------------------- just returns all interned-scope symbols, but defined relative to a module expansion in case it's necessary to do better in the future ---------------------------------------- ---------------------------------------- Works well enough for some backward compatibility:
#lang racket/base (require "../common/set.rkt" "../common/struct-star.rkt" "../syntax/syntax.rkt" "../common/phase.rkt" "../common/phase+space.rkt" "../syntax/scope.rkt" "../syntax/binding.rkt" "../syntax/taint.rkt" "env.rkt" "context.rkt" "main.rkt" "../namespace/core.rkt" "use-site.rkt" "rename-trans.rkt" "lift-context.rkt" "require.rkt" "require+provide.rkt" "protect.rkt" "log.rkt" "module-path.rkt" "definition-context.rkt" "../common/module-path.rkt" "../namespace/namespace.rkt" "../namespace/module.rkt" "../common/contract.rkt") (provide syntax-transforming? syntax-transforming-with-lifts? syntax-transforming-module-expression? syntax-local-transforming-module-provides? syntax-local-context syntax-local-introduce syntax-local-identifier-as-binding syntax-local-phase-level syntax-local-name make-syntax-introducer make-interned-syntax-introducer make-syntax-delta-introducer syntax-local-make-delta-introducer syntax-local-value syntax-local-value/immediate syntax-local-lift-expression syntax-local-lift-values-expression syntax-local-lift-context syntax-local-lift-module syntax-local-lift-require syntax-local-lift-provide syntax-local-lift-module-end-declaration syntax-local-module-defined-identifiers syntax-local-module-required-identifiers syntax-local-module-exports syntax-local-submodules syntax-local-module-interned-scope-symbols syntax-local-expand-observer syntax-local-get-shadower) (define (syntax-transforming?) (and (get-current-expand-context #:fail-ok? #t) #t)) (define (syntax-transforming-with-lifts?) (define ctx (get-current-expand-context #:fail-ok? #t)) (and ctx (expand-context-lifts ctx) #t)) (define (syntax-transforming-module-expression?) (define ctx (get-current-expand-context #:fail-ok? #t)) (and ctx (expand-context-to-module-lifts ctx) #t)) (define (syntax-local-transforming-module-provides?) (define ctx (get-current-expand-context #:fail-ok? #t)) (and ctx (expand-context-requires+provides ctx) #t)) (define (syntax-local-context) (define ctx (get-current-expand-context 'syntax-local-context)) (expand-context-context ctx)) (define/who (syntax-local-introduce s) (check who syntax? s) (define ctx (get-current-expand-context 'syntax-local-introduce)) (define new-s (flip-introduction-and-use-scopes s ctx)) (log-expand ctx 'track-syntax 'syntax-local-introduce new-s s) new-s) (define/who (syntax-local-identifier-as-binding id [intdef #f]) (check who identifier? id) (when intdef (check who internal-definition-context? intdef)) (define ctx (get-current-expand-context 'syntax-local-identifier-as-binding)) (define new-id (if intdef (remove-intdef-use-site-scopes id intdef) (remove-use-site-scopes id ctx))) (log-expand ctx 'track-syntax 'syntax-local-identifier-as-binding new-id id) new-id) (define (syntax-local-phase-level) (define ctx (get-current-expand-context #:fail-ok? #t)) (if ctx (expand-context-phase ctx) 0)) (define/who (syntax-local-name) (define ctx (get-current-expand-context who)) (define id (expand-context-name ctx)) (and id Strip lexical context , but keep source - location information (datum->syntax #f (syntax-e id) id))) (define (make-syntax-introducer [as-use-site? #f]) (do-make-syntax-introducer (new-scope (if as-use-site? 'use-site 'macro)))) (define/who (make-interned-syntax-introducer sym-key) (check who (lambda (v) (and (symbol? v) (symbol-interned? v))) #:contract "(and/c symbol? symbol-interned?)" sym-key) (do-make-syntax-introducer (make-interned-scope sym-key))) (define (do-make-syntax-introducer sc) (lambda (s [mode 'flip]) (check 'syntax-introducer syntax? s) (define new-s (case mode [(add) (add-scope s sc)] [(remove) (remove-scope s sc)] [(flip) (flip-scope s sc)] [else (raise-argument-error 'syntax-introducer "(or/c 'add 'remove 'flip)" mode)])) (define ctx (get-current-expand-context #:fail-ok? #t)) (when ctx (log-expand ctx 'track-syntax mode new-s s)) new-s)) (define/who (make-syntax-delta-introducer ext-s base-s [phase (syntax-local-phase-level)]) (check who syntax? ext-s) (check who syntax? #:or-false base-s) (check who phase? #:contract phase?-string phase) (define ext-scs (syntax-scope-set ext-s phase)) (define base-scs (syntax-scope-set (or base-s empty-syntax) phase)) (define use-base-scs (if (subset? base-scs ext-scs) base-scs (or (and (identifier? base-s) (resolve base-s phase #:get-scopes? #t)) (seteq)))) (define delta-scs (set->list (set-subtract ext-scs use-base-scs))) (define maybe-taint (if (syntax-clean? ext-s) values syntax-taint)) (define shifts (syntax-mpi-shifts ext-s)) (lambda (s [mode 'add]) (check 'syntax-introducer syntax? s) (define new-s (maybe-taint (case mode [(add) (syntax-add-shifts (add-scopes s delta-scs) shifts #:non-source? #t)] [(remove) (remove-scopes s delta-scs)] [(flip) (syntax-add-shifts (flip-scopes s delta-scs) shifts #:non-source? #t)] [else (raise-argument-error 'syntax-introducer "(or/c 'add 'remove 'flip)" mode)]))) (define ctx (get-current-expand-context #:fail-ok? #t)) (when ctx (log-expand ctx 'track-syntax mode new-s s)) new-s)) (define/who (syntax-local-make-delta-introducer id-stx) (check who identifier? id-stx) (raise (exn:fail:unsupported "syntax-local-make-delta-introducer: not supported anymore" (current-continuation-marks)))) (define (do-syntax-local-value who id intdefs failure-thunk #:immediate? immediate?) (check who identifier? id) (check who #:or-false (procedure-arity-includes/c 0) failure-thunk) (check who intdefs-or-false? #:contract intdefs-or-false?-string intdefs) (define current-ctx (get-current-expand-context who)) (define ctx (if intdefs (struct*-copy expand-context current-ctx [env (add-intdef-bindings (expand-context-env current-ctx) intdefs)]) current-ctx)) (log-expand ctx 'local-value id) (define phase (expand-context-phase ctx)) (let loop ([id (flip-introduction-scopes id ctx)]) (define b (if immediate? (resolve+shift id phase #:immediate? #t) (resolve+shift/extra-inspector id phase (expand-context-namespace ctx)))) (log-expand ctx 'resolve id) (cond [(not b) (log-expand ctx 'local-value-result #f) (if failure-thunk (failure-thunk) (error who "unbound identifier: ~v" id))] [else (define-values (v primitive? insp protected?) (lookup b ctx id #:out-of-context-as-variable? #t)) (cond [(or (variable? v) (core-form? v)) (log-expand ctx 'local-value-result #f) (if failure-thunk (failure-thunk) (error who "identifier is not bound to syntax: ~v" id))] [else (log-expand* ctx #:unless (and (rename-transformer? v) (not immediate?)) ['local-value-result #t]) (cond [(rename-transformer? v) (if immediate? (values v (rename-transformer-target-in-context v ctx)) (loop (rename-transformer-target-in-context v ctx)))] [immediate? (values v #f)] [else v])])]))) (define/who (syntax-local-value id [failure-thunk #f] [intdef #f]) (do-syntax-local-value who #:immediate? #f id intdef failure-thunk)) (define/who (syntax-local-value/immediate id [failure-thunk #f] [intdef #f]) (do-syntax-local-value who #:immediate? #t id intdef failure-thunk)) (define (do-lift-values-expression who n s) (check who syntax? s) (check who exact-nonnegative-integer? n) (define ctx (get-current-expand-context who)) (define lifts (expand-context-lifts ctx)) (unless lifts (raise-arguments-error who "no lift target")) (define counter (root-expand-context-counter ctx)) (define ids (for/list ([i (in-range n)]) (set-box! counter (add1 (unbox counter))) (define name (string->unreadable-symbol (format "lifted/~a" (unbox counter)))) (add-scope (datum->syntax #f name) (new-scope 'macro)))) (define added-s (flip-introduction-scopes s ctx)) (log-expand ctx 'lift-expr ids s added-s) (map (lambda (id) (flip-introduction-scopes id ctx)) (add-lifted! lifts ids added-s (expand-context-phase ctx)))) (define/who (syntax-local-lift-expression s) (car (do-lift-values-expression who 1 s))) (define/who (syntax-local-lift-values-expression n s) (do-lift-values-expression who n s)) (define/who (syntax-local-lift-context) (define ctx (get-current-expand-context who)) (root-expand-context-lift-key ctx)) (define/who (syntax-local-lift-module s) (check who syntax? s) (define ctx (get-current-expand-context who)) (define phase (expand-context-phase ctx)) (case (core-form-sym s phase) [(module module*) (define lifts (expand-context-module-lifts ctx)) (unless lifts (raise-arguments-error who "not currently transforming within a module declaration or top level" "form to lift" s)) (define added-s (flip-introduction-scopes s ctx)) (add-lifted-module! lifts added-s phase) (log-expand ctx 'lift-module s added-s)] [else (raise-arguments-error who "not a module form" "given form" s)])) (define (do-local-lift-to-module who s #:log-tag [log-tag #f] #:no-target-msg no-target-msg #:intro? [intro? #t] #:more-checks [more-checks void] #:get-lift-ctx get-lift-ctx #:add-lifted! add-lifted! #:get-wrt-phase get-wrt-phase #:pre-wrap [pre-wrap (lambda (s phase lift-ctx) s)] #:shift-wrap [shift-wrap (lambda (s phase lift-ctx) s)] #:post-wrap [post-wrap (lambda (s phase lift-ctx) s)]) (check who syntax? s) (more-checks) (define ctx (get-current-expand-context who)) (define lift-ctx (get-lift-ctx ctx)) (unless lift-ctx (raise-arguments-error who no-target-msg "form to lift" s)) (define added-s (if intro? (flip-introduction-scopes s ctx) s)) (shift-wrap s (sub1 phase) lift-ctx))) (when log-tag (log-expand ctx log-tag s added-s post-s)) (values ctx post-s)) (define/who (syntax-local-lift-require s use-s) (define sc (new-scope 'lifted-require)) (define-values (ctx added-s) (do-local-lift-to-module who (datum->syntax #f s) #:no-target-msg "could not find target context" #:intro? #f #:more-checks (lambda () (check who syntax? use-s)) #:get-lift-ctx expand-context-require-lifts #:get-wrt-phase require-lift-context-wrt-phase #:add-lifted! add-lifted-require! #:shift-wrap (lambda (s phase require-lift-ctx) (require-spec-shift-for-syntax s)) #:post-wrap (lambda (s phase require-lift-ctx) (wrap-form '#%require (add-scope s sc) phase)))) (without-expand-context (namespace-visit-available-modules! (expand-context-namespace ctx) (expand-context-phase ctx))) (define result-s (add-scope use-s sc)) (log-expand ctx 'lift-require added-s use-s result-s) result-s) (define/who (syntax-local-lift-provide s) (define-values (ctx result-s) (do-local-lift-to-module who s #:no-target-msg "not expanding in a module run-time body" #:get-lift-ctx expand-context-to-module-lifts #:get-wrt-phase to-module-lift-context-wrt-phase #:add-lifted! add-lifted-to-module-provide! #:shift-wrap (lambda (s phase to-module-lift-ctx) (wrap-form 'for-syntax s #f)) #:post-wrap (lambda (s phase to-module-lift-ctx) (wrap-form '#%provide s phase)))) (log-expand ctx 'lift-provide result-s)) (define/who (syntax-local-lift-module-end-declaration s) (define-values (ctx also-s) (do-local-lift-to-module who s #:log-tag 'lift-end-decl #:no-target-msg "not currently transforming an expression within a module declaration" #:get-lift-ctx expand-context-to-module-lifts always relative to 0 #:add-lifted! add-lifted-to-module-end! #:pre-wrap (lambda (orig-s phase to-module-lift-ctx) (if (to-module-lift-context-end-as-expressions? to-module-lift-ctx) (wrap-form '#%expression orig-s phase) orig-s)) #:shift-wrap (lambda (s phase to-module-lift-ctx) (wrap-form 'begin-for-syntax s phase)))) (void)) (define (wrap-form sym s phase) (datum->syntax #f (list (datum->syntax (if phase (syntax-shift-phase-level core-stx phase) #f) sym) s))) (define/who (syntax-local-module-defined-identifiers) (unless (syntax-local-transforming-module-provides?) (raise-arguments-error who "not currently transforming module provides")) (define ctx (get-current-expand-context 'syntax-local-module-defined-identifiers)) (requireds->phase-ht (extract-module-definitions (expand-context-requires+provides ctx)))) (define/who (syntax-local-module-required-identifiers mod-path phase+space-shift) (unless (or (not mod-path) (module-path? mod-path)) (raise-argument-error who "(or/c module-path? #f)" mod-path)) (unless (or (eq? phase+space-shift #t) (phase+space-shift? phase+space-shift)) (raise-argument-error who (format "(or/c ~a #t)" phase+space-shift?-string) phase+space-shift)) (unless (syntax-local-transforming-module-provides?) (raise-arguments-error who "not currently transforming module provides")) (define ctx (get-current-expand-context 'syntax-local-module-required-identifiers)) (define requires+provides (expand-context-requires+provides ctx)) (define mpi (and mod-path (module-path->mpi/context mod-path ctx))) (define requireds (extract-all-module-requires requires+provides mpi (if (eq? phase+space-shift #t) 'all (intern-phase+space-shift phase+space-shift)))) (and requireds (for/list ([(phase+space-shift ids) (in-hash (requireds->phase-ht requireds))]) (cons phase+space-shift ids)))) (define (requireds->phase-ht requireds) (for/fold ([ht (hasheqv)]) ([r (in-list requireds)]) (hash-update ht (required-phase+space r) (lambda (l) (cons (required-id r) l)) null))) (define/who (syntax-local-module-exports mod-path) (unless (or (module-path? mod-path) (and (syntax? mod-path) (module-path? (syntax->datum mod-path)))) (raise-argument-error who (string-append "(or/c module-path?\n" " (and/c syntax?\n" " (lambda (stx)\n" " (module-path? (syntax->datum stx)))))") mod-path)) (define ctx (get-current-expand-context 'syntax-local-module-exports)) (define ns (expand-context-namespace ctx)) (define mod-name (module-path-index-resolve (module-path->mpi/context (if (syntax? mod-path) (syntax->datum mod-path) mod-path) ctx) #t)) (define m (namespace->module ns mod-name)) (unless m (raise-unknown-module-error 'syntax-local-module-exports mod-name)) (for/list ([(phase syms) (in-hash (module-provides m))]) (cons phase (for/list ([sym (in-hash-keys syms)]) sym)))) (define/who (syntax-local-submodules) (define ctx (get-current-expand-context who)) (define submods (expand-context-declared-submodule-names ctx)) (for/list ([(name kind) (in-hash submods)] #:when (eq? kind 'module)) name)) (define/who (syntax-local-module-interned-scope-symbols) (void (get-current-expand-context who)) (interned-scope-symbols)) Exported via # % expobs , not # % kernel (define/who (syntax-local-expand-observer) (define ctx (get-current-expand-context 'syntax-local-expand-observer)) (expand-context-observer ctx)) (define/who (syntax-local-get-shadower id [only-generated? #f]) (check who identifier? id) (define ctx (get-current-expand-context who)) (define new-id (add-scopes id (expand-context-scopes ctx))) (if (syntax-clean? id) new-id (syntax-taint new-id)))
426718ce1772e7810740ccad0e8bc56ae639b20904302892591c720015ce5b8a
cornell-netlab/yates
Edksp.ml
open Core open Apsp open LP_Lang open Util open Yates_types.Types let prev_scheme = ref SrcDstMap.empty let use_min_cut = true let () = match !Globals.rand_seed with | Some x -> Random.init x | None -> Random.self_init ~allow_in_tests:true () let objective = Var "Z" let capacity_constraints (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = (* For every inter-switch edge, there is a unit capacity constraint *) Topology.fold_edges (fun edge acc -> if edge_connects_switches edge topo then let flow_on_edge = Var(var_name topo edge (src,dst)) in (* Total flow is at most 1 *) let name = Printf.sprintf "cap_%s" (string_of_edge topo edge) in (Leq (name, flow_on_edge, 1.))::acc else acc) topo init_acc let num_path_constraints (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (k:int) (init_acc : constrain list) : constrain list = (* Constraint: sum of out going flows to other switches from src's ingress switch = k *) let ingress_switch = outgoing_edges topo src |> List.hd_exn |> Topology.edge_dst |> fst in let edges = outgoing_edges topo ingress_switch in let diffs = List.fold_left edges ~init:[] ~f:(fun acc edge -> if edge_connects_switches edge topo then let forward_amt = var_name topo edge (src,dst) in let reverse_amt = var_name_rev topo edge (src,dst) in let net_outgoing = minus (Var (forward_amt)) (Var (reverse_amt)) in net_outgoing::acc else acc) in let sum_net_outgoing = Sum (diffs) in let name = Printf.sprintf "num-%s-%s" (name_of_vertex topo src) (name_of_vertex topo dst) in (Eq (name, sum_net_outgoing, Float.of_int k))::init_acc let conservation_constraints_st (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = (* Every node in the topology except the source and sink has conservation constraints *) Topology.fold_vertexes (fun v acc -> if Stdlib.(v = src || v = dst) then acc else let edges = outgoing_edges topo v in let outgoing = List.fold_left edges ~init:[] ~f:(fun acc_vars e -> (Var (var_name topo e (src,dst)))::acc_vars) in let incoming = List.fold_left edges ~init:[] ~f:(fun acc_vars e -> (Var (var_name_rev topo e (src,dst)))::acc_vars) in let total_out = Sum (outgoing) in let total_in = Sum (incoming) in let net = minus total_out total_in in let name = Printf.sprintf "con-%s-%s_%s" (name_of_vertex topo src) (name_of_vertex topo dst) (name_of_vertex topo v) in let constr = Eq (name, net, 0.) in constr::acc) topo init_acc let minimize_path_lengths (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = (* Set objective = sum of all path lengths *) let paths_list = Topology.fold_edges (fun e acc -> let weight = Link.weight (Topology.edge_to_label topo e) in (Times (weight, (Var (var_name topo e (src,dst)))))::acc) topo [] in let total_path_length = Sum (paths_list) in let path_length_obj = minus total_path_length objective in let name = Printf.sprintf "obj-%s-%s" (name_of_vertex topo src) (name_of_vertex topo dst) in let constr = Eq (name, path_length_obj, 0.) in constr::init_acc let edksp_lp_of_st (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (k : int) = let all_constrs = capacity_constraints topo src dst [] |> num_path_constraints topo src dst k |> conservation_constraints_st topo src dst |> minimize_path_lengths topo src dst in (objective, all_constrs) let rec new_rand () : float = let rand = (Random.float 1.0) in let try_fn = (Printf.sprintf "/tmp/edksp_%f.lp" rand) in match Sys.file_exists try_fn with `Yes -> new_rand () | _ -> rand (***************** Minimum s-t cut ******************) (* Given a topology, a source src and a sink dst, find the minimum src-dst cut * assuming unit link capacity *) let max_st_flow (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = (* objective = sum of out going flows to other switches from src's ingress switch *) let ingress_switch = outgoing_edges topo src |> List.hd_exn |> Topology.edge_dst |> fst in let edges = outgoing_edges topo ingress_switch in let diffs = List.fold_left edges ~init:[] ~f:(fun acc edge -> if edge_connects_switches edge topo then let forward_amt = var_name topo edge (src,dst) in let reverse_amt = var_name_rev topo edge (src,dst) in let net_outgoing = minus (Var (forward_amt)) (Var (reverse_amt)) in net_outgoing::acc else acc) in let sum_net_outgoing = Sum (diffs) in let constr = minus sum_net_outgoing objective in let name = Printf.sprintf "obj-%s-%s" (name_of_vertex topo src) (name_of_vertex topo dst) in (Eq (name, constr, 0.))::init_acc let min_st_cut (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) = let all_constrs = capacity_constraints topo src dst [] |> conservation_constraints_st topo src dst |> max_st_flow topo src dst in let rand = new_rand () in let lp_filename = (Printf.sprintf "/tmp/cut_%f.lp" rand) in let lp_solname = (Printf.sprintf "/tmp/cut_%f.sol" rand) in Serialize LP and call serialize_max_lp (objective, all_constrs) lp_filename; let gurobi_in = gurobi_process lp_filename lp_solname in let obj_str = "Optimal objective \\([0-9.e+-]+\\)" in let obj_regex = Str.regexp obj_str in let rec read_output gurobi opt_z = try let line = In_channel.input_line_exn gurobi in let opt_z = if Str.string_match obj_regex line 0 then Float.of_string (Str.matched_group 1 line) else opt_z in read_output gurobi opt_z with End_of_file -> opt_z in let opt_z = read_output gurobi_in 0. in ignore (Unix.close_process_in gurobi_in); let _ = Sys.remove lp_filename in let _ = Sys.remove lp_solname in let min_cut = int_of_float opt_z in Printf.printf "Min cut: %s - %s : %d\n" (name_of_vertex topo src) (name_of_vertex topo dst) min_cut; min_cut (****************************************************) (* Given a topology, * returns k edge-disjoint shortest paths per src-dst pair * if k edge-disjoint shortest paths are not possible, * returns k-shortest paths for that pair *) let solve_lp (topo:topology) : scheme = (* TODO: handle edge router constrains *) if !Globals.er_mode then failwith "Not implemented" else let sd_pairs = get_srcdst_pairs topo in List.fold_left sd_pairs ~init:SrcDstMap.empty ~f:(fun acc (src, dst) -> (* Iterate over each src-dst pair to find k edge-disjoint shortest paths *) let name_table = Hashtbl.Poly.create () in Topology.iter_vertexes (fun vert -> let label = Topology.vertex_to_label topo vert in let name = Node.name label in Hashtbl.Poly.add_exn name_table ~key:name ~data:vert) topo; let max_budget = if use_min_cut then min (min_st_cut topo src dst) (!Globals.budget) else (!Globals.budget) in let lp = edksp_lp_of_st topo src dst max_budget in let rand = new_rand () in let lp_filename = (Printf.sprintf "/tmp/edksp_%f.lp" rand) in let lp_solname = (Printf.sprintf "/tmp/edksp_%f.sol" rand) in Serialize LP and call serialize_lp lp lp_filename; call_gurobi lp_filename lp_solname; (* read back all the edge flows from the .sol file *) let read_results input = let results = In_channel.create input in let result_str = "^f_\\([a-zA-Z0-9]+\\)--\\([a-zA-Z0-9]+\\)_" ^ "\\([a-zA-Z0-9]+\\)--\\([a-zA-Z0-9]+\\) \\([0-9.e+-]+\\)$" in let regex = Str.regexp result_str in let rec read inp opt_z flows = let line = try In_channel.input_line_exn inp with End_of_file -> "" in if String.(line = "") then (opt_z,flows) else let new_z, new_flows = if Char.(line.[0] = '#') then (opt_z, flows) else if Char.(line.[0] = 'Z') then let ratio_str = Str.string_after line 2 in let ratio = Float.of_string ratio_str in (ratio *. demand_divisor /. cap_divisor, flows) else (if Str.string_match regex line 0 then let vertex s = Topology.vertex_to_label topo (Hashtbl.Poly.find_exn name_table s) in let dem_src = vertex (Str.matched_group 1 line) in let dem_dst = vertex (Str.matched_group 2 line) in let edge_src = vertex (Str.matched_group 3 line) in let edge_dst = vertex (Str.matched_group 4 line) in let flow_amt = Float.of_string (Str.matched_group 5 line) in if Float.(flow_amt = 0.) then (opt_z, flows) else let tup = (dem_src, dem_dst, flow_amt, edge_src, edge_dst) in (opt_z, (tup::flows)) else (opt_z, flows)) in read inp new_z new_flows in (* end read *) let result = read results 0. [] in In_channel.close results; result in (* end read_results *) let ratio, flows = read_results lp_solname in let _ = Sys.remove lp_filename in let _ = Sys.remove lp_solname in let flows_table = Hashtbl.Poly.create () in (* partition the edge flows based on which commodity they are *) List.iter flows ~f:(fun (d_src, d_dst, flow, e_src, e_dst) -> if Hashtbl.Poly.mem flows_table (d_src, d_dst) then let prev_edges = Hashtbl.Poly.find_exn flows_table (d_src, d_dst) in Hashtbl.Poly.set flows_table ~key:(d_src, d_dst) ~data:((e_src, e_dst, flow)::prev_edges) else Hashtbl.Poly.add_exn flows_table ~key:(d_src, d_dst) ~data:[(e_src, e_dst, flow)]); (* tmp_scheme has paths for only src->dst *) let tmp_scheme = Mcf.recover_paths topo flows_table in let st_ppmap = SrcDstMap.find tmp_scheme (src,dst) in match st_ppmap with | None -> if use_min_cut then failwith "EdKSP failed to find min-cut # paths." else (* If k-edge-disjoint paths is not feasible, fall back to k-shortest paths *) let ksp = k_shortest_paths topo src dst (min !Globals.budget 100) in let num_paths = Float.of_int (List.length ksp) in let path_map = List.fold_left ksp ~init:PathMap.empty ~f:(fun acc2 path -> let prob = 1.0 /. num_paths in PathMap.set acc2 ~key:path ~data:prob) in SrcDstMap.set ~key:(src,dst) ~data:path_map acc | Some x -> SrcDstMap.set ~key:(src,dst) ~data:x acc) let solve (topo:topology) (_:demands) : scheme = let new_scheme = if not (SrcDstMap.is_empty !prev_scheme) then !prev_scheme else solve_lp topo in prev_scheme := new_scheme; new_scheme let initialize (s:scheme) : unit = prev_scheme := s; () let local_recovery = normalization_recovery
null
https://raw.githubusercontent.com/cornell-netlab/yates/fc30922933fae3184923f7b138d24454a9537536/lib/routing/Edksp.ml
ocaml
For every inter-switch edge, there is a unit capacity constraint Total flow is at most 1 Constraint: sum of out going flows to other switches from src's ingress switch = k Every node in the topology except the source and sink has conservation constraints Set objective = sum of all path lengths **************** Minimum s-t cut ***************** Given a topology, a source src and a sink dst, find the minimum src-dst cut * assuming unit link capacity objective = sum of out going flows to other switches from src's ingress switch ************************************************** Given a topology, * returns k edge-disjoint shortest paths per src-dst pair * if k edge-disjoint shortest paths are not possible, * returns k-shortest paths for that pair TODO: handle edge router constrains Iterate over each src-dst pair to find k edge-disjoint shortest paths read back all the edge flows from the .sol file end read end read_results partition the edge flows based on which commodity they are tmp_scheme has paths for only src->dst If k-edge-disjoint paths is not feasible, fall back to k-shortest paths
open Core open Apsp open LP_Lang open Util open Yates_types.Types let prev_scheme = ref SrcDstMap.empty let use_min_cut = true let () = match !Globals.rand_seed with | Some x -> Random.init x | None -> Random.self_init ~allow_in_tests:true () let objective = Var "Z" let capacity_constraints (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = Topology.fold_edges (fun edge acc -> if edge_connects_switches edge topo then let flow_on_edge = Var(var_name topo edge (src,dst)) in let name = Printf.sprintf "cap_%s" (string_of_edge topo edge) in (Leq (name, flow_on_edge, 1.))::acc else acc) topo init_acc let num_path_constraints (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (k:int) (init_acc : constrain list) : constrain list = let ingress_switch = outgoing_edges topo src |> List.hd_exn |> Topology.edge_dst |> fst in let edges = outgoing_edges topo ingress_switch in let diffs = List.fold_left edges ~init:[] ~f:(fun acc edge -> if edge_connects_switches edge topo then let forward_amt = var_name topo edge (src,dst) in let reverse_amt = var_name_rev topo edge (src,dst) in let net_outgoing = minus (Var (forward_amt)) (Var (reverse_amt)) in net_outgoing::acc else acc) in let sum_net_outgoing = Sum (diffs) in let name = Printf.sprintf "num-%s-%s" (name_of_vertex topo src) (name_of_vertex topo dst) in (Eq (name, sum_net_outgoing, Float.of_int k))::init_acc let conservation_constraints_st (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = Topology.fold_vertexes (fun v acc -> if Stdlib.(v = src || v = dst) then acc else let edges = outgoing_edges topo v in let outgoing = List.fold_left edges ~init:[] ~f:(fun acc_vars e -> (Var (var_name topo e (src,dst)))::acc_vars) in let incoming = List.fold_left edges ~init:[] ~f:(fun acc_vars e -> (Var (var_name_rev topo e (src,dst)))::acc_vars) in let total_out = Sum (outgoing) in let total_in = Sum (incoming) in let net = minus total_out total_in in let name = Printf.sprintf "con-%s-%s_%s" (name_of_vertex topo src) (name_of_vertex topo dst) (name_of_vertex topo v) in let constr = Eq (name, net, 0.) in constr::acc) topo init_acc let minimize_path_lengths (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = let paths_list = Topology.fold_edges (fun e acc -> let weight = Link.weight (Topology.edge_to_label topo e) in (Times (weight, (Var (var_name topo e (src,dst)))))::acc) topo [] in let total_path_length = Sum (paths_list) in let path_length_obj = minus total_path_length objective in let name = Printf.sprintf "obj-%s-%s" (name_of_vertex topo src) (name_of_vertex topo dst) in let constr = Eq (name, path_length_obj, 0.) in constr::init_acc let edksp_lp_of_st (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (k : int) = let all_constrs = capacity_constraints topo src dst [] |> num_path_constraints topo src dst k |> conservation_constraints_st topo src dst |> minimize_path_lengths topo src dst in (objective, all_constrs) let rec new_rand () : float = let rand = (Random.float 1.0) in let try_fn = (Printf.sprintf "/tmp/edksp_%f.lp" rand) in match Sys.file_exists try_fn with `Yes -> new_rand () | _ -> rand let max_st_flow (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) (init_acc : constrain list) : constrain list = let ingress_switch = outgoing_edges topo src |> List.hd_exn |> Topology.edge_dst |> fst in let edges = outgoing_edges topo ingress_switch in let diffs = List.fold_left edges ~init:[] ~f:(fun acc edge -> if edge_connects_switches edge topo then let forward_amt = var_name topo edge (src,dst) in let reverse_amt = var_name_rev topo edge (src,dst) in let net_outgoing = minus (Var (forward_amt)) (Var (reverse_amt)) in net_outgoing::acc else acc) in let sum_net_outgoing = Sum (diffs) in let constr = minus sum_net_outgoing objective in let name = Printf.sprintf "obj-%s-%s" (name_of_vertex topo src) (name_of_vertex topo dst) in (Eq (name, constr, 0.))::init_acc let min_st_cut (topo : Topology.t) (src : Topology.vertex) (dst : Topology.vertex) = let all_constrs = capacity_constraints topo src dst [] |> conservation_constraints_st topo src dst |> max_st_flow topo src dst in let rand = new_rand () in let lp_filename = (Printf.sprintf "/tmp/cut_%f.lp" rand) in let lp_solname = (Printf.sprintf "/tmp/cut_%f.sol" rand) in Serialize LP and call serialize_max_lp (objective, all_constrs) lp_filename; let gurobi_in = gurobi_process lp_filename lp_solname in let obj_str = "Optimal objective \\([0-9.e+-]+\\)" in let obj_regex = Str.regexp obj_str in let rec read_output gurobi opt_z = try let line = In_channel.input_line_exn gurobi in let opt_z = if Str.string_match obj_regex line 0 then Float.of_string (Str.matched_group 1 line) else opt_z in read_output gurobi opt_z with End_of_file -> opt_z in let opt_z = read_output gurobi_in 0. in ignore (Unix.close_process_in gurobi_in); let _ = Sys.remove lp_filename in let _ = Sys.remove lp_solname in let min_cut = int_of_float opt_z in Printf.printf "Min cut: %s - %s : %d\n" (name_of_vertex topo src) (name_of_vertex topo dst) min_cut; min_cut let solve_lp (topo:topology) : scheme = if !Globals.er_mode then failwith "Not implemented" else let sd_pairs = get_srcdst_pairs topo in List.fold_left sd_pairs ~init:SrcDstMap.empty ~f:(fun acc (src, dst) -> let name_table = Hashtbl.Poly.create () in Topology.iter_vertexes (fun vert -> let label = Topology.vertex_to_label topo vert in let name = Node.name label in Hashtbl.Poly.add_exn name_table ~key:name ~data:vert) topo; let max_budget = if use_min_cut then min (min_st_cut topo src dst) (!Globals.budget) else (!Globals.budget) in let lp = edksp_lp_of_st topo src dst max_budget in let rand = new_rand () in let lp_filename = (Printf.sprintf "/tmp/edksp_%f.lp" rand) in let lp_solname = (Printf.sprintf "/tmp/edksp_%f.sol" rand) in Serialize LP and call serialize_lp lp lp_filename; call_gurobi lp_filename lp_solname; let read_results input = let results = In_channel.create input in let result_str = "^f_\\([a-zA-Z0-9]+\\)--\\([a-zA-Z0-9]+\\)_" ^ "\\([a-zA-Z0-9]+\\)--\\([a-zA-Z0-9]+\\) \\([0-9.e+-]+\\)$" in let regex = Str.regexp result_str in let rec read inp opt_z flows = let line = try In_channel.input_line_exn inp with End_of_file -> "" in if String.(line = "") then (opt_z,flows) else let new_z, new_flows = if Char.(line.[0] = '#') then (opt_z, flows) else if Char.(line.[0] = 'Z') then let ratio_str = Str.string_after line 2 in let ratio = Float.of_string ratio_str in (ratio *. demand_divisor /. cap_divisor, flows) else (if Str.string_match regex line 0 then let vertex s = Topology.vertex_to_label topo (Hashtbl.Poly.find_exn name_table s) in let dem_src = vertex (Str.matched_group 1 line) in let dem_dst = vertex (Str.matched_group 2 line) in let edge_src = vertex (Str.matched_group 3 line) in let edge_dst = vertex (Str.matched_group 4 line) in let flow_amt = Float.of_string (Str.matched_group 5 line) in if Float.(flow_amt = 0.) then (opt_z, flows) else let tup = (dem_src, dem_dst, flow_amt, edge_src, edge_dst) in (opt_z, (tup::flows)) else (opt_z, flows)) in read inp new_z new_flows in let result = read results 0. [] in In_channel.close results; result in let ratio, flows = read_results lp_solname in let _ = Sys.remove lp_filename in let _ = Sys.remove lp_solname in let flows_table = Hashtbl.Poly.create () in List.iter flows ~f:(fun (d_src, d_dst, flow, e_src, e_dst) -> if Hashtbl.Poly.mem flows_table (d_src, d_dst) then let prev_edges = Hashtbl.Poly.find_exn flows_table (d_src, d_dst) in Hashtbl.Poly.set flows_table ~key:(d_src, d_dst) ~data:((e_src, e_dst, flow)::prev_edges) else Hashtbl.Poly.add_exn flows_table ~key:(d_src, d_dst) ~data:[(e_src, e_dst, flow)]); let tmp_scheme = Mcf.recover_paths topo flows_table in let st_ppmap = SrcDstMap.find tmp_scheme (src,dst) in match st_ppmap with | None -> if use_min_cut then failwith "EdKSP failed to find min-cut # paths." else let ksp = k_shortest_paths topo src dst (min !Globals.budget 100) in let num_paths = Float.of_int (List.length ksp) in let path_map = List.fold_left ksp ~init:PathMap.empty ~f:(fun acc2 path -> let prob = 1.0 /. num_paths in PathMap.set acc2 ~key:path ~data:prob) in SrcDstMap.set ~key:(src,dst) ~data:path_map acc | Some x -> SrcDstMap.set ~key:(src,dst) ~data:x acc) let solve (topo:topology) (_:demands) : scheme = let new_scheme = if not (SrcDstMap.is_empty !prev_scheme) then !prev_scheme else solve_lp topo in prev_scheme := new_scheme; new_scheme let initialize (s:scheme) : unit = prev_scheme := s; () let local_recovery = normalization_recovery
378d12610ba818d672e1695174b3fc3a2d46910ccba3d086dbaec1d30b341af5
nikodemus/SBCL
parse-lambda-list.lisp
This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!C") (/show0 "parse-lambda-list.lisp 12") ;;; Break something like a lambda list (but not necessarily actually a ;;; lambda list, e.g. the representation of argument types which is used within an FTYPE specification ) into its component parts . We return twelve values : 1 . a list of the required args ; 2 . a list of the & OPTIONAL arg specs ; 3 . true if a & REST arg was specified ; 4 . the & REST arg ; 5 . true if & KEY args are present ; 6 . a list of the & KEY arg specs ; 7 . true if & ALLOW - OTHER - KEYS was specified . ; 8 . true if any & AUX is present ( new in SBCL vs. CMU CL ) ; 9 . a list of the & AUX specifiers ; 10 . true if a & MORE arg was specified ; 11 . the & MORE context var ; 12 . the & MORE count var ; 13 . true if any lambda list keyword is present ( only for PARSE - LAMBDA - LIST - LIKE - THING ) . ;;; ;;; The top level lambda list syntax is checked for validity, but the ;;; arg specifiers are just passed through untouched. If something is wrong , we use COMPILER - ERROR , aborting compilation to the last ;;; recovery point. (declaim (ftype (sfunction (list &key (:silent boolean)) (values list list boolean t boolean list boolean boolean list boolean t t boolean)) parse-lambda-list-like-thing)) (declaim (ftype (sfunction (list &key (:silent boolean)) (values list list boolean t boolean list boolean boolean list boolean t t)) parse-lambda-list)) (defun parse-lambda-list-like-thing (list &key silent) (collect ((required) (optional) (keys) (aux)) (let ((restp nil) (rest nil) (morep nil) (more-context nil) (more-count nil) (keyp nil) (auxp nil) (allowp nil) (state :required)) (declare (type (member :allow-other-keys :aux :key :more-context :more-count :optional :post-more :post-rest :required :rest) state)) (dolist (arg list) (if (member arg sb!xc:lambda-list-keywords) (case arg (&optional (unless (eq state :required) (compiler-error "misplaced &OPTIONAL in lambda list: ~S" list)) (setq state :optional)) (&rest (unless (member state '(:required :optional)) (compiler-error "misplaced &REST in lambda list: ~S" list)) (setq state :rest)) (&more (unless (member state '(:required :optional)) (compiler-error "misplaced &MORE in lambda list: ~S" list)) (setq morep t state :more-context)) (&key (unless (member state '(:required :optional :post-rest :post-more)) (compiler-error "misplaced &KEY in lambda list: ~S" list)) #-sb-xc-host (when (optional) (unless silent (compiler-style-warn "&OPTIONAL and &KEY found in the same lambda list: ~S" list))) (setq keyp t state :key)) (&allow-other-keys (unless (eq state ':key) (compiler-error "misplaced &ALLOW-OTHER-KEYS in ~ lambda list: ~S" list)) (setq allowp t state :allow-other-keys)) (&aux (when (member state '(:rest :more-context :more-count)) (compiler-error "misplaced &AUX in lambda list: ~S" list)) (when auxp (compiler-error "multiple &AUX in lambda list: ~S" list)) (setq auxp t state :aux)) (t It could be argued that & WHOLE and friends would be ;; just ordinary variables in an ordinary lambda-list, ;; but since (1) that seem exceedingly to have been the programmers intent and ( 2 ) the spec can be ;; interpreted as giving as licence to signal an ;; error[*] that is what we do. ;; ;; [* All lambda list keywords used in the implementation appear in LAMBDA - LIST - KEYWORDS . Each ;; member of a lambda list is either a parameter specifier ot a lambda list keyword . Ergo , symbols appearing in LAMBDA - LIST - KEYWORDS can not be ;; parameter specifiers.] (compiler-error 'simple-program-error :format-control "Bad lambda list keyword ~S in: ~S" :format-arguments (list arg list)))) (progn (when (symbolp arg) (let ((name (symbol-name arg))) (when (and (plusp (length name)) (char= (char name 0) #\&)) ;; Should this be COMPILER-STYLE-WARN? (unless silent (style-warn "suspicious variable in lambda list: ~S." arg))))) (case state (:required (required arg)) (:optional (optional arg)) (:rest (setq restp t rest arg state :post-rest)) (:more-context (setq more-context arg state :more-count)) (:more-count (setq more-count arg state :post-more)) (:key (keys arg)) (:aux (aux arg)) (t (compiler-error "found garbage in lambda list when expecting ~ a keyword: ~S" arg)))))) (when (eq state :rest) (compiler-error "&REST without rest variable")) (values (required) (optional) restp rest keyp (keys) allowp auxp (aux) morep more-context more-count (neq state :required))))) like PARSE - LAMBDA - LIST - LIKE - THING , except our LAMBDA - LIST argument ;;; really *is* a lambda list, not just a "lambda-list-like thing", so ;;; can barf on things which're illegal as arguments in lambda lists ;;; even if they could conceivably be legal in not-quite-a-lambda-list weirdosities (defun parse-lambda-list (lambda-list &key silent) ;; Classify parameters without checking their validity individually. (multiple-value-bind (required optional restp rest keyp keys allowp auxp aux morep more-context more-count) (parse-lambda-list-like-thing lambda-list :silent silent) ;; Check validity of parameters. (flet ((need-symbol (x why) (unless (symbolp x) (compiler-error "~A is not a symbol: ~S" why x)))) (dolist (i required) (need-symbol i "Required argument")) (dolist (i optional) (typecase i (symbol) (cons (destructuring-bind (var &optional init-form supplied-p) i (declare (ignore init-form supplied-p)) (need-symbol var "&OPTIONAL parameter name"))) (t (compiler-error "&OPTIONAL parameter is not a symbol or cons: ~S" i)))) (when restp (need-symbol rest "&REST argument")) (when keyp (dolist (i keys) (typecase i (symbol) (cons (destructuring-bind (var-or-kv &optional init-form supplied-p) i (declare (ignore init-form supplied-p)) (if (consp var-or-kv) (destructuring-bind (keyword-name var) var-or-kv (declare (ignore keyword-name)) (need-symbol var "&KEY parameter name")) (need-symbol var-or-kv "&KEY parameter name")))) (t (compiler-error "&KEY parameter is not a symbol or cons: ~S" i)))))) ;; Voila. (values required optional restp rest keyp keys allowp auxp aux morep more-context more-count))) (/show0 "parse-lambda-list.lisp end of file")
null
https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/src/compiler/parse-lambda-list.lisp
lisp
more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. Break something like a lambda list (but not necessarily actually a lambda list, e.g. the representation of argument types which is The top level lambda list syntax is checked for validity, but the arg specifiers are just passed through untouched. If something is recovery point. just ordinary variables in an ordinary lambda-list, but since (1) that seem exceedingly to have been the interpreted as giving as licence to signal an error[*] that is what we do. [* All lambda list keywords used in the member of a lambda list is either a parameter parameter specifiers.] Should this be COMPILER-STYLE-WARN? really *is* a lambda list, not just a "lambda-list-like thing", so can barf on things which're illegal as arguments in lambda lists even if they could conceivably be legal in not-quite-a-lambda-list Classify parameters without checking their validity individually. Check validity of parameters. Voila.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!C") (/show0 "parse-lambda-list.lisp 12") used within an FTYPE specification ) into its component parts . We return twelve values : 13 . true if any lambda list keyword is present ( only for PARSE - LAMBDA - LIST - LIKE - THING ) . wrong , we use COMPILER - ERROR , aborting compilation to the last (declaim (ftype (sfunction (list &key (:silent boolean)) (values list list boolean t boolean list boolean boolean list boolean t t boolean)) parse-lambda-list-like-thing)) (declaim (ftype (sfunction (list &key (:silent boolean)) (values list list boolean t boolean list boolean boolean list boolean t t)) parse-lambda-list)) (defun parse-lambda-list-like-thing (list &key silent) (collect ((required) (optional) (keys) (aux)) (let ((restp nil) (rest nil) (morep nil) (more-context nil) (more-count nil) (keyp nil) (auxp nil) (allowp nil) (state :required)) (declare (type (member :allow-other-keys :aux :key :more-context :more-count :optional :post-more :post-rest :required :rest) state)) (dolist (arg list) (if (member arg sb!xc:lambda-list-keywords) (case arg (&optional (unless (eq state :required) (compiler-error "misplaced &OPTIONAL in lambda list: ~S" list)) (setq state :optional)) (&rest (unless (member state '(:required :optional)) (compiler-error "misplaced &REST in lambda list: ~S" list)) (setq state :rest)) (&more (unless (member state '(:required :optional)) (compiler-error "misplaced &MORE in lambda list: ~S" list)) (setq morep t state :more-context)) (&key (unless (member state '(:required :optional :post-rest :post-more)) (compiler-error "misplaced &KEY in lambda list: ~S" list)) #-sb-xc-host (when (optional) (unless silent (compiler-style-warn "&OPTIONAL and &KEY found in the same lambda list: ~S" list))) (setq keyp t state :key)) (&allow-other-keys (unless (eq state ':key) (compiler-error "misplaced &ALLOW-OTHER-KEYS in ~ lambda list: ~S" list)) (setq allowp t state :allow-other-keys)) (&aux (when (member state '(:rest :more-context :more-count)) (compiler-error "misplaced &AUX in lambda list: ~S" list)) (when auxp (compiler-error "multiple &AUX in lambda list: ~S" list)) (setq auxp t state :aux)) (t It could be argued that & WHOLE and friends would be programmers intent and ( 2 ) the spec can be implementation appear in LAMBDA - LIST - KEYWORDS . Each specifier ot a lambda list keyword . Ergo , symbols appearing in LAMBDA - LIST - KEYWORDS can not be (compiler-error 'simple-program-error :format-control "Bad lambda list keyword ~S in: ~S" :format-arguments (list arg list)))) (progn (when (symbolp arg) (let ((name (symbol-name arg))) (when (and (plusp (length name)) (char= (char name 0) #\&)) (unless silent (style-warn "suspicious variable in lambda list: ~S." arg))))) (case state (:required (required arg)) (:optional (optional arg)) (:rest (setq restp t rest arg state :post-rest)) (:more-context (setq more-context arg state :more-count)) (:more-count (setq more-count arg state :post-more)) (:key (keys arg)) (:aux (aux arg)) (t (compiler-error "found garbage in lambda list when expecting ~ a keyword: ~S" arg)))))) (when (eq state :rest) (compiler-error "&REST without rest variable")) (values (required) (optional) restp rest keyp (keys) allowp auxp (aux) morep more-context more-count (neq state :required))))) like PARSE - LAMBDA - LIST - LIKE - THING , except our LAMBDA - LIST argument weirdosities (defun parse-lambda-list (lambda-list &key silent) (multiple-value-bind (required optional restp rest keyp keys allowp auxp aux morep more-context more-count) (parse-lambda-list-like-thing lambda-list :silent silent) (flet ((need-symbol (x why) (unless (symbolp x) (compiler-error "~A is not a symbol: ~S" why x)))) (dolist (i required) (need-symbol i "Required argument")) (dolist (i optional) (typecase i (symbol) (cons (destructuring-bind (var &optional init-form supplied-p) i (declare (ignore init-form supplied-p)) (need-symbol var "&OPTIONAL parameter name"))) (t (compiler-error "&OPTIONAL parameter is not a symbol or cons: ~S" i)))) (when restp (need-symbol rest "&REST argument")) (when keyp (dolist (i keys) (typecase i (symbol) (cons (destructuring-bind (var-or-kv &optional init-form supplied-p) i (declare (ignore init-form supplied-p)) (if (consp var-or-kv) (destructuring-bind (keyword-name var) var-or-kv (declare (ignore keyword-name)) (need-symbol var "&KEY parameter name")) (need-symbol var-or-kv "&KEY parameter name")))) (t (compiler-error "&KEY parameter is not a symbol or cons: ~S" i)))))) (values required optional restp rest keyp keys allowp auxp aux morep more-context more-count))) (/show0 "parse-lambda-list.lisp end of file")
d7d47c547c9ca75a443b66197f7493a3f8e690788a66510433f5d2291e3c1780
aartaka/nyxt-config
config.lisp
(in-package #:nyxt-user) (let ((*default-pathname-defaults* (uiop:pathname-directory-pathname (files:expand *config-file*)))) (load "init"))
null
https://raw.githubusercontent.com/aartaka/nyxt-config/f127750978260fa79b9537f81c4f6664149e4b69/config.lisp
lisp
(in-package #:nyxt-user) (let ((*default-pathname-defaults* (uiop:pathname-directory-pathname (files:expand *config-file*)))) (load "init"))
849576cc6ce445331820e69869c1a5516fd8002f38c8f9da4cd0a68fff2f20ab
herd/herdtools7
X86_64ParseTest.ml
(****************************************************************************) (* the diy toolsuite *) (* *) , University College London , UK . , INRIA Paris - Rocquencourt , France . (* *) Copyright 2023 - present Institut National de Recherche en Informatique et (* en Automatique and the authors. All rights reserved. *) (* *) This software is governed by the CeCILL - B license under French law and (* abiding by the rules of distribution of free software. You can use, *) modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . (****************************************************************************) module Make(Conf:RunTest.Config)(ModelConfig:MemWithCav12.Config) = struct module LexConfig = struct let debug = Conf.debug.Debug_herd.lexer end module ArchConfig = SemExtra.ConfigToArchConfig(Conf) module X86_64Value = Int64Value.Make(X86_64Base.Instr) module X86_64 = X86_64Arch_herd.Make(ArchConfig)(X86_64Value) module X86_64LexParse = struct type instruction = X86_64.pseudo type token = X86_64Parser.token module Lexer = X86_64Lexer.Make(LexConfig) let lexer = Lexer.token let parser = MiscParser.mach2generic X86_64Parser.main end module X86_64S = X86_64Sem.Make(Conf)(X86_64Value) module X86_64M = MemWithCav12.Make(ModelConfig)(X86_64S) module P = GenParser.Make(Conf)(X86_64)(X86_64LexParse) module X = RunTest.Make(X86_64S)(P)(X86_64M)(Conf) let run = X.run end
null
https://raw.githubusercontent.com/herd/herdtools7/574c59e111deda09afbba1f2bdd94353f437faaf/herd/X86_64ParseTest.ml
ocaml
************************************************************************** the diy toolsuite en Automatique and the authors. All rights reserved. abiding by the rules of distribution of free software. You can use, **************************************************************************
, University College London , UK . , INRIA Paris - Rocquencourt , France . Copyright 2023 - present Institut National de Recherche en Informatique et This software is governed by the CeCILL - B license under French law and modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . module Make(Conf:RunTest.Config)(ModelConfig:MemWithCav12.Config) = struct module LexConfig = struct let debug = Conf.debug.Debug_herd.lexer end module ArchConfig = SemExtra.ConfigToArchConfig(Conf) module X86_64Value = Int64Value.Make(X86_64Base.Instr) module X86_64 = X86_64Arch_herd.Make(ArchConfig)(X86_64Value) module X86_64LexParse = struct type instruction = X86_64.pseudo type token = X86_64Parser.token module Lexer = X86_64Lexer.Make(LexConfig) let lexer = Lexer.token let parser = MiscParser.mach2generic X86_64Parser.main end module X86_64S = X86_64Sem.Make(Conf)(X86_64Value) module X86_64M = MemWithCav12.Make(ModelConfig)(X86_64S) module P = GenParser.Make(Conf)(X86_64)(X86_64LexParse) module X = RunTest.Make(X86_64S)(P)(X86_64M)(Conf) let run = X.run end
99e16e2dec9592102f049dcc33356e0e694b17fb5e095586c8ead8cacce0b17b
petitnau/algoml
crowdfunding.ml
open General open Int open Frontend open Amlprinter open Batteries open! Comp let script = parse_file "contracts/crowdfund/crowdfunding.aml";; ; ; failwith " end " ; ; let account_a = Account.bind_balance (Account.empty_user()) Algo 100 let address_a = Account.get_address account_a let account_b = Account.bind_balance (Account.empty_user()) Algo 100 let address_b = Account.get_address account_b let account_c = Account.bind_balance (Account.empty_user()) Algo 100 let address_c = Account.get_address account_c let s' = State.empty let s'' = State.bind s' account_a let s''' = State.bind s'' account_b let s = State.bind s''' account_c let start_date = 10 let end_date = 20 let fund_close_date = 30 let goal = 100 let receiver = address_c let s = s >=>! [CreateTransaction(address_a, script, Ide("crowdfund"), [ VInt(start_date); VInt(end_date); VInt(fund_close_date); VInt(goal); VAddress(receiver)])] let address_cf = Address.latest() let s = s >=>! [CallTransaction(address_a, address_cf, OptIn, Ide("optin"), [])] >=>! [CallTransaction(address_b, address_cf, OptIn, Ide("optin"), [])] >=>! [CallTransaction(address_c, address_cf, OptIn, Ide("optin"), [])] >:> (start_date + 5, 0) (* >?> "Address(0).balance[algo] = 0" *) >=>! [PayTransaction(90, Algo, address_a, address_cf); CallTransaction(address_a, address_cf, NoOp, Ide("donate"), []);] >=>! [PayTransaction(80, Algo, address_b, address_cf); CallTransaction(address_b, address_cf, NoOp, Ide("donate"), []);] >:> (end_date + 5, 0) >=>! [PayTransaction(170, Algo, address_cf, address_c); CallTransaction(address_c, address_cf, NoOp, Ide("claim"), []);] >:> (fund_close_date + 5, 0) ;; print_endline (string_of_state s);
null
https://raw.githubusercontent.com/petitnau/algoml/c0122c85004114ba634b4946549a78325ff844ee/src/tests/crowdfunding.ml
ocaml
>?> "Address(0).balance[algo] = 0"
open General open Int open Frontend open Amlprinter open Batteries open! Comp let script = parse_file "contracts/crowdfund/crowdfunding.aml";; ; ; failwith " end " ; ; let account_a = Account.bind_balance (Account.empty_user()) Algo 100 let address_a = Account.get_address account_a let account_b = Account.bind_balance (Account.empty_user()) Algo 100 let address_b = Account.get_address account_b let account_c = Account.bind_balance (Account.empty_user()) Algo 100 let address_c = Account.get_address account_c let s' = State.empty let s'' = State.bind s' account_a let s''' = State.bind s'' account_b let s = State.bind s''' account_c let start_date = 10 let end_date = 20 let fund_close_date = 30 let goal = 100 let receiver = address_c let s = s >=>! [CreateTransaction(address_a, script, Ide("crowdfund"), [ VInt(start_date); VInt(end_date); VInt(fund_close_date); VInt(goal); VAddress(receiver)])] let address_cf = Address.latest() let s = s >=>! [CallTransaction(address_a, address_cf, OptIn, Ide("optin"), [])] >=>! [CallTransaction(address_b, address_cf, OptIn, Ide("optin"), [])] >=>! [CallTransaction(address_c, address_cf, OptIn, Ide("optin"), [])] >:> (start_date + 5, 0) >=>! [PayTransaction(90, Algo, address_a, address_cf); CallTransaction(address_a, address_cf, NoOp, Ide("donate"), []);] >=>! [PayTransaction(80, Algo, address_b, address_cf); CallTransaction(address_b, address_cf, NoOp, Ide("donate"), []);] >:> (end_date + 5, 0) >=>! [PayTransaction(170, Algo, address_cf, address_c); CallTransaction(address_c, address_cf, NoOp, Ide("claim"), []);] >:> (fund_close_date + 5, 0) ;; print_endline (string_of_state s);
f7855a2a9d03aa0051b83b7b6965ff196f0c1a158122071d453d039b3035b0ae
okuoku/nausicaa
test-ffi-core.sps
;;; Part of : Nausicaa / Sceme ;;;Contents: tests for ffi library Date : Tue Nov 18 , 2008 ;;; ;;;Abstract ;;; ;;; ;;; Copyright ( c ) 2008 - 2011 < > ;;; ;;;This program is free software: you can redistribute it and/or modify ;;;it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at ;;;your option) any later version. ;;; ;;;This program is distributed in the hope that it will be useful, but ;;;WITHOUT ANY WARRANTY; without even the implied warranty of ;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details . ;;; You should have received a copy of the GNU General Public License ;;;along with this program. If not, see </>. ;;; (import (nausicaa) (nausicaa ffi) (nausicaa ffi memory) (nausicaa ffi cstrings) (nausicaa ffi errno) (nausicaa ffi clang type-translation) (nausicaa checks)) (cond-expand ((or larceny petite) (exit)) (else #f)) (check-set-mode! 'report-failed) (display "*** testing FFI core\n") (define-shared-object ffitest-lib 'libnausicaa-ffitest1.0.so) (parametrise ((check-test-name 'open-shared)) (check (shared-object? (open-shared-object 'libc.so.6)) => #t) (check (guard (E ((shared-object-opening-error-condition? E) ( write ( condition - message E))(newline ) (list (condition-library-name E) (condition-who E)))) (open-shared-object 'ciao)) => '("ciao" open-shared-object)) #t) (parametrise ((check-test-name 'lookup)) (check (pointer? (lookup-shared-object libc-shared-object 'printf)) => #t) (check (guard (E ((shared-object-lookup-error-condition? E) ( write ( condition - message E))(newline ) (list (condition-shared-object E) (condition-foreign-symbol E) (condition-who E)))) (lookup-shared-object libc-shared-object 'ciao)) => `(,libc-shared-object "ciao" lookup-shared-object)) #t) (parameterize ((check-test-name 'conditions) (debugging #f)) ;;; -------------------------------------------------------------------- This is used to raise a ENOENT errno error . (define-c-functions/with-errno libc-shared-object (primitive-chdir (int chdir (char*)))) (define (chdir directory-pathname) (with-compensations (receive (result errno) (primitive-chdir (string->cstring/c directory-pathname)) (unless (= 0 result) (raise-errno-error 'chdir errno directory-pathname)) result))) ;;; -------------------------------------------------------------------- ;;; This is used to raise a EINVAL errno error. (define-c-functions/with-errno libc-shared-object (platform-pread (int pread (int void* int int)))) (define-syntax temp-failure-retry-minus-one (syntax-rules () ((_ ?funcname (?primitive ?arg ...) ?irritants) (let loop () (receive (result errno) (?primitive ?arg ...) (when (= -1 result) (when (= EINTR errno) (loop)) (raise-errno-error (quote ?funcname) errno ?irritants)) result))))) (define-syntax do-pread-or-pwrite (syntax-rules () ((_ ?funcname ?primitive ?fd ?pointer ?number-of-bytes ?offset) (temp-failure-retry-minus-one ?funcname (?primitive ?fd ?pointer ?number-of-bytes ?offset) ?fd)))) (define (primitive-pread fd pointer number-of-bytes offset) (do-pread-or-pwrite primitive-pread platform-pread fd pointer number-of-bytes offset)) ;;; -------------------------------------------------------------------- This is used to raise a ENOEXEC errno error . (define-c-functions/with-errno libc-shared-object (platform-execv (int execv (char* pointer)))) (define (primitive-execv pathname args) (with-compensations (receive (result errno) (platform-execv (string->cstring/c pathname) (strings->argv args malloc-block/c)) (when (= -1 result) (raise-errno-error 'primitive-execv errno (list pathname args)))))) (define primitive-execv-function (make-parameter primitive-execv (lambda (func) (unless (procedure? func) (assertion-violation 'primitive-execv-function "expected procedure as value for the PRIMITIVE-EXECV-FUNCTION parameter" func)) func))) (define (execv pathname args) ((primitive-execv-function) pathname args)) ;;; -------------------------------------------------------------------- This is used to raise a ENOTDIR errno error . (define-c-functions/with-errno libc-shared-object (platform-opendir (pointer opendir (char*)))) (define (primitive-opendir pathname) (with-compensations (receive (result errno) (platform-opendir (string->cstring/c pathname)) (when (pointer-null? result) (raise-errno-error 'primitive-opendir errno pathname)) result))) (define primitive-opendir-function (make-parameter primitive-opendir (lambda (func) (unless (procedure? func) (assertion-violation 'primitive-opendir-function "expected procedure as value for the PRIMITIVE-OPENDIR-FUNCTION parameter" func)) func))) (define (opendir pathname) ((primitive-opendir-function) pathname)) ;;;If the raised exception has the expected "errno" value, it means that ;;;the foreign function call was performed correctly. (check (let ((dirname '/scrappy/dappy/doo)) (guard (E (else ;;(debug-print-condition "condition" E) (list (errno-condition? E) (condition-who E) (errno-symbolic-value E)))) (chdir dirname))) => '(#t chdir ENOENT)) (check (guard (E (else (list (errno-condition? E) (condition-who E) (errno-symbolic-value E) ))) (primitive-pread 0 (integer->pointer 1234) 10 -10)) => '(#t primitive-pread EINVAL)) (check (let ((pathname '/etc/passwd)) (guard (E (else (list (errno-condition? E) (condition-who E) (errno-symbolic-value E) ))) (execv pathname '()))) => '(#t primitive-execv EACCES)) (check (let ((pathname '/etc/passwd)) (guard (E ((errno-condition? E) (list (condition-who E) (errno-symbolic-value E)))) (opendir pathname))) => '(primitive-opendir ENOTDIR)) #t) (parametrise ((check-test-name 'callouts-basic)) (define-c-functions ffitest-lib (callout_int8 (int8_t nausicaa_ffitest_callout_int8 (int int8_t int))) (callout_int16 (int16_t nausicaa_ffitest_callout_int16 (int int16_t int))) (callout_int32 (int32_t nausicaa_ffitest_callout_int32 (int int32_t int))) (callout_int64 (int64_t nausicaa_ffitest_callout_int64 (int int64_t int))) (callout_char (char nausicaa_ffitest_callout_char (int char int))) (callout_uchar (unsigned-char nausicaa_ffitest_callout_uchar (int unsigned-char int))) (callout_short (signed-short nausicaa_ffitest_callout_short (int signed-short int))) (callout_ushort (unsigned-short nausicaa_ffitest_callout_ushort (int unsigned-short int))) (callout_int (int nausicaa_ffitest_callout_int (int int int))) (callout_uint (unsigned-int nausicaa_ffitest_callout_uint (int unsigned-int int))) (callout_long (long nausicaa_ffitest_callout_long (int long int))) (callout_ulong (unsigned-long nausicaa_ffitest_callout_ulong (int unsigned-long int))) (callout_llong (long-long nausicaa_ffitest_callout_llong (int long-long int))) (callout_ullong (unsigned-long-long nausicaa_ffitest_callout_ullong (int unsigned-long-long int))) (callout_float (float nausicaa_ffitest_callout_float (int float int))) (callout_double (double nausicaa_ffitest_callout_double (int double int))) (callout_pointer (void* nausicaa_ffitest_callout_pointer (int void* int)))) (check (callout_int8 1 2 3) => 2) (check (callout_int16 1 2 3) => 2) (check (callout_int32 1 2 3) => 2) (check (callout_int64 1 2 3) => 2) (check (integer->char (callout_char 1 (char->integer #\a) 3)) => #\a) (check (integer->char (callout_uchar 1 (char->integer #\a) 3)) => #\a) (check (callout_short 1 2 3) => 2) (check (callout_ushort 1 2 3) => 2) (check (callout_int 1 2 3) => 2) (check (callout_uint 1 2 3) => 2) (check (callout_long 1 2 3) => 2) (check (callout_ulong 1 2 3) => 2) (check (callout_llong 1 2 3) => 2) (check (callout_ullong 1 2 3) => 2) (check (callout_float 1 2.3 3) (=> (lambda (a b) (< (abs (- a b)) 1e-6))) 2.3) (check (callout_double 1 2.3 3) => 2.3) (check (pointer->integer (callout_pointer 1 (integer->pointer 2) 3)) => 2) #t) (parametrise ((check-test-name 'callouts-with-errno)) (define-c-functions/with-errno ffitest-lib (callout_int8 (int8_t nausicaa_ffitest_callout_int8 (int int8_t int))) (callout_int16 (int16_t nausicaa_ffitest_callout_int16 (int int16_t int))) (callout_int32 (int32_t nausicaa_ffitest_callout_int32 (int int32_t int))) (callout_int64 (int64_t nausicaa_ffitest_callout_int64 (int int64_t int))) (callout_uint8 (int8_t nausicaa_ffitest_callout_uint8 (int int8_t int))) (callout_uint16 (int16_t nausicaa_ffitest_callout_uint16 (int int16_t int))) (callout_uint32 (int32_t nausicaa_ffitest_callout_uint32 (int int32_t int))) (callout_uint64 (int64_t nausicaa_ffitest_callout_uint64 (int int64_t int))) (callout_char (char nausicaa_ffitest_callout_char (int char int))) (callout_uchar (unsigned-char nausicaa_ffitest_callout_uchar (int unsigned-char int))) (callout_short (signed-short nausicaa_ffitest_callout_short (int signed-short int))) (callout_ushort (unsigned-short nausicaa_ffitest_callout_ushort (int unsigned-short int))) (callout_int (int nausicaa_ffitest_callout_int (int int int))) (callout_uint (unsigned-int nausicaa_ffitest_callout_uint (int unsigned-int int))) (callout_long (long nausicaa_ffitest_callout_long (int long int))) (callout_ulong (unsigned-long nausicaa_ffitest_callout_ulong (int unsigned-long int))) (callout_llong (long-long nausicaa_ffitest_callout_llong (int long-long int))) (callout_ullong (unsigned-long-long nausicaa_ffitest_callout_ullong (int unsigned-long-long int))) (callout_float (float nausicaa_ffitest_callout_float (int float int))) (callout_double (double nausicaa_ffitest_callout_double (int double int))) (callout_pointer (void* nausicaa_ffitest_callout_pointer (int void* int)))) (check (let-values (((ret errno) (callout_int8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_char 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_uchar 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_short 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ushort 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_long 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ulong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_llong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ullong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_float 1 2.3 3))) (list ret errno)) (=> (lambda (a b) (and (< (abs (- (car a) (car b))) 1e-6) (= (cadr a) (cadr b))))) '(2.3 1)) (check (let-values (((ret errno) (callout_double 1 2.3 3))) (list ret errno)) => '(2.3 1)) (check (let-values (((ret errno) (callout_pointer 1 (integer->pointer 2) 3))) (list (pointer->integer ret) errno)) => '(2 1)) #t) (parametrise ((check-test-name 'callouts-pointers)) (define-c-callouts (callout_int8 (int8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int8) (int int8_t int))) (callout_int16 (int16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int16) (int int16_t int))) (callout_int32 (int32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int32) (int int32_t int))) (callout_int64 (int64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int64) (int int64_t int))) (callout_uint8 (uint8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint8) (int uint8_t int))) (callout_uint16 (uint16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint16) (int uint16_t int))) (callout_uint32 (uint32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint32) (int uint32_t int))) (callout_uint64 (uint64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint64) (int uint64_t int))) (callout_char (char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_char) (int char int))) (callout_uchar (unsigned-char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uchar) (int unsigned-char int))) (callout_short (signed-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_short) (int signed-short int))) (callout_ushort (unsigned-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ushort) (int unsigned-short int))) (callout_int (int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int) (int int int))) (callout_uint (unsigned-int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint) (int unsigned-int int))) (callout_long (long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_long) (int long int))) (callout_ulong (unsigned-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ulong) (int unsigned-long int))) (callout_llong (long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_llong) (int long-long int))) (callout_ullong (unsigned-long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ullong) (int unsigned-long-long int))) (callout_float (float (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_float) (int float int))) (callout_double (double (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_double) (int double int))) (callout_pointer (void* (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_pointer) (int void* int)))) (check (callout_int8 1 2 3) => 2) (check (callout_int16 1 2 3) => 2) (check (callout_int32 1 2 3) => 2) (check (callout_int64 1 2 3) => 2) (check (callout_uint8 1 2 3) => 2) (check (callout_uint16 1 2 3) => 2) (check (callout_uint32 1 2 3) => 2) (check (callout_uint64 1 2 3) => 2) (check (integer->char (callout_char 1 (char->integer #\a) 3)) => #\a) (check (integer->char (callout_uchar 1 (char->integer #\a) 3)) => #\a) (check (callout_short 1 2 3) => 2) (check (callout_ushort 1 2 3) => 2) (check (callout_int 1 2 3) => 2) (check (callout_uint 1 2 3) => 2) (check (callout_long 1 2 3) => 2) (check (callout_ulong 1 2 3) => 2) (check (callout_llong 1 2 3) => 2) (check (callout_ullong 1 2 3) => 2) (check (callout_float 1 2.3 3) (=> (lambda (a b) (< (abs (- a b)) 1e-6))) 2.3) (check (callout_double 1 2.3 3) => 2.3) (check (pointer->integer (callout_pointer 1 (integer->pointer 2) 3)) => 2) #t) (parametrise ((check-test-name 'callouts-pointers-with-errno)) (define-c-callouts/with-errno (callout_int8 (int8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int8) (int int8_t int))) (callout_int16 (int16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int16) (int int16_t int))) (callout_int32 (int32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int32) (int int32_t int))) (callout_int64 (int64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int64) (int int64_t int))) (callout_uint8 (uint8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint8) (int uint8_t int))) (callout_uint16 (uint16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint16) (int uint16_t int))) (callout_uint32 (uint32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint32) (int uint32_t int))) (callout_uint64 (uint64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint64) (int uint64_t int))) (callout_char (char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_char) (int char int))) (callout_uchar (unsigned-char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uchar) (int unsigned-char int))) (callout_short (signed-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_short) (int signed-short int))) (callout_ushort (unsigned-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ushort) (int unsigned-short int))) (callout_int (int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int) (int int int))) (callout_uint (unsigned-int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint) (int unsigned-int int))) (callout_long (long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_long) (int long int))) (callout_ulong (unsigned-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ulong) (int unsigned-long int))) (callout_llong (long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_llong) (int long-long int))) (callout_ullong (unsigned-long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ullong) (int unsigned-long-long int))) (callout_float (float (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_float) (int float int))) (callout_double (double (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_double) (int double int))) (callout_pointer (void* (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_pointer) (int void* int)))) (check (let-values (((ret errno) (callout_int8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_char 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_uchar 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_short 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ushort 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_long 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ulong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_llong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ullong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_float 1 2.3 3))) (list ret errno)) (=> (lambda (a b) (and (< (abs (- (car a) (car b))) 1e-6) (= (cadr a) (cadr b))))) '(2.3 1)) (check (let-values (((ret errno) (callout_double 1 2.3 3))) (list ret errno)) => '(2.3 1)) (check (let-values (((ret errno) (callout_pointer 1 (integer->pointer 2) 3))) (list (pointer->integer ret) errno)) => '(2 1)) #t) (parametrise ((check-test-name 'callback)) (define-c-functions ffitest-lib (callback_int8 (int8_t nausicaa_ffitest_callback_int8 (callback int int8_t int))) (callback_int16 (int16_t nausicaa_ffitest_callback_int16 (callback int int16_t int))) (callback_int32 (int32_t nausicaa_ffitest_callback_int32 (callback int int32_t int))) (callback_int64 (int64_t nausicaa_ffitest_callback_int64 (callback int int64_t int))) (callback_uint8 (uint8_t nausicaa_ffitest_callback_uint8 (callback int uint8_t int))) (callback_uint16 (uint16_t nausicaa_ffitest_callback_uint16 (callback int uint16_t int))) (callback_uint32 (uint32_t nausicaa_ffitest_callback_uint32 (callback int uint32_t int))) (callback_uint64 (uint64_t nausicaa_ffitest_callback_uint64 (callback int uint64_t int))) (callback_char (char nausicaa_ffitest_callback_char (callback int char int))) (callback_uchar (unsigned-char nausicaa_ffitest_callback_uchar (callback int unsigned-char int))) (callback_short (short nausicaa_ffitest_callback_short (callback int short int))) (callback_ushort (unsigned-short nausicaa_ffitest_callback_ushort (callback int unsigned-short int))) (callback_int (unsigned nausicaa_ffitest_callback_int (callback int int int))) (callback_uint (unsigned nausicaa_ffitest_callback_uint (callback int unsigned-int int))) (callback_long (long nausicaa_ffitest_callback_long (callback int long int))) (callback_ulong (unsigned-long nausicaa_ffitest_callback_ulong (callback int unsigned-long int))) (callback_llong (long-long nausicaa_ffitest_callback_llong (callback int long-long int))) (callback_ullong (unsigned-long-long nausicaa_ffitest_callback_ullong (callback int unsigned-long-long int))) (callback_float (float nausicaa_ffitest_callback_float (callback int float int))) (callback_double (double nausicaa_ffitest_callback_double (callback int double int))) (callback_pointer (void* nausicaa_ffitest_callback_pointer (callback int void* int)))) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int8_t fn (int int8_t int)))) (begin0 (callback_int8 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int16_t fn (int int16_t int)))) (begin0 (callback_int16 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int32_t fn (int int32_t int)))) (begin0 (callback_int32 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int64_t fn (int int64_t int)))) (begin0 (callback_int64 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint8_t fn (int uint8_t int)))) (begin0 (callback_uint8 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint16_t fn (int uint16_t int)))) (begin0 (callback_uint16 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint32_t fn (int uint32_t int)))) (begin0 (callback_uint32 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint64_t fn (int uint64_t int)))) (begin0 (callback_uint64 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* short fn (int short int)))) (begin0 (callback_short cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* ushort fn (int ushort int)))) (begin0 (callback_ushort cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int fn (int int int)))) (begin0 (callback_int cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint fn (int uint int)))) (begin0 (callback_uint cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* long fn (int long int)))) (begin0 (callback_long cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* ulong fn (int ulong int)))) (begin0 (callback_ulong cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* llong fn (int llong int)))) (begin0 (callback_llong cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* ullong fn (int ullong int)))) (begin0 (callback_ullong cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* char fn (int char int)))) (begin0 (callback_char cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uchar fn (int uchar int)))) (begin0 (callback_uchar cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* float fn (int float int)))) (begin0 (callback_float cb 1 2.3 3) (free-c-callback cb))) (=> (lambda (a b) (< (abs (- a b)) 1e-6))) (+ 1 2.3 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* double fn (int double int)))) (begin0 (callback_double cb 1 2.3 3) (free-c-callback cb))) => (+ 1 2.3 3)) (check (let* ((fn (lambda (a b c) (pointer-add (pointer-add b a) c))) (cb (make-c-callback* void* fn (int void* int)))) (begin0 (pointer->integer (callback_pointer cb 1 (integer->pointer 2) 3)) (free-c-callback cb))) => (+ 1 2 3)) #t) ;;;; done (check-report) ;;; end of file
null
https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/tests/test-ffi-core.sps
scheme
Contents: tests for ffi library Abstract 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 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 along with this program. If not, see </>. -------------------------------------------------------------------- -------------------------------------------------------------------- This is used to raise a EINVAL errno error. -------------------------------------------------------------------- -------------------------------------------------------------------- If the raised exception has the expected "errno" value, it means that the foreign function call was performed correctly. (debug-print-condition "condition" E) done end of file
Part of : Nausicaa / Sceme Date : Tue Nov 18 , 2008 Copyright ( c ) 2008 - 2011 < > the Free Software Foundation , either version 3 of the License , or ( at General Public License for more details . You should have received a copy of the GNU General Public License (import (nausicaa) (nausicaa ffi) (nausicaa ffi memory) (nausicaa ffi cstrings) (nausicaa ffi errno) (nausicaa ffi clang type-translation) (nausicaa checks)) (cond-expand ((or larceny petite) (exit)) (else #f)) (check-set-mode! 'report-failed) (display "*** testing FFI core\n") (define-shared-object ffitest-lib 'libnausicaa-ffitest1.0.so) (parametrise ((check-test-name 'open-shared)) (check (shared-object? (open-shared-object 'libc.so.6)) => #t) (check (guard (E ((shared-object-opening-error-condition? E) ( write ( condition - message E))(newline ) (list (condition-library-name E) (condition-who E)))) (open-shared-object 'ciao)) => '("ciao" open-shared-object)) #t) (parametrise ((check-test-name 'lookup)) (check (pointer? (lookup-shared-object libc-shared-object 'printf)) => #t) (check (guard (E ((shared-object-lookup-error-condition? E) ( write ( condition - message E))(newline ) (list (condition-shared-object E) (condition-foreign-symbol E) (condition-who E)))) (lookup-shared-object libc-shared-object 'ciao)) => `(,libc-shared-object "ciao" lookup-shared-object)) #t) (parameterize ((check-test-name 'conditions) (debugging #f)) This is used to raise a ENOENT errno error . (define-c-functions/with-errno libc-shared-object (primitive-chdir (int chdir (char*)))) (define (chdir directory-pathname) (with-compensations (receive (result errno) (primitive-chdir (string->cstring/c directory-pathname)) (unless (= 0 result) (raise-errno-error 'chdir errno directory-pathname)) result))) (define-c-functions/with-errno libc-shared-object (platform-pread (int pread (int void* int int)))) (define-syntax temp-failure-retry-minus-one (syntax-rules () ((_ ?funcname (?primitive ?arg ...) ?irritants) (let loop () (receive (result errno) (?primitive ?arg ...) (when (= -1 result) (when (= EINTR errno) (loop)) (raise-errno-error (quote ?funcname) errno ?irritants)) result))))) (define-syntax do-pread-or-pwrite (syntax-rules () ((_ ?funcname ?primitive ?fd ?pointer ?number-of-bytes ?offset) (temp-failure-retry-minus-one ?funcname (?primitive ?fd ?pointer ?number-of-bytes ?offset) ?fd)))) (define (primitive-pread fd pointer number-of-bytes offset) (do-pread-or-pwrite primitive-pread platform-pread fd pointer number-of-bytes offset)) This is used to raise a ENOEXEC errno error . (define-c-functions/with-errno libc-shared-object (platform-execv (int execv (char* pointer)))) (define (primitive-execv pathname args) (with-compensations (receive (result errno) (platform-execv (string->cstring/c pathname) (strings->argv args malloc-block/c)) (when (= -1 result) (raise-errno-error 'primitive-execv errno (list pathname args)))))) (define primitive-execv-function (make-parameter primitive-execv (lambda (func) (unless (procedure? func) (assertion-violation 'primitive-execv-function "expected procedure as value for the PRIMITIVE-EXECV-FUNCTION parameter" func)) func))) (define (execv pathname args) ((primitive-execv-function) pathname args)) This is used to raise a ENOTDIR errno error . (define-c-functions/with-errno libc-shared-object (platform-opendir (pointer opendir (char*)))) (define (primitive-opendir pathname) (with-compensations (receive (result errno) (platform-opendir (string->cstring/c pathname)) (when (pointer-null? result) (raise-errno-error 'primitive-opendir errno pathname)) result))) (define primitive-opendir-function (make-parameter primitive-opendir (lambda (func) (unless (procedure? func) (assertion-violation 'primitive-opendir-function "expected procedure as value for the PRIMITIVE-OPENDIR-FUNCTION parameter" func)) func))) (define (opendir pathname) ((primitive-opendir-function) pathname)) (check (let ((dirname '/scrappy/dappy/doo)) (guard (E (else (list (errno-condition? E) (condition-who E) (errno-symbolic-value E)))) (chdir dirname))) => '(#t chdir ENOENT)) (check (guard (E (else (list (errno-condition? E) (condition-who E) (errno-symbolic-value E) ))) (primitive-pread 0 (integer->pointer 1234) 10 -10)) => '(#t primitive-pread EINVAL)) (check (let ((pathname '/etc/passwd)) (guard (E (else (list (errno-condition? E) (condition-who E) (errno-symbolic-value E) ))) (execv pathname '()))) => '(#t primitive-execv EACCES)) (check (let ((pathname '/etc/passwd)) (guard (E ((errno-condition? E) (list (condition-who E) (errno-symbolic-value E)))) (opendir pathname))) => '(primitive-opendir ENOTDIR)) #t) (parametrise ((check-test-name 'callouts-basic)) (define-c-functions ffitest-lib (callout_int8 (int8_t nausicaa_ffitest_callout_int8 (int int8_t int))) (callout_int16 (int16_t nausicaa_ffitest_callout_int16 (int int16_t int))) (callout_int32 (int32_t nausicaa_ffitest_callout_int32 (int int32_t int))) (callout_int64 (int64_t nausicaa_ffitest_callout_int64 (int int64_t int))) (callout_char (char nausicaa_ffitest_callout_char (int char int))) (callout_uchar (unsigned-char nausicaa_ffitest_callout_uchar (int unsigned-char int))) (callout_short (signed-short nausicaa_ffitest_callout_short (int signed-short int))) (callout_ushort (unsigned-short nausicaa_ffitest_callout_ushort (int unsigned-short int))) (callout_int (int nausicaa_ffitest_callout_int (int int int))) (callout_uint (unsigned-int nausicaa_ffitest_callout_uint (int unsigned-int int))) (callout_long (long nausicaa_ffitest_callout_long (int long int))) (callout_ulong (unsigned-long nausicaa_ffitest_callout_ulong (int unsigned-long int))) (callout_llong (long-long nausicaa_ffitest_callout_llong (int long-long int))) (callout_ullong (unsigned-long-long nausicaa_ffitest_callout_ullong (int unsigned-long-long int))) (callout_float (float nausicaa_ffitest_callout_float (int float int))) (callout_double (double nausicaa_ffitest_callout_double (int double int))) (callout_pointer (void* nausicaa_ffitest_callout_pointer (int void* int)))) (check (callout_int8 1 2 3) => 2) (check (callout_int16 1 2 3) => 2) (check (callout_int32 1 2 3) => 2) (check (callout_int64 1 2 3) => 2) (check (integer->char (callout_char 1 (char->integer #\a) 3)) => #\a) (check (integer->char (callout_uchar 1 (char->integer #\a) 3)) => #\a) (check (callout_short 1 2 3) => 2) (check (callout_ushort 1 2 3) => 2) (check (callout_int 1 2 3) => 2) (check (callout_uint 1 2 3) => 2) (check (callout_long 1 2 3) => 2) (check (callout_ulong 1 2 3) => 2) (check (callout_llong 1 2 3) => 2) (check (callout_ullong 1 2 3) => 2) (check (callout_float 1 2.3 3) (=> (lambda (a b) (< (abs (- a b)) 1e-6))) 2.3) (check (callout_double 1 2.3 3) => 2.3) (check (pointer->integer (callout_pointer 1 (integer->pointer 2) 3)) => 2) #t) (parametrise ((check-test-name 'callouts-with-errno)) (define-c-functions/with-errno ffitest-lib (callout_int8 (int8_t nausicaa_ffitest_callout_int8 (int int8_t int))) (callout_int16 (int16_t nausicaa_ffitest_callout_int16 (int int16_t int))) (callout_int32 (int32_t nausicaa_ffitest_callout_int32 (int int32_t int))) (callout_int64 (int64_t nausicaa_ffitest_callout_int64 (int int64_t int))) (callout_uint8 (int8_t nausicaa_ffitest_callout_uint8 (int int8_t int))) (callout_uint16 (int16_t nausicaa_ffitest_callout_uint16 (int int16_t int))) (callout_uint32 (int32_t nausicaa_ffitest_callout_uint32 (int int32_t int))) (callout_uint64 (int64_t nausicaa_ffitest_callout_uint64 (int int64_t int))) (callout_char (char nausicaa_ffitest_callout_char (int char int))) (callout_uchar (unsigned-char nausicaa_ffitest_callout_uchar (int unsigned-char int))) (callout_short (signed-short nausicaa_ffitest_callout_short (int signed-short int))) (callout_ushort (unsigned-short nausicaa_ffitest_callout_ushort (int unsigned-short int))) (callout_int (int nausicaa_ffitest_callout_int (int int int))) (callout_uint (unsigned-int nausicaa_ffitest_callout_uint (int unsigned-int int))) (callout_long (long nausicaa_ffitest_callout_long (int long int))) (callout_ulong (unsigned-long nausicaa_ffitest_callout_ulong (int unsigned-long int))) (callout_llong (long-long nausicaa_ffitest_callout_llong (int long-long int))) (callout_ullong (unsigned-long-long nausicaa_ffitest_callout_ullong (int unsigned-long-long int))) (callout_float (float nausicaa_ffitest_callout_float (int float int))) (callout_double (double nausicaa_ffitest_callout_double (int double int))) (callout_pointer (void* nausicaa_ffitest_callout_pointer (int void* int)))) (check (let-values (((ret errno) (callout_int8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_char 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_uchar 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_short 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ushort 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_long 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ulong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_llong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ullong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_float 1 2.3 3))) (list ret errno)) (=> (lambda (a b) (and (< (abs (- (car a) (car b))) 1e-6) (= (cadr a) (cadr b))))) '(2.3 1)) (check (let-values (((ret errno) (callout_double 1 2.3 3))) (list ret errno)) => '(2.3 1)) (check (let-values (((ret errno) (callout_pointer 1 (integer->pointer 2) 3))) (list (pointer->integer ret) errno)) => '(2 1)) #t) (parametrise ((check-test-name 'callouts-pointers)) (define-c-callouts (callout_int8 (int8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int8) (int int8_t int))) (callout_int16 (int16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int16) (int int16_t int))) (callout_int32 (int32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int32) (int int32_t int))) (callout_int64 (int64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int64) (int int64_t int))) (callout_uint8 (uint8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint8) (int uint8_t int))) (callout_uint16 (uint16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint16) (int uint16_t int))) (callout_uint32 (uint32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint32) (int uint32_t int))) (callout_uint64 (uint64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint64) (int uint64_t int))) (callout_char (char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_char) (int char int))) (callout_uchar (unsigned-char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uchar) (int unsigned-char int))) (callout_short (signed-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_short) (int signed-short int))) (callout_ushort (unsigned-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ushort) (int unsigned-short int))) (callout_int (int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int) (int int int))) (callout_uint (unsigned-int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint) (int unsigned-int int))) (callout_long (long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_long) (int long int))) (callout_ulong (unsigned-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ulong) (int unsigned-long int))) (callout_llong (long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_llong) (int long-long int))) (callout_ullong (unsigned-long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ullong) (int unsigned-long-long int))) (callout_float (float (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_float) (int float int))) (callout_double (double (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_double) (int double int))) (callout_pointer (void* (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_pointer) (int void* int)))) (check (callout_int8 1 2 3) => 2) (check (callout_int16 1 2 3) => 2) (check (callout_int32 1 2 3) => 2) (check (callout_int64 1 2 3) => 2) (check (callout_uint8 1 2 3) => 2) (check (callout_uint16 1 2 3) => 2) (check (callout_uint32 1 2 3) => 2) (check (callout_uint64 1 2 3) => 2) (check (integer->char (callout_char 1 (char->integer #\a) 3)) => #\a) (check (integer->char (callout_uchar 1 (char->integer #\a) 3)) => #\a) (check (callout_short 1 2 3) => 2) (check (callout_ushort 1 2 3) => 2) (check (callout_int 1 2 3) => 2) (check (callout_uint 1 2 3) => 2) (check (callout_long 1 2 3) => 2) (check (callout_ulong 1 2 3) => 2) (check (callout_llong 1 2 3) => 2) (check (callout_ullong 1 2 3) => 2) (check (callout_float 1 2.3 3) (=> (lambda (a b) (< (abs (- a b)) 1e-6))) 2.3) (check (callout_double 1 2.3 3) => 2.3) (check (pointer->integer (callout_pointer 1 (integer->pointer 2) 3)) => 2) #t) (parametrise ((check-test-name 'callouts-pointers-with-errno)) (define-c-callouts/with-errno (callout_int8 (int8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int8) (int int8_t int))) (callout_int16 (int16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int16) (int int16_t int))) (callout_int32 (int32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int32) (int int32_t int))) (callout_int64 (int64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int64) (int int64_t int))) (callout_uint8 (uint8_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint8) (int uint8_t int))) (callout_uint16 (uint16_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint16) (int uint16_t int))) (callout_uint32 (uint32_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint32) (int uint32_t int))) (callout_uint64 (uint64_t (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint64) (int uint64_t int))) (callout_char (char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_char) (int char int))) (callout_uchar (unsigned-char (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uchar) (int unsigned-char int))) (callout_short (signed-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_short) (int signed-short int))) (callout_ushort (unsigned-short (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ushort) (int unsigned-short int))) (callout_int (int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_int) (int int int))) (callout_uint (unsigned-int (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_uint) (int unsigned-int int))) (callout_long (long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_long) (int long int))) (callout_ulong (unsigned-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ulong) (int unsigned-long int))) (callout_llong (long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_llong) (int long-long int))) (callout_ullong (unsigned-long-long (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_ullong) (int unsigned-long-long int))) (callout_float (float (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_float) (int float int))) (callout_double (double (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_double) (int double int))) (callout_pointer (void* (lookup-shared-object ffitest-lib 'nausicaa_ffitest_callout_pointer) (int void* int)))) (check (let-values (((ret errno) (callout_int8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint8 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint16 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint32 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint64 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_char 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_uchar 1 (char->integer #\a) 3))) (list (integer->char ret) errno)) => '(#\a 1)) (check (let-values (((ret errno) (callout_short 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ushort 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_int 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_uint 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_long 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ulong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_llong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_ullong 1 2 3))) (list ret errno)) => '(2 1)) (check (let-values (((ret errno) (callout_float 1 2.3 3))) (list ret errno)) (=> (lambda (a b) (and (< (abs (- (car a) (car b))) 1e-6) (= (cadr a) (cadr b))))) '(2.3 1)) (check (let-values (((ret errno) (callout_double 1 2.3 3))) (list ret errno)) => '(2.3 1)) (check (let-values (((ret errno) (callout_pointer 1 (integer->pointer 2) 3))) (list (pointer->integer ret) errno)) => '(2 1)) #t) (parametrise ((check-test-name 'callback)) (define-c-functions ffitest-lib (callback_int8 (int8_t nausicaa_ffitest_callback_int8 (callback int int8_t int))) (callback_int16 (int16_t nausicaa_ffitest_callback_int16 (callback int int16_t int))) (callback_int32 (int32_t nausicaa_ffitest_callback_int32 (callback int int32_t int))) (callback_int64 (int64_t nausicaa_ffitest_callback_int64 (callback int int64_t int))) (callback_uint8 (uint8_t nausicaa_ffitest_callback_uint8 (callback int uint8_t int))) (callback_uint16 (uint16_t nausicaa_ffitest_callback_uint16 (callback int uint16_t int))) (callback_uint32 (uint32_t nausicaa_ffitest_callback_uint32 (callback int uint32_t int))) (callback_uint64 (uint64_t nausicaa_ffitest_callback_uint64 (callback int uint64_t int))) (callback_char (char nausicaa_ffitest_callback_char (callback int char int))) (callback_uchar (unsigned-char nausicaa_ffitest_callback_uchar (callback int unsigned-char int))) (callback_short (short nausicaa_ffitest_callback_short (callback int short int))) (callback_ushort (unsigned-short nausicaa_ffitest_callback_ushort (callback int unsigned-short int))) (callback_int (unsigned nausicaa_ffitest_callback_int (callback int int int))) (callback_uint (unsigned nausicaa_ffitest_callback_uint (callback int unsigned-int int))) (callback_long (long nausicaa_ffitest_callback_long (callback int long int))) (callback_ulong (unsigned-long nausicaa_ffitest_callback_ulong (callback int unsigned-long int))) (callback_llong (long-long nausicaa_ffitest_callback_llong (callback int long-long int))) (callback_ullong (unsigned-long-long nausicaa_ffitest_callback_ullong (callback int unsigned-long-long int))) (callback_float (float nausicaa_ffitest_callback_float (callback int float int))) (callback_double (double nausicaa_ffitest_callback_double (callback int double int))) (callback_pointer (void* nausicaa_ffitest_callback_pointer (callback int void* int)))) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int8_t fn (int int8_t int)))) (begin0 (callback_int8 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int16_t fn (int int16_t int)))) (begin0 (callback_int16 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int32_t fn (int int32_t int)))) (begin0 (callback_int32 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int64_t fn (int int64_t int)))) (begin0 (callback_int64 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint8_t fn (int uint8_t int)))) (begin0 (callback_uint8 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint16_t fn (int uint16_t int)))) (begin0 (callback_uint16 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint32_t fn (int uint32_t int)))) (begin0 (callback_uint32 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint64_t fn (int uint64_t int)))) (begin0 (callback_uint64 cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* short fn (int short int)))) (begin0 (callback_short cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* ushort fn (int ushort int)))) (begin0 (callback_ushort cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* int fn (int int int)))) (begin0 (callback_int cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uint fn (int uint int)))) (begin0 (callback_uint cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* long fn (int long int)))) (begin0 (callback_long cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* ulong fn (int ulong int)))) (begin0 (callback_ulong cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* llong fn (int llong int)))) (begin0 (callback_llong cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* ullong fn (int ullong int)))) (begin0 (callback_ullong cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* char fn (int char int)))) (begin0 (callback_char cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* uchar fn (int uchar int)))) (begin0 (callback_uchar cb 1 2 3) (free-c-callback cb))) => (+ 1 2 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* float fn (int float int)))) (begin0 (callback_float cb 1 2.3 3) (free-c-callback cb))) (=> (lambda (a b) (< (abs (- a b)) 1e-6))) (+ 1 2.3 3)) (check (let* ((fn (lambda (a b c) (+ a b c))) (cb (make-c-callback* double fn (int double int)))) (begin0 (callback_double cb 1 2.3 3) (free-c-callback cb))) => (+ 1 2.3 3)) (check (let* ((fn (lambda (a b c) (pointer-add (pointer-add b a) c))) (cb (make-c-callback* void* fn (int void* int)))) (begin0 (pointer->integer (callback_pointer cb 1 (integer->pointer 2) 3)) (free-c-callback cb))) => (+ 1 2 3)) #t) (check-report)
ce77ddfa9d5522fa5be8871a5805836ffd3b5b72925aefc3d64c9dbd2e5f362b
ktahar/ocaml-lp
test_glpk_ffi.ml
open Lp_glpk_ffi.M open Lp_glpk_types.M module C = Ctypes let prob = create_prob () let smcp = C.make Smcp.t let () = init_smcp (C.addr smcp) let iocp = C.make Iocp.t let () = init_iocp (C.addr iocp) let near_eq f0 f1 = Float.abs (f0 -. f1) < 1e-12 let max_int32 = Int32.to_int Int32.max_int module To_test = struct let set_get_pname () = set_prob_name prob "problem0" ; get_prob_name prob we can not use ( = ) to compare Ctypes structure let smcp_default () = List.for_all Fun.id [ (match C.getf smcp Smcp.msg_lev with Msg.ALL -> true | _ -> false) ; ( match C.getf smcp Smcp.meth with | Smcp.Meth.PRIMAL -> true | _ -> false ) ; (match C.getf smcp Smcp.pricing with Smcp.Pt.PSE -> true | _ -> false) ; (match C.getf smcp Smcp.r_test with Smcp.Rt.HAR -> true | _ -> false) ; near_eq 1e-7 (C.getf smcp Smcp.tol_bnd) ; near_eq 1e-7 (C.getf smcp Smcp.tol_dj) ; near_eq 1e-9 (C.getf smcp Smcp.tol_piv) ; ~-.max_float = C.getf smcp Smcp.obj_ll ; max_float = C.getf smcp Smcp.obj_ul ; max_int32 = C.getf smcp Smcp.it_lim ; max_int32 = C.getf smcp Smcp.tm_lim ; 5000 = C.getf smcp Smcp.out_frq ; 0 = C.getf smcp Smcp.out_dly ; not (C.getf smcp Smcp.presolve) ; C.getf smcp Smcp.excl ; C.getf smcp Smcp.shift ; (match C.getf smcp Smcp.aorn with Smcp.An.NT -> true | _ -> false) ] let iocp_default () = List.for_all Fun.id [ (match C.getf iocp Iocp.msg_lev with Msg.ALL -> true | _ -> false) ; (match C.getf iocp Iocp.br_tech with Iocp.Br.DTH -> true | _ -> false) ; (match C.getf iocp Iocp.bt_tech with Iocp.Bt.BLB -> true | _ -> false) ; near_eq 1e-5 (C.getf iocp Iocp.tol_int) ; near_eq 1e-7 (C.getf iocp Iocp.tol_obj) ; max_int32 = C.getf iocp Iocp.tm_lim ; 5000 = C.getf iocp Iocp.out_frq ; 10000 = C.getf iocp Iocp.out_dly ; C.null = C.getf iocp Iocp.cb_func ; C.null = C.getf iocp Iocp.cb_info ; 0 = C.getf iocp Iocp.cb_size ; (match C.getf iocp Iocp.pp_tech with Iocp.Pp.ALL -> true | _ -> false) ; near_eq 0.0 (C.getf iocp Iocp.mip_gap) ; not (C.getf iocp Iocp.mir_cuts) ; not (C.getf iocp Iocp.gmi_cuts) ; not (C.getf iocp Iocp.cov_cuts) ; not (C.getf iocp Iocp.clq_cuts) ; not (C.getf iocp Iocp.presolve) ; not (C.getf iocp Iocp.binarize) ; not (C.getf iocp Iocp.fp_heur) ; not (C.getf iocp Iocp.ps_heur) ; 60000 = C.getf iocp Iocp.ps_tm_lim ; C.getf iocp Iocp.sr_heur ; not (C.getf iocp Iocp.use_sol) can not get save_sol as it 's initialized with nullptr ; not (C.getf iocp Iocp.alien) ; C.getf iocp Iocp.flip ] end let set_get_pname () = Alcotest.(check string) "set_get_pname" "problem0" (To_test.set_get_pname ()) let smcp_default () = Alcotest.(check bool) "smcp_default" true (To_test.smcp_default ()) let iocp_default () = Alcotest.(check bool) "iocp_default" true (To_test.iocp_default ()) let () = let open Alcotest in run "Glp" [ ("set_get_pname", [test_case "set_get_pname" `Quick set_get_pname]) (* temporarily disable these tests due to dependency on GLPK version. *) TODO put more robust tests ; ( " smcp_default " , [ test_case " smcp_default " ` Quick smcp_default ] ) (* ; ("iocp_default", [test_case "iocp_default" `Quick iocp_default]) *) ]
null
https://raw.githubusercontent.com/ktahar/ocaml-lp/d8e2ad3fcef91cef6b3ec1fc39026bc07010c16b/test/lp-glpk/test_glpk_ffi.ml
ocaml
temporarily disable these tests due to dependency on GLPK version. ; ("iocp_default", [test_case "iocp_default" `Quick iocp_default])
open Lp_glpk_ffi.M open Lp_glpk_types.M module C = Ctypes let prob = create_prob () let smcp = C.make Smcp.t let () = init_smcp (C.addr smcp) let iocp = C.make Iocp.t let () = init_iocp (C.addr iocp) let near_eq f0 f1 = Float.abs (f0 -. f1) < 1e-12 let max_int32 = Int32.to_int Int32.max_int module To_test = struct let set_get_pname () = set_prob_name prob "problem0" ; get_prob_name prob we can not use ( = ) to compare Ctypes structure let smcp_default () = List.for_all Fun.id [ (match C.getf smcp Smcp.msg_lev with Msg.ALL -> true | _ -> false) ; ( match C.getf smcp Smcp.meth with | Smcp.Meth.PRIMAL -> true | _ -> false ) ; (match C.getf smcp Smcp.pricing with Smcp.Pt.PSE -> true | _ -> false) ; (match C.getf smcp Smcp.r_test with Smcp.Rt.HAR -> true | _ -> false) ; near_eq 1e-7 (C.getf smcp Smcp.tol_bnd) ; near_eq 1e-7 (C.getf smcp Smcp.tol_dj) ; near_eq 1e-9 (C.getf smcp Smcp.tol_piv) ; ~-.max_float = C.getf smcp Smcp.obj_ll ; max_float = C.getf smcp Smcp.obj_ul ; max_int32 = C.getf smcp Smcp.it_lim ; max_int32 = C.getf smcp Smcp.tm_lim ; 5000 = C.getf smcp Smcp.out_frq ; 0 = C.getf smcp Smcp.out_dly ; not (C.getf smcp Smcp.presolve) ; C.getf smcp Smcp.excl ; C.getf smcp Smcp.shift ; (match C.getf smcp Smcp.aorn with Smcp.An.NT -> true | _ -> false) ] let iocp_default () = List.for_all Fun.id [ (match C.getf iocp Iocp.msg_lev with Msg.ALL -> true | _ -> false) ; (match C.getf iocp Iocp.br_tech with Iocp.Br.DTH -> true | _ -> false) ; (match C.getf iocp Iocp.bt_tech with Iocp.Bt.BLB -> true | _ -> false) ; near_eq 1e-5 (C.getf iocp Iocp.tol_int) ; near_eq 1e-7 (C.getf iocp Iocp.tol_obj) ; max_int32 = C.getf iocp Iocp.tm_lim ; 5000 = C.getf iocp Iocp.out_frq ; 10000 = C.getf iocp Iocp.out_dly ; C.null = C.getf iocp Iocp.cb_func ; C.null = C.getf iocp Iocp.cb_info ; 0 = C.getf iocp Iocp.cb_size ; (match C.getf iocp Iocp.pp_tech with Iocp.Pp.ALL -> true | _ -> false) ; near_eq 0.0 (C.getf iocp Iocp.mip_gap) ; not (C.getf iocp Iocp.mir_cuts) ; not (C.getf iocp Iocp.gmi_cuts) ; not (C.getf iocp Iocp.cov_cuts) ; not (C.getf iocp Iocp.clq_cuts) ; not (C.getf iocp Iocp.presolve) ; not (C.getf iocp Iocp.binarize) ; not (C.getf iocp Iocp.fp_heur) ; not (C.getf iocp Iocp.ps_heur) ; 60000 = C.getf iocp Iocp.ps_tm_lim ; C.getf iocp Iocp.sr_heur ; not (C.getf iocp Iocp.use_sol) can not get save_sol as it 's initialized with nullptr ; not (C.getf iocp Iocp.alien) ; C.getf iocp Iocp.flip ] end let set_get_pname () = Alcotest.(check string) "set_get_pname" "problem0" (To_test.set_get_pname ()) let smcp_default () = Alcotest.(check bool) "smcp_default" true (To_test.smcp_default ()) let iocp_default () = Alcotest.(check bool) "iocp_default" true (To_test.iocp_default ()) let () = let open Alcotest in run "Glp" [ ("set_get_pname", [test_case "set_get_pname" `Quick set_get_pname]) TODO put more robust tests ; ( " smcp_default " , [ test_case " smcp_default " ` Quick smcp_default ] ) ]
de4ffc50cd21ce9db7f8623afe4c2c559dfcc9f7dbdfa8bd786bc5c01c72a917
tsloughter/rebar3_tests
exometer_histogram.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved . %% This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% %% ------------------------------------------------------------------- @doc Exometer histogram probe behavior %% This module implements histogram metrics. Each histogram is a sliding %% window, for which the following datapoints are calculated: %% %% * `max': the maximum value %% * `min': the minimum value %% * `mean': the arithmetic mean %% * `median': the median * ` 50|75|90|95|97|99 ' : percentiles %% * `999': the 99.9th percentile %% * `n': the number of values used in the calculation (Note) %% Two histogram implementations are supported and can be selected using %% the option `histogram_module': %% %% * `exometer_slide' implements a sliding window, which saves all elements %% within the window. Updating the histogram is cheap, but calculating the %% datapoints may be expensive depending on the size of the window. %% * ` exometer_slot_slide ' ( default ) , aggregates mean , min and values %% within given time slots, thereby reducing the amount of data kept for %% datapoint calculation. The update overhead should be insignificant. %% However, some loss of precision must be expected. To achieve slightly better accuracy of percentiles , ' extra values ' are kept ( every 4th %% value). For the calculation, extra vaules are included in the set until a suitable number has been reached ( up to 600 ) . Note that %% `n' reflects the number of values used in the calculation - not the %% number of updates made within the time window. %% %% Supported options: %% * ` time_span ' ( default : ` 60000 ' ) size of the window in milliseconds . * ` slot_period ' ( default : ` 10 ' ) size of the time slots in milliseconds . %% * `histogram_module' (default: `exometer_slot_slide'). %% * `truncate' (default: `true') whether to truncate the datapoint values. %% Supported values: `true | false | round', where `round' means to round %% the value rather than truncating it. %% * `keep_high' (default: `0') number of top values to actually keep. %% %% The `keep_high' option can be used to get better precision for the higher %% percentiles. A bounded buffer (see {@link exometer_shallowtree}) is used %% to store the highest values, and these values are used to calculate the %% exact higher percentiles, as far as they go. For example, if the window saw 10,000 values , and the 1000 highest values are kept , these can be used to determine the percentiles ` 90 ' and up . %% %% @end -module(exometer_histogram). -behaviour(exometer_probe). %% exometer_probe callbacks -export([behaviour/0, probe_init/3, probe_terminate/1, probe_setopts/3, probe_update/2, probe_get_value/2, probe_get_datapoints/1, probe_reset/1, probe_code_change/3, probe_sample/1, probe_handle_msg/2]). -compile(inline). -compile(inline_list_funcs). -export([datapoints/0]). -export([average_sample/3, average_transform/2]). -export([test_run/1, test_run/2, test_series/0]). %% -compile({parse_transform, exometer_igor}). %% -compile({igor, [{files, ["src/exometer_util.erl" %% , "src/exometer_proc.erl" %% , "src/exometer_slot_slide.erl" %% , "src/exometer_slide.erl" %% ]}]}). -include("exometer.hrl"). -record(st, {name, slide = undefined, %% slot_period = 10, %% msec time_span = 60000, %% msec truncate = true, histogram_module = exometer_slot_slide, heap, opts = []}). %% for auto-conversion -define(OLDSTATE, {st,_,_,_,_,_,_,_}). -define(DATAPOINTS, [n, mean, min, max, median, 50, 75, 90, 95, 99, 999 ]). -spec behaviour() -> exometer:behaviour(). behaviour() -> probe. probe_init(Name, _Type, Options) -> {ok, init_state(Name, Options)}. init_state(Name, Options) -> St = process_opts(#st{name = Name}, Options), Slide = (St#st.histogram_module):new(St#st.time_span, St#st.slot_period, fun average_sample/3, fun average_transform/2, Options), Heap = if St#st.histogram_module == exometer_slot_slide -> case lists:keyfind(keep_high, 1, Options) of false -> undefined; {_, N} when is_integer(N), N > 0 -> T = exometer_shallowtree:new(N), {T, T}; {_, 0} -> undefined end; true -> undefined end, St#st{slide = Slide, heap = Heap}. probe_terminate(_St) -> ok. probe_get_value(DPs, ?OLDSTATE = St) -> probe_get_value(DPs, convert(St)); probe_get_value(DataPoints, St) -> {ok, get_value_int(St, DataPoints)}. probe_get_datapoints(_St) -> {ok, datapoints()}. datapoints() -> ?DATAPOINTS. get_value_int(St, default) -> get_value_int_(St, ?DATAPOINTS); get_value_int(_, []) -> []; get_value_int(?OLDSTATE = St, DPs) -> get_value_int(convert(St), DPs); get_value_int(St, DataPoints) -> get_value_int_(St, DataPoints). get_value_int_(#st{truncate = Trunc, histogram_module = Module, time_span = TimeSpan, heap = Heap} = St, DataPoints) -> %% We need element count and sum of all elements to get mean value. Tot0 = case Trunc of true -> 0; round -> 0; false -> 0.0 end, TS = exometer_util:timestamp(), {Length, FullLength, Total, Min0, Max, Lst0, Xtra} = Module:foldl( TS, fun ({_TS1, {Val, Cnt, NMin, NMax, X}}, {Length, FullLen, Total, OMin, OMax, List, Xs}) -> {Length + 1, FullLen + Cnt, Total + Val, min(OMin, NMin), max(OMax, NMax), [Val|List], [X|Xs]}; ({_TS1, Val}, {Length, _, Total, Min, Max, List, Xs}) -> L1 = Length+1, {L1, L1, Total + Val, min(Val, Min), max(Val, Max), [Val|List], Xs} end, {0, 0, Tot0, infinity, 0, [], []}, St#st.slide), Min = if Min0 == infinity -> 0; true -> Min0 end, Mean = case Length of 0 -> 0.0; N -> Total / N end, {Len, List} = if Module == exometer_slot_slide -> {Length1, Lst} = add_extra(Length, Lst0, Xtra), {Length1 + 2, [Min|lists:sort(Lst)] ++ [Max]}; true -> {Length, lists:sort(Lst0)} end, TopPercentiles = get_from_heap(Heap, TS, TimeSpan, FullLength, DataPoints), Results = case List of [0, 0] -> a case where and are the only data , nil []; _ -> exometer_util:get_statistics2(Len, List, Total, Mean) end, CombinedResults = TopPercentiles ++ Results, [get_dp(K, CombinedResults, Trunc) || K <- DataPoints]. get_from_heap({New,Old}, TS, TSpan, N, DPs) when N > 0 -> Sz = exometer_shallowtree:size(New) + exometer_shallowtree:size(Old), if Sz > 0 -> MinPerc = 100 - ((Sz*100) div N), MinPerc10 = MinPerc * 10, GetDPs = lists:foldl( fun(D, Acc) when is_integer(D), D < 100, D >= MinPerc -> [{D, p(D, N)}|Acc]; (D, Acc) when is_integer(D), D > 100, D >= MinPerc10 -> [{D, p(D, N)}|Acc]; (_, Acc) -> Acc end, [], DPs), pick_heap_vals(GetDPs, New, Old, TS, TSpan); true -> [] end; get_from_heap(_, _, _, _, _) -> []. pick_heap_vals([], _, _, _, _) -> []; pick_heap_vals(DPs, New, Old, TS, TSpan) -> TS0 = TS - TSpan, NewVals = exometer_shallowtree:filter(fun(V,_) -> {true,V} end, New), OldVals = exometer_shallowtree:filter( fun(V,T) -> if T >= TS0 -> {true, V}; true -> false end end, Old), Vals = revsort(OldVals ++ NewVals), exometer_util:pick_items(Vals, DPs). revsort(L) -> lists:sort(fun erlang:'>'/2, L). p(50, N) -> perc(0.5, N); p(75, N) -> perc(0.75, N); p(90, N) -> perc(0.9, N); p(95, N) -> perc(0.95, N); p(99, N) -> perc(0.99, N); p(999,N) -> perc(0.999, N). perc(P, N) -> N - exometer_util:perc(P, N) + 1. add_extra(Length, L, []) -> {Length, L}; add_extra(Length, L, X) when Length < 300 -> aim for 600 elements , since experiments indicate that this gives decent accuracy at decent speed ( ca 300 - 400 us on a Core i7 ) Pick = max(2, ((600 - Length) div Length) + 1), pick_extra(X, Pick, Pick, L, Length); add_extra(Length, L, X) -> Always take something from the Xtra , since this improves percentile %% accuracy pick_extra(X, 1, 1, L, Length). pick_extra([[H|T]|T1], P, Pick, L, Length) when P > 0 -> pick_extra([T|T1], P-1, Pick, [H|L], Length+1); pick_extra([_|T], 0, Pick, L, Length) -> pick_extra(T, Pick, Pick, L, Length); pick_extra([[]|T], _, Pick, L, Length) -> pick_extra(T, Pick, Pick, L, Length); pick_extra([], _, _, L, Length) -> {Length, L}. get_dp(K, L, Trunc) -> case lists:keyfind(K, 1, L) of false -> {K, if Trunc -> 0; Trunc==round -> 0; true -> 0.0 end}; {median, F} when is_float(F) -> %% always truncate median {median, trunc(F)}; {_, V} = DP when is_integer(V) -> DP; {_,_} = DP -> opt_trunc(Trunc, DP) end. probe_setopts(_Entry, _Opts, _St) -> ok. probe_update(Value, ?OLDSTATE = St) -> probe_update(Value, convert(St)); probe_update(Value, St) -> if is_number(Value) -> {ok, update_int(exometer_util:timestamp(), Value, St)}; true -> %% ignore {ok, St} end. update_int(Timestamp, Value, #st{slide = Slide, histogram_module = Module, heap = Heap} = St) -> {Wrapped, Slide1} = Module:add_element(Timestamp, Value, Slide, true), St#st{slide = Slide1, heap = into_heap(Wrapped, Value, Timestamp, Heap)}. into_heap(_, _Val, _TS, undefined) -> undefined; into_heap(false, Val, TS, {New,Old}) -> {exometer_shallowtree:insert(Val, TS, New), Old}; into_heap(true, Val, TS, {New,_}) -> Limit = exometer_shallowtree:limit(New), {exometer_shallowtree:insert( Val, TS, exometer_shallowtree:new(Limit)), New}. probe_reset(?OLDSTATE = St) -> probe_reset(convert(St)); probe_reset(#st{slide = Slide, histogram_module = Module} = St) -> {ok, St#st{slide = Module:reset(Slide)}}. probe_sample(_St) -> {error, unsupported}. probe_handle_msg(_, S) -> {ok, S}. probe_code_change(_, ?OLDSTATE = S, _) -> {ok, convert(S)}; probe_code_change(_, S, _) -> {ok, S}. convert({st, Name, Slide, Slot_period, Time_span, Truncate, Histogram_module, Opts}) -> #st{name = Name, slide = Slide, slot_period = Slot_period, time_span = Time_span, truncate = Truncate, histogram_module = Histogram_module, opts = Opts}. process_opts(St, Options) -> exometer_proc:process_options(Options), lists:foldl( fun %% Sample interval. ( {time_span, Val}, St1) -> St1#st {time_span = Val}; ( {slot_period, Val}, St1) -> St1#st {slot_period = Val}; ( {histogram_module, Val}, St1) -> St1#st {histogram_module = Val}; ( {truncate, Val}, St1) when is_boolean(Val); Val == round -> St1#st{truncate = Val}; Unknown option , pass on to State options list , replacing %% any earlier versions of the same option. ({Opt, Val}, St1) -> St1#st{ opts = [ {Opt, Val} | lists:keydelete(Opt, 1, St1#st.opts) ] } end, St, Options). -record(sample, {count, total, min, max, extra = []}). %% Simple sample processor that maintains an average %% of all sampled values average_sample(_TS, Val, undefined) -> #sample{count = 1, total = Val, min = Val, max = Val}; average_sample(_TS, Val, #sample{count = Count, total = Total, min = Min, max = Max, extra = X} = S) -> Count1 = Count + 1, X1 = if Count1 rem 4 == 0 -> [Val|X]; true -> X end, S#sample{count = Count1, total = Total + Val, min = min(Min, Val), max = max(Max, Val), extra = X1}. %% If average_sample() has not been called for the current time slot, %% then the provided state will still be 'undefined' average_transform(_TS, undefined) -> undefined; %% Return the calculated total for the slot and return it as the %% element to be stored in the histogram. average_transform(_TS, #sample{count = Count, total = Total, min = Min, max = Max, extra = X}) -> %% Return the sum of all counter increments received during this slot {Total / Count, Count, Min, Max, X}. opt_trunc(true, {K,V}) when is_float(V) -> {K, trunc(V)}; opt_trunc(round, {K,V}) when is_float(V) -> {K, round(V)}; opt_trunc(_, V) -> V. test_new(Opts) -> init_state(test, Opts). %% @equiv test_run(Module, 1) test_run(Module) -> test_run(Module, 1). %% @doc Test the performance and accuracy of a histogram callback module. %% %% This function uses a test set ({@link test_series/0}) and initializes %% and updates a histogram using the callback module `Module'. %% The ` Module ' argument can either be the module name , or ` { ModName , } ' where ` Opts ' are options passed on to the histogram module . %% %% `Interval' is the gap in milliseconds between the inserts. The test run %% will not actually wait, but instead manipulate the timestamp. %% Return value : ` [ Result1 , ] ' , where the results are ` { Time1 , Time2 , Datapoints } ' . ` Time1 ' is the time ( in microsecs ) it took to %% insert the values. `Time2' is the time it took to calculate all default datapoints . The data set is shuffled between the two runs . %% %% To assess the accuracy of the reported percentiles, use e.g. %% `bear:get_statistics(exometer_histogram:test_series())' as a reference. %% @end test_run(Module, Interval) -> Series = test_series(), [test_run(Module, Interval, Series), test_run(Module, Interval, shuffle(Series))]. test_run(Module, Int, Series) -> St = test_new(test_opts(Module)), {T1, St1} = tc(fun() -> test_update( Series, Int, exometer_util:timestamp(), St) end), {T2, Result} = tc(fun() -> get_value_int(St1, default) end), erlang:garbage_collect(), erlang:yield(), {T1, T2, Result}. test_opts(M) when is_atom(M) -> [{histogram_module, M}]; test_opts({M, Opts}) -> [{histogram_module, M}|Opts]. test_update([H|T], Int, TS, St) -> test_update(T, Int, TS+Int, update_int(TS, H, St)); test_update([], _, _, St) -> St. tc(F) -> T1 = os:timestamp(), Res = F(), T2 = os:timestamp(), {timer:now_diff(T2, T1), Res}. -spec test_series() -> [integer()]. %% @doc Create a series of values for histogram testing. %% %% These are the properties of the current test set: %% <pre lang="erlang"> %% 1&gt; rp(bear:get_statistics(exometer_histogram:test_series())). %% [{min,3}, %% {max,100}, %% {arithmetic_mean,6.696}, %% {geometric_mean,5.546722009408586}, %% {harmonic_mean,5.033909932832006}, %% {median,5}, %% {variance,63.92468674297564}, %% {standard_deviation,7.995291535833802}, %% {skewness,7.22743137858698}, %% {kurtosis,59.15674033499604}, %% {percentile,[{50,5},{75,7},{90,8},{95,9},{99,50},{999,83}]}, %% {histogram,[{4,2700}, { 5,1800 } , { 6,900 } , %% {7,1800}, { 8,900 } , { 9,720 } , { 53,135 } , , { 103,9 } ] } , %% {n,9000}] %% </pre> %% @end test_series() -> S = lists:flatten( [dupl(200,3), dupl(100,4), dupl(200,5), dupl(100,6), dupl(200,7), dupl(100,8), dupl(80,9), dupl(15,50), 80,81,82,83,100]), shuffle(S ++ S ++ S ++ S ++ S ++ S ++ S ++ S ++ S). dupl(N,V) -> lists:duplicate(N, V). shuffle(List) -> exometer_util:seed(exometer_util:seed0()), Randomized = lists:keysort(1, [{exometer_util:uniform(), Item} || Item <- List]), [Value || {_, Value} <- Randomized].
null
https://raw.githubusercontent.com/tsloughter/rebar3_tests/af19097d597b061a0fde5c58ce354a623ca05f38/ptrans_deporder/_checkouts/exometer_core/src/exometer_histogram.erl
erlang
------------------------------------------------------------------- ------------------------------------------------------------------- This module implements histogram metrics. Each histogram is a sliding window, for which the following datapoints are calculated: * `max': the maximum value * `min': the minimum value * `mean': the arithmetic mean * `median': the median * `999': the 99.9th percentile * `n': the number of values used in the calculation (Note) the option `histogram_module': * `exometer_slide' implements a sliding window, which saves all elements within the window. Updating the histogram is cheap, but calculating the datapoints may be expensive depending on the size of the window. within given time slots, thereby reducing the amount of data kept for datapoint calculation. The update overhead should be insignificant. However, some loss of precision must be expected. To achieve slightly value). For the calculation, extra vaules are included in the set `n' reflects the number of values used in the calculation - not the number of updates made within the time window. Supported options: * `histogram_module' (default: `exometer_slot_slide'). * `truncate' (default: `true') whether to truncate the datapoint values. Supported values: `true | false | round', where `round' means to round the value rather than truncating it. * `keep_high' (default: `0') number of top values to actually keep. The `keep_high' option can be used to get better precision for the higher percentiles. A bounded buffer (see {@link exometer_shallowtree}) is used to store the highest values, and these values are used to calculate the exact higher percentiles, as far as they go. For example, if the window @end exometer_probe callbacks -compile({parse_transform, exometer_igor}). -compile({igor, [{files, ["src/exometer_util.erl" , "src/exometer_proc.erl" , "src/exometer_slot_slide.erl" , "src/exometer_slide.erl" ]}]}). msec msec for auto-conversion We need element count and sum of all elements to get mean value. accuracy always truncate median ignore Sample interval. any earlier versions of the same option. Simple sample processor that maintains an average of all sampled values If average_sample() has not been called for the current time slot, then the provided state will still be 'undefined' Return the calculated total for the slot and return it as the element to be stored in the histogram. Return the sum of all counter increments received during this slot @equiv test_run(Module, 1) @doc Test the performance and accuracy of a histogram callback module. This function uses a test set ({@link test_series/0}) and initializes and updates a histogram using the callback module `Module'. `Interval' is the gap in milliseconds between the inserts. The test run will not actually wait, but instead manipulate the timestamp. insert the values. `Time2' is the time it took to calculate all default To assess the accuracy of the reported percentiles, use e.g. `bear:get_statistics(exometer_histogram:test_series())' as a reference. @end @doc Create a series of values for histogram testing. These are the properties of the current test set: <pre lang="erlang"> 1&gt; rp(bear:get_statistics(exometer_histogram:test_series())). [{min,3}, {max,100}, {arithmetic_mean,6.696}, {geometric_mean,5.546722009408586}, {harmonic_mean,5.033909932832006}, {median,5}, {variance,63.92468674297564}, {standard_deviation,7.995291535833802}, {skewness,7.22743137858698}, {kurtosis,59.15674033499604}, {percentile,[{50,5},{75,7},{90,8},{95,9},{99,50},{999,83}]}, {histogram,[{4,2700}, {7,1800}, {n,9000}] </pre> @end
Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved . This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. @doc Exometer histogram probe behavior * ` 50|75|90|95|97|99 ' : percentiles Two histogram implementations are supported and can be selected using * ` exometer_slot_slide ' ( default ) , aggregates mean , min and values better accuracy of percentiles , ' extra values ' are kept ( every 4th until a suitable number has been reached ( up to 600 ) . Note that * ` time_span ' ( default : ` 60000 ' ) size of the window in milliseconds . * ` slot_period ' ( default : ` 10 ' ) size of the time slots in milliseconds . saw 10,000 values , and the 1000 highest values are kept , these can be used to determine the percentiles ` 90 ' and up . -module(exometer_histogram). -behaviour(exometer_probe). -export([behaviour/0, probe_init/3, probe_terminate/1, probe_setopts/3, probe_update/2, probe_get_value/2, probe_get_datapoints/1, probe_reset/1, probe_code_change/3, probe_sample/1, probe_handle_msg/2]). -compile(inline). -compile(inline_list_funcs). -export([datapoints/0]). -export([average_sample/3, average_transform/2]). -export([test_run/1, test_run/2, test_series/0]). -include("exometer.hrl"). -record(st, {name, truncate = true, histogram_module = exometer_slot_slide, heap, opts = []}). -define(OLDSTATE, {st,_,_,_,_,_,_,_}). -define(DATAPOINTS, [n, mean, min, max, median, 50, 75, 90, 95, 99, 999 ]). -spec behaviour() -> exometer:behaviour(). behaviour() -> probe. probe_init(Name, _Type, Options) -> {ok, init_state(Name, Options)}. init_state(Name, Options) -> St = process_opts(#st{name = Name}, Options), Slide = (St#st.histogram_module):new(St#st.time_span, St#st.slot_period, fun average_sample/3, fun average_transform/2, Options), Heap = if St#st.histogram_module == exometer_slot_slide -> case lists:keyfind(keep_high, 1, Options) of false -> undefined; {_, N} when is_integer(N), N > 0 -> T = exometer_shallowtree:new(N), {T, T}; {_, 0} -> undefined end; true -> undefined end, St#st{slide = Slide, heap = Heap}. probe_terminate(_St) -> ok. probe_get_value(DPs, ?OLDSTATE = St) -> probe_get_value(DPs, convert(St)); probe_get_value(DataPoints, St) -> {ok, get_value_int(St, DataPoints)}. probe_get_datapoints(_St) -> {ok, datapoints()}. datapoints() -> ?DATAPOINTS. get_value_int(St, default) -> get_value_int_(St, ?DATAPOINTS); get_value_int(_, []) -> []; get_value_int(?OLDSTATE = St, DPs) -> get_value_int(convert(St), DPs); get_value_int(St, DataPoints) -> get_value_int_(St, DataPoints). get_value_int_(#st{truncate = Trunc, histogram_module = Module, time_span = TimeSpan, heap = Heap} = St, DataPoints) -> Tot0 = case Trunc of true -> 0; round -> 0; false -> 0.0 end, TS = exometer_util:timestamp(), {Length, FullLength, Total, Min0, Max, Lst0, Xtra} = Module:foldl( TS, fun ({_TS1, {Val, Cnt, NMin, NMax, X}}, {Length, FullLen, Total, OMin, OMax, List, Xs}) -> {Length + 1, FullLen + Cnt, Total + Val, min(OMin, NMin), max(OMax, NMax), [Val|List], [X|Xs]}; ({_TS1, Val}, {Length, _, Total, Min, Max, List, Xs}) -> L1 = Length+1, {L1, L1, Total + Val, min(Val, Min), max(Val, Max), [Val|List], Xs} end, {0, 0, Tot0, infinity, 0, [], []}, St#st.slide), Min = if Min0 == infinity -> 0; true -> Min0 end, Mean = case Length of 0 -> 0.0; N -> Total / N end, {Len, List} = if Module == exometer_slot_slide -> {Length1, Lst} = add_extra(Length, Lst0, Xtra), {Length1 + 2, [Min|lists:sort(Lst)] ++ [Max]}; true -> {Length, lists:sort(Lst0)} end, TopPercentiles = get_from_heap(Heap, TS, TimeSpan, FullLength, DataPoints), Results = case List of [0, 0] -> a case where and are the only data , nil []; _ -> exometer_util:get_statistics2(Len, List, Total, Mean) end, CombinedResults = TopPercentiles ++ Results, [get_dp(K, CombinedResults, Trunc) || K <- DataPoints]. get_from_heap({New,Old}, TS, TSpan, N, DPs) when N > 0 -> Sz = exometer_shallowtree:size(New) + exometer_shallowtree:size(Old), if Sz > 0 -> MinPerc = 100 - ((Sz*100) div N), MinPerc10 = MinPerc * 10, GetDPs = lists:foldl( fun(D, Acc) when is_integer(D), D < 100, D >= MinPerc -> [{D, p(D, N)}|Acc]; (D, Acc) when is_integer(D), D > 100, D >= MinPerc10 -> [{D, p(D, N)}|Acc]; (_, Acc) -> Acc end, [], DPs), pick_heap_vals(GetDPs, New, Old, TS, TSpan); true -> [] end; get_from_heap(_, _, _, _, _) -> []. pick_heap_vals([], _, _, _, _) -> []; pick_heap_vals(DPs, New, Old, TS, TSpan) -> TS0 = TS - TSpan, NewVals = exometer_shallowtree:filter(fun(V,_) -> {true,V} end, New), OldVals = exometer_shallowtree:filter( fun(V,T) -> if T >= TS0 -> {true, V}; true -> false end end, Old), Vals = revsort(OldVals ++ NewVals), exometer_util:pick_items(Vals, DPs). revsort(L) -> lists:sort(fun erlang:'>'/2, L). p(50, N) -> perc(0.5, N); p(75, N) -> perc(0.75, N); p(90, N) -> perc(0.9, N); p(95, N) -> perc(0.95, N); p(99, N) -> perc(0.99, N); p(999,N) -> perc(0.999, N). perc(P, N) -> N - exometer_util:perc(P, N) + 1. add_extra(Length, L, []) -> {Length, L}; add_extra(Length, L, X) when Length < 300 -> aim for 600 elements , since experiments indicate that this gives decent accuracy at decent speed ( ca 300 - 400 us on a Core i7 ) Pick = max(2, ((600 - Length) div Length) + 1), pick_extra(X, Pick, Pick, L, Length); add_extra(Length, L, X) -> Always take something from the Xtra , since this improves percentile pick_extra(X, 1, 1, L, Length). pick_extra([[H|T]|T1], P, Pick, L, Length) when P > 0 -> pick_extra([T|T1], P-1, Pick, [H|L], Length+1); pick_extra([_|T], 0, Pick, L, Length) -> pick_extra(T, Pick, Pick, L, Length); pick_extra([[]|T], _, Pick, L, Length) -> pick_extra(T, Pick, Pick, L, Length); pick_extra([], _, _, L, Length) -> {Length, L}. get_dp(K, L, Trunc) -> case lists:keyfind(K, 1, L) of false -> {K, if Trunc -> 0; Trunc==round -> 0; true -> 0.0 end}; {median, F} when is_float(F) -> {median, trunc(F)}; {_, V} = DP when is_integer(V) -> DP; {_,_} = DP -> opt_trunc(Trunc, DP) end. probe_setopts(_Entry, _Opts, _St) -> ok. probe_update(Value, ?OLDSTATE = St) -> probe_update(Value, convert(St)); probe_update(Value, St) -> if is_number(Value) -> {ok, update_int(exometer_util:timestamp(), Value, St)}; true -> {ok, St} end. update_int(Timestamp, Value, #st{slide = Slide, histogram_module = Module, heap = Heap} = St) -> {Wrapped, Slide1} = Module:add_element(Timestamp, Value, Slide, true), St#st{slide = Slide1, heap = into_heap(Wrapped, Value, Timestamp, Heap)}. into_heap(_, _Val, _TS, undefined) -> undefined; into_heap(false, Val, TS, {New,Old}) -> {exometer_shallowtree:insert(Val, TS, New), Old}; into_heap(true, Val, TS, {New,_}) -> Limit = exometer_shallowtree:limit(New), {exometer_shallowtree:insert( Val, TS, exometer_shallowtree:new(Limit)), New}. probe_reset(?OLDSTATE = St) -> probe_reset(convert(St)); probe_reset(#st{slide = Slide, histogram_module = Module} = St) -> {ok, St#st{slide = Module:reset(Slide)}}. probe_sample(_St) -> {error, unsupported}. probe_handle_msg(_, S) -> {ok, S}. probe_code_change(_, ?OLDSTATE = S, _) -> {ok, convert(S)}; probe_code_change(_, S, _) -> {ok, S}. convert({st, Name, Slide, Slot_period, Time_span, Truncate, Histogram_module, Opts}) -> #st{name = Name, slide = Slide, slot_period = Slot_period, time_span = Time_span, truncate = Truncate, histogram_module = Histogram_module, opts = Opts}. process_opts(St, Options) -> exometer_proc:process_options(Options), lists:foldl( fun ( {time_span, Val}, St1) -> St1#st {time_span = Val}; ( {slot_period, Val}, St1) -> St1#st {slot_period = Val}; ( {histogram_module, Val}, St1) -> St1#st {histogram_module = Val}; ( {truncate, Val}, St1) when is_boolean(Val); Val == round -> St1#st{truncate = Val}; Unknown option , pass on to State options list , replacing ({Opt, Val}, St1) -> St1#st{ opts = [ {Opt, Val} | lists:keydelete(Opt, 1, St1#st.opts) ] } end, St, Options). -record(sample, {count, total, min, max, extra = []}). average_sample(_TS, Val, undefined) -> #sample{count = 1, total = Val, min = Val, max = Val}; average_sample(_TS, Val, #sample{count = Count, total = Total, min = Min, max = Max, extra = X} = S) -> Count1 = Count + 1, X1 = if Count1 rem 4 == 0 -> [Val|X]; true -> X end, S#sample{count = Count1, total = Total + Val, min = min(Min, Val), max = max(Max, Val), extra = X1}. average_transform(_TS, undefined) -> undefined; average_transform(_TS, #sample{count = Count, total = Total, min = Min, max = Max, extra = X}) -> {Total / Count, Count, Min, Max, X}. opt_trunc(true, {K,V}) when is_float(V) -> {K, trunc(V)}; opt_trunc(round, {K,V}) when is_float(V) -> {K, round(V)}; opt_trunc(_, V) -> V. test_new(Opts) -> init_state(test, Opts). test_run(Module) -> test_run(Module, 1). The ` Module ' argument can either be the module name , or ` { ModName , } ' where ` Opts ' are options passed on to the histogram module . Return value : ` [ Result1 , ] ' , where the results are ` { Time1 , Time2 , Datapoints } ' . ` Time1 ' is the time ( in microsecs ) it took to datapoints . The data set is shuffled between the two runs . test_run(Module, Interval) -> Series = test_series(), [test_run(Module, Interval, Series), test_run(Module, Interval, shuffle(Series))]. test_run(Module, Int, Series) -> St = test_new(test_opts(Module)), {T1, St1} = tc(fun() -> test_update( Series, Int, exometer_util:timestamp(), St) end), {T2, Result} = tc(fun() -> get_value_int(St1, default) end), erlang:garbage_collect(), erlang:yield(), {T1, T2, Result}. test_opts(M) when is_atom(M) -> [{histogram_module, M}]; test_opts({M, Opts}) -> [{histogram_module, M}|Opts]. test_update([H|T], Int, TS, St) -> test_update(T, Int, TS+Int, update_int(TS, H, St)); test_update([], _, _, St) -> St. tc(F) -> T1 = os:timestamp(), Res = F(), T2 = os:timestamp(), {timer:now_diff(T2, T1), Res}. -spec test_series() -> [integer()]. { 5,1800 } , { 6,900 } , { 8,900 } , { 9,720 } , { 53,135 } , , { 103,9 } ] } , test_series() -> S = lists:flatten( [dupl(200,3), dupl(100,4), dupl(200,5), dupl(100,6), dupl(200,7), dupl(100,8), dupl(80,9), dupl(15,50), 80,81,82,83,100]), shuffle(S ++ S ++ S ++ S ++ S ++ S ++ S ++ S ++ S). dupl(N,V) -> lists:duplicate(N, V). shuffle(List) -> exometer_util:seed(exometer_util:seed0()), Randomized = lists:keysort(1, [{exometer_util:uniform(), Item} || Item <- List]), [Value || {_, Value} <- Randomized].
97c13a01be3f1d8a69fbb60e5c6d5e201c697a4afa7ec3ac6e3343a19253ed4b
IBM/wcs-ocaml
cnl2cnl.ml
* This file is part of the Watson Conversation Service OCaml API project . * * Copyright 2016 - 2017 IBM Corporation * * Licensed under the Apache License , Version 2.0 ( the " License " ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an " AS IS " BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . * This file is part of the Watson Conversation Service OCaml API project. * * Copyright 2016-2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) open Cnl_t (***************************) * { 6 . Shallow Iterators } (***************************) * { 8 . node } let node_sh_map_fold (f: 'a -> 'b -> 'c * 'b) (node: 'a node) (acc: 'b) : 'c node * 'b = begin match node with | N_undefined id -> N_undefined id, acc | N_filled (id, x) -> let x, acc = f x acc in N_filled (id, x), acc | N_rejected (id, x) -> let x, acc = f x acc in N_rejected (id, x), acc | N_accepted x -> let x, acc = f x acc in N_accepted x, acc end let node_sh_map (f: 'a -> 'b) (node: 'a node) : 'b node = let node, () = node_sh_map_fold (fun x () -> f x, ()) node () in node let node_sh_fold (f: 'a -> 'b -> 'b) (node: 'a node) (acc: 'b) : 'b = let _, acc = node_sh_map_fold (fun x acc -> x, f x acc) node acc in acc let node_list_sh_map_fold (f_elem: 'a -> 'b -> 'c * 'b) (f_closed: unit node -> 'b -> unit node * 'b) (l: 'a node_list) (acc: 'b) : 'c node_list * 'b = let rev_l, acc = List.fold_left (fun (rev_l, acc) elem -> let elem, acc = f_elem elem acc in elem::rev_l, acc) ([], acc) l.list_elems in let closed, acc = f_closed l.list_closed acc in { list_elems = List.rev rev_l; list_closed = closed; }, acc let node_list_sh_map (f_elem: 'a -> 'b) (f_closed: unit node -> unit node) (node: 'a node_list) : 'b node_list = let node, () = node_list_sh_map_fold (fun x () -> f_elem x, ()) (fun x () -> f_closed x, ()) node () in node let node_list_sh_fold (f_elem: 'a -> 'b -> 'b) (f_closed: unit node -> 'b -> 'b) (node: 'a node_list) (acc: 'b) : 'b = let _, acc = node_list_sh_map_fold (fun x acc -> x, f_elem x acc) (fun x acc -> x, f_closed x acc) node acc in acc * { 8 . rule } let rule_sh_map_fold (f_evnt: cnl_event -> 'a -> cnl_event * 'a) (f_cond: cnl_cond -> 'a -> cnl_cond * 'a) (f_actns: cnl_actions -> 'a -> cnl_actions * 'a) (rule: cnl_rule) (acc: 'a) : cnl_rule * 'a = let node, acc = node_sh_map_fold (fun desc acc -> let evnt, acc = f_evnt desc.rule_evnt acc in let cond, acc = f_cond desc.rule_cond acc in let actns, acc = f_actns desc.rule_actns acc in { rule_evnt = evnt; rule_cond = cond; rule_actns = actns; }, acc) rule.rule_node acc in { rule with rule_node = node; }, acc let rule_sh_map (f_evnt: cnl_event -> cnl_event) (f_cond: cnl_cond -> cnl_cond) (f_actns: cnl_actions -> cnl_actions) (rule: cnl_rule) : cnl_rule = let rule, () = rule_sh_map_fold (fun x () -> f_evnt x, ()) (fun x () -> f_cond x, ()) (fun x () -> f_actns x, ()) rule () in rule let rule_sh_fold (f_evnt: cnl_event -> 'a -> 'a) (f_cond: cnl_cond -> 'a -> 'a) (f_actns: cnl_actions -> 'a -> 'a) (rule: cnl_rule) (acc: 'a) : 'a = let _, acc = rule_sh_map_fold (fun x acc -> x, f_evnt x acc) (fun x acc -> x, f_cond x acc) (fun x acc -> x, f_actns x acc) rule acc in acc * { 8 . event } (** This function is useless. It is present only for symetry reason. *) let evnt_sh_map_fold (f: unit -> 'a -> unit * 'a) (evnt: cnl_event) (acc: 'a) : cnl_event * 'a = evnt, acc let evnt_sh_map (f: unit -> unit) (evnt: cnl_event) : cnl_event = let evnt, () = evnt_sh_map_fold (fun x () -> f x, ()) evnt () in evnt let evnt_sh_fold (f: unit -> 'a -> 'a) (evnt: cnl_event) (acc: 'a) : 'a = let _, acc = evnt_sh_map_fold (fun x acc -> x, f x acc) evnt acc in acc * { 8 . cond } let cond_sh_map_fold (f_expr: cnl_expr -> 'a -> cnl_expr * 'a) (cond: cnl_cond) (acc: 'a) : cnl_cond * 'a = let node, acc = node_sh_map_fold (fun desc acc -> begin match desc with | C_no_condition -> C_no_condition, acc | C_condition e -> let e, acc = f_expr e acc in C_condition e, acc end) cond.cond_node acc in { cond with cond_node = node; }, acc let cond_sh_map (f_expr: cnl_expr -> cnl_expr) (cond: cnl_cond) : cnl_cond = let cond, () = cond_sh_map_fold (fun x () -> f_expr x, ()) cond () in cond let cond_sh_fold (f_expr: cnl_expr -> 'a -> 'a) (cond: cnl_cond) (acc: 'a) : 'a = let _, acc = cond_sh_map_fold (fun x acc -> x, f_expr x acc) cond acc in acc * { 8 . actions } let actns_sh_map_fold (f_actn: cnl_action -> 'a -> cnl_action * 'a) (f_closed: unit node -> 'a -> unit node * 'a) (actns: cnl_actions) (acc: 'a) : cnl_actions * 'a = let f_desc desc acc = node_list_sh_map_fold f_actn f_closed desc acc in let node, acc = node_sh_map_fold f_desc actns.actns_node acc in { actns with actns_node = node; }, acc let actns_sh_map (f_actn: cnl_action -> cnl_action) (f_closed: unit node -> unit node) (actns: cnl_actions) : cnl_actions = let actns, () = actns_sh_map_fold (fun x () -> f_actn x, ()) (fun x () -> f_closed x, ()) actns () in actns let actns_sh_fold (f_actn: cnl_action -> 'a -> 'a) (f_closed: unit node -> 'a -> 'a) (actns: cnl_actions) (acc: 'a) : 'a = let _, acc = actns_sh_map_fold (fun x acc -> x, f_actn x acc) (fun x acc -> x, f_closed x acc) actns acc in acc * { 8 . action } let actn_sh_map_fold (f_expr: cnl_expr -> 'a -> cnl_expr * 'a) (actn: cnl_action) (acc: 'a) : cnl_action * 'a = let f_desc desc acc = begin match desc with | A_print e -> let e, acc = f_expr e acc in A_print e, acc | A_emit e -> let e, acc = f_expr e acc in A_emit e, acc | A_define (x, e) -> let e, acc = f_expr e acc in A_define (x, e), acc | A_set (fld, x, e) -> let e, acc = f_expr e acc in A_set (fld, x, e), acc end in let node, acc = node_sh_map_fold f_desc actn.actn_node acc in { actn with actn_node = node }, acc let actns_sh_map (f_expr: cnl_expr -> cnl_expr) (actn: cnl_action) : cnl_action = let actn, () = actn_sh_map_fold (fun x () -> f_expr x, ()) actn () in actn let actn_sh_fold (f_expr: cnl_expr -> 'a -> 'a) (actn: cnl_action) (acc: 'a) : 'a = let _, acc = actn_sh_map_fold (fun x acc -> x, f_expr x acc) actn acc in acc * { 8 . expr } let expr_sh_map_fold (f_expr: cnl_expr -> 'a -> cnl_expr * 'a) (expr: cnl_expr) (acc: 'a) : cnl_expr * 'a = let f_desc expr_desc acc = begin match expr_desc with | E_lit x -> E_lit x, acc | E_var x -> E_var x, acc | E_get (e, x) -> let e, acc = f_expr e acc in E_get (e, x), acc | E_agg (op, e, x) -> let e, acc = f_expr e acc in E_agg (op, e, x), acc | E_unop (op, e) -> let e, acc = f_expr e acc in E_unop (op, e), acc | E_binop (op, e1, e2) -> let e1, acc = f_expr e1 acc in let e2, acc = f_expr e2 acc in E_binop (op, e1, e2), acc | E_error err -> E_error err, acc | E_this x -> E_this x, acc | E_new (x, l) -> let rev_l, acc = List.fold_left (fun (rev_l, acc) (y, e) -> let e, acc = f_expr e acc in ((y, e) :: rev_l, acc)) ([], acc) l in E_new (x, List.rev rev_l), acc end in let node, acc = node_sh_map_fold f_desc expr.expr_node acc in { expr with expr_node = node; }, acc let expr_sh_map (f_expr: cnl_expr -> cnl_expr) (expr: cnl_expr) : cnl_expr = let expr, () = expr_sh_map_fold (fun x () -> f_expr x, ()) expr () in expr let expr_sh_fold (f_expr: cnl_expr -> 'a -> 'a) (expr: cnl_expr) (acc: 'a) : 'a = let _, acc = expr_sh_map_fold (fun x acc -> x, f_expr x acc) expr acc in acc (************************) * { 6 . } (************************) * { 8 . Iterators over nodes } These iterators implements a prefix traversal of the ASTs . These iterators implements a prefix traversal of the ASTs. *) type 'acc map_fold_over_node_fun = { poly_map_fold_fun : 'a. cnl_kind -> 'a node -> 'acc -> 'a node * 'acc; rule_map_fold_fun : (cnl_rule_desc node -> 'acc -> cnl_rule_desc node * 'acc); evnt_map_fold_fun : (cnl_evnt_desc node -> 'acc -> cnl_evnt_desc node * 'acc); cond_map_fold_fun : (cnl_cond_desc node -> 'acc -> cnl_cond_desc node * 'acc); actns_map_fold_fun : (cnl_actns_desc node -> 'acc -> cnl_actns_desc node * 'acc); actn_map_fold_fun : (cnl_actn_desc node -> 'acc -> cnl_actn_desc node * 'acc); expr_map_fold_fun : (cnl_expr_desc node -> 'acc -> cnl_expr_desc node * 'acc); } type map_over_node_fun = { poly_map_fun : 'a. cnl_kind -> 'a node -> 'a node; rule_map_fun : (cnl_rule_desc node -> cnl_rule_desc node); evnt_map_fun : (cnl_evnt_desc node -> cnl_evnt_desc node); cond_map_fun : (cnl_cond_desc node -> cnl_cond_desc node); actns_map_fun : (cnl_actns_desc node -> cnl_actns_desc node); actn_map_fun : (cnl_actn_desc node -> cnl_actn_desc node); expr_map_fun : (cnl_expr_desc node -> cnl_expr_desc node); } type 'acc fold_over_node_fun = { poly_fold_fun : 'a. cnl_kind -> 'a node -> 'acc -> 'acc; rule_fold_fun : (cnl_rule_desc node -> 'acc -> 'acc); evnt_fold_fun : (cnl_evnt_desc node -> 'acc -> 'acc); cond_fold_fun : (cnl_cond_desc node -> 'acc -> 'acc); actns_fold_fun : (cnl_actns_desc node -> 'acc -> 'acc); actn_fold_fun : (cnl_actn_desc node -> 'acc -> 'acc); expr_fold_fun : (cnl_expr_desc node -> 'acc -> 'acc); } * { 8 . Default Iterators } let id_map_fold_over_node_fun = let id node acc = (node, acc) in { poly_map_fold_fun = (fun kind node acc -> (node, acc)); rule_map_fold_fun = id; evnt_map_fold_fun = id; cond_map_fold_fun = id; actns_map_fold_fun = id; actn_map_fold_fun = id; expr_map_fold_fun = id; } let id_map_over_node_fun = let id node = node in { poly_map_fun = (fun kind node -> node); rule_map_fun = id; evnt_map_fun = id; cond_map_fun = id; actns_map_fun = id; actn_map_fun = id; expr_map_fun = id; } let id_fold_over_node_fun = let id node acc = acc in { poly_fold_fun = (fun kind node acc -> acc); rule_fold_fun = id; evnt_fold_fun = id; cond_fold_fun = id; actns_fold_fun = id; actn_fold_fun = id; expr_fold_fun = id; } let map_fold_over_node_fun_of_map_over_node_fun f = { poly_map_fold_fun = (fun kind node acc -> (f.poly_map_fun kind node, acc)); rule_map_fold_fun = (fun node acc -> (f.rule_map_fun node, acc)); evnt_map_fold_fun = (fun node acc -> (f.evnt_map_fun node, acc)); cond_map_fold_fun = (fun node acc -> (f.cond_map_fun node, acc)); actns_map_fold_fun = (fun node acc -> (f.actns_map_fun node, acc)); actn_map_fold_fun = (fun node acc -> (f.actn_map_fun node, acc)); expr_map_fold_fun = (fun node acc -> (f.expr_map_fun node, acc)); } let map_fold_over_node_fun_of_fold_over_node_fun f = { poly_map_fold_fun = (fun kind node acc -> (node, f.poly_fold_fun kind node acc)); rule_map_fold_fun = (fun node acc -> (node, f.rule_fold_fun node acc)); evnt_map_fold_fun = (fun node acc -> (node, f.evnt_fold_fun node acc)); cond_map_fold_fun = (fun node acc -> (node, f.cond_fold_fun node acc)); actns_map_fold_fun = (fun node acc -> (node, f.actns_fold_fun node acc)); actn_map_fold_fun = (fun node acc -> (node, f.actn_fold_fun node acc)); expr_map_fold_fun = (fun node acc -> (node, f.expr_fold_fun node acc)); } * { 8 . Expr } let rec expr_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (expr: cnl_expr) (acc: 'a) : cnl_expr * 'a = let node, acc = f.poly_map_fold_fun (K_expr expr.expr_field) expr.expr_node acc in let node, acc = f.expr_map_fold_fun node acc in expr_sh_map_fold (fun e acc -> expr_dp_map_fold_over_nodes f e acc) { expr with expr_node = node } acc let expr_dp_map_over_nodes (f: map_over_node_fun) (expr: cnl_expr) : cnl_expr = let node, _ = expr_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) expr () in node let expr_dp_fold_over_nodes (f: 'a fold_over_node_fun) (expr: cnl_expr) (acc: 'a) : 'a = let _, acc = expr_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) expr acc in acc * { 8 . Event } let evnt_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (evnt: cnl_event) (acc: 'a) : cnl_event * 'a = let node, acc = f.poly_map_fold_fun K_evnt evnt.evnt_node acc in let node, acc = f.evnt_map_fold_fun node acc in evnt_sh_map_fold (fun () acc -> (), acc) { evnt with evnt_node = node } acc let evnt_dp_map_over_nodes (f: map_over_node_fun) (evnt: cnl_event) : cnl_event = let node, _ = evnt_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) evnt () in node let evnt_dp_fold_over_nodes (f: 'a fold_over_node_fun) (evnt: cnl_event) (acc: 'a) : 'a = let _, acc = evnt_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) evnt acc in acc * { 8 . Cond } let cond_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (cond: cnl_cond) (acc: 'a) : cnl_cond * 'a = let node, acc = f.poly_map_fold_fun K_cond cond.cond_node acc in let node, acc = f.cond_map_fold_fun node acc in cond_sh_map_fold (expr_dp_map_fold_over_nodes f) { cond with cond_node = node } acc let cond_dp_map_over_nodes (f: map_over_node_fun) (cond: cnl_cond) : cnl_cond = let node, _ = cond_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) cond () in node let cond_dp_fold_over_nodes (f: 'a fold_over_node_fun) (cond: cnl_cond) (acc: 'a) : 'a = let _, acc = cond_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) cond acc in acc * { 8 . Action } let actn_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (actn: cnl_action) (acc: 'a) : cnl_action * 'a = let node, acc = f.poly_map_fold_fun K_actn actn.actn_node acc in let node, acc = f.actn_map_fold_fun node acc in actn_sh_map_fold (expr_dp_map_fold_over_nodes f) { actn with actn_node = node } acc let actn_dp_map_over_nodes (f: map_over_node_fun) (actn: cnl_action) : cnl_action = let node, _ = actn_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) actn () in node let actn_dp_fold_over_nodes (f: 'a fold_over_node_fun) (actn: cnl_action) (acc: 'a) : 'a = let _, acc = actn_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) actn acc in acc * { 8 . Actions } let actns_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (actns: cnl_actions) (acc: 'a) : cnl_actions * 'a = let node, acc = f.poly_map_fold_fun K_actns actns.actns_node acc in let node, acc = f.actns_map_fold_fun node acc in actns_sh_map_fold (actn_dp_map_fold_over_nodes f) (f.poly_map_fold_fun K_actns_closed) { actns with actns_node = node } acc let actns_dp_map_over_nodes (f: map_over_node_fun) (actns: cnl_actions) : cnl_actions = let node, _ = actns_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) actns () in node let actns_dp_fold_over_nodes (f: 'a fold_over_node_fun) (actns: cnl_actions) (acc: 'a) : 'a = let _, acc = actns_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) actns acc in acc * { 8 . Rule } let rule_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (rule: cnl_rule) (acc: 'a) : cnl_rule * 'a = let node, acc = f.poly_map_fold_fun K_rule rule.rule_node acc in let node, acc = f.rule_map_fold_fun node acc in rule_sh_map_fold (evnt_dp_map_fold_over_nodes f) (cond_dp_map_fold_over_nodes f) (actns_dp_map_fold_over_nodes f) { rule with rule_node = node } acc let rule_dp_map_over_nodes (f: map_over_node_fun) (rule: cnl_rule) : cnl_rule = let node, _ = rule_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) rule () in node let rule_dp_fold_over_nodes (f: 'a fold_over_node_fun) (rule: cnl_rule) (acc: 'a) : 'a = let _, acc = rule_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) rule acc in acc * { 8 . CNL } let cnl_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (cnl: cnl_ast) (acc: 'a) : cnl_ast * 'a = begin match cnl with | Cnl_expr expr -> let expr, acc = expr_dp_map_fold_over_nodes f expr acc in Cnl_expr expr, acc | Cnl_actn actn -> let actn, acc = actn_dp_map_fold_over_nodes f actn acc in Cnl_actn actn, acc | Cnl_evnt evnt -> let evnt, acc = evnt_dp_map_fold_over_nodes f evnt acc in Cnl_evnt evnt, acc | Cnl_cond cond -> let cond, acc = cond_dp_map_fold_over_nodes f cond acc in Cnl_cond cond, acc | Cnl_actns actns -> let actns, acc = actns_dp_map_fold_over_nodes f actns acc in Cnl_actns actns, acc | Cnl_rule rule -> let rule, acc = rule_dp_map_fold_over_nodes f rule acc in Cnl_rule rule, acc end
null
https://raw.githubusercontent.com/IBM/wcs-ocaml/b237b7057f44caa09d36e466be015e2bc3173dd5/examples/rulebot/src/cnl2cnl.ml
ocaml
************************* ************************* * This function is useless. It is present only for symetry reason. ********************** **********************
* This file is part of the Watson Conversation Service OCaml API project . * * Copyright 2016 - 2017 IBM Corporation * * Licensed under the Apache License , Version 2.0 ( the " License " ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an " AS IS " BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . * This file is part of the Watson Conversation Service OCaml API project. * * Copyright 2016-2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) open Cnl_t * { 6 . Shallow Iterators } * { 8 . node } let node_sh_map_fold (f: 'a -> 'b -> 'c * 'b) (node: 'a node) (acc: 'b) : 'c node * 'b = begin match node with | N_undefined id -> N_undefined id, acc | N_filled (id, x) -> let x, acc = f x acc in N_filled (id, x), acc | N_rejected (id, x) -> let x, acc = f x acc in N_rejected (id, x), acc | N_accepted x -> let x, acc = f x acc in N_accepted x, acc end let node_sh_map (f: 'a -> 'b) (node: 'a node) : 'b node = let node, () = node_sh_map_fold (fun x () -> f x, ()) node () in node let node_sh_fold (f: 'a -> 'b -> 'b) (node: 'a node) (acc: 'b) : 'b = let _, acc = node_sh_map_fold (fun x acc -> x, f x acc) node acc in acc let node_list_sh_map_fold (f_elem: 'a -> 'b -> 'c * 'b) (f_closed: unit node -> 'b -> unit node * 'b) (l: 'a node_list) (acc: 'b) : 'c node_list * 'b = let rev_l, acc = List.fold_left (fun (rev_l, acc) elem -> let elem, acc = f_elem elem acc in elem::rev_l, acc) ([], acc) l.list_elems in let closed, acc = f_closed l.list_closed acc in { list_elems = List.rev rev_l; list_closed = closed; }, acc let node_list_sh_map (f_elem: 'a -> 'b) (f_closed: unit node -> unit node) (node: 'a node_list) : 'b node_list = let node, () = node_list_sh_map_fold (fun x () -> f_elem x, ()) (fun x () -> f_closed x, ()) node () in node let node_list_sh_fold (f_elem: 'a -> 'b -> 'b) (f_closed: unit node -> 'b -> 'b) (node: 'a node_list) (acc: 'b) : 'b = let _, acc = node_list_sh_map_fold (fun x acc -> x, f_elem x acc) (fun x acc -> x, f_closed x acc) node acc in acc * { 8 . rule } let rule_sh_map_fold (f_evnt: cnl_event -> 'a -> cnl_event * 'a) (f_cond: cnl_cond -> 'a -> cnl_cond * 'a) (f_actns: cnl_actions -> 'a -> cnl_actions * 'a) (rule: cnl_rule) (acc: 'a) : cnl_rule * 'a = let node, acc = node_sh_map_fold (fun desc acc -> let evnt, acc = f_evnt desc.rule_evnt acc in let cond, acc = f_cond desc.rule_cond acc in let actns, acc = f_actns desc.rule_actns acc in { rule_evnt = evnt; rule_cond = cond; rule_actns = actns; }, acc) rule.rule_node acc in { rule with rule_node = node; }, acc let rule_sh_map (f_evnt: cnl_event -> cnl_event) (f_cond: cnl_cond -> cnl_cond) (f_actns: cnl_actions -> cnl_actions) (rule: cnl_rule) : cnl_rule = let rule, () = rule_sh_map_fold (fun x () -> f_evnt x, ()) (fun x () -> f_cond x, ()) (fun x () -> f_actns x, ()) rule () in rule let rule_sh_fold (f_evnt: cnl_event -> 'a -> 'a) (f_cond: cnl_cond -> 'a -> 'a) (f_actns: cnl_actions -> 'a -> 'a) (rule: cnl_rule) (acc: 'a) : 'a = let _, acc = rule_sh_map_fold (fun x acc -> x, f_evnt x acc) (fun x acc -> x, f_cond x acc) (fun x acc -> x, f_actns x acc) rule acc in acc * { 8 . event } let evnt_sh_map_fold (f: unit -> 'a -> unit * 'a) (evnt: cnl_event) (acc: 'a) : cnl_event * 'a = evnt, acc let evnt_sh_map (f: unit -> unit) (evnt: cnl_event) : cnl_event = let evnt, () = evnt_sh_map_fold (fun x () -> f x, ()) evnt () in evnt let evnt_sh_fold (f: unit -> 'a -> 'a) (evnt: cnl_event) (acc: 'a) : 'a = let _, acc = evnt_sh_map_fold (fun x acc -> x, f x acc) evnt acc in acc * { 8 . cond } let cond_sh_map_fold (f_expr: cnl_expr -> 'a -> cnl_expr * 'a) (cond: cnl_cond) (acc: 'a) : cnl_cond * 'a = let node, acc = node_sh_map_fold (fun desc acc -> begin match desc with | C_no_condition -> C_no_condition, acc | C_condition e -> let e, acc = f_expr e acc in C_condition e, acc end) cond.cond_node acc in { cond with cond_node = node; }, acc let cond_sh_map (f_expr: cnl_expr -> cnl_expr) (cond: cnl_cond) : cnl_cond = let cond, () = cond_sh_map_fold (fun x () -> f_expr x, ()) cond () in cond let cond_sh_fold (f_expr: cnl_expr -> 'a -> 'a) (cond: cnl_cond) (acc: 'a) : 'a = let _, acc = cond_sh_map_fold (fun x acc -> x, f_expr x acc) cond acc in acc * { 8 . actions } let actns_sh_map_fold (f_actn: cnl_action -> 'a -> cnl_action * 'a) (f_closed: unit node -> 'a -> unit node * 'a) (actns: cnl_actions) (acc: 'a) : cnl_actions * 'a = let f_desc desc acc = node_list_sh_map_fold f_actn f_closed desc acc in let node, acc = node_sh_map_fold f_desc actns.actns_node acc in { actns with actns_node = node; }, acc let actns_sh_map (f_actn: cnl_action -> cnl_action) (f_closed: unit node -> unit node) (actns: cnl_actions) : cnl_actions = let actns, () = actns_sh_map_fold (fun x () -> f_actn x, ()) (fun x () -> f_closed x, ()) actns () in actns let actns_sh_fold (f_actn: cnl_action -> 'a -> 'a) (f_closed: unit node -> 'a -> 'a) (actns: cnl_actions) (acc: 'a) : 'a = let _, acc = actns_sh_map_fold (fun x acc -> x, f_actn x acc) (fun x acc -> x, f_closed x acc) actns acc in acc * { 8 . action } let actn_sh_map_fold (f_expr: cnl_expr -> 'a -> cnl_expr * 'a) (actn: cnl_action) (acc: 'a) : cnl_action * 'a = let f_desc desc acc = begin match desc with | A_print e -> let e, acc = f_expr e acc in A_print e, acc | A_emit e -> let e, acc = f_expr e acc in A_emit e, acc | A_define (x, e) -> let e, acc = f_expr e acc in A_define (x, e), acc | A_set (fld, x, e) -> let e, acc = f_expr e acc in A_set (fld, x, e), acc end in let node, acc = node_sh_map_fold f_desc actn.actn_node acc in { actn with actn_node = node }, acc let actns_sh_map (f_expr: cnl_expr -> cnl_expr) (actn: cnl_action) : cnl_action = let actn, () = actn_sh_map_fold (fun x () -> f_expr x, ()) actn () in actn let actn_sh_fold (f_expr: cnl_expr -> 'a -> 'a) (actn: cnl_action) (acc: 'a) : 'a = let _, acc = actn_sh_map_fold (fun x acc -> x, f_expr x acc) actn acc in acc * { 8 . expr } let expr_sh_map_fold (f_expr: cnl_expr -> 'a -> cnl_expr * 'a) (expr: cnl_expr) (acc: 'a) : cnl_expr * 'a = let f_desc expr_desc acc = begin match expr_desc with | E_lit x -> E_lit x, acc | E_var x -> E_var x, acc | E_get (e, x) -> let e, acc = f_expr e acc in E_get (e, x), acc | E_agg (op, e, x) -> let e, acc = f_expr e acc in E_agg (op, e, x), acc | E_unop (op, e) -> let e, acc = f_expr e acc in E_unop (op, e), acc | E_binop (op, e1, e2) -> let e1, acc = f_expr e1 acc in let e2, acc = f_expr e2 acc in E_binop (op, e1, e2), acc | E_error err -> E_error err, acc | E_this x -> E_this x, acc | E_new (x, l) -> let rev_l, acc = List.fold_left (fun (rev_l, acc) (y, e) -> let e, acc = f_expr e acc in ((y, e) :: rev_l, acc)) ([], acc) l in E_new (x, List.rev rev_l), acc end in let node, acc = node_sh_map_fold f_desc expr.expr_node acc in { expr with expr_node = node; }, acc let expr_sh_map (f_expr: cnl_expr -> cnl_expr) (expr: cnl_expr) : cnl_expr = let expr, () = expr_sh_map_fold (fun x () -> f_expr x, ()) expr () in expr let expr_sh_fold (f_expr: cnl_expr -> 'a -> 'a) (expr: cnl_expr) (acc: 'a) : 'a = let _, acc = expr_sh_map_fold (fun x acc -> x, f_expr x acc) expr acc in acc * { 6 . } * { 8 . Iterators over nodes } These iterators implements a prefix traversal of the ASTs . These iterators implements a prefix traversal of the ASTs. *) type 'acc map_fold_over_node_fun = { poly_map_fold_fun : 'a. cnl_kind -> 'a node -> 'acc -> 'a node * 'acc; rule_map_fold_fun : (cnl_rule_desc node -> 'acc -> cnl_rule_desc node * 'acc); evnt_map_fold_fun : (cnl_evnt_desc node -> 'acc -> cnl_evnt_desc node * 'acc); cond_map_fold_fun : (cnl_cond_desc node -> 'acc -> cnl_cond_desc node * 'acc); actns_map_fold_fun : (cnl_actns_desc node -> 'acc -> cnl_actns_desc node * 'acc); actn_map_fold_fun : (cnl_actn_desc node -> 'acc -> cnl_actn_desc node * 'acc); expr_map_fold_fun : (cnl_expr_desc node -> 'acc -> cnl_expr_desc node * 'acc); } type map_over_node_fun = { poly_map_fun : 'a. cnl_kind -> 'a node -> 'a node; rule_map_fun : (cnl_rule_desc node -> cnl_rule_desc node); evnt_map_fun : (cnl_evnt_desc node -> cnl_evnt_desc node); cond_map_fun : (cnl_cond_desc node -> cnl_cond_desc node); actns_map_fun : (cnl_actns_desc node -> cnl_actns_desc node); actn_map_fun : (cnl_actn_desc node -> cnl_actn_desc node); expr_map_fun : (cnl_expr_desc node -> cnl_expr_desc node); } type 'acc fold_over_node_fun = { poly_fold_fun : 'a. cnl_kind -> 'a node -> 'acc -> 'acc; rule_fold_fun : (cnl_rule_desc node -> 'acc -> 'acc); evnt_fold_fun : (cnl_evnt_desc node -> 'acc -> 'acc); cond_fold_fun : (cnl_cond_desc node -> 'acc -> 'acc); actns_fold_fun : (cnl_actns_desc node -> 'acc -> 'acc); actn_fold_fun : (cnl_actn_desc node -> 'acc -> 'acc); expr_fold_fun : (cnl_expr_desc node -> 'acc -> 'acc); } * { 8 . Default Iterators } let id_map_fold_over_node_fun = let id node acc = (node, acc) in { poly_map_fold_fun = (fun kind node acc -> (node, acc)); rule_map_fold_fun = id; evnt_map_fold_fun = id; cond_map_fold_fun = id; actns_map_fold_fun = id; actn_map_fold_fun = id; expr_map_fold_fun = id; } let id_map_over_node_fun = let id node = node in { poly_map_fun = (fun kind node -> node); rule_map_fun = id; evnt_map_fun = id; cond_map_fun = id; actns_map_fun = id; actn_map_fun = id; expr_map_fun = id; } let id_fold_over_node_fun = let id node acc = acc in { poly_fold_fun = (fun kind node acc -> acc); rule_fold_fun = id; evnt_fold_fun = id; cond_fold_fun = id; actns_fold_fun = id; actn_fold_fun = id; expr_fold_fun = id; } let map_fold_over_node_fun_of_map_over_node_fun f = { poly_map_fold_fun = (fun kind node acc -> (f.poly_map_fun kind node, acc)); rule_map_fold_fun = (fun node acc -> (f.rule_map_fun node, acc)); evnt_map_fold_fun = (fun node acc -> (f.evnt_map_fun node, acc)); cond_map_fold_fun = (fun node acc -> (f.cond_map_fun node, acc)); actns_map_fold_fun = (fun node acc -> (f.actns_map_fun node, acc)); actn_map_fold_fun = (fun node acc -> (f.actn_map_fun node, acc)); expr_map_fold_fun = (fun node acc -> (f.expr_map_fun node, acc)); } let map_fold_over_node_fun_of_fold_over_node_fun f = { poly_map_fold_fun = (fun kind node acc -> (node, f.poly_fold_fun kind node acc)); rule_map_fold_fun = (fun node acc -> (node, f.rule_fold_fun node acc)); evnt_map_fold_fun = (fun node acc -> (node, f.evnt_fold_fun node acc)); cond_map_fold_fun = (fun node acc -> (node, f.cond_fold_fun node acc)); actns_map_fold_fun = (fun node acc -> (node, f.actns_fold_fun node acc)); actn_map_fold_fun = (fun node acc -> (node, f.actn_fold_fun node acc)); expr_map_fold_fun = (fun node acc -> (node, f.expr_fold_fun node acc)); } * { 8 . Expr } let rec expr_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (expr: cnl_expr) (acc: 'a) : cnl_expr * 'a = let node, acc = f.poly_map_fold_fun (K_expr expr.expr_field) expr.expr_node acc in let node, acc = f.expr_map_fold_fun node acc in expr_sh_map_fold (fun e acc -> expr_dp_map_fold_over_nodes f e acc) { expr with expr_node = node } acc let expr_dp_map_over_nodes (f: map_over_node_fun) (expr: cnl_expr) : cnl_expr = let node, _ = expr_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) expr () in node let expr_dp_fold_over_nodes (f: 'a fold_over_node_fun) (expr: cnl_expr) (acc: 'a) : 'a = let _, acc = expr_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) expr acc in acc * { 8 . Event } let evnt_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (evnt: cnl_event) (acc: 'a) : cnl_event * 'a = let node, acc = f.poly_map_fold_fun K_evnt evnt.evnt_node acc in let node, acc = f.evnt_map_fold_fun node acc in evnt_sh_map_fold (fun () acc -> (), acc) { evnt with evnt_node = node } acc let evnt_dp_map_over_nodes (f: map_over_node_fun) (evnt: cnl_event) : cnl_event = let node, _ = evnt_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) evnt () in node let evnt_dp_fold_over_nodes (f: 'a fold_over_node_fun) (evnt: cnl_event) (acc: 'a) : 'a = let _, acc = evnt_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) evnt acc in acc * { 8 . Cond } let cond_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (cond: cnl_cond) (acc: 'a) : cnl_cond * 'a = let node, acc = f.poly_map_fold_fun K_cond cond.cond_node acc in let node, acc = f.cond_map_fold_fun node acc in cond_sh_map_fold (expr_dp_map_fold_over_nodes f) { cond with cond_node = node } acc let cond_dp_map_over_nodes (f: map_over_node_fun) (cond: cnl_cond) : cnl_cond = let node, _ = cond_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) cond () in node let cond_dp_fold_over_nodes (f: 'a fold_over_node_fun) (cond: cnl_cond) (acc: 'a) : 'a = let _, acc = cond_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) cond acc in acc * { 8 . Action } let actn_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (actn: cnl_action) (acc: 'a) : cnl_action * 'a = let node, acc = f.poly_map_fold_fun K_actn actn.actn_node acc in let node, acc = f.actn_map_fold_fun node acc in actn_sh_map_fold (expr_dp_map_fold_over_nodes f) { actn with actn_node = node } acc let actn_dp_map_over_nodes (f: map_over_node_fun) (actn: cnl_action) : cnl_action = let node, _ = actn_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) actn () in node let actn_dp_fold_over_nodes (f: 'a fold_over_node_fun) (actn: cnl_action) (acc: 'a) : 'a = let _, acc = actn_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) actn acc in acc * { 8 . Actions } let actns_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (actns: cnl_actions) (acc: 'a) : cnl_actions * 'a = let node, acc = f.poly_map_fold_fun K_actns actns.actns_node acc in let node, acc = f.actns_map_fold_fun node acc in actns_sh_map_fold (actn_dp_map_fold_over_nodes f) (f.poly_map_fold_fun K_actns_closed) { actns with actns_node = node } acc let actns_dp_map_over_nodes (f: map_over_node_fun) (actns: cnl_actions) : cnl_actions = let node, _ = actns_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) actns () in node let actns_dp_fold_over_nodes (f: 'a fold_over_node_fun) (actns: cnl_actions) (acc: 'a) : 'a = let _, acc = actns_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) actns acc in acc * { 8 . Rule } let rule_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (rule: cnl_rule) (acc: 'a) : cnl_rule * 'a = let node, acc = f.poly_map_fold_fun K_rule rule.rule_node acc in let node, acc = f.rule_map_fold_fun node acc in rule_sh_map_fold (evnt_dp_map_fold_over_nodes f) (cond_dp_map_fold_over_nodes f) (actns_dp_map_fold_over_nodes f) { rule with rule_node = node } acc let rule_dp_map_over_nodes (f: map_over_node_fun) (rule: cnl_rule) : cnl_rule = let node, _ = rule_dp_map_fold_over_nodes (map_fold_over_node_fun_of_map_over_node_fun f) rule () in node let rule_dp_fold_over_nodes (f: 'a fold_over_node_fun) (rule: cnl_rule) (acc: 'a) : 'a = let _, acc = rule_dp_map_fold_over_nodes (map_fold_over_node_fun_of_fold_over_node_fun f) rule acc in acc * { 8 . CNL } let cnl_dp_map_fold_over_nodes (f: 'a map_fold_over_node_fun) (cnl: cnl_ast) (acc: 'a) : cnl_ast * 'a = begin match cnl with | Cnl_expr expr -> let expr, acc = expr_dp_map_fold_over_nodes f expr acc in Cnl_expr expr, acc | Cnl_actn actn -> let actn, acc = actn_dp_map_fold_over_nodes f actn acc in Cnl_actn actn, acc | Cnl_evnt evnt -> let evnt, acc = evnt_dp_map_fold_over_nodes f evnt acc in Cnl_evnt evnt, acc | Cnl_cond cond -> let cond, acc = cond_dp_map_fold_over_nodes f cond acc in Cnl_cond cond, acc | Cnl_actns actns -> let actns, acc = actns_dp_map_fold_over_nodes f actns acc in Cnl_actns actns, acc | Cnl_rule rule -> let rule, acc = rule_dp_map_fold_over_nodes f rule acc in Cnl_rule rule, acc end
005eae901f018421b7b870d55f4b3baf6b04904a0cc31e5311d3c3d7d72c4b4b
nojb/llvm-min-caml
globals.ml
open MiniMLRuntime;; * * * * * * * * * * * * * * * グローバル変数の宣言 * * * * * * * * * * * * * * * (* オブジェクトのデータを入れるベクトル(最大60個)*) let objects = let dummy = Array.create 0 0.0 in Array.create (60) (0, 0, 0, 0, dummy, dummy, false, dummy, dummy, dummy) [ | x軸の走査線本数 , y軸の走査線本数 | ] let size = Array.create 2 128 (* 実行時オプション: デバッグ出力の有無 *) let dbg = Array.create 1 true (* Screen の座標 *) let screen = Array.create 3 0.0 (* 視点の座標 (offset なし) *) let vp = Array.create 3 0.0 (* 視点の座標 (screen 位置分の offset あり) *) let view = Array.create 3 0.0 光源方向ベクトル ( ) let light = Array.create 3 0.0 スクリーンの回転方向 : let cos_v = Array.create 2 0.0 let sin_v = Array.create 2 0.0 (* 鏡面ハイライト強度 (標準=255) *) let beam = Array.create 1 255.0 (* AND ネットワークを保持 *) let and_net = Array.create 50 (Array.create 1 (-1)) (* OR ネットワークを保持 *) let or_net = Array.create 1 (Array.create 1 (and_net.(0))) (* reader *) let temp = Array.create 14 0.0 (* read_nth_object 内の作業変数 *) let cs_temp = Array.create 16 0.0 (* solver *) * * * との通信用グローバル変数 * * * (* 交点 の t の値 *) let solver_dist = Array.create 1 0.0 (* スキャンの方向 *) let vscan = Array.create 3 0.0 (* 交点の直方体表面での方向 *) let intsec_rectside = Array.create 1 0 (* 発見した交点の最小の t *) let tmin = Array.create 1 (1000000000.0) (* 交点の座標 *) let crashed_point = Array.create 3 0.0 (* 衝突したオブジェクト *) let crashed_object = Array.create 1 0 (* 1つの AND ネットワークについての終了フラグ *) let end_flag = Array.create 1 false (* トレース開始点 *) let viewpoint = Array.create 3 0.0 (* 法線ベクトル *) let nvector = Array.create 3 0.0 スクリーン上の点の明るさ let rgb = Array.create 3 0.0 (* 交点の色 *) let texture_color = Array.create 3 0.0 (* オブジェクト中心を原点にした視点ベクトル *) let solver_w_vec = Array.create 3 0.0 (* check_all_inside 用引数ベクトル *) let chkinside_p = Array.create 3 0.0 (* is_outside 用内部利用 (中心差分) ベクトル *) let isoutside_q = Array.create 3 0.0 (* グローバルに切り出したローカル変数 *) (* nvector *) let nvector_w = Array.create 3 0.0 (* main *) let scan_d = Array.create 1 0.0 let scan_offset = Array.create 1 0.0 let scan_sscany = Array.create 1 0.0 let scan_met1 = Array.create 1 0.0 let wscan = Array.create 3 0.0
null
https://raw.githubusercontent.com/nojb/llvm-min-caml/68703b905f8292cb2e20b41bbd90cfea85ca2a19/min-rt/globals.ml
ocaml
オブジェクトのデータを入れるベクトル(最大60個) 実行時オプション: デバッグ出力の有無 Screen の座標 視点の座標 (offset なし) 視点の座標 (screen 位置分の offset あり) 鏡面ハイライト強度 (標準=255) AND ネットワークを保持 OR ネットワークを保持 reader read_nth_object 内の作業変数 solver 交点 の t の値 スキャンの方向 交点の直方体表面での方向 発見した交点の最小の t 交点の座標 衝突したオブジェクト 1つの AND ネットワークについての終了フラグ トレース開始点 法線ベクトル 交点の色 オブジェクト中心を原点にした視点ベクトル check_all_inside 用引数ベクトル is_outside 用内部利用 (中心差分) ベクトル グローバルに切り出したローカル変数 nvector main
open MiniMLRuntime;; * * * * * * * * * * * * * * * グローバル変数の宣言 * * * * * * * * * * * * * * * let objects = let dummy = Array.create 0 0.0 in Array.create (60) (0, 0, 0, 0, dummy, dummy, false, dummy, dummy, dummy) [ | x軸の走査線本数 , y軸の走査線本数 | ] let size = Array.create 2 128 let dbg = Array.create 1 true let screen = Array.create 3 0.0 let vp = Array.create 3 0.0 let view = Array.create 3 0.0 光源方向ベクトル ( ) let light = Array.create 3 0.0 スクリーンの回転方向 : let cos_v = Array.create 2 0.0 let sin_v = Array.create 2 0.0 let beam = Array.create 1 255.0 let and_net = Array.create 50 (Array.create 1 (-1)) let or_net = Array.create 1 (Array.create 1 (and_net.(0))) let cs_temp = Array.create 16 0.0 * * * との通信用グローバル変数 * * * let solver_dist = Array.create 1 0.0 let vscan = Array.create 3 0.0 let intsec_rectside = Array.create 1 0 let tmin = Array.create 1 (1000000000.0) let crashed_point = Array.create 3 0.0 let crashed_object = Array.create 1 0 let end_flag = Array.create 1 false let viewpoint = Array.create 3 0.0 let nvector = Array.create 3 0.0 スクリーン上の点の明るさ let rgb = Array.create 3 0.0 let texture_color = Array.create 3 0.0 let solver_w_vec = Array.create 3 0.0 let chkinside_p = Array.create 3 0.0 let isoutside_q = Array.create 3 0.0 let nvector_w = Array.create 3 0.0 let scan_d = Array.create 1 0.0 let scan_offset = Array.create 1 0.0 let scan_sscany = Array.create 1 0.0 let scan_met1 = Array.create 1 0.0 let wscan = Array.create 3 0.0
0e9f9c05f50466004864cd866b7db8a1385759248da47cb6e24f9f773a5ce75c
paurkedal/batyr
log.ml
Copyright ( C ) 2022 < > * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. *) let src = Logs.Src.create "rockettime" include (val Logs_lwt.src_log src) module Wire = struct let src = Logs.Src.create "rockettime.wire" include (val Logs_lwt.src_log src) end
null
https://raw.githubusercontent.com/paurkedal/batyr/ca1d9b53d1d7328003eaa21037469281e250135d/rockettime/lib/log.ml
ocaml
Copyright ( C ) 2022 < > * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. *) let src = Logs.Src.create "rockettime" include (val Logs_lwt.src_log src) module Wire = struct let src = Logs.Src.create "rockettime.wire" include (val Logs_lwt.src_log src) end
eaa0c25f37aa41f814b90386f61a17fa9113a81a13f630c58575e10c736cdcdc
hexlet-codebattle/battle_asserts
complex_number_mul.clj
(ns battle-asserts.issues.complex-number-mul (:require [clojure.test.check.generators :as gen])) (def level :medium) (def tags ["math"]) (def description {:en "Implement a function that multiply two complex numbers. Return result as array where first number is real part and second number is imaginary part." :ru "Создайте функцию, которая умножает два комплексных числа. Верните результат как массив, где первое число - реальная часть, а вторая - мнимая."}) (def signature {:input [{:argument-name "first" :type {:name "array" :nested {:name "integer"}}} {:argument-name "second" :type {:name "array" :nested {:name "integer"}}}] :output {:type {:name "array" :nested {:name "integer"}}}}) (defn arguments-generator [] (gen/tuple (gen/tuple gen/small-integer gen/small-integer) (gen/tuple gen/small-integer gen/small-integer))) (def test-data [{:expected [1 -7] :arguments [[1 -2] [3 -1]]} {:expected [-8 1] :arguments [[-3 2] [2 1]]} {:expected [4 7] :arguments [[3 2] [2 1]]} {:expected [-5 -1] :arguments [[2 3] [-1 1]]}]) (defn solution [[real1 img1] [real2 img2]] (letfn [(real-part [first-pair second-pair] (- (* (first first-pair) (first second-pair)) (* (last first-pair) (last second-pair)))) (imaginary-part [first-pair second-pair] (+ (* (first first-pair) (last second-pair)) (* (last first-pair) (first second-pair))))] [(real-part [real1 img1] [real2 img2]) (imaginary-part [real1 img1] [real2 img2])]))
null
https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/dc5ed5ebae4b38d6251abda3da23590cbfa5af5f/src/battle_asserts/issues/complex_number_mul.clj
clojure
(ns battle-asserts.issues.complex-number-mul (:require [clojure.test.check.generators :as gen])) (def level :medium) (def tags ["math"]) (def description {:en "Implement a function that multiply two complex numbers. Return result as array where first number is real part and second number is imaginary part." :ru "Создайте функцию, которая умножает два комплексных числа. Верните результат как массив, где первое число - реальная часть, а вторая - мнимая."}) (def signature {:input [{:argument-name "first" :type {:name "array" :nested {:name "integer"}}} {:argument-name "second" :type {:name "array" :nested {:name "integer"}}}] :output {:type {:name "array" :nested {:name "integer"}}}}) (defn arguments-generator [] (gen/tuple (gen/tuple gen/small-integer gen/small-integer) (gen/tuple gen/small-integer gen/small-integer))) (def test-data [{:expected [1 -7] :arguments [[1 -2] [3 -1]]} {:expected [-8 1] :arguments [[-3 2] [2 1]]} {:expected [4 7] :arguments [[3 2] [2 1]]} {:expected [-5 -1] :arguments [[2 3] [-1 1]]}]) (defn solution [[real1 img1] [real2 img2]] (letfn [(real-part [first-pair second-pair] (- (* (first first-pair) (first second-pair)) (* (last first-pair) (last second-pair)))) (imaginary-part [first-pair second-pair] (+ (* (first first-pair) (last second-pair)) (* (last first-pair) (first second-pair))))] [(real-part [real1 img1] [real2 img2]) (imaginary-part [real1 img1] [real2 img2])]))
e0f266984c52f5fc15dd2b7fbff1647ddfd383fc2c5aba134e9c2a3730c04114
dannywillems/RML
grammarToolbox.mli
val ba_raw_term : Grammar.nominal_term -> string list val fa_raw_term : Grammar.nominal_term -> string list val string_of_term_for_fresh_variable : Grammar.raw_term -> string val is_raw_variable : Grammar.raw_term -> bool val extract_variable : Grammar.raw_term -> string option
null
https://raw.githubusercontent.com/dannywillems/RML/6f34748a4ea0b44037519d67200850acf6067481/src/grammar/grammarToolbox.mli
ocaml
val ba_raw_term : Grammar.nominal_term -> string list val fa_raw_term : Grammar.nominal_term -> string list val string_of_term_for_fresh_variable : Grammar.raw_term -> string val is_raw_variable : Grammar.raw_term -> bool val extract_variable : Grammar.raw_term -> string option
bb85cc83b0572195a8b1ea4493fc51810e4e425821962c841470fd28ff64f7b0
glguy/advent2021
Format.hs
# Language BlockArguments , TemplateHaskell # | Module : Advent . Format Description : Input file format quasiquoter Copyright : ( c ) , 2018 - 2021 License : ISC Maintainer : Usage : @[format|<day > < format string>|]@ When day is specified as @0@ the quasiquoter returns a pure parser function . Otherwise day uses command line arguments to find the input file and parses it as an IO action . A format string can optionally be specified across multiple lines . In this case the day number goes on the first line and the pattern starts on the second line . All common leading white space from all the remaining lines is trimmed off and newlines are discarded ( use @%n@ for matching newlines ) The following are identical : @ example1 = [ format|1 % s%n % s%n| ] example2 = [ format|1 % s%n%s%n| ] @ Patterns : * @%u@ unsigned integer as ' Int ' * @%d@ signed integer as ' Int ' * @%lu@ unsigned integer as ' Integer ' * @%ld@ signed integer as ' Integer ' * @%s@ non - empty list of non - space characters as ' String ' * @%c@ single , non - newline character as ' ' * @%a@ single ASCII letter as ' ' * @%n@ single newline character * other characters match literally * use @%@ to escape literal matches of special characters * @\@A@ matches the names of the constructors of type @A@ as an @A@ Structures : * @p|q@ combine alternatives @p@ and @q@ * @(pq)@ group subpattern @pq@ * @p*@ zero - to - many repititions of @p@ as a ' [ ] ' * @p+@ one - to - many repititions of @p@ as a ' [ ] ' * @p&q@ zero - to - many repititions of @p@ separated by @q@ as a ' [ ] ' * @p!@ returns the characters that matched pattern @p@ as a ' String ' Module : Advent.Format Description : Input file format quasiquoter Copyright : (c) Eric Mertens, 2018-2021 License : ISC Maintainer : Usage: @[format|<day> <format string>|]@ When day is specified as @0@ the quasiquoter returns a pure parser function. Otherwise day uses command line arguments to find the input file and parses it as an IO action. A format string can optionally be specified across multiple lines. In this case the day number goes on the first line and the pattern starts on the second line. All common leading white space from all the remaining lines is trimmed off and newlines are discarded (use @%n@ for matching newlines) The following are identical: @ example1 = [format|1 %s%n %s%n|] example2 = [format|1 %s%n%s%n|] @ Patterns: * @%u@ unsigned integer as 'Int' * @%d@ signed integer as 'Int' * @%lu@ unsigned integer as 'Integer' * @%ld@ signed integer as 'Integer' * @%s@ non-empty list of non-space characters as 'String' * @%c@ single, non-newline character as 'Char' * @%a@ single ASCII letter as 'Char' * @%n@ single newline character * other characters match literally * use @%@ to escape literal matches of special characters * @\@A@ matches the names of the constructors of type @A@ as an @A@ Structures: * @p|q@ combine alternatives @p@ and @q@ * @(pq)@ group subpattern @pq@ * @p*@ zero-to-many repititions of @p@ as a '[]' * @p+@ one-to-many repititions of @p@ as a '[]' * @p&q@ zero-to-many repititions of @p@ separated by @q@ as a '[]' * @p!@ returns the characters that matched pattern @p@ as a 'String' -} module Advent.Format (format) where import Advent.Prelude (countBy) import Advent.Input (getRawInput) import Advent.Format.Lexer ( alexScanTokens, AlexPosn(..) ) import Advent.Format.Parser (parseFormat, ParseError(..) ) import Advent.Format.Types ( interesting, Format(..), acceptsEmpty, showFormat, showToken ) import Control.Applicative ((<|>), some) import Control.Monad ( (<=<) ) import Data.Char ( isDigit, isSpace, isUpper ) import Data.Maybe ( listToMaybe ) import Data.Traversable ( for ) import Data.List (stripPrefix) import Language.Haskell.TH import Language.Haskell.TH.Quote ( QuasiQuoter(..) ) import Text.ParserCombinators.ReadP import Text.Read (readMaybe) parse :: String -> Q Format parse txt = case parseFormat (alexScanTokens txt) of Right fmt -> pure fmt Left (Unclosed p) -> failAt p "Unclosed parenthesis" Left (UnexpectedToken p t) -> failAt p ("Unexpected token " ++ showToken t) Left UnexpectedEOF -> fail "Format parse error, unexpected end-of-input" failAt :: AlexPosn -> String -> Q a failAt (AlexPn _ line col) msg = fail ("Format parse error at " ++ show line ++ ":" ++ show col ++ ", " ++ msg) -- | Constructs an input parser. See "Advent.Format" format :: QuasiQuoter format = QuasiQuoter { quoteExp = uncurry makeParser <=< prepare , quotePat = \_ -> fail "format: patterns not supported" , quoteType = toType <=< parse . snd <=< prepare , quoteDec = \_ -> fail "format: declarations not supported" } prepare :: String -> Q (Int,String) prepare str = case lines str of [] -> fail "Empty input format" [x] -> case reads x of [(n,rest)] -> pure (n, dropWhile (' '==) rest) _ -> fail "Failed to parse single-line input pattern" x:xs -> do n <- case readMaybe x of Nothing -> fail "Failed to parse format day number" Just n -> pure n pure (n, concatMap (drop indent) xs1) where xs1 = filter (any (' ' /=)) xs indent = minimum (map (length . takeWhile (' '==)) xs1) makeParser :: Int -> String -> ExpQ makeParser n str = do fmt <- parse str let formats = [| readP_to_S ($(toReadP fmt) <* eof) |] let qf = [| maybe (error "bad input parse") fst . listToMaybe . $formats |] if n == 0 then qf else [| $qf <$> getRawInput n |] toReadP :: Format -> ExpQ toReadP s = case s of Literal xs -> [| () <$ string xs |] Gather p -> [| fst <$> gather $(toReadP p) |] Named n | isUpper (head n) -> enumParser n | otherwise -> varE (mkName n) UnsignedInteger -> [| (read :: String -> Integer) <$> munch1 isDigit |] SignedInteger -> [| (read :: String -> Integer) <$> ((++) <$> option "" (string "-") <*> munch1 isDigit) |] UnsignedInt -> [| (read :: String -> Int ) <$> munch1 isDigit |] SignedInt -> [| (read :: String -> Int ) <$> ((++) <$> option "" (string "-") <*> munch1 isDigit) |] Char -> [| satisfy ('\n' /=) |] Letter -> [| satisfy (\x -> 'a' <= x && x <= 'z' || 'A' <= x && x <= 'Z') |] Word -> [| some (satisfy (not . isSpace)) |] Many x | acceptsEmpty x -> fail ("Argument to * accepts ε: " ++ showFormat 0 s "") | interesting x -> [| many $(toReadP x) |] | otherwise -> [| () <$ many $(toReadP x) |] Some x | acceptsEmpty x -> fail ("Argument to + accepts ε: " ++ showFormat 0 s "") | interesting x -> [| some $(toReadP x) |] | otherwise -> [| () <$ some $(toReadP x) |] SepBy x y | acceptsEmpty x, acceptsEmpty y -> fail ("Both arguments to & accept ε: " ++ showFormat 0 s "") | interesting x -> [| sepBy $(toReadP x) $(toReadP y) |] | otherwise -> [| () <$ sepBy $(toReadP x) $(toReadP y) |] Alt x y | xi, yi -> [| Left <$> $xp <|> Right <$> $yp |] | xi -> [| Just <$> $xp <|> Nothing <$ $yp |] | yi -> [| Nothing <$ $xp <|> Just <$> $yp |] | otherwise -> [| $xp <|> $yp |] where xi = interesting x yi = interesting y xp = toReadP x yp = toReadP y _ -> case [(interesting x, toReadP x) | x <- follows s []] of [] -> [| pure () |] xxs@((ix,x):xs) | n == 0 -> foldl apply0 x xs | n <= 1 -> foldl apply1 x xs | ix -> foldl applyN [| $tup <$> $x |] xs | otherwise -> foldl applyN [| $tup <$ $x |] xs where tup = conE (tupleDataName n) n = countBy fst xxs apply0 l (_,r) = [| $l *> $r |] apply1 l (i,r) = if i then [| $l *> $r |] else [| $l <* $r |] applyN l (i,r) = if i then [| $l <*> $r |] else [| $l <* $r |] toType :: Format -> TypeQ toType fmt = case fmt of Literal _ -> [t| () |] Gather _ -> [t| String |] Named n | isUpper (head n) -> conT (mkName n) | otherwise -> fail "toType: not implemented for variable yet" UnsignedInteger -> [t| Integer |] SignedInteger -> [t| Integer |] UnsignedInt -> [t| Int |] SignedInt -> [t| Int |] Char -> [t| Char |] Letter -> [t| Char |] Word -> [t| String |] Many x | acceptsEmpty x -> fail ("Argument to * accepts ε: " ++ showFormat 0 fmt "") | interesting x -> [t| [$(toType x)] |] | otherwise -> [t| () |] Some x | acceptsEmpty x -> fail ("Argument to + accepts ε: " ++ showFormat 0 fmt "") | interesting x -> [t| [$(toType x)] |] | otherwise -> [t| () |] SepBy x y | acceptsEmpty x, acceptsEmpty y -> fail ("Both arguments to & accept ε: " ++ showFormat 0 fmt "") | interesting x -> [t| [$(toType x)] |] | otherwise -> [t| () |] Alt x y | xi, yi -> [t| Either $xt $yt |] | xi -> [t| Maybe $xt |] | yi -> [t| Maybe $yt |] | otherwise -> [t| () |] where xi = interesting x yi = interesting y xt = toType x yt = toType y _ -> case [toType x | x <- follows fmt [], interesting x] of [] -> [t| () |] [t] -> t ts -> foldl appT (tupleT (length ts)) ts -- | Prefix a list of format strings with a format string. -- If the given list has all the topmost 'Follow' constructors -- removed, the output list will as well. Any consecutive literals found -- while flattening will be combined. follows :: Format -> [Format] -> [Format] follows (Follow x y) zs = follows x (follows y zs) follows Empty zs = zs follows (Literal x) (Literal y : zs) = follows (Literal (x ++ y)) zs follows x zs = x : zs enumParser :: String -> ExpQ enumParser nameStr = do tyName <- maybe (fail ("Failed to find type named " ++ show nameStr)) pure =<< lookupTypeName nameStr info <- reify tyName cons <- case info of TyConI (DataD _ _ _ _ cons _) -> pure cons _ -> fail ("Failed to find data declaration for " ++ show nameStr) entries <- for cons \con -> case con of NormalC name [] | Just str <- stripPrefix nameStr (nameBase name) -> pure (name, str) _ -> fail ("Unsupported constructor: " ++ show con) let parsers = [[| $(conE name) <$ string str |] | (name, str) <- entries] [| choice $(listE parsers) |]
null
https://raw.githubusercontent.com/glguy/advent2021/faf0ed1f684199c2e97cef9489256cea201babee/common/Advent/Format.hs
haskell
| Constructs an input parser. See "Advent.Format" | Prefix a list of format strings with a format string. If the given list has all the topmost 'Follow' constructors removed, the output list will as well. Any consecutive literals found while flattening will be combined.
# Language BlockArguments , TemplateHaskell # | Module : Advent . Format Description : Input file format quasiquoter Copyright : ( c ) , 2018 - 2021 License : ISC Maintainer : Usage : @[format|<day > < format string>|]@ When day is specified as @0@ the quasiquoter returns a pure parser function . Otherwise day uses command line arguments to find the input file and parses it as an IO action . A format string can optionally be specified across multiple lines . In this case the day number goes on the first line and the pattern starts on the second line . All common leading white space from all the remaining lines is trimmed off and newlines are discarded ( use @%n@ for matching newlines ) The following are identical : @ example1 = [ format|1 % s%n % s%n| ] example2 = [ format|1 % s%n%s%n| ] @ Patterns : * @%u@ unsigned integer as ' Int ' * @%d@ signed integer as ' Int ' * @%lu@ unsigned integer as ' Integer ' * @%ld@ signed integer as ' Integer ' * @%s@ non - empty list of non - space characters as ' String ' * @%c@ single , non - newline character as ' ' * @%a@ single ASCII letter as ' ' * @%n@ single newline character * other characters match literally * use @%@ to escape literal matches of special characters * @\@A@ matches the names of the constructors of type @A@ as an @A@ Structures : * @p|q@ combine alternatives @p@ and @q@ * @(pq)@ group subpattern @pq@ * @p*@ zero - to - many repititions of @p@ as a ' [ ] ' * @p+@ one - to - many repititions of @p@ as a ' [ ] ' * @p&q@ zero - to - many repititions of @p@ separated by @q@ as a ' [ ] ' * @p!@ returns the characters that matched pattern @p@ as a ' String ' Module : Advent.Format Description : Input file format quasiquoter Copyright : (c) Eric Mertens, 2018-2021 License : ISC Maintainer : Usage: @[format|<day> <format string>|]@ When day is specified as @0@ the quasiquoter returns a pure parser function. Otherwise day uses command line arguments to find the input file and parses it as an IO action. A format string can optionally be specified across multiple lines. In this case the day number goes on the first line and the pattern starts on the second line. All common leading white space from all the remaining lines is trimmed off and newlines are discarded (use @%n@ for matching newlines) The following are identical: @ example1 = [format|1 %s%n %s%n|] example2 = [format|1 %s%n%s%n|] @ Patterns: * @%u@ unsigned integer as 'Int' * @%d@ signed integer as 'Int' * @%lu@ unsigned integer as 'Integer' * @%ld@ signed integer as 'Integer' * @%s@ non-empty list of non-space characters as 'String' * @%c@ single, non-newline character as 'Char' * @%a@ single ASCII letter as 'Char' * @%n@ single newline character * other characters match literally * use @%@ to escape literal matches of special characters * @\@A@ matches the names of the constructors of type @A@ as an @A@ Structures: * @p|q@ combine alternatives @p@ and @q@ * @(pq)@ group subpattern @pq@ * @p*@ zero-to-many repititions of @p@ as a '[]' * @p+@ one-to-many repititions of @p@ as a '[]' * @p&q@ zero-to-many repititions of @p@ separated by @q@ as a '[]' * @p!@ returns the characters that matched pattern @p@ as a 'String' -} module Advent.Format (format) where import Advent.Prelude (countBy) import Advent.Input (getRawInput) import Advent.Format.Lexer ( alexScanTokens, AlexPosn(..) ) import Advent.Format.Parser (parseFormat, ParseError(..) ) import Advent.Format.Types ( interesting, Format(..), acceptsEmpty, showFormat, showToken ) import Control.Applicative ((<|>), some) import Control.Monad ( (<=<) ) import Data.Char ( isDigit, isSpace, isUpper ) import Data.Maybe ( listToMaybe ) import Data.Traversable ( for ) import Data.List (stripPrefix) import Language.Haskell.TH import Language.Haskell.TH.Quote ( QuasiQuoter(..) ) import Text.ParserCombinators.ReadP import Text.Read (readMaybe) parse :: String -> Q Format parse txt = case parseFormat (alexScanTokens txt) of Right fmt -> pure fmt Left (Unclosed p) -> failAt p "Unclosed parenthesis" Left (UnexpectedToken p t) -> failAt p ("Unexpected token " ++ showToken t) Left UnexpectedEOF -> fail "Format parse error, unexpected end-of-input" failAt :: AlexPosn -> String -> Q a failAt (AlexPn _ line col) msg = fail ("Format parse error at " ++ show line ++ ":" ++ show col ++ ", " ++ msg) format :: QuasiQuoter format = QuasiQuoter { quoteExp = uncurry makeParser <=< prepare , quotePat = \_ -> fail "format: patterns not supported" , quoteType = toType <=< parse . snd <=< prepare , quoteDec = \_ -> fail "format: declarations not supported" } prepare :: String -> Q (Int,String) prepare str = case lines str of [] -> fail "Empty input format" [x] -> case reads x of [(n,rest)] -> pure (n, dropWhile (' '==) rest) _ -> fail "Failed to parse single-line input pattern" x:xs -> do n <- case readMaybe x of Nothing -> fail "Failed to parse format day number" Just n -> pure n pure (n, concatMap (drop indent) xs1) where xs1 = filter (any (' ' /=)) xs indent = minimum (map (length . takeWhile (' '==)) xs1) makeParser :: Int -> String -> ExpQ makeParser n str = do fmt <- parse str let formats = [| readP_to_S ($(toReadP fmt) <* eof) |] let qf = [| maybe (error "bad input parse") fst . listToMaybe . $formats |] if n == 0 then qf else [| $qf <$> getRawInput n |] toReadP :: Format -> ExpQ toReadP s = case s of Literal xs -> [| () <$ string xs |] Gather p -> [| fst <$> gather $(toReadP p) |] Named n | isUpper (head n) -> enumParser n | otherwise -> varE (mkName n) UnsignedInteger -> [| (read :: String -> Integer) <$> munch1 isDigit |] SignedInteger -> [| (read :: String -> Integer) <$> ((++) <$> option "" (string "-") <*> munch1 isDigit) |] UnsignedInt -> [| (read :: String -> Int ) <$> munch1 isDigit |] SignedInt -> [| (read :: String -> Int ) <$> ((++) <$> option "" (string "-") <*> munch1 isDigit) |] Char -> [| satisfy ('\n' /=) |] Letter -> [| satisfy (\x -> 'a' <= x && x <= 'z' || 'A' <= x && x <= 'Z') |] Word -> [| some (satisfy (not . isSpace)) |] Many x | acceptsEmpty x -> fail ("Argument to * accepts ε: " ++ showFormat 0 s "") | interesting x -> [| many $(toReadP x) |] | otherwise -> [| () <$ many $(toReadP x) |] Some x | acceptsEmpty x -> fail ("Argument to + accepts ε: " ++ showFormat 0 s "") | interesting x -> [| some $(toReadP x) |] | otherwise -> [| () <$ some $(toReadP x) |] SepBy x y | acceptsEmpty x, acceptsEmpty y -> fail ("Both arguments to & accept ε: " ++ showFormat 0 s "") | interesting x -> [| sepBy $(toReadP x) $(toReadP y) |] | otherwise -> [| () <$ sepBy $(toReadP x) $(toReadP y) |] Alt x y | xi, yi -> [| Left <$> $xp <|> Right <$> $yp |] | xi -> [| Just <$> $xp <|> Nothing <$ $yp |] | yi -> [| Nothing <$ $xp <|> Just <$> $yp |] | otherwise -> [| $xp <|> $yp |] where xi = interesting x yi = interesting y xp = toReadP x yp = toReadP y _ -> case [(interesting x, toReadP x) | x <- follows s []] of [] -> [| pure () |] xxs@((ix,x):xs) | n == 0 -> foldl apply0 x xs | n <= 1 -> foldl apply1 x xs | ix -> foldl applyN [| $tup <$> $x |] xs | otherwise -> foldl applyN [| $tup <$ $x |] xs where tup = conE (tupleDataName n) n = countBy fst xxs apply0 l (_,r) = [| $l *> $r |] apply1 l (i,r) = if i then [| $l *> $r |] else [| $l <* $r |] applyN l (i,r) = if i then [| $l <*> $r |] else [| $l <* $r |] toType :: Format -> TypeQ toType fmt = case fmt of Literal _ -> [t| () |] Gather _ -> [t| String |] Named n | isUpper (head n) -> conT (mkName n) | otherwise -> fail "toType: not implemented for variable yet" UnsignedInteger -> [t| Integer |] SignedInteger -> [t| Integer |] UnsignedInt -> [t| Int |] SignedInt -> [t| Int |] Char -> [t| Char |] Letter -> [t| Char |] Word -> [t| String |] Many x | acceptsEmpty x -> fail ("Argument to * accepts ε: " ++ showFormat 0 fmt "") | interesting x -> [t| [$(toType x)] |] | otherwise -> [t| () |] Some x | acceptsEmpty x -> fail ("Argument to + accepts ε: " ++ showFormat 0 fmt "") | interesting x -> [t| [$(toType x)] |] | otherwise -> [t| () |] SepBy x y | acceptsEmpty x, acceptsEmpty y -> fail ("Both arguments to & accept ε: " ++ showFormat 0 fmt "") | interesting x -> [t| [$(toType x)] |] | otherwise -> [t| () |] Alt x y | xi, yi -> [t| Either $xt $yt |] | xi -> [t| Maybe $xt |] | yi -> [t| Maybe $yt |] | otherwise -> [t| () |] where xi = interesting x yi = interesting y xt = toType x yt = toType y _ -> case [toType x | x <- follows fmt [], interesting x] of [] -> [t| () |] [t] -> t ts -> foldl appT (tupleT (length ts)) ts follows :: Format -> [Format] -> [Format] follows (Follow x y) zs = follows x (follows y zs) follows Empty zs = zs follows (Literal x) (Literal y : zs) = follows (Literal (x ++ y)) zs follows x zs = x : zs enumParser :: String -> ExpQ enumParser nameStr = do tyName <- maybe (fail ("Failed to find type named " ++ show nameStr)) pure =<< lookupTypeName nameStr info <- reify tyName cons <- case info of TyConI (DataD _ _ _ _ cons _) -> pure cons _ -> fail ("Failed to find data declaration for " ++ show nameStr) entries <- for cons \con -> case con of NormalC name [] | Just str <- stripPrefix nameStr (nameBase name) -> pure (name, str) _ -> fail ("Unsupported constructor: " ++ show con) let parsers = [[| $(conE name) <$ string str |] | (name, str) <- entries] [| choice $(listE parsers) |]
3bb43fc61fcc7543cf7b0ee66dc979f4500dae46ec08fb56289321864d1f2084
andreypopp/type-systems
type_error.ml
open Base open Syntax type t = | Error_unification of ty * ty | Error_recursive_type | Error_unknown_name of string include ( Showable (struct type nonrec t = t let layout = let open PPrint in function | Error_unification (ty1, ty2) -> string "incompatible types:" ^^ nest 2 (break 1 ^^ Ty.layout ty1) ^^ break 1 ^^ string "and" ^^ nest 2 (break 1 ^^ Ty.layout ty2) | Error_recursive_type -> string "recursive type" | Error_unknown_name name -> string "unknown name: " ^^ string name end) : SHOWABLE with type t := t) exception Type_error of t let raise error = raise (Type_error error)
null
https://raw.githubusercontent.com/andreypopp/type-systems/d379e6ebc73914189b0054549f6c0191319c443a/hmx/type_error.ml
ocaml
open Base open Syntax type t = | Error_unification of ty * ty | Error_recursive_type | Error_unknown_name of string include ( Showable (struct type nonrec t = t let layout = let open PPrint in function | Error_unification (ty1, ty2) -> string "incompatible types:" ^^ nest 2 (break 1 ^^ Ty.layout ty1) ^^ break 1 ^^ string "and" ^^ nest 2 (break 1 ^^ Ty.layout ty2) | Error_recursive_type -> string "recursive type" | Error_unknown_name name -> string "unknown name: " ^^ string name end) : SHOWABLE with type t := t) exception Type_error of t let raise error = raise (Type_error error)
f8e00dcba7aea03bd84d284cc8d608dfa1b4a63cb022eb8718876a2793909dc0
mzp/coq-ruby
states.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) $ I d : states.ml 13175 2010 - 06 - 22 06:28:37Z herbelin $ open System type state = Lib.frozen * Summary.frozen let freeze () = (Lib.freeze(), Summary.freeze_summaries()) let unfreeze (fl,fs) = Lib.unfreeze fl; Summary.unfreeze_summaries fs let (extern_state,intern_state) = let (raw_extern, raw_intern) = extern_intern Coq_config.state_magic_number ".coq" in (fun s -> raw_extern s (freeze())), (fun s -> unfreeze (with_magic_number_check (raw_intern (Library.get_load_paths ())) s); Library.overwrite_library_filenames s) (* Rollback. *) let with_heavy_rollback f x = let st = freeze () in try f x with reraise -> (unfreeze st; raise reraise) let with_state_protection f x = let st = freeze () in try let a = f x in unfreeze st; a with reraise -> (unfreeze st; raise reraise)
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/library/states.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Rollback.
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * $ I d : states.ml 13175 2010 - 06 - 22 06:28:37Z herbelin $ open System type state = Lib.frozen * Summary.frozen let freeze () = (Lib.freeze(), Summary.freeze_summaries()) let unfreeze (fl,fs) = Lib.unfreeze fl; Summary.unfreeze_summaries fs let (extern_state,intern_state) = let (raw_extern, raw_intern) = extern_intern Coq_config.state_magic_number ".coq" in (fun s -> raw_extern s (freeze())), (fun s -> unfreeze (with_magic_number_check (raw_intern (Library.get_load_paths ())) s); Library.overwrite_library_filenames s) let with_heavy_rollback f x = let st = freeze () in try f x with reraise -> (unfreeze st; raise reraise) let with_state_protection f x = let st = freeze () in try let a = f x in unfreeze st; a with reraise -> (unfreeze st; raise reraise)
2602e89c433d2cf897b1f975f6ed3e83ac4a3b9665cb6574604a02dd683423f3
ichiban/cl-jack
jack.lisp
This file was automatically generated by SWIG ( ) . ;;; Version 3.0.3 ;;; ;;; Do not make changes to this file unless you know what you are doing--modify the SWIG interface file instead . (in-package :cl-jack) (load-foreign-library "/usr/local/lib/libjack.so") SWIG wrapper code starts here (cl:defmacro defanonenum (cl:&body enums) "Converts anonymous enums to defconstants." `(cl:progn ,@(cl:loop for value in enums for index = 0 then (cl:1+ index) when (cl:listp value) do (cl:setf index (cl:second value) value (cl:first value)) collect `(cl:defconstant ,value ,index)))) (cl:eval-when (:compile-toplevel :load-toplevel) (cl:unless (cl:fboundp 'swig-lispify) (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*)) (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst))) (cl:cond ((cl:null lst) rest) ((cl:upper-case-p c) (helper (cl:cdr lst) 'upper (cl:case last ((lower digit) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:lower-case-p c) (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest))) ((cl:digit-char-p c) (helper (cl:cdr lst) 'digit (cl:case last ((upper lower) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:char-equal c #\_) (helper (cl:cdr lst) '_ (cl:cons #\- rest))) (cl:t (cl:error "Invalid character: ~A" c))))) (cl:let ((fix (cl:case flag ((constant enumvalue) "+") (variable "*") (cl:t "")))) (cl:intern (cl:concatenate 'cl:string fix (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil)) fix) package)))))) SWIG wrapper code ends here (cffi:defcfun ("jack_get_version" #.(swig-lispify "jack_get_version" 'function)) :void (major_ptr :pointer) (minor_ptr :pointer) (micro_ptr :pointer) (proto_ptr :pointer)) (cffi:defcfun ("jack_get_version_string" #.(swig-lispify "jack_get_version_string" 'function)) :string) (cffi:defcfun ("jack_client_open" #.(swig-lispify "jack_client_open" 'function)) :pointer (client_name :string) (options :pointer) (status :pointer) &rest) (cffi:defcfun ("jack_client_new" #.(swig-lispify "jack_client_new" 'function)) :pointer (client_name :string)) (cffi:defcfun ("jack_client_close" #.(swig-lispify "jack_client_close" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_client_name_size" #.(swig-lispify "jack_client_name_size" 'function)) :int) (cffi:defcfun ("jack_get_client_name" #.(swig-lispify "jack_get_client_name" 'function)) :string (client :pointer)) (cffi:defcfun ("jack_get_uuid_for_client_name" #.(swig-lispify "jack_get_uuid_for_client_name" 'function)) :string (client :pointer) (client_name :string)) (cffi:defcfun ("jack_get_client_name_by_uuid" #.(swig-lispify "jack_get_client_name_by_uuid" 'function)) :string (client :pointer) (client_uuid :string)) (cffi:defcfun ("jack_internal_client_new" #.(swig-lispify "jack_internal_client_new" 'function)) :int (client_name :string) (load_name :string) (load_init :string)) (cffi:defcfun ("jack_internal_client_close" #.(swig-lispify "jack_internal_client_close" 'function)) :void (client_name :string)) (cffi:defcfun ("jack_activate" #.(swig-lispify "jack_activate" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_deactivate" #.(swig-lispify "jack_deactivate" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_get_client_pid" #.(swig-lispify "jack_get_client_pid" 'function)) :int (name :string)) (cffi:defcfun ("jack_client_thread_id" #.(swig-lispify "jack_client_thread_id" 'function)) :pointer (client :pointer)) (cffi:defcfun ("jack_is_realtime" #.(swig-lispify "jack_is_realtime" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_thread_wait" #.(swig-lispify "jack_thread_wait" 'function)) :pointer (client :pointer) (status :int)) (cffi:defcfun ("jack_cycle_wait" #.(swig-lispify "jack_cycle_wait" 'function)) :pointer (client :pointer)) (cffi:defcfun ("jack_cycle_signal" #.(swig-lispify "jack_cycle_signal" 'function)) :void (client :pointer) (status :int)) (cffi:defcfun ("jack_set_process_thread" #.(swig-lispify "jack_set_process_thread" 'function)) :int (client :pointer) (thread_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_thread_init_callback" #.(swig-lispify "jack_set_thread_init_callback" 'function)) :int (client :pointer) (thread_init_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_on_shutdown" #.(swig-lispify "jack_on_shutdown" 'function)) :void (client :pointer) (shutdown_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_on_info_shutdown" #.(swig-lispify "jack_on_info_shutdown" 'function)) :void (client :pointer) (shutdown_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_process_callback" #.(swig-lispify "jack_set_process_callback" 'function)) :int (client :pointer) (process_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_freewheel_callback" #.(swig-lispify "jack_set_freewheel_callback" 'function)) :int (client :pointer) (freewheel_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_buffer_size_callback" #.(swig-lispify "jack_set_buffer_size_callback" 'function)) :int (client :pointer) (bufsize_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_sample_rate_callback" #.(swig-lispify "jack_set_sample_rate_callback" 'function)) :int (client :pointer) (srate_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_client_registration_callback" #.(swig-lispify "jack_set_client_registration_callback" 'function)) :int (client :pointer) (registration_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_registration_callback" #.(swig-lispify "jack_set_port_registration_callback" 'function)) :int (client :pointer) (registration_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_connect_callback" #.(swig-lispify "jack_set_port_connect_callback" 'function)) :int (client :pointer) (connect_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_rename_callback" #.(swig-lispify "jack_set_port_rename_callback" 'function)) :int (client :pointer) (rename_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_graph_order_callback" #.(swig-lispify "jack_set_graph_order_callback" 'function)) :int (client :pointer) (graph_callback :pointer) (arg2 :pointer)) (cffi:defcfun ("jack_set_xrun_callback" #.(swig-lispify "jack_set_xrun_callback" 'function)) :int (client :pointer) (xrun_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_latency_callback" #.(swig-lispify "jack_set_latency_callback" 'function)) :int (client :pointer) (latency_callback :pointer) (arg2 :pointer)) (cffi:defcfun ("jack_set_freewheel" #.(swig-lispify "jack_set_freewheel" 'function)) :int (client :pointer) (onoff :int)) (cffi:defcfun ("jack_set_buffer_size" #.(swig-lispify "jack_set_buffer_size" 'function)) :int (client :pointer) (nframes :pointer)) (cffi:defcfun ("jack_get_sample_rate" #.(swig-lispify "jack_get_sample_rate" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_get_buffer_size" #.(swig-lispify "jack_get_buffer_size" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_engine_takeover_timebase" #.(swig-lispify "jack_engine_takeover_timebase" 'function)) :int (arg0 :pointer)) (cffi:defcfun ("jack_cpu_load" #.(swig-lispify "jack_cpu_load" 'function)) :float (client :pointer)) (cffi:defcfun ("jack_port_register" #.(swig-lispify "jack_port_register" 'function)) :pointer (client :pointer) (port_name :string) (port_type :string) (flags :unsigned-long) (buffer_size :unsigned-long)) (cffi:defcfun ("jack_port_unregister" #.(swig-lispify "jack_port_unregister" 'function)) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_get_buffer" #.(swig-lispify "jack_port_get_buffer" 'function)) :pointer (port :pointer) (arg1 :int)) (cffi:defcfun ("jack_port_uuid" #.(swig-lispify "jack_port_uuid" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_name" #.(swig-lispify "jack_port_name" 'function)) :string (port :pointer)) (cffi:defcfun ("jack_port_short_name" #.(swig-lispify "jack_port_short_name" 'function)) :string (port :pointer)) (cffi:defcfun ("jack_port_flags" #.(swig-lispify "jack_port_flags" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_port_type" #.(swig-lispify "jack_port_type" 'function)) :string (port :pointer)) (cffi:defcfun ("jack_port_type_id" #.(swig-lispify "jack_port_type_id" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_is_mine" #.(swig-lispify "jack_port_is_mine" 'function)) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_connected" #.(swig-lispify "jack_port_connected" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_port_connected_to" #.(swig-lispify "jack_port_connected_to" 'function)) :int (port :pointer) (port_name :string)) (cffi:defcfun ("jack_port_get_connections" #.(swig-lispify "jack_port_get_connections" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_get_all_connections" #.(swig-lispify "jack_port_get_all_connections" 'function)) :pointer (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_tie" #.(swig-lispify "jack_port_tie" 'function)) :int (src :pointer) (dst :pointer)) (cffi:defcfun ("jack_port_untie" #.(swig-lispify "jack_port_untie" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_port_set_name" #.(swig-lispify "jack_port_set_name" 'function)) :int (port :pointer) (port_name :string)) (cffi:defcfun ("jack_port_set_alias" #.(swig-lispify "jack_port_set_alias" 'function)) :int (port :pointer) (alias :string)) (cffi:defcfun ("jack_port_unset_alias" #.(swig-lispify "jack_port_unset_alias" 'function)) :int (port :pointer) (alias :string)) (cffi:defcfun ("jack_port_get_aliases" #.(swig-lispify "jack_port_get_aliases" 'function)) :int (port :pointer) (aliases :pointer)) (cffi:defcfun ("jack_port_request_monitor" #.(swig-lispify "jack_port_request_monitor" 'function)) :int (port :pointer) (onoff :int)) (cffi:defcfun ("jack_port_request_monitor_by_name" #.(swig-lispify "jack_port_request_monitor_by_name" 'function)) :int (client :pointer) (port_name :string) (onoff :int)) (cffi:defcfun ("jack_port_ensure_monitor" #.(swig-lispify "jack_port_ensure_monitor" 'function)) :int (port :pointer) (onoff :int)) (cffi:defcfun ("jack_port_monitoring_input" #.(swig-lispify "jack_port_monitoring_input" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_connect" #.(swig-lispify "jack_connect" 'function)) :int (client :pointer) (source_port :string) (destination_port :string)) (cffi:defcfun ("jack_disconnect" #.(swig-lispify "jack_disconnect" 'function)) :int (client :pointer) (source_port :string) (destination_port :string)) (cffi:defcfun ("jack_port_disconnect" #.(swig-lispify "jack_port_disconnect" 'function)) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_name_size" #.(swig-lispify "jack_port_name_size" 'function)) :int) (cffi:defcfun ("jack_port_type_size" #.(swig-lispify "jack_port_type_size" 'function)) :int) (cffi:defcfun ("jack_port_type_get_buffer_size" #.(swig-lispify "jack_port_type_get_buffer_size" 'function)) :pointer (client :pointer) (port_type :string)) (cffi:defcfun ("jack_port_set_latency" #.(swig-lispify "jack_port_set_latency" 'function)) :void (port :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_port_get_latency_range" #.(swig-lispify "jack_port_get_latency_range" 'function)) :void (port :pointer) (mode :pointer) (range :pointer)) (cffi:defcfun ("jack_port_set_latency_range" #.(swig-lispify "jack_port_set_latency_range" 'function)) :void (port :pointer) (mode :pointer) (range :pointer)) (cffi:defcfun ("jack_recompute_total_latencies" #.(swig-lispify "jack_recompute_total_latencies" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_port_get_latency" #.(swig-lispify "jack_port_get_latency" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_get_total_latency" #.(swig-lispify "jack_port_get_total_latency" 'function)) :pointer (client :pointer) (port :pointer)) (cffi:defcfun ("jack_recompute_total_latency" #.(swig-lispify "jack_recompute_total_latency" 'function)) :int (arg0 :pointer) (port :pointer)) (cffi:defcfun ("jack_get_ports" #.(swig-lispify "jack_get_ports" 'function)) :pointer (client :pointer) (port_name_pattern :string) (type_name_pattern :string) (flags :unsigned-long)) (cffi:defcfun ("jack_port_by_name" #.(swig-lispify "jack_port_by_name" 'function)) :pointer (client :pointer) (port_name :string)) (cffi:defcfun ("jack_port_by_id" #.(swig-lispify "jack_port_by_id" 'function)) :pointer (client :pointer) (port_id :pointer)) (cffi:defcfun ("jack_frames_since_cycle_start" #.(swig-lispify "jack_frames_since_cycle_start" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_frame_time" #.(swig-lispify "jack_frame_time" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_last_frame_time" #.(swig-lispify "jack_last_frame_time" 'function)) :pointer (client :pointer)) (cffi:defcfun ("jack_get_cycle_times" #.(swig-lispify "jack_get_cycle_times" 'function)) :int (client :pointer) (current_frames :pointer) (current_usecs :pointer) (next_usecs :pointer) (period_usecs :pointer)) (cffi:defcfun ("jack_frames_to_time" #.(swig-lispify "jack_frames_to_time" 'function)) :pointer (client :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_time_to_frames" #.(swig-lispify "jack_time_to_frames" 'function)) :pointer (client :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_get_time" #.(swig-lispify "jack_get_time" 'function)) :pointer) (cffi:defcvar ("jack_error_callback" #.(swig-lispify "jack_error_callback" 'variable)) :pointer) (cffi:defcfun ("jack_set_error_function" #.(swig-lispify "jack_set_error_function" 'function)) :void (func :pointer)) (cffi:defcvar ("jack_info_callback" #.(swig-lispify "jack_info_callback" 'variable)) :pointer) (cffi:defcfun ("jack_set_info_function" #.(swig-lispify "jack_set_info_function" 'function)) :void (func :pointer)) (cffi:defcfun ("jack_free" #.(swig-lispify "jack_free" 'function)) :void (ptr :pointer))
null
https://raw.githubusercontent.com/ichiban/cl-jack/ffdcfe863d4b841aceb85622bded0ad34a278fee/jack.lisp
lisp
Version 3.0.3 Do not make changes to this file unless you know what you are doing--modify
This file was automatically generated by SWIG ( ) . the SWIG interface file instead . (in-package :cl-jack) (load-foreign-library "/usr/local/lib/libjack.so") SWIG wrapper code starts here (cl:defmacro defanonenum (cl:&body enums) "Converts anonymous enums to defconstants." `(cl:progn ,@(cl:loop for value in enums for index = 0 then (cl:1+ index) when (cl:listp value) do (cl:setf index (cl:second value) value (cl:first value)) collect `(cl:defconstant ,value ,index)))) (cl:eval-when (:compile-toplevel :load-toplevel) (cl:unless (cl:fboundp 'swig-lispify) (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*)) (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst))) (cl:cond ((cl:null lst) rest) ((cl:upper-case-p c) (helper (cl:cdr lst) 'upper (cl:case last ((lower digit) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:lower-case-p c) (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest))) ((cl:digit-char-p c) (helper (cl:cdr lst) 'digit (cl:case last ((upper lower) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:char-equal c #\_) (helper (cl:cdr lst) '_ (cl:cons #\- rest))) (cl:t (cl:error "Invalid character: ~A" c))))) (cl:let ((fix (cl:case flag ((constant enumvalue) "+") (variable "*") (cl:t "")))) (cl:intern (cl:concatenate 'cl:string fix (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil)) fix) package)))))) SWIG wrapper code ends here (cffi:defcfun ("jack_get_version" #.(swig-lispify "jack_get_version" 'function)) :void (major_ptr :pointer) (minor_ptr :pointer) (micro_ptr :pointer) (proto_ptr :pointer)) (cffi:defcfun ("jack_get_version_string" #.(swig-lispify "jack_get_version_string" 'function)) :string) (cffi:defcfun ("jack_client_open" #.(swig-lispify "jack_client_open" 'function)) :pointer (client_name :string) (options :pointer) (status :pointer) &rest) (cffi:defcfun ("jack_client_new" #.(swig-lispify "jack_client_new" 'function)) :pointer (client_name :string)) (cffi:defcfun ("jack_client_close" #.(swig-lispify "jack_client_close" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_client_name_size" #.(swig-lispify "jack_client_name_size" 'function)) :int) (cffi:defcfun ("jack_get_client_name" #.(swig-lispify "jack_get_client_name" 'function)) :string (client :pointer)) (cffi:defcfun ("jack_get_uuid_for_client_name" #.(swig-lispify "jack_get_uuid_for_client_name" 'function)) :string (client :pointer) (client_name :string)) (cffi:defcfun ("jack_get_client_name_by_uuid" #.(swig-lispify "jack_get_client_name_by_uuid" 'function)) :string (client :pointer) (client_uuid :string)) (cffi:defcfun ("jack_internal_client_new" #.(swig-lispify "jack_internal_client_new" 'function)) :int (client_name :string) (load_name :string) (load_init :string)) (cffi:defcfun ("jack_internal_client_close" #.(swig-lispify "jack_internal_client_close" 'function)) :void (client_name :string)) (cffi:defcfun ("jack_activate" #.(swig-lispify "jack_activate" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_deactivate" #.(swig-lispify "jack_deactivate" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_get_client_pid" #.(swig-lispify "jack_get_client_pid" 'function)) :int (name :string)) (cffi:defcfun ("jack_client_thread_id" #.(swig-lispify "jack_client_thread_id" 'function)) :pointer (client :pointer)) (cffi:defcfun ("jack_is_realtime" #.(swig-lispify "jack_is_realtime" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_thread_wait" #.(swig-lispify "jack_thread_wait" 'function)) :pointer (client :pointer) (status :int)) (cffi:defcfun ("jack_cycle_wait" #.(swig-lispify "jack_cycle_wait" 'function)) :pointer (client :pointer)) (cffi:defcfun ("jack_cycle_signal" #.(swig-lispify "jack_cycle_signal" 'function)) :void (client :pointer) (status :int)) (cffi:defcfun ("jack_set_process_thread" #.(swig-lispify "jack_set_process_thread" 'function)) :int (client :pointer) (thread_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_thread_init_callback" #.(swig-lispify "jack_set_thread_init_callback" 'function)) :int (client :pointer) (thread_init_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_on_shutdown" #.(swig-lispify "jack_on_shutdown" 'function)) :void (client :pointer) (shutdown_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_on_info_shutdown" #.(swig-lispify "jack_on_info_shutdown" 'function)) :void (client :pointer) (shutdown_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_process_callback" #.(swig-lispify "jack_set_process_callback" 'function)) :int (client :pointer) (process_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_freewheel_callback" #.(swig-lispify "jack_set_freewheel_callback" 'function)) :int (client :pointer) (freewheel_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_buffer_size_callback" #.(swig-lispify "jack_set_buffer_size_callback" 'function)) :int (client :pointer) (bufsize_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_sample_rate_callback" #.(swig-lispify "jack_set_sample_rate_callback" 'function)) :int (client :pointer) (srate_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_client_registration_callback" #.(swig-lispify "jack_set_client_registration_callback" 'function)) :int (client :pointer) (registration_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_registration_callback" #.(swig-lispify "jack_set_port_registration_callback" 'function)) :int (client :pointer) (registration_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_connect_callback" #.(swig-lispify "jack_set_port_connect_callback" 'function)) :int (client :pointer) (connect_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_rename_callback" #.(swig-lispify "jack_set_port_rename_callback" 'function)) :int (client :pointer) (rename_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_graph_order_callback" #.(swig-lispify "jack_set_graph_order_callback" 'function)) :int (client :pointer) (graph_callback :pointer) (arg2 :pointer)) (cffi:defcfun ("jack_set_xrun_callback" #.(swig-lispify "jack_set_xrun_callback" 'function)) :int (client :pointer) (xrun_callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_latency_callback" #.(swig-lispify "jack_set_latency_callback" 'function)) :int (client :pointer) (latency_callback :pointer) (arg2 :pointer)) (cffi:defcfun ("jack_set_freewheel" #.(swig-lispify "jack_set_freewheel" 'function)) :int (client :pointer) (onoff :int)) (cffi:defcfun ("jack_set_buffer_size" #.(swig-lispify "jack_set_buffer_size" 'function)) :int (client :pointer) (nframes :pointer)) (cffi:defcfun ("jack_get_sample_rate" #.(swig-lispify "jack_get_sample_rate" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_get_buffer_size" #.(swig-lispify "jack_get_buffer_size" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_engine_takeover_timebase" #.(swig-lispify "jack_engine_takeover_timebase" 'function)) :int (arg0 :pointer)) (cffi:defcfun ("jack_cpu_load" #.(swig-lispify "jack_cpu_load" 'function)) :float (client :pointer)) (cffi:defcfun ("jack_port_register" #.(swig-lispify "jack_port_register" 'function)) :pointer (client :pointer) (port_name :string) (port_type :string) (flags :unsigned-long) (buffer_size :unsigned-long)) (cffi:defcfun ("jack_port_unregister" #.(swig-lispify "jack_port_unregister" 'function)) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_get_buffer" #.(swig-lispify "jack_port_get_buffer" 'function)) :pointer (port :pointer) (arg1 :int)) (cffi:defcfun ("jack_port_uuid" #.(swig-lispify "jack_port_uuid" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_name" #.(swig-lispify "jack_port_name" 'function)) :string (port :pointer)) (cffi:defcfun ("jack_port_short_name" #.(swig-lispify "jack_port_short_name" 'function)) :string (port :pointer)) (cffi:defcfun ("jack_port_flags" #.(swig-lispify "jack_port_flags" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_port_type" #.(swig-lispify "jack_port_type" 'function)) :string (port :pointer)) (cffi:defcfun ("jack_port_type_id" #.(swig-lispify "jack_port_type_id" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_is_mine" #.(swig-lispify "jack_port_is_mine" 'function)) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_connected" #.(swig-lispify "jack_port_connected" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_port_connected_to" #.(swig-lispify "jack_port_connected_to" 'function)) :int (port :pointer) (port_name :string)) (cffi:defcfun ("jack_port_get_connections" #.(swig-lispify "jack_port_get_connections" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_get_all_connections" #.(swig-lispify "jack_port_get_all_connections" 'function)) :pointer (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_tie" #.(swig-lispify "jack_port_tie" 'function)) :int (src :pointer) (dst :pointer)) (cffi:defcfun ("jack_port_untie" #.(swig-lispify "jack_port_untie" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_port_set_name" #.(swig-lispify "jack_port_set_name" 'function)) :int (port :pointer) (port_name :string)) (cffi:defcfun ("jack_port_set_alias" #.(swig-lispify "jack_port_set_alias" 'function)) :int (port :pointer) (alias :string)) (cffi:defcfun ("jack_port_unset_alias" #.(swig-lispify "jack_port_unset_alias" 'function)) :int (port :pointer) (alias :string)) (cffi:defcfun ("jack_port_get_aliases" #.(swig-lispify "jack_port_get_aliases" 'function)) :int (port :pointer) (aliases :pointer)) (cffi:defcfun ("jack_port_request_monitor" #.(swig-lispify "jack_port_request_monitor" 'function)) :int (port :pointer) (onoff :int)) (cffi:defcfun ("jack_port_request_monitor_by_name" #.(swig-lispify "jack_port_request_monitor_by_name" 'function)) :int (client :pointer) (port_name :string) (onoff :int)) (cffi:defcfun ("jack_port_ensure_monitor" #.(swig-lispify "jack_port_ensure_monitor" 'function)) :int (port :pointer) (onoff :int)) (cffi:defcfun ("jack_port_monitoring_input" #.(swig-lispify "jack_port_monitoring_input" 'function)) :int (port :pointer)) (cffi:defcfun ("jack_connect" #.(swig-lispify "jack_connect" 'function)) :int (client :pointer) (source_port :string) (destination_port :string)) (cffi:defcfun ("jack_disconnect" #.(swig-lispify "jack_disconnect" 'function)) :int (client :pointer) (source_port :string) (destination_port :string)) (cffi:defcfun ("jack_port_disconnect" #.(swig-lispify "jack_port_disconnect" 'function)) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_name_size" #.(swig-lispify "jack_port_name_size" 'function)) :int) (cffi:defcfun ("jack_port_type_size" #.(swig-lispify "jack_port_type_size" 'function)) :int) (cffi:defcfun ("jack_port_type_get_buffer_size" #.(swig-lispify "jack_port_type_get_buffer_size" 'function)) :pointer (client :pointer) (port_type :string)) (cffi:defcfun ("jack_port_set_latency" #.(swig-lispify "jack_port_set_latency" 'function)) :void (port :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_port_get_latency_range" #.(swig-lispify "jack_port_get_latency_range" 'function)) :void (port :pointer) (mode :pointer) (range :pointer)) (cffi:defcfun ("jack_port_set_latency_range" #.(swig-lispify "jack_port_set_latency_range" 'function)) :void (port :pointer) (mode :pointer) (range :pointer)) (cffi:defcfun ("jack_recompute_total_latencies" #.(swig-lispify "jack_recompute_total_latencies" 'function)) :int (client :pointer)) (cffi:defcfun ("jack_port_get_latency" #.(swig-lispify "jack_port_get_latency" 'function)) :pointer (port :pointer)) (cffi:defcfun ("jack_port_get_total_latency" #.(swig-lispify "jack_port_get_total_latency" 'function)) :pointer (client :pointer) (port :pointer)) (cffi:defcfun ("jack_recompute_total_latency" #.(swig-lispify "jack_recompute_total_latency" 'function)) :int (arg0 :pointer) (port :pointer)) (cffi:defcfun ("jack_get_ports" #.(swig-lispify "jack_get_ports" 'function)) :pointer (client :pointer) (port_name_pattern :string) (type_name_pattern :string) (flags :unsigned-long)) (cffi:defcfun ("jack_port_by_name" #.(swig-lispify "jack_port_by_name" 'function)) :pointer (client :pointer) (port_name :string)) (cffi:defcfun ("jack_port_by_id" #.(swig-lispify "jack_port_by_id" 'function)) :pointer (client :pointer) (port_id :pointer)) (cffi:defcfun ("jack_frames_since_cycle_start" #.(swig-lispify "jack_frames_since_cycle_start" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_frame_time" #.(swig-lispify "jack_frame_time" 'function)) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_last_frame_time" #.(swig-lispify "jack_last_frame_time" 'function)) :pointer (client :pointer)) (cffi:defcfun ("jack_get_cycle_times" #.(swig-lispify "jack_get_cycle_times" 'function)) :int (client :pointer) (current_frames :pointer) (current_usecs :pointer) (next_usecs :pointer) (period_usecs :pointer)) (cffi:defcfun ("jack_frames_to_time" #.(swig-lispify "jack_frames_to_time" 'function)) :pointer (client :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_time_to_frames" #.(swig-lispify "jack_time_to_frames" 'function)) :pointer (client :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_get_time" #.(swig-lispify "jack_get_time" 'function)) :pointer) (cffi:defcvar ("jack_error_callback" #.(swig-lispify "jack_error_callback" 'variable)) :pointer) (cffi:defcfun ("jack_set_error_function" #.(swig-lispify "jack_set_error_function" 'function)) :void (func :pointer)) (cffi:defcvar ("jack_info_callback" #.(swig-lispify "jack_info_callback" 'variable)) :pointer) (cffi:defcfun ("jack_set_info_function" #.(swig-lispify "jack_set_info_function" 'function)) :void (func :pointer)) (cffi:defcfun ("jack_free" #.(swig-lispify "jack_free" 'function)) :void (ptr :pointer))
4c532a3f923931f8a102fd91ddb0a62d3dedd1fe18cec619a4dded6e71e4ba71
mejgun/haskell-tdlib
CallbackQueryAnswer.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Data.CallbackQueryAnswer where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U -- | | Contains a bot 's answer to a callback query @text Text of the answer @show_alert True , if an alert must be shown to the user instead of a toast notification @url URL to be opened CallbackQueryAnswer { -- | url :: Maybe String, -- | show_alert :: Maybe Bool, -- | text :: Maybe String } deriving (Eq) instance Show CallbackQueryAnswer where show CallbackQueryAnswer { url = url_, show_alert = show_alert_, text = text_ } = "CallbackQueryAnswer" ++ U.cc [ U.p "url" url_, U.p "show_alert" show_alert_, U.p "text" text_ ] instance T.FromJSON CallbackQueryAnswer where parseJSON v@(T.Object obj) = do t <- obj A..: "@type" :: T.Parser String case t of "callbackQueryAnswer" -> parseCallbackQueryAnswer v _ -> mempty where parseCallbackQueryAnswer :: A.Value -> T.Parser CallbackQueryAnswer parseCallbackQueryAnswer = A.withObject "CallbackQueryAnswer" $ \o -> do url_ <- o A..:? "url" show_alert_ <- o A..:? "show_alert" text_ <- o A..:? "text" return $ CallbackQueryAnswer {url = url_, show_alert = show_alert_, text = text_} parseJSON _ = mempty instance T.ToJSON CallbackQueryAnswer where toJSON CallbackQueryAnswer { url = url_, show_alert = show_alert_, text = text_ } = A.object [ "@type" A..= T.String "callbackQueryAnswer", "url" A..= url_, "show_alert" A..= show_alert_, "text" A..= text_ ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/beb6635177d7626b70fd909b1d89f2156a992cd2/src/TD/Data/CallbackQueryAnswer.hs
haskell
# LANGUAGE OverloadedStrings # | | | | |
module TD.Data.CallbackQueryAnswer where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U | Contains a bot 's answer to a callback query @text Text of the answer @show_alert True , if an alert must be shown to the user instead of a toast notification @url URL to be opened CallbackQueryAnswer url :: Maybe String, show_alert :: Maybe Bool, text :: Maybe String } deriving (Eq) instance Show CallbackQueryAnswer where show CallbackQueryAnswer { url = url_, show_alert = show_alert_, text = text_ } = "CallbackQueryAnswer" ++ U.cc [ U.p "url" url_, U.p "show_alert" show_alert_, U.p "text" text_ ] instance T.FromJSON CallbackQueryAnswer where parseJSON v@(T.Object obj) = do t <- obj A..: "@type" :: T.Parser String case t of "callbackQueryAnswer" -> parseCallbackQueryAnswer v _ -> mempty where parseCallbackQueryAnswer :: A.Value -> T.Parser CallbackQueryAnswer parseCallbackQueryAnswer = A.withObject "CallbackQueryAnswer" $ \o -> do url_ <- o A..:? "url" show_alert_ <- o A..:? "show_alert" text_ <- o A..:? "text" return $ CallbackQueryAnswer {url = url_, show_alert = show_alert_, text = text_} parseJSON _ = mempty instance T.ToJSON CallbackQueryAnswer where toJSON CallbackQueryAnswer { url = url_, show_alert = show_alert_, text = text_ } = A.object [ "@type" A..= T.String "callbackQueryAnswer", "url" A..= url_, "show_alert" A..= show_alert_, "text" A..= text_ ]
94cdc93e212f1f14cac074a282d4539fcdf94453b3190841e2c723487297ceb5
OCamlPro/ocp-build
buildTerm.ml
(**************************************************************************) (* *) (* Typerex Tools *) (* *) Copyright 2011 - 2017 OCamlPro SAS (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU General Public License version 3 described in the file (* LICENSE. *) (* *) (**************************************************************************) open BuildBase (* open Stdlib2 *) let term = try Sys.getenv "TERM" with Not_found -> "none" let need_escape = if term <> "" then true else match MinUnix.os_type with MinUnix.WINDOWS | MinUnix.CYGWIN -> true | MinUnix.UNIX -> false let term_escape s = if need_escape then String.escaped s else s let has_colors = try match BuildMisc.get_stdout_lines [ "tput"; "-T" ^ term; "colors" ] [] with | `OUTPUT (0, line :: _) -> (int_of_string line) >= 8 | _ -> false with _ -> false let ncolumns = try (* terminfo *) match BuildMisc.get_stdout_lines [ "tput"; "cols" ] [] with | `OUTPUT (0, line :: _) -> int_of_string line | _ -> raise Not_found with _ -> try GNU match BuildMisc.get_stdout_lines [ "stty"; "size" ] [] with | `OUTPUT (0, line :: _) -> begin match OcpString.split line ' ' with | [_ ; v] -> int_of_string v | _ -> failwith "stty" end | _ -> raise Not_found with MinUnix.Unix_error _ | End_of_file | Failure _ | Not_found -> try (* shell envvar *) int_of_string (Sys.getenv "COLUMNS") with Not_found | Failure _ -> 80 let csi_m n = Printf.sprintf "\027[%sm" n type ansi_sequences = { mutable esc_ansi : bool; mutable esc_bold : string; mutable esc_black_text : string; mutable esc_red_text : string; mutable esc_green_text : string; mutable esc_yellow_text : string; mutable esc_blue_text : string; mutable esc_magenta_text : string; mutable esc_cyan_text : string; mutable esc_white_text : string; mutable esc_end : string; mutable esc_linefeed : string; mutable esc_killline : string; mutable esc_columns : int; } let term = { esc_ansi = has_colors; esc_bold = csi_m "1"; esc_black_text = csi_m "30"; esc_red_text = csi_m "31"; esc_green_text = csi_m "32"; esc_yellow_text = csi_m "33"; esc_blue_text = csi_m "34"; esc_magenta_text = csi_m "35"; esc_cyan_text = csi_m "36"; esc_white_text = csi_m "37"; esc_end = csi_m ""; esc_linefeed = "\r"; esc_killline = "\027[K"; esc_columns = ncolumns; } let set_ansi_term is_ansi = if is_ansi then begin term.esc_ansi <- true; term.esc_bold <- csi_m "1"; term.esc_black_text <- csi_m "30"; term.esc_red_text <- csi_m "31"; term.esc_green_text <- csi_m "32"; term.esc_yellow_text <- csi_m "33"; term.esc_blue_text <- csi_m "34"; term.esc_magenta_text <- csi_m "35"; term.esc_cyan_text <- csi_m "36"; term.esc_white_text <- csi_m "37"; term.esc_end <- csi_m ""; term.esc_linefeed <- "\r"; term.esc_killline <- "\027[K"; term.esc_columns <- ncolumns; end else begin term.esc_ansi <- false; term.esc_bold <- ""; term.esc_black_text <- ""; term.esc_red_text <- ""; term.esc_green_text <- ""; term.esc_yellow_text <- ""; term.esc_blue_text <- ""; term.esc_magenta_text <- ""; term.esc_cyan_text <- ""; term.esc_white_text <- ""; term.esc_end <- ""; term.esc_linefeed <- ""; term.esc_killline <- ""; term.esc_columns <- ncolumns; end let term_bold s = term.esc_bold ^ s ^ term.esc_end
null
https://raw.githubusercontent.com/OCamlPro/ocp-build/56aff560bb438c12b2929feaf8379bc6f31b9840/tools/ocp-build/misc/buildTerm.ml
ocaml
************************************************************************ Typerex Tools All rights reserved. This file is distributed under the terms of LICENSE. ************************************************************************ open Stdlib2 terminfo shell envvar
Copyright 2011 - 2017 OCamlPro SAS the GNU General Public License version 3 described in the file open BuildBase let term = try Sys.getenv "TERM" with Not_found -> "none" let need_escape = if term <> "" then true else match MinUnix.os_type with MinUnix.WINDOWS | MinUnix.CYGWIN -> true | MinUnix.UNIX -> false let term_escape s = if need_escape then String.escaped s else s let has_colors = try match BuildMisc.get_stdout_lines [ "tput"; "-T" ^ term; "colors" ] [] with | `OUTPUT (0, line :: _) -> (int_of_string line) >= 8 | _ -> false with _ -> false let ncolumns = try match BuildMisc.get_stdout_lines [ "tput"; "cols" ] [] with | `OUTPUT (0, line :: _) -> int_of_string line | _ -> raise Not_found with _ -> try GNU match BuildMisc.get_stdout_lines [ "stty"; "size" ] [] with | `OUTPUT (0, line :: _) -> begin match OcpString.split line ' ' with | [_ ; v] -> int_of_string v | _ -> failwith "stty" end | _ -> raise Not_found with MinUnix.Unix_error _ | End_of_file | Failure _ | Not_found -> try int_of_string (Sys.getenv "COLUMNS") with Not_found | Failure _ -> 80 let csi_m n = Printf.sprintf "\027[%sm" n type ansi_sequences = { mutable esc_ansi : bool; mutable esc_bold : string; mutable esc_black_text : string; mutable esc_red_text : string; mutable esc_green_text : string; mutable esc_yellow_text : string; mutable esc_blue_text : string; mutable esc_magenta_text : string; mutable esc_cyan_text : string; mutable esc_white_text : string; mutable esc_end : string; mutable esc_linefeed : string; mutable esc_killline : string; mutable esc_columns : int; } let term = { esc_ansi = has_colors; esc_bold = csi_m "1"; esc_black_text = csi_m "30"; esc_red_text = csi_m "31"; esc_green_text = csi_m "32"; esc_yellow_text = csi_m "33"; esc_blue_text = csi_m "34"; esc_magenta_text = csi_m "35"; esc_cyan_text = csi_m "36"; esc_white_text = csi_m "37"; esc_end = csi_m ""; esc_linefeed = "\r"; esc_killline = "\027[K"; esc_columns = ncolumns; } let set_ansi_term is_ansi = if is_ansi then begin term.esc_ansi <- true; term.esc_bold <- csi_m "1"; term.esc_black_text <- csi_m "30"; term.esc_red_text <- csi_m "31"; term.esc_green_text <- csi_m "32"; term.esc_yellow_text <- csi_m "33"; term.esc_blue_text <- csi_m "34"; term.esc_magenta_text <- csi_m "35"; term.esc_cyan_text <- csi_m "36"; term.esc_white_text <- csi_m "37"; term.esc_end <- csi_m ""; term.esc_linefeed <- "\r"; term.esc_killline <- "\027[K"; term.esc_columns <- ncolumns; end else begin term.esc_ansi <- false; term.esc_bold <- ""; term.esc_black_text <- ""; term.esc_red_text <- ""; term.esc_green_text <- ""; term.esc_yellow_text <- ""; term.esc_blue_text <- ""; term.esc_magenta_text <- ""; term.esc_cyan_text <- ""; term.esc_white_text <- ""; term.esc_end <- ""; term.esc_linefeed <- ""; term.esc_killline <- ""; term.esc_columns <- ncolumns; end let term_bold s = term.esc_bold ^ s ^ term.esc_end
4777fab66a0cdfc6ca0f3e5cdb92fb44f77a28bf059a45bc2b0e489bc1d2470d
mathematical-systems/clml
histogram.lisp
(in-package :statistics) (defun histogram (values n) (let ((min (reduce #'min values)) (max (reduce #'max values)) (len (length values))) (loop with delta = (/ (- max min) n) for lst = values then (set-difference lst current :test #'=) for i from 1 to n for x = (linear-combination min (/ i n) max) for current = (remove-if-not (lambda (y) (< y x)) lst) collect (list x (/ (length current) len delta))))) (defun discrete-histogram (values) (let ((min (reduce #'min values)) (max (reduce #'max values)) (len (length values))) (loop for x from min to max collect (list x (/ (count x values) len))))) (defun plot-function (fn min max n) (loop for i from 0 below n for x = (linear-combination min (/ i (1- n)) max) collect (list x (funcall fn x)))) (defun plot-discrete-function (fn min max) (loop for x from min to max collect (list x (funcall fn x)))) ;;; Usage example: #+nil (with-open-file (s "/tmp/random-standard-normal.data" :direction :output :if-exists :supersede) (let ((values (rand-n (standard-normal-distribution) 10000))) (format s "~{~{~f ~f~}~%~}" (histogram values 50)))) #+nil (with-open-file (s "/tmp/real-standard-normal.data" :direction :output :if-exists :supersede) (format s "~{~{~f ~f~}~%~}" (let ((d (standard-normal-distribution))) (plot-function (lambda (x) (density d x)) -4 4 50)))) .. then in GNUPlot : ;; plot [-4:4] "/tmp/random-standard-normal.data" \ title " Random values ( 100 ranges from 10 ^ 5 data ) " , \ ;; "/tmp/real-standard-normal.data" with lines title "Exact distribution" ;;; Discrete case: #+nil (with-open-file (s "/tmp/random-pascal.data" :direction :output :if-exists :supersede) (let ((values (rand-n (pascal-distribution 10 0.6d0) 10000))) (format s "~{~{~f ~f~}~%~}" (discrete-histogram values)))) #+nil (with-open-file (s "/tmp/real-pascal.data" :direction :output :if-exists :supersede) (format s "~{~{~f ~f~}~%~}" (let ((d (pascal-distribution 10 0.6d0))) (plot-discrete-function (lambda (x) (mass d x)) 0 20))))
null
https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/distribution/histogram.lisp
lisp
Usage example: plot [-4:4] "/tmp/random-standard-normal.data" \ "/tmp/real-standard-normal.data" with lines title "Exact distribution" Discrete case:
(in-package :statistics) (defun histogram (values n) (let ((min (reduce #'min values)) (max (reduce #'max values)) (len (length values))) (loop with delta = (/ (- max min) n) for lst = values then (set-difference lst current :test #'=) for i from 1 to n for x = (linear-combination min (/ i n) max) for current = (remove-if-not (lambda (y) (< y x)) lst) collect (list x (/ (length current) len delta))))) (defun discrete-histogram (values) (let ((min (reduce #'min values)) (max (reduce #'max values)) (len (length values))) (loop for x from min to max collect (list x (/ (count x values) len))))) (defun plot-function (fn min max n) (loop for i from 0 below n for x = (linear-combination min (/ i (1- n)) max) collect (list x (funcall fn x)))) (defun plot-discrete-function (fn min max) (loop for x from min to max collect (list x (funcall fn x)))) #+nil (with-open-file (s "/tmp/random-standard-normal.data" :direction :output :if-exists :supersede) (let ((values (rand-n (standard-normal-distribution) 10000))) (format s "~{~{~f ~f~}~%~}" (histogram values 50)))) #+nil (with-open-file (s "/tmp/real-standard-normal.data" :direction :output :if-exists :supersede) (format s "~{~{~f ~f~}~%~}" (let ((d (standard-normal-distribution))) (plot-function (lambda (x) (density d x)) -4 4 50)))) .. then in GNUPlot : title " Random values ( 100 ranges from 10 ^ 5 data ) " , \ #+nil (with-open-file (s "/tmp/random-pascal.data" :direction :output :if-exists :supersede) (let ((values (rand-n (pascal-distribution 10 0.6d0) 10000))) (format s "~{~{~f ~f~}~%~}" (discrete-histogram values)))) #+nil (with-open-file (s "/tmp/real-pascal.data" :direction :output :if-exists :supersede) (format s "~{~{~f ~f~}~%~}" (let ((d (pascal-distribution 10 0.6d0))) (plot-discrete-function (lambda (x) (mass d x)) 0 20))))