_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
4fadb2e23d1bffc44a3be3dacda79fb9527b1da6bb7970c061268cc8b7e7baec
haskellari/qc-instances
CustomPrelude.hs
-- | Custom prelude. -- -- We don't need much, and we don't care about precise types ( Monad or Applicative constraints , e.g. ) -- So this is simple approach. -- module Test.QuickCheck.Instances.CustomPrelude ( module Export, ) where import Control.Applicative as Export (Applicative (pure, (<*>)), (<$>)) import Data.Traversable as Export (Traversable (..)) import Prelude as Export (Bounded (..), Either (..), Enum (..), Eq (..), Functor (..), Maybe (..), Monad ((>>=)), Ord (..), Ordering (..), const, flip, fst, id, otherwise, replicate, return, uncurry, ($), (.)) -- lists import Prelude as Export (length, map, (++)) -- numbers import Prelude as Export (Double, Fractional (..), Int, Integral (..), Num (..), Real (..), fromIntegral) -- errors import Prelude as Export (error, undefined)
null
https://raw.githubusercontent.com/haskellari/qc-instances/94ec49f96c9afd7d29880c22bedfbabe01ad30d5/src/Test/QuickCheck/Instances/CustomPrelude.hs
haskell
| Custom prelude. We don't need much, and we don't care about precise types So this is simple approach. lists numbers errors
( Monad or Applicative constraints , e.g. ) module Test.QuickCheck.Instances.CustomPrelude ( module Export, ) where import Control.Applicative as Export (Applicative (pure, (<*>)), (<$>)) import Data.Traversable as Export (Traversable (..)) import Prelude as Export (Bounded (..), Either (..), Enum (..), Eq (..), Functor (..), Maybe (..), Monad ((>>=)), Ord (..), Ordering (..), const, flip, fst, id, otherwise, replicate, return, uncurry, ($), (.)) import Prelude as Export (length, map, (++)) import Prelude as Export (Double, Fractional (..), Int, Integral (..), Num (..), Real (..), fromIntegral) import Prelude as Export (error, undefined)
8a02445e6d70b728b7bcbfdc48ba7f43617f4b36cbbeae5bca9d1392f18a99cd
hammerlab/biokepi
sambamba.ml
open Biokepi_run_environment open Common module Remove = Workflow_utilities.Remove module Filter = struct type t = [ `String of string ] let of_string s = `String s let to_string f = match f with | `String s -> s module Defaults = struct let only_split_reads = of_string "cigar =~ /^.*N.*$/" let drop_split_reads = of_string "cigar =~ /^[0-9MIDSHPX=]*$/" end end (* Filter language syntax at -view%5D-Filter-expression-syntax *) let view ~(run_with : Machine.t) ~bam ~filter output_file_path = let open KEDSL in let name = sprintf "Sambamba.view %s %s" (Filename.basename bam#product#path) (Filter.to_string filter) in let clean_up = Remove.file ~run_with output_file_path in let reference_build = bam#product#reference_build in let product = KEDSL.bam_file ?sorting:bam#product#sorting ~reference_build ~host:(Machine.as_host run_with) output_file_path in let sambamba = Machine.get_tool run_with Machine.Tool.Default.sambamba in workflow_node product ~name ~make:(Machine.run_big_program run_with ~name ~self_ids:["sambamba"; "view"] Program.( Machine.Tool.(init sambamba) && shf "sambamba_v0.6.5 view --format=bam -F '%s' %s > %s" (Filter.to_string filter) bam#product#path output_file_path )) ~edges:([ depends_on Machine.Tool.(ensure sambamba); depends_on bam; on_failure_activate clean_up;])
null
https://raw.githubusercontent.com/hammerlab/biokepi/d64eb2c891b41bda3444445cd2adf4e3251725d4/src/bfx_tools/sambamba.ml
ocaml
Filter language syntax at -view%5D-Filter-expression-syntax
open Biokepi_run_environment open Common module Remove = Workflow_utilities.Remove module Filter = struct type t = [ `String of string ] let of_string s = `String s let to_string f = match f with | `String s -> s module Defaults = struct let only_split_reads = of_string "cigar =~ /^.*N.*$/" let drop_split_reads = of_string "cigar =~ /^[0-9MIDSHPX=]*$/" end end let view ~(run_with : Machine.t) ~bam ~filter output_file_path = let open KEDSL in let name = sprintf "Sambamba.view %s %s" (Filename.basename bam#product#path) (Filter.to_string filter) in let clean_up = Remove.file ~run_with output_file_path in let reference_build = bam#product#reference_build in let product = KEDSL.bam_file ?sorting:bam#product#sorting ~reference_build ~host:(Machine.as_host run_with) output_file_path in let sambamba = Machine.get_tool run_with Machine.Tool.Default.sambamba in workflow_node product ~name ~make:(Machine.run_big_program run_with ~name ~self_ids:["sambamba"; "view"] Program.( Machine.Tool.(init sambamba) && shf "sambamba_v0.6.5 view --format=bam -F '%s' %s > %s" (Filter.to_string filter) bam#product#path output_file_path )) ~edges:([ depends_on Machine.Tool.(ensure sambamba); depends_on bam; on_failure_activate clean_up;])
781eb6d8a17a56bad0f7591085575fb3e687b54cf38c1cca2df47f7c11489d68
antifuchs/cl-beanstalk
package.lisp
(defpackage :beanstalk (:use) (:export #:with-beanstalk-connection #:quit #:connect #:disconnect ;; Conditions: #:beanstalk-error #:bad-reply #:beanstalkd-out-of-memory #:buried-job #:beanstalkd-draining #:beanstalkd-internal-error #:bad-message-format #:expected-crlf #:unknown-command #:deadline-soon #:yaml-parsing-failed Protocol commands : #:use #:put #:reserve #:delete #:release #:bury #:touch #:watch #:ignore #:peek #:peek-ready #:peek-delayed #:peek-buried #:kick #:list-tube-used #:stats-job #:stats-tube #:stats #:list-tubes #:list-tubes-watched)) (defpackage :beanstalk-internal (:use :cl))
null
https://raw.githubusercontent.com/antifuchs/cl-beanstalk/7b925a769d6e61fbcf0c122400146123f18e55cc/package.lisp
lisp
Conditions:
(defpackage :beanstalk (:use) (:export #:with-beanstalk-connection #:quit #:connect #:disconnect #:beanstalk-error #:bad-reply #:beanstalkd-out-of-memory #:buried-job #:beanstalkd-draining #:beanstalkd-internal-error #:bad-message-format #:expected-crlf #:unknown-command #:deadline-soon #:yaml-parsing-failed Protocol commands : #:use #:put #:reserve #:delete #:release #:bury #:touch #:watch #:ignore #:peek #:peek-ready #:peek-delayed #:peek-buried #:kick #:list-tube-used #:stats-job #:stats-tube #:stats #:list-tubes #:list-tubes-watched)) (defpackage :beanstalk-internal (:use :cl))
41eebb62ef7a63acf61344a4889a8b48a92d436694a271d75d7116d63ec7b5a1
davidlazar/ocaml-semantics
fun02.ml
(fun x -> x - x) (-42)
null
https://raw.githubusercontent.com/davidlazar/ocaml-semantics/6f302c6b9cced0407d501d70ad25c2d2aefbb77d/tests/unit/fun02.ml
ocaml
(fun x -> x - x) (-42)
4aa9681b7b429800b573a6cbfa7a7cda99428046b21aca191ccdea0b0295d099
evancz/elm-project-survey
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Prelude hiding (lines) import qualified Control.Monad as M import Data.Aeson ((.=)) import qualified Data.Aeson as Json import Data.Binary (get, put) import qualified Data.Binary as Binary import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as Map import qualified System.Directory as Dir import System.FilePath ((</>)) -- MAIN -- -- Create a directory called logs/ that contains all of the build.log files -- submitted to -project-survey/issues -- The names should be like 4.evancz.log to capture the issue number and OP . -- -- This code generates a file called results.json that has all the data in one place in a format that will be easier to use in Elm . main :: IO () main = do logs <- Dir.listDirectory "logs" json <- mapM convertLog logs LBS.writeFile "results.json" (Json.encode json) convertLog :: String -> IO Json.Value convertLog name = do results <- Binary.decodeFile ("logs" </> name) return (encode name results) -- RESULTS data Results = Results { _info :: SystemInfo , _deps :: Deps , _normal :: FlagResult , _devnull :: FlagResult , _sizes :: Sizes } data SystemInfo = SystemInfo { _platform :: String , _distro :: String , _release :: String , _memory :: Integer , _manufacturer :: String , _brand :: String , _speed :: String , _logicalCores :: Int , _physicalCores :: Int } data Deps = Deps { _direct :: Map.Map String String , _indirect :: Map.Map String String } data FlagResult = FlagResult { _scratch :: Time , _incremental :: [FileResult] } data FileResult = FileResult { _bytes :: Int , _lines :: Int , _time :: Time } data Sizes = Sizes { _initial :: Int , _minified :: Int , _gzipped :: Int } newtype Time = Time { _milliseconds :: Integer } instance Binary.Binary Results where get = M.liftM5 Results get get get get get put (Results a b c d e) = put a >> put b >> put c >> put d >> put e instance Binary.Binary SystemInfo where get = SystemInfo <$> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get put (SystemInfo a b c d e f g h i) = put a >> put b >> put c >> put d >> put e >> put f >> put g >> put h >> put i instance Binary.Binary Deps where get = M.liftM2 Deps get get put (Deps a b) = put a >> put b instance Binary.Binary FlagResult where get = M.liftM2 FlagResult get get put (FlagResult a b) = put a >> put b instance Binary.Binary FileResult where get = M.liftM3 FileResult get get get put (FileResult a b c) = put a >> put b >> put c instance Binary.Binary Sizes where get = M.liftM3 Sizes get get get put (Sizes a b c) = put a >> put b >> put c instance Binary.Binary Time where get = Time <$> get put (Time a) = put a -- JSON encode :: String -> Results -> Json.Value encode fileName (Results info deps normal devnull sizes) = let [issueNumber,user,_] = words (map (\c -> if c == '.' then ' ' else c) fileName) in Json.object [ "user" .= user , "issue" .= Json.toJSON ("-project-survey/issues/" ++ issueNumber) , "systemInfo" .= encodeSystemInfo info , "dependencies" .= encodeDeps deps , "buildTime" .= Json.object [ "normal" .= encodeFlagResult normal , "devnull" .= encodeFlagResult devnull ] , "assetSize" .= encodeSizes sizes ] encodeSystemInfo :: SystemInfo -> Json.Value encodeSystemInfo info = Json.object [ "platform" .= _platform info , "distro" .= _distro info , "release" .= _release info , "memory" .= _memory info , "manufacturer" .= _manufacturer info , "brand" .= _brand info , "speed" .= _speed info , "logicalCores" .= _logicalCores info , "physicalCores" .= _physicalCores info ] encodeDeps :: Deps -> Json.Value encodeDeps (Deps direct indirect) = Json.object [ "direct" .= direct , "indirect" .= indirect ] encodeFlagResult :: FlagResult -> Json.Value encodeFlagResult (FlagResult scratch incremental) = Json.object [ "fromScratch" .= scratch , "incremental" .= incremental ] instance Json.ToJSON FileResult where toJSON (FileResult bytes lines time) = Json.object [ "bytes" .= bytes , "lines" .= lines , "time" .= time ] instance Json.ToJSON Time where toJSON (Time millis) = Json.toJSON millis encodeSizes :: Sizes -> Json.Value encodeSizes (Sizes initial minified gzipped) = Json.object [ "initial" .= initial , "minified" .= minified , "gzipped" .= gzipped ]
null
https://raw.githubusercontent.com/evancz/elm-project-survey/ccd96187ca1e1ddee26a491cdc480337bc944302/2-process/src/Main.hs
haskell
# LANGUAGE OverloadedStrings # MAIN Create a directory called logs/ that contains all of the build.log files submitted to -project-survey/issues This code generates a file called results.json that has all the data in RESULTS JSON
module Main (main) where import Prelude hiding (lines) import qualified Control.Monad as M import Data.Aeson ((.=)) import qualified Data.Aeson as Json import Data.Binary (get, put) import qualified Data.Binary as Binary import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as Map import qualified System.Directory as Dir import System.FilePath ((</>)) The names should be like 4.evancz.log to capture the issue number and OP . one place in a format that will be easier to use in Elm . main :: IO () main = do logs <- Dir.listDirectory "logs" json <- mapM convertLog logs LBS.writeFile "results.json" (Json.encode json) convertLog :: String -> IO Json.Value convertLog name = do results <- Binary.decodeFile ("logs" </> name) return (encode name results) data Results = Results { _info :: SystemInfo , _deps :: Deps , _normal :: FlagResult , _devnull :: FlagResult , _sizes :: Sizes } data SystemInfo = SystemInfo { _platform :: String , _distro :: String , _release :: String , _memory :: Integer , _manufacturer :: String , _brand :: String , _speed :: String , _logicalCores :: Int , _physicalCores :: Int } data Deps = Deps { _direct :: Map.Map String String , _indirect :: Map.Map String String } data FlagResult = FlagResult { _scratch :: Time , _incremental :: [FileResult] } data FileResult = FileResult { _bytes :: Int , _lines :: Int , _time :: Time } data Sizes = Sizes { _initial :: Int , _minified :: Int , _gzipped :: Int } newtype Time = Time { _milliseconds :: Integer } instance Binary.Binary Results where get = M.liftM5 Results get get get get get put (Results a b c d e) = put a >> put b >> put c >> put d >> put e instance Binary.Binary SystemInfo where get = SystemInfo <$> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get put (SystemInfo a b c d e f g h i) = put a >> put b >> put c >> put d >> put e >> put f >> put g >> put h >> put i instance Binary.Binary Deps where get = M.liftM2 Deps get get put (Deps a b) = put a >> put b instance Binary.Binary FlagResult where get = M.liftM2 FlagResult get get put (FlagResult a b) = put a >> put b instance Binary.Binary FileResult where get = M.liftM3 FileResult get get get put (FileResult a b c) = put a >> put b >> put c instance Binary.Binary Sizes where get = M.liftM3 Sizes get get get put (Sizes a b c) = put a >> put b >> put c instance Binary.Binary Time where get = Time <$> get put (Time a) = put a encode :: String -> Results -> Json.Value encode fileName (Results info deps normal devnull sizes) = let [issueNumber,user,_] = words (map (\c -> if c == '.' then ' ' else c) fileName) in Json.object [ "user" .= user , "issue" .= Json.toJSON ("-project-survey/issues/" ++ issueNumber) , "systemInfo" .= encodeSystemInfo info , "dependencies" .= encodeDeps deps , "buildTime" .= Json.object [ "normal" .= encodeFlagResult normal , "devnull" .= encodeFlagResult devnull ] , "assetSize" .= encodeSizes sizes ] encodeSystemInfo :: SystemInfo -> Json.Value encodeSystemInfo info = Json.object [ "platform" .= _platform info , "distro" .= _distro info , "release" .= _release info , "memory" .= _memory info , "manufacturer" .= _manufacturer info , "brand" .= _brand info , "speed" .= _speed info , "logicalCores" .= _logicalCores info , "physicalCores" .= _physicalCores info ] encodeDeps :: Deps -> Json.Value encodeDeps (Deps direct indirect) = Json.object [ "direct" .= direct , "indirect" .= indirect ] encodeFlagResult :: FlagResult -> Json.Value encodeFlagResult (FlagResult scratch incremental) = Json.object [ "fromScratch" .= scratch , "incremental" .= incremental ] instance Json.ToJSON FileResult where toJSON (FileResult bytes lines time) = Json.object [ "bytes" .= bytes , "lines" .= lines , "time" .= time ] instance Json.ToJSON Time where toJSON (Time millis) = Json.toJSON millis encodeSizes :: Sizes -> Json.Value encodeSizes (Sizes initial minified gzipped) = Json.object [ "initial" .= initial , "minified" .= minified , "gzipped" .= gzipped ]
805741f29175fb472f332961c143f5105dfe01a7de464272f3605e7a1eff731f
cryptosense/enumerators
enumerator.ml
type 'a t = { size : Beint.t; nth : Beint.t -> 'a; shape : string; (* how the enumerator was created, useful for debugging *) depth : int (* number of composed functions to create values, useful for debugging *) } exception Out_of_bounds let nth s i = let i = Beint.of_int64 i in if Beint.lt i s.size && Beint.(le zero i) then s.nth i else raise Out_of_bounds let is_empty s = Beint.equal Beint.zero s.size let size s = Beint.to_int64 s.size let size_int s = Beint.to_int s.size let fold_left (f : 'a -> 'b -> 'a) (acc : 'a) (e : 'b t) : 'a = let rec aux i acc = if Beint.equal i e.size then acc else aux (Beint.succ i) (f acc (e.nth i)) in aux Beint.zero acc let map f e = let e_nth = e.nth in let nth i = f (e_nth i) in { size = e.size; nth; shape = "map"; depth = e.depth + 1; } let iteri (f : int64 -> 'a -> unit) (e : 'a t) : unit = let rec aux i = if not (Beint.equal i e.size) then begin f (Beint.to_int64 i) (e.nth i); aux (Beint.succ i) end in aux Beint.zero let iter f a = iteri (fun _ x -> f x) a let max_i (x : int) y = if x < y then y else x let min_i (x : int) y = if x < y then x else y let of_array (v : 'a array) : 'a t = let size = Beint.of_int (Array.length v) in let nth i = let i = Beint.to_int i in Array.get v i in { size; nth; shape = "of_array"; depth = 0 } let make l = let v = Array.of_list l in of_array v let of_list = make type ('t, 'elt) set = (module Set.S with type t = 't and type elt = 'elt) The following version is the most efficient way to build an enumerator out of a set . I experimented with two versions that use Set.fold , but they were much less efficient . I experimented with two versions that use Set.fold, but they were much less efficient. *) let of_set (type t) (type elt) ((module Set) : (t, elt) set) (t : t) = make (Set.elements t) let empty = let nth _ = raise Out_of_bounds in { size = Beint.zero; nth; shape = "empty"; depth = 0 } let constant e = let nth i = assert (Beint.equal Beint.zero i); e in {size = Beint.one; nth; shape = "constant"; depth = 0} let constant_delayed e = let nth i = assert (Beint.equal Beint.zero i); e () in {size = Beint.one; nth; shape = "constant_delayed"; depth = 0} (** [range a b] produces an enumerator for the integers between [a] and [b] included. If [b < a], the enumerator is empty. *) let range a b = let size = succ (b - a) in let size = max_i 0 size in let nth i = let i = Beint.to_int i in assert (i < size); a + i in let size = Beint.of_int size in { size; nth; shape = "range"; depth = 1 } let memoize e = Array.init (Beint.to_int e.size) (fun i -> Beint.of_int i |> e.nth) |> of_array let filter (f : 'a -> bool) (e : 'a t) : 'a t = let rec indices acc i = if Beint.equal i e.size then List.rev acc else let elt = e.nth i in if f elt then indices (elt :: acc) (Beint.succ i) else indices acc (Beint.succ i) in let indices = (indices [] Beint.zero) in let indices = Array.of_list indices in let enum = of_array indices in {enum with shape = "filter"} let append e1 e2 = if is_empty e1 then e2 (* optimization *) else if is_empty e2 then e1 (* optimization *) else let e1_size = e1.size in let e1_nth = e1.nth in let e2_size = e2.size in let e2_nth = e2.nth in let nth i = if Beint.lt i e1_size then e1_nth i else e2_nth (Beint.sub i e1_size) in { size = Beint.add e1_size e2_size; nth; shape = "append"; depth = max_i e1.depth e2.depth + 1 } let sub s start len = if Beint.lt start Beint.zero || Beint.lt len Beint.zero || Beint.lt s.size (Beint.add start len) then invalid_arg (Printf.sprintf "sub (start:%s) (len%s) (size:%s)" (Beint.to_string start) (Beint.to_string len) (Beint.to_string s.size)) else let size = len in let s_nth = s.nth in let nth i = s_nth (Beint.add start i) in { size; nth; shape = "sub"; depth = 1 + s.depth } let map_product e1 e2 f = let e1_size = e1.size in let size = Beint.mul e1_size e2.size in let e1_nth = e1.nth in let e2_nth = e2.nth in let nth i = f (e1_nth (Beint.rem i e1_size)) (e2_nth (Beint.div i e1_size)) in { size; nth; shape = "prod"; depth = 1 + max_i e1.depth e2.depth } let product a b = if is_empty a || is_empty b then empty (* optimization *) else map_product a b (fun a b -> (a, b)) Interleaving two enumerators of the same size . let interleave' e1 e2 = assert (Beint.equal e1.size e2.size); let e1_nth = e1.nth in let e2_nth = e2.nth in let nth i = if Beint.(equal zero (rem i two)) then e1_nth (Beint.shift_right i 1) else e2_nth (Beint.shift_right i 1) in {size = Beint.add e1.size e2.size; nth; shape = "interleave"; depth = 1 + max_i e1.depth e2.depth } let interleave e1 e2 = if Beint.lt e1.size e2.size then begin let e = interleave' (e1) (sub e2 Beint.zero e1.size) in append e (sub e2 e1.size (Beint.sub e2.size e1.size)) end else if Beint.equal e1.size e2.size then interleave' e1 e2 e1.size > e2.size let e = interleave' (sub e1 Beint.zero e2.size) e2 in append e (sub e1 e2.size (Beint.sub e1.size e2.size)) (* Return an equivalent sequence of enumerators where empty enumerators have been removed for optimization. *) let prune (e : 'a t t) : 'a t t = First , compute the number of non - empty enumerations in e. let rec non_empty i acc = if Beint.equal i e.size then acc else if Beint.equal Beint.zero (e.nth i).size then non_empty (Beint.succ i) acc else non_empty (Beint.succ i) (Beint.succ acc) in let non_empty = non_empty Beint.zero Beint.zero in if Beint.equal non_empty Beint.zero then empty else begin let v = Array.make (Beint.to_int non_empty) empty in let rec aux i cursor = if not (Beint.equal i e.size) then if is_empty (e.nth i) then aux (Beint.succ i) cursor else begin Array.set v cursor (e.nth i); aux (Beint.succ i) (succ cursor) end in aux Beint.zero 0; of_array v end let squash e = let e = prune e in let size, depth = let rec aux i size depth = if Beint.equal i e.size then size, depth else let size = Beint.add (e.nth i).size size in let depth = max_i depth (e.nth i).depth in aux (Beint.succ i) size depth in aux Beint.zero Beint.zero min_int in let e_nth = e.nth in let rec nth k i = let f = e_nth k in let f_size = f.size in if Beint.lt i f_size then f.nth i else nth (Beint.succ k) (Beint.sub i f_size) in { size; depth; nth = nth Beint.zero; shape = "squash"; } (** [list e] takes as input a list of enumerators and enumerate the the cartesian product of these enumerators. Hence, each element in the resulting enumerator has the same length. *) let rec list (e : 'a t list) : 'a list t = match e with | [] -> constant [] | t::q -> map_product t (list q) (fun t q -> t :: q) let partition f e = let e_size = e.size in let e_nth = e.nth in let rec indices ok ko i = if Beint.equal i e_size then List.rev ok, List.rev ko else let elt = e_nth i in if f elt then indices (elt :: ok) ko (Beint.succ i) else indices ok (elt :: ko) (Beint.succ i) in let (ok, ko) = indices [] [] Beint.zero in if ok = [] then empty, e else if ko = [] then (e, empty) else let ok = of_array (Array.of_list ok) in let ko = of_array (Array.of_list ko) in (ok, ko) let scalar_left : 'a -> 'b t -> ('a * 'b) t = fun k t -> { size = t.size; nth = (fun i -> k, t.nth i); shape = "scalar_left"; depth = succ t.depth } let scalar_right : 'a t -> 'b -> ('a * 'b) t = fun t k -> { size = t.size; nth = (fun i -> t.nth i, k); shape = "scalar_right"; depth = succ t.depth } (******************************************************************************) (******************************************************************************) module Bitset = struct (* Gosper's Hack *) let step (element : int) (size : int) = begin let c = element land (- element) in let r = element + c in let next = (((r lxor element) lsr 2) / c) lor r in if (next land size) <> 0 then ((next land (size - 1)) lsl 2) lor 3 else next end end To avoid a division by zero , k must be greater than one . let from_n_choose_k ~n ~k = let element = 1 lsl k - 1 in (* k ones *) let size = 1 lsl n in let rec generate acc set = if set < size then let c = set land ( - set) in let r = set + c in let next = (((r lxor set) lsr 2) / c) lor r in generate (set::acc) next else List.rev acc in make (generate [] element) ;; (** [binomial n k] computes the binomial coefficient, that is the number of ways to pick [k] elements among [n]. *) let rec binomial n k = if k > n then 0 else if k = 0 then 1 else if k = n then 1 else binomial (n - 1) (k - 1) + binomial (n - 1) k let bitset ?k n : int t = let size = match k with | None -> 1 lsl n | Some k -> let r = ref 0 in for i = 0 to min_i k n do r := !r + binomial n i done; !r in let v = Array.make size 0 in let r = ref 1 in let n = 1 lsl n in for i = 1 to size - 1 do Array.set v i !r; r := Bitset.step !r n done; of_array v (******************************************************************************) (* Round robin *) (******************************************************************************) module Round_robin = struct * We want to compute a round - robin enumeration . The problem is to find the nth element in this enumeration . This is an easy task if all the enumerations have the same length , but more complicated otherwise . To solve this issue , we decompose this round robin in chunks . The first chunk is a round - robin enumeration of enumerators that have the same size . The second chunk is a round - robin enumeration of enumerators that have the same size , and are the remainders of what was not done in the first chunk . find the nth element in this enumeration. This is an easy task if all the enumerations have the same length, but more complicated otherwise. To solve this issue, we decompose this round robin in chunks. The first chunk is a round-robin enumeration of enumerators that have the same size. The second chunk is a round-robin enumeration of enumerators that have the same size, and are the remainders of what was not done in the first chunk. *) (* Check that all elements of [e] have size [size]. *) let equal_size size (e : 'a t t) : bool = fold_left (fun acc x -> acc && Beint.equal x.size size) true e let round_robin_equal_size size (e : 'a t t) : 'a t = assert (equal_size size e); let e_nth = e.nth and e_size = e.size in let nth i = (e_nth (Beint.rem i e_size)).nth (Beint.div i e_size) in { size = Beint.mul e.size size; depth = 1 + fold_left (fun acc x -> max_i acc x.depth) 0 e; shape = "round_robin"; nth } let round_robin (e : 'a t t) : 'a t = let rec chunks (e : 'a t t) (acc : 'a t list) = let e = prune e in if is_empty e then begin List.rev acc end else let min_size = fold_left (fun acc x -> Beint.min acc x.size) Beint.max_int e in let chunk = map (fun f -> sub f Beint.zero min_size) e in let chunk = round_robin_equal_size min_size chunk in let rest = map (fun f -> sub f min_size (Beint.sub f.size min_size)) e in chunks rest (chunk::acc) in let chunks = chunks e [] in begin match chunks with | [] -> empty | [enum] -> enum | chunks -> squash (make chunks) end end let round_robin = Round_robin.round_robin (******************************************************************************) (* Subset *) (******************************************************************************) module Subset = struct let enum_of_bitmask (g : 'a array) (bits : int) = let rec aux i acc= if i = Array.length g then List.rev acc else if bits land (1 lsl i) <> 0 then aux (i + 1) (Array.get g i :: acc) else aux (i+1) acc in list (aux 0 []) let of_list ?k list = match list with | [] -> empty | _ :: _ -> let g = Array.of_list list in map (enum_of_bitmask g) (bitset ?k (Array.length g)) end let subset ?k l = Subset.of_list ?k l let choose_k_from_list ~k l = if k <= 0 then invalid_arg "choose_k_from_list: k must be greater than zero"; match l with | [] -> empty | _ :: _ -> let k = min k (List.length l) in let g = Array.of_list l in let n = Array.length g in map (Subset.enum_of_bitmask g) (from_n_choose_k ~k ~n) let elements s = let r = ref [] in let i = ref Beint.zero in while Beint.lt !i s.size do r := (s.nth !i) :: !r; i := Beint.succ !i done; List.rev !r let firstn len s = let len = Beint.of_int64 len in if Beint.lt s.size len then elements s, empty else elements (sub s Beint.zero len), sub s len (Beint.sub s.size len) let shuffle_array arr = for n = Array.length arr - 1 downto 1 do let k = Random.int (n + 1) in let temp = arr.(n) in arr.(n) <- arr.(k); arr.(k) <- temp done let shuffle e = let permutation = Array.init (Beint.to_int e.size) Beint.of_int in shuffle_array permutation; { size = e.size ; nth = (fun i -> e.nth (permutation.(Beint.to_int i))) ; shape = "shuffle" ; depth = 1 + e.depth } (******************************************************************************) (* Maybe combinators *) (******************************************************************************) let maybe f e = interleave e (map f e) let maybe_cons (hd : 'a) (e : 'a list t) : 'a list t = maybe (fun x -> hd :: x) e let maybe_some_of ~k (list : 'a list) (e : 'a list t) : 'a list t = if list == [] then e else let options = subset ~k (List.map constant list) |> squash in map (fun options -> map (fun base -> options @ base) e) options |> round_robin let depth s = s.depth
null
https://raw.githubusercontent.com/cryptosense/enumerators/0ba393e993a3a1574453395a5a424a3bccda522c/src/enumerator.ml
ocaml
how the enumerator was created, useful for debugging number of composed functions to create values, useful for debugging * [range a b] produces an enumerator for the integers between [a] and [b] included. If [b < a], the enumerator is empty. optimization optimization optimization Return an equivalent sequence of enumerators where empty enumerators have been removed for optimization. * [list e] takes as input a list of enumerators and enumerate the the cartesian product of these enumerators. Hence, each element in the resulting enumerator has the same length. **************************************************************************** **************************************************************************** Gosper's Hack k ones * [binomial n k] computes the binomial coefficient, that is the number of ways to pick [k] elements among [n]. **************************************************************************** Round robin **************************************************************************** Check that all elements of [e] have size [size]. **************************************************************************** Subset **************************************************************************** **************************************************************************** Maybe combinators ****************************************************************************
type 'a t = { size : Beint.t; nth : Beint.t -> 'a; } exception Out_of_bounds let nth s i = let i = Beint.of_int64 i in if Beint.lt i s.size && Beint.(le zero i) then s.nth i else raise Out_of_bounds let is_empty s = Beint.equal Beint.zero s.size let size s = Beint.to_int64 s.size let size_int s = Beint.to_int s.size let fold_left (f : 'a -> 'b -> 'a) (acc : 'a) (e : 'b t) : 'a = let rec aux i acc = if Beint.equal i e.size then acc else aux (Beint.succ i) (f acc (e.nth i)) in aux Beint.zero acc let map f e = let e_nth = e.nth in let nth i = f (e_nth i) in { size = e.size; nth; shape = "map"; depth = e.depth + 1; } let iteri (f : int64 -> 'a -> unit) (e : 'a t) : unit = let rec aux i = if not (Beint.equal i e.size) then begin f (Beint.to_int64 i) (e.nth i); aux (Beint.succ i) end in aux Beint.zero let iter f a = iteri (fun _ x -> f x) a let max_i (x : int) y = if x < y then y else x let min_i (x : int) y = if x < y then x else y let of_array (v : 'a array) : 'a t = let size = Beint.of_int (Array.length v) in let nth i = let i = Beint.to_int i in Array.get v i in { size; nth; shape = "of_array"; depth = 0 } let make l = let v = Array.of_list l in of_array v let of_list = make type ('t, 'elt) set = (module Set.S with type t = 't and type elt = 'elt) The following version is the most efficient way to build an enumerator out of a set . I experimented with two versions that use Set.fold , but they were much less efficient . I experimented with two versions that use Set.fold, but they were much less efficient. *) let of_set (type t) (type elt) ((module Set) : (t, elt) set) (t : t) = make (Set.elements t) let empty = let nth _ = raise Out_of_bounds in { size = Beint.zero; nth; shape = "empty"; depth = 0 } let constant e = let nth i = assert (Beint.equal Beint.zero i); e in {size = Beint.one; nth; shape = "constant"; depth = 0} let constant_delayed e = let nth i = assert (Beint.equal Beint.zero i); e () in {size = Beint.one; nth; shape = "constant_delayed"; depth = 0} let range a b = let size = succ (b - a) in let size = max_i 0 size in let nth i = let i = Beint.to_int i in assert (i < size); a + i in let size = Beint.of_int size in { size; nth; shape = "range"; depth = 1 } let memoize e = Array.init (Beint.to_int e.size) (fun i -> Beint.of_int i |> e.nth) |> of_array let filter (f : 'a -> bool) (e : 'a t) : 'a t = let rec indices acc i = if Beint.equal i e.size then List.rev acc else let elt = e.nth i in if f elt then indices (elt :: acc) (Beint.succ i) else indices acc (Beint.succ i) in let indices = (indices [] Beint.zero) in let indices = Array.of_list indices in let enum = of_array indices in {enum with shape = "filter"} let append e1 e2 = if is_empty e1 then else if is_empty e2 then else let e1_size = e1.size in let e1_nth = e1.nth in let e2_size = e2.size in let e2_nth = e2.nth in let nth i = if Beint.lt i e1_size then e1_nth i else e2_nth (Beint.sub i e1_size) in { size = Beint.add e1_size e2_size; nth; shape = "append"; depth = max_i e1.depth e2.depth + 1 } let sub s start len = if Beint.lt start Beint.zero || Beint.lt len Beint.zero || Beint.lt s.size (Beint.add start len) then invalid_arg (Printf.sprintf "sub (start:%s) (len%s) (size:%s)" (Beint.to_string start) (Beint.to_string len) (Beint.to_string s.size)) else let size = len in let s_nth = s.nth in let nth i = s_nth (Beint.add start i) in { size; nth; shape = "sub"; depth = 1 + s.depth } let map_product e1 e2 f = let e1_size = e1.size in let size = Beint.mul e1_size e2.size in let e1_nth = e1.nth in let e2_nth = e2.nth in let nth i = f (e1_nth (Beint.rem i e1_size)) (e2_nth (Beint.div i e1_size)) in { size; nth; shape = "prod"; depth = 1 + max_i e1.depth e2.depth } let product a b = if is_empty a || is_empty b then else map_product a b (fun a b -> (a, b)) Interleaving two enumerators of the same size . let interleave' e1 e2 = assert (Beint.equal e1.size e2.size); let e1_nth = e1.nth in let e2_nth = e2.nth in let nth i = if Beint.(equal zero (rem i two)) then e1_nth (Beint.shift_right i 1) else e2_nth (Beint.shift_right i 1) in {size = Beint.add e1.size e2.size; nth; shape = "interleave"; depth = 1 + max_i e1.depth e2.depth } let interleave e1 e2 = if Beint.lt e1.size e2.size then begin let e = interleave' (e1) (sub e2 Beint.zero e1.size) in append e (sub e2 e1.size (Beint.sub e2.size e1.size)) end else if Beint.equal e1.size e2.size then interleave' e1 e2 e1.size > e2.size let e = interleave' (sub e1 Beint.zero e2.size) e2 in append e (sub e1 e2.size (Beint.sub e1.size e2.size)) let prune (e : 'a t t) : 'a t t = First , compute the number of non - empty enumerations in e. let rec non_empty i acc = if Beint.equal i e.size then acc else if Beint.equal Beint.zero (e.nth i).size then non_empty (Beint.succ i) acc else non_empty (Beint.succ i) (Beint.succ acc) in let non_empty = non_empty Beint.zero Beint.zero in if Beint.equal non_empty Beint.zero then empty else begin let v = Array.make (Beint.to_int non_empty) empty in let rec aux i cursor = if not (Beint.equal i e.size) then if is_empty (e.nth i) then aux (Beint.succ i) cursor else begin Array.set v cursor (e.nth i); aux (Beint.succ i) (succ cursor) end in aux Beint.zero 0; of_array v end let squash e = let e = prune e in let size, depth = let rec aux i size depth = if Beint.equal i e.size then size, depth else let size = Beint.add (e.nth i).size size in let depth = max_i depth (e.nth i).depth in aux (Beint.succ i) size depth in aux Beint.zero Beint.zero min_int in let e_nth = e.nth in let rec nth k i = let f = e_nth k in let f_size = f.size in if Beint.lt i f_size then f.nth i else nth (Beint.succ k) (Beint.sub i f_size) in { size; depth; nth = nth Beint.zero; shape = "squash"; } let rec list (e : 'a t list) : 'a list t = match e with | [] -> constant [] | t::q -> map_product t (list q) (fun t q -> t :: q) let partition f e = let e_size = e.size in let e_nth = e.nth in let rec indices ok ko i = if Beint.equal i e_size then List.rev ok, List.rev ko else let elt = e_nth i in if f elt then indices (elt :: ok) ko (Beint.succ i) else indices ok (elt :: ko) (Beint.succ i) in let (ok, ko) = indices [] [] Beint.zero in if ok = [] then empty, e else if ko = [] then (e, empty) else let ok = of_array (Array.of_list ok) in let ko = of_array (Array.of_list ko) in (ok, ko) let scalar_left : 'a -> 'b t -> ('a * 'b) t = fun k t -> { size = t.size; nth = (fun i -> k, t.nth i); shape = "scalar_left"; depth = succ t.depth } let scalar_right : 'a t -> 'b -> ('a * 'b) t = fun t k -> { size = t.size; nth = (fun i -> t.nth i, k); shape = "scalar_right"; depth = succ t.depth } module Bitset = struct let step (element : int) (size : int) = begin let c = element land (- element) in let r = element + c in let next = (((r lxor element) lsr 2) / c) lor r in if (next land size) <> 0 then ((next land (size - 1)) lsl 2) lor 3 else next end end To avoid a division by zero , k must be greater than one . let from_n_choose_k ~n ~k = let size = 1 lsl n in let rec generate acc set = if set < size then let c = set land ( - set) in let r = set + c in let next = (((r lxor set) lsr 2) / c) lor r in generate (set::acc) next else List.rev acc in make (generate [] element) ;; let rec binomial n k = if k > n then 0 else if k = 0 then 1 else if k = n then 1 else binomial (n - 1) (k - 1) + binomial (n - 1) k let bitset ?k n : int t = let size = match k with | None -> 1 lsl n | Some k -> let r = ref 0 in for i = 0 to min_i k n do r := !r + binomial n i done; !r in let v = Array.make size 0 in let r = ref 1 in let n = 1 lsl n in for i = 1 to size - 1 do Array.set v i !r; r := Bitset.step !r n done; of_array v module Round_robin = struct * We want to compute a round - robin enumeration . The problem is to find the nth element in this enumeration . This is an easy task if all the enumerations have the same length , but more complicated otherwise . To solve this issue , we decompose this round robin in chunks . The first chunk is a round - robin enumeration of enumerators that have the same size . The second chunk is a round - robin enumeration of enumerators that have the same size , and are the remainders of what was not done in the first chunk . find the nth element in this enumeration. This is an easy task if all the enumerations have the same length, but more complicated otherwise. To solve this issue, we decompose this round robin in chunks. The first chunk is a round-robin enumeration of enumerators that have the same size. The second chunk is a round-robin enumeration of enumerators that have the same size, and are the remainders of what was not done in the first chunk. *) let equal_size size (e : 'a t t) : bool = fold_left (fun acc x -> acc && Beint.equal x.size size) true e let round_robin_equal_size size (e : 'a t t) : 'a t = assert (equal_size size e); let e_nth = e.nth and e_size = e.size in let nth i = (e_nth (Beint.rem i e_size)).nth (Beint.div i e_size) in { size = Beint.mul e.size size; depth = 1 + fold_left (fun acc x -> max_i acc x.depth) 0 e; shape = "round_robin"; nth } let round_robin (e : 'a t t) : 'a t = let rec chunks (e : 'a t t) (acc : 'a t list) = let e = prune e in if is_empty e then begin List.rev acc end else let min_size = fold_left (fun acc x -> Beint.min acc x.size) Beint.max_int e in let chunk = map (fun f -> sub f Beint.zero min_size) e in let chunk = round_robin_equal_size min_size chunk in let rest = map (fun f -> sub f min_size (Beint.sub f.size min_size)) e in chunks rest (chunk::acc) in let chunks = chunks e [] in begin match chunks with | [] -> empty | [enum] -> enum | chunks -> squash (make chunks) end end let round_robin = Round_robin.round_robin module Subset = struct let enum_of_bitmask (g : 'a array) (bits : int) = let rec aux i acc= if i = Array.length g then List.rev acc else if bits land (1 lsl i) <> 0 then aux (i + 1) (Array.get g i :: acc) else aux (i+1) acc in list (aux 0 []) let of_list ?k list = match list with | [] -> empty | _ :: _ -> let g = Array.of_list list in map (enum_of_bitmask g) (bitset ?k (Array.length g)) end let subset ?k l = Subset.of_list ?k l let choose_k_from_list ~k l = if k <= 0 then invalid_arg "choose_k_from_list: k must be greater than zero"; match l with | [] -> empty | _ :: _ -> let k = min k (List.length l) in let g = Array.of_list l in let n = Array.length g in map (Subset.enum_of_bitmask g) (from_n_choose_k ~k ~n) let elements s = let r = ref [] in let i = ref Beint.zero in while Beint.lt !i s.size do r := (s.nth !i) :: !r; i := Beint.succ !i done; List.rev !r let firstn len s = let len = Beint.of_int64 len in if Beint.lt s.size len then elements s, empty else elements (sub s Beint.zero len), sub s len (Beint.sub s.size len) let shuffle_array arr = for n = Array.length arr - 1 downto 1 do let k = Random.int (n + 1) in let temp = arr.(n) in arr.(n) <- arr.(k); arr.(k) <- temp done let shuffle e = let permutation = Array.init (Beint.to_int e.size) Beint.of_int in shuffle_array permutation; { size = e.size ; nth = (fun i -> e.nth (permutation.(Beint.to_int i))) ; shape = "shuffle" ; depth = 1 + e.depth } let maybe f e = interleave e (map f e) let maybe_cons (hd : 'a) (e : 'a list t) : 'a list t = maybe (fun x -> hd :: x) e let maybe_some_of ~k (list : 'a list) (e : 'a list t) : 'a list t = if list == [] then e else let options = subset ~k (List.map constant list) |> squash in map (fun options -> map (fun base -> options @ base) e) options |> round_robin let depth s = s.depth
3a3d9f8df25bcafbaf78b68370e58c77174b2a99b0f722074a263dd2c7c6c241
achirkin/vulkan
ProcessVkXml.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE Strict #-} module ProcessVkXml ( processVkXmlFile , generateVkSource , processVulkanHFile ) where import Control.Monad (unless) import Control.Monad.Trans.Resource import Data.Conduit import Data.Conduit.Binary (sourceFile) import Data.Semigroup import qualified Data.Text.IO as Text (readFile, writeFile) import Path import Path.IO import Text.RE.TDFA.Text import Text.XML as Xml import Text.XML.Stream.Parse as Xml import VkXml.Parser import VkXml.Sections import Write processVkXmlFile :: Path a File -- ^ path to vk.xml -> Path b Dir -- ^ output directory for saving generated sources -> Path c File -- ^ path to cabal file to generate -> IO () processVkXmlFile vkXmlFile outputDir outCabalFile = do doesFileExist vkXmlFile >>= flip unless (error $ "vk.xml file located at " <> show vkXmlFile <> " is not found!") createDirIfMissing True outputDir putStrLn $ "Parsing file " <> show vkXmlFile <> ";" putStrLn $ "Output folder is " <> show outputDir <> ";" x <- runResourceT $ sourceFile (toFilePath vkXmlFile) =$= Xml.parseBytesPos Xml.def $$ parseWithLoc initLoc parseVkXml putStrLn "Done parsing, start generating..." y <- generateVkSource outputDir outCabalFile x putStrLn "Done generating." return y where initLoc = defParseLoc vkXmlFile processVulkanHFile :: Path a File -- ^ input file vulkan.h from submodule -> Path b File -- ^ outout file vulkan.h in includes -> IO () processVulkanHFile inputVulkanH outputVulkanH = do doesFileExist inputVulkanH >>= flip unless (error $ "vulkan.h file located at " <> show inputVulkanH <> " is not found!") vulkanHTxt <- Text.readFile (toFilePath inputVulkanH) Text.writeFile (toFilePath outputVulkanH) $ vulkanHTxt *=~/ [ed|^#include[[:space:]]"vk_platform.h"///#include "vulkan/vk_platform.h"|]
null
https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/genvulkan/src/ProcessVkXml.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE QuasiQuotes # # LANGUAGE Strict # ^ path to vk.xml ^ output directory for saving generated sources ^ path to cabal file to generate ^ input file vulkan.h from submodule ^ outout file vulkan.h in includes
module ProcessVkXml ( processVkXmlFile , generateVkSource , processVulkanHFile ) where import Control.Monad (unless) import Control.Monad.Trans.Resource import Data.Conduit import Data.Conduit.Binary (sourceFile) import Data.Semigroup import qualified Data.Text.IO as Text (readFile, writeFile) import Path import Path.IO import Text.RE.TDFA.Text import Text.XML as Xml import Text.XML.Stream.Parse as Xml import VkXml.Parser import VkXml.Sections import Write processVkXmlFile :: -> IO () processVkXmlFile vkXmlFile outputDir outCabalFile = do doesFileExist vkXmlFile >>= flip unless (error $ "vk.xml file located at " <> show vkXmlFile <> " is not found!") createDirIfMissing True outputDir putStrLn $ "Parsing file " <> show vkXmlFile <> ";" putStrLn $ "Output folder is " <> show outputDir <> ";" x <- runResourceT $ sourceFile (toFilePath vkXmlFile) =$= Xml.parseBytesPos Xml.def $$ parseWithLoc initLoc parseVkXml putStrLn "Done parsing, start generating..." y <- generateVkSource outputDir outCabalFile x putStrLn "Done generating." return y where initLoc = defParseLoc vkXmlFile processVulkanHFile :: -> IO () processVulkanHFile inputVulkanH outputVulkanH = do doesFileExist inputVulkanH >>= flip unless (error $ "vulkan.h file located at " <> show inputVulkanH <> " is not found!") vulkanHTxt <- Text.readFile (toFilePath inputVulkanH) Text.writeFile (toFilePath outputVulkanH) $ vulkanHTxt *=~/ [ed|^#include[[:space:]]"vk_platform.h"///#include "vulkan/vk_platform.h"|]
aa355175044702fe3c11e6478c4f51752fa4b3a90f9aa661b221f0834a662cc8
EFanZh/EOPL-Exercises
exercise-4.26.rkt
#lang eopl ;; Exercise 4.26 [★★★] Extend the solution to the preceding exercise so that procedures declared in a single block ;; aremutually recursive. Consider restricting the language so that the variable declarations in a block are followed by ;; the procedure declarations. ;; Grammar. (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (statement) a-program] [statement (identifier "=" expression) assign-statement] [statement ("print" expression) print-statement] [statement ("{" (separated-list statement ";") "}") brace-statement] [statement ("if" expression statement statement) if-statement] [statement ("while" expression statement) while-statement] [statement ("var" (separated-list identifier "=" expression ",") ";" statement) block-statement] [statement ("read" identifier) read-statement] [statement ("do" statement "while" expression) do-while-statement] [expression (number) const-exp] [expression ("+" "(" expression "," expression ")") add-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("*" "(" expression "," expression ")") multiply-exp] [expression ("not" "(" expression ")") not-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("let" (arbno identifier "=" expression) "in" expression) let-exp] [expression ("proc" "(" (separated-list identifier ",") ")" expression) proc-exp] [expression ("(" expression (arbno expression) ")") call-exp] [expression ("letrec" (arbno identifier "(" (separated-list identifier ",") ")" "=" expression) "in" expression) letrec-exp] [expression ("begin" expression (arbno ";" expression) "end") begin-exp] [expression ("set" identifier "=" expression) assign-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) ;; Data structures. (define-datatype proc proc? [procedure [bvars (list-of symbol?)] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) ;; Environments. (define reference? (lambda (v) (integer? v))) (define-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval reference?] [saved-env environment?]]) (define location (lambda (sym syms) (cond [(null? syms) #f] [(eqv? sym (car syms)) 0] [(location sym (cdr syms)) => (lambda (n) (+ n 1))] [else #f]))) (define apply-env (lambda (env search-var) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-var)] [extend-env (bvar bval saved-env) (if (eqv? search-var bvar) bval (apply-env saved-env search-var))]))) ;; Store. (define the-store 'uninitialized) (define empty-store (lambda () '())) (define initialize-store! (lambda () (set! the-store (empty-store)))) (define newref (lambda (val) (let ([next-ref (length the-store)]) (set! the-store (append the-store (list val))) next-ref))) (define deref (lambda (ref) (list-ref the-store ref))) (define report-invalid-reference (lambda (ref the-store) (eopl:error 'setref "illegal reference ~s in store ~s" ref the-store))) (define setref! (lambda (ref val) (set! the-store (letrec ([setref-inner (lambda (store1 ref1) (cond [(null? store1) (report-invalid-reference ref the-store)] [(zero? ref1) (cons val (cdr store1))] [else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))]))]) (setref-inner the-store ref))))) ;; Interpreter. (define apply-procedure (lambda (proc1 args) (cases proc proc1 [procedure (vars body saved-env) (let ([new-env (let loop ([vars vars] [args args] [env saved-env]) (if (null? vars) env (loop (cdr vars) (cdr args) (extend-env (car vars) (newref (car args)) env))))]) (value-of body new-env))]))) (define value-of (lambda (exp env) (cases expression exp [const-exp (num) (num-val num)] [var-exp (var) (deref (apply-env env var))] [add-exp (exp1 exp2) (let ([val1 (value-of exp1 env)] [val2 (value-of exp2 env)]) (let ([num1 (expval->num val1)] [num2 (expval->num val2)]) (num-val (+ num1 num2))))] [diff-exp (exp1 exp2) (let ([val1 (value-of exp1 env)] [val2 (value-of exp2 env)]) (let ([num1 (expval->num val1)] [num2 (expval->num val2)]) (num-val (- num1 num2))))] [multiply-exp (exp1 exp2) (let ([val1 (value-of exp1 env)] [val2 (value-of exp2 env)]) (let ([num1 (expval->num val1)] [num2 (expval->num val2)]) (num-val (* num1 num2))))] [not-exp (exp) (let ([val (value-of exp env)]) (bool-val (not (expval->bool val))))] [zero?-exp (exp1) (let ([val1 (value-of exp1 env)]) (let ([num1 (expval->num val1)]) (if (zero? num1) (bool-val #t) (bool-val #f))))] [if-exp (exp1 exp2 exp3) (let ([val1 (value-of exp1 env)]) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))] [let-exp (vars exps body) (let ([body-env (let loop ([vars vars] [exps exps] [env1 env]) (if (null? vars) env1 (loop (cdr vars) (cdr exps) (extend-env (car vars) (newref (value-of (car exps) env)) env1))))]) (value-of body body-env))] [proc-exp (vars body) (proc-val (procedure vars body env))] [call-exp (rator rands) (let ([proc (expval->proc (value-of rator env))] [args (map (lambda (rand) (value-of rand env)) rands)]) (apply-procedure proc args))] [letrec-exp (p-names b-vars p-bodies letrec-body) (let* ([refs (map (lambda (p-name) (newref 0)) p-names)] [rec-env (let loop ([p-names p-names] [refs refs] [env env]) (if (null? p-names) env (loop (cdr p-names) (cdr refs) (extend-env (car p-names) (car refs) env))))]) (for-each (lambda (ref b-vars p-body) (setref! ref (proc-val (procedure b-vars p-body rec-env)))) refs b-vars p-bodies) (value-of letrec-body rec-env))] [begin-exp (exp1 exps) (letrec ([value-of-begins (lambda (e1 es) (let ([v1 (value-of e1 env)]) (if (null? es) v1 (value-of-begins (car es) (cdr es)))))]) (value-of-begins exp1 exps))] [assign-exp (var exp1) (setref! (apply-env env var) (value-of exp1 env)) (num-val 27)]))) (define (value-of-statement statement1 env) (cases statement statement1 [assign-statement (var exp) (setref! (apply-env env var) (value-of exp env)) (num-val 27)] [print-statement (exp) (cases expval (value-of exp env) [num-val (num) (display num) (newline)] [bool-val (bool) (display bool) (newline)] [proc-val (proc) (display "<procedure>") (newline)])] [brace-statement (statements) (for-each (lambda (s) (value-of-statement s env)) statements)] [if-statement (exp statement1 statement2) (if (expval->bool (value-of exp env)) (value-of-statement statement1 env) (value-of-statement statement2 env))] [while-statement (exp statement) (let loop () (if (expval->bool (value-of exp env)) (begin (value-of-statement statement env) (loop)) 'break))] [block-statement (vars exps body) (let* ([refs (map (lambda (var) (newref 0)) vars)] [block-env (let loop ([vars vars] [refs refs] [env env]) (if (null? vars) env (loop (cdr vars) (cdr refs) (extend-env (car vars) (car refs) env))))]) (for-each (lambda (ref exp) (setref! ref (value-of exp block-env))) refs exps) (value-of-statement body block-env))] [read-statement (var) (let ([num (read)]) (if (and (integer? num) (not (negative? num))) (setref! (apply-env env var) (num-val num)) (eopl:error 'value-of-statement "Expect a nonnegative integer, but got ~s." num)))] [do-while-statement (statement exp) (let loop () (begin (value-of-statement statement env) (if (expval->bool (value-of exp env)) (loop) 'break)))])) (define value-of-program (lambda (pgm) (initialize-store!) (cases program pgm [a-program (statement) (value-of-statement statement (empty-env))]))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide run)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-4.26.rkt
racket
Exercise 4.26 [★★★] Extend the solution to the preceding exercise so that procedures declared in a single block aremutually recursive. Consider restricting the language so that the variable declarations in a block are followed by the procedure declarations. Grammar. Data structures. Environments. Store. Interpreter.
#lang eopl (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (statement) a-program] [statement (identifier "=" expression) assign-statement] [statement ("print" expression) print-statement] [statement ("{" (separated-list statement ";") "}") brace-statement] [statement ("if" expression statement statement) if-statement] [statement ("while" expression statement) while-statement] [statement ("var" (separated-list identifier "=" expression ",") ";" statement) block-statement] [statement ("read" identifier) read-statement] [statement ("do" statement "while" expression) do-while-statement] [expression (number) const-exp] [expression ("+" "(" expression "," expression ")") add-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("*" "(" expression "," expression ")") multiply-exp] [expression ("not" "(" expression ")") not-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("let" (arbno identifier "=" expression) "in" expression) let-exp] [expression ("proc" "(" (separated-list identifier ",") ")" expression) proc-exp] [expression ("(" expression (arbno expression) ")") call-exp] [expression ("letrec" (arbno identifier "(" (separated-list identifier ",") ")" "=" expression) "in" expression) letrec-exp] [expression ("begin" expression (arbno ";" expression) "end") begin-exp] [expression ("set" identifier "=" expression) assign-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define-datatype proc proc? [procedure [bvars (list-of symbol?)] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define reference? (lambda (v) (integer? v))) (define-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval reference?] [saved-env environment?]]) (define location (lambda (sym syms) (cond [(null? syms) #f] [(eqv? sym (car syms)) 0] [(location sym (cdr syms)) => (lambda (n) (+ n 1))] [else #f]))) (define apply-env (lambda (env search-var) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-var)] [extend-env (bvar bval saved-env) (if (eqv? search-var bvar) bval (apply-env saved-env search-var))]))) (define the-store 'uninitialized) (define empty-store (lambda () '())) (define initialize-store! (lambda () (set! the-store (empty-store)))) (define newref (lambda (val) (let ([next-ref (length the-store)]) (set! the-store (append the-store (list val))) next-ref))) (define deref (lambda (ref) (list-ref the-store ref))) (define report-invalid-reference (lambda (ref the-store) (eopl:error 'setref "illegal reference ~s in store ~s" ref the-store))) (define setref! (lambda (ref val) (set! the-store (letrec ([setref-inner (lambda (store1 ref1) (cond [(null? store1) (report-invalid-reference ref the-store)] [(zero? ref1) (cons val (cdr store1))] [else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))]))]) (setref-inner the-store ref))))) (define apply-procedure (lambda (proc1 args) (cases proc proc1 [procedure (vars body saved-env) (let ([new-env (let loop ([vars vars] [args args] [env saved-env]) (if (null? vars) env (loop (cdr vars) (cdr args) (extend-env (car vars) (newref (car args)) env))))]) (value-of body new-env))]))) (define value-of (lambda (exp env) (cases expression exp [const-exp (num) (num-val num)] [var-exp (var) (deref (apply-env env var))] [add-exp (exp1 exp2) (let ([val1 (value-of exp1 env)] [val2 (value-of exp2 env)]) (let ([num1 (expval->num val1)] [num2 (expval->num val2)]) (num-val (+ num1 num2))))] [diff-exp (exp1 exp2) (let ([val1 (value-of exp1 env)] [val2 (value-of exp2 env)]) (let ([num1 (expval->num val1)] [num2 (expval->num val2)]) (num-val (- num1 num2))))] [multiply-exp (exp1 exp2) (let ([val1 (value-of exp1 env)] [val2 (value-of exp2 env)]) (let ([num1 (expval->num val1)] [num2 (expval->num val2)]) (num-val (* num1 num2))))] [not-exp (exp) (let ([val (value-of exp env)]) (bool-val (not (expval->bool val))))] [zero?-exp (exp1) (let ([val1 (value-of exp1 env)]) (let ([num1 (expval->num val1)]) (if (zero? num1) (bool-val #t) (bool-val #f))))] [if-exp (exp1 exp2 exp3) (let ([val1 (value-of exp1 env)]) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))] [let-exp (vars exps body) (let ([body-env (let loop ([vars vars] [exps exps] [env1 env]) (if (null? vars) env1 (loop (cdr vars) (cdr exps) (extend-env (car vars) (newref (value-of (car exps) env)) env1))))]) (value-of body body-env))] [proc-exp (vars body) (proc-val (procedure vars body env))] [call-exp (rator rands) (let ([proc (expval->proc (value-of rator env))] [args (map (lambda (rand) (value-of rand env)) rands)]) (apply-procedure proc args))] [letrec-exp (p-names b-vars p-bodies letrec-body) (let* ([refs (map (lambda (p-name) (newref 0)) p-names)] [rec-env (let loop ([p-names p-names] [refs refs] [env env]) (if (null? p-names) env (loop (cdr p-names) (cdr refs) (extend-env (car p-names) (car refs) env))))]) (for-each (lambda (ref b-vars p-body) (setref! ref (proc-val (procedure b-vars p-body rec-env)))) refs b-vars p-bodies) (value-of letrec-body rec-env))] [begin-exp (exp1 exps) (letrec ([value-of-begins (lambda (e1 es) (let ([v1 (value-of e1 env)]) (if (null? es) v1 (value-of-begins (car es) (cdr es)))))]) (value-of-begins exp1 exps))] [assign-exp (var exp1) (setref! (apply-env env var) (value-of exp1 env)) (num-val 27)]))) (define (value-of-statement statement1 env) (cases statement statement1 [assign-statement (var exp) (setref! (apply-env env var) (value-of exp env)) (num-val 27)] [print-statement (exp) (cases expval (value-of exp env) [num-val (num) (display num) (newline)] [bool-val (bool) (display bool) (newline)] [proc-val (proc) (display "<procedure>") (newline)])] [brace-statement (statements) (for-each (lambda (s) (value-of-statement s env)) statements)] [if-statement (exp statement1 statement2) (if (expval->bool (value-of exp env)) (value-of-statement statement1 env) (value-of-statement statement2 env))] [while-statement (exp statement) (let loop () (if (expval->bool (value-of exp env)) (begin (value-of-statement statement env) (loop)) 'break))] [block-statement (vars exps body) (let* ([refs (map (lambda (var) (newref 0)) vars)] [block-env (let loop ([vars vars] [refs refs] [env env]) (if (null? vars) env (loop (cdr vars) (cdr refs) (extend-env (car vars) (car refs) env))))]) (for-each (lambda (ref exp) (setref! ref (value-of exp block-env))) refs exps) (value-of-statement body block-env))] [read-statement (var) (let ([num (read)]) (if (and (integer? num) (not (negative? num))) (setref! (apply-env env var) (num-val num)) (eopl:error 'value-of-statement "Expect a nonnegative integer, but got ~s." num)))] [do-while-statement (statement exp) (let loop () (begin (value-of-statement statement env) (if (expval->bool (value-of exp env)) (loop) 'break)))])) (define value-of-program (lambda (pgm) (initialize-store!) (cases program pgm [a-program (statement) (value-of-statement statement (empty-env))]))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide run)
630b2d5ca034d3337537ec3dd1770ef5a6e7a0f9dda18d0200ab473ed022f781
RyanGlScott/code-page
CodePage.hs
# LANGUAGE CPP # # LANGUAGE NamedFieldPuns # | Module : System . IO.CodePage Copyright : ( C ) 2016 - 2017 License : BSD - style ( see the file LICENSE ) Maintainer : Stability : Provisional Portability : Portable Exports functions which adjust code pages on Windows , and do nothing on other operating systems . Module: System.IO.CodePage Copyright: (C) 2016-2017 Ryan Scott License: BSD-style (see the file LICENSE) Maintainer: Ryan Scott Stability: Provisional Portability: Portable Exports functions which adjust code pages on Windows, and do nothing on other operating systems. -} module System.IO.CodePage ( -- * Adjusting 'CodePage's withCP65001 , withCP1200 , withCP1201 , withCP12000 , withCP12001 , withCP1252 , withCodePage , withCodePageOptions -- * Notable 'CodePage's , CodePage , cp65001 , cp1200 , cp1201 , cp12000 , cp12001 , cp1252 -- * 'Options' , Options , defaultOptions -- ** Record fields of 'Options' , chatty , nonWindowsBehavior -- ** 'NonWindowsBehavior' , NonWindowsBehavior -- ** Constructing 'NonWindowsBehavior' , nonWindowsDoNothing , nonWindowsFallbackCodePageEncoding , defaultFallbackCodePageEncoding ) where import Control.Exception (bracket_) import Control.Monad (when) import Data.Foldable (forM_) import GHC.IO.Encoding (textEncodingName) import System.IO ( TextEncoding, hGetEncoding, hPutStrLn, hSetEncoding , stderr, stdin, stdout ) import System.IO.CodePage.Internal #if MIN_VERSION_base(4,5,0) import GHC.IO.Encoding (getLocaleEncoding, setLocaleEncoding) #endif #ifdef WINDOWS import System.Win32.CodePage hiding (CodePage) #endif | Sets the code page for an action to UTF-8 as necessary . withCP65001 :: IO a -> IO a withCP65001 = withCodePage cp65001 | Sets the code page for an action to UTF-16LE as necessary . withCP1200 :: IO a -> IO a withCP1200 = withCodePage cp1200 | Sets the code page for an action to UTF-16BE as necessary . withCP1201 :: IO a -> IO a withCP1201 = withCodePage cp1201 -- | Sets the code page for an action to UTF-32LE as necessary. withCP12000 :: IO a -> IO a withCP12000 = withCodePage cp12000 -- | Sets the code page for an action to UTF-32BE as necessary. withCP12001 :: IO a -> IO a withCP12001 = withCodePage cp12001 | Sets the code page for an action to Latin1 as necessary . withCP1252 :: IO a -> IO a withCP1252 = withCodePage cp1252 -- | Sets the code page for an action as necessary. -- On operating systems besides Windows , this will make an effort to change -- the current 'TextEncoding' to something that is equivalent to the supplied ' CodePage ' . Currently , the only supported ' CodePage 's on non - Windows OSes are ' cp65001 ' , ' ' , ' cp1201 ' , ' cp12000 ' , and . Supplying any other ' CodePage ' will result in a runtime error on non - Windows OSes . ( If you -- would like to configure this behavior, use 'withCodePageOptions' instead.) withCodePage :: CodePage -> IO a -> IO a withCodePage = withCodePageOptions defaultOptions -- | Sets the code page for an action as necessary. If the 'Bool' argument is 'True', this function will emit a warning to indicating that the code page has -- been changed. ('withCodePage' sets this argument to 'False'.) -- Taken from the stack codebase -- (#L82-L123) which is under a 3 - clause BSD license withCodePageOptions :: Options -> CodePage -> IO a -> IO a withCodePageOptions (Options{chatty, nonWindowsBehavior}) cp inner = case nonWindowsBehavior of NonWindowsDoNothing -> inner NonWindowsFallbackCodePageEncoding fallback -> do #ifdef WINDOWS origCPI <- getConsoleCP origCPO <- getConsoleOutputCP #else These are never used on non - Windows OSes , -- so their values are irrelevant let origCPI = 0 origCPO = 0 #endif mbOrigStdinEnc <- hGetEncoding stdin mbOrigStdoutEnc <- hGetEncoding stdout mbOrigStderrEnc <- hGetEncoding stderr #if MIN_VERSION_base(4,5,0) origLocaleEnc <- getLocaleEncoding #endif let expected = codePageEncoding' fallback cp expectedName = textEncodingName expected warn typ = when chatty $ hPutStrLn stderr $ concat [ "Setting" , typ , " codepage to " ++ show cp , if expectedName == ("CP" ++ show cp) then "" else " (" ++ expectedName ++ ")" ] #ifdef WINDOWS setInput = origCPI /= cp setOutput = origCPO /= cp #else -- Crude, but the best available option setInput = fmap textEncodingName mbOrigStdinEnc /= Just expectedName setOutput = fmap textEncodingName mbOrigStdoutEnc /= Just expectedName #endif #if MIN_VERSION_base(4,5,0) setLocale = textEncodingName origLocaleEnc /= expectedName #endif fixInput | setInput = bracket_ (do setConsoleCP' cp hSetEncoding stdin expected ) (do setConsoleCP' origCPI forM_ mbOrigStdinEnc $ hSetEncoding stdin ) | otherwise = id fixOutput | setOutput = bracket_ (do setConsoleOutputCP' cp hSetEncoding stdout expected hSetEncoding stderr expected ) (do setConsoleOutputCP' origCPO forM_ mbOrigStdoutEnc $ hSetEncoding stdout forM_ mbOrigStderrEnc $ hSetEncoding stderr ) | otherwise = id fixLocale #if MIN_VERSION_base(4,5,0) | setLocale = bracket_ (do when chatty $ hPutStrLn stderr $ unwords [ "Setting locale encoding to" , expectedName ] setLocaleEncoding expected) (setLocaleEncoding origLocaleEnc) | otherwise #endif = id case (setInput, setOutput) of (False, False) -> return () (True, True) -> warn "" (True, False) -> warn " input" (False, True) -> warn " output" fixInput $ fixOutput $ fixLocale inner codePageEncoding' :: (CodePage -> TextEncoding) -> CodePage -> TextEncoding #ifdef WINDOWS codePageEncoding' _ = codePageEncoding #else codePageEncoding' = id #endif setConsoleCP', setConsoleOutputCP' :: CodePage -> IO () #ifdef WINDOWS setConsoleCP' = setConsoleCP setConsoleOutputCP' = setConsoleOutputCP #else setConsoleCP' _ = return () setConsoleOutputCP' _ = return () #endif
null
https://raw.githubusercontent.com/RyanGlScott/code-page/2638c61104eb54615db604ffde00ffb76132c9ae/src/System/IO/CodePage.hs
haskell
* Adjusting 'CodePage's * Notable 'CodePage's * 'Options' ** Record fields of 'Options' ** 'NonWindowsBehavior' ** Constructing 'NonWindowsBehavior' | Sets the code page for an action to UTF-32LE as necessary. | Sets the code page for an action to UTF-32BE as necessary. | Sets the code page for an action as necessary. the current 'TextEncoding' to something that is equivalent to the supplied would like to configure this behavior, use 'withCodePageOptions' instead.) | Sets the code page for an action as necessary. If the 'Bool' argument is 'True', been changed. ('withCodePage' sets this argument to 'False'.) Taken from the stack codebase (#L82-L123) so their values are irrelevant Crude, but the best available option
# LANGUAGE CPP # # LANGUAGE NamedFieldPuns # | Module : System . IO.CodePage Copyright : ( C ) 2016 - 2017 License : BSD - style ( see the file LICENSE ) Maintainer : Stability : Provisional Portability : Portable Exports functions which adjust code pages on Windows , and do nothing on other operating systems . Module: System.IO.CodePage Copyright: (C) 2016-2017 Ryan Scott License: BSD-style (see the file LICENSE) Maintainer: Ryan Scott Stability: Provisional Portability: Portable Exports functions which adjust code pages on Windows, and do nothing on other operating systems. -} module System.IO.CodePage ( withCP65001 , withCP1200 , withCP1201 , withCP12000 , withCP12001 , withCP1252 , withCodePage , withCodePageOptions , CodePage , cp65001 , cp1200 , cp1201 , cp12000 , cp12001 , cp1252 , Options , defaultOptions , chatty , nonWindowsBehavior , NonWindowsBehavior , nonWindowsDoNothing , nonWindowsFallbackCodePageEncoding , defaultFallbackCodePageEncoding ) where import Control.Exception (bracket_) import Control.Monad (when) import Data.Foldable (forM_) import GHC.IO.Encoding (textEncodingName) import System.IO ( TextEncoding, hGetEncoding, hPutStrLn, hSetEncoding , stderr, stdin, stdout ) import System.IO.CodePage.Internal #if MIN_VERSION_base(4,5,0) import GHC.IO.Encoding (getLocaleEncoding, setLocaleEncoding) #endif #ifdef WINDOWS import System.Win32.CodePage hiding (CodePage) #endif | Sets the code page for an action to UTF-8 as necessary . withCP65001 :: IO a -> IO a withCP65001 = withCodePage cp65001 | Sets the code page for an action to UTF-16LE as necessary . withCP1200 :: IO a -> IO a withCP1200 = withCodePage cp1200 | Sets the code page for an action to UTF-16BE as necessary . withCP1201 :: IO a -> IO a withCP1201 = withCodePage cp1201 withCP12000 :: IO a -> IO a withCP12000 = withCodePage cp12000 withCP12001 :: IO a -> IO a withCP12001 = withCodePage cp12001 | Sets the code page for an action to Latin1 as necessary . withCP1252 :: IO a -> IO a withCP1252 = withCodePage cp1252 On operating systems besides Windows , this will make an effort to change ' CodePage ' . Currently , the only supported ' CodePage 's on non - Windows OSes are ' cp65001 ' , ' ' , ' cp1201 ' , ' cp12000 ' , and . Supplying any other ' CodePage ' will result in a runtime error on non - Windows OSes . ( If you withCodePage :: CodePage -> IO a -> IO a withCodePage = withCodePageOptions defaultOptions this function will emit a warning to indicating that the code page has which is under a 3 - clause BSD license withCodePageOptions :: Options -> CodePage -> IO a -> IO a withCodePageOptions (Options{chatty, nonWindowsBehavior}) cp inner = case nonWindowsBehavior of NonWindowsDoNothing -> inner NonWindowsFallbackCodePageEncoding fallback -> do #ifdef WINDOWS origCPI <- getConsoleCP origCPO <- getConsoleOutputCP #else These are never used on non - Windows OSes , let origCPI = 0 origCPO = 0 #endif mbOrigStdinEnc <- hGetEncoding stdin mbOrigStdoutEnc <- hGetEncoding stdout mbOrigStderrEnc <- hGetEncoding stderr #if MIN_VERSION_base(4,5,0) origLocaleEnc <- getLocaleEncoding #endif let expected = codePageEncoding' fallback cp expectedName = textEncodingName expected warn typ = when chatty $ hPutStrLn stderr $ concat [ "Setting" , typ , " codepage to " ++ show cp , if expectedName == ("CP" ++ show cp) then "" else " (" ++ expectedName ++ ")" ] #ifdef WINDOWS setInput = origCPI /= cp setOutput = origCPO /= cp #else setInput = fmap textEncodingName mbOrigStdinEnc /= Just expectedName setOutput = fmap textEncodingName mbOrigStdoutEnc /= Just expectedName #endif #if MIN_VERSION_base(4,5,0) setLocale = textEncodingName origLocaleEnc /= expectedName #endif fixInput | setInput = bracket_ (do setConsoleCP' cp hSetEncoding stdin expected ) (do setConsoleCP' origCPI forM_ mbOrigStdinEnc $ hSetEncoding stdin ) | otherwise = id fixOutput | setOutput = bracket_ (do setConsoleOutputCP' cp hSetEncoding stdout expected hSetEncoding stderr expected ) (do setConsoleOutputCP' origCPO forM_ mbOrigStdoutEnc $ hSetEncoding stdout forM_ mbOrigStderrEnc $ hSetEncoding stderr ) | otherwise = id fixLocale #if MIN_VERSION_base(4,5,0) | setLocale = bracket_ (do when chatty $ hPutStrLn stderr $ unwords [ "Setting locale encoding to" , expectedName ] setLocaleEncoding expected) (setLocaleEncoding origLocaleEnc) | otherwise #endif = id case (setInput, setOutput) of (False, False) -> return () (True, True) -> warn "" (True, False) -> warn " input" (False, True) -> warn " output" fixInput $ fixOutput $ fixLocale inner codePageEncoding' :: (CodePage -> TextEncoding) -> CodePage -> TextEncoding #ifdef WINDOWS codePageEncoding' _ = codePageEncoding #else codePageEncoding' = id #endif setConsoleCP', setConsoleOutputCP' :: CodePage -> IO () #ifdef WINDOWS setConsoleCP' = setConsoleCP setConsoleOutputCP' = setConsoleOutputCP #else setConsoleCP' _ = return () setConsoleOutputCP' _ = return () #endif
5d9a8c1d85bffe17ea92104712a348c51f4cb0e386865eb253e3e090e8c72058
fhur/gabo
core.clj
(ns gabo.core (:require [gabo.util :refer :all] [gabo.lexer :refer :all])) (defn- unexpected-token-exception [token] (new IllegalArgumentException (str "Unexpected token " token))) ;; execute define-is-token-funcs to actually define the given functions: ;; is-literal, is-symbol, etc. (define-is-token-funcs :literal :symbol :iter-init :iter-end :iter) (defn- find-iter-sub-list "Returns all tokens between an :iter-init and corresponding closing :iter-end pair." [tokens] {:pre [(is-iter-init (first tokens))]} (loop [remaining-tokens (rest tokens) sub-list [] stack 0] (let [token (first remaining-tokens)] (if (and (zero? stack) (is-iter-end token)) sub-list (recur (rest remaining-tokens) (conj sub-list token) (cond (is-iter-init token) (inc stack) (is-iter-end token) (dec stack) :else stack)))))) (defn- build-ast "Builds an abstract syntax tree given a list of tokens as produced by tokenize" [tokens] (loop [tokens tokens ast []] (if (empty? tokens) ast (let [token (first tokens)] (cond (or (is-literal token) (is-symbol token)) (recur (rest tokens) (conj ast token)) (is-iter-init token) (let [sub-list (find-iter-sub-list tokens) [_ token-val separator] token] (recur (drop (+ 2 (count sub-list)) tokens) (conj ast [:iter token-val separator (build-ast sub-list)]))) :else (throw (unexpected-token-exception token))))))) (defn parse "Parses a template string and returns a compiled tree representation of the template. You can later use (eval-tree tree context) to render a compiled template with a given context." [string] (-> (tokenize string) build-ast)) (defn eval-tree "Evaluates a compiled template as a tree with the given context" [tree ctx] (cond (is-literal tree) (second tree) (is-symbol tree) (let [[_ token-val] tree] (if (= token-val ".") (str ctx) (get ctx (keyword token-val) ""))) (is-iter tree) (let [[_ token-val separator sub-tree] tree coll (get ctx (keyword token-val) [])] (->> (map #(eval-tree sub-tree %) coll) (interpose (if (= :default separator) "," separator)) (apply str))) Only executed once : the first time eval - tree is called , no subsequent ;; recursive call will go through this branch. (coll? tree) (apply str (map #(eval-tree % ctx) tree)))) (defn render "Compiles and evaluates the template with the given context" [template ctx] (eval-tree (parse template) ctx))
null
https://raw.githubusercontent.com/fhur/gabo/41563e04a131ce33aadd575f20a87acfecdbdc09/src/gabo/core.clj
clojure
execute define-is-token-funcs to actually define the given functions: is-literal, is-symbol, etc. recursive call will go through this branch.
(ns gabo.core (:require [gabo.util :refer :all] [gabo.lexer :refer :all])) (defn- unexpected-token-exception [token] (new IllegalArgumentException (str "Unexpected token " token))) (define-is-token-funcs :literal :symbol :iter-init :iter-end :iter) (defn- find-iter-sub-list "Returns all tokens between an :iter-init and corresponding closing :iter-end pair." [tokens] {:pre [(is-iter-init (first tokens))]} (loop [remaining-tokens (rest tokens) sub-list [] stack 0] (let [token (first remaining-tokens)] (if (and (zero? stack) (is-iter-end token)) sub-list (recur (rest remaining-tokens) (conj sub-list token) (cond (is-iter-init token) (inc stack) (is-iter-end token) (dec stack) :else stack)))))) (defn- build-ast "Builds an abstract syntax tree given a list of tokens as produced by tokenize" [tokens] (loop [tokens tokens ast []] (if (empty? tokens) ast (let [token (first tokens)] (cond (or (is-literal token) (is-symbol token)) (recur (rest tokens) (conj ast token)) (is-iter-init token) (let [sub-list (find-iter-sub-list tokens) [_ token-val separator] token] (recur (drop (+ 2 (count sub-list)) tokens) (conj ast [:iter token-val separator (build-ast sub-list)]))) :else (throw (unexpected-token-exception token))))))) (defn parse "Parses a template string and returns a compiled tree representation of the template. You can later use (eval-tree tree context) to render a compiled template with a given context." [string] (-> (tokenize string) build-ast)) (defn eval-tree "Evaluates a compiled template as a tree with the given context" [tree ctx] (cond (is-literal tree) (second tree) (is-symbol tree) (let [[_ token-val] tree] (if (= token-val ".") (str ctx) (get ctx (keyword token-val) ""))) (is-iter tree) (let [[_ token-val separator sub-tree] tree coll (get ctx (keyword token-val) [])] (->> (map #(eval-tree sub-tree %) coll) (interpose (if (= :default separator) "," separator)) (apply str))) Only executed once : the first time eval - tree is called , no subsequent (coll? tree) (apply str (map #(eval-tree % ctx) tree)))) (defn render "Compiles and evaluates the template with the given context" [template ctx] (eval-tree (parse template) ctx))
11cba4a1c437984e3cf93419d674e4d3c1d2ec0b9e29f1391fc8b3453c6eab49
YoshikuniJujo/funpaala
hpt.hs
type Human = (String, Int) age :: Human -> String age (n, a) = n ++ " is " ++ show a ++ " years old." masuo :: Human masuo = ("Masuo", 32) type Product = (String, Int) price :: Product -> String price (n, p) = n ++ " is " ++ show p ++ " yen." smartphone :: Product smartphone = ("Smartphone", 99000)
null
https://raw.githubusercontent.com/YoshikuniJujo/funpaala/5366130826da0e6b1180992dfff94c4a634cda99/samples/21_adt/hpt.hs
haskell
type Human = (String, Int) age :: Human -> String age (n, a) = n ++ " is " ++ show a ++ " years old." masuo :: Human masuo = ("Masuo", 32) type Product = (String, Int) price :: Product -> String price (n, p) = n ++ " is " ++ show p ++ " yen." smartphone :: Product smartphone = ("Smartphone", 99000)
aa12625d081604faf892af8ba4d5cfeb76b63f6ef0635910d1267b2d988da80f
gregnwosu/haskellbook
exercises.hs
module Exercises where replaceThe :: String -> String replaceThe [] = [] replaceThe ('t':'h':'e':xs) = 'a':replaceThe xs replaceThe (x:xs) = x:replaceThe xs notThe :: String -> Maybe String notThe [] = Just [] notThe ('t':'h':'e':xs) = Nothing notThe (x:xs) = (:) <$> Just x <*> notThe xs vowels = "aeiou" countTheBeforeVowel :: String -> Integer countTheBeforeVowel = fst . foldr go (0, False) . words where go "the" (n,True) = (n+1, False) go "the" (n,False) = (n,False) go [] t = t go (x:_) (n,_) = (n,x `elem` vowels) countVowels :: String -> Integer countVowels = foldr go 0 where go l n | l `elem` vowels = n + 1 | otherwise = n newtype Word' = Word' String deriving (Eq, Show) mkWord :: String -> Maybe Word' mkWord s = mkWord' (nv > nc) where nv = countVowels s nc = fromIntegral ( length s) - nv mkWord' True = Nothing mkWord' _ = Just $ Word' s data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ n) = 1 + natToInteger n integerToNat :: Integer -> Maybe Nat integerToNat x | x < 0 = Nothing | x == 0 = Just Zero | otherwise = go (integerToNat $ x - 1) where go Nothing = Nothing go (Just n) = Just $ Succ n isJust :: Maybe a -> Bool isJust Nothing = False isJust _ = True isNothing :: Maybe a -> Bool isNothing = not . isJust mayybee :: b -> (a -> b ) -> Maybe a -> b mayybee b _ Nothing = b mayybee _ f (Just x) = f x fromMaybe :: a -> Maybe a -> a fromMaybe a = mayybee a id listToMaybe :: [a] -> Maybe a listToMaybe [] = Nothing listToMaybe l = Just $ head l maybeToList :: Maybe a -> [a] maybeToList Nothing = [] maybeToList (Just n) = [n] catMaybes :: [Maybe a] -> [a] catMaybes = foldr go [] where go Nothing = id go (Just x ) = (x:) flipMaybe :: [Maybe a] -> Maybe [a] flipMaybe = foldr go $ Just [] where go Nothing _ = Nothing go _ Nothing = Nothing go (Just x) (Just xs) = Just $ x:xs lefts' :: [Either a b] -> [a] lefts' = foldr go [] where go (Right _ ) = id go (Left x) = (x:) rights' :: [Either a b] -> [b] rights' = foldr go [] where go (Left _ ) = id go (Right x) = (x:) partitionEithers' :: [Either a b] -> ([a], [b]) partitionEithers' = foldr go ([],[]) where go (Left a) (as, bs) = (a:as, bs) go (Right b) (as, bs) = (as, b:bs) eitherMaybe' :: (b -> c) -> Either a b -> Maybe c eitherMaybe' _ (Left _) = Nothing eitherMaybe' f (Right x) = Just $ f x either' :: (a -> c) -> (b -> c) -> Either a b -> c either' f _ (Left x) = f x either' _ f (Right x) = f x eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c eitherMaybe'' f = either' (const Nothing) (Just . f) myIterate :: (a -> a) -> a -> [a] myIterate f a = a: myIterate f (f a) myUnfoldr :: (b -> Maybe (a,b)) -> b -> [a] myUnfoldr f = maybe [] (\(x,y) -> x : myUnfoldr f y) . f betterIterate :: (a -> a) -> a -> [a] betterIterate f a = a : myUnfoldr (\ y -> Just (f y, f y)) a data BinaryTree a = Leaf | Node (BinaryTree a) a (BinaryTree a) deriving (Show, Ord, Eq) unfold :: (a -> Maybe (a,b,a)) -> a -> BinaryTree b unfold f = maybe Leaf (\(l,b,r) -> Node (unfold f l) b (unfold f r) ) . f treeBuild :: Integer -> BinaryTree Integer treeBuild n = unfold go 0 where go x | x == n = Nothing | otherwise = Just (x+1,x,x+1)
null
https://raw.githubusercontent.com/gregnwosu/haskellbook/b21fb6772e58f07cff334d9c551d0477ec856897/chapter12/exercises.hs
haskell
module Exercises where replaceThe :: String -> String replaceThe [] = [] replaceThe ('t':'h':'e':xs) = 'a':replaceThe xs replaceThe (x:xs) = x:replaceThe xs notThe :: String -> Maybe String notThe [] = Just [] notThe ('t':'h':'e':xs) = Nothing notThe (x:xs) = (:) <$> Just x <*> notThe xs vowels = "aeiou" countTheBeforeVowel :: String -> Integer countTheBeforeVowel = fst . foldr go (0, False) . words where go "the" (n,True) = (n+1, False) go "the" (n,False) = (n,False) go [] t = t go (x:_) (n,_) = (n,x `elem` vowels) countVowels :: String -> Integer countVowels = foldr go 0 where go l n | l `elem` vowels = n + 1 | otherwise = n newtype Word' = Word' String deriving (Eq, Show) mkWord :: String -> Maybe Word' mkWord s = mkWord' (nv > nc) where nv = countVowels s nc = fromIntegral ( length s) - nv mkWord' True = Nothing mkWord' _ = Just $ Word' s data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ n) = 1 + natToInteger n integerToNat :: Integer -> Maybe Nat integerToNat x | x < 0 = Nothing | x == 0 = Just Zero | otherwise = go (integerToNat $ x - 1) where go Nothing = Nothing go (Just n) = Just $ Succ n isJust :: Maybe a -> Bool isJust Nothing = False isJust _ = True isNothing :: Maybe a -> Bool isNothing = not . isJust mayybee :: b -> (a -> b ) -> Maybe a -> b mayybee b _ Nothing = b mayybee _ f (Just x) = f x fromMaybe :: a -> Maybe a -> a fromMaybe a = mayybee a id listToMaybe :: [a] -> Maybe a listToMaybe [] = Nothing listToMaybe l = Just $ head l maybeToList :: Maybe a -> [a] maybeToList Nothing = [] maybeToList (Just n) = [n] catMaybes :: [Maybe a] -> [a] catMaybes = foldr go [] where go Nothing = id go (Just x ) = (x:) flipMaybe :: [Maybe a] -> Maybe [a] flipMaybe = foldr go $ Just [] where go Nothing _ = Nothing go _ Nothing = Nothing go (Just x) (Just xs) = Just $ x:xs lefts' :: [Either a b] -> [a] lefts' = foldr go [] where go (Right _ ) = id go (Left x) = (x:) rights' :: [Either a b] -> [b] rights' = foldr go [] where go (Left _ ) = id go (Right x) = (x:) partitionEithers' :: [Either a b] -> ([a], [b]) partitionEithers' = foldr go ([],[]) where go (Left a) (as, bs) = (a:as, bs) go (Right b) (as, bs) = (as, b:bs) eitherMaybe' :: (b -> c) -> Either a b -> Maybe c eitherMaybe' _ (Left _) = Nothing eitherMaybe' f (Right x) = Just $ f x either' :: (a -> c) -> (b -> c) -> Either a b -> c either' f _ (Left x) = f x either' _ f (Right x) = f x eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c eitherMaybe'' f = either' (const Nothing) (Just . f) myIterate :: (a -> a) -> a -> [a] myIterate f a = a: myIterate f (f a) myUnfoldr :: (b -> Maybe (a,b)) -> b -> [a] myUnfoldr f = maybe [] (\(x,y) -> x : myUnfoldr f y) . f betterIterate :: (a -> a) -> a -> [a] betterIterate f a = a : myUnfoldr (\ y -> Just (f y, f y)) a data BinaryTree a = Leaf | Node (BinaryTree a) a (BinaryTree a) deriving (Show, Ord, Eq) unfold :: (a -> Maybe (a,b,a)) -> a -> BinaryTree b unfold f = maybe Leaf (\(l,b,r) -> Node (unfold f l) b (unfold f r) ) . f treeBuild :: Integer -> BinaryTree Integer treeBuild n = unfold go 0 where go x | x == n = Nothing | otherwise = Just (x+1,x,x+1)
a59b1048241d05535936002aecfdfadf4b9ab5ad2b0f78e645f036b0780606b2
ranjitjhala/haddock-annot
UserHooks.hs
----------------------------------------------------------------------------- -- | Module : Distribution . Simple . UserHooks Copyright : 2003 - 2005 -- -- Maintainer : -- Portability : portable -- -- This defines the API that @Setup.hs@ scripts can use to customise the way the build works . This module just defines the ' UserHooks ' type . The predefined sets of hooks that implement the @Simple@ , @Make@ and @Configure@ -- build systems are defined in "Distribution.Simple". The 'UserHooks' is a big record of functions . There are 3 for each action , a pre , post and the action -- itself. There are few other miscellaneous hooks, ones to extend the set of -- programs and preprocessors and one to override the function used to read the -- @.cabal@ file. -- -- This hooks type is widely agreed to not be the right solution. Partly this -- is because changes to it usually break custom @Setup.hs@ files and yet many -- internal code changes do require changes to the hooks. For example we cannot -- pass any extra parameters to most of the functions that implement the -- various phases because it would involve changing the types of the -- corresponding hook. At some point it will have to be replaced. All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * 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 . * Neither the name of nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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 . Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Simple.UserHooks ( UserHooks(..), Args, emptyUserHooks, ) where import Distribution.PackageDescription (PackageDescription, GenericPackageDescription, HookedBuildInfo, emptyHookedBuildInfo) import Distribution.Simple.Program (Program) import Distribution.Simple.Command (noExtraFlags) import Distribution.Simple.PreProcess (PPSuffixHandler) import Distribution.Simple.Setup (ConfigFlags, BuildFlags, CleanFlags, CopyFlags, InstallFlags, SDistFlags, RegisterFlags, HscolourFlags, HaddockFlags, TestFlags) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo) type Args = [String] -- | Hooks allow authors to add specific functionality before and after a -- command is run, and also to specify additional preprocessors. -- -- * WARNING: The hooks interface is under rather constant flux as we try to -- understand users needs. Setup files that depend on this interface may -- break in future releases. data UserHooks = UserHooks { -- | Used for @.\/setup test@ runTests :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO (), -- | Read the description file readDesc :: IO (Maybe GenericPackageDescription), -- | Custom preprocessors in addition to and overriding 'knownSuffixHandlers'. hookedPreProcessors :: [ PPSuffixHandler ], -- | These programs are detected at configure time. Arguments for them are -- added to the configure command. hookedPrograms :: [Program], -- |Hook to run before configure command preConf :: Args -> ConfigFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during configure. confHook :: (GenericPackageDescription, HookedBuildInfo) -> ConfigFlags -> IO LocalBuildInfo, -- |Hook to run after configure command postConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before build command . Second arg indicates verbosity level . preBuild :: Args -> BuildFlags -> IO HookedBuildInfo, -- |Over-ride this hook to gbet different behavior during build. buildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO (), |Hook to run after build command . Second arg indicates verbosity level . postBuild :: Args -> BuildFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before clean command . Second arg indicates verbosity level . preClean :: Args -> CleanFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during clean. cleanHook :: PackageDescription -> () -> UserHooks -> CleanFlags -> IO (), |Hook to run after clean command . Second arg indicates verbosity level . postClean :: Args -> CleanFlags -> PackageDescription -> () -> IO (), -- |Hook to run before copy command preCopy :: Args -> CopyFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during copy. copyHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> CopyFlags -> IO (), -- |Hook to run after copy command postCopy :: Args -> CopyFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before install command preInst :: Args -> InstallFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during install. instHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO (), -- |Hook to run after install command. postInst should be run -- on the target, not on the build machine. postInst :: Args -> InstallFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before sdist command . Second arg indicates verbosity level . preSDist :: Args -> SDistFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during sdist. sDistHook :: PackageDescription -> Maybe LocalBuildInfo -> UserHooks -> SDistFlags -> IO (), |Hook to run after sdist command . Second arg indicates verbosity level . postSDist :: Args -> SDistFlags -> PackageDescription -> Maybe LocalBuildInfo -> IO (), -- |Hook to run before register command preReg :: Args -> RegisterFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during registration. regHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (), -- |Hook to run after register command postReg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before unregister command preUnreg :: Args -> RegisterFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during registration. unregHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (), -- |Hook to run after unregister command postUnreg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before hscolour command . Second arg indicates verbosity level . preHscolour :: Args -> HscolourFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during hscolour. hscolourHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HscolourFlags -> IO (), |Hook to run after hscolour command . Second arg indicates verbosity level . postHscolour :: Args -> HscolourFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before haddock command . Second arg indicates verbosity level . preHaddock :: Args -> HaddockFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during haddock. haddockHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HaddockFlags -> IO (), |Hook to run after haddock command . Second arg indicates verbosity level . postHaddock :: Args -> HaddockFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before test command. preTest :: Args -> TestFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during test. testHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> TestFlags -> IO (), -- |Hook to run after test command. postTest :: Args -> TestFlags -> PackageDescription -> LocalBuildInfo -> IO () } {-# DEPRECATED runTests "Please use the new testing interface instead!" #-} -- |Empty 'UserHooks' which do nothing. emptyUserHooks :: UserHooks emptyUserHooks = UserHooks { runTests = ru, readDesc = return Nothing, hookedPreProcessors = [], hookedPrograms = [], preConf = rn, confHook = (\_ _ -> return (error "No local build info generated during configure. Over-ride empty configure hook.")), postConf = ru, preBuild = rn, buildHook = ru, postBuild = ru, preClean = rn, cleanHook = ru, postClean = ru, preCopy = rn, copyHook = ru, postCopy = ru, preInst = rn, instHook = ru, postInst = ru, preSDist = rn, sDistHook = ru, postSDist = ru, preReg = rn, regHook = ru, postReg = ru, preUnreg = rn, unregHook = ru, postUnreg = ru, preHscolour = rn, hscolourHook = ru, postHscolour = ru, preHaddock = rn, haddockHook = ru, postHaddock = ru, preTest = \_ _ -> return emptyHookedBuildInfo, -- same as rn, but without -- noExtraFlags testHook = ru, postTest = ru } where rn args _ = noExtraFlags args >> return emptyHookedBuildInfo ru _ _ _ _ = return ()
null
https://raw.githubusercontent.com/ranjitjhala/haddock-annot/ffaa182b17c3047887ff43dbe358c246011903f6/Cabal-1.10.1.1/Distribution/Simple/UserHooks.hs
haskell
--------------------------------------------------------------------------- | Maintainer : Portability : portable This defines the API that @Setup.hs@ scripts can use to customise the way build systems are defined in "Distribution.Simple". The 'UserHooks' is a big itself. There are few other miscellaneous hooks, ones to extend the set of programs and preprocessors and one to override the function used to read the @.cabal@ file. This hooks type is widely agreed to not be the right solution. Partly this is because changes to it usually break custom @Setup.hs@ files and yet many internal code changes do require changes to the hooks. For example we cannot pass any extra parameters to most of the functions that implement the various phases because it would involve changing the types of the corresponding hook. At some point it will have to be replaced. | Hooks allow authors to add specific functionality before and after a command is run, and also to specify additional preprocessors. * WARNING: The hooks interface is under rather constant flux as we try to understand users needs. Setup files that depend on this interface may break in future releases. | Used for @.\/setup test@ | Read the description file | Custom preprocessors in addition to and overriding 'knownSuffixHandlers'. | These programs are detected at configure time. Arguments for them are added to the configure command. |Hook to run before configure command |Over-ride this hook to get different behavior during configure. |Hook to run after configure command |Over-ride this hook to gbet different behavior during build. |Over-ride this hook to get different behavior during clean. |Hook to run before copy command |Over-ride this hook to get different behavior during copy. |Hook to run after copy command |Hook to run before install command |Over-ride this hook to get different behavior during install. |Hook to run after install command. postInst should be run on the target, not on the build machine. |Over-ride this hook to get different behavior during sdist. |Hook to run before register command |Over-ride this hook to get different behavior during registration. |Hook to run after register command |Hook to run before unregister command |Over-ride this hook to get different behavior during registration. |Hook to run after unregister command |Over-ride this hook to get different behavior during hscolour. |Over-ride this hook to get different behavior during haddock. |Hook to run before test command. |Over-ride this hook to get different behavior during test. |Hook to run after test command. # DEPRECATED runTests "Please use the new testing interface instead!" # |Empty 'UserHooks' which do nothing. same as rn, but without noExtraFlags
Module : Distribution . Simple . UserHooks Copyright : 2003 - 2005 the build works . This module just defines the ' UserHooks ' type . The predefined sets of hooks that implement the @Simple@ , @Make@ and @Configure@ record of functions . There are 3 for each action , a pre , post and the action All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * 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 . * Neither the name of nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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 . Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Simple.UserHooks ( UserHooks(..), Args, emptyUserHooks, ) where import Distribution.PackageDescription (PackageDescription, GenericPackageDescription, HookedBuildInfo, emptyHookedBuildInfo) import Distribution.Simple.Program (Program) import Distribution.Simple.Command (noExtraFlags) import Distribution.Simple.PreProcess (PPSuffixHandler) import Distribution.Simple.Setup (ConfigFlags, BuildFlags, CleanFlags, CopyFlags, InstallFlags, SDistFlags, RegisterFlags, HscolourFlags, HaddockFlags, TestFlags) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo) type Args = [String] data UserHooks = UserHooks { runTests :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO (), readDesc :: IO (Maybe GenericPackageDescription), hookedPreProcessors :: [ PPSuffixHandler ], hookedPrograms :: [Program], preConf :: Args -> ConfigFlags -> IO HookedBuildInfo, confHook :: (GenericPackageDescription, HookedBuildInfo) -> ConfigFlags -> IO LocalBuildInfo, postConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before build command . Second arg indicates verbosity level . preBuild :: Args -> BuildFlags -> IO HookedBuildInfo, buildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO (), |Hook to run after build command . Second arg indicates verbosity level . postBuild :: Args -> BuildFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before clean command . Second arg indicates verbosity level . preClean :: Args -> CleanFlags -> IO HookedBuildInfo, cleanHook :: PackageDescription -> () -> UserHooks -> CleanFlags -> IO (), |Hook to run after clean command . Second arg indicates verbosity level . postClean :: Args -> CleanFlags -> PackageDescription -> () -> IO (), preCopy :: Args -> CopyFlags -> IO HookedBuildInfo, copyHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> CopyFlags -> IO (), postCopy :: Args -> CopyFlags -> PackageDescription -> LocalBuildInfo -> IO (), preInst :: Args -> InstallFlags -> IO HookedBuildInfo, instHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO (), postInst :: Args -> InstallFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before sdist command . Second arg indicates verbosity level . preSDist :: Args -> SDistFlags -> IO HookedBuildInfo, sDistHook :: PackageDescription -> Maybe LocalBuildInfo -> UserHooks -> SDistFlags -> IO (), |Hook to run after sdist command . Second arg indicates verbosity level . postSDist :: Args -> SDistFlags -> PackageDescription -> Maybe LocalBuildInfo -> IO (), preReg :: Args -> RegisterFlags -> IO HookedBuildInfo, regHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (), postReg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (), preUnreg :: Args -> RegisterFlags -> IO HookedBuildInfo, unregHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (), postUnreg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before hscolour command . Second arg indicates verbosity level . preHscolour :: Args -> HscolourFlags -> IO HookedBuildInfo, hscolourHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HscolourFlags -> IO (), |Hook to run after hscolour command . Second arg indicates verbosity level . postHscolour :: Args -> HscolourFlags -> PackageDescription -> LocalBuildInfo -> IO (), |Hook to run before haddock command . Second arg indicates verbosity level . preHaddock :: Args -> HaddockFlags -> IO HookedBuildInfo, haddockHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HaddockFlags -> IO (), |Hook to run after haddock command . Second arg indicates verbosity level . postHaddock :: Args -> HaddockFlags -> PackageDescription -> LocalBuildInfo -> IO (), preTest :: Args -> TestFlags -> IO HookedBuildInfo, testHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> TestFlags -> IO (), postTest :: Args -> TestFlags -> PackageDescription -> LocalBuildInfo -> IO () } emptyUserHooks :: UserHooks emptyUserHooks = UserHooks { runTests = ru, readDesc = return Nothing, hookedPreProcessors = [], hookedPrograms = [], preConf = rn, confHook = (\_ _ -> return (error "No local build info generated during configure. Over-ride empty configure hook.")), postConf = ru, preBuild = rn, buildHook = ru, postBuild = ru, preClean = rn, cleanHook = ru, postClean = ru, preCopy = rn, copyHook = ru, postCopy = ru, preInst = rn, instHook = ru, postInst = ru, preSDist = rn, sDistHook = ru, postSDist = ru, preReg = rn, regHook = ru, postReg = ru, preUnreg = rn, unregHook = ru, postUnreg = ru, preHscolour = rn, hscolourHook = ru, postHscolour = ru, preHaddock = rn, haddockHook = ru, postHaddock = ru, testHook = ru, postTest = ru } where rn args _ = noExtraFlags args >> return emptyHookedBuildInfo ru _ _ _ _ = return ()
60445f50c582a5cb3fa9b411033b3c6bdffe5497695d63e748afaab3fda1f7ab
james-iohk/plutus-scripts
EcdsaSecp256k1LoopValidator.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} module EcdsaSecp256k1LoopValidator (writeSerialisedScript) where import Cardano.Api (PlutusScript, PlutusScriptV2, writeFileTextEnvelope) import Cardano.Api.Shelley (PlutusScript (..)) import Codec.Serialise (serialise) import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Short as SBS import Data.Functor (void) import qualified Plutus.V2.Ledger.Api as PlutusV2 import qualified PlutusTx import qualified PlutusTx.Builtins as BI import PlutusTx.Prelude as P hiding (Semigroup (..), unless, (.)) import Prelude (IO, (.)) {-# INLINEABLE mkValidator #-} mkValidator :: BuiltinData -> BuiltinData -> BuiltinData -> () mkValidator _datum red _txContext = case PlutusV2.fromBuiltinData red of Nothing -> P.traceError "Trace error: Invalid redeemer" Just (n, vkey, msg, sig) -> if n < (1000000 :: Integer) then traceError "redeemer is < 1000000" else loop n vkey msg sig where loop i v m s | i == 1000000 = () | BI.verifyEcdsaSecp256k1Signature v m s = loop (pred i) v m s | otherwise = P.traceError "Trace error: ECDSA validation failed" validator :: PlutusV2.Validator validator = PlutusV2.mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||]) script :: PlutusV2.Script script = PlutusV2.unValidatorScript validator loopScriptShortBs :: SBS.ShortByteString loopScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script loopScript :: PlutusScript PlutusScriptV2 loopScript = PlutusScriptSerialised loopScriptShortBs writeSerialisedScript :: IO () writeSerialisedScript = void $ writeFileTextEnvelope "ecdsa-secp256k-loop.plutus" Nothing loopScript
null
https://raw.githubusercontent.com/james-iohk/plutus-scripts/337462973f2debf7c3d5da748ee1564f69d53187/src/EcdsaSecp256k1LoopValidator.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators # # INLINEABLE mkValidator #
# LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module EcdsaSecp256k1LoopValidator (writeSerialisedScript) where import Cardano.Api (PlutusScript, PlutusScriptV2, writeFileTextEnvelope) import Cardano.Api.Shelley (PlutusScript (..)) import Codec.Serialise (serialise) import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Short as SBS import Data.Functor (void) import qualified Plutus.V2.Ledger.Api as PlutusV2 import qualified PlutusTx import qualified PlutusTx.Builtins as BI import PlutusTx.Prelude as P hiding (Semigroup (..), unless, (.)) import Prelude (IO, (.)) mkValidator :: BuiltinData -> BuiltinData -> BuiltinData -> () mkValidator _datum red _txContext = case PlutusV2.fromBuiltinData red of Nothing -> P.traceError "Trace error: Invalid redeemer" Just (n, vkey, msg, sig) -> if n < (1000000 :: Integer) then traceError "redeemer is < 1000000" else loop n vkey msg sig where loop i v m s | i == 1000000 = () | BI.verifyEcdsaSecp256k1Signature v m s = loop (pred i) v m s | otherwise = P.traceError "Trace error: ECDSA validation failed" validator :: PlutusV2.Validator validator = PlutusV2.mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||]) script :: PlutusV2.Script script = PlutusV2.unValidatorScript validator loopScriptShortBs :: SBS.ShortByteString loopScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script loopScript :: PlutusScript PlutusScriptV2 loopScript = PlutusScriptSerialised loopScriptShortBs writeSerialisedScript :: IO () writeSerialisedScript = void $ writeFileTextEnvelope "ecdsa-secp256k-loop.plutus" Nothing loopScript
7be8ebf4c8ea5c51daec0444968be1147bbacfaf0a347b26faeb5c5d51b24030
racket/rackunit
format-test.rkt
#lang racket/base (require racket/function racket/port racket/list racket/pretty rackunit rackunit/private/check-info (submod rackunit/private/format for-test)) (define-check (check-output expected thnk) (define actual (with-output-to-string thnk)) (with-check-info* (list (make-check-actual actual) (make-check-expected expected)) (thunk (unless (equal? actual expected) (fail-check))))) (test-case "display-check-info-stack" (test-case "basic" (check-output "name: \"foo\"\nactual: 1\nexpected: 2\n" (thunk (display-check-info-stack (list (make-check-name "foo") (make-check-actual 1) (make-check-expected 2)))))) (test-case "string-info" (check-output "name: foo\n" (thunk (display-check-info-stack (list (make-check-info 'name (string-info "foo"))))))) (test-case "nested-info" (check-output "name:\n foo: 1\n bar: 2\n" (thunk (display-check-info-stack (list (make-check-name (nested-info (list (make-check-info 'foo 1) (make-check-info 'bar 2))))))))) (test-case "dynamic-info" (check-output "foo: 1\n" (thunk (display-check-info-stack (list (make-check-info 'foo (dynamic-info (thunk 1))))))) (test-case "with-nested-info" (check-output "name:\n foo: 1\n bar: 2\n" (thunk (display-check-info-stack (list (make-check-name (dynamic-info (thunk (nested-info (list (make-check-info 'foo 1) (make-check-info 'bar 2)))))))))))) (let ([big (make-list 30 99)]) (test-case "multi-line" (check-output (format "foo:\n ~s\n" big) (thunk (display-check-info-stack (list (make-check-info 'foo big))))))))
null
https://raw.githubusercontent.com/racket/rackunit/b6f59fdc857d2236a4465dc68296cb70813968b1/rackunit-test/tests/rackunit/format-test.rkt
racket
#lang racket/base (require racket/function racket/port racket/list racket/pretty rackunit rackunit/private/check-info (submod rackunit/private/format for-test)) (define-check (check-output expected thnk) (define actual (with-output-to-string thnk)) (with-check-info* (list (make-check-actual actual) (make-check-expected expected)) (thunk (unless (equal? actual expected) (fail-check))))) (test-case "display-check-info-stack" (test-case "basic" (check-output "name: \"foo\"\nactual: 1\nexpected: 2\n" (thunk (display-check-info-stack (list (make-check-name "foo") (make-check-actual 1) (make-check-expected 2)))))) (test-case "string-info" (check-output "name: foo\n" (thunk (display-check-info-stack (list (make-check-info 'name (string-info "foo"))))))) (test-case "nested-info" (check-output "name:\n foo: 1\n bar: 2\n" (thunk (display-check-info-stack (list (make-check-name (nested-info (list (make-check-info 'foo 1) (make-check-info 'bar 2))))))))) (test-case "dynamic-info" (check-output "foo: 1\n" (thunk (display-check-info-stack (list (make-check-info 'foo (dynamic-info (thunk 1))))))) (test-case "with-nested-info" (check-output "name:\n foo: 1\n bar: 2\n" (thunk (display-check-info-stack (list (make-check-name (dynamic-info (thunk (nested-info (list (make-check-info 'foo 1) (make-check-info 'bar 2)))))))))))) (let ([big (make-list 30 99)]) (test-case "multi-line" (check-output (format "foo:\n ~s\n" big) (thunk (display-check-info-stack (list (make-check-info 'foo big))))))))
5f2a05ee64261746dc50ae0ab90dfa8d3221aa3e218973e87caa90299d38782c
dyoo/whalesong
m.rkt
#lang s-exp "../../lang/base.rkt" (require "m2.rkt" "m3.rkt")
null
https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/tests/older-tests/require-test/m.rkt
racket
#lang s-exp "../../lang/base.rkt" (require "m2.rkt" "m3.rkt")
fde52d8fdd631a9bb22c6d38376eb8293cfcc4f8937dc0b32f2a143c779b7158
eareese/htdp-exercises
059-rocket-mockups.rkt
#lang htdp/bsl (require 2htdp/image) ; physical constants (define HEIGHT 300) (define WIDTH 100) (define YDELTA 3) ; graphical constants (define BACKG (empty-scene WIDTH HEIGHT)) (define ROCKET (rectangle 5 30 "solid" "blue")) (define ROCKET-CENTER (/ (image-height ROCKET) 2)) (define ROCKET-X 10) ; given 0, rocket should be on the ground (place-image ROCKET ROCKET-X (- (- HEIGHT 0) ROCKET-CENTER) BACKG) given 33 , rocket should be a lil up from the ground (place-image ROCKET ROCKET-X (- (- HEIGHT 33) ROCKET-CENTER) BACKG)
null
https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part01-fixed-size-data/059/059-rocket-mockups.rkt
racket
physical constants graphical constants given 0, rocket should be on the ground
#lang htdp/bsl (require 2htdp/image) (define HEIGHT 300) (define WIDTH 100) (define YDELTA 3) (define BACKG (empty-scene WIDTH HEIGHT)) (define ROCKET (rectangle 5 30 "solid" "blue")) (define ROCKET-CENTER (/ (image-height ROCKET) 2)) (define ROCKET-X 10) (place-image ROCKET ROCKET-X (- (- HEIGHT 0) ROCKET-CENTER) BACKG) given 33 , rocket should be a lil up from the ground (place-image ROCKET ROCKET-X (- (- HEIGHT 33) ROCKET-CENTER) BACKG)
5183cdd1795286a39f3ccf8b6b7da44370200fcf4718fe07fd435e4467ddce26
GaloisInc/LIMA
Gcd.hs
-- | -- Module: Gcd Description : Example design which computes GCD ( greatest - common divisor ) Copyright : ( c ) 2013 Lee Pike -- module Language.LIMA.C.Example.Gcd ( compileExample , example ) where import Language.LIMA import Language.LIMA.C | Invoke the LIMA compiler compileExample :: IO () compileExample = do r <- compile "example" defaults { cCode = prePostCode } example putStrLn $ reportSchedule (compSchedule r) prePostCode :: [Name] -> [Name] -> [(Name, Type)] -> (String, String) prePostCode _ _ _ = ( unlines [ "#include <stdlib.h>" , "#include <stdio.h>" , "unsigned long int a;" , "unsigned long int b;" , "unsigned long int x;" , "unsigned char running = 1;" ] , unlines [ "int main(int argc, char* argv[]) {" , " if (argc < 3) {" , " printf(\"usage: gcd <num1> <num2>\\n\");" , " }" , " else {" , " a = atoi(argv[1]);" , " b = atoi(argv[2]);" , " printf(\"Computing the GCD of %lu and %lu...\\n\", a, b);" , " while(running) {" , " example();" , " printf(\"iteration: a = %lu b = %lu\\n\", a, b);" , " }" , " printf(\"GCD result: %lu\\n\", a);" , " }" , " return 0;" , "}" ] ) -- | An example design that computes the greatest common divisor. example :: Atom () example = do -- External reference to value A. let a = word32' "a" -- External reference to value B. let b = word32' "b" -- The external running flag. let running = bool' "running" -- A rule to modify A. atom "a_minus_b" $ do cond $ value a >. value b a <== value a - value b -- A rule to modify B. atom "b_minus_a" $ do cond $ value b >. value a b <== value b - value a -- A rule to clear the running flag. atom "stop" $ do cond $ value a ==. value b running <== false
null
https://raw.githubusercontent.com/GaloisInc/LIMA/8006bb52b2fb5d3264fe55ef8c9b7c89ab7f4630/lima-c/src/Language/LIMA/C/Example/Gcd.hs
haskell
| Module: Gcd | An example design that computes the greatest common divisor. External reference to value A. External reference to value B. The external running flag. A rule to modify A. A rule to modify B. A rule to clear the running flag.
Description : Example design which computes GCD ( greatest - common divisor ) Copyright : ( c ) 2013 Lee Pike module Language.LIMA.C.Example.Gcd ( compileExample , example ) where import Language.LIMA import Language.LIMA.C | Invoke the LIMA compiler compileExample :: IO () compileExample = do r <- compile "example" defaults { cCode = prePostCode } example putStrLn $ reportSchedule (compSchedule r) prePostCode :: [Name] -> [Name] -> [(Name, Type)] -> (String, String) prePostCode _ _ _ = ( unlines [ "#include <stdlib.h>" , "#include <stdio.h>" , "unsigned long int a;" , "unsigned long int b;" , "unsigned long int x;" , "unsigned char running = 1;" ] , unlines [ "int main(int argc, char* argv[]) {" , " if (argc < 3) {" , " printf(\"usage: gcd <num1> <num2>\\n\");" , " }" , " else {" , " a = atoi(argv[1]);" , " b = atoi(argv[2]);" , " printf(\"Computing the GCD of %lu and %lu...\\n\", a, b);" , " while(running) {" , " example();" , " printf(\"iteration: a = %lu b = %lu\\n\", a, b);" , " }" , " printf(\"GCD result: %lu\\n\", a);" , " }" , " return 0;" , "}" ] ) example :: Atom () example = do let a = word32' "a" let b = word32' "b" let running = bool' "running" atom "a_minus_b" $ do cond $ value a >. value b a <== value a - value b atom "b_minus_a" $ do cond $ value b >. value a b <== value b - value a atom "stop" $ do cond $ value a ==. value b running <== false
019b075c9628612c0d4d3baf3f7e6f95f0ef75546eef7f4d0848ef3b356169e0
ArulselvanMadhavan/haskell-first-principles
Ex26_12_1.hs
module Ex26_12_1 where --Read this - -readert-maybe-or-maybet-reader main :: IO () main = putStrLn "-readert-maybe-or-maybet-reader"
null
https://raw.githubusercontent.com/ArulselvanMadhavan/haskell-first-principles/06e0c71c502848c8e75c8109dd49c0954d815bba/chapter26/src/Ex26_12_1.hs
haskell
Read this - -readert-maybe-or-maybet-reader
module Ex26_12_1 where main :: IO () main = putStrLn "-readert-maybe-or-maybet-reader"
77dbbdecef942d21860f79e33689163c548d95ef3adbf0c38ab3f8c628f4d3be
iu-parfunc/lvars
Sparks.hs
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module Control.Par.Scheds.Sparks ( Par , runPar , runParPoly ) where import Control.Monad (void) import System.IO.Unsafe (unsafePerformIO) import Control.Par.Class import qualified Control.Par.Class.Unsafe as PC import Control.Par.EffectSigs newtype Par (e :: EffectSig) s a = Sparks { unwrapSparks :: S.Par a } newtype SparksFuture s a = SparksFuture { unwrapSparksFuture :: S.Future a }
null
https://raw.githubusercontent.com/iu-parfunc/lvars/78e73c96a929aa75aa4f991d42b2f677849e433a/src/par-schedulers/Control/Par/Scheds/Sparks.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE KindSignatures # # LANGUAGE RankNTypes # # LANGUAGE TypeFamilies #
module Control.Par.Scheds.Sparks ( Par , runPar , runParPoly ) where import Control.Monad (void) import System.IO.Unsafe (unsafePerformIO) import Control.Par.Class import qualified Control.Par.Class.Unsafe as PC import Control.Par.EffectSigs newtype Par (e :: EffectSig) s a = Sparks { unwrapSparks :: S.Par a } newtype SparksFuture s a = SparksFuture { unwrapSparksFuture :: S.Future a }
1bb864af0947dcfebcde1240722b6c5b4b903fc399e9755e63acec25c42ef236
effectfully-ou/sketches
UnliftIO.hs
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE RankNTypes #-} module UnliftIO where import SomeAction import Control.Concurrent import Control.Monad.Except import Control.Monad.Morph import Control.Monad.Trans.Reader class MonadIO m => MonadUnliftIO m where withRunInIO :: ((forall a. m a -> IO a) -> IO r) -> m r instance MonadUnliftIO IO where withRunInIO k = k id instance MonadUnliftIO m => MonadUnliftIO (ReaderT e m) where withRunInIO k = ReaderT $ \r -> withRunInIO $ \runInIO -> k $ runInIO . flip runReaderT r liftU :: MonadUnliftIO m => IO r -> m r liftU a = withRunInIO $ \_ -> a forkU :: MonadUnliftIO m => m () -> m ThreadId forkU a = withRunInIO $ \runInIO -> forkIO $ runInIO a newtype App a = App { unApp :: ReaderT () IO a } deriving newtype (Functor, Applicative, Monad, MonadIO, MonadUnliftIO) deriving anyclass (SomeAction) testApp :: ExceptT () App () testApp = throwError () `catchError` \() -> do _ <- lift $ forkU someAction printM () newtype AppT m a = AppT { unAppT :: ReaderT () m a } deriving newtype (Functor, Applicative, Monad, MonadIO, MonadUnliftIO, MonadError e, MFunctor) deriving anyclass (SomeAction) testAppT :: AppT (ExceptT () IO) () testAppT = throwError () `catchError` \() -> do _ <- hoist lift $ forkU someAction printM ()
null
https://raw.githubusercontent.com/effectfully-ou/sketches/27e112618840a461376973e9594ad37bf5aa243a/generalizing-unliftio/src/UnliftIO.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE DerivingStrategies # # LANGUAGE RankNTypes #
# LANGUAGE GeneralizedNewtypeDeriving # module UnliftIO where import SomeAction import Control.Concurrent import Control.Monad.Except import Control.Monad.Morph import Control.Monad.Trans.Reader class MonadIO m => MonadUnliftIO m where withRunInIO :: ((forall a. m a -> IO a) -> IO r) -> m r instance MonadUnliftIO IO where withRunInIO k = k id instance MonadUnliftIO m => MonadUnliftIO (ReaderT e m) where withRunInIO k = ReaderT $ \r -> withRunInIO $ \runInIO -> k $ runInIO . flip runReaderT r liftU :: MonadUnliftIO m => IO r -> m r liftU a = withRunInIO $ \_ -> a forkU :: MonadUnliftIO m => m () -> m ThreadId forkU a = withRunInIO $ \runInIO -> forkIO $ runInIO a newtype App a = App { unApp :: ReaderT () IO a } deriving newtype (Functor, Applicative, Monad, MonadIO, MonadUnliftIO) deriving anyclass (SomeAction) testApp :: ExceptT () App () testApp = throwError () `catchError` \() -> do _ <- lift $ forkU someAction printM () newtype AppT m a = AppT { unAppT :: ReaderT () m a } deriving newtype (Functor, Applicative, Monad, MonadIO, MonadUnliftIO, MonadError e, MFunctor) deriving anyclass (SomeAction) testAppT :: AppT (ExceptT () IO) () testAppT = throwError () `catchError` \() -> do _ <- hoist lift $ forkU someAction printM ()
9d43db2c0a44345ae5d68e858e8975dea15673cb1073aa8d7ac1ae5133c3bdd8
autolwe/autolwe
Test_Solve_Fq.ml
open Norm open Type open Expr open DeducField open OUnit let vx = Vsym.mk "x" mk_Fq let vy = Vsym.mk "y" mk_Fq let vz = Vsym.mk "z" mk_Fq let vu = Vsym.mk "u" mk_Fq let vv = Vsym.mk "v" mk_Fq let vw = Vsym.mk "w" mk_Fq let vhh = Vsym.mk "hh" mk_Fq let (x,y,z) = (mk_V vx, mk_V vy, mk_V vz) let (u,v,w) = (mk_V vu, mk_V vv, mk_V vw) let hh = mk_V vhh let vx2 = Vsym.mk "x2" mk_Fq let vy2 = Vsym.mk "y2" mk_Fq let vz2 = Vsym.mk "z2" mk_Fq let vu2 = Vsym.mk "u2" mk_Fq let vv2 = Vsym.mk "v2" mk_Fq let vw2 = Vsym.mk "w2" mk_Fq let (x2,y2,z2) = (mk_V vx2, mk_V vy2, mk_V vz2 ) let (u2,v2,w2) = (mk_V vu2, mk_V vv2, mk_V vw2) let p1 = mk_V (Vsym.mk "p1" mk_Fq) let p2 = mk_V (Vsym.mk "p2" mk_Fq) let p3 = mk_V (Vsym.mk "p3" mk_Fq) let p4 = mk_V (Vsym.mk "p4" mk_Fq) let p5 = mk_V (Vsym.mk "p5" mk_Fq) let p6 = mk_V (Vsym.mk "p6" mk_Fq) let p7 = mk_V (Vsym.mk "p7" mk_Fq) let p8 = mk_V (Vsym.mk "p8" mk_Fq) let eval_ctx known ctx = let m = me_of_list known in norm_expr (e_subst m ctx) let test1 _ = let a = x in let b = mk_FPlus [x;z] in let sec = z in let known = [ (p1,a); (p2,b) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test1: solution valid" (eval_ctx known ctx) sec let test2 _ = let a = mk_FPlus [x;y] in let b = mk_FPlus [x;z] in let sec = z in let known = [ (p1,a); (p2,b) ] in assert_raises ~msg:"test2: no solution" Not_found (fun () -> solve_fq known sec) let test3 _ = let a = x in let b = mk_FPlus [x;z] in let c = y in let sec = mk_FMult [z;y] in let known = [ (p1,a); (p2,b); (p3,c) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test3: solution valid" (eval_ctx known ctx) sec test cases from rrandom for Cramer - Shoup ( modulo renaming ) (* x -> y*z + x *) let test4 _ = let e1 = y in let e2 = z in let e3 = mk_FPlus [x; mk_FMult [y;z]] in let sec = x in let known = [ (p1,e1); (p2,e2); (p3,e3) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test4: solution valid" (eval_ctx known ctx) sec (* y -> x*z + y*v + u - w*y*z *) let test5 _ = let e1 = x in let e2 = z in let e3 = u in let e4 = v in let e5 = w in let e6 = mk_FPlus [mk_FMult [x;z]; mk_FMult [y;v]; u; mk_FOpp (mk_FMult [w; y; z])] in let sec = y in let known = [ (p1,e1); (p2,e2); (p3,e3); (p4,e4); (p5,e5); (p6,e6) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test5: solution valid" (eval_ctx known ctx) sec (* y -> x*u + y*v - w*y*u - w*y2*u*hh + z*u*hh + y2*v*hh *) let test6 _ = let e1 = x in let e2 = u in let e3 = v in let e4 = w in let e5 = y2 in let e6 = hh in let e7 = z in let e8 = mk_FPlus [ mk_FMult [x;u] ; mk_FMult [y;v] ; mk_FOpp (mk_FMult [w;y;u]) ; mk_FOpp (mk_FMult [w;y2;u;hh]) ; mk_FMult [z;u;hh] ; mk_FMult [y2;v;hh] ] in let sec = y in let known = [ (p1,e1); (p2,e2); (p3,e3); (p4,e4); (p5,e5); (p6,e6); (p7,e7); (p8,e8) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test6: solution valid" (eval_ctx known ctx) sec let suite = "Solve_fq" >::: [ "test_solve_fq_1" >:: test1 ; "test_solve_fq_2" >:: test2 ; "test_solve_fq_3" >:: test3 ; "test_solve_fq_4" >:: test4 ; "test_solve_fq_5" >:: test5 ; "test_solve_fq_6" >:: test6 ] let _ = run_test_tt_main suite
null
https://raw.githubusercontent.com/autolwe/autolwe/3452c3dae06fc8e9815d94133fdeb8f3b8315f32/src/Test/Test_Solve_Fq.ml
ocaml
x -> y*z + x y -> x*z + y*v + u - w*y*z y -> x*u + y*v - w*y*u - w*y2*u*hh + z*u*hh + y2*v*hh
open Norm open Type open Expr open DeducField open OUnit let vx = Vsym.mk "x" mk_Fq let vy = Vsym.mk "y" mk_Fq let vz = Vsym.mk "z" mk_Fq let vu = Vsym.mk "u" mk_Fq let vv = Vsym.mk "v" mk_Fq let vw = Vsym.mk "w" mk_Fq let vhh = Vsym.mk "hh" mk_Fq let (x,y,z) = (mk_V vx, mk_V vy, mk_V vz) let (u,v,w) = (mk_V vu, mk_V vv, mk_V vw) let hh = mk_V vhh let vx2 = Vsym.mk "x2" mk_Fq let vy2 = Vsym.mk "y2" mk_Fq let vz2 = Vsym.mk "z2" mk_Fq let vu2 = Vsym.mk "u2" mk_Fq let vv2 = Vsym.mk "v2" mk_Fq let vw2 = Vsym.mk "w2" mk_Fq let (x2,y2,z2) = (mk_V vx2, mk_V vy2, mk_V vz2 ) let (u2,v2,w2) = (mk_V vu2, mk_V vv2, mk_V vw2) let p1 = mk_V (Vsym.mk "p1" mk_Fq) let p2 = mk_V (Vsym.mk "p2" mk_Fq) let p3 = mk_V (Vsym.mk "p3" mk_Fq) let p4 = mk_V (Vsym.mk "p4" mk_Fq) let p5 = mk_V (Vsym.mk "p5" mk_Fq) let p6 = mk_V (Vsym.mk "p6" mk_Fq) let p7 = mk_V (Vsym.mk "p7" mk_Fq) let p8 = mk_V (Vsym.mk "p8" mk_Fq) let eval_ctx known ctx = let m = me_of_list known in norm_expr (e_subst m ctx) let test1 _ = let a = x in let b = mk_FPlus [x;z] in let sec = z in let known = [ (p1,a); (p2,b) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test1: solution valid" (eval_ctx known ctx) sec let test2 _ = let a = mk_FPlus [x;y] in let b = mk_FPlus [x;z] in let sec = z in let known = [ (p1,a); (p2,b) ] in assert_raises ~msg:"test2: no solution" Not_found (fun () -> solve_fq known sec) let test3 _ = let a = x in let b = mk_FPlus [x;z] in let c = y in let sec = mk_FMult [z;y] in let known = [ (p1,a); (p2,b); (p3,c) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test3: solution valid" (eval_ctx known ctx) sec test cases from rrandom for Cramer - Shoup ( modulo renaming ) let test4 _ = let e1 = y in let e2 = z in let e3 = mk_FPlus [x; mk_FMult [y;z]] in let sec = x in let known = [ (p1,e1); (p2,e2); (p3,e3) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test4: solution valid" (eval_ctx known ctx) sec let test5 _ = let e1 = x in let e2 = z in let e3 = u in let e4 = v in let e5 = w in let e6 = mk_FPlus [mk_FMult [x;z]; mk_FMult [y;v]; u; mk_FOpp (mk_FMult [w; y; z])] in let sec = y in let known = [ (p1,e1); (p2,e2); (p3,e3); (p4,e4); (p5,e5); (p6,e6) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test5: solution valid" (eval_ctx known ctx) sec let test6 _ = let e1 = x in let e2 = u in let e3 = v in let e4 = w in let e5 = y2 in let e6 = hh in let e7 = z in let e8 = mk_FPlus [ mk_FMult [x;u] ; mk_FMult [y;v] ; mk_FOpp (mk_FMult [w;y;u]) ; mk_FOpp (mk_FMult [w;y2;u;hh]) ; mk_FMult [z;u;hh] ; mk_FMult [y2;v;hh] ] in let sec = y in let known = [ (p1,e1); (p2,e2); (p3,e3); (p4,e4); (p5,e5); (p6,e6); (p7,e7); (p8,e8) ] in let ctx = solve_fq known sec in assert_equal ~msg:"test6: solution valid" (eval_ctx known ctx) sec let suite = "Solve_fq" >::: [ "test_solve_fq_1" >:: test1 ; "test_solve_fq_2" >:: test2 ; "test_solve_fq_3" >:: test3 ; "test_solve_fq_4" >:: test4 ; "test_solve_fq_5" >:: test5 ; "test_solve_fq_6" >:: test6 ] let _ = run_test_tt_main suite
90fc6ae46c88a6ef00b9e2363dde120c1d9eb9a8d2a869dc451a52aac57377f1
ucsd-progsys/mist
linearAccess.hs
type Linear size e1 e2 t a = Reader [ t ] a pure as forall t , a. size : Nat ~ > e1 ~ > x : a - > Linear size e1 e2 t { v : a | v = x } pure x = pure x ( > > =) as forall t , a , b. size : Nat ~ > e1 ~ > e2 ~ > e3 ~ > Linear size e1 e2 t a - > ( a - > Linear size e2 e3 t b ) - > Linear size e1 e3 t b read as forall t. size : Nat ~ > e ~ > n:{v : Int | v > = 0 & & v < size & & v ∉ e } - > Linear size e { v | v = e + { n } } t t read = ask > > = ( \r - > pure r!n ) runLinear as forall t , a. size : Nat ~ > Linear [ ] { v | len v = size } a ~ > { v : [ t ] | len v = size } - > a runAffine as forall t , a. size : Nat ~ > Linear [ ] { v | len v < = size } a ~ > { v : [ t ] | len v = size } - > a type Linear size e1 e2 t a = Reader [t] a pure as forall t, a. size:Nat ~> e1 ~> x:a -> Linear size e1 e2 t {v:a | v = x} pure x = pure x (>>=) as forall t, a, b. size:Nat ~> e1 ~> e2 ~> e3 ~> Linear size e1 e2 t a -> (a -> Linear size e2 e3 t b) -> Linear size e1 e3 t b read as forall t. size:Nat ~> e ~> n:{v: Int | v >= 0 && v < size && v ∉ e} -> Linear size e {v | v = e + {n}} t t read = ask >>= (\r -> pure r!n) runLinear as forall t, a. size:Nat ~> Linear [] {v | len v = size} a ~> {v: [t] | len v = size} -> a runAffine as forall t, a. size:Nat ~> Linear [] {v | len v <= size} a ~> {v: [t] | len v = size} -> a -}
null
https://raw.githubusercontent.com/ucsd-progsys/mist/0a9345e73dc53ff8e8adb8bed78d0e3e0cdc6af0/tests/Tests/Integration/todo/linearAccess.hs
haskell
type Linear size e1 e2 t a = Reader [ t ] a pure as forall t , a. size : Nat ~ > e1 ~ > x : a - > Linear size e1 e2 t { v : a | v = x } pure x = pure x ( > > =) as forall t , a , b. size : Nat ~ > e1 ~ > e2 ~ > e3 ~ > Linear size e1 e2 t a - > ( a - > Linear size e2 e3 t b ) - > Linear size e1 e3 t b read as forall t. size : Nat ~ > e ~ > n:{v : Int | v > = 0 & & v < size & & v ∉ e } - > Linear size e { v | v = e + { n } } t t read = ask > > = ( \r - > pure r!n ) runLinear as forall t , a. size : Nat ~ > Linear [ ] { v | len v = size } a ~ > { v : [ t ] | len v = size } - > a runAffine as forall t , a. size : Nat ~ > Linear [ ] { v | len v < = size } a ~ > { v : [ t ] | len v = size } - > a type Linear size e1 e2 t a = Reader [t] a pure as forall t, a. size:Nat ~> e1 ~> x:a -> Linear size e1 e2 t {v:a | v = x} pure x = pure x (>>=) as forall t, a, b. size:Nat ~> e1 ~> e2 ~> e3 ~> Linear size e1 e2 t a -> (a -> Linear size e2 e3 t b) -> Linear size e1 e3 t b read as forall t. size:Nat ~> e ~> n:{v: Int | v >= 0 && v < size && v ∉ e} -> Linear size e {v | v = e + {n}} t t read = ask >>= (\r -> pure r!n) runLinear as forall t, a. size:Nat ~> Linear [] {v | len v = size} a ~> {v: [t] | len v = size} -> a runAffine as forall t, a. size:Nat ~> Linear [] {v | len v <= size} a ~> {v: [t] | len v = size} -> a -}
72de2043e522e65dc0cd7ccf4364eeff368a320599ea1e8ef281d9c694a34721
fulcrologic/fulcro-inspect
main.cljs
(ns fulcro.inspect.electron.background.main (:require ["electron" :as electron] ["path" :as path] ["electron-settings" :as settings] ["url" :as url] [goog.functions :as g.fns] [fulcro.inspect.electron.background.server :as server])) (defn get-setting [k default] (or (.get settings k) default)) (defn set-setting! [k v] (.set settings k v)) (defn save-state! [window] (mapv (fn [[k v]] (set-setting! (str "BrowserWindow/" k) v)) (js->clj (.getBounds window)))) (defn toggle-settings-window! [] (server/send-message-to-renderer! {:type :fulcro.inspect.client/toggle-settings :data {}})) (defn create-window [] (let [win (electron/BrowserWindow. #js {:width (get-setting "BrowserWindow/width" 800) :height (get-setting "BrowserWindow/height" 600) :x (get-setting "BrowserWindow/x" js/undefined) :y (get-setting "BrowserWindow/y" js/undefined) :webPreferences #js {:nodeIntegration true}})] (.loadURL win (url/format #js {:pathname (path/join js/__dirname ".." ".." "index.html") :protocol "file:" :slashes "true"})) (when (get-setting "BrowserWindow/OpenDevTools?" false) (.. win -webContents openDevTools)) (.on (.-webContents win) "devtools-opened" #(set-setting! "BrowserWindow/OpenDevTools?" true)) (.on (.-webContents win) "devtools-closed" #(set-setting! "BrowserWindow/OpenDevTools?" false)) (let [save-window-state! (g.fns/debounce #(save-state! win) 500)] (doto win (.on "resize" save-window-state!) (.on "move" save-window-state!) (.on "close" save-window-state!))) (.setApplicationMenu electron/Menu (.buildFromTemplate electron/Menu FIXME : cmd only if is osx (clj->js [{:label (.-name electron/app) :submenu [{:role "about"} {:type "separator"} {:label "Settings" :accelerator "cmd+," :click #(toggle-settings-window!)} {:type "separator"} {:role "quit"}]} {:label "Edit" :submenu [{:label "Undo" :accelerator "CmdOrCtrl+Z" :selector "undo:"} {:label "Redo" :accelerator "Shift+CmdOrCtrl+Z" :selector "redo:"} {:type "separator"} {:label "Cut" :accelerator "CmdOrCtrl+X" :selector "cut:"} {:label "Copy" :accelerator "CmdOrCtrl+C" :selector "copy:"} {:label "Paste" :accelerator "CmdOrCtrl+V" :selector "paste:"} {:label "Select All" :accelerator "CmdOrCtrl+A" :selector "selectAll:"}]} {:label "View" :submenu [{:role "reload"} {:role "forcereload"} {:role "toggledevtools"} {:type "separator"} {:role "resetzoom"} {:role "zoomin" :accelerator "cmd+="} {:role "zoomout"} {:type "separator"} {:role "togglefullscreen"}]}]))) (server/start! (.-webContents win)))) (defn init [] (js/console.log "init") (electron/app.on "ready" create-window)) (defn done [] (js/console.log "Done reloading"))
null
https://raw.githubusercontent.com/fulcrologic/fulcro-inspect/a03b61cbd95384c0f03aa936368bcf5cf573fa32/src/electron/fulcro/inspect/electron/background/main.cljs
clojure
(ns fulcro.inspect.electron.background.main (:require ["electron" :as electron] ["path" :as path] ["electron-settings" :as settings] ["url" :as url] [goog.functions :as g.fns] [fulcro.inspect.electron.background.server :as server])) (defn get-setting [k default] (or (.get settings k) default)) (defn set-setting! [k v] (.set settings k v)) (defn save-state! [window] (mapv (fn [[k v]] (set-setting! (str "BrowserWindow/" k) v)) (js->clj (.getBounds window)))) (defn toggle-settings-window! [] (server/send-message-to-renderer! {:type :fulcro.inspect.client/toggle-settings :data {}})) (defn create-window [] (let [win (electron/BrowserWindow. #js {:width (get-setting "BrowserWindow/width" 800) :height (get-setting "BrowserWindow/height" 600) :x (get-setting "BrowserWindow/x" js/undefined) :y (get-setting "BrowserWindow/y" js/undefined) :webPreferences #js {:nodeIntegration true}})] (.loadURL win (url/format #js {:pathname (path/join js/__dirname ".." ".." "index.html") :protocol "file:" :slashes "true"})) (when (get-setting "BrowserWindow/OpenDevTools?" false) (.. win -webContents openDevTools)) (.on (.-webContents win) "devtools-opened" #(set-setting! "BrowserWindow/OpenDevTools?" true)) (.on (.-webContents win) "devtools-closed" #(set-setting! "BrowserWindow/OpenDevTools?" false)) (let [save-window-state! (g.fns/debounce #(save-state! win) 500)] (doto win (.on "resize" save-window-state!) (.on "move" save-window-state!) (.on "close" save-window-state!))) (.setApplicationMenu electron/Menu (.buildFromTemplate electron/Menu FIXME : cmd only if is osx (clj->js [{:label (.-name electron/app) :submenu [{:role "about"} {:type "separator"} {:label "Settings" :accelerator "cmd+," :click #(toggle-settings-window!)} {:type "separator"} {:role "quit"}]} {:label "Edit" :submenu [{:label "Undo" :accelerator "CmdOrCtrl+Z" :selector "undo:"} {:label "Redo" :accelerator "Shift+CmdOrCtrl+Z" :selector "redo:"} {:type "separator"} {:label "Cut" :accelerator "CmdOrCtrl+X" :selector "cut:"} {:label "Copy" :accelerator "CmdOrCtrl+C" :selector "copy:"} {:label "Paste" :accelerator "CmdOrCtrl+V" :selector "paste:"} {:label "Select All" :accelerator "CmdOrCtrl+A" :selector "selectAll:"}]} {:label "View" :submenu [{:role "reload"} {:role "forcereload"} {:role "toggledevtools"} {:type "separator"} {:role "resetzoom"} {:role "zoomin" :accelerator "cmd+="} {:role "zoomout"} {:type "separator"} {:role "togglefullscreen"}]}]))) (server/start! (.-webContents win)))) (defn init [] (js/console.log "init") (electron/app.on "ready" create-window)) (defn done [] (js/console.log "Done reloading"))
c5ecb39db577829ddd88a6107349da4853be3b5275d4846f2d3746bc12769c79
mbj/stratosphere
ActionProperty.hs
module Stratosphere.WAFRegional.WebACL.ActionProperty ( ActionProperty(..), mkActionProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data ActionProperty = ActionProperty {type' :: (Value Prelude.Text)} mkActionProperty :: Value Prelude.Text -> ActionProperty mkActionProperty type' = ActionProperty {type' = type'} instance ToResourceProperties ActionProperty where toResourceProperties ActionProperty {..} = ResourceProperties {awsType = "AWS::WAFRegional::WebACL.Action", supportsTags = Prelude.False, properties = ["Type" JSON..= type']} instance JSON.ToJSON ActionProperty where toJSON ActionProperty {..} = JSON.object ["Type" JSON..= type'] instance Property "Type" ActionProperty where type PropertyType "Type" ActionProperty = Value Prelude.Text set newValue ActionProperty {} = ActionProperty {type' = newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafregional/gen/Stratosphere/WAFRegional/WebACL/ActionProperty.hs
haskell
module Stratosphere.WAFRegional.WebACL.ActionProperty ( ActionProperty(..), mkActionProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data ActionProperty = ActionProperty {type' :: (Value Prelude.Text)} mkActionProperty :: Value Prelude.Text -> ActionProperty mkActionProperty type' = ActionProperty {type' = type'} instance ToResourceProperties ActionProperty where toResourceProperties ActionProperty {..} = ResourceProperties {awsType = "AWS::WAFRegional::WebACL.Action", supportsTags = Prelude.False, properties = ["Type" JSON..= type']} instance JSON.ToJSON ActionProperty where toJSON ActionProperty {..} = JSON.object ["Type" JSON..= type'] instance Property "Type" ActionProperty where type PropertyType "Type" ActionProperty = Value Prelude.Text set newValue ActionProperty {} = ActionProperty {type' = newValue, ..}
07fc37dfaff45b599ee0a08f41e0f34f238c91bada72e1b46d2e13dfd11def3e
coq/coq
invfun.ml
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) open Util open Names open Constr open EConstr open Tacmach open Tactics open Tacticals open Indfun_common (***********************************************) [ revert_graph kn post_tac hid ] transforme an hypothesis [ hid ] having type Ind(kn , num ) t1 ... when [ kn ] denotes a graph block into f_num t1 ... tn = res ( by applying [ f_complete ] to the first type ) before apply post_tac on the result if the type of hypothesis has not this form or if we can not find the completeness lemma then we do nothing when [kn] denotes a graph block into f_num t1... tn = res (by applying [f_complete] to the first type) before apply post_tac on the result if the type of hypothesis has not this form or if we cannot find the completeness lemma then we do nothing *) let revert_graph kn post_tac hid = Proofview.Goal.enter (fun gl -> let env = Proofview.Goal.env gl in let sigma = project gl in let typ = pf_get_hyp_typ hid gl in match EConstr.kind sigma typ with | App (i, args) when isInd sigma i -> let ((kn', num) as ind'), u = destInd sigma i in if Environ.QMutInd.equal env kn kn' then (* We have generated a graph hypothesis so that we must change it if we can *) let info = match find_Function_of_graph ind' with | Some info -> info | None -> The graphs are mutually recursive but we can not find one of them ! CErrors.anomaly (Pp.str "Cannot retrieve infos about a mutual block.") in (* if we can find a completeness lemma for this function then we can come back to the functional form. If not, we do nothing *) match info.completeness_lemma with | None -> tclIDTAC | Some f_complete -> let f_args, res = Array.chop (Array.length args - 1) args in tclTHENLIST [ generalize [ applist ( mkConst f_complete , Array.to_list f_args @ [res.(0); mkVar hid] ) ] ; clear [hid] ; Simple.intro hid ; post_tac hid ] else tclIDTAC | _ -> tclIDTAC) [ functional_inversion hid f_correct ] is the functional version of [ inversion ] [ hid ] is the hypothesis to invert , [ fconst ] is the function to invert and [ f_correct ] is the correctness lemma for [ ] . The sketch is the following~ : \begin{enumerate } \item Transforms the hypothesis [ hid ] such that its type is now $ res\ = \ f\ t_1 \ldots t_n$ ( fails if it is not possible ) replace [ hid ] with $ R\_f t_1 \ldots t_n res$ using [ f_correct ] \item apply [ inversion ] on [ hid ] \item finally in each branch , replace each hypothesis [ R\_f .. ] by [ f ... ] using [ f_complete ] ( whenever such a lemma exists ) \end{enumerate } [functional_inversion hid fconst f_correct ] is the functional version of [inversion] [hid] is the hypothesis to invert, [fconst] is the function to invert and [f_correct] is the correctness lemma for [fconst]. The sketch is the following~: \begin{enumerate} \item Transforms the hypothesis [hid] such that its type is now $res\ =\ f\ t_1 \ldots t_n$ (fails if it is not possible) \item replace [hid] with $R\_f t_1 \ldots t_n res$ using [f_correct] \item apply [inversion] on [hid] \item finally in each branch, replace each hypothesis [R\_f ..] by [f ...] using [f_complete] (whenever such a lemma exists) \end{enumerate} *) let functional_inversion kn hid fconst f_correct = Proofview.Goal.enter (fun gl -> let old_ids = List.fold_right Id.Set.add (pf_ids_of_hyps gl) Id.Set.empty in let sigma = project gl in let type_of_h = pf_get_hyp_typ hid gl in match EConstr.kind sigma type_of_h with | App (eq, args) when EConstr.eq_constr sigma eq (make_eq ()) -> let pre_tac, f_args, res = match (EConstr.kind sigma args.(1), EConstr.kind sigma args.(2)) with | App (f, f_args), _ when EConstr.eq_constr sigma f fconst -> ((fun hid -> intros_symmetry (Locusops.onHyp hid)), f_args, args.(2)) | _, App (f, f_args) when EConstr.eq_constr sigma f fconst -> ((fun hid -> tclIDTAC), f_args, args.(1)) | _ -> ((fun hid -> tclFAILn 1 Pp.(mt ())), [||], args.(2)) in tclTHENLIST [ pre_tac hid ; generalize [applist (f_correct, Array.to_list f_args @ [res; mkVar hid])] ; clear [hid] ; Simple.intro hid ; Inv.inv Inv.FullInversion None (Tactypes.NamedHyp (CAst.make hid)) ; Proofview.Goal.enter (fun gl -> let new_ids = List.filter (fun id -> not (Id.Set.mem id old_ids)) (pf_ids_of_hyps gl) in tclMAP (revert_graph kn pre_tac) (hid :: new_ids)) ] | _ -> tclFAILn 1 Pp.(mt ())) let invfun qhyp f = let f = match f with | GlobRef.ConstRef f -> f | _ -> CErrors.user_err Pp.(str "Not a function") in match find_Function_infos f with | None -> CErrors.user_err (Pp.str "No graph found") | Some finfos -> ( match finfos.correctness_lemma with | None -> CErrors.user_err (Pp.str "Cannot use equivalence with graph!") | Some f_correct -> let f_correct = mkConst f_correct and kn = fst finfos.graph_ind in Tactics.try_intros_until (fun hid -> functional_inversion kn hid (mkConst f) f_correct) qhyp ) let invfun qhyp f = let exception NoFunction in match f with | Some f -> invfun qhyp f | None -> let tac_action hid gl = let sigma = project gl in let hyp_typ = pf_get_hyp_typ hid gl in match EConstr.kind sigma hyp_typ with | App (eq, args) when EConstr.eq_constr sigma eq (make_eq ()) -> ( let f1, _ = decompose_app sigma args.(1) in try if not (isConst sigma f1) then raise NoFunction; let finfos = Option.get (find_Function_infos (fst (destConst sigma f1))) in let f_correct = mkConst (Option.get finfos.correctness_lemma) and kn = fst finfos.graph_ind in functional_inversion kn hid f1 f_correct with NoFunction | Option.IsNone -> let f2, _ = decompose_app sigma args.(2) in if isConst sigma f2 then match find_Function_infos (fst (destConst sigma f2)) with | None -> if do_observe () then CErrors.user_err (Pp.str "No graph found for any side of equality") else CErrors.user_err Pp.( str "Cannot find inversion information for hypothesis " ++ Ppconstr.pr_id hid) | Some finfos -> ( match finfos.correctness_lemma with | None -> if do_observe () then CErrors.user_err (Pp.str "Cannot use equivalence with graph for any side of the \ equality") else CErrors.user_err Pp.( str "Cannot find inversion information for hypothesis " ++ Ppconstr.pr_id hid) | Some f_correct -> let f_correct = mkConst f_correct and kn = fst finfos.graph_ind in functional_inversion kn hid f2 f_correct ) else NoFunction CErrors.user_err Pp.( str "Hypothesis " ++ Ppconstr.pr_id hid ++ str " must contain at least one Function") ) | _ -> CErrors.user_err Pp.(Ppconstr.pr_id hid ++ str " must be an equality ") in try_intros_until (tac_action %> Proofview.Goal.enter) qhyp
null
https://raw.githubusercontent.com/coq/coq/05e22aef122aed5564d879cbca6aa59f32afe220/plugins/funind/invfun.ml
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** ********************************************* We have generated a graph hypothesis so that we must change it if we can if we can find a completeness lemma for this function then we can come back to the functional form. If not, we do nothing
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Util open Names open Constr open EConstr open Tacmach open Tactics open Tacticals open Indfun_common [ revert_graph kn post_tac hid ] transforme an hypothesis [ hid ] having type Ind(kn , num ) t1 ... when [ kn ] denotes a graph block into f_num t1 ... tn = res ( by applying [ f_complete ] to the first type ) before apply post_tac on the result if the type of hypothesis has not this form or if we can not find the completeness lemma then we do nothing when [kn] denotes a graph block into f_num t1... tn = res (by applying [f_complete] to the first type) before apply post_tac on the result if the type of hypothesis has not this form or if we cannot find the completeness lemma then we do nothing *) let revert_graph kn post_tac hid = Proofview.Goal.enter (fun gl -> let env = Proofview.Goal.env gl in let sigma = project gl in let typ = pf_get_hyp_typ hid gl in match EConstr.kind sigma typ with | App (i, args) when isInd sigma i -> let ((kn', num) as ind'), u = destInd sigma i in if Environ.QMutInd.equal env kn kn' then let info = match find_Function_of_graph ind' with | Some info -> info | None -> The graphs are mutually recursive but we can not find one of them ! CErrors.anomaly (Pp.str "Cannot retrieve infos about a mutual block.") in match info.completeness_lemma with | None -> tclIDTAC | Some f_complete -> let f_args, res = Array.chop (Array.length args - 1) args in tclTHENLIST [ generalize [ applist ( mkConst f_complete , Array.to_list f_args @ [res.(0); mkVar hid] ) ] ; clear [hid] ; Simple.intro hid ; post_tac hid ] else tclIDTAC | _ -> tclIDTAC) [ functional_inversion hid f_correct ] is the functional version of [ inversion ] [ hid ] is the hypothesis to invert , [ fconst ] is the function to invert and [ f_correct ] is the correctness lemma for [ ] . The sketch is the following~ : \begin{enumerate } \item Transforms the hypothesis [ hid ] such that its type is now $ res\ = \ f\ t_1 \ldots t_n$ ( fails if it is not possible ) replace [ hid ] with $ R\_f t_1 \ldots t_n res$ using [ f_correct ] \item apply [ inversion ] on [ hid ] \item finally in each branch , replace each hypothesis [ R\_f .. ] by [ f ... ] using [ f_complete ] ( whenever such a lemma exists ) \end{enumerate } [functional_inversion hid fconst f_correct ] is the functional version of [inversion] [hid] is the hypothesis to invert, [fconst] is the function to invert and [f_correct] is the correctness lemma for [fconst]. The sketch is the following~: \begin{enumerate} \item Transforms the hypothesis [hid] such that its type is now $res\ =\ f\ t_1 \ldots t_n$ (fails if it is not possible) \item replace [hid] with $R\_f t_1 \ldots t_n res$ using [f_correct] \item apply [inversion] on [hid] \item finally in each branch, replace each hypothesis [R\_f ..] by [f ...] using [f_complete] (whenever such a lemma exists) \end{enumerate} *) let functional_inversion kn hid fconst f_correct = Proofview.Goal.enter (fun gl -> let old_ids = List.fold_right Id.Set.add (pf_ids_of_hyps gl) Id.Set.empty in let sigma = project gl in let type_of_h = pf_get_hyp_typ hid gl in match EConstr.kind sigma type_of_h with | App (eq, args) when EConstr.eq_constr sigma eq (make_eq ()) -> let pre_tac, f_args, res = match (EConstr.kind sigma args.(1), EConstr.kind sigma args.(2)) with | App (f, f_args), _ when EConstr.eq_constr sigma f fconst -> ((fun hid -> intros_symmetry (Locusops.onHyp hid)), f_args, args.(2)) | _, App (f, f_args) when EConstr.eq_constr sigma f fconst -> ((fun hid -> tclIDTAC), f_args, args.(1)) | _ -> ((fun hid -> tclFAILn 1 Pp.(mt ())), [||], args.(2)) in tclTHENLIST [ pre_tac hid ; generalize [applist (f_correct, Array.to_list f_args @ [res; mkVar hid])] ; clear [hid] ; Simple.intro hid ; Inv.inv Inv.FullInversion None (Tactypes.NamedHyp (CAst.make hid)) ; Proofview.Goal.enter (fun gl -> let new_ids = List.filter (fun id -> not (Id.Set.mem id old_ids)) (pf_ids_of_hyps gl) in tclMAP (revert_graph kn pre_tac) (hid :: new_ids)) ] | _ -> tclFAILn 1 Pp.(mt ())) let invfun qhyp f = let f = match f with | GlobRef.ConstRef f -> f | _ -> CErrors.user_err Pp.(str "Not a function") in match find_Function_infos f with | None -> CErrors.user_err (Pp.str "No graph found") | Some finfos -> ( match finfos.correctness_lemma with | None -> CErrors.user_err (Pp.str "Cannot use equivalence with graph!") | Some f_correct -> let f_correct = mkConst f_correct and kn = fst finfos.graph_ind in Tactics.try_intros_until (fun hid -> functional_inversion kn hid (mkConst f) f_correct) qhyp ) let invfun qhyp f = let exception NoFunction in match f with | Some f -> invfun qhyp f | None -> let tac_action hid gl = let sigma = project gl in let hyp_typ = pf_get_hyp_typ hid gl in match EConstr.kind sigma hyp_typ with | App (eq, args) when EConstr.eq_constr sigma eq (make_eq ()) -> ( let f1, _ = decompose_app sigma args.(1) in try if not (isConst sigma f1) then raise NoFunction; let finfos = Option.get (find_Function_infos (fst (destConst sigma f1))) in let f_correct = mkConst (Option.get finfos.correctness_lemma) and kn = fst finfos.graph_ind in functional_inversion kn hid f1 f_correct with NoFunction | Option.IsNone -> let f2, _ = decompose_app sigma args.(2) in if isConst sigma f2 then match find_Function_infos (fst (destConst sigma f2)) with | None -> if do_observe () then CErrors.user_err (Pp.str "No graph found for any side of equality") else CErrors.user_err Pp.( str "Cannot find inversion information for hypothesis " ++ Ppconstr.pr_id hid) | Some finfos -> ( match finfos.correctness_lemma with | None -> if do_observe () then CErrors.user_err (Pp.str "Cannot use equivalence with graph for any side of the \ equality") else CErrors.user_err Pp.( str "Cannot find inversion information for hypothesis " ++ Ppconstr.pr_id hid) | Some f_correct -> let f_correct = mkConst f_correct and kn = fst finfos.graph_ind in functional_inversion kn hid f2 f_correct ) else NoFunction CErrors.user_err Pp.( str "Hypothesis " ++ Ppconstr.pr_id hid ++ str " must contain at least one Function") ) | _ -> CErrors.user_err Pp.(Ppconstr.pr_id hid ++ str " must be an equality ") in try_intros_until (tac_action %> Proofview.Goal.enter) qhyp
318f96f8a7345697d8792cb5c29de4c182b78d999cf97209a15a7073e0625328
BekaValentine/SimpleFP-v2
TypeChecking.hs
{-# OPTIONS -Wall #-} -- | A unification-based type checker. module Require.Unification.TypeChecking where import Utils.ABT import Utils.Elaborator import Utils.Eval import Utils.Names import Utils.Plicity import Utils.Pretty import Utils.Unifier import Utils.Telescope import Utils.Vars import Require.Core.ConSig import Require.Core.Evaluation () import Require.Core.Term import Require.Unification.Elaborator import Require.Unification.Unification () import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State import Data.List (inits) -- | In the dependently typed variant, it's useful to have a type for normal -- terms. While this type won't actually be representationally different, we -- can use it to help ensure we're using normal forms in places where we want -- them, such as the type arguments to checking. newtype NormalTerm = NormalTerm { normTerm :: Term } -- | It's useful to have a way of evaluating without having to constantly get -- make an environment and run the evaluator manually. evaluate :: SubstitutedTerm -> TypeChecker NormalTerm evaluate (SubstitutedTerm m) = do defs <- getElab definitions l <- getElab quoteLevel case runReaderT (paramEval l m) (definitionsToEnvironment defs) of Left e -> throwError e Right m' -> return $ NormalTerm m' -- | Similarly, it's also useful to be able to ensure that we're using terms -- that have been substituted into. This doesn't exist in the monadic variant -- because there's no unification going on. newtype SubstitutedTerm = SubstitutedTerm Term substitute :: Term -> TypeChecker SubstitutedTerm substitute t = do subs <- getElab substitution return $ SubstitutedTerm (substMetas subs t) -- | Another helpful type, used for ensuring that we return elaborated terms -- from inference and checking. newtype ElaboratedTerm = ElaboratedTerm { elabTerm :: Term } -- | We'd like to make sure that unification only happens to normal terms, so -- we'll define a convenience function we can use. unifyHelper :: NormalTerm -> NormalTerm -> TypeChecker () unifyHelper (NormalTerm x) (NormalTerm y) = unifyJ substitution context x y | We can unalias a name . This corresponds to the judgment @L ∋ n alias n'@ -- which is just an lookup on aliases. @n@ here can be either a bare local name such as @foo@ or a dotted name like @Mod.foo@ , and @n'@ is an absolute name unalias :: Name -> TypeChecker (String,String) unalias (BareLocal n) = do als <- getElab aliases case lookup (Left n) als of Nothing -> throwError $ "The symbol " ++ n ++ " is not an alias for any " ++ "module-declared symbol." Just p -> return p unalias (DottedLocal m n) = do als <- getElab aliases case lookup (Right (m,n)) als of Nothing -> throwError $ "The symbol " ++ m ++ "." ++ n ++ " is not an alias for any " ++ "module-declared symbol." Just p -> return p unalias (Absolute m n) = return (m,n) -- | We can modify the quote level we check at by adding a quote level. addQuoteLevel :: TypeChecker a -> TypeChecker a addQuoteLevel tc = do l <- getElab quoteLevel putElab quoteLevel (l+1) x <- tc putElab quoteLevel l return x -- | We can modify the quote level we check at by removing a quote level. removeQuoteLevel :: TypeChecker a -> TypeChecker a removeQuoteLevel tc = do l <- getElab quoteLevel putElab quoteLevel (l-1) x <- tc putElab quoteLevel l return x -- | We can get the consig of a constructor by looking in the signature. -- This corresponds to the judgment @Σ ∋ n ▹ n' con S@. In the presence of -- aliases, this also requires some amount of elaboration. typeInSignature :: Name -> Elaborator (Name,ConSig) typeInSignature n0 = do (m,n) <- unalias n0 consigs <- getElab signature case lookup (m,n) consigs of Nothing -> throwError $ "Unknown constructor: " ++ showName (Absolute m n) Just t -> return (Absolute m n, t) -- | We can get the type of a declared name by looking in the definitions. -- This corresponds to the judgment @Δ ∋ n ▹ n' : A@. In the presence of -- aliases, this also requires some amount of elaboration. typeInDefinitions :: Name -> Elaborator (Name,Term) typeInDefinitions n0 = do (m,n) <- unalias n0 defs <- getElab definitions case lookup (m,n) defs of Nothing -> throwError $ "Unknown constant/defined term: " ++ showName (Absolute m n) Just (_,t) -> return (Absolute m n, t) -- | We can get the type of a free variable by looking in the context. This corresponds to the judgment : A at l@ typeInContext :: FreeVar -> Elaborator (QLJ Term) typeInContext v@(FreeVar n) = do ctx <- getElab context case lookup v ctx of Nothing -> throwError $ "Unbound variable: " ++ n Just t -> return t -- | We can extend the set of reset positions in scope currently. extendResets :: [String] -> Elaborator a -> Elaborator a extendResets newResets tc = do resets <- getElab resetPointsInScope putElab resetPointsInScope (newResets ++ resets) x <- tc putElab resetPointsInScope resets return x -- | We can get the types of a reset point. getResetPoint :: String -> Elaborator (Term,Term) getResetPoint res = do resets <- getElab resetPoints case lookup res resets of Nothing -> throwError $ "The reset point " ++ res ++ " has not been declared." Just (lower,upper) -> return (lower,upper) -- | We can add a shifted reset point by pushing it onto the in scope shift -- stack, and zeroing out the context temporarilly. addShift :: String -> Elaborator a -> Elaborator a addShift res tc = do shifts <- getElab shiftsInScope putElab shiftsInScope (res:shifts) ctx <- getElab context l <- getElab quoteLevel putElab context (filter (\(_, QLJ _ l') -> l' < l) ctx) x <- tc putElab context ctx putElab shiftsInScope shifts return x -- | We can remove a shift by popping a the top shift from the shift stack. removeShift :: Elaborator a -> Elaborator a removeShift tc = do shifts <- getElab shiftsInScope case shifts of [] -> tc _:shifts' -> do putElab shiftsInScope shifts' x <- tc putElab shiftsInScope shifts return x | Type inference corresponds to the judgment @Γ ⇒ A true@. This throws a error when trying to infer the type of a bound variable , -- because all bound variables should be replaced by free variables during -- this part of type checking. -- The second term @M'@ in the judgment is the output term that has all -- implicit arguments elaborated. For instance, application of a function -- with implicit arguments initially will need to have those arguments -- inserted. Those arguments are necessary for computation, so we need to -- have a resulting elaborated term returned by the type checker. -- The judgment ⇒ A true@ is defined inductively as follows : -- -- @ -- Γ ∋ x : A at l -- ------------------ variable ▹ x ⇒ A at l -- -- Δ ∋ n ▹ n' : A -- ------------------------------------- definition defined[n ] ▹ defined[n ' ] ⇒ A at l -- ▹ A ' ⇐ Type at l Γ ⊢ M ▹ M ' ⇐ A ' at l -- ---------------------------------------------- annotation -- Γ ⊢ M : A ▹ M' : A' ⇒ A' at l -- -- --------------------------- type at l -- ▹ A ' ⇐ Type at l Γ , x : A ' at l ⊢ B ▹ B ' ⇐ Type at l -- ------------------------------------------------------------ function ( x : A ) - > B ▹ ( x : A ' ) - > B ' ⇒ Type at l -- ⇒ S at l Γ ⊢ M ' at S applied Plic to N ▹ P ⇒ B -- ----------------------------------------------------------- application ) ▹ P ⇒ B at l -- c ▹ c ' sig(Pl*;(A*)B ) ) at B of M * ▹ M * ' ⇒ B ' -- --------------------------------------- con data ) ▹ con[c'](M * ' ) ⇒ B ' at l -- : A0, ... ,xm : Am)B ) motive ⇐ A0 at l -- ... ⇐ [ ... ]An at l ( : A0) ... (xm : Am)B -- ------------------------------------------------------------------- case ... ,Mm ; mot((x0 : A0, ... )B ) ; C0, ... ,Cn ) ⇒ [ M0 / x0, ... ]B at l -- ▹ A0 ' ⇐ Type at l Γ , : A0 ' at l ⊢ A1 ▹ A1 ' ⇐ Type at l -- ... Γ , : A0 ' at l , ... , xn-1 : ' at l An ' ⇐ Type at l -- --------------------------------------------------------------- rec x0 : A0 , ... , xn : An } ▹ rec : A0 ' , ... , xn : An ' } ⇒ Type at l -- Γ ⊢ M ▹ M ' ⇒ { : A0 , ... , xn : An } at l -- ------------------------------------------------------ projection Γ ⊢ M.xi ▹ M'.xi ⇒ [ M'.x0 / x0 , ... , / xi-1]Ai at l -- -- Γ ; K' ⊢ A ▹ A' ⇐ Type at l Resets ∋ Ki -- ----------------------------------------------- quoted -- Γ ; K' ⊢ Quoted[K] A ▹ Quoted[K] A' ⇒ Type at l -- -- Γ ; K' ⊢ M ▹ M' ⇒ Quoted[K] A at l-1 K ⊆ K' -- ---------------------------------------------- unquote Γ ; K ' ⊢ ~M ▹ ~M ' ⇒ A at l -- -- Resets ∋ s : A resets B Γ ; S ⊢ M ▹ M' ⇐ A at l+1 -- ---------------------------------------------------- continue -- Γ ; S, s ⊢ continue M ▹ continue M' ⇒ B at l+1 -- Resets ∋ k : A resets B Γ @ ; K , k ; S , k ⊢ M ▹ M ' ⇐ B at l+1 -- -------------------------------------------------------------- shift Γ ; K , k ; S ⊢ shift k in M ▹ shift k in M ' ⇒ A at l+1 -- -- Resets ∋ k : A resets B Γ ; K, k ⊢ M ▹ M' ⇐ B at l+1 -- ------------------------------------------------------- reset Γ ; K ⊢ reset k in M ▹ reset k in M ' ⇒ B at l+1 -- @ -- -- This judgment will also happily infer the type of a constructor, because -- it has similarities to functions in that the "type" (really, signature) is -- given prior to the arguments. However, unlike functions, this is not -- guaranteed to work, as constructors in theory should be checked, not -- inferred. This is a kind of best-effort inferrence, that will sometimes -- fail in practice (tho the judgment doesn't make this clear) when the -- constructor in question has implicit arguments that take part in computed -- indexes of the return type. For instance, the type -- -- @ data Inv ( f : ) ( y : ) where | MkInv { f : } ( x : ) : Inv f ( f x ) -- end -- @ -- This would happily check , for instance @MkInv 3 : Inv ( +2 ) 1@ , but to try to infer the type of @MkInv@ requires implicitly fetermining some function @f@ , which is obviously not possible , as there could be infinitely many . -- In other cases, the implicit argument to the constructor may not even be -- an index of the type, making the inference problem even harder. This -- function is therefore only for certain use cases, where the constructor is -- "obviously" inferrable. inferify :: Term -> TypeChecker (ElaboratedTerm,Term) inferify (Var (Free x)) = do QLJ t lvl <- typeInContext x curLvl <- getElab quoteLevel unless (curLvl == lvl) $ throwError $ "Mismatching quote levels for " ++ pretty (Var (Free x) :: Term) return (ElaboratedTerm (Var (Free x)), t) inferify (Var (Bound _ _)) = error "Bound type variables should not be the subject of type checking." inferify (Var (Meta x)) = throwError $ "The metavariable " ++ show x ++ " appears in checkable code, when it should not." inferify (In (Defined x)) = do (ex,t) <- typeInDefinitions x return (ElaboratedTerm (In (Defined ex)), t) inferify (In (Ann m t0)) = do let t = instantiate0 t0 ElaboratedTerm elt <- checkify t (NormalTerm (In Type)) et <- evaluate (SubstitutedTerm elt) -- @t@ can't be changed by checking. elm <- checkify (instantiate0 m) et return (elm, normTerm et) inferify (In Type) = return $ (ElaboratedTerm (In Type), In Type) inferify (In (Fun plic arg0 sc)) = do let arg = instantiate0 arg0 ElaboratedTerm elarg <- checkify arg (NormalTerm (In Type)) [x@(FreeVar n)] <- freshRelTo (names sc) context l <- getElab quoteLevel ElaboratedTerm elbody <- extendElab context [(x, QLJ elarg l)] $ checkify (instantiate sc [Var (Free x)]) (NormalTerm (In Type)) let t' = funH plic n elarg elbody SubstitutedTerm subt' <- substitute t' return (ElaboratedTerm subt', In Type) inferify (In (Lam _ _)) = throwError "Cannot infer the type of a lambda expression." inferify (In (App plic f0 a0)) = do let f = instantiate0 f0 a = instantiate0 a0 (ElaboratedTerm elf,t) <- inferify f subt <- substitute t NormalTerm et <- evaluate subt (app',t') <- inferifyApplication elf et plic a SubstitutedTerm subapp' <- substitute app' SubstitutedTerm subt' <- substitute t' return (ElaboratedTerm subapp', subt') inferify (In (Con c ms0)) = do (ec, ConSig plics (BindingTelescope ascs bsc)) <- typeInSignature c let ts = zip plics ascs ms = [ (plic, instantiate0 m) | (plic,m) <- ms0 ] (ms',b') <- inferifyConArgs ts bsc ms let m' = conH ec ms' SubstitutedTerm subm' <- substitute m' return (ElaboratedTerm subm', b') inferify (In (Case as0 motive cs)) = do let as = map instantiate0 as0 elmotive <- checkifyCaseMotive motive let CaseMotive tele = elmotive (args,ret) = instantiateBindingTelescope tele as las = length as largs = length args unless (las == largs) $ throwError $ "Motive " ++ pretty motive ++ " expects " ++ show largs ++ " case " ++ (if largs == 1 then "arg" else "args") ++ " but was given " ++ show las eargs <- mapM (evaluate.SubstitutedTerm) args -- @args@ is already substituted elas <- zipWithM checkify as eargs elcs <- forM cs $ \c -> checkifyClause c elmotive let m' = caseH (map elabTerm elas) elmotive elcs SubstitutedTerm subm' <- substitute m' return (ElaboratedTerm subm', ret) inferify (In (RecordType fields tele)) = do tele' <- checkifyTelescope tele return (ElaboratedTerm (In (RecordType fields tele')), In Type) inferify (In (RecordCon _)) = throwError "Cannot infer the type of a record." inferify (In (RecordProj r x)) = do (ElaboratedTerm r',t) <- inferify (instantiate0 r) subt <- substitute t NormalTerm et <- evaluate subt case et of In (RecordType fields (Telescope ascs')) -> let fieldTable = zip fields (instantiations r' fields ascs') in case lookup x fieldTable of Nothing -> throwError $ "Missing field " ++ x Just fieldT -> return (ElaboratedTerm (recordProjH r' x), fieldT) _ -> throwError $ "Expecting a record type but found " ++ pretty et where | This just defines all the possible projections of @r'@ using fields @fs'@ , eg . @projections R [ " foo","bar","baz"]@ is the terms -- @R.foo@, @R.bar@, and @R.baz@. projections :: Term -> [String] -> [Term] projections r' fs' = [ recordProjH r' f' | f' <- fs' ] -- | This instantiates scopes from a record type at all its possible -- fields, so that you get the types for each field. For instance, -- we want to take a record @R : Rec { foo : A, bar : B}@ and extract @A@ for the type of @R.foo@ and @[R.foo / foo]B@ for the type of @R.bar@. instantiations :: Term -> [String] -> [Scope TermF] -> [Term] instantiations r' fs' ascs' = zipWith instantiate ascs' (inits (projections r' fs')) inferify (In (QuotedType resets a)) = do ElaboratedTerm ela <- checkify (instantiate0 a) (NormalTerm (In Type)) return (ElaboratedTerm (quotedTypeH resets ela), In Type) inferify (In (Quote _)) = throwError "Cannot infer the type of a quoted term." inferify (In (Unquote m)) = do (ElaboratedTerm elm, t) <- removeQuoteLevel $ inferify (instantiate0 m) subt <- substitute t NormalTerm et <- evaluate subt case et of In (QuotedType res a) -> do resets <- getElab resetPointsInScope unless (all (`elem` resets) res) $ throwError $ "Reset points mismatch for the term " ++ pretty (instantiate0 m) ++ " which has points " ++ unwords res ++ " and the context which has " ++ unwords resets return (ElaboratedTerm (unquoteH elm), instantiate0 a) _ -> throwError $ "Expected a quoted type but found " ++ pretty et inferify (In (Continue m)) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use continuations outside of a quote." shifts <- getElab shiftsInScope case shifts of [] -> throwError $ "Cannot continue with " ++ pretty (instantiate0 m) ++ " because there are no shifted reset points in scope." res:_ -> do (lower,upper) <- getResetPoint res ElaboratedTerm elm <- removeShift $ checkify (instantiate0 m) (NormalTerm lower) return (ElaboratedTerm (continueH elm), upper) inferify (In (Shift res m)) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use continuations outside of a quote." resets <- getElab resetPointsInScope unless (res `elem` resets) $ throwError $ "The reset point " ++ res ++ " is not in scope." (lower,upper) <- getResetPoint res ElaboratedTerm elm <- addShift res $ checkify (instantiate0 m) (NormalTerm upper) return (ElaboratedTerm (shiftH res elm), lower) inferify (In (Reset res m)) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use continuations outside of a quote." (_,upper) <- getResetPoint res ElaboratedTerm elm <- extendResets [res] $ checkify (instantiate0 m) (NormalTerm upper) return (ElaboratedTerm (resetH res elm), upper) inferify (In (Require _ _)) = throwError "Cannot infer the type of a require term." -- | Because implicit application exists to make certain applications more -- convenient for the user, we want to be able to apply a function which has some number of implicit arguments first to an explicit argument by -- inserting however many implicit arguments as necessary. That is, given @M : { : A0 } - > ... - > { xn : An } - > ( y : B ) - > C@ and @N : B@ we want -- to be able to write @M N@ and have that type check. So we have this helper judgment at S applied Plic to N ▹ P ⇒ B@ to make ' inferify ' easier -- to define. -- -- This can be seen as actually not necessary, where the above rules are -- defined instead purely in terms of just application, since the underlying -- type theory doesn't have truly implicit application of any sort, but -- because this is an elaborating type checker, it's clearer if we explain -- things in terms of this. -- -- @ -- Γ ⊢ N ▹ N' ⇐ A true -- -------------------------------------------------------------- at ( x : A ) - > B applied explicitly to ⇒ [ N'/x]B -- -- Γ ⊢ N ▹ N' ⇐ A true -- -------------------------------------------------------------- at { x : A } - > B applied implicitly to N ▹ M N ' ⇒ [ N'/x]B -- -- Γ ⊢ M {P} at [P/x]B applied explicitly to N ▹ Q ⇒ C -- ----------------------------------------------------- at { x : A } - > B applied explicitly to N ▹ Q ⇒ C -- @ inferifyApplication :: Term -> Term -> Plicity -> Term -> TypeChecker (Term,Term) inferifyApplication f (In (Fun Expl a sc)) Expl m = do ElaboratedTerm m' <- checkify m (NormalTerm (instantiate0 a)) return (appH Expl f m', instantiate sc [m']) inferifyApplication f (In (Fun Impl a sc)) Impl m = do ElaboratedTerm m' <- checkify m (NormalTerm (instantiate0 a)) return (appH Impl f m', instantiate sc [m']) inferifyApplication f (In (Fun Expl _ _)) Impl m = throwError $ "Mismatching plicities when checking the application " ++ pretty (appH Impl f m) inferifyApplication f (In (Fun Impl _ sc)) Expl m = do meta <- nextElab nextMeta let f' = appH Impl f (Var (Meta meta)) t' = instantiate sc [Var (Meta meta)] inferifyApplication f' t' Expl m inferifyApplication f _ _ _ = throwError $ "Cannot apply non-function: " ++ pretty f -- | As with function application, we can infer the type of a constructor -- application while simultaneously inserting implicit arguments with the judgment at B of M * ▹ M * ' ⇒ where @T@ is a sequence of -- plicity-scope pairs (which we treat as a telescope for readability), and @M*@ and @M*'@ are plicity - term pairs . The judgment is defined as -- -- @ -- ------------------------ at B of e ▹ e ⇒ B -- Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇒ B ' -- ---------------------------------------------------------------------- , : A0 ) , T at B of ( Expl , M0 ) , M * ▹ ( Expl , M0 ' ) , M * ' ⇒ B ' -- Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇒ B ' -- ---------------------------------------------------------------------- ( Impl , : A0 ) , T at B of ( Impl , M0 ) , M * ▹ ( Impl , M0 ' ) , M * ' ⇒ B ' -- Γ ⊢ [ P / xi]T at [ P / xi]B of ( Expl , M0 ) , M * ▹ M * ' ⇒ B ' -- ----------------------------------------------------------------- ( Impl , xi : Ai ) , T at B of ( Expl , M0 ) , M * ▹ ( Impl , P ) , M * ' ⇒ B ' -- @ inferifyConArgs :: [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Term)] -> TypeChecker ([(Plicity,Term)], Term) inferifyConArgs ascs0 bsc0 ms0 = go [] ascs0 bsc0 ms0 where go :: [(Plicity,Term)] -> [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Term)] -> TypeChecker ([(Plicity,Term)], Term) go acc [] bsc [] = return (acc, instantiate bsc (map snd acc)) go acc ((Expl,asc):ascs) bsc ((Expl,m):ms) = do suba <- substitute (instantiate asc (map snd acc)) ea <- evaluate suba ElaboratedTerm m' <- checkify m ea go (acc ++ [(Expl,m')]) ascs bsc ms go acc ((Impl,asc):ascs) bsc ((Impl,m):ms) = do suba <- substitute (instantiate asc (map snd acc)) ea <- evaluate suba ElaboratedTerm m' <- checkify m ea go (acc ++ [(Impl,m')]) ascs bsc ms go acc ((Impl,_):ascs) bsc ms = do meta <- nextElab nextMeta go (acc ++ [(Impl,Var (Meta meta))]) ascs bsc ms go _ _ _ _ = throwError "Cannot match signature." | Type checking corresponds to the judgment @Γ ⇐ A true@. The -- implementation inserts implicit lambdas as necessary because implicit -- arguments exist to make the language more convenient. -- The judgment ⇐ A true@ is defined inductively as follows : -- -- @ -- Γ, x : A true ⊢ M ▹ M' ⇐ B true -- ----------------------------------------------------- lambda . M ) ▹ lam(Pl;x . M ' ) ⇐ Fun(Pl ; A ; x. B ) true -- c ▹ c ' sig(Pl*;(A*)B ) ) at B of M * ▹ M * ' ⇐ B ' true -- ------------------------------------------ con data -- Γ ⊢ con[c](M*) ▹ con[c'](M*') ⇐ B' true -- ⇒ A ' true A = A ' -- ----------------------------- direction change -- Γ ⊢ M ▹ M' ⇐ A true -- M0 ' ⇐ A0 true Γ ⊢ M1 ▹ M1 ' ⇐ [ M0'/x0]A1 true -- ... ▹ Mn ' ⇐ [ ... ,Mn-1'/xn-1]An true -- ----------------------------------------------------------- record Γ ⊢ { x0 = M0 , ... , xn : Mn } ▹ { x0 = M0 ' , ... , xn : Mn ' } ⇐ rec { : A0 , ... , xn : An } true -- -- Γ ; K ⊢ M ▹ M' ⇐ A at l+1 -- ------------------------------------ quote -- Γ ; K' ⊢ `M ▹ `M' ⇐ Quoted[K] A at l -- ▹ A ' ⇐ Type at l+1 Γ , x : A ' at l+1 ⊢ M ▹ M ' ⇐ B at l+1 ----------------------------------------------------------------- req Γ ⊢ require x : A in M ▹ require x : A ' in M ' ⇐ B at l+1 -- @ checkify :: Term -> NormalTerm -> TypeChecker ElaboratedTerm checkify (In (Lam plic sc)) (NormalTerm t) = do lam' <- case (plic,t) of \x - > M : ( x : A ) - > B do [v@(FreeVar n)] <- freshRelTo (names sc) context let x = Var (Free v) ElaboratedTerm m' <- do l <- getElab quoteLevel extendElab context [(v,QLJ (instantiate0 a) l)] $ checkify (instantiate sc [x]) (NormalTerm (instantiate sc2 [x])) return $ lamH Expl n m' (Impl, In (Fun Impl a sc2)) -> -- \{x} -> M : {x : A} -> B do [v@(FreeVar n)] <- freshRelTo (names sc) context let x = Var (Free v) ElaboratedTerm m' <- do l <- getElab quoteLevel extendElab context [(v,QLJ (instantiate0 a) l)] $ checkify (instantiate sc [x]) (NormalTerm (instantiate sc2 [x])) return $ lamH Impl n m' \x - > M : { y : A } - > B do [v@(FreeVar n)] <- freshRelTo (names sc2) context let x = Var (Free v) ElaboratedTerm m' <- do l <- getElab quoteLevel extendElab context [(v,QLJ (instantiate0 a) l)] $ checkify (In (Lam plic sc)) (NormalTerm (instantiate sc2 [x])) return $ lamH Impl n m' (Impl, In (Fun Expl _ _)) -> -- \{x} -> M : (y : A) -> B throwError $ "Expected an explicit argument but found an implicit " ++ "argument when checking " ++ pretty (In (Lam plic sc)) ++ " matches the signature " ++ pretty t _ -> throwError $ "Cannot check term: " ++ pretty (In (Lam plic sc)) ++ "\nAgainst non-function type: " ++ pretty t SubstitutedTerm sublam' <- substitute lam' return $ ElaboratedTerm sublam' checkify (In (Con c ms)) (NormalTerm t) = do (ec,ConSig plics (BindingTelescope ascs bsc)) <- typeInSignature c elms' <- checkifyConArgs (zip plics ascs) bsc [ (plic, instantiate0 m) | (plic,m) <- ms ] t let ms' = [ (plic,m') | (plic, ElaboratedTerm m') <- elms' ] elm = conH ec ms' SubstitutedTerm subelm <- substitute elm return $ ElaboratedTerm subelm checkify (In (RecordCon fields)) (NormalTerm t) = case t of In (RecordType typeFields (Telescope ascs)) -> if length typeFields >= length fields then case lookupMany typeFields fields of Left missingField -> throwError $ "Cannot check the record " ++ pretty (In (RecordCon fields)) ++ " against type " ++ pretty t ++ " because the record is missing the field " ++ missingField Right ms -> do ms' <- go [] (map instantiate0 ms) ascs return $ ElaboratedTerm (recordConH (zip typeFields ms')) else throwError $ "Cannot check the record " ++ pretty (In (RecordCon fields)) ++ " against type " ++ pretty t ++ " because the record has too many fields" _ -> throwError $ "Cannot check the record " ++ pretty (In (RecordCon fields)) ++ " against type " ++ pretty t where lookupMany :: Eq k => [k] -> [(k,v)] -> Either k [v] lookupMany [] _ = Right [] lookupMany (k:ks) kvs = case lookup k kvs of Nothing -> Left k Just v -> do vs <- lookupMany ks kvs return (v:vs) go :: [Term] -> [Term] -> [Scope TermF] -> TypeChecker [Term] go acc [] [] = return acc go acc (m:ms) (asc:ascs) = do suba <- substitute (instantiate asc acc) ea <- evaluate suba ElaboratedTerm m' <- checkify m ea go (acc ++ [m']) ms ascs go _ _ _ = error $ "This case of 'go' in 'checkify' of a record type should " ++ "be unreachable." checkify (In (Quote m)) (NormalTerm t) = case t of In (QuotedType res a) -> do ElaboratedTerm em <- addQuoteLevel $ extendResets res $ checkify (instantiate0 m) (NormalTerm (instantiate0 a)) return $ ElaboratedTerm (quoteH em) _ -> throwError $ "Cannot check quoted term " ++ pretty (In (Quote m)) ++ " against type " ++ pretty t checkify (In (Require a sc)) (NormalTerm t) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use requires outside of a quote." ElaboratedTerm ea <- checkify (instantiate0 a) (NormalTerm (In Type)) [x@(FreeVar n)] <- freshRelTo (names sc) context ElaboratedTerm em <- extendElab context [(x,QLJ ea l)] $ checkify (instantiate sc [Var (Free x)]) (NormalTerm t) return $ ElaboratedTerm (requireH n ea em) checkify m t = do (ElaboratedTerm m',t') <- inferify m subt' <- substitute t' et' <- evaluate subt' unifyHelper t et' SubstitutedTerm subm' <- substitute m' return $ ElaboratedTerm subm' -- | Ideally, we'd like to check a sequence of args like so: -- -- @ c sig(Pl0, ... ,Pln ; ( : A0, ... ,xn : An)B ) M0 ' ⇐ A0 Γ ⊢ M1 ▹ M1 ' ⇐ [ M0'/x0]A1 -- ... ▹ Mn ' ⇐ [ M0'/x0,M1'/x1, ... ,Mn-1'/xn-1]An -- -------------------------------------------------------- ... ;(Pln , Mn ) ) : [ ... ,Mn',xn]B -- @ -- -- In practice this is tricky, so we have an auxiliary judgment @Γ at B of M * ▹ M * ' ⇐ B'@ , which is defined inductively as -- -- @ -- ----------------------- at B of e ▹ e ⇐ B -- Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇐ B ' -- ---------------------------------------------------------------------- , : A0 ) , T at B of ( Expl , M0 ) , M * ▹ ( Expl , M0 ' ) , M * ' ⇐ B ' -- Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇐ B ' -- ---------------------------------------------------------------------- ( Impl , : A0 ) , T at B of ( Impl , M0 ) , M * ▹ ( Impl , M0 ' ) , M * ' ⇐ B ' -- Γ ⊢ [ P / xi]T at [ P / xi]B of ( Expl , M0 ) , M * ▹ M * ' ⇐ B ' -- ----------------------------------------------------------------- ( Impl , xi : Ai ) , T at B of ( Expl , M0 ) , M * ▹ ( Impl , P ) , M * ' ⇐ B ' -- @ -- -- This judgment is essentially the same as the inference judgment, except -- that the implementation here is justified as a bidirectional rule. The -- implementation, however, is a bit odd, because of how information flows and how equality via evaluation - and - unification works . This arises from two facts . Firstly , constructors can have argument types which compute from -- indexes. For example -- -- @ data Image ( f : ) ( x : ) where | MkImage { f : } { x : ( y : f x ) : Image f x -- end -- @ -- -- The implicit arguments need to therefore be determined by the type checker -- given the type being checked against. For instance, given @ifZero : Type - > Type - > Nat - > Type@ , which behaves as expected , the term @MkImage Unit@ ought to type check at @Image ( ifZero ) Zero@. This means that when type checking the argument @Unit@ , we need to check it against @ifZero Top Bot Zero@ which needs to therefore compute to @Top@. -- Therefore information has to flow from the expected type into the arguments -- of the constructor, as expected from bidi type checking (lambdas do the same ) . However there 's a second issue , which is that indexes can also be determined by computation , as with the example of @Inv@ from earlier . So -- information has to in some sense flow in the other direction as well. However , we can avoid this second problem with a cute trick from McBride 's paper Elimination with a Motive ( learned by from ) , where we extract the computed index into an equation that needs -- to be solved. -- -- The overall structure of the algorithm is as follows: for each of the -- scopes for the constructor argument types, we make a new metavariable. This -- will eventually be unified with the elaborated argument of that type. We -- use these to instantiate the scopes, because each term needs to check -- against a scope and elaborate to some new term, but that scope itself needs -- to have been instantiated at the fully-elaborated values of previous args. -- This means we can't use the previous args as-is to instantiate, we need to -- incrementally instantiate. However, we also need to pass information in -- from the return type, so these metas are also used to instantiate that. -- We can then take the return type, swap out its non-meta args (because they -- might require computation) for purely meta args, and unify. We can now go -- back, check against the argument types now that we've gotten all the -- information we can from the return type. This will also involve unifying -- the returned elabbed arguments with the now-possibly-solved metas that they -- correspond to. Finally, we can also solve the equations we extracted from -- the return type. checkifyConArgs :: [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Term)] -> Term -> TypeChecker [(Plicity,ElaboratedTerm)] checkifyConArgs ascs0 bsc ms0 t = do argsToCheck <- accArgsToCheck [] ascs0 ms0 (eqs,ret') <- case instantiate bsc [ x | (_,_,x,_) <- argsToCheck ] of In (Con c as) -> do (eqs,as') <- swapMetas [ (plic,instantiate0 a) | (plic,a) <- as ] let ret' = conH c as' return (eqs,ret') ret' -> return ([],ret') unifyHelper (NormalTerm ret') (NormalTerm t) ms' <- forM argsToCheck $ \(plic,m0,mToElabInto,a) -> case m0 of Nothing -> do subMToElabInto <- substitute mToElabInto eMToElabInto <- evaluate subMToElabInto return (plic, ElaboratedTerm (normTerm eMToElabInto)) Just m -> do subMToElabInto <- substitute mToElabInto eMToElabInto <- evaluate subMToElabInto suba <- substitute a ea <- evaluate suba ElaboratedTerm m' <- checkify m ea SubstitutedTerm subm' <- substitute m' unifyHelper eMToElabInto (NormalTerm subm') return (plic, ElaboratedTerm subm') forM_ eqs $ \(l,r) -> do subl <- substitute l el <- evaluate subl subr <- substitute r er <- evaluate subr unifyHelper el er return ms' where accArgsToCheck :: [(Plicity,Maybe Term,Term,Term)] -> [(Plicity,Scope TermF)] -> [(Plicity,Term)] -> TypeChecker [(Plicity,Maybe Term,Term,Term)] accArgsToCheck acc [] [] = return acc accArgsToCheck acc ((Expl,asc):ascs) ((Expl,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Expl, Just m, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ms accArgsToCheck acc ((Impl,asc):ascs) ((Impl,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Just m, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ms accArgsToCheck acc ((Impl,asc):ascs) ms = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Nothing, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ms accArgsToCheck _ _ _ = throwError "Cannot match signature." swapMetas :: [(Plicity,Term)] -> TypeChecker ([(Term,Term)], [(Plicity,Term)]) swapMetas [] = return ([],[]) swapMetas ((plic, Var (Meta meta)):ms) = do (eqs,ms') <- swapMetas ms return (eqs, (plic,Var (Meta meta)):ms') swapMetas ((plic,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) (eqs,ms') <- swapMetas ms return ((x,m):eqs, (plic,x):ms') | This corresponds to the judgment which is defined directly -- in terms of telescopes as as -- -- @ telescope -- ------------------------- ) ▹ mot(T ' ) motive -- @ checkifyCaseMotive :: CaseMotive -> TypeChecker CaseMotive checkifyCaseMotive (CaseMotive tele) = do tele' <- checkifyBindingTelescope tele return $ CaseMotive tele' | This corresponds to the judgment @Γ yielding M@. The -- returned term @M@ is the term that corresponds to the pattern, which is -- necessary for determining if subsequent patterns and the clause body are -- well typed, since their types can compute over this term. For example, given the motive @(b : ) || if b String@ , the clause @True - > Zero@ should type check , because @True@ is a @Bool@ pattern , and @if True Nat String@ would compute to @Nat@ which @5@ would check against . -- -- The judgment is defined inductively as follows: -- -- @ -- ------------------------------ ▹ x pattern A yielding x -- -- c ▹ c ' con S ... ,Pn ▹ P0', ... ,Pn ' patterns S yielding M0, ... ,Mn at B ' -- B = B' -- --------------------------------------------------------------- Γ ⊢ con[c](P0; ... ;Pn ) ▹ con[c](P0'; ... ;Pn ' ) pattern B -- yielding con[c'](M0,...,Mn) -- -- -- Γ ⊢ M ▹ M' ⇐ A true -- ----------------------------------------------- ) ▹ assert(M ' ) pattern A yielding M -- @ checkifyPattern :: Pattern -> NormalTerm -> TypeChecker (Pattern,ElaboratedTerm) checkifyPattern (Var (Bound _ _)) _ = error "A bound variable should not be the subject of pattern type checking." checkifyPattern (Var (Free x)) t = do QLJ t' _ <- typeInContext x @t'@ is guaranteed to be normal return ( Var (Free x) , ElaboratedTerm (Var (Free x)) ) checkifyPattern (Var (Meta _)) _ = error "Metavariables should not be the subject of pattern type checking." checkifyPattern (In (ConPat c ps)) (NormalTerm t) = do (ec,ConSig plics (BindingTelescope ascs bsc)) <- typeInSignature c (ps',elms') <- checkifyPatterns (zip plics ascs) bsc [ (plic, instantiate0 p) | (plic,p) <- ps ] t let ms' = [ (plic,m') | (plic, ElaboratedTerm m') <- elms' ] return ( conPatH ec ps' , ElaboratedTerm (conH ec ms') ) checkifyPattern (In (AssertionPat m)) t = do ElaboratedTerm m' <- checkify m t return ( In (AssertionPat m') , ElaboratedTerm m' ) checkifyPattern (In MakeMeta) _ = do meta <- nextElab nextMeta let x = Var (Meta meta) return ( In (AssertionPat x) , ElaboratedTerm x ) -- | This is the pattern version of 'checkifyConArgs', which corresponds to the judgment at B of P * ▹ P * ' pattern B ' yielding M*@ , which is -- defined inductively as -- -- @ -- ---------------------------------------- at B of e ▹ e pattern B yielding e -- Γ ⊢ P0 ▹ P0 ' pattern A0 yielding M0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of P * ▹ P * ' pattern B ' yielding M * -- ---------------------------------------------------------------- , : A0 ) , T at B of ( Expl , P0 ) , P * ▹ ( Expl , P0 ' ) , P * ' pattern B ' yielding ( Expl , M0 ) , M * -- Γ ⊢ P0 ▹ P0 ' pattern A0 yielding M0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of P * ▹ P * ' pattern B ' yielding M * -- ---------------------------------------------------------------- ( Impl , : A0 ) , T at B of ( Expl , P0 ) , P * ▹ ( Impl , P0 ' ) , P * ' pattern B ' yielding ( Impl , M0 ) , M * -- / xi]T at [ M / xi]B of ( Expl , P0 ) , P * ▹ P * ' pattern B ' yielding M * -- -------------------------------------------------------------------- ( Impl , xi : Ai ) , T at B of ( Expl , P0 ) , P * ▹ ( Impl , assert(M ) ) , P * ' pattern B ' yielding ( Impl , M ) , M * -- @ checkifyPatterns :: [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Pattern)] -> Term -> TypeChecker ( [(Plicity,Pattern)] , [(Plicity,ElaboratedTerm)] ) checkifyPatterns ascs0 bsc ps0 t = do argsToCheck <- accArgsToCheck [] ascs0 ps0 (eqs,ret') <- case instantiate bsc [ x | (_,_,x,_) <- argsToCheck ] of In (Con c as) -> do (eqs,as') <- swapMetas [ (plic,instantiate0 a) | (plic,a) <- as ] let ret' = conH c as' return (eqs,ret') ret' -> return ([],ret') unifyHelper (NormalTerm ret') (NormalTerm t) psms' <- forM argsToCheck $ \(plic,p0,mToElabInto,a) -> case p0 of Nothing -> do subMToElabInto <- substitute mToElabInto em' <- evaluate subMToElabInto return ( (plic, In (AssertionPat (normTerm em'))) , (plic, ElaboratedTerm (normTerm em')) ) Just p -> do subMToElabInto <- substitute mToElabInto eMToElabInto <- evaluate subMToElabInto suba <- substitute a ea <- evaluate suba (p',ElaboratedTerm m') <- checkifyPattern p ea subm' <- substitute m' em' <- evaluate subm' unifyHelper eMToElabInto em' return ( (plic, p') , (plic, ElaboratedTerm (normTerm em')) ) forM_ eqs $ \(l,r) -> do subl <- substitute l el <- evaluate subl subr <- substitute r er <- evaluate subr unifyHelper el er return $ unzip psms' where accArgsToCheck :: [(Plicity,Maybe Pattern,Term,Term)] -> [(Plicity,Scope TermF)] -> [(Plicity,Pattern)] -> TypeChecker [(Plicity,Maybe Pattern,Term,Term)] accArgsToCheck acc [] [] = return acc accArgsToCheck acc ((Expl,asc):ascs) ((Expl,p):ps) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Expl, Just p, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ps accArgsToCheck acc ((Impl,asc):ascs) ((Impl,p):ps) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Just p, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ps accArgsToCheck acc ((Impl,asc):ascs) ps = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Nothing, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ps accArgsToCheck _ _ _ = throwError "Cannot match signature." swapMetas :: [(Plicity,Term)] -> TypeChecker ([(Term,Term)], [(Plicity,Term)]) swapMetas [] = return ([],[]) swapMetas ((plic, Var (Meta meta)):ms) = do (eqs,ms') <- swapMetas ms return (eqs, (plic,Var (Meta meta)):ms') swapMetas ((plic,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) (eqs,ms') <- swapMetas ms return ((x,m):eqs, (plic,x):ms') -- | This corresponds to the judgment -- @Γ ⊢ P* ▹ P*' patterns M at B@ which is defined as follows: -- -- @ Γ ⊢ P0 ▹ P0 ' pattern A0 yielding M0 Γ ⊢ P1 ▹ P1 ' pattern [ M0 / x0]A1 yielding M1 Γ ⊢ P2 ▹ P2 ' pattern [ M0 / x0,M1 / x1]A2 yielding M2 -- ... ▹ Pn ' pattern [ M0 / x0, ... ,Mn-1 / xn-1]An yielding Mn -- -------------------------------------------------------------------- ... ,Pn ▹ P0', ... ,Pn ' patterns mot((x0 : A0, ... ,xn : An)B ) -- at [M0/x0,...,Mn/xn]B -- @ checkifyPatternsCaseMotive :: [Pattern] -> CaseMotive -> TypeChecker ([Pattern], ElaboratedTerm) checkifyPatternsCaseMotive ps0 (CaseMotive (BindingTelescope ascs bsc)) = do (ps',ms') <- go [] ps0 ascs return (ps', ElaboratedTerm (instantiate bsc ms')) where go :: [Term] -> [Pattern] -> [Scope TermF] -> TypeChecker ([Pattern],[Term]) go _ [] [] = return ([],[]) go acc (p:ps) (sc:scs) = do subt <- substitute (instantiate sc acc) et <- evaluate subt (p',ElaboratedTerm m') <- checkifyPattern p et (ps',ms') <- go (acc ++ [m']) ps scs return (p':ps', m':ms') go _ _ _ = error $ "The auxiliary function 'go' in 'checkPatternsCaseMotive'" ++ " should always have equal number of args for its patterns and" ++ " scopes. This branch should never have been reached." | This corresponds to the judgment M@ which is defined as -- -- @ ... ,Pn patterns M ⇝ Γ ' at B Γ , Γ ' ⊢ N ⇐ B true -- ------------------------------------------------------- Γ ⊢ clause(P0, ... ,Pn ; N ) clause M -- @ -- -- This also handles the checking of delayed assertion patterns. checkifyClause :: Clause -> CaseMotive -> TypeChecker Clause checkifyClause (Clause pscs sc) mot@(CaseMotive (BindingTelescope ascs _)) = do let lps = length pscs las = length ascs unless (lps == las) $ throwError $ "Motive " ++ pretty mot ++ " expects " ++ show las ++ " case " ++ (if las == 1 then "arg" else "args") ++ " but was given " ++ show lps ns <- freshRelTo (names sc) context let xs1 = map (Var . Free) ns xs2 = map (Var . Free) ns l <- getElab quoteLevel ctx' <- forM ns $ \n -> do m <- nextElab nextMeta return (n, QLJ (Var (Meta m)) l) extendElab context ctx' $ do (ps',ElaboratedTerm ret) <- checkifyPatternsCaseMotive (map (\psc -> patternInstantiate psc xs1 xs2) pscs) mot subret <- substitute ret eret <- evaluate subret ElaboratedTerm b' <- checkify (instantiate sc xs2) eret return $ clauseH [ n | FreeVar n <- ns ] ps' b' | This corresponds to the judgment which is defined -- directly in terms of telescopes as -- -- @ -- Γ ⊢ T ▹ T' telescope -- -------------------------------------- ) ▹ sig(Pl*;T ' ) signature -- @ checkifyConSig :: ConSig -> TypeChecker ConSig checkifyConSig (ConSig plics tele) = do tele' <- checkifyBindingTelescope tele return $ ConSig plics tele' | This corresponds to the judgment which is used -- to check that a telescope is well formed as a stack of binders. This is -- defined inductively as -- -- @ ▹ A0 ' : Type true -- ... Γ , : A0 ' , ... , xn-1 : ' An ' : Type true -- ----------------------------------------------------- A0, ... ,xn : An ▹ x0 : A0', ... ,xn : An ' telescope -- @ checkifyTelescope :: Telescope (Scope TermF) -> TypeChecker (Telescope (Scope TermF)) checkifyTelescope (Telescope ascs) = do ns <- freshRelTo (names (last ascs)) context as' <- go ns [] ascs let tele' = telescopeH [ n | FreeVar n <- ns ] as' return $ tele' where go :: [FreeVar] -> [Term] -> [Scope TermF] -> TypeChecker [Term] go _ _ [] = return [] go vars acc (sc:scs) = do l <- getElab quoteLevel let ctx' = zipWith (\x y -> (x,QLJ y l)) vars acc xs = [ Var (Free x) | x <- take (length (names sc)) vars ] ElaboratedTerm a' <- extendElab context ctx' $ checkify (instantiate sc xs) (NormalTerm (In Type)) as' <- go vars (acc ++ [a']) scs return $ a':as' | This corresponds to the judgment which is used -- to check that a telescope is well formed as a stack of binders. This is -- defined inductively as -- -- @ ▹ A0 ' : Type true -- ... Γ , : A0 ' , ... , xn-1 : ' An ' : Type true Γ , : A0 ' , ... , xn : An ' ⊢ B ▹ B ' : Type true -- ----------------------------------------------------- ( : A0, ... ,xn : An)B ▹ ( : An')B ' telescope -- @ checkifyBindingTelescope :: BindingTelescope (Scope TermF) -> TypeChecker (BindingTelescope (Scope TermF)) checkifyBindingTelescope (BindingTelescope ascs bsc) = do ns <- freshRelTo (names bsc) context asb' <- go ns [] (ascs ++ [bsc]) let as' = init asb' b' = last asb' let tele' = bindingTelescopeH [ n | FreeVar n <- ns ] as' b' return $ tele' where go :: [FreeVar] -> [Term] -> [Scope TermF] -> TypeChecker [Term] go _ _ [] = return [] go vars acc (sc:scs) = do l <- getElab quoteLevel let ctx' = zipWith (\x y -> (x,QLJ y l)) vars acc xs = [ Var (Free x) | x <- take (length (names sc)) vars ] ElaboratedTerm a' <- extendElab context ctx' $ checkify (instantiate sc xs) (NormalTerm (In Type)) as' <- go vars (acc ++ [a']) scs return $ a':as' -- | All metavariables have been solved when the next metavar to produces is -- the number of substitutions we've found. metasSolved :: TypeChecker () metasSolved = do s <- get unless (_nextMeta s == MetaVar (length (_substitution s))) $ throwError "Not all metavariables have been solved." -- | Checking is just checkifying with a requirement that all metas have been -- solved. check :: Term -> NormalTerm -> TypeChecker Term check m t = do ElaboratedTerm m' <- checkify m t SubstitutedTerm subm' <- substitute m' metasSolved return subm' is just inferifying with a requirement that all metas have been -- solved. The returned type is instantiated with the solutions. infer :: Term -> TypeChecker (Term,Term) infer m = do (ElaboratedTerm m', t) <- inferify m metasSolved subt <- substitute t NormalTerm et <- evaluate subt SubstitutedTerm subm' <- substitute m' return (subm',et)
null
https://raw.githubusercontent.com/BekaValentine/SimpleFP-v2/ae00ec809caefcd13664395b0ae2fc66145f6a74/src/Require/Unification/TypeChecking.hs
haskell
# OPTIONS -Wall # | A unification-based type checker. | In the dependently typed variant, it's useful to have a type for normal terms. While this type won't actually be representationally different, we can use it to help ensure we're using normal forms in places where we want them, such as the type arguments to checking. | It's useful to have a way of evaluating without having to constantly get make an environment and run the evaluator manually. | Similarly, it's also useful to be able to ensure that we're using terms that have been substituted into. This doesn't exist in the monadic variant because there's no unification going on. | Another helpful type, used for ensuring that we return elaborated terms from inference and checking. | We'd like to make sure that unification only happens to normal terms, so we'll define a convenience function we can use. which is just an lookup on aliases. @n@ here can be either a bare local | We can modify the quote level we check at by adding a quote level. | We can modify the quote level we check at by removing a quote level. | We can get the consig of a constructor by looking in the signature. This corresponds to the judgment @Σ ∋ n ▹ n' con S@. In the presence of aliases, this also requires some amount of elaboration. | We can get the type of a declared name by looking in the definitions. This corresponds to the judgment @Δ ∋ n ▹ n' : A@. In the presence of aliases, this also requires some amount of elaboration. | We can get the type of a free variable by looking in the context. This | We can extend the set of reset positions in scope currently. | We can get the types of a reset point. | We can add a shifted reset point by pushing it onto the in scope shift stack, and zeroing out the context temporarilly. | We can remove a shift by popping a the top shift from the shift stack. because all bound variables should be replaced by free variables during this part of type checking. implicit arguments elaborated. For instance, application of a function with implicit arguments initially will need to have those arguments inserted. Those arguments are necessary for computation, so we need to have a resulting elaborated term returned by the type checker. @ Γ ∋ x : A at l ------------------ variable Δ ∋ n ▹ n' : A ------------------------------------- definition ---------------------------------------------- annotation Γ ⊢ M : A ▹ M' : A' ⇒ A' at l --------------------------- type ------------------------------------------------------------ function ----------------------------------------------------------- application --------------------------------------- con data ... ------------------------------------------------------------------- case ... --------------------------------------------------------------- rec ------------------------------------------------------ projection Γ ; K' ⊢ A ▹ A' ⇐ Type at l Resets ∋ Ki ----------------------------------------------- quoted Γ ; K' ⊢ Quoted[K] A ▹ Quoted[K] A' ⇒ Type at l Γ ; K' ⊢ M ▹ M' ⇒ Quoted[K] A at l-1 K ⊆ K' ---------------------------------------------- unquote Resets ∋ s : A resets B Γ ; S ⊢ M ▹ M' ⇐ A at l+1 ---------------------------------------------------- continue Γ ; S, s ⊢ continue M ▹ continue M' ⇒ B at l+1 -------------------------------------------------------------- shift Resets ∋ k : A resets B Γ ; K, k ⊢ M ▹ M' ⇐ B at l+1 ------------------------------------------------------- reset @ This judgment will also happily infer the type of a constructor, because it has similarities to functions in that the "type" (really, signature) is given prior to the arguments. However, unlike functions, this is not guaranteed to work, as constructors in theory should be checked, not inferred. This is a kind of best-effort inferrence, that will sometimes fail in practice (tho the judgment doesn't make this clear) when the constructor in question has implicit arguments that take part in computed indexes of the return type. For instance, the type @ end @ In other cases, the implicit argument to the constructor may not even be an index of the type, making the inference problem even harder. This function is therefore only for certain use cases, where the constructor is "obviously" inferrable. @t@ can't be changed by checking. @args@ is already substituted @R.foo@, @R.bar@, and @R.baz@. | This instantiates scopes from a record type at all its possible fields, so that you get the types for each field. For instance, we want to take a record @R : Rec { foo : A, bar : B}@ and extract | Because implicit application exists to make certain applications more convenient for the user, we want to be able to apply a function which inserting however many implicit arguments as necessary. That is, given to be able to write @M N@ and have that type check. So we have this helper to define. This can be seen as actually not necessary, where the above rules are defined instead purely in terms of just application, since the underlying type theory doesn't have truly implicit application of any sort, but because this is an elaborating type checker, it's clearer if we explain things in terms of this. @ Γ ⊢ N ▹ N' ⇐ A true -------------------------------------------------------------- Γ ⊢ N ▹ N' ⇐ A true -------------------------------------------------------------- Γ ⊢ M {P} at [P/x]B applied explicitly to N ▹ Q ⇒ C ----------------------------------------------------- @ | As with function application, we can infer the type of a constructor application while simultaneously inserting implicit arguments with the plicity-scope pairs (which we treat as a telescope for readability), and @ ------------------------ ---------------------------------------------------------------------- ---------------------------------------------------------------------- ----------------------------------------------------------------- @ implementation inserts implicit lambdas as necessary because implicit arguments exist to make the language more convenient. @ Γ, x : A true ⊢ M ▹ M' ⇐ B true ----------------------------------------------------- lambda ------------------------------------------ con data Γ ⊢ con[c](M*) ▹ con[c'](M*') ⇐ B' true ----------------------------- direction change Γ ⊢ M ▹ M' ⇐ A true ... ----------------------------------------------------------- record Γ ; K ⊢ M ▹ M' ⇐ A at l+1 ------------------------------------ quote Γ ; K' ⊢ `M ▹ `M' ⇐ Quoted[K] A at l --------------------------------------------------------------- req @ \{x} -> M : {x : A} -> B \{x} -> M : (y : A) -> B | Ideally, we'd like to check a sequence of args like so: @ ... -------------------------------------------------------- @ In practice this is tricky, so we have an auxiliary judgment @ ----------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ----------------------------------------------------------------- @ This judgment is essentially the same as the inference judgment, except that the implementation here is justified as a bidirectional rule. The implementation, however, is a bit odd, because of how information flows and indexes. For example @ end @ The implicit arguments need to therefore be determined by the type checker given the type being checked against. For instance, given Therefore information has to flow from the expected type into the arguments of the constructor, as expected from bidi type checking (lambdas do the information has to in some sense flow in the other direction as well. to be solved. The overall structure of the algorithm is as follows: for each of the scopes for the constructor argument types, we make a new metavariable. This will eventually be unified with the elaborated argument of that type. We use these to instantiate the scopes, because each term needs to check against a scope and elaborate to some new term, but that scope itself needs to have been instantiated at the fully-elaborated values of previous args. This means we can't use the previous args as-is to instantiate, we need to incrementally instantiate. However, we also need to pass information in from the return type, so these metas are also used to instantiate that. We can then take the return type, swap out its non-meta args (because they might require computation) for purely meta args, and unify. We can now go back, check against the argument types now that we've gotten all the information we can from the return type. This will also involve unifying the returned elabbed arguments with the now-possibly-solved metas that they correspond to. Finally, we can also solve the equations we extracted from the return type. in terms of telescopes as as @ ------------------------- @ returned term @M@ is the term that corresponds to the pattern, which is necessary for determining if subsequent patterns and the clause body are well typed, since their types can compute over this term. For example, The judgment is defined inductively as follows: @ ------------------------------ B = B' --------------------------------------------------------------- yielding con[c'](M0,...,Mn) Γ ⊢ M ▹ M' ⇐ A true ----------------------------------------------- @ | This is the pattern version of 'checkifyConArgs', which corresponds to defined inductively as @ ---------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- -------------------------------------------------------------------- @ | This corresponds to the judgment @Γ ⊢ P* ▹ P*' patterns M at B@ which is defined as follows: @ ... -------------------------------------------------------------------- at [M0/x0,...,Mn/xn]B @ @ ------------------------------------------------------- @ This also handles the checking of delayed assertion patterns. directly in terms of telescopes as @ Γ ⊢ T ▹ T' telescope -------------------------------------- @ to check that a telescope is well formed as a stack of binders. This is defined inductively as @ ... ----------------------------------------------------- @ to check that a telescope is well formed as a stack of binders. This is defined inductively as @ ... ----------------------------------------------------- @ | All metavariables have been solved when the next metavar to produces is the number of substitutions we've found. | Checking is just checkifying with a requirement that all metas have been solved. solved. The returned type is instantiated with the solutions.
module Require.Unification.TypeChecking where import Utils.ABT import Utils.Elaborator import Utils.Eval import Utils.Names import Utils.Plicity import Utils.Pretty import Utils.Unifier import Utils.Telescope import Utils.Vars import Require.Core.ConSig import Require.Core.Evaluation () import Require.Core.Term import Require.Unification.Elaborator import Require.Unification.Unification () import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State import Data.List (inits) newtype NormalTerm = NormalTerm { normTerm :: Term } evaluate :: SubstitutedTerm -> TypeChecker NormalTerm evaluate (SubstitutedTerm m) = do defs <- getElab definitions l <- getElab quoteLevel case runReaderT (paramEval l m) (definitionsToEnvironment defs) of Left e -> throwError e Right m' -> return $ NormalTerm m' newtype SubstitutedTerm = SubstitutedTerm Term substitute :: Term -> TypeChecker SubstitutedTerm substitute t = do subs <- getElab substitution return $ SubstitutedTerm (substMetas subs t) newtype ElaboratedTerm = ElaboratedTerm { elabTerm :: Term } unifyHelper :: NormalTerm -> NormalTerm -> TypeChecker () unifyHelper (NormalTerm x) (NormalTerm y) = unifyJ substitution context x y | We can unalias a name . This corresponds to the judgment @L ∋ n alias n'@ name such as @foo@ or a dotted name like @Mod.foo@ , and @n'@ is an absolute name unalias :: Name -> TypeChecker (String,String) unalias (BareLocal n) = do als <- getElab aliases case lookup (Left n) als of Nothing -> throwError $ "The symbol " ++ n ++ " is not an alias for any " ++ "module-declared symbol." Just p -> return p unalias (DottedLocal m n) = do als <- getElab aliases case lookup (Right (m,n)) als of Nothing -> throwError $ "The symbol " ++ m ++ "." ++ n ++ " is not an alias for any " ++ "module-declared symbol." Just p -> return p unalias (Absolute m n) = return (m,n) addQuoteLevel :: TypeChecker a -> TypeChecker a addQuoteLevel tc = do l <- getElab quoteLevel putElab quoteLevel (l+1) x <- tc putElab quoteLevel l return x removeQuoteLevel :: TypeChecker a -> TypeChecker a removeQuoteLevel tc = do l <- getElab quoteLevel putElab quoteLevel (l-1) x <- tc putElab quoteLevel l return x typeInSignature :: Name -> Elaborator (Name,ConSig) typeInSignature n0 = do (m,n) <- unalias n0 consigs <- getElab signature case lookup (m,n) consigs of Nothing -> throwError $ "Unknown constructor: " ++ showName (Absolute m n) Just t -> return (Absolute m n, t) typeInDefinitions :: Name -> Elaborator (Name,Term) typeInDefinitions n0 = do (m,n) <- unalias n0 defs <- getElab definitions case lookup (m,n) defs of Nothing -> throwError $ "Unknown constant/defined term: " ++ showName (Absolute m n) Just (_,t) -> return (Absolute m n, t) corresponds to the judgment : A at l@ typeInContext :: FreeVar -> Elaborator (QLJ Term) typeInContext v@(FreeVar n) = do ctx <- getElab context case lookup v ctx of Nothing -> throwError $ "Unbound variable: " ++ n Just t -> return t extendResets :: [String] -> Elaborator a -> Elaborator a extendResets newResets tc = do resets <- getElab resetPointsInScope putElab resetPointsInScope (newResets ++ resets) x <- tc putElab resetPointsInScope resets return x getResetPoint :: String -> Elaborator (Term,Term) getResetPoint res = do resets <- getElab resetPoints case lookup res resets of Nothing -> throwError $ "The reset point " ++ res ++ " has not been declared." Just (lower,upper) -> return (lower,upper) addShift :: String -> Elaborator a -> Elaborator a addShift res tc = do shifts <- getElab shiftsInScope putElab shiftsInScope (res:shifts) ctx <- getElab context l <- getElab quoteLevel putElab context (filter (\(_, QLJ _ l') -> l' < l) ctx) x <- tc putElab context ctx putElab shiftsInScope shifts return x removeShift :: Elaborator a -> Elaborator a removeShift tc = do shifts <- getElab shiftsInScope case shifts of [] -> tc _:shifts' -> do putElab shiftsInScope shifts' x <- tc putElab shiftsInScope shifts return x | Type inference corresponds to the judgment @Γ ⇒ A true@. This throws a error when trying to infer the type of a bound variable , The second term @M'@ in the judgment is the output term that has all The judgment ⇒ A true@ is defined inductively as follows : ▹ x ⇒ A at l defined[n ] ▹ defined[n ' ] ⇒ A at l ▹ A ' ⇐ Type at l Γ ⊢ M ▹ M ' ⇐ A ' at l at l ▹ A ' ⇐ Type at l Γ , x : A ' at l ⊢ B ▹ B ' ⇐ Type at l ( x : A ) - > B ▹ ( x : A ' ) - > B ' ⇒ Type at l ⇒ S at l Γ ⊢ M ' at S applied Plic to N ▹ P ⇒ B ) ▹ P ⇒ B at l c ▹ c ' sig(Pl*;(A*)B ) ) at B of M * ▹ M * ' ⇒ B ' ) ▹ con[c'](M * ' ) ⇒ B ' at l : A0, ... ,xm : Am)B ) motive ⇐ A0 at l ⇐ [ ... ]An at l ( : A0) ... (xm : Am)B ... ,Mm ; mot((x0 : A0, ... )B ) ; C0, ... ,Cn ) ⇒ [ M0 / x0, ... ]B at l ▹ A0 ' ⇐ Type at l Γ , : A0 ' at l ⊢ A1 ▹ A1 ' ⇐ Type at l Γ , : A0 ' at l , ... , xn-1 : ' at l An ' ⇐ Type at l x0 : A0 , ... , xn : An } ▹ rec : A0 ' , ... , xn : An ' } ⇒ Type at l Γ ⊢ M ▹ M ' ⇒ { : A0 , ... , xn : An } at l Γ ⊢ M.xi ▹ M'.xi ⇒ [ M'.x0 / x0 , ... , / xi-1]Ai at l Γ ; K ' ⊢ ~M ▹ ~M ' ⇒ A at l Resets ∋ k : A resets B Γ @ ; K , k ; S , k ⊢ M ▹ M ' ⇐ B at l+1 Γ ; K , k ; S ⊢ shift k in M ▹ shift k in M ' ⇒ A at l+1 Γ ; K ⊢ reset k in M ▹ reset k in M ' ⇒ B at l+1 data Inv ( f : ) ( y : ) where | MkInv { f : } ( x : ) : Inv f ( f x ) This would happily check , for instance @MkInv 3 : Inv ( +2 ) 1@ , but to try to infer the type of @MkInv@ requires implicitly fetermining some function @f@ , which is obviously not possible , as there could be infinitely many . inferify :: Term -> TypeChecker (ElaboratedTerm,Term) inferify (Var (Free x)) = do QLJ t lvl <- typeInContext x curLvl <- getElab quoteLevel unless (curLvl == lvl) $ throwError $ "Mismatching quote levels for " ++ pretty (Var (Free x) :: Term) return (ElaboratedTerm (Var (Free x)), t) inferify (Var (Bound _ _)) = error "Bound type variables should not be the subject of type checking." inferify (Var (Meta x)) = throwError $ "The metavariable " ++ show x ++ " appears in checkable code, when it should not." inferify (In (Defined x)) = do (ex,t) <- typeInDefinitions x return (ElaboratedTerm (In (Defined ex)), t) inferify (In (Ann m t0)) = do let t = instantiate0 t0 ElaboratedTerm elt <- checkify t (NormalTerm (In Type)) elm <- checkify (instantiate0 m) et return (elm, normTerm et) inferify (In Type) = return $ (ElaboratedTerm (In Type), In Type) inferify (In (Fun plic arg0 sc)) = do let arg = instantiate0 arg0 ElaboratedTerm elarg <- checkify arg (NormalTerm (In Type)) [x@(FreeVar n)] <- freshRelTo (names sc) context l <- getElab quoteLevel ElaboratedTerm elbody <- extendElab context [(x, QLJ elarg l)] $ checkify (instantiate sc [Var (Free x)]) (NormalTerm (In Type)) let t' = funH plic n elarg elbody SubstitutedTerm subt' <- substitute t' return (ElaboratedTerm subt', In Type) inferify (In (Lam _ _)) = throwError "Cannot infer the type of a lambda expression." inferify (In (App plic f0 a0)) = do let f = instantiate0 f0 a = instantiate0 a0 (ElaboratedTerm elf,t) <- inferify f subt <- substitute t NormalTerm et <- evaluate subt (app',t') <- inferifyApplication elf et plic a SubstitutedTerm subapp' <- substitute app' SubstitutedTerm subt' <- substitute t' return (ElaboratedTerm subapp', subt') inferify (In (Con c ms0)) = do (ec, ConSig plics (BindingTelescope ascs bsc)) <- typeInSignature c let ts = zip plics ascs ms = [ (plic, instantiate0 m) | (plic,m) <- ms0 ] (ms',b') <- inferifyConArgs ts bsc ms let m' = conH ec ms' SubstitutedTerm subm' <- substitute m' return (ElaboratedTerm subm', b') inferify (In (Case as0 motive cs)) = do let as = map instantiate0 as0 elmotive <- checkifyCaseMotive motive let CaseMotive tele = elmotive (args,ret) = instantiateBindingTelescope tele as las = length as largs = length args unless (las == largs) $ throwError $ "Motive " ++ pretty motive ++ " expects " ++ show largs ++ " case " ++ (if largs == 1 then "arg" else "args") ++ " but was given " ++ show las eargs <- mapM (evaluate.SubstitutedTerm) args elas <- zipWithM checkify as eargs elcs <- forM cs $ \c -> checkifyClause c elmotive let m' = caseH (map elabTerm elas) elmotive elcs SubstitutedTerm subm' <- substitute m' return (ElaboratedTerm subm', ret) inferify (In (RecordType fields tele)) = do tele' <- checkifyTelescope tele return (ElaboratedTerm (In (RecordType fields tele')), In Type) inferify (In (RecordCon _)) = throwError "Cannot infer the type of a record." inferify (In (RecordProj r x)) = do (ElaboratedTerm r',t) <- inferify (instantiate0 r) subt <- substitute t NormalTerm et <- evaluate subt case et of In (RecordType fields (Telescope ascs')) -> let fieldTable = zip fields (instantiations r' fields ascs') in case lookup x fieldTable of Nothing -> throwError $ "Missing field " ++ x Just fieldT -> return (ElaboratedTerm (recordProjH r' x), fieldT) _ -> throwError $ "Expecting a record type but found " ++ pretty et where | This just defines all the possible projections of @r'@ using fields @fs'@ , eg . @projections R [ " foo","bar","baz"]@ is the terms projections :: Term -> [String] -> [Term] projections r' fs' = [ recordProjH r' f' | f' <- fs' ] @A@ for the type of @R.foo@ and @[R.foo / foo]B@ for the type of @R.bar@. instantiations :: Term -> [String] -> [Scope TermF] -> [Term] instantiations r' fs' ascs' = zipWith instantiate ascs' (inits (projections r' fs')) inferify (In (QuotedType resets a)) = do ElaboratedTerm ela <- checkify (instantiate0 a) (NormalTerm (In Type)) return (ElaboratedTerm (quotedTypeH resets ela), In Type) inferify (In (Quote _)) = throwError "Cannot infer the type of a quoted term." inferify (In (Unquote m)) = do (ElaboratedTerm elm, t) <- removeQuoteLevel $ inferify (instantiate0 m) subt <- substitute t NormalTerm et <- evaluate subt case et of In (QuotedType res a) -> do resets <- getElab resetPointsInScope unless (all (`elem` resets) res) $ throwError $ "Reset points mismatch for the term " ++ pretty (instantiate0 m) ++ " which has points " ++ unwords res ++ " and the context which has " ++ unwords resets return (ElaboratedTerm (unquoteH elm), instantiate0 a) _ -> throwError $ "Expected a quoted type but found " ++ pretty et inferify (In (Continue m)) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use continuations outside of a quote." shifts <- getElab shiftsInScope case shifts of [] -> throwError $ "Cannot continue with " ++ pretty (instantiate0 m) ++ " because there are no shifted reset points in scope." res:_ -> do (lower,upper) <- getResetPoint res ElaboratedTerm elm <- removeShift $ checkify (instantiate0 m) (NormalTerm lower) return (ElaboratedTerm (continueH elm), upper) inferify (In (Shift res m)) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use continuations outside of a quote." resets <- getElab resetPointsInScope unless (res `elem` resets) $ throwError $ "The reset point " ++ res ++ " is not in scope." (lower,upper) <- getResetPoint res ElaboratedTerm elm <- addShift res $ checkify (instantiate0 m) (NormalTerm upper) return (ElaboratedTerm (shiftH res elm), lower) inferify (In (Reset res m)) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use continuations outside of a quote." (_,upper) <- getResetPoint res ElaboratedTerm elm <- extendResets [res] $ checkify (instantiate0 m) (NormalTerm upper) return (ElaboratedTerm (resetH res elm), upper) inferify (In (Require _ _)) = throwError "Cannot infer the type of a require term." has some number of implicit arguments first to an explicit argument by @M : { : A0 } - > ... - > { xn : An } - > ( y : B ) - > C@ and @N : B@ we want judgment at S applied Plic to N ▹ P ⇒ B@ to make ' inferify ' easier at ( x : A ) - > B applied explicitly to ⇒ [ N'/x]B at { x : A } - > B applied implicitly to N ▹ M N ' ⇒ [ N'/x]B at { x : A } - > B applied explicitly to N ▹ Q ⇒ C inferifyApplication :: Term -> Term -> Plicity -> Term -> TypeChecker (Term,Term) inferifyApplication f (In (Fun Expl a sc)) Expl m = do ElaboratedTerm m' <- checkify m (NormalTerm (instantiate0 a)) return (appH Expl f m', instantiate sc [m']) inferifyApplication f (In (Fun Impl a sc)) Impl m = do ElaboratedTerm m' <- checkify m (NormalTerm (instantiate0 a)) return (appH Impl f m', instantiate sc [m']) inferifyApplication f (In (Fun Expl _ _)) Impl m = throwError $ "Mismatching plicities when checking the application " ++ pretty (appH Impl f m) inferifyApplication f (In (Fun Impl _ sc)) Expl m = do meta <- nextElab nextMeta let f' = appH Impl f (Var (Meta meta)) t' = instantiate sc [Var (Meta meta)] inferifyApplication f' t' Expl m inferifyApplication f _ _ _ = throwError $ "Cannot apply non-function: " ++ pretty f judgment at B of M * ▹ M * ' ⇒ where @T@ is a sequence of @M*@ and @M*'@ are plicity - term pairs . The judgment is defined as at B of e ▹ e ⇒ B Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇒ B ' , : A0 ) , T at B of ( Expl , M0 ) , M * ▹ ( Expl , M0 ' ) , M * ' ⇒ B ' Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇒ B ' ( Impl , : A0 ) , T at B of ( Impl , M0 ) , M * ▹ ( Impl , M0 ' ) , M * ' ⇒ B ' Γ ⊢ [ P / xi]T at [ P / xi]B of ( Expl , M0 ) , M * ▹ M * ' ⇒ B ' ( Impl , xi : Ai ) , T at B of ( Expl , M0 ) , M * ▹ ( Impl , P ) , M * ' ⇒ B ' inferifyConArgs :: [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Term)] -> TypeChecker ([(Plicity,Term)], Term) inferifyConArgs ascs0 bsc0 ms0 = go [] ascs0 bsc0 ms0 where go :: [(Plicity,Term)] -> [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Term)] -> TypeChecker ([(Plicity,Term)], Term) go acc [] bsc [] = return (acc, instantiate bsc (map snd acc)) go acc ((Expl,asc):ascs) bsc ((Expl,m):ms) = do suba <- substitute (instantiate asc (map snd acc)) ea <- evaluate suba ElaboratedTerm m' <- checkify m ea go (acc ++ [(Expl,m')]) ascs bsc ms go acc ((Impl,asc):ascs) bsc ((Impl,m):ms) = do suba <- substitute (instantiate asc (map snd acc)) ea <- evaluate suba ElaboratedTerm m' <- checkify m ea go (acc ++ [(Impl,m')]) ascs bsc ms go acc ((Impl,_):ascs) bsc ms = do meta <- nextElab nextMeta go (acc ++ [(Impl,Var (Meta meta))]) ascs bsc ms go _ _ _ _ = throwError "Cannot match signature." | Type checking corresponds to the judgment @Γ ⇐ A true@. The The judgment ⇐ A true@ is defined inductively as follows : . M ) ▹ lam(Pl;x . M ' ) ⇐ Fun(Pl ; A ; x. B ) true c ▹ c ' sig(Pl*;(A*)B ) ) at B of M * ▹ M * ' ⇐ B ' true ⇒ A ' true A = A ' M0 ' ⇐ A0 true Γ ⊢ M1 ▹ M1 ' ⇐ [ M0'/x0]A1 true ▹ Mn ' ⇐ [ ... ,Mn-1'/xn-1]An true Γ ⊢ { x0 = M0 , ... , xn : Mn } ▹ { x0 = M0 ' , ... , xn : Mn ' } ⇐ rec { : A0 , ... , xn : An } true ▹ A ' ⇐ Type at l+1 Γ , x : A ' at l+1 ⊢ M ▹ M ' ⇐ B at l+1 Γ ⊢ require x : A in M ▹ require x : A ' in M ' ⇐ B at l+1 checkify :: Term -> NormalTerm -> TypeChecker ElaboratedTerm checkify (In (Lam plic sc)) (NormalTerm t) = do lam' <- case (plic,t) of \x - > M : ( x : A ) - > B do [v@(FreeVar n)] <- freshRelTo (names sc) context let x = Var (Free v) ElaboratedTerm m' <- do l <- getElab quoteLevel extendElab context [(v,QLJ (instantiate0 a) l)] $ checkify (instantiate sc [x]) (NormalTerm (instantiate sc2 [x])) return $ lamH Expl n m' do [v@(FreeVar n)] <- freshRelTo (names sc) context let x = Var (Free v) ElaboratedTerm m' <- do l <- getElab quoteLevel extendElab context [(v,QLJ (instantiate0 a) l)] $ checkify (instantiate sc [x]) (NormalTerm (instantiate sc2 [x])) return $ lamH Impl n m' \x - > M : { y : A } - > B do [v@(FreeVar n)] <- freshRelTo (names sc2) context let x = Var (Free v) ElaboratedTerm m' <- do l <- getElab quoteLevel extendElab context [(v,QLJ (instantiate0 a) l)] $ checkify (In (Lam plic sc)) (NormalTerm (instantiate sc2 [x])) return $ lamH Impl n m' throwError $ "Expected an explicit argument but found an implicit " ++ "argument when checking " ++ pretty (In (Lam plic sc)) ++ " matches the signature " ++ pretty t _ -> throwError $ "Cannot check term: " ++ pretty (In (Lam plic sc)) ++ "\nAgainst non-function type: " ++ pretty t SubstitutedTerm sublam' <- substitute lam' return $ ElaboratedTerm sublam' checkify (In (Con c ms)) (NormalTerm t) = do (ec,ConSig plics (BindingTelescope ascs bsc)) <- typeInSignature c elms' <- checkifyConArgs (zip plics ascs) bsc [ (plic, instantiate0 m) | (plic,m) <- ms ] t let ms' = [ (plic,m') | (plic, ElaboratedTerm m') <- elms' ] elm = conH ec ms' SubstitutedTerm subelm <- substitute elm return $ ElaboratedTerm subelm checkify (In (RecordCon fields)) (NormalTerm t) = case t of In (RecordType typeFields (Telescope ascs)) -> if length typeFields >= length fields then case lookupMany typeFields fields of Left missingField -> throwError $ "Cannot check the record " ++ pretty (In (RecordCon fields)) ++ " against type " ++ pretty t ++ " because the record is missing the field " ++ missingField Right ms -> do ms' <- go [] (map instantiate0 ms) ascs return $ ElaboratedTerm (recordConH (zip typeFields ms')) else throwError $ "Cannot check the record " ++ pretty (In (RecordCon fields)) ++ " against type " ++ pretty t ++ " because the record has too many fields" _ -> throwError $ "Cannot check the record " ++ pretty (In (RecordCon fields)) ++ " against type " ++ pretty t where lookupMany :: Eq k => [k] -> [(k,v)] -> Either k [v] lookupMany [] _ = Right [] lookupMany (k:ks) kvs = case lookup k kvs of Nothing -> Left k Just v -> do vs <- lookupMany ks kvs return (v:vs) go :: [Term] -> [Term] -> [Scope TermF] -> TypeChecker [Term] go acc [] [] = return acc go acc (m:ms) (asc:ascs) = do suba <- substitute (instantiate asc acc) ea <- evaluate suba ElaboratedTerm m' <- checkify m ea go (acc ++ [m']) ms ascs go _ _ _ = error $ "This case of 'go' in 'checkify' of a record type should " ++ "be unreachable." checkify (In (Quote m)) (NormalTerm t) = case t of In (QuotedType res a) -> do ElaboratedTerm em <- addQuoteLevel $ extendResets res $ checkify (instantiate0 m) (NormalTerm (instantiate0 a)) return $ ElaboratedTerm (quoteH em) _ -> throwError $ "Cannot check quoted term " ++ pretty (In (Quote m)) ++ " against type " ++ pretty t checkify (In (Require a sc)) (NormalTerm t) = do l <- getElab quoteLevel unless (l > 0) $ throwError "Cannot use requires outside of a quote." ElaboratedTerm ea <- checkify (instantiate0 a) (NormalTerm (In Type)) [x@(FreeVar n)] <- freshRelTo (names sc) context ElaboratedTerm em <- extendElab context [(x,QLJ ea l)] $ checkify (instantiate sc [Var (Free x)]) (NormalTerm t) return $ ElaboratedTerm (requireH n ea em) checkify m t = do (ElaboratedTerm m',t') <- inferify m subt' <- substitute t' et' <- evaluate subt' unifyHelper t et' SubstitutedTerm subm' <- substitute m' return $ ElaboratedTerm subm' c sig(Pl0, ... ,Pln ; ( : A0, ... ,xn : An)B ) M0 ' ⇐ A0 Γ ⊢ M1 ▹ M1 ' ⇐ [ M0'/x0]A1 ▹ Mn ' ⇐ [ M0'/x0,M1'/x1, ... ,Mn-1'/xn-1]An ... ;(Pln , Mn ) ) : [ ... ,Mn',xn]B @Γ at B of M * ▹ M * ' ⇐ B'@ , which is defined inductively as at B of e ▹ e ⇐ B Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇐ B ' , : A0 ) , T at B of ( Expl , M0 ) , M * ▹ ( Expl , M0 ' ) , M * ' ⇐ B ' Γ ⊢ M0 ▹ M0 ' ⇐ A0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of M * ▹ M * ' ⇐ B ' ( Impl , : A0 ) , T at B of ( Impl , M0 ) , M * ▹ ( Impl , M0 ' ) , M * ' ⇐ B ' Γ ⊢ [ P / xi]T at [ P / xi]B of ( Expl , M0 ) , M * ▹ M * ' ⇐ B ' ( Impl , xi : Ai ) , T at B of ( Expl , M0 ) , M * ▹ ( Impl , P ) , M * ' ⇐ B ' how equality via evaluation - and - unification works . This arises from two facts . Firstly , constructors can have argument types which compute from data Image ( f : ) ( x : ) where | MkImage { f : } { x : ( y : f x ) : Image f x @ifZero : Type - > Type - > Nat - > Type@ , which behaves as expected , the term @MkImage Unit@ ought to type check at @Image ( ifZero ) Zero@. This means that when type checking the argument @Unit@ , we need to check it against @ifZero Top Bot Zero@ which needs to therefore compute to @Top@. same ) . However there 's a second issue , which is that indexes can also be determined by computation , as with the example of @Inv@ from earlier . So However , we can avoid this second problem with a cute trick from McBride 's paper Elimination with a Motive ( learned by from ) , where we extract the computed index into an equation that needs checkifyConArgs :: [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Term)] -> Term -> TypeChecker [(Plicity,ElaboratedTerm)] checkifyConArgs ascs0 bsc ms0 t = do argsToCheck <- accArgsToCheck [] ascs0 ms0 (eqs,ret') <- case instantiate bsc [ x | (_,_,x,_) <- argsToCheck ] of In (Con c as) -> do (eqs,as') <- swapMetas [ (plic,instantiate0 a) | (plic,a) <- as ] let ret' = conH c as' return (eqs,ret') ret' -> return ([],ret') unifyHelper (NormalTerm ret') (NormalTerm t) ms' <- forM argsToCheck $ \(plic,m0,mToElabInto,a) -> case m0 of Nothing -> do subMToElabInto <- substitute mToElabInto eMToElabInto <- evaluate subMToElabInto return (plic, ElaboratedTerm (normTerm eMToElabInto)) Just m -> do subMToElabInto <- substitute mToElabInto eMToElabInto <- evaluate subMToElabInto suba <- substitute a ea <- evaluate suba ElaboratedTerm m' <- checkify m ea SubstitutedTerm subm' <- substitute m' unifyHelper eMToElabInto (NormalTerm subm') return (plic, ElaboratedTerm subm') forM_ eqs $ \(l,r) -> do subl <- substitute l el <- evaluate subl subr <- substitute r er <- evaluate subr unifyHelper el er return ms' where accArgsToCheck :: [(Plicity,Maybe Term,Term,Term)] -> [(Plicity,Scope TermF)] -> [(Plicity,Term)] -> TypeChecker [(Plicity,Maybe Term,Term,Term)] accArgsToCheck acc [] [] = return acc accArgsToCheck acc ((Expl,asc):ascs) ((Expl,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Expl, Just m, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ms accArgsToCheck acc ((Impl,asc):ascs) ((Impl,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Just m, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ms accArgsToCheck acc ((Impl,asc):ascs) ms = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Nothing, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ms accArgsToCheck _ _ _ = throwError "Cannot match signature." swapMetas :: [(Plicity,Term)] -> TypeChecker ([(Term,Term)], [(Plicity,Term)]) swapMetas [] = return ([],[]) swapMetas ((plic, Var (Meta meta)):ms) = do (eqs,ms') <- swapMetas ms return (eqs, (plic,Var (Meta meta)):ms') swapMetas ((plic,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) (eqs,ms') <- swapMetas ms return ((x,m):eqs, (plic,x):ms') | This corresponds to the judgment which is defined directly telescope ) ▹ mot(T ' ) motive checkifyCaseMotive :: CaseMotive -> TypeChecker CaseMotive checkifyCaseMotive (CaseMotive tele) = do tele' <- checkifyBindingTelescope tele return $ CaseMotive tele' | This corresponds to the judgment @Γ yielding M@. The given the motive @(b : ) || if b String@ , the clause @True - > Zero@ should type check , because @True@ is a @Bool@ pattern , and @if True Nat String@ would compute to @Nat@ which @5@ would check against . ▹ x pattern A yielding x c ▹ c ' con S ... ,Pn ▹ P0', ... ,Pn ' patterns S yielding M0, ... ,Mn at B ' Γ ⊢ con[c](P0; ... ;Pn ) ▹ con[c](P0'; ... ;Pn ' ) pattern B ) ▹ assert(M ' ) pattern A yielding M checkifyPattern :: Pattern -> NormalTerm -> TypeChecker (Pattern,ElaboratedTerm) checkifyPattern (Var (Bound _ _)) _ = error "A bound variable should not be the subject of pattern type checking." checkifyPattern (Var (Free x)) t = do QLJ t' _ <- typeInContext x @t'@ is guaranteed to be normal return ( Var (Free x) , ElaboratedTerm (Var (Free x)) ) checkifyPattern (Var (Meta _)) _ = error "Metavariables should not be the subject of pattern type checking." checkifyPattern (In (ConPat c ps)) (NormalTerm t) = do (ec,ConSig plics (BindingTelescope ascs bsc)) <- typeInSignature c (ps',elms') <- checkifyPatterns (zip plics ascs) bsc [ (plic, instantiate0 p) | (plic,p) <- ps ] t let ms' = [ (plic,m') | (plic, ElaboratedTerm m') <- elms' ] return ( conPatH ec ps' , ElaboratedTerm (conH ec ms') ) checkifyPattern (In (AssertionPat m)) t = do ElaboratedTerm m' <- checkify m t return ( In (AssertionPat m') , ElaboratedTerm m' ) checkifyPattern (In MakeMeta) _ = do meta <- nextElab nextMeta let x = Var (Meta meta) return ( In (AssertionPat x) , ElaboratedTerm x ) the judgment at B of P * ▹ P * ' pattern B ' yielding M*@ , which is at B of e ▹ e pattern B yielding e Γ ⊢ P0 ▹ P0 ' pattern A0 yielding M0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of P * ▹ P * ' pattern B ' yielding M * , : A0 ) , T at B of ( Expl , P0 ) , P * ▹ ( Expl , P0 ' ) , P * ' pattern B ' yielding ( Expl , M0 ) , M * Γ ⊢ P0 ▹ P0 ' pattern A0 yielding M0 Γ ⊢ [ M0'/x0]T at [ M0'/x0]B of P * ▹ P * ' pattern B ' yielding M * ( Impl , : A0 ) , T at B of ( Expl , P0 ) , P * ▹ ( Impl , P0 ' ) , P * ' pattern B ' yielding ( Impl , M0 ) , M * / xi]T at [ M / xi]B of ( Expl , P0 ) , P * ▹ P * ' pattern B ' yielding M * ( Impl , xi : Ai ) , T at B of ( Expl , P0 ) , P * ▹ ( Impl , assert(M ) ) , P * ' pattern B ' yielding ( Impl , M ) , M * checkifyPatterns :: [(Plicity,Scope TermF)] -> Scope TermF -> [(Plicity,Pattern)] -> Term -> TypeChecker ( [(Plicity,Pattern)] , [(Plicity,ElaboratedTerm)] ) checkifyPatterns ascs0 bsc ps0 t = do argsToCheck <- accArgsToCheck [] ascs0 ps0 (eqs,ret') <- case instantiate bsc [ x | (_,_,x,_) <- argsToCheck ] of In (Con c as) -> do (eqs,as') <- swapMetas [ (plic,instantiate0 a) | (plic,a) <- as ] let ret' = conH c as' return (eqs,ret') ret' -> return ([],ret') unifyHelper (NormalTerm ret') (NormalTerm t) psms' <- forM argsToCheck $ \(plic,p0,mToElabInto,a) -> case p0 of Nothing -> do subMToElabInto <- substitute mToElabInto em' <- evaluate subMToElabInto return ( (plic, In (AssertionPat (normTerm em'))) , (plic, ElaboratedTerm (normTerm em')) ) Just p -> do subMToElabInto <- substitute mToElabInto eMToElabInto <- evaluate subMToElabInto suba <- substitute a ea <- evaluate suba (p',ElaboratedTerm m') <- checkifyPattern p ea subm' <- substitute m' em' <- evaluate subm' unifyHelper eMToElabInto em' return ( (plic, p') , (plic, ElaboratedTerm (normTerm em')) ) forM_ eqs $ \(l,r) -> do subl <- substitute l el <- evaluate subl subr <- substitute r er <- evaluate subr unifyHelper el er return $ unzip psms' where accArgsToCheck :: [(Plicity,Maybe Pattern,Term,Term)] -> [(Plicity,Scope TermF)] -> [(Plicity,Pattern)] -> TypeChecker [(Plicity,Maybe Pattern,Term,Term)] accArgsToCheck acc [] [] = return acc accArgsToCheck acc ((Expl,asc):ascs) ((Expl,p):ps) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Expl, Just p, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ps accArgsToCheck acc ((Impl,asc):ascs) ((Impl,p):ps) = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Just p, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ps accArgsToCheck acc ((Impl,asc):ascs) ps = do meta <- nextElab nextMeta let x = Var (Meta meta) xs = [ x' | (_,_,x',_) <- acc ] newSuspension = (Impl, Nothing, x, instantiate asc xs) accArgsToCheck (acc ++ [newSuspension]) ascs ps accArgsToCheck _ _ _ = throwError "Cannot match signature." swapMetas :: [(Plicity,Term)] -> TypeChecker ([(Term,Term)], [(Plicity,Term)]) swapMetas [] = return ([],[]) swapMetas ((plic, Var (Meta meta)):ms) = do (eqs,ms') <- swapMetas ms return (eqs, (plic,Var (Meta meta)):ms') swapMetas ((plic,m):ms) = do meta <- nextElab nextMeta let x = Var (Meta meta) (eqs,ms') <- swapMetas ms return ((x,m):eqs, (plic,x):ms') Γ ⊢ P0 ▹ P0 ' pattern A0 yielding M0 Γ ⊢ P1 ▹ P1 ' pattern [ M0 / x0]A1 yielding M1 Γ ⊢ P2 ▹ P2 ' pattern [ M0 / x0,M1 / x1]A2 yielding M2 ▹ Pn ' pattern [ M0 / x0, ... ,Mn-1 / xn-1]An yielding Mn ... ,Pn ▹ P0', ... ,Pn ' patterns mot((x0 : A0, ... ,xn : An)B ) checkifyPatternsCaseMotive :: [Pattern] -> CaseMotive -> TypeChecker ([Pattern], ElaboratedTerm) checkifyPatternsCaseMotive ps0 (CaseMotive (BindingTelescope ascs bsc)) = do (ps',ms') <- go [] ps0 ascs return (ps', ElaboratedTerm (instantiate bsc ms')) where go :: [Term] -> [Pattern] -> [Scope TermF] -> TypeChecker ([Pattern],[Term]) go _ [] [] = return ([],[]) go acc (p:ps) (sc:scs) = do subt <- substitute (instantiate sc acc) et <- evaluate subt (p',ElaboratedTerm m') <- checkifyPattern p et (ps',ms') <- go (acc ++ [m']) ps scs return (p':ps', m':ms') go _ _ _ = error $ "The auxiliary function 'go' in 'checkPatternsCaseMotive'" ++ " should always have equal number of args for its patterns and" ++ " scopes. This branch should never have been reached." | This corresponds to the judgment M@ which is defined as ... ,Pn patterns M ⇝ Γ ' at B Γ , Γ ' ⊢ N ⇐ B true Γ ⊢ clause(P0, ... ,Pn ; N ) clause M checkifyClause :: Clause -> CaseMotive -> TypeChecker Clause checkifyClause (Clause pscs sc) mot@(CaseMotive (BindingTelescope ascs _)) = do let lps = length pscs las = length ascs unless (lps == las) $ throwError $ "Motive " ++ pretty mot ++ " expects " ++ show las ++ " case " ++ (if las == 1 then "arg" else "args") ++ " but was given " ++ show lps ns <- freshRelTo (names sc) context let xs1 = map (Var . Free) ns xs2 = map (Var . Free) ns l <- getElab quoteLevel ctx' <- forM ns $ \n -> do m <- nextElab nextMeta return (n, QLJ (Var (Meta m)) l) extendElab context ctx' $ do (ps',ElaboratedTerm ret) <- checkifyPatternsCaseMotive (map (\psc -> patternInstantiate psc xs1 xs2) pscs) mot subret <- substitute ret eret <- evaluate subret ElaboratedTerm b' <- checkify (instantiate sc xs2) eret return $ clauseH [ n | FreeVar n <- ns ] ps' b' | This corresponds to the judgment which is defined ) ▹ sig(Pl*;T ' ) signature checkifyConSig :: ConSig -> TypeChecker ConSig checkifyConSig (ConSig plics tele) = do tele' <- checkifyBindingTelescope tele return $ ConSig plics tele' | This corresponds to the judgment which is used ▹ A0 ' : Type true Γ , : A0 ' , ... , xn-1 : ' An ' : Type true A0, ... ,xn : An ▹ x0 : A0', ... ,xn : An ' telescope checkifyTelescope :: Telescope (Scope TermF) -> TypeChecker (Telescope (Scope TermF)) checkifyTelescope (Telescope ascs) = do ns <- freshRelTo (names (last ascs)) context as' <- go ns [] ascs let tele' = telescopeH [ n | FreeVar n <- ns ] as' return $ tele' where go :: [FreeVar] -> [Term] -> [Scope TermF] -> TypeChecker [Term] go _ _ [] = return [] go vars acc (sc:scs) = do l <- getElab quoteLevel let ctx' = zipWith (\x y -> (x,QLJ y l)) vars acc xs = [ Var (Free x) | x <- take (length (names sc)) vars ] ElaboratedTerm a' <- extendElab context ctx' $ checkify (instantiate sc xs) (NormalTerm (In Type)) as' <- go vars (acc ++ [a']) scs return $ a':as' | This corresponds to the judgment which is used ▹ A0 ' : Type true Γ , : A0 ' , ... , xn-1 : ' An ' : Type true Γ , : A0 ' , ... , xn : An ' ⊢ B ▹ B ' : Type true ( : A0, ... ,xn : An)B ▹ ( : An')B ' telescope checkifyBindingTelescope :: BindingTelescope (Scope TermF) -> TypeChecker (BindingTelescope (Scope TermF)) checkifyBindingTelescope (BindingTelescope ascs bsc) = do ns <- freshRelTo (names bsc) context asb' <- go ns [] (ascs ++ [bsc]) let as' = init asb' b' = last asb' let tele' = bindingTelescopeH [ n | FreeVar n <- ns ] as' b' return $ tele' where go :: [FreeVar] -> [Term] -> [Scope TermF] -> TypeChecker [Term] go _ _ [] = return [] go vars acc (sc:scs) = do l <- getElab quoteLevel let ctx' = zipWith (\x y -> (x,QLJ y l)) vars acc xs = [ Var (Free x) | x <- take (length (names sc)) vars ] ElaboratedTerm a' <- extendElab context ctx' $ checkify (instantiate sc xs) (NormalTerm (In Type)) as' <- go vars (acc ++ [a']) scs return $ a':as' metasSolved :: TypeChecker () metasSolved = do s <- get unless (_nextMeta s == MetaVar (length (_substitution s))) $ throwError "Not all metavariables have been solved." check :: Term -> NormalTerm -> TypeChecker Term check m t = do ElaboratedTerm m' <- checkify m t SubstitutedTerm subm' <- substitute m' metasSolved return subm' is just inferifying with a requirement that all metas have been infer :: Term -> TypeChecker (Term,Term) infer m = do (ElaboratedTerm m', t) <- inferify m metasSolved subt <- substitute t NormalTerm et <- evaluate subt SubstitutedTerm subm' <- substitute m' return (subm',et)
b3ddf86eaa8de5ead7c766e52d283f4643a2d6af937cbbfd73dc37434007c87c
jsarracino/spyder
Parser.hs
module Language.Spyder.Parser.Parser ( expr , stmt , prog , block , relDeclP , relP , comp , spaced , typ , dataDeclP , mainCompP , derivCompP , loopP , elifP , condP , relPrev , specTerm ) where import Text.Parsec import Text.Parsec.Expr import qualified Text.Parsec.Token as Tok import Language.Spyder.Parser.Lexer (spyderLexer, Parser) import Language.Spyder.AST.Component import qualified Language.Spyder.AST.Imp as Imp import qualified Language.Spyder.AST.Spec as Spec import Language.Spyder.AST (Program) import Control.Monad (liftM, liftM2) import Data.List (partition) import Language.Boogie.Parser as BP -- import lexer = spyderLexer res = Tok.reserved lexer parens = Tok.parens lexer symb = Tok.symbol lexer ident = Tok.identifier lexer semi = Tok.semi lexer comma = Tok.comma lexer commas = Tok.commaSep lexer braces = Tok.braces lexer brackets = Tok.brackets lexer followedBy :: Parser a -> Parser b -> Parser a followedBy p q = do {r <- p; q; return r} spaced :: Parser a -> Parser [a] spaced p = p `sepBy` Tok.whiteSpace lexer semis p = p `sepBy` semi ints = liftM fromIntegral $ Tok.integer lexer bools = tru <|> fls where tru = do {res "true"; return True } fls = do {res "false"; return False } arrAccess = do { pref <- liftM Imp.VConst ident; rhs <- many1 $ brackets expr; return $ foldl Imp.Index pref rhs } arrPrim = liftM Imp.AConst (brackets $ commas expr) exprTerm :: Parser Imp.Expr exprTerm = parens expr <|> try (liftM Imp.IConst ints) <|> try (liftM Imp.BConst bools) <|> try arrPrim <|> try arrAccess <|> try (liftM Imp.VConst ident) <?> "simple expr" relPrev :: Parser Spec.RelExpr relPrev = do { res "prev"; (v, ifFls) <- parens prevPair; return $ Spec.Prev v ifFls } where prevPair = do { nme <- ident; comma; tl <- relexpr; return (nme, tl) } relApp :: Parser Spec.RelExpr relApp = do { nme <- ident; args <- parens $ commas relexpr; return $ Spec.RelApp nme args } relForeach :: Parser Spec.RelExpr relForeach = do { res "foreach"; vs <- parens $ commas ident; idx <- loopIdxP; res "in"; arrs <- parens $ commas ident; body <- braces relexpr; return $ Spec.Foreach vs idx arrs body } specTerm :: Parser Spec.RelExpr specTerm = parens relexpr <|> try (liftM Spec.RelInt ints) <|> try (liftM Spec.RelBool bools) <|> try relForeach <|> try relPrev < | > try relIndex <|> try relApp <|> try (liftM Spec.RelVar ident) <?> "spec expr" -- relIndex = do { -- pref <- liftM Spec.RelVar ident; -- rhs <- many1 $ brackets relexpr; return $ foldl Spec . RelIndex pref rhs -- } expr :: Parser Imp.Expr expr = buildExpressionParser exprTable exprTerm <?> "expression" relexpr :: Parser Spec.RelExpr relexpr = buildExpressionParser relTable specTerm <?> "relation expression" exprTable = [ [unary "!" (Imp.UnOp Imp.Not), unary "-" (Imp.UnOp Imp.Neg)] , [binary "*" (Imp.BinOp Imp.Mul) AssocLeft, binary "/" (Imp.BinOp Imp.Div) AssocLeft ] , [binary "+" (Imp.BinOp Imp.Plus) AssocLeft, binary "-" (Imp.BinOp Imp.Minus) AssocLeft ] , [binary "%" (Imp.BinOp Imp.Mod) AssocLeft] , [ binary "<" (Imp.BinOp Imp.Lt) AssocLeft, binary "<=" (Imp.BinOp Imp.Le) AssocLeft , binary ">" (Imp.BinOp Imp.Gt) AssocLeft, binary ">=" (Imp.BinOp Imp.Ge) AssocLeft ] , [binary "==" (Imp.BinOp Imp.Eq) AssocLeft, binary "!=" (Imp.BinOp Imp.Neq) AssocLeft] , [binary "&&" (Imp.BinOp Imp.And) AssocLeft, binary "||" (Imp.BinOp Imp.Or) AssocLeft] ] relTable = [ [unary "!" (Spec.RelUnop Spec.Not), unary "-" (Spec.RelUnop Spec.Neg)] , [binary "*" (Spec.RelBinop Spec.Mul) AssocLeft, binary "/" (Spec.RelBinop Spec.Div) AssocLeft ] , [binary "%" (Spec.RelBinop Spec.Mod) AssocLeft] , [binary "+" (Spec.RelBinop Spec.Plus) AssocLeft, binary "-" (Spec.RelBinop Spec.Minus) AssocLeft ] , [ binary "<" (Spec.RelBinop Spec.Lt) AssocLeft, binary "<=" (Spec.RelBinop Spec.Le) AssocLeft , binary ">" (Spec.RelBinop Spec.Gt) AssocLeft, binary ">=" (Spec.RelBinop Spec.Ge) AssocLeft ] , [binary "=" (Spec.RelBinop Spec.Eq) AssocLeft, binary "!=" (Spec.RelBinop Spec.Neq) AssocLeft] , [binary "&&" (Spec.RelBinop Spec.And) AssocLeft, binary "||" (Spec.RelBinop Spec.Or) AssocLeft] , [binary "==>" (Spec.RelBinop Spec.Imp) AssocLeft, binary "<=>" (Spec.RelBinop Spec.Iff) AssocLeft] ] binary name fun = Infix (do{ Tok.reservedOp lexer name; return fun }) unary name fun = Prefix (do{ Tok.reservedOp lexer name; return fun }) baseTy :: Parser Imp.Type baseTy = try (res "int" >> return Imp.IntTy) <|> try (res "bool" >> return Imp.BoolTy) <?> "Base Type" typ :: Parser Imp.Type typ = try arrTy <|> baseTy <?> "Type" arrTy :: Parser Imp.Type arrTy = do { h <- baseTy; arrs <- many1 (symb "[]"); return $ foldl (\x s -> Imp.ArrTy x) h arrs } vdecl :: Parser Imp.VDecl vdecl = do { vname <- ident; symb ":"; ty <- typ; return (vname, ty) } loopIdxP :: Parser (Maybe String) loopIdxP = optionMaybe $ res "with" >> ident loopP :: Parser Imp.Statement loopP = do { res "for"; vs <- parens $ commas vdecl; idx <- loopIdxP; res "in"; arrs <- parens $ commas expr; body <- braces block; return $ Imp.For vs idx arrs body } whileP :: Parser Imp.Statement whileP = do { res "while"; cond <- parens expr; body <- braces block; return $ Imp.While cond body } declP :: Parser Imp.Statement declP = do { res "let"; vname <- vdecl; rhs <- optionMaybe $ try $ symb "=" >> expr; semi; return $ Imp.Decl vname rhs } condP :: Parser Imp.Statement condP = do { res "if"; cond <- parens expr; tru <- braces block; fls <- option (Imp.Seq []) tail; return $ Imp.Cond cond tru fls; } where tail = try (res "else" >> braces block) <|> elifP elifP :: Parser Imp.Block elifP = do { res "else"; cond <- condP; return $ Imp.Seq [cond]; } block :: Parser Imp.Block block = liftM Imp.Seq (spaced stmt) <?> "Block" stmt :: Parser Imp.Statement stmt = try declP <|> try loopP <|> try whileP <|> try condP <|> try (liftM2 Imp.Assgn ident ((symb "=" >> expr) `followedBy` semi)) <?> "Statement" derivCompP :: Parser DerivDecl derivCompP = try (liftM DeriveDDecl dataDeclP) <|> try relDeclP <|> try alwaysP <?> "Component Member" alwaysP :: Parser DerivDecl alwaysP = res "always" >> liftM InvClaus relP `followedBy` semi usingP :: Parser UseClause usingP = do { res "using"; cname <- ident; args <- parens $ ident `sepBy` comma; semi; return (cname, args ) } dataDeclP :: Parser Imp.VDecl dataDeclP = res "data" >> vdecl `followedBy` semi relP :: Parser Spec.RelExpr relP = relexpr mainCompP :: Parser MainDecl mainCompP = try (liftM MainDDecl dataDeclP) <|> try procP <|> try (liftM MainUD usingP) <?> "Main decl parser" relDeclP :: Parser DerivDecl relDeclP = do { res "relation"; name <- ident; formals <- parens $ commas vdecl; bod <- braces relP; return $ RelDecl name formals bod; } procP :: Parser MainDecl procP = do { res "procedure"; name <- ident; args <- parens $ commas vdecl; bod <- braces block; return $ ProcDecl name args bod } comp :: Parser Component comp = do { res "Component"; name <- ident; if name=="Main" then do { decls <- braces $ spaced mainCompP; return $ MainComp decls } else do { decls <- braces $ spaced derivCompP; return $ DerivComp name decls } } prog :: Parser Program prog = do { spaces; comps <- spaced comp; let ([it], others) = partition takeMain comps in return (others, it) } where takeMain MainComp{} = True takeMain _ = False
null
https://raw.githubusercontent.com/jsarracino/spyder/a2f6d08eb2a3907d31a89ae3d942b50aaba96a88/Language/Spyder/Parser/Parser.hs
haskell
import relIndex = do { pref <- liftM Spec.RelVar ident; rhs <- many1 $ brackets relexpr; }
module Language.Spyder.Parser.Parser ( expr , stmt , prog , block , relDeclP , relP , comp , spaced , typ , dataDeclP , mainCompP , derivCompP , loopP , elifP , condP , relPrev , specTerm ) where import Text.Parsec import Text.Parsec.Expr import qualified Text.Parsec.Token as Tok import Language.Spyder.Parser.Lexer (spyderLexer, Parser) import Language.Spyder.AST.Component import qualified Language.Spyder.AST.Imp as Imp import qualified Language.Spyder.AST.Spec as Spec import Language.Spyder.AST (Program) import Control.Monad (liftM, liftM2) import Data.List (partition) import Language.Boogie.Parser as BP lexer = spyderLexer res = Tok.reserved lexer parens = Tok.parens lexer symb = Tok.symbol lexer ident = Tok.identifier lexer semi = Tok.semi lexer comma = Tok.comma lexer commas = Tok.commaSep lexer braces = Tok.braces lexer brackets = Tok.brackets lexer followedBy :: Parser a -> Parser b -> Parser a followedBy p q = do {r <- p; q; return r} spaced :: Parser a -> Parser [a] spaced p = p `sepBy` Tok.whiteSpace lexer semis p = p `sepBy` semi ints = liftM fromIntegral $ Tok.integer lexer bools = tru <|> fls where tru = do {res "true"; return True } fls = do {res "false"; return False } arrAccess = do { pref <- liftM Imp.VConst ident; rhs <- many1 $ brackets expr; return $ foldl Imp.Index pref rhs } arrPrim = liftM Imp.AConst (brackets $ commas expr) exprTerm :: Parser Imp.Expr exprTerm = parens expr <|> try (liftM Imp.IConst ints) <|> try (liftM Imp.BConst bools) <|> try arrPrim <|> try arrAccess <|> try (liftM Imp.VConst ident) <?> "simple expr" relPrev :: Parser Spec.RelExpr relPrev = do { res "prev"; (v, ifFls) <- parens prevPair; return $ Spec.Prev v ifFls } where prevPair = do { nme <- ident; comma; tl <- relexpr; return (nme, tl) } relApp :: Parser Spec.RelExpr relApp = do { nme <- ident; args <- parens $ commas relexpr; return $ Spec.RelApp nme args } relForeach :: Parser Spec.RelExpr relForeach = do { res "foreach"; vs <- parens $ commas ident; idx <- loopIdxP; res "in"; arrs <- parens $ commas ident; body <- braces relexpr; return $ Spec.Foreach vs idx arrs body } specTerm :: Parser Spec.RelExpr specTerm = parens relexpr <|> try (liftM Spec.RelInt ints) <|> try (liftM Spec.RelBool bools) <|> try relForeach <|> try relPrev < | > try relIndex <|> try relApp <|> try (liftM Spec.RelVar ident) <?> "spec expr" return $ foldl Spec . RelIndex pref rhs expr :: Parser Imp.Expr expr = buildExpressionParser exprTable exprTerm <?> "expression" relexpr :: Parser Spec.RelExpr relexpr = buildExpressionParser relTable specTerm <?> "relation expression" exprTable = [ [unary "!" (Imp.UnOp Imp.Not), unary "-" (Imp.UnOp Imp.Neg)] , [binary "*" (Imp.BinOp Imp.Mul) AssocLeft, binary "/" (Imp.BinOp Imp.Div) AssocLeft ] , [binary "+" (Imp.BinOp Imp.Plus) AssocLeft, binary "-" (Imp.BinOp Imp.Minus) AssocLeft ] , [binary "%" (Imp.BinOp Imp.Mod) AssocLeft] , [ binary "<" (Imp.BinOp Imp.Lt) AssocLeft, binary "<=" (Imp.BinOp Imp.Le) AssocLeft , binary ">" (Imp.BinOp Imp.Gt) AssocLeft, binary ">=" (Imp.BinOp Imp.Ge) AssocLeft ] , [binary "==" (Imp.BinOp Imp.Eq) AssocLeft, binary "!=" (Imp.BinOp Imp.Neq) AssocLeft] , [binary "&&" (Imp.BinOp Imp.And) AssocLeft, binary "||" (Imp.BinOp Imp.Or) AssocLeft] ] relTable = [ [unary "!" (Spec.RelUnop Spec.Not), unary "-" (Spec.RelUnop Spec.Neg)] , [binary "*" (Spec.RelBinop Spec.Mul) AssocLeft, binary "/" (Spec.RelBinop Spec.Div) AssocLeft ] , [binary "%" (Spec.RelBinop Spec.Mod) AssocLeft] , [binary "+" (Spec.RelBinop Spec.Plus) AssocLeft, binary "-" (Spec.RelBinop Spec.Minus) AssocLeft ] , [ binary "<" (Spec.RelBinop Spec.Lt) AssocLeft, binary "<=" (Spec.RelBinop Spec.Le) AssocLeft , binary ">" (Spec.RelBinop Spec.Gt) AssocLeft, binary ">=" (Spec.RelBinop Spec.Ge) AssocLeft ] , [binary "=" (Spec.RelBinop Spec.Eq) AssocLeft, binary "!=" (Spec.RelBinop Spec.Neq) AssocLeft] , [binary "&&" (Spec.RelBinop Spec.And) AssocLeft, binary "||" (Spec.RelBinop Spec.Or) AssocLeft] , [binary "==>" (Spec.RelBinop Spec.Imp) AssocLeft, binary "<=>" (Spec.RelBinop Spec.Iff) AssocLeft] ] binary name fun = Infix (do{ Tok.reservedOp lexer name; return fun }) unary name fun = Prefix (do{ Tok.reservedOp lexer name; return fun }) baseTy :: Parser Imp.Type baseTy = try (res "int" >> return Imp.IntTy) <|> try (res "bool" >> return Imp.BoolTy) <?> "Base Type" typ :: Parser Imp.Type typ = try arrTy <|> baseTy <?> "Type" arrTy :: Parser Imp.Type arrTy = do { h <- baseTy; arrs <- many1 (symb "[]"); return $ foldl (\x s -> Imp.ArrTy x) h arrs } vdecl :: Parser Imp.VDecl vdecl = do { vname <- ident; symb ":"; ty <- typ; return (vname, ty) } loopIdxP :: Parser (Maybe String) loopIdxP = optionMaybe $ res "with" >> ident loopP :: Parser Imp.Statement loopP = do { res "for"; vs <- parens $ commas vdecl; idx <- loopIdxP; res "in"; arrs <- parens $ commas expr; body <- braces block; return $ Imp.For vs idx arrs body } whileP :: Parser Imp.Statement whileP = do { res "while"; cond <- parens expr; body <- braces block; return $ Imp.While cond body } declP :: Parser Imp.Statement declP = do { res "let"; vname <- vdecl; rhs <- optionMaybe $ try $ symb "=" >> expr; semi; return $ Imp.Decl vname rhs } condP :: Parser Imp.Statement condP = do { res "if"; cond <- parens expr; tru <- braces block; fls <- option (Imp.Seq []) tail; return $ Imp.Cond cond tru fls; } where tail = try (res "else" >> braces block) <|> elifP elifP :: Parser Imp.Block elifP = do { res "else"; cond <- condP; return $ Imp.Seq [cond]; } block :: Parser Imp.Block block = liftM Imp.Seq (spaced stmt) <?> "Block" stmt :: Parser Imp.Statement stmt = try declP <|> try loopP <|> try whileP <|> try condP <|> try (liftM2 Imp.Assgn ident ((symb "=" >> expr) `followedBy` semi)) <?> "Statement" derivCompP :: Parser DerivDecl derivCompP = try (liftM DeriveDDecl dataDeclP) <|> try relDeclP <|> try alwaysP <?> "Component Member" alwaysP :: Parser DerivDecl alwaysP = res "always" >> liftM InvClaus relP `followedBy` semi usingP :: Parser UseClause usingP = do { res "using"; cname <- ident; args <- parens $ ident `sepBy` comma; semi; return (cname, args ) } dataDeclP :: Parser Imp.VDecl dataDeclP = res "data" >> vdecl `followedBy` semi relP :: Parser Spec.RelExpr relP = relexpr mainCompP :: Parser MainDecl mainCompP = try (liftM MainDDecl dataDeclP) <|> try procP <|> try (liftM MainUD usingP) <?> "Main decl parser" relDeclP :: Parser DerivDecl relDeclP = do { res "relation"; name <- ident; formals <- parens $ commas vdecl; bod <- braces relP; return $ RelDecl name formals bod; } procP :: Parser MainDecl procP = do { res "procedure"; name <- ident; args <- parens $ commas vdecl; bod <- braces block; return $ ProcDecl name args bod } comp :: Parser Component comp = do { res "Component"; name <- ident; if name=="Main" then do { decls <- braces $ spaced mainCompP; return $ MainComp decls } else do { decls <- braces $ spaced derivCompP; return $ DerivComp name decls } } prog :: Parser Program prog = do { spaces; comps <- spaced comp; let ([it], others) = partition takeMain comps in return (others, it) } where takeMain MainComp{} = True takeMain _ = False
6e5b302e34641de5bb152df72edecc85ec3e0f53ab0a13c30714561728fa151a
hgoes/smtlib2
Type.hs
module Language.SMTLib2.Internals.Type where import Language.SMTLib2.Internals.Type.Nat import Language.SMTLib2.Internals.Type.List (List(..)) import qualified Language.SMTLib2.Internals.Type.List as List import Data.Proxy import Data.Typeable import Numeric import Data.List (genericLength,genericReplicate) import Data.GADT.Compare import Data.GADT.Show import Data.Functor.Identity import Data.Graph import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.Bits import qualified GHC.TypeLits as TL import Unsafe.Coerce | Describes the kind of all SMT types . -- It is only used in promoted form, for a concrete representation see 'Repr'. data Type = BoolType | IntType | RealType | BitVecType TL.Nat | ArrayType [Type] Type | forall a. DataType a [Type] | ParameterType Nat deriving Typeable type family Lifted (tps :: [Type]) (idx :: [Type]) :: [Type] where Lifted '[] idx = '[] Lifted (tp ': tps) idx = (ArrayType idx tp) ': Lifted tps idx class Unlift (tps::[Type]) (idx::[Type]) where unliftType :: List Repr (Lifted tps idx) -> (List Repr tps,List Repr idx) unliftTypeWith :: List Repr (Lifted tps idx) -> List Repr tps -> List Repr idx instance Unlift '[tp] idx where unliftType (ArrayRepr idx tp ::: Nil) = (tp ::: Nil,idx) unliftTypeWith (ArrayRepr idx tp ::: Nil) (tp' ::: Nil) = idx instance Unlift (t2 ': ts) idx => Unlift (t1 ': t2 ': ts) idx where unliftType (ArrayRepr idx tp ::: ts) = let (tps,idx') = unliftType ts in (tp ::: tps,idx) unliftTypeWith (ArrayRepr idx tp ::: ts) (tp' ::: tps) = idx type family Fst (a :: (p,q)) :: p where Fst '(x,y) = x type family Snd (a :: (p,q)) :: q where Snd '(x,y) = y class (Typeable dt,Ord (Datatype dt),GCompare (Constr dt),GCompare (Field dt)) => IsDatatype (dt :: [Type] -> (Type -> *) -> *) where type Parameters dt :: Nat type Signature dt :: [[Type]] data Datatype dt :: * data Constr dt (csig :: [Type]) data Field dt (tp :: Type) -- | Get the data type from a value datatypeGet :: (GetType e,List.Length par ~ Parameters dt) => dt par e -> (Datatype dt,List Repr par) -- | How many polymorphic parameters does this datatype have parameters :: Datatype dt -> Natural (Parameters dt) -- | The name of the datatype. Must be unique. datatypeName :: Datatype dt -> String -- | Get all of the constructors of this datatype constructors :: Datatype dt -> List (Constr dt) (Signature dt) -- | Get the name of a constructor constrName :: Constr dt csig -> String -- | Test if a value is constructed using a specific constructor test :: dt par e -> Constr dt csig -> Bool -- | Get all the fields of a constructor fields :: Constr dt csig -> List (Field dt) csig -- | Construct a value using a constructor construct :: (List.Length par ~ Parameters dt) => List Repr par -> Constr dt csig -> List e (Instantiated csig par) -> dt par e -- | Deconstruct a value into a constructor and a list of arguments deconstruct :: GetType e => dt par e -> ConApp dt par e -- | Get the name of a field fieldName :: Field dt tp -> String -- | Get the type of a field fieldType :: Field dt tp -> Repr tp -- | Extract a field value from a value fieldGet :: dt par e -> Field dt tp -> e (CType tp par) type family CType (tp :: Type) (par :: [Type]) :: Type where CType 'BoolType par = 'BoolType CType 'IntType par = 'IntType CType 'RealType par = 'RealType CType ('BitVecType w) par = 'BitVecType w CType ('ArrayType idx el) par = 'ArrayType (Instantiated idx par) (CType el par) CType ('DataType dt arg) par = 'DataType dt (Instantiated arg par) CType ('ParameterType n) par = List.Index par n type family Instantiated (sig :: [Type]) (par :: [Type]) :: [Type] where Instantiated '[] par = '[] Instantiated (tp ': tps) par = (CType tp par) ': Instantiated tps par data ConApp dt par e = forall csig. (List.Length par ~ Parameters dt) => ConApp { parameters' :: List Repr par , constructor :: Constr dt csig , arguments :: List e (Instantiated csig par) } data FieldType tp where FieldType : : Repr tp - > FieldType ( ' Left tp ) ParType : : Natural n - > FieldType ( ' Right n ) data AnyDatatype = forall dt. IsDatatype dt => AnyDatatype (Datatype dt) data AnyConstr = forall dt csig. IsDatatype dt => AnyConstr (Datatype dt) (Constr dt csig) data AnyField = forall dt csig tp. IsDatatype dt => AnyField (Datatype dt) (Field dt tp) data TypeRegistry dt con field = TypeRegistry { allDatatypes :: Map dt AnyDatatype , revDatatypes :: Map AnyDatatype dt , allConstructors :: Map con AnyConstr , revConstructors :: Map AnyConstr con , allFields :: Map field AnyField , revFields :: Map AnyField field } emptyTypeRegistry :: TypeRegistry dt con field emptyTypeRegistry = TypeRegistry Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty dependencies :: IsDatatype dt => Set String -- ^ Already registered datatypes -> Datatype dt -> (Set String,[[AnyDatatype]]) dependencies known p = (known',dts) where dts = fmap (\scc -> fmap (\(dt,_,_) -> dt) $ flattenSCC scc) sccs sccs = stronglyConnCompR edges (known',edges) = dependencies' known p dependencies' :: IsDatatype dt => Set String -> Datatype dt -> (Set String,[(AnyDatatype,String,[String])]) dependencies' known dt | Set.member (datatypeName dt) known = (known,[]) | otherwise = let name = datatypeName dt known1 = Set.insert name known deps = dependenciesCons (constructors dt) (known2,edges) = foldl (\(cknown,cedges) (AnyDatatype dt) -> dependencies' cknown dt ) (known1,[]) deps in (known2,(AnyDatatype dt,name,[ datatypeName dt | AnyDatatype dt <- deps ]):edges) dependenciesCons :: IsDatatype dt => List (Constr dt) tps -> [AnyDatatype] dependenciesCons Nil = [] dependenciesCons (con ::: cons) = let dep1 = dependenciesFields (fields con) dep2 = dependenciesCons cons in dep1++dep2 dependenciesFields :: IsDatatype dt => List (Field dt) tps -> [AnyDatatype] dependenciesFields Nil = [] dependenciesFields (f ::: fs) = let dep1 = dependenciesTp (fieldType f) dep2 = dependenciesFields fs in dep1++dep2 dependenciesTp :: Repr tp -> [AnyDatatype] dependenciesTp (ArrayRepr idx el) = let dep1 = dependenciesTps idx dep2 = dependenciesTp el in dep1++dep2 dependenciesTp (DataRepr dt par) = let dep1 = [AnyDatatype dt] dep2 = dependenciesTps par in dep1++dep2 dependenciesTp _ = [] dependenciesTps :: List Repr tps -> [AnyDatatype] dependenciesTps Nil = [] dependenciesTps (tp ::: tps) = let dep1 = dependenciesTp tp dep2 = dependenciesTps tps in dep1++dep2 signature :: IsDatatype dt => Datatype dt -> List (List Repr) (Signature dt) signature dt = runIdentity $ List.mapM (\con -> List.mapM (\f -> return (fieldType f) ) (fields con) ) (constructors dt) constrSig :: IsDatatype dt => Constr dt sig -> List Repr sig constrSig constr = runIdentity $ List.mapM (\f -> return (fieldType f)) (fields constr) instantiate :: List Repr sig -> List Repr par -> (List Repr (Instantiated sig par), List.Length sig :~: List.Length (Instantiated sig par)) instantiate Nil _ = (Nil,Refl) instantiate (tp ::: tps) par = case instantiate tps par of (ntps,Refl) -> (ctype tp par ::: ntps,Refl) ctype :: Repr tp -> List Repr par -> Repr (CType tp par) ctype BoolRepr _ = BoolRepr ctype IntRepr _ = IntRepr ctype RealRepr _ = RealRepr ctype (BitVecRepr w) _ = BitVecRepr w ctype (ArrayRepr idx el) par = case instantiate idx par of (nidx,Refl) -> ArrayRepr nidx (ctype el par) ctype (DataRepr dt args) par = case instantiate args par of (nargs,Refl) -> DataRepr dt nargs ctype (ParameterRepr p) par = List.index par p determines :: IsDatatype dt => Datatype dt -> Constr dt sig -> Bool determines dt con = allDetermined (fromInteger $ naturalToInteger $ parameters dt) $ determines' (fields con) Set.empty where determines' :: IsDatatype dt => List (Field dt) tps -> Set Integer -> Set Integer determines' Nil mp = mp determines' (f ::: fs) mp = determines' fs (containedParameter (fieldType f) mp) allDetermined sz mp = Set.size mp == sz containedParameter :: Repr tp -> Set Integer -> Set Integer containedParameter (ArrayRepr idx el) det = runIdentity $ List.foldM (\det tp -> return $ containedParameter tp det ) (containedParameter el det) idx containedParameter (DataRepr i args) det = runIdentity $ List.foldM (\det tp -> return $ containedParameter tp det ) det args containedParameter (ParameterRepr p) det = Set.insert (naturalToInteger p) det containedParameter _ det = det typeInference :: Repr atp -- ^ The type containing parameters -> Repr ctp -- ^ The concrete type without parameters -> (forall n ntp. Natural n -> Repr ntp -> a -> Maybe a) -- ^ Action to execute when a parameter is assigned -> a -> Maybe a typeInference BoolRepr BoolRepr _ x = Just x typeInference IntRepr IntRepr _ x = Just x typeInference RealRepr RealRepr _ x = Just x typeInference (BitVecRepr w1) (BitVecRepr w2) _ x = do Refl <- geq w1 w2 return x typeInference (ParameterRepr n) tp f x = f n tp x typeInference (ArrayRepr idx el) (ArrayRepr idx' el') f x = do x1 <- typeInferences idx idx' f x typeInference el el' f x1 typeInference (DataRepr (_::Datatype dt) par) (DataRepr (_::Datatype dt') par') f x = do Refl <- eqT :: Maybe (dt :~: dt') typeInferences par par' f x typeInference _ _ _ _ = Nothing typeInferences :: List Repr atps -> List Repr ctps -> (forall n ntp. Natural n -> Repr ntp -> a -> Maybe a) -> a -> Maybe a typeInferences Nil Nil _ x = Just x typeInferences (atp ::: atps) (ctp ::: ctps) f x = do x1 <- typeInference atp ctp f x typeInferences atps ctps f x1 typeInferences _ _ _ _ = Nothing partialInstantiation :: Repr tp -> (forall n a. Natural n -> (forall ntp. Repr ntp -> a) -> Maybe a) -> (forall rtp. Repr rtp -> a) -> a partialInstantiation BoolRepr _ res = res BoolRepr partialInstantiation IntRepr _ res = res IntRepr partialInstantiation RealRepr _ res = res RealRepr partialInstantiation (BitVecRepr w) _ res = res (BitVecRepr w) partialInstantiation (ArrayRepr idx el) f res = partialInstantiations idx f $ \nidx -> partialInstantiation el f $ \nel -> res $ ArrayRepr nidx nel partialInstantiation (DataRepr dt par) f res = partialInstantiations par f $ \npar -> res $ DataRepr dt npar partialInstantiation (ParameterRepr n) f res = case f n res of Just r -> r Nothing -> res (ParameterRepr n) partialInstantiations :: List Repr tp -> (forall n a. Natural n -> (forall ntp. Repr ntp -> a) -> Maybe a) -> (forall rtp. List.Length tp ~ List.Length rtp => List Repr rtp -> a) -> a partialInstantiations Nil _ res = res Nil partialInstantiations (tp ::: tps) f res = partialInstantiation tp f $ \ntp -> partialInstantiations tps f $ \ntps -> res (ntp ::: ntps) registerType :: (Monad m,IsDatatype tp,Ord dt,Ord con,Ord field) => dt -> (forall sig. Constr tp sig -> m con) -> (forall sig tp'. Field tp tp' -> m field) -> Datatype tp -> TypeRegistry dt con field -> m (TypeRegistry dt con field) registerType i f g dt reg = List.foldM (\reg con -> do c <- f con let reg' = reg { allConstructors = Map.insert c (AnyConstr dt con) (allConstructors reg) } List.foldM (\reg field -> do fi <- g field return $ reg { allFields = Map.insert fi (AnyField dt field) (allFields reg) } ) reg' (fields con) ) reg1 (constructors dt) where reg1 = reg { allDatatypes = Map.insert i (AnyDatatype dt) (allDatatypes reg) , revDatatypes = Map.insert (AnyDatatype dt) i (revDatatypes reg) } registerTypeName :: IsDatatype dt => Datatype dt -> TypeRegistry String String String -> TypeRegistry String String String registerTypeName dt reg = runIdentity (registerType (datatypeName dt) (return . constrName) (return . fieldName) dt reg) instance Eq AnyDatatype where (==) (AnyDatatype x) (AnyDatatype y) = datatypeName x == datatypeName y instance Eq AnyConstr where (==) (AnyConstr _ c1) (AnyConstr _ c2) = constrName c1 == constrName c2 instance Eq AnyField where (==) (AnyField _ f1) (AnyField _ f2) = fieldName f1 == fieldName f2 instance Ord AnyDatatype where compare (AnyDatatype x) (AnyDatatype y) = compare (datatypeName x) (datatypeName y) instance Ord AnyConstr where compare (AnyConstr _ c1) (AnyConstr _ c2) = compare (constrName c1) (constrName c2) instance Ord AnyField where compare (AnyField _ f1) (AnyField _ f2) = compare (fieldName f1) (fieldName f2) data DynamicDatatype (par :: Nat) (sig :: [[Type]]) = DynDatatype { dynDatatypeParameters :: Natural par , dynDatatypeSig :: List (DynamicConstructor sig) sig , dynDatatypeName :: String } deriving (Eq,Ord) data DynamicConstructor (sig :: [[Type]]) (csig :: [Type]) where DynConstructor :: Natural idx -> String -> List (DynamicField sig) (List.Index sig idx) -> DynamicConstructor sig (List.Index sig idx) data DynamicField (sig :: [[Type]]) (tp :: Type) where DynField :: Natural idx -> Natural fidx -> String -> Repr (List.Index (List.Index sig idx) fidx) -> DynamicField sig (List.Index (List.Index sig idx) fidx) data DynamicValue (plen :: Nat) (sig :: [[Type]]) (par :: [Type]) e where DynValue :: DynamicDatatype (List.Length par) sig -> List Repr par -> DynamicConstructor sig csig -> List e (Instantiated csig par) -> DynamicValue (List.Length par) sig par e instance (Typeable l,Typeable sig) => IsDatatype (DynamicValue l sig) where type Parameters (DynamicValue l sig) = l type Signature (DynamicValue l sig) = sig newtype Datatype (DynamicValue l sig) = DynDatatypeInfo { dynDatatypeInfo :: DynamicDatatype l sig } deriving (Eq,Ord) data Constr (DynamicValue l sig) csig = DynConstr (DynamicDatatype l sig) (DynamicConstructor sig csig) newtype Field (DynamicValue l sig) tp = DynField' (DynamicField sig tp) parameters = dynDatatypeParameters . dynDatatypeInfo datatypeGet (DynValue dt par _ _) = (DynDatatypeInfo dt,par) datatypeName = dynDatatypeName . dynDatatypeInfo constructors (DynDatatypeInfo dt) = runIdentity $ List.mapM (\con -> return (DynConstr dt con)) (dynDatatypeSig dt) constrName (DynConstr _ (DynConstructor _ n _)) = n test (DynValue _ _ (DynConstructor n _ _) _) (DynConstr _ (DynConstructor m _ _)) = case geq n m of Just Refl -> True Nothing -> False fields (DynConstr _ (DynConstructor _ _ fs)) = runIdentity $ List.mapM (\f -> return (DynField' f)) fs construct par (DynConstr dt con) args = DynValue dt par con args deconstruct (DynValue dt par con args) = ConApp par (DynConstr dt con) args fieldName (DynField' (DynField _ _ n _)) = n fieldType (DynField' (DynField _ _ _ tp)) = tp fieldGet (DynValue dt par con@(DynConstructor cidx _ fs) args) (DynField' (DynField cidx' fidx _ _)) = case geq cidx cidx' of Just Refl -> index par fs args fidx where index :: List Repr par -> List (DynamicField sig) csig -> List e (Instantiated csig par) -> Natural n -> e (CType (List.Index csig n) par) index _ (_ ::: _) (tp ::: _) Zero = tp index par (_ ::: sig) (_ ::: tps) (Succ n) = index par sig tps n instance Show (Datatype (DynamicValue l sig)) where showsPrec p (DynDatatypeInfo dt) = showString (dynDatatypeName dt) instance GEq (DynamicConstructor sig) where geq (DynConstructor i1 _ _) (DynConstructor i2 _ _) = do Refl <- geq i1 i2 return Refl instance GCompare (DynamicConstructor sig) where gcompare (DynConstructor i1 _ _) (DynConstructor i2 _ _) = case gcompare i1 i2 of GEQ -> GEQ GLT -> GLT GGT -> GGT instance GEq (Constr (DynamicValue l sig)) where geq (DynConstr _ (DynConstructor n _ _)) (DynConstr _ (DynConstructor m _ _)) = do Refl <- geq n m return Refl instance GCompare (Constr (DynamicValue l sig)) where gcompare (DynConstr _ (DynConstructor n _ _)) (DynConstr _ (DynConstructor m _ _)) = case gcompare n m of GEQ -> GEQ GLT -> GLT GGT -> GGT instance GEq (Field (DynamicValue l sig)) where geq (DynField' (DynField cidx1 fidx1 _ _)) (DynField' (DynField cidx2 fidx2 _ _)) = do Refl <- geq cidx1 cidx2 Refl <- geq fidx1 fidx2 return Refl instance GCompare (Field (DynamicValue l sig)) where gcompare (DynField' (DynField cidx1 fidx1 _ _)) (DynField' (DynField cidx2 fidx2 _ _)) = case gcompare cidx1 cidx2 of GEQ -> case gcompare fidx1 fidx2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT newtype BitWidth (bw :: TL.Nat) = BitWidth { bwSize :: Integer } getBw :: Integer -> (forall bw. TL.KnownNat bw => BitWidth bw -> a) -> a getBw w f = case TL.someNatVal w of Just (TL.SomeNat (_::Proxy bw)) -> f (BitWidth w::BitWidth bw) -- | Values that can be used as constants in expressions. data Value (a :: Type) where BoolValue :: Bool -> Value BoolType IntValue :: Integer -> Value IntType RealValue :: Rational -> Value RealType BitVecValue :: Integer -> BitWidth bw -> Value (BitVecType bw) DataValue :: (IsDatatype dt,List.Length par ~ Parameters dt) => dt par Value -> Value (DataType dt par) #if __GLASGOW_HASKELL__ >= 800 pattern ConstrValue :: () => (List.Length par ~ Parameters dt,a ~ DataType dt par,IsDatatype dt) #else pattern ConstrValue :: (List.Length par ~ Parameters dt,a ~ DataType dt par,IsDatatype dt) => () #endif => List Repr par -> Constr dt csig -> List Value (Instantiated csig par) -> Value a pattern ConstrValue par con args <- DataValue (deconstruct -> ConApp par con args) where ConstrValue par con args = DataValue (construct par con args) data AnyValue = forall (t :: Type). AnyValue (Value t) | A concrete representation of an SMT type . -- For aesthetic reasons, it's recommended to use the functions 'bool', 'int', 'real', 'bitvec' or 'array'. data Repr (t :: Type) where BoolRepr :: Repr BoolType IntRepr :: Repr IntType RealRepr :: Repr RealType BitVecRepr :: BitWidth bw -> Repr (BitVecType bw) ArrayRepr :: List Repr idx -> Repr val -> Repr (ArrayType idx val) DataRepr :: (IsDatatype dt,List.Length par ~ Parameters dt) => Datatype dt -> List Repr par -> Repr (DataType dt par) ParameterRepr :: Natural p -> Repr (ParameterType p) data NumRepr (t :: Type) where NumInt :: NumRepr IntType NumReal :: NumRepr RealType data FunRepr (sig :: ([Type],Type)) where FunRepr :: List Repr arg -> Repr tp -> FunRepr '(arg,tp) class GetType v where getType :: v tp -> Repr tp class GetFunType fun where getFunType :: fun '(arg,res) -> (List Repr arg,Repr res) bw :: TL.KnownNat bw => Proxy bw -> BitWidth bw bw = BitWidth . TL.natVal instance Eq (BitWidth bw) where (==) (BitWidth _) (BitWidth _) = True -- | A representation of the SMT Bool type. -- Holds the values 'Language.SMTLib2.true' or 'Language.SMTLib2.Internals.false'. -- Constants can be created using 'Language.SMTLib2.cbool'. bool :: Repr BoolType bool = BoolRepr -- | A representation of the SMT Int type. -- Holds the unbounded positive and negative integers. -- Constants can be created using 'Language.SMTLib2.cint'. int :: Repr IntType int = IntRepr | A representation of the SMT Real type . -- Holds positive and negative reals x/y where x and y are integers. -- Constants can be created using 'Language.SMTLib2.creal'. real :: Repr RealType real = RealRepr -- | A typed representation of the SMT BitVec type. -- Holds bitvectors (a vector of booleans) of a certain bitwidth. -- Constants can be created using 'Language.SMTLib2.cbv'. bitvec :: BitWidth bw -- ^ The width of the bitvector -> Repr (BitVecType bw) bitvec = BitVecRepr -- | A representation of the SMT Array type. -- Has a list of index types and an element type. Stores one value of the element type for each combination of the index types . Constants can be created using ' Language . SMTLib2.constArray ' . array :: List Repr idx -> Repr el -> Repr (ArrayType idx el) array = ArrayRepr -- | A representation of a user-defined datatype without parameters. dt :: (IsDatatype dt,Parameters dt ~ 'Z) => Datatype dt -> Repr (DataType dt '[]) dt dt = DataRepr dt List.Nil -- | A representation of a user-defined datatype with parameters. dt' :: (IsDatatype dt,List.Length par ~ Parameters dt) => Datatype dt -> List Repr par -> Repr (DataType dt par) dt' = DataRepr instance GEq BitWidth where geq (BitWidth bw1) (BitWidth bw2) | bw1==bw2 = Just $ unsafeCoerce Refl | otherwise = Nothing instance GCompare BitWidth where gcompare (BitWidth bw1) (BitWidth bw2) = case compare bw1 bw2 of EQ -> unsafeCoerce GEQ LT -> GLT GT -> GGT instance GetType Repr where getType = id instance GetType Value where getType = valueType instance GEq Value where geq (BoolValue v1) (BoolValue v2) = if v1==v2 then Just Refl else Nothing geq (IntValue v1) (IntValue v2) = if v1==v2 then Just Refl else Nothing geq (RealValue v1) (RealValue v2) = if v1==v2 then Just Refl else Nothing geq (BitVecValue v1 bw1) (BitVecValue v2 bw2) = do Refl <- geq bw1 bw2 if v1==v2 then return Refl else Nothing geq (DataValue (v1::dt1 par1 Value)) (DataValue (v2::dt2 par2 Value)) = do Refl <- eqT :: Maybe (dt1 :~: dt2) case deconstruct v1 of ConApp p1 c1 arg1 -> case deconstruct v2 of ConApp p2 c2 arg2 -> do Refl <- geq p1 p2 Refl <- geq c1 c2 Refl <- geq arg1 arg2 return Refl geq _ _ = Nothing instance Eq (Value t) where (==) = defaultEq instance GCompare Value where gcompare (BoolValue v1) (BoolValue v2) = case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT gcompare (BoolValue _) _ = GLT gcompare _ (BoolValue _) = GGT gcompare (IntValue v1) (IntValue v2) = case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT gcompare (IntValue _) _ = GLT gcompare _ (IntValue _) = GGT gcompare (RealValue v1) (RealValue v2) = case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT gcompare (RealValue _) _ = GLT gcompare _ (RealValue _) = GGT gcompare (BitVecValue v1 bw1) (BitVecValue v2 bw2) = case gcompare bw1 bw2 of GEQ -> case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT GLT -> GLT GGT -> GGT gcompare (BitVecValue _ _) _ = GLT gcompare _ (BitVecValue _ _) = GGT gcompare (DataValue (v1::dt1 par1 Value)) (DataValue (v2::dt2 par2 Value)) = case eqT :: Maybe (dt1 :~: dt2) of Just Refl -> case deconstruct v1 of ConApp p1 c1 arg1 -> case deconstruct v2 of ConApp p2 c2 arg2 -> case gcompare p1 p2 of GEQ -> case gcompare c1 c2 of GEQ -> case gcompare arg1 arg2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT Nothing -> case compare (typeRep (Proxy::Proxy dt1)) (typeRep (Proxy::Proxy dt2)) of LT -> GLT GT -> GGT instance Ord (Value t) where compare = defaultCompare instance GEq Repr where geq BoolRepr BoolRepr = Just Refl geq IntRepr IntRepr = Just Refl geq RealRepr RealRepr = Just Refl geq (BitVecRepr bw1) (BitVecRepr bw2) = do Refl <- geq bw1 bw2 return Refl geq (ArrayRepr idx1 val1) (ArrayRepr idx2 val2) = do Refl <- geq idx1 idx2 Refl <- geq val1 val2 return Refl geq (DataRepr (_::Datatype dt1) p1) (DataRepr (_::Datatype dt2) p2) = do Refl <- eqT :: Maybe (Datatype dt1 :~: Datatype dt2) Refl <- geq p1 p2 return Refl geq _ _ = Nothing instance Eq (Repr tp) where (==) _ _ = True instance GEq NumRepr where geq NumInt NumInt = Just Refl geq NumReal NumReal = Just Refl geq _ _ = Nothing instance GEq FunRepr where geq (FunRepr a1 r1) (FunRepr a2 r2) = do Refl <- geq a1 a2 Refl <- geq r1 r2 return Refl instance GCompare Repr where gcompare BoolRepr BoolRepr = GEQ gcompare BoolRepr _ = GLT gcompare _ BoolRepr = GGT gcompare IntRepr IntRepr = GEQ gcompare IntRepr _ = GLT gcompare _ IntRepr = GGT gcompare RealRepr RealRepr = GEQ gcompare RealRepr _ = GLT gcompare _ RealRepr = GGT gcompare (BitVecRepr bw1) (BitVecRepr bw2) = case gcompare bw1 bw2 of GEQ -> GEQ GLT -> GLT GGT -> GGT gcompare (BitVecRepr _) _ = GLT gcompare _ (BitVecRepr _) = GGT gcompare (ArrayRepr idx1 val1) (ArrayRepr idx2 val2) = case gcompare idx1 idx2 of GEQ -> case gcompare val1 val2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT gcompare (ArrayRepr _ _) _ = GLT gcompare _ (ArrayRepr _ _) = GGT gcompare (DataRepr (dt1 :: Datatype dt1) p1 ) (DataRepr (dt2 :: Datatype dt2) p2) = case eqT of Just (Refl :: Datatype dt1 :~: Datatype dt2) -> case gcompare p1 p2 of GEQ -> GEQ GLT -> GLT GGT -> GGT Nothing -> case compare (datatypeName dt1) (datatypeName dt2) of LT -> GLT GT -> GGT instance Ord (Repr tp) where compare _ _ = EQ instance GCompare NumRepr where gcompare NumInt NumInt = GEQ gcompare NumInt _ = GLT gcompare _ NumInt = GGT gcompare NumReal NumReal = GEQ instance GCompare FunRepr where gcompare (FunRepr a1 r1) (FunRepr a2 r2) = case gcompare a1 a2 of GEQ -> case gcompare r1 r2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT instance Show (Value tp) where showsPrec p (BoolValue b) = showsPrec p b showsPrec p (IntValue i) = showsPrec p i showsPrec p (RealValue i) = showsPrec p i showsPrec p (BitVecValue v n) = showBitVec p v (bwSize n) showsPrec p (DataValue val) = case deconstruct val of ConApp par con args -> showParen (p>10) $ showString "ConstrValue " . showString (constrName con). showChar ' ' . showsPrec 11 args showBitVec :: Int -> Integer -> Integer -> ShowS showBitVec p v bw | bw `mod` 4 == 0 = let str = showHex rv "" exp_len = bw `div` 4 len = genericLength str in showString "#x" . showString (genericReplicate (exp_len-len) '0') . showString str | otherwise = let str = showIntAtBase 2 (\x -> case x of 0 -> '0' 1 -> '1' ) rv "" len = genericLength str in showString "#b" . showString (genericReplicate (bw-len) '0') . showString str where rv = v `mod` 2^bw instance GShow Value where gshowsPrec = showsPrec instance Show (Repr t) where showsPrec _ BoolRepr = showString "bool" showsPrec _ IntRepr = showString "int" showsPrec _ RealRepr = showString "real" showsPrec p (BitVecRepr n) = showParen (p>10) $ showString "bitvec " . showsPrec 11 (bwSize n) showsPrec p (ArrayRepr idx el) = showParen (p>10) $ showString "array " . showsPrec 11 idx . showChar ' ' . showsPrec 11 el showsPrec p (DataRepr dt par) = showParen (p>10) $ showString "dt " . showString (datatypeName dt) instance GShow Repr where gshowsPrec = showsPrec deriving instance Show (NumRepr t) instance GShow NumRepr where gshowsPrec = showsPrec valueType :: Value tp -> Repr tp valueType (BoolValue _) = BoolRepr valueType (IntValue _) = IntRepr valueType (RealValue _) = RealRepr valueType (BitVecValue _ bw) = BitVecRepr bw valueType (DataValue v) = let (dt,par) = datatypeGet v in DataRepr dt par liftType :: List Repr tps -> List Repr idx -> List Repr (Lifted tps idx) liftType Nil idx = Nil liftType (x ::: xs) idx = (ArrayRepr idx x) ::: (liftType xs idx) numRepr :: NumRepr tp -> Repr tp numRepr NumInt = IntRepr numRepr NumReal = RealRepr asNumRepr :: Repr tp -> Maybe (NumRepr tp) asNumRepr IntRepr = Just NumInt asNumRepr RealRepr = Just NumReal asNumRepr _ = Nothing getTypes :: GetType e => List e tps -> List Repr tps getTypes Nil = Nil getTypes (x ::: xs) = getType x ::: getTypes xs -- | Determine the number of elements a type contains. -- 'Nothing' means the type has infinite elements. typeSize :: Maybe (List Repr par) -> Repr tp -> Maybe Integer typeSize _ BoolRepr = Just 2 typeSize _ IntRepr = Nothing typeSize _ RealRepr = Nothing typeSize _ (BitVecRepr bw) = Just $ 2^(bwSize bw) typeSize par (ArrayRepr idx el) = do idxSz <- List.toList (typeSize par) idx elSz <- typeSize par el return $ product (elSz:idxSz) typeSize _ (DataRepr dt par) = do conSz <- List.toList (constrSize dt par) (constructors dt) return $ sum conSz where constrSize :: IsDatatype dt => Datatype dt -> List Repr par -> Constr dt sig -> Maybe Integer constrSize dt par con = do fieldSz <- List.toList (fieldSize dt par) (fields con) return $ product fieldSz fieldSize :: IsDatatype dt => Datatype dt -> List Repr par -> Field dt tp -> Maybe Integer fieldSize dt par field = typeSize (Just par) (fieldType field) typeSize (Just par) (ParameterRepr p) = typeSize Nothing (List.index par p) typeFiniteDomain :: Repr tp -> Maybe [Value tp] typeFiniteDomain BoolRepr = Just [BoolValue False,BoolValue True] typeFiniteDomain (BitVecRepr bw) = Just [ BitVecValue n bw | n <- [0..2^(bwSize bw)-1] ] typeFiniteDomain _ = Nothing instance Enum (Value BoolType) where succ (BoolValue x) = BoolValue (succ x) pred (BoolValue x) = BoolValue (pred x) toEnum i = BoolValue (toEnum i) fromEnum (BoolValue x) = fromEnum x enumFrom (BoolValue x) = fmap BoolValue (enumFrom x) enumFromThen (BoolValue x) (BoolValue y) = fmap BoolValue (enumFromThen x y) enumFromTo (BoolValue x) (BoolValue y) = fmap BoolValue (enumFromTo x y) enumFromThenTo (BoolValue x) (BoolValue y) (BoolValue z) = fmap BoolValue (enumFromThenTo x y z) instance Bounded (Value BoolType) where minBound = BoolValue False maxBound = BoolValue True instance Num (Value IntType) where (+) (IntValue x) (IntValue y) = IntValue (x+y) (-) (IntValue x) (IntValue y) = IntValue (x-y) (*) (IntValue x) (IntValue y) = IntValue (x*y) negate (IntValue x) = IntValue (negate x) abs (IntValue x) = IntValue (abs x) signum (IntValue x) = IntValue (signum x) fromInteger = IntValue instance Enum (Value IntType) where succ (IntValue x) = IntValue (succ x) pred (IntValue x) = IntValue (pred x) toEnum i = IntValue (toEnum i) fromEnum (IntValue x) = fromEnum x enumFrom (IntValue x) = fmap IntValue (enumFrom x) enumFromThen (IntValue x) (IntValue y) = fmap IntValue (enumFromThen x y) enumFromTo (IntValue x) (IntValue y) = fmap IntValue (enumFromTo x y) enumFromThenTo (IntValue x) (IntValue y) (IntValue z) = fmap IntValue (enumFromThenTo x y z) instance Real (Value IntType) where toRational (IntValue x) = toRational x instance Integral (Value IntType) where quot (IntValue x) (IntValue y) = IntValue $ quot x y rem (IntValue x) (IntValue y) = IntValue $ rem x y div (IntValue x) (IntValue y) = IntValue $ div x y mod (IntValue x) (IntValue y) = IntValue $ mod x y quotRem (IntValue x) (IntValue y) = (IntValue q,IntValue r) where (q,r) = quotRem x y divMod (IntValue x) (IntValue y) = (IntValue d,IntValue m) where (d,m) = divMod x y toInteger (IntValue x) = x instance Num (Value RealType) where (+) (RealValue x) (RealValue y) = RealValue (x+y) (-) (RealValue x) (RealValue y) = RealValue (x-y) (*) (RealValue x) (RealValue y) = RealValue (x*y) negate (RealValue x) = RealValue (negate x) abs (RealValue x) = RealValue (abs x) signum (RealValue x) = RealValue (signum x) fromInteger = RealValue . fromInteger instance Real (Value RealType) where toRational (RealValue x) = x instance Fractional (Value RealType) where (/) (RealValue x) (RealValue y) = RealValue (x/y) recip (RealValue x) = RealValue (recip x) fromRational = RealValue instance RealFrac (Value RealType) where properFraction (RealValue x) = let (p,q) = properFraction x in (p,RealValue q) truncate (RealValue x) = truncate x round (RealValue x) = round x ceiling (RealValue x) = ceiling x floor (RealValue x) = floor x withBW :: TL.KnownNat bw => (Proxy bw -> res (BitVecType bw)) -> res (BitVecType bw) withBW f = f Proxy bvAdd :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvAdd (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvAdd: Bitvector size mismatch" | otherwise = BitVecValue ((x+y) `mod` (2^(bwSize bw1))) bw1 bvSub :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvSub (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvSub: Bitvector size mismatch" | otherwise = BitVecValue ((x-y) `mod` (2^(bwSize bw1))) bw1 bvMul :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvMul (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvMul: Bitvector size mismatch" | otherwise = BitVecValue ((x*y) `mod` (2^(bwSize bw1))) bw1 bvDiv :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvDiv (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvDiv: Bitvector size mismatch" | otherwise = BitVecValue (x `div` y) bw1 bvMod :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvMod (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvMod: Bitvector size mismatch" | otherwise = BitVecValue (x `mod` y) bw1 bvNegate :: Value (BitVecType bw) -> Value (BitVecType bw) bvNegate (BitVecValue x bw) = BitVecValue (if x==0 then 0 else 2^(bwSize bw)-x) bw bvSignum :: Value (BitVecType bw) -> Value (BitVecType bw) bvSignum (BitVecValue x bw) = BitVecValue (if x==0 then 0 else 1) bw instance TL.KnownNat bw => Num (Value (BitVecType bw)) where (+) = bvAdd (-) = bvSub (*) = bvMul negate = bvNegate abs = id signum = bvSignum fromInteger x = withBW $ \pr -> let bw = TL.natVal pr in BitVecValue (x `mod` (2^bw)) (BitWidth bw) -- | Get the smallest bitvector value that is bigger than the given one. -- Also known as the successor. bvSucc :: Value (BitVecType bw) -> Value (BitVecType bw) bvSucc (BitVecValue i bw) | i < 2^(bwSize bw) - 1 = BitVecValue (i+1) bw | otherwise = error "bvSucc: tried to take `succ' of maxBound" -- | Get the largest bitvector value that is smaller than the given one. -- Also known as the predecessor. bvPred :: Value (BitVecType bw) -> Value (BitVecType bw) bvPred (BitVecValue i bw) | i > 0 = BitVecValue (i-1) bw | otherwise = error "bvPred: tried to take `pred' of minBound" instance TL.KnownNat bw => Enum (Value (BitVecType bw)) where succ = bvSucc pred = bvPred toEnum i = withBW $ \bw -> let i' = toInteger i bw' = TL.natVal bw in if i >= 0 && i < 2^bw' then BitVecValue i' (BitWidth bw') else error "Prelude.toEnum: argument out of range for bitvector value." fromEnum (BitVecValue i _) = fromInteger i enumFrom (BitVecValue x bw) = [ BitVecValue i bw | i <- [x..2^(bwSize bw)-1] ] enumFromThen (BitVecValue x bw) (BitVecValue y _) = [ BitVecValue i bw | i <- [x,y..2^(bwSize bw)-1] ] enumFromTo (BitVecValue x bw) (BitVecValue y _) = [ BitVecValue i bw | i <- [x..y] ] enumFromThenTo (BitVecValue x bw) (BitVecValue y _) (BitVecValue z _) = [ BitVecValue i bw | i <- [x,y..z] ] instance TL.KnownNat bw => Bounded (Value (BitVecType bw)) where minBound = withBW $ \w -> BitVecValue 0 (bw w) maxBound = withBW $ \bw -> let bw' = TL.natVal bw in BitVecValue (2^bw'-1) (BitWidth bw') -- | Get the minimal value for a bitvector. If unsigned , the value is 0 , otherwise 2^(bw-1 ) . bvMinValue :: Bool -- ^ Signed bitvector? -> Repr (BitVecType bw) -> Value (BitVecType bw) bvMinValue False (BitVecRepr bw) = BitVecValue 0 bw bvMinValue True (BitVecRepr bw) = BitVecValue (2^(bwSize bw-1)) bw -- | Get the maximal value for a bitvector. If unsigned , the value is 2^(bw-1)-1 , otherwise 2^bw-1 . bvMaxValue :: Bool -- ^ Signed bitvector? -> Repr (BitVecType bw) -> Value (BitVecType bw) bvMaxValue False (BitVecRepr bw) = BitVecValue (2^(bwSize bw)-1) bw bvMaxValue True (BitVecRepr bw) = BitVecValue (2^(bwSize bw-1)-1) bw instance TL.KnownNat bw => Bits (Value (BitVecType bw)) where (.&.) (BitVecValue x bw) (BitVecValue y _) = BitVecValue (x .&. y) bw (.|.) (BitVecValue x bw) (BitVecValue y _) = BitVecValue (x .|. y) bw xor (BitVecValue x bw) (BitVecValue y _) = BitVecValue ((x .|. max) `xor` (y .|. max)) bw where max = bit $ fromInteger $ bwSize bw complement (BitVecValue x bw) = BitVecValue (2^(bwSize bw)-1-x) bw shift (BitVecValue x bw) i = BitVecValue ((x `shift` i) `mod` (2^(bwSize bw))) bw rotate (BitVecValue x bw) i = BitVecValue ((x `rotate` i) `mod` (2^(bwSize bw))) bw zeroBits = withBW $ \w -> BitVecValue 0 (bw w) bit n = withBW $ \bw -> let bw' = TL.natVal bw in if toInteger n < bw' && n >= 0 then BitVecValue (bit n) (BitWidth bw') else BitVecValue 0 (BitWidth bw') setBit (BitVecValue x bw) i = if toInteger i < bwSize bw && i >= 0 then BitVecValue (setBit x i) bw else BitVecValue x bw clearBit (BitVecValue x bw) i = if toInteger i < bwSize bw && i >= 0 then BitVecValue (clearBit x i) bw else BitVecValue x bw complementBit (BitVecValue x bw) i = if toInteger i < bwSize bw && i >= 0 then BitVecValue (complementBit x i) bw else BitVecValue x bw testBit (BitVecValue x _) i = testBit x i #if MIN_VERSION_base(4,7,0) bitSizeMaybe (BitVecValue _ bw) = Just (fromInteger $ bwSize bw) #endif bitSize (BitVecValue _ bw) = fromInteger $ bwSize bw isSigned _ = False shiftL (BitVecValue x bw) i = BitVecValue ((shiftL x i) `mod` 2^(bwSize bw)) bw shiftR (BitVecValue x bw) i = BitVecValue ((shiftR x i) `mod` 2^(bwSize bw)) bw rotateL (BitVecValue x bw) i = BitVecValue ((rotateL x i) `mod` 2^(bwSize bw)) bw rotateR (BitVecValue x bw) i = BitVecValue ((rotateR x i) `mod` 2^(bwSize bw)) bw popCount (BitVecValue x _) = popCount x #if MIN_VERSION_base(4,7,0) instance TL.KnownNat bw => FiniteBits (Value (BitVecType bw)) where finiteBitSize (BitVecValue _ bw) = fromInteger $ bwSize bw #endif instance TL.KnownNat bw => Real (Value (BitVecType bw)) where toRational (BitVecValue x _) = toRational x instance TL.KnownNat bw => Integral (Value (BitVecType bw)) where quot (BitVecValue x bw) (BitVecValue y _) = BitVecValue (quot x y) bw rem (BitVecValue x bw) (BitVecValue y _) = BitVecValue (rem x y) bw div (BitVecValue x bw) (BitVecValue y _) = BitVecValue (div x y) bw mod (BitVecValue x bw) (BitVecValue y _) = BitVecValue (mod x y) bw quotRem (BitVecValue x bw) (BitVecValue y _) = (BitVecValue q bw,BitVecValue r bw) where (q,r) = quotRem x y divMod (BitVecValue x bw) (BitVecValue y _) = (BitVecValue d bw,BitVecValue m bw) where (d,m) = divMod x y toInteger (BitVecValue x _) = x instance GetType NumRepr where getType NumInt = IntRepr getType NumReal = RealRepr instance Show (BitWidth bw) where showsPrec p bw = showsPrec p (bwSize bw) bwAdd :: BitWidth bw1 -> BitWidth bw2 -> BitWidth (bw1 TL.+ bw2) bwAdd (BitWidth w1) (BitWidth w2) = BitWidth (w1+w2) datatypeEq :: (IsDatatype dt1,IsDatatype dt2) => Datatype dt1 -> Datatype dt2 -> Maybe (dt1 :~: dt2) datatypeEq (d1 :: Datatype dt1) (d2 :: Datatype dt2) = do Refl <- eqT :: Maybe (dt1 :~: dt2) if d1==d2 then return Refl else Nothing datatypeCompare :: (IsDatatype dt1,IsDatatype dt2) => Datatype dt1 -> Datatype dt2 -> GOrdering dt1 dt2 datatypeCompare (d1 :: Datatype dt1) (d2 :: Datatype dt2) = case eqT of Just (Refl :: dt1 :~: dt2) -> case compare d1 d2 of EQ -> GEQ LT -> GLT GT -> GGT Nothing -> case compare (typeRep (Proxy::Proxy dt1)) (typeRep (Proxy::Proxy dt2)) of LT -> GLT GT -> GGT
null
https://raw.githubusercontent.com/hgoes/smtlib2/c35747f2a5a9ec88dc7b1db41a5aab6e98c0458d/Language/SMTLib2/Internals/Type.hs
haskell
It is only used in promoted form, for a concrete representation see 'Repr'. | Get the data type from a value | How many polymorphic parameters does this datatype have | The name of the datatype. Must be unique. | Get all of the constructors of this datatype | Get the name of a constructor | Test if a value is constructed using a specific constructor | Get all the fields of a constructor | Construct a value using a constructor | Deconstruct a value into a constructor and a list of arguments | Get the name of a field | Get the type of a field | Extract a field value from a value ^ Already registered datatypes ^ The type containing parameters ^ The concrete type without parameters ^ Action to execute when a parameter is assigned | Values that can be used as constants in expressions. For aesthetic reasons, it's recommended to use the functions 'bool', 'int', 'real', 'bitvec' or 'array'. | A representation of the SMT Bool type. Holds the values 'Language.SMTLib2.true' or 'Language.SMTLib2.Internals.false'. Constants can be created using 'Language.SMTLib2.cbool'. | A representation of the SMT Int type. Holds the unbounded positive and negative integers. Constants can be created using 'Language.SMTLib2.cint'. Holds positive and negative reals x/y where x and y are integers. Constants can be created using 'Language.SMTLib2.creal'. | A typed representation of the SMT BitVec type. Holds bitvectors (a vector of booleans) of a certain bitwidth. Constants can be created using 'Language.SMTLib2.cbv'. ^ The width of the bitvector | A representation of the SMT Array type. Has a list of index types and an element type. | A representation of a user-defined datatype without parameters. | A representation of a user-defined datatype with parameters. | Determine the number of elements a type contains. 'Nothing' means the type has infinite elements. | Get the smallest bitvector value that is bigger than the given one. Also known as the successor. | Get the largest bitvector value that is smaller than the given one. Also known as the predecessor. | Get the minimal value for a bitvector. ^ Signed bitvector? | Get the maximal value for a bitvector. ^ Signed bitvector?
module Language.SMTLib2.Internals.Type where import Language.SMTLib2.Internals.Type.Nat import Language.SMTLib2.Internals.Type.List (List(..)) import qualified Language.SMTLib2.Internals.Type.List as List import Data.Proxy import Data.Typeable import Numeric import Data.List (genericLength,genericReplicate) import Data.GADT.Compare import Data.GADT.Show import Data.Functor.Identity import Data.Graph import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.Bits import qualified GHC.TypeLits as TL import Unsafe.Coerce | Describes the kind of all SMT types . data Type = BoolType | IntType | RealType | BitVecType TL.Nat | ArrayType [Type] Type | forall a. DataType a [Type] | ParameterType Nat deriving Typeable type family Lifted (tps :: [Type]) (idx :: [Type]) :: [Type] where Lifted '[] idx = '[] Lifted (tp ': tps) idx = (ArrayType idx tp) ': Lifted tps idx class Unlift (tps::[Type]) (idx::[Type]) where unliftType :: List Repr (Lifted tps idx) -> (List Repr tps,List Repr idx) unliftTypeWith :: List Repr (Lifted tps idx) -> List Repr tps -> List Repr idx instance Unlift '[tp] idx where unliftType (ArrayRepr idx tp ::: Nil) = (tp ::: Nil,idx) unliftTypeWith (ArrayRepr idx tp ::: Nil) (tp' ::: Nil) = idx instance Unlift (t2 ': ts) idx => Unlift (t1 ': t2 ': ts) idx where unliftType (ArrayRepr idx tp ::: ts) = let (tps,idx') = unliftType ts in (tp ::: tps,idx) unliftTypeWith (ArrayRepr idx tp ::: ts) (tp' ::: tps) = idx type family Fst (a :: (p,q)) :: p where Fst '(x,y) = x type family Snd (a :: (p,q)) :: q where Snd '(x,y) = y class (Typeable dt,Ord (Datatype dt),GCompare (Constr dt),GCompare (Field dt)) => IsDatatype (dt :: [Type] -> (Type -> *) -> *) where type Parameters dt :: Nat type Signature dt :: [[Type]] data Datatype dt :: * data Constr dt (csig :: [Type]) data Field dt (tp :: Type) datatypeGet :: (GetType e,List.Length par ~ Parameters dt) => dt par e -> (Datatype dt,List Repr par) parameters :: Datatype dt -> Natural (Parameters dt) datatypeName :: Datatype dt -> String constructors :: Datatype dt -> List (Constr dt) (Signature dt) constrName :: Constr dt csig -> String test :: dt par e -> Constr dt csig -> Bool fields :: Constr dt csig -> List (Field dt) csig construct :: (List.Length par ~ Parameters dt) => List Repr par -> Constr dt csig -> List e (Instantiated csig par) -> dt par e deconstruct :: GetType e => dt par e -> ConApp dt par e fieldName :: Field dt tp -> String fieldType :: Field dt tp -> Repr tp fieldGet :: dt par e -> Field dt tp -> e (CType tp par) type family CType (tp :: Type) (par :: [Type]) :: Type where CType 'BoolType par = 'BoolType CType 'IntType par = 'IntType CType 'RealType par = 'RealType CType ('BitVecType w) par = 'BitVecType w CType ('ArrayType idx el) par = 'ArrayType (Instantiated idx par) (CType el par) CType ('DataType dt arg) par = 'DataType dt (Instantiated arg par) CType ('ParameterType n) par = List.Index par n type family Instantiated (sig :: [Type]) (par :: [Type]) :: [Type] where Instantiated '[] par = '[] Instantiated (tp ': tps) par = (CType tp par) ': Instantiated tps par data ConApp dt par e = forall csig. (List.Length par ~ Parameters dt) => ConApp { parameters' :: List Repr par , constructor :: Constr dt csig , arguments :: List e (Instantiated csig par) } data FieldType tp where FieldType : : Repr tp - > FieldType ( ' Left tp ) ParType : : Natural n - > FieldType ( ' Right n ) data AnyDatatype = forall dt. IsDatatype dt => AnyDatatype (Datatype dt) data AnyConstr = forall dt csig. IsDatatype dt => AnyConstr (Datatype dt) (Constr dt csig) data AnyField = forall dt csig tp. IsDatatype dt => AnyField (Datatype dt) (Field dt tp) data TypeRegistry dt con field = TypeRegistry { allDatatypes :: Map dt AnyDatatype , revDatatypes :: Map AnyDatatype dt , allConstructors :: Map con AnyConstr , revConstructors :: Map AnyConstr con , allFields :: Map field AnyField , revFields :: Map AnyField field } emptyTypeRegistry :: TypeRegistry dt con field emptyTypeRegistry = TypeRegistry Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty dependencies :: IsDatatype dt -> Datatype dt -> (Set String,[[AnyDatatype]]) dependencies known p = (known',dts) where dts = fmap (\scc -> fmap (\(dt,_,_) -> dt) $ flattenSCC scc) sccs sccs = stronglyConnCompR edges (known',edges) = dependencies' known p dependencies' :: IsDatatype dt => Set String -> Datatype dt -> (Set String,[(AnyDatatype,String,[String])]) dependencies' known dt | Set.member (datatypeName dt) known = (known,[]) | otherwise = let name = datatypeName dt known1 = Set.insert name known deps = dependenciesCons (constructors dt) (known2,edges) = foldl (\(cknown,cedges) (AnyDatatype dt) -> dependencies' cknown dt ) (known1,[]) deps in (known2,(AnyDatatype dt,name,[ datatypeName dt | AnyDatatype dt <- deps ]):edges) dependenciesCons :: IsDatatype dt => List (Constr dt) tps -> [AnyDatatype] dependenciesCons Nil = [] dependenciesCons (con ::: cons) = let dep1 = dependenciesFields (fields con) dep2 = dependenciesCons cons in dep1++dep2 dependenciesFields :: IsDatatype dt => List (Field dt) tps -> [AnyDatatype] dependenciesFields Nil = [] dependenciesFields (f ::: fs) = let dep1 = dependenciesTp (fieldType f) dep2 = dependenciesFields fs in dep1++dep2 dependenciesTp :: Repr tp -> [AnyDatatype] dependenciesTp (ArrayRepr idx el) = let dep1 = dependenciesTps idx dep2 = dependenciesTp el in dep1++dep2 dependenciesTp (DataRepr dt par) = let dep1 = [AnyDatatype dt] dep2 = dependenciesTps par in dep1++dep2 dependenciesTp _ = [] dependenciesTps :: List Repr tps -> [AnyDatatype] dependenciesTps Nil = [] dependenciesTps (tp ::: tps) = let dep1 = dependenciesTp tp dep2 = dependenciesTps tps in dep1++dep2 signature :: IsDatatype dt => Datatype dt -> List (List Repr) (Signature dt) signature dt = runIdentity $ List.mapM (\con -> List.mapM (\f -> return (fieldType f) ) (fields con) ) (constructors dt) constrSig :: IsDatatype dt => Constr dt sig -> List Repr sig constrSig constr = runIdentity $ List.mapM (\f -> return (fieldType f)) (fields constr) instantiate :: List Repr sig -> List Repr par -> (List Repr (Instantiated sig par), List.Length sig :~: List.Length (Instantiated sig par)) instantiate Nil _ = (Nil,Refl) instantiate (tp ::: tps) par = case instantiate tps par of (ntps,Refl) -> (ctype tp par ::: ntps,Refl) ctype :: Repr tp -> List Repr par -> Repr (CType tp par) ctype BoolRepr _ = BoolRepr ctype IntRepr _ = IntRepr ctype RealRepr _ = RealRepr ctype (BitVecRepr w) _ = BitVecRepr w ctype (ArrayRepr idx el) par = case instantiate idx par of (nidx,Refl) -> ArrayRepr nidx (ctype el par) ctype (DataRepr dt args) par = case instantiate args par of (nargs,Refl) -> DataRepr dt nargs ctype (ParameterRepr p) par = List.index par p determines :: IsDatatype dt => Datatype dt -> Constr dt sig -> Bool determines dt con = allDetermined (fromInteger $ naturalToInteger $ parameters dt) $ determines' (fields con) Set.empty where determines' :: IsDatatype dt => List (Field dt) tps -> Set Integer -> Set Integer determines' Nil mp = mp determines' (f ::: fs) mp = determines' fs (containedParameter (fieldType f) mp) allDetermined sz mp = Set.size mp == sz containedParameter :: Repr tp -> Set Integer -> Set Integer containedParameter (ArrayRepr idx el) det = runIdentity $ List.foldM (\det tp -> return $ containedParameter tp det ) (containedParameter el det) idx containedParameter (DataRepr i args) det = runIdentity $ List.foldM (\det tp -> return $ containedParameter tp det ) det args containedParameter (ParameterRepr p) det = Set.insert (naturalToInteger p) det containedParameter _ det = det -> a -> Maybe a typeInference BoolRepr BoolRepr _ x = Just x typeInference IntRepr IntRepr _ x = Just x typeInference RealRepr RealRepr _ x = Just x typeInference (BitVecRepr w1) (BitVecRepr w2) _ x = do Refl <- geq w1 w2 return x typeInference (ParameterRepr n) tp f x = f n tp x typeInference (ArrayRepr idx el) (ArrayRepr idx' el') f x = do x1 <- typeInferences idx idx' f x typeInference el el' f x1 typeInference (DataRepr (_::Datatype dt) par) (DataRepr (_::Datatype dt') par') f x = do Refl <- eqT :: Maybe (dt :~: dt') typeInferences par par' f x typeInference _ _ _ _ = Nothing typeInferences :: List Repr atps -> List Repr ctps -> (forall n ntp. Natural n -> Repr ntp -> a -> Maybe a) -> a -> Maybe a typeInferences Nil Nil _ x = Just x typeInferences (atp ::: atps) (ctp ::: ctps) f x = do x1 <- typeInference atp ctp f x typeInferences atps ctps f x1 typeInferences _ _ _ _ = Nothing partialInstantiation :: Repr tp -> (forall n a. Natural n -> (forall ntp. Repr ntp -> a) -> Maybe a) -> (forall rtp. Repr rtp -> a) -> a partialInstantiation BoolRepr _ res = res BoolRepr partialInstantiation IntRepr _ res = res IntRepr partialInstantiation RealRepr _ res = res RealRepr partialInstantiation (BitVecRepr w) _ res = res (BitVecRepr w) partialInstantiation (ArrayRepr idx el) f res = partialInstantiations idx f $ \nidx -> partialInstantiation el f $ \nel -> res $ ArrayRepr nidx nel partialInstantiation (DataRepr dt par) f res = partialInstantiations par f $ \npar -> res $ DataRepr dt npar partialInstantiation (ParameterRepr n) f res = case f n res of Just r -> r Nothing -> res (ParameterRepr n) partialInstantiations :: List Repr tp -> (forall n a. Natural n -> (forall ntp. Repr ntp -> a) -> Maybe a) -> (forall rtp. List.Length tp ~ List.Length rtp => List Repr rtp -> a) -> a partialInstantiations Nil _ res = res Nil partialInstantiations (tp ::: tps) f res = partialInstantiation tp f $ \ntp -> partialInstantiations tps f $ \ntps -> res (ntp ::: ntps) registerType :: (Monad m,IsDatatype tp,Ord dt,Ord con,Ord field) => dt -> (forall sig. Constr tp sig -> m con) -> (forall sig tp'. Field tp tp' -> m field) -> Datatype tp -> TypeRegistry dt con field -> m (TypeRegistry dt con field) registerType i f g dt reg = List.foldM (\reg con -> do c <- f con let reg' = reg { allConstructors = Map.insert c (AnyConstr dt con) (allConstructors reg) } List.foldM (\reg field -> do fi <- g field return $ reg { allFields = Map.insert fi (AnyField dt field) (allFields reg) } ) reg' (fields con) ) reg1 (constructors dt) where reg1 = reg { allDatatypes = Map.insert i (AnyDatatype dt) (allDatatypes reg) , revDatatypes = Map.insert (AnyDatatype dt) i (revDatatypes reg) } registerTypeName :: IsDatatype dt => Datatype dt -> TypeRegistry String String String -> TypeRegistry String String String registerTypeName dt reg = runIdentity (registerType (datatypeName dt) (return . constrName) (return . fieldName) dt reg) instance Eq AnyDatatype where (==) (AnyDatatype x) (AnyDatatype y) = datatypeName x == datatypeName y instance Eq AnyConstr where (==) (AnyConstr _ c1) (AnyConstr _ c2) = constrName c1 == constrName c2 instance Eq AnyField where (==) (AnyField _ f1) (AnyField _ f2) = fieldName f1 == fieldName f2 instance Ord AnyDatatype where compare (AnyDatatype x) (AnyDatatype y) = compare (datatypeName x) (datatypeName y) instance Ord AnyConstr where compare (AnyConstr _ c1) (AnyConstr _ c2) = compare (constrName c1) (constrName c2) instance Ord AnyField where compare (AnyField _ f1) (AnyField _ f2) = compare (fieldName f1) (fieldName f2) data DynamicDatatype (par :: Nat) (sig :: [[Type]]) = DynDatatype { dynDatatypeParameters :: Natural par , dynDatatypeSig :: List (DynamicConstructor sig) sig , dynDatatypeName :: String } deriving (Eq,Ord) data DynamicConstructor (sig :: [[Type]]) (csig :: [Type]) where DynConstructor :: Natural idx -> String -> List (DynamicField sig) (List.Index sig idx) -> DynamicConstructor sig (List.Index sig idx) data DynamicField (sig :: [[Type]]) (tp :: Type) where DynField :: Natural idx -> Natural fidx -> String -> Repr (List.Index (List.Index sig idx) fidx) -> DynamicField sig (List.Index (List.Index sig idx) fidx) data DynamicValue (plen :: Nat) (sig :: [[Type]]) (par :: [Type]) e where DynValue :: DynamicDatatype (List.Length par) sig -> List Repr par -> DynamicConstructor sig csig -> List e (Instantiated csig par) -> DynamicValue (List.Length par) sig par e instance (Typeable l,Typeable sig) => IsDatatype (DynamicValue l sig) where type Parameters (DynamicValue l sig) = l type Signature (DynamicValue l sig) = sig newtype Datatype (DynamicValue l sig) = DynDatatypeInfo { dynDatatypeInfo :: DynamicDatatype l sig } deriving (Eq,Ord) data Constr (DynamicValue l sig) csig = DynConstr (DynamicDatatype l sig) (DynamicConstructor sig csig) newtype Field (DynamicValue l sig) tp = DynField' (DynamicField sig tp) parameters = dynDatatypeParameters . dynDatatypeInfo datatypeGet (DynValue dt par _ _) = (DynDatatypeInfo dt,par) datatypeName = dynDatatypeName . dynDatatypeInfo constructors (DynDatatypeInfo dt) = runIdentity $ List.mapM (\con -> return (DynConstr dt con)) (dynDatatypeSig dt) constrName (DynConstr _ (DynConstructor _ n _)) = n test (DynValue _ _ (DynConstructor n _ _) _) (DynConstr _ (DynConstructor m _ _)) = case geq n m of Just Refl -> True Nothing -> False fields (DynConstr _ (DynConstructor _ _ fs)) = runIdentity $ List.mapM (\f -> return (DynField' f)) fs construct par (DynConstr dt con) args = DynValue dt par con args deconstruct (DynValue dt par con args) = ConApp par (DynConstr dt con) args fieldName (DynField' (DynField _ _ n _)) = n fieldType (DynField' (DynField _ _ _ tp)) = tp fieldGet (DynValue dt par con@(DynConstructor cidx _ fs) args) (DynField' (DynField cidx' fidx _ _)) = case geq cidx cidx' of Just Refl -> index par fs args fidx where index :: List Repr par -> List (DynamicField sig) csig -> List e (Instantiated csig par) -> Natural n -> e (CType (List.Index csig n) par) index _ (_ ::: _) (tp ::: _) Zero = tp index par (_ ::: sig) (_ ::: tps) (Succ n) = index par sig tps n instance Show (Datatype (DynamicValue l sig)) where showsPrec p (DynDatatypeInfo dt) = showString (dynDatatypeName dt) instance GEq (DynamicConstructor sig) where geq (DynConstructor i1 _ _) (DynConstructor i2 _ _) = do Refl <- geq i1 i2 return Refl instance GCompare (DynamicConstructor sig) where gcompare (DynConstructor i1 _ _) (DynConstructor i2 _ _) = case gcompare i1 i2 of GEQ -> GEQ GLT -> GLT GGT -> GGT instance GEq (Constr (DynamicValue l sig)) where geq (DynConstr _ (DynConstructor n _ _)) (DynConstr _ (DynConstructor m _ _)) = do Refl <- geq n m return Refl instance GCompare (Constr (DynamicValue l sig)) where gcompare (DynConstr _ (DynConstructor n _ _)) (DynConstr _ (DynConstructor m _ _)) = case gcompare n m of GEQ -> GEQ GLT -> GLT GGT -> GGT instance GEq (Field (DynamicValue l sig)) where geq (DynField' (DynField cidx1 fidx1 _ _)) (DynField' (DynField cidx2 fidx2 _ _)) = do Refl <- geq cidx1 cidx2 Refl <- geq fidx1 fidx2 return Refl instance GCompare (Field (DynamicValue l sig)) where gcompare (DynField' (DynField cidx1 fidx1 _ _)) (DynField' (DynField cidx2 fidx2 _ _)) = case gcompare cidx1 cidx2 of GEQ -> case gcompare fidx1 fidx2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT newtype BitWidth (bw :: TL.Nat) = BitWidth { bwSize :: Integer } getBw :: Integer -> (forall bw. TL.KnownNat bw => BitWidth bw -> a) -> a getBw w f = case TL.someNatVal w of Just (TL.SomeNat (_::Proxy bw)) -> f (BitWidth w::BitWidth bw) data Value (a :: Type) where BoolValue :: Bool -> Value BoolType IntValue :: Integer -> Value IntType RealValue :: Rational -> Value RealType BitVecValue :: Integer -> BitWidth bw -> Value (BitVecType bw) DataValue :: (IsDatatype dt,List.Length par ~ Parameters dt) => dt par Value -> Value (DataType dt par) #if __GLASGOW_HASKELL__ >= 800 pattern ConstrValue :: () => (List.Length par ~ Parameters dt,a ~ DataType dt par,IsDatatype dt) #else pattern ConstrValue :: (List.Length par ~ Parameters dt,a ~ DataType dt par,IsDatatype dt) => () #endif => List Repr par -> Constr dt csig -> List Value (Instantiated csig par) -> Value a pattern ConstrValue par con args <- DataValue (deconstruct -> ConApp par con args) where ConstrValue par con args = DataValue (construct par con args) data AnyValue = forall (t :: Type). AnyValue (Value t) | A concrete representation of an SMT type . data Repr (t :: Type) where BoolRepr :: Repr BoolType IntRepr :: Repr IntType RealRepr :: Repr RealType BitVecRepr :: BitWidth bw -> Repr (BitVecType bw) ArrayRepr :: List Repr idx -> Repr val -> Repr (ArrayType idx val) DataRepr :: (IsDatatype dt,List.Length par ~ Parameters dt) => Datatype dt -> List Repr par -> Repr (DataType dt par) ParameterRepr :: Natural p -> Repr (ParameterType p) data NumRepr (t :: Type) where NumInt :: NumRepr IntType NumReal :: NumRepr RealType data FunRepr (sig :: ([Type],Type)) where FunRepr :: List Repr arg -> Repr tp -> FunRepr '(arg,tp) class GetType v where getType :: v tp -> Repr tp class GetFunType fun where getFunType :: fun '(arg,res) -> (List Repr arg,Repr res) bw :: TL.KnownNat bw => Proxy bw -> BitWidth bw bw = BitWidth . TL.natVal instance Eq (BitWidth bw) where (==) (BitWidth _) (BitWidth _) = True bool :: Repr BoolType bool = BoolRepr int :: Repr IntType int = IntRepr | A representation of the SMT Real type . real :: Repr RealType real = RealRepr -> Repr (BitVecType bw) bitvec = BitVecRepr Stores one value of the element type for each combination of the index types . Constants can be created using ' Language . SMTLib2.constArray ' . array :: List Repr idx -> Repr el -> Repr (ArrayType idx el) array = ArrayRepr dt :: (IsDatatype dt,Parameters dt ~ 'Z) => Datatype dt -> Repr (DataType dt '[]) dt dt = DataRepr dt List.Nil dt' :: (IsDatatype dt,List.Length par ~ Parameters dt) => Datatype dt -> List Repr par -> Repr (DataType dt par) dt' = DataRepr instance GEq BitWidth where geq (BitWidth bw1) (BitWidth bw2) | bw1==bw2 = Just $ unsafeCoerce Refl | otherwise = Nothing instance GCompare BitWidth where gcompare (BitWidth bw1) (BitWidth bw2) = case compare bw1 bw2 of EQ -> unsafeCoerce GEQ LT -> GLT GT -> GGT instance GetType Repr where getType = id instance GetType Value where getType = valueType instance GEq Value where geq (BoolValue v1) (BoolValue v2) = if v1==v2 then Just Refl else Nothing geq (IntValue v1) (IntValue v2) = if v1==v2 then Just Refl else Nothing geq (RealValue v1) (RealValue v2) = if v1==v2 then Just Refl else Nothing geq (BitVecValue v1 bw1) (BitVecValue v2 bw2) = do Refl <- geq bw1 bw2 if v1==v2 then return Refl else Nothing geq (DataValue (v1::dt1 par1 Value)) (DataValue (v2::dt2 par2 Value)) = do Refl <- eqT :: Maybe (dt1 :~: dt2) case deconstruct v1 of ConApp p1 c1 arg1 -> case deconstruct v2 of ConApp p2 c2 arg2 -> do Refl <- geq p1 p2 Refl <- geq c1 c2 Refl <- geq arg1 arg2 return Refl geq _ _ = Nothing instance Eq (Value t) where (==) = defaultEq instance GCompare Value where gcompare (BoolValue v1) (BoolValue v2) = case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT gcompare (BoolValue _) _ = GLT gcompare _ (BoolValue _) = GGT gcompare (IntValue v1) (IntValue v2) = case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT gcompare (IntValue _) _ = GLT gcompare _ (IntValue _) = GGT gcompare (RealValue v1) (RealValue v2) = case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT gcompare (RealValue _) _ = GLT gcompare _ (RealValue _) = GGT gcompare (BitVecValue v1 bw1) (BitVecValue v2 bw2) = case gcompare bw1 bw2 of GEQ -> case compare v1 v2 of EQ -> GEQ LT -> GLT GT -> GGT GLT -> GLT GGT -> GGT gcompare (BitVecValue _ _) _ = GLT gcompare _ (BitVecValue _ _) = GGT gcompare (DataValue (v1::dt1 par1 Value)) (DataValue (v2::dt2 par2 Value)) = case eqT :: Maybe (dt1 :~: dt2) of Just Refl -> case deconstruct v1 of ConApp p1 c1 arg1 -> case deconstruct v2 of ConApp p2 c2 arg2 -> case gcompare p1 p2 of GEQ -> case gcompare c1 c2 of GEQ -> case gcompare arg1 arg2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT Nothing -> case compare (typeRep (Proxy::Proxy dt1)) (typeRep (Proxy::Proxy dt2)) of LT -> GLT GT -> GGT instance Ord (Value t) where compare = defaultCompare instance GEq Repr where geq BoolRepr BoolRepr = Just Refl geq IntRepr IntRepr = Just Refl geq RealRepr RealRepr = Just Refl geq (BitVecRepr bw1) (BitVecRepr bw2) = do Refl <- geq bw1 bw2 return Refl geq (ArrayRepr idx1 val1) (ArrayRepr idx2 val2) = do Refl <- geq idx1 idx2 Refl <- geq val1 val2 return Refl geq (DataRepr (_::Datatype dt1) p1) (DataRepr (_::Datatype dt2) p2) = do Refl <- eqT :: Maybe (Datatype dt1 :~: Datatype dt2) Refl <- geq p1 p2 return Refl geq _ _ = Nothing instance Eq (Repr tp) where (==) _ _ = True instance GEq NumRepr where geq NumInt NumInt = Just Refl geq NumReal NumReal = Just Refl geq _ _ = Nothing instance GEq FunRepr where geq (FunRepr a1 r1) (FunRepr a2 r2) = do Refl <- geq a1 a2 Refl <- geq r1 r2 return Refl instance GCompare Repr where gcompare BoolRepr BoolRepr = GEQ gcompare BoolRepr _ = GLT gcompare _ BoolRepr = GGT gcompare IntRepr IntRepr = GEQ gcompare IntRepr _ = GLT gcompare _ IntRepr = GGT gcompare RealRepr RealRepr = GEQ gcompare RealRepr _ = GLT gcompare _ RealRepr = GGT gcompare (BitVecRepr bw1) (BitVecRepr bw2) = case gcompare bw1 bw2 of GEQ -> GEQ GLT -> GLT GGT -> GGT gcompare (BitVecRepr _) _ = GLT gcompare _ (BitVecRepr _) = GGT gcompare (ArrayRepr idx1 val1) (ArrayRepr idx2 val2) = case gcompare idx1 idx2 of GEQ -> case gcompare val1 val2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT gcompare (ArrayRepr _ _) _ = GLT gcompare _ (ArrayRepr _ _) = GGT gcompare (DataRepr (dt1 :: Datatype dt1) p1 ) (DataRepr (dt2 :: Datatype dt2) p2) = case eqT of Just (Refl :: Datatype dt1 :~: Datatype dt2) -> case gcompare p1 p2 of GEQ -> GEQ GLT -> GLT GGT -> GGT Nothing -> case compare (datatypeName dt1) (datatypeName dt2) of LT -> GLT GT -> GGT instance Ord (Repr tp) where compare _ _ = EQ instance GCompare NumRepr where gcompare NumInt NumInt = GEQ gcompare NumInt _ = GLT gcompare _ NumInt = GGT gcompare NumReal NumReal = GEQ instance GCompare FunRepr where gcompare (FunRepr a1 r1) (FunRepr a2 r2) = case gcompare a1 a2 of GEQ -> case gcompare r1 r2 of GEQ -> GEQ GLT -> GLT GGT -> GGT GLT -> GLT GGT -> GGT instance Show (Value tp) where showsPrec p (BoolValue b) = showsPrec p b showsPrec p (IntValue i) = showsPrec p i showsPrec p (RealValue i) = showsPrec p i showsPrec p (BitVecValue v n) = showBitVec p v (bwSize n) showsPrec p (DataValue val) = case deconstruct val of ConApp par con args -> showParen (p>10) $ showString "ConstrValue " . showString (constrName con). showChar ' ' . showsPrec 11 args showBitVec :: Int -> Integer -> Integer -> ShowS showBitVec p v bw | bw `mod` 4 == 0 = let str = showHex rv "" exp_len = bw `div` 4 len = genericLength str in showString "#x" . showString (genericReplicate (exp_len-len) '0') . showString str | otherwise = let str = showIntAtBase 2 (\x -> case x of 0 -> '0' 1 -> '1' ) rv "" len = genericLength str in showString "#b" . showString (genericReplicate (bw-len) '0') . showString str where rv = v `mod` 2^bw instance GShow Value where gshowsPrec = showsPrec instance Show (Repr t) where showsPrec _ BoolRepr = showString "bool" showsPrec _ IntRepr = showString "int" showsPrec _ RealRepr = showString "real" showsPrec p (BitVecRepr n) = showParen (p>10) $ showString "bitvec " . showsPrec 11 (bwSize n) showsPrec p (ArrayRepr idx el) = showParen (p>10) $ showString "array " . showsPrec 11 idx . showChar ' ' . showsPrec 11 el showsPrec p (DataRepr dt par) = showParen (p>10) $ showString "dt " . showString (datatypeName dt) instance GShow Repr where gshowsPrec = showsPrec deriving instance Show (NumRepr t) instance GShow NumRepr where gshowsPrec = showsPrec valueType :: Value tp -> Repr tp valueType (BoolValue _) = BoolRepr valueType (IntValue _) = IntRepr valueType (RealValue _) = RealRepr valueType (BitVecValue _ bw) = BitVecRepr bw valueType (DataValue v) = let (dt,par) = datatypeGet v in DataRepr dt par liftType :: List Repr tps -> List Repr idx -> List Repr (Lifted tps idx) liftType Nil idx = Nil liftType (x ::: xs) idx = (ArrayRepr idx x) ::: (liftType xs idx) numRepr :: NumRepr tp -> Repr tp numRepr NumInt = IntRepr numRepr NumReal = RealRepr asNumRepr :: Repr tp -> Maybe (NumRepr tp) asNumRepr IntRepr = Just NumInt asNumRepr RealRepr = Just NumReal asNumRepr _ = Nothing getTypes :: GetType e => List e tps -> List Repr tps getTypes Nil = Nil getTypes (x ::: xs) = getType x ::: getTypes xs typeSize :: Maybe (List Repr par) -> Repr tp -> Maybe Integer typeSize _ BoolRepr = Just 2 typeSize _ IntRepr = Nothing typeSize _ RealRepr = Nothing typeSize _ (BitVecRepr bw) = Just $ 2^(bwSize bw) typeSize par (ArrayRepr idx el) = do idxSz <- List.toList (typeSize par) idx elSz <- typeSize par el return $ product (elSz:idxSz) typeSize _ (DataRepr dt par) = do conSz <- List.toList (constrSize dt par) (constructors dt) return $ sum conSz where constrSize :: IsDatatype dt => Datatype dt -> List Repr par -> Constr dt sig -> Maybe Integer constrSize dt par con = do fieldSz <- List.toList (fieldSize dt par) (fields con) return $ product fieldSz fieldSize :: IsDatatype dt => Datatype dt -> List Repr par -> Field dt tp -> Maybe Integer fieldSize dt par field = typeSize (Just par) (fieldType field) typeSize (Just par) (ParameterRepr p) = typeSize Nothing (List.index par p) typeFiniteDomain :: Repr tp -> Maybe [Value tp] typeFiniteDomain BoolRepr = Just [BoolValue False,BoolValue True] typeFiniteDomain (BitVecRepr bw) = Just [ BitVecValue n bw | n <- [0..2^(bwSize bw)-1] ] typeFiniteDomain _ = Nothing instance Enum (Value BoolType) where succ (BoolValue x) = BoolValue (succ x) pred (BoolValue x) = BoolValue (pred x) toEnum i = BoolValue (toEnum i) fromEnum (BoolValue x) = fromEnum x enumFrom (BoolValue x) = fmap BoolValue (enumFrom x) enumFromThen (BoolValue x) (BoolValue y) = fmap BoolValue (enumFromThen x y) enumFromTo (BoolValue x) (BoolValue y) = fmap BoolValue (enumFromTo x y) enumFromThenTo (BoolValue x) (BoolValue y) (BoolValue z) = fmap BoolValue (enumFromThenTo x y z) instance Bounded (Value BoolType) where minBound = BoolValue False maxBound = BoolValue True instance Num (Value IntType) where (+) (IntValue x) (IntValue y) = IntValue (x+y) (-) (IntValue x) (IntValue y) = IntValue (x-y) (*) (IntValue x) (IntValue y) = IntValue (x*y) negate (IntValue x) = IntValue (negate x) abs (IntValue x) = IntValue (abs x) signum (IntValue x) = IntValue (signum x) fromInteger = IntValue instance Enum (Value IntType) where succ (IntValue x) = IntValue (succ x) pred (IntValue x) = IntValue (pred x) toEnum i = IntValue (toEnum i) fromEnum (IntValue x) = fromEnum x enumFrom (IntValue x) = fmap IntValue (enumFrom x) enumFromThen (IntValue x) (IntValue y) = fmap IntValue (enumFromThen x y) enumFromTo (IntValue x) (IntValue y) = fmap IntValue (enumFromTo x y) enumFromThenTo (IntValue x) (IntValue y) (IntValue z) = fmap IntValue (enumFromThenTo x y z) instance Real (Value IntType) where toRational (IntValue x) = toRational x instance Integral (Value IntType) where quot (IntValue x) (IntValue y) = IntValue $ quot x y rem (IntValue x) (IntValue y) = IntValue $ rem x y div (IntValue x) (IntValue y) = IntValue $ div x y mod (IntValue x) (IntValue y) = IntValue $ mod x y quotRem (IntValue x) (IntValue y) = (IntValue q,IntValue r) where (q,r) = quotRem x y divMod (IntValue x) (IntValue y) = (IntValue d,IntValue m) where (d,m) = divMod x y toInteger (IntValue x) = x instance Num (Value RealType) where (+) (RealValue x) (RealValue y) = RealValue (x+y) (-) (RealValue x) (RealValue y) = RealValue (x-y) (*) (RealValue x) (RealValue y) = RealValue (x*y) negate (RealValue x) = RealValue (negate x) abs (RealValue x) = RealValue (abs x) signum (RealValue x) = RealValue (signum x) fromInteger = RealValue . fromInteger instance Real (Value RealType) where toRational (RealValue x) = x instance Fractional (Value RealType) where (/) (RealValue x) (RealValue y) = RealValue (x/y) recip (RealValue x) = RealValue (recip x) fromRational = RealValue instance RealFrac (Value RealType) where properFraction (RealValue x) = let (p,q) = properFraction x in (p,RealValue q) truncate (RealValue x) = truncate x round (RealValue x) = round x ceiling (RealValue x) = ceiling x floor (RealValue x) = floor x withBW :: TL.KnownNat bw => (Proxy bw -> res (BitVecType bw)) -> res (BitVecType bw) withBW f = f Proxy bvAdd :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvAdd (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvAdd: Bitvector size mismatch" | otherwise = BitVecValue ((x+y) `mod` (2^(bwSize bw1))) bw1 bvSub :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvSub (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvSub: Bitvector size mismatch" | otherwise = BitVecValue ((x-y) `mod` (2^(bwSize bw1))) bw1 bvMul :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvMul (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvMul: Bitvector size mismatch" | otherwise = BitVecValue ((x*y) `mod` (2^(bwSize bw1))) bw1 bvDiv :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvDiv (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvDiv: Bitvector size mismatch" | otherwise = BitVecValue (x `div` y) bw1 bvMod :: Value (BitVecType bw) -> Value (BitVecType bw) -> Value (BitVecType bw) bvMod (BitVecValue x bw1) (BitVecValue y bw2) | bw1 /= bw2 = error "bvMod: Bitvector size mismatch" | otherwise = BitVecValue (x `mod` y) bw1 bvNegate :: Value (BitVecType bw) -> Value (BitVecType bw) bvNegate (BitVecValue x bw) = BitVecValue (if x==0 then 0 else 2^(bwSize bw)-x) bw bvSignum :: Value (BitVecType bw) -> Value (BitVecType bw) bvSignum (BitVecValue x bw) = BitVecValue (if x==0 then 0 else 1) bw instance TL.KnownNat bw => Num (Value (BitVecType bw)) where (+) = bvAdd (-) = bvSub (*) = bvMul negate = bvNegate abs = id signum = bvSignum fromInteger x = withBW $ \pr -> let bw = TL.natVal pr in BitVecValue (x `mod` (2^bw)) (BitWidth bw) bvSucc :: Value (BitVecType bw) -> Value (BitVecType bw) bvSucc (BitVecValue i bw) | i < 2^(bwSize bw) - 1 = BitVecValue (i+1) bw | otherwise = error "bvSucc: tried to take `succ' of maxBound" bvPred :: Value (BitVecType bw) -> Value (BitVecType bw) bvPred (BitVecValue i bw) | i > 0 = BitVecValue (i-1) bw | otherwise = error "bvPred: tried to take `pred' of minBound" instance TL.KnownNat bw => Enum (Value (BitVecType bw)) where succ = bvSucc pred = bvPred toEnum i = withBW $ \bw -> let i' = toInteger i bw' = TL.natVal bw in if i >= 0 && i < 2^bw' then BitVecValue i' (BitWidth bw') else error "Prelude.toEnum: argument out of range for bitvector value." fromEnum (BitVecValue i _) = fromInteger i enumFrom (BitVecValue x bw) = [ BitVecValue i bw | i <- [x..2^(bwSize bw)-1] ] enumFromThen (BitVecValue x bw) (BitVecValue y _) = [ BitVecValue i bw | i <- [x,y..2^(bwSize bw)-1] ] enumFromTo (BitVecValue x bw) (BitVecValue y _) = [ BitVecValue i bw | i <- [x..y] ] enumFromThenTo (BitVecValue x bw) (BitVecValue y _) (BitVecValue z _) = [ BitVecValue i bw | i <- [x,y..z] ] instance TL.KnownNat bw => Bounded (Value (BitVecType bw)) where minBound = withBW $ \w -> BitVecValue 0 (bw w) maxBound = withBW $ \bw -> let bw' = TL.natVal bw in BitVecValue (2^bw'-1) (BitWidth bw') If unsigned , the value is 0 , otherwise 2^(bw-1 ) . -> Repr (BitVecType bw) -> Value (BitVecType bw) bvMinValue False (BitVecRepr bw) = BitVecValue 0 bw bvMinValue True (BitVecRepr bw) = BitVecValue (2^(bwSize bw-1)) bw If unsigned , the value is 2^(bw-1)-1 , otherwise 2^bw-1 . -> Repr (BitVecType bw) -> Value (BitVecType bw) bvMaxValue False (BitVecRepr bw) = BitVecValue (2^(bwSize bw)-1) bw bvMaxValue True (BitVecRepr bw) = BitVecValue (2^(bwSize bw-1)-1) bw instance TL.KnownNat bw => Bits (Value (BitVecType bw)) where (.&.) (BitVecValue x bw) (BitVecValue y _) = BitVecValue (x .&. y) bw (.|.) (BitVecValue x bw) (BitVecValue y _) = BitVecValue (x .|. y) bw xor (BitVecValue x bw) (BitVecValue y _) = BitVecValue ((x .|. max) `xor` (y .|. max)) bw where max = bit $ fromInteger $ bwSize bw complement (BitVecValue x bw) = BitVecValue (2^(bwSize bw)-1-x) bw shift (BitVecValue x bw) i = BitVecValue ((x `shift` i) `mod` (2^(bwSize bw))) bw rotate (BitVecValue x bw) i = BitVecValue ((x `rotate` i) `mod` (2^(bwSize bw))) bw zeroBits = withBW $ \w -> BitVecValue 0 (bw w) bit n = withBW $ \bw -> let bw' = TL.natVal bw in if toInteger n < bw' && n >= 0 then BitVecValue (bit n) (BitWidth bw') else BitVecValue 0 (BitWidth bw') setBit (BitVecValue x bw) i = if toInteger i < bwSize bw && i >= 0 then BitVecValue (setBit x i) bw else BitVecValue x bw clearBit (BitVecValue x bw) i = if toInteger i < bwSize bw && i >= 0 then BitVecValue (clearBit x i) bw else BitVecValue x bw complementBit (BitVecValue x bw) i = if toInteger i < bwSize bw && i >= 0 then BitVecValue (complementBit x i) bw else BitVecValue x bw testBit (BitVecValue x _) i = testBit x i #if MIN_VERSION_base(4,7,0) bitSizeMaybe (BitVecValue _ bw) = Just (fromInteger $ bwSize bw) #endif bitSize (BitVecValue _ bw) = fromInteger $ bwSize bw isSigned _ = False shiftL (BitVecValue x bw) i = BitVecValue ((shiftL x i) `mod` 2^(bwSize bw)) bw shiftR (BitVecValue x bw) i = BitVecValue ((shiftR x i) `mod` 2^(bwSize bw)) bw rotateL (BitVecValue x bw) i = BitVecValue ((rotateL x i) `mod` 2^(bwSize bw)) bw rotateR (BitVecValue x bw) i = BitVecValue ((rotateR x i) `mod` 2^(bwSize bw)) bw popCount (BitVecValue x _) = popCount x #if MIN_VERSION_base(4,7,0) instance TL.KnownNat bw => FiniteBits (Value (BitVecType bw)) where finiteBitSize (BitVecValue _ bw) = fromInteger $ bwSize bw #endif instance TL.KnownNat bw => Real (Value (BitVecType bw)) where toRational (BitVecValue x _) = toRational x instance TL.KnownNat bw => Integral (Value (BitVecType bw)) where quot (BitVecValue x bw) (BitVecValue y _) = BitVecValue (quot x y) bw rem (BitVecValue x bw) (BitVecValue y _) = BitVecValue (rem x y) bw div (BitVecValue x bw) (BitVecValue y _) = BitVecValue (div x y) bw mod (BitVecValue x bw) (BitVecValue y _) = BitVecValue (mod x y) bw quotRem (BitVecValue x bw) (BitVecValue y _) = (BitVecValue q bw,BitVecValue r bw) where (q,r) = quotRem x y divMod (BitVecValue x bw) (BitVecValue y _) = (BitVecValue d bw,BitVecValue m bw) where (d,m) = divMod x y toInteger (BitVecValue x _) = x instance GetType NumRepr where getType NumInt = IntRepr getType NumReal = RealRepr instance Show (BitWidth bw) where showsPrec p bw = showsPrec p (bwSize bw) bwAdd :: BitWidth bw1 -> BitWidth bw2 -> BitWidth (bw1 TL.+ bw2) bwAdd (BitWidth w1) (BitWidth w2) = BitWidth (w1+w2) datatypeEq :: (IsDatatype dt1,IsDatatype dt2) => Datatype dt1 -> Datatype dt2 -> Maybe (dt1 :~: dt2) datatypeEq (d1 :: Datatype dt1) (d2 :: Datatype dt2) = do Refl <- eqT :: Maybe (dt1 :~: dt2) if d1==d2 then return Refl else Nothing datatypeCompare :: (IsDatatype dt1,IsDatatype dt2) => Datatype dt1 -> Datatype dt2 -> GOrdering dt1 dt2 datatypeCompare (d1 :: Datatype dt1) (d2 :: Datatype dt2) = case eqT of Just (Refl :: dt1 :~: dt2) -> case compare d1 d2 of EQ -> GEQ LT -> GLT GT -> GGT Nothing -> case compare (typeRep (Proxy::Proxy dt1)) (typeRep (Proxy::Proxy dt2)) of LT -> GLT GT -> GGT
6542d5576947d92a01a48bb35106723f09d24bc32d2fb731dbdedaa2fa1c3dd4
fission-codes/fission
Types.hs
module Fission.Web.Server.AWS.Zone.Types (ZoneID (..)) where import Data.Swagger as Swagger import Database.Persist.Sql import Servant.API import Fission.Prelude import Fission.Error.NotFound.Types | Type safety wrapper for a Route53 zone ID newtype ZoneID = ZoneID { getZoneID :: Text } deriving (Eq, Show) instance Arbitrary ZoneID where arbitrary = ZoneID <$> arbitrary instance Display ZoneID where textDisplay = getZoneID instance Display (NotFound ZoneID) where display _ = "AWS.ZoneID not found" instance PersistField ZoneID where toPersistValue (ZoneID txt) = PersistText txt fromPersistValue = \case PersistText txt -> Right $ ZoneID txt bad -> Left $ "ZoneID must be PersistText, but got: " <> toUrlPiece bad instance PersistFieldSql ZoneID where sqlType _ = SqlString instance Swagger.ToSchema ZoneID where declareNamedSchema _ = mempty |> type_ ?~ SwaggerString |> NamedSchema (Just "AWS.ZoneId") |> pure instance FromJSON ZoneID where parseJSON = withText "AWS.ZoneID" \txt -> ZoneID <$> parseJSON (String txt)
null
https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-web-server/library/Fission/Web/Server/AWS/Zone/Types.hs
haskell
module Fission.Web.Server.AWS.Zone.Types (ZoneID (..)) where import Data.Swagger as Swagger import Database.Persist.Sql import Servant.API import Fission.Prelude import Fission.Error.NotFound.Types | Type safety wrapper for a Route53 zone ID newtype ZoneID = ZoneID { getZoneID :: Text } deriving (Eq, Show) instance Arbitrary ZoneID where arbitrary = ZoneID <$> arbitrary instance Display ZoneID where textDisplay = getZoneID instance Display (NotFound ZoneID) where display _ = "AWS.ZoneID not found" instance PersistField ZoneID where toPersistValue (ZoneID txt) = PersistText txt fromPersistValue = \case PersistText txt -> Right $ ZoneID txt bad -> Left $ "ZoneID must be PersistText, but got: " <> toUrlPiece bad instance PersistFieldSql ZoneID where sqlType _ = SqlString instance Swagger.ToSchema ZoneID where declareNamedSchema _ = mempty |> type_ ?~ SwaggerString |> NamedSchema (Just "AWS.ZoneId") |> pure instance FromJSON ZoneID where parseJSON = withText "AWS.ZoneID" \txt -> ZoneID <$> parseJSON (String txt)
c0d668fd3cd67b7bc6eec3727cc04a999bbc7111a3903488e14408f4d6fdc389
Clojure2D/clojure2d-examples
material.clj
(ns rt4.the-next-week.ch07b.material (:require [rt4.common :as common] [rt4.the-next-week.ch07b.ray :as ray] [rt4.the-next-week.ch07b.texture :as texture] [fastmath.vector :as v] [fastmath.core :as m] [fastmath.random :as r]) (:import [fastmath.vector Vec3])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defprotocol MaterialProto (scatter [material ray-in rec]) (emitted [material u v p])) (defrecord MaterialData [attenuation scattered]) (def ^:private black (v/vec3 0.0 0.0 0.0)) (defrecord Lambertian [albedo] MaterialProto (emitted [_ _ _ _] black) (scatter [_ ray-in rec] (let [scatter-direction (v/add (:normal rec) (common/random-unit-vector)) attenuation (texture/value albedo (:u rec) (:v rec) (:p rec))] (if (v/is-near-zero? scatter-direction) (->MaterialData attenuation (ray/ray (:p rec) (:normal rec) (:time ray-in))) (->MaterialData attenuation (ray/ray (:p rec) scatter-direction (:time ray-in))))))) (defn lambertian [albedo] (if (instance? Vec3 albedo) (->Lambertian (texture/solid-color albedo)) (->Lambertian albedo))) (defrecord Metal [albedo ^double fuzz] MaterialProto (emitted [_ _ _ _] black) (scatter [_ ray-in rec] (let [reflected (v/add (common/reflect (v/normalize (:direction ray-in)) (:normal rec)) (v/mult (common/random-in-unit-sphere) fuzz))] (when (pos? (v/dot reflected (:normal rec))) (->MaterialData albedo (ray/ray (:p rec) reflected (:time ray-in))))))) (defn metal [albedo ^double fuzz] (->Metal albedo (min fuzz 1.0))) (def one (v/vec3 1.0 1.0 1.0)) (defn- reflectance ^double [^double cosine ^double ref-idx] (let [r0 (m/sq (/ (- 1.0 ref-idx) (inc ref-idx)))] (+ r0 (* (- 1.0 r0) (m/pow (- 1.0 cosine) 5.0))))) (defrecord Dielectric [^double ir] MaterialProto (emitted [_ _ _ _] black) (scatter [_ ray-in rec] (let [refraction-ratio (if (:front-face? rec) (/ ir) ir) unit-direction (v/normalize (:direction ray-in)) cos-theta (min (v/dot (v/sub unit-direction) (:normal rec)) 1.0) sin-theta (m/sqrt (- 1.0 (* cos-theta cos-theta))) cannot-refract? (pos? (dec (* refraction-ratio sin-theta))) direction (if (or cannot-refract? (> (reflectance cos-theta refraction-ratio) (r/drand))) (common/reflect unit-direction (:normal rec)) (common/refract unit-direction (:normal rec) refraction-ratio))] (->MaterialData one (ray/ray (:p rec) direction (:time ray-in)))))) (defn dielectric [ir] (->Dielectric ir)) ;; (defrecord DiffuseLight [emit] MaterialProto (scatter [_ _ _] nil) (emitted [_ u v p] (texture/value emit u v p))) (defn diffuse-light [texture-or-color] (let [emit (if (instance? Vec3 texture-or-color) (texture/solid-color texture-or-color) texture-or-color)] (->DiffuseLight emit)))
null
https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch07b/material.clj
clojure
(ns rt4.the-next-week.ch07b.material (:require [rt4.common :as common] [rt4.the-next-week.ch07b.ray :as ray] [rt4.the-next-week.ch07b.texture :as texture] [fastmath.vector :as v] [fastmath.core :as m] [fastmath.random :as r]) (:import [fastmath.vector Vec3])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defprotocol MaterialProto (scatter [material ray-in rec]) (emitted [material u v p])) (defrecord MaterialData [attenuation scattered]) (def ^:private black (v/vec3 0.0 0.0 0.0)) (defrecord Lambertian [albedo] MaterialProto (emitted [_ _ _ _] black) (scatter [_ ray-in rec] (let [scatter-direction (v/add (:normal rec) (common/random-unit-vector)) attenuation (texture/value albedo (:u rec) (:v rec) (:p rec))] (if (v/is-near-zero? scatter-direction) (->MaterialData attenuation (ray/ray (:p rec) (:normal rec) (:time ray-in))) (->MaterialData attenuation (ray/ray (:p rec) scatter-direction (:time ray-in))))))) (defn lambertian [albedo] (if (instance? Vec3 albedo) (->Lambertian (texture/solid-color albedo)) (->Lambertian albedo))) (defrecord Metal [albedo ^double fuzz] MaterialProto (emitted [_ _ _ _] black) (scatter [_ ray-in rec] (let [reflected (v/add (common/reflect (v/normalize (:direction ray-in)) (:normal rec)) (v/mult (common/random-in-unit-sphere) fuzz))] (when (pos? (v/dot reflected (:normal rec))) (->MaterialData albedo (ray/ray (:p rec) reflected (:time ray-in))))))) (defn metal [albedo ^double fuzz] (->Metal albedo (min fuzz 1.0))) (def one (v/vec3 1.0 1.0 1.0)) (defn- reflectance ^double [^double cosine ^double ref-idx] (let [r0 (m/sq (/ (- 1.0 ref-idx) (inc ref-idx)))] (+ r0 (* (- 1.0 r0) (m/pow (- 1.0 cosine) 5.0))))) (defrecord Dielectric [^double ir] MaterialProto (emitted [_ _ _ _] black) (scatter [_ ray-in rec] (let [refraction-ratio (if (:front-face? rec) (/ ir) ir) unit-direction (v/normalize (:direction ray-in)) cos-theta (min (v/dot (v/sub unit-direction) (:normal rec)) 1.0) sin-theta (m/sqrt (- 1.0 (* cos-theta cos-theta))) cannot-refract? (pos? (dec (* refraction-ratio sin-theta))) direction (if (or cannot-refract? (> (reflectance cos-theta refraction-ratio) (r/drand))) (common/reflect unit-direction (:normal rec)) (common/refract unit-direction (:normal rec) refraction-ratio))] (->MaterialData one (ray/ray (:p rec) direction (:time ray-in)))))) (defn dielectric [ir] (->Dielectric ir)) (defrecord DiffuseLight [emit] MaterialProto (scatter [_ _ _] nil) (emitted [_ u v p] (texture/value emit u v p))) (defn diffuse-light [texture-or-color] (let [emit (if (instance? Vec3 texture-or-color) (texture/solid-color texture-or-color) texture-or-color)] (->DiffuseLight emit)))
b91f60df4c5b1b4c90e0f3e81a96b450cc75de5d06ee5a534198825e312544f1
orionsbelt-battlegrounds/obb-rules
rotate.cljc
(ns obb-rules.actions.rotate (:require [obb-rules.game :as game] [obb-rules.simplifier :as simplify] [obb-rules.result :as result] [obb-rules.board :as board] [obb-rules.element :as element])) (defn- rotate-restrictions "Checks for invalid scenarios" [player board element] (cond (nil? element) "EmptyCoordinate" (not (game/player-turn? board player)) "StateMismatch" (element/frozen? element) "FrozenElement" (simplify/not-name= player (element/element-player element)) "NotOwnedElement")) (defn- process-rotate "Processes the rotate" [board coord elem new-dir] (let [new-elem (element/element-direction elem new-dir) new-board (board/swap-element board coord new-elem)] (result/action-success new-board 1))) (defn build-rotate "Builds a rotate action on a board" [[coord new-direction]] (fn rotator [board player] (let [element (board/get-element board coord)] (if-let [error (rotate-restrictions player board element)] (result/action-failed error) (process-rotate board coord element new-direction)))))
null
https://raw.githubusercontent.com/orionsbelt-battlegrounds/obb-rules/97fad6506eb81142f74f4722aca58b80d618bf45/src/obb_rules/actions/rotate.cljc
clojure
(ns obb-rules.actions.rotate (:require [obb-rules.game :as game] [obb-rules.simplifier :as simplify] [obb-rules.result :as result] [obb-rules.board :as board] [obb-rules.element :as element])) (defn- rotate-restrictions "Checks for invalid scenarios" [player board element] (cond (nil? element) "EmptyCoordinate" (not (game/player-turn? board player)) "StateMismatch" (element/frozen? element) "FrozenElement" (simplify/not-name= player (element/element-player element)) "NotOwnedElement")) (defn- process-rotate "Processes the rotate" [board coord elem new-dir] (let [new-elem (element/element-direction elem new-dir) new-board (board/swap-element board coord new-elem)] (result/action-success new-board 1))) (defn build-rotate "Builds a rotate action on a board" [[coord new-direction]] (fn rotator [board player] (let [element (board/get-element board coord)] (if-let [error (rotate-restrictions player board element)] (result/action-failed error) (process-rotate board coord element new-direction)))))
34dc69c7fa4b5631a9cc6d5913eba9b4fc50f16b28596750388592537ae6b01b
karimarttila/clojure
prop.clj
(ns simpleserver.util.prop (:require [clojure.string :as str] [clojure.java.io :as io] [clojure.tools.logging :as log] [environ.core :as environ] [clojure.pprint :as pp])) (def config "Global configuration as atom (which is read from property file)." (atom nil)) (defn reset-config! "Use to reset configuration (e.g. if you change properties and call create-test in REPL)." [] (reset! simpleserver.util.prop/config nil)) (def property-filename "Property file, must be initialized." (atom nil)) (defn -check-file "Checks if `file` exists." [file] (.isFile (io/file file))) (defn set-property-file "Initializes property file with `filename`." [filename] (reset! property-filename filename)) (defn -load-property-filename "Loads the property file name from environmental variable `SIMPLESERVER_CONFIG_FILE`." [] (log/debug (str "ENTER -load-property-filename")) (log/trace (str "Current directory: " (-> (java.io.File. ".") .getAbsolutePath))) (let [from-env (environ/env :simpleserver-config-file) configfile-name (if (nil? from-env) "resources/simpleserver.properties" from-env)] (if (-check-file configfile-name) (do (log/info (str "Using poperty file: " configfile-name)) (set-property-file configfile-name)) (do (log/info (str "Property file: " configfile-name " not found, exiting.")) (throw (ex-info (str "Property file: " configfile-name " not found") {})))))) (defn -load-props "Loads properties from property file and returns a map of properties." {:doc/format :markdown} [filename] (let [io (java.io.FileInputStream. filename) prop (java.util.Properties.)] (.load prop io) (into {} prop))) (defn -load-configuration "Loads the configuration (property file) to [[config]] atom." [] (if (nil? @property-filename) (-load-property-filename)) (reset! config (-load-props @property-filename))) (defn get-int-value "Gets int value of `key`." [key] (if (nil? @config) (-load-configuration)) (Integer/parseInt (get @config key))) (defn get-double-value "Gets double value of `key`." [key] (if (nil? @config) (-load-configuration)) (Double/parseDouble (get @config key))) (defn get-str-value "Gets string value of `key`." [key] (if (nil? @config) (-load-configuration)) (get @config key)) (defn get-vec-value "Gets vector (list) value of `key`." [key] (if (nil? @config) (-load-configuration)) (str/split (get @config key) #","))
null
https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/clj-ring-cljs-reagent-demo/simple-server/src/simpleserver/util/prop.clj
clojure
(ns simpleserver.util.prop (:require [clojure.string :as str] [clojure.java.io :as io] [clojure.tools.logging :as log] [environ.core :as environ] [clojure.pprint :as pp])) (def config "Global configuration as atom (which is read from property file)." (atom nil)) (defn reset-config! "Use to reset configuration (e.g. if you change properties and call create-test in REPL)." [] (reset! simpleserver.util.prop/config nil)) (def property-filename "Property file, must be initialized." (atom nil)) (defn -check-file "Checks if `file` exists." [file] (.isFile (io/file file))) (defn set-property-file "Initializes property file with `filename`." [filename] (reset! property-filename filename)) (defn -load-property-filename "Loads the property file name from environmental variable `SIMPLESERVER_CONFIG_FILE`." [] (log/debug (str "ENTER -load-property-filename")) (log/trace (str "Current directory: " (-> (java.io.File. ".") .getAbsolutePath))) (let [from-env (environ/env :simpleserver-config-file) configfile-name (if (nil? from-env) "resources/simpleserver.properties" from-env)] (if (-check-file configfile-name) (do (log/info (str "Using poperty file: " configfile-name)) (set-property-file configfile-name)) (do (log/info (str "Property file: " configfile-name " not found, exiting.")) (throw (ex-info (str "Property file: " configfile-name " not found") {})))))) (defn -load-props "Loads properties from property file and returns a map of properties." {:doc/format :markdown} [filename] (let [io (java.io.FileInputStream. filename) prop (java.util.Properties.)] (.load prop io) (into {} prop))) (defn -load-configuration "Loads the configuration (property file) to [[config]] atom." [] (if (nil? @property-filename) (-load-property-filename)) (reset! config (-load-props @property-filename))) (defn get-int-value "Gets int value of `key`." [key] (if (nil? @config) (-load-configuration)) (Integer/parseInt (get @config key))) (defn get-double-value "Gets double value of `key`." [key] (if (nil? @config) (-load-configuration)) (Double/parseDouble (get @config key))) (defn get-str-value "Gets string value of `key`." [key] (if (nil? @config) (-load-configuration)) (get @config key)) (defn get-vec-value "Gets vector (list) value of `key`." [key] (if (nil? @config) (-load-configuration)) (str/split (get @config key) #","))
fe82a506eb2361f59b442ad5dce7b634c42214d3dac19d15c5644ad4cea95911
motemen/jusk
JSDate.hs
{- JSDate.hs Dateオブジェクト /~oz-07ams/prog/ecma262r3/15-9_Date_Objects.html -} module JSDate where import Control.Monad import System.Time import DataTypes import Internal -- Date.prototype prototypeObject :: Value prototypeObject = nullObject { objPropMap = nativeFuncPropMap [ ("constructor", constructor, 7), ("toString", toStringMethod, 0), ("valueOf", valueOf, 1), ("getTime", getTime, 1) ] } -- Date() function :: NativeCode function _ [] = do time <- liftIO $ getClockTime return $ String $ show time -- new Date() constructor :: NativeCode constructor _ [] = do time <- liftIO $ getClockTime return $ nullObject { objClass = "Date", objValue = toValue $ toMillisecs time } -- Date.prototype.toString toStringMethod :: NativeCode toStringMethod this _ = do this <- readRef this klass <- classOf this if klass == "Date" then liftIO $ liftM (String . calendarTimeToString) (millisecsToCT $ getMillisecs this) else throw "TypeError" "Date.prototype.toString called on incompatible" -- Date.prototype.valueOf valueOf :: NativeCode valueOf this _ = do this <- readRef this klass <- classOf this if klass == "Date" then return $ toValue $ getMillisecs this else throw "TypeError" $ "Date.prototype.toString called on incompatible " ++ klass -- Date.prototype.getTime getTime :: NativeCode getTime this _ = do this <- readRef this klass <- classOf this if klass == "Date" then return $ toValue $ getMillisecs this else throw "TypeError" $ "Date.prototype.getTime called on incompatible " ++ klass getMillisecs (Object { objValue = Number (Integer millisecs) }) = millisecs toMillisecs ct = let TOD secs picosecs = ct in secs * 1000 + picosecs `div` 1000000000 millisecsToCT millisecs = do let (secs, milli) = millisecs `divMod` 1000 nanosecs = milli * 1000000000 toCalendarTime =<< return (TOD secs nanosecs)
null
https://raw.githubusercontent.com/motemen/jusk/4975915b8550aa09c452fb89dcad7bfcb1037c39/src/JSDate.hs
haskell
JSDate.hs Dateオブジェクト /~oz-07ams/prog/ecma262r3/15-9_Date_Objects.html Date.prototype Date() new Date() Date.prototype.toString Date.prototype.valueOf Date.prototype.getTime
module JSDate where import Control.Monad import System.Time import DataTypes import Internal prototypeObject :: Value prototypeObject = nullObject { objPropMap = nativeFuncPropMap [ ("constructor", constructor, 7), ("toString", toStringMethod, 0), ("valueOf", valueOf, 1), ("getTime", getTime, 1) ] } function :: NativeCode function _ [] = do time <- liftIO $ getClockTime return $ String $ show time constructor :: NativeCode constructor _ [] = do time <- liftIO $ getClockTime return $ nullObject { objClass = "Date", objValue = toValue $ toMillisecs time } toStringMethod :: NativeCode toStringMethod this _ = do this <- readRef this klass <- classOf this if klass == "Date" then liftIO $ liftM (String . calendarTimeToString) (millisecsToCT $ getMillisecs this) else throw "TypeError" "Date.prototype.toString called on incompatible" valueOf :: NativeCode valueOf this _ = do this <- readRef this klass <- classOf this if klass == "Date" then return $ toValue $ getMillisecs this else throw "TypeError" $ "Date.prototype.toString called on incompatible " ++ klass getTime :: NativeCode getTime this _ = do this <- readRef this klass <- classOf this if klass == "Date" then return $ toValue $ getMillisecs this else throw "TypeError" $ "Date.prototype.getTime called on incompatible " ++ klass getMillisecs (Object { objValue = Number (Integer millisecs) }) = millisecs toMillisecs ct = let TOD secs picosecs = ct in secs * 1000 + picosecs `div` 1000000000 millisecsToCT millisecs = do let (secs, milli) = millisecs `divMod` 1000 nanosecs = milli * 1000000000 toCalendarTime =<< return (TOD secs nanosecs)
c79d6adaebbf015dff662cec8b79e61da8bf5f34fc5ba64f96ebc1e3d07245ae
LaurentMazare/ocaml-wasmtime
linker.ml
open! Base module W = Wasmtime.Wrappers let linking1_wat = {| (module (import "linking2" "double" (func $double (param i32) (result i32))) (import "linking2" "log" (func $log (param i32 i32))) (import "linking2" "memory" (memory 1)) (import "linking2" "memory_offset" (global $offset i32)) (func (export "run") ;; Call into the other module to double our number, and we could print it ;; here but for now we just drop it i32.const 2 call $double drop ;; Our `data` segment initialized our imported memory, so let's print the ;; string there now. global.get $offset i32.const 14 call $log ) (data (global.get $offset) "Hello, world!\n") ) |} let linking2_wat = {| (module (type $fd_write_ty (func (param i32 i32 i32 i32) (result i32))) (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (type $fd_write_ty))) (func (export "double") (param i32) (result i32) local.get 0 i32.const 2 i32.mul ) (func (export "log") (param i32 i32) ;; store the pointer in the first iovec field i32.const 4 local.get 0 i32.store ;; store the length in the first iovec field i32.const 4 local.get 1 i32.store offset=4 ;; call the `fd_write` import i32.const 1 ;; stdout fd i32.const 4 ;; iovs start i32.const 1 ;; number of iovs i32.const 0 ;; where to write nwritten bytes call $fd_write drop ) (memory (export "memory") 2) (global (export "memory_offset") i32 (i32.const 65536)) ) |} let%expect_test _ = let engine = W.Engine.create () in let store = W.Store.create engine in let wasi_instance = W.Wasi_instance.create store `wasi_snapshot_preview ~inherit_argv:true ~inherit_env:true ~inherit_stdin:true ~inherit_stderr:true ~inherit_stdout:true in let linker = W.Wasmtime.Linker.create store in let instantiate ~wat = let wasm = W.Wasmtime.wat_to_wasm ~wat in W.Wasmtime.new_module engine ~wasm |> W.Wasmtime.Linker.instantiate linker in W.Wasmtime.Linker.define_wasi linker wasi_instance; let name2 = W.Byte_vec.of_string "linking2" in let instance2 = instantiate ~wat:(W.Byte_vec.of_string linking2_wat) in W.Wasmtime.Linker.define_instance linker ~name:name2 instance2; let instance1 = instantiate ~wat:(W.Byte_vec.of_string linking1_wat) in let run = match W.Instance.exports instance1 with | [ run ] -> W.Extern.as_func run | l -> Printf.failwithf "expected a single export, got %d" (List.length l) () in W.Wasmtime.func_call0 run []; [%expect {| Hello, world! |}]
null
https://raw.githubusercontent.com/LaurentMazare/ocaml-wasmtime/49d3e35676d79d6573600fa4e9ff7460106341e3/tests/linker.ml
ocaml
open! Base module W = Wasmtime.Wrappers let linking1_wat = {| (module (import "linking2" "double" (func $double (param i32) (result i32))) (import "linking2" "log" (func $log (param i32 i32))) (import "linking2" "memory" (memory 1)) (import "linking2" "memory_offset" (global $offset i32)) (func (export "run") ;; Call into the other module to double our number, and we could print it ;; here but for now we just drop it i32.const 2 call $double drop ;; Our `data` segment initialized our imported memory, so let's print the ;; string there now. global.get $offset i32.const 14 call $log ) (data (global.get $offset) "Hello, world!\n") ) |} let linking2_wat = {| (module (type $fd_write_ty (func (param i32 i32 i32 i32) (result i32))) (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (type $fd_write_ty))) (func (export "double") (param i32) (result i32) local.get 0 i32.const 2 i32.mul ) (func (export "log") (param i32 i32) ;; store the pointer in the first iovec field i32.const 4 local.get 0 i32.store ;; store the length in the first iovec field i32.const 4 local.get 1 i32.store offset=4 ;; call the `fd_write` import i32.const 1 ;; stdout fd i32.const 4 ;; iovs start i32.const 1 ;; number of iovs i32.const 0 ;; where to write nwritten bytes call $fd_write drop ) (memory (export "memory") 2) (global (export "memory_offset") i32 (i32.const 65536)) ) |} let%expect_test _ = let engine = W.Engine.create () in let store = W.Store.create engine in let wasi_instance = W.Wasi_instance.create store `wasi_snapshot_preview ~inherit_argv:true ~inherit_env:true ~inherit_stdin:true ~inherit_stderr:true ~inherit_stdout:true in let linker = W.Wasmtime.Linker.create store in let instantiate ~wat = let wasm = W.Wasmtime.wat_to_wasm ~wat in W.Wasmtime.new_module engine ~wasm |> W.Wasmtime.Linker.instantiate linker in W.Wasmtime.Linker.define_wasi linker wasi_instance; let name2 = W.Byte_vec.of_string "linking2" in let instance2 = instantiate ~wat:(W.Byte_vec.of_string linking2_wat) in W.Wasmtime.Linker.define_instance linker ~name:name2 instance2; let instance1 = instantiate ~wat:(W.Byte_vec.of_string linking1_wat) in let run = match W.Instance.exports instance1 with | [ run ] -> W.Extern.as_func run | l -> Printf.failwithf "expected a single export, got %d" (List.length l) () in W.Wasmtime.func_call0 run []; [%expect {| Hello, world! |}]
d7f724352cf9bfcdcfdffa769aa4c8b81f754d9289d3d39ff77a5d2ddebb30d0
ghcjs/ghcjs-dom
SVGZoomAndPan.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.SVGZoomAndPan (pattern SVG_ZOOMANDPAN_UNKNOWN, pattern SVG_ZOOMANDPAN_DISABLE, pattern SVG_ZOOMANDPAN_MAGNIFY, js_setZoomAndPan, setZoomAndPan, js_getZoomAndPan, getZoomAndPan, SVGZoomAndPan(..), gTypeSVGZoomAndPan, IsSVGZoomAndPan, toSVGZoomAndPan) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums pattern SVG_ZOOMANDPAN_UNKNOWN = 0 pattern SVG_ZOOMANDPAN_DISABLE = 1 pattern SVG_ZOOMANDPAN_MAGNIFY = 2 foreign import javascript unsafe "$1[\"zoomAndPan\"] = $2;" js_setZoomAndPan :: SVGZoomAndPan -> Word -> IO () | < -US/docs/Web/API/SVGZoomAndPan.zoomAndPan Mozilla SVGZoomAndPan.zoomAndPan documentation > setZoomAndPan :: (MonadIO m, IsSVGZoomAndPan self) => self -> Word -> m () setZoomAndPan self val = liftIO (js_setZoomAndPan (toSVGZoomAndPan self) val) foreign import javascript unsafe "$1[\"zoomAndPan\"]" js_getZoomAndPan :: SVGZoomAndPan -> IO Word | < -US/docs/Web/API/SVGZoomAndPan.zoomAndPan Mozilla SVGZoomAndPan.zoomAndPan documentation > getZoomAndPan :: (MonadIO m, IsSVGZoomAndPan self) => self -> m Word getZoomAndPan self = liftIO (js_getZoomAndPan (toSVGZoomAndPan self))
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGZoomAndPan.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.SVGZoomAndPan (pattern SVG_ZOOMANDPAN_UNKNOWN, pattern SVG_ZOOMANDPAN_DISABLE, pattern SVG_ZOOMANDPAN_MAGNIFY, js_setZoomAndPan, setZoomAndPan, js_getZoomAndPan, getZoomAndPan, SVGZoomAndPan(..), gTypeSVGZoomAndPan, IsSVGZoomAndPan, toSVGZoomAndPan) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums pattern SVG_ZOOMANDPAN_UNKNOWN = 0 pattern SVG_ZOOMANDPAN_DISABLE = 1 pattern SVG_ZOOMANDPAN_MAGNIFY = 2 foreign import javascript unsafe "$1[\"zoomAndPan\"] = $2;" js_setZoomAndPan :: SVGZoomAndPan -> Word -> IO () | < -US/docs/Web/API/SVGZoomAndPan.zoomAndPan Mozilla SVGZoomAndPan.zoomAndPan documentation > setZoomAndPan :: (MonadIO m, IsSVGZoomAndPan self) => self -> Word -> m () setZoomAndPan self val = liftIO (js_setZoomAndPan (toSVGZoomAndPan self) val) foreign import javascript unsafe "$1[\"zoomAndPan\"]" js_getZoomAndPan :: SVGZoomAndPan -> IO Word | < -US/docs/Web/API/SVGZoomAndPan.zoomAndPan Mozilla SVGZoomAndPan.zoomAndPan documentation > getZoomAndPan :: (MonadIO m, IsSVGZoomAndPan self) => self -> m Word getZoomAndPan self = liftIO (js_getZoomAndPan (toSVGZoomAndPan self))
ca3b08720b3682e62fdcacc52a0cb5052a315ac08a5b001c37c1d8e0b12dcc0b
anmonteiro/ocaml-mongodb
header.ml
type t = { message_len : int32 ; request_id : int32 ; response_to : int32 ; op : Operation.t } let create_header body_len request_id response_to op = { message_len = Int32.of_int (body_len + (4 * 4)) ; request_id ; response_to ; op } let create_request_header body_len request_id op = { message_len = Int32.of_int (body_len + (4 * 4)) ; request_id ; response_to = 0l ; op } let to_string h = let buf = Buffer.create 64 in Buffer.add_string buf "message_len = "; Buffer.add_string buf (Int32.to_string h.message_len); Buffer.add_string buf "\n"; Buffer.add_string buf "request_id = "; Buffer.add_string buf (Int32.to_string h.request_id); Buffer.add_string buf "\n"; Buffer.add_string buf "response_to = "; Buffer.add_string buf (Int32.to_string h.response_to); Buffer.add_string buf "\n"; Buffer.add_string buf "op = "; Buffer.add_string buf (Int32.to_string (Operation.to_code h.op)); Buffer.add_string buf "\n"; Buffer.contents buf
null
https://raw.githubusercontent.com/anmonteiro/ocaml-mongodb/535ae1b003b9c8a3844b92a78d2123881f2d404b/src/header.ml
ocaml
type t = { message_len : int32 ; request_id : int32 ; response_to : int32 ; op : Operation.t } let create_header body_len request_id response_to op = { message_len = Int32.of_int (body_len + (4 * 4)) ; request_id ; response_to ; op } let create_request_header body_len request_id op = { message_len = Int32.of_int (body_len + (4 * 4)) ; request_id ; response_to = 0l ; op } let to_string h = let buf = Buffer.create 64 in Buffer.add_string buf "message_len = "; Buffer.add_string buf (Int32.to_string h.message_len); Buffer.add_string buf "\n"; Buffer.add_string buf "request_id = "; Buffer.add_string buf (Int32.to_string h.request_id); Buffer.add_string buf "\n"; Buffer.add_string buf "response_to = "; Buffer.add_string buf (Int32.to_string h.response_to); Buffer.add_string buf "\n"; Buffer.add_string buf "op = "; Buffer.add_string buf (Int32.to_string (Operation.to_code h.op)); Buffer.add_string buf "\n"; Buffer.contents buf
74b84f6ed51d2f3082f571c6393326693d56e27408e9a7687b2f9a720fe8c174
Quid2/flat
Endian.hs
{-# LANGUAGE NoMonomorphismRestriction, ExtendedDefaultRules#-} module DocTest.Flat.Endian where import qualified DocTest import Test.Tasty(TestTree,testGroup) import Flat.Endian import Numeric (showHex) tests :: IO TestTree tests = testGroup "Flat.Endian" <$> sequence [ DocTest.test "src/Data/Flat/Endian.hs:36" ["True"] (DocTest.asPrint( toBE64 0xF0F1F2F3F4F5F6F7 == if isBigEndian then 0xF0F1F2F3F4F5F6F7 else 0xF7F6F5F4F3F2F1F0 )), DocTest.test "src/Data/Flat/Endian.hs:49" ["True"] (DocTest.asPrint( toBE32 0xF0F1F2F3 == if isBigEndian then 0xF0F1F2F3 else 0xF3F2F1F0 )), DocTest.test "src/Data/Flat/Endian.hs:62" ["True"] (DocTest.asPrint( toBE16 0xF0F1 == if isBigEndian then 0xF0F1 else 0xF1F0 ))]
null
https://raw.githubusercontent.com/Quid2/flat/95e5d7488451e43062ca84d5376b3adcc465f1cd/test/DocTest/Data/Flat/Endian.hs
haskell
# LANGUAGE NoMonomorphismRestriction, ExtendedDefaultRules#
module DocTest.Flat.Endian where import qualified DocTest import Test.Tasty(TestTree,testGroup) import Flat.Endian import Numeric (showHex) tests :: IO TestTree tests = testGroup "Flat.Endian" <$> sequence [ DocTest.test "src/Data/Flat/Endian.hs:36" ["True"] (DocTest.asPrint( toBE64 0xF0F1F2F3F4F5F6F7 == if isBigEndian then 0xF0F1F2F3F4F5F6F7 else 0xF7F6F5F4F3F2F1F0 )), DocTest.test "src/Data/Flat/Endian.hs:49" ["True"] (DocTest.asPrint( toBE32 0xF0F1F2F3 == if isBigEndian then 0xF0F1F2F3 else 0xF3F2F1F0 )), DocTest.test "src/Data/Flat/Endian.hs:62" ["True"] (DocTest.asPrint( toBE16 0xF0F1 == if isBigEndian then 0xF0F1 else 0xF1F0 ))]
f12b3ab8be2054d090ca5127f814acd644c005f1785c5147a966e803faf646d5
facebook/duckling
Corpus.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.TR.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale TR Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "0" , "yok" , "hiç" , "sıfır" ] , examples (NumeralValue 1) [ "1" , "bir" , "tek" , "yek" ] , examples (NumeralValue 2) [ "2" , "iki" , "çift" ] , examples (NumeralValue 33) [ "33" , "otuzüç" , "otuz üç" , "0033" ] , examples (NumeralValue 14) [ "14" , "ondört" , "on dört" ] , examples (NumeralValue 16) [ "16" , "onaltı" , "on altı" ] , examples (NumeralValue 17) [ "17" , "onyedi" , "on yedi" ] , examples (NumeralValue 18) [ "18" , "onsekiz" , "on sekiz" ] , examples (NumeralValue 1.1) [ "1,1" , "1,10" , "01,10" , "bir virgül bir" , "bir nokta bir" ] , examples (NumeralValue 0.77) [ "0,77" , ",77" , "sıfır virgül yetmişyedi" , "sıfır virgül yetmiş yedi" ] , examples (NumeralValue 100000) [ "100.000" , "100000" , "100K" , "100k" , "100b" ] , examples (NumeralValue 3000000) [ "3M" , "3000K" , "3000000" , "3.000.000" ] , examples (NumeralValue 1200000) [ "1.200.000" , "1200000" , "1,2M" , "1200K" , ",0012G" , "1200B" ] , examples (NumeralValue (-1200000)) [ "- 1.200.000" , "-1200000" , "eksi 1.200.000" , "negatif 1200000" , "-1,2M" , "-1200K" , "-,0012G" , "-1200B" ] , examples (NumeralValue 5000) [ "5 bin" , "beş bin" ] , examples (NumeralValue 50) [ "5 deste" , "beş deste" ] , examples (NumeralValue 200000) [ "iki yüz bin" , "ikiyüzbin" ] , examples (NumeralValue 21011) [ "yirmi bir bin on bir" , "yirmibir bin onbir" ] , examples (NumeralValue 721012) [ "yedi yüz yirmibir bin on iki" , "yedi yüz yirmi bir bin on iki" , "yediyüz yirmibir bin oniki" ] , examples (NumeralValue 300341) [ "üçyüzbin üçyüz kırkbir" , "üç yüz bin üç yüz kırk bir" ] , examples (NumeralValue 40348) [ "kırkbin üçyüz kırksekiz" , "kırk bin üç yüz kırk sekiz" ] , examples (NumeralValue 31256721) [ "otuz bir milyon iki yüz elli altı bin yedi yüz yirmi bir" ] , examples (NumeralValue 107) [ "107" , "yüz yedi" ] , examples (NumeralValue 5.5) [ "beş buçuk" , "beşbuçuk" , "5 buçuk" , "5,5" ] , examples (NumeralValue 3500000) [ "3,5 milyon" , "3500000" , "üç buçuk milyon" , "üçbuçuk milyon" , "3,5M" ] , examples (NumeralValue 0.5) [ "yarım" , "0,5" ] , examples (NumeralValue 2500) [ "2,5 bin" , "2500" , "iki bin beş yüz" , "ikibin beşyüz" ] , examples (NumeralValue 2200000) [ "2,2 milyon" , "iki nokta iki milyon" , "iki virgül iki milyon" ] , examples (NumeralValue 72.5) [ "yetmişikibuçuk" , "yetmişiki buçuk" , "yetmiş iki buçuk" , "72,5" ] ]
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Numeral/TR/Corpus.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. # LANGUAGE OverloadedStrings #
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.Numeral.TR.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale TR Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "0" , "yok" , "hiç" , "sıfır" ] , examples (NumeralValue 1) [ "1" , "bir" , "tek" , "yek" ] , examples (NumeralValue 2) [ "2" , "iki" , "çift" ] , examples (NumeralValue 33) [ "33" , "otuzüç" , "otuz üç" , "0033" ] , examples (NumeralValue 14) [ "14" , "ondört" , "on dört" ] , examples (NumeralValue 16) [ "16" , "onaltı" , "on altı" ] , examples (NumeralValue 17) [ "17" , "onyedi" , "on yedi" ] , examples (NumeralValue 18) [ "18" , "onsekiz" , "on sekiz" ] , examples (NumeralValue 1.1) [ "1,1" , "1,10" , "01,10" , "bir virgül bir" , "bir nokta bir" ] , examples (NumeralValue 0.77) [ "0,77" , ",77" , "sıfır virgül yetmişyedi" , "sıfır virgül yetmiş yedi" ] , examples (NumeralValue 100000) [ "100.000" , "100000" , "100K" , "100k" , "100b" ] , examples (NumeralValue 3000000) [ "3M" , "3000K" , "3000000" , "3.000.000" ] , examples (NumeralValue 1200000) [ "1.200.000" , "1200000" , "1,2M" , "1200K" , ",0012G" , "1200B" ] , examples (NumeralValue (-1200000)) [ "- 1.200.000" , "-1200000" , "eksi 1.200.000" , "negatif 1200000" , "-1,2M" , "-1200K" , "-,0012G" , "-1200B" ] , examples (NumeralValue 5000) [ "5 bin" , "beş bin" ] , examples (NumeralValue 50) [ "5 deste" , "beş deste" ] , examples (NumeralValue 200000) [ "iki yüz bin" , "ikiyüzbin" ] , examples (NumeralValue 21011) [ "yirmi bir bin on bir" , "yirmibir bin onbir" ] , examples (NumeralValue 721012) [ "yedi yüz yirmibir bin on iki" , "yedi yüz yirmi bir bin on iki" , "yediyüz yirmibir bin oniki" ] , examples (NumeralValue 300341) [ "üçyüzbin üçyüz kırkbir" , "üç yüz bin üç yüz kırk bir" ] , examples (NumeralValue 40348) [ "kırkbin üçyüz kırksekiz" , "kırk bin üç yüz kırk sekiz" ] , examples (NumeralValue 31256721) [ "otuz bir milyon iki yüz elli altı bin yedi yüz yirmi bir" ] , examples (NumeralValue 107) [ "107" , "yüz yedi" ] , examples (NumeralValue 5.5) [ "beş buçuk" , "beşbuçuk" , "5 buçuk" , "5,5" ] , examples (NumeralValue 3500000) [ "3,5 milyon" , "3500000" , "üç buçuk milyon" , "üçbuçuk milyon" , "3,5M" ] , examples (NumeralValue 0.5) [ "yarım" , "0,5" ] , examples (NumeralValue 2500) [ "2,5 bin" , "2500" , "iki bin beş yüz" , "ikibin beşyüz" ] , examples (NumeralValue 2200000) [ "2,2 milyon" , "iki nokta iki milyon" , "iki virgül iki milyon" ] , examples (NumeralValue 72.5) [ "yetmişikibuçuk" , "yetmişiki buçuk" , "yetmiş iki buçuk" , "72,5" ] ]
fa185448f8aa9d20cda7ca3acfec7f7f7870a18f3914e2def7701ec21687db56
Herzult/vindinium-starter-haskell
Types.hs
# LANGUAGE GeneralizedNewtypeDeriving # module Vindinium.Types ( Vindinium , runVindinium , asks , Settings (..) , Key (..) , Bot , State (..) , GameId (..) , Game (..) , HeroId (..) , Hero (..) , Board (..) , Tile (..) , Pos (..) , Dir (..) ) where import Data.Text (Text) import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, asks) import Control.Monad.IO.Class (MonadIO) newtype Key = Key Text deriving (Show, Eq) data Settings = Settings { settingsKey :: Key , settingsUrl :: Text } deriving (Show, Eq) newtype Vindinium a = Vindinium { unVindinium :: ReaderT Settings IO a } deriving (Monad, MonadReader Settings, MonadIO) runVindinium :: Settings -> Vindinium a -> IO a runVindinium s = flip runReaderT s . unVindinium type Bot = State -> Vindinium Dir data State = State { stateGame :: Game , stateHero :: Hero , stateToken :: Text , stateViewUrl :: Text , statePlayUrl :: Text } deriving (Show, Eq) newtype GameId = GameId Text deriving (Show, Eq) data Game = Game { gameId :: GameId , gameTurn :: Integer , gameMaxTurns :: Integer , gameHeroes :: [Hero] , gameBoard :: Board , gameFinished :: Bool } deriving (Show, Eq) newtype HeroId = HeroId Int deriving (Show, Eq) data Hero = Hero { heroId :: HeroId , heroName :: Text , heroUserId :: Maybe Text , heroElo :: Maybe Integer , heroPos :: Pos , heroLife :: Integer , heroGold :: Integer , heroMineCount :: Integer , heroSpawnPos :: Pos , heroCrashed :: Bool } deriving (Show, Eq) data Board = Board { boardSize :: Int , boardTiles :: [Tile] } deriving (Show, Eq) data Tile = FreeTile | WoodTile | TavernTile | HeroTile HeroId | MineTile (Maybe HeroId) deriving (Show, Eq) data Pos = Pos { posX :: Int , posY :: Int } deriving (Show, Eq) data Dir = Stay | North | South | East | West deriving (Show, Eq)
null
https://raw.githubusercontent.com/Herzult/vindinium-starter-haskell/48b108f6913133794ab5bfcdc52eba6a48ed537f/src/Vindinium/Types.hs
haskell
# LANGUAGE GeneralizedNewtypeDeriving # module Vindinium.Types ( Vindinium , runVindinium , asks , Settings (..) , Key (..) , Bot , State (..) , GameId (..) , Game (..) , HeroId (..) , Hero (..) , Board (..) , Tile (..) , Pos (..) , Dir (..) ) where import Data.Text (Text) import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, asks) import Control.Monad.IO.Class (MonadIO) newtype Key = Key Text deriving (Show, Eq) data Settings = Settings { settingsKey :: Key , settingsUrl :: Text } deriving (Show, Eq) newtype Vindinium a = Vindinium { unVindinium :: ReaderT Settings IO a } deriving (Monad, MonadReader Settings, MonadIO) runVindinium :: Settings -> Vindinium a -> IO a runVindinium s = flip runReaderT s . unVindinium type Bot = State -> Vindinium Dir data State = State { stateGame :: Game , stateHero :: Hero , stateToken :: Text , stateViewUrl :: Text , statePlayUrl :: Text } deriving (Show, Eq) newtype GameId = GameId Text deriving (Show, Eq) data Game = Game { gameId :: GameId , gameTurn :: Integer , gameMaxTurns :: Integer , gameHeroes :: [Hero] , gameBoard :: Board , gameFinished :: Bool } deriving (Show, Eq) newtype HeroId = HeroId Int deriving (Show, Eq) data Hero = Hero { heroId :: HeroId , heroName :: Text , heroUserId :: Maybe Text , heroElo :: Maybe Integer , heroPos :: Pos , heroLife :: Integer , heroGold :: Integer , heroMineCount :: Integer , heroSpawnPos :: Pos , heroCrashed :: Bool } deriving (Show, Eq) data Board = Board { boardSize :: Int , boardTiles :: [Tile] } deriving (Show, Eq) data Tile = FreeTile | WoodTile | TavernTile | HeroTile HeroId | MineTile (Maybe HeroId) deriving (Show, Eq) data Pos = Pos { posX :: Int , posY :: Int } deriving (Show, Eq) data Dir = Stay | North | South | East | West deriving (Show, Eq)
be3f76a02049f0b99ba17af8ff3e88b85bf26a830585cd5104e21ba8c0b85f1f
TouK/re-cms
core.cljs
(ns re-cms.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [re-cms.handlers] [re-cms.subs] [re-cms.views :as views] [re-cms.config :as config])) (when config/debug? (println "dev mode")) (defn mount-root [elem] (reagent/render [views/app] elem)) (defn ^:export init [elem url] (re-frame/dispatch-sync [:initialize-db url]) (mount-root elem)) (defn fig-init [] (mount-root (.getElementById js/document "app")))
null
https://raw.githubusercontent.com/TouK/re-cms/98b54e79c349b5db7f8b3a6d30348c23bbe65a2e/src/cljs/re_cms/core.cljs
clojure
(ns re-cms.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [re-cms.handlers] [re-cms.subs] [re-cms.views :as views] [re-cms.config :as config])) (when config/debug? (println "dev mode")) (defn mount-root [elem] (reagent/render [views/app] elem)) (defn ^:export init [elem url] (re-frame/dispatch-sync [:initialize-db url]) (mount-root elem)) (defn fig-init [] (mount-root (.getElementById js/document "app")))
891d815952327c8739f9da55299c7ded970c2bf00c7bac5420908836cc8e8bf8
phylogeography/spread
subs.cljs
(ns shared.subs (:require [re-frame.core :refer [reg-sub]])) (reg-sub :collapsible-tabs/tabs (fn [db _] (:ui.collapsible-tabs/tabs db))) (reg-sub :collapsible-tabs/open? :<- [:collapsible-tabs/tabs] (fn [tabs [_ tab-id]] (get tabs tab-id)))
null
https://raw.githubusercontent.com/phylogeography/spread/56f3500e6d83e0ebd50041dc336ffa0697d7baf8/src/cljs/shared/subs.cljs
clojure
(ns shared.subs (:require [re-frame.core :refer [reg-sub]])) (reg-sub :collapsible-tabs/tabs (fn [db _] (:ui.collapsible-tabs/tabs db))) (reg-sub :collapsible-tabs/open? :<- [:collapsible-tabs/tabs] (fn [tabs [_ tab-id]] (get tabs tab-id)))
ccca354e43b6fd8495037e35c91334c5113b66fa63a8aa9ee2e277733a59b638
lambe-lang/nethra
t00_tests.ml
let () = Alcotest.( run "Type checker Test" [ T02_equivalence.cases ; T03_checker_basic.cases ; T04_checker_function.cases ; T05_checker_pair.cases ; T06_checker_sum.cases ; T07_checker_mu.cases ; T08_checker_hole.cases ; T09_infer_basic.cases ; T10_infer_function.cases ; T11_infer_pair.cases ; T12_infer_sum.cases ; T13_infer_mu.cases ] )
null
https://raw.githubusercontent.com/lambe-lang/nethra/42e04f741264c01de60e2a6ff890c117d01b55fa/test/nethra/lang/system/s03_typer/t00_tests.ml
ocaml
let () = Alcotest.( run "Type checker Test" [ T02_equivalence.cases ; T03_checker_basic.cases ; T04_checker_function.cases ; T05_checker_pair.cases ; T06_checker_sum.cases ; T07_checker_mu.cases ; T08_checker_hole.cases ; T09_infer_basic.cases ; T10_infer_function.cases ; T11_infer_pair.cases ; T12_infer_sum.cases ; T13_infer_mu.cases ] )
94b89d705b8558d4b01ac447f562c33c2f2a269a6e3cc99954cb1d3dbea6402f
city41/mario-review
crop_tool.cljs
(ns daisy.client.tools.crop-tool (:require [daisy.client.canvas-util :as util])) (defn- crop-frame [ctx frame x y sw sh dw dh] (let [source-img-data (.createImageData ctx sw sh) source-data (.-data source-img-data)] (.set source-data frame) (.putImageData ctx source-img-data 0 0) (let [dest-img-data (.getImageData ctx x y dw dh)] (.-data dest-img-data)))) (defn crop-frames [frames sw sh {:keys [x y w h] :as spec} cb progress-cb] (let [cropped-frames #js [] canvas (util/create-canvas sw sh) context (.getContext canvas "2d") i (atom 0)] (letfn [(step [] (if (= (alength cropped-frames) (alength frames)) (do (set! js/frames nil) ;; fixes a large memory leak (cb cropped-frames spec)) (do (.push cropped-frames (crop-frame context (aget frames @i) x y sw sh w h)) (swap! i inc) (progress-cb @i (alength frames)) (js/setTimeout step 1))))] (step))))
null
https://raw.githubusercontent.com/city41/mario-review/1b6ebfff88ad778a52865a062204cabb8deed0f9/cropping-app/src/client/crop_tool.cljs
clojure
fixes a large memory leak
(ns daisy.client.tools.crop-tool (:require [daisy.client.canvas-util :as util])) (defn- crop-frame [ctx frame x y sw sh dw dh] (let [source-img-data (.createImageData ctx sw sh) source-data (.-data source-img-data)] (.set source-data frame) (.putImageData ctx source-img-data 0 0) (let [dest-img-data (.getImageData ctx x y dw dh)] (.-data dest-img-data)))) (defn crop-frames [frames sw sh {:keys [x y w h] :as spec} cb progress-cb] (let [cropped-frames #js [] canvas (util/create-canvas sw sh) context (.getContext canvas "2d") i (atom 0)] (letfn [(step [] (if (= (alength cropped-frames) (alength frames)) (do (cb cropped-frames spec)) (do (.push cropped-frames (crop-frame context (aget frames @i) x y sw sh w h)) (swap! i inc) (progress-cb @i (alength frames)) (js/setTimeout step 1))))] (step))))
7595309325bdb12319e2c3d4c676346b09c8dcff606afb03628b6bbad6ffc8a5
rbkmoney/cds
cds_ident_doc_client.erl
-module(cds_ident_doc_client). %% Identity document operations -export([get_ident_doc/2]). -export([put_ident_doc/2]). %% %% Internal Types %% -type result() :: cds_woody_client:result(). -type ident_doc() :: identdocstore_identity_document_storage_thrift:'IdentityDocument'(). %% %% API %% -spec get_ident_doc(cds:token(), woody:url()) -> result(). get_ident_doc(Token, RootUrl) -> call(ident_doc, 'Get', {Token}, RootUrl). -spec put_ident_doc(ident_doc(), woody:url()) -> result(). put_ident_doc(IdentityDoc, RootUrl) -> call(ident_doc, 'Put', {IdentityDoc}, RootUrl). call(Service, Method, Args, RootUrl) -> cds_ct_utils:call(Service, Method, Args, RootUrl).
null
https://raw.githubusercontent.com/rbkmoney/cds/6e6541c99d34b0633775f0c5304f5008e6b2aaf3/apps/cds/test/cds_ident_doc_client.erl
erlang
Identity document operations Internal Types API
-module(cds_ident_doc_client). -export([get_ident_doc/2]). -export([put_ident_doc/2]). -type result() :: cds_woody_client:result(). -type ident_doc() :: identdocstore_identity_document_storage_thrift:'IdentityDocument'(). -spec get_ident_doc(cds:token(), woody:url()) -> result(). get_ident_doc(Token, RootUrl) -> call(ident_doc, 'Get', {Token}, RootUrl). -spec put_ident_doc(ident_doc(), woody:url()) -> result(). put_ident_doc(IdentityDoc, RootUrl) -> call(ident_doc, 'Put', {IdentityDoc}, RootUrl). call(Service, Method, Args, RootUrl) -> cds_ct_utils:call(Service, Method, Args, RootUrl).
3498e53483aca493bca0d806ae0151565f3bcfb5598ec7d828ffedd3b98538dc
khotyn/4clojure-answer
112-sequs-horribilis.clj
(fn [max-sum coll] (letfn [(step [coll current-sum max-sum] (if (seq coll) (let [head (first coll)] (if (coll? head) (let [sub (step head current-sum max-sum) next-sum (+ current-sum (reduce + (flatten sub)))] (if (<= next-sum max-sum) (cons sub (step (next coll) next-sum max-sum)) sub)) (let [next-sum (+ head current-sum)] (if (<= next-sum max-sum) (cons head (step (next coll) next-sum max-sum)) []))))))] (step coll 0 max-sum)))
null
https://raw.githubusercontent.com/khotyn/4clojure-answer/3de82d732faedceafac4f1585a72d0712fe5d3c6/112-sequs-horribilis.clj
clojure
(fn [max-sum coll] (letfn [(step [coll current-sum max-sum] (if (seq coll) (let [head (first coll)] (if (coll? head) (let [sub (step head current-sum max-sum) next-sum (+ current-sum (reduce + (flatten sub)))] (if (<= next-sum max-sum) (cons sub (step (next coll) next-sum max-sum)) sub)) (let [next-sum (+ head current-sum)] (if (<= next-sum max-sum) (cons head (step (next coll) next-sum max-sum)) []))))))] (step coll 0 max-sum)))
0ca5f530a7bb7b80f52c4e2abadd400d6340bbe4a63ae2cf0058a370a793c3fc
LeiWangHoward/Common-Lisp-Playground
map-color.lisp
(in-package #:ddr-tests) (defparameter *map-color-kb* '( (color red) (color blue) (color green) (color yellow) (-> (all-different ?c1 ?c2 ?c3 ?c4) (all-different ?c1 ?c2 ?c3) (all-different ?c1 ?c2 ?c4) (all-different ?c1 ?c3 ?c4) (all-different ?c2 ?c3 ?c4)) (-> (all-different ?c1 ?c2 ?c3) (different ?c1 ?c2) (different ?c1 ?c3) (different ?c2 ?c3)) (-> (different ?x ?y) (different ?y ?x)) (all-different red blue green yellow) (<- (colors-for map1 ?a ?b ?c ?d) (color ?a) (color ?b) (different ?a ?b) (color ?c) (different ?a ?c) (different ?b ?c) (color ?d) (different ?a ?d) (different ?b ?d) (different ?c ?d)) (<- (colors-for map2 ?a ?b ?c ?d ?e) (color ?a) (color ?b) (different ?a ?b) (color ?c) (different ?a ?c) (different ?b ?c) (color ?d) (different ?a ?d) (different ?c ?d) (color ?e) (different ?a ?e) (different ?b ?e) (different ?c ?e) (different ?d ?e)) (<- (colors-for map3 ?a ?b ?c ?d ?e ?f) (color ?a) (color ?b) (different ?a ?b) (color ?c) (different ?a ?c) (different ?b ?c) (color ?d) (different ?a ?d) (different ?b ?d) (different ?c ?d) (color ?e) (different ?a ?e) (different ?b ?e) (different ?d ?e) (color ?f) (different ?a ?f) (different ?d ?f) (different ?e ?f)) ))
null
https://raw.githubusercontent.com/LeiWangHoward/Common-Lisp-Playground/4130232954f1bbf8aa003d856ccb2ab382da0534/DDR/map-color.lisp
lisp
(in-package #:ddr-tests) (defparameter *map-color-kb* '( (color red) (color blue) (color green) (color yellow) (-> (all-different ?c1 ?c2 ?c3 ?c4) (all-different ?c1 ?c2 ?c3) (all-different ?c1 ?c2 ?c4) (all-different ?c1 ?c3 ?c4) (all-different ?c2 ?c3 ?c4)) (-> (all-different ?c1 ?c2 ?c3) (different ?c1 ?c2) (different ?c1 ?c3) (different ?c2 ?c3)) (-> (different ?x ?y) (different ?y ?x)) (all-different red blue green yellow) (<- (colors-for map1 ?a ?b ?c ?d) (color ?a) (color ?b) (different ?a ?b) (color ?c) (different ?a ?c) (different ?b ?c) (color ?d) (different ?a ?d) (different ?b ?d) (different ?c ?d)) (<- (colors-for map2 ?a ?b ?c ?d ?e) (color ?a) (color ?b) (different ?a ?b) (color ?c) (different ?a ?c) (different ?b ?c) (color ?d) (different ?a ?d) (different ?c ?d) (color ?e) (different ?a ?e) (different ?b ?e) (different ?c ?e) (different ?d ?e)) (<- (colors-for map3 ?a ?b ?c ?d ?e ?f) (color ?a) (color ?b) (different ?a ?b) (color ?c) (different ?a ?c) (different ?b ?c) (color ?d) (different ?a ?d) (different ?b ?d) (different ?c ?d) (color ?e) (different ?a ?e) (different ?b ?e) (different ?d ?e) (color ?f) (different ?a ?f) (different ?d ?f) (different ?e ?f)) ))
141b0248dc311a9dcfe45361c639fab9df048f966faab14d5ed58536ac071f6e
gulige/neuroevo
gstk_menu.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2016 . 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% %% %% %%----------------------------------------------------------------------------- %% BASIC MENU TYPE %%------------------------------------------------------------------------------ -module(gstk_menu). -compile([{nowarn_deprecated_function,{gs,error,2}}]). %%------------------------------------------------------------------------------ %% MENU OPTIONS %% %% Attribute: activebg Color %% activebw Int %% activefg Color %% bg Color %% bw Int %% data Data disabledfg Color %% fg Color %% relief Relief [flat|raised|sunken|ridge|groove] selectcolor Color %% %% Commands: %% setfocus [Bool | {Bool, Data}] %% %% Events: %% buttonpress [Bool | {Bool, Data}] %% buttonrelease [Bool | {Bool, Data}] %% configure [Bool | {Bool, Data}] %% destroy [Bool | {Bool, Data}] %% enter [Bool | {Bool, Data}] %% focus [Bool | {Bool, Data}] %% keypress [Bool | {Bool, Data}] keyrelease [ Bool | { Bool , Data } ] %% leave [Bool | {Bool, Data}] %% motion [Bool | {Bool, Data}] %% Read Options : %% children %% id %% parent %% type %% %% Not Implemented: %% post {X,Y} unpost align n , w , s , e , nw , , ne , sw , center anchor n , w , s , e , nw , , ne , sw , center %% cursor ?????? focus ? ? ? ? ? ? ( -takefocus ) %% height Int %% justify left|right|center (multiline text only) %% width Int %% x Int (valid only for popup menus) %% y Int (valid only for popup menus) %% -export([create/3, config/3, read/3, delete/2, event/5,option/5,read_option/5]). -export([delete_menuitem/3, insert_menuitem/4, lookup_menuitem_pos/3, mk_create_opts_for_child/4]). -include("gstk.hrl"). %%------------------------------------------------------------------------------ %% MANDATORY INTERFACE FUNCTIONS %%------------------------------------------------------------------------------ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Function : create/3 %% Purpose : Create a widget of the type defined in this module. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% create(DB, GstkId, Opts) -> #gstkid{parent=Parent,owner=Owner,objtype=Objtype}=GstkId, Pgstkid = gstk_db:lookup_gstkid(DB, Parent, Owner), Oref = gstk_db:counter(DB, Objtype), PF = gstk_widgets:suffix(Objtype), case Pgstkid#gstkid.objtype of menuitem -> PMenu = Pgstkid#gstkid.parent, PMgstkid = gstk_db:lookup_gstkid(DB, PMenu, Owner), PMW = PMgstkid#gstkid.widget, Index = gstk_menu:lookup_menuitem_pos(DB, PMgstkid, Pgstkid#gstkid.id), TkW = lists:concat([PMW, PF, Oref]), Gstkid=GstkId#gstkid{widget=TkW, widget_data=[]}, MPreCmd = ["menu ", TkW, " -tearoff 0 -relief raised -bo 2"], MPostCmd = [$;,PMW," entryco ",gstk:to_ascii(Index)," -menu ",TkW], case gstk_generic:make_command(Opts, Gstkid, TkW, "", "", DB) of {error,Reason} -> {error,Reason}; Cmd when is_list(Cmd) -> gstk:exec([MPreCmd,Cmd,MPostCmd]), Gstkid end; OtherParent -> true = lists:member(OtherParent, %% grid+canvas har skumma coord system [menubutton,window,frame]), PW = Pgstkid#gstkid.widget, TkW = lists:concat([PW, PF, Oref]), Gstkid=GstkId#gstkid{widget=TkW, widget_data=[]}, MPreCmd = ["menu ", TkW, " -tearoff 0 -relief raised -bo 2 "], MPostCmd = if OtherParent == menubutton -> [$;, PW, " conf -menu ", TkW]; true -> [] end, case gstk_generic:make_command(Opts, Gstkid, TkW, "","", DB) of {error,Reason} -> {error,Reason}; Cmd when is_list(Cmd) -> gstk:exec([MPreCmd,Cmd,MPostCmd]), Gstkid end end. mk_create_opts_for_child(DB,Cgstkid, Pgstkid, Opts) -> gstk_generic:mk_create_opts_for_child(DB,Cgstkid,Pgstkid,Opts). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Function : config/3 %% Purpose : Configure a widget of the type defined in this module. : DB - The Database - The gstkid of the widget %% Opts - A list of options for configuring the widget %% %% Return : [true | {bad_result, Reason}] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% config(DB, Gstkid, Opts) -> TkW = Gstkid#gstkid.widget, PreCmd = [TkW, " conf"], gstk_generic:mk_cmd_and_exec(Opts, Gstkid, TkW, PreCmd, "", DB). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Function : read/3 Purpose : Read one option from a widget : DB - The Database - The gstkid of the widget %% Opt - An option to read %% Return : [ OptionValue | { bad_result , Reason } ] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% read(DB, Gstkid, Opt) -> gstk_generic:read_option(DB, Gstkid, Opt). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Function : delete/2 %% Purpose : Delete widget from databas and return tkwidget to destroy : DB - The Database - The gstkid of the widget %% %% Return : TkWidget to destroy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% delete(DB, Gstkid) -> gstk_db:delete_widget(DB, Gstkid), Gstkid#gstkid.widget. event(DB, Gstkid, Etype, Edata, Args) -> gstk_generic:event(DB, Gstkid, Etype, Edata, Args). %%------------------------------------------------------------------------------ %% MANDATORY FUNCTIONS %%------------------------------------------------------------------------------ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Function : option/4 %% Purpose : Take care of options : Option - An option tuple - The gstkid of the widget TkW - The tk - widget %% DB - The Database %% Return : A tuple { OptionType , OptionCmd } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% option(Option, Gstkid, TkW, DB,_) -> case Option of {activebw, Int} -> {s, [" -activebo ", gstk:to_ascii(Int)]}; {disabledfg, Color} -> {s, [" -disabledf ", gstk:to_color(Color)]}; {selectcolor, Color} -> {s, [" -selectc ", gstk:to_color(Color)]}; {post_at, {X,Y}} -> post_at(X,Y,Gstkid,TkW,DB); _ -> invalid_option end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Function : read_option/5 %% Purpose : Take care of a read option : DB - The Database - The gstkid of the widget %% Option - An option %% %% Return : The value of the option or invalid_option [ OptionValue | { bad_result , Reason } ] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% read_option(Option, Gstkid, TkW, _DB, _AItem) -> case Option of activebw -> tcl2erl:ret_int([TkW," cg -activebo"]); disabledfg -> tcl2erl:ret_color([TkW," cg -disabledfo"]); selectcolor -> tcl2erl:ret_color([TkW," cg -selectc"]); _ -> {error,{invalid_option,Option, Gstkid#gstkid.objtype}} end. post_at(X,Y,Gstkid,TkW,DB) -> Pgstkid = gstk_db:lookup_gstkid(DB, Gstkid#gstkid.parent), PtkW = Pgstkid#gstkid.widget, RootX = tcl2erl:ret_int(["winfo rootx ",PtkW]), RootY = tcl2erl:ret_int(["winfo rooty ",PtkW]), {c,[" tk_popup ",TkW," ",gstk:to_ascii(RootX+X)," ",gstk:to_ascii(RootY+Y)]}. %%----------------------------------------------------------------------------- %% PRIMITIVES %%----------------------------------------------------------------------------- %%---------------------------------------------------------------------- gstk_db functions for handling %% Tk menuitems are numbered from 0, thus we have to recalc the position. %%---------------------------------------------------------------------- insert_menuitem(DB, MenuId, ItemId, Pos) -> Mgstkid = gstk_db:lookup_gstkid(DB, MenuId), Items = Mgstkid#gstkid.widget_data, NewItems = insert_at(ItemId, Pos+1, Items), gstk_db:update_widget(DB, Mgstkid#gstkid{widget_data=NewItems}). delete_menuitem(DB, MenuId, ItemId) -> Mgstkid = gstk_db:lookup_gstkid(DB, MenuId), Items = Mgstkid#gstkid.widget_data, NewItems = lists:delete(ItemId, Items), gstk_db:insert_widget(DB, Mgstkid#gstkid{widget_data=NewItems}). lookup_menuitem_pos(_DB, Mgstkid, ItemId) -> Items = Mgstkid#gstkid.widget_data, find_pos(ItemId, Items) - 1. %%---------------------------------------------------------------------- Generic list processing %%---------------------------------------------------------------------- find_pos(ItemId, Items) -> find_pos(ItemId, Items, 1). find_pos(_ItemId, [], _N) -> gs:error("Couldn't find item in menu~n", []); find_pos(ItemId, [ItemId|_Items], N) -> N; find_pos(ItemId, [_|Items], N) -> find_pos(ItemId, Items, N + 1). insert_at(Elem, 1, L) -> [Elem | L]; insert_at(Elem, N, [H|T]) -> [H|insert_at(Elem, N-1, T)]. %% ----- Done -----
null
https://raw.githubusercontent.com/gulige/neuroevo/09e67928c2417f2b27ec6522acc82f8b3c844949/apps/gs/src/gstk_menu.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% ----------------------------------------------------------------------------- BASIC MENU TYPE ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ MENU OPTIONS Attribute: activebw Int activefg Color bg Color bw Int data Data fg Color relief Relief [flat|raised|sunken|ridge|groove] Commands: setfocus [Bool | {Bool, Data}] Events: buttonpress [Bool | {Bool, Data}] buttonrelease [Bool | {Bool, Data}] configure [Bool | {Bool, Data}] destroy [Bool | {Bool, Data}] enter [Bool | {Bool, Data}] focus [Bool | {Bool, Data}] keypress [Bool | {Bool, Data}] leave [Bool | {Bool, Data}] motion [Bool | {Bool, Data}] children id parent type Not Implemented: post {X,Y} cursor ?????? height Int justify left|right|center (multiline text only) width Int x Int (valid only for popup menus) y Int (valid only for popup menus) ------------------------------------------------------------------------------ MANDATORY INTERFACE FUNCTIONS ------------------------------------------------------------------------------ Purpose : Create a widget of the type defined in this module. grid+canvas har skumma coord system Purpose : Configure a widget of the type defined in this module. Opts - A list of options for configuring the widget Return : [true | {bad_result, Reason}] Opt - An option to read Purpose : Delete widget from databas and return tkwidget to destroy Return : TkWidget to destroy ------------------------------------------------------------------------------ MANDATORY FUNCTIONS ------------------------------------------------------------------------------ Purpose : Take care of options DB - The Database Purpose : Take care of a read option Option - An option Return : The value of the option or invalid_option ----------------------------------------------------------------------------- PRIMITIVES ----------------------------------------------------------------------------- ---------------------------------------------------------------------- Tk menuitems are numbered from 0, thus we have to recalc the position. ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ----- Done -----
Copyright Ericsson AB 1996 - 2016 . 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(gstk_menu). -compile([{nowarn_deprecated_function,{gs,error,2}}]). activebg Color disabledfg Color selectcolor Color keyrelease [ Bool | { Bool , Data } ] Read Options : unpost align n , w , s , e , nw , , ne , sw , center anchor n , w , s , e , nw , , ne , sw , center focus ? ? ? ? ? ? ( -takefocus ) -export([create/3, config/3, read/3, delete/2, event/5,option/5,read_option/5]). -export([delete_menuitem/3, insert_menuitem/4, lookup_menuitem_pos/3, mk_create_opts_for_child/4]). -include("gstk.hrl"). Function : create/3 create(DB, GstkId, Opts) -> #gstkid{parent=Parent,owner=Owner,objtype=Objtype}=GstkId, Pgstkid = gstk_db:lookup_gstkid(DB, Parent, Owner), Oref = gstk_db:counter(DB, Objtype), PF = gstk_widgets:suffix(Objtype), case Pgstkid#gstkid.objtype of menuitem -> PMenu = Pgstkid#gstkid.parent, PMgstkid = gstk_db:lookup_gstkid(DB, PMenu, Owner), PMW = PMgstkid#gstkid.widget, Index = gstk_menu:lookup_menuitem_pos(DB, PMgstkid, Pgstkid#gstkid.id), TkW = lists:concat([PMW, PF, Oref]), Gstkid=GstkId#gstkid{widget=TkW, widget_data=[]}, MPreCmd = ["menu ", TkW, " -tearoff 0 -relief raised -bo 2"], MPostCmd = [$;,PMW," entryco ",gstk:to_ascii(Index)," -menu ",TkW], case gstk_generic:make_command(Opts, Gstkid, TkW, "", "", DB) of {error,Reason} -> {error,Reason}; Cmd when is_list(Cmd) -> gstk:exec([MPreCmd,Cmd,MPostCmd]), Gstkid end; OtherParent -> true = lists:member(OtherParent, [menubutton,window,frame]), PW = Pgstkid#gstkid.widget, TkW = lists:concat([PW, PF, Oref]), Gstkid=GstkId#gstkid{widget=TkW, widget_data=[]}, MPreCmd = ["menu ", TkW, " -tearoff 0 -relief raised -bo 2 "], MPostCmd = if OtherParent == menubutton -> [$;, PW, " conf -menu ", TkW]; true -> [] end, case gstk_generic:make_command(Opts, Gstkid, TkW, "","", DB) of {error,Reason} -> {error,Reason}; Cmd when is_list(Cmd) -> gstk:exec([MPreCmd,Cmd,MPostCmd]), Gstkid end end. mk_create_opts_for_child(DB,Cgstkid, Pgstkid, Opts) -> gstk_generic:mk_create_opts_for_child(DB,Cgstkid,Pgstkid,Opts). Function : config/3 : DB - The Database - The gstkid of the widget config(DB, Gstkid, Opts) -> TkW = Gstkid#gstkid.widget, PreCmd = [TkW, " conf"], gstk_generic:mk_cmd_and_exec(Opts, Gstkid, TkW, PreCmd, "", DB). Function : read/3 Purpose : Read one option from a widget : DB - The Database - The gstkid of the widget Return : [ OptionValue | { bad_result , Reason } ] read(DB, Gstkid, Opt) -> gstk_generic:read_option(DB, Gstkid, Opt). Function : delete/2 : DB - The Database - The gstkid of the widget delete(DB, Gstkid) -> gstk_db:delete_widget(DB, Gstkid), Gstkid#gstkid.widget. event(DB, Gstkid, Etype, Edata, Args) -> gstk_generic:event(DB, Gstkid, Etype, Edata, Args). Function : option/4 : Option - An option tuple - The gstkid of the widget TkW - The tk - widget Return : A tuple { OptionType , OptionCmd } option(Option, Gstkid, TkW, DB,_) -> case Option of {activebw, Int} -> {s, [" -activebo ", gstk:to_ascii(Int)]}; {disabledfg, Color} -> {s, [" -disabledf ", gstk:to_color(Color)]}; {selectcolor, Color} -> {s, [" -selectc ", gstk:to_color(Color)]}; {post_at, {X,Y}} -> post_at(X,Y,Gstkid,TkW,DB); _ -> invalid_option end. Function : read_option/5 : DB - The Database - The gstkid of the widget [ OptionValue | { bad_result , Reason } ] read_option(Option, Gstkid, TkW, _DB, _AItem) -> case Option of activebw -> tcl2erl:ret_int([TkW," cg -activebo"]); disabledfg -> tcl2erl:ret_color([TkW," cg -disabledfo"]); selectcolor -> tcl2erl:ret_color([TkW," cg -selectc"]); _ -> {error,{invalid_option,Option, Gstkid#gstkid.objtype}} end. post_at(X,Y,Gstkid,TkW,DB) -> Pgstkid = gstk_db:lookup_gstkid(DB, Gstkid#gstkid.parent), PtkW = Pgstkid#gstkid.widget, RootX = tcl2erl:ret_int(["winfo rootx ",PtkW]), RootY = tcl2erl:ret_int(["winfo rooty ",PtkW]), {c,[" tk_popup ",TkW," ",gstk:to_ascii(RootX+X)," ",gstk:to_ascii(RootY+Y)]}. gstk_db functions for handling insert_menuitem(DB, MenuId, ItemId, Pos) -> Mgstkid = gstk_db:lookup_gstkid(DB, MenuId), Items = Mgstkid#gstkid.widget_data, NewItems = insert_at(ItemId, Pos+1, Items), gstk_db:update_widget(DB, Mgstkid#gstkid{widget_data=NewItems}). delete_menuitem(DB, MenuId, ItemId) -> Mgstkid = gstk_db:lookup_gstkid(DB, MenuId), Items = Mgstkid#gstkid.widget_data, NewItems = lists:delete(ItemId, Items), gstk_db:insert_widget(DB, Mgstkid#gstkid{widget_data=NewItems}). lookup_menuitem_pos(_DB, Mgstkid, ItemId) -> Items = Mgstkid#gstkid.widget_data, find_pos(ItemId, Items) - 1. Generic list processing find_pos(ItemId, Items) -> find_pos(ItemId, Items, 1). find_pos(_ItemId, [], _N) -> gs:error("Couldn't find item in menu~n", []); find_pos(ItemId, [ItemId|_Items], N) -> N; find_pos(ItemId, [_|Items], N) -> find_pos(ItemId, Items, N + 1). insert_at(Elem, 1, L) -> [Elem | L]; insert_at(Elem, N, [H|T]) -> [H|insert_at(Elem, N-1, T)].
d6cb3d8efb0eff5581e02bb80f2c9466cf596fae522a3821c1a4d8301d87cf51
runtimeverification/haskell-backend
With.hs
module Test.Kore.With ( With (..), Attribute (..), OpaqueSet (..), VariableElement (..), ) where import Control.Lens qualified as Lens import Data.Generics.Product ( field, ) import Data.HashMap.Strict qualified as HashMap import Data.HashSet qualified as HashSet import Data.List qualified as List import Data.List.NonEmpty qualified as NonEmpty ( cons, reverse, ) import Data.Map.Strict qualified as Map import Kore.Attribute.Sort.Constructors qualified as Attribute ( Constructors (Constructors), ) import Kore.Attribute.Sort.Constructors qualified as Attribute.Constructors ( Constructor (Constructor), ConstructorLike (..), ) import Kore.Attribute.Sort.Constructors qualified as Attribute.Constructors.Constructor ( Constructor (..), ) import Kore.Internal.InternalMap import Kore.Internal.InternalSet import Kore.Internal.TermLike ( Key, ) import Kore.Rewrite.SMT.AST qualified as AST ( Declarations (Declarations), IndirectSymbolDeclaration (IndirectSymbolDeclaration), KoreSortDeclaration (..), KoreSymbolDeclaration (..), Sort (Sort), SortReference (SortReference), Symbol (Symbol), UnresolvedIndirectSymbolDeclaration, UnresolvedKoreSymbolDeclaration, UnresolvedSymbol, ) import Kore.Rewrite.SMT.AST qualified as AST.Declarations ( Declarations (..), ) import Kore.Rewrite.SMT.AST qualified as AST.IndirectSymbolDeclaration ( IndirectSymbolDeclaration (..), ) import Kore.Rewrite.SMT.AST qualified as AST.Sort ( Sort (..), ) import Kore.Rewrite.SMT.AST qualified as AST.Symbol ( Symbol (..), ) import Kore.Sort qualified as Kore ( Sort, ) import Kore.Syntax.Definition ( Definition (Definition), ) import Kore.Syntax.Definition qualified as Definition ( Definition (..), ) import Kore.Syntax.Id qualified as Kore ( Id, ) import Kore.Syntax.Module qualified as Module ( Module (..), ) import Kore.Syntax.Sentence import Kore.Syntax.Sentence qualified as SentenceAlias ( SentenceAlias (..), ) import Kore.Syntax.Sentence qualified as SentenceAxiom ( SentenceAxiom (..), ) import Kore.Syntax.Sentence qualified as SentenceImport ( SentenceImport (..), ) import Kore.Syntax.Sentence qualified as SentenceSort ( SentenceSort (..), ) import Kore.Syntax.Sentence qualified as SentenceSymbol ( SentenceSymbol (..), ) import Prelude.Kore import SMT.AST qualified as AST ( Constructor (Constructor), ConstructorArgument, DataTypeDeclaration (DataTypeDeclaration), ) import SMT.AST qualified as AST.Constructor ( Constructor (..), ) import SMT.AST qualified as AST.DataTypeDeclaration ( DataTypeDeclaration (..), ) class With a b where with :: a -> b -> a newtype Attribute = Attribute {getAttribute :: AttributePattern} instance (With b c) => With (a -> b) (a -> c) where with fb fc = \a -> fb a `with` fc a instance With [a] a where with as a = a : as instance With (Module sentence) Attribute where with m@Module{moduleAttributes = Attributes as} Attribute{getAttribute} = m{Module.moduleAttributes = Attributes (as `with` getAttribute)} instance With (Module sentence) [Attribute] where with = foldl' with instance With (Definition sentence) Attribute where with d@Definition{definitionAttributes = Attributes as} Attribute{getAttribute} = d { Definition.definitionAttributes = Attributes (as `with` getAttribute) } instance With (Definition sentence) [Attribute] where with = foldl' with instance With (Sentence patt) Attribute where (SentenceAliasSentence s) `with` attribute = SentenceAliasSentence (s `with` attribute) (SentenceSymbolSentence s) `with` attribute = SentenceSymbolSentence (s `with` attribute) (SentenceImportSentence s) `with` attribute = SentenceImportSentence (s `with` attribute) (SentenceAxiomSentence s) `with` attribute = SentenceAxiomSentence (s `with` attribute) (SentenceClaimSentence s) `with` attribute = SentenceClaimSentence (s `with` attribute) (SentenceSortSentence s) `with` attribute = SentenceSortSentence (s `with` attribute) (SentenceHookSentence (SentenceHookedSort s)) `with` attribute = SentenceHookSentence (SentenceHookedSort (s `with` attribute)) (SentenceHookSentence (SentenceHookedSymbol s)) `with` attribute = SentenceHookSentence (SentenceHookedSymbol (s `with` attribute)) instance With (Sentence patt) [Attribute] where with = foldl' with instance With (SentenceAlias patt) Attribute where s@SentenceAlias{sentenceAliasAttributes} `with` attribute = s { SentenceAlias.sentenceAliasAttributes = sentenceAliasAttributes `with` attribute } instance With (SentenceAlias patt) [Attribute] where with = foldl' with instance With (SentenceAxiom patt) Attribute where s@SentenceAxiom{sentenceAxiomAttributes} `with` attribute = s { SentenceAxiom.sentenceAxiomAttributes = sentenceAxiomAttributes `with` attribute } instance With (SentenceAxiom patt) [Attribute] where with = foldl' with instance With (SentenceClaim patt) Attribute where with a b = SentenceClaim (with (getSentenceClaim a) b) instance With (SentenceClaim patt) [Attribute] where with a b = SentenceClaim (with (getSentenceClaim a) b) instance With SentenceImport Attribute where s@SentenceImport{sentenceImportAttributes} `with` attribute = s { SentenceImport.sentenceImportAttributes = sentenceImportAttributes `with` attribute } instance With SentenceImport [Attribute] where with = foldl' with instance With SentenceSymbol Attribute where s@SentenceSymbol{sentenceSymbolAttributes} `with` attribute = s { SentenceSymbol.sentenceSymbolAttributes = sentenceSymbolAttributes `with` attribute } instance With SentenceSymbol [Attribute] where with = foldl' with instance With SentenceSort Attribute where s@SentenceSort{sentenceSortAttributes} `with` attribute = s { SentenceSort.sentenceSortAttributes = sentenceSortAttributes `with` attribute } instance With SentenceSort [Attribute] where with = foldl' with instance With Attributes Attribute where (Attributes attributes) `with` Attribute{getAttribute} = Attributes (attributes `with` getAttribute) instance With Attributes [Attribute] where with = foldl' with instance With (Module sentence) sentence where with m@Module{moduleSentences = sentences} sentence = m{Module.moduleSentences = sentences `with` sentence} instance With (AST.Declarations sort symbol name) (Kore.Id, AST.Sort sort symbol name) where with {sorts} (sortId, sort) = d{AST.Declarations.sorts = Map.insert sortId sort sorts} instance With (Kore.Id, AST.Sort sort symbol name) (AST.Constructor sort symbol name) where with (sortId, sort) constructor = (sortId, sort `with` constructor) instance With (AST.Sort sort symbol name) (AST.Constructor sort symbol name) where with {sortDeclaration} constructor = s{AST.Sort.sortDeclaration = sortDeclaration `with` constructor} instance With (AST.KoreSortDeclaration sort symbol name) (AST.Constructor sort symbol name) where with (AST.SortDeclarationDataType declaration) constructor = AST.SortDeclarationDataType (declaration `with` constructor) with (AST.SortDeclarationSort _) _ = error "Cannot add constructors to SortDeclarationSort." with (AST.SortDeclaredIndirectly _) _ = error "Cannot add constructors to SortDeclaredIndirectly." instance With (AST.DataTypeDeclaration sort symbol name) (AST.Constructor sort symbol name) where with {constructors} constructor = s { AST.DataTypeDeclaration.constructors = constructors `with` constructor } instance With (AST.Constructor sort symbol name) (AST.ConstructorArgument sort name) where with {arguments} argument = s { AST.Constructor.arguments = arguments `with` argument } instance With (Kore.Id, AST.UnresolvedSymbol) Kore.Sort where with (symbolId, symbol) sort = (symbolId, symbol `with` sort) instance With AST.UnresolvedSymbol Kore.Sort where with {symbolDeclaration} sort = s{AST.Symbol.symbolDeclaration = symbolDeclaration `with` sort} instance With AST.UnresolvedKoreSymbolDeclaration Kore.Sort where with (AST.SymbolDeclaredDirectly _) _ = error "Cannot add sorts to SymbolDeclaredDirectly." with (AST.SymbolBuiltin declaration) sort = AST.SymbolBuiltin (declaration `with` sort) with (AST.SymbolConstructor declaration) sort = AST.SymbolConstructor (declaration `with` sort) instance With AST.UnresolvedIndirectSymbolDeclaration Kore.Sort where with {sortDependencies} sort = s { AST.IndirectSymbolDeclaration.sortDependencies = sortDependencies `with` AST.SortReference sort } instance With (NormalizedAc NormalizedSet Key child) Key where with s@NormalizedAc{concreteElements} key | HashMap.member key concreteElements = error "Duplicated key in set." | otherwise = s { concreteElements = HashMap.insert key SetValue concreteElements } instance With (NormalizedAc NormalizedSet Key child) [Key] where with = foldl' with instance With (NormalizedSet Key child) Key where with (NormalizedSet ac) value = NormalizedSet (ac `with` value) instance With (NormalizedSet Key child) [Key] where with = foldl' with -- VariableElement newtype VariableElement child = VariableElement {getVariableElement :: child} instance Hashable child => With (NormalizedAc NormalizedSet Key child) (VariableElement child) where with internalSet (VariableElement v) = Lens.over (field @"elementsWithVariables") ( \symbolicVariables -> let newElement = SetElement v newSymbolicVariables = newElement : symbolicVariables simulateNormalize = HashSet.toList . HashSet.fromList in if newElement `elem` symbolicVariables then -- user intended for a de-normalized internalSet newSymbolicVariables else -- this simulates the reordering of the elements -- which happens during AC normalization simulateNormalize newSymbolicVariables ) internalSet instance Hashable child => With (NormalizedAc NormalizedSet Key child) [VariableElement child] where with = foldl' with instance Hashable child => With (NormalizedSet Key child) (VariableElement child) where with (NormalizedSet ac) value = NormalizedSet (ac `with` value) instance Hashable child => With (NormalizedSet Key child) [VariableElement child] where with = foldl' with OpaqueSet newtype OpaqueSet child = OpaqueSet {getOpaqueSet :: child} instance Ord child => With (NormalizedAc NormalizedSet Key child) (OpaqueSet child) where with s@NormalizedAc{opaque} (OpaqueSet v) = s { opaque = List.sort (v : opaque) } instance Ord child => With (NormalizedAc NormalizedSet Key child) [OpaqueSet child] where with = foldl' with instance Ord child => With (NormalizedSet Key child) (OpaqueSet child) where with (NormalizedSet ac) value = NormalizedSet (ac `with` value) instance Ord child => With (NormalizedSet Key child) [OpaqueSet child] where with = foldl' with instance With Attribute.Constructors Attribute.Constructors.ConstructorLike where with (Attribute.Constructors Nothing) constructorLike = Attribute.Constructors (Just (constructorLike :| [])) with (Attribute.Constructors (Just constructors)) constructorLike = Attribute.Constructors $ Just $ nonEmptyAppend constructorLike constructors instance With Attribute.Constructors.ConstructorLike Kore.Sort where with (Attribute.Constructors.ConstructorLikeConstructor constructor) sort = Attribute.Constructors.ConstructorLikeConstructor (constructor `with` sort) with Attribute.Constructors.ConstructorLikeInjection _sort = error "Cannot add sort to injection." instance With Attribute.Constructors.Constructor Kore.Sort where with {sorts} sort = c{Attribute.Constructors.Constructor.sorts = sorts ++ [sort]} nonEmptyAppend :: a -> NonEmpty a -> NonEmpty a nonEmptyAppend a = NonEmpty.reverse . NonEmpty.cons a . NonEmpty.reverse
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/fae73ac06cc9bcf8e24b0bdd2f07069610277d58/kore/test/Test/Kore/With.hs
haskell
VariableElement user intended for a de-normalized internalSet this simulates the reordering of the elements which happens during AC normalization
module Test.Kore.With ( With (..), Attribute (..), OpaqueSet (..), VariableElement (..), ) where import Control.Lens qualified as Lens import Data.Generics.Product ( field, ) import Data.HashMap.Strict qualified as HashMap import Data.HashSet qualified as HashSet import Data.List qualified as List import Data.List.NonEmpty qualified as NonEmpty ( cons, reverse, ) import Data.Map.Strict qualified as Map import Kore.Attribute.Sort.Constructors qualified as Attribute ( Constructors (Constructors), ) import Kore.Attribute.Sort.Constructors qualified as Attribute.Constructors ( Constructor (Constructor), ConstructorLike (..), ) import Kore.Attribute.Sort.Constructors qualified as Attribute.Constructors.Constructor ( Constructor (..), ) import Kore.Internal.InternalMap import Kore.Internal.InternalSet import Kore.Internal.TermLike ( Key, ) import Kore.Rewrite.SMT.AST qualified as AST ( Declarations (Declarations), IndirectSymbolDeclaration (IndirectSymbolDeclaration), KoreSortDeclaration (..), KoreSymbolDeclaration (..), Sort (Sort), SortReference (SortReference), Symbol (Symbol), UnresolvedIndirectSymbolDeclaration, UnresolvedKoreSymbolDeclaration, UnresolvedSymbol, ) import Kore.Rewrite.SMT.AST qualified as AST.Declarations ( Declarations (..), ) import Kore.Rewrite.SMT.AST qualified as AST.IndirectSymbolDeclaration ( IndirectSymbolDeclaration (..), ) import Kore.Rewrite.SMT.AST qualified as AST.Sort ( Sort (..), ) import Kore.Rewrite.SMT.AST qualified as AST.Symbol ( Symbol (..), ) import Kore.Sort qualified as Kore ( Sort, ) import Kore.Syntax.Definition ( Definition (Definition), ) import Kore.Syntax.Definition qualified as Definition ( Definition (..), ) import Kore.Syntax.Id qualified as Kore ( Id, ) import Kore.Syntax.Module qualified as Module ( Module (..), ) import Kore.Syntax.Sentence import Kore.Syntax.Sentence qualified as SentenceAlias ( SentenceAlias (..), ) import Kore.Syntax.Sentence qualified as SentenceAxiom ( SentenceAxiom (..), ) import Kore.Syntax.Sentence qualified as SentenceImport ( SentenceImport (..), ) import Kore.Syntax.Sentence qualified as SentenceSort ( SentenceSort (..), ) import Kore.Syntax.Sentence qualified as SentenceSymbol ( SentenceSymbol (..), ) import Prelude.Kore import SMT.AST qualified as AST ( Constructor (Constructor), ConstructorArgument, DataTypeDeclaration (DataTypeDeclaration), ) import SMT.AST qualified as AST.Constructor ( Constructor (..), ) import SMT.AST qualified as AST.DataTypeDeclaration ( DataTypeDeclaration (..), ) class With a b where with :: a -> b -> a newtype Attribute = Attribute {getAttribute :: AttributePattern} instance (With b c) => With (a -> b) (a -> c) where with fb fc = \a -> fb a `with` fc a instance With [a] a where with as a = a : as instance With (Module sentence) Attribute where with m@Module{moduleAttributes = Attributes as} Attribute{getAttribute} = m{Module.moduleAttributes = Attributes (as `with` getAttribute)} instance With (Module sentence) [Attribute] where with = foldl' with instance With (Definition sentence) Attribute where with d@Definition{definitionAttributes = Attributes as} Attribute{getAttribute} = d { Definition.definitionAttributes = Attributes (as `with` getAttribute) } instance With (Definition sentence) [Attribute] where with = foldl' with instance With (Sentence patt) Attribute where (SentenceAliasSentence s) `with` attribute = SentenceAliasSentence (s `with` attribute) (SentenceSymbolSentence s) `with` attribute = SentenceSymbolSentence (s `with` attribute) (SentenceImportSentence s) `with` attribute = SentenceImportSentence (s `with` attribute) (SentenceAxiomSentence s) `with` attribute = SentenceAxiomSentence (s `with` attribute) (SentenceClaimSentence s) `with` attribute = SentenceClaimSentence (s `with` attribute) (SentenceSortSentence s) `with` attribute = SentenceSortSentence (s `with` attribute) (SentenceHookSentence (SentenceHookedSort s)) `with` attribute = SentenceHookSentence (SentenceHookedSort (s `with` attribute)) (SentenceHookSentence (SentenceHookedSymbol s)) `with` attribute = SentenceHookSentence (SentenceHookedSymbol (s `with` attribute)) instance With (Sentence patt) [Attribute] where with = foldl' with instance With (SentenceAlias patt) Attribute where s@SentenceAlias{sentenceAliasAttributes} `with` attribute = s { SentenceAlias.sentenceAliasAttributes = sentenceAliasAttributes `with` attribute } instance With (SentenceAlias patt) [Attribute] where with = foldl' with instance With (SentenceAxiom patt) Attribute where s@SentenceAxiom{sentenceAxiomAttributes} `with` attribute = s { SentenceAxiom.sentenceAxiomAttributes = sentenceAxiomAttributes `with` attribute } instance With (SentenceAxiom patt) [Attribute] where with = foldl' with instance With (SentenceClaim patt) Attribute where with a b = SentenceClaim (with (getSentenceClaim a) b) instance With (SentenceClaim patt) [Attribute] where with a b = SentenceClaim (with (getSentenceClaim a) b) instance With SentenceImport Attribute where s@SentenceImport{sentenceImportAttributes} `with` attribute = s { SentenceImport.sentenceImportAttributes = sentenceImportAttributes `with` attribute } instance With SentenceImport [Attribute] where with = foldl' with instance With SentenceSymbol Attribute where s@SentenceSymbol{sentenceSymbolAttributes} `with` attribute = s { SentenceSymbol.sentenceSymbolAttributes = sentenceSymbolAttributes `with` attribute } instance With SentenceSymbol [Attribute] where with = foldl' with instance With SentenceSort Attribute where s@SentenceSort{sentenceSortAttributes} `with` attribute = s { SentenceSort.sentenceSortAttributes = sentenceSortAttributes `with` attribute } instance With SentenceSort [Attribute] where with = foldl' with instance With Attributes Attribute where (Attributes attributes) `with` Attribute{getAttribute} = Attributes (attributes `with` getAttribute) instance With Attributes [Attribute] where with = foldl' with instance With (Module sentence) sentence where with m@Module{moduleSentences = sentences} sentence = m{Module.moduleSentences = sentences `with` sentence} instance With (AST.Declarations sort symbol name) (Kore.Id, AST.Sort sort symbol name) where with {sorts} (sortId, sort) = d{AST.Declarations.sorts = Map.insert sortId sort sorts} instance With (Kore.Id, AST.Sort sort symbol name) (AST.Constructor sort symbol name) where with (sortId, sort) constructor = (sortId, sort `with` constructor) instance With (AST.Sort sort symbol name) (AST.Constructor sort symbol name) where with {sortDeclaration} constructor = s{AST.Sort.sortDeclaration = sortDeclaration `with` constructor} instance With (AST.KoreSortDeclaration sort symbol name) (AST.Constructor sort symbol name) where with (AST.SortDeclarationDataType declaration) constructor = AST.SortDeclarationDataType (declaration `with` constructor) with (AST.SortDeclarationSort _) _ = error "Cannot add constructors to SortDeclarationSort." with (AST.SortDeclaredIndirectly _) _ = error "Cannot add constructors to SortDeclaredIndirectly." instance With (AST.DataTypeDeclaration sort symbol name) (AST.Constructor sort symbol name) where with {constructors} constructor = s { AST.DataTypeDeclaration.constructors = constructors `with` constructor } instance With (AST.Constructor sort symbol name) (AST.ConstructorArgument sort name) where with {arguments} argument = s { AST.Constructor.arguments = arguments `with` argument } instance With (Kore.Id, AST.UnresolvedSymbol) Kore.Sort where with (symbolId, symbol) sort = (symbolId, symbol `with` sort) instance With AST.UnresolvedSymbol Kore.Sort where with {symbolDeclaration} sort = s{AST.Symbol.symbolDeclaration = symbolDeclaration `with` sort} instance With AST.UnresolvedKoreSymbolDeclaration Kore.Sort where with (AST.SymbolDeclaredDirectly _) _ = error "Cannot add sorts to SymbolDeclaredDirectly." with (AST.SymbolBuiltin declaration) sort = AST.SymbolBuiltin (declaration `with` sort) with (AST.SymbolConstructor declaration) sort = AST.SymbolConstructor (declaration `with` sort) instance With AST.UnresolvedIndirectSymbolDeclaration Kore.Sort where with {sortDependencies} sort = s { AST.IndirectSymbolDeclaration.sortDependencies = sortDependencies `with` AST.SortReference sort } instance With (NormalizedAc NormalizedSet Key child) Key where with s@NormalizedAc{concreteElements} key | HashMap.member key concreteElements = error "Duplicated key in set." | otherwise = s { concreteElements = HashMap.insert key SetValue concreteElements } instance With (NormalizedAc NormalizedSet Key child) [Key] where with = foldl' with instance With (NormalizedSet Key child) Key where with (NormalizedSet ac) value = NormalizedSet (ac `with` value) instance With (NormalizedSet Key child) [Key] where with = foldl' with newtype VariableElement child = VariableElement {getVariableElement :: child} instance Hashable child => With (NormalizedAc NormalizedSet Key child) (VariableElement child) where with internalSet (VariableElement v) = Lens.over (field @"elementsWithVariables") ( \symbolicVariables -> let newElement = SetElement v newSymbolicVariables = newElement : symbolicVariables simulateNormalize = HashSet.toList . HashSet.fromList in if newElement `elem` symbolicVariables newSymbolicVariables simulateNormalize newSymbolicVariables ) internalSet instance Hashable child => With (NormalizedAc NormalizedSet Key child) [VariableElement child] where with = foldl' with instance Hashable child => With (NormalizedSet Key child) (VariableElement child) where with (NormalizedSet ac) value = NormalizedSet (ac `with` value) instance Hashable child => With (NormalizedSet Key child) [VariableElement child] where with = foldl' with OpaqueSet newtype OpaqueSet child = OpaqueSet {getOpaqueSet :: child} instance Ord child => With (NormalizedAc NormalizedSet Key child) (OpaqueSet child) where with s@NormalizedAc{opaque} (OpaqueSet v) = s { opaque = List.sort (v : opaque) } instance Ord child => With (NormalizedAc NormalizedSet Key child) [OpaqueSet child] where with = foldl' with instance Ord child => With (NormalizedSet Key child) (OpaqueSet child) where with (NormalizedSet ac) value = NormalizedSet (ac `with` value) instance Ord child => With (NormalizedSet Key child) [OpaqueSet child] where with = foldl' with instance With Attribute.Constructors Attribute.Constructors.ConstructorLike where with (Attribute.Constructors Nothing) constructorLike = Attribute.Constructors (Just (constructorLike :| [])) with (Attribute.Constructors (Just constructors)) constructorLike = Attribute.Constructors $ Just $ nonEmptyAppend constructorLike constructors instance With Attribute.Constructors.ConstructorLike Kore.Sort where with (Attribute.Constructors.ConstructorLikeConstructor constructor) sort = Attribute.Constructors.ConstructorLikeConstructor (constructor `with` sort) with Attribute.Constructors.ConstructorLikeInjection _sort = error "Cannot add sort to injection." instance With Attribute.Constructors.Constructor Kore.Sort where with {sorts} sort = c{Attribute.Constructors.Constructor.sorts = sorts ++ [sort]} nonEmptyAppend :: a -> NonEmpty a -> NonEmpty a nonEmptyAppend a = NonEmpty.reverse . NonEmpty.cons a . NonEmpty.reverse
c1a96e2d5c8bd81b092db73f94da77d593e864d8b4c8a14f030f2fdd0fab6076
thattommyhall/offline-4clojure
p143.clj
;; dot product - Easy Create a function that computes the < a href=" / wiki / Dot_product#Definition">dot product</a > of two sequences . You may assume that the vectors will have the same length . ;; tags - seqs:math ;; restricted - (ns offline-4clojure.p143 (:use clojure.test)) (def __ ;; your solution here ) (defn -main [] (are [soln] soln (= 0 (__ [0 1 0] [1 0 0])) (= 3 (__ [1 1 1] [1 1 1])) (= 32 (__ [1 2 3] [4 5 6])) (= 256 (__ [2 5 6] [100 10 1])) ))
null
https://raw.githubusercontent.com/thattommyhall/offline-4clojure/73e32fc6687816aea3c514767cef3916176589ab/src/offline_4clojure/p143.clj
clojure
dot product - Easy tags - seqs:math restricted - your solution here
Create a function that computes the < a href=" / wiki / Dot_product#Definition">dot product</a > of two sequences . You may assume that the vectors will have the same length . (ns offline-4clojure.p143 (:use clojure.test)) (def __ ) (defn -main [] (are [soln] soln (= 0 (__ [0 1 0] [1 0 0])) (= 3 (__ [1 1 1] [1 1 1])) (= 32 (__ [1 2 3] [4 5 6])) (= 256 (__ [2 5 6] [100 10 1])) ))
caec128de76bdbb770a034ef995335d6386bae0ec95fa5169663a608c9c26f6b
haskell-works/hw-prim
AsVector64nsSpec.hs
# OPTIONS_GHC -fno - warn - incomplete - patterns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module HaskellWorks.Data.Vector.AsVector64nsSpec ( spec ) where import HaskellWorks.Data.Vector.AsVector64 import HaskellWorks.Data.Vector.AsVector64ns import HaskellWorks.Hspec.Hedgehog import Hedgehog import Test.Hspec import qualified Data.ByteString as BS import qualified Data.Vector.Storable as DVS import qualified Hedgehog.Gen as G import qualified Hedgehog.Range as R HLINT ignore " Redundant do " spec :: Spec spec = describe "HaskellWorks.Data.Vector.AsVector64nsSpec" $ do it "Conversion of ByteString works 1" $ requireProperty $ do bss <- forAll $ (BS.pack <$>) <$> G.list (R.linear 0 8) (G.list (R.linear 0 24) (G.word8 R.constantBounded)) chunkSize <- forAll $ G.int (R.linear 1 4) mconcat (asVector64ns chunkSize [mconcat bss]) === mconcat (asVector64ns chunkSize bss) True === True it "Conversion of ByteString works 2" $ requireProperty $ do bss <- forAll $ (BS.pack <$>) <$> G.list (R.linear 0 8) (G.list (R.linear 0 24) (G.word8 R.constantBounded)) chunkSize <- forAll $ G.int (R.linear 1 4) let actual = mconcat (asVector64ns chunkSize [mconcat bss]) let expected = mconcat (asVector64ns chunkSize bss) (reverse . dropWhile (== 0) . reverse) (DVS.toList actual) === (reverse . dropWhile (== 0) . reverse) (DVS.toList expected) True === True it "Conversion of ByteString works 3" $ requireProperty $ do bss <- forAll $ (BS.pack <$>) <$> G.list (R.linear 0 8) (G.list (R.linear 0 24) (G.word8 R.constantBounded)) chunkSize <- forAll $ G.int (R.linear 1 4) let actual = mconcat (asVector64ns chunkSize bss) let expected = asVector64 (mconcat bss) (reverse . dropWhile (== 0) . reverse) (DVS.toList actual) === (reverse . dropWhile (== 0) . reverse) (DVS.toList expected) True === True
null
https://raw.githubusercontent.com/haskell-works/hw-prim/aff74834cd2d3fb0eb4994b24b2d1cdef1e3e673/test/HaskellWorks/Data/Vector/AsVector64nsSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# OPTIONS_GHC -fno - warn - incomplete - patterns # # LANGUAGE ScopedTypeVariables # module HaskellWorks.Data.Vector.AsVector64nsSpec ( spec ) where import HaskellWorks.Data.Vector.AsVector64 import HaskellWorks.Data.Vector.AsVector64ns import HaskellWorks.Hspec.Hedgehog import Hedgehog import Test.Hspec import qualified Data.ByteString as BS import qualified Data.Vector.Storable as DVS import qualified Hedgehog.Gen as G import qualified Hedgehog.Range as R HLINT ignore " Redundant do " spec :: Spec spec = describe "HaskellWorks.Data.Vector.AsVector64nsSpec" $ do it "Conversion of ByteString works 1" $ requireProperty $ do bss <- forAll $ (BS.pack <$>) <$> G.list (R.linear 0 8) (G.list (R.linear 0 24) (G.word8 R.constantBounded)) chunkSize <- forAll $ G.int (R.linear 1 4) mconcat (asVector64ns chunkSize [mconcat bss]) === mconcat (asVector64ns chunkSize bss) True === True it "Conversion of ByteString works 2" $ requireProperty $ do bss <- forAll $ (BS.pack <$>) <$> G.list (R.linear 0 8) (G.list (R.linear 0 24) (G.word8 R.constantBounded)) chunkSize <- forAll $ G.int (R.linear 1 4) let actual = mconcat (asVector64ns chunkSize [mconcat bss]) let expected = mconcat (asVector64ns chunkSize bss) (reverse . dropWhile (== 0) . reverse) (DVS.toList actual) === (reverse . dropWhile (== 0) . reverse) (DVS.toList expected) True === True it "Conversion of ByteString works 3" $ requireProperty $ do bss <- forAll $ (BS.pack <$>) <$> G.list (R.linear 0 8) (G.list (R.linear 0 24) (G.word8 R.constantBounded)) chunkSize <- forAll $ G.int (R.linear 1 4) let actual = mconcat (asVector64ns chunkSize bss) let expected = asVector64 (mconcat bss) (reverse . dropWhile (== 0) . reverse) (DVS.toList actual) === (reverse . dropWhile (== 0) . reverse) (DVS.toList expected) True === True
603aafa5024ecd32993e483cba46e3d9ecc63ca0dbfb222f992f09c30a7b600e
baskeboler/cljs-karaoke-client
audio.cljs
(ns cljs-karaoke.subs.audio (:require [re-frame.core :as rf])) (rf/reg-sub ::audio-data (fn [db _] (:audio-data db))) (defn reg-audio-data-sub [sub-name attr-name] (rf/reg-sub sub-name :<- [::audio-data] (fn [data _] (get data attr-name)))) (reg-audio-data-sub ::feedback-reduction? :feedback-reduction?) (reg-audio-data-sub ::reverb-buffer :reverb-buffer) (reg-audio-data-sub ::dry-gain :dry-gain) (reg-audio-data-sub ::wet-gain :wet-gain) (reg-audio-data-sub ::effect-input :effect-input) (reg-audio-data-sub ::output-mix :output-mix) (reg-audio-data-sub ::audio-input :audio-input) (reg-audio-data-sub ::lp-input-filter :lp-input-filter) (reg-audio-data-sub ::clean-analyser :clean-analyser) (reg-audio-data-sub ::reverb-analyser :reverb-analyser) (reg-audio-data-sub ::freq-data :freq-data) (reg-audio-data-sub ::audio-context :audio-context) (reg-audio-data-sub ::stream :stream) (reg-audio-data-sub ::audio-input-available? :audio-input-available?) (reg-audio-data-sub ::recording-enabled? :recording-enabled?) (reg-audio-data-sub ::recorded-blobs :recorded-blobs) (reg-audio-data-sub ::media-recorder :media-recorder) (reg-audio-data-sub ::recording? :recording?) (rf/reg-sub ::recording-button-enabled? :<- [::recording?] :<- [::recording-enabled?] (fn [[recording? enabled?] _] (and enabled? (not recording?)))) (rf/reg-sub ::microphone-enabled? :<- [::output-mix] (fn [mix _] (not (nil? mix)))) (cljs-karaoke.subs/reg-attr-sub ::song-stream :song-stream) (cljs-karaoke.subs/reg-attr-sub ::effects-audio-ready? :effects-audio-ready?) ;; (rf/reg-sub ;; ::song-stream ;; (fn [db _] ;; (:song-stream db))
null
https://raw.githubusercontent.com/baskeboler/cljs-karaoke-client/bb6512435eaa436d35034886be99213625847ee0/src/main/cljs_karaoke/subs/audio.cljs
clojure
(rf/reg-sub ::song-stream (fn [db _] (:song-stream db))
(ns cljs-karaoke.subs.audio (:require [re-frame.core :as rf])) (rf/reg-sub ::audio-data (fn [db _] (:audio-data db))) (defn reg-audio-data-sub [sub-name attr-name] (rf/reg-sub sub-name :<- [::audio-data] (fn [data _] (get data attr-name)))) (reg-audio-data-sub ::feedback-reduction? :feedback-reduction?) (reg-audio-data-sub ::reverb-buffer :reverb-buffer) (reg-audio-data-sub ::dry-gain :dry-gain) (reg-audio-data-sub ::wet-gain :wet-gain) (reg-audio-data-sub ::effect-input :effect-input) (reg-audio-data-sub ::output-mix :output-mix) (reg-audio-data-sub ::audio-input :audio-input) (reg-audio-data-sub ::lp-input-filter :lp-input-filter) (reg-audio-data-sub ::clean-analyser :clean-analyser) (reg-audio-data-sub ::reverb-analyser :reverb-analyser) (reg-audio-data-sub ::freq-data :freq-data) (reg-audio-data-sub ::audio-context :audio-context) (reg-audio-data-sub ::stream :stream) (reg-audio-data-sub ::audio-input-available? :audio-input-available?) (reg-audio-data-sub ::recording-enabled? :recording-enabled?) (reg-audio-data-sub ::recorded-blobs :recorded-blobs) (reg-audio-data-sub ::media-recorder :media-recorder) (reg-audio-data-sub ::recording? :recording?) (rf/reg-sub ::recording-button-enabled? :<- [::recording?] :<- [::recording-enabled?] (fn [[recording? enabled?] _] (and enabled? (not recording?)))) (rf/reg-sub ::microphone-enabled? :<- [::output-mix] (fn [mix _] (not (nil? mix)))) (cljs-karaoke.subs/reg-attr-sub ::song-stream :song-stream) (cljs-karaoke.subs/reg-attr-sub ::effects-audio-ready? :effects-audio-ready?)
4fdafb919d0840b8445fd830a9f31bb2eaf9cf390e8fccbf18ce25bfdb27d8a1
janestreet/ppx_type_directed_value
type_directed_command.ml
(* $MDX part-begin=of_applicative *) open Ppx_type_directed_value_runtime include Converters.Of_applicative (Core.Command.Param) (* $MDX part-end *)
null
https://raw.githubusercontent.com/janestreet/ppx_type_directed_value/f85693cc6d0ad8a9bc3bad55fed22a3d78e1fcaf/examples/type_directed_command.ml
ocaml
$MDX part-begin=of_applicative $MDX part-end
open Ppx_type_directed_value_runtime include Converters.Of_applicative (Core.Command.Param)
4da9ac611d3a8ab54c0f1758f660785ae47d3ee38fce7f2c864cfd12d04fb8a5
Netflix/PigPen
parquet_test.clj
;; ;; Copyright 2014 - 2015 Netflix , Inc. ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.local.parquet-test (:require [clojure.test :refer :all] [pigpen.local.test-harness :refer [local-harness]] [pigpen.functional-suite :refer [def-functional-tests]] [pigpen.parquet.core-test])) (def prefix "build/functional/local-parquet/") (.mkdirs (java.io.File. prefix)) (def-functional-tests "local-parquet" (local-harness prefix) #{} [pigpen.parquet.core-test/test-load-parquet pigpen.parquet.core-test/test-store-parquet])
null
https://raw.githubusercontent.com/Netflix/PigPen/18d461d9b2ee6c1bb7eee7324889d32757fc7513/pigpen-parquet/src/test/clojure/pigpen/local/parquet_test.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2014 - 2015 Netflix , Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns pigpen.local.parquet-test (:require [clojure.test :refer :all] [pigpen.local.test-harness :refer [local-harness]] [pigpen.functional-suite :refer [def-functional-tests]] [pigpen.parquet.core-test])) (def prefix "build/functional/local-parquet/") (.mkdirs (java.io.File. prefix)) (def-functional-tests "local-parquet" (local-harness prefix) #{} [pigpen.parquet.core-test/test-load-parquet pigpen.parquet.core-test/test-store-parquet])
c74f2de2bb313eb43294f8c8f9462a41831322746830347f0caa2a57eb4e1285
ont-app/igraph-jena
core.clj
(ns ont-app.igraph-jena.core { :clj-kondo/config '{:linters {:unresolved-symbol {:level :off} :unresolved-namespace {:level :off} }} } (:require [clojure.java.io :as io] [ont-app.igraph.core :as igraph :refer [IGraph IGraphMutable add-to-graph get-p-o normal-form match-or-traverse reduce-spo remove-from-graph unique ]] [ont-app.igraph.graph :as native-normal] [ont-app.vocabulary.core :as voc] [ont-app.rdf.core :as rdf] [ont-app.graph-log.levels :refer [trace debug]] [ont-app.vocabulary.lstr] [ont-app.igraph-jena.ont :as ont] ) (:import [ont_app.vocabulary.lstr LangStr] [org.apache.jena.rdf.model.impl LiteralImpl] [org.apache.jena.riot RDFDataMgr RDFFormat ] [org.apache.jena.query Dataset QueryExecution QueryExecutionFactory QueryFactory ] [org.apache.jena.rdf.model Model ModelFactory Resource ResourceFactory ] )) (voc/put-ns-meta! 'ont-app.igraph-jena.core { :voc/mapsTo 'ont-app.igraph-jena.ont } ) TODO remove this when ont - app / rdf issue 8 is fixed (voc/put-ns-meta! 'cognitect.transit { :vann/preferredNamespacePrefix "transit" :vann/preferredNamespaceUri "#" :dc/description "Functionality for the transit serialization format" :foaf/homepage "-format" }) (def ontology "A native-normal graph holding the supporting ontology for igraph-jena" @ont/ontology-atom) (defonce query-template-defaults (merge @rdf/query-template-defaults {:rebind-_s "IRI(?_s)" :rebind-_p "IRI(?_p)" :rebind-_o "IF(isBlank(?_o), IRI(?_o), ?_o)" })) (reset! rdf/query-template-defaults query-template-defaults) ;; TODO: Eplore the trade-offs this way vs. (binding [rdf/query-template-defaults query-template-defaults] (defmethod rdf/render-literal LiteralImpl [elt] (cond (re-find #"langString$" (.getDatatypeURI elt)) (ont-app.vocabulary.lstr/->LangStr (.getLexicalForm elt) (.getLanguage elt)) (= (voc/uri-for :transit/json) (.getDatatypeURI elt)) (rdf/read-transit-json (.lexicalValue (.getValue elt))) :else ;; else it's some other kinda literal (.getValue elt))) (defn interpret-binding-element "Returns a KWI or literal value as appropriate to `elt` Where - `elt` is bound to some variable in a query posed to a jena model." [elt] (trace ::StartingInterpretBindingElement :elt elt) (if (instance? Resource elt) (if-let [uri (.getURI elt)] it 's a URI - ified bnode (keyword "_" (str "<" uri ">")) ;; else it's a regular uri... (voc/keyword-for (str uri))) else it 's a bnode ResourceImpl (keyword "_" (str "<_:" (.getId elt) ">"))) ;; else it's a literal (rdf/render-literal elt))) (defn ask-jena-model "Returns true/false for ASK query `q` posed to Jena model `g`" [g q] (let [qe (-> (QueryFactory/create q) (QueryExecutionFactory/create g))] (try (.execAsk qe) (finally (.close qe))))) (defn query-jena-model "Returns (`binding-map`, ...) for `q` posed to `g` using `query-op` Where - `binding-map` := {`var` `value`, ...} - `q` is a SPARQL query - `g` is a jena model - `query-op` is the jena query operation (optional. defualt is #(.execSelect %) - `var` is a keyword corresponding to a variable in `q` - `value` is an interpretation of the value bound to `var` this will be either a KWI or a literal, as appropriate. " ([g q] (query-jena-model #(.execSelect %) g q)) ([query-op g q] (debug ::StartingQueryJenaModel :g g :q q) (let [qe (-> (QueryFactory/create q) (QueryExecutionFactory/create g))] (try (let [collect-binding-values (fn [b m k] (assoc m (keyword k) (let [v (.get b k)] (interpret-binding-element v)))) render-binding-as-map (fn [b] (reduce (partial collect-binding-values b) {} (iterator-seq (.varNames b)))) bindings (iterator-seq (query-op qe)) ;;(.execSelect qe)) result (doall (map render-binding-as-map bindings)) ] result) (finally (.close qe)))))) (defn create-object-resource-dispatch [g o] [(type g) (type o)]) (defmulti create-object-resource "returns a resource suitable as an object given `g` and `object` - where - `g` is a Jena IGraph - `object` is any argument - dispatched on fn [g obj] -> [(type g) (type obj)] " create-object-resource-dispatch) (defmethod create-object-resource :default [_g object] (ResourceFactory/createTypedLiteral object)) (defn make-statement "Returns a Jena Statment for `s` `p` and `o`" [g s p o] (trace ::starting-make-statement ::g g ::s s ::p p ::o o) (ResourceFactory/createStatement (ResourceFactory/createResource (cond (keyword? s) (voc/uri-for s) (instance? java.net.URI s) (str s) :else (throw (ex-info "Unexpected subject" {:type ::UnexpectedSubject ::s s })))) , (ResourceFactory/createProperty (cond (keyword? p) (voc/uri-for p) (instance? java.net.URI p) (str p) :else (throw (ex-info "Unexpected property" {:type ::UnexpectedProperty ::p p })))) , (create-object-resource g o) )) (defn get-subjects "Returns a sequence of KWIs corresponding to subjects in `jena-model`" [jena-model] (->> (.listSubjects jena-model) (iterator-seq) (map interpret-binding-element) )) (defn- get-normal-form "Returns IGraph normal form representaion of `g`." [g] (rdf/query-for-normal-form query-jena-model g) ) (defn- do-get-p-o "Implements get-p-o for Jena" [g s] (rdf/query-for-p-o query-jena-model g s) ) (defn- do-get-o "Implements get-o for Jena" [g s p] (rdf/query-for-o query-jena-model g s p) ) (defn- do-ask "Implements ask for Jena" [g s p o] Transit data is a special case which is hard ( impossible ? ) to query for with (if (isa? (type o) :rdf-app/TransitData) (-> (do-get-o g s p) (clojure.set/intersection #{o}) (seq) (not)) ;; else this is not transit data (rdf/ask-s-p-o ask-jena-model g s p o) )) (defrecord JenaGraph [model] IGraph (subjects [_] (get-subjects model)) (normal-form [_] (get-normal-form model)) (get-p-o [_ s] (do-get-p-o model s)) (get-o [_ s p] (do-get-o model s p)) (ask [_ s p o] (do-ask model s p o)) (query [_ q] (query-jena-model model q)) (mutability [_] ::igraph/mutable) clojure.lang.IFn (invoke [g] (normal-form g)) (invoke [g s] (get-p-o g s)) (invoke [g s p] (match-or-traverse g s p)) (invoke [g s p o] (match-or-traverse g s p o)) IGraphMutable (add! [g to-add] (add-to-graph g to-add)) (subtract! [g to-subtract] (remove-from-graph g to-subtract)) ) (defmethod print-method JenaGraph [g ^java.io.Writer w] (.write w (format "<JenaGraph hash=%s size=%s>" (hash g) (.size (:model g))))) (defn make-jena-graph "Returns an implementation of igraph using a `model` or a named model in `ds` named `kwi` Where default is a jena default model ) - `ds` is a jena dataset to which we will declare a graph name with `kwi` - `kwi` is a keyword identifier translatable to the URI of a named graph in `ds` " ([] (make-jena-graph (ModelFactory/createDefaultModel))) ([model] (new JenaGraph model)) ([ds kwi] (new JenaGraph (.getNamedModel ds (voc/uri-for kwi))))) (defmethod create-object-resource [JenaGraph clojure.lang.Keyword] [_g kwi] (ResourceFactory/createResource (try (voc/uri-for kwi) (catch clojure.lang.ExceptionInfo e (let [d (ex-data e) ] (case (:type d) ::voc/NoUriDeclaredForPrefix (str kwi) ::voc/NoIRIForKw (str kwi) ;; else it's some other error (throw e))))))) (defmethod create-object-resource [JenaGraph LangStr] [_g lstr] (ResourceFactory/createLangLiteral (str lstr) (.lang lstr))) (defmethod create-object-resource [JenaGraph :rdf-app/TransitData] [g transit-data] (.createTypedLiteral (:model g) (rdf/render-transit-json transit-data) (voc/uri-for :transit/json))) (defmethod add-to-graph [JenaGraph :normal-form] [g to-add] (let [g' (native-normal/make-graph :contents to-add) ] (add-to-graph g ^:vector-of-vectors (reduce-spo (fn [v s p o] (conj v [s p o])) [] g')))) (defmethod add-to-graph [JenaGraph :vector] [g v] {:pre [(odd? (count v)) (>= (count v) 3) ] } (let [collect-triple (fn collect-triple [s g [p o]] (.add (:model g) (make-statement g s p o)) g) ] (reduce (partial collect-triple (first v)) g (partition 2 (rest v))) g)) (defmethod add-to-graph [JenaGraph :underspecified-triple] [g v] (case (count v) 1 (let [[s] v po (g s)] (doseq [p (keys po)] (doseq [o (po p)] (add-to-graph g ^:vector [s p o])))) 2 (let [[s p] v] (doseq [o (g s p)] (add-to-graph ^:vector [s p o]))))) (defmethod add-to-graph [JenaGraph :vector-of-vectors] [g vs] ;; todo: is there a more efficient way to do this? (doseq [v vs] (add-to-graph g ^:vector v)) g) (defmethod remove-from-graph [JenaGraph :normal-form] [g v] (let [g' (native-normal/make-graph :contents v) ] (remove-from-graph g ^:vector-of-vectors (reduce-spo (fn [v s p o] (conj v [s p o])) [] g')))) (defmethod remove-from-graph [JenaGraph :vector] [g to-remove] (let [remove-triple (fn [s p o] (.removeAll (:model g) (ResourceFactory/createResource (voc/uri-for s)) (ResourceFactory/createProperty (voc/uri-for p)) (create-object-resource g o) ) g) ] (if (empty? to-remove) g ;; else there are arguments (let [[s & po-s] to-remove] (assert (even? (count po-s))) (doseq [[p o] (partition 2 po-s)] (remove-triple s p o)) g)))) (defmethod remove-from-graph [JenaGraph :underspecified-triple] [g v] (case (count v) 1 (let [[s] v po (g s)] (doseq [p (keys po)] (doseq [o (po p)] (remove-from-graph g ^:vector [s p o])))) 2 (let [[s p] v] (doseq [o (g s p)] (remove-from-graph g ^:vector [s p o])))) g) (defmethod remove-from-graph [JenaGraph :vector-of-vectors] [g vs] ;; todo: is there a more efficient way to do this? (doseq [v vs] (remove-from-graph g ^:vector v)) g) ;;;;;;;; ;; I/O ;;;;;;;;; (derive JenaGraph :rdf-app/IGraph) (defn derivable-media-types "Returns {child parent, ...} for media types - where - `child` should be declared to derive from `parent`, being subsumed by `:dct/MediaTypeOrExtent` - note - these derivations would inform method dispatch for rdf/write-rdf methods. " [ont] (let [subsumedBy (igraph/traverse-or :rdf/type :rdfs/subClassOf) subsumedBy* (igraph/transitive-closure subsumedBy) media-types (->> (igraph/query ont [[:?media-type subsumedBy* :dct/MediaTypeOrExtent]]) (map :?media-type) (set) ) get-derivable (fn [macc media-type] ;; macc := {child parent, ...} (let [parent (unique (filter media-types (ont media-type subsumedBy))) ] (assoc macc media-type parent))) ] (reduce get-derivable {} media-types ))) ;; Declare derivations for media types for write method dispatch... (doseq [[child parent] (derivable-media-types ontology)] (when parent (derive child parent))) (def standard-io-context "The standard context argument to igraph/rdf i/o methods" (-> @rdf/default-context (igraph/add [[#'rdf/load-rdf :rdf-app/hasGraphDispatch JenaGraph ] [#'rdf/read-rdf :rdf-app/hasGraphDispatch JenaGraph ] [#'rdf/write-rdf :rdf-app/hasGraphDispatch JenaGraph ] ]))) (defn load-rdf "Returns a new graph initialized with `to-load` This is a wrapper around `rdf/load-rdf` with context as `standard-io-context`" [to-load] (rdf/load-rdf standard-io-context to-load)) (defmethod rdf/load-rdf [JenaGraph :rdf-app/LocalFile] [_context rdf-file] (try (make-jena-graph (RDFDataMgr/loadModel (str rdf-file))) (catch Error e (throw (ex-info "Jena riot error" (merge (ex-data e) {:type ::RiotError ::file-name (str rdf-file) })))) )) (defn read-rdf "Side-effect: updates `g` to include contents of `to-read` This is a wrapper around rdf/read-rdf " [g to-read] (rdf/read-rdf standard-io-context g to-read)) (defmethod rdf/read-rdf [JenaGraph :rdf-app/LocalFile] [_context g rdf-file] (.read (:model g) (str rdf-file)) g) ;; output ... (defn write-with-jena-writer "Side-effect: writes contents of `g` to `target` in `fmt` - Where - `g` is a jena igraph - `target` names a file - `fmt` names an RDF format, e.g. 'Turtle' or 'text/turtle' - `base` (optional) isthe base URI of any relative URIs. Default is nil." ([g target fmt] (write-with-jena-writer g target fmt nil)) ([g target fmt base] (with-open [out (io/output-stream target)] (.write (.getWriter (:model g) fmt) (:model g) out (if (keyword? base) (voc/uri-for base) base))))) (defmethod rdf/write-rdf [JenaGraph :rdf-app/LocalFile :dct/MediaTypeOrExtent] [_context g rdf-file fmt] (let [ont-and-catalog (igraph/union @rdf/resource-catalog ontology ) mime-type (unique (ont-and-catalog fmt :formats/media_type)) base (unique (ont-and-catalog rdf-file :rdf-app/baseUri)) ;; ...optional ] (assert mime-type) (write-with-jena-writer g rdf-file mime-type base) )) (defmethod rdf/write-rdf [JenaGraph :rdf-app/LocalFile :riot-format/RiotFormat] [context g rdf-file fmt] ;; pending further research, we'll just use the standard format. (let [media-type (unique (ontology fmt :dcat/mediaType)) ] (assert media-type) ;; ... a URI associated with a mime type string .... (assert (ontology media-type :formats/media_type)) (rdf/write-rdf context g rdf-file media-type)))
null
https://raw.githubusercontent.com/ont-app/igraph-jena/b6ce294bd4b9c9d2db96df227b54b9e961cf43df/src/ont_app/igraph_jena/core.clj
clojure
TODO: Eplore the trade-offs this way vs. (binding [rdf/query-template-defaults query-template-defaults] else it's some other kinda literal else it's a regular uri... else it's a literal (.execSelect qe)) else this is not transit data else it's some other error todo: is there a more efficient way to do this? else there are arguments todo: is there a more efficient way to do this? I/O macc := {child parent, ...} Declare derivations for media types for write method dispatch... output ... ...optional pending further research, we'll just use the standard format. ... a URI associated with a mime type string ....
(ns ont-app.igraph-jena.core { :clj-kondo/config '{:linters {:unresolved-symbol {:level :off} :unresolved-namespace {:level :off} }} } (:require [clojure.java.io :as io] [ont-app.igraph.core :as igraph :refer [IGraph IGraphMutable add-to-graph get-p-o normal-form match-or-traverse reduce-spo remove-from-graph unique ]] [ont-app.igraph.graph :as native-normal] [ont-app.vocabulary.core :as voc] [ont-app.rdf.core :as rdf] [ont-app.graph-log.levels :refer [trace debug]] [ont-app.vocabulary.lstr] [ont-app.igraph-jena.ont :as ont] ) (:import [ont_app.vocabulary.lstr LangStr] [org.apache.jena.rdf.model.impl LiteralImpl] [org.apache.jena.riot RDFDataMgr RDFFormat ] [org.apache.jena.query Dataset QueryExecution QueryExecutionFactory QueryFactory ] [org.apache.jena.rdf.model Model ModelFactory Resource ResourceFactory ] )) (voc/put-ns-meta! 'ont-app.igraph-jena.core { :voc/mapsTo 'ont-app.igraph-jena.ont } ) TODO remove this when ont - app / rdf issue 8 is fixed (voc/put-ns-meta! 'cognitect.transit { :vann/preferredNamespacePrefix "transit" :vann/preferredNamespaceUri "#" :dc/description "Functionality for the transit serialization format" :foaf/homepage "-format" }) (def ontology "A native-normal graph holding the supporting ontology for igraph-jena" @ont/ontology-atom) (defonce query-template-defaults (merge @rdf/query-template-defaults {:rebind-_s "IRI(?_s)" :rebind-_p "IRI(?_p)" :rebind-_o "IF(isBlank(?_o), IRI(?_o), ?_o)" })) (reset! rdf/query-template-defaults query-template-defaults) (defmethod rdf/render-literal LiteralImpl [elt] (cond (re-find #"langString$" (.getDatatypeURI elt)) (ont-app.vocabulary.lstr/->LangStr (.getLexicalForm elt) (.getLanguage elt)) (= (voc/uri-for :transit/json) (.getDatatypeURI elt)) (rdf/read-transit-json (.lexicalValue (.getValue elt))) (.getValue elt))) (defn interpret-binding-element "Returns a KWI or literal value as appropriate to `elt` Where - `elt` is bound to some variable in a query posed to a jena model." [elt] (trace ::StartingInterpretBindingElement :elt elt) (if (instance? Resource elt) (if-let [uri (.getURI elt)] it 's a URI - ified bnode (keyword "_" (str "<" uri ">")) (voc/keyword-for (str uri))) else it 's a bnode ResourceImpl (keyword "_" (str "<_:" (.getId elt) ">"))) (rdf/render-literal elt))) (defn ask-jena-model "Returns true/false for ASK query `q` posed to Jena model `g`" [g q] (let [qe (-> (QueryFactory/create q) (QueryExecutionFactory/create g))] (try (.execAsk qe) (finally (.close qe))))) (defn query-jena-model "Returns (`binding-map`, ...) for `q` posed to `g` using `query-op` Where - `binding-map` := {`var` `value`, ...} - `q` is a SPARQL query - `g` is a jena model - `query-op` is the jena query operation (optional. defualt is #(.execSelect %) - `var` is a keyword corresponding to a variable in `q` - `value` is an interpretation of the value bound to `var` this will be either a KWI or a literal, as appropriate. " ([g q] (query-jena-model #(.execSelect %) g q)) ([query-op g q] (debug ::StartingQueryJenaModel :g g :q q) (let [qe (-> (QueryFactory/create q) (QueryExecutionFactory/create g))] (try (let [collect-binding-values (fn [b m k] (assoc m (keyword k) (let [v (.get b k)] (interpret-binding-element v)))) render-binding-as-map (fn [b] (reduce (partial collect-binding-values b) {} (iterator-seq (.varNames b)))) result (doall (map render-binding-as-map bindings)) ] result) (finally (.close qe)))))) (defn create-object-resource-dispatch [g o] [(type g) (type o)]) (defmulti create-object-resource "returns a resource suitable as an object given `g` and `object` - where - `g` is a Jena IGraph - `object` is any argument - dispatched on fn [g obj] -> [(type g) (type obj)] " create-object-resource-dispatch) (defmethod create-object-resource :default [_g object] (ResourceFactory/createTypedLiteral object)) (defn make-statement "Returns a Jena Statment for `s` `p` and `o`" [g s p o] (trace ::starting-make-statement ::g g ::s s ::p p ::o o) (ResourceFactory/createStatement (ResourceFactory/createResource (cond (keyword? s) (voc/uri-for s) (instance? java.net.URI s) (str s) :else (throw (ex-info "Unexpected subject" {:type ::UnexpectedSubject ::s s })))) , (ResourceFactory/createProperty (cond (keyword? p) (voc/uri-for p) (instance? java.net.URI p) (str p) :else (throw (ex-info "Unexpected property" {:type ::UnexpectedProperty ::p p })))) , (create-object-resource g o) )) (defn get-subjects "Returns a sequence of KWIs corresponding to subjects in `jena-model`" [jena-model] (->> (.listSubjects jena-model) (iterator-seq) (map interpret-binding-element) )) (defn- get-normal-form "Returns IGraph normal form representaion of `g`." [g] (rdf/query-for-normal-form query-jena-model g) ) (defn- do-get-p-o "Implements get-p-o for Jena" [g s] (rdf/query-for-p-o query-jena-model g s) ) (defn- do-get-o "Implements get-o for Jena" [g s p] (rdf/query-for-o query-jena-model g s p) ) (defn- do-ask "Implements ask for Jena" [g s p o] Transit data is a special case which is hard ( impossible ? ) to query for with (if (isa? (type o) :rdf-app/TransitData) (-> (do-get-o g s p) (clojure.set/intersection #{o}) (seq) (not)) (rdf/ask-s-p-o ask-jena-model g s p o) )) (defrecord JenaGraph [model] IGraph (subjects [_] (get-subjects model)) (normal-form [_] (get-normal-form model)) (get-p-o [_ s] (do-get-p-o model s)) (get-o [_ s p] (do-get-o model s p)) (ask [_ s p o] (do-ask model s p o)) (query [_ q] (query-jena-model model q)) (mutability [_] ::igraph/mutable) clojure.lang.IFn (invoke [g] (normal-form g)) (invoke [g s] (get-p-o g s)) (invoke [g s p] (match-or-traverse g s p)) (invoke [g s p o] (match-or-traverse g s p o)) IGraphMutable (add! [g to-add] (add-to-graph g to-add)) (subtract! [g to-subtract] (remove-from-graph g to-subtract)) ) (defmethod print-method JenaGraph [g ^java.io.Writer w] (.write w (format "<JenaGraph hash=%s size=%s>" (hash g) (.size (:model g))))) (defn make-jena-graph "Returns an implementation of igraph using a `model` or a named model in `ds` named `kwi` Where default is a jena default model ) - `ds` is a jena dataset to which we will declare a graph name with `kwi` - `kwi` is a keyword identifier translatable to the URI of a named graph in `ds` " ([] (make-jena-graph (ModelFactory/createDefaultModel))) ([model] (new JenaGraph model)) ([ds kwi] (new JenaGraph (.getNamedModel ds (voc/uri-for kwi))))) (defmethod create-object-resource [JenaGraph clojure.lang.Keyword] [_g kwi] (ResourceFactory/createResource (try (voc/uri-for kwi) (catch clojure.lang.ExceptionInfo e (let [d (ex-data e) ] (case (:type d) ::voc/NoUriDeclaredForPrefix (str kwi) ::voc/NoIRIForKw (str kwi) (throw e))))))) (defmethod create-object-resource [JenaGraph LangStr] [_g lstr] (ResourceFactory/createLangLiteral (str lstr) (.lang lstr))) (defmethod create-object-resource [JenaGraph :rdf-app/TransitData] [g transit-data] (.createTypedLiteral (:model g) (rdf/render-transit-json transit-data) (voc/uri-for :transit/json))) (defmethod add-to-graph [JenaGraph :normal-form] [g to-add] (let [g' (native-normal/make-graph :contents to-add) ] (add-to-graph g ^:vector-of-vectors (reduce-spo (fn [v s p o] (conj v [s p o])) [] g')))) (defmethod add-to-graph [JenaGraph :vector] [g v] {:pre [(odd? (count v)) (>= (count v) 3) ] } (let [collect-triple (fn collect-triple [s g [p o]] (.add (:model g) (make-statement g s p o)) g) ] (reduce (partial collect-triple (first v)) g (partition 2 (rest v))) g)) (defmethod add-to-graph [JenaGraph :underspecified-triple] [g v] (case (count v) 1 (let [[s] v po (g s)] (doseq [p (keys po)] (doseq [o (po p)] (add-to-graph g ^:vector [s p o])))) 2 (let [[s p] v] (doseq [o (g s p)] (add-to-graph ^:vector [s p o]))))) (defmethod add-to-graph [JenaGraph :vector-of-vectors] [g vs] (doseq [v vs] (add-to-graph g ^:vector v)) g) (defmethod remove-from-graph [JenaGraph :normal-form] [g v] (let [g' (native-normal/make-graph :contents v) ] (remove-from-graph g ^:vector-of-vectors (reduce-spo (fn [v s p o] (conj v [s p o])) [] g')))) (defmethod remove-from-graph [JenaGraph :vector] [g to-remove] (let [remove-triple (fn [s p o] (.removeAll (:model g) (ResourceFactory/createResource (voc/uri-for s)) (ResourceFactory/createProperty (voc/uri-for p)) (create-object-resource g o) ) g) ] (if (empty? to-remove) g (let [[s & po-s] to-remove] (assert (even? (count po-s))) (doseq [[p o] (partition 2 po-s)] (remove-triple s p o)) g)))) (defmethod remove-from-graph [JenaGraph :underspecified-triple] [g v] (case (count v) 1 (let [[s] v po (g s)] (doseq [p (keys po)] (doseq [o (po p)] (remove-from-graph g ^:vector [s p o])))) 2 (let [[s p] v] (doseq [o (g s p)] (remove-from-graph g ^:vector [s p o])))) g) (defmethod remove-from-graph [JenaGraph :vector-of-vectors] [g vs] (doseq [v vs] (remove-from-graph g ^:vector v)) g) (derive JenaGraph :rdf-app/IGraph) (defn derivable-media-types "Returns {child parent, ...} for media types - where - `child` should be declared to derive from `parent`, being subsumed by `:dct/MediaTypeOrExtent` - note - these derivations would inform method dispatch for rdf/write-rdf methods. " [ont] (let [subsumedBy (igraph/traverse-or :rdf/type :rdfs/subClassOf) subsumedBy* (igraph/transitive-closure subsumedBy) media-types (->> (igraph/query ont [[:?media-type subsumedBy* :dct/MediaTypeOrExtent]]) (map :?media-type) (set) ) get-derivable (fn [macc media-type] (let [parent (unique (filter media-types (ont media-type subsumedBy))) ] (assoc macc media-type parent))) ] (reduce get-derivable {} media-types ))) (doseq [[child parent] (derivable-media-types ontology)] (when parent (derive child parent))) (def standard-io-context "The standard context argument to igraph/rdf i/o methods" (-> @rdf/default-context (igraph/add [[#'rdf/load-rdf :rdf-app/hasGraphDispatch JenaGraph ] [#'rdf/read-rdf :rdf-app/hasGraphDispatch JenaGraph ] [#'rdf/write-rdf :rdf-app/hasGraphDispatch JenaGraph ] ]))) (defn load-rdf "Returns a new graph initialized with `to-load` This is a wrapper around `rdf/load-rdf` with context as `standard-io-context`" [to-load] (rdf/load-rdf standard-io-context to-load)) (defmethod rdf/load-rdf [JenaGraph :rdf-app/LocalFile] [_context rdf-file] (try (make-jena-graph (RDFDataMgr/loadModel (str rdf-file))) (catch Error e (throw (ex-info "Jena riot error" (merge (ex-data e) {:type ::RiotError ::file-name (str rdf-file) })))) )) (defn read-rdf "Side-effect: updates `g` to include contents of `to-read` This is a wrapper around rdf/read-rdf " [g to-read] (rdf/read-rdf standard-io-context g to-read)) (defmethod rdf/read-rdf [JenaGraph :rdf-app/LocalFile] [_context g rdf-file] (.read (:model g) (str rdf-file)) g) (defn write-with-jena-writer "Side-effect: writes contents of `g` to `target` in `fmt` - Where - `g` is a jena igraph - `target` names a file - `fmt` names an RDF format, e.g. 'Turtle' or 'text/turtle' - `base` (optional) isthe base URI of any relative URIs. Default is nil." ([g target fmt] (write-with-jena-writer g target fmt nil)) ([g target fmt base] (with-open [out (io/output-stream target)] (.write (.getWriter (:model g) fmt) (:model g) out (if (keyword? base) (voc/uri-for base) base))))) (defmethod rdf/write-rdf [JenaGraph :rdf-app/LocalFile :dct/MediaTypeOrExtent] [_context g rdf-file fmt] (let [ont-and-catalog (igraph/union @rdf/resource-catalog ontology ) mime-type (unique (ont-and-catalog fmt :formats/media_type)) base (unique (ont-and-catalog rdf-file :rdf-app/baseUri)) ] (assert mime-type) (write-with-jena-writer g rdf-file mime-type base) )) (defmethod rdf/write-rdf [JenaGraph :rdf-app/LocalFile :riot-format/RiotFormat] [context g rdf-file fmt] (let [media-type (unique (ontology fmt :dcat/mediaType)) ] (assert media-type) (assert (ontology media-type :formats/media_type)) (rdf/write-rdf context g rdf-file media-type)))
551d5c708f87f3961130cc9670fa117fa0d5553aaef9adfdcd8cde05fb0f1acc
lachenmayer/arrowsmith
CrawlPackage.hs
# LANGUAGE FlexibleContexts # module CrawlPackage where import Control.Arrow (second) import Control.Monad.Error (MonadError, MonadIO, catchError, liftIO, throwError) import qualified Data.Map as Map import qualified Data.Maybe as Maybe import System.Directory (doesFileExist, getCurrentDirectory, setCurrentDirectory) import System.FilePath ((</>), (<.>)) import qualified Elm.Compiler as Compiler import qualified Elm.Compiler.Module as Module import qualified Elm.Package.Description as Desc import qualified Elm.Package.Name as Pkg import qualified Elm.Package.Paths as Path import qualified Elm.Package.Solution as Solution import qualified Elm.Package.Version as V import qualified TheMasterPlan as TMP import TheMasterPlan ( PackageSummary(..), PackageData(..) ) -- STATE and ENVIRONMENT data Env = Env { sourceDirs :: [FilePath] , availableForeignModules :: Map.Map Module.Name [(Pkg.Name, V.Version)] } initEnv :: (MonadIO m, MonadError String m) => FilePath -> Desc.Description -> Solution.Solution -> m Env initEnv root desc solution = do availableForeignModules <- readAvailableForeignModules desc solution let sourceDirs = map (root </>) (Desc.sourceDirs desc) return (Env sourceDirs availableForeignModules) GENERIC CRAWLER dfsFromFiles :: (MonadIO m, MonadError String m) => FilePath -> Solution.Solution -> Desc.Description -> [FilePath] -> m ([Module.Name], PackageSummary) dfsFromFiles root solution desc filePaths = do env <- initEnv root desc solution let pkgName = Desc.name desc info <- mapM (readPackageData pkgName Nothing) filePaths let names = map fst info let unvisited = concatMap (snd . snd) info let pkgData = Map.fromList (map (second fst) info) let initialSummary = PackageSummary pkgData Map.empty Map.empty summary <- dfs (Desc.natives desc) pkgName unvisited env initialSummary return (names, summary) dfsFromExposedModules :: (MonadIO m, MonadError String m) => FilePath -> Solution.Solution -> Desc.Description -> m PackageSummary dfsFromExposedModules root solution desc = do env <- initEnv root desc solution let unvisited = addParent Nothing (Desc.exposed desc) let summary = PackageSummary Map.empty Map.empty Map.empty dfs (Desc.natives desc) (Desc.name desc) unvisited env summary -- DEPTH FIRST SEARCH dfs :: (MonadIO m, MonadError String m) => Bool -> Pkg.Name -> [(Module.Name, Maybe Module.Name)] -> Env -> PackageSummary -> m PackageSummary dfs _allowNatives _pkgName [] _env summary = return summary dfs allowNatives pkgName ((name,_) : unvisited) env summary | Map.member name (packageData summary) = dfs allowNatives pkgName unvisited env summary dfs allowNatives pkgName ((name,maybeParent) : unvisited) env summary = do filePaths <- find allowNatives name (sourceDirs env) case (filePaths, Map.lookup name (availableForeignModules env)) of ([Elm filePath], Nothing) -> do (name, (pkgData, newUnvisited)) <- readPackageData pkgName (Just name) filePath dfs allowNatives pkgName (newUnvisited ++ unvisited) env $ summary { packageData = Map.insert name pkgData (packageData summary) } ([JS filePath], Nothing) -> dfs allowNatives pkgName unvisited env $ summary { packageNatives = Map.insert name filePath (packageNatives summary) } ([], Just [pkg]) -> dfs allowNatives pkgName unvisited env $ summary { packageForeignDependencies = Map.insert name pkg (packageForeignDependencies summary) } ([], Nothing) -> throwError (errorNotFound name maybeParent) (_, maybePkgs) -> throwError (errorTooMany name maybeParent filePaths maybePkgs) -- FIND LOCAL FILE PATH data CodePath = Elm FilePath | JS FilePath find :: (MonadIO m) => Bool -> Module.Name -> [FilePath] -> m [CodePath] find allowNatives moduleName sourceDirs = findHelp allowNatives [] moduleName sourceDirs findHelp :: (MonadIO m) => Bool -> [CodePath] -> Module.Name -> [FilePath] -> m [CodePath] findHelp _allowNatives locations _moduleName [] = return locations findHelp allowNatives locations moduleName (dir:srcDirs) = do locations' <- addElmPath locations updatedLocations <- if allowNatives then addJsPath locations' else return locations' findHelp allowNatives updatedLocations moduleName srcDirs where consIf bool x xs = if bool then x:xs else xs addElmPath locs = do let elmPath = dir </> Module.nameToPath moduleName <.> "elm" elmExists <- liftIO (doesFileExist elmPath) return (consIf elmExists (Elm elmPath) locs) addJsPath locs = do let jsPath = dir </> Module.nameToPath moduleName <.> "js" jsExists <- case moduleName of Module.Name ("Native" : _) -> liftIO (doesFileExist jsPath) _ -> return False return (consIf jsExists (JS jsPath) locs) READ and VALIDATE PACKAGE DATA for a file readPackageData :: (MonadIO m, MonadError String m) => Pkg.Name -> Maybe Module.Name -> FilePath -> m (Module.Name, (PackageData, [(Module.Name, Maybe Module.Name)])) readPackageData pkgName maybeName filePath = do source <- liftIO (readFile filePath) (name, rawDeps) <- Compiler.parseDependencies source `catchError` \msg -> throwError (addContext msg) checkName filePath name maybeName let deps = if pkgName == TMP.core then rawDeps else Module.defaultImports ++ rawDeps return (name, (PackageData filePath deps, addParent (Just name) deps)) where addContext msg = "Problem parsing imports in file " ++ filePath ++ " " ++ msg ++ "\n\n" ++ "There is probably a problem with the syntax of your imports. For example,\n" ++ "import syntax was changed a bit from 0.14 to 0.15:\n\n" ++ " 0.14: import Html (..)\n" ++ " 0.15: import Html exposing (..)\n\n" ++ "See <-lang.org/learn/Syntax.elm> for more info.\n\n" checkName :: (MonadError String m) => FilePath -> Module.Name -> Maybe Module.Name -> m () checkName path nameFromSource maybeName = case maybeName of Nothing -> return () Just nameFromPath | nameFromSource == nameFromPath -> return () | otherwise -> throwError (errorNameMismatch path nameFromPath nameFromSource) addParent :: Maybe Module.Name -> [Module.Name] -> [(Module.Name, Maybe Module.Name)] addParent maybeParent names = map (\name -> (name, maybeParent)) names -- FOREIGN MODULES -- which ones are available, who exposes them? readAvailableForeignModules :: (MonadIO m, MonadError String m) => Desc.Description -> Solution.Solution -> m (Map.Map Module.Name [(Pkg.Name, V.Version)]) readAvailableForeignModules desc solution = do visiblePackages <- allVisible desc solution rawLocations <- mapM exposedModules visiblePackages return (Map.unionsWith (++) rawLocations) allVisible :: (MonadError String m) => Desc.Description -> Solution.Solution -> m [(Pkg.Name, V.Version)] allVisible desc solution = mapM getVersion visible where visible = map fst (Desc.dependencies desc) getVersion name = case Map.lookup name solution of Just version -> return (name, version) Nothing -> throwError $ unlines [ "your " ++ Path.description ++ " file says you depend on package " ++ Pkg.toString name ++ "," , "but it looks like it is not properly installed. Try running 'elm-package install'." ] exposedModules :: (MonadIO m, MonadError String m) => (Pkg.Name, V.Version) -> m (Map.Map Module.Name [(Pkg.Name, V.Version)]) exposedModules packageID@(pkgName, version) = within (Path.package pkgName version) $ do description <- Desc.read Path.description let exposed = Desc.exposed description return (foldr insert Map.empty exposed) where insert moduleName dict = Map.insert moduleName [packageID] dict within :: (MonadIO m) => FilePath -> m a -> m a within directory command = do root <- liftIO getCurrentDirectory liftIO (setCurrentDirectory directory) result <- command liftIO (setCurrentDirectory root) return result -- ERROR MESSAGES errorNotFound :: Module.Name -> Maybe Module.Name -> String errorNotFound name maybeParent = unlines [ "Error when searching for modules" ++ context ++ ":" , " Could not find module '" ++ Module.nameToString name ++ "'" , "" , "Potential problems could be:" , " * Misspelled the module name" , " * Need to add a source directory or new dependency to " ++ Path.description ] where context = case maybeParent of Nothing -> " exposed by " ++ Path.description Just parent -> " imported by module '" ++ Module.nameToString parent ++ "'" errorTooMany :: Module.Name -> Maybe Module.Name -> [CodePath] -> Maybe [(Pkg.Name,V.Version)] -> String errorTooMany name maybeParent filePaths maybePkgs = "Error when searching for modules" ++ context ++ ".\n" ++ "Found multiple modules named '" ++ Module.nameToString name ++ "'\n" ++ "Modules with that name were found in the following locations:\n\n" ++ concatMap (\str -> " " ++ str ++ "\n") (paths ++ packages) where context = case maybeParent of Nothing -> " exposed by " ++ Path.description Just parent -> " imported by module '" ++ Module.nameToString parent ++ "'" packages = map ("package " ++) (Maybe.maybe [] (map (Pkg.toString . fst)) maybePkgs) paths = map ("directory " ++) (map extract filePaths) extract codePath = case codePath of Elm path -> path JS path -> path errorNameMismatch :: FilePath -> Module.Name -> Module.Name -> String errorNameMismatch path nameFromPath nameFromSource = unlines [ "The module name is messed up for " ++ path , " According to the file's name it should be " ++ Module.nameToString nameFromPath , " According to the source code it should be " ++ Module.nameToString nameFromSource , "Which is it?" ]
null
https://raw.githubusercontent.com/lachenmayer/arrowsmith/34b6bdeddddb2d8b9c6f41002e87ec65ce8a701a/elm-make/src/CrawlPackage.hs
haskell
STATE and ENVIRONMENT DEPTH FIRST SEARCH FIND LOCAL FILE PATH FOREIGN MODULES -- which ones are available, who exposes them? ERROR MESSAGES
# LANGUAGE FlexibleContexts # module CrawlPackage where import Control.Arrow (second) import Control.Monad.Error (MonadError, MonadIO, catchError, liftIO, throwError) import qualified Data.Map as Map import qualified Data.Maybe as Maybe import System.Directory (doesFileExist, getCurrentDirectory, setCurrentDirectory) import System.FilePath ((</>), (<.>)) import qualified Elm.Compiler as Compiler import qualified Elm.Compiler.Module as Module import qualified Elm.Package.Description as Desc import qualified Elm.Package.Name as Pkg import qualified Elm.Package.Paths as Path import qualified Elm.Package.Solution as Solution import qualified Elm.Package.Version as V import qualified TheMasterPlan as TMP import TheMasterPlan ( PackageSummary(..), PackageData(..) ) data Env = Env { sourceDirs :: [FilePath] , availableForeignModules :: Map.Map Module.Name [(Pkg.Name, V.Version)] } initEnv :: (MonadIO m, MonadError String m) => FilePath -> Desc.Description -> Solution.Solution -> m Env initEnv root desc solution = do availableForeignModules <- readAvailableForeignModules desc solution let sourceDirs = map (root </>) (Desc.sourceDirs desc) return (Env sourceDirs availableForeignModules) GENERIC CRAWLER dfsFromFiles :: (MonadIO m, MonadError String m) => FilePath -> Solution.Solution -> Desc.Description -> [FilePath] -> m ([Module.Name], PackageSummary) dfsFromFiles root solution desc filePaths = do env <- initEnv root desc solution let pkgName = Desc.name desc info <- mapM (readPackageData pkgName Nothing) filePaths let names = map fst info let unvisited = concatMap (snd . snd) info let pkgData = Map.fromList (map (second fst) info) let initialSummary = PackageSummary pkgData Map.empty Map.empty summary <- dfs (Desc.natives desc) pkgName unvisited env initialSummary return (names, summary) dfsFromExposedModules :: (MonadIO m, MonadError String m) => FilePath -> Solution.Solution -> Desc.Description -> m PackageSummary dfsFromExposedModules root solution desc = do env <- initEnv root desc solution let unvisited = addParent Nothing (Desc.exposed desc) let summary = PackageSummary Map.empty Map.empty Map.empty dfs (Desc.natives desc) (Desc.name desc) unvisited env summary dfs :: (MonadIO m, MonadError String m) => Bool -> Pkg.Name -> [(Module.Name, Maybe Module.Name)] -> Env -> PackageSummary -> m PackageSummary dfs _allowNatives _pkgName [] _env summary = return summary dfs allowNatives pkgName ((name,_) : unvisited) env summary | Map.member name (packageData summary) = dfs allowNatives pkgName unvisited env summary dfs allowNatives pkgName ((name,maybeParent) : unvisited) env summary = do filePaths <- find allowNatives name (sourceDirs env) case (filePaths, Map.lookup name (availableForeignModules env)) of ([Elm filePath], Nothing) -> do (name, (pkgData, newUnvisited)) <- readPackageData pkgName (Just name) filePath dfs allowNatives pkgName (newUnvisited ++ unvisited) env $ summary { packageData = Map.insert name pkgData (packageData summary) } ([JS filePath], Nothing) -> dfs allowNatives pkgName unvisited env $ summary { packageNatives = Map.insert name filePath (packageNatives summary) } ([], Just [pkg]) -> dfs allowNatives pkgName unvisited env $ summary { packageForeignDependencies = Map.insert name pkg (packageForeignDependencies summary) } ([], Nothing) -> throwError (errorNotFound name maybeParent) (_, maybePkgs) -> throwError (errorTooMany name maybeParent filePaths maybePkgs) data CodePath = Elm FilePath | JS FilePath find :: (MonadIO m) => Bool -> Module.Name -> [FilePath] -> m [CodePath] find allowNatives moduleName sourceDirs = findHelp allowNatives [] moduleName sourceDirs findHelp :: (MonadIO m) => Bool -> [CodePath] -> Module.Name -> [FilePath] -> m [CodePath] findHelp _allowNatives locations _moduleName [] = return locations findHelp allowNatives locations moduleName (dir:srcDirs) = do locations' <- addElmPath locations updatedLocations <- if allowNatives then addJsPath locations' else return locations' findHelp allowNatives updatedLocations moduleName srcDirs where consIf bool x xs = if bool then x:xs else xs addElmPath locs = do let elmPath = dir </> Module.nameToPath moduleName <.> "elm" elmExists <- liftIO (doesFileExist elmPath) return (consIf elmExists (Elm elmPath) locs) addJsPath locs = do let jsPath = dir </> Module.nameToPath moduleName <.> "js" jsExists <- case moduleName of Module.Name ("Native" : _) -> liftIO (doesFileExist jsPath) _ -> return False return (consIf jsExists (JS jsPath) locs) READ and VALIDATE PACKAGE DATA for a file readPackageData :: (MonadIO m, MonadError String m) => Pkg.Name -> Maybe Module.Name -> FilePath -> m (Module.Name, (PackageData, [(Module.Name, Maybe Module.Name)])) readPackageData pkgName maybeName filePath = do source <- liftIO (readFile filePath) (name, rawDeps) <- Compiler.parseDependencies source `catchError` \msg -> throwError (addContext msg) checkName filePath name maybeName let deps = if pkgName == TMP.core then rawDeps else Module.defaultImports ++ rawDeps return (name, (PackageData filePath deps, addParent (Just name) deps)) where addContext msg = "Problem parsing imports in file " ++ filePath ++ " " ++ msg ++ "\n\n" ++ "There is probably a problem with the syntax of your imports. For example,\n" ++ "import syntax was changed a bit from 0.14 to 0.15:\n\n" ++ " 0.14: import Html (..)\n" ++ " 0.15: import Html exposing (..)\n\n" ++ "See <-lang.org/learn/Syntax.elm> for more info.\n\n" checkName :: (MonadError String m) => FilePath -> Module.Name -> Maybe Module.Name -> m () checkName path nameFromSource maybeName = case maybeName of Nothing -> return () Just nameFromPath | nameFromSource == nameFromPath -> return () | otherwise -> throwError (errorNameMismatch path nameFromPath nameFromSource) addParent :: Maybe Module.Name -> [Module.Name] -> [(Module.Name, Maybe Module.Name)] addParent maybeParent names = map (\name -> (name, maybeParent)) names readAvailableForeignModules :: (MonadIO m, MonadError String m) => Desc.Description -> Solution.Solution -> m (Map.Map Module.Name [(Pkg.Name, V.Version)]) readAvailableForeignModules desc solution = do visiblePackages <- allVisible desc solution rawLocations <- mapM exposedModules visiblePackages return (Map.unionsWith (++) rawLocations) allVisible :: (MonadError String m) => Desc.Description -> Solution.Solution -> m [(Pkg.Name, V.Version)] allVisible desc solution = mapM getVersion visible where visible = map fst (Desc.dependencies desc) getVersion name = case Map.lookup name solution of Just version -> return (name, version) Nothing -> throwError $ unlines [ "your " ++ Path.description ++ " file says you depend on package " ++ Pkg.toString name ++ "," , "but it looks like it is not properly installed. Try running 'elm-package install'." ] exposedModules :: (MonadIO m, MonadError String m) => (Pkg.Name, V.Version) -> m (Map.Map Module.Name [(Pkg.Name, V.Version)]) exposedModules packageID@(pkgName, version) = within (Path.package pkgName version) $ do description <- Desc.read Path.description let exposed = Desc.exposed description return (foldr insert Map.empty exposed) where insert moduleName dict = Map.insert moduleName [packageID] dict within :: (MonadIO m) => FilePath -> m a -> m a within directory command = do root <- liftIO getCurrentDirectory liftIO (setCurrentDirectory directory) result <- command liftIO (setCurrentDirectory root) return result errorNotFound :: Module.Name -> Maybe Module.Name -> String errorNotFound name maybeParent = unlines [ "Error when searching for modules" ++ context ++ ":" , " Could not find module '" ++ Module.nameToString name ++ "'" , "" , "Potential problems could be:" , " * Misspelled the module name" , " * Need to add a source directory or new dependency to " ++ Path.description ] where context = case maybeParent of Nothing -> " exposed by " ++ Path.description Just parent -> " imported by module '" ++ Module.nameToString parent ++ "'" errorTooMany :: Module.Name -> Maybe Module.Name -> [CodePath] -> Maybe [(Pkg.Name,V.Version)] -> String errorTooMany name maybeParent filePaths maybePkgs = "Error when searching for modules" ++ context ++ ".\n" ++ "Found multiple modules named '" ++ Module.nameToString name ++ "'\n" ++ "Modules with that name were found in the following locations:\n\n" ++ concatMap (\str -> " " ++ str ++ "\n") (paths ++ packages) where context = case maybeParent of Nothing -> " exposed by " ++ Path.description Just parent -> " imported by module '" ++ Module.nameToString parent ++ "'" packages = map ("package " ++) (Maybe.maybe [] (map (Pkg.toString . fst)) maybePkgs) paths = map ("directory " ++) (map extract filePaths) extract codePath = case codePath of Elm path -> path JS path -> path errorNameMismatch :: FilePath -> Module.Name -> Module.Name -> String errorNameMismatch path nameFromPath nameFromSource = unlines [ "The module name is messed up for " ++ path , " According to the file's name it should be " ++ Module.nameToString nameFromPath , " According to the source code it should be " ++ Module.nameToString nameFromSource , "Which is it?" ]
71685b2a91c9a04b7c5aef7352bc055f245d27656aa4c4c983b62828a7d08dea
lowasser/TrieMap
Utils.hs
# LANGUAGE TemplateHaskell # module Data.TrieMap.Representation.TH.Utils where import Language.Haskell.TH import Language.Haskell.TH.ExpandSyns decompose :: Type -> (Type, [Type]) decompose (tyfun `AppT` ty) = case decompose tyfun of (tyfun, tys) -> (tyfun, tys ++ [ty]) decompose ty = (ty, []) decompose' :: Type -> Maybe (Name, [Name]) decompose' (tyfun `AppT` VarT ty) = do (tyfun, tys) <- decompose' tyfun return (tyfun, tys ++ [ty]) decompose' (ConT ty) = return (ty, []) decompose' _ = Nothing compose :: Name -> [Name] -> Type compose tyCon tyArgs = foldl AppT (ConT tyCon) (map VarT tyArgs) tyVarBndrVar :: TyVarBndr -> Name tyVarBndrVar (PlainTV tyvar) = tyvar tyVarBndrVar (KindedTV tyvar _) = tyvar tyVarBndrType :: TyVarBndr -> Type tyVarBndrType = VarT . tyVarBndrVar tyProd, tySum :: Type -> Type -> Type tyProd t1 t2 = TupleT 2 `AppT` t1 `AppT` t2 tySum t1 t2 = ConT ''Either `AppT` t1 `AppT` t2 fstExp, sndExp :: Exp -> Exp fstExp (TupE [e, _]) = e fstExp e = VarE 'fst `AppE` e sndExp (TupE [_, e]) = e sndExp e = VarE 'snd `AppE` e leftN, rightN :: Name leftN = 'Left rightN = 'Right leftExp, rightExp :: Exp -> Exp leftExp = AppE (ConE leftN) rightExp = AppE (ConE rightN) fstTy, sndTy :: Type -> Type fstTy (TupleT 2 `AppT` t1 `AppT` _) = t1 fstTy _ = error "Error: not a pair type" sndTy (TupleT 2 `AppT` _ `AppT` t2) = t2 sndTy _ = error "Error: not a pair type" isEnumTy :: Type -> Bool isEnumTy (ConT eith `AppT` t1 `AppT` t2) = eith == ''Either && isEnumTy t1 && isEnumTy t2 isEnumTy (TupleT 0) = True isEnumTy _ = False type AlgCon = (Name, [Type]) algCon :: Con -> AlgCon algCon (NormalC name args) = (name, map snd args) algCon (RecC name args) = (name, [argTy | (_, _, argTy) <- args]) algCon (InfixC (_, ty1) name (_, ty2)) = (name, [ty1, ty2]) algCon _ = error "Error: universally quantified constructors are not algebraic" substInAlgCon :: (Name, Type) -> AlgCon -> AlgCon substInAlgCon sub (conName, args) = (conName, map (substInType sub) args) substInPred :: (Name, Type) -> Pred -> Pred substInPred sub (ClassP cName tys) = ClassP cName (map (substInType sub) tys) substInPred sub (EqualP ty1 ty2) = EqualP (substInType sub ty1) (substInType sub ty2) mergeWith :: (a -> a -> a) -> [a] -> a mergeWith _ [a] = a mergeWith _ [] = error "Error: mergeWith called with empty list" mergeWith f xs = mergeWith f (combine xs) where combine (x1:x2:xs) = f x1 x2:combine xs combine xs = xs
null
https://raw.githubusercontent.com/lowasser/TrieMap/1ab52b8d83469974a629f2aa577a85de3f9e867a/Data/TrieMap/Representation/TH/Utils.hs
haskell
# LANGUAGE TemplateHaskell # module Data.TrieMap.Representation.TH.Utils where import Language.Haskell.TH import Language.Haskell.TH.ExpandSyns decompose :: Type -> (Type, [Type]) decompose (tyfun `AppT` ty) = case decompose tyfun of (tyfun, tys) -> (tyfun, tys ++ [ty]) decompose ty = (ty, []) decompose' :: Type -> Maybe (Name, [Name]) decompose' (tyfun `AppT` VarT ty) = do (tyfun, tys) <- decompose' tyfun return (tyfun, tys ++ [ty]) decompose' (ConT ty) = return (ty, []) decompose' _ = Nothing compose :: Name -> [Name] -> Type compose tyCon tyArgs = foldl AppT (ConT tyCon) (map VarT tyArgs) tyVarBndrVar :: TyVarBndr -> Name tyVarBndrVar (PlainTV tyvar) = tyvar tyVarBndrVar (KindedTV tyvar _) = tyvar tyVarBndrType :: TyVarBndr -> Type tyVarBndrType = VarT . tyVarBndrVar tyProd, tySum :: Type -> Type -> Type tyProd t1 t2 = TupleT 2 `AppT` t1 `AppT` t2 tySum t1 t2 = ConT ''Either `AppT` t1 `AppT` t2 fstExp, sndExp :: Exp -> Exp fstExp (TupE [e, _]) = e fstExp e = VarE 'fst `AppE` e sndExp (TupE [_, e]) = e sndExp e = VarE 'snd `AppE` e leftN, rightN :: Name leftN = 'Left rightN = 'Right leftExp, rightExp :: Exp -> Exp leftExp = AppE (ConE leftN) rightExp = AppE (ConE rightN) fstTy, sndTy :: Type -> Type fstTy (TupleT 2 `AppT` t1 `AppT` _) = t1 fstTy _ = error "Error: not a pair type" sndTy (TupleT 2 `AppT` _ `AppT` t2) = t2 sndTy _ = error "Error: not a pair type" isEnumTy :: Type -> Bool isEnumTy (ConT eith `AppT` t1 `AppT` t2) = eith == ''Either && isEnumTy t1 && isEnumTy t2 isEnumTy (TupleT 0) = True isEnumTy _ = False type AlgCon = (Name, [Type]) algCon :: Con -> AlgCon algCon (NormalC name args) = (name, map snd args) algCon (RecC name args) = (name, [argTy | (_, _, argTy) <- args]) algCon (InfixC (_, ty1) name (_, ty2)) = (name, [ty1, ty2]) algCon _ = error "Error: universally quantified constructors are not algebraic" substInAlgCon :: (Name, Type) -> AlgCon -> AlgCon substInAlgCon sub (conName, args) = (conName, map (substInType sub) args) substInPred :: (Name, Type) -> Pred -> Pred substInPred sub (ClassP cName tys) = ClassP cName (map (substInType sub) tys) substInPred sub (EqualP ty1 ty2) = EqualP (substInType sub ty1) (substInType sub ty2) mergeWith :: (a -> a -> a) -> [a] -> a mergeWith _ [a] = a mergeWith _ [] = error "Error: mergeWith called with empty list" mergeWith f xs = mergeWith f (combine xs) where combine (x1:x2:xs) = f x1 x2:combine xs combine xs = xs
24ad8563887149289c41304792fe7529455e6b55d43c82df8accdcd1ff56949b
aws-beam/aws-erlang
aws_managedblockchain.erl
%% WARNING: DO NOT EDIT, AUTO-GENERATED CODE! See -beam/aws-codegen for more details . %% @doc %% Amazon Managed Blockchain is a fully managed service for creating and %% managing blockchain networks using open-source frameworks. %% %% Blockchain allows you to build applications where multiple parties can %% securely and transparently run transactions and share data without the %% need for a trusted, central authority. %% Managed Blockchain supports the Hyperledger Fabric and Ethereum %% open-source frameworks. Because of fundamental differences between the %% frameworks, some API actions or data types may only apply in the context of one framework and not the other . For example , actions related to Hyperledger Fabric network members such as ` CreateMember ' and ` DeleteMember ' do n't apply to Ethereum . %% %% The description for each action indicates the framework or frameworks to %% which it applies. Data types and properties that apply only in the context %% of a particular framework are similarly indicated. -module(aws_managedblockchain). -export([create_accessor/2, create_accessor/3, create_member/3, create_member/4, create_network/2, create_network/3, create_node/3, create_node/4, create_proposal/3, create_proposal/4, delete_accessor/3, delete_accessor/4, delete_member/4, delete_member/5, delete_node/4, delete_node/5, get_accessor/2, get_accessor/4, get_accessor/5, get_member/3, get_member/5, get_member/6, get_network/2, get_network/4, get_network/5, get_node/3, get_node/5, get_node/6, get_proposal/3, get_proposal/5, get_proposal/6, list_accessors/1, list_accessors/3, list_accessors/4, list_invitations/1, list_invitations/3, list_invitations/4, list_members/2, list_members/4, list_members/5, list_networks/1, list_networks/3, list_networks/4, list_nodes/2, list_nodes/4, list_nodes/5, list_proposal_votes/3, list_proposal_votes/5, list_proposal_votes/6, list_proposals/2, list_proposals/4, list_proposals/5, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, reject_invitation/3, reject_invitation/4, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4, update_member/4, update_member/5, update_node/4, update_node/5, vote_on_proposal/4, vote_on_proposal/5]). -include_lib("hackney/include/hackney_lib.hrl"). %%==================================================================== %% API %%==================================================================== %% @doc Creates a new accessor for use with Managed Blockchain Ethereum %% nodes. %% %% An accessor contains information required for token based access to your %% Ethereum nodes. create_accessor(Client, Input) -> create_accessor(Client, Input, []). create_accessor(Client, Input0, Options0) -> Method = post, Path = ["/accessors"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Creates a member within a Managed Blockchain network. %% Applies only to Hyperledger Fabric . create_member(Client, NetworkId, Input) -> create_member(Client, NetworkId, Input, []). create_member(Client, NetworkId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Creates a new blockchain network using Amazon Managed Blockchain . %% Applies only to Hyperledger Fabric . create_network(Client, Input) -> create_network(Client, Input, []). create_network(Client, Input0, Options0) -> Method = post, Path = ["/networks"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Creates a node on the specified blockchain network. %% Applies to Hyperledger Fabric and Ethereum . create_node(Client, NetworkId, Input) -> create_node(Client, NetworkId, Input, []). create_node(Client, NetworkId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Creates a proposal for a change to the network that other members of %% the network can vote on, for example, a proposal to add a new member to %% the network. %% %% Any member can create a proposal. %% Applies only to Hyperledger Fabric . create_proposal(Client, NetworkId, Input) -> create_proposal(Client, NetworkId, Input, []). create_proposal(Client, NetworkId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Deletes an accessor that your Amazon Web Services account owns . %% %% An accessor object is a container that has the information required for token based access to your Ethereum nodes including , the %% `BILLING_TOKEN'. After an accessor is deleted, the status of the %% accessor changes from `AVAILABLE' to `PENDING_DELETION'. An %% accessor in the `PENDING_DELETION' state can’t be used for new %% WebSocket requests or HTTP requests. However, WebSocket connections that %% were initiated while the accessor was in the `AVAILABLE' state remain open until they expire ( up to 2 hours ) . delete_accessor(Client, AccessorId, Input) -> delete_accessor(Client, AccessorId, Input, []). delete_accessor(Client, AccessorId, Input0, Options0) -> Method = delete, Path = ["/accessors/", aws_util:encode_uri(AccessorId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Deletes a member. %% %% Deleting a member removes the member and all associated resources from the %% network. `DeleteMember' can only be called for a specified ` MemberId ' if the principal performing the action is associated with the Amazon Web Services account that owns the member . In all other cases , the ` DeleteMember ' action is carried out as the result of an approved proposal to remove a member . If ` MemberId ' is the last member in a network specified by the last Amazon Web Services account , the network is %% deleted also. %% Applies only to Hyperledger Fabric . delete_member(Client, MemberId, NetworkId, Input) -> delete_member(Client, MemberId, NetworkId, Input, []). delete_member(Client, MemberId, NetworkId, Input0, Options0) -> Method = delete, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members/", aws_util:encode_uri(MemberId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Deletes a node that your Amazon Web Services account owns . %% %% All data on the node is lost and cannot be recovered. %% Applies to Hyperledger Fabric and Ethereum . delete_node(Client, NetworkId, NodeId, Input) -> delete_node(Client, NetworkId, NodeId, Input, []). delete_node(Client, NetworkId, NodeId, Input0, Options0) -> Method = delete, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes/", aws_util:encode_uri(NodeId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"memberId">>, <<"MemberId">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Returns detailed information about an accessor. %% %% An accessor object is a container that has the information required for %% token based access to your Ethereum nodes. get_accessor(Client, AccessorId) when is_map(Client) -> get_accessor(Client, AccessorId, #{}, #{}). get_accessor(Client, AccessorId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_accessor(Client, AccessorId, QueryMap, HeadersMap, []). get_accessor(Client, AccessorId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/accessors/", aws_util:encode_uri(AccessorId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns detailed information about a member. %% Applies only to Hyperledger Fabric . get_member(Client, MemberId, NetworkId) when is_map(Client) -> get_member(Client, MemberId, NetworkId, #{}, #{}). get_member(Client, MemberId, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_member(Client, MemberId, NetworkId, QueryMap, HeadersMap, []). get_member(Client, MemberId, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members/", aws_util:encode_uri(MemberId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns detailed information about a network. %% Applies to Hyperledger Fabric and Ethereum . get_network(Client, NetworkId) when is_map(Client) -> get_network(Client, NetworkId, #{}, #{}). get_network(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_network(Client, NetworkId, QueryMap, HeadersMap, []). get_network(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns detailed information about a node. %% Applies to Hyperledger Fabric and Ethereum . get_node(Client, NetworkId, NodeId) when is_map(Client) -> get_node(Client, NetworkId, NodeId, #{}, #{}). get_node(Client, NetworkId, NodeId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_node(Client, NetworkId, NodeId, QueryMap, HeadersMap, []). get_node(Client, NetworkId, NodeId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes/", aws_util:encode_uri(NodeId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"memberId">>, maps:get(<<"memberId">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns detailed information about a proposal. %% Applies only to Hyperledger Fabric . get_proposal(Client, NetworkId, ProposalId) when is_map(Client) -> get_proposal(Client, NetworkId, ProposalId, #{}, #{}). get_proposal(Client, NetworkId, ProposalId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_proposal(Client, NetworkId, ProposalId, QueryMap, HeadersMap, []). get_proposal(Client, NetworkId, ProposalId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals/", aws_util:encode_uri(ProposalId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of the accessors and their properties. %% Accessor objects are containers that have the information required for %% token based access to your Ethereum nodes. list_accessors(Client) when is_map(Client) -> list_accessors(Client, #{}, #{}). list_accessors(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_accessors(Client, QueryMap, HeadersMap, []). list_accessors(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/accessors"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Returns a list of all invitations for the current Amazon Web Services %% account. %% Applies only to Hyperledger Fabric . list_invitations(Client) when is_map(Client) -> list_invitations(Client, #{}, #{}). list_invitations(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_invitations(Client, QueryMap, HeadersMap, []). list_invitations(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/invitations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of the members in a network and properties of their %% configurations. %% Applies only to Hyperledger Fabric . list_members(Client, NetworkId) when is_map(Client) -> list_members(Client, NetworkId, #{}, #{}). list_members(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_members(Client, NetworkId, QueryMap, HeadersMap, []). list_members(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"isOwned">>, maps:get(<<"isOwned">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"name">>, maps:get(<<"name">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"status">>, maps:get(<<"status">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Returns information about the networks in which the current Amazon Web Services account participates . %% Applies to Hyperledger Fabric and Ethereum . list_networks(Client) when is_map(Client) -> list_networks(Client, #{}, #{}). list_networks(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_networks(Client, QueryMap, HeadersMap, []). list_networks(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"framework">>, maps:get(<<"framework">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"name">>, maps:get(<<"name">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"status">>, maps:get(<<"status">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns information about the nodes within a network. %% Applies to Hyperledger Fabric and Ethereum . list_nodes(Client, NetworkId) when is_map(Client) -> list_nodes(Client, NetworkId, #{}, #{}). list_nodes(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_nodes(Client, NetworkId, QueryMap, HeadersMap, []). list_nodes(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"memberId">>, maps:get(<<"memberId">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"status">>, maps:get(<<"status">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns the list of votes for a specified proposal, including the %% value of each vote and the unique identifier of the member that cast the %% vote. %% Applies only to Hyperledger Fabric . list_proposal_votes(Client, NetworkId, ProposalId) when is_map(Client) -> list_proposal_votes(Client, NetworkId, ProposalId, #{}, #{}). list_proposal_votes(Client, NetworkId, ProposalId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_proposal_votes(Client, NetworkId, ProposalId, QueryMap, HeadersMap, []). list_proposal_votes(Client, NetworkId, ProposalId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals/", aws_util:encode_uri(ProposalId), "/votes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of proposals for the network. %% Applies only to Hyperledger Fabric . list_proposals(Client, NetworkId) when is_map(Client) -> list_proposals(Client, NetworkId, #{}, #{}). list_proposals(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_proposals(Client, NetworkId, QueryMap, HeadersMap, []). list_proposals(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of tags for the specified resource. %% %% Each tag consists of a key and optional value. %% For more information about tags , see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide , or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide . list_tags_for_resource(Client, ResourceArn) when is_map(Client) -> list_tags_for_resource(Client, ResourceArn, #{}, #{}). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Rejects an invitation to join a network. %% This action can be called by a principal in an Amazon Web Services account %% that has received an invitation to create a member and join a network. %% Applies only to Hyperledger Fabric . reject_invitation(Client, InvitationId, Input) -> reject_invitation(Client, InvitationId, Input, []). reject_invitation(Client, InvitationId, Input0, Options0) -> Method = delete, Path = ["/invitations/", aws_util:encode_uri(InvitationId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Adds or overwrites the specified tags for the specified Amazon %% Managed Blockchain resource. %% %% Each tag consists of a key and optional value. %% %% When you specify a tag key that already exists, the tag value is overwritten with the new value . Use ` UntagResource ' to remove tag %% keys. %% A resource can have up to 50 tags . If you try to create more than 50 tags %% for a resource, your request fails and returns an error. %% For more information about tags , see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide , or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide . tag_resource(Client, ResourceArn, Input) -> tag_resource(Client, ResourceArn, Input, []). tag_resource(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Removes the specified tags from the Amazon Managed Blockchain %% resource. %% For more information about tags , see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide , or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide . untag_resource(Client, ResourceArn, Input) -> untag_resource(Client, ResourceArn, Input, []). untag_resource(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates a member configuration with new parameters. %% Applies only to Hyperledger Fabric . update_member(Client, MemberId, NetworkId, Input) -> update_member(Client, MemberId, NetworkId, Input, []). update_member(Client, MemberId, NetworkId, Input0, Options0) -> Method = patch, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members/", aws_util:encode_uri(MemberId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates a node configuration with new parameters. %% Applies only to Hyperledger Fabric . update_node(Client, NetworkId, NodeId, Input) -> update_node(Client, NetworkId, NodeId, Input, []). update_node(Client, NetworkId, NodeId, Input0, Options0) -> Method = patch, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes/", aws_util:encode_uri(NodeId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Casts a vote for a specified `ProposalId' on behalf of a member. %% %% The member to vote as, specified by `VoterMemberId', must be in the same Amazon Web Services account as the principal that calls the action . %% Applies only to Hyperledger Fabric . vote_on_proposal(Client, NetworkId, ProposalId, Input) -> vote_on_proposal(Client, NetworkId, ProposalId, Input, []). vote_on_proposal(Client, NetworkId, ProposalId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals/", aws_util:encode_uri(ProposalId), "/votes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %%==================================================================== Internal functions %%==================================================================== -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"managedblockchain">>}, Host = build_host(<<"managedblockchain">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
null
https://raw.githubusercontent.com/aws-beam/aws-erlang/ab253bb501fc2e39d4ff902d0f0672a6c68a3a57/src/aws_managedblockchain.erl
erlang
WARNING: DO NOT EDIT, AUTO-GENERATED CODE! @doc managing blockchain networks using open-source frameworks. Blockchain allows you to build applications where multiple parties can securely and transparently run transactions and share data without the need for a trusted, central authority. open-source frameworks. Because of fundamental differences between the frameworks, some API actions or data types may only apply in the context The description for each action indicates the framework or frameworks to which it applies. Data types and properties that apply only in the context of a particular framework are similarly indicated. ==================================================================== API ==================================================================== @doc Creates a new accessor for use with Managed Blockchain Ethereum nodes. An accessor contains information required for token based access to your Ethereum nodes. @doc Creates a member within a Managed Blockchain network. @doc Creates a node on the specified blockchain network. @doc Creates a proposal for a change to the network that other members of the network can vote on, for example, a proposal to add a new member to the network. Any member can create a proposal. An accessor object is a container that has the information required for `BILLING_TOKEN'. After an accessor is deleted, the status of the accessor changes from `AVAILABLE' to `PENDING_DELETION'. An accessor in the `PENDING_DELETION' state can’t be used for new WebSocket requests or HTTP requests. However, WebSocket connections that were initiated while the accessor was in the `AVAILABLE' state remain @doc Deletes a member. Deleting a member removes the member and all associated resources from the network. `DeleteMember' can only be called for a specified deleted also. All data on the node is lost and cannot be recovered. @doc Returns detailed information about an accessor. An accessor object is a container that has the information required for token based access to your Ethereum nodes. @doc Returns detailed information about a member. @doc Returns detailed information about a network. @doc Returns detailed information about a node. @doc Returns detailed information about a proposal. @doc Returns a list of the accessors and their properties. token based access to your Ethereum nodes. account. @doc Returns a list of the members in a network and properties of their configurations. @doc Returns information about the nodes within a network. @doc Returns the list of votes for a specified proposal, including the value of each vote and the unique identifier of the member that cast the vote. @doc Returns a list of proposals for the network. @doc Returns a list of tags for the specified resource. Each tag consists of a key and optional value. @doc Rejects an invitation to join a network. that has received an invitation to create a member and join a network. Managed Blockchain resource. Each tag consists of a key and optional value. When you specify a tag key that already exists, the tag value is keys. for a resource, your request fails and returns an error. resource. @doc Updates a member configuration with new parameters. @doc Updates a node configuration with new parameters. @doc Casts a vote for a specified `ProposalId' on behalf of a member. The member to vote as, specified by `VoterMemberId', must be in the ==================================================================== ====================================================================
See -beam/aws-codegen for more details . Amazon Managed Blockchain is a fully managed service for creating and Managed Blockchain supports the Hyperledger Fabric and Ethereum of one framework and not the other . For example , actions related to Hyperledger Fabric network members such as ` CreateMember ' and ` DeleteMember ' do n't apply to Ethereum . -module(aws_managedblockchain). -export([create_accessor/2, create_accessor/3, create_member/3, create_member/4, create_network/2, create_network/3, create_node/3, create_node/4, create_proposal/3, create_proposal/4, delete_accessor/3, delete_accessor/4, delete_member/4, delete_member/5, delete_node/4, delete_node/5, get_accessor/2, get_accessor/4, get_accessor/5, get_member/3, get_member/5, get_member/6, get_network/2, get_network/4, get_network/5, get_node/3, get_node/5, get_node/6, get_proposal/3, get_proposal/5, get_proposal/6, list_accessors/1, list_accessors/3, list_accessors/4, list_invitations/1, list_invitations/3, list_invitations/4, list_members/2, list_members/4, list_members/5, list_networks/1, list_networks/3, list_networks/4, list_nodes/2, list_nodes/4, list_nodes/5, list_proposal_votes/3, list_proposal_votes/5, list_proposal_votes/6, list_proposals/2, list_proposals/4, list_proposals/5, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, reject_invitation/3, reject_invitation/4, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4, update_member/4, update_member/5, update_node/4, update_node/5, vote_on_proposal/4, vote_on_proposal/5]). -include_lib("hackney/include/hackney_lib.hrl"). create_accessor(Client, Input) -> create_accessor(Client, Input, []). create_accessor(Client, Input0, Options0) -> Method = post, Path = ["/accessors"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . create_member(Client, NetworkId, Input) -> create_member(Client, NetworkId, Input, []). create_member(Client, NetworkId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Creates a new blockchain network using Amazon Managed Blockchain . Applies only to Hyperledger Fabric . create_network(Client, Input) -> create_network(Client, Input, []). create_network(Client, Input0, Options0) -> Method = post, Path = ["/networks"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Applies to Hyperledger Fabric and Ethereum . create_node(Client, NetworkId, Input) -> create_node(Client, NetworkId, Input, []). create_node(Client, NetworkId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . create_proposal(Client, NetworkId, Input) -> create_proposal(Client, NetworkId, Input, []). create_proposal(Client, NetworkId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Deletes an accessor that your Amazon Web Services account owns . token based access to your Ethereum nodes including , the open until they expire ( up to 2 hours ) . delete_accessor(Client, AccessorId, Input) -> delete_accessor(Client, AccessorId, Input, []). delete_accessor(Client, AccessorId, Input0, Options0) -> Method = delete, Path = ["/accessors/", aws_util:encode_uri(AccessorId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). ` MemberId ' if the principal performing the action is associated with the Amazon Web Services account that owns the member . In all other cases , the ` DeleteMember ' action is carried out as the result of an approved proposal to remove a member . If ` MemberId ' is the last member in a network specified by the last Amazon Web Services account , the network is Applies only to Hyperledger Fabric . delete_member(Client, MemberId, NetworkId, Input) -> delete_member(Client, MemberId, NetworkId, Input, []). delete_member(Client, MemberId, NetworkId, Input0, Options0) -> Method = delete, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members/", aws_util:encode_uri(MemberId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Deletes a node that your Amazon Web Services account owns . Applies to Hyperledger Fabric and Ethereum . delete_node(Client, NetworkId, NodeId, Input) -> delete_node(Client, NetworkId, NodeId, Input, []). delete_node(Client, NetworkId, NodeId, Input0, Options0) -> Method = delete, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes/", aws_util:encode_uri(NodeId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"memberId">>, <<"MemberId">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). get_accessor(Client, AccessorId) when is_map(Client) -> get_accessor(Client, AccessorId, #{}, #{}). get_accessor(Client, AccessorId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_accessor(Client, AccessorId, QueryMap, HeadersMap, []). get_accessor(Client, AccessorId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/accessors/", aws_util:encode_uri(AccessorId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . get_member(Client, MemberId, NetworkId) when is_map(Client) -> get_member(Client, MemberId, NetworkId, #{}, #{}). get_member(Client, MemberId, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_member(Client, MemberId, NetworkId, QueryMap, HeadersMap, []). get_member(Client, MemberId, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members/", aws_util:encode_uri(MemberId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies to Hyperledger Fabric and Ethereum . get_network(Client, NetworkId) when is_map(Client) -> get_network(Client, NetworkId, #{}, #{}). get_network(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_network(Client, NetworkId, QueryMap, HeadersMap, []). get_network(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies to Hyperledger Fabric and Ethereum . get_node(Client, NetworkId, NodeId) when is_map(Client) -> get_node(Client, NetworkId, NodeId, #{}, #{}). get_node(Client, NetworkId, NodeId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_node(Client, NetworkId, NodeId, QueryMap, HeadersMap, []). get_node(Client, NetworkId, NodeId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes/", aws_util:encode_uri(NodeId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"memberId">>, maps:get(<<"memberId">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . get_proposal(Client, NetworkId, ProposalId) when is_map(Client) -> get_proposal(Client, NetworkId, ProposalId, #{}, #{}). get_proposal(Client, NetworkId, ProposalId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_proposal(Client, NetworkId, ProposalId, QueryMap, HeadersMap, []). get_proposal(Client, NetworkId, ProposalId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals/", aws_util:encode_uri(ProposalId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Accessor objects are containers that have the information required for list_accessors(Client) when is_map(Client) -> list_accessors(Client, #{}, #{}). list_accessors(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_accessors(Client, QueryMap, HeadersMap, []). list_accessors(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/accessors"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Returns a list of all invitations for the current Amazon Web Services Applies only to Hyperledger Fabric . list_invitations(Client) when is_map(Client) -> list_invitations(Client, #{}, #{}). list_invitations(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_invitations(Client, QueryMap, HeadersMap, []). list_invitations(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/invitations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . list_members(Client, NetworkId) when is_map(Client) -> list_members(Client, NetworkId, #{}, #{}). list_members(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_members(Client, NetworkId, QueryMap, HeadersMap, []). list_members(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"isOwned">>, maps:get(<<"isOwned">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"name">>, maps:get(<<"name">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"status">>, maps:get(<<"status">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Returns information about the networks in which the current Amazon Web Services account participates . Applies to Hyperledger Fabric and Ethereum . list_networks(Client) when is_map(Client) -> list_networks(Client, #{}, #{}). list_networks(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_networks(Client, QueryMap, HeadersMap, []). list_networks(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"framework">>, maps:get(<<"framework">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"name">>, maps:get(<<"name">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"status">>, maps:get(<<"status">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies to Hyperledger Fabric and Ethereum . list_nodes(Client, NetworkId) when is_map(Client) -> list_nodes(Client, NetworkId, #{}, #{}). list_nodes(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_nodes(Client, NetworkId, QueryMap, HeadersMap, []). list_nodes(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"memberId">>, maps:get(<<"memberId">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"status">>, maps:get(<<"status">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . list_proposal_votes(Client, NetworkId, ProposalId) when is_map(Client) -> list_proposal_votes(Client, NetworkId, ProposalId, #{}, #{}). list_proposal_votes(Client, NetworkId, ProposalId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_proposal_votes(Client, NetworkId, ProposalId, QueryMap, HeadersMap, []). list_proposal_votes(Client, NetworkId, ProposalId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals/", aws_util:encode_uri(ProposalId), "/votes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . list_proposals(Client, NetworkId) when is_map(Client) -> list_proposals(Client, NetworkId, #{}, #{}). list_proposals(Client, NetworkId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_proposals(Client, NetworkId, QueryMap, HeadersMap, []). list_proposals(Client, NetworkId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). For more information about tags , see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide , or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide . list_tags_for_resource(Client, ResourceArn) when is_map(Client) -> list_tags_for_resource(Client, ResourceArn, #{}, #{}). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). This action can be called by a principal in an Amazon Web Services account Applies only to Hyperledger Fabric . reject_invitation(Client, InvitationId, Input) -> reject_invitation(Client, InvitationId, Input, []). reject_invitation(Client, InvitationId, Input0, Options0) -> Method = delete, Path = ["/invitations/", aws_util:encode_uri(InvitationId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Adds or overwrites the specified tags for the specified Amazon overwritten with the new value . Use ` UntagResource ' to remove tag A resource can have up to 50 tags . If you try to create more than 50 tags For more information about tags , see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide , or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide . tag_resource(Client, ResourceArn, Input) -> tag_resource(Client, ResourceArn, Input, []). tag_resource(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Removes the specified tags from the Amazon Managed Blockchain For more information about tags , see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide , or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide . untag_resource(Client, ResourceArn, Input) -> untag_resource(Client, ResourceArn, Input, []). untag_resource(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . update_member(Client, MemberId, NetworkId, Input) -> update_member(Client, MemberId, NetworkId, Input, []). update_member(Client, MemberId, NetworkId, Input0, Options0) -> Method = patch, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/members/", aws_util:encode_uri(MemberId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Applies only to Hyperledger Fabric . update_node(Client, NetworkId, NodeId, Input) -> update_node(Client, NetworkId, NodeId, Input, []). update_node(Client, NetworkId, NodeId, Input0, Options0) -> Method = patch, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/nodes/", aws_util:encode_uri(NodeId), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). same Amazon Web Services account as the principal that calls the action . Applies only to Hyperledger Fabric . vote_on_proposal(Client, NetworkId, ProposalId, Input) -> vote_on_proposal(Client, NetworkId, ProposalId, Input, []). vote_on_proposal(Client, NetworkId, ProposalId, Input0, Options0) -> Method = post, Path = ["/networks/", aws_util:encode_uri(NetworkId), "/proposals/", aws_util:encode_uri(ProposalId), "/votes"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Internal functions -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"managedblockchain">>}, Host = build_host(<<"managedblockchain">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
db0985987ce27bd899a553efbbc32663edcd3cb769468f878c2757b2233bf628
codinuum/volt
logger.ml
* This file is part of Bolt . * Copyright ( C ) 2009 - 2012 . * * Bolt is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation ; either version 3 of the License , or * ( at your option ) any later version . * * Bolt is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program . If not , see < / > . * This file is part of Bolt. * Copyright (C) 2009-2012 Xavier Clerc. * * Bolt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Bolt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see </>. *) let register_logger normalized_name level filter pass layout mode output (output_name, output_rotate) = let layout = lazy (try Layout.get layout with Not_found -> Layout.default) in let output = lazy (try (Output.get output) output_name output_rotate layout with Not_found -> Output.void output_name output_rotate layout) in let infos = { Tree.name = normalized_name; level; filter; pass; layout; mode; output; } in Tree.register_logger infos let register name level filter pass layout mode output output_params = let normalized_name = Name.of_string name in let filter = lazy (try Filter.get filter with Not_found -> Filter.all) in let pass = lazy (try Filter.get pass with Not_found -> Filter.all) in register_logger normalized_name level filter pass layout mode output output_params let log_event name level file line column properties error msg = let orig_event = Event.make name level ~file:file ~line:line ~column:column ~properties:properties ~error:error msg in let loggers = Tree.get_loggers name in try List.iter (fun (nam, lst) -> let event = Event.with_logger nam orig_event in List.iter (fun logger -> try let _, _, layout = Lazy.force logger.Tree.layout in let mode = logger.Tree.mode in let output = Lazy.force logger.Tree.output in let filter = Lazy.force logger.Tree.filter in let pass = Lazy.force logger.Tree.pass in if (level <= logger.Tree.level) && (filter event) then mode#deliver output (layout event); if not (pass event) then raise Exit with Exit -> raise Exit | _ -> ()) lst) loggers with Exit -> () let check_level name level = (* Printf.fprintf stderr "check_level: \"%s\" %s\n" name (Level.to_string level); *) let name = Name.of_string name in let loggers = Tree.get_loggers name in try List.iter (fun (_, lst) -> if List.exists (fun logger -> level <= logger.Tree.level) lst then raise Exit ) loggers; false with Exit -> true let logf name level ?(file="") ?(line=(-1)) ?(column=(-1)) ?(properties=[]) ?(error=None) fmt = let f msg = let name = Name.of_string name in log_event name level file line column properties error msg in Printf.ksprintf f fmt let log name level ?(file="") ?(line=(-1)) ?(column=(-1)) ?(properties=[]) ?(error=None) msg = let name = Name.of_string name in log_event name level file line column properties error msg let prepare name = let name = Name.of_string name in Tree.make_node name let configuration = let get_from_env () = try (Sys.getenv "BOLT_CONFIG"), ConfigurationNew.load with _ -> (Sys.getenv "BOLT_FILE"), ConfigurationOld.load in try let file, func = get_from_env () in Some (func file) with | Not_found -> None | Configuration.Exception (line, err) -> let msg = Printf.sprintf "syntax error in configuration file at line %d:\n %s" line err in Utils.verbose msg; None | _ -> Utils.verbose "unable to load configuration"; None let () = try let plugins_env = Sys.getenv "BOLT_PLUGINS" in let plugins_list = Utils.split "," plugins_env in let plugins_list = List.map Utils.trim plugins_list in List.iter Dynlink.loadfile_private plugins_list with _ -> () let () = let used_signals = Array.make Signal.max_int false in let read_lines file = try let ch = open_in file in let res = ref [] in (try while true do res := (input_line ch) :: !res done with End_of_file -> ()); List.rev !res with _ -> [] in let rec make_filter = function | Configuration.Identifier s | Configuration.String s -> lazy (try Filter.get s with Not_found -> Filter.all) | Configuration.Integer _ | Configuration.Float _ -> lazy Filter.all | Configuration.And (v1, v2) -> let f1 = make_filter v1 in let f2 = make_filter v2 in lazy (fun e -> ((Lazy.force f1) e) && ((Lazy.force f2) e)) | Configuration.Or (v1, v2) -> let f1 = make_filter v1 in let f2 = make_filter v2 in lazy (fun e -> ((Lazy.force f1) e) || ((Lazy.force f2) e)) in match configuration with | Some conf -> List.iter (fun section -> let assoc x = List.assoc x section.Configuration.elements in let assoc_string x = try match List.assoc x section.Configuration.elements with | Configuration.Identifier s | Configuration.String s -> Some s | _ -> None with _ -> None in let level = try match assoc_string "level" with | Some s -> Level.of_string s | None -> Level.FATAL with _ -> Level.FATAL in let filter = try match assoc "filter" with | Configuration.Identifier s | Configuration.String s -> lazy (try Filter.get s with Not_found -> Filter.all) | f -> make_filter f with _ -> lazy Filter.all in let pass = try match assoc "pass" with | Configuration.Identifier s | Configuration.String s -> lazy (try Filter.get s with Not_found -> Filter.all) | f -> make_filter f with _ -> lazy Filter.all in let layout = try match assoc "layout" with | Configuration.Identifier "pattern" | Configuration.String "pattern" -> let header = try match assoc_string "pattern-header-file" with | Some s -> read_lines s | None -> [] with _ -> [] in let footer = try match assoc_string "pattern-footer-file" with | Some s -> read_lines s | _ -> [] with _ -> [] in let pattern = match assoc_string "pattern" with | Some s -> s | None -> "" in Layout.register_unnamed (Layout.pattern header footer pattern) | Configuration.Identifier "csv" | Configuration.String "csv" -> let sep = match assoc_string "csv-separator" with | Some s -> s | None -> ";" in let list = match assoc_string "csv-elements" with | Some s -> s | None -> "" in let elems = Utils.split " \t" list in Layout.register_unnamed (Layout.csv sep elems) | Configuration.Identifier s | Configuration.String s -> s | _ -> "default" with _ -> "default" in let mode = try match assoc "mode" with | Configuration.Identifier "direct" | Configuration.String "direct" -> Mode.direct () | Configuration.Identifier "memory" | Configuration.String "memory" -> Mode.memory () | Configuration.Identifier "retained" | Configuration.String "retained" -> Mode.retained (match assoc_string "retention" with | Some s -> s | None -> "") | _ -> Mode.direct () with _ -> Mode.direct () in let output = match assoc_string "output" with | Some s -> s | None -> "file" in let name = match assoc_string "name" with | Some s -> s | None -> "<stderr>" in let seconds = try match assoc "rotate" with | Configuration.Integer i -> Some (float_of_int i) | Configuration.Float f -> Some f | Configuration.Identifier s | Configuration.String s -> Some (float_of_string s) | _ -> None with _ -> None in let signal = try match assoc_string "signal" with | Some s -> let s = Signal.of_string s in used_signals.(Signal.to_int s) <- true; Some s | None -> None with _ -> None in let rotate = { Output.seconds_elapsed = seconds; Output.signal_caught = signal; } in register_logger section.Configuration.name level filter pass layout mode output (name, rotate)) conf; Array.iteri (fun i v -> let handler _ = Output.signals.(i) <- true in let s = Signal.to_sys (Signal.of_int i) in if v then Sys.set_signal s (Sys.Signal_handle handler)) used_signals | None -> ()
null
https://raw.githubusercontent.com/codinuum/volt/546207693ef102a2f02c85af935f64a8f16882e6/src/library/logger.ml
ocaml
Printf.fprintf stderr "check_level: \"%s\" %s\n" name (Level.to_string level);
* This file is part of Bolt . * Copyright ( C ) 2009 - 2012 . * * Bolt is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation ; either version 3 of the License , or * ( at your option ) any later version . * * Bolt is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program . If not , see < / > . * This file is part of Bolt. * Copyright (C) 2009-2012 Xavier Clerc. * * Bolt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Bolt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see </>. *) let register_logger normalized_name level filter pass layout mode output (output_name, output_rotate) = let layout = lazy (try Layout.get layout with Not_found -> Layout.default) in let output = lazy (try (Output.get output) output_name output_rotate layout with Not_found -> Output.void output_name output_rotate layout) in let infos = { Tree.name = normalized_name; level; filter; pass; layout; mode; output; } in Tree.register_logger infos let register name level filter pass layout mode output output_params = let normalized_name = Name.of_string name in let filter = lazy (try Filter.get filter with Not_found -> Filter.all) in let pass = lazy (try Filter.get pass with Not_found -> Filter.all) in register_logger normalized_name level filter pass layout mode output output_params let log_event name level file line column properties error msg = let orig_event = Event.make name level ~file:file ~line:line ~column:column ~properties:properties ~error:error msg in let loggers = Tree.get_loggers name in try List.iter (fun (nam, lst) -> let event = Event.with_logger nam orig_event in List.iter (fun logger -> try let _, _, layout = Lazy.force logger.Tree.layout in let mode = logger.Tree.mode in let output = Lazy.force logger.Tree.output in let filter = Lazy.force logger.Tree.filter in let pass = Lazy.force logger.Tree.pass in if (level <= logger.Tree.level) && (filter event) then mode#deliver output (layout event); if not (pass event) then raise Exit with Exit -> raise Exit | _ -> ()) lst) loggers with Exit -> () let check_level name level = let name = Name.of_string name in let loggers = Tree.get_loggers name in try List.iter (fun (_, lst) -> if List.exists (fun logger -> level <= logger.Tree.level) lst then raise Exit ) loggers; false with Exit -> true let logf name level ?(file="") ?(line=(-1)) ?(column=(-1)) ?(properties=[]) ?(error=None) fmt = let f msg = let name = Name.of_string name in log_event name level file line column properties error msg in Printf.ksprintf f fmt let log name level ?(file="") ?(line=(-1)) ?(column=(-1)) ?(properties=[]) ?(error=None) msg = let name = Name.of_string name in log_event name level file line column properties error msg let prepare name = let name = Name.of_string name in Tree.make_node name let configuration = let get_from_env () = try (Sys.getenv "BOLT_CONFIG"), ConfigurationNew.load with _ -> (Sys.getenv "BOLT_FILE"), ConfigurationOld.load in try let file, func = get_from_env () in Some (func file) with | Not_found -> None | Configuration.Exception (line, err) -> let msg = Printf.sprintf "syntax error in configuration file at line %d:\n %s" line err in Utils.verbose msg; None | _ -> Utils.verbose "unable to load configuration"; None let () = try let plugins_env = Sys.getenv "BOLT_PLUGINS" in let plugins_list = Utils.split "," plugins_env in let plugins_list = List.map Utils.trim plugins_list in List.iter Dynlink.loadfile_private plugins_list with _ -> () let () = let used_signals = Array.make Signal.max_int false in let read_lines file = try let ch = open_in file in let res = ref [] in (try while true do res := (input_line ch) :: !res done with End_of_file -> ()); List.rev !res with _ -> [] in let rec make_filter = function | Configuration.Identifier s | Configuration.String s -> lazy (try Filter.get s with Not_found -> Filter.all) | Configuration.Integer _ | Configuration.Float _ -> lazy Filter.all | Configuration.And (v1, v2) -> let f1 = make_filter v1 in let f2 = make_filter v2 in lazy (fun e -> ((Lazy.force f1) e) && ((Lazy.force f2) e)) | Configuration.Or (v1, v2) -> let f1 = make_filter v1 in let f2 = make_filter v2 in lazy (fun e -> ((Lazy.force f1) e) || ((Lazy.force f2) e)) in match configuration with | Some conf -> List.iter (fun section -> let assoc x = List.assoc x section.Configuration.elements in let assoc_string x = try match List.assoc x section.Configuration.elements with | Configuration.Identifier s | Configuration.String s -> Some s | _ -> None with _ -> None in let level = try match assoc_string "level" with | Some s -> Level.of_string s | None -> Level.FATAL with _ -> Level.FATAL in let filter = try match assoc "filter" with | Configuration.Identifier s | Configuration.String s -> lazy (try Filter.get s with Not_found -> Filter.all) | f -> make_filter f with _ -> lazy Filter.all in let pass = try match assoc "pass" with | Configuration.Identifier s | Configuration.String s -> lazy (try Filter.get s with Not_found -> Filter.all) | f -> make_filter f with _ -> lazy Filter.all in let layout = try match assoc "layout" with | Configuration.Identifier "pattern" | Configuration.String "pattern" -> let header = try match assoc_string "pattern-header-file" with | Some s -> read_lines s | None -> [] with _ -> [] in let footer = try match assoc_string "pattern-footer-file" with | Some s -> read_lines s | _ -> [] with _ -> [] in let pattern = match assoc_string "pattern" with | Some s -> s | None -> "" in Layout.register_unnamed (Layout.pattern header footer pattern) | Configuration.Identifier "csv" | Configuration.String "csv" -> let sep = match assoc_string "csv-separator" with | Some s -> s | None -> ";" in let list = match assoc_string "csv-elements" with | Some s -> s | None -> "" in let elems = Utils.split " \t" list in Layout.register_unnamed (Layout.csv sep elems) | Configuration.Identifier s | Configuration.String s -> s | _ -> "default" with _ -> "default" in let mode = try match assoc "mode" with | Configuration.Identifier "direct" | Configuration.String "direct" -> Mode.direct () | Configuration.Identifier "memory" | Configuration.String "memory" -> Mode.memory () | Configuration.Identifier "retained" | Configuration.String "retained" -> Mode.retained (match assoc_string "retention" with | Some s -> s | None -> "") | _ -> Mode.direct () with _ -> Mode.direct () in let output = match assoc_string "output" with | Some s -> s | None -> "file" in let name = match assoc_string "name" with | Some s -> s | None -> "<stderr>" in let seconds = try match assoc "rotate" with | Configuration.Integer i -> Some (float_of_int i) | Configuration.Float f -> Some f | Configuration.Identifier s | Configuration.String s -> Some (float_of_string s) | _ -> None with _ -> None in let signal = try match assoc_string "signal" with | Some s -> let s = Signal.of_string s in used_signals.(Signal.to_int s) <- true; Some s | None -> None with _ -> None in let rotate = { Output.seconds_elapsed = seconds; Output.signal_caught = signal; } in register_logger section.Configuration.name level filter pass layout mode output (name, rotate)) conf; Array.iteri (fun i v -> let handler _ = Output.signals.(i) <- true in let s = Signal.to_sys (Signal.of_int i) in if v then Sys.set_signal s (Sys.Signal_handle handler)) used_signals | None -> ()
8c3bd8d82a885e1f2f262ec85cabdcd09ed9044ef90caa261ca9d5adfc6d87a4
jeffshrager/biobike
reload-gene.lisp
-*- Package : bio ; mode : lisp ; base : 10 ; Syntax : Common - Lisp ; -*- (in-package :bio) ;;; +=========================================================================+ | Copyright ( c ) 2011 JP Massar | ;;; | | ;;; | Permission is hereby granted, free of charge, to any person obtaining | ;;; | a copy of this software and associated documentation files (the | | " Software " ) , to deal in the Software without restriction , including | ;;; | without limitation the rights to use, copy, modify, merge, publish, | | distribute , sublicense , and/or sell copies of the Software , and to | | permit persons to whom the Software is furnished to do so , subject to | ;;; | the following conditions: | ;;; | | ;;; | The above copyright notice and this permission notice shall be included | | in all copies or substantial portions of the Software . | ;;; | | | THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , | ;;; | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ;;; | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ;;; | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | | CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , | ;;; | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | ;;; | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ;;; +=========================================================================+ ;;; Author: JP Massar (defun sync-seed-gene (seed-id &key (commit? t)) (declare (ignorable commit?)) (block exit ;; We've been asked to reload information for a seed gene with id = seed-id First determine whether that gene exists in biobike . (multiple-value-bind (gene-frame orgf error) (seed-id->frame seed-id) (declare (ignore error)) ;; It's possible that while the gene doesn't exist, the organism ;; it belongs to exists but is not currently loaded. If so, ;; load the organism, and that should load the gene with the ;; new information. (when orgf (unless (#^organism-loaded? orgf) (load-organism orgf) (return-from exit (seed-id->frame seed-id)))) This seed - id is not known at all to Biobike . It might ;; be a valid gene in the seed but if the organism it belongs to is not in the master list Biobike wo n't know about it . (unless gene-frame (return-from exit (values nil "No frame to update!"))) ;; any change in the subsystem role will be reflected ;; in the standard seed database in the assigned_functions table. (let ((new-subsystem-role (mysql-get-description-for-peg seed-id))) (setf (#^subsystem-role gene-frame) new-subsystem-role)) (let* ((in-data (fids-to-mysql-in-format (list seed-id)))) (flet ((sync-category (category-type slot) (let* ((records (mysql-get-categories-info-by-type in-data category-type )) (last-record (lastelem (sort records 'string-lessp :key 'categories-timestamp )))) (when last-record (let ((new-annotation (categories-annotation last-record))) (setf (slotv gene-frame slot) new-annotation) ))))) (sync-category "ANN" #$description) (sync-category "GEN" #$genetic-name) )) We 're done . Commit the change permanently to acache . #-:lispworks (when commit? (db.ac::commit)) (values gene-frame nil) ))) (defun retrieve-gene-info-from-seed-database (seed-id orgf) ;; All the information we retrieve gets stored as a property list ;; in the *features-info-hash* hash table using the seed-id as sole key. (multiple-value-bind (features-data column-names) (seed-gene-info-for-seed-id seed-id) ;; Get all the information from the features table (process-features-info-msf features-data column-names) ;; Get the description data for this gene from the assigned_functions table (set-feature-item seed-id :description (mysql-get-description-for-peg seed-id)) ;; Get the annotation history for this gene. (let* ((annotations-hash (get-seed-info-for-annotations (#^seed-id orgf))) (annotation-history (gethash seed-id annotations-hash))) (set-feature-item seed-id :annotation annotation-history) )))
null
https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/seedorgs/reload-gene.lisp
lisp
mode : lisp ; base : 10 ; Syntax : Common - Lisp ; -*- +=========================================================================+ | | | Permission is hereby granted, free of charge, to any person obtaining | | a copy of this software and associated documentation files (the | | without limitation the rights to use, copy, modify, merge, publish, | | the following conditions: | | | | The above copyright notice and this permission notice shall be included | | | | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | +=========================================================================+ Author: JP Massar We've been asked to reload information for a seed gene with id = seed-id It's possible that while the gene doesn't exist, the organism it belongs to exists but is not currently loaded. If so, load the organism, and that should load the gene with the new information. be a valid gene in the seed but if the organism it belongs to any change in the subsystem role will be reflected in the standard seed database in the assigned_functions table. All the information we retrieve gets stored as a property list in the *features-info-hash* hash table using the seed-id as sole key. Get all the information from the features table Get the description data for this gene from the assigned_functions table Get the annotation history for this gene.
(in-package :bio) | Copyright ( c ) 2011 JP Massar | | " Software " ) , to deal in the Software without restriction , including | | distribute , sublicense , and/or sell copies of the Software , and to | | permit persons to whom the Software is furnished to do so , subject to | | in all copies or substantial portions of the Software . | | THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , | | CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , | (defun sync-seed-gene (seed-id &key (commit? t)) (declare (ignorable commit?)) (block exit First determine whether that gene exists in biobike . (multiple-value-bind (gene-frame orgf error) (seed-id->frame seed-id) (declare (ignore error)) (when orgf (unless (#^organism-loaded? orgf) (load-organism orgf) (return-from exit (seed-id->frame seed-id)))) This seed - id is not known at all to Biobike . It might is not in the master list Biobike wo n't know about it . (unless gene-frame (return-from exit (values nil "No frame to update!"))) (let ((new-subsystem-role (mysql-get-description-for-peg seed-id))) (setf (#^subsystem-role gene-frame) new-subsystem-role)) (let* ((in-data (fids-to-mysql-in-format (list seed-id)))) (flet ((sync-category (category-type slot) (let* ((records (mysql-get-categories-info-by-type in-data category-type )) (last-record (lastelem (sort records 'string-lessp :key 'categories-timestamp )))) (when last-record (let ((new-annotation (categories-annotation last-record))) (setf (slotv gene-frame slot) new-annotation) ))))) (sync-category "ANN" #$description) (sync-category "GEN" #$genetic-name) )) We 're done . Commit the change permanently to acache . #-:lispworks (when commit? (db.ac::commit)) (values gene-frame nil) ))) (defun retrieve-gene-info-from-seed-database (seed-id orgf) (multiple-value-bind (features-data column-names) (seed-gene-info-for-seed-id seed-id) (process-features-info-msf features-data column-names) (set-feature-item seed-id :description (mysql-get-description-for-peg seed-id)) (let* ((annotations-hash (get-seed-info-for-annotations (#^seed-id orgf))) (annotation-history (gethash seed-id annotations-hash))) (set-feature-item seed-id :annotation annotation-history) )))
40ba56a50b15745e92e2cd3fd5301be49a36ca02fb541c6f66ae9948bfcaac8c
MLstate/opalang
imp_Common.ml
Copyright © 2011 , 2012 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with . If not , see < / > . Copyright © 2011, 2012 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Opa. If not, see </>. *) (* depends *) module Format = Base.Format (* alias *) module FieldSet = StringSet (* shorthand *) module J = JsAst module Q = QmlAst (* -- *) let pp_esc fmt s = Format.fprintf fmt "%S" s let pp_path fmt list = Format.pp_list " ; " pp_esc fmt list let pp_fieldset fmt set = let sep = ref false in FieldSet.iter ( fun field -> (if !sep then Format.fprintf fmt " ; " ; sep := true) ; Format.pp_print_string fmt field ) set (* contains all the calls to the runtime (except the bsl which is called with * bypasses) *) module ClientLib = struct let (!!) s = JsCons.Expr.native_global s let build_true = !! "build_true" let build_false = !! "build_false" let build_bool b = if b then build_true else build_false let dot_true = !! "dot_true" let dot_false = !! "dot_false" let dot_bool b = if b then dot_true else dot_false let dot = !! "dot" let udot = !! "udot" let env_apply_with_ty = !! "_env_apply_with_ty" let error = !! "error" let extend_record = !! "extend_record" let match_failure pos = let message = JsCons.Expr.string (Format.sprintf "%a: Match failure %d" FilePos.pp_pos pos (BaseRandom.int 10000000)) in JsCons.Expr.call ~pure:false error [ message ] let size = !! "size" let void = !! "js_void" let none = !! "js_none" let some = !! "js_some" let option2js = !! "option2js" let js2option = !! "js2option" let type_string = !! "type_string" let type_char = !! "type_char" let type_int = !! "type_int" let type_float = !! "type_float" let type_fun = !! "type_fun" let type_fun_arity = !! "type_fun_arity" let type_var = !! "type_var" let type_option = !! "type_option" let type_void = !! "type_void" let type_native_option = !! "type_native_option" let type_native_void = !! "type_native_void" let type_bool = !! "type_bool" let type_extern = !! "type_extern" let type_opavalue = !! "type_opavalue" let assert_length = !! "assert_length" let wrap_tc = JsCons.Expr.native_global ~pure:true "wrap_tc" end (* a very conservative approximation of which expressions do observable side * effects *) let does_side_effects e = JsWalk.OnlyExpr.exists (function | J.Je_hole _ | J.Je_new _ | J.Je_call (_,_,_,false) -> true | J.Je_unop (_, ( J.Ju_delete | J.Ju_add2_pre | J.Ju_sub2_pre | J.Ju_add2_post | J.Ju_sub2_post), _) -> true | J.Je_binop (_, ( J.Jb_assign | J.Jb_mul_assign | J.Jb_div_assign | J.Jb_mod_assign | J.Jb_add_assign | J.Jb_sub_assign | J.Jb_lsl_assign | J.Jb_lsr_assign | J.Jb_asr_assign | J.Jb_and_assign | J.Jb_xor_assign | J.Jb_or_assign ), _, _) -> true | J.Je_runtime (_, e) -> ( match e with | JsAstRuntime.SetDistant _ -> true | JsAstRuntime.TaggedString _ -> false ) | _ -> false ) e (* ************************************************************************** *) * { b } : Returns [ true ] if the type has some values that may be evaluated into false in JS . The following types are considered " dangerous " because the specified value is evaluated into false in JS : - int : 0 - float : 0.0 - string : " " - char : '' - bool : false - type variable since we do not know what it will finally be , perhaps especially one of the above " dangerous " type . - abstract type since we do n't known what it is really . - named type that remain named type after expansion since , if this happens this means that we have no explicit representation of them in term of basic types combinations , hence this probably corresponds to an abstract type . Note that currently , with the way represents abstract types , I 'm really not sure that this can happen . { b Visibility } : Not exported outside this module . into false in JS. The following types are considered "dangerous" because the specified value is evaluated into false in JS: - int : 0 - float : 0.0 - string : "" - char : '' - bool : false - type variable since we do not know what it will finally be, perhaps especially one of the above "dangerous" type. - abstract type since we don't known what it is really. - named type that remain named type after expansion since, if this happens this means that we have no explicit representation of them in term of basic types combinations, hence this probably corresponds to an abstract type. Note that currently, with the way QML represents abstract types, I'm really not sure that this can happen. {b Visibility}: Not exported outside this module. *) (* ************************************************************************** *) let maybe_void gamma ty = let rec do_job ~already_expanded = function | Q.TypeRecord (Q.TyRow ([], _)) -> true | Q.TypeSum (Q.TyCol (list, colvar)) -> Option.is_some colvar || List.exists (function [] -> true | _ -> false) list | Q.TypeRecord _ | Q.TypeArrow _ | Q.TypeConst _ -> false | Q.TypeAbstract | Q.TypeVar _ -> true | Q.TypeSumSugar _ -> (* There should not remain such type at this point. *) assert false | Q.TypeForall (_, _, _, t) -> do_job ~already_expanded t | (Q.TypeName _) as t -> if already_expanded then true else ( (* The type has not already been expanded, hence we are allowed to expand it. *) let t = QmlTypesUtils.Inspect.follow_alias_noopt_private gamma t in (* And now it has been expanded, we are not allowed to expand it again forever. *) do_job ~already_expanded: true t ) in do_job ~already_expanded: false ty let maybe_js_false gamma ty = (* Local function processing the type. We only expand the type if it appears to be a named type. This saves time in case the type is not a named one. The flag [~already_expanded] tells if the type has been expanded, hence must not be again. *) let rec do_job ~already_expanded = function (* Special case for boolean. Do not call Inspect.is_type_bool, because it would perform a expansion everytime, and is not exactly what we need there. We are caring about value that are potentially [false], which includes bool value, but not only (e.g. with an open col, or row variable) *) | Q.TypeRecord (Q.TyRow (["false", ty], _)) -> maybe_void gamma ty | Q.TypeRecord (Q.TyRow ([], Some _)) -> true | Q.TypeSum (Q.TyCol (cols, colvar)) -> let void = ref true in let exists case = match case with | [ "false", tyf ] -> void := maybe_void gamma tyf ; !void | _ -> false in List.exists exists cols || (Option.is_some colvar && !void) From there , sum and record may not be bool From there, sum and record may not be bool *) | Q.TypeRecord _ | Q.TypeArrow _ -> false | Q.TypeAbstract | Q.TypeVar _ -> true | Q.TypeConst ct -> ( (* In fact, all basic types are "dangerous". *) match ct with | Q.TyFloat | Q.TyInt | Q.TyString -> true | Q.TyNull -> assert false ) | Q.TypeSumSugar _ -> (* There should not remain such type at this point. *) assert false | Q.TypeForall (_, _, _, t) -> do_job ~already_expanded t | (Q.TypeName _) as t -> if already_expanded then true else ( (* The type has not already been expanded, hence we are allowed to expand it. *) let t = QmlTypesUtils.Inspect.follow_alias_noopt_private gamma t in (* And now it has been expanded, we are not allowed to expand it again forever. *) do_job ~already_expanded: true t ) in (* Now, really do the job. Effective body of the function [maybe_js_false]. *) do_job ~already_expanded: false ty let const const = match const with | Q.Int i -> JsCons.Expr.bint i | Q.Float f -> JsCons.Expr.float f | Q.String s -> JsCons.Expr.string s
null
https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/qmljsimp/imp_Common.ml
ocaml
depends alias shorthand -- contains all the calls to the runtime (except the bsl which is called with * bypasses) a very conservative approximation of which expressions do observable side * effects ************************************************************************** ************************************************************************** There should not remain such type at this point. The type has not already been expanded, hence we are allowed to expand it. And now it has been expanded, we are not allowed to expand it again forever. Local function processing the type. We only expand the type if it appears to be a named type. This saves time in case the type is not a named one. The flag [~already_expanded] tells if the type has been expanded, hence must not be again. Special case for boolean. Do not call Inspect.is_type_bool, because it would perform a expansion everytime, and is not exactly what we need there. We are caring about value that are potentially [false], which includes bool value, but not only (e.g. with an open col, or row variable) In fact, all basic types are "dangerous". There should not remain such type at this point. The type has not already been expanded, hence we are allowed to expand it. And now it has been expanded, we are not allowed to expand it again forever. Now, really do the job. Effective body of the function [maybe_js_false].
Copyright © 2011 , 2012 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with . If not , see < / > . Copyright © 2011, 2012 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Opa. If not, see </>. *) module Format = Base.Format module FieldSet = StringSet module J = JsAst module Q = QmlAst let pp_esc fmt s = Format.fprintf fmt "%S" s let pp_path fmt list = Format.pp_list " ; " pp_esc fmt list let pp_fieldset fmt set = let sep = ref false in FieldSet.iter ( fun field -> (if !sep then Format.fprintf fmt " ; " ; sep := true) ; Format.pp_print_string fmt field ) set module ClientLib = struct let (!!) s = JsCons.Expr.native_global s let build_true = !! "build_true" let build_false = !! "build_false" let build_bool b = if b then build_true else build_false let dot_true = !! "dot_true" let dot_false = !! "dot_false" let dot_bool b = if b then dot_true else dot_false let dot = !! "dot" let udot = !! "udot" let env_apply_with_ty = !! "_env_apply_with_ty" let error = !! "error" let extend_record = !! "extend_record" let match_failure pos = let message = JsCons.Expr.string (Format.sprintf "%a: Match failure %d" FilePos.pp_pos pos (BaseRandom.int 10000000)) in JsCons.Expr.call ~pure:false error [ message ] let size = !! "size" let void = !! "js_void" let none = !! "js_none" let some = !! "js_some" let option2js = !! "option2js" let js2option = !! "js2option" let type_string = !! "type_string" let type_char = !! "type_char" let type_int = !! "type_int" let type_float = !! "type_float" let type_fun = !! "type_fun" let type_fun_arity = !! "type_fun_arity" let type_var = !! "type_var" let type_option = !! "type_option" let type_void = !! "type_void" let type_native_option = !! "type_native_option" let type_native_void = !! "type_native_void" let type_bool = !! "type_bool" let type_extern = !! "type_extern" let type_opavalue = !! "type_opavalue" let assert_length = !! "assert_length" let wrap_tc = JsCons.Expr.native_global ~pure:true "wrap_tc" end let does_side_effects e = JsWalk.OnlyExpr.exists (function | J.Je_hole _ | J.Je_new _ | J.Je_call (_,_,_,false) -> true | J.Je_unop (_, ( J.Ju_delete | J.Ju_add2_pre | J.Ju_sub2_pre | J.Ju_add2_post | J.Ju_sub2_post), _) -> true | J.Je_binop (_, ( J.Jb_assign | J.Jb_mul_assign | J.Jb_div_assign | J.Jb_mod_assign | J.Jb_add_assign | J.Jb_sub_assign | J.Jb_lsl_assign | J.Jb_lsr_assign | J.Jb_asr_assign | J.Jb_and_assign | J.Jb_xor_assign | J.Jb_or_assign ), _, _) -> true | J.Je_runtime (_, e) -> ( match e with | JsAstRuntime.SetDistant _ -> true | JsAstRuntime.TaggedString _ -> false ) | _ -> false ) e * { b } : Returns [ true ] if the type has some values that may be evaluated into false in JS . The following types are considered " dangerous " because the specified value is evaluated into false in JS : - int : 0 - float : 0.0 - string : " " - char : '' - bool : false - type variable since we do not know what it will finally be , perhaps especially one of the above " dangerous " type . - abstract type since we do n't known what it is really . - named type that remain named type after expansion since , if this happens this means that we have no explicit representation of them in term of basic types combinations , hence this probably corresponds to an abstract type . Note that currently , with the way represents abstract types , I 'm really not sure that this can happen . { b Visibility } : Not exported outside this module . into false in JS. The following types are considered "dangerous" because the specified value is evaluated into false in JS: - int : 0 - float : 0.0 - string : "" - char : '' - bool : false - type variable since we do not know what it will finally be, perhaps especially one of the above "dangerous" type. - abstract type since we don't known what it is really. - named type that remain named type after expansion since, if this happens this means that we have no explicit representation of them in term of basic types combinations, hence this probably corresponds to an abstract type. Note that currently, with the way QML represents abstract types, I'm really not sure that this can happen. {b Visibility}: Not exported outside this module. *) let maybe_void gamma ty = let rec do_job ~already_expanded = function | Q.TypeRecord (Q.TyRow ([], _)) -> true | Q.TypeSum (Q.TyCol (list, colvar)) -> Option.is_some colvar || List.exists (function [] -> true | _ -> false) list | Q.TypeRecord _ | Q.TypeArrow _ | Q.TypeConst _ -> false | Q.TypeAbstract | Q.TypeVar _ -> true | Q.TypeSumSugar _ -> assert false | Q.TypeForall (_, _, _, t) -> do_job ~already_expanded t | (Q.TypeName _) as t -> if already_expanded then true else ( let t = QmlTypesUtils.Inspect.follow_alias_noopt_private gamma t in do_job ~already_expanded: true t ) in do_job ~already_expanded: false ty let maybe_js_false gamma ty = let rec do_job ~already_expanded = function | Q.TypeRecord (Q.TyRow (["false", ty], _)) -> maybe_void gamma ty | Q.TypeRecord (Q.TyRow ([], Some _)) -> true | Q.TypeSum (Q.TyCol (cols, colvar)) -> let void = ref true in let exists case = match case with | [ "false", tyf ] -> void := maybe_void gamma tyf ; !void | _ -> false in List.exists exists cols || (Option.is_some colvar && !void) From there , sum and record may not be bool From there, sum and record may not be bool *) | Q.TypeRecord _ | Q.TypeArrow _ -> false | Q.TypeAbstract | Q.TypeVar _ -> true | Q.TypeConst ct -> ( match ct with | Q.TyFloat | Q.TyInt | Q.TyString -> true | Q.TyNull -> assert false ) | Q.TypeSumSugar _ -> assert false | Q.TypeForall (_, _, _, t) -> do_job ~already_expanded t | (Q.TypeName _) as t -> if already_expanded then true else ( let t = QmlTypesUtils.Inspect.follow_alias_noopt_private gamma t in do_job ~already_expanded: true t ) in do_job ~already_expanded: false ty let const const = match const with | Q.Int i -> JsCons.Expr.bint i | Q.Float f -> JsCons.Expr.float f | Q.String s -> JsCons.Expr.string s
e7d11f3bf308d1e2cd2e8856cff1d105fcf1a5b624e994336f5208f615898dfe
skanev/playground
17.scm
SICP exercise 2.17 ; ; Define a procedure last-pair that returns the list that contains only the last ; element of a given (nonempty) list: ; ( list - pair ( list 23 72 149 34 ) ) ( 34 ) (define (last-pair items) (if (null? (cdr items)) items (last-pair (cdr items))))
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/02/17.scm
scheme
Define a procedure last-pair that returns the list that contains only the last element of a given (nonempty) list:
SICP exercise 2.17 ( list - pair ( list 23 72 149 34 ) ) ( 34 ) (define (last-pair items) (if (null? (cdr items)) items (last-pair (cdr items))))
d8d42b17534070ccfa4a1b5edaeaade36f9d8418cb5beeb612af4f5021dd18a3
danidiaz/really-small-backpack-example
Main.hs
module Main where import Intermediate (barAsString, myIdFunc) main :: IO () main = do print $ myIdFunc 3 putStrLn $ barAsString
null
https://raw.githubusercontent.com/danidiaz/really-small-backpack-example/b5828e4ef35abea5630f9b3f5ec0e99ff9240a5e/lesson9-template-haskell/Main.hs
haskell
module Main where import Intermediate (barAsString, myIdFunc) main :: IO () main = do print $ myIdFunc 3 putStrLn $ barAsString
7d9ffcbed087758aa32580043068e506e72fd1bcaa8f20d19753c16b052dcaef
LexiFi/menhir
action.mli
(******************************************************************************) (* *) (* *) , Paris , PPS , Université Paris Diderot (* *) . All rights reserved . This file is distributed under the terms of the GNU General Public License version 2 , as described in the (* file LICENSE. *) (* *) (******************************************************************************) open Keyword (* from sdk/ *) (** A semantic action is a piece of OCaml code together with information about the free variables that appear in this code (which refer to semantic values) and information about the keywords that appear in this code. The code can be represented internally as a piece of text or (more generally) as an IL expression. *) type t (* -------------------------------------------------------------------------- *) (* Constructors. *) (** [from_stretch xs s] builds an action out of a textual piece of code. The set [xs] must contain all of the variables that occur free in the semantic action and denote a semantic value. *) val from_stretch: StringSet.t -> Stretch.t -> t * [ ] builds an action out of an IL expression . Not every IL expression is accepted ; only the expressions built by NewRuleSyntax are accepted . expression is accepted; only the expressions built by NewRuleSyntax are accepted. *) val from_il_expr: IL.expr -> t (** [compose x a1 a2] builds the action [let x = a1 in a2]. This combinator is used during inlining (that is, while eliminating %inlined symbols). *) val compose : string -> t -> t -> t (** [bind p x a] binds the OCaml pattern [p] to the OCaml variable [x] in the semantic action [a]. Therefore, it builds the action [let p = x in a]. Not every IL pattern is accepted; only those built by NewRuleSyntax are accepted. *) val bind: IL.pattern -> string -> t -> t (* -------------------------------------------------------------------------- *) (* Accessors. *) (** [to_il_expr] converts an action to an IL expression. *) val to_il_expr: t -> IL.expr * [ is_standard a ] indicates whether the action [ a ] originates from Menhir 's standard library . Via inlining , several actions can be combined into one ; in that case , we take a conjunction standard library. Via inlining, several actions can be combined into one; in that case, we take a conjunction *) val is_standard: t -> bool (** [semvars a] is a superset of the free variables that may appear in the action [a] to denote a semantic value. *) val semvars: t -> StringSet.t (** [keywords a] is the set of keywords used in the action [a]. *) val keywords: t -> KeywordSet.t (** [has_syntaxerror a] tests whether the keyword [$syntaxerror] appears in the set [keywords a]. *) val has_syntaxerror: t -> bool (** [has_beforeend a] tests whether the keyword [$endpos($0)] appears in the set [keywords a]. *) val has_beforeend: t -> bool (** [posvars a] is the set of conventional position variables that correspond to the position keywords used in the action [a]. *) val posvars: t -> StringSet.t (** [vars a] is the union of [semvars a] and [posvars a]. *) val vars: t -> StringSet.t (* -------------------------------------------------------------------------- *) (* Keyword expansion. *) (** [define keyword keywords f a] defines away the keyword [keyword]. This keyword is removed from the set of keywords of the action [a]; the set [keywords] is added in its place. The code of the action [a] is transformed by the function [f], which typically wraps its argument in some new [let] bindings. *) val define: keyword -> KeywordSet.t -> (IL.expr -> IL.expr) -> t -> t (* -------------------------------------------------------------------------- *) (* Variable renaming and keyword transformation. *) Some keyword contains names : [ $ startpos(foo ) ] is an example . If one wishes for some reason to rename the variable [ foo ] to [ bar ] , then this keyword must be renamed to [ $ startpos(bar ) ] . Furthermore , during inlining , it may be necessary to transform a keyword into another keyword : e.g. , if [ x ] is inlined away and replaced with a sequence of [ y ] and [ z ] , then [ $ startpos(x ) ] must be renamed to [ $ startpos(y ) ] and [ $ endpos(x ) ] must be renamed to [ $ endpos(z ) ] . for some reason to rename the variable [foo] to [bar], then this keyword must be renamed to [$startpos(bar)]. Furthermore, during inlining, it may be necessary to transform a keyword into another keyword: e.g., if [x] is inlined away and replaced with a sequence of [y] and [z], then [$startpos(x)] must be renamed to [$startpos(y)] and [$endpos(x)] must be renamed to [$endpos(z)]. *) (** A variable-to-variable substitution is a finite map of variables to variables. It can be semantically interpreted as a simultaneous binding construct, that is, as a [let/and] construct. *) type subst (** The empty substitution. *) val empty: subst (** Extending a substitution. *) val extend: string -> string -> subst -> subst * [ rename a ] transforms the action [ a ] by applying the renaming [ phi ] as well as the keyword transformations determined by the function [ f ] . The function [ f ] is applied to each ( not - yet - renamed ) keyword and may decide to transform it into another keyword , by returning [ Some _ ] , or to not transform it , by returning [ None ] . In the latter case , [ phi ] still applies to the keyword . as well as the keyword transformations determined by the function [f]. The function [f] is applied to each (not-yet-renamed) keyword and may decide to transform it into another keyword, by returning [Some _], or to not transform it, by returning [None]. In the latter case, [phi] still applies to the keyword. *) val rename: (subject * where -> (subject * where) option) -> subst -> t -> t
null
https://raw.githubusercontent.com/LexiFi/menhir/794e64e7997d4d3f91d36dd49aaecc942ea858b7/src/action.mli
ocaml
**************************************************************************** file LICENSE. **************************************************************************** from sdk/ * A semantic action is a piece of OCaml code together with information about the free variables that appear in this code (which refer to semantic values) and information about the keywords that appear in this code. The code can be represented internally as a piece of text or (more generally) as an IL expression. -------------------------------------------------------------------------- Constructors. * [from_stretch xs s] builds an action out of a textual piece of code. The set [xs] must contain all of the variables that occur free in the semantic action and denote a semantic value. * [compose x a1 a2] builds the action [let x = a1 in a2]. This combinator is used during inlining (that is, while eliminating %inlined symbols). * [bind p x a] binds the OCaml pattern [p] to the OCaml variable [x] in the semantic action [a]. Therefore, it builds the action [let p = x in a]. Not every IL pattern is accepted; only those built by NewRuleSyntax are accepted. -------------------------------------------------------------------------- Accessors. * [to_il_expr] converts an action to an IL expression. * [semvars a] is a superset of the free variables that may appear in the action [a] to denote a semantic value. * [keywords a] is the set of keywords used in the action [a]. * [has_syntaxerror a] tests whether the keyword [$syntaxerror] appears in the set [keywords a]. * [has_beforeend a] tests whether the keyword [$endpos($0)] appears in the set [keywords a]. * [posvars a] is the set of conventional position variables that correspond to the position keywords used in the action [a]. * [vars a] is the union of [semvars a] and [posvars a]. -------------------------------------------------------------------------- Keyword expansion. * [define keyword keywords f a] defines away the keyword [keyword]. This keyword is removed from the set of keywords of the action [a]; the set [keywords] is added in its place. The code of the action [a] is transformed by the function [f], which typically wraps its argument in some new [let] bindings. -------------------------------------------------------------------------- Variable renaming and keyword transformation. * A variable-to-variable substitution is a finite map of variables to variables. It can be semantically interpreted as a simultaneous binding construct, that is, as a [let/and] construct. * The empty substitution. * Extending a substitution.
, Paris , PPS , Université Paris Diderot . All rights reserved . This file is distributed under the terms of the GNU General Public License version 2 , as described in the type t val from_stretch: StringSet.t -> Stretch.t -> t * [ ] builds an action out of an IL expression . Not every IL expression is accepted ; only the expressions built by NewRuleSyntax are accepted . expression is accepted; only the expressions built by NewRuleSyntax are accepted. *) val from_il_expr: IL.expr -> t val compose : string -> t -> t -> t val bind: IL.pattern -> string -> t -> t val to_il_expr: t -> IL.expr * [ is_standard a ] indicates whether the action [ a ] originates from Menhir 's standard library . Via inlining , several actions can be combined into one ; in that case , we take a conjunction standard library. Via inlining, several actions can be combined into one; in that case, we take a conjunction *) val is_standard: t -> bool val semvars: t -> StringSet.t val keywords: t -> KeywordSet.t val has_syntaxerror: t -> bool val has_beforeend: t -> bool val posvars: t -> StringSet.t val vars: t -> StringSet.t val define: keyword -> KeywordSet.t -> (IL.expr -> IL.expr) -> t -> t Some keyword contains names : [ $ startpos(foo ) ] is an example . If one wishes for some reason to rename the variable [ foo ] to [ bar ] , then this keyword must be renamed to [ $ startpos(bar ) ] . Furthermore , during inlining , it may be necessary to transform a keyword into another keyword : e.g. , if [ x ] is inlined away and replaced with a sequence of [ y ] and [ z ] , then [ $ startpos(x ) ] must be renamed to [ $ startpos(y ) ] and [ $ endpos(x ) ] must be renamed to [ $ endpos(z ) ] . for some reason to rename the variable [foo] to [bar], then this keyword must be renamed to [$startpos(bar)]. Furthermore, during inlining, it may be necessary to transform a keyword into another keyword: e.g., if [x] is inlined away and replaced with a sequence of [y] and [z], then [$startpos(x)] must be renamed to [$startpos(y)] and [$endpos(x)] must be renamed to [$endpos(z)]. *) type subst val empty: subst val extend: string -> string -> subst -> subst * [ rename a ] transforms the action [ a ] by applying the renaming [ phi ] as well as the keyword transformations determined by the function [ f ] . The function [ f ] is applied to each ( not - yet - renamed ) keyword and may decide to transform it into another keyword , by returning [ Some _ ] , or to not transform it , by returning [ None ] . In the latter case , [ phi ] still applies to the keyword . as well as the keyword transformations determined by the function [f]. The function [f] is applied to each (not-yet-renamed) keyword and may decide to transform it into another keyword, by returning [Some _], or to not transform it, by returning [None]. In the latter case, [phi] still applies to the keyword. *) val rename: (subject * where -> (subject * where) option) -> subst -> t -> t
ca7f256a2905a8dc8ec3d4d3e1d1fae650c31ef98f4906f7c5f2f0df49ae0af6
tcsprojects/mlsolver
lmmcvaliditygame.ml
open Tcsautomata;; open Tcsautohelper;; open Tcsautotransform;; open Tcstransitionsys;; open Tcsgames;; open Tcsset;; open Tcslist;; open Tcsarray;; open Tcstiming;; open Tcsbasedata;; open Tcsmessage;; open Tcslmmcformula;; open Lmmcthreadnba;; open Validitygamesregistry;; type 'a state = TT | NT of int list | Tuple of ((int list) * (* variables, branching *) (int list) * (* modalities *) (int list)) * (* propositions *) 'a;; (* automaton *) type 'a validity_game = 'a state initpg;; type simplification_result = SimplTT | SimplFF | SimplKeep;; let rec simplify ((_, fmls, prop, _, _) as fml) props i = match fmls.(i) with FIntAtom b -> if b then SimplTT else SimplFF | FIntProp (b, p) -> if TreeSet.mem ((if b then fst else snd) (snd prop.(p))) props then SimplFF else if TreeSet.mem ((if b then snd else fst) (snd prop.(p))) props then SimplTT else SimplKeep | FIntBranch (true, l, r) -> ( match simplify fml props l with SimplTT -> SimplTT | SimplFF -> simplify fml props r | SimplKeep -> if simplify fml props r = SimplTT then SimplTT else SimplKeep ) | FIntBranch (false, l, r) -> ( match simplify fml props l with SimplFF -> SimplFF | SimplTT -> simplify fml props r | SimplKeep -> if simplify fml props r = SimplFF then SimplFF else SimplKeep ) | _ -> SimplKeep let get_validity_game (((r, fmls, props, vars, lbls) as fml): decomposed_labelled_mmc_formula) dpa use_literal_propagation allow_removal_of_mu = let dpa_initial_state = DMA.initial dpa in let dpa_delta x y = DMA.delta dpa x y in let dpa_omega = DMA.accept dpa in let state_cmp = Domain.compare (DMA.states dpa) in let dpa_state_format = Domain.format (DMA.states dpa) in let format_formula = format_decomposed_formula fml in let rec finish new_formulas = function TT -> TT | NT s -> NT s | Tuple ((a, b, c), d) -> ( let (newa, newb, newc, is_true) = (ref [], ref [], ref [], ref false) in List.iter (fun f -> match fmls.(f) with FIntAtom b -> if b then is_true := true | FIntModality _ -> newb := f::!newb | FIntProp (b, p) -> newc := (f, (if b then snd else fst) (snd props.(p)))::!newc | _ -> newa := f::!newa ) new_formulas; if !is_true then TT else ( let c = ref (TreeSet.of_list_def c) in List.iter (fun (f, f') -> if (TreeSet.mem f' !c) then is_true := true else c := TreeSet.add f !c ) !newc; if !is_true then TT else ( let a = TreeSet.elements (TreeSet.union (TreeSet.of_list_def !newa) (TreeSet.of_list_def a)) in let b = TreeSet.elements (TreeSet.union (TreeSet.of_list_def !newb) (TreeSet.of_list_def b)) in let c = TreeSet.elements !c in if (a = []) && (b = []) then NT c else Tuple ((a, b, c), d) ) ) ) in let initial_state = finish [r] (Tuple (([], [], []), dpa_initial_state)) in let exist_pos = function Tuple ((x::_, _, _), _) -> if allow_removal_of_mu then ( match fmls.(x) with FIntVariable i -> let (nufp, _, _, _) = snd vars.(i) in not nufp | _ -> false ) else false | _ -> true in let rec delta = function Tuple ((a, b, c), d) -> ( match a with f::a -> ( match fmls.(f) with FIntVariable i -> let (nufp, _, gua, f') = snd vars.(i) in let s = finish [f'] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Follow f))) in if allow_removal_of_mu && (not nufp) && not gua then [s; finish [] (Tuple ((a,b,c), dpa_delta d (Lmmcthreadnba.Delete f)))] else [s] | FIntBranch (true, f1, f2) -> if use_literal_propagation then ( let propsset = TreeSet.of_list_def c in let f1s = simplify fml propsset f1 in let f2s = simplify fml propsset f2 in if (f1s = SimplFF && f2s = SimplFF) then [finish [] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Delete f)))] else if (f1s = SimplTT || f2s = SimplTT) then [TT] else if (f1s = SimplFF || f2s = SimplFF) then let d = dpa_delta d (Lmmcthreadnba.Follow f) in let d = dpa_delta d (Lmmcthreadnba.Delete (if f1s = SimplFF then f1 else f2)) in [finish [if f2s = SimplFF then f1 else f2] (Tuple ((a, b, c), d))] else [finish [f1; f2] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Follow f)))] ) else [finish [f1; f2] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Follow f)))] | FIntBranch (false, f1, f2) -> if use_literal_propagation then ( let propsset = TreeSet.of_list_def c in let f1s = simplify fml propsset f1 in let f2s = simplify fml propsset f2 in if (f1s = SimplFF || f2s = SimplFF) then [finish [] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Delete f)))] else if (f1s = SimplTT && f2s = SimplTT) then [TT] else if (f1s = SimplTT || f2s = SimplTT) then [finish [if f2s = SimplTT then f1 else f2] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Branch (f2s = SimplTT, f))))] else let d1 = dpa_delta d (Lmmcthreadnba.Branch (true, f)) in let d2 = dpa_delta d (Lmmcthreadnba.Branch (false, f)) in [finish [f1] (Tuple ((a, b, c), d1)); finish [f2] (Tuple ((a, b, c), d2))] ) else let d1 = dpa_delta d (Lmmcthreadnba.Branch (true, f)) in let d2 = dpa_delta d (Lmmcthreadnba.Branch (false, f)) in [finish [f1] (Tuple ((a, b, c), d1)); finish [f2] (Tuple ((a, b, c), d2))] | _ -> failwith "Labelledmmcvaliditygame.delta: Failure 1!" ) | [] -> if b = [] then failwith "Labelledmmcvaliditygame.delta: Failure 2!" else ( let b = List.map (fun f -> match fmls.(f) with (FIntModality (x,y,z)) -> (f, (x,y,z)) | _ -> failwith "Labelledmmcvaliditygame.delta: Failure 3!" ) b in let (diamonds, boxes) = List.partition (fun (_, (b, _, _)) -> b) b in if boxes = [] then [NT c] else ( let l = ref 0 in let mp = ref TreeMap.empty_def in List.iter (fun (_, (_, lab, _)) -> if not (TreeMap.mem lab !mp) then ( mp := TreeMap.add lab !l !mp; incr l ) ) boxes; let part = Array.make !l ([], [], -1) in List.iter (fun (f, (b, lab, g)) -> try let i = TreeMap.find lab !mp in let (dia, box, _) = part.(i) in part.(i) <- if b then (g::dia, box, lab) else (dia, (f, g)::box, lab) with Not_found -> () ) b; let ret = ref [] in Array.iter (fun (dia, box, lab) -> List.iter (fun (f, g) -> let d = dpa_delta d (Lmmcthreadnba.Follow f) in let s = finish (g::dia) (Tuple (([], [], []), d)) in ret := s::!ret ) box ) part; !ret ) ) ) | s -> [s] in let omega = function TT -> 0 | NT _ -> 1 | Tuple (_, q) -> dpa_omega q in let format_state = function TT -> "TT" | NT s -> "NT (" ^ ListUtils.format format_formula s ^ ")" | Tuple ((a, b, c), f) -> "Tuple (" ^ ListUtils.format format_formula (a@b@c) ^ ", " ^ dpa_state_format f ^ ")" in let comp' cmp s1 s2 = match (s1, s2) with (Tuple (a, x), Tuple (b, y)) -> ( let c = compare a b in if c = 0 then cmp x y else c ) | _ -> compare s1 s2 in let comp = Some (comp' state_cmp) in ((initial_state, delta, omega, exist_pos, format_state), (None, None, comp));; let extract_counter_model (dec_formula: decomposed_labelled_mmc_formula) (validity_game: int initpg) strategy int_to_state state_to_int = let (_, fmls, props, _, labels) = dec_formula in let ((init, delta, _, ex, fo), _) = validity_game in let props_final i = fst props.(i) in let labels_final i = labels.(i) in let rec finalize i = match (fst (int_to_state i)) with TT -> i | NT _ -> i | Tuple (([], _, _), _) -> i | _ -> finalize (if ex i then List.hd (delta i) else OptionUtils.get_some (strategy i)) in let init_final = finalize init in let get_props_final i = let convert l = List.filter (fun i -> i >= 0) (List.map (fun f -> match fmls.(f) with FIntProp (false, p) -> p | _ -> -1 ) l) in match (fst (int_to_state i)) with TT -> [] | NT l -> convert l | Tuple ((_, _, l), _) -> convert l in let get_delta_final i = match (int_to_state i) with (Tuple (([], b, _), q), r) -> ( let boxes = ref [] in let diamonds = ref [] in List.iter (fun f -> match fmls.(f) with (FIntModality (b,l,_)) -> ( if b then diamonds := f::!diamonds else boxes := (f,l)::!boxes ) | _ -> failwith "Impossible." ) b; List.map (fun (box, lab) -> (lab, finalize (List.hd (delta (state_to_int (Tuple (([], box::!diamonds, []), q), r))))) ) !boxes ) | _ -> [] in let get_annot_final i = fo i in let compare_final i j = compare i j in ((init_final, get_props_final, get_delta_final, get_annot_final), (Some compare_final, labels_final, props_final)) let compare_formula f g = match (f, g) with (FIntBranch (true, _, _), FIntBranch (false, _, _)) -> -1 | (FIntBranch (false, _, _), FIntBranch (true, _, _)) -> 1 | _ -> compare f g;; let validity_proc formula options (info_chan, formula_chan, constr_chan) = let proof_game_in_annot = ArrayUtils.mem "ann" options in let compact_game = ArrayUtils.mem "comp" options in let use_literal_propagation = ArrayUtils.mem "litpro" options in let length_sort = if ArrayUtils.mem "prefersmall" options then 1 else if ArrayUtils.mem "preferlarge" options then -1 else 0 in let without_guardedness = ArrayUtils.mem "woguarded" options in let info_msg = MessageChannel.send_message info_chan in let formula_msg = MessageChannel.send_message formula_chan in let constr_msg = MessageChannel.send_message constr_chan in info_msg (fun _ -> "Decision Procedure For Labelled Modal Mu Calculus\n"); formula_msg (fun _ -> "Transforming given formula..."); let t = SimpleTiming.init true in let formula' = eval_metaformula formula in let goalformula' = make_uniquely_bound (formula_to_positive formula') in let goalformula = if is_guarded goalformula' || without_guardedness then goalformula' else make_uniquely_bound (guarded_transform goalformula') in formula_msg (fun _ -> SimpleTiming.format t ^ "\n"); formula_msg (fun _ -> "Transformed formula: " ^ format_formula goalformula ^ "\n"); formula_msg (fun _ -> "Formula Length: " ^ string_of_int (formula_length goalformula) ^ "\n"); formula_msg (fun _ -> let (t,g,u) = formula_variable_occs goalformula in "Formula Variable Occurrences: " ^ string_of_int t ^ "\n"); constr_msg (fun _ -> "Decompose formula..."); let t = SimpleTiming.init true in let decformula = normal_form_formula_to_decomposed_formula goalformula in let decformula = if length_sort = 0 then sort_decomposed_formula decformula (fun _ -> compare_formula) else sort_decomposed_formula decformula (fun d a b -> length_sort * compare (get_formula_depth d a) (get_formula_depth d b)) in constr_msg (fun _ -> SimpleTiming.format t ^ "\n"); formula_msg (fun _ -> "Subformula Cardinality: " ^ string_of_int (decomposed_formula_subformula_cardinality decformula) ^ "\n"); constr_msg (fun _ -> "Initializing automata..."); let t = SimpleTiming.init true in let timing_list = ref [] in let new_timing s = let t = SimpleTiming.init false in timing_list := (s, t)::!timing_list; t in let listening = MessageChannel.channel_is_listening constr_chan in let nba_without_timing = lmmc_thread_nba decformula in let nba = if listening then NMATiming.full_timing nba_without_timing (new_timing "nba_timing") else nba_without_timing in let nba_state_cache = NMAStateCache.make2 nba in let nba_delta_cache = NMADeltaCache.make (NMAStateCache.automaton2 nba_state_cache) in let nba_accept_cache = NMAAcceptCache.make (NMADeltaCache.automaton nba_delta_cache) in let nba_cached_without_timing = NMAAcceptCache.automaton nba_accept_cache in let nba_cached = if listening then NMATiming.full_timing nba_cached_without_timing (new_timing "nba_cached_timing") else nba_cached_without_timing in let dpa_without_timing = NBAtoDPA.transform nba_cached (lmmc_thread_nba_state_size decformula) in let dpa = if listening then DMATiming.full_timing dpa_without_timing (new_timing "dpa_timing") else dpa_without_timing in let dpa_state_cache = DMAStateCache.make2 dpa in let dpa_delta_cache = DMADeltaCache.make (DMAStateCache.automaton2 dpa_state_cache) in let dpa_accept_cache = DMAAcceptCache.make (DMADeltaCache.automaton dpa_delta_cache) in let dpa_cached_without_timing = DMAAcceptCache.automaton dpa_accept_cache in let dpa_cached = if listening then DMATiming.full_timing dpa_cached_without_timing (new_timing "dpa_cached_timing") else dpa_cached_without_timing in let states_nba _ = NMAStateCache.state_size2 nba_state_cache in let transitions_nba _ = NMADeltaCache.edge_size nba_delta_cache in let states_dpa _ = DMAStateCache.state_size2 dpa_state_cache in let transitions_dpa _ = DMADeltaCache.edge_size dpa_delta_cache in let states_game = ref 0 in let info_list = [("nba_states", states_nba); ("nba_transitions", transitions_nba); ("dpa_states", states_dpa); ("dpa_transitions", transitions_dpa); ("game_states", fun () -> !states_game)] in let game = let temp = get_validity_game decformula dpa_cached use_literal_propagation (without_guardedness && not (is_guarded goalformula)) in let temp = if compact_game then get_compact_initpg_by_player temp false else get_escaped_initpg temp 0 in if listening then get_timed_initpg temp (new_timing "game_timing") else temp in let (game_cached, state_to_int, int_to_state) = ( let (temp, state_to_int, int_to_state) = get_int_cached_initpg game (fun _ i -> states_game := i) in ((if listening then get_timed_initpg temp (new_timing "game_cached_timing") else temp), state_to_int, int_to_state) ) in constr_msg (fun _ -> SimpleTiming.format t ^ "\n"); let ((init, b, c, d, fo), e) = game_cached in let fo' = if proof_game_in_annot then (fun s -> fo s) else (fun _ -> "") in let game_cached' = ((init, b, c, d, fo'), e) in let show_stats _ = if listening then ( List.iter (fun (s, v) -> constr_msg (fun _ -> s ^ ": " ^ string_of_int (v ()) ^ "\n") ) info_list; List.iter (fun (s, t) -> constr_msg (fun _ -> s ^ ": " ^ (SimpleTiming.format t) ^ "\n") ) !timing_list ); info_msg (fun _ -> "Game has " ^ string_of_int !states_game ^ " states (NBA " ^ string_of_int (states_nba ()) ^ " , DPA " ^ string_of_int (states_dpa ()) ^ ").\n") in let counter_mod strategy printer = info_msg (fun _ -> "Extracting Transition System.\n"); constr_msg (fun _ -> "Building Transition System...\n"); let t = SimpleTiming.init true in let lts = extract_counter_model decformula game_cached strategy int_to_state state_to_int in let ((_, _, _, fo), _) = lts in let states_lts = ref 0 in let (lts_cached, lts_state_to_int, lts_int_to_state) = get_int_cached_initlts lts (fun _ i -> states_lts := i) in let fmt = if proof_game_in_annot then (fun s -> Some (fo s)) else (fun _ -> None) in let explicit_lts = build_explicit_initlts lts_cached lts_int_to_state fmt (fun i -> if (i mod 1000 = 0) then constr_msg (fun _ -> "\rBuilding..." ^ string_of_int i) ) in constr_msg (fun _ -> "\rBuilding... finished in " ^ SimpleTiming.format t ^ "\n\n"); let (_, (_, _, graph)) = explicit_lts in info_msg (fun _ -> "Transition System has " ^ string_of_int (Array.length graph) ^ " states.\n"); print_explicit_initlts explicit_lts printer in (game_cached', show_stats, (fun sol strat -> if sol init = Some true then FormulaValid else FormulaFalsifiableBy (counter_mod strat)));; let register _ = register_validity_procedure validity_proc "lmmc" "Decision Procedure For Labelled Modal Mu Calculus"
null
https://raw.githubusercontent.com/tcsprojects/mlsolver/fdd1d7550aa57a42886160ae1e8336c1111b7d94/src/automata/lmmc/lmmcvaliditygame.ml
ocaml
variables, branching modalities propositions automaton
open Tcsautomata;; open Tcsautohelper;; open Tcsautotransform;; open Tcstransitionsys;; open Tcsgames;; open Tcsset;; open Tcslist;; open Tcsarray;; open Tcstiming;; open Tcsbasedata;; open Tcsmessage;; open Tcslmmcformula;; open Lmmcthreadnba;; open Validitygamesregistry;; type 'a state = TT | NT of int list type 'a validity_game = 'a state initpg;; type simplification_result = SimplTT | SimplFF | SimplKeep;; let rec simplify ((_, fmls, prop, _, _) as fml) props i = match fmls.(i) with FIntAtom b -> if b then SimplTT else SimplFF | FIntProp (b, p) -> if TreeSet.mem ((if b then fst else snd) (snd prop.(p))) props then SimplFF else if TreeSet.mem ((if b then snd else fst) (snd prop.(p))) props then SimplTT else SimplKeep | FIntBranch (true, l, r) -> ( match simplify fml props l with SimplTT -> SimplTT | SimplFF -> simplify fml props r | SimplKeep -> if simplify fml props r = SimplTT then SimplTT else SimplKeep ) | FIntBranch (false, l, r) -> ( match simplify fml props l with SimplFF -> SimplFF | SimplTT -> simplify fml props r | SimplKeep -> if simplify fml props r = SimplFF then SimplFF else SimplKeep ) | _ -> SimplKeep let get_validity_game (((r, fmls, props, vars, lbls) as fml): decomposed_labelled_mmc_formula) dpa use_literal_propagation allow_removal_of_mu = let dpa_initial_state = DMA.initial dpa in let dpa_delta x y = DMA.delta dpa x y in let dpa_omega = DMA.accept dpa in let state_cmp = Domain.compare (DMA.states dpa) in let dpa_state_format = Domain.format (DMA.states dpa) in let format_formula = format_decomposed_formula fml in let rec finish new_formulas = function TT -> TT | NT s -> NT s | Tuple ((a, b, c), d) -> ( let (newa, newb, newc, is_true) = (ref [], ref [], ref [], ref false) in List.iter (fun f -> match fmls.(f) with FIntAtom b -> if b then is_true := true | FIntModality _ -> newb := f::!newb | FIntProp (b, p) -> newc := (f, (if b then snd else fst) (snd props.(p)))::!newc | _ -> newa := f::!newa ) new_formulas; if !is_true then TT else ( let c = ref (TreeSet.of_list_def c) in List.iter (fun (f, f') -> if (TreeSet.mem f' !c) then is_true := true else c := TreeSet.add f !c ) !newc; if !is_true then TT else ( let a = TreeSet.elements (TreeSet.union (TreeSet.of_list_def !newa) (TreeSet.of_list_def a)) in let b = TreeSet.elements (TreeSet.union (TreeSet.of_list_def !newb) (TreeSet.of_list_def b)) in let c = TreeSet.elements !c in if (a = []) && (b = []) then NT c else Tuple ((a, b, c), d) ) ) ) in let initial_state = finish [r] (Tuple (([], [], []), dpa_initial_state)) in let exist_pos = function Tuple ((x::_, _, _), _) -> if allow_removal_of_mu then ( match fmls.(x) with FIntVariable i -> let (nufp, _, _, _) = snd vars.(i) in not nufp | _ -> false ) else false | _ -> true in let rec delta = function Tuple ((a, b, c), d) -> ( match a with f::a -> ( match fmls.(f) with FIntVariable i -> let (nufp, _, gua, f') = snd vars.(i) in let s = finish [f'] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Follow f))) in if allow_removal_of_mu && (not nufp) && not gua then [s; finish [] (Tuple ((a,b,c), dpa_delta d (Lmmcthreadnba.Delete f)))] else [s] | FIntBranch (true, f1, f2) -> if use_literal_propagation then ( let propsset = TreeSet.of_list_def c in let f1s = simplify fml propsset f1 in let f2s = simplify fml propsset f2 in if (f1s = SimplFF && f2s = SimplFF) then [finish [] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Delete f)))] else if (f1s = SimplTT || f2s = SimplTT) then [TT] else if (f1s = SimplFF || f2s = SimplFF) then let d = dpa_delta d (Lmmcthreadnba.Follow f) in let d = dpa_delta d (Lmmcthreadnba.Delete (if f1s = SimplFF then f1 else f2)) in [finish [if f2s = SimplFF then f1 else f2] (Tuple ((a, b, c), d))] else [finish [f1; f2] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Follow f)))] ) else [finish [f1; f2] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Follow f)))] | FIntBranch (false, f1, f2) -> if use_literal_propagation then ( let propsset = TreeSet.of_list_def c in let f1s = simplify fml propsset f1 in let f2s = simplify fml propsset f2 in if (f1s = SimplFF || f2s = SimplFF) then [finish [] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Delete f)))] else if (f1s = SimplTT && f2s = SimplTT) then [TT] else if (f1s = SimplTT || f2s = SimplTT) then [finish [if f2s = SimplTT then f1 else f2] (Tuple ((a, b, c), dpa_delta d (Lmmcthreadnba.Branch (f2s = SimplTT, f))))] else let d1 = dpa_delta d (Lmmcthreadnba.Branch (true, f)) in let d2 = dpa_delta d (Lmmcthreadnba.Branch (false, f)) in [finish [f1] (Tuple ((a, b, c), d1)); finish [f2] (Tuple ((a, b, c), d2))] ) else let d1 = dpa_delta d (Lmmcthreadnba.Branch (true, f)) in let d2 = dpa_delta d (Lmmcthreadnba.Branch (false, f)) in [finish [f1] (Tuple ((a, b, c), d1)); finish [f2] (Tuple ((a, b, c), d2))] | _ -> failwith "Labelledmmcvaliditygame.delta: Failure 1!" ) | [] -> if b = [] then failwith "Labelledmmcvaliditygame.delta: Failure 2!" else ( let b = List.map (fun f -> match fmls.(f) with (FIntModality (x,y,z)) -> (f, (x,y,z)) | _ -> failwith "Labelledmmcvaliditygame.delta: Failure 3!" ) b in let (diamonds, boxes) = List.partition (fun (_, (b, _, _)) -> b) b in if boxes = [] then [NT c] else ( let l = ref 0 in let mp = ref TreeMap.empty_def in List.iter (fun (_, (_, lab, _)) -> if not (TreeMap.mem lab !mp) then ( mp := TreeMap.add lab !l !mp; incr l ) ) boxes; let part = Array.make !l ([], [], -1) in List.iter (fun (f, (b, lab, g)) -> try let i = TreeMap.find lab !mp in let (dia, box, _) = part.(i) in part.(i) <- if b then (g::dia, box, lab) else (dia, (f, g)::box, lab) with Not_found -> () ) b; let ret = ref [] in Array.iter (fun (dia, box, lab) -> List.iter (fun (f, g) -> let d = dpa_delta d (Lmmcthreadnba.Follow f) in let s = finish (g::dia) (Tuple (([], [], []), d)) in ret := s::!ret ) box ) part; !ret ) ) ) | s -> [s] in let omega = function TT -> 0 | NT _ -> 1 | Tuple (_, q) -> dpa_omega q in let format_state = function TT -> "TT" | NT s -> "NT (" ^ ListUtils.format format_formula s ^ ")" | Tuple ((a, b, c), f) -> "Tuple (" ^ ListUtils.format format_formula (a@b@c) ^ ", " ^ dpa_state_format f ^ ")" in let comp' cmp s1 s2 = match (s1, s2) with (Tuple (a, x), Tuple (b, y)) -> ( let c = compare a b in if c = 0 then cmp x y else c ) | _ -> compare s1 s2 in let comp = Some (comp' state_cmp) in ((initial_state, delta, omega, exist_pos, format_state), (None, None, comp));; let extract_counter_model (dec_formula: decomposed_labelled_mmc_formula) (validity_game: int initpg) strategy int_to_state state_to_int = let (_, fmls, props, _, labels) = dec_formula in let ((init, delta, _, ex, fo), _) = validity_game in let props_final i = fst props.(i) in let labels_final i = labels.(i) in let rec finalize i = match (fst (int_to_state i)) with TT -> i | NT _ -> i | Tuple (([], _, _), _) -> i | _ -> finalize (if ex i then List.hd (delta i) else OptionUtils.get_some (strategy i)) in let init_final = finalize init in let get_props_final i = let convert l = List.filter (fun i -> i >= 0) (List.map (fun f -> match fmls.(f) with FIntProp (false, p) -> p | _ -> -1 ) l) in match (fst (int_to_state i)) with TT -> [] | NT l -> convert l | Tuple ((_, _, l), _) -> convert l in let get_delta_final i = match (int_to_state i) with (Tuple (([], b, _), q), r) -> ( let boxes = ref [] in let diamonds = ref [] in List.iter (fun f -> match fmls.(f) with (FIntModality (b,l,_)) -> ( if b then diamonds := f::!diamonds else boxes := (f,l)::!boxes ) | _ -> failwith "Impossible." ) b; List.map (fun (box, lab) -> (lab, finalize (List.hd (delta (state_to_int (Tuple (([], box::!diamonds, []), q), r))))) ) !boxes ) | _ -> [] in let get_annot_final i = fo i in let compare_final i j = compare i j in ((init_final, get_props_final, get_delta_final, get_annot_final), (Some compare_final, labels_final, props_final)) let compare_formula f g = match (f, g) with (FIntBranch (true, _, _), FIntBranch (false, _, _)) -> -1 | (FIntBranch (false, _, _), FIntBranch (true, _, _)) -> 1 | _ -> compare f g;; let validity_proc formula options (info_chan, formula_chan, constr_chan) = let proof_game_in_annot = ArrayUtils.mem "ann" options in let compact_game = ArrayUtils.mem "comp" options in let use_literal_propagation = ArrayUtils.mem "litpro" options in let length_sort = if ArrayUtils.mem "prefersmall" options then 1 else if ArrayUtils.mem "preferlarge" options then -1 else 0 in let without_guardedness = ArrayUtils.mem "woguarded" options in let info_msg = MessageChannel.send_message info_chan in let formula_msg = MessageChannel.send_message formula_chan in let constr_msg = MessageChannel.send_message constr_chan in info_msg (fun _ -> "Decision Procedure For Labelled Modal Mu Calculus\n"); formula_msg (fun _ -> "Transforming given formula..."); let t = SimpleTiming.init true in let formula' = eval_metaformula formula in let goalformula' = make_uniquely_bound (formula_to_positive formula') in let goalformula = if is_guarded goalformula' || without_guardedness then goalformula' else make_uniquely_bound (guarded_transform goalformula') in formula_msg (fun _ -> SimpleTiming.format t ^ "\n"); formula_msg (fun _ -> "Transformed formula: " ^ format_formula goalformula ^ "\n"); formula_msg (fun _ -> "Formula Length: " ^ string_of_int (formula_length goalformula) ^ "\n"); formula_msg (fun _ -> let (t,g,u) = formula_variable_occs goalformula in "Formula Variable Occurrences: " ^ string_of_int t ^ "\n"); constr_msg (fun _ -> "Decompose formula..."); let t = SimpleTiming.init true in let decformula = normal_form_formula_to_decomposed_formula goalformula in let decformula = if length_sort = 0 then sort_decomposed_formula decformula (fun _ -> compare_formula) else sort_decomposed_formula decformula (fun d a b -> length_sort * compare (get_formula_depth d a) (get_formula_depth d b)) in constr_msg (fun _ -> SimpleTiming.format t ^ "\n"); formula_msg (fun _ -> "Subformula Cardinality: " ^ string_of_int (decomposed_formula_subformula_cardinality decformula) ^ "\n"); constr_msg (fun _ -> "Initializing automata..."); let t = SimpleTiming.init true in let timing_list = ref [] in let new_timing s = let t = SimpleTiming.init false in timing_list := (s, t)::!timing_list; t in let listening = MessageChannel.channel_is_listening constr_chan in let nba_without_timing = lmmc_thread_nba decformula in let nba = if listening then NMATiming.full_timing nba_without_timing (new_timing "nba_timing") else nba_without_timing in let nba_state_cache = NMAStateCache.make2 nba in let nba_delta_cache = NMADeltaCache.make (NMAStateCache.automaton2 nba_state_cache) in let nba_accept_cache = NMAAcceptCache.make (NMADeltaCache.automaton nba_delta_cache) in let nba_cached_without_timing = NMAAcceptCache.automaton nba_accept_cache in let nba_cached = if listening then NMATiming.full_timing nba_cached_without_timing (new_timing "nba_cached_timing") else nba_cached_without_timing in let dpa_without_timing = NBAtoDPA.transform nba_cached (lmmc_thread_nba_state_size decformula) in let dpa = if listening then DMATiming.full_timing dpa_without_timing (new_timing "dpa_timing") else dpa_without_timing in let dpa_state_cache = DMAStateCache.make2 dpa in let dpa_delta_cache = DMADeltaCache.make (DMAStateCache.automaton2 dpa_state_cache) in let dpa_accept_cache = DMAAcceptCache.make (DMADeltaCache.automaton dpa_delta_cache) in let dpa_cached_without_timing = DMAAcceptCache.automaton dpa_accept_cache in let dpa_cached = if listening then DMATiming.full_timing dpa_cached_without_timing (new_timing "dpa_cached_timing") else dpa_cached_without_timing in let states_nba _ = NMAStateCache.state_size2 nba_state_cache in let transitions_nba _ = NMADeltaCache.edge_size nba_delta_cache in let states_dpa _ = DMAStateCache.state_size2 dpa_state_cache in let transitions_dpa _ = DMADeltaCache.edge_size dpa_delta_cache in let states_game = ref 0 in let info_list = [("nba_states", states_nba); ("nba_transitions", transitions_nba); ("dpa_states", states_dpa); ("dpa_transitions", transitions_dpa); ("game_states", fun () -> !states_game)] in let game = let temp = get_validity_game decformula dpa_cached use_literal_propagation (without_guardedness && not (is_guarded goalformula)) in let temp = if compact_game then get_compact_initpg_by_player temp false else get_escaped_initpg temp 0 in if listening then get_timed_initpg temp (new_timing "game_timing") else temp in let (game_cached, state_to_int, int_to_state) = ( let (temp, state_to_int, int_to_state) = get_int_cached_initpg game (fun _ i -> states_game := i) in ((if listening then get_timed_initpg temp (new_timing "game_cached_timing") else temp), state_to_int, int_to_state) ) in constr_msg (fun _ -> SimpleTiming.format t ^ "\n"); let ((init, b, c, d, fo), e) = game_cached in let fo' = if proof_game_in_annot then (fun s -> fo s) else (fun _ -> "") in let game_cached' = ((init, b, c, d, fo'), e) in let show_stats _ = if listening then ( List.iter (fun (s, v) -> constr_msg (fun _ -> s ^ ": " ^ string_of_int (v ()) ^ "\n") ) info_list; List.iter (fun (s, t) -> constr_msg (fun _ -> s ^ ": " ^ (SimpleTiming.format t) ^ "\n") ) !timing_list ); info_msg (fun _ -> "Game has " ^ string_of_int !states_game ^ " states (NBA " ^ string_of_int (states_nba ()) ^ " , DPA " ^ string_of_int (states_dpa ()) ^ ").\n") in let counter_mod strategy printer = info_msg (fun _ -> "Extracting Transition System.\n"); constr_msg (fun _ -> "Building Transition System...\n"); let t = SimpleTiming.init true in let lts = extract_counter_model decformula game_cached strategy int_to_state state_to_int in let ((_, _, _, fo), _) = lts in let states_lts = ref 0 in let (lts_cached, lts_state_to_int, lts_int_to_state) = get_int_cached_initlts lts (fun _ i -> states_lts := i) in let fmt = if proof_game_in_annot then (fun s -> Some (fo s)) else (fun _ -> None) in let explicit_lts = build_explicit_initlts lts_cached lts_int_to_state fmt (fun i -> if (i mod 1000 = 0) then constr_msg (fun _ -> "\rBuilding..." ^ string_of_int i) ) in constr_msg (fun _ -> "\rBuilding... finished in " ^ SimpleTiming.format t ^ "\n\n"); let (_, (_, _, graph)) = explicit_lts in info_msg (fun _ -> "Transition System has " ^ string_of_int (Array.length graph) ^ " states.\n"); print_explicit_initlts explicit_lts printer in (game_cached', show_stats, (fun sol strat -> if sol init = Some true then FormulaValid else FormulaFalsifiableBy (counter_mod strat)));; let register _ = register_validity_procedure validity_proc "lmmc" "Decision Procedure For Labelled Modal Mu Calculus"
0effad88d71d198199b0dd4cd09651a8009a0ad6ad986b5b388dd3bae6c5a95e
tjammer/raylib-ocaml
shaders_mesh_instanced.ml
open Raylib open Rlights let width = 800 let height = 450 let count = 10000 let main () = set_config_flags [ ConfigFlags.Msaa_4x_hint; ConfigFlags.Window_resizable ]; init_window width height "raylib [shaders] example - rlgl mesh instanced"; let position = Vector3.create 125.0 125.0 125.0 in let target = Vector3.create 0.0 0.0 0.0 in let up = Vector3.create 0.0 1.0 0.0 in let camera = Camera.create position target up 45.0 CameraProjection.Perspective in set_camera_mode camera CameraMode.Free; set_target_fps 60; let cube = gen_mesh_cube 1.0 1.0 1.0 in let rand_float lower upper = get_random_value lower upper |> float_of_int in let matrix_translation _ = Matrix.translate (rand_float (-50) 50) (rand_float (-50) 50) (rand_float (-50) 50) in let matrix_rotation _ = let axis = Vector3.create (rand_float 0 360) (rand_float 0 360) (rand_float 0 360) |> Vector3.normalize in let angle = rand_float 0 50 *. Float.pi /. 180.0 /. 1000.0 in Matrix.rotate axis angle in (* draw_mesh_instanced takes a ptr. CArrays can be instantly cast to/from ptrs *) let translations = CArray.from_ptr (Ctypes.allocate_n Matrix.t ~count) count in let rotations_inc = Array.init count matrix_rotation in let rotations = CArray.from_ptr (Ctypes.allocate_n Matrix.t ~count) count in for i = 0 to count - 1 do CArray.set translations i (matrix_translation i); CArray.set rotations i (matrix_rotation i) done; let shader = load_shader "resources/base_lighting_instanced.vs" "resources/lighting.fs" in if Shader.id shader = Unsigned.UInt.zero then failwith "Shader failed to compile"; let mvp = get_shader_location shader "mvp" in let view_pos = get_shader_location shader "viewPos" in let instance = get_shader_location_attrib shader "instance" in let ambient = get_shader_location shader "ambient" in (* Get the locs array and assign the locations of the variables. This is necessary for the draw_mesh_instanced call. * Curiously, draw_mesh works without setting these. *) let locs = Shader.locs shader in CArray.set locs ShaderLocationIndex.(Matrix_mvp |> to_int) mvp; CArray.set locs ShaderLocationIndex.(Vector_view |> to_int) view_pos; CArray.set locs ShaderLocationIndex.(Matrix_model |> to_int) instance; let ambient_vec = Vector4.create 0.2 0.2 0.2 1.0 in set_shader_value shader ambient (to_voidp (addr ambient_vec)) ShaderUniformDataType.Vec4; create_light Directional (Vector3.create 50.0 50.0 0.0) (Vector3.zero ()) Color.white shader |> ignore; let material = load_material_default () in Material.set_shader material shader; MaterialMap.set_color (CArray.get (Material.maps material) 0) Color.red; while not (Raylib.window_should_close ()) do update_camera (addr camera); let cpos = Camera3D.position camera in let pos = Vector3.(create (x cpos) (y cpos) (z cpos)) in set_shader_value (Material.shader material) view_pos (pos |> addr |> to_voidp) ShaderUniformDataType.Vec3; for i = 0 to count - 1 do CArray.set rotations i Matrix.(multiply (CArray.get rotations i) rotations_inc.(i)); CArray.set translations i Matrix.(multiply (CArray.get rotations i) (CArray.get translations i)) done; begin_drawing (); clear_background Color.raywhite; begin_mode_3d camera; draw_mesh_instanced cube material (CArray.start translations) count; end_mode_3d (); draw_text "A CUBE OF DANCING CUBES!" 490 10 20 Color.maroon; draw_fps 10 10; end_drawing () done; Raylib.close_window (); print_endline "Execute from the examples/shaders directory. The shaders are accessed via \ relative paths." let () = main ()
null
https://raw.githubusercontent.com/tjammer/raylib-ocaml/76955c30d0a776138daeb93bfc73b104aefc6f6d/examples/shaders/shaders_mesh_instanced.ml
ocaml
draw_mesh_instanced takes a ptr. CArrays can be instantly cast to/from ptrs Get the locs array and assign the locations of the variables. This is necessary for the draw_mesh_instanced call. * Curiously, draw_mesh works without setting these.
open Raylib open Rlights let width = 800 let height = 450 let count = 10000 let main () = set_config_flags [ ConfigFlags.Msaa_4x_hint; ConfigFlags.Window_resizable ]; init_window width height "raylib [shaders] example - rlgl mesh instanced"; let position = Vector3.create 125.0 125.0 125.0 in let target = Vector3.create 0.0 0.0 0.0 in let up = Vector3.create 0.0 1.0 0.0 in let camera = Camera.create position target up 45.0 CameraProjection.Perspective in set_camera_mode camera CameraMode.Free; set_target_fps 60; let cube = gen_mesh_cube 1.0 1.0 1.0 in let rand_float lower upper = get_random_value lower upper |> float_of_int in let matrix_translation _ = Matrix.translate (rand_float (-50) 50) (rand_float (-50) 50) (rand_float (-50) 50) in let matrix_rotation _ = let axis = Vector3.create (rand_float 0 360) (rand_float 0 360) (rand_float 0 360) |> Vector3.normalize in let angle = rand_float 0 50 *. Float.pi /. 180.0 /. 1000.0 in Matrix.rotate axis angle in let translations = CArray.from_ptr (Ctypes.allocate_n Matrix.t ~count) count in let rotations_inc = Array.init count matrix_rotation in let rotations = CArray.from_ptr (Ctypes.allocate_n Matrix.t ~count) count in for i = 0 to count - 1 do CArray.set translations i (matrix_translation i); CArray.set rotations i (matrix_rotation i) done; let shader = load_shader "resources/base_lighting_instanced.vs" "resources/lighting.fs" in if Shader.id shader = Unsigned.UInt.zero then failwith "Shader failed to compile"; let mvp = get_shader_location shader "mvp" in let view_pos = get_shader_location shader "viewPos" in let instance = get_shader_location_attrib shader "instance" in let ambient = get_shader_location shader "ambient" in let locs = Shader.locs shader in CArray.set locs ShaderLocationIndex.(Matrix_mvp |> to_int) mvp; CArray.set locs ShaderLocationIndex.(Vector_view |> to_int) view_pos; CArray.set locs ShaderLocationIndex.(Matrix_model |> to_int) instance; let ambient_vec = Vector4.create 0.2 0.2 0.2 1.0 in set_shader_value shader ambient (to_voidp (addr ambient_vec)) ShaderUniformDataType.Vec4; create_light Directional (Vector3.create 50.0 50.0 0.0) (Vector3.zero ()) Color.white shader |> ignore; let material = load_material_default () in Material.set_shader material shader; MaterialMap.set_color (CArray.get (Material.maps material) 0) Color.red; while not (Raylib.window_should_close ()) do update_camera (addr camera); let cpos = Camera3D.position camera in let pos = Vector3.(create (x cpos) (y cpos) (z cpos)) in set_shader_value (Material.shader material) view_pos (pos |> addr |> to_voidp) ShaderUniformDataType.Vec3; for i = 0 to count - 1 do CArray.set rotations i Matrix.(multiply (CArray.get rotations i) rotations_inc.(i)); CArray.set translations i Matrix.(multiply (CArray.get rotations i) (CArray.get translations i)) done; begin_drawing (); clear_background Color.raywhite; begin_mode_3d camera; draw_mesh_instanced cube material (CArray.start translations) count; end_mode_3d (); draw_text "A CUBE OF DANCING CUBES!" 490 10 20 Color.maroon; draw_fps 10 10; end_drawing () done; Raylib.close_window (); print_endline "Execute from the examples/shaders directory. The shaders are accessed via \ relative paths." let () = main ()
eaef58d59fb423e828d4629f7b740ab4abf63b6297c82ee7970908d38b984147
johnwhitington/ocamli
tinyocamlrw.mli
* Raised by [ of_real_ocaml ] if the program can not be represented in tiny ocaml . exception UnknownNode of string val realops : bool ref * Convert real ocaml to tiny ocaml , raising [ UnknownNode ] if not possible for the given program the given program *) val of_real_ocaml : Tinyocaml.env -> Parsetree.structure -> Tinyocaml.env * Tinyocaml.t val to_real_ocaml : Tinyocaml.t -> Parsetree.structure (* Quick & nasty for top level. Removes the outside struct, returns env, removes let _ = of final. *) val of_string : string -> Tinyocaml.env * Tinyocaml.t
null
https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/tinyocamlrw.mli
ocaml
Quick & nasty for top level. Removes the outside struct, returns env, removes let _ = of final.
* Raised by [ of_real_ocaml ] if the program can not be represented in tiny ocaml . exception UnknownNode of string val realops : bool ref * Convert real ocaml to tiny ocaml , raising [ UnknownNode ] if not possible for the given program the given program *) val of_real_ocaml : Tinyocaml.env -> Parsetree.structure -> Tinyocaml.env * Tinyocaml.t val to_real_ocaml : Tinyocaml.t -> Parsetree.structure val of_string : string -> Tinyocaml.env * Tinyocaml.t
7ed9d8c11c3203837dba7d57f6dc0e4f9a7ce24997ee23c368e2fdc39ee9ee08
retrogradeorbit/cloud-fighter
user.clj
(ns user (:require [figwheel-sidecar.repl-api :as f])) user is a namespace that the Clojure runtime looks for and ;; loads if its available ;; You can place helper functions in here. This is great for starting ;; and stopping your webserver and other development services The definitions in here will be available if you run " repl " or launch a Clojure repl some other way ;; You have to ensure that the libraries you :require are listed in your dependencies ;; Once you start down this path ;; you will probably want to look at ;; tools.namespace ;; and Component (defn fig-start "This starts the figwheel server and watch based auto-compiler." [] this call will only work are long as your : and ;; :figwheel configurations are at the top level of your project.clj and are not spread across different profiles ;; otherwise you can pass a configuration into start-figwheel! manually (f/start-figwheel!)) (defn fig-stop "Stop the figwheel server and watch based auto-compiler." [] (f/stop-figwheel!)) if you are in an nREPL environment you will need to make sure you ;; have setup piggieback for this to work (defn cljs-repl "Launch a ClojureScript REPL that is connected to your build and host environment." [] (f/cljs-repl))
null
https://raw.githubusercontent.com/retrogradeorbit/cloud-fighter/4c4d30fc2d9b14ce4c73f3d252be519daaa09d51/dev/user.clj
clojure
loads if its available You can place helper functions in here. This is great for starting and stopping your webserver and other development services You have to ensure that the libraries you :require are listed in your dependencies Once you start down this path you will probably want to look at tools.namespace and Component :figwheel configurations are at the top level of your project.clj otherwise you can pass a configuration into start-figwheel! manually have setup piggieback for this to work
(ns user (:require [figwheel-sidecar.repl-api :as f])) user is a namespace that the Clojure runtime looks for and The definitions in here will be available if you run " repl " or launch a Clojure repl some other way (defn fig-start "This starts the figwheel server and watch based auto-compiler." [] this call will only work are long as your : and and are not spread across different profiles (f/start-figwheel!)) (defn fig-stop "Stop the figwheel server and watch based auto-compiler." [] (f/stop-figwheel!)) if you are in an nREPL environment you will need to make sure you (defn cljs-repl "Launch a ClojureScript REPL that is connected to your build and host environment." [] (f/cljs-repl))
f751ffd605b0b388ed3f74c106a387f337870dbcc626906d20509baac50b7e91
markus-git/co-feldspar
Compile.hs
# language GADTs # {-# language TypeOperators #-} # language FlexibleContexts # {-# language ScopedTypeVariables #-} {-# language ConstraintKinds #-} {-# language TypeSynonymInstances #-} # language FlexibleInstances # # language MultiParamTypeClasses # # language QuasiQuotes # module Feldspar.Software.Compile where import Feldspar.Representation import Feldspar.Software.Primitive import Feldspar.Software.Primitive.Backend import Feldspar.Software.Expression import Feldspar.Software.Representation import Feldspar.Software.Optimize import Data.Struct import Control.Monad.Identity import Control.Monad.Reader import Data.Proxy import Data.Constraint hiding (Sub) import Data.Map (Map) import qualified Data.Map as Map import Data.Selection import Data.Default.Class -- syntactic. import Language.Syntactic (AST (..), ASTF, (:&:) (..), Args((:*)), prj) import Language.Syntactic.Functional hiding (Binding (..)) import Language.Syntactic.Functional.Tuple import qualified Language.Syntactic as Syn -- operational-higher. import Control.Monad.Operational.Higher (Program) import qualified Control.Monad.Operational.Higher as Oper -- imperative-edsl. import Language.Embedded.Expression import qualified Language.Embedded.Imperative as Imp import qualified Language.Embedded.Imperative.CMD as Imp import qualified Language.Embedded.Imperative.Frontend as Imp import qualified Language.Embedded.Backend.C as Imp import qualified Language.C.Monad as C (CGen, addGlobal, addLocal, addInclude, addStm, gensym) -- hardware-edsl import qualified Language.Embedded.Hardware.Command as Hard -- language-c-quote import Language.C.Quote.GCC import qualified Language.C.Syntax as C -- hmm! import Feldspar.Hardware.Primitive (HardwarePrimType(..), HardwarePrimTypeRep(..)) import Feldspar.Hardware.Expression (HType') import Feldspar.Hardware.Frontend (HSig, withHType') -- debug. import Debug.Trace -------------------------------------------------------------------------------- -- * Software compiler. -------------------------------------------------------------------------------- | Target software instructions . type TargetCMD = Imp.RefCMD Oper.:+: Imp.ArrCMD Oper.:+: Imp.ControlCMD Oper.:+: Imp.FileCMD Oper.:+: Imp.PtrCMD Oper.:+: Imp.C_CMD -- Oper.:+: MMapCMD -- | Target monad during translation. type TargetT m = ReaderT Env (Oper.ProgramT TargetCMD (Oper.Param2 Prim SoftwarePrimType) m) -- | Monad for translated programs. type ProgC = Program TargetCMD (Oper.Param2 Prim SoftwarePrimType) -------------------------------------------------------------------------------- -- ** Compilation of expressions. -- | Struct expression. type VExp = Struct SoftwarePrimType Prim -- | Struct expression with hidden result type. data VExp' where VExp' :: Struct SoftwarePrimType Prim a -> VExp' newRefV :: Monad m => STypeRep a -> String -> TargetT m (Struct SoftwarePrimType Imp.Ref a) newRefV t base = lift $ mapStructA (const (Imp.newNamedRef base)) t initRefV :: Monad m => String -> VExp a -> TargetT m (Struct SoftwarePrimType Imp.Ref a) initRefV base = lift . mapStructA (Imp.initNamedRef base) getRefV :: Monad m => Struct SoftwarePrimType Imp.Ref a -> TargetT m (VExp a) getRefV = lift . mapStructA Imp.getRef setRefV :: Monad m => Struct SoftwarePrimType Imp.Ref a -> VExp a -> TargetT m () setRefV r = lift . sequence_ . zipListStruct Imp.setRef r unsafeFreezeRefV :: Monad m => Struct SoftwarePrimType Imp.Ref a -> TargetT m (VExp a) unsafeFreezeRefV = lift . mapStructA Imp.unsafeFreezeRef -------------------------------------------------------------------------------- -- ** Compilation options. -- | Options affecting code generation -- -- A default set of options is given by 'def'. -- -- The assertion labels to include in the generated code can be stated using the -- functions 'select', 'allExcept' and 'selectBy'. For example -- @`def ` { compilerAssertions = ` allExcept ` [ ` InternalAssertion`]}@ -- -- states that we want to include all except internal assertions. data CompilerOpts = CompilerOpts { compilerAssertions :: Selection AssertionLabel -- ^ Which assertions to include in the generated code } instance Default CompilerOpts where def = CompilerOpts { compilerAssertions = universal } -------------------------------------------------------------------------------- -- ** Compilation environment. data Env = Env { envAliases :: Map Name VExp' , envOptions :: CompilerOpts } env0 :: Env env0 = Env Map.empty def localAlias :: MonadReader Env m => Name -> VExp a -> m b -> m b localAlias v e = local (\env -> env {envAliases = Map.insert v (VExp' e) (envAliases env)}) lookAlias :: MonadReader Env m => STypeRep a -> Name -> m (VExp a) lookAlias t v = do env <- asks envAliases return $ case Map.lookup v env of Nothing -> error $ "lookAlias: variable " ++ show v ++ " not in scope." Just (VExp' e) -> case softwareTypeEq t (softwareTypeRep e) of Just Dict -> e -------------------------------------------------------------------------------- translateExp :: forall m a . Monad m => SExp a -> TargetT m (VExp a) translateExp = goAST . optimize . unSExp where goAST :: ASTF SoftwareDomain b -> TargetT m (VExp b) goAST = Syn.simpleMatch (\(s :&: ValT t) -> go t s) goSmallAST :: SoftwarePrimType b => ASTF SoftwareDomain b -> TargetT m (Prim b) goSmallAST = fmap extractNode . goAST go :: STypeRep (Syn.DenResult sig) -> SoftwareConstructs sig -> Syn.Args (AST SoftwareDomain) sig -> TargetT m (VExp (Syn.DenResult sig)) go t lit Syn.Nil | Just (Lit a) <- prj lit = return $ mapStruct (constExp . runIdentity) $ toStruct t a -- go t lit Syn.Nil -- | Just (Literal a) <- prj lit = return $ mapStruct ( constExp . runIdentity ) $ toStruct t a go t var Syn.Nil | Just (FreeVar v) <- prj var = return $ Node $ sugarSymPrim $ FreeVar v go t var Syn.Nil | Just (VarT v) <- prj var = do lookAlias t v go t lt (a :* (lam :$ body) :* Syn.Nil) | Just (Let tag) <- prj lt , Just (LamT v) <- prj lam = do let base = if null tag then "let" else tag r <- initRefV base =<< goAST a a' <- unsafeFreezeRefV r localAlias v a' $ goAST body go t ffi args | Just (Construct addr sem) <- prj ffi = do undefined go t tup (a :* b :* Syn.Nil) | Just Pair <- prj tup = Branch <$> goAST a <*> goAST b go t sel (ab :* Syn.Nil) | Just Fst <- prj sel = do branch <- goAST ab case branch of (Branch a _) -> return a | Just Snd <- prj sel = do branch <- goAST ab case branch of (Branch _ b) -> return b go ty cond (b :* t :* f :* Syn.Nil) | Just Cond <- prj cond = do res <- newRefV ty "b" b' <- goSmallAST b ReaderT $ \env -> Imp.iff b' (flip runReaderT env $ setRefV res =<< goAST t) (flip runReaderT env $ setRefV res =<< goAST f) unsafeFreezeRefV res go _ op (a :* Syn.Nil) | Just Neg <- prj op = liftStruct (sugarSymPrim Neg) <$> goAST a | Just Not <- prj op = liftStruct (sugarSymPrim Not) <$> goAST a | Just Exp <- prj op = liftStruct (sugarSymPrim Exp) <$> goAST a | Just Log <- prj op = liftStruct (sugarSymPrim Log) <$> goAST a | Just Sqrt <- prj op = liftStruct (sugarSymPrim Sqrt) <$> goAST a | Just Sin <- prj op = liftStruct (sugarSymPrim Sin) <$> goAST a | Just Cos <- prj op = liftStruct (sugarSymPrim Cos) <$> goAST a | Just Tan <- prj op = liftStruct (sugarSymPrim Tan) <$> goAST a | Just Asin <- prj op = liftStruct (sugarSymPrim Asin) <$> goAST a | Just Acos <- prj op = liftStruct (sugarSymPrim Acos) <$> goAST a | Just Atan <- prj op = liftStruct (sugarSymPrim Atan) <$> goAST a | Just Sinh <- prj op = liftStruct (sugarSymPrim Sinh) <$> goAST a | Just Cosh <- prj op = liftStruct (sugarSymPrim Cosh) <$> goAST a | Just Tanh <- prj op = liftStruct (sugarSymPrim Tanh) <$> goAST a | Just Asinh <- prj op = liftStruct (sugarSymPrim Asinh) <$> goAST a | Just Acosh <- prj op = liftStruct (sugarSymPrim Acosh) <$> goAST a | Just Atanh <- prj op = liftStruct (sugarSymPrim Atanh) <$> goAST a | Just Real <- prj op = liftStruct (sugarSymPrim Real) <$> goAST a | Just Imag <- prj op = liftStruct (sugarSymPrim Imag) <$> goAST a | Just Magnitude <- prj op = liftStruct (sugarSymPrim Magnitude) <$> goAST a | Just Phase <- prj op = liftStruct (sugarSymPrim Phase) <$> goAST a | Just Conjugate <- prj op = liftStruct (sugarSymPrim Conjugate) <$> goAST a | Just I2N <- prj op = liftStruct (sugarSymPrim I2N) <$> goAST a | Just I2B <- prj op = liftStruct (sugarSymPrim I2B) <$> goAST a | Just B2I <- prj op = liftStruct (sugarSymPrim B2I) <$> goAST a | Just Round <- prj op = liftStruct (sugarSymPrim Round) <$> goAST a | Just BitCompl <- prj op = liftStruct (sugarSymPrim BitCompl) <$> goAST a go _ op (a :* b :* Syn.Nil) | Just Add <- prj op = liftStruct2 (sugarSymPrim Add) <$> goAST a <*> goAST b | Just Sub <- prj op = liftStruct2 (sugarSymPrim Sub) <$> goAST a <*> goAST b | Just Mul <- prj op = liftStruct2 (sugarSymPrim Mul) <$> goAST a <*> goAST b | Just Div <- prj op = liftStruct2 (sugarSymPrim Div) <$> goAST a <*> goAST b | Just Mod <- prj op = liftStruct2 (sugarSymPrim Mod) <$> goAST a <*> goAST b | Just Eq <- prj op = liftStruct2 (sugarSymPrim Eq) <$> goAST a <*> goAST b | Just And <- prj op = liftStruct2 (sugarSymPrim And) <$> goAST a <*> goAST b | Just Or <- prj op = liftStruct2 (sugarSymPrim Or) <$> goAST a <*> goAST b | Just Lt <- prj op = liftStruct2 (sugarSymPrim Lt) <$> goAST a <*> goAST b | Just Lte <- prj op = liftStruct2 (sugarSymPrim Lte) <$> goAST a <*> goAST b | Just Gt <- prj op = liftStruct2 (sugarSymPrim Gt) <$> goAST a <*> goAST b | Just Gte <- prj op = liftStruct2 (sugarSymPrim Gte) <$> goAST a <*> goAST b | Just FDiv <- prj op = liftStruct2 (sugarSymPrim FDiv) <$> goAST a <*> goAST b | Just Complex <- prj op = liftStruct2 (sugarSymPrim Complex) <$> goAST a <*> goAST b | Just Polar <- prj op = liftStruct2 (sugarSymPrim Polar) <$> goAST a <*> goAST b | Just Pow <- prj op = liftStruct2 (sugarSymPrim Pow) <$> goAST a <*> goAST b | Just BitAnd <- prj op = liftStruct2 (sugarSymPrim BitAnd) <$> goAST a <*> goAST b | Just BitOr <- prj op = liftStruct2 (sugarSymPrim BitOr) <$> goAST a <*> goAST b | Just BitXor <- prj op = liftStruct2 (sugarSymPrim BitXor) <$> goAST a <*> goAST b | Just ShiftL <- prj op = liftStruct2 (sugarSymPrim ShiftL) <$> goAST a <*> goAST b | Just ShiftR <- prj op = liftStruct2 (sugarSymPrim ShiftR) <$> goAST a <*> goAST b | Just RotateL <- prj op = liftStruct2 (sugarSymPrim RotateL) <$> goAST a <*> goAST b | Just RotateR <- prj op = liftStruct2 (sugarSymPrim RotateR) <$> goAST a <*> goAST b go t guard (cond :* a :* Syn.Nil) | Just (GuardVal lbl msg) <- prj guard = do cond' <- extractNode <$> goAST cond lift $ Imp.assert cond' msg goAST a go t hint (cond :* a :* Syn.Nil) | Just (HintVal) <- prj hint = do cond' <- extractNode <$> goAST cond lift $ Imp.hint cond' goAST a go t loop (min :* max :* init :* (lami :$ (lams :$ body)) :* Syn.Nil) | Just ForLoop <- prj loop , Just (LamT iv) <- prj lami , Just (LamT sv) <- prj lams = do min' <- goSmallAST min max' <- goSmallAST max state <- initRefV "state" =<< goAST init ReaderT $ \env -> Imp.for (min', 1, Imp.Excl max') $ \i -> flip runReaderT env $ do s <- case t of Node _ -> unsafeFreezeRefV state _ -> getRefV state s' <- localAlias iv (Node i) $ localAlias sv s $ goAST body setRefV state s' unsafeFreezeRefV state go _ arrIx (i :* Syn.Nil) | Just (ArrIx arr) <- prj arrIx = do i' <- goSmallAST i return $ Node $ sugarSymPrim (ArrIx arr) i' go _ s _ = error $ "software translation handling for symbol " ++ Syn.renderSym s ++ " is missing." unsafeTranslateSmallExp :: Monad m => SExp a -> TargetT m (Prim a) unsafeTranslateSmallExp a = do node <- translateExp a case node of (Node b) -> return b -------------------------------------------------------------------------------- -- * Interpretation of software commands. -------------------------------------------------------------------------------- instance ( Imp . CompExp exp , Imp . CompTypeClass ct ) = > Oper . Interp PtrCMD C.CGen ( Oper . Param2 exp ct ) where interp = compPtrCMD compPtrCMD : : forall exp ct a . ( Imp . CompExp exp , Imp . CompTypeClass ct ) = > PtrCMD ( Oper . ) a - > C.CGen a compPtrCMD = undefined instance (Imp.CompExp exp, Imp.CompTypeClass ct) => Oper.Interp PtrCMD C.CGen (Oper.Param2 exp ct) where interp = compPtrCMD compPtrCMD :: forall exp ct a . (Imp.CompExp exp, Imp.CompTypeClass ct) => PtrCMD (Oper.Param3 C.CGen exp ct) a -> C.CGen a compPtrCMD = undefined -} -------------------------------------------------------------------------------- instance (Imp.CompExp exp, Imp.CompTypeClass ct) => Oper.Interp MMapCMD C.CGen (Oper.Param2 exp ct) where interp = compMMapCMD -- todo: -- > only need one 'ix' for read/write to arrays in 'Call'. > ' n ' in ' MMap ' is n't really an ' $ i d ' . compMMapCMD :: forall exp ct a . (Imp.CompExp exp, Imp.CompTypeClass ct) => MMapCMD (Oper.Param3 C.CGen exp ct) a -> C.CGen a compMMapCMD (MMap n sig) = do C.addInclude "<stdio.h>" C.addInclude "<stdlib.h>" C.addInclude "<stddef.h>" C.addInclude "<unistd.h>" C.addInclude "<sys/mman.h>" C.addInclude "<fcntl.h>" C.addGlobal [cedecl| unsigned page_size = 0; |] C.addGlobal [cedecl| int mem_fd = -1; |] C.addGlobal mmap_def mem <- C.gensym "mem" C.addLocal [cdecl| int * $id:mem = f_map($id:n); |] return mem compMMapCMD (Call (Address ptr sig) arg) = do traverse 0 sig arg where traverse :: Integer -> HSig b -> Argument ct (Soften b) -> C.CGen () traverse ix (Hard.Ret _) (Nil) = return () traverse ix (Hard.SSig _ Hard.Out rf) (ARef (Ref (Node ref@(Imp.RefComp r))) arg) = do typ <- compRefType (Proxy :: Proxy ct) ref C.addStm [cstm| $id:r = ($ty:typ) *($id:ptr + $int:ix); |] traverse (ix + 1) (rf dummy) arg traverse ix (Hard.SArr _ Hard.Out len af) (AArr (Arr _ _ (Node arr@(Imp.ArrComp a))) arg) = do let end = ix + toInteger len i <- C.gensym "ix" typ <- compArrType (Proxy :: Proxy ct) arr C.addLocal [cdecl| int $id:i; |] C.addStm [cstm| for ($id:i=$int:ix; $id:i<$int:end; $id:i++) { $id:arr[$id:i] = ($ty:typ) *($id:ptr + $id:i); } |] traverse end (af dummy) arg traverse ix (Hard.SSig _ Hard.In rf) (ARef (Ref (Node (Imp.RefComp r))) arg) = do C.addStm [cstm| *($id:ptr + $int:ix) = (int) $id:r; |] traverse (ix + 1) (rf dummy) arg traverse ix (Hard.SArr _ Hard.In len af) (AArr (Arr _ _ (Node arr@(Imp.ArrComp a))) arg) = do let end = ix + toInteger len i <- C.gensym "ix" typ <- compArrType (Proxy :: Proxy ct) arr C.addLocal [cdecl| int $id:i; |] C.addStm [cstm| for ($id:i=$int:ix; $id:i<$int:end; $id:i++) { *($id:ptr + $id:i) = (int) $id:arr[$id:i]; } |] traverse end (af dummy) arg dummy :: forall x . x dummy = error "dummy evaluated." compRefType :: forall x . (Imp.CompTypeClass ct, HardwarePrimType x, ct x) => Proxy ct -> Imp.Ref x -> C.CGen C.Type compRefType ct _ = case witnessSP (Proxy :: Proxy x) of Dict -> Imp.compType ct (Proxy :: Proxy x) compArrType :: forall i x . (Imp.CompTypeClass ct, HardwarePrimType x, ct x) => Proxy ct -> Imp.Arr i x -> C.CGen C.Type compArrType ct _ = case witnessSP (Proxy :: Proxy x) of Dict -> Imp.compType ct (Proxy :: Proxy x) witnessSP :: forall x . HardwarePrimType x => Proxy x -> Dict (SoftwarePrimType x) witnessSP _ = case hardwareRep :: HardwarePrimTypeRep x of BoolHT -> Dict Int8HT -> Dict Int16HT -> Dict Int32HT -> Dict Int64HT -> Dict Word8HT -> Dict Word16HT -> Dict Word32HT -> Dict Word64HT -> Dict _ -> error "unrecognized software type used by mmap." -------------------------------------------------------------------------------- mmap_def :: C.Definition mmap_def = [cedecl| int * f_map(unsigned addr) { unsigned page_addr; unsigned offset; void * ptr; if (!page_size) { page_size = sysconf(_SC_PAGESIZE); } if (mem_fd < 1) { mem_fd = open("/dev/mem", O_RDWR); if (mem_fd < 1) { perror("f_map"); } } page_addr = (addr & (~(page_size - 1))); offset = addr - page_addr; ptr = mmap(NULL, page_size, PROT_READ|PROT_WRITE, MAP_SHARED, mem_fd, page_addr); if (ptr == MAP_FAILED || !ptr) { perror("f_map"); } return (int*) (ptr + offset); } |] -------------------------------------------------------------------------------- translate' :: Env -> Software a -> ProgC a translate' env = flip runReaderT env . Oper.reexpressEnv unsafeTranslateSmallExp . unSoftware translate :: Software a -> ProgC a translate = translate' env0 -------------------------------------------------------------------------------- -- * Interpretation of software programs. -------------------------------------------------------------------------------- runIO :: Software a -> IO a runIO = Imp.runIO . translate captureIO :: Software a -> String -> IO String captureIO = Imp.captureIO . translate compile :: Software a -> String compile = Imp.compile . translate icompile :: Software a -> IO () icompile = Imp.icompile . translate runCompiled :: Software a -> IO () runCompiled = Imp.runCompiled' opts . translate withCompiled :: Software a -> ((String -> IO String) -> IO b) -> IO b withCompiled = Imp.withCompiled' opts . translate compareCompiled :: Software a -> IO a -> String -> IO () compareCompiled = Imp.compareCompiled' opts . translate opts :: Imp.ExternalCompilerOpts opts = Imp.def { Imp.externalFlagsPost = ["-lm"] } -------------------------------------------------------------------------------- runCompiled' :: CompilerOpts -> Imp.ExternalCompilerOpts -> Software a -> IO () runCompiled' opts eopts = Imp.runCompiled' eopts . translate' (Env mempty opts) --------------------------------------------------------------------------------
null
https://raw.githubusercontent.com/markus-git/co-feldspar/bf598c803d41e03ed894bbcb490da855cce9250e/src/Feldspar/Software/Compile.hs
haskell
# language TypeOperators # # language ScopedTypeVariables # # language ConstraintKinds # # language TypeSynonymInstances # syntactic. operational-higher. imperative-edsl. hardware-edsl language-c-quote hmm! debug. ------------------------------------------------------------------------------ * Software compiler. ------------------------------------------------------------------------------ | Target monad during translation. | Monad for translated programs. ------------------------------------------------------------------------------ ** Compilation of expressions. | Struct expression. | Struct expression with hidden result type. ------------------------------------------------------------------------------ ** Compilation options. | Options affecting code generation A default set of options is given by 'def'. The assertion labels to include in the generated code can be stated using the functions 'select', 'allExcept' and 'selectBy'. For example states that we want to include all except internal assertions. ^ Which assertions to include in the generated code ------------------------------------------------------------------------------ ** Compilation environment. ------------------------------------------------------------------------------ go t lit Syn.Nil | Just (Literal a) <- prj lit ------------------------------------------------------------------------------ * Interpretation of software commands. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ todo: > only need one 'ix' for read/write to arrays in 'Call'. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ * Interpretation of software programs. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
# language GADTs # # language FlexibleContexts # # language FlexibleInstances # # language MultiParamTypeClasses # # language QuasiQuotes # module Feldspar.Software.Compile where import Feldspar.Representation import Feldspar.Software.Primitive import Feldspar.Software.Primitive.Backend import Feldspar.Software.Expression import Feldspar.Software.Representation import Feldspar.Software.Optimize import Data.Struct import Control.Monad.Identity import Control.Monad.Reader import Data.Proxy import Data.Constraint hiding (Sub) import Data.Map (Map) import qualified Data.Map as Map import Data.Selection import Data.Default.Class import Language.Syntactic (AST (..), ASTF, (:&:) (..), Args((:*)), prj) import Language.Syntactic.Functional hiding (Binding (..)) import Language.Syntactic.Functional.Tuple import qualified Language.Syntactic as Syn import Control.Monad.Operational.Higher (Program) import qualified Control.Monad.Operational.Higher as Oper import Language.Embedded.Expression import qualified Language.Embedded.Imperative as Imp import qualified Language.Embedded.Imperative.CMD as Imp import qualified Language.Embedded.Imperative.Frontend as Imp import qualified Language.Embedded.Backend.C as Imp import qualified Language.C.Monad as C (CGen, addGlobal, addLocal, addInclude, addStm, gensym) import qualified Language.Embedded.Hardware.Command as Hard import Language.C.Quote.GCC import qualified Language.C.Syntax as C import Feldspar.Hardware.Primitive (HardwarePrimType(..), HardwarePrimTypeRep(..)) import Feldspar.Hardware.Expression (HType') import Feldspar.Hardware.Frontend (HSig, withHType') import Debug.Trace | Target software instructions . type TargetCMD = Imp.RefCMD Oper.:+: Imp.ArrCMD Oper.:+: Imp.ControlCMD Oper.:+: Imp.FileCMD Oper.:+: Imp.PtrCMD Oper.:+: Imp.C_CMD Oper.:+: MMapCMD type TargetT m = ReaderT Env (Oper.ProgramT TargetCMD (Oper.Param2 Prim SoftwarePrimType) m) type ProgC = Program TargetCMD (Oper.Param2 Prim SoftwarePrimType) type VExp = Struct SoftwarePrimType Prim data VExp' where VExp' :: Struct SoftwarePrimType Prim a -> VExp' newRefV :: Monad m => STypeRep a -> String -> TargetT m (Struct SoftwarePrimType Imp.Ref a) newRefV t base = lift $ mapStructA (const (Imp.newNamedRef base)) t initRefV :: Monad m => String -> VExp a -> TargetT m (Struct SoftwarePrimType Imp.Ref a) initRefV base = lift . mapStructA (Imp.initNamedRef base) getRefV :: Monad m => Struct SoftwarePrimType Imp.Ref a -> TargetT m (VExp a) getRefV = lift . mapStructA Imp.getRef setRefV :: Monad m => Struct SoftwarePrimType Imp.Ref a -> VExp a -> TargetT m () setRefV r = lift . sequence_ . zipListStruct Imp.setRef r unsafeFreezeRefV :: Monad m => Struct SoftwarePrimType Imp.Ref a -> TargetT m (VExp a) unsafeFreezeRefV = lift . mapStructA Imp.unsafeFreezeRef @`def ` { compilerAssertions = ` allExcept ` [ ` InternalAssertion`]}@ data CompilerOpts = CompilerOpts { compilerAssertions :: Selection AssertionLabel } instance Default CompilerOpts where def = CompilerOpts { compilerAssertions = universal } data Env = Env { envAliases :: Map Name VExp' , envOptions :: CompilerOpts } env0 :: Env env0 = Env Map.empty def localAlias :: MonadReader Env m => Name -> VExp a -> m b -> m b localAlias v e = local (\env -> env {envAliases = Map.insert v (VExp' e) (envAliases env)}) lookAlias :: MonadReader Env m => STypeRep a -> Name -> m (VExp a) lookAlias t v = do env <- asks envAliases return $ case Map.lookup v env of Nothing -> error $ "lookAlias: variable " ++ show v ++ " not in scope." Just (VExp' e) -> case softwareTypeEq t (softwareTypeRep e) of Just Dict -> e translateExp :: forall m a . Monad m => SExp a -> TargetT m (VExp a) translateExp = goAST . optimize . unSExp where goAST :: ASTF SoftwareDomain b -> TargetT m (VExp b) goAST = Syn.simpleMatch (\(s :&: ValT t) -> go t s) goSmallAST :: SoftwarePrimType b => ASTF SoftwareDomain b -> TargetT m (Prim b) goSmallAST = fmap extractNode . goAST go :: STypeRep (Syn.DenResult sig) -> SoftwareConstructs sig -> Syn.Args (AST SoftwareDomain) sig -> TargetT m (VExp (Syn.DenResult sig)) go t lit Syn.Nil | Just (Lit a) <- prj lit = return $ mapStruct (constExp . runIdentity) $ toStruct t a = return $ mapStruct ( constExp . runIdentity ) $ toStruct t a go t var Syn.Nil | Just (FreeVar v) <- prj var = return $ Node $ sugarSymPrim $ FreeVar v go t var Syn.Nil | Just (VarT v) <- prj var = do lookAlias t v go t lt (a :* (lam :$ body) :* Syn.Nil) | Just (Let tag) <- prj lt , Just (LamT v) <- prj lam = do let base = if null tag then "let" else tag r <- initRefV base =<< goAST a a' <- unsafeFreezeRefV r localAlias v a' $ goAST body go t ffi args | Just (Construct addr sem) <- prj ffi = do undefined go t tup (a :* b :* Syn.Nil) | Just Pair <- prj tup = Branch <$> goAST a <*> goAST b go t sel (ab :* Syn.Nil) | Just Fst <- prj sel = do branch <- goAST ab case branch of (Branch a _) -> return a | Just Snd <- prj sel = do branch <- goAST ab case branch of (Branch _ b) -> return b go ty cond (b :* t :* f :* Syn.Nil) | Just Cond <- prj cond = do res <- newRefV ty "b" b' <- goSmallAST b ReaderT $ \env -> Imp.iff b' (flip runReaderT env $ setRefV res =<< goAST t) (flip runReaderT env $ setRefV res =<< goAST f) unsafeFreezeRefV res go _ op (a :* Syn.Nil) | Just Neg <- prj op = liftStruct (sugarSymPrim Neg) <$> goAST a | Just Not <- prj op = liftStruct (sugarSymPrim Not) <$> goAST a | Just Exp <- prj op = liftStruct (sugarSymPrim Exp) <$> goAST a | Just Log <- prj op = liftStruct (sugarSymPrim Log) <$> goAST a | Just Sqrt <- prj op = liftStruct (sugarSymPrim Sqrt) <$> goAST a | Just Sin <- prj op = liftStruct (sugarSymPrim Sin) <$> goAST a | Just Cos <- prj op = liftStruct (sugarSymPrim Cos) <$> goAST a | Just Tan <- prj op = liftStruct (sugarSymPrim Tan) <$> goAST a | Just Asin <- prj op = liftStruct (sugarSymPrim Asin) <$> goAST a | Just Acos <- prj op = liftStruct (sugarSymPrim Acos) <$> goAST a | Just Atan <- prj op = liftStruct (sugarSymPrim Atan) <$> goAST a | Just Sinh <- prj op = liftStruct (sugarSymPrim Sinh) <$> goAST a | Just Cosh <- prj op = liftStruct (sugarSymPrim Cosh) <$> goAST a | Just Tanh <- prj op = liftStruct (sugarSymPrim Tanh) <$> goAST a | Just Asinh <- prj op = liftStruct (sugarSymPrim Asinh) <$> goAST a | Just Acosh <- prj op = liftStruct (sugarSymPrim Acosh) <$> goAST a | Just Atanh <- prj op = liftStruct (sugarSymPrim Atanh) <$> goAST a | Just Real <- prj op = liftStruct (sugarSymPrim Real) <$> goAST a | Just Imag <- prj op = liftStruct (sugarSymPrim Imag) <$> goAST a | Just Magnitude <- prj op = liftStruct (sugarSymPrim Magnitude) <$> goAST a | Just Phase <- prj op = liftStruct (sugarSymPrim Phase) <$> goAST a | Just Conjugate <- prj op = liftStruct (sugarSymPrim Conjugate) <$> goAST a | Just I2N <- prj op = liftStruct (sugarSymPrim I2N) <$> goAST a | Just I2B <- prj op = liftStruct (sugarSymPrim I2B) <$> goAST a | Just B2I <- prj op = liftStruct (sugarSymPrim B2I) <$> goAST a | Just Round <- prj op = liftStruct (sugarSymPrim Round) <$> goAST a | Just BitCompl <- prj op = liftStruct (sugarSymPrim BitCompl) <$> goAST a go _ op (a :* b :* Syn.Nil) | Just Add <- prj op = liftStruct2 (sugarSymPrim Add) <$> goAST a <*> goAST b | Just Sub <- prj op = liftStruct2 (sugarSymPrim Sub) <$> goAST a <*> goAST b | Just Mul <- prj op = liftStruct2 (sugarSymPrim Mul) <$> goAST a <*> goAST b | Just Div <- prj op = liftStruct2 (sugarSymPrim Div) <$> goAST a <*> goAST b | Just Mod <- prj op = liftStruct2 (sugarSymPrim Mod) <$> goAST a <*> goAST b | Just Eq <- prj op = liftStruct2 (sugarSymPrim Eq) <$> goAST a <*> goAST b | Just And <- prj op = liftStruct2 (sugarSymPrim And) <$> goAST a <*> goAST b | Just Or <- prj op = liftStruct2 (sugarSymPrim Or) <$> goAST a <*> goAST b | Just Lt <- prj op = liftStruct2 (sugarSymPrim Lt) <$> goAST a <*> goAST b | Just Lte <- prj op = liftStruct2 (sugarSymPrim Lte) <$> goAST a <*> goAST b | Just Gt <- prj op = liftStruct2 (sugarSymPrim Gt) <$> goAST a <*> goAST b | Just Gte <- prj op = liftStruct2 (sugarSymPrim Gte) <$> goAST a <*> goAST b | Just FDiv <- prj op = liftStruct2 (sugarSymPrim FDiv) <$> goAST a <*> goAST b | Just Complex <- prj op = liftStruct2 (sugarSymPrim Complex) <$> goAST a <*> goAST b | Just Polar <- prj op = liftStruct2 (sugarSymPrim Polar) <$> goAST a <*> goAST b | Just Pow <- prj op = liftStruct2 (sugarSymPrim Pow) <$> goAST a <*> goAST b | Just BitAnd <- prj op = liftStruct2 (sugarSymPrim BitAnd) <$> goAST a <*> goAST b | Just BitOr <- prj op = liftStruct2 (sugarSymPrim BitOr) <$> goAST a <*> goAST b | Just BitXor <- prj op = liftStruct2 (sugarSymPrim BitXor) <$> goAST a <*> goAST b | Just ShiftL <- prj op = liftStruct2 (sugarSymPrim ShiftL) <$> goAST a <*> goAST b | Just ShiftR <- prj op = liftStruct2 (sugarSymPrim ShiftR) <$> goAST a <*> goAST b | Just RotateL <- prj op = liftStruct2 (sugarSymPrim RotateL) <$> goAST a <*> goAST b | Just RotateR <- prj op = liftStruct2 (sugarSymPrim RotateR) <$> goAST a <*> goAST b go t guard (cond :* a :* Syn.Nil) | Just (GuardVal lbl msg) <- prj guard = do cond' <- extractNode <$> goAST cond lift $ Imp.assert cond' msg goAST a go t hint (cond :* a :* Syn.Nil) | Just (HintVal) <- prj hint = do cond' <- extractNode <$> goAST cond lift $ Imp.hint cond' goAST a go t loop (min :* max :* init :* (lami :$ (lams :$ body)) :* Syn.Nil) | Just ForLoop <- prj loop , Just (LamT iv) <- prj lami , Just (LamT sv) <- prj lams = do min' <- goSmallAST min max' <- goSmallAST max state <- initRefV "state" =<< goAST init ReaderT $ \env -> Imp.for (min', 1, Imp.Excl max') $ \i -> flip runReaderT env $ do s <- case t of Node _ -> unsafeFreezeRefV state _ -> getRefV state s' <- localAlias iv (Node i) $ localAlias sv s $ goAST body setRefV state s' unsafeFreezeRefV state go _ arrIx (i :* Syn.Nil) | Just (ArrIx arr) <- prj arrIx = do i' <- goSmallAST i return $ Node $ sugarSymPrim (ArrIx arr) i' go _ s _ = error $ "software translation handling for symbol " ++ Syn.renderSym s ++ " is missing." unsafeTranslateSmallExp :: Monad m => SExp a -> TargetT m (Prim a) unsafeTranslateSmallExp a = do node <- translateExp a case node of (Node b) -> return b instance ( Imp . CompExp exp , Imp . CompTypeClass ct ) = > Oper . Interp PtrCMD C.CGen ( Oper . Param2 exp ct ) where interp = compPtrCMD compPtrCMD : : forall exp ct a . ( Imp . CompExp exp , Imp . CompTypeClass ct ) = > PtrCMD ( Oper . ) a - > C.CGen a compPtrCMD = undefined instance (Imp.CompExp exp, Imp.CompTypeClass ct) => Oper.Interp PtrCMD C.CGen (Oper.Param2 exp ct) where interp = compPtrCMD compPtrCMD :: forall exp ct a . (Imp.CompExp exp, Imp.CompTypeClass ct) => PtrCMD (Oper.Param3 C.CGen exp ct) a -> C.CGen a compPtrCMD = undefined -} instance (Imp.CompExp exp, Imp.CompTypeClass ct) => Oper.Interp MMapCMD C.CGen (Oper.Param2 exp ct) where interp = compMMapCMD > ' n ' in ' MMap ' is n't really an ' $ i d ' . compMMapCMD :: forall exp ct a . (Imp.CompExp exp, Imp.CompTypeClass ct) => MMapCMD (Oper.Param3 C.CGen exp ct) a -> C.CGen a compMMapCMD (MMap n sig) = do C.addInclude "<stdio.h>" C.addInclude "<stdlib.h>" C.addInclude "<stddef.h>" C.addInclude "<unistd.h>" C.addInclude "<sys/mman.h>" C.addInclude "<fcntl.h>" C.addGlobal [cedecl| unsigned page_size = 0; |] C.addGlobal [cedecl| int mem_fd = -1; |] C.addGlobal mmap_def mem <- C.gensym "mem" C.addLocal [cdecl| int * $id:mem = f_map($id:n); |] return mem compMMapCMD (Call (Address ptr sig) arg) = do traverse 0 sig arg where traverse :: Integer -> HSig b -> Argument ct (Soften b) -> C.CGen () traverse ix (Hard.Ret _) (Nil) = return () traverse ix (Hard.SSig _ Hard.Out rf) (ARef (Ref (Node ref@(Imp.RefComp r))) arg) = do typ <- compRefType (Proxy :: Proxy ct) ref C.addStm [cstm| $id:r = ($ty:typ) *($id:ptr + $int:ix); |] traverse (ix + 1) (rf dummy) arg traverse ix (Hard.SArr _ Hard.Out len af) (AArr (Arr _ _ (Node arr@(Imp.ArrComp a))) arg) = do let end = ix + toInteger len i <- C.gensym "ix" typ <- compArrType (Proxy :: Proxy ct) arr C.addLocal [cdecl| int $id:i; |] C.addStm [cstm| for ($id:i=$int:ix; $id:i<$int:end; $id:i++) { $id:arr[$id:i] = ($ty:typ) *($id:ptr + $id:i); } |] traverse end (af dummy) arg traverse ix (Hard.SSig _ Hard.In rf) (ARef (Ref (Node (Imp.RefComp r))) arg) = do C.addStm [cstm| *($id:ptr + $int:ix) = (int) $id:r; |] traverse (ix + 1) (rf dummy) arg traverse ix (Hard.SArr _ Hard.In len af) (AArr (Arr _ _ (Node arr@(Imp.ArrComp a))) arg) = do let end = ix + toInteger len i <- C.gensym "ix" typ <- compArrType (Proxy :: Proxy ct) arr C.addLocal [cdecl| int $id:i; |] C.addStm [cstm| for ($id:i=$int:ix; $id:i<$int:end; $id:i++) { *($id:ptr + $id:i) = (int) $id:arr[$id:i]; } |] traverse end (af dummy) arg dummy :: forall x . x dummy = error "dummy evaluated." compRefType :: forall x . (Imp.CompTypeClass ct, HardwarePrimType x, ct x) => Proxy ct -> Imp.Ref x -> C.CGen C.Type compRefType ct _ = case witnessSP (Proxy :: Proxy x) of Dict -> Imp.compType ct (Proxy :: Proxy x) compArrType :: forall i x . (Imp.CompTypeClass ct, HardwarePrimType x, ct x) => Proxy ct -> Imp.Arr i x -> C.CGen C.Type compArrType ct _ = case witnessSP (Proxy :: Proxy x) of Dict -> Imp.compType ct (Proxy :: Proxy x) witnessSP :: forall x . HardwarePrimType x => Proxy x -> Dict (SoftwarePrimType x) witnessSP _ = case hardwareRep :: HardwarePrimTypeRep x of BoolHT -> Dict Int8HT -> Dict Int16HT -> Dict Int32HT -> Dict Int64HT -> Dict Word8HT -> Dict Word16HT -> Dict Word32HT -> Dict Word64HT -> Dict _ -> error "unrecognized software type used by mmap." mmap_def :: C.Definition mmap_def = [cedecl| int * f_map(unsigned addr) { unsigned page_addr; unsigned offset; void * ptr; if (!page_size) { page_size = sysconf(_SC_PAGESIZE); } if (mem_fd < 1) { mem_fd = open("/dev/mem", O_RDWR); if (mem_fd < 1) { perror("f_map"); } } page_addr = (addr & (~(page_size - 1))); offset = addr - page_addr; ptr = mmap(NULL, page_size, PROT_READ|PROT_WRITE, MAP_SHARED, mem_fd, page_addr); if (ptr == MAP_FAILED || !ptr) { perror("f_map"); } return (int*) (ptr + offset); } |] translate' :: Env -> Software a -> ProgC a translate' env = flip runReaderT env . Oper.reexpressEnv unsafeTranslateSmallExp . unSoftware translate :: Software a -> ProgC a translate = translate' env0 runIO :: Software a -> IO a runIO = Imp.runIO . translate captureIO :: Software a -> String -> IO String captureIO = Imp.captureIO . translate compile :: Software a -> String compile = Imp.compile . translate icompile :: Software a -> IO () icompile = Imp.icompile . translate runCompiled :: Software a -> IO () runCompiled = Imp.runCompiled' opts . translate withCompiled :: Software a -> ((String -> IO String) -> IO b) -> IO b withCompiled = Imp.withCompiled' opts . translate compareCompiled :: Software a -> IO a -> String -> IO () compareCompiled = Imp.compareCompiled' opts . translate opts :: Imp.ExternalCompilerOpts opts = Imp.def { Imp.externalFlagsPost = ["-lm"] } runCompiled' :: CompilerOpts -> Imp.ExternalCompilerOpts -> Software a -> IO () runCompiled' opts eopts = Imp.runCompiled' eopts . translate' (Env mempty opts)
df9b8b28de0cd5048e5d60d0ae6cd4dfdb365e6d4acd5f8be94a2e1e587291c5
zenspider/schemers
exercise.1.20.scm
#lang racket/base Exercise 1.20 : ;; The process that a procedure generates is of course dependent on ;; the rules used by the interpreter. As an example, consider the ;; iterative `gcd' procedure given above. Suppose we were to interpret ;; this procedure using normal-order evaluation, as discussed in section * Note 1 - 1 - 5 : : . ( The normal - order - evaluation rule for ` if ' is described in * Note Exercise 1 - 5 : : . ) Using the substitution ;; method (for normal order), illustrate the process generated in ;; evaluating `(gcd 206 40)' and indicate the `remainder' operations ;; that are actually performed. How many `remainder' operations are actually performed in the normal - order evaluation of ` ( gcd 206 40 ) ' ? In the applicative - order evaluation ? (define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) ;; applicative order: > ( remainder 206 40 ) > ( remainder 40 6 ) > ( remainder 6 4 ) > ( remainder 4 2 ) (gcd 2 0) 2 4 calls to remainder ;; normal order: ;; shorten for readibility... not that it really helps... ugh (define g gcd) (define r remainder) step 1 (g 206 40) ; expand/eval/substitute to: (if (= 40 0) 206 (g 40 (r 206 40))) ; expands (if #f 206 (g 40 (r 206 40))) ; evals and substitutes, and so on: step 2 (g 40 (r 206 40)) (if (= (r 206 40) 0) 40 (g (r 206 40) (r 40 (r 206 40)))) (if (= 6 0) 40 (g (r 206 40) (r 40 (r 206 40)))) (if #f 40 (g (r 206 40) (r 40 (r 206 40)))) step 3 (g (r 206 40) (r 40 (r 206 40))) (if (= (r 40 (r 206 40)) 0) (r 206 40) (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) (if (= 4 0) (r 206 40) (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) (if #f (r 206 40) (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) step 4 (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (if (= (r (r 206 40) (r 40 (r 206 40))) 0) (r 40 (r 206 40)) (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) (if (= 2 0) (r 40 (r 206 40)) (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) (if #f (r 40 (r 206 40)) (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) step 5 (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) (if (= (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) 0) (r (r 206 40) (r 40 (r 206 40))) (g (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) (if (= 0 0) (r (r 206 40) (r 40 (r 206 40))) (g (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) (if #t (r (r 206 40) (r 40 (r 206 40))) (g (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) step 6 - finally done (r (r 206 40) (r 40 (r 206 40))) 2 so ... 18 calls to remainder ? I think I counted that right . ;; and so on... ugh
null
https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_1/exercise.1.20.scm
scheme
The process that a procedure generates is of course dependent on the rules used by the interpreter. As an example, consider the iterative `gcd' procedure given above. Suppose we were to interpret this procedure using normal-order evaluation, as discussed in method (for normal order), illustrate the process generated in evaluating `(gcd 206 40)' and indicate the `remainder' operations that are actually performed. How many `remainder' operations are applicative order: normal order: shorten for readibility... not that it really helps... ugh expand/eval/substitute to: expands evals and substitutes, and so on: and so on... ugh
#lang racket/base Exercise 1.20 : section * Note 1 - 1 - 5 : : . ( The normal - order - evaluation rule for ` if ' is described in * Note Exercise 1 - 5 : : . ) Using the substitution actually performed in the normal - order evaluation of ` ( gcd 206 40 ) ' ? In the applicative - order evaluation ? (define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) > ( remainder 206 40 ) > ( remainder 40 6 ) > ( remainder 6 4 ) > ( remainder 4 2 ) (gcd 2 0) 2 4 calls to remainder (define g gcd) (define r remainder) step 1 step 2 (g 40 (r 206 40)) (if (= (r 206 40) 0) 40 (g (r 206 40) (r 40 (r 206 40)))) (if (= 6 0) 40 (g (r 206 40) (r 40 (r 206 40)))) (if #f 40 (g (r 206 40) (r 40 (r 206 40)))) step 3 (g (r 206 40) (r 40 (r 206 40))) (if (= (r 40 (r 206 40)) 0) (r 206 40) (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) (if (= 4 0) (r 206 40) (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) (if #f (r 206 40) (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) step 4 (g (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (if (= (r (r 206 40) (r 40 (r 206 40))) 0) (r 40 (r 206 40)) (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) (if (= 2 0) (r 40 (r 206 40)) (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) (if #f (r 40 (r 206 40)) (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))))) step 5 (g (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))) (if (= (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) 0) (r (r 206 40) (r 40 (r 206 40))) (g (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) (if (= 0 0) (r (r 206 40) (r 40 (r 206 40))) (g (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) (if #t (r (r 206 40) (r 40 (r 206 40))) (g (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40)))) (r (r (r 206 40) (r 40 (r 206 40))) (r (r 40 (r 206 40)) (r (r 206 40) (r 40 (r 206 40))))))) step 6 - finally done (r (r 206 40) (r 40 (r 206 40))) 2 so ... 18 calls to remainder ? I think I counted that right .
a7959c94cf54b76085c3edc48704bbed319893d7bddabeffb02b84781111b198
rtoy/ansi-cl-tests
cosh.lsp
;-*- Mode: Lisp -*- Author : Created : We d Feb 11 06:54:15 2004 ;;;; Contains: Tests of COSH (in-package :cl-test) (deftest cosh.1 (let ((result (cosh 0))) (or (eqlt result 1) (eqlt result 1.0))) t) (deftest cosh.2 (loop for type in '(short-float single-float double-float long-float) for zero = (coerce 0 type) for one = (coerce 1 type) unless (equal (multiple-value-list (cosh zero)) (list one)) collect type) nil) (deftest cosh.3 (loop for type in '(short-float single-float double-float long-float) for zero = (coerce 0 `(complex ,type)) for one = (coerce 1 `(complex ,type)) unless (equal (multiple-value-list (cosh zero)) (list one)) collect type) nil) (deftest cosh.4 (loop for den = (1+ (random 10000)) for num = (random (* 10 den)) for x = (/ num den) for rlist = (multiple-value-list (cosh x)) for y = (car rlist) repeat 1000 unless (and (null (cdr rlist)) (numberp y)) collect (list x rlist)) nil) (deftest cosh.5 (loop for type in '(short-float single-float double-float long-float) nconc (loop for x = (- (random (coerce 20 type)) 10) for rlist = (multiple-value-list (cosh x)) for y = (car rlist) repeat 1000 unless (and (null (cdr rlist)) (typep y type)) collect (list x rlist))) nil) (deftest cosh.6 (loop for type in '(short-float single-float double-float long-float) nconc (loop for x1 = (- (random (coerce 20 type)) 10) for x2 = (- (random (coerce 20 type)) 10) for rlist = (multiple-value-list (cosh (complex x1 x2))) for y = (car rlist) repeat 1000 unless (and (null (cdr rlist)) (typep y `(complex ,type))) collect (list x1 x2 rlist))) nil) FIXME ;;; Add accuracy tests here ;;; Error tests (deftest cosh.error.1 (signals-error (cosh) program-error) t) (deftest cosh.error.2 (signals-error (cosh 1.0 1.0) program-error) t) (deftest cosh.error.3 (check-type-error #'cosh #'numberp) nil)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/cosh.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of COSH Add accuracy tests here Error tests
Author : Created : We d Feb 11 06:54:15 2004 (in-package :cl-test) (deftest cosh.1 (let ((result (cosh 0))) (or (eqlt result 1) (eqlt result 1.0))) t) (deftest cosh.2 (loop for type in '(short-float single-float double-float long-float) for zero = (coerce 0 type) for one = (coerce 1 type) unless (equal (multiple-value-list (cosh zero)) (list one)) collect type) nil) (deftest cosh.3 (loop for type in '(short-float single-float double-float long-float) for zero = (coerce 0 `(complex ,type)) for one = (coerce 1 `(complex ,type)) unless (equal (multiple-value-list (cosh zero)) (list one)) collect type) nil) (deftest cosh.4 (loop for den = (1+ (random 10000)) for num = (random (* 10 den)) for x = (/ num den) for rlist = (multiple-value-list (cosh x)) for y = (car rlist) repeat 1000 unless (and (null (cdr rlist)) (numberp y)) collect (list x rlist)) nil) (deftest cosh.5 (loop for type in '(short-float single-float double-float long-float) nconc (loop for x = (- (random (coerce 20 type)) 10) for rlist = (multiple-value-list (cosh x)) for y = (car rlist) repeat 1000 unless (and (null (cdr rlist)) (typep y type)) collect (list x rlist))) nil) (deftest cosh.6 (loop for type in '(short-float single-float double-float long-float) nconc (loop for x1 = (- (random (coerce 20 type)) 10) for x2 = (- (random (coerce 20 type)) 10) for rlist = (multiple-value-list (cosh (complex x1 x2))) for y = (car rlist) repeat 1000 unless (and (null (cdr rlist)) (typep y `(complex ,type))) collect (list x1 x2 rlist))) nil) FIXME (deftest cosh.error.1 (signals-error (cosh) program-error) t) (deftest cosh.error.2 (signals-error (cosh 1.0 1.0) program-error) t) (deftest cosh.error.3 (check-type-error #'cosh #'numberp) nil)
0b686c7c1f4101f687358c1a88059799625c98ea2954ff1598f3bce717872eab
ssadler/zeno
Synchronous.hs
# LANGUAGE KindSignatures # -- | Zeno uses a consensus algorithm, but it is stateless, it doesn't write any data -- to disk. So, at any point it can pick up the current state from external blockchains -- without syncing blocks. The synchronous process performs notarisations back and forth between two chains in a synchronous manner . module Zeno.Notariser.Synchronous where import Data.Bits import Control.Monad.Skeleton import Network.Komodo import Zeno.Consensus.Types import Zeno.Console import Zeno.Notariser.EthGateway import Zeno.Notariser.Types import Zeno.Notariser.Targets import Zeno.Prelude -------------------------------------------------------------------------------- interface -------------------------------------------------------------------------------- type NotariserSync s d m = Skeleton (NotariserSyncI s d m) instance MonadLogger m => MonadLogger (NotariserSync s d m) where monadLoggerLog a b c d = bone $ NotariserSyncLift $ monadLoggerLog a b c d instance MonadIO m => MonadIO (Skeleton (NotariserSyncI a b m)) where liftIO = bone . NotariserSyncLift . liftIO data NotariserSyncI s d m x where GetLastNotarisation :: NotariserSyncI s d m (Maybe (ChainNotarisation d)) GetLastNotarisationReceipt :: NotariserSyncI s d m (Maybe (ChainNotarisationReceipt s)) RunNotarise :: Word32 -> Maybe (ChainNotarisationReceipt s) -> NotariserSyncI s d m () RunNotariseReceipt :: Word32 -> ChainNotarisation d -> NotariserSyncI s d m () WaitNextSourceHeight :: Word32 -> NotariserSyncI s d m (Maybe Word32) WaitNextDestHeight :: Word32 -> NotariserSyncI s d m (Maybe Word32) NotariserSyncLift :: m a -> NotariserSyncI s d m a -------------------------------------------------------------------------------- skeleton -------------------------------------------------------------------------------- type Notariser a b m = (SourceChain a m, DestChain b m, MonadLogger m) notariserSyncFree :: forall a b m. Notariser a b m => AbstractNotariserConfig a b -> Skeleton (NotariserSyncI a b m) () notariserSyncFree nc@NotariserConfig{..} = start where start = bone GetLastNotarisation >>= go go :: Maybe (ChainNotarisation b) -> NotariserSync a b m () go Nothing = do logInfo "No prior notarisations found" notarise 0 Nothing go (Just notarisation) = do let notarisedHeight = foreignHeight notarisation backnotarise lastHeight = do bone (WaitNextDestHeight lastHeight) >>= \case Nothing -> start Just newHeight -> do bone $ RunNotariseReceipt newHeight notarisation logDebug $ "Found notarisation on %s for %s.%i" % (getSymbol destChain, getSymbol sourceChain, notarisedHeight) bone GetLastNotarisationReceipt >>= \case Just receipt -> do let fwd = notarise notarisedHeight (Just receipt) case compare (receiptHeight receipt) notarisedHeight of LT -> do logDebug $ "Posting receipt to %s" % getSymbol sourceChain backnotarise (foreignHeight receipt) EQ -> do logDebug $ "Found receipt for %s.%i on %s" % (getSymbol sourceChain, notarisedHeight, getSymbol destChain) fwd GT -> do logError $ show notarisation logError $ show receipt logError $ "The receipt height in %s is higher than the notarised\ \ height in %s. Is %s node is lagging? Proceeding anyway." % (getSymbol sourceChain, getSymbol destChain, getSymbol destChain) fwd _ -> do logDebug "Receipt not found, proceed to backnotarise" backnotarise 0 notarise lastHeight mlastReceipt = do bone (WaitNextSourceHeight lastHeight) >>= \case Nothing -> start Just h -> bone $ RunNotarise h mlastReceipt waitNextNotariseHeight :: (MonadIO m, MonadLoggerUI m, BlockchainAPI c m) => c -> Word32 -> m (Maybe Word32) waitNextNotariseHeight chain lastHeight = do height <- getHeight chain let interval = getNotarisationBlockInterval chain let nextHeight = getNextHeight interval lastHeight height if (height >= nextHeight) then pure $ Just nextHeight else do let s = "Waiting for %s.%i" % (getSymbol chain, nextHeight) logInfo s sendUI $ UI_Process $ Just $ UIOther s fix \f -> do threadDelayS 5 height <- getHeight chain when (height < nextHeight) f pure Nothing getNextHeight :: Word32 -> Word32 -> Word32 -> Word32 getNextHeight interval last current = let nextLo = last + interval - mod last interval nextHi = current - mod current interval in max nextLo nextHi
null
https://raw.githubusercontent.com/ssadler/zeno/9f715d7104a7b7b00dee9fe35275fb217532fdb6/src/Zeno/Notariser/Synchronous.hs
haskell
| Zeno uses a consensus algorithm, but it is stateless, it doesn't write any data to disk. So, at any point it can pick up the current state from external blockchains without syncing blocks. The synchronous process performs notarisations back and forth ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
# LANGUAGE KindSignatures # between two chains in a synchronous manner . module Zeno.Notariser.Synchronous where import Data.Bits import Control.Monad.Skeleton import Network.Komodo import Zeno.Consensus.Types import Zeno.Console import Zeno.Notariser.EthGateway import Zeno.Notariser.Types import Zeno.Notariser.Targets import Zeno.Prelude interface type NotariserSync s d m = Skeleton (NotariserSyncI s d m) instance MonadLogger m => MonadLogger (NotariserSync s d m) where monadLoggerLog a b c d = bone $ NotariserSyncLift $ monadLoggerLog a b c d instance MonadIO m => MonadIO (Skeleton (NotariserSyncI a b m)) where liftIO = bone . NotariserSyncLift . liftIO data NotariserSyncI s d m x where GetLastNotarisation :: NotariserSyncI s d m (Maybe (ChainNotarisation d)) GetLastNotarisationReceipt :: NotariserSyncI s d m (Maybe (ChainNotarisationReceipt s)) RunNotarise :: Word32 -> Maybe (ChainNotarisationReceipt s) -> NotariserSyncI s d m () RunNotariseReceipt :: Word32 -> ChainNotarisation d -> NotariserSyncI s d m () WaitNextSourceHeight :: Word32 -> NotariserSyncI s d m (Maybe Word32) WaitNextDestHeight :: Word32 -> NotariserSyncI s d m (Maybe Word32) NotariserSyncLift :: m a -> NotariserSyncI s d m a skeleton type Notariser a b m = (SourceChain a m, DestChain b m, MonadLogger m) notariserSyncFree :: forall a b m. Notariser a b m => AbstractNotariserConfig a b -> Skeleton (NotariserSyncI a b m) () notariserSyncFree nc@NotariserConfig{..} = start where start = bone GetLastNotarisation >>= go go :: Maybe (ChainNotarisation b) -> NotariserSync a b m () go Nothing = do logInfo "No prior notarisations found" notarise 0 Nothing go (Just notarisation) = do let notarisedHeight = foreignHeight notarisation backnotarise lastHeight = do bone (WaitNextDestHeight lastHeight) >>= \case Nothing -> start Just newHeight -> do bone $ RunNotariseReceipt newHeight notarisation logDebug $ "Found notarisation on %s for %s.%i" % (getSymbol destChain, getSymbol sourceChain, notarisedHeight) bone GetLastNotarisationReceipt >>= \case Just receipt -> do let fwd = notarise notarisedHeight (Just receipt) case compare (receiptHeight receipt) notarisedHeight of LT -> do logDebug $ "Posting receipt to %s" % getSymbol sourceChain backnotarise (foreignHeight receipt) EQ -> do logDebug $ "Found receipt for %s.%i on %s" % (getSymbol sourceChain, notarisedHeight, getSymbol destChain) fwd GT -> do logError $ show notarisation logError $ show receipt logError $ "The receipt height in %s is higher than the notarised\ \ height in %s. Is %s node is lagging? Proceeding anyway." % (getSymbol sourceChain, getSymbol destChain, getSymbol destChain) fwd _ -> do logDebug "Receipt not found, proceed to backnotarise" backnotarise 0 notarise lastHeight mlastReceipt = do bone (WaitNextSourceHeight lastHeight) >>= \case Nothing -> start Just h -> bone $ RunNotarise h mlastReceipt waitNextNotariseHeight :: (MonadIO m, MonadLoggerUI m, BlockchainAPI c m) => c -> Word32 -> m (Maybe Word32) waitNextNotariseHeight chain lastHeight = do height <- getHeight chain let interval = getNotarisationBlockInterval chain let nextHeight = getNextHeight interval lastHeight height if (height >= nextHeight) then pure $ Just nextHeight else do let s = "Waiting for %s.%i" % (getSymbol chain, nextHeight) logInfo s sendUI $ UI_Process $ Just $ UIOther s fix \f -> do threadDelayS 5 height <- getHeight chain when (height < nextHeight) f pure Nothing getNextHeight :: Word32 -> Word32 -> Word32 -> Word32 getNextHeight interval last current = let nextLo = last + interval - mod last interval nextHi = current - mod current interval in max nextLo nextHi
64ee78a9885be6bfc63077c2d6a159d82f1f62065125f195606be68f5030bf57
cyverse-archive/DiscoveryEnvironmentBackend
listing.clj
(ns metadactyl.routes.domain.analysis.listing (:use [common-swagger-api.schema :only [describe]] [metadactyl.routes.params :only [ResultsTotalParam]] [schema.core :only [defschema optional-key Any Int Bool]]) (:import [java.util UUID])) (def Timestamp (describe String "A timestamp in milliseconds since the epoch.")) (defschema BatchStatus {:total (describe Int "The total number of jobs in the batch.") :completed (describe Int "The number of completed jobs in the batch.") :running (describe Int "The number of running jobs in the batch.") :submitted (describe Int "The number of submitted jobs in the batch.")}) (defschema Analysis {(optional-key :app_description) (describe String "A description of the app used to perform the analysis.") :app_disabled (describe Boolean "Indicates whether the app is currently disabled.") :app_id (describe String "The ID of the app used to perform the analysis.") (optional-key :app_name) (describe String "The name of the app used to perform the analysis.") (optional-key :batch) (describe Boolean "Indicates whether the analysis is a batch analysis.") (optional-key :description) (describe String "The analysis description.") (optional-key :enddate) (describe Timestamp "The time the analysis ended.") :id (describe UUID "The analysis ID.") (optional-key :name) (describe String "The analysis name.") :notify (describe Boolean "Indicates whether the user wants status updates via email.") (optional-key :resultfolderid) (describe String "The path to the folder containing the anlaysis results.") (optional-key :startdate) (describe Timestamp "The time the analysis started.") :status (describe String "The status of the analysis.") :username (describe String "The name of the user who submitted the analysis.") (optional-key :wiki_url) (describe String "The URL to app documentation in Confluence.") (optional-key :parent_id) (describe UUID "The identifier of the parent analysis.") (optional-key :batch_status) (describe BatchStatus "A summary of the status of the batch.")}) (defschema AnalysisList {:analyses (describe [Analysis] "The list of analyses.") :timestamp (describe Timestamp "The time the analysis list was retrieved.") :total ResultsTotalParam}) (defschema AnalysisUpdate (select-keys Analysis (map optional-key [:description :name]))) (defschema AnalysisUpdateResponse (select-keys Analysis (cons :id (map optional-key [:description :name])))) (def AppStepNumber (describe Integer (str "The sequential step number from the app, which might be different " "from the analysis step number if app steps have been combined."))) (defschema AnalysisStep {:step_number (describe Integer "The sequential step number in the analysis.") (optional-key :external_id) (describe String "The step ID from the execution system.") (optional-key :startdate) (describe Timestamp "The time the step started.") (optional-key :enddate) (describe Timestamp "The time the step ended.") (optional-key :status) (describe String "The status of the step.") (optional-key :app_step_number) AppStepNumber (optional-key :step_type) (describe String "The analysis type associated with the step.")}) (defschema AnalysisStepList {:analysis_id (describe UUID "The analysis ID.") :steps (describe [AnalysisStep] "The list of analysis steps.") :timestamp (describe Timestamp "The time the list of analysis steps was retrieved.") :total ResultsTotalParam})
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/metadactyl-clj/src/metadactyl/routes/domain/analysis/listing.clj
clojure
(ns metadactyl.routes.domain.analysis.listing (:use [common-swagger-api.schema :only [describe]] [metadactyl.routes.params :only [ResultsTotalParam]] [schema.core :only [defschema optional-key Any Int Bool]]) (:import [java.util UUID])) (def Timestamp (describe String "A timestamp in milliseconds since the epoch.")) (defschema BatchStatus {:total (describe Int "The total number of jobs in the batch.") :completed (describe Int "The number of completed jobs in the batch.") :running (describe Int "The number of running jobs in the batch.") :submitted (describe Int "The number of submitted jobs in the batch.")}) (defschema Analysis {(optional-key :app_description) (describe String "A description of the app used to perform the analysis.") :app_disabled (describe Boolean "Indicates whether the app is currently disabled.") :app_id (describe String "The ID of the app used to perform the analysis.") (optional-key :app_name) (describe String "The name of the app used to perform the analysis.") (optional-key :batch) (describe Boolean "Indicates whether the analysis is a batch analysis.") (optional-key :description) (describe String "The analysis description.") (optional-key :enddate) (describe Timestamp "The time the analysis ended.") :id (describe UUID "The analysis ID.") (optional-key :name) (describe String "The analysis name.") :notify (describe Boolean "Indicates whether the user wants status updates via email.") (optional-key :resultfolderid) (describe String "The path to the folder containing the anlaysis results.") (optional-key :startdate) (describe Timestamp "The time the analysis started.") :status (describe String "The status of the analysis.") :username (describe String "The name of the user who submitted the analysis.") (optional-key :wiki_url) (describe String "The URL to app documentation in Confluence.") (optional-key :parent_id) (describe UUID "The identifier of the parent analysis.") (optional-key :batch_status) (describe BatchStatus "A summary of the status of the batch.")}) (defschema AnalysisList {:analyses (describe [Analysis] "The list of analyses.") :timestamp (describe Timestamp "The time the analysis list was retrieved.") :total ResultsTotalParam}) (defschema AnalysisUpdate (select-keys Analysis (map optional-key [:description :name]))) (defschema AnalysisUpdateResponse (select-keys Analysis (cons :id (map optional-key [:description :name])))) (def AppStepNumber (describe Integer (str "The sequential step number from the app, which might be different " "from the analysis step number if app steps have been combined."))) (defschema AnalysisStep {:step_number (describe Integer "The sequential step number in the analysis.") (optional-key :external_id) (describe String "The step ID from the execution system.") (optional-key :startdate) (describe Timestamp "The time the step started.") (optional-key :enddate) (describe Timestamp "The time the step ended.") (optional-key :status) (describe String "The status of the step.") (optional-key :app_step_number) AppStepNumber (optional-key :step_type) (describe String "The analysis type associated with the step.")}) (defschema AnalysisStepList {:analysis_id (describe UUID "The analysis ID.") :steps (describe [AnalysisStep] "The list of analysis steps.") :timestamp (describe Timestamp "The time the list of analysis steps was retrieved.") :total ResultsTotalParam})
208992af4900aafe17efc8e3da7db183a0f9a7a2380d2e097021aaa7c3531eac
piotr-yuxuan/slava
config.clj
(ns piotr-yuxuan.slava.config "FIXME add cljdoc" (:require [piotr-yuxuan.slava.decode :as decode] [piotr-yuxuan.slava.encode :as encode] [camel-snake-kebab.core :as csk]) (:import (org.apache.avro.generic GenericData$EnumSymbol GenericData$Record) (org.apache.avro.util Utf8) (java.nio ByteBuffer) (java.util Collection List Map) (org.apache.avro Schema$EnumSchema))) (defn slava-key? [k] (not (string? k))) (def avro-decoders "FIXME add cljdoc" #:decoder{:avro-record decode/avro-record :avro-enum nil :avro-array decode/avro-array :map-key-fn (constantly nil) :avro-map decode/avro-map :avro-union decode/avro-union :avro-fixed nil :avro-string nil :avro-bytes nil :avro-int nil :avro-long nil :avro-float nil :avro-double nil :avro-boolean nil :avro-null nil}) (def generic-concrete-types "Concrete types returned by GenericAvroSerde. You probably don't need to change them if you're getting started." ;; It's important to have all of them to resolve unions and further decode any nested datum when there is a need. #:decoder{:avro-record #(instance? GenericData$Record %) :avro-enum #(instance? GenericData$EnumSymbol %) :avro-array #(or (instance? Collection %) (instance? List %)) :avro-map #(instance? Map %) :avro-union (constantly false) ; Union type can't be a concrete type. :avro-fixed #(instance? ByteBuffer %) :avro-string #(or (string? %) (instance? Utf8 %)) :avro-bytes #(instance? ByteBuffer %) :avro-int int? :avro-long #(instance? Long %) :avro-float float? :avro-double double? :avro-boolean boolean? :avro-null nil?}) (def avro-encoders "FIXME add cljdoc" #:encoder{:avro-record encode/avro-record :avro-enum nil :avro-array encode/avro-array :map-key-fn (constantly nil) :avro-map encode/avro-map :avro-union encode/avro-union :avro-fixed nil :avro-string nil :avro-bytes nil :avro-int nil :avro-long nil :avro-float nil :avro-double nil :avro-boolean nil :avro-null nil}) (def clojure-types "Used by the encoder. Must match types returned by the decoder." ;; It's important to have all of them to resolve unions and further encode any nested datum when there is a need. #:encoder{:avro-record map? :avro-enum #(instance? GenericData$EnumSymbol %) :avro-array sequential? :avro-map map? :avro-union (constantly false) ; Union type can't be a concrete type. :avro-fixed #(instance? ByteBuffer %) :avro-string #(or (string? %) (instance? Utf8 %)) :avro-bytes #(instance? ByteBuffer %) :avro-int int? :avro-long #(instance? Long %) :avro-float float? :avro-double double? :avro-boolean boolean? :avro-null nil?}) (def default "FIXME add cljdoc" (merge {:record-key-fn (constantly str) :clojure-types clojure-types :generic-concrete-types generic-concrete-types} avro-decoders avro-encoders)) (def opinionated "FIXME add cljdoc" (assoc default :record-key-fn (constantly csk/->kebab-case-keyword) ;; Explicit example of a decoder :decoder/avro-enum (fn enum-decoder-compiler [_config ^Schema$EnumSchema _reader-schema] (fn enum-decoder [^GenericData$EnumSymbol data] (csk/->kebab-case-keyword (str data)))) ;; Explicit example of an encoder :encoder/avro-enum (fn enum-encoder-compiler [_config ^Schema$EnumSchema writer-schema] (fn enum-encoder [data] (GenericData$EnumSymbol. writer-schema (csk/->SCREAMING_SNAKE_CASE_STRING data)))) :decoder/map-key-fn (fn [{:keys [field-name]} _] (partial keyword field-name)) :encoder/map-key-fn (constantly name) avoid Utf8 :decoder/avro-string (constantly str)))
null
https://raw.githubusercontent.com/piotr-yuxuan/slava/e894f6a8797577cfb7c2c48097fedd3c74946dd8/src/piotr_yuxuan/slava/config.clj
clojure
It's important to have all of them to resolve unions and further decode any nested datum when there is a need. Union type can't be a concrete type. It's important to have all of them to resolve unions and further encode any nested datum when there is a need. Union type can't be a concrete type. Explicit example of a decoder Explicit example of an encoder
(ns piotr-yuxuan.slava.config "FIXME add cljdoc" (:require [piotr-yuxuan.slava.decode :as decode] [piotr-yuxuan.slava.encode :as encode] [camel-snake-kebab.core :as csk]) (:import (org.apache.avro.generic GenericData$EnumSymbol GenericData$Record) (org.apache.avro.util Utf8) (java.nio ByteBuffer) (java.util Collection List Map) (org.apache.avro Schema$EnumSchema))) (defn slava-key? [k] (not (string? k))) (def avro-decoders "FIXME add cljdoc" #:decoder{:avro-record decode/avro-record :avro-enum nil :avro-array decode/avro-array :map-key-fn (constantly nil) :avro-map decode/avro-map :avro-union decode/avro-union :avro-fixed nil :avro-string nil :avro-bytes nil :avro-int nil :avro-long nil :avro-float nil :avro-double nil :avro-boolean nil :avro-null nil}) (def generic-concrete-types "Concrete types returned by GenericAvroSerde. You probably don't need to change them if you're getting started." #:decoder{:avro-record #(instance? GenericData$Record %) :avro-enum #(instance? GenericData$EnumSymbol %) :avro-array #(or (instance? Collection %) (instance? List %)) :avro-map #(instance? Map %) :avro-fixed #(instance? ByteBuffer %) :avro-string #(or (string? %) (instance? Utf8 %)) :avro-bytes #(instance? ByteBuffer %) :avro-int int? :avro-long #(instance? Long %) :avro-float float? :avro-double double? :avro-boolean boolean? :avro-null nil?}) (def avro-encoders "FIXME add cljdoc" #:encoder{:avro-record encode/avro-record :avro-enum nil :avro-array encode/avro-array :map-key-fn (constantly nil) :avro-map encode/avro-map :avro-union encode/avro-union :avro-fixed nil :avro-string nil :avro-bytes nil :avro-int nil :avro-long nil :avro-float nil :avro-double nil :avro-boolean nil :avro-null nil}) (def clojure-types "Used by the encoder. Must match types returned by the decoder." #:encoder{:avro-record map? :avro-enum #(instance? GenericData$EnumSymbol %) :avro-array sequential? :avro-map map? :avro-fixed #(instance? ByteBuffer %) :avro-string #(or (string? %) (instance? Utf8 %)) :avro-bytes #(instance? ByteBuffer %) :avro-int int? :avro-long #(instance? Long %) :avro-float float? :avro-double double? :avro-boolean boolean? :avro-null nil?}) (def default "FIXME add cljdoc" (merge {:record-key-fn (constantly str) :clojure-types clojure-types :generic-concrete-types generic-concrete-types} avro-decoders avro-encoders)) (def opinionated "FIXME add cljdoc" (assoc default :record-key-fn (constantly csk/->kebab-case-keyword) :decoder/avro-enum (fn enum-decoder-compiler [_config ^Schema$EnumSchema _reader-schema] (fn enum-decoder [^GenericData$EnumSymbol data] (csk/->kebab-case-keyword (str data)))) :encoder/avro-enum (fn enum-encoder-compiler [_config ^Schema$EnumSchema writer-schema] (fn enum-encoder [data] (GenericData$EnumSymbol. writer-schema (csk/->SCREAMING_SNAKE_CASE_STRING data)))) :decoder/map-key-fn (fn [{:keys [field-name]} _] (partial keyword field-name)) :encoder/map-key-fn (constantly name) avoid Utf8 :decoder/avro-string (constantly str)))
2c1119810aaaed6e8f581e28af5ebfd78645753fcb7ba32dc781ff06e01c2c26
thlack/surfs
spec.clj
(ns ^:no-doc thlack.surfs.blocks.components.spec (:require [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [thlack.surfs.blocks.spec :as blocks.spec] [thlack.surfs.blocks.spec.actions :as actions] [thlack.surfs.blocks.spec.context :as context] [thlack.surfs.blocks.spec.header :as header] [thlack.surfs.blocks.spec.image :as image] [thlack.surfs.blocks.spec.input :as input] [thlack.surfs.blocks.spec.section :as section] [thlack.surfs.composition.spec :as comp.spec] [thlack.surfs.strings.spec :as strings.spec :refer [deftext]])) (s/def ::block.props (s/keys :opt-un [::strings.spec/block_id])) Internal use only - used for validating prop maps that MUST contain block_id in order to be considered props (s/def ::block.props* (s/keys :req-un [::strings.spec/block_id])) ;;; [:actions] (s/def ::actions.children (s/with-gen (s/+ ::actions/element) #(s/gen ::actions/elements))) ;;; [:section] (s/def ::section.child (s/or :text ::section/text :fields ::blocks.spec/fields :accessory ::section/accessory)) ;;; [:context] (s/def ::context.children (s/with-gen (s/+ ::context/element) #(s/gen ::context/elements))) ;;; [:header] (deftext :thlack.surfs.blocks.components.spec.header-child/text (s/or :string ::strings.spec/string :text ::header/text) 150) ;;; [:image] (deftext :thlack.surfs.blocks.components.spec.image-child/title (s/or :string ::strings.spec/string :text ::image/title) 2000) (s/def ::image.props (s/merge ::block.props (s/keys :req-un [::image/image_url ::image/alt_text]))) ;;; [:input] (deftext :thlack.surfs.blocks.components.spec.input-child/label (s/or :string ::strings.spec/string :text ::input/label) 2000) (s/def ::input.child (s/or :hint ::comp.spec/plain-text :element ::input/element)) (s/def ::input.children (s/with-gen (s/+ ::input.child) #(gen/fmap (fn [input] (vals (select-keys input [:hint :element]))) (s/gen ::blocks.spec/input)))) (s/def ::input.props (s/merge ::block.props (s/keys :opt-un [::input/dispatch_action ::input/optional]))) (defn input-props? "Predicate for seeing if the given props map constitutes input block props" [props] (if (map? props) (-> props (select-keys [:block_id :dispatch_action :optional]) (seq) (some?)) false)) (s/fdef input-props? :args any? :ret boolean?)
null
https://raw.githubusercontent.com/thlack/surfs/e03d137d6d43c4b73a45a71984cf084d2904c4b0/src/thlack/surfs/blocks/components/spec.clj
clojure
[:actions] [:section] [:context] [:header] [:image] [:input]
(ns ^:no-doc thlack.surfs.blocks.components.spec (:require [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [thlack.surfs.blocks.spec :as blocks.spec] [thlack.surfs.blocks.spec.actions :as actions] [thlack.surfs.blocks.spec.context :as context] [thlack.surfs.blocks.spec.header :as header] [thlack.surfs.blocks.spec.image :as image] [thlack.surfs.blocks.spec.input :as input] [thlack.surfs.blocks.spec.section :as section] [thlack.surfs.composition.spec :as comp.spec] [thlack.surfs.strings.spec :as strings.spec :refer [deftext]])) (s/def ::block.props (s/keys :opt-un [::strings.spec/block_id])) Internal use only - used for validating prop maps that MUST contain block_id in order to be considered props (s/def ::block.props* (s/keys :req-un [::strings.spec/block_id])) (s/def ::actions.children (s/with-gen (s/+ ::actions/element) #(s/gen ::actions/elements))) (s/def ::section.child (s/or :text ::section/text :fields ::blocks.spec/fields :accessory ::section/accessory)) (s/def ::context.children (s/with-gen (s/+ ::context/element) #(s/gen ::context/elements))) (deftext :thlack.surfs.blocks.components.spec.header-child/text (s/or :string ::strings.spec/string :text ::header/text) 150) (deftext :thlack.surfs.blocks.components.spec.image-child/title (s/or :string ::strings.spec/string :text ::image/title) 2000) (s/def ::image.props (s/merge ::block.props (s/keys :req-un [::image/image_url ::image/alt_text]))) (deftext :thlack.surfs.blocks.components.spec.input-child/label (s/or :string ::strings.spec/string :text ::input/label) 2000) (s/def ::input.child (s/or :hint ::comp.spec/plain-text :element ::input/element)) (s/def ::input.children (s/with-gen (s/+ ::input.child) #(gen/fmap (fn [input] (vals (select-keys input [:hint :element]))) (s/gen ::blocks.spec/input)))) (s/def ::input.props (s/merge ::block.props (s/keys :opt-un [::input/dispatch_action ::input/optional]))) (defn input-props? "Predicate for seeing if the given props map constitutes input block props" [props] (if (map? props) (-> props (select-keys [:block_id :dispatch_action :optional]) (seq) (some?)) false)) (s/fdef input-props? :args any? :ret boolean?)
57436ae01e507f0a45fda53d830e5425a8d71279d5e03153b22852b3b5c549dd
brendanhay/amazonka
TimeSeriesServiceStatistics.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . -- | Module : Amazonka . . Types . TimeSeriesServiceStatistics Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Amazonka.XRay.Types.TimeSeriesServiceStatistics where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import Amazonka.XRay.Types.EdgeStatistics import Amazonka.XRay.Types.ForecastStatistics import Amazonka.XRay.Types.HistogramEntry import Amazonka.XRay.Types.ServiceStatistics -- | A list of TimeSeriesStatistic structures. -- /See:/ ' newTimeSeriesServiceStatistics ' smart constructor . data TimeSeriesServiceStatistics = TimeSeriesServiceStatistics' { edgeSummaryStatistics :: Prelude.Maybe EdgeStatistics, -- | The response time histogram for the selected entities. responseTimeHistogram :: Prelude.Maybe [HistogramEntry], -- | The forecasted high and low fault count values. serviceForecastStatistics :: Prelude.Maybe ForecastStatistics, serviceSummaryStatistics :: Prelude.Maybe ServiceStatistics, -- | Timestamp of the window for which statistics are aggregated. timestamp :: Prelude.Maybe Data.POSIX } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) -- | -- Create a value of 'TimeSeriesServiceStatistics' with all optional fields omitted. -- Use < -lens generic - lens > or < optics > to modify other optional fields . -- -- The following record fields are available, with the corresponding lenses provided -- for backwards compatibility: -- -- 'edgeSummaryStatistics', 'timeSeriesServiceStatistics_edgeSummaryStatistics' - Undocumented member. -- -- 'responseTimeHistogram', 'timeSeriesServiceStatistics_responseTimeHistogram' - The response time histogram for the selected entities. -- -- 'serviceForecastStatistics', 'timeSeriesServiceStatistics_serviceForecastStatistics' - The forecasted high and low fault count values. -- -- 'serviceSummaryStatistics', 'timeSeriesServiceStatistics_serviceSummaryStatistics' - Undocumented member. -- -- 'timestamp', 'timeSeriesServiceStatistics_timestamp' - Timestamp of the window for which statistics are aggregated. newTimeSeriesServiceStatistics :: TimeSeriesServiceStatistics newTimeSeriesServiceStatistics = TimeSeriesServiceStatistics' { edgeSummaryStatistics = Prelude.Nothing, responseTimeHistogram = Prelude.Nothing, serviceForecastStatistics = Prelude.Nothing, serviceSummaryStatistics = Prelude.Nothing, timestamp = Prelude.Nothing } -- | Undocumented member. timeSeriesServiceStatistics_edgeSummaryStatistics :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe EdgeStatistics) timeSeriesServiceStatistics_edgeSummaryStatistics = Lens.lens (\TimeSeriesServiceStatistics' {edgeSummaryStatistics} -> edgeSummaryStatistics) (\s@TimeSeriesServiceStatistics' {} a -> s {edgeSummaryStatistics = a} :: TimeSeriesServiceStatistics) -- | The response time histogram for the selected entities. timeSeriesServiceStatistics_responseTimeHistogram :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe [HistogramEntry]) timeSeriesServiceStatistics_responseTimeHistogram = Lens.lens (\TimeSeriesServiceStatistics' {responseTimeHistogram} -> responseTimeHistogram) (\s@TimeSeriesServiceStatistics' {} a -> s {responseTimeHistogram = a} :: TimeSeriesServiceStatistics) Prelude.. Lens.mapping Lens.coerced -- | The forecasted high and low fault count values. timeSeriesServiceStatistics_serviceForecastStatistics :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe ForecastStatistics) timeSeriesServiceStatistics_serviceForecastStatistics = Lens.lens (\TimeSeriesServiceStatistics' {serviceForecastStatistics} -> serviceForecastStatistics) (\s@TimeSeriesServiceStatistics' {} a -> s {serviceForecastStatistics = a} :: TimeSeriesServiceStatistics) -- | Undocumented member. timeSeriesServiceStatistics_serviceSummaryStatistics :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe ServiceStatistics) timeSeriesServiceStatistics_serviceSummaryStatistics = Lens.lens (\TimeSeriesServiceStatistics' {serviceSummaryStatistics} -> serviceSummaryStatistics) (\s@TimeSeriesServiceStatistics' {} a -> s {serviceSummaryStatistics = a} :: TimeSeriesServiceStatistics) -- | Timestamp of the window for which statistics are aggregated. timeSeriesServiceStatistics_timestamp :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe Prelude.UTCTime) timeSeriesServiceStatistics_timestamp = Lens.lens (\TimeSeriesServiceStatistics' {timestamp} -> timestamp) (\s@TimeSeriesServiceStatistics' {} a -> s {timestamp = a} :: TimeSeriesServiceStatistics) Prelude.. Lens.mapping Data._Time instance Data.FromJSON TimeSeriesServiceStatistics where parseJSON = Data.withObject "TimeSeriesServiceStatistics" ( \x -> TimeSeriesServiceStatistics' Prelude.<$> (x Data..:? "EdgeSummaryStatistics") Prelude.<*> ( x Data..:? "ResponseTimeHistogram" Data..!= Prelude.mempty ) Prelude.<*> (x Data..:? "ServiceForecastStatistics") Prelude.<*> (x Data..:? "ServiceSummaryStatistics") Prelude.<*> (x Data..:? "Timestamp") ) instance Prelude.Hashable TimeSeriesServiceStatistics where hashWithSalt _salt TimeSeriesServiceStatistics' {..} = _salt `Prelude.hashWithSalt` edgeSummaryStatistics `Prelude.hashWithSalt` responseTimeHistogram `Prelude.hashWithSalt` serviceForecastStatistics `Prelude.hashWithSalt` serviceSummaryStatistics `Prelude.hashWithSalt` timestamp instance Prelude.NFData TimeSeriesServiceStatistics where rnf TimeSeriesServiceStatistics' {..} = Prelude.rnf edgeSummaryStatistics `Prelude.seq` Prelude.rnf responseTimeHistogram `Prelude.seq` Prelude.rnf serviceForecastStatistics `Prelude.seq` Prelude.rnf serviceSummaryStatistics `Prelude.seq` Prelude.rnf timestamp
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-xray/gen/Amazonka/XRay/Types/TimeSeriesServiceStatistics.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated | A list of TimeSeriesStatistic structures. | The response time histogram for the selected entities. | The forecasted high and low fault count values. | Timestamp of the window for which statistics are aggregated. | Create a value of 'TimeSeriesServiceStatistics' with all optional fields omitted. The following record fields are available, with the corresponding lenses provided for backwards compatibility: 'edgeSummaryStatistics', 'timeSeriesServiceStatistics_edgeSummaryStatistics' - Undocumented member. 'responseTimeHistogram', 'timeSeriesServiceStatistics_responseTimeHistogram' - The response time histogram for the selected entities. 'serviceForecastStatistics', 'timeSeriesServiceStatistics_serviceForecastStatistics' - The forecasted high and low fault count values. 'serviceSummaryStatistics', 'timeSeriesServiceStatistics_serviceSummaryStatistics' - Undocumented member. 'timestamp', 'timeSeriesServiceStatistics_timestamp' - Timestamp of the window for which statistics are aggregated. | Undocumented member. | The response time histogram for the selected entities. | The forecasted high and low fault count values. | Undocumented member. | Timestamp of the window for which statistics are aggregated.
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . Module : Amazonka . . Types . TimeSeriesServiceStatistics Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Amazonka.XRay.Types.TimeSeriesServiceStatistics where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import Amazonka.XRay.Types.EdgeStatistics import Amazonka.XRay.Types.ForecastStatistics import Amazonka.XRay.Types.HistogramEntry import Amazonka.XRay.Types.ServiceStatistics /See:/ ' newTimeSeriesServiceStatistics ' smart constructor . data TimeSeriesServiceStatistics = TimeSeriesServiceStatistics' { edgeSummaryStatistics :: Prelude.Maybe EdgeStatistics, responseTimeHistogram :: Prelude.Maybe [HistogramEntry], serviceForecastStatistics :: Prelude.Maybe ForecastStatistics, serviceSummaryStatistics :: Prelude.Maybe ServiceStatistics, timestamp :: Prelude.Maybe Data.POSIX } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) Use < -lens generic - lens > or < optics > to modify other optional fields . newTimeSeriesServiceStatistics :: TimeSeriesServiceStatistics newTimeSeriesServiceStatistics = TimeSeriesServiceStatistics' { edgeSummaryStatistics = Prelude.Nothing, responseTimeHistogram = Prelude.Nothing, serviceForecastStatistics = Prelude.Nothing, serviceSummaryStatistics = Prelude.Nothing, timestamp = Prelude.Nothing } timeSeriesServiceStatistics_edgeSummaryStatistics :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe EdgeStatistics) timeSeriesServiceStatistics_edgeSummaryStatistics = Lens.lens (\TimeSeriesServiceStatistics' {edgeSummaryStatistics} -> edgeSummaryStatistics) (\s@TimeSeriesServiceStatistics' {} a -> s {edgeSummaryStatistics = a} :: TimeSeriesServiceStatistics) timeSeriesServiceStatistics_responseTimeHistogram :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe [HistogramEntry]) timeSeriesServiceStatistics_responseTimeHistogram = Lens.lens (\TimeSeriesServiceStatistics' {responseTimeHistogram} -> responseTimeHistogram) (\s@TimeSeriesServiceStatistics' {} a -> s {responseTimeHistogram = a} :: TimeSeriesServiceStatistics) Prelude.. Lens.mapping Lens.coerced timeSeriesServiceStatistics_serviceForecastStatistics :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe ForecastStatistics) timeSeriesServiceStatistics_serviceForecastStatistics = Lens.lens (\TimeSeriesServiceStatistics' {serviceForecastStatistics} -> serviceForecastStatistics) (\s@TimeSeriesServiceStatistics' {} a -> s {serviceForecastStatistics = a} :: TimeSeriesServiceStatistics) timeSeriesServiceStatistics_serviceSummaryStatistics :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe ServiceStatistics) timeSeriesServiceStatistics_serviceSummaryStatistics = Lens.lens (\TimeSeriesServiceStatistics' {serviceSummaryStatistics} -> serviceSummaryStatistics) (\s@TimeSeriesServiceStatistics' {} a -> s {serviceSummaryStatistics = a} :: TimeSeriesServiceStatistics) timeSeriesServiceStatistics_timestamp :: Lens.Lens' TimeSeriesServiceStatistics (Prelude.Maybe Prelude.UTCTime) timeSeriesServiceStatistics_timestamp = Lens.lens (\TimeSeriesServiceStatistics' {timestamp} -> timestamp) (\s@TimeSeriesServiceStatistics' {} a -> s {timestamp = a} :: TimeSeriesServiceStatistics) Prelude.. Lens.mapping Data._Time instance Data.FromJSON TimeSeriesServiceStatistics where parseJSON = Data.withObject "TimeSeriesServiceStatistics" ( \x -> TimeSeriesServiceStatistics' Prelude.<$> (x Data..:? "EdgeSummaryStatistics") Prelude.<*> ( x Data..:? "ResponseTimeHistogram" Data..!= Prelude.mempty ) Prelude.<*> (x Data..:? "ServiceForecastStatistics") Prelude.<*> (x Data..:? "ServiceSummaryStatistics") Prelude.<*> (x Data..:? "Timestamp") ) instance Prelude.Hashable TimeSeriesServiceStatistics where hashWithSalt _salt TimeSeriesServiceStatistics' {..} = _salt `Prelude.hashWithSalt` edgeSummaryStatistics `Prelude.hashWithSalt` responseTimeHistogram `Prelude.hashWithSalt` serviceForecastStatistics `Prelude.hashWithSalt` serviceSummaryStatistics `Prelude.hashWithSalt` timestamp instance Prelude.NFData TimeSeriesServiceStatistics where rnf TimeSeriesServiceStatistics' {..} = Prelude.rnf edgeSummaryStatistics `Prelude.seq` Prelude.rnf responseTimeHistogram `Prelude.seq` Prelude.rnf serviceForecastStatistics `Prelude.seq` Prelude.rnf serviceSummaryStatistics `Prelude.seq` Prelude.rnf timestamp
b29bf4acd2e6f12b97ab522f99b4e8071cbd03905a0f2cdf1d8e250dc246b5d5
mcorbin/tour-of-clojure
fn_map_second.clj
;; add value in nested maps (println (assoc-in {:foo {:bar {:hello "hello"}}} [:foo :bar :goodbye] "goodbye") "\n") ;; get a value in nested maps (println (get-in {:foo {:bar {:hello 1}}} [:foo :bar :hello]) "\n") ;; update value in nested maps (println (update-in {:foo {:bar {:hello 1}}} [:foo :bar :hello] inc) "\n") ;; select keys in a map (println (select-keys {:foo 1 :bar 2 :baz 3} [:foo :baz]) "\n") merge two maps (println (merge {:foo 1 :bar 2} {:foo 2 :baz 3}))
null
https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/resources/public/pages/code/fn_map_second.clj
clojure
add value in nested maps get a value in nested maps update value in nested maps select keys in a map
(println (assoc-in {:foo {:bar {:hello "hello"}}} [:foo :bar :goodbye] "goodbye") "\n") (println (get-in {:foo {:bar {:hello 1}}} [:foo :bar :hello]) "\n") (println (update-in {:foo {:bar {:hello 1}}} [:foo :bar :hello] inc) "\n") (println (select-keys {:foo 1 :bar 2 :baz 3} [:foo :baz]) "\n") merge two maps (println (merge {:foo 1 :bar 2} {:foo 2 :baz 3}))
649c39522e4453c4caefe2089d9d85c21b2ca8451a03b2d14ef571e57fed95bb
disteph/cdsat
Eq.ml
open Top module Known = struct let known = let open Symbols in function | Eq _ | NEq _ -> true | _ -> false end include Generic.Make(Known)
null
https://raw.githubusercontent.com/disteph/cdsat/1b569f3eae59802148f4274186746a9ed3e667ed/src/kernel/kernel.mld/termstructures.mld/VarSet.mld/Eq.ml
ocaml
open Top module Known = struct let known = let open Symbols in function | Eq _ | NEq _ -> true | _ -> false end include Generic.Make(Known)
b6add00e0a09bd6ad094c7ee8555447654242520ca60d99e203a2bb40b154617
raviksharma/bartosz-basics-of-haskell
cat.hs
Implement function cat that concatenates two lists . cat :: [a] -> [a] -> [a] cat [] j = j cat (i : rest) j = i : cat rest j main = putStrLn $ cat "Hello " "World!"
null
https://raw.githubusercontent.com/raviksharma/bartosz-basics-of-haskell/86d40d831f61415ef0022bff7fe7060ae6a23701/06-tokenizer-function-types/cat.hs
haskell
Implement function cat that concatenates two lists . cat :: [a] -> [a] -> [a] cat [] j = j cat (i : rest) j = i : cat rest j main = putStrLn $ cat "Hello " "World!"
2c51ad0b0bee2de6788727ae2509c793746583d2299c5f8461c829f77ef8e5a5
gedge-platform/gedge-platform
prometheus_text_format.erl
%% @doc %% Serializes Prometheus registry using the latest %% [text format](). %% %% Example output: %% <pre> %% # TYPE http_request_duration_milliseconds histogram %% # HELP http_request_duration_milliseconds Http Request execution time %% http_request_duration_milliseconds_bucket{method="post",le="100"} 0 http_request_duration_milliseconds_bucket{method="post",le="300 " } 1 http_request_duration_milliseconds_bucket{method="post",le="500 " } 3 http_request_duration_milliseconds_bucket{method="post",le="750 " } 4 http_request_duration_milliseconds_bucket{method="post",le="1000 " } 5 http_request_duration_milliseconds_bucket{method="post",le="+Inf " } 6 http_request_duration_milliseconds_count{method="post " } 6 %% http_request_duration_milliseconds_sum{method="post"} 4350 %% </pre> %% @end -module(prometheus_text_format). -export([content_type/0, format/0, format/1]). -ifdef(TEST). -export([escape_metric_help/1, escape_label_value/1, emit_mf_prologue/2, emit_mf_metrics/2 ]). -endif. -include("prometheus.hrl"). -include("prometheus_model.hrl"). -behaviour(prometheus_format). %%==================================================================== Macros %%==================================================================== %%==================================================================== %% Format API %%==================================================================== -spec content_type() -> binary(). %% @doc %% Returns content type of the latest [text format](). %% @end content_type() -> <<"text/plain; version=0.0.4">>. %% @equiv format(default) -spec format() -> binary(). %% @doc %% Formats `default' registry using the latest text format. %% @end format() -> format(default). -spec format(Registry :: prometheus_registry:registry()) -> binary(). %% @doc %% Formats `Registry' using the latest text format. %% @end format(Registry) -> {ok, Fd} = ram_file:open("", [write, read, binary]), Callback = fun (_, Collector) -> registry_collect_callback(Fd, Registry, Collector) end, prometheus_registry:collect(Registry, Callback), file:write(Fd, "\n"), {ok, Size} = ram_file:get_size(Fd), {ok, Str} = file:pread(Fd, 0, Size), ok = file:close(Fd), Str. %%==================================================================== %% Private Parts %%==================================================================== registry_collect_callback(Fd, Registry, Collector) -> Callback = fun (MF) -> emit_mf_prologue(Fd, MF), emit_mf_metrics(Fd, MF) end, prometheus_collector:collect_mf(Registry, Collector, Callback). @private emit_mf_prologue(Fd, #'MetricFamily'{name=Name, help=Help, type=Type}) -> Bytes = ["# TYPE ", Name, " ", string_type(Type), "\n# HELP ", Name, " ", escape_metric_help(Help), "\n"], file:write(Fd, Bytes). @private emit_mf_metrics(Fd, #'MetricFamily'{name=Name, metric = Metrics}) -> [emit_metric(Fd, Name, Metric) || Metric <- Metrics]. emit_metric(Fd, Name, #'Metric'{label=Labels, counter=#'Counter'{value=Value}}) -> emit_series(Fd, Name, labels_string(labels_stringify(Labels)), Value); emit_metric(Fd, Name, #'Metric'{label=Labels, gauge=#'Gauge'{value=Value}}) -> emit_series(Fd, Name, labels_string(labels_stringify(Labels)), Value); emit_metric(Fd, Name, #'Metric'{label=Labels, untyped=#'Untyped'{value=Value}}) -> emit_series(Fd, Name, labels_string(labels_stringify(Labels)), Value); emit_metric(Fd, Name, #'Metric'{label=Labels, summary=#'Summary'{sample_count=Count, sample_sum=Sum, quantile=Quantiles}}) -> StringLabels = labels_stringify(Labels), LString = labels_string(StringLabels), emit_series(Fd, [Name, "_count"], LString, Count), emit_series(Fd, [Name, "_sum"], LString, Sum), [ emit_series( Fd, [Name], labels_string(StringLabels ++ labels_stringify([#'LabelPair'{name="quantile", value=io_lib:format("~p", [QN])}])), QV) || #'Quantile'{quantile = QN, value = QV} <- Quantiles ]; emit_metric(Fd, Name, #'Metric'{label=Labels, histogram=#'Histogram'{sample_count=Count, sample_sum=Sum, bucket=Buckets}}) -> StringLabels = labels_stringify(Labels), LString = labels_string(StringLabels), [emit_histogram_bucket(Fd, Name, StringLabels, Bucket) || Bucket <- Buckets], emit_series(Fd, [Name, "_count"], LString, Count), emit_series(Fd, [Name, "_sum"], LString, Sum). emit_histogram_bucket(Fd, Name, StringLabels, #'Bucket'{cumulative_count=BCount, upper_bound=BBound}) -> BLValue = bound_to_label_value(BBound), emit_series(Fd, [Name, "_bucket"], labels_string(StringLabels ++ labels_stringify([#'LabelPair'{name="le", value=BLValue}])), BCount). string_type('COUNTER') -> "counter"; string_type('GAUGE') -> "gauge"; string_type('SUMMARY') -> "summary"; string_type('HISTOGRAM') -> "histogram"; string_type('UNTYPED') -> "untyped". labels_stringify(Labels) -> Fun = fun (#'LabelPair'{name=Name, value=Value}) -> [Name, "=\"", escape_label_value(Value), "\""] end, lists:map(Fun, Labels). labels_string([]) -> ""; labels_string(Labels) -> ["{", join(",", Labels), "}"]. emit_series(Fd, Name, LString, undefined) -> file:write(Fd, [Name, LString, " NaN\n"]); emit_series(Fd, Name, LString, Value) when is_integer(Value) -> file:write(Fd, [Name, LString, " ", integer_to_list(Value) , "\n"]); emit_series(Fd, Name, LString, Value) -> file:write(Fd, [Name, LString, " ", io_lib:format("~p", [Value]) , "\n"]). @private escape_metric_help(Help) -> escape_string(fun escape_help_char/1, Help). @private escape_help_char($\\ = X) -> <<X, X>>; escape_help_char($\n) -> <<$\\, $n>>; escape_help_char(X) -> <<X>>. bound_to_label_value(Bound) when is_integer(Bound) -> integer_to_list(Bound); bound_to_label_value(Bound) when is_float(Bound) -> float_to_list(Bound); bound_to_label_value(infinity) -> "+Inf". -spec escape_label_value(binary() | iolist() | undefined) -> binary(). @private escape_label_value(LValue) when is_list(LValue); is_binary(LValue) -> escape_string(fun escape_label_char/1, LValue); escape_label_value(Value) -> erlang:error({wtf, Value}). @private escape_label_char($\\ = X) -> <<X, X>>; escape_label_char($\n) -> <<$\\, $n>>; escape_label_char($" = X) -> <<$\\, X>>; escape_label_char(X) -> <<X>>. @private escape_string(Fun, Str) when is_binary(Str) -> << <<(Fun(X))/binary>> || <<X:8>> <= Str >>; escape_string(Fun, Str) -> escape_string(Fun, iolist_to_binary(Str)). %% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2016 . 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% %% -spec join(Sep, List1) -> List2 when Sep :: T, List1 :: [T], List2 :: [T], T :: term(). join(Sep, [H|T]) -> [H|join_prepend(Sep, T)]. join_prepend(_Sep, []) -> []; join_prepend(Sep, [H|T]) -> [Sep, H|join_prepend(Sep, T)].
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/prometheus/src/formats/prometheus_text_format.erl
erlang
@doc [text format](). Example output: <pre> # TYPE http_request_duration_milliseconds histogram # HELP http_request_duration_milliseconds Http Request execution time http_request_duration_milliseconds_bucket{method="post",le="100"} 0 http_request_duration_milliseconds_sum{method="post"} 4350 </pre> @end ==================================================================== ==================================================================== ==================================================================== Format API ==================================================================== @doc Returns content type of the latest [text format](). @end @equiv format(default) @doc Formats `default' registry using the latest text format. @end @doc Formats `Registry' using the latest text format. @end ==================================================================== Private Parts ==================================================================== %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%
Serializes Prometheus registry using the latest http_request_duration_milliseconds_bucket{method="post",le="300 " } 1 http_request_duration_milliseconds_bucket{method="post",le="500 " } 3 http_request_duration_milliseconds_bucket{method="post",le="750 " } 4 http_request_duration_milliseconds_bucket{method="post",le="1000 " } 5 http_request_duration_milliseconds_bucket{method="post",le="+Inf " } 6 http_request_duration_milliseconds_count{method="post " } 6 -module(prometheus_text_format). -export([content_type/0, format/0, format/1]). -ifdef(TEST). -export([escape_metric_help/1, escape_label_value/1, emit_mf_prologue/2, emit_mf_metrics/2 ]). -endif. -include("prometheus.hrl"). -include("prometheus_model.hrl"). -behaviour(prometheus_format). Macros -spec content_type() -> binary(). content_type() -> <<"text/plain; version=0.0.4">>. -spec format() -> binary(). format() -> format(default). -spec format(Registry :: prometheus_registry:registry()) -> binary(). format(Registry) -> {ok, Fd} = ram_file:open("", [write, read, binary]), Callback = fun (_, Collector) -> registry_collect_callback(Fd, Registry, Collector) end, prometheus_registry:collect(Registry, Callback), file:write(Fd, "\n"), {ok, Size} = ram_file:get_size(Fd), {ok, Str} = file:pread(Fd, 0, Size), ok = file:close(Fd), Str. registry_collect_callback(Fd, Registry, Collector) -> Callback = fun (MF) -> emit_mf_prologue(Fd, MF), emit_mf_metrics(Fd, MF) end, prometheus_collector:collect_mf(Registry, Collector, Callback). @private emit_mf_prologue(Fd, #'MetricFamily'{name=Name, help=Help, type=Type}) -> Bytes = ["# TYPE ", Name, " ", string_type(Type), "\n# HELP ", Name, " ", escape_metric_help(Help), "\n"], file:write(Fd, Bytes). @private emit_mf_metrics(Fd, #'MetricFamily'{name=Name, metric = Metrics}) -> [emit_metric(Fd, Name, Metric) || Metric <- Metrics]. emit_metric(Fd, Name, #'Metric'{label=Labels, counter=#'Counter'{value=Value}}) -> emit_series(Fd, Name, labels_string(labels_stringify(Labels)), Value); emit_metric(Fd, Name, #'Metric'{label=Labels, gauge=#'Gauge'{value=Value}}) -> emit_series(Fd, Name, labels_string(labels_stringify(Labels)), Value); emit_metric(Fd, Name, #'Metric'{label=Labels, untyped=#'Untyped'{value=Value}}) -> emit_series(Fd, Name, labels_string(labels_stringify(Labels)), Value); emit_metric(Fd, Name, #'Metric'{label=Labels, summary=#'Summary'{sample_count=Count, sample_sum=Sum, quantile=Quantiles}}) -> StringLabels = labels_stringify(Labels), LString = labels_string(StringLabels), emit_series(Fd, [Name, "_count"], LString, Count), emit_series(Fd, [Name, "_sum"], LString, Sum), [ emit_series( Fd, [Name], labels_string(StringLabels ++ labels_stringify([#'LabelPair'{name="quantile", value=io_lib:format("~p", [QN])}])), QV) || #'Quantile'{quantile = QN, value = QV} <- Quantiles ]; emit_metric(Fd, Name, #'Metric'{label=Labels, histogram=#'Histogram'{sample_count=Count, sample_sum=Sum, bucket=Buckets}}) -> StringLabels = labels_stringify(Labels), LString = labels_string(StringLabels), [emit_histogram_bucket(Fd, Name, StringLabels, Bucket) || Bucket <- Buckets], emit_series(Fd, [Name, "_count"], LString, Count), emit_series(Fd, [Name, "_sum"], LString, Sum). emit_histogram_bucket(Fd, Name, StringLabels, #'Bucket'{cumulative_count=BCount, upper_bound=BBound}) -> BLValue = bound_to_label_value(BBound), emit_series(Fd, [Name, "_bucket"], labels_string(StringLabels ++ labels_stringify([#'LabelPair'{name="le", value=BLValue}])), BCount). string_type('COUNTER') -> "counter"; string_type('GAUGE') -> "gauge"; string_type('SUMMARY') -> "summary"; string_type('HISTOGRAM') -> "histogram"; string_type('UNTYPED') -> "untyped". labels_stringify(Labels) -> Fun = fun (#'LabelPair'{name=Name, value=Value}) -> [Name, "=\"", escape_label_value(Value), "\""] end, lists:map(Fun, Labels). labels_string([]) -> ""; labels_string(Labels) -> ["{", join(",", Labels), "}"]. emit_series(Fd, Name, LString, undefined) -> file:write(Fd, [Name, LString, " NaN\n"]); emit_series(Fd, Name, LString, Value) when is_integer(Value) -> file:write(Fd, [Name, LString, " ", integer_to_list(Value) , "\n"]); emit_series(Fd, Name, LString, Value) -> file:write(Fd, [Name, LString, " ", io_lib:format("~p", [Value]) , "\n"]). @private escape_metric_help(Help) -> escape_string(fun escape_help_char/1, Help). @private escape_help_char($\\ = X) -> <<X, X>>; escape_help_char($\n) -> <<$\\, $n>>; escape_help_char(X) -> <<X>>. bound_to_label_value(Bound) when is_integer(Bound) -> integer_to_list(Bound); bound_to_label_value(Bound) when is_float(Bound) -> float_to_list(Bound); bound_to_label_value(infinity) -> "+Inf". -spec escape_label_value(binary() | iolist() | undefined) -> binary(). @private escape_label_value(LValue) when is_list(LValue); is_binary(LValue) -> escape_string(fun escape_label_char/1, LValue); escape_label_value(Value) -> erlang:error({wtf, Value}). @private escape_label_char($\\ = X) -> <<X, X>>; escape_label_char($\n) -> <<$\\, $n>>; escape_label_char($" = X) -> <<$\\, X>>; escape_label_char(X) -> <<X>>. @private escape_string(Fun, Str) when is_binary(Str) -> << <<(Fun(X))/binary>> || <<X:8>> <= Str >>; escape_string(Fun, Str) -> escape_string(Fun, iolist_to_binary(Str)). Copyright Ericsson AB 1996 - 2016 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -spec join(Sep, List1) -> List2 when Sep :: T, List1 :: [T], List2 :: [T], T :: term(). join(Sep, [H|T]) -> [H|join_prepend(Sep, T)]. join_prepend(_Sep, []) -> []; join_prepend(Sep, [H|T]) -> [Sep, H|join_prepend(Sep, T)].
c1f12867c06e697d17ca70e45cf46e923015d5bf63c8a6e4c196d99d9d0189f2
tommaisey/aeon
snippets.scm
;; A bit of sawtooth inspiration (let ([prog (over 8 [I III VI V])]) (pattern fake-inspiration ;; bass (syn "saw-grain" (euc 16 13) (to: :octave -2 :amp 0.15 :cutoff (sine 8 0.3 0.55) :pan (over 1/4 [0.45 0.55]) :scd prog) (legato) (to* :sustain 3)) ;; melody (syn "saw-grain" (over 2 [(euc 8 5 1) ~]) (to: :cutoff (sine 15 0.3 0.4) :octave -1 :scd prog :chd (over 1/2 [5 4 2 0]))))) ;; A little drum groove (pattern drums (syn "bd" (euc 8 5) (to: :scd V :amp 0.6) (legato 1/2)) (syn "hh" (euc 16 13 2) (to: :amp (over 1/8 [0.1 0.3]) :sustain (over 1/8 [~ (? [1/6 1/8 1/4])]))) (syn "cp" (euc 8 2 3) (to: :freq 60 :sustain (over 2 [(? [1/8 1/4 1/2]) 1/16 (! 4)])) (sq: (over 1/2 (? [~ ~ (taps 1/16 2) (taps 1/16 -3)]))) (to: :amp (over 1/2 [(? 0.1 0.25) 0.4]))) (to* :amp 0.4) (tt+ 1/4) (swing 1/16 0.08)) ;; A nice fluttery synth (pattern flutter (in: :scd (over [[I III V IV] (/ 4) [III VI VIII X] (* 3)]) :pan (sine 1/2 0.3 0.7) :inst "pulse-pluck" :cutoff (sine 3/2 0.4 0.7) :attack 0.01 :sustain (over [1 1/2])))
null
https://raw.githubusercontent.com/tommaisey/aeon/12e8ff92bd5efed2923aecf974fa12d39835abc6/examples/snippets.scm
scheme
A bit of sawtooth inspiration bass melody A little drum groove A nice fluttery synth
(let ([prog (over 8 [I III VI V])]) (pattern fake-inspiration (syn "saw-grain" (euc 16 13) (to: :octave -2 :amp 0.15 :cutoff (sine 8 0.3 0.55) :pan (over 1/4 [0.45 0.55]) :scd prog) (legato) (to* :sustain 3)) (syn "saw-grain" (over 2 [(euc 8 5 1) ~]) (to: :cutoff (sine 15 0.3 0.4) :octave -1 :scd prog :chd (over 1/2 [5 4 2 0]))))) (pattern drums (syn "bd" (euc 8 5) (to: :scd V :amp 0.6) (legato 1/2)) (syn "hh" (euc 16 13 2) (to: :amp (over 1/8 [0.1 0.3]) :sustain (over 1/8 [~ (? [1/6 1/8 1/4])]))) (syn "cp" (euc 8 2 3) (to: :freq 60 :sustain (over 2 [(? [1/8 1/4 1/2]) 1/16 (! 4)])) (sq: (over 1/2 (? [~ ~ (taps 1/16 2) (taps 1/16 -3)]))) (to: :amp (over 1/2 [(? 0.1 0.25) 0.4]))) (to* :amp 0.4) (tt+ 1/4) (swing 1/16 0.08)) (pattern flutter (in: :scd (over [[I III V IV] (/ 4) [III VI VIII X] (* 3)]) :pan (sine 1/2 0.3 0.7) :inst "pulse-pluck" :cutoff (sine 3/2 0.4 0.7) :attack 0.01 :sustain (over [1 1/2])))
78e9302cde3cc0505eb9603011450e4a97391115e3c15be2146269aa3df33c2f
chiroptical/book-of-monads
Reader.hs
module Reader where -- Terminology below is a reminder to self newtype Reader r a = -- ^ is called a "type constructor" Reader -- ^ is called a "data constructor" { runReader :: r -> a -- ^ is called a "field" } instance Functor (Reader r) where fmap f (Reader ra) = Reader $ f . ra instance Applicative (Reader r) where pure = Reader . const Reader rab <*> Reader ra = Reader $ \r -> rab r $ ra r instance Monad (Reader r) where return = pure Reader ra >>= farrb = Reader $ \r -> runReader (farrb . ra $ r) r ask :: Reader r r ask = Reader id asks :: (r -> a) -> Reader r a asks f = f <$> ask withReader :: (r -> s) -> Reader s a -> Reader r a withReader rs (Reader sa) = Reader $ sa . rs -- handle :: Config -> Request -> Response handle = produceResponse cfg ( initializeHeader cfg ) ( getArguments cfg req ) -- Refactor the above with the Reader Monad -- Think of `cfg` as being threaded through the computation -- handle :: Request -> Reader Config Response -- handle req = do -- header <- initializeHeader -- args <- getArguments req produceResponse header args -- Use withReader to operate on a subset -- of fields, example -- data Config = -- Config { userConfig : : UserConfig -- , dbConfig :: DbConfig , : : LogConfig -- } -- handle = do -- q <- ... -- r <- withReader dbConfig (query q) -- ... -- where -- query :: DatabaseQuery -> Reader DbConfig Result -- query q = do -- dbc <- ask -- ...
null
https://raw.githubusercontent.com/chiroptical/book-of-monads/c2eff1c67a8958b28cfd2001d652f8b68e7c84df/chapter6/src/Reader.hs
haskell
Terminology below is a reminder to self ^ is called a "type constructor" ^ is called a "data constructor" ^ is called a "field" handle :: Config -> Request -> Response Refactor the above with the Reader Monad Think of `cfg` as being threaded through the computation handle :: Request -> Reader Config Response handle req = do header <- initializeHeader args <- getArguments req Use withReader to operate on a subset of fields, example data Config = Config , dbConfig :: DbConfig } handle = do q <- ... r <- withReader dbConfig (query q) ... where query :: DatabaseQuery -> Reader DbConfig Result query q = do dbc <- ask ...
module Reader where newtype Reader r a = Reader { runReader :: r -> a } instance Functor (Reader r) where fmap f (Reader ra) = Reader $ f . ra instance Applicative (Reader r) where pure = Reader . const Reader rab <*> Reader ra = Reader $ \r -> rab r $ ra r instance Monad (Reader r) where return = pure Reader ra >>= farrb = Reader $ \r -> runReader (farrb . ra $ r) r ask :: Reader r r ask = Reader id asks :: (r -> a) -> Reader r a asks f = f <$> ask withReader :: (r -> s) -> Reader s a -> Reader r a withReader rs (Reader sa) = Reader $ sa . rs handle = produceResponse cfg ( initializeHeader cfg ) ( getArguments cfg req ) produceResponse header args { userConfig : : UserConfig , : : LogConfig
8bf603b664a7891a5e8535aa93225bbda39d83a3b072a479c8be8beddb0f2025
xsc/kithara
project.clj
(defproject kithara "0.1.9-SNAPSHOT" :description "A Clojure Library for Reliable RabbitMQ Consumers." :url "" :license {:name "MIT License" :url "" :year 2016 :key "mit"} :dependencies [[org.clojure/clojure "1.8.0" :scope "provided"] [org.clojure/tools.logging "0.3.1"] [net.jodah/lyra "0.5.2"] [com.rabbitmq/amqp-client "3.6.1"] [peripheral "0.5.2"] [manifold "0.1.4"] [potemkin "0.4.3"]] :profiles {:dev {:dependencies [[ch.qos.logback/logback-classic "1.1.7"] [org.slf4j/slf4j-api "1.7.21"] [org.clojure/test.check "0.9.0"] [io.aviso/pretty "0.1.26"]]} :silent-test {:resource-paths ["test-resources"]} :codox [:dev {:plugins [[lein-codox "0.10.0"]] :dependencies [[codox-theme-rdash "0.1.1"]] :codox {:project {:name "kithara"} :metadata {:doc/format :markdown} :themes [:rdash] :source-uri "{version}/{filepath}#L{line}"}}] :codox-consumers [:codox {:codox {:output-path "target/doc" :namespaces [kithara.core kithara.config kithara.protocols #"^kithara\.patterns\.[a-z\-]+" #"^kithara\.middlewares\.[a-z\-]+"]}}] :codox-rabbitmq [:codox {:codox {:output-path "target/doc/rabbitmq" :namespaces [kithara.config #"kithara\.rabbitmq\.[a-z\-]+"]}}]} :aliases {"codox" ["do" "with-profile" "+codox-consumers" "codox," "with-profile" "+codox-rabbitmq" "codox"] "silent-test" ["with-profile" "+silent-test" "test"]} :pedantic? :abort)
null
https://raw.githubusercontent.com/xsc/kithara/3394a9e9ef5e6e605637a74e070c7d24bfaf19cc/project.clj
clojure
(defproject kithara "0.1.9-SNAPSHOT" :description "A Clojure Library for Reliable RabbitMQ Consumers." :url "" :license {:name "MIT License" :url "" :year 2016 :key "mit"} :dependencies [[org.clojure/clojure "1.8.0" :scope "provided"] [org.clojure/tools.logging "0.3.1"] [net.jodah/lyra "0.5.2"] [com.rabbitmq/amqp-client "3.6.1"] [peripheral "0.5.2"] [manifold "0.1.4"] [potemkin "0.4.3"]] :profiles {:dev {:dependencies [[ch.qos.logback/logback-classic "1.1.7"] [org.slf4j/slf4j-api "1.7.21"] [org.clojure/test.check "0.9.0"] [io.aviso/pretty "0.1.26"]]} :silent-test {:resource-paths ["test-resources"]} :codox [:dev {:plugins [[lein-codox "0.10.0"]] :dependencies [[codox-theme-rdash "0.1.1"]] :codox {:project {:name "kithara"} :metadata {:doc/format :markdown} :themes [:rdash] :source-uri "{version}/{filepath}#L{line}"}}] :codox-consumers [:codox {:codox {:output-path "target/doc" :namespaces [kithara.core kithara.config kithara.protocols #"^kithara\.patterns\.[a-z\-]+" #"^kithara\.middlewares\.[a-z\-]+"]}}] :codox-rabbitmq [:codox {:codox {:output-path "target/doc/rabbitmq" :namespaces [kithara.config #"kithara\.rabbitmq\.[a-z\-]+"]}}]} :aliases {"codox" ["do" "with-profile" "+codox-consumers" "codox," "with-profile" "+codox-rabbitmq" "codox"] "silent-test" ["with-profile" "+silent-test" "test"]} :pedantic? :abort)
fe57945586cd108a65536152d26530fc16dd77332053d0be8becd2d7e8fb8956
ocaml-gospel/gospel
t29.mli
(**************************************************************************) (* *) GOSPEL -- A Specification Language for OCaml (* *) Copyright ( c ) 2018- The VOCaL Project (* *) This software is free software , distributed under the MIT license (* (as described in file LICENSE enclosed). *) (**************************************************************************) exception E of float list val f : 'a -> 'a @ x = f y raises E l - > match l with | [ ] - > false | y : : ys - > y = 2 raises E l -> match l with | [] -> false | y :: ys -> y = 2 *) ERROR : Line 16 y is of type float and 2 of type integer replace " 2 " by " 2 . " in line 18 Line 16 y is of type float and 2 of type integer replace "2" by "2." in line 18 *) { gospel_expected| [ 125 ] File " t29.mli " , line 17 , characters 31 - 32 : 17 | | y : : ys - > y = 2 [125] File "t29.mli", line 17, characters 31-32: 17 | | y :: ys -> y = 2 *) ^ Error: This term has type `float' but a term was expected of type `integer'. |gospel_expected} *)
null
https://raw.githubusercontent.com/ocaml-gospel/gospel/79841c510baeb396d9a695ae33b290899188380b/test/negative/t29.mli
ocaml
************************************************************************ (as described in file LICENSE enclosed). ************************************************************************
GOSPEL -- A Specification Language for OCaml Copyright ( c ) 2018- The VOCaL Project This software is free software , distributed under the MIT license exception E of float list val f : 'a -> 'a @ x = f y raises E l - > match l with | [ ] - > false | y : : ys - > y = 2 raises E l -> match l with | [] -> false | y :: ys -> y = 2 *) ERROR : Line 16 y is of type float and 2 of type integer replace " 2 " by " 2 . " in line 18 Line 16 y is of type float and 2 of type integer replace "2" by "2." in line 18 *) { gospel_expected| [ 125 ] File " t29.mli " , line 17 , characters 31 - 32 : 17 | | y : : ys - > y = 2 [125] File "t29.mli", line 17, characters 31-32: 17 | | y :: ys -> y = 2 *) ^ Error: This term has type `float' but a term was expected of type `integer'. |gospel_expected} *)
42f1095a8d879d4adad9349679228f6d44439d14174e1d878876d76ff3de5128
mistupv/cauder
dining_philo_dist.erl
-module(dining_philo_dist). -export([main/0, waiter/0, fork/1, philo/2]). main() -> spawn_nodes(5), io:format("Nodes: ~p~n", [nodes()]), erlang:spawn(?MODULE, waiter, []). spawn_nodes(0) -> ok; spawn_nodes(N) -> slave:start('mac', string:concat("philo", integer_to_list(N))), spawn_nodes(N - 1). spawn_forks([], Dict) -> Dict; spawn_forks([Node | Nodes], Dict) -> N = length([Node | Nodes]), Pair = {N, erlang:spawn(Node, ?MODULE, fork, [free])}, spawn_forks(Nodes, [Pair] ++ Dict). spawn_philos([], Dict, _) -> Dict; spawn_philos([Node | Nodes], Dict, Pid) -> N = length([Node | Nodes]), Pair = {erlang:spawn(Node, ?MODULE, philo, [Pid, N]), N}, spawn_philos(Nodes, [Pair] ++ Dict, Pid). waiter() -> ListOfNodes = nodes(), ForkDict = spawn_forks(ListOfNodes, []), PhiloDict = spawn_philos(ListOfNodes, [], self()), waiter_1(ForkDict, PhiloDict). waiter_1(ForkDict, PhiloDict) -> receive {eaten, PhiloPid} -> PhiloId = proplists:get_value(PhiloPid, PhiloDict), LeftForkId = PhiloId, % Correct version RightForkId = 1 + (LeftForkId rem 5), RightForkId = 1 + ( 5 rem LeftForkId ) , % Buggy version LeftPid = proplists:get_value(LeftForkId, ForkDict), RightPid = proplists:get_value(RightForkId, ForkDict), set_state(LeftPid, free), set_state(RightPid, free); {hungry, PhiloPid} -> PhiloId = proplists:get_value(PhiloPid, PhiloDict), LeftForkId = PhiloId, RightForkId = 1 + (LeftForkId rem 5), LeftPid = proplists:get_value(LeftForkId, ForkDict), RightPid = proplists:get_value(RightForkId, ForkDict), LeftForkState = ask_state(LeftPid), RightForkState = ask_state(RightPid), case {LeftForkState, RightForkState} of {free, free} -> set_state(LeftPid, used), set_state(RightPid, used), PhiloPid ! eat; _ -> PhiloPid ! think end end, waiter_1(ForkDict, PhiloDict). ask_state(Pid) -> Pid ! {get_state, self()}, receive {state, State, _} -> State end. set_state(Pid, State) -> Pid ! {set_state, State, self()}, receive {been_set, _} -> ok end. philo(WaiterPid, PhiloId) -> think(PhiloId), request_until_eaten(WaiterPid, PhiloId), philo(WaiterPid, PhiloId). think(PhiloId) -> io:fwrite("Philo " ++ integer_to_list(PhiloId) ++ " is thinking~n"), ThinkTime = rand:uniform(1000), timer:sleep(ThinkTime), ok. eat(PhiloId) -> io:fwrite("Philo " ++ integer_to_list(PhiloId) ++ " has eaten~n"), timer:sleep(1000), ok. request_until_eaten(WaiterPid, PhiloId) -> io:fwrite("Philo " ++ integer_to_list(PhiloId) ++ " is hungry~n"), WaiterPid ! {hungry, self()}, receive think -> think(PhiloId), request_until_eaten(WaiterPid, PhiloId); eat -> eat(PhiloId), WaiterPid ! {eaten, self()} end. fork(State) -> receive {get_state, WaiterPid} -> WaiterPid ! {state, State, self()}, fork(State); {set_state, NewState, WaiterPid} -> WaiterPid ! {been_set, self()}, fork(NewState) end.
null
https://raw.githubusercontent.com/mistupv/cauder/ff4955cca4b0aa6ae9d682e9f0532be188a5cc16/examples/distributed/dining_philo_dist.erl
erlang
Correct version Buggy version
-module(dining_philo_dist). -export([main/0, waiter/0, fork/1, philo/2]). main() -> spawn_nodes(5), io:format("Nodes: ~p~n", [nodes()]), erlang:spawn(?MODULE, waiter, []). spawn_nodes(0) -> ok; spawn_nodes(N) -> slave:start('mac', string:concat("philo", integer_to_list(N))), spawn_nodes(N - 1). spawn_forks([], Dict) -> Dict; spawn_forks([Node | Nodes], Dict) -> N = length([Node | Nodes]), Pair = {N, erlang:spawn(Node, ?MODULE, fork, [free])}, spawn_forks(Nodes, [Pair] ++ Dict). spawn_philos([], Dict, _) -> Dict; spawn_philos([Node | Nodes], Dict, Pid) -> N = length([Node | Nodes]), Pair = {erlang:spawn(Node, ?MODULE, philo, [Pid, N]), N}, spawn_philos(Nodes, [Pair] ++ Dict, Pid). waiter() -> ListOfNodes = nodes(), ForkDict = spawn_forks(ListOfNodes, []), PhiloDict = spawn_philos(ListOfNodes, [], self()), waiter_1(ForkDict, PhiloDict). waiter_1(ForkDict, PhiloDict) -> receive {eaten, PhiloPid} -> PhiloId = proplists:get_value(PhiloPid, PhiloDict), LeftForkId = PhiloId, RightForkId = 1 + (LeftForkId rem 5), LeftPid = proplists:get_value(LeftForkId, ForkDict), RightPid = proplists:get_value(RightForkId, ForkDict), set_state(LeftPid, free), set_state(RightPid, free); {hungry, PhiloPid} -> PhiloId = proplists:get_value(PhiloPid, PhiloDict), LeftForkId = PhiloId, RightForkId = 1 + (LeftForkId rem 5), LeftPid = proplists:get_value(LeftForkId, ForkDict), RightPid = proplists:get_value(RightForkId, ForkDict), LeftForkState = ask_state(LeftPid), RightForkState = ask_state(RightPid), case {LeftForkState, RightForkState} of {free, free} -> set_state(LeftPid, used), set_state(RightPid, used), PhiloPid ! eat; _ -> PhiloPid ! think end end, waiter_1(ForkDict, PhiloDict). ask_state(Pid) -> Pid ! {get_state, self()}, receive {state, State, _} -> State end. set_state(Pid, State) -> Pid ! {set_state, State, self()}, receive {been_set, _} -> ok end. philo(WaiterPid, PhiloId) -> think(PhiloId), request_until_eaten(WaiterPid, PhiloId), philo(WaiterPid, PhiloId). think(PhiloId) -> io:fwrite("Philo " ++ integer_to_list(PhiloId) ++ " is thinking~n"), ThinkTime = rand:uniform(1000), timer:sleep(ThinkTime), ok. eat(PhiloId) -> io:fwrite("Philo " ++ integer_to_list(PhiloId) ++ " has eaten~n"), timer:sleep(1000), ok. request_until_eaten(WaiterPid, PhiloId) -> io:fwrite("Philo " ++ integer_to_list(PhiloId) ++ " is hungry~n"), WaiterPid ! {hungry, self()}, receive think -> think(PhiloId), request_until_eaten(WaiterPid, PhiloId); eat -> eat(PhiloId), WaiterPid ! {eaten, self()} end. fork(State) -> receive {get_state, WaiterPid} -> WaiterPid ! {state, State, self()}, fork(State); {set_state, NewState, WaiterPid} -> WaiterPid ! {been_set, self()}, fork(NewState) end.
821ea401cc6745d9366e96a5cb51d84205e001441f66c166d5b4285b1dd2fb69
philnguyen/soft-contract
data-adaptor.rkt
#lang racket (module sub racket/base (require racket/contract "data.rkt") (provide (contract-out (struct posn ([x real?]))))) (require 'sub) (define x 42) (provide [struct-out posn] (contract-out ; make sure it's reached [x string?]))
null
https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/unsafe/issues/struct-out-twice/data-adaptor.rkt
racket
make sure it's reached
#lang racket (module sub racket/base (require racket/contract "data.rkt") (provide (contract-out (struct posn ([x real?]))))) (require 'sub) (define x 42) (provide [struct-out posn] [x string?]))
75627ad690e168ffb7eb3a0be37ab89f2384f96ffbd6bb68c13ef6a26df03c3e
FPtje/miso-isomorphic-example
Main.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # {-# LANGUAGE TypeOperators #-} module Main where import qualified Common import Data.Proxy import qualified Lucid as L import qualified Lucid.Base as L import qualified Network.HTTP.Types as HTTP import qualified Network.Wai as Wai import qualified Network.Wai.Handler.Warp as Wai import qualified Network.Wai.Middleware.Gzip as Wai import qualified Network.Wai.Middleware.RequestLogger as Wai import qualified Servant import Servant ( (:>), (:<|>)(..) ) import qualified System.IO as IO import qualified Miso import Miso ( View ) main :: IO () main = do IO.hPutStrLn IO.stderr "Running on port 3003..." Wai.run 3003 $ Wai.logStdout $ compress app where compress :: Wai.Middleware compress = Wai.gzip Wai.def { Wai.gzipFiles = Wai.GzipCompress } app :: Wai.Application app = Servant.serve (Proxy @ServerAPI) ( static :<|> serverHandlers :<|> Servant.Tagged page404 ) where static :: Servant.Server StaticAPI static = Servant.serveDirectoryFileServer "static" serverHandlers :: Servant.Server ServerRoutes serverHandlers = homeServer :<|> flippedServer -- Alternative type: -- Servant.Server (ToServerRoutes Common.Home HtmlPage Common.Action) Handles the route for the home page , rendering Common.homeView . homeServer :: Servant.Handler (HtmlPage (View Common.Action)) homeServer = pure $ HtmlPage $ Common.viewModel $ Common.initialModel Common.homeLink -- Alternative type: -- Servant.Server (ToServerRoutes Common.Flipped HtmlPage Common.Action) -- Renders the /flipped page. flippedServer :: Servant.Handler (HtmlPage (View Common.Action)) flippedServer = pure $ HtmlPage $ Common.viewModel $ Common.initialModel Common.flippedLink The 404 page is a application because the endpoint is Raw . -- It just renders the page404View and sends it to the client. page404 :: Wai.Application page404 _ respond = respond $ Wai.responseLBS HTTP.status404 [("Content-Type", "text/html")] $ L.renderBS $ L.toHtml Common.page404View -- | Represents the top level Html code. Its value represents the body of the -- page. newtype HtmlPage a = HtmlPage a deriving (Show, Eq) instance L.ToHtml a => L.ToHtml (HtmlPage a) where toHtmlRaw = L.toHtml toHtml (HtmlPage x) = do L.doctype_ L.head_ $ do L.title_ "Miso isomorphic example" L.meta_ [L.charset_ "utf-8"] L.with (L.script_ mempty) [ L.makeAttribute "src" "/static/all.js" , L.makeAttribute "async" mempty , L.makeAttribute "defer" mempty ] L.body_ (L.toHtml x) -- Converts the ClientRoutes (which are a servant tree of routes leading to -- some `View action`) to lead to `Get '[Html] (HtmlPage (View Common.Action))` type ServerRoutes = Miso.ToServerRoutes Common.ViewRoutes HtmlPage Common.Action The server serves static files besides the ServerRoutes , among which is the -- javascript file of the client. type ServerAPI = StaticAPI :<|> (ServerRoutes This will show the 404 page for any unknown route type StaticAPI = "static" :> Servant.Raw
null
https://raw.githubusercontent.com/FPtje/miso-isomorphic-example/f14d9d40cd66d6e663c38b3798bcc8d3fe8ab2cf/server/Main.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators # Alternative type: Servant.Server (ToServerRoutes Common.Home HtmlPage Common.Action) Alternative type: Servant.Server (ToServerRoutes Common.Flipped HtmlPage Common.Action) Renders the /flipped page. It just renders the page404View and sends it to the client. | Represents the top level Html code. Its value represents the body of the page. Converts the ClientRoutes (which are a servant tree of routes leading to some `View action`) to lead to `Get '[Html] (HtmlPage (View Common.Action))` javascript file of the client.
# LANGUAGE TypeApplications # module Main where import qualified Common import Data.Proxy import qualified Lucid as L import qualified Lucid.Base as L import qualified Network.HTTP.Types as HTTP import qualified Network.Wai as Wai import qualified Network.Wai.Handler.Warp as Wai import qualified Network.Wai.Middleware.Gzip as Wai import qualified Network.Wai.Middleware.RequestLogger as Wai import qualified Servant import Servant ( (:>), (:<|>)(..) ) import qualified System.IO as IO import qualified Miso import Miso ( View ) main :: IO () main = do IO.hPutStrLn IO.stderr "Running on port 3003..." Wai.run 3003 $ Wai.logStdout $ compress app where compress :: Wai.Middleware compress = Wai.gzip Wai.def { Wai.gzipFiles = Wai.GzipCompress } app :: Wai.Application app = Servant.serve (Proxy @ServerAPI) ( static :<|> serverHandlers :<|> Servant.Tagged page404 ) where static :: Servant.Server StaticAPI static = Servant.serveDirectoryFileServer "static" serverHandlers :: Servant.Server ServerRoutes serverHandlers = homeServer :<|> flippedServer Handles the route for the home page , rendering Common.homeView . homeServer :: Servant.Handler (HtmlPage (View Common.Action)) homeServer = pure $ HtmlPage $ Common.viewModel $ Common.initialModel Common.homeLink flippedServer :: Servant.Handler (HtmlPage (View Common.Action)) flippedServer = pure $ HtmlPage $ Common.viewModel $ Common.initialModel Common.flippedLink The 404 page is a application because the endpoint is Raw . page404 :: Wai.Application page404 _ respond = respond $ Wai.responseLBS HTTP.status404 [("Content-Type", "text/html")] $ L.renderBS $ L.toHtml Common.page404View newtype HtmlPage a = HtmlPage a deriving (Show, Eq) instance L.ToHtml a => L.ToHtml (HtmlPage a) where toHtmlRaw = L.toHtml toHtml (HtmlPage x) = do L.doctype_ L.head_ $ do L.title_ "Miso isomorphic example" L.meta_ [L.charset_ "utf-8"] L.with (L.script_ mempty) [ L.makeAttribute "src" "/static/all.js" , L.makeAttribute "async" mempty , L.makeAttribute "defer" mempty ] L.body_ (L.toHtml x) type ServerRoutes = Miso.ToServerRoutes Common.ViewRoutes HtmlPage Common.Action The server serves static files besides the ServerRoutes , among which is the type ServerAPI = StaticAPI :<|> (ServerRoutes This will show the 404 page for any unknown route type StaticAPI = "static" :> Servant.Raw
f4e59617e0167b824b2683c6f7feafcea219b309cd878331ceaa4a4762f73807
hugoduncan/oldmj
bump.clj
(ns makejack.tools.bump "Bump version" (:require [clojure.edn :as edn] [clojure.string :as str] [makejack.api.core :as makejack] [makejack.api.filesystem :as filesystem] [makejack.api.path :as path] [makejack.api.tool :as tool] [makejack.api.util :as util])) (defn infer-source [{:keys [dir]}] (if (filesystem/file-exists? (path/path-for dir "version.edn")) {:type :version-edn :path "version.edn"} {:type :project-edn})) (defn maybe-long [x] (try (Long/parseLong x) (catch Exception _e x))) (defn read-version-map [version] {:pre [(string? version)]} (let [components (mapv maybe-long (str/split version #"[.-]"))] (zipmap [:major :minor :incremental :qualifier] components))) (defmulti current-version (fn [version-source _project _options] (:type version-source))) (defmethod current-version :project-edn [_version-source {:keys [version]} _options] (read-version-map version)) (defmethod current-version :version-edn [{:keys [path]} {:keys [version]} {:keys [dir]}] (edn/read-string (slurp (path/as-file (path/path-for dir path))))) (defn next-version [version-map [part value]] (let [part-kw (keyword part)] (cond value (assoc version-map part-kw (maybe-long value)) (number? (part-kw version-map)) (update version-map part-kw inc) :else (throw (ex-info "Must supply a value for non-numeric part" {:version-map version-map :part part-kw}))))) (defn- update-file-with-regex [path search-regex old-str new-str] (let [path (path/path path) content-str (slurp (path/as-file path)) found-str (re-find search-regex content-str) new-found-str (str/replace found-str old-str new-str) new-content-str (str/replace content-str found-str new-found-str)] (spit (path/as-file path) new-content-str))) (defmulti update-version-source (fn [version-source _old-version-map _new-version-map _options] (:type version-source))) (defmethod update-version-source :project-edn [_version-source old-version-map new-version-map {:keys [dir]}] (let [project-file (path/path-for dir "project.edn")] (update-file-with-regex project-file #":version\s+\".*\"" (util/format-version-map old-version-map) (util/format-version-map new-version-map)))) (defmethod update-version-source :version-edn [{:keys [path]} _old-version-map new-version-map {:keys [dir]}] (spit (path/as-file (path/path-for dir path)) (pr-str new-version-map))) (defmulti update-version (fn [filedef _old-version-map _new-version-map _options] (cond (string? filedef) :file-literal (path/path? filedef) :file-literal {:search filedef} :file-search))) (defmethod update-version :file-literal [filedef old-version-map new-version-map {:keys [dir]}] (let [path (path/path-for dir filedef) content-str (slurp (path/as-file path)) new-version-str (str/replace content-str (util/format-version-map old-version-map) (util/format-version-map new-version-map))] (spit (path/as-file path) new-version-str))) (defmethod update-version :file-search [{:keys [search path]} old-version-map new-version-map {:keys [dir]}] (update-file-with-regex (path/path-for dir path) search (util/format-version-map old-version-map) (util/format-version-map new-version-map))) (defn bump "Bump project version" [options args {:keys [mj project]}] (let [version-source (infer-source options) version-map (current-version version-source project options) new-version (next-version version-map args)] (makejack/verbose-println "Updating from" (util/format-version-map version-map) "to" (util/format-version-map new-version)) (update-version-source version-source version-map new-version options) (doseq [update (:versioned-files project)] (update-version update version-map new-version options)))) (def extra-options []) (defn bump-xfun [{:keys [updates dir profiles verbpse debug args] :as options}] (let [{:keys [project] :as config} (makejack/load-config options)] (tool/with-shutdown-agents (tool/with-makejack-tool ["bump" "[options]" project] (bump (dissoc options :args) args config))))) (defn -main [& args] (tool/with-shutdown-agents (tool/dispatch-main "bump" "[options] [:major|:minor|:incremental] [qualifier]" bump extra-options args)))
null
https://raw.githubusercontent.com/hugoduncan/oldmj/0a97488be7457baed01d2d9dd0ea6df4383832ab/tools/src/makejack/tools/bump.clj
clojure
(ns makejack.tools.bump "Bump version" (:require [clojure.edn :as edn] [clojure.string :as str] [makejack.api.core :as makejack] [makejack.api.filesystem :as filesystem] [makejack.api.path :as path] [makejack.api.tool :as tool] [makejack.api.util :as util])) (defn infer-source [{:keys [dir]}] (if (filesystem/file-exists? (path/path-for dir "version.edn")) {:type :version-edn :path "version.edn"} {:type :project-edn})) (defn maybe-long [x] (try (Long/parseLong x) (catch Exception _e x))) (defn read-version-map [version] {:pre [(string? version)]} (let [components (mapv maybe-long (str/split version #"[.-]"))] (zipmap [:major :minor :incremental :qualifier] components))) (defmulti current-version (fn [version-source _project _options] (:type version-source))) (defmethod current-version :project-edn [_version-source {:keys [version]} _options] (read-version-map version)) (defmethod current-version :version-edn [{:keys [path]} {:keys [version]} {:keys [dir]}] (edn/read-string (slurp (path/as-file (path/path-for dir path))))) (defn next-version [version-map [part value]] (let [part-kw (keyword part)] (cond value (assoc version-map part-kw (maybe-long value)) (number? (part-kw version-map)) (update version-map part-kw inc) :else (throw (ex-info "Must supply a value for non-numeric part" {:version-map version-map :part part-kw}))))) (defn- update-file-with-regex [path search-regex old-str new-str] (let [path (path/path path) content-str (slurp (path/as-file path)) found-str (re-find search-regex content-str) new-found-str (str/replace found-str old-str new-str) new-content-str (str/replace content-str found-str new-found-str)] (spit (path/as-file path) new-content-str))) (defmulti update-version-source (fn [version-source _old-version-map _new-version-map _options] (:type version-source))) (defmethod update-version-source :project-edn [_version-source old-version-map new-version-map {:keys [dir]}] (let [project-file (path/path-for dir "project.edn")] (update-file-with-regex project-file #":version\s+\".*\"" (util/format-version-map old-version-map) (util/format-version-map new-version-map)))) (defmethod update-version-source :version-edn [{:keys [path]} _old-version-map new-version-map {:keys [dir]}] (spit (path/as-file (path/path-for dir path)) (pr-str new-version-map))) (defmulti update-version (fn [filedef _old-version-map _new-version-map _options] (cond (string? filedef) :file-literal (path/path? filedef) :file-literal {:search filedef} :file-search))) (defmethod update-version :file-literal [filedef old-version-map new-version-map {:keys [dir]}] (let [path (path/path-for dir filedef) content-str (slurp (path/as-file path)) new-version-str (str/replace content-str (util/format-version-map old-version-map) (util/format-version-map new-version-map))] (spit (path/as-file path) new-version-str))) (defmethod update-version :file-search [{:keys [search path]} old-version-map new-version-map {:keys [dir]}] (update-file-with-regex (path/path-for dir path) search (util/format-version-map old-version-map) (util/format-version-map new-version-map))) (defn bump "Bump project version" [options args {:keys [mj project]}] (let [version-source (infer-source options) version-map (current-version version-source project options) new-version (next-version version-map args)] (makejack/verbose-println "Updating from" (util/format-version-map version-map) "to" (util/format-version-map new-version)) (update-version-source version-source version-map new-version options) (doseq [update (:versioned-files project)] (update-version update version-map new-version options)))) (def extra-options []) (defn bump-xfun [{:keys [updates dir profiles verbpse debug args] :as options}] (let [{:keys [project] :as config} (makejack/load-config options)] (tool/with-shutdown-agents (tool/with-makejack-tool ["bump" "[options]" project] (bump (dissoc options :args) args config))))) (defn -main [& args] (tool/with-shutdown-agents (tool/dispatch-main "bump" "[options] [:major|:minor|:incremental] [qualifier]" bump extra-options args)))
d38929a03d13b773ee8001b07491f31da1d2c938ae8125cd2c858b3ad6097451
blindglobe/clocc
sysdef.lisp
(in-package :user) (eval-when (load eval) (unless (find-package :mk) (load "library:defsystem")) ) (defparameter *here* (make-pathname :directory (pathname-directory *load-truename*))) #+pcl (progn (pushnew 'compile pcl::*defclass-times*) (pushnew 'compile pcl::*defgeneric-times*)) (defvar *clx-directory* "target:clx/*") (defvar *clue-directory* (merge-pathnames "clue/" *here*)) #+cmu (setf (search-list "clue:") (list *here*)) ;; Ensure VALUES is a legal declaration #-cmu17 (proclaim '(declaration values)) #+cmu17 ;; Don't warn about botched values decls (setf c:*suppress-values-declaration* t) #+pcl ;; This is now in current sources (pushnew 'values pcl::*non-variable-declarations*) Ensure * features * knows about CLOS and PCL (when (find-package 'pcl) (pushnew :pcl *features*) (pushnew :clos *features*) (unless (find-package :clos) (rename-package :pcl :pcl '(:clos)))) (when (find-package 'clos) (pushnew :clos *features*)) Ensure * features * knows about the Common Lisp Error Handler (when (find-package 'conditions) (pushnew :cleh *features*)) handle PCL 's precompile " feature " (defun hack-precom (path op &optional (pathname "precom")) (declare (type (member :compile :load :ignore) op)) (let* ((src (merge-pathnames (make-pathname :name pathname :type "lisp") path)) (obj (compile-file-pathname src))) ( format t " ~ & ~a ~a ~a ~a~% " path op pathname ) (case op (:compile (when (probe-file src) (unless (probe-file obj) (compile-file src)))) (:load (when (probe-file obj) (load obj)))))) (mk:defsystem clx :source-pathname "target:clx/" :components ((:file "macros")(:file "bufmac"))) (defvar *clue-precom* "clue:clue/precom") (defvar *pict-precom* "clue:pictures/precom") (when (probe-file "clue:patch.lisp") (load "clue:patch" :if-source-newer :compile)) (mk:defsystem clue :source-pathname "clue:clue/" :depends-on (clx) :components ( #+nil(:file "common-lisp") (:file "clue") ; Define packages (:module clue-precom-load :load-form (hack-precom "clue:clue/" :load) :compile-form t) #+nil(:file "clx-patch") ; Modify xlib:create-window #+nil(:file "window-doc") ; pointer documentation window support (:file "defgeneric") ; pw adds Utilities for event translation CLOS for resources and type conversion (:file "intrinsics") ; The "guts" Support for gcontext , pixmap , cursor (:file "resource") ; Resource and type conversion (:file "gray") ; Gray stipple patterns (:file "cursor") ; Standard cursor names (:file "events") ; Event handling (:file "virtual") ; Support for windowless contacts (:file "shells") ; Support for top-level window/session mgr. Geometry management methods for root contacts #+nil(:file "stream") ; interactive-stream (non-portable!!) (:file "package") ; External cluei symbols exported from clue (:module clue-precom-com :load-form t :compile-only t :compile-form (hack-precom "clue:clue/" :compile)) )) (mk:defsystem clio :depends-on ( clue ) :source-pathname "clue:clio/" :components ((:file "clio") (:file "defgeneric") (:module clio-precom-load :load-form (hack-precom "clue:clio/" :load) :compile-form t) (:file "ol-defs") (:file "utility") (:file "core-mixins") (:file "gravity") (:file "ol-images") (:file "buttons") (:file "form") (:file "table") (:file "choices") (:file "scroller") (:file "slider") (:file "scroll-frame") (:file "mchoices") (:file "menu") (:file "psheet") (:file "command") (:file "confirm") (:file "buffer") (:file "text-command") (:file "display-text") (:file "edit-text") (:file "display-imag") (:file "dlog-button") (:module clio-precom-com :load-form t :compile-only t :compile-form (hack-precom "clue:clio/" :compile)) )) (mk:defsystem clio-examples :source-pathname "clue:clio/examples/" :components ("package" "cmd-frame" "sketchpad" "sketch")) (mk:defsystem pictures :source-pathname "clue:pictures/" :depends-on (clue ) :components ((:file "package") (:module pict-precom-load :load-form (hack-precom "clue:pictures/" :load) :compile-form t) (:file "defgeneric") (:file "types") (:file "macros") (:file "sequence") (:file "transform") (:file "extent") (:file "edge" ) (:file "class-def" :depends-on ("edge" "extent")) ;; these have circular dependencies (:file "gstate" :depends-on ("class-def")) (:file "gstack") (:file "graphic") (:file "font-family") (:file "view-draw") (:file "scene") (:file "line") (:file "circle") (:file "polypoint") (:file "polygon") (:file "rectangle") (:file "bspline") (:file "ellipse") (:file "label") (:file "gimage") (:file "gevents") (:file "grabber") (:file "view") (:file "view-events") (:file "view-select") (:file "view-zoom") (:file "view-pan") (:file "utilities") (:file "save") (:file "restore") (:module pict-precom-com :load-form t :compile-only t :compile-form (hack-precom "clue:pictures/" :compile)) )) (defun load-clue() (mk:oos 'clue :load) (purify)) (defun compile-it (thing) (with-compilation-unit (:optimize '(optimize (ext:inhibit-warnings 3) (debug #-small 2 #+small .5) ( speed 2 ) ( inhibit - warnings 3 ) (safety #-small 1 #+small 0) ) :optimize-interface '(optimize-interface (debug .5)) :context-declarations '(((:and :external :global) (declare (optimize-interface (safety 2) (debug 1)))) ((:and :external :macro) (declare (optimize (safety 2)))) (:macro (declare (optimize (speed 0)))))) (mk:oos thing :compile))) (defun compile-all() (with-compilation-unit (:optimize '(optimize ( ext : inhibit - warnings 3 ) (debug #-small 2 #+small .5) (speed 2) (inhibit-warnings 3) (safety #-small 1 #+small 1) ) :optimize-interface '(optimize-interface (debug .5)) :context-declarations '(((:and :external :global) (declare (optimize-interface (safety 2) (debug 1)))) ((:and :external :macro) (declare (optimize (safety 2)))) (:macro (declare (optimize (speed 0)))))) (mk:oos 'graphics :compile))) (unintern 'name)
null
https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/sysdef.lisp
lisp
Ensure VALUES is a legal declaration Don't warn about botched values decls This is now in current sources Define packages Modify xlib:create-window pointer documentation window support pw adds The "guts" Resource and type conversion Gray stipple patterns Standard cursor names Event handling Support for windowless contacts Support for top-level window/session mgr. interactive-stream (non-portable!!) External cluei symbols exported from clue these have circular dependencies
(in-package :user) (eval-when (load eval) (unless (find-package :mk) (load "library:defsystem")) ) (defparameter *here* (make-pathname :directory (pathname-directory *load-truename*))) #+pcl (progn (pushnew 'compile pcl::*defclass-times*) (pushnew 'compile pcl::*defgeneric-times*)) (defvar *clx-directory* "target:clx/*") (defvar *clue-directory* (merge-pathnames "clue/" *here*)) #+cmu (setf (search-list "clue:") (list *here*)) #-cmu17 (proclaim '(declaration values)) (setf c:*suppress-values-declaration* t) (pushnew 'values pcl::*non-variable-declarations*) Ensure * features * knows about CLOS and PCL (when (find-package 'pcl) (pushnew :pcl *features*) (pushnew :clos *features*) (unless (find-package :clos) (rename-package :pcl :pcl '(:clos)))) (when (find-package 'clos) (pushnew :clos *features*)) Ensure * features * knows about the Common Lisp Error Handler (when (find-package 'conditions) (pushnew :cleh *features*)) handle PCL 's precompile " feature " (defun hack-precom (path op &optional (pathname "precom")) (declare (type (member :compile :load :ignore) op)) (let* ((src (merge-pathnames (make-pathname :name pathname :type "lisp") path)) (obj (compile-file-pathname src))) ( format t " ~ & ~a ~a ~a ~a~% " path op pathname ) (case op (:compile (when (probe-file src) (unless (probe-file obj) (compile-file src)))) (:load (when (probe-file obj) (load obj)))))) (mk:defsystem clx :source-pathname "target:clx/" :components ((:file "macros")(:file "bufmac"))) (defvar *clue-precom* "clue:clue/precom") (defvar *pict-precom* "clue:pictures/precom") (when (probe-file "clue:patch.lisp") (load "clue:patch" :if-source-newer :compile)) (mk:defsystem clue :source-pathname "clue:clue/" :depends-on (clx) :components ( #+nil(:file "common-lisp") (:module clue-precom-load :load-form (hack-precom "clue:clue/" :load) :compile-form t) Utilities for event translation CLOS for resources and type conversion Support for gcontext , pixmap , cursor Geometry management methods for root contacts (:module clue-precom-com :load-form t :compile-only t :compile-form (hack-precom "clue:clue/" :compile)) )) (mk:defsystem clio :depends-on ( clue ) :source-pathname "clue:clio/" :components ((:file "clio") (:file "defgeneric") (:module clio-precom-load :load-form (hack-precom "clue:clio/" :load) :compile-form t) (:file "ol-defs") (:file "utility") (:file "core-mixins") (:file "gravity") (:file "ol-images") (:file "buttons") (:file "form") (:file "table") (:file "choices") (:file "scroller") (:file "slider") (:file "scroll-frame") (:file "mchoices") (:file "menu") (:file "psheet") (:file "command") (:file "confirm") (:file "buffer") (:file "text-command") (:file "display-text") (:file "edit-text") (:file "display-imag") (:file "dlog-button") (:module clio-precom-com :load-form t :compile-only t :compile-form (hack-precom "clue:clio/" :compile)) )) (mk:defsystem clio-examples :source-pathname "clue:clio/examples/" :components ("package" "cmd-frame" "sketchpad" "sketch")) (mk:defsystem pictures :source-pathname "clue:pictures/" :depends-on (clue ) :components ((:file "package") (:module pict-precom-load :load-form (hack-precom "clue:pictures/" :load) :compile-form t) (:file "defgeneric") (:file "types") (:file "macros") (:file "sequence") (:file "transform") (:file "extent") (:file "edge" ) (:file "class-def" :depends-on ("edge" "extent")) (:file "gstate" :depends-on ("class-def")) (:file "gstack") (:file "graphic") (:file "font-family") (:file "view-draw") (:file "scene") (:file "line") (:file "circle") (:file "polypoint") (:file "polygon") (:file "rectangle") (:file "bspline") (:file "ellipse") (:file "label") (:file "gimage") (:file "gevents") (:file "grabber") (:file "view") (:file "view-events") (:file "view-select") (:file "view-zoom") (:file "view-pan") (:file "utilities") (:file "save") (:file "restore") (:module pict-precom-com :load-form t :compile-only t :compile-form (hack-precom "clue:pictures/" :compile)) )) (defun load-clue() (mk:oos 'clue :load) (purify)) (defun compile-it (thing) (with-compilation-unit (:optimize '(optimize (ext:inhibit-warnings 3) (debug #-small 2 #+small .5) ( speed 2 ) ( inhibit - warnings 3 ) (safety #-small 1 #+small 0) ) :optimize-interface '(optimize-interface (debug .5)) :context-declarations '(((:and :external :global) (declare (optimize-interface (safety 2) (debug 1)))) ((:and :external :macro) (declare (optimize (safety 2)))) (:macro (declare (optimize (speed 0)))))) (mk:oos thing :compile))) (defun compile-all() (with-compilation-unit (:optimize '(optimize ( ext : inhibit - warnings 3 ) (debug #-small 2 #+small .5) (speed 2) (inhibit-warnings 3) (safety #-small 1 #+small 1) ) :optimize-interface '(optimize-interface (debug .5)) :context-declarations '(((:and :external :global) (declare (optimize-interface (safety 2) (debug 1)))) ((:and :external :macro) (declare (optimize (safety 2)))) (:macro (declare (optimize (speed 0)))))) (mk:oos 'graphics :compile))) (unintern 'name)
4d8c4ce19a01ba3765e701b4fcbbbe8aa877f5343b47733ffebd1703a9458af2
Spivoxity/obc-3
info.ml
* info.ml * * This file is part of the Oxford Oberon-2 compiler * Copyright ( c ) 2006 - -2016 J. M. Spivey * 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 name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission . * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` 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 AUTHOR 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 , * 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 . * info.ml * * This file is part of the Oxford Oberon-2 compiler * Copyright (c) 2006--2016 J. M. Spivey * 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 name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. *) open Print open Symtab open Symfile open Dict open Mach let modules = Hashtbl.create 20 let debug_defs = Hashtbl.create 100 let enum_dict = Hashtbl.create 100 let put_debug d = if d.d_lab <> nosym then Hashtbl.add debug_defs d.d_lab d let get_debug x = Hashtbl.find debug_defs x let init = Dict.debugger := put_debug; let p = { p_kind = Procedure; p_pcount = 0; p_fparams = []; p_result = voidtype } in put_debug { d_tag = intern "MAIN"; d_module = intern "%Main"; d_kind = ProcDef; d_type = new_type 0 (proctype p); d_export = Private; d_loc = Error.no_loc; d_line = 0; d_used = true; d_lab = "MAIN"; d_level = 0; d_offset = 0; d_param = 0; d_env = init_env (); d_comment = None; d_map = Gcmap.null_map } let import m objchk = try let symfile = Symfile.import m in if symfile.y_checksum <> objchk then fprintf stderr "? Symbol file for $ has wrong checksum\n" [fId m]; Hashtbl.add modules m symfile; List.iter (fun d -> match d.d_kind with EnumDef n -> if is_enum d.d_type then Hashtbl.add enum_dict (d.d_type.t_module, d.d_type.t_id, n) d | _ -> ()) (top_block symfile.y_env) with Not_found -> fprintf stderr "? Couldn't find symbol file for $\n" [fId m] let get_module m = let symfile = Hashtbl.find modules m in symfile.y_env let module_source m = let symfile = Hashtbl.find modules m in Debconf.find_source symfile.y_fname let find_enum t v = Hashtbl.find enum_dict (t.t_module, t.t_id, Eval.int_of_integer (Eval.int_value v))
null
https://raw.githubusercontent.com/Spivoxity/obc-3/9e5094df8382ac5dd25ff08768277be6bd71a4ae/debugger/info.ml
ocaml
* info.ml * * This file is part of the Oxford Oberon-2 compiler * Copyright ( c ) 2006 - -2016 J. M. Spivey * 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 name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission . * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` 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 AUTHOR 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 , * 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 . * info.ml * * This file is part of the Oxford Oberon-2 compiler * Copyright (c) 2006--2016 J. M. Spivey * 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 name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. *) open Print open Symtab open Symfile open Dict open Mach let modules = Hashtbl.create 20 let debug_defs = Hashtbl.create 100 let enum_dict = Hashtbl.create 100 let put_debug d = if d.d_lab <> nosym then Hashtbl.add debug_defs d.d_lab d let get_debug x = Hashtbl.find debug_defs x let init = Dict.debugger := put_debug; let p = { p_kind = Procedure; p_pcount = 0; p_fparams = []; p_result = voidtype } in put_debug { d_tag = intern "MAIN"; d_module = intern "%Main"; d_kind = ProcDef; d_type = new_type 0 (proctype p); d_export = Private; d_loc = Error.no_loc; d_line = 0; d_used = true; d_lab = "MAIN"; d_level = 0; d_offset = 0; d_param = 0; d_env = init_env (); d_comment = None; d_map = Gcmap.null_map } let import m objchk = try let symfile = Symfile.import m in if symfile.y_checksum <> objchk then fprintf stderr "? Symbol file for $ has wrong checksum\n" [fId m]; Hashtbl.add modules m symfile; List.iter (fun d -> match d.d_kind with EnumDef n -> if is_enum d.d_type then Hashtbl.add enum_dict (d.d_type.t_module, d.d_type.t_id, n) d | _ -> ()) (top_block symfile.y_env) with Not_found -> fprintf stderr "? Couldn't find symbol file for $\n" [fId m] let get_module m = let symfile = Hashtbl.find modules m in symfile.y_env let module_source m = let symfile = Hashtbl.find modules m in Debconf.find_source symfile.y_fname let find_enum t v = Hashtbl.find enum_dict (t.t_module, t.t_id, Eval.int_of_integer (Eval.int_value v))
c9ecaa16e84801b3a30382ea624e2dabbbcc3e2b20cd8679b74cb911a62d99dd
reagent-project/reagent-template
core_test.cljs
(ns {{project-ns}}.core-test (:require [cljs.test :refer-macros [is are deftest testing use-fixtures]] [reagent.core :as reagent :refer [atom]] [reagent.dom :as rdom] [{{project-ns}}.core :as rc])) (def isClient (not (nil? (try (.-document js/window) (catch js/Object e nil))))) (def rflush reagent/flush) (defn add-test-div [name] (let [doc js/document body (.-body js/document) div (.createElement doc "div")] (.appendChild body div) div)) (defn with-mounted-component [comp f] (when isClient (let [div (add-test-div "_testreagent")] (let [comp (rdom/render comp div #(f comp div))] (rdom/unmount-component-at-node div) (rflush) (.removeChild (.-body js/document) div))))) (defn found-in [re div] (let [res (.-innerHTML div)] (if (re-find re res) true (do (println "Not found: " res) false)))) (deftest test-home (with-mounted-component (rc/home-page) (fn [c div] (is (found-in #"Welcome to" div)))))
null
https://raw.githubusercontent.com/reagent-project/reagent-template/c769c6806540a9faafec36c27b07a1c86ae5eff7/resources/leiningen/new/reagent/test/cljs/reagent/core_test.cljs
clojure
(ns {{project-ns}}.core-test (:require [cljs.test :refer-macros [is are deftest testing use-fixtures]] [reagent.core :as reagent :refer [atom]] [reagent.dom :as rdom] [{{project-ns}}.core :as rc])) (def isClient (not (nil? (try (.-document js/window) (catch js/Object e nil))))) (def rflush reagent/flush) (defn add-test-div [name] (let [doc js/document body (.-body js/document) div (.createElement doc "div")] (.appendChild body div) div)) (defn with-mounted-component [comp f] (when isClient (let [div (add-test-div "_testreagent")] (let [comp (rdom/render comp div #(f comp div))] (rdom/unmount-component-at-node div) (rflush) (.removeChild (.-body js/document) div))))) (defn found-in [re div] (let [res (.-innerHTML div)] (if (re-find re res) true (do (println "Not found: " res) false)))) (deftest test-home (with-mounted-component (rc/home-page) (fn [c div] (is (found-in #"Welcome to" div)))))
fb44faeb326f3a344b40403092889478aec5efba6ed2b6a1446d438bb404fe90
facebookincubator/hsthrift
MD5Test.hs
Copyright ( c ) Facebook , Inc. and its affiliates . module MD5Test (main) where import Test.HUnit import TestRunner import Util.MD5 tests :: Test tests = TestList [ TestLabel "md5Test" $ TestCase $ assertEqual "md5Test" (md5 "wibble") "50eccc6e2b0d307d5e8a40fb296f6171" ] main :: IO () main = testRunner tests
null
https://raw.githubusercontent.com/facebookincubator/hsthrift/d3ff75d487e9d0c2904d18327373b603456e7a01/common/util/tests/MD5Test.hs
haskell
Copyright ( c ) Facebook , Inc. and its affiliates . module MD5Test (main) where import Test.HUnit import TestRunner import Util.MD5 tests :: Test tests = TestList [ TestLabel "md5Test" $ TestCase $ assertEqual "md5Test" (md5 "wibble") "50eccc6e2b0d307d5e8a40fb296f6171" ] main :: IO () main = testRunner tests
87bb0bde21ebc5d1e4f8e1730b595951dc166721894ad0f61763d6be89b4f75f
TiltMeSenpai/Discord.hs
language.hs
{-# LANGUAGE OverloadedStrings, RecordWildCards #-} import Network.Discord import Pipes import Data.Text import Control.Monad.IO.Class main = runBot (Bot "TOKEN") $ do with ReadyEvent $ \_ -> do liftIO $ putStr "Hello, World!" with MessageCreateEvent $ \msg@Message{messageAuthor=User{userIsBot=bot}} -> do liftIO $ print msg unless bot $ fetch' $ CreateMessage 188134500411244545 (pack $ show msg) Nothing
null
https://raw.githubusercontent.com/TiltMeSenpai/Discord.hs/91f688f03813982bbf7c37d048bd7bcc08671d8e/examples/language.hs
haskell
# LANGUAGE OverloadedStrings, RecordWildCards #
import Network.Discord import Pipes import Data.Text import Control.Monad.IO.Class main = runBot (Bot "TOKEN") $ do with ReadyEvent $ \_ -> do liftIO $ putStr "Hello, World!" with MessageCreateEvent $ \msg@Message{messageAuthor=User{userIsBot=bot}} -> do liftIO $ print msg unless bot $ fetch' $ CreateMessage 188134500411244545 (pack $ show msg) Nothing
2fbc8793b396c70c6b5f6d0940e7178ac2a2e31b85e6573030cfe3431529c75f
softlab-ntua/bencherl
api_json_dht_raw.erl
2012 Zuse Institute Berlin 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. @author < > %% @doc JSON API for access to raw DHT functions. %% @version $Id$ -module(api_json_dht_raw). -author(''). -vsn('$Id$'). -export([handler/2]). for : -export([range_read/2]). -include("scalaris.hrl"). -include("client_types.hrl"). main handler for calls -spec handler(atom(), list()) -> any(). handler(nop, [_Value]) -> "ok"; handler(range_read, [From, To]) -> range_read(From, To); handler(AnyOp, AnyParams) -> io:format("Unknown request = ~s:~p(~p)~n", [?MODULE, AnyOp, AnyParams]), {struct, [{failure, "unknownreq"}]}. -spec range_read(intervals:key(), intervals:key()) -> api_json_tx:result(). range_read(From, To) -> {ErrorCode, Data} = api_dht_raw:range_read(From, To), {struct, [{status, atom_to_list(ErrorCode)}, {value, data_to_json(Data)}]}. -spec data_to_json(Data::[db_entry:entry()]) -> {array, [{struct, [{key, ?RT:key()} | {value, api_json_tx:value()} | {version, ?DB:version()}] }]}. data_to_json(Data) -> {array, [ {struct, [{key, db_entry:get_key(DBEntry)}, api_json_tx:value_to_json(db_entry:get_value(DBEntry)), {version, db_entry:get_version(DBEntry)}]} || DBEntry <- Data]}.
null
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/scalaris/src/json/api_json_dht_raw.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc JSON API for access to raw DHT functions. @version $Id$
2012 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > -module(api_json_dht_raw). -author(''). -vsn('$Id$'). -export([handler/2]). for : -export([range_read/2]). -include("scalaris.hrl"). -include("client_types.hrl"). main handler for calls -spec handler(atom(), list()) -> any(). handler(nop, [_Value]) -> "ok"; handler(range_read, [From, To]) -> range_read(From, To); handler(AnyOp, AnyParams) -> io:format("Unknown request = ~s:~p(~p)~n", [?MODULE, AnyOp, AnyParams]), {struct, [{failure, "unknownreq"}]}. -spec range_read(intervals:key(), intervals:key()) -> api_json_tx:result(). range_read(From, To) -> {ErrorCode, Data} = api_dht_raw:range_read(From, To), {struct, [{status, atom_to_list(ErrorCode)}, {value, data_to_json(Data)}]}. -spec data_to_json(Data::[db_entry:entry()]) -> {array, [{struct, [{key, ?RT:key()} | {value, api_json_tx:value()} | {version, ?DB:version()}] }]}. data_to_json(Data) -> {array, [ {struct, [{key, db_entry:get_key(DBEntry)}, api_json_tx:value_to_json(db_entry:get_value(DBEntry)), {version, db_entry:get_version(DBEntry)}]} || DBEntry <- Data]}.
d144046a2b3abaa345cf1ada950a17a46dc604111d133c6772f494d6440119f2
ndmitchell/uniplate
Typeable.hs
# LANGUAGE CPP , FlexibleInstances , FlexibleContexts , UndecidableInstances , MultiParamTypeClasses # # OPTIONS_GHC -Wno - orphans -Wno - simplifiable - class - constraints # module Uniplate.Typeable where import Data.Generics.Uniplate.Typeable #include "CommonInc.hs" toMap = id fromMap = id instance (Ord a, Typeable a, PlateAll a c, Typeable b, PlateAll b c, Typeable c, PlateAll c c) => PlateAll (Map.Map a b) c where plateAll = plateProject Map.toList Map.fromList -- GENERATED instance (Typeable to, Uniplate to) => PlateAll Expr to where plateAll (Val x1) = plate Val |+ x1 plateAll (Var x1) = plate Var |+ x1 plateAll (Neg x1) = plate Neg |+ x1 plateAll (Add x1 x2) = plate Add |+ x1 |+ x2 plateAll (Sub x1 x2) = plate Sub |+ x1 |+ x2 plateAll (Mul x1 x2) = plate Mul |+ x1 |+ x2 plateAll (Div x1 x2) = plate Div |+ x1 |+ x2 instance (Typeable to, Uniplate to) => PlateAll Stm to where plateAll (SDecl x1 x2) = plate SDecl |+ x1 |+ x2 plateAll (SAss x1 x2) = plate SAss |+ x1 |+ x2 plateAll (SBlock x1) = plate SBlock |+ x1 plateAll (SReturn x1) = plate SReturn |+ x1 instance (Typeable to, Uniplate to) => PlateAll Exp to where plateAll (EStm x1) = plate EStm |+ x1 plateAll (EAdd x1 x2) = plate EAdd |+ x1 |+ x2 plateAll (EVar x1) = plate EVar |+ x1 plateAll (EInt x1) = plate EInt |+ x1 instance (Typeable to, Uniplate to) => PlateAll Var to where plateAll (V x1) = plate V |+ x1 instance (Typeable to, Uniplate to) => PlateAll Typ to where plateAll (T_int) = plate T_int plateAll (T_float) = plate T_float instance (Typeable to, Uniplate to) => PlateAll Company to where plateAll (C x1) = plate C |+ x1 instance (Typeable to, Uniplate to) => PlateAll Dept to where plateAll (D x1 x2 x3) = plate D |+ x1 |+ x2 |+ x3 instance (Typeable to, Uniplate to) => PlateAll Unt to where plateAll (PU x1) = plate PU |+ x1 plateAll (DU x1) = plate DU |+ x1 instance (Typeable to, Uniplate to) => PlateAll Employee to where plateAll (E x1 x2) = plate E |+ x1 |+ x2 instance (Typeable to, Uniplate to) => PlateAll Person to where plateAll (P x1 x2) = plate P |+ x1 |+ x2 instance (Typeable to, Uniplate to) => PlateAll Salary to where plateAll (S x1) = plate S |+ x1
null
https://raw.githubusercontent.com/ndmitchell/uniplate/7d3039606d7a083f6d77f9f960c919668788de91/Uniplate/Typeable.hs
haskell
GENERATED
# LANGUAGE CPP , FlexibleInstances , FlexibleContexts , UndecidableInstances , MultiParamTypeClasses # # OPTIONS_GHC -Wno - orphans -Wno - simplifiable - class - constraints # module Uniplate.Typeable where import Data.Generics.Uniplate.Typeable #include "CommonInc.hs" toMap = id fromMap = id instance (Ord a, Typeable a, PlateAll a c, Typeable b, PlateAll b c, Typeable c, PlateAll c c) => PlateAll (Map.Map a b) c where plateAll = plateProject Map.toList Map.fromList instance (Typeable to, Uniplate to) => PlateAll Expr to where plateAll (Val x1) = plate Val |+ x1 plateAll (Var x1) = plate Var |+ x1 plateAll (Neg x1) = plate Neg |+ x1 plateAll (Add x1 x2) = plate Add |+ x1 |+ x2 plateAll (Sub x1 x2) = plate Sub |+ x1 |+ x2 plateAll (Mul x1 x2) = plate Mul |+ x1 |+ x2 plateAll (Div x1 x2) = plate Div |+ x1 |+ x2 instance (Typeable to, Uniplate to) => PlateAll Stm to where plateAll (SDecl x1 x2) = plate SDecl |+ x1 |+ x2 plateAll (SAss x1 x2) = plate SAss |+ x1 |+ x2 plateAll (SBlock x1) = plate SBlock |+ x1 plateAll (SReturn x1) = plate SReturn |+ x1 instance (Typeable to, Uniplate to) => PlateAll Exp to where plateAll (EStm x1) = plate EStm |+ x1 plateAll (EAdd x1 x2) = plate EAdd |+ x1 |+ x2 plateAll (EVar x1) = plate EVar |+ x1 plateAll (EInt x1) = plate EInt |+ x1 instance (Typeable to, Uniplate to) => PlateAll Var to where plateAll (V x1) = plate V |+ x1 instance (Typeable to, Uniplate to) => PlateAll Typ to where plateAll (T_int) = plate T_int plateAll (T_float) = plate T_float instance (Typeable to, Uniplate to) => PlateAll Company to where plateAll (C x1) = plate C |+ x1 instance (Typeable to, Uniplate to) => PlateAll Dept to where plateAll (D x1 x2 x3) = plate D |+ x1 |+ x2 |+ x3 instance (Typeable to, Uniplate to) => PlateAll Unt to where plateAll (PU x1) = plate PU |+ x1 plateAll (DU x1) = plate DU |+ x1 instance (Typeable to, Uniplate to) => PlateAll Employee to where plateAll (E x1 x2) = plate E |+ x1 |+ x2 instance (Typeable to, Uniplate to) => PlateAll Person to where plateAll (P x1 x2) = plate P |+ x1 |+ x2 instance (Typeable to, Uniplate to) => PlateAll Salary to where plateAll (S x1) = plate S |+ x1
eed45da14b14494ec43d0ee95f06144bb3a345f0c6eb51948bc0549db3487118
afronski/bferl
bferl_vm_thread.erl
-module(bferl_vm_thread). -behaviour(gen_server). -include("../include/virtual_machine_definitions.hrl"). -export([ start_link/1 ]). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3 ]). enable_flags({debug, true}, State) -> State#{ "Debug" => true }; enable_flags(debug, State) -> State#{ "Debug" => true }; enable_flags({interactive, true}, State) -> State#{ "Interactive" => true }; enable_flags(interactive, State) -> State#{ "Interactive" => true }; enable_flags({optimize, true}, State) -> State#{ "Optimize" => true }; enable_flags(optimize, State) -> State#{ "Optimize" => true }; enable_flags({jit, true}, State) -> State#{ "JIT" => true }; enable_flags(jit, State) -> State#{ "JIT" => true }; enable_flags(_, State) -> State. enable_flags(Flags) -> lists:foldl(fun enable_flags/2, #{}, Flags). continue({finished, Result}) -> {false, Result}; continue(Intermediate) -> {true, Intermediate}. finished(Result) -> gen_server:cast(bferl_tools_virtual_machine, {thread_finished, self(), Result}), Result. start_link(Context) -> gen_server:start_link(?MODULE, [ Context ], []). init([ Context ]) -> State = enable_flags(maps:get("Flags", Context)), Program = maps:get("Program", Context), Machine = bferl_vm_ir_executor:start_machine(Program), MachineWithIO = case maps:get("Tape", Context) of not_attached -> bferl_vm_ir_executor:register_console(Machine); Tape -> bferl_io:tape(Tape), bferl_vm_ir_executor:register_tape(Machine) end, NewState = State#{ "Context" => Context, "Machine" => MachineWithIO }, pretty_print_when_interactive(NewState, MachineWithIO), {ok, NewState}. handle_call(step, _From, State) -> Machine = maps:get("Machine", State), {Status, NewMachine} = case continue(bferl_vm_ir_executor:step(Machine)) of {true, Intermediate} -> pretty_print_when_interactive(State, Intermediate), {running, Intermediate}; {false, Result} -> {finished, finished(Result)} end, {reply, Status, State#{ "Machine" := NewMachine }}. handle_cast(_Message, State) -> {noreply, State}. handle_info(_Message, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. map_opcode_to_string({add, T, V}) -> io_lib:format("add(~p, ~B)", [T, V]); map_opcode_to_string({sub, T, V}) -> io_lib:format("sub(~p, ~B)", [T, V]); map_opcode_to_string({jze, T}) -> io_lib:format("jze(~B)", [T]); map_opcode_to_string({jmp, T}) -> io_lib:format("jmp(~B)", [T]); map_opcode_to_string({jnze, T}) -> io_lib:format("jnze(~B)", [T]); map_opcode_to_string({const, T, V}) -> io_lib:format("const(~p, ~B)", [T, V]); map_opcode_to_string({load, _, _}) -> "load(ir0, r0)"; map_opcode_to_string({store, _, _}) -> "store(r0, ir0)"; map_opcode_to_string({call, in}) -> "call(in)"; map_opcode_to_string({call, out}) -> "call(out)"; map_opcode_to_string({call, fork}) -> "call(fork)". get_memory_cell(CellIndex, Machine) when CellIndex >= 0, CellIndex < ?VM_MEMORY_SIZE -> array:get(CellIndex, Machine#register_based_virtual_machine.memory); get_memory_cell(_CellIndex, _Machine) -> 0. get_opcode(Index, Machine) when Index >= 1, Index =< length(Machine#register_based_virtual_machine.ir_code) -> map_opcode_to_string(lists:nth(Index, Machine#register_based_virtual_machine.ir_code)); get_opcode(_Index, _Machine) -> "". pretty_print_when_interactive(State, _Machine) -> case maps:get("Interactive", State, false) of false -> ok; true -> Context = maps:get("Context", State), {Input, Output} = case maps:get("Tape", Context, not_attached) of not_attached -> {"[No tape attached]", "[No tape attached]"}; _ -> {bferl_io:get_input_tape(), bferl_io:get_output_tape()} end, DebugModeState = maps:get("Debug", State, false), DebugMode = case DebugModeState of true -> "D"; false -> "-" end, InteractiveModeState = maps:get("Interactive", State, false), InteractiveMode = case InteractiveModeState of true -> "I"; false -> "-" end, OptModeState = maps:get("Optimize", State, false), OptMode = case OptModeState of true -> "O"; false -> "-" end, JitModeState = maps:get("JIT", State, false), JitMode = case JitModeState of true -> "J"; false -> "-" end, Machine = maps:get("Machine", State), IP = Machine#register_based_virtual_machine.ip, IC = Machine#register_based_virtual_machine.ic, ZF = Machine#register_based_virtual_machine.zf, IR0 = Machine#register_based_virtual_machine.ir0, R0 = Machine#register_based_virtual_machine.r0, MM2 = get_memory_cell(IR0 - 2, Machine), MM1 = get_memory_cell(IR0 - 1, Machine), M0 = get_memory_cell(IR0 , Machine), MP1 = get_memory_cell(IR0 + 1, Machine), MP2 = get_memory_cell(IR0 + 2, Machine), Memory = [ MM2, MM1, M0, MP1, MP2, R0], OpcodeM2 = get_opcode(IP - 2, Machine), OpcodeM1 = get_opcode(IP - 1, Machine), Opcode0 = get_opcode(IP , Machine), OpcodeP1 = get_opcode(IP + 1, Machine), OpcodeP2 = get_opcode(IP + 2, Machine), io:format("--MEMORY-FLAGS-AND-REGISTERS-------~n", []), io:format(".. ~3B ~3B (~3B) ~3B ~3B .. R0: ~3B~n", Memory), io:format(".. -2 -1 0 +1 +2 .. IR0: ~3B~n", [IR0]), io:format(".. IP: ~3B~n", [IP]), io:format(".. ZF: ~3B~n", [ZF]), io:format(".. IC: ~3B~n", [IC]), io:format("--CODE--------------------[~1s~1s][~1s~1s]-~n", [DebugMode, InteractiveMode, OptMode, JitMode]), io:format(" -2 ~s~n", [OpcodeM2]), io:format(" -1 ~s~n", [OpcodeM1]), io:format(" 0 (IP: ~3B) ==> ~s~n", [IP, Opcode0]), io:format(" +1 ~s~n", [OpcodeP1]), io:format(" +2 ~s~n", [OpcodeP2]), io:format("--TAPE-----------------------------~n", []), io:format("Input: ~s~n", [Input]), io:format("Output: ~s~n", [Output]), io:format("-----------------------------------~n", []) end.
null
https://raw.githubusercontent.com/afronski/bferl/18d3482c71cdb0e39bde090d436245a2a9531f49/src/bferl_vm_thread.erl
erlang
-module(bferl_vm_thread). -behaviour(gen_server). -include("../include/virtual_machine_definitions.hrl"). -export([ start_link/1 ]). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3 ]). enable_flags({debug, true}, State) -> State#{ "Debug" => true }; enable_flags(debug, State) -> State#{ "Debug" => true }; enable_flags({interactive, true}, State) -> State#{ "Interactive" => true }; enable_flags(interactive, State) -> State#{ "Interactive" => true }; enable_flags({optimize, true}, State) -> State#{ "Optimize" => true }; enable_flags(optimize, State) -> State#{ "Optimize" => true }; enable_flags({jit, true}, State) -> State#{ "JIT" => true }; enable_flags(jit, State) -> State#{ "JIT" => true }; enable_flags(_, State) -> State. enable_flags(Flags) -> lists:foldl(fun enable_flags/2, #{}, Flags). continue({finished, Result}) -> {false, Result}; continue(Intermediate) -> {true, Intermediate}. finished(Result) -> gen_server:cast(bferl_tools_virtual_machine, {thread_finished, self(), Result}), Result. start_link(Context) -> gen_server:start_link(?MODULE, [ Context ], []). init([ Context ]) -> State = enable_flags(maps:get("Flags", Context)), Program = maps:get("Program", Context), Machine = bferl_vm_ir_executor:start_machine(Program), MachineWithIO = case maps:get("Tape", Context) of not_attached -> bferl_vm_ir_executor:register_console(Machine); Tape -> bferl_io:tape(Tape), bferl_vm_ir_executor:register_tape(Machine) end, NewState = State#{ "Context" => Context, "Machine" => MachineWithIO }, pretty_print_when_interactive(NewState, MachineWithIO), {ok, NewState}. handle_call(step, _From, State) -> Machine = maps:get("Machine", State), {Status, NewMachine} = case continue(bferl_vm_ir_executor:step(Machine)) of {true, Intermediate} -> pretty_print_when_interactive(State, Intermediate), {running, Intermediate}; {false, Result} -> {finished, finished(Result)} end, {reply, Status, State#{ "Machine" := NewMachine }}. handle_cast(_Message, State) -> {noreply, State}. handle_info(_Message, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. map_opcode_to_string({add, T, V}) -> io_lib:format("add(~p, ~B)", [T, V]); map_opcode_to_string({sub, T, V}) -> io_lib:format("sub(~p, ~B)", [T, V]); map_opcode_to_string({jze, T}) -> io_lib:format("jze(~B)", [T]); map_opcode_to_string({jmp, T}) -> io_lib:format("jmp(~B)", [T]); map_opcode_to_string({jnze, T}) -> io_lib:format("jnze(~B)", [T]); map_opcode_to_string({const, T, V}) -> io_lib:format("const(~p, ~B)", [T, V]); map_opcode_to_string({load, _, _}) -> "load(ir0, r0)"; map_opcode_to_string({store, _, _}) -> "store(r0, ir0)"; map_opcode_to_string({call, in}) -> "call(in)"; map_opcode_to_string({call, out}) -> "call(out)"; map_opcode_to_string({call, fork}) -> "call(fork)". get_memory_cell(CellIndex, Machine) when CellIndex >= 0, CellIndex < ?VM_MEMORY_SIZE -> array:get(CellIndex, Machine#register_based_virtual_machine.memory); get_memory_cell(_CellIndex, _Machine) -> 0. get_opcode(Index, Machine) when Index >= 1, Index =< length(Machine#register_based_virtual_machine.ir_code) -> map_opcode_to_string(lists:nth(Index, Machine#register_based_virtual_machine.ir_code)); get_opcode(_Index, _Machine) -> "". pretty_print_when_interactive(State, _Machine) -> case maps:get("Interactive", State, false) of false -> ok; true -> Context = maps:get("Context", State), {Input, Output} = case maps:get("Tape", Context, not_attached) of not_attached -> {"[No tape attached]", "[No tape attached]"}; _ -> {bferl_io:get_input_tape(), bferl_io:get_output_tape()} end, DebugModeState = maps:get("Debug", State, false), DebugMode = case DebugModeState of true -> "D"; false -> "-" end, InteractiveModeState = maps:get("Interactive", State, false), InteractiveMode = case InteractiveModeState of true -> "I"; false -> "-" end, OptModeState = maps:get("Optimize", State, false), OptMode = case OptModeState of true -> "O"; false -> "-" end, JitModeState = maps:get("JIT", State, false), JitMode = case JitModeState of true -> "J"; false -> "-" end, Machine = maps:get("Machine", State), IP = Machine#register_based_virtual_machine.ip, IC = Machine#register_based_virtual_machine.ic, ZF = Machine#register_based_virtual_machine.zf, IR0 = Machine#register_based_virtual_machine.ir0, R0 = Machine#register_based_virtual_machine.r0, MM2 = get_memory_cell(IR0 - 2, Machine), MM1 = get_memory_cell(IR0 - 1, Machine), M0 = get_memory_cell(IR0 , Machine), MP1 = get_memory_cell(IR0 + 1, Machine), MP2 = get_memory_cell(IR0 + 2, Machine), Memory = [ MM2, MM1, M0, MP1, MP2, R0], OpcodeM2 = get_opcode(IP - 2, Machine), OpcodeM1 = get_opcode(IP - 1, Machine), Opcode0 = get_opcode(IP , Machine), OpcodeP1 = get_opcode(IP + 1, Machine), OpcodeP2 = get_opcode(IP + 2, Machine), io:format("--MEMORY-FLAGS-AND-REGISTERS-------~n", []), io:format(".. ~3B ~3B (~3B) ~3B ~3B .. R0: ~3B~n", Memory), io:format(".. -2 -1 0 +1 +2 .. IR0: ~3B~n", [IR0]), io:format(".. IP: ~3B~n", [IP]), io:format(".. ZF: ~3B~n", [ZF]), io:format(".. IC: ~3B~n", [IC]), io:format("--CODE--------------------[~1s~1s][~1s~1s]-~n", [DebugMode, InteractiveMode, OptMode, JitMode]), io:format(" -2 ~s~n", [OpcodeM2]), io:format(" -1 ~s~n", [OpcodeM1]), io:format(" 0 (IP: ~3B) ==> ~s~n", [IP, Opcode0]), io:format(" +1 ~s~n", [OpcodeP1]), io:format(" +2 ~s~n", [OpcodeP2]), io:format("--TAPE-----------------------------~n", []), io:format("Input: ~s~n", [Input]), io:format("Output: ~s~n", [Output]), io:format("-----------------------------------~n", []) end.
79eb793dc5c7baa0e6ba0585d568e0d311c9aa4a2d431f451f5bd16ac4561e23
paramander/mollie-api-haskell
API.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PartialTypeSignatures # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} module Mollie.API ( MollieServantAPI , MollieAPI , HalJSON , chargebackClient , customerClient , mandateClient , methodClient , paymentClient , refundClient , subscriptionClient , createEnv , runMollie , module Mollie.API.Types ) where import Data.Proxy (Proxy (..)) import GHC.Generics (Generic) import Mollie.API.Chargebacks (ChargebackAPI) import Mollie.API.Customers (CustomerAPI) import Mollie.API.Internal import Mollie.API.Mandates (MandateAPI) import Mollie.API.Methods (MethodAPI) import Mollie.API.Payments (PaymentAPI) import Mollie.API.Refunds (RefundAPI) import Mollie.API.Subscriptions (SubscriptionAPI) import Mollie.API.Types import Servant.API import Servant.API.Generic import Servant.Client import Servant.Client.Generic -- import qualified Paths_mollie_api_haskell as Self | All v2 endpoints of API . All v2 endpoints of Mollie API. -} data MollieAPI route = MollieAPI { customerAPI :: route :- ToServantApi CustomerAPI , chargebackAPI :: route :- ToServantApi ChargebackAPI , methodAPI :: route :- ToServantApi MethodAPI , mandateAPI :: route :- ToServantApi MandateAPI , paymentAPI :: route :- ToServantApi PaymentAPI , refundAPI :: route :- ToServantApi RefundAPI , subscriptionAPI :: route :- ToServantApi SubscriptionAPI } deriving Generic | The fully combined API definition of Haskell . The fully combined Mollie API definition of Haskell. -} type MollieServantAPI = "v2" :> ToServantApi MollieAPI servantApi :: Proxy MollieServantAPI servantApi = Proxy | Record that holds the endpoints for the Chargeback API . Usage : @ import . API import . API.Chargebacks env < - createEnv " test_mollieapikeyexample " let chargebacksResult = runMollie env ( getChargebacks chargebackClient ) @ Record that holds the endpoints for the Chargeback API. Usage: @ import Mollie.API import Mollie.API.Chargebacks env <- createEnv "test_mollieapikeyexample" let chargebacksResult = runMollie env (getChargebacks chargebackClient) @ -} chargebackClient :: ChargebackAPI (AsClientT ClientM) chargebackClient = fromServant $ chargebackAPI mollieClient | Record that holds the endpoints for the Customer API . Usage : @ import . API import . API.Customers env < - createEnv " test_mollieapikeyexample " let customersResult = runMollie env ( getCustomers customerClient ) @ Record that holds the endpoints for the Customer API. Usage: @ import Mollie.API import Mollie.API.Customers env <- createEnv "test_mollieapikeyexample" let customersResult = runMollie env (getCustomers customerClient) @ -} customerClient :: CustomerAPI (AsClientT ClientM) customerClient = fromServant $ customerAPI mollieClient | Record that holds the endpoints for the Method API . Usage : @ import . API import . API.Methods env < - createEnv " test_mollieapikeyexample " let = runMollie env ( getMethods methodClient ) @ Record that holds the endpoints for the Method API. Usage: @ import Mollie.API import Mollie.API.Methods env <- createEnv "test_mollieapikeyexample" let methodsResult = runMollie env (getMethods methodClient) @ -} methodClient :: MethodAPI (AsClientT ClientM) methodClient = fromServant $ methodAPI mollieClient | Record that holds the endpoints for the Mandate API . Usage : @ import . API import . API.Mandates env < - createEnv " test_mollieapikeyexample " let = ( getCustomerMandates mandateClient ) " cst_eaaEuAnqW " ) @ Record that holds the endpoints for the Mandate API. Usage: @ import Mollie.API import Mollie.API.Mandates env <- createEnv "test_mollieapikeyexample" let mandatesResult = runMollie env ((getCustomerMandates mandateClient) "cst_eaaEuAnqW") @ -} mandateClient :: MandateAPI (AsClientT ClientM) mandateClient = fromServant $ mandateAPI mollieClient | Record that holds the endpoints for the Payments API . Usage : @ import . API import . env < - createEnv " test_mollieapikeyexample " let = ( ) @ Record that holds the endpoints for the Payments API. Usage: @ import Mollie.API import Mollie.API.Payments env <- createEnv "test_mollieapikeyexample" let paymentsResult = runMollie env (getPayments paymentClient) @ -} paymentClient :: PaymentAPI (AsClientT ClientM) paymentClient = fromServant $ paymentAPI mollieClient | Record that holds the endpoints for the Refunds API . Usage : @ import . API import . API.Refunds env < - createEnv " test_mollieapikeyexample " let refundsResult = getRefunds refundClient ) @ Record that holds the endpoints for the Refunds API. Usage: @ import Mollie.API import Mollie.API.Refunds env <- createEnv "test_mollieapikeyexample" let refundsResult = runMollie env (getRefunds refundClient) @ -} refundClient :: RefundAPI (AsClientT ClientM) refundClient = fromServant $ refundAPI mollieClient | Record that holds the endpoints for the Subscriptions API . Usage : @ import . API import . env < - createEnv " test_mollieapikeyexample " let subscriptionsResult = ( getCustomerSubscriptions refundClient ) " cst_eaaEuAnqW " ) @ Record that holds the endpoints for the Subscriptions API. Usage: @ import Mollie.API import Mollie.API.Subscriptions env <- createEnv "test_mollieapikeyexample" let subscriptionsResult = runMollie env ((getCustomerSubscriptions refundClient) "cst_eaaEuAnqW") @ -} subscriptionClient :: SubscriptionAPI (AsClientT ClientM) subscriptionClient = fromServant $ subscriptionAPI mollieClient mollieClient :: MollieAPI (AsClientT ClientM) mollieClient = fromServant $ client servantApi | Execute an API call to the API . Uses Servant under the hood . Execute an API call to the Mollie API. Uses Servant under the hood. -} runMollie :: ClientEnv -> ClientM a -> IO (Either ResponseError a) runMollie env apiFunction = do res <- runClientM apiFunction env return $ mapLeft handleError res where mapLeft :: (a -> c) -> Either a b -> Either c b mapLeft f (Left x) = Left (f x) mapLeft _ (Right x) = Right x
null
https://raw.githubusercontent.com/paramander/mollie-api-haskell/4bd8386a7682abd5007b291fe72649e4cf41a7b0/src/Mollie/API.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE RankNTypes # # LANGUAGE TypeOperators # import qualified Paths_mollie_api_haskell as Self
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PartialTypeSignatures # # LANGUAGE TypeFamilies # module Mollie.API ( MollieServantAPI , MollieAPI , HalJSON , chargebackClient , customerClient , mandateClient , methodClient , paymentClient , refundClient , subscriptionClient , createEnv , runMollie , module Mollie.API.Types ) where import Data.Proxy (Proxy (..)) import GHC.Generics (Generic) import Mollie.API.Chargebacks (ChargebackAPI) import Mollie.API.Customers (CustomerAPI) import Mollie.API.Internal import Mollie.API.Mandates (MandateAPI) import Mollie.API.Methods (MethodAPI) import Mollie.API.Payments (PaymentAPI) import Mollie.API.Refunds (RefundAPI) import Mollie.API.Subscriptions (SubscriptionAPI) import Mollie.API.Types import Servant.API import Servant.API.Generic import Servant.Client import Servant.Client.Generic | All v2 endpoints of API . All v2 endpoints of Mollie API. -} data MollieAPI route = MollieAPI { customerAPI :: route :- ToServantApi CustomerAPI , chargebackAPI :: route :- ToServantApi ChargebackAPI , methodAPI :: route :- ToServantApi MethodAPI , mandateAPI :: route :- ToServantApi MandateAPI , paymentAPI :: route :- ToServantApi PaymentAPI , refundAPI :: route :- ToServantApi RefundAPI , subscriptionAPI :: route :- ToServantApi SubscriptionAPI } deriving Generic | The fully combined API definition of Haskell . The fully combined Mollie API definition of Haskell. -} type MollieServantAPI = "v2" :> ToServantApi MollieAPI servantApi :: Proxy MollieServantAPI servantApi = Proxy | Record that holds the endpoints for the Chargeback API . Usage : @ import . API import . API.Chargebacks env < - createEnv " test_mollieapikeyexample " let chargebacksResult = runMollie env ( getChargebacks chargebackClient ) @ Record that holds the endpoints for the Chargeback API. Usage: @ import Mollie.API import Mollie.API.Chargebacks env <- createEnv "test_mollieapikeyexample" let chargebacksResult = runMollie env (getChargebacks chargebackClient) @ -} chargebackClient :: ChargebackAPI (AsClientT ClientM) chargebackClient = fromServant $ chargebackAPI mollieClient | Record that holds the endpoints for the Customer API . Usage : @ import . API import . API.Customers env < - createEnv " test_mollieapikeyexample " let customersResult = runMollie env ( getCustomers customerClient ) @ Record that holds the endpoints for the Customer API. Usage: @ import Mollie.API import Mollie.API.Customers env <- createEnv "test_mollieapikeyexample" let customersResult = runMollie env (getCustomers customerClient) @ -} customerClient :: CustomerAPI (AsClientT ClientM) customerClient = fromServant $ customerAPI mollieClient | Record that holds the endpoints for the Method API . Usage : @ import . API import . API.Methods env < - createEnv " test_mollieapikeyexample " let = runMollie env ( getMethods methodClient ) @ Record that holds the endpoints for the Method API. Usage: @ import Mollie.API import Mollie.API.Methods env <- createEnv "test_mollieapikeyexample" let methodsResult = runMollie env (getMethods methodClient) @ -} methodClient :: MethodAPI (AsClientT ClientM) methodClient = fromServant $ methodAPI mollieClient | Record that holds the endpoints for the Mandate API . Usage : @ import . API import . API.Mandates env < - createEnv " test_mollieapikeyexample " let = ( getCustomerMandates mandateClient ) " cst_eaaEuAnqW " ) @ Record that holds the endpoints for the Mandate API. Usage: @ import Mollie.API import Mollie.API.Mandates env <- createEnv "test_mollieapikeyexample" let mandatesResult = runMollie env ((getCustomerMandates mandateClient) "cst_eaaEuAnqW") @ -} mandateClient :: MandateAPI (AsClientT ClientM) mandateClient = fromServant $ mandateAPI mollieClient | Record that holds the endpoints for the Payments API . Usage : @ import . API import . env < - createEnv " test_mollieapikeyexample " let = ( ) @ Record that holds the endpoints for the Payments API. Usage: @ import Mollie.API import Mollie.API.Payments env <- createEnv "test_mollieapikeyexample" let paymentsResult = runMollie env (getPayments paymentClient) @ -} paymentClient :: PaymentAPI (AsClientT ClientM) paymentClient = fromServant $ paymentAPI mollieClient | Record that holds the endpoints for the Refunds API . Usage : @ import . API import . API.Refunds env < - createEnv " test_mollieapikeyexample " let refundsResult = getRefunds refundClient ) @ Record that holds the endpoints for the Refunds API. Usage: @ import Mollie.API import Mollie.API.Refunds env <- createEnv "test_mollieapikeyexample" let refundsResult = runMollie env (getRefunds refundClient) @ -} refundClient :: RefundAPI (AsClientT ClientM) refundClient = fromServant $ refundAPI mollieClient | Record that holds the endpoints for the Subscriptions API . Usage : @ import . API import . env < - createEnv " test_mollieapikeyexample " let subscriptionsResult = ( getCustomerSubscriptions refundClient ) " cst_eaaEuAnqW " ) @ Record that holds the endpoints for the Subscriptions API. Usage: @ import Mollie.API import Mollie.API.Subscriptions env <- createEnv "test_mollieapikeyexample" let subscriptionsResult = runMollie env ((getCustomerSubscriptions refundClient) "cst_eaaEuAnqW") @ -} subscriptionClient :: SubscriptionAPI (AsClientT ClientM) subscriptionClient = fromServant $ subscriptionAPI mollieClient mollieClient :: MollieAPI (AsClientT ClientM) mollieClient = fromServant $ client servantApi | Execute an API call to the API . Uses Servant under the hood . Execute an API call to the Mollie API. Uses Servant under the hood. -} runMollie :: ClientEnv -> ClientM a -> IO (Either ResponseError a) runMollie env apiFunction = do res <- runClientM apiFunction env return $ mapLeft handleError res where mapLeft :: (a -> c) -> Either a b -> Either c b mapLeft f (Left x) = Left (f x) mapLeft _ (Right x) = Right x
5e79f947ecfac0b20b5898e1fc4c490a20e0741844abee376e988e410f50fadd
zk/nsfw
mongo_test.clj
(ns nsfw.mongo-test (:use [nsfw.mongo :as mon] :reload) (:use [clojure.test])) (deftest test-parse-username (is (= "foo" (parse-username (java.net.URI. ":")))) (is (= nil (parse-username (java.net.URI. ""))))) (deftest test-parse-password (is (= "bar" (parse-password (java.net.URI. ":")))) (is (= nil (parse-password (java.net.URI. ""))))) (deftest test-parse-mongo-url (is (= {:username "user" :password "pass" :host "host" :port 123 :db "db"} (parse-mongo-url "mongodb:pass@host:123/db"))))
null
https://raw.githubusercontent.com/zk/nsfw/ea07ba20cc5453b34a56b34c9d8738bf9bf8e92f/test/clj/nsfw/mongo_test.clj
clojure
(ns nsfw.mongo-test (:use [nsfw.mongo :as mon] :reload) (:use [clojure.test])) (deftest test-parse-username (is (= "foo" (parse-username (java.net.URI. ":")))) (is (= nil (parse-username (java.net.URI. ""))))) (deftest test-parse-password (is (= "bar" (parse-password (java.net.URI. ":")))) (is (= nil (parse-password (java.net.URI. ""))))) (deftest test-parse-mongo-url (is (= {:username "user" :password "pass" :host "host" :port 123 :db "db"} (parse-mongo-url "mongodb:pass@host:123/db"))))
7049cc1969b04f4138d77ab1205916cce4eaadc2934d0af995fe601679aadd7e
daveliepmann/vdquil
figure8.clj
, Chapter 4 ( Time Series ) , figure 8 : ;; Continuously drawn time series using vertices Converted from Processing to Quil as an exercise by (ns vdquil.chapter4.figure8 (:use [quil.core] [vdquil.util] [vdquil.chapter4.ch4data])) (def current-column (atom 0)) (defn get-current-column "Key handling function `switch-data-set` increments and decrements `current-column`. Access to the atom goes through this function because putting the modulus arithmetic in the keyhandler is unavoidably messy around the edges." [] (inc (mod @current-column (- (count (first milk-tea-coffee-data)) 1)))) (def WIDTH 720) (def HEIGHT 405) (def plotx1 120) (def plotx2 (- WIDTH 80)) (def ploty1 60) (def ploty2 (- HEIGHT 70)) (def year-min (apply min (map first (rest milk-tea-coffee-data)))) (def year-max (apply max (map first (rest milk-tea-coffee-data)))) (def year-interval 10) (def volume-interval 5) (def data-first 0) (def data-min (apply min (mapcat rest (rest milk-tea-coffee-data)))) (def data-max (* volume-interval (ceil (/ (apply max (mapcat rest (rest milk-tea-coffee-data))) volume-interval)))) (defn setup [] (smooth)) (defn draw-plot-area "Show the plot area as a white box"[] (background 224) (fill 255) (no-stroke) (rect-mode :corners) (rect plotx1 ploty1 plotx2 ploty2)) (defn draw-title [] (fill 0) (text-size 20) (text-align :left :baseline) (text-font (create-font "Sans-Serif" 20)) (text (nth (first milk-tea-coffee-data) (get-current-column)) plotx1 (- ploty1 10))) (defn annotate-x-axis [] ;; Draw year labels (text-size 10) (text-align :center :top) (stroke-weight 1) ;; Use thin, gray lines to draw the grid (stroke 224) (doseq [year (range year-min year-max year-interval)] (let [x (map-range year year-min year-max plotx1 plotx2)] (text (str year) x (+ 10 ploty2)) (line x ploty1 x ploty2)))) (defn annotate-y-axis [] ;; Draw volume labels ;; Since we're not drawing the minor ticks, we would ideally increase volume - interval to 10 and remove the modulo-10 check . We keep it in to show how to produce figure 5 . (text-align :right :center) (doseq [volume (range data-first (+ 1 data-max) volume-interval)] (let [y (map-range volume data-first data-max ploty2 ploty1)] ;; Commented out--the minor tick marks are too visually distracting ( stroke 128 ) ( line ( - plotx1 2 ) y ) ; ; Draw minor tick (when (= 0 (mod volume 10)) ;; Draw major tick mark (stroke 0) (line plotx1 y (- plotx1 4) y) (text-align :right :center) ;; Center vertically ;; Align the "0" label by the bottom: (when (= volume data-first) (text-align :right :bottom)) (text (str (ceil volume)) (- plotx1 10) y))))) (defn draw-axis-labels [] (text-size 13) (text-leading 15) (text-align :center :center) (text "Gallons\nconsumer\nper capita" 50 (/ (+ ploty1 ploty2) 2)) (text (str (first (first milk-tea-coffee-data))) (/ (+ plotx1 plotx2) 2) (- (height) 25))) (defn draw-data-point [row] (stroke-weight 5) (stroke (apply color (hex-to-rgb "#5679C1"))) (let [[year milk tea coffee] row] (vertex (map-range year year-min year-max plotx1 plotx2) (map-range (nth row (get-current-column)) data-min data-max ploty2 ploty1)))) (defn draw [] (draw-plot-area) (draw-title) (annotate-x-axis) (annotate-y-axis) (draw-axis-labels) (no-fill) (begin-shape) (doseq [row (rest milk-tea-coffee-data)] (draw-data-point row)) (end-shape)) (defn switch-data-set [] (condp = (raw-key) \[ (swap! current-column dec) \] (swap! current-column inc) nil)) (defsketch mtc :title "Milk, Tea, Coffee" :setup setup :draw draw :size [WIDTH HEIGHT] :key-pressed switch-data-set)
null
https://raw.githubusercontent.com/daveliepmann/vdquil/f40788ff7634870a9a5f1dc4ca3df8543beaf00b/src/vdquil/chapter4/figure8.clj
clojure
Continuously drawn time series using vertices Draw year labels Use thin, gray lines to draw the grid Draw volume labels Since we're not drawing the minor ticks, we would ideally Commented out--the minor tick marks are too visually distracting ; Draw minor tick Draw major tick mark Center vertically Align the "0" label by the bottom:
, Chapter 4 ( Time Series ) , figure 8 : Converted from Processing to Quil as an exercise by (ns vdquil.chapter4.figure8 (:use [quil.core] [vdquil.util] [vdquil.chapter4.ch4data])) (def current-column (atom 0)) (defn get-current-column "Key handling function `switch-data-set` increments and decrements `current-column`. Access to the atom goes through this function because putting the modulus arithmetic in the keyhandler is unavoidably messy around the edges." [] (inc (mod @current-column (- (count (first milk-tea-coffee-data)) 1)))) (def WIDTH 720) (def HEIGHT 405) (def plotx1 120) (def plotx2 (- WIDTH 80)) (def ploty1 60) (def ploty2 (- HEIGHT 70)) (def year-min (apply min (map first (rest milk-tea-coffee-data)))) (def year-max (apply max (map first (rest milk-tea-coffee-data)))) (def year-interval 10) (def volume-interval 5) (def data-first 0) (def data-min (apply min (mapcat rest (rest milk-tea-coffee-data)))) (def data-max (* volume-interval (ceil (/ (apply max (mapcat rest (rest milk-tea-coffee-data))) volume-interval)))) (defn setup [] (smooth)) (defn draw-plot-area "Show the plot area as a white box"[] (background 224) (fill 255) (no-stroke) (rect-mode :corners) (rect plotx1 ploty1 plotx2 ploty2)) (defn draw-title [] (fill 0) (text-size 20) (text-align :left :baseline) (text-font (create-font "Sans-Serif" 20)) (text (nth (first milk-tea-coffee-data) (get-current-column)) plotx1 (- ploty1 10))) (defn annotate-x-axis [] (text-size 10) (text-align :center :top) (stroke-weight 1) (stroke 224) (doseq [year (range year-min year-max year-interval)] (let [x (map-range year year-min year-max plotx1 plotx2)] (text (str year) x (+ 10 ploty2)) (line x ploty1 x ploty2)))) (defn annotate-y-axis [] increase volume - interval to 10 and remove the modulo-10 check . We keep it in to show how to produce figure 5 . (text-align :right :center) (doseq [volume (range data-first (+ 1 data-max) volume-interval)] (let [y (map-range volume data-first data-max ploty2 ploty1)] ( stroke 128 ) (stroke 0) (line plotx1 y (- plotx1 4) y) (when (= volume data-first) (text-align :right :bottom)) (text (str (ceil volume)) (- plotx1 10) y))))) (defn draw-axis-labels [] (text-size 13) (text-leading 15) (text-align :center :center) (text "Gallons\nconsumer\nper capita" 50 (/ (+ ploty1 ploty2) 2)) (text (str (first (first milk-tea-coffee-data))) (/ (+ plotx1 plotx2) 2) (- (height) 25))) (defn draw-data-point [row] (stroke-weight 5) (stroke (apply color (hex-to-rgb "#5679C1"))) (let [[year milk tea coffee] row] (vertex (map-range year year-min year-max plotx1 plotx2) (map-range (nth row (get-current-column)) data-min data-max ploty2 ploty1)))) (defn draw [] (draw-plot-area) (draw-title) (annotate-x-axis) (annotate-y-axis) (draw-axis-labels) (no-fill) (begin-shape) (doseq [row (rest milk-tea-coffee-data)] (draw-data-point row)) (end-shape)) (defn switch-data-set [] (condp = (raw-key) \[ (swap! current-column dec) \] (swap! current-column inc) nil)) (defsketch mtc :title "Milk, Tea, Coffee" :setup setup :draw draw :size [WIDTH HEIGHT] :key-pressed switch-data-set)
282171d10f0a81cc833d7e9abb69f4287be6ad3c7fad2a4025bd5272ce1989fb
gregtatcam/imaplet-lwt
maildir_read.ml
open Lwt open Re open Irmin_unix open Sexplib open Sexplib.Conv open Imaplet open Commands exception InvalidCommand let re = Re_posix.compile_pat "^([0-9]+) (.+)$" let re_read = Re_posix.compile_pat "^read ([0-9]+|\\*)$" let re_fetch = Re_posix.compile_pat "^([^ ]+) fetch 1:([^ ]+)" let re_login = Re_posix.compile_pat "^([^ ]+) login ([^ ]+)" let re_select = Re_posix.compile_pat "^([^ ]+) select ([^ ]+)" mutest1000r:{SHA256}iBNo0571Fbtry25GuXs230leItrk6KxO16fVd73o057OKP704=::::/var / mail / accounts / mutest1000r / repo : : af : ef : cff : sf : hf : mf mutest1000r:{SHA256}iBNo0571Fbtry25GuXs230leItrk6KxO16fVd73o057OKP704=::::/var/mail/accounts/mutest1000r/repo:maildir:af:ef:cff:sf:hf:mf *) let login user = let users_db = "/usr/local/share/imaplet/users" in Lwt_io.with_file ~flags:[Unix.O_NONBLOCK] ~mode:Lwt_io.Input users_db (fun ic -> let rec read () = Lwt_io.read_line_opt ic >>= function | Some line -> begin let re = String.concat "" ["^"; user; ":.+:([^:]+):(gitl|irmin|maildir):a[tf]:e[tf]:c([tf][tf][-0-9]?):sf:hf:mf$"] in try let subs = Re.exec (Re_posix.compile_pat re) line in let inflate = try match String.get (Re.get subs 3) 2 with | '-' -> None | c -> Some (int_of_char c - 48) with Invalid_argument c -> None in return (Some (Re.get subs 1, Re.get subs 2, inflate)) with Not_found -> read() end | None -> return None in read () ) let get_tag re str = let subs = Re.exec re str in (subs,Re.get subs 1) let imap str = if Re.execp re_fetch str then ( let subs,tag = get_tag re_fetch str in return (`Fetch (tag,Re.get subs 2)) ) else if Re.execp re_login str then ( let subs,tag = get_tag re_login str in login (Re.get subs 2) >>= function | Some (repo,store,inflate) -> return (`Login (tag,Re.get subs 2,repo,store,inflate)) | None -> return (`Error tag) ) else if Re.execp re_select str then ( let subs,tag = get_tag re_select str in return (`Select (tag,Re.get subs 2)) ) else raise InvalidCommand let opt_val = function | None -> raise InvalidCommand | Some v -> v let rec args i port = if i >= Array.length Sys.argv then port else match Sys.argv.(i) with | "-port" -> args (i+2) (Some (int_of_string Sys.argv.(i+1))) | _ -> raise InvalidCommand let commands f = try let port = args 1 None in if port = None then raise InvalidCommand; f (opt_val port) with _ -> Printf.printf "usage: maildir_read -port [port number]\n%!" let try_close cio = catch (fun () -> Lwt_io.close cio) (function _ -> return ()) let try_close_sock sock = catch (fun () -> Lwt_unix.close sock) (function _ -> return ()) let init_socket ?(stype=Unix.SOCK_STREAM) addr port = let sockaddr = Unix.ADDR_INET (Unix.inet_addr_of_string addr, port) in let socket = Lwt_unix.socket Unix.PF_INET stype 0 in Lwt_unix.setsockopt socket Unix.SO_REUSEADDR true; Lwt_unix.set_blocking socket false; Lwt_unix.bind socket sockaddr; return socket let create_srv_socket addr port = init_socket addr port >>= fun socket -> Lwt_unix.listen socket 10; return socket let accept_cmn sock = Lwt_unix.accept sock >>= fun (sock_c, addr) -> let ic = Lwt_io.of_fd ~close:(fun()->return()) ~mode:Lwt_io.input sock_c in let oc = Lwt_io.of_fd ~close:(fun()->return()) ~mode:Lwt_io.output sock_c in return (sock_c,(ic,oc)) let server addr port f = create_srv_socket addr port >>= fun sock -> let rec connect f sock = accept_cmn sock >>= fun (sock_c,(netr,netw)) -> async ( fun () -> catch( fun () -> f netr netw >>= fun () -> try_close netr >>= fun () -> try_close netw >>= fun () -> try_close_sock sock_c ) (fun ex -> try_close netr >>= fun () -> try_close netw >>= fun () -> try_close_sock sock_c >>= fun () -> Printf.printf "exception %s\n%!" (Printexc.to_string ex); return () ) ); connect f sock in connect f sock let readt = ref 0. let writet = ref 0. let comprt = ref 0. let timeit acc t = let t1 = Unix.gettimeofday() in acc := !acc +. (t1 -. t); t1 let sp = " " module type Maildir_intf = sig type t val create : user:string -> repo:string -> mailbox:string -> inflate:int option -> t Lwt.t val read_index: t -> num:string -> (int * string) list Lwt.t val read_message: t -> id:string -> string Lwt.t end module MaildirFile : Maildir_intf = struct type t = {user:string; repo:string; mailbox:string; inflate:int option} let get_dir t = if String.lowercase t.mailbox = "inbox" then t.repo else Filename.concat t.repo ("." ^ t.mailbox) let create ~user ~repo ~mailbox ~inflate = return {user;repo;mailbox;inflate} let read_index t ~num = let file = Filename.concat (get_dir t) "imaplet.uidlst" in Lwt_io.with_file ~flags:[Unix.O_NONBLOCK] ~mode:Lwt_io.Input file (fun ic -> let rec read uids = if num = "*" || (int_of_string num) > (List.length uids) then ( Lwt_io.read_line_opt ic >>= function | Some l -> let subs = Re.exec re l in let uid = int_of_string (Re.get subs 1) in let file = Re.get subs 2 in read ((uid,file) :: uids) | None -> return (List.rev uids) ) else return (List.rev uids) in read [] ) let read_message t ~id = let file = Filename.concat (Filename.concat (get_dir t) "cur") id in Lwt_io.with_file ~flags:[Unix.O_NONBLOCK] ~mode:Lwt_io.Input file (fun ic -> Lwt_io.read ic ) end module MaildirGitl : Maildir_intf = struct type t = {user:string; repo:string; mailbox:string; store:Gitl.t;inflate:int option} let create_store repo inflate = Gitl.create ~repo ?compress:inflate () let create ~user ~repo ~mailbox ~inflate = create_store repo inflate >>= fun store -> return {user;repo;mailbox;store;inflate} let read_index t ~num = catch(fun() -> let mailbox = if (String.lowercase t.mailbox = "inbox") then "INBOX" else t.mailbox in let key = ["INBOX";".index"] in Gitl.read_exn t.store key >>= fun index_sexp_str -> return (list_of_sexp (fun i -> change to same as let (file,uid) = pair_of_sexp Sexp.to_string (fun b -> int_of_string (Sexp.to_string b)) i in (uid,file) ) (Sexp.of_string index_sexp_str)) )(fun ex -> Printf.printf "exception:%s\n%!" (Printexc.to_string ex);return[]) let read_message t ~id = let key = ["INBOX";id] in Gitl.read_exn t.store key end module MaildirIrmin : Maildir_intf = struct module Store = Irmin_unix.Git.FS.KV(Irmin.Contents.String) type t = {user:string; repo:string; mailbox:string; store:Store.t;inflate:int option} let create_store repo = let _config = Irmin_git.config ~bare:true repo in Store.Repo.v _config >>= fun repo -> Store.master repo let create ~user ~repo ~mailbox ~inflate = create_store repo >>= fun store -> return {user;repo;mailbox;store;inflate} let read_index t ~num = catch(fun() -> let mailbox = if (String.lowercase t.mailbox = "inbox") then "INBOX" else t.mailbox in let key = ["imaplet"; t.user; "mailboxes"; mailbox; "index"] in Store.get t.store key >>= fun index_sexp_str -> return (list_of_sexp (fun i -> change to same as let (file,uid) = pair_of_sexp Sexp.to_string (fun b -> int_of_string (Sexp.to_string b)) i in (uid,file) ) (Sexp.of_string index_sexp_str)) )(fun ex -> Printf.printf "exception:%s\n%!" (Printexc.to_string ex);return[]) let read_message t ~id = let key = ["imaplet"; t.user; "storage";id] in Store.get t.store key end module type MaildirReader_intf = sig val read_files : user:string -> repo:string -> mailbox:string -> writer:Lwt_io.output_channel -> num:string -> inflate:int option -> unit Lwt.t end module MakeMaildirReader(M:Maildir_intf) : MaildirReader_intf = struct let write_messages d strm w uncompress = let rec _write d uid = Lwt_stream.get strm >>= function | Some message -> let del = (Unix.gettimeofday() -. d) in if uid = 1 then Printf.printf "initial write delay %.04f\n" del; Printf.printf "writing data %d, delay %.04f\r%!" uid del; let t=Unix.gettimeofday() in let message = if uncompress <> None then (Imap_crypto.do_uncompress message) else message in let l = ["*"; sp;string_of_int uid; sp; "FETCH"; sp; "("; "BODY[]"; sp; "{";string_of_int (String.length message); "}";"\r\n";message;")";"\r\n"] in let t = timeit comprt t in Lwt_list.iter_s (Lwt_io.write w) l >>= fun () -> let _ = timeit writet t in _write (Unix.gettimeofday()) (uid+1) | None -> return () in _write d 1 let read_files ~user ~repo ~mailbox ~writer ~num ~inflate = let (strm,push_strm) = Lwt_stream.create () in M.create ~user ~repo ~mailbox ~inflate >>= fun maildir -> M.read_index maildir ~num >>= fun uids -> let t = Unix.gettimeofday() in Lwt_list.iter_p (fun f -> f()) [ ( (fun () -> Lwt_list.iter_s (fun (_,file) -> let t = Unix.gettimeofday () in M.read_message maildir ~id:file >>= fun message -> let _ = timeit readt t in push_strm (Some message); Lwt_main.yield () ) uids >>= fun () -> push_strm None; return () ) ); ( (fun () -> write_messages t strm writer inflate ) ) ] end let () = commands (fun port -> Lwt_main.run ( server "0.0.0.0" port (fun r w -> Lwt_io.write w "CAPABILITY\r\n" >>= fun () -> let rec loop ?(user="") ?(repo="") ?(store="") ?(mailbox="") ?inflate () = Lwt_io.read_line_opt r >>= function | Some l -> begin imap l >>= function | `Fetch (tag,num) -> let open Gitl in begin try readt := 0.; writet := 0.; comprt := 0.; gitreadt := 0.; gitcomprt := 0.; let t = Unix.gettimeofday () in begin if store = "maildir" then ( let module MaildirReader = MakeMaildirReader(MaildirFile) in MaildirReader.read_files ~user ~repo ~mailbox ~writer:w ~num ~inflate ) else if store = "gitl" then ( let module MaildirReader = MakeMaildirReader(MaildirGitl) in MaildirReader.read_files ~user ~repo ~mailbox ~writer:w ~num ~inflate ) else ( let module MaildirReader = MakeMaildirReader(MaildirIrmin) in MaildirReader.read_files ~user ~repo ~mailbox ~writer:w ~num ~inflate ) end >>= fun () -> Lwt_io.write w (tag ^ " ok\r\n") >>= fun () -> Printf.printf "total read: %.04f, write %.04f, compress %.04f, time %.04f\n%!" !readt !writet !comprt (Unix.gettimeofday() -. t); Printf.printf "\tgit read: %.04f, compress %.04f\n%!" !gitreadt !gitcomprt; loop () with Not_found -> return () end | `Login (tag,user,repo,store,inflate) -> Lwt_io.write w (tag ^ " ok\r\n") >>= fun () -> loop ~user ~repo ~store ?inflate () | `Select (tag,mailbox) -> Lwt_io.write w (tag ^ " ok\r\n") >>= fun () -> loop ~user ~repo ~store ~mailbox ?inflate () | `Error tag -> Lwt_io.write w (tag ^ " bad\r\n") >>= fun () -> loop () end | None -> return () in loop () ) ) )
null
https://raw.githubusercontent.com/gregtatcam/imaplet-lwt/d7b51253e79cffa97e98ab899ed833cd7cb44bb6/test/maildir_read.ml
ocaml
open Lwt open Re open Irmin_unix open Sexplib open Sexplib.Conv open Imaplet open Commands exception InvalidCommand let re = Re_posix.compile_pat "^([0-9]+) (.+)$" let re_read = Re_posix.compile_pat "^read ([0-9]+|\\*)$" let re_fetch = Re_posix.compile_pat "^([^ ]+) fetch 1:([^ ]+)" let re_login = Re_posix.compile_pat "^([^ ]+) login ([^ ]+)" let re_select = Re_posix.compile_pat "^([^ ]+) select ([^ ]+)" mutest1000r:{SHA256}iBNo0571Fbtry25GuXs230leItrk6KxO16fVd73o057OKP704=::::/var / mail / accounts / mutest1000r / repo : : af : ef : cff : sf : hf : mf mutest1000r:{SHA256}iBNo0571Fbtry25GuXs230leItrk6KxO16fVd73o057OKP704=::::/var/mail/accounts/mutest1000r/repo:maildir:af:ef:cff:sf:hf:mf *) let login user = let users_db = "/usr/local/share/imaplet/users" in Lwt_io.with_file ~flags:[Unix.O_NONBLOCK] ~mode:Lwt_io.Input users_db (fun ic -> let rec read () = Lwt_io.read_line_opt ic >>= function | Some line -> begin let re = String.concat "" ["^"; user; ":.+:([^:]+):(gitl|irmin|maildir):a[tf]:e[tf]:c([tf][tf][-0-9]?):sf:hf:mf$"] in try let subs = Re.exec (Re_posix.compile_pat re) line in let inflate = try match String.get (Re.get subs 3) 2 with | '-' -> None | c -> Some (int_of_char c - 48) with Invalid_argument c -> None in return (Some (Re.get subs 1, Re.get subs 2, inflate)) with Not_found -> read() end | None -> return None in read () ) let get_tag re str = let subs = Re.exec re str in (subs,Re.get subs 1) let imap str = if Re.execp re_fetch str then ( let subs,tag = get_tag re_fetch str in return (`Fetch (tag,Re.get subs 2)) ) else if Re.execp re_login str then ( let subs,tag = get_tag re_login str in login (Re.get subs 2) >>= function | Some (repo,store,inflate) -> return (`Login (tag,Re.get subs 2,repo,store,inflate)) | None -> return (`Error tag) ) else if Re.execp re_select str then ( let subs,tag = get_tag re_select str in return (`Select (tag,Re.get subs 2)) ) else raise InvalidCommand let opt_val = function | None -> raise InvalidCommand | Some v -> v let rec args i port = if i >= Array.length Sys.argv then port else match Sys.argv.(i) with | "-port" -> args (i+2) (Some (int_of_string Sys.argv.(i+1))) | _ -> raise InvalidCommand let commands f = try let port = args 1 None in if port = None then raise InvalidCommand; f (opt_val port) with _ -> Printf.printf "usage: maildir_read -port [port number]\n%!" let try_close cio = catch (fun () -> Lwt_io.close cio) (function _ -> return ()) let try_close_sock sock = catch (fun () -> Lwt_unix.close sock) (function _ -> return ()) let init_socket ?(stype=Unix.SOCK_STREAM) addr port = let sockaddr = Unix.ADDR_INET (Unix.inet_addr_of_string addr, port) in let socket = Lwt_unix.socket Unix.PF_INET stype 0 in Lwt_unix.setsockopt socket Unix.SO_REUSEADDR true; Lwt_unix.set_blocking socket false; Lwt_unix.bind socket sockaddr; return socket let create_srv_socket addr port = init_socket addr port >>= fun socket -> Lwt_unix.listen socket 10; return socket let accept_cmn sock = Lwt_unix.accept sock >>= fun (sock_c, addr) -> let ic = Lwt_io.of_fd ~close:(fun()->return()) ~mode:Lwt_io.input sock_c in let oc = Lwt_io.of_fd ~close:(fun()->return()) ~mode:Lwt_io.output sock_c in return (sock_c,(ic,oc)) let server addr port f = create_srv_socket addr port >>= fun sock -> let rec connect f sock = accept_cmn sock >>= fun (sock_c,(netr,netw)) -> async ( fun () -> catch( fun () -> f netr netw >>= fun () -> try_close netr >>= fun () -> try_close netw >>= fun () -> try_close_sock sock_c ) (fun ex -> try_close netr >>= fun () -> try_close netw >>= fun () -> try_close_sock sock_c >>= fun () -> Printf.printf "exception %s\n%!" (Printexc.to_string ex); return () ) ); connect f sock in connect f sock let readt = ref 0. let writet = ref 0. let comprt = ref 0. let timeit acc t = let t1 = Unix.gettimeofday() in acc := !acc +. (t1 -. t); t1 let sp = " " module type Maildir_intf = sig type t val create : user:string -> repo:string -> mailbox:string -> inflate:int option -> t Lwt.t val read_index: t -> num:string -> (int * string) list Lwt.t val read_message: t -> id:string -> string Lwt.t end module MaildirFile : Maildir_intf = struct type t = {user:string; repo:string; mailbox:string; inflate:int option} let get_dir t = if String.lowercase t.mailbox = "inbox" then t.repo else Filename.concat t.repo ("." ^ t.mailbox) let create ~user ~repo ~mailbox ~inflate = return {user;repo;mailbox;inflate} let read_index t ~num = let file = Filename.concat (get_dir t) "imaplet.uidlst" in Lwt_io.with_file ~flags:[Unix.O_NONBLOCK] ~mode:Lwt_io.Input file (fun ic -> let rec read uids = if num = "*" || (int_of_string num) > (List.length uids) then ( Lwt_io.read_line_opt ic >>= function | Some l -> let subs = Re.exec re l in let uid = int_of_string (Re.get subs 1) in let file = Re.get subs 2 in read ((uid,file) :: uids) | None -> return (List.rev uids) ) else return (List.rev uids) in read [] ) let read_message t ~id = let file = Filename.concat (Filename.concat (get_dir t) "cur") id in Lwt_io.with_file ~flags:[Unix.O_NONBLOCK] ~mode:Lwt_io.Input file (fun ic -> Lwt_io.read ic ) end module MaildirGitl : Maildir_intf = struct type t = {user:string; repo:string; mailbox:string; store:Gitl.t;inflate:int option} let create_store repo inflate = Gitl.create ~repo ?compress:inflate () let create ~user ~repo ~mailbox ~inflate = create_store repo inflate >>= fun store -> return {user;repo;mailbox;store;inflate} let read_index t ~num = catch(fun() -> let mailbox = if (String.lowercase t.mailbox = "inbox") then "INBOX" else t.mailbox in let key = ["INBOX";".index"] in Gitl.read_exn t.store key >>= fun index_sexp_str -> return (list_of_sexp (fun i -> change to same as let (file,uid) = pair_of_sexp Sexp.to_string (fun b -> int_of_string (Sexp.to_string b)) i in (uid,file) ) (Sexp.of_string index_sexp_str)) )(fun ex -> Printf.printf "exception:%s\n%!" (Printexc.to_string ex);return[]) let read_message t ~id = let key = ["INBOX";id] in Gitl.read_exn t.store key end module MaildirIrmin : Maildir_intf = struct module Store = Irmin_unix.Git.FS.KV(Irmin.Contents.String) type t = {user:string; repo:string; mailbox:string; store:Store.t;inflate:int option} let create_store repo = let _config = Irmin_git.config ~bare:true repo in Store.Repo.v _config >>= fun repo -> Store.master repo let create ~user ~repo ~mailbox ~inflate = create_store repo >>= fun store -> return {user;repo;mailbox;store;inflate} let read_index t ~num = catch(fun() -> let mailbox = if (String.lowercase t.mailbox = "inbox") then "INBOX" else t.mailbox in let key = ["imaplet"; t.user; "mailboxes"; mailbox; "index"] in Store.get t.store key >>= fun index_sexp_str -> return (list_of_sexp (fun i -> change to same as let (file,uid) = pair_of_sexp Sexp.to_string (fun b -> int_of_string (Sexp.to_string b)) i in (uid,file) ) (Sexp.of_string index_sexp_str)) )(fun ex -> Printf.printf "exception:%s\n%!" (Printexc.to_string ex);return[]) let read_message t ~id = let key = ["imaplet"; t.user; "storage";id] in Store.get t.store key end module type MaildirReader_intf = sig val read_files : user:string -> repo:string -> mailbox:string -> writer:Lwt_io.output_channel -> num:string -> inflate:int option -> unit Lwt.t end module MakeMaildirReader(M:Maildir_intf) : MaildirReader_intf = struct let write_messages d strm w uncompress = let rec _write d uid = Lwt_stream.get strm >>= function | Some message -> let del = (Unix.gettimeofday() -. d) in if uid = 1 then Printf.printf "initial write delay %.04f\n" del; Printf.printf "writing data %d, delay %.04f\r%!" uid del; let t=Unix.gettimeofday() in let message = if uncompress <> None then (Imap_crypto.do_uncompress message) else message in let l = ["*"; sp;string_of_int uid; sp; "FETCH"; sp; "("; "BODY[]"; sp; "{";string_of_int (String.length message); "}";"\r\n";message;")";"\r\n"] in let t = timeit comprt t in Lwt_list.iter_s (Lwt_io.write w) l >>= fun () -> let _ = timeit writet t in _write (Unix.gettimeofday()) (uid+1) | None -> return () in _write d 1 let read_files ~user ~repo ~mailbox ~writer ~num ~inflate = let (strm,push_strm) = Lwt_stream.create () in M.create ~user ~repo ~mailbox ~inflate >>= fun maildir -> M.read_index maildir ~num >>= fun uids -> let t = Unix.gettimeofday() in Lwt_list.iter_p (fun f -> f()) [ ( (fun () -> Lwt_list.iter_s (fun (_,file) -> let t = Unix.gettimeofday () in M.read_message maildir ~id:file >>= fun message -> let _ = timeit readt t in push_strm (Some message); Lwt_main.yield () ) uids >>= fun () -> push_strm None; return () ) ); ( (fun () -> write_messages t strm writer inflate ) ) ] end let () = commands (fun port -> Lwt_main.run ( server "0.0.0.0" port (fun r w -> Lwt_io.write w "CAPABILITY\r\n" >>= fun () -> let rec loop ?(user="") ?(repo="") ?(store="") ?(mailbox="") ?inflate () = Lwt_io.read_line_opt r >>= function | Some l -> begin imap l >>= function | `Fetch (tag,num) -> let open Gitl in begin try readt := 0.; writet := 0.; comprt := 0.; gitreadt := 0.; gitcomprt := 0.; let t = Unix.gettimeofday () in begin if store = "maildir" then ( let module MaildirReader = MakeMaildirReader(MaildirFile) in MaildirReader.read_files ~user ~repo ~mailbox ~writer:w ~num ~inflate ) else if store = "gitl" then ( let module MaildirReader = MakeMaildirReader(MaildirGitl) in MaildirReader.read_files ~user ~repo ~mailbox ~writer:w ~num ~inflate ) else ( let module MaildirReader = MakeMaildirReader(MaildirIrmin) in MaildirReader.read_files ~user ~repo ~mailbox ~writer:w ~num ~inflate ) end >>= fun () -> Lwt_io.write w (tag ^ " ok\r\n") >>= fun () -> Printf.printf "total read: %.04f, write %.04f, compress %.04f, time %.04f\n%!" !readt !writet !comprt (Unix.gettimeofday() -. t); Printf.printf "\tgit read: %.04f, compress %.04f\n%!" !gitreadt !gitcomprt; loop () with Not_found -> return () end | `Login (tag,user,repo,store,inflate) -> Lwt_io.write w (tag ^ " ok\r\n") >>= fun () -> loop ~user ~repo ~store ?inflate () | `Select (tag,mailbox) -> Lwt_io.write w (tag ^ " ok\r\n") >>= fun () -> loop ~user ~repo ~store ~mailbox ?inflate () | `Error tag -> Lwt_io.write w (tag ^ " bad\r\n") >>= fun () -> loop () end | None -> return () in loop () ) ) )