_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
b47f6d920b830916807bba560e3dc66a876ddbab52fed8c2ac43c93b47ea57d2
lisp/de.setf.xml
schema.lisp
20100513T131919Z00 ;;; from #<doc-node +oil #x2A825416> (common-lisp:in-package "+oil#") (de.setf.resource.schema:defclass |Class| (|-schema#|:|Class|) nil) (de.setf.resource.schema:defclass |Datatype| (|-schema#|:|Class|) nil) (de.setf.resource.schema:defclass |DatatypeProperty| (|-rdf-syntax-ns#|:|Property|) nil) (de.setf.resource.schema:defclass |List| (|-rdf-syntax-ns#|:|Seq|) nil) (de.setf.resource.schema:defclass |Literal| nil nil) (de.setf.resource.schema:defclass |ObjectProperty| (|-rdf-syntax-ns#|:|Property|) nil) (de.setf.resource.schema:defclass |Ontology| nil nil) (de.setf.resource.schema:defclass |Property| nil nil) (de.setf.resource.schema:defclass |Restriction| (|Class|) nil) (de.setf.resource.schema:defclass |TransitiveProperty| (|ObjectProperty|) nil) (de.setf.resource.schema:defclass |UnambiguousProperty| (|ObjectProperty|) nil) (de.setf.resource.schema:defclass |UniqueProperty| (|-rdf-syntax-ns#|:|Property|) nil)
null
https://raw.githubusercontent.com/lisp/de.setf.xml/827681c969342096c3b95735d84b447befa69fa6/namespaces/www-daml-org/2001/03/daml-oil/schema.lisp
lisp
from #<doc-node +oil #x2A825416>
20100513T131919Z00 (common-lisp:in-package "+oil#") (de.setf.resource.schema:defclass |Class| (|-schema#|:|Class|) nil) (de.setf.resource.schema:defclass |Datatype| (|-schema#|:|Class|) nil) (de.setf.resource.schema:defclass |DatatypeProperty| (|-rdf-syntax-ns#|:|Property|) nil) (de.setf.resource.schema:defclass |List| (|-rdf-syntax-ns#|:|Seq|) nil) (de.setf.resource.schema:defclass |Literal| nil nil) (de.setf.resource.schema:defclass |ObjectProperty| (|-rdf-syntax-ns#|:|Property|) nil) (de.setf.resource.schema:defclass |Ontology| nil nil) (de.setf.resource.schema:defclass |Property| nil nil) (de.setf.resource.schema:defclass |Restriction| (|Class|) nil) (de.setf.resource.schema:defclass |TransitiveProperty| (|ObjectProperty|) nil) (de.setf.resource.schema:defclass |UnambiguousProperty| (|ObjectProperty|) nil) (de.setf.resource.schema:defclass |UniqueProperty| (|-rdf-syntax-ns#|:|Property|) nil)
1555535929e180bb9cadc0f510ce913004916a97a3d2f76cd1984500664a4980
janestreet/rpc_parallel
qtest.ml
open Core open Poly open Async open Qtest_deprecated.Std module Add_map_function = Rpc_parallel.Map_reduce.Make_map_function_with_init (struct module Param = Int module Input = Int module Output = Int type state_type = int let init = return let map state x = return (x + state) end) module Count_map_reduce_function = Rpc_parallel.Map_reduce.Make_map_reduce_function_with_init (struct module Param = Int module Accum = Int module Input = struct type t = int list [@@deriving bin_io] end type state_type = int let init = return let map state l = return (state * List.fold l ~init:0 ~f:( + )) let combine _state x y = return (x + y) end) module Concat_map_reduce_function = Rpc_parallel.Map_reduce.Make_map_reduce_function (struct module Accum = struct type t = int list [@@deriving bin_io] end module Input = Int let map x = return [ x ] let combine l1 l2 = return (l1 @ l2) end) let test_map_unordered () = let n = 1000 in let input = List.init n ~f:Fn.id in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind output = Rpc_parallel.Map_reduce.map_unordered config (Pipe.of_list input) ~m:(module Add_map_function) ~param:n >>= Pipe.to_list in let numbers = List.sort (List.map output ~f:fst) ~compare:Int.compare in let expected_numbers = List.init n ~f:(( + ) n) in let indices = List.sort (List.map output ~f:snd) ~compare:Int.compare in let expected_indices = input in assert (List.equal ( = ) indices expected_indices); assert (List.equal ( = ) numbers expected_numbers); Deferred.unit ;; let test_map () = let n = 1000 in let input = List.init n ~f:Fn.id in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind output = Rpc_parallel.Map_reduce.map config (Pipe.of_list input) ~m:(module Add_map_function) ~param:n >>= Pipe.to_list in let expected_output = List.init n ~f:(( + ) n) in assert (List.equal ( = ) output expected_output); Deferred.unit ;; let test_map_reduce_commutative () = let n = 1000 in let multiplier = 2 in let input = List.init n ~f:(fun m -> List.init m ~f:Fn.id) in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind sum = Rpc_parallel.Map_reduce.map_reduce_commutative config (Pipe.of_list input) ~m:(module Count_map_reduce_function) ~param:multiplier in assert ( Option.value_exn sum = multiplier * List.fold ~init:0 ~f:( + ) (List.map input ~f:(List.fold ~init:0 ~f:( + )))); Deferred.unit ;; let test_map_reduce () = let n = 1000 in let input = List.init n ~f:Fn.id in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind l = Rpc_parallel.Map_reduce.map_reduce config (Pipe.of_list input) ~m:(module Concat_map_reduce_function) ~param:() in assert (Option.value_exn l = input); Deferred.unit ;; let tests = [ "map_unordered", test_map_unordered ; "map", test_map ; "map_reduce_commutative", test_map_reduce_commutative ; "map_reduce", test_map_reduce ] ;; let () = Rpc_parallel_krb_public.start_app ~krb_mode:For_unit_test (Command.basic_spec Command.Spec.empty ~summary:"Run tests" (fun () -> Runner.main ~check_fds:false tests)) ;;
null
https://raw.githubusercontent.com/janestreet/rpc_parallel/28bffcaa8a9fb73c321a616e724cf88efd38870f/test/qtest.ml
ocaml
open Core open Poly open Async open Qtest_deprecated.Std module Add_map_function = Rpc_parallel.Map_reduce.Make_map_function_with_init (struct module Param = Int module Input = Int module Output = Int type state_type = int let init = return let map state x = return (x + state) end) module Count_map_reduce_function = Rpc_parallel.Map_reduce.Make_map_reduce_function_with_init (struct module Param = Int module Accum = Int module Input = struct type t = int list [@@deriving bin_io] end type state_type = int let init = return let map state l = return (state * List.fold l ~init:0 ~f:( + )) let combine _state x y = return (x + y) end) module Concat_map_reduce_function = Rpc_parallel.Map_reduce.Make_map_reduce_function (struct module Accum = struct type t = int list [@@deriving bin_io] end module Input = Int let map x = return [ x ] let combine l1 l2 = return (l1 @ l2) end) let test_map_unordered () = let n = 1000 in let input = List.init n ~f:Fn.id in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind output = Rpc_parallel.Map_reduce.map_unordered config (Pipe.of_list input) ~m:(module Add_map_function) ~param:n >>= Pipe.to_list in let numbers = List.sort (List.map output ~f:fst) ~compare:Int.compare in let expected_numbers = List.init n ~f:(( + ) n) in let indices = List.sort (List.map output ~f:snd) ~compare:Int.compare in let expected_indices = input in assert (List.equal ( = ) indices expected_indices); assert (List.equal ( = ) numbers expected_numbers); Deferred.unit ;; let test_map () = let n = 1000 in let input = List.init n ~f:Fn.id in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind output = Rpc_parallel.Map_reduce.map config (Pipe.of_list input) ~m:(module Add_map_function) ~param:n >>= Pipe.to_list in let expected_output = List.init n ~f:(( + ) n) in assert (List.equal ( = ) output expected_output); Deferred.unit ;; let test_map_reduce_commutative () = let n = 1000 in let multiplier = 2 in let input = List.init n ~f:(fun m -> List.init m ~f:Fn.id) in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind sum = Rpc_parallel.Map_reduce.map_reduce_commutative config (Pipe.of_list input) ~m:(module Count_map_reduce_function) ~param:multiplier in assert ( Option.value_exn sum = multiplier * List.fold ~init:0 ~f:( + ) (List.map input ~f:(List.fold ~init:0 ~f:( + )))); Deferred.unit ;; let test_map_reduce () = let n = 1000 in let input = List.init n ~f:Fn.id in let config = Rpc_parallel.Map_reduce.Config.create ~local:5 ~redirect_stderr:`Dev_null ~redirect_stdout:`Dev_null () in let%bind l = Rpc_parallel.Map_reduce.map_reduce config (Pipe.of_list input) ~m:(module Concat_map_reduce_function) ~param:() in assert (Option.value_exn l = input); Deferred.unit ;; let tests = [ "map_unordered", test_map_unordered ; "map", test_map ; "map_reduce_commutative", test_map_reduce_commutative ; "map_reduce", test_map_reduce ] ;; let () = Rpc_parallel_krb_public.start_app ~krb_mode:For_unit_test (Command.basic_spec Command.Spec.empty ~summary:"Run tests" (fun () -> Runner.main ~check_fds:false tests)) ;;
ff14fe39dadb7b1aab5a40b0bc1e0ca7fc2992abf43ca5c3cd52d9ec459469b9
puffnfresh/haskell-jwt
JWTTestsCompat.hs
# LANGUAGE BangPatterns , OverloadedStrings , ScopedTypeVariables , TemplateHaskell # {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - orphans # {- - Turn of deprecation warnings as these tests deliberately use - deprecated types/functions to ensure that the library is backward compatible -} # OPTIONS_GHC -fno - warn - warnings - deprecations # module Web.JWTTestsCompat ( main , defaultTestGroup ) where import Test.Tasty import Test.Tasty.TH import Test.Tasty.HUnit import qualified Data.Map as Map import Data.Aeson.Types import Web.JWT defaultTestGroup :: TestTree defaultTestGroup = $(testGroupGenerator) main :: IO () main = defaultMain defaultTestGroup case_intDateDeriveOrd = do Tue 6 Jan 2009 19:40:31 Tue 6 Jan 2009 19:57:11 LT @=? i1 `compare` i2 case_encodeDecodeJWTIntDateIat = do let now = 1394573404 cs = mempty { iss = stringOrURI "Foo" , iat = intDate now , unregisteredClaims = ClaimsMap $ Map.fromList [("", Bool True)] } key = hmacSecret "secret-key" mJwt = decode $ encodeSigned key mempty cs let (Just claims') = fmap claims mJwt cs @=? claims' Just now @=? fmap secondsSinceEpoch (iat claims')
null
https://raw.githubusercontent.com/puffnfresh/haskell-jwt/260f9c358dc11ef3930653dd0ae3f3373fbd1c0c/tests/src/Web/JWTTestsCompat.hs
haskell
# LANGUAGE TypeSynonymInstances, FlexibleInstances # - Turn of deprecation warnings as these tests deliberately use - deprecated types/functions to ensure that the library is backward compatible
# LANGUAGE BangPatterns , OverloadedStrings , ScopedTypeVariables , TemplateHaskell # # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - orphans # # OPTIONS_GHC -fno - warn - warnings - deprecations # module Web.JWTTestsCompat ( main , defaultTestGroup ) where import Test.Tasty import Test.Tasty.TH import Test.Tasty.HUnit import qualified Data.Map as Map import Data.Aeson.Types import Web.JWT defaultTestGroup :: TestTree defaultTestGroup = $(testGroupGenerator) main :: IO () main = defaultMain defaultTestGroup case_intDateDeriveOrd = do Tue 6 Jan 2009 19:40:31 Tue 6 Jan 2009 19:57:11 LT @=? i1 `compare` i2 case_encodeDecodeJWTIntDateIat = do let now = 1394573404 cs = mempty { iss = stringOrURI "Foo" , iat = intDate now , unregisteredClaims = ClaimsMap $ Map.fromList [("", Bool True)] } key = hmacSecret "secret-key" mJwt = decode $ encodeSigned key mempty cs let (Just claims') = fmap claims mJwt cs @=? claims' Just now @=? fmap secondsSinceEpoch (iat claims')
55138e73a7351d31b97b1d733f4015dfea97afabaf0c85c8961e15e64729ad36
koka-lang/koka
Printer.hs
------------------------------------------------------------------------------ Copyright 2012 - 2021 , Microsoft Research , . -- -- This is free software; you can redistribute it and/or modify it under the terms of the Apache License , Version 2.0 . A copy of the License can be -- found in the LICENSE file at the root of this distribution. ----------------------------------------------------------------------------- {- Module for portable control of colors in a console. Only the color of 'stdout' is influenced by these functions. -} ----------------------------------------------------------------------------- module Lib.Printer( -- * Color Color(..) -- * Printer , Printer( write, writeText, writeLn, writeTextLn, flush, withColor, withBackColor, withReverse, withUnderline , setColor , setBackColor , setReverse , ) -- * Printers , MonoPrinter, withMonoPrinter , ColorPrinter, withColorPrinter, withNoColorPrinter, withFileNoColorPrinter, isAnsiPrinter, isConsolePrinter , AnsiPrinter, withAnsiPrinter , withFilePrinter, withNewFilePrinter , withHtmlPrinter, withHtmlColorPrinter -- * Misc. , ansiWithColor , ansiColor ) where import Data.List( intersperse ) import Data . ( toLower ) import System.IO ( hFlush, stdout, hPutStr, hPutStrLn, openFile, IOMode(..), hClose, Handle ) import Platform.Var( Var, newVar, putVar, takeVar ) import Platform.Runtime( finally ) import Platform.Config( exeExtension ) import qualified Platform.Console as Con import Data.Monoid (mappend, mconcat) import qualified Data.Text as T import qualified Data.Text.IO as T import Debug.Trace import System.Console.Isocline( withTerm, termWriteLn, termWrite, termFlush ) {-------------------------------------------------------------------------- Printer --------------------------------------------------------------------------} -- | A printer is an abstraction for something where we can send -- character output to. class Printer p where write :: p -> String -> IO () writeText :: p -> T.Text -> IO () writeText p t = write p (T.unpack t) writeLn :: p -> String -> IO () writeTextLn :: p -> T.Text -> IO () writeTextLn p t = writeLn p (T.unpack t) flush :: p -> IO () withColor :: p -> Color -> IO a -> IO a withBackColor :: p -> Color -> IO a -> IO a withReverse :: p -> Bool -> IO a -> IO a withUnderline :: p -> Bool -> IO a -> IO a setColor :: p -> Color -> IO () setBackColor :: p -> Color -> IO () setReverse :: p -> Bool -> IO () setUnderline :: p -> Bool -> IO () ------------------------------------------------------------------------- Interface ------------------------------------------------------------------------- Interface --------------------------------------------------------------------------} -- | Available colors on a console. Normally, background colors are -- converted to their /dark/ variant. data Color = Black | DarkRed | DarkGreen | DarkYellow | DarkBlue | DarkMagenta | DarkCyan | Gray | DarkGray | Red | Green | Yellow | Blue | Magenta | Cyan | White | ColorDefault deriving (Show,Eq,Ord,Enum) {-------------------------------------------------------------------------- Simple monochrome printer --------------------------------------------------------------------------} -- | On windows, we cannot print unicode characters :-( sanitize :: String -> String sanitize s | null exeExtension = s sanitize s = map (\c -> if (c > '~') then '?' else c) s sanitizeT :: T.Text -> T.Text sanitizeT s | null exeExtension = s sanitizeT s = T.map (\c -> if (c > '~') then '?' else c) s -- | Monochrome console newtype MonoPrinter = MonoPrinter () -- | Use a black and white printer that ignores colors. withMonoPrinter :: (MonoPrinter -> IO a) -> IO a withMonoPrinter f = f (MonoPrinter ()) instance Printer MonoPrinter where write p s = putStr $ sanitize s writeText p s = T.putStr $ sanitizeT s writeLn p s = putStrLn $ sanitize s writeTextLn p s = T.putStrLn $ sanitizeT s flush p = hFlush stdout withColor p c io = io withBackColor p c io = io withReverse p r io = io withUnderline p u io = io setColor p c = return () setBackColor p c = return () setReverse p r = return () setUnderline p u = return () {-------------------------------------------------------------------------- Simple file printer --------------------------------------------------------------------------} -- | File printer newtype FilePrinter = FilePrinter Handle -- | Use a file printer that ignores colors. Appends, or creates the file withFilePrinter :: FilePath -> (FilePrinter -> IO a) -> IO a withFilePrinter fname f = do h <- openFile fname AppendMode x <- f (FilePrinter h) hFlush h hClose h return x -- | Use a file printer that ignores colors. Creates or overwrites the file withNewFilePrinter :: FilePath -> (FilePrinter -> IO a) -> IO a withNewFilePrinter fname f = do h <- openFile fname WriteMode x <- f (FilePrinter h) hFlush h hClose h return x instance Printer FilePrinter where write (FilePrinter h) s = hPutStr h s writeText (FilePrinter h) s = T.hPutStr h s writeLn (FilePrinter h) s = hPutStrLn h s writeTextLn (FilePrinter h) s = T.hPutStrLn h s flush (FilePrinter h) = hFlush h withColor p c io = io withBackColor p c io = io withReverse p r io = io withUnderline p u io = io setColor p c = return () setBackColor p c = return () setReverse p r = return () setUnderline p u = return () {-------------------------------------------------------------------------- Standard ANSI escape sequences --------------------------------------------------------------------------} -- | Use a color printer that uses ANSI escape sequences. withAnsiPrinter :: (AnsiPrinter -> IO a) -> IO a withAnsiPrinter f = -- withTerm $ do ansi <- newVar ansiDefault finally (f (Ansi ansi)) (do ansiEscapeIO seqReset hFlush stdout) ansiDefault = AnsiConsole ColorDefault ColorDefault False False -- | Standard ANSI console newtype AnsiPrinter = Ansi (Var AnsiConsole) data AnsiConsole = AnsiConsole{ fcolor :: Color , bcolor :: Color , invert :: Bool , underline :: Bool } instance Printer AnsiPrinter where write p s = termWrite s -- putStr s T.putStr s writeLn p s = termWriteLn s -- putStrLn s T.putStrLn s flush p = termFlush -- hFlush stdout withColor p c io = ansiWithConsole p (\con -> con{ fcolor = c }) io withBackColor p c io = ansiWithConsole p (\con -> con{ bcolor = c }) io withReverse p r io = ansiWithConsole p (\con -> con{ invert = r }) io withUnderline p u io = ansiWithConsole p (\con -> con{ underline = u }) io setColor p c = unit $ ansiSetConsole p (\con -> con{ fcolor = c }) setBackColor p c = unit $ ansiSetConsole p (\con -> con{ bcolor = c }) setReverse p r = unit $ ansiSetConsole p (\con -> con{ invert = r }) setUnderline p u = unit $ ansiSetConsole p (\con -> con{ underline = u }) -- | Helper function to put a string into a certain color ansiWithColor :: Color -> String -> String ansiWithColor color s = let con0 = ansiDefault con1 = con0{ fcolor = color } pre = ansiEscape (seqSetConsole con0 con1) post = ansiEscape (seqSetConsole con1 con0) in T.unpack $ pre `mappend` (T.pack s `mappend` post) -- | Enable console color code. unit io = io >> return () -- Console code ansiWithConsole :: AnsiPrinter -> (AnsiConsole -> AnsiConsole) -> IO a -> IO a ansiWithConsole p f io = do old <- ansiSetConsole p f finally io (ansiSetConsole p (const old)) ansiSetConsole :: AnsiPrinter -> (AnsiConsole -> AnsiConsole) -> IO AnsiConsole ansiSetConsole (Ansi varAnsi) f = do con <- takeVar varAnsi let new = f con ansiEscapeIO (seqSetConsole con new) putVar varAnsi new return con ansiEscapeIO :: [T.Text] -> IO () ansiEscapeIO xs | null xs = return () T.putStr ansiEscape :: [T.Text] -> T.Text ansiEscape xs | null xs = T.empty | otherwise = T.pack "\ESC[" `mappend` ((mconcat $ intersperse (T.pack ";") xs) `mappend` T.pack "m") seqSetConsole old new -- reset when any attributes are disabled | invert old > invert new = reset | underline old > underline new = reset -- no attributes are disabled, we take a diff | otherwise = diff where reset = concat [seqReset ,seqReverse (invert new) ,seqUnderline (underline new) ,seqColor False (fcolor new) ,seqColor True (bcolor new)] diff = concat [max seqReverse invert ,max seqUnderline underline ,max (seqColor False) fcolor ,max (seqColor True) bcolor ] max f field = if (field old /= field new) then f (field new) else [] seqReset :: [T.Text] seqReset = [T.pack "0"] seqUnderline :: Bool -> [T.Text] seqUnderline u = if u then [T.pack "4"] else [] seqReverse rev = if rev then [T.pack "7"] else [] seqBold b = if b then [T.pack "1"] else [] seqColor :: Bool -> Color -> [T.Text] seqColor backGround c = encode (ansiColor c) where encode i = [T.pack $ show (i + if backGround then 10 else 0)] ansiColor :: Color -> Int ansiColor c = let i = fromEnum c in if (i < 8) then 30 + i else if (i < 16) then 90 + i - 8 else 39 ------------------------------------------------------------------------- Color console code ------------------------------------------------------------------------- Color console code --------------------------------------------------------------------------} -- | A color printer supports colored output data ColorPrinter = PCon ConsolePrinter | PAnsi AnsiPrinter | PMono MonoPrinter | PFile FilePrinter | PHTML HtmlPrinter -- | Use a color-enabled printer. withColorPrinter :: (ColorPrinter -> IO b) -> IO b withColorPrinter f Con.withConsole $ \success - > if success then f ( PCon ( ConsolePrinter ( ) ) ) else if success then f (PCon (ConsolePrinter ())) else -} withAnsiPrinter (f . PAnsi) withHtmlColorPrinter :: (ColorPrinter -> IO b) -> IO b withHtmlColorPrinter f = withHtmlPrinter (f. PHTML) -- | Disable the color output of a color printer. -- This can be useful if one wants to avoid overloading. withNoColorPrinter :: (ColorPrinter -> IO b) -> IO b withNoColorPrinter f = withMonoPrinter (\p -> f (PMono p)) -- | Disable the color output of a color printer. -- This can be useful if one wants to avoid overloading. withFileNoColorPrinter :: FilePath -> (ColorPrinter -> IO b) -> IO b withFileNoColorPrinter fname f = withFilePrinter fname (\p -> f (PFile p)) -- | Is this an ANSI printer? isAnsiPrinter :: ColorPrinter -> Bool isAnsiPrinter cp = case cp of PAnsi ansi -> True _ -> False isConsolePrinter :: ColorPrinter -> Bool isConsolePrinter cp = case cp of PCon _ -> True _ -> False instance Printer ColorPrinter where write p s = cmap p write write write write write s writeLn p s = cmap p writeLn writeLn writeLn writeLn writeLn s flush p = cmap p flush flush flush flush flush withColor p c io = cmap p withColor withColor withColor withColor withColor c io withBackColor p c io = cmap p withBackColor withBackColor withBackColor withBackColor withBackColor c io withReverse p r io = cmap p withReverse withReverse withReverse withReverse withReverse r io withUnderline p u io = cmap p withUnderline withUnderline withUnderline withUnderline withUnderline u io setColor p c = cmap p setColor setColor setColor setColor setColor c setBackColor p c = cmap p setBackColor setBackColor setBackColor setBackColor setBackColor c setReverse p r = cmap p setReverse setReverse setReverse setReverse setReverse r setUnderline p u = cmap p setUnderline setUnderline setUnderline setUnderline setUnderline u cmap p f g h i j = case p of PCon cp -> f cp PAnsi ap -> g ap PMono mp -> h mp PFile fp -> i fp PHTML hp -> j hp ------------------------------------------------------------------------- Windows console code ------------------------------------------------------------------------- Windows console code --------------------------------------------------------------------------} -- | Windows console printer newtype ConsolePrinter = ConsolePrinter () instance Printer ConsolePrinter where write p s = putStr $ sanitize s writeText p s = T.putStr $ sanitizeT s writeLn p s = putStrLn $ sanitize s writeTextLn p s = T.putStrLn $ sanitizeT s flush p = hFlush stdout withColor p c io = Con.bracketConsole (do Con.setColor c; io) withBackColor p c io = Con.bracketConsole (do Con.setBackColor c; io) withReverse p r io = Con.bracketConsole (do Con.setReverse r; io) withUnderline p u io = Con.bracketConsole (do Con.setUnderline u; io) setColor p c = Con.setColor c setBackColor p c = Con.setBackColor c setReverse p r = Con.setReverse r setUnderline p u = Con.setUnderline u {-------------------------------------------------------------------------- HTML printer --------------------------------------------------------------------------} data HtmlPrinter = HtmlPrinter () withHtmlPrinter :: (HtmlPrinter -> IO a) -> IO a withHtmlPrinter f = f (HtmlPrinter ()) instance Printer HtmlPrinter where write p s = putStr (htmlEscape s) writeText p s = write p (T.unpack s) writeLn p s = putStrLn (htmlEscape s) writeTextLn p s = writeLn p (T.unpack s) flush p = hFlush stdout withColor p c io = htmlSpan (T.pack "color") (htmlColor c) io withBackColor p c io = htmlSpan (T.pack "background-color") (htmlColor c) io withReverse p r io = {- no supported -} io withUnderline p u io = htmlSpan (T.pack "text-decoration") (T.pack "underline") io setColor p c = return () setBackColor p c = return () setReverse p r = return () setUnderline p u = return () htmlSpan :: T.Text -> T.Text -> IO a -> IO a htmlSpan prop val io = do T.putStr $ T.pack "<span style='" T.putStr $ prop T.putStr $ T.pack ": " T.putStr $ val T.putStr $ T.pack "'>" x <- io T.putStr $ T.pack "</span>" return x htmlColor :: Color -> T.Text htmlColor c = case c of ColorDefault -> T.pack "black" _ -> T.toLower (T.pack $ show c) htmlEscape s = concatMap escape s where escape c = case c of '&' -> "&amp;" '<' -> "&lt;" '>' -> "&gt;" '"' -> "&quot;" '\'' -> "&apos;" _ -> [c]
null
https://raw.githubusercontent.com/koka-lang/koka/50cd25fdfb0f917c2908ac12df14dd628547e0ad/src/Lib/Printer.hs
haskell
---------------------------------------------------------------------------- This is free software; you can redistribute it and/or modify it under the found in the LICENSE file at the root of this distribution. --------------------------------------------------------------------------- Module for portable control of colors in a console. Only the color of 'stdout' is influenced by these functions. --------------------------------------------------------------------------- * Color * Printer * Printers * Misc. ------------------------------------------------------------------------- Printer ------------------------------------------------------------------------- | A printer is an abstraction for something where we can send character output to. ----------------------------------------------------------------------- ----------------------------------------------------------------------- ------------------------------------------------------------------------} | Available colors on a console. Normally, background colors are converted to their /dark/ variant. ------------------------------------------------------------------------- Simple monochrome printer ------------------------------------------------------------------------- | On windows, we cannot print unicode characters :-( | Monochrome console | Use a black and white printer that ignores colors. ------------------------------------------------------------------------- Simple file printer ------------------------------------------------------------------------- | File printer | Use a file printer that ignores colors. Appends, or creates the file | Use a file printer that ignores colors. Creates or overwrites the file ------------------------------------------------------------------------- Standard ANSI escape sequences ------------------------------------------------------------------------- | Use a color printer that uses ANSI escape sequences. withTerm $ | Standard ANSI console putStr s putStrLn s hFlush stdout | Helper function to put a string into a certain color | Enable console color code. Console code reset when any attributes are disabled no attributes are disabled, we take a diff ----------------------------------------------------------------------- ----------------------------------------------------------------------- ------------------------------------------------------------------------} | A color printer supports colored output | Use a color-enabled printer. | Disable the color output of a color printer. This can be useful if one wants to avoid overloading. | Disable the color output of a color printer. This can be useful if one wants to avoid overloading. | Is this an ANSI printer? ----------------------------------------------------------------------- ----------------------------------------------------------------------- ------------------------------------------------------------------------} | Windows console printer ------------------------------------------------------------------------- HTML printer ------------------------------------------------------------------------- no supported
Copyright 2012 - 2021 , Microsoft Research , . terms of the Apache License , Version 2.0 . A copy of the License can be module Lib.Printer( Color(..) , Printer( write, writeText, writeLn, writeTextLn, flush, withColor, withBackColor, withReverse, withUnderline , setColor , setBackColor , setReverse , ) , MonoPrinter, withMonoPrinter , ColorPrinter, withColorPrinter, withNoColorPrinter, withFileNoColorPrinter, isAnsiPrinter, isConsolePrinter , AnsiPrinter, withAnsiPrinter , withFilePrinter, withNewFilePrinter , withHtmlPrinter, withHtmlColorPrinter , ansiWithColor , ansiColor ) where import Data.List( intersperse ) import Data . ( toLower ) import System.IO ( hFlush, stdout, hPutStr, hPutStrLn, openFile, IOMode(..), hClose, Handle ) import Platform.Var( Var, newVar, putVar, takeVar ) import Platform.Runtime( finally ) import Platform.Config( exeExtension ) import qualified Platform.Console as Con import Data.Monoid (mappend, mconcat) import qualified Data.Text as T import qualified Data.Text.IO as T import Debug.Trace import System.Console.Isocline( withTerm, termWriteLn, termWrite, termFlush ) class Printer p where write :: p -> String -> IO () writeText :: p -> T.Text -> IO () writeText p t = write p (T.unpack t) writeLn :: p -> String -> IO () writeTextLn :: p -> T.Text -> IO () writeTextLn p t = writeLn p (T.unpack t) flush :: p -> IO () withColor :: p -> Color -> IO a -> IO a withBackColor :: p -> Color -> IO a -> IO a withReverse :: p -> Bool -> IO a -> IO a withUnderline :: p -> Bool -> IO a -> IO a setColor :: p -> Color -> IO () setBackColor :: p -> Color -> IO () setReverse :: p -> Bool -> IO () setUnderline :: p -> Bool -> IO () Interface Interface data Color = Black | DarkRed | DarkGreen | DarkYellow | DarkBlue | DarkMagenta | DarkCyan | Gray | DarkGray | Red | Green | Yellow | Blue | Magenta | Cyan | White | ColorDefault deriving (Show,Eq,Ord,Enum) sanitize :: String -> String sanitize s | null exeExtension = s sanitize s = map (\c -> if (c > '~') then '?' else c) s sanitizeT :: T.Text -> T.Text sanitizeT s | null exeExtension = s sanitizeT s = T.map (\c -> if (c > '~') then '?' else c) s newtype MonoPrinter = MonoPrinter () withMonoPrinter :: (MonoPrinter -> IO a) -> IO a withMonoPrinter f = f (MonoPrinter ()) instance Printer MonoPrinter where write p s = putStr $ sanitize s writeText p s = T.putStr $ sanitizeT s writeLn p s = putStrLn $ sanitize s writeTextLn p s = T.putStrLn $ sanitizeT s flush p = hFlush stdout withColor p c io = io withBackColor p c io = io withReverse p r io = io withUnderline p u io = io setColor p c = return () setBackColor p c = return () setReverse p r = return () setUnderline p u = return () newtype FilePrinter = FilePrinter Handle withFilePrinter :: FilePath -> (FilePrinter -> IO a) -> IO a withFilePrinter fname f = do h <- openFile fname AppendMode x <- f (FilePrinter h) hFlush h hClose h return x withNewFilePrinter :: FilePath -> (FilePrinter -> IO a) -> IO a withNewFilePrinter fname f = do h <- openFile fname WriteMode x <- f (FilePrinter h) hFlush h hClose h return x instance Printer FilePrinter where write (FilePrinter h) s = hPutStr h s writeText (FilePrinter h) s = T.hPutStr h s writeLn (FilePrinter h) s = hPutStrLn h s writeTextLn (FilePrinter h) s = T.hPutStrLn h s flush (FilePrinter h) = hFlush h withColor p c io = io withBackColor p c io = io withReverse p r io = io withUnderline p u io = io setColor p c = return () setBackColor p c = return () setReverse p r = return () setUnderline p u = return () withAnsiPrinter :: (AnsiPrinter -> IO a) -> IO a withAnsiPrinter f do ansi <- newVar ansiDefault finally (f (Ansi ansi)) (do ansiEscapeIO seqReset hFlush stdout) ansiDefault = AnsiConsole ColorDefault ColorDefault False False newtype AnsiPrinter = Ansi (Var AnsiConsole) data AnsiConsole = AnsiConsole{ fcolor :: Color , bcolor :: Color , invert :: Bool , underline :: Bool } instance Printer AnsiPrinter where T.putStr s T.putStrLn s withColor p c io = ansiWithConsole p (\con -> con{ fcolor = c }) io withBackColor p c io = ansiWithConsole p (\con -> con{ bcolor = c }) io withReverse p r io = ansiWithConsole p (\con -> con{ invert = r }) io withUnderline p u io = ansiWithConsole p (\con -> con{ underline = u }) io setColor p c = unit $ ansiSetConsole p (\con -> con{ fcolor = c }) setBackColor p c = unit $ ansiSetConsole p (\con -> con{ bcolor = c }) setReverse p r = unit $ ansiSetConsole p (\con -> con{ invert = r }) setUnderline p u = unit $ ansiSetConsole p (\con -> con{ underline = u }) ansiWithColor :: Color -> String -> String ansiWithColor color s = let con0 = ansiDefault con1 = con0{ fcolor = color } pre = ansiEscape (seqSetConsole con0 con1) post = ansiEscape (seqSetConsole con1 con0) in T.unpack $ pre `mappend` (T.pack s `mappend` post) unit io = io >> return () ansiWithConsole :: AnsiPrinter -> (AnsiConsole -> AnsiConsole) -> IO a -> IO a ansiWithConsole p f io = do old <- ansiSetConsole p f finally io (ansiSetConsole p (const old)) ansiSetConsole :: AnsiPrinter -> (AnsiConsole -> AnsiConsole) -> IO AnsiConsole ansiSetConsole (Ansi varAnsi) f = do con <- takeVar varAnsi let new = f con ansiEscapeIO (seqSetConsole con new) putVar varAnsi new return con ansiEscapeIO :: [T.Text] -> IO () ansiEscapeIO xs | null xs = return () T.putStr ansiEscape :: [T.Text] -> T.Text ansiEscape xs | null xs = T.empty | otherwise = T.pack "\ESC[" `mappend` ((mconcat $ intersperse (T.pack ";") xs) `mappend` T.pack "m") seqSetConsole old new | invert old > invert new = reset | underline old > underline new = reset | otherwise = diff where reset = concat [seqReset ,seqReverse (invert new) ,seqUnderline (underline new) ,seqColor False (fcolor new) ,seqColor True (bcolor new)] diff = concat [max seqReverse invert ,max seqUnderline underline ,max (seqColor False) fcolor ,max (seqColor True) bcolor ] max f field = if (field old /= field new) then f (field new) else [] seqReset :: [T.Text] seqReset = [T.pack "0"] seqUnderline :: Bool -> [T.Text] seqUnderline u = if u then [T.pack "4"] else [] seqReverse rev = if rev then [T.pack "7"] else [] seqBold b = if b then [T.pack "1"] else [] seqColor :: Bool -> Color -> [T.Text] seqColor backGround c = encode (ansiColor c) where encode i = [T.pack $ show (i + if backGround then 10 else 0)] ansiColor :: Color -> Int ansiColor c = let i = fromEnum c in if (i < 8) then 30 + i else if (i < 16) then 90 + i - 8 else 39 Color console code Color console code data ColorPrinter = PCon ConsolePrinter | PAnsi AnsiPrinter | PMono MonoPrinter | PFile FilePrinter | PHTML HtmlPrinter withColorPrinter :: (ColorPrinter -> IO b) -> IO b withColorPrinter f Con.withConsole $ \success - > if success then f ( PCon ( ConsolePrinter ( ) ) ) else if success then f (PCon (ConsolePrinter ())) else -} withAnsiPrinter (f . PAnsi) withHtmlColorPrinter :: (ColorPrinter -> IO b) -> IO b withHtmlColorPrinter f = withHtmlPrinter (f. PHTML) withNoColorPrinter :: (ColorPrinter -> IO b) -> IO b withNoColorPrinter f = withMonoPrinter (\p -> f (PMono p)) withFileNoColorPrinter :: FilePath -> (ColorPrinter -> IO b) -> IO b withFileNoColorPrinter fname f = withFilePrinter fname (\p -> f (PFile p)) isAnsiPrinter :: ColorPrinter -> Bool isAnsiPrinter cp = case cp of PAnsi ansi -> True _ -> False isConsolePrinter :: ColorPrinter -> Bool isConsolePrinter cp = case cp of PCon _ -> True _ -> False instance Printer ColorPrinter where write p s = cmap p write write write write write s writeLn p s = cmap p writeLn writeLn writeLn writeLn writeLn s flush p = cmap p flush flush flush flush flush withColor p c io = cmap p withColor withColor withColor withColor withColor c io withBackColor p c io = cmap p withBackColor withBackColor withBackColor withBackColor withBackColor c io withReverse p r io = cmap p withReverse withReverse withReverse withReverse withReverse r io withUnderline p u io = cmap p withUnderline withUnderline withUnderline withUnderline withUnderline u io setColor p c = cmap p setColor setColor setColor setColor setColor c setBackColor p c = cmap p setBackColor setBackColor setBackColor setBackColor setBackColor c setReverse p r = cmap p setReverse setReverse setReverse setReverse setReverse r setUnderline p u = cmap p setUnderline setUnderline setUnderline setUnderline setUnderline u cmap p f g h i j = case p of PCon cp -> f cp PAnsi ap -> g ap PMono mp -> h mp PFile fp -> i fp PHTML hp -> j hp Windows console code Windows console code newtype ConsolePrinter = ConsolePrinter () instance Printer ConsolePrinter where write p s = putStr $ sanitize s writeText p s = T.putStr $ sanitizeT s writeLn p s = putStrLn $ sanitize s writeTextLn p s = T.putStrLn $ sanitizeT s flush p = hFlush stdout withColor p c io = Con.bracketConsole (do Con.setColor c; io) withBackColor p c io = Con.bracketConsole (do Con.setBackColor c; io) withReverse p r io = Con.bracketConsole (do Con.setReverse r; io) withUnderline p u io = Con.bracketConsole (do Con.setUnderline u; io) setColor p c = Con.setColor c setBackColor p c = Con.setBackColor c setReverse p r = Con.setReverse r setUnderline p u = Con.setUnderline u data HtmlPrinter = HtmlPrinter () withHtmlPrinter :: (HtmlPrinter -> IO a) -> IO a withHtmlPrinter f = f (HtmlPrinter ()) instance Printer HtmlPrinter where write p s = putStr (htmlEscape s) writeText p s = write p (T.unpack s) writeLn p s = putStrLn (htmlEscape s) writeTextLn p s = writeLn p (T.unpack s) flush p = hFlush stdout withColor p c io = htmlSpan (T.pack "color") (htmlColor c) io withBackColor p c io = htmlSpan (T.pack "background-color") (htmlColor c) io withUnderline p u io = htmlSpan (T.pack "text-decoration") (T.pack "underline") io setColor p c = return () setBackColor p c = return () setReverse p r = return () setUnderline p u = return () htmlSpan :: T.Text -> T.Text -> IO a -> IO a htmlSpan prop val io = do T.putStr $ T.pack "<span style='" T.putStr $ prop T.putStr $ T.pack ": " T.putStr $ val T.putStr $ T.pack "'>" x <- io T.putStr $ T.pack "</span>" return x htmlColor :: Color -> T.Text htmlColor c = case c of ColorDefault -> T.pack "black" _ -> T.toLower (T.pack $ show c) htmlEscape s = concatMap escape s where escape c = case c of '&' -> "&amp;" '<' -> "&lt;" '>' -> "&gt;" '"' -> "&quot;" '\'' -> "&apos;" _ -> [c]
470ac180791ec38b0d53f4a89369740829074d271a96573c7e00f2c9d75d3e68
jeffshrager/biobike
accessors.lisp
-*- Package : aframes ; mode : lisp ; base : 10 ; Syntax : Common - Lisp ; -*- (in-package :aframes) ;;; +=========================================================================+ | Copyright ( c ) 2002 , 2003 , 2004 JP , , | ;;; | | ;;; | 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. | ;;; +=========================================================================+ (defvar *frames-safety* nil) Now we assume readtable is set up , so we can use # $ and # ^. ;;; High-level slot access (defun bad-slot-access (frame slot) (error (one-string-nl "You are trying to access or set a component of the frame ~A," "but components of frames are referenced by other frames." "You used ~S as the reference, which is a ~S, not a frame.") frame slot (type-of slot))) (defun bad-slotv-call (non-frame) (error (one-string-nl "You are trying to use SLOTV to access or set ~S, but that" "function can only be used with frames. You called it with ~S," "which is of type ~S.") non-frame non-frame (type-of non-frame))) (defmethod slotv ((frame aframe) (slot t)) #.(one-string-nl "Access the value of SLOT within FRAME. This form is setf-able." "A second value is returned which is T if the slot actually" "exists, and NIL if it does not exist (The first value will be NIL" "if either the value of the slot is NIL, or the slot does not exist.") (internal-slotv frame slot) ) (defun internal-slotv (frame slot) (when *frames-safety* (unless (isframe? slot) (bad-slot-access frame slot))) (cond ((eq slot *fname-frame*) (values (fname frame) t)) ((eq slot *iname-frame*) (values (iname frame) t)) (t (multiple-value-bind (value exists?) (%slotv frame slot) (if exists? (values value t) (inheriting-slotv frame slot) ))))) (defun inheriting-slotv (frame slot) (let ((frame-type (type-of frame))) (if (eq frame-type 'aframe) (values nil nil) (let ((type-frame (frame-fnamed (string frame-type)))) (if (null type-frame) (values nil nil) (multiple-value-bind (value exists?) (%slotv type-frame slot) (if exists? (values value :inherited) (values nil nil)) )))))) (defmethod set-slotv ((frame aframe) (slot t) value) #.(one-string-nl "Store VALUE as the value of SLOT within FRAME." "Assuming no errors, the SLOT's value is set to VALUE and VALUE is" "returned as the first value, while either :NEW or :EXISTING is returned" "as the 2nd value, depending on whether the slot was added to the frame" "or was already there.") (when *frames-safety* (unless (isframe? frame) (bad-slot-access frame slot)) (unless (isframe? slot) (bad-slotv-call frame))) (when (eq slot *fname-frame*) (error "You cannot change a frame's fName!")) (when (eq slot *iname-frame*) (error "You cannot change a frame's iName!")) (%set-slotv frame slot value) ) (defsetf slotv set-slotv) (defmethod delete-slot ((frame aframe) (slot t)) #.(one-string-nl "Removes SLOT from FRAME (as opposed to just setting its" "value to NIL, say.) Once this is called, the function" "(FRAME-HAS-SLOT? FRAME SLOT) will return NIL." "(Note that (SLOTV FRAME SLOT) will return NIL whether a slot exists" "or the slot value is NIL.)") (unless (isframe? frame) (error "Not a frame: ~A" frame)) (unless (isframe? slot) (error "Not a frame: ~A" slot)) (when (eq slot *fname-frame*) (error "You cannot delete the #$Fname slot of a frame!")) (when (eq slot *iname-frame*) (error "You cannot delete the #$iName slot of a frame!")) (%remove-slot frame slot) frame ) ;;; shorthand for functional access (defun slot-accessor (slot) (lambda (frame) (slotv frame slot))) (defmethod describe-frame ((frame aframe)) "Print the frame object name and value for every frame slot of FRAME" (if (not (isframe? frame)) (progn (warn "~A is not frame object! Using DESCRIBE..." frame) (describe frame)) (progn (terpri) (format t "~&Slots of ~A (of type ~A):" frame (type-of frame)) (let ((slots-and-values nil) (current-slot nil)) (handler-case (progn (for-each-frame-slot (slot value) frame (unless (eq slot *fname-frame*) (push (list slot value) slots-and-values))) (setq slots-and-values (sort slots-and-values 'string-lessp :key (lambda (x) (fname (first x))))) (loop for (slot value) in slots-and-values do (setq current-slot slot) (format t "~& ~S:~8T~S" slot value) )) (error () (formatt (one-string-nl "" "ERROR: There is undisplayable content in this frame." "The slot containing the undisplayable content is ~A" ) current-slot )))))) (terpri) (values) ) (defmethod describe-object ((frame aframe) stream) (let ((*standard-output* stream)) (describe-frame frame))) (defun df (frame) "Describe (pretty print) a frame's slots and their values" (describe-frame frame)) ;;; define a frame plus some slots (defun def-frame (frame &rest slots) #.(one-string-nl "If FRAME does not yet exist create it. (FRAME may be a string or symbol" "naming a frame). SLOTS is a list of the form:" "(<slot1> <value1> <slot2> <value2> ... <slotn> <valuen>)" "For each corresponding slot and value in the list, FRAME is made to" "explicitly have that slot storing that value." "The existing or newly created frame is returned.") Coerce FRAME to be a frame , explicitly (setq frame (frame-fnamed (fstring frame) t)) ;; fill in slots (do ((rest-slots slots (cddr rest-slots))) ((null rest-slots)) (setf (slotv frame (car rest-slots)) (cadr rest-slots))) frame) (defmethod delete-frame ((frame aframe)) #.(one-string-nl '("Actually deletes a frame and removes it from the acache database." "Must commit to really get rid of the acache object in a real acache." "WARNING: If there are any slots or other references to this frame, an" "acache error will be signaled in real acache each time anyone tries to" "access the frame (e.g., the slot)." "Therefore, this is likely to break everything!" )) (%delete-frame frame) t) (defun unintern-frame (frame) (delete-frame frame)) (defun frame-print-prefix (frame) (declare (ignore frame)) "#$") (defun print-frame (frame stream &rest ignore) (declare (ignore ignore)) (format stream "~A~A" (frame-print-prefix frame) (fname frame)) ) ;;; Abstraction for slots whose value is a list. (defun add-element (frame slot elt &key (test 'eql)) (pushnew elt (slotv frame slot) :test test) elt) (defun delete-element (frame slot elt &key (test 'eql)) "Remove the element ELT from the value of SLOT in FRAME" (setf (slotv frame slot) (delete elt (slotv frame slot) :test test))) (defun has-element? (frame slot elt &key (key 'identity) (test 'eql)) "Non-NIL if the element ELT is included in the value of SLOT in FRAME" (member elt (slotv frame slot) :key key :test test))
null
https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/Sframes/accessors.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. | +=========================================================================+ High-level slot access shorthand for functional access define a frame plus some slots fill in slots Abstraction for slots whose value is a list.
(in-package :aframes) | Copyright ( c ) 2002 , 2003 , 2004 JP , , | | " 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 , | (defvar *frames-safety* nil) Now we assume readtable is set up , so we can use # $ and # ^. (defun bad-slot-access (frame slot) (error (one-string-nl "You are trying to access or set a component of the frame ~A," "but components of frames are referenced by other frames." "You used ~S as the reference, which is a ~S, not a frame.") frame slot (type-of slot))) (defun bad-slotv-call (non-frame) (error (one-string-nl "You are trying to use SLOTV to access or set ~S, but that" "function can only be used with frames. You called it with ~S," "which is of type ~S.") non-frame non-frame (type-of non-frame))) (defmethod slotv ((frame aframe) (slot t)) #.(one-string-nl "Access the value of SLOT within FRAME. This form is setf-able." "A second value is returned which is T if the slot actually" "exists, and NIL if it does not exist (The first value will be NIL" "if either the value of the slot is NIL, or the slot does not exist.") (internal-slotv frame slot) ) (defun internal-slotv (frame slot) (when *frames-safety* (unless (isframe? slot) (bad-slot-access frame slot))) (cond ((eq slot *fname-frame*) (values (fname frame) t)) ((eq slot *iname-frame*) (values (iname frame) t)) (t (multiple-value-bind (value exists?) (%slotv frame slot) (if exists? (values value t) (inheriting-slotv frame slot) ))))) (defun inheriting-slotv (frame slot) (let ((frame-type (type-of frame))) (if (eq frame-type 'aframe) (values nil nil) (let ((type-frame (frame-fnamed (string frame-type)))) (if (null type-frame) (values nil nil) (multiple-value-bind (value exists?) (%slotv type-frame slot) (if exists? (values value :inherited) (values nil nil)) )))))) (defmethod set-slotv ((frame aframe) (slot t) value) #.(one-string-nl "Store VALUE as the value of SLOT within FRAME." "Assuming no errors, the SLOT's value is set to VALUE and VALUE is" "returned as the first value, while either :NEW or :EXISTING is returned" "as the 2nd value, depending on whether the slot was added to the frame" "or was already there.") (when *frames-safety* (unless (isframe? frame) (bad-slot-access frame slot)) (unless (isframe? slot) (bad-slotv-call frame))) (when (eq slot *fname-frame*) (error "You cannot change a frame's fName!")) (when (eq slot *iname-frame*) (error "You cannot change a frame's iName!")) (%set-slotv frame slot value) ) (defsetf slotv set-slotv) (defmethod delete-slot ((frame aframe) (slot t)) #.(one-string-nl "Removes SLOT from FRAME (as opposed to just setting its" "value to NIL, say.) Once this is called, the function" "(FRAME-HAS-SLOT? FRAME SLOT) will return NIL." "(Note that (SLOTV FRAME SLOT) will return NIL whether a slot exists" "or the slot value is NIL.)") (unless (isframe? frame) (error "Not a frame: ~A" frame)) (unless (isframe? slot) (error "Not a frame: ~A" slot)) (when (eq slot *fname-frame*) (error "You cannot delete the #$Fname slot of a frame!")) (when (eq slot *iname-frame*) (error "You cannot delete the #$iName slot of a frame!")) (%remove-slot frame slot) frame ) (defun slot-accessor (slot) (lambda (frame) (slotv frame slot))) (defmethod describe-frame ((frame aframe)) "Print the frame object name and value for every frame slot of FRAME" (if (not (isframe? frame)) (progn (warn "~A is not frame object! Using DESCRIBE..." frame) (describe frame)) (progn (terpri) (format t "~&Slots of ~A (of type ~A):" frame (type-of frame)) (let ((slots-and-values nil) (current-slot nil)) (handler-case (progn (for-each-frame-slot (slot value) frame (unless (eq slot *fname-frame*) (push (list slot value) slots-and-values))) (setq slots-and-values (sort slots-and-values 'string-lessp :key (lambda (x) (fname (first x))))) (loop for (slot value) in slots-and-values do (setq current-slot slot) (format t "~& ~S:~8T~S" slot value) )) (error () (formatt (one-string-nl "" "ERROR: There is undisplayable content in this frame." "The slot containing the undisplayable content is ~A" ) current-slot )))))) (terpri) (values) ) (defmethod describe-object ((frame aframe) stream) (let ((*standard-output* stream)) (describe-frame frame))) (defun df (frame) "Describe (pretty print) a frame's slots and their values" (describe-frame frame)) (defun def-frame (frame &rest slots) #.(one-string-nl "If FRAME does not yet exist create it. (FRAME may be a string or symbol" "naming a frame). SLOTS is a list of the form:" "(<slot1> <value1> <slot2> <value2> ... <slotn> <valuen>)" "For each corresponding slot and value in the list, FRAME is made to" "explicitly have that slot storing that value." "The existing or newly created frame is returned.") Coerce FRAME to be a frame , explicitly (setq frame (frame-fnamed (fstring frame) t)) (do ((rest-slots slots (cddr rest-slots))) ((null rest-slots)) (setf (slotv frame (car rest-slots)) (cadr rest-slots))) frame) (defmethod delete-frame ((frame aframe)) #.(one-string-nl '("Actually deletes a frame and removes it from the acache database." "Must commit to really get rid of the acache object in a real acache." "WARNING: If there are any slots or other references to this frame, an" "acache error will be signaled in real acache each time anyone tries to" "access the frame (e.g., the slot)." "Therefore, this is likely to break everything!" )) (%delete-frame frame) t) (defun unintern-frame (frame) (delete-frame frame)) (defun frame-print-prefix (frame) (declare (ignore frame)) "#$") (defun print-frame (frame stream &rest ignore) (declare (ignore ignore)) (format stream "~A~A" (frame-print-prefix frame) (fname frame)) ) (defun add-element (frame slot elt &key (test 'eql)) (pushnew elt (slotv frame slot) :test test) elt) (defun delete-element (frame slot elt &key (test 'eql)) "Remove the element ELT from the value of SLOT in FRAME" (setf (slotv frame slot) (delete elt (slotv frame slot) :test test))) (defun has-element? (frame slot elt &key (key 'identity) (test 'eql)) "Non-NIL if the element ELT is included in the value of SLOT in FRAME" (member elt (slotv frame slot) :key key :test test))
03864a2a4e9cc08d9dc2bfcc590fcc22073d962a1a4f17ffe536164243452a56
bartima3us/gen_bittorrent
gen_bittorrent_impl.erl
%%%------------------------------------------------------------------- @author ( C ) 2018 , %%% @doc %%% %%% @end Created : 21 . Jul 2019 19.29 %%%------------------------------------------------------------------- -module(gen_bittorrent_impl). -author("bartimaeus"). -behaviour(gen_bittorrent). %% API -export([ start_link/0 ]). -export([ init/1, peer_handshaked/2, peer_unchoked/2, peer_choked/2, block_requested/4, block_downloaded/5, piece_completed/2, handle_call/3, handle_info/2, code_change/3, terminate/1 ]). %% %% %% start_link() -> gen_bittorrent:start_link(?MODULE, {109,161,87,5}, 26449, "-ER0000-45AF6T-NM81-", <<20,6,22,150,209,14,72,58,240,183,227,28,144,88,78,197,85,137,236,91>>, 3, 1048576, [], []). %% %% %% init(_Args) -> {ok, []}. peer_handshaked(_PieceId, State) -> io:format("Handshaked!~n"), {ok, State}. peer_unchoked(_PieceId, State) -> io:format("Unchoked!~n"), {ok, State}. peer_choked(_PieceId, State) -> io:format("Choked!~n"), {ok, State}. block_requested(_PieceId, Offset, Length, State) -> io:format("Block requested! Offset / length = ~p / ~p~n", [Offset, Length]), {ok, State}. block_downloaded(_PieceId, _Payload, Offset, Length, State) -> io:format("Block downloaded! Offset / length = ~p / ~p~n", [Offset, Length]), {ok, State}. piece_completed(_PieceId, State) -> io:format("Piece completed!~n"), {ok, State}. handle_call(Msg, _From, State) -> io:format("Handle call. Msg = ~p~n", [Msg]), {reply, answer, State}. handle_info(Msg, State) -> io:format("Handle info. Msg = ~p~n", [Msg]), {ok, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_State) -> ok.
null
https://raw.githubusercontent.com/bartima3us/gen_bittorrent/e06c99a042c9312f37b75162171606cd8f24c576/examples/gen_bittorrent_impl.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API
@author ( C ) 2018 , Created : 21 . Jul 2019 19.29 -module(gen_bittorrent_impl). -author("bartimaeus"). -behaviour(gen_bittorrent). -export([ start_link/0 ]). -export([ init/1, peer_handshaked/2, peer_unchoked/2, peer_choked/2, block_requested/4, block_downloaded/5, piece_completed/2, handle_call/3, handle_info/2, code_change/3, terminate/1 ]). start_link() -> gen_bittorrent:start_link(?MODULE, {109,161,87,5}, 26449, "-ER0000-45AF6T-NM81-", <<20,6,22,150,209,14,72,58,240,183,227,28,144,88,78,197,85,137,236,91>>, 3, 1048576, [], []). init(_Args) -> {ok, []}. peer_handshaked(_PieceId, State) -> io:format("Handshaked!~n"), {ok, State}. peer_unchoked(_PieceId, State) -> io:format("Unchoked!~n"), {ok, State}. peer_choked(_PieceId, State) -> io:format("Choked!~n"), {ok, State}. block_requested(_PieceId, Offset, Length, State) -> io:format("Block requested! Offset / length = ~p / ~p~n", [Offset, Length]), {ok, State}. block_downloaded(_PieceId, _Payload, Offset, Length, State) -> io:format("Block downloaded! Offset / length = ~p / ~p~n", [Offset, Length]), {ok, State}. piece_completed(_PieceId, State) -> io:format("Piece completed!~n"), {ok, State}. handle_call(Msg, _From, State) -> io:format("Handle call. Msg = ~p~n", [Msg]), {reply, answer, State}. handle_info(Msg, State) -> io:format("Handle info. Msg = ~p~n", [Msg]), {ok, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_State) -> ok.
6f3c0c46cdb247151c882e4131f6e3c0fef20bf2d05d05e8d30ffc8f3d209fc3
clash-lang/clash-compiler
T2334.hs
module T2334 where import qualified Prelude as P import Clash.Explicit.Prelude import Clash.Driver import Clash.Driver.Manifest import GHC.Stack import System.Environment import System.FilePath import qualified Control.Exception as Exception topEntity :: Clock System -> Reset System -> Signal System Int -> Signal System Int -> Signal System Int -> Signal System Int topEntity clk rst = assert clk rst "FileOrder" {-# NOINLINE topEntity #-} assertBool :: HasCallStack => Bool -> IO () assertBool b = Exception.assert b pure () mainVHDL :: IO () mainVHDL = do [topDir] <- getArgs Just manifest <- readManifest (topDir </> show 'topEntity </> "clash-manifest.json") let ([sdc, slv2string, types, top], _hashes) = P.unzip (fileNames manifest) assertBool (sdc == "topEntity.sdc") assertBool (P.take 20 slv2string == "topEntity_slv2string") assertBool (types == "T2334_topEntity_types.vhdl") assertBool (top == "topEntity.vhdl")
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/b4b326e4a1b1ba739bf430540fe2f8bc7238e144/tests/shouldwork/Issues/T2334.hs
haskell
# NOINLINE topEntity #
module T2334 where import qualified Prelude as P import Clash.Explicit.Prelude import Clash.Driver import Clash.Driver.Manifest import GHC.Stack import System.Environment import System.FilePath import qualified Control.Exception as Exception topEntity :: Clock System -> Reset System -> Signal System Int -> Signal System Int -> Signal System Int -> Signal System Int topEntity clk rst = assert clk rst "FileOrder" assertBool :: HasCallStack => Bool -> IO () assertBool b = Exception.assert b pure () mainVHDL :: IO () mainVHDL = do [topDir] <- getArgs Just manifest <- readManifest (topDir </> show 'topEntity </> "clash-manifest.json") let ([sdc, slv2string, types, top], _hashes) = P.unzip (fileNames manifest) assertBool (sdc == "topEntity.sdc") assertBool (P.take 20 slv2string == "topEntity_slv2string") assertBool (types == "T2334_topEntity_types.vhdl") assertBool (top == "topEntity.vhdl")
d543f0d6c25d290cd4c00e12da622ebc53e6ecac1b78d53e3a9bbc7862c6bc0f
processone/xmpp
xep0328.erl
Created automatically by XML generator ( fxml_gen.erl ) %% Source: xmpp_codec.spec -module(xep0328). -compile(export_all). do_decode(<<"jid">>, <<"urn:xmpp:jidprep:0">>, El, Opts) -> decode_jidprep(<<"urn:xmpp:jidprep:0">>, Opts, El); do_decode(Name, <<>>, _, _) -> erlang:error({xmpp_codec, {missing_tag_xmlns, Name}}); do_decode(Name, XMLNS, _, _) -> erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}). tags() -> [{<<"jid">>, <<"urn:xmpp:jidprep:0">>}]. do_encode({jidprep, _} = Jid, TopXMLNS) -> encode_jidprep(Jid, TopXMLNS). do_get_name({jidprep, _}) -> <<"jid">>. do_get_ns({jidprep, _}) -> <<"urn:xmpp:jidprep:0">>. pp(jidprep, 1) -> [jid]; pp(_, _) -> no. records() -> [{jidprep, 1}]. decode_jidprep(__TopXMLNS, __Opts, {xmlel, <<"jid">>, _attrs, _els}) -> Jid = decode_jidprep_els(__TopXMLNS, __Opts, _els, <<>>), {jidprep, Jid}. decode_jidprep_els(__TopXMLNS, __Opts, [], Jid) -> decode_jidprep_cdata(__TopXMLNS, Jid); decode_jidprep_els(__TopXMLNS, __Opts, [{xmlcdata, _data} | _els], Jid) -> decode_jidprep_els(__TopXMLNS, __Opts, _els, <<Jid/binary, _data/binary>>); decode_jidprep_els(__TopXMLNS, __Opts, [_ | _els], Jid) -> decode_jidprep_els(__TopXMLNS, __Opts, _els, Jid). encode_jidprep({jidprep, Jid}, __TopXMLNS) -> __NewTopXMLNS = xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jidprep:0">>, [], __TopXMLNS), _els = encode_jidprep_cdata(Jid, []), _attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS), {xmlel, <<"jid">>, _attrs, _els}. decode_jidprep_cdata(__TopXMLNS, <<>>) -> erlang:error({xmpp_codec, {missing_cdata, <<>>, <<"jid">>, __TopXMLNS}}); decode_jidprep_cdata(__TopXMLNS, _val) -> case catch jid:decode(_val) of {'EXIT', _} -> erlang:error({xmpp_codec, {bad_cdata_value, <<>>, <<"jid">>, __TopXMLNS}}); _res -> _res end. encode_jidprep_cdata(_val, _acc) -> [{xmlcdata, jid:encode(_val)} | _acc].
null
https://raw.githubusercontent.com/processone/xmpp/88c43c3cf5843a8a0f76eac390980a3a39c972dd/src/xep0328.erl
erlang
Source: xmpp_codec.spec
Created automatically by XML generator ( fxml_gen.erl ) -module(xep0328). -compile(export_all). do_decode(<<"jid">>, <<"urn:xmpp:jidprep:0">>, El, Opts) -> decode_jidprep(<<"urn:xmpp:jidprep:0">>, Opts, El); do_decode(Name, <<>>, _, _) -> erlang:error({xmpp_codec, {missing_tag_xmlns, Name}}); do_decode(Name, XMLNS, _, _) -> erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}). tags() -> [{<<"jid">>, <<"urn:xmpp:jidprep:0">>}]. do_encode({jidprep, _} = Jid, TopXMLNS) -> encode_jidprep(Jid, TopXMLNS). do_get_name({jidprep, _}) -> <<"jid">>. do_get_ns({jidprep, _}) -> <<"urn:xmpp:jidprep:0">>. pp(jidprep, 1) -> [jid]; pp(_, _) -> no. records() -> [{jidprep, 1}]. decode_jidprep(__TopXMLNS, __Opts, {xmlel, <<"jid">>, _attrs, _els}) -> Jid = decode_jidprep_els(__TopXMLNS, __Opts, _els, <<>>), {jidprep, Jid}. decode_jidprep_els(__TopXMLNS, __Opts, [], Jid) -> decode_jidprep_cdata(__TopXMLNS, Jid); decode_jidprep_els(__TopXMLNS, __Opts, [{xmlcdata, _data} | _els], Jid) -> decode_jidprep_els(__TopXMLNS, __Opts, _els, <<Jid/binary, _data/binary>>); decode_jidprep_els(__TopXMLNS, __Opts, [_ | _els], Jid) -> decode_jidprep_els(__TopXMLNS, __Opts, _els, Jid). encode_jidprep({jidprep, Jid}, __TopXMLNS) -> __NewTopXMLNS = xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jidprep:0">>, [], __TopXMLNS), _els = encode_jidprep_cdata(Jid, []), _attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS), {xmlel, <<"jid">>, _attrs, _els}. decode_jidprep_cdata(__TopXMLNS, <<>>) -> erlang:error({xmpp_codec, {missing_cdata, <<>>, <<"jid">>, __TopXMLNS}}); decode_jidprep_cdata(__TopXMLNS, _val) -> case catch jid:decode(_val) of {'EXIT', _} -> erlang:error({xmpp_codec, {bad_cdata_value, <<>>, <<"jid">>, __TopXMLNS}}); _res -> _res end. encode_jidprep_cdata(_val, _acc) -> [{xmlcdata, jid:encode(_val)} | _acc].
cac09f51e49afae4ff4cfed3e378b203319f89a4b8a026039b4821c0c5778c25
functionally/mantis
Bech32.hs
module Mantra.Command.Bech32 ( command , mainDecode , mainEncode ) where import Control.Monad.IO.Class (MonadIO) import Mantra.Command.Types (Mantra(Bech32Decode, Bech32Encode)) import Mantra.Types (MantraM, foistMantraEither, foistMantraMaybe, printMantra) import qualified Codec.Binary.Bech32 as Bech32 (dataPartFromBytes, dataPartToBytes, decodeLenient, encodeLenient, humanReadablePartFromText, humanReadablePartToText) import qualified Data.ByteString.Base16 as Base16 (decode, encode) import qualified Data.ByteString.Char8 as BS (pack, unpack) import qualified Options.Applicative as O import qualified Data.Text as T (pack, unpack) command :: O.Mod O.CommandFields Mantra command = mconcat [ O.command "bech32-decode" $ O.info ( Bech32Decode <$> O.strArgument (O.metavar "BECH32" <> O.help "The Bech32 text." ) ) (O.progDesc "Decode a Bech32 string.") , O.command "bech32-encode" $ O.info ( Bech32Encode <$> O.strArgument (O.metavar "PREFIX" <> O.help "The human-readable part." ) <*> O.strArgument (O.metavar "DATA" <> O.help "The data part.") ) (O.progDesc "Encode a Bech32 string.") ] mainDecode :: MonadIO m => (String -> MantraM m ()) -> String -> MantraM m () mainDecode debugMantra text = do (humanReadablePart, dataPart) <- foistMantraEither . Bech32.decodeLenient $ T.pack text let humanReadablePart' = T.unpack $ Bech32.humanReadablePartToText humanReadablePart dataPart' <- foistMantraMaybe "Failed decoding data part." $ BS.unpack . Base16.encode <$> Bech32.dataPartToBytes dataPart debugMantra $ "Human-readable part: " ++ humanReadablePart' printMantra dataPart' mainEncode :: MonadIO m => (String -> MantraM m ()) -> String -> String -> MantraM m () mainEncode _ humanReadablePart dataPart = do humanReadablePart' <- foistMantraEither . Bech32.humanReadablePartFromText $ T.pack humanReadablePart datapart' <- foistMantraEither . fmap Bech32.dataPartFromBytes . Base16.decode $ BS.pack dataPart let encoded = T.unpack $ Bech32.encodeLenient humanReadablePart' datapart' printMantra encoded
null
https://raw.githubusercontent.com/functionally/mantis/1cd121202452dcc1bce56ed4b4f41f0e880c9d04/app/Mantra/Command/Bech32.hs
haskell
module Mantra.Command.Bech32 ( command , mainDecode , mainEncode ) where import Control.Monad.IO.Class (MonadIO) import Mantra.Command.Types (Mantra(Bech32Decode, Bech32Encode)) import Mantra.Types (MantraM, foistMantraEither, foistMantraMaybe, printMantra) import qualified Codec.Binary.Bech32 as Bech32 (dataPartFromBytes, dataPartToBytes, decodeLenient, encodeLenient, humanReadablePartFromText, humanReadablePartToText) import qualified Data.ByteString.Base16 as Base16 (decode, encode) import qualified Data.ByteString.Char8 as BS (pack, unpack) import qualified Options.Applicative as O import qualified Data.Text as T (pack, unpack) command :: O.Mod O.CommandFields Mantra command = mconcat [ O.command "bech32-decode" $ O.info ( Bech32Decode <$> O.strArgument (O.metavar "BECH32" <> O.help "The Bech32 text." ) ) (O.progDesc "Decode a Bech32 string.") , O.command "bech32-encode" $ O.info ( Bech32Encode <$> O.strArgument (O.metavar "PREFIX" <> O.help "The human-readable part." ) <*> O.strArgument (O.metavar "DATA" <> O.help "The data part.") ) (O.progDesc "Encode a Bech32 string.") ] mainDecode :: MonadIO m => (String -> MantraM m ()) -> String -> MantraM m () mainDecode debugMantra text = do (humanReadablePart, dataPart) <- foistMantraEither . Bech32.decodeLenient $ T.pack text let humanReadablePart' = T.unpack $ Bech32.humanReadablePartToText humanReadablePart dataPart' <- foistMantraMaybe "Failed decoding data part." $ BS.unpack . Base16.encode <$> Bech32.dataPartToBytes dataPart debugMantra $ "Human-readable part: " ++ humanReadablePart' printMantra dataPart' mainEncode :: MonadIO m => (String -> MantraM m ()) -> String -> String -> MantraM m () mainEncode _ humanReadablePart dataPart = do humanReadablePart' <- foistMantraEither . Bech32.humanReadablePartFromText $ T.pack humanReadablePart datapart' <- foistMantraEither . fmap Bech32.dataPartFromBytes . Base16.decode $ BS.pack dataPart let encoded = T.unpack $ Bech32.encodeLenient humanReadablePart' datapart' printMantra encoded
0483c32914d95caa6f13b73831a5c7c14ab21ddd737d0104020c02eda7147f59
wlitwin/graphv
ogl_intf.ml
module type Buffer = Sigs.BufferS module type S = sig module Buffer : Buffer module Dyn : sig type t = private { mutable arr : Buffer.Float.t; mutable size : int; } type underlying = Buffer.Float.t val create : int -> t val clear : t -> unit val get : t -> int -> float val set : t -> int -> float -> unit val capacity : t -> int val length : t -> int val add_range : t -> int -> int val unsafe_array : t -> underlying module Sub : sig type sub = private { off : int; len : int; t : t } val sub : t -> int -> int -> sub val offset : sub -> int val length : sub -> int val blit : src:sub -> dst:t -> src_start:int -> dst_start:int -> len:int -> unit end end module VertexBuffer : sig type t = { mutable arr : Buffer.Float.t; mutable size : int } val create : unit -> t val clear : t -> unit val iteri : t -> f:(int -> float -> unit) -> unit val iter : t -> f:(float -> unit) -> unit val num_verts : t -> int val capacity : t -> int val iterv : t -> f:(float -> float -> float -> float -> unit) -> unit val check_size : t -> int -> unit val set : t -> int -> float -> float -> float -> float -> unit val unsafe_set : t -> int -> float -> float -> float -> float -> unit val get : t -> int -> float * float * float * float val num_bytes : t -> int val num_floats : t -> int val unsafe_array : t -> Dyn.underlying module Sub : sig type parent = t type nonrec t = { off : int; len : int; t : t; } val empty : t val sub : parent -> int -> int -> t val vertex_offset : t -> int val length : t -> int val blit : src:t -> dst:parent -> src_start:int -> dst_start:int -> len:int -> unit val num_verts : t -> int val create : unit -> t end end module Path : sig type t = { mutable first : int; mutable count : int; mutable closed : bool; mutable nbevel : int; mutable fill : VertexBuffer.Sub.t; mutable stroke : VertexBuffer.Sub.t; mutable winding : Winding.t; mutable convex : bool; } val create : unit -> t val reset : t -> unit val copy : t -> t end type arg type t val create : arg -> t type blending_factor type texture_target type pixel_format type pixel_type type tex_filter type wrap_mode type tex_param_filter type tex_param_wrap type tex_param_filter_param type tex_param_wrap_param type pixel_store_param type enable_cap type depth_function type stencil_op type begin_mode type cull_face_mode type 'a uniform_location type front_face_dir type uniform_type type buffer_target type buffer_usage type error_code type texture type data_type type buffer type buffer_id type enum val zero : blending_factor val zero_ : stencil_op val one : blending_factor val src_color : blending_factor val dst_color : blending_factor val one_minus_src_color : blending_factor val one_minus_dst_color : blending_factor val one_minus_src_alpha : blending_factor val one_minus_dst_alpha : blending_factor val src_alpha_saturate : blending_factor val src_alpha : blending_factor val dst_alpha : blending_factor val texture_2d : texture_target val rgba : pixel_format val luminance : pixel_format val unsigned_byte : pixel_type val nearest_mipmap_nearest : tex_param_filter_param val linear_mipmap_linear : tex_param_filter_param val nearest : tex_param_filter_param val linear : tex_param_filter_param val texture_min_filter : tex_param_filter val texture_mag_filter : tex_param_filter val clamp_to_edge : tex_param_wrap_param val texture_wrap_s : tex_param_wrap val texture_wrap_t : tex_param_wrap val repeat : tex_param_wrap_param val unpack_alignment : pixel_store_param val stencil_test : enable_cap val equal : depth_function val keep : stencil_op val incr : stencil_op val triangle_strip : begin_mode val triangle_fan : begin_mode val always : depth_function val notequal : depth_function val cull_face_enum : enable_cap val back : cull_face_mode val ccw : front_face_dir val blend : enable_cap val depth_test : enable_cap val front : cull_face_mode val incr_wrap : stencil_op val decr_wrap : stencil_op val scissor_test : enable_cap val texture0 : enum val float : data_type val array_buffer : buffer_target val triangles : begin_mode val stream_draw : buffer_usage val invalid_enum : error_code val cull_face : t -> cull_face_mode -> unit val front_face : t -> front_face_dir -> unit val texture_equal : t -> texture option -> texture option -> bool val bind_texture : t -> texture_target -> texture option -> unit val active_texture : t -> enum -> unit val stencil_mask : t -> int -> unit val stencil_func : t -> depth_function -> int -> int -> unit val stencil_op : t -> stencil_op -> stencil_op -> stencil_op -> unit val stencil_op_separate : t -> cull_face_mode -> stencil_op -> stencil_op -> stencil_op -> unit val blending_factor_equal : blending_factor -> blending_factor -> bool val blend_func_separate : t -> blending_factor -> blending_factor -> blending_factor -> blending_factor -> unit val gen_textures : t -> int -> texture array val pixel_storei : t -> pixel_store_param -> int -> unit val enable_vertex_attrib_array : t -> int -> unit val disable_vertex_attrib_array : t -> int -> unit val vertex_attrib_pointer : t -> int -> int -> data_type -> bool -> int -> int -> unit type program val use_program : t -> program -> unit val uniform1i : t -> int uniform_location -> int -> unit val uniform2fv : t -> [`vec2] uniform_location -> Buffer.Float.t -> unit val tex_image2d : t -> texture_target -> int -> pixel_format -> int -> int -> int -> pixel_format -> pixel_type -> Buffer.UByte.t -> unit val tex_sub_image2d : t -> texture_target -> int -> int -> int -> int -> int -> pixel_format -> pixel_type -> Buffer.UByte.t -> unit val tex_parameteri_1 : t -> texture_target -> tex_param_filter -> tex_param_filter_param -> unit val tex_parameteri_2 : t -> texture_target -> tex_param_wrap -> tex_param_wrap_param -> unit val generate_mipmap : t -> texture_target -> unit val delete_textures : t -> texture array -> unit val uniform4fv : t -> [`vec4] uniform_location -> Buffer.Float.t -> unit val buffer_data : t -> buffer_target -> Buffer.Float.t -> int -> buffer_usage -> unit val bind_buffer : t -> buffer_target -> buffer_id -> unit val draw_arrays : t -> begin_mode -> int -> int -> unit val color_mask : t -> bool -> bool -> bool -> bool -> unit val enable : t -> enable_cap -> unit val disable : t -> enable_cap -> unit val finish : t -> unit val get_uniform_location : t -> program -> string -> 'a uniform_location val check_error : t -> string -> unit type locs = { frag : [`vec4] uniform_location; tex : int uniform_location; view_size : [`vec2] uniform_location; vert_buf : buffer_id; } val create_program : t -> (program * locs) option end with type Buffer . UByte.t = B.ubyte_t and type . Float.t with type Buffer.UByte.t = B.ubyte_t and type Buffer.Float.t = B.float_t *)
null
https://raw.githubusercontent.com/wlitwin/graphv/d0a09575c5ff5ee3727c222dd6130d22e4cf62d9/gles3/core/ogl_intf.ml
ocaml
module type Buffer = Sigs.BufferS module type S = sig module Buffer : Buffer module Dyn : sig type t = private { mutable arr : Buffer.Float.t; mutable size : int; } type underlying = Buffer.Float.t val create : int -> t val clear : t -> unit val get : t -> int -> float val set : t -> int -> float -> unit val capacity : t -> int val length : t -> int val add_range : t -> int -> int val unsafe_array : t -> underlying module Sub : sig type sub = private { off : int; len : int; t : t } val sub : t -> int -> int -> sub val offset : sub -> int val length : sub -> int val blit : src:sub -> dst:t -> src_start:int -> dst_start:int -> len:int -> unit end end module VertexBuffer : sig type t = { mutable arr : Buffer.Float.t; mutable size : int } val create : unit -> t val clear : t -> unit val iteri : t -> f:(int -> float -> unit) -> unit val iter : t -> f:(float -> unit) -> unit val num_verts : t -> int val capacity : t -> int val iterv : t -> f:(float -> float -> float -> float -> unit) -> unit val check_size : t -> int -> unit val set : t -> int -> float -> float -> float -> float -> unit val unsafe_set : t -> int -> float -> float -> float -> float -> unit val get : t -> int -> float * float * float * float val num_bytes : t -> int val num_floats : t -> int val unsafe_array : t -> Dyn.underlying module Sub : sig type parent = t type nonrec t = { off : int; len : int; t : t; } val empty : t val sub : parent -> int -> int -> t val vertex_offset : t -> int val length : t -> int val blit : src:t -> dst:parent -> src_start:int -> dst_start:int -> len:int -> unit val num_verts : t -> int val create : unit -> t end end module Path : sig type t = { mutable first : int; mutable count : int; mutable closed : bool; mutable nbevel : int; mutable fill : VertexBuffer.Sub.t; mutable stroke : VertexBuffer.Sub.t; mutable winding : Winding.t; mutable convex : bool; } val create : unit -> t val reset : t -> unit val copy : t -> t end type arg type t val create : arg -> t type blending_factor type texture_target type pixel_format type pixel_type type tex_filter type wrap_mode type tex_param_filter type tex_param_wrap type tex_param_filter_param type tex_param_wrap_param type pixel_store_param type enable_cap type depth_function type stencil_op type begin_mode type cull_face_mode type 'a uniform_location type front_face_dir type uniform_type type buffer_target type buffer_usage type error_code type texture type data_type type buffer type buffer_id type enum val zero : blending_factor val zero_ : stencil_op val one : blending_factor val src_color : blending_factor val dst_color : blending_factor val one_minus_src_color : blending_factor val one_minus_dst_color : blending_factor val one_minus_src_alpha : blending_factor val one_minus_dst_alpha : blending_factor val src_alpha_saturate : blending_factor val src_alpha : blending_factor val dst_alpha : blending_factor val texture_2d : texture_target val rgba : pixel_format val luminance : pixel_format val unsigned_byte : pixel_type val nearest_mipmap_nearest : tex_param_filter_param val linear_mipmap_linear : tex_param_filter_param val nearest : tex_param_filter_param val linear : tex_param_filter_param val texture_min_filter : tex_param_filter val texture_mag_filter : tex_param_filter val clamp_to_edge : tex_param_wrap_param val texture_wrap_s : tex_param_wrap val texture_wrap_t : tex_param_wrap val repeat : tex_param_wrap_param val unpack_alignment : pixel_store_param val stencil_test : enable_cap val equal : depth_function val keep : stencil_op val incr : stencil_op val triangle_strip : begin_mode val triangle_fan : begin_mode val always : depth_function val notequal : depth_function val cull_face_enum : enable_cap val back : cull_face_mode val ccw : front_face_dir val blend : enable_cap val depth_test : enable_cap val front : cull_face_mode val incr_wrap : stencil_op val decr_wrap : stencil_op val scissor_test : enable_cap val texture0 : enum val float : data_type val array_buffer : buffer_target val triangles : begin_mode val stream_draw : buffer_usage val invalid_enum : error_code val cull_face : t -> cull_face_mode -> unit val front_face : t -> front_face_dir -> unit val texture_equal : t -> texture option -> texture option -> bool val bind_texture : t -> texture_target -> texture option -> unit val active_texture : t -> enum -> unit val stencil_mask : t -> int -> unit val stencil_func : t -> depth_function -> int -> int -> unit val stencil_op : t -> stencil_op -> stencil_op -> stencil_op -> unit val stencil_op_separate : t -> cull_face_mode -> stencil_op -> stencil_op -> stencil_op -> unit val blending_factor_equal : blending_factor -> blending_factor -> bool val blend_func_separate : t -> blending_factor -> blending_factor -> blending_factor -> blending_factor -> unit val gen_textures : t -> int -> texture array val pixel_storei : t -> pixel_store_param -> int -> unit val enable_vertex_attrib_array : t -> int -> unit val disable_vertex_attrib_array : t -> int -> unit val vertex_attrib_pointer : t -> int -> int -> data_type -> bool -> int -> int -> unit type program val use_program : t -> program -> unit val uniform1i : t -> int uniform_location -> int -> unit val uniform2fv : t -> [`vec2] uniform_location -> Buffer.Float.t -> unit val tex_image2d : t -> texture_target -> int -> pixel_format -> int -> int -> int -> pixel_format -> pixel_type -> Buffer.UByte.t -> unit val tex_sub_image2d : t -> texture_target -> int -> int -> int -> int -> int -> pixel_format -> pixel_type -> Buffer.UByte.t -> unit val tex_parameteri_1 : t -> texture_target -> tex_param_filter -> tex_param_filter_param -> unit val tex_parameteri_2 : t -> texture_target -> tex_param_wrap -> tex_param_wrap_param -> unit val generate_mipmap : t -> texture_target -> unit val delete_textures : t -> texture array -> unit val uniform4fv : t -> [`vec4] uniform_location -> Buffer.Float.t -> unit val buffer_data : t -> buffer_target -> Buffer.Float.t -> int -> buffer_usage -> unit val bind_buffer : t -> buffer_target -> buffer_id -> unit val draw_arrays : t -> begin_mode -> int -> int -> unit val color_mask : t -> bool -> bool -> bool -> bool -> unit val enable : t -> enable_cap -> unit val disable : t -> enable_cap -> unit val finish : t -> unit val get_uniform_location : t -> program -> string -> 'a uniform_location val check_error : t -> string -> unit type locs = { frag : [`vec4] uniform_location; tex : int uniform_location; view_size : [`vec2] uniform_location; vert_buf : buffer_id; } val create_program : t -> (program * locs) option end with type Buffer . UByte.t = B.ubyte_t and type . Float.t with type Buffer.UByte.t = B.ubyte_t and type Buffer.Float.t = B.float_t *)
4f4cf905b3a0b8c83de3075446723d4861a1777fff778f69295ae7f084263028
kudu-dynamics/blaze
SolverSpec.hs
# OPTIONS_GHC -fno - warn - incomplete - uni - patterns # HLINT ignore " Evaluate " HLINT ignore " Use head " HLINT ignore " Reduce duplication " HLINT ignore " Eta reduce " module Blaze.Pil.SolverSpec where import Blaze.Prelude hiding (const, numerator, denominator) import Blaze.Pil.Solver hiding (pilVar) import Blaze.Pil.Construct import qualified Blaze.Types.Pil as Pil import qualified Data.SBV.Trans as SBV import qualified Data.HashMap.Strict as HashMap import Data.SBV.Dynamic hiding (Solver) import Blaze.Types.Pil.Checker as Ch hiding (signed) import Blaze.Pil.Checker (checkStmts) import Data.SBV.Trans ( (.>=) , (.<) , (.&&) ) import Data.SBV.Internals (unSBV) import Test.Hspec import Numeric (showHex) type SolverOutput = Either SolverError (SolverResult, [SolverError]) -- | Get a concrete variable from solver output. getVar :: Text -> SolverOutput -> Maybe CV getVar k r = r ^? _Right . _1 . #_Sat . at k . _Just getInt :: CV -> Maybe Integer getInt (CV _kind val) = case val of CInteger x -> Just x _ -> Nothing getVal :: Text -> SolverOutput -> Maybe Integer getVal k r = getVar k r >>= getInt spec :: Spec spec = describe "Blaze.Pil.SolverSpec" $ do let solveSolver m = checkSatWith_ SBV.z3 False AbortOnError m signed32 = Ch.DSType $ Ch.TInt (bw 32) (Just True) signed64 = Ch.DSType $ Ch.TInt (bw 64) (Just True) unsigned32 = Ch.DSType $ Ch.TInt (bw 32) (Just False) unsigned64 = Ch.DSType $ Ch.TInt (bw 64) (Just False) unsigned8 = Ch.DSType $ Ch.TInt (bw 8) (Just False) unsigned4 = Ch.DSType $ Ch.TInt (bw 4) (Just False) carry = Ch.DSType Ch.TBool bw = Just char = Ch.DSType $ Ch.TChar (Just 8) float = Ch.DSType $ Ch.TFloat (bw 80) tbool = Ch.DSType Ch.TBool pointer = Ch . DSType . Ch . TPointer ( bw 64 ) bitVec = Ch.DSType . Ch.TBitVector floatEqual x y = unSBV $ (toSFloat' x .>= toSFloat' y) .&& (toSFloat' x .< SBV.fpAdd SBV.sRoundNearestTiesToAway (toSFloat' y) (toSFloat' . constFloat $ 0.0000001)) -- x >= y && x < y + 0.0000..... context "aux ops" $ do context "signExtend" $ do let cmd = do a <- newSymVar "a" (KBounded True 32) b <- newSymVar "b" (KBounded True 64) let sE = signExtend 64 a r = constInt 32 9 constrain $ r `svEqual` a constrain $ sE `svEqual` b vars = [("a", CV (KBounded True 32) (CInteger 9)), ("b", CV (KBounded True 64) (CInteger 9))] r <- runIO $ solveSolver cmd it "extends signed value so constraint on 32-bit number is also a constraint on 64-bit number" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "zeroExtend" $ do let cmd = do a <- newSymVar "a" (KBounded False 32) b <- newSymVar "b" (KBounded False 64) let zE = zeroExtend 64 a r = constWord 32 9 constrain $ r `svEqual` a constrain $ zE `svEqual` b vars = [("a", CV (KBounded False 32) (CInteger 9)), ("b", CV (KBounded False 64) (CInteger 9))] r <- runIO $ solveSolver cmd it "extends unsigned value so constraint on 32-bit number is also a constraint on 64-bit number" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "matchBoundedWidth" $ do let cmd = do a <- newSymVar "a" (KBounded True 32) b <- newSymVar "b" (KBounded True 32) constrain $ b `svEqual` (a `matchBoundedWidth` b) vars = [("a", CV (KBounded True 32) (CInteger 0)), ("b", CV (KBounded True 32) (CInteger 0))] r <- runIO $ solveSolver cmd it "should find a equals b after matching width" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "matchBoundedWidth" $ do let cmd = do a <- newSymVar "a" (KBounded True 64) b <- newSymVar "b" (KBounded True 32) constrain $ a `svEqual` (a `matchBoundedWidth` b) vars = [("a", CV (KBounded True 64) (CInteger 0)), ("b", CV (KBounded True 32) (CInteger 0))] r <- runIO $ solveSolver cmd it "should find a equals b after matching width" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "matchSign" $ do let cmd = do a <- newSymVar "a" (KBounded True 64) b <- newSymVar "b" (KBounded False 64) constrain $ a `svEqual` (a `matchSign` b) vars = [("a", CV (KBounded True 64) (CInteger 0)), ("b", CV (KBounded False 64) (CInteger 0))] r <- runIO $ solveSolver cmd it "should find a equals b after matching sign" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "Most Significant Bit" $ do let cmd = do a <- newSymVar "a" (KBounded True 4) b <- newSymVar "b" KBool constrain $ a `svEqual` constInt 4 7 constrain $ b `svEqual` msb a vars = [("a", CV (KBounded True 4) (CInteger 7)), ("b", CV KBool (CInteger 0))] r <- runIO $ solveSolver cmd it "should find the msb is zero" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "Most Significant Bit" $ do let cmd = do a <- newSymVar "a" (KBounded True 4) b <- newSymVar "b" KBool constrain $ a `svEqual` constInt 4 8 constrain $ b `svEqual` msb a vars = [("a", CV (KBounded True 4) (CInteger $ -8)), ("b", CV KBool (CInteger 1))] r <- runIO $ solveSolver cmd it "should find the msb is one" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "declarePilVars" $ do let runDecl tenvTuples = do r <- runSolverWith SBV.z3 declarePilVars (emptyState, SolverCtx (HashMap.fromList tenvTuples) mempty False AbortOnError) case r of Left _ -> return $ Left () Right (_, ss) -> return . Right $ ( kindOf <$> ss ^. #varMap , ss ^. #varNames ) context "declarePilVars" $ do let tenv = [(pilVar "a", char)] vmap = [(pilVar "a", KBounded False 8)] vnames = [(pilVar "a", "a")] r <- runIO $ runDecl tenv it "put single pilvar in varMap and varNames in state" $ do r `shouldBe` Right (HashMap.fromList vmap, HashMap.fromList vnames) context "declarePilVars" $ do let tenv = [(pilVar "a", Ch.DSVar $ Sym 0)] r <- runIO $ runDecl tenv it "fail if a var is just a sym" $ do r `shouldBe` Left () context "declarePilVars" $ do let tenv = [ (pilVar "a", char) , (pilVar "b", signed32) , (pilVar "c", Ch.DSType Ch.TBool) ] vmap = [ (pilVar "a", KBounded False 8) , (pilVar "b", KBounded True 32) , (pilVar "c", KBool) ] vnames = [ (pilVar "a", "a") , (pilVar "b", "b") , (pilVar "c", "c") ] r <- runIO $ runDecl tenv it "put many pilvars in varMap and varNames in state" $ do r `shouldBe` Right (HashMap.fromList vmap, HashMap.fromList vnames) context "solve Expr/Stmt" $ do let runSolveCmd tenvTuples cmd = do r <- flip (checkSatWith SBV.z3) (emptyState, SolverCtx (HashMap.fromList tenvTuples) mempty False AbortOnError) $ declarePilVars >> cmd case r of Left e -> return $ Left e Right (x, ss) -> return . Right $ ( x , ss ^. #errors ) context "solveExpr: ADD" $ do let tenv = [] arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 1 ) -- . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.CONST . Pil.ConstOp $ 11 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 88 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.ADD $ Pil.AddOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 99 rvars = [] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) let helper op (inw, l, r) (outw, outv) = do let tenv = [] arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 1 ) -- . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo inw $ Sym 2, Just (bitVec $ Just inw)) . Pil.CONST . Pil.ConstOp $ l arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo inw $ Sym 1, Just (bitVec $ Just inw)) . Pil.CONST . Pil.ConstOp $ r expr = Ch.InfoExpression (Ch.SymInfo outw $ Sym 0, Just (bitVec $ Just outw)) $ op arg1 arg2 cmd = do res <- solveExpr expr constrain $ res `svEqual` constWord outw outv rvars = [] errs = [] res <- runIO $ runSolveCmd tenv cmd let hex n = "0x" <> showHex n "" it (hex l <> " " <> hex r <> " ~> " <> hex outv) $ do res `shouldBe` Right (Sat $ HashMap.fromList rvars, errs) in do context "ADD_WILL_CARRY" $ do context "two constants of the same size" $ do let helper' = helper (\l r -> Pil.ADD_WILL_CARRY $ Pil.AddWillCarryOp l r) helper' (32, 0x00000000, 0x00000000) (1, 0) helper' (32, 0x00000000, 0x00000001) (1, 0) helper' (32, 0x00000000, 0xffffffff) (1, 0) helper' (32, 0x7fffffff, 0x00000000) (1, 0) helper' (32, 0x7fffffff, 0x00000001) (1, 0) helper' (32, 0x7fffffff, 0xffffffff) (1, 1) helper' (32, 0x80000000, 0x00000000) (1, 0) helper' (32, 0x80000000, 0x00000001) (1, 0) helper' (32, 0x80000000, 0xffffffff) (1, 1) helper' (32, 0xffffffff, 0x00000000) (1, 0) helper' (32, 0xffffffff, 0x00000001) (1, 1) helper' (32, 0xffffffff, 0xffffffff) (1, 1) helper' (8, 0x00, 0x00) (1, 0) helper' (8, 0x00, 0x01) (1, 0) helper' (8, 0x00, 0xff) (1, 0) helper' (8, 0x7f, 0x00) (1, 0) helper' (8, 0x7f, 0x01) (1, 0) helper' (8, 0x7f, 0xff) (1, 1) helper' (8, 0x80, 0x00) (1, 0) helper' (8, 0x80, 0x01) (1, 0) helper' (8, 0x80, 0xff) (1, 1) helper' (8, 0xff, 0x00) (1, 0) helper' (8, 0xff, 0x01) (1, 1) helper' (8, 0xff, 0xff) (1, 1) context "ADD_WILL_OVERFLOW" $ do context "two constants of the same size" $ do let helper' = helper (\l r -> Pil.ADD_WILL_OVERFLOW $ Pil.AddWillOverflowOp l r) helper' (32, 0x00000000, 0x00000000) (1, 0) helper' (32, 0x00000000, 0x00000001) (1, 0) helper' (32, 0x00000000, 0xffffffff) (1, 0) helper' (32, 0x7fffffff, 0x00000000) (1, 0) helper' (32, 0x7fffffff, 0x00000001) (1, 1) helper' (32, 0x7fffffff, 0xffffffff) (1, 0) helper' (32, 0x80000000, 0x00000000) (1, 0) helper' (32, 0x80000000, 0x00000001) (1, 0) helper' (32, 0x80000000, 0xffffffff) (1, 1) helper' (32, 0xffffffff, 0x00000000) (1, 0) helper' (32, 0xffffffff, 0x00000001) (1, 0) helper' (32, 0xffffffff, 0xffffffff) (1, 0) helper' (8, 0x00, 0x00) (1, 0) helper' (8, 0x00, 0x01) (1, 0) helper' (8, 0x00, 0xff) (1, 0) helper' (8, 0x7f, 0x00) (1, 0) helper' (8, 0x7f, 0x01) (1, 1) helper' (8, 0x7f, 0xff) (1, 0) helper' (8, 0x80, 0x00) (1, 0) helper' (8, 0x80, 0x01) (1, 0) helper' (8, 0x80, 0xff) (1, 1) helper' (8, 0xff, 0x00) (1, 0) helper' (8, 0xff, 0x01) (1, 0) helper' (8, 0xff, 0xff) (1, 0) context "SUB_WILL_OVERFLOW" $ do context "two constants of the same size" $ do let helper' = helper (\l r -> Pil.SUB_WILL_OVERFLOW $ Pil.SubWillOverflowOp l r) helper' (32, 0x00000000, 0x00000000) (1, 0) helper' (32, 0x00000000, 0x00000001) (1, 0) helper' (32, 0x00000000, 0xffffffff) (1, 0) helper' (32, 0x7fffffff, 0x00000000) (1, 0) helper' (32, 0x7fffffff, 0x00000001) (1, 0) helper' (32, 0x7fffffff, 0xffffffff) (1, 1) helper' (32, 0x80000000, 0x00000000) (1, 0) helper' (32, 0x80000000, 0x00000001) (1, 1) helper' (32, 0x80000000, 0xffffffff) (1, 0) helper' (32, 0xffffffff, 0x00000000) (1, 0) helper' (32, 0xffffffff, 0x00000001) (1, 0) helper' (32, 0xffffffff, 0xffffffff) (1, 0) helper' (8, 0x00, 0x00) (1, 0) helper' (8, 0x00, 0x01) (1, 0) helper' (8, 0x00, 0xff) (1, 0) helper' (8, 0x7f, 0x00) (1, 0) helper' (8, 0x7f, 0x01) (1, 0) helper' (8, 0x7f, 0xff) (1, 1) helper' (8, 0x80, 0x00) (1, 0) helper' (8, 0x80, 0x01) (1, 1) helper' (8, 0x80, 0xff) (1, 0) helper' (8, 0xff, 0x00) (1, 0) helper' (8, 0xff, 0x01) (1, 0) helper' (8, 0xff, 0xff) (1, 0) let helper (baseW, base) (indexW, index) stride (outw, outv) = do let tenv = [] base' = Ch.InfoExpression (Ch.SymInfo baseW $ Sym 0, Just (bitVec $ Just baseW)) . Pil.CONST . Pil.ConstOp $ base index' = Ch.InfoExpression (Ch.SymInfo indexW $ Sym 1, Just (bitVec $ Just indexW)) . Pil.CONST . Pil.ConstOp $ index expr = Ch.InfoExpression (Ch.SymInfo outw $ Sym 3, Just (bitVec $ Just outw)) . Pil.ARRAY_ADDR $ Pil.ArrayAddrOp base' index' stride cmd = do res <- solveExpr expr constrain $ res `svEqual` constWord outw outv rvars = [] errs = [] res <- runIO $ runSolveCmd tenv cmd let hex n = let n' = fromIntegral n :: Word64 in (if n' >= 0 then "0x" else "-0x") <> showHex (abs n') "" it (hex base <> "[" <> hex index <> " * " <> hex stride <> " bits] ~> " <> hex outv) $ do res `shouldBe` Right (Sat $ HashMap.fromList rvars, errs) in do context "ARRAY_ADDRESS" $ do context "all constants" $ do let base = fromIntegral (0xdeadbeefdeadbeef :: Word64) :: Int64 res = 0xdeadbeefdeadbf3f helper (64, base) (32, 5) 16 (64, res) helper (64, base) ( 8, 5) 16 (64, res) helper (64, base) ( 3, 5) 16 (64, res) context "solveExpr: VAR" $ do let tenv = [(pilVar "a", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 88 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.ADD $ Pil.AddOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 99 rvars = [("a", CV (KBounded False 8) (CInteger 11))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "add one constant and one var" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: SUB" $ do let tenv = [(pilVar "a", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 2 , Just char ) . Pil . CONST . Pil . $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.SUB $ Pil.SubOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 77 rvars = [("a", CV (KBounded False 8) (CInteger 88))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: DIVS" $ do let tenv = [(pilVar "a", char)] numerator = 88 expected = 8 arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 2 , Just char ) . Pil . CONST . Pil . $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ numerator expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.DIVS $ Pil.DivsOp arg2 arg1 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 expected rvsMatch [("a", CV (KBounded False 8) (CInteger denominator))] = denominator /= 0 && numerator `div` denominator == expected rvsMatch _ = False r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldSatisfy` \case Right (Sat rvs, []) -> rvsMatch $ HashMap.toList rvs _ -> False context "solveExpr: MODS" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ 93 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just signed32) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.MODS $ Pil.ModsOp arg1 arg2 cmd = do r <- solveExpr expr rArg0 <- solveExpr arg0 constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 32) (CInteger 5))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive numbers" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: MODS" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ -93 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just signed32) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.MODS $ Pil.ModsOp arg1 arg2 cmd = do r <- solveExpr expr rArg0 <- solveExpr arg0 constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 32) (CInteger $ -5))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive numbers" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: MODU" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 303 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 100 expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.MODU $ Pil.ModuOp arg1 arg2 cmd = do r <- solveExpr expr rArg0 <- solveExpr arg0 constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive numbers" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: MUL" $ do let tenv = [(pilVar "a", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 2 , Just char ) . Pil . CONST . Pil . $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.MUL $ Pil.MulOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 77 rvars = [("a", CV (KBounded False 8) (CInteger 7))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: INT_TO_FLOAT" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 42 arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 80 $ Sym 1, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 80 $ Sym 0, Just float) . Pil.INT_TO_FLOAT $ Pil.IntToFloatOp arg0 cmd = do r <- solveExpr expr rArg1 <- solveExpr arg1 constrain $ rArg1 `svEqual` r rvars = [("a", CV KDouble (CDouble 42.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: CMP_SGE" $ do let tenv = [(pilVar "x", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "x" arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.CMP_SGE $ Pil.CmpSgeOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` svBool True r <- runIO $ runSolveCmd tenv cmd it "should provide a value x, where x >= 11" $ do r `shouldSatisfy` maybe False (>= 11) . getVal "x" context "solveExpr: CMP_SGT & CMP_SLT" $ do let tenv = [(pilVar "x", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "x" arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 arg3 :: DSTExpression arg3 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 13 expr0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.CMP_SGT $ Pil.CmpSgtOp arg1 arg2 expr1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.CMP_SLT $ Pil.CmpSltOp arg1 arg3 cmd = do r <- solveExpr expr0 r2 <- solveExpr expr1 constrain $ r `svEqual` svBool True constrain $ r2 `svEqual` svBool True r <- runIO $ runSolveCmd tenv cmd it "should provide a value x bound by 11 < x < 13" $ do getVal "x" r `shouldBe` Just 12 context "solveExpr: FADD" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 11.0 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FADD $ Pil.FaddOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 14.3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: CEIL" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.CEIL $ Pil.CeilOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 4.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FABS" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ -3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FABS $ Pil.FabsOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FLOOR" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FLOOR $ Pil.FloorOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FLOAT_TO_INT" $ do let tenv = [(pilVar "a", unsigned64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 2, Just unsigned64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 80 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.0 expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just unsigned64) . Pil.FLOAT_TO_INT $ Pil.FloatToIntOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 64) (CInteger 3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FNEG" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FNEG $ Pil.FnegOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble $ -3.3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FSQRT" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.0 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FSQRT $ Pil.FsqrtOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 2.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FTrunc" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FLOOR $ Pil.FloorOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive number" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FTrunc" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ -3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FTRUNC $ Pil.FtruncOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble $ -3.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "negative number" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FDIV" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 12.3 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FDIV $ Pil.FdivOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.0000000000000004))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FMUL" $ do let tenv = [(pilVar "a", float) , (pilVar "b", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" argEq :: DSTExpression argEq = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "b" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.0 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FMUL $ Pil.FmulOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr rArgEq <- solveExpr argEq constrain $ rArg0 `svEqual` r constrain $ rArgEq `svEqual` (rArg0 `floatEqual` constFloat 12.6) rvars = [("a", CV KDouble (CDouble 12.600000000000001)) , ("b", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FSUB" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 12.3 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FSUB $ Pil.FsubOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 8.200000000000001))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_E" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_E $ Pil.FcmpEOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_GE" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_GE $ Pil.FcmpGeOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_GT" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 5.2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_GT $ Pil.FcmpGtOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_LE" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.5 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_LE $ Pil.FcmpLeOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_LT" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 2.0 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_LT $ Pil.FcmpLtOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_NE" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.0 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_NE $ Pil.FcmpNeOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_O" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ SBV.nan arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_O $ Pil.FcmpOOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_UO" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ SBV.nan arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_UO $ Pil.FcmpUoOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: CMP_E" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.CONST . Pil.ConstOp $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.CMP_E $ Pil.CmpEOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: LOW_PART" $ do let tenv = [(pilVar "a", unsigned8)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just unsigned8) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned8) . Pil.CONST . Pil.ConstOp $ 271 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just unsigned8) . Pil.LOW_PART $ Pil.LowPartOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 8) (CInteger 15))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: AND" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 92 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.AND $ Pil.AndOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 12))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: OR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 92 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.OR $ Pil.OrOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 95))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: TEST_BIT" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just tbool) . Pil.TEST_BIT $ Pil.TestBitOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: XOR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 92 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.XOR $ Pil.XorOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 83))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ROL" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.ROL $ Pil.RolOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 8))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ROR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.ROR $ Pil.RorOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 536870912))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: LSR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.LSR $ Pil.LsrOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: LSL" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.LSL $ Pil.LslOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 16))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: NEG" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ 2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.NEG $ Pil.NegOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 32) (CInteger $ -2))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: NOT" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.NOT $ Pil.NotOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 4294967293))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) let helper op (inw, x) (outw, outv) = do let tenv = [] arg :: DSTExpression arg = Ch.InfoExpression (Ch.SymInfo inw $ Sym 1, Just (bitVec $ Just inw)) . Pil.CONST . Pil.ConstOp $ x expr = Ch.InfoExpression (Ch.SymInfo outw $ Sym 0, Just (bitVec $ Just outw)) $ op arg cmd = do res <- solveExpr expr constrain $ res `svEqual` constWord outw outv rvars = [] errs = [] res <- runIO $ runSolveCmd tenv cmd let hex n = let n' = fromIntegral n :: Word64 in (if n' >= 0 then "0x" else "-0x") <> showHex (abs n') "" it (hex x <> " ~> " <> hex outv) $ do res `shouldBe` Right (Sat $ HashMap.fromList rvars, errs) in do context "POPCNT" $ do context "one constant" $ do let helper' = helper (Pil.POPCNT . Pil.PopcntOp) helper' (64, -0x5335533553355336) (8, 32) helper' (64, -0x0000000000000001) (8, 64) helper' (64, -0x8000000000000000) (8, 1) helper' (32, 0x00000000) (8, 0) helper' (32, 0x00000001) (8, 1) helper' (32, 0x80000000) (8, 1) helper' (32, 0xf1f1f1f1) (8, 20) helper' (32, 0xffffffff) (8, 32) helper' (16, 0x0000) (8, 0) helper' (16, 0x0001) (8, 1) helper' (16, 0x8000) (8, 1) helper' (16, 0xf1f1) (8, 10) helper' (16, 0xffff) (8, 16) helper' (8, 0x0000) (8, 0) helper' (8, 0x01) (8, 1) helper' (8, 0x80) (8, 1) helper' (8, 0xf1) (8, 5) helper' (8, 0xff) (8, 8) context "solveExpr: SX" $ do let tenv = [(pilVar "a", signed64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 3, Just signed64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ -2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just signed64) . Pil.SX $ Pil.SxOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 64) (CInteger $ -2))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "32 to 64 bit, negative value" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: SX" $ do let tenv = [(pilVar "a", signed64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 3, Just signed64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ 2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just signed64) . Pil.SX $ Pil.SxOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 64) (CInteger 2))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "32 to 64 bit, positive value" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ZX" $ do let tenv = [(pilVar "a", unsigned64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 3, Just unsigned64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 42 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just unsigned64) . Pil.ZX $ Pil.ZxOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 64) (CInteger 42))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "32 to 64 bit" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ASR" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ -2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.ASR $ Pil.AsrOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r -- TODO: is this correct? rvars = [("a", CV (KBounded True 32) (CInteger $ -1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) TODO : All these tests could use a CONST_BOOL pil instruction for the carry : context "solveExpr: ADC" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 34 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 22 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.ADC $ Pil.AdcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 57))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: SBB" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 34 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 22 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.SBB $ Pil.SbbOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 11))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RLC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RLC $ Pil.RlcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 15))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RLC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ False expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RLC $ Pil.RlcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 14))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 0" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RRC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RRC $ Pil.RrcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 15))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RRC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ False expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RRC $ Pil.RrcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 7))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 0" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveStmt:" $ do context "Pil.Def" $ do let tenv = [(pilVar "a", bitVec (bw 32))] stmts' = [def "a" $ const 888 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, stmtInfoExpr) = (tReport ^. #symTypedStmts) !! 0 solveStmt stmtInfoExpr rvars = [("a", CV (KBounded False 32) (CInteger 888))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Def" $ do let tenv = [ (pilVar "a", bitVec (bw 32)) , (pilVar "b", bitVec (bw 32)) ] stmts' = [ def "a" $ const 888 4 , def "b" $ var "a" 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, defA) = (tReport ^. #symTypedStmts) !! 0 let (_, defB) = (tReport ^. #symTypedStmts) !! 1 solveStmt defA solveStmt defB rvars = [ ("a", CV (KBounded False 32) (CInteger 888)) , ("b", CV (KBounded False 32) (CInteger 888)) ] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var equal to another" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) eTReport ` shouldBe ` ( Left $ Ch . UnhandledExpr ) context "Pil.Def" $ do let tenv = [ (pilVar "a", bitVec (bw 32)) , (pilVar "b", bitVec (bw 32)) , (pilVar "c", bitVec (bw 32)) , (pilVar "d", bitVec (bw 32)) ] stmts' = [ def "a" $ const 888 4 , def "b" $ var "a" 4 , def "c" $ var "b" 4 , def "d" $ var "c" 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, defA) = (tReport ^. #symTypedStmts) !! 0 (_, defB) = (tReport ^. #symTypedStmts) !! 1 (_, defC) = (tReport ^. #symTypedStmts) !! 2 (_, defD) = (tReport ^. #symTypedStmts) !! 3 solveStmt defA solveStmt defB solveStmt defC solveStmt defD rvars = [ ("a", CV (KBounded False 32) (CInteger 888)) , ("b", CV (KBounded False 32) (CInteger 888)) , ("c", CV (KBounded False 32) (CInteger 888)) , ("d", CV (KBounded False 32) (CInteger 888)) ] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var equal to another" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Def" $ do let tenv = [(pilVar "a", tbool)] stmts' = [def "a" $ const 888 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, stmtInfoExpr) = (tReport ^. #symTypedStmts) !! 0 solveStmt stmtInfoExpr errs = [ StmtError { stmtIndex = 0 , stmtErr = GuardError "guardSameKind" [KBool, KBounded False 32] "not same kind" }] r <- runIO $ runSolveCmd tenv cmd it "mismatch variables" $ do fmap snd r `shouldBe` Right errs context "Pil.Constraint" $ do let tenv = [(pilVar "a", bitVec (bw 32))] stmts' = [constraint $ cmpE (var "a" 4) (const 42 4) 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, stmtInfoExpr) = (tReport ^. #symTypedStmts) !! 0 solveStmt stmtInfoExpr rvars = [("a", CV (KBounded False 32) (CInteger 42))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Store/Load" $ do let tenv = [(pilVar "a", unsigned32)] ptr = constPtr 0xdeadbeef 4 stmts' = [ store ptr $ const 42 4 , def "a" $ load ptr 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, storeStmt) = (tReport ^. #symTypedStmts) !! 0 let (_, loadStmt) = (tReport ^. #symTypedStmts) !! 1 solveStmt storeStmt solveStmt loadStmt rvars = [("a", CV (KBounded False 32) (CInteger 42))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "one store/load" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Load" $ do let tenv = [(pilVar "a", unsigned32)] ptr = constPtr 0xdeadbeef 4 stmts' = [def "a" $ load ptr 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, loadStmt) = (tReport ^. #symTypedStmts) !! 0 solveStmt loadStmt rvars = [ ("s1", CV (KBounded False 32) (CInteger 0)) , ("a", CV (KBounded False 32) (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "load non existing var; create free variable" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Load" $ do let tenv = [ (pilVar "a", unsigned32) , (pilVar "b", unsigned32) , (pilVar "c", tbool) ] ptr = constPtr 0xdeadbeef 4 stmts' = [ def "a" $ load ptr 4 , def "b" $ load ptr 4 , def "c" $ cmpE (var "a" 4) (var "b" 4) 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, arg0) = (tReport ^. #symTypedStmts) !! 0 let (_, arg1) = (tReport ^. #symTypedStmts) !! 1 let (_, arg2) = (tReport ^. #symTypedStmts) !! 2 solveStmt arg0 solveStmt arg1 solveStmt arg2 rvars = [ ("s3", CV (KBounded False 32) (CInteger 0)) , ("a", CV (KBounded False 32) (CInteger 0)) , ("b", CV (KBounded False 32) (CInteger 0)) , ("c", CV KBool (CInteger 1)) ] errs = [] r <- runIO $ runSolveCmd tenv cmd it "load non existing var; create free variable" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs) context "Pil.Load" $ do let tenv = [ (pilVar "a", unsigned64) ] ptr = constPtr 0xdeadbeef 4 stmts' = [ def "a" $ zx ( sx (load ptr 1) 4) 8 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, arg0) = (tReport ^. #symTypedStmts) !! 0 solveStmt arg0 rvars = [ ("s1", CV (KBounded False 8) (CInteger 0)) , ("a", CV (KBounded False 64) (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "load non existing var; create free variable" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs)
null
https://raw.githubusercontent.com/kudu-dynamics/blaze/2220a07d372a817e79525ec2707984b189fe98c9/test/general/Blaze/Pil/SolverSpec.hs
haskell
| Get a concrete variable from solver output. x >= y && x < y + 0.0000..... . Pil.VAR . Pil.VarOp $ pilVar "a" . Pil.VAR . Pil.VarOp $ pilVar "a" TODO: is this correct?
# OPTIONS_GHC -fno - warn - incomplete - uni - patterns # HLINT ignore " Evaluate " HLINT ignore " Use head " HLINT ignore " Reduce duplication " HLINT ignore " Eta reduce " module Blaze.Pil.SolverSpec where import Blaze.Prelude hiding (const, numerator, denominator) import Blaze.Pil.Solver hiding (pilVar) import Blaze.Pil.Construct import qualified Blaze.Types.Pil as Pil import qualified Data.SBV.Trans as SBV import qualified Data.HashMap.Strict as HashMap import Data.SBV.Dynamic hiding (Solver) import Blaze.Types.Pil.Checker as Ch hiding (signed) import Blaze.Pil.Checker (checkStmts) import Data.SBV.Trans ( (.>=) , (.<) , (.&&) ) import Data.SBV.Internals (unSBV) import Test.Hspec import Numeric (showHex) type SolverOutput = Either SolverError (SolverResult, [SolverError]) getVar :: Text -> SolverOutput -> Maybe CV getVar k r = r ^? _Right . _1 . #_Sat . at k . _Just getInt :: CV -> Maybe Integer getInt (CV _kind val) = case val of CInteger x -> Just x _ -> Nothing getVal :: Text -> SolverOutput -> Maybe Integer getVal k r = getVar k r >>= getInt spec :: Spec spec = describe "Blaze.Pil.SolverSpec" $ do let solveSolver m = checkSatWith_ SBV.z3 False AbortOnError m signed32 = Ch.DSType $ Ch.TInt (bw 32) (Just True) signed64 = Ch.DSType $ Ch.TInt (bw 64) (Just True) unsigned32 = Ch.DSType $ Ch.TInt (bw 32) (Just False) unsigned64 = Ch.DSType $ Ch.TInt (bw 64) (Just False) unsigned8 = Ch.DSType $ Ch.TInt (bw 8) (Just False) unsigned4 = Ch.DSType $ Ch.TInt (bw 4) (Just False) carry = Ch.DSType Ch.TBool bw = Just char = Ch.DSType $ Ch.TChar (Just 8) float = Ch.DSType $ Ch.TFloat (bw 80) tbool = Ch.DSType Ch.TBool pointer = Ch . DSType . Ch . TPointer ( bw 64 ) bitVec = Ch.DSType . Ch.TBitVector floatEqual x y = unSBV $ (toSFloat' x .>= toSFloat' y) .&& (toSFloat' x .< SBV.fpAdd SBV.sRoundNearestTiesToAway (toSFloat' y) (toSFloat' . constFloat $ 0.0000001)) context "aux ops" $ do context "signExtend" $ do let cmd = do a <- newSymVar "a" (KBounded True 32) b <- newSymVar "b" (KBounded True 64) let sE = signExtend 64 a r = constInt 32 9 constrain $ r `svEqual` a constrain $ sE `svEqual` b vars = [("a", CV (KBounded True 32) (CInteger 9)), ("b", CV (KBounded True 64) (CInteger 9))] r <- runIO $ solveSolver cmd it "extends signed value so constraint on 32-bit number is also a constraint on 64-bit number" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "zeroExtend" $ do let cmd = do a <- newSymVar "a" (KBounded False 32) b <- newSymVar "b" (KBounded False 64) let zE = zeroExtend 64 a r = constWord 32 9 constrain $ r `svEqual` a constrain $ zE `svEqual` b vars = [("a", CV (KBounded False 32) (CInteger 9)), ("b", CV (KBounded False 64) (CInteger 9))] r <- runIO $ solveSolver cmd it "extends unsigned value so constraint on 32-bit number is also a constraint on 64-bit number" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "matchBoundedWidth" $ do let cmd = do a <- newSymVar "a" (KBounded True 32) b <- newSymVar "b" (KBounded True 32) constrain $ b `svEqual` (a `matchBoundedWidth` b) vars = [("a", CV (KBounded True 32) (CInteger 0)), ("b", CV (KBounded True 32) (CInteger 0))] r <- runIO $ solveSolver cmd it "should find a equals b after matching width" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "matchBoundedWidth" $ do let cmd = do a <- newSymVar "a" (KBounded True 64) b <- newSymVar "b" (KBounded True 32) constrain $ a `svEqual` (a `matchBoundedWidth` b) vars = [("a", CV (KBounded True 64) (CInteger 0)), ("b", CV (KBounded True 32) (CInteger 0))] r <- runIO $ solveSolver cmd it "should find a equals b after matching width" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "matchSign" $ do let cmd = do a <- newSymVar "a" (KBounded True 64) b <- newSymVar "b" (KBounded False 64) constrain $ a `svEqual` (a `matchSign` b) vars = [("a", CV (KBounded True 64) (CInteger 0)), ("b", CV (KBounded False 64) (CInteger 0))] r <- runIO $ solveSolver cmd it "should find a equals b after matching sign" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "Most Significant Bit" $ do let cmd = do a <- newSymVar "a" (KBounded True 4) b <- newSymVar "b" KBool constrain $ a `svEqual` constInt 4 7 constrain $ b `svEqual` msb a vars = [("a", CV (KBounded True 4) (CInteger 7)), ("b", CV KBool (CInteger 0))] r <- runIO $ solveSolver cmd it "should find the msb is zero" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "Most Significant Bit" $ do let cmd = do a <- newSymVar "a" (KBounded True 4) b <- newSymVar "b" KBool constrain $ a `svEqual` constInt 4 8 constrain $ b `svEqual` msb a vars = [("a", CV (KBounded True 4) (CInteger $ -8)), ("b", CV KBool (CInteger 1))] r <- runIO $ solveSolver cmd it "should find the msb is one" $ do r `shouldBe` Right (Sat (HashMap.fromList vars)) context "declarePilVars" $ do let runDecl tenvTuples = do r <- runSolverWith SBV.z3 declarePilVars (emptyState, SolverCtx (HashMap.fromList tenvTuples) mempty False AbortOnError) case r of Left _ -> return $ Left () Right (_, ss) -> return . Right $ ( kindOf <$> ss ^. #varMap , ss ^. #varNames ) context "declarePilVars" $ do let tenv = [(pilVar "a", char)] vmap = [(pilVar "a", KBounded False 8)] vnames = [(pilVar "a", "a")] r <- runIO $ runDecl tenv it "put single pilvar in varMap and varNames in state" $ do r `shouldBe` Right (HashMap.fromList vmap, HashMap.fromList vnames) context "declarePilVars" $ do let tenv = [(pilVar "a", Ch.DSVar $ Sym 0)] r <- runIO $ runDecl tenv it "fail if a var is just a sym" $ do r `shouldBe` Left () context "declarePilVars" $ do let tenv = [ (pilVar "a", char) , (pilVar "b", signed32) , (pilVar "c", Ch.DSType Ch.TBool) ] vmap = [ (pilVar "a", KBounded False 8) , (pilVar "b", KBounded True 32) , (pilVar "c", KBool) ] vnames = [ (pilVar "a", "a") , (pilVar "b", "b") , (pilVar "c", "c") ] r <- runIO $ runDecl tenv it "put many pilvars in varMap and varNames in state" $ do r `shouldBe` Right (HashMap.fromList vmap, HashMap.fromList vnames) context "solve Expr/Stmt" $ do let runSolveCmd tenvTuples cmd = do r <- flip (checkSatWith SBV.z3) (emptyState, SolverCtx (HashMap.fromList tenvTuples) mempty False AbortOnError) $ declarePilVars >> cmd case r of Left e -> return $ Left e Right (x, ss) -> return . Right $ ( x , ss ^. #errors ) context "solveExpr: ADD" $ do let tenv = [] arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 1 ) arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.CONST . Pil.ConstOp $ 11 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 88 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.ADD $ Pil.AddOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 99 rvars = [] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) let helper op (inw, l, r) (outw, outv) = do let tenv = [] arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 1 ) arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo inw $ Sym 2, Just (bitVec $ Just inw)) . Pil.CONST . Pil.ConstOp $ l arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo inw $ Sym 1, Just (bitVec $ Just inw)) . Pil.CONST . Pil.ConstOp $ r expr = Ch.InfoExpression (Ch.SymInfo outw $ Sym 0, Just (bitVec $ Just outw)) $ op arg1 arg2 cmd = do res <- solveExpr expr constrain $ res `svEqual` constWord outw outv rvars = [] errs = [] res <- runIO $ runSolveCmd tenv cmd let hex n = "0x" <> showHex n "" it (hex l <> " " <> hex r <> " ~> " <> hex outv) $ do res `shouldBe` Right (Sat $ HashMap.fromList rvars, errs) in do context "ADD_WILL_CARRY" $ do context "two constants of the same size" $ do let helper' = helper (\l r -> Pil.ADD_WILL_CARRY $ Pil.AddWillCarryOp l r) helper' (32, 0x00000000, 0x00000000) (1, 0) helper' (32, 0x00000000, 0x00000001) (1, 0) helper' (32, 0x00000000, 0xffffffff) (1, 0) helper' (32, 0x7fffffff, 0x00000000) (1, 0) helper' (32, 0x7fffffff, 0x00000001) (1, 0) helper' (32, 0x7fffffff, 0xffffffff) (1, 1) helper' (32, 0x80000000, 0x00000000) (1, 0) helper' (32, 0x80000000, 0x00000001) (1, 0) helper' (32, 0x80000000, 0xffffffff) (1, 1) helper' (32, 0xffffffff, 0x00000000) (1, 0) helper' (32, 0xffffffff, 0x00000001) (1, 1) helper' (32, 0xffffffff, 0xffffffff) (1, 1) helper' (8, 0x00, 0x00) (1, 0) helper' (8, 0x00, 0x01) (1, 0) helper' (8, 0x00, 0xff) (1, 0) helper' (8, 0x7f, 0x00) (1, 0) helper' (8, 0x7f, 0x01) (1, 0) helper' (8, 0x7f, 0xff) (1, 1) helper' (8, 0x80, 0x00) (1, 0) helper' (8, 0x80, 0x01) (1, 0) helper' (8, 0x80, 0xff) (1, 1) helper' (8, 0xff, 0x00) (1, 0) helper' (8, 0xff, 0x01) (1, 1) helper' (8, 0xff, 0xff) (1, 1) context "ADD_WILL_OVERFLOW" $ do context "two constants of the same size" $ do let helper' = helper (\l r -> Pil.ADD_WILL_OVERFLOW $ Pil.AddWillOverflowOp l r) helper' (32, 0x00000000, 0x00000000) (1, 0) helper' (32, 0x00000000, 0x00000001) (1, 0) helper' (32, 0x00000000, 0xffffffff) (1, 0) helper' (32, 0x7fffffff, 0x00000000) (1, 0) helper' (32, 0x7fffffff, 0x00000001) (1, 1) helper' (32, 0x7fffffff, 0xffffffff) (1, 0) helper' (32, 0x80000000, 0x00000000) (1, 0) helper' (32, 0x80000000, 0x00000001) (1, 0) helper' (32, 0x80000000, 0xffffffff) (1, 1) helper' (32, 0xffffffff, 0x00000000) (1, 0) helper' (32, 0xffffffff, 0x00000001) (1, 0) helper' (32, 0xffffffff, 0xffffffff) (1, 0) helper' (8, 0x00, 0x00) (1, 0) helper' (8, 0x00, 0x01) (1, 0) helper' (8, 0x00, 0xff) (1, 0) helper' (8, 0x7f, 0x00) (1, 0) helper' (8, 0x7f, 0x01) (1, 1) helper' (8, 0x7f, 0xff) (1, 0) helper' (8, 0x80, 0x00) (1, 0) helper' (8, 0x80, 0x01) (1, 0) helper' (8, 0x80, 0xff) (1, 1) helper' (8, 0xff, 0x00) (1, 0) helper' (8, 0xff, 0x01) (1, 0) helper' (8, 0xff, 0xff) (1, 0) context "SUB_WILL_OVERFLOW" $ do context "two constants of the same size" $ do let helper' = helper (\l r -> Pil.SUB_WILL_OVERFLOW $ Pil.SubWillOverflowOp l r) helper' (32, 0x00000000, 0x00000000) (1, 0) helper' (32, 0x00000000, 0x00000001) (1, 0) helper' (32, 0x00000000, 0xffffffff) (1, 0) helper' (32, 0x7fffffff, 0x00000000) (1, 0) helper' (32, 0x7fffffff, 0x00000001) (1, 0) helper' (32, 0x7fffffff, 0xffffffff) (1, 1) helper' (32, 0x80000000, 0x00000000) (1, 0) helper' (32, 0x80000000, 0x00000001) (1, 1) helper' (32, 0x80000000, 0xffffffff) (1, 0) helper' (32, 0xffffffff, 0x00000000) (1, 0) helper' (32, 0xffffffff, 0x00000001) (1, 0) helper' (32, 0xffffffff, 0xffffffff) (1, 0) helper' (8, 0x00, 0x00) (1, 0) helper' (8, 0x00, 0x01) (1, 0) helper' (8, 0x00, 0xff) (1, 0) helper' (8, 0x7f, 0x00) (1, 0) helper' (8, 0x7f, 0x01) (1, 0) helper' (8, 0x7f, 0xff) (1, 1) helper' (8, 0x80, 0x00) (1, 0) helper' (8, 0x80, 0x01) (1, 1) helper' (8, 0x80, 0xff) (1, 0) helper' (8, 0xff, 0x00) (1, 0) helper' (8, 0xff, 0x01) (1, 0) helper' (8, 0xff, 0xff) (1, 0) let helper (baseW, base) (indexW, index) stride (outw, outv) = do let tenv = [] base' = Ch.InfoExpression (Ch.SymInfo baseW $ Sym 0, Just (bitVec $ Just baseW)) . Pil.CONST . Pil.ConstOp $ base index' = Ch.InfoExpression (Ch.SymInfo indexW $ Sym 1, Just (bitVec $ Just indexW)) . Pil.CONST . Pil.ConstOp $ index expr = Ch.InfoExpression (Ch.SymInfo outw $ Sym 3, Just (bitVec $ Just outw)) . Pil.ARRAY_ADDR $ Pil.ArrayAddrOp base' index' stride cmd = do res <- solveExpr expr constrain $ res `svEqual` constWord outw outv rvars = [] errs = [] res <- runIO $ runSolveCmd tenv cmd let hex n = let n' = fromIntegral n :: Word64 in (if n' >= 0 then "0x" else "-0x") <> showHex (abs n') "" it (hex base <> "[" <> hex index <> " * " <> hex stride <> " bits] ~> " <> hex outv) $ do res `shouldBe` Right (Sat $ HashMap.fromList rvars, errs) in do context "ARRAY_ADDRESS" $ do context "all constants" $ do let base = fromIntegral (0xdeadbeefdeadbeef :: Word64) :: Int64 res = 0xdeadbeefdeadbf3f helper (64, base) (32, 5) 16 (64, res) helper (64, base) ( 8, 5) 16 (64, res) helper (64, base) ( 3, 5) 16 (64, res) context "solveExpr: VAR" $ do let tenv = [(pilVar "a", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 88 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.ADD $ Pil.AddOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 99 rvars = [("a", CV (KBounded False 8) (CInteger 11))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "add one constant and one var" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: SUB" $ do let tenv = [(pilVar "a", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 2 , Just char ) . Pil . CONST . Pil . $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.SUB $ Pil.SubOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 77 rvars = [("a", CV (KBounded False 8) (CInteger 88))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: DIVS" $ do let tenv = [(pilVar "a", char)] numerator = 88 expected = 8 arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 2 , Just char ) . Pil . CONST . Pil . $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ numerator expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.DIVS $ Pil.DivsOp arg2 arg1 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 expected rvsMatch [("a", CV (KBounded False 8) (CInteger denominator))] = denominator /= 0 && numerator `div` denominator == expected rvsMatch _ = False r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldSatisfy` \case Right (Sat rvs, []) -> rvsMatch $ HashMap.toList rvs _ -> False context "solveExpr: MODS" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ 93 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just signed32) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.MODS $ Pil.ModsOp arg1 arg2 cmd = do r <- solveExpr expr rArg0 <- solveExpr arg0 constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 32) (CInteger 5))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive numbers" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: MODS" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ -93 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just signed32) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.MODS $ Pil.ModsOp arg1 arg2 cmd = do r <- solveExpr expr rArg0 <- solveExpr arg0 constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 32) (CInteger $ -5))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive numbers" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: MODU" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 303 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 100 expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.MODU $ Pil.ModuOp arg1 arg2 cmd = do r <- solveExpr expr rArg0 <- solveExpr arg0 constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive numbers" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: MUL" $ do let tenv = [(pilVar "a", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 : : DSTExpression arg1 = Ch . ( Ch . SymInfo 8 $ Sym 2 , Just char ) . Pil . CONST . Pil . $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.MUL $ Pil.MulOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` constWord 8 77 rvars = [("a", CV (KBounded False 8) (CInteger 7))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: INT_TO_FLOAT" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 42 arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 80 $ Sym 1, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 80 $ Sym 0, Just float) . Pil.INT_TO_FLOAT $ Pil.IntToFloatOp arg0 cmd = do r <- solveExpr expr rArg1 <- solveExpr arg1 constrain $ rArg1 `svEqual` r rvars = [("a", CV KDouble (CDouble 42.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: CMP_SGE" $ do let tenv = [(pilVar "x", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "x" arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.CMP_SGE $ Pil.CmpSgeOp arg1 arg2 cmd = do r <- solveExpr expr constrain $ r `svEqual` svBool True r <- runIO $ runSolveCmd tenv cmd it "should provide a value x, where x >= 11" $ do r `shouldSatisfy` maybe False (>= 11) . getVal "x" context "solveExpr: CMP_SGT & CMP_SLT" $ do let tenv = [(pilVar "x", char)] arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.VAR . Pil.VarOp $ pilVar "x" arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 arg3 :: DSTExpression arg3 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 13 expr0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.CMP_SGT $ Pil.CmpSgtOp arg1 arg2 expr1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just char) . Pil.CMP_SLT $ Pil.CmpSltOp arg1 arg3 cmd = do r <- solveExpr expr0 r2 <- solveExpr expr1 constrain $ r `svEqual` svBool True constrain $ r2 `svEqual` svBool True r <- runIO $ runSolveCmd tenv cmd it "should provide a value x bound by 11 < x < 13" $ do getVal "x" r `shouldBe` Just 12 context "solveExpr: FADD" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 11.0 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FADD $ Pil.FaddOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 14.3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: CEIL" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.CEIL $ Pil.CeilOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 4.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FABS" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ -3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FABS $ Pil.FabsOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FLOOR" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FLOOR $ Pil.FloorOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FLOAT_TO_INT" $ do let tenv = [(pilVar "a", unsigned64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 2, Just unsigned64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 80 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.0 expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just unsigned64) . Pil.FLOAT_TO_INT $ Pil.FloatToIntOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 64) (CInteger 3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FNEG" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FNEG $ Pil.FnegOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble $ -3.3))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FSQRT" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.0 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FSQRT $ Pil.FsqrtOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 2.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FTrunc" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FLOOR $ Pil.FloorOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "positive number" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FTrunc" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ -3.3 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FTRUNC $ Pil.FtruncOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble $ -3.0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "negative number" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FDIV" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 12.3 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FDIV $ Pil.FdivOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 3.0000000000000004))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FMUL" $ do let tenv = [(pilVar "a", float) , (pilVar "b", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" argEq :: DSTExpression argEq = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "b" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.0 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FMUL $ Pil.FmulOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr rArgEq <- solveExpr argEq constrain $ rArg0 `svEqual` r constrain $ rArgEq `svEqual` (rArg0 `floatEqual` constFloat 12.6) rvars = [("a", CV KDouble (CDouble 12.600000000000001)) , ("b", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FSUB" $ do let tenv = [(pilVar "a", float)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 12.3 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just float) . Pil.FSUB $ Pil.FsubOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KDouble (CDouble 8.200000000000001))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_E" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_E $ Pil.FcmpEOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_GE" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 3.2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_GE $ Pil.FcmpGeOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_GT" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 5.2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_GT $ Pil.FcmpGtOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_LE" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.5 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_LE $ Pil.FcmpLeOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_LT" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 2.0 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_LT $ Pil.FcmpLtOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_NE" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.0 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_NE $ Pil.FcmpNeOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_O" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ SBV.nan arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_O $ Pil.FcmpOOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: FCMP_UO" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ SBV.nan arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just float) . Pil.CONST_FLOAT . Pil.ConstFloatOp $ 4.1 expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.FCMP_UO $ Pil.FcmpUoOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: CMP_E" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 2, Just char) . Pil.CONST . Pil.ConstOp $ 88 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 1, Just char) . Pil.CONST . Pil.ConstOp $ 11 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just tbool) . Pil.CMP_E $ Pil.CmpEOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: LOW_PART" $ do let tenv = [(pilVar "a", unsigned8)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just unsigned8) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned8) . Pil.CONST . Pil.ConstOp $ 271 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 0, Just unsigned8) . Pil.LOW_PART $ Pil.LowPartOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 8) (CInteger 15))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: AND" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 92 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.AND $ Pil.AndOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 12))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: OR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 92 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.OR $ Pil.OrOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 95))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: TEST_BIT" $ do let tenv = [(pilVar "a", tbool)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just tbool) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just tbool) . Pil.TEST_BIT $ Pil.TestBitOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV KBool (CInteger 1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: XOR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 92 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 15 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.XOR $ Pil.XorOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 83))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ROL" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.ROL $ Pil.RolOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 8))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ROR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.ROR $ Pil.RorOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 536870912))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: LSR" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 1 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.LSR $ Pil.LsrOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: LSL" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.LSL $ Pil.LslOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 16))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: NEG" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ 2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.NEG $ Pil.NegOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 32) (CInteger $ -2))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: NOT" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.NOT $ Pil.NotOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 4294967293))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) let helper op (inw, x) (outw, outv) = do let tenv = [] arg :: DSTExpression arg = Ch.InfoExpression (Ch.SymInfo inw $ Sym 1, Just (bitVec $ Just inw)) . Pil.CONST . Pil.ConstOp $ x expr = Ch.InfoExpression (Ch.SymInfo outw $ Sym 0, Just (bitVec $ Just outw)) $ op arg cmd = do res <- solveExpr expr constrain $ res `svEqual` constWord outw outv rvars = [] errs = [] res <- runIO $ runSolveCmd tenv cmd let hex n = let n' = fromIntegral n :: Word64 in (if n' >= 0 then "0x" else "-0x") <> showHex (abs n') "" it (hex x <> " ~> " <> hex outv) $ do res `shouldBe` Right (Sat $ HashMap.fromList rvars, errs) in do context "POPCNT" $ do context "one constant" $ do let helper' = helper (Pil.POPCNT . Pil.PopcntOp) helper' (64, -0x5335533553355336) (8, 32) helper' (64, -0x0000000000000001) (8, 64) helper' (64, -0x8000000000000000) (8, 1) helper' (32, 0x00000000) (8, 0) helper' (32, 0x00000001) (8, 1) helper' (32, 0x80000000) (8, 1) helper' (32, 0xf1f1f1f1) (8, 20) helper' (32, 0xffffffff) (8, 32) helper' (16, 0x0000) (8, 0) helper' (16, 0x0001) (8, 1) helper' (16, 0x8000) (8, 1) helper' (16, 0xf1f1) (8, 10) helper' (16, 0xffff) (8, 16) helper' (8, 0x0000) (8, 0) helper' (8, 0x01) (8, 1) helper' (8, 0x80) (8, 1) helper' (8, 0xf1) (8, 5) helper' (8, 0xff) (8, 8) context "solveExpr: SX" $ do let tenv = [(pilVar "a", signed64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 3, Just signed64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ -2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just signed64) . Pil.SX $ Pil.SxOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 64) (CInteger $ -2))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "32 to 64 bit, negative value" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: SX" $ do let tenv = [(pilVar "a", signed64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 3, Just signed64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ 2 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just signed64) . Pil.SX $ Pil.SxOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 64) (CInteger 2))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "32 to 64 bit, positive value" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ZX" $ do let tenv = [(pilVar "a", unsigned64)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 3, Just unsigned64) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 42 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 64 $ Sym 0, Just unsigned64) . Pil.ZX $ Pil.ZxOp arg1 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 64) (CInteger 42))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "32 to 64 bit" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: ASR" $ do let tenv = [(pilVar "a", signed32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 3, Just signed32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just signed32) . Pil.CONST . Pil.ConstOp $ -2 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 3 expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just signed32) . Pil.ASR $ Pil.AsrOp arg1 arg2 cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded True 32) (CInteger $ -1))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "two constants of same size" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) TODO : All these tests could use a CONST_BOOL pil instruction for the carry : context "solveExpr: ADC" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 34 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 22 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.ADC $ Pil.AdcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 57))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: SBB" $ do let tenv = [(pilVar "a", unsigned32)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 8 $ Sym 3, Just unsigned32) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 2, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 34 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 1, Just unsigned32) . Pil.CONST . Pil.ConstOp $ 22 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 32 $ Sym 0, Just unsigned32) . Pil.SBB $ Pil.SbbOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 32) (CInteger 11))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RLC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RLC $ Pil.RlcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 15))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RLC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ False expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RLC $ Pil.RlcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 14))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 0" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RRC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ True expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RRC $ Pil.RrcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 15))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 1" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveExpr: RRC" $ do let tenv = [(pilVar "a", unsigned4)] arg0 :: DSTExpression arg0 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 3, Just unsigned4) . Pil.VAR . Pil.VarOp $ pilVar "a" arg1 :: DSTExpression arg1 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 2, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 15 arg2 :: DSTExpression arg2 = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 1, Just unsigned4) . Pil.CONST . Pil.ConstOp $ 1 c :: DSTExpression c = Ch.InfoExpression (Ch.SymInfo 1 $ Sym 4, Just carry) . Pil.CONST_BOOL . Pil.ConstBoolOp $ False expr :: DSTExpression expr = Ch.InfoExpression (Ch.SymInfo 4 $ Sym 0, Just unsigned4) . Pil.RRC $ Pil.RrcOp arg1 arg2 c cmd = do rArg0 <- solveExpr arg0 r <- solveExpr expr constrain $ rArg0 `svEqual` r rvars = [("a", CV (KBounded False 4) (CInteger 7))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "with carry = 0" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "solveStmt:" $ do context "Pil.Def" $ do let tenv = [(pilVar "a", bitVec (bw 32))] stmts' = [def "a" $ const 888 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, stmtInfoExpr) = (tReport ^. #symTypedStmts) !! 0 solveStmt stmtInfoExpr rvars = [("a", CV (KBounded False 32) (CInteger 888))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Def" $ do let tenv = [ (pilVar "a", bitVec (bw 32)) , (pilVar "b", bitVec (bw 32)) ] stmts' = [ def "a" $ const 888 4 , def "b" $ var "a" 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, defA) = (tReport ^. #symTypedStmts) !! 0 let (_, defB) = (tReport ^. #symTypedStmts) !! 1 solveStmt defA solveStmt defB rvars = [ ("a", CV (KBounded False 32) (CInteger 888)) , ("b", CV (KBounded False 32) (CInteger 888)) ] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var equal to another" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) eTReport ` shouldBe ` ( Left $ Ch . UnhandledExpr ) context "Pil.Def" $ do let tenv = [ (pilVar "a", bitVec (bw 32)) , (pilVar "b", bitVec (bw 32)) , (pilVar "c", bitVec (bw 32)) , (pilVar "d", bitVec (bw 32)) ] stmts' = [ def "a" $ const 888 4 , def "b" $ var "a" 4 , def "c" $ var "b" 4 , def "d" $ var "c" 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, defA) = (tReport ^. #symTypedStmts) !! 0 (_, defB) = (tReport ^. #symTypedStmts) !! 1 (_, defC) = (tReport ^. #symTypedStmts) !! 2 (_, defD) = (tReport ^. #symTypedStmts) !! 3 solveStmt defA solveStmt defB solveStmt defC solveStmt defD rvars = [ ("a", CV (KBounded False 32) (CInteger 888)) , ("b", CV (KBounded False 32) (CInteger 888)) , ("c", CV (KBounded False 32) (CInteger 888)) , ("d", CV (KBounded False 32) (CInteger 888)) ] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var equal to another" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Def" $ do let tenv = [(pilVar "a", tbool)] stmts' = [def "a" $ const 888 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, stmtInfoExpr) = (tReport ^. #symTypedStmts) !! 0 solveStmt stmtInfoExpr errs = [ StmtError { stmtIndex = 0 , stmtErr = GuardError "guardSameKind" [KBool, KBounded False 32] "not same kind" }] r <- runIO $ runSolveCmd tenv cmd it "mismatch variables" $ do fmap snd r `shouldBe` Right errs context "Pil.Constraint" $ do let tenv = [(pilVar "a", bitVec (bw 32))] stmts' = [constraint $ cmpE (var "a" 4) (const 42 4) 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, stmtInfoExpr) = (tReport ^. #symTypedStmts) !! 0 solveStmt stmtInfoExpr rvars = [("a", CV (KBounded False 32) (CInteger 42))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "def one var" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Store/Load" $ do let tenv = [(pilVar "a", unsigned32)] ptr = constPtr 0xdeadbeef 4 stmts' = [ store ptr $ const 42 4 , def "a" $ load ptr 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, storeStmt) = (tReport ^. #symTypedStmts) !! 0 let (_, loadStmt) = (tReport ^. #symTypedStmts) !! 1 solveStmt storeStmt solveStmt loadStmt rvars = [("a", CV (KBounded False 32) (CInteger 42))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "one store/load" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Load" $ do let tenv = [(pilVar "a", unsigned32)] ptr = constPtr 0xdeadbeef 4 stmts' = [def "a" $ load ptr 4] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, loadStmt) = (tReport ^. #symTypedStmts) !! 0 solveStmt loadStmt rvars = [ ("s1", CV (KBounded False 32) (CInteger 0)) , ("a", CV (KBounded False 32) (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "load non existing var; create free variable" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs ) context "Pil.Load" $ do let tenv = [ (pilVar "a", unsigned32) , (pilVar "b", unsigned32) , (pilVar "c", tbool) ] ptr = constPtr 0xdeadbeef 4 stmts' = [ def "a" $ load ptr 4 , def "b" $ load ptr 4 , def "c" $ cmpE (var "a" 4) (var "b" 4) 4 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, arg0) = (tReport ^. #symTypedStmts) !! 0 let (_, arg1) = (tReport ^. #symTypedStmts) !! 1 let (_, arg2) = (tReport ^. #symTypedStmts) !! 2 solveStmt arg0 solveStmt arg1 solveStmt arg2 rvars = [ ("s3", CV (KBounded False 32) (CInteger 0)) , ("a", CV (KBounded False 32) (CInteger 0)) , ("b", CV (KBounded False 32) (CInteger 0)) , ("c", CV KBool (CInteger 1)) ] errs = [] r <- runIO $ runSolveCmd tenv cmd it "load non existing var; create free variable" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs) context "Pil.Load" $ do let tenv = [ (pilVar "a", unsigned64) ] ptr = constPtr 0xdeadbeef 4 stmts' = [ def "a" $ zx ( sx (load ptr 1) 4) 8 ] eTReport = checkStmts stmts' (Right tReport) = eTReport cmd = do let (_, arg0) = (tReport ^. #symTypedStmts) !! 0 solveStmt arg0 rvars = [ ("s1", CV (KBounded False 8) (CInteger 0)) , ("a", CV (KBounded False 64) (CInteger 0))] errs = [] r <- runIO $ runSolveCmd tenv cmd it "load non existing var; create free variable" $ do r `shouldBe` Right ( Sat $ HashMap.fromList rvars , errs)
c3a96c753d642bd3477235ed65f6022a942a5747ca1dd4084ec71d9219ab8d45
RRethy/nvim-treesitter-textsubjects
textsubjects-container-outer.scm
(([ (method) (singleton_method) (module) (class) (singleton_class) ] @_start @_end) (#make-range! "range" @_start @_end)) ; sorbet type *annotation* (((call method: (identifier) @_start) . [(singleton_method) (method)] @_end) (#match? @_start "sig") (#make-range! "range" @_start @_end))
null
https://raw.githubusercontent.com/RRethy/nvim-treesitter-textsubjects/b18ab0e2fa677bc2f58062233ba5f7914a01e53f/queries/ruby/textsubjects-container-outer.scm
scheme
sorbet type *annotation*
(([ (method) (singleton_method) (module) (class) (singleton_class) ] @_start @_end) (#make-range! "range" @_start @_end)) (((call method: (identifier) @_start) . [(singleton_method) (method)] @_end) (#match? @_start "sig") (#make-range! "range" @_start @_end))
e88cea7a90c697ec38d2393b9a432114261e5caee1530cad49eaa28a66cf1fe5
zotonic/zotonic
controller_log_client.erl
@author < > 2019 < > %% @doc Log client side events Copyright 2019 %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(controller_log_client). -author("Marc Worrell <>"). -export([ service_available/1, allowed_methods/1, content_types_accepted/1, process/4 ]). -include_lib("zotonic_core/include/zotonic.hrl"). Default max body length ( 50 KB ) for HTTP log requests . -define(MAX_BODY_LENGTH, 50*1024). service_available(Context) -> Context1 = z_context:set_resp_header(<<"access-control-allow-origin">>, <<"*">>, Context), {true, Context1}. allowed_methods(Context) -> {[ <<"POST">> ], Context}. content_types_accepted(Context) -> {[ {<<"application">>, <<"json">>, []} ], Context}. -spec process( binary(), cowmachine_req:media_type() | undefined, cowmachine_req:media_type(), z:context() ) -> {iodata(), z:context()} | {{halt, HttpCode :: pos_integer()}, z:context()}. process(<<"POST">>, _AcceptedCT, _ProvidedCT, Context) -> {Body, Context1} = req_body(Context), log(Body, Context1), {<<>>, Context1}. log(<<>>, _Context) -> ok; log(Body, Context) -> Body1 = filter_text(Body), case json_decode(Body1) of {ok, LogEvent} when is_map(LogEvent) -> case mod_logging:is_ui_ratelimit_check(Context) of true -> m_log_ui:insert_event(LogEvent, Context), ?LOG_INFO(#{ text => <<"UI event">>, in => zotonic_mod_logging, event => Body1 }); false -> ok end; {error, _} -> ok end. filter_text(Body) -> filter_text(Body, <<>>). filter_text(<<>>, Acc) -> Acc; filter_text(<<10, Rest/binary>>, Acc) -> filter_text(Rest, <<Acc/binary, 10>>); filter_text(<<9, Rest/binary>>, Acc) -> filter_text(Rest, <<Acc/binary, 9>>); filter_text(<<C/utf8, Rest/binary>>, Acc) when C < 32 -> filter_text(Rest, Acc); filter_text(<<C/utf8, Rest/binary>>, Acc) -> filter_text(Rest, <<Acc/binary, C/utf8>>). json_decode(Body) -> try {ok, z_json:decode(Body)} catch _:_ -> {error, json} end. -spec req_body( z:context() ) -> {binary(), z:context()}. req_body(Context) -> case cowmachine_req:req_body(?MAX_BODY_LENGTH, Context) of {undefined, Context1} -> {<<>>, Context1}; {Body, Context1} -> {Body, Context1} end.
null
https://raw.githubusercontent.com/zotonic/zotonic/1bb4aa8a0688d007dd8ec8ba271546f658312da8/apps/zotonic_mod_logging/src/controllers/controller_log_client.erl
erlang
@doc Log client side events 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.
@author < > 2019 < > Copyright 2019 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(controller_log_client). -author("Marc Worrell <>"). -export([ service_available/1, allowed_methods/1, content_types_accepted/1, process/4 ]). -include_lib("zotonic_core/include/zotonic.hrl"). Default max body length ( 50 KB ) for HTTP log requests . -define(MAX_BODY_LENGTH, 50*1024). service_available(Context) -> Context1 = z_context:set_resp_header(<<"access-control-allow-origin">>, <<"*">>, Context), {true, Context1}. allowed_methods(Context) -> {[ <<"POST">> ], Context}. content_types_accepted(Context) -> {[ {<<"application">>, <<"json">>, []} ], Context}. -spec process( binary(), cowmachine_req:media_type() | undefined, cowmachine_req:media_type(), z:context() ) -> {iodata(), z:context()} | {{halt, HttpCode :: pos_integer()}, z:context()}. process(<<"POST">>, _AcceptedCT, _ProvidedCT, Context) -> {Body, Context1} = req_body(Context), log(Body, Context1), {<<>>, Context1}. log(<<>>, _Context) -> ok; log(Body, Context) -> Body1 = filter_text(Body), case json_decode(Body1) of {ok, LogEvent} when is_map(LogEvent) -> case mod_logging:is_ui_ratelimit_check(Context) of true -> m_log_ui:insert_event(LogEvent, Context), ?LOG_INFO(#{ text => <<"UI event">>, in => zotonic_mod_logging, event => Body1 }); false -> ok end; {error, _} -> ok end. filter_text(Body) -> filter_text(Body, <<>>). filter_text(<<>>, Acc) -> Acc; filter_text(<<10, Rest/binary>>, Acc) -> filter_text(Rest, <<Acc/binary, 10>>); filter_text(<<9, Rest/binary>>, Acc) -> filter_text(Rest, <<Acc/binary, 9>>); filter_text(<<C/utf8, Rest/binary>>, Acc) when C < 32 -> filter_text(Rest, Acc); filter_text(<<C/utf8, Rest/binary>>, Acc) -> filter_text(Rest, <<Acc/binary, C/utf8>>). json_decode(Body) -> try {ok, z_json:decode(Body)} catch _:_ -> {error, json} end. -spec req_body( z:context() ) -> {binary(), z:context()}. req_body(Context) -> case cowmachine_req:req_body(?MAX_BODY_LENGTH, Context) of {undefined, Context1} -> {<<>>, Context1}; {Body, Context1} -> {Body, Context1} end.
1779212483c9f3089241cb887e3249e6b9f5b66ce44b3a822bd19d1c09f75fec
charlieg/Sparser
pause.lisp
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- copyright ( c ) 1994 - 1996 -- all rights reserved ;;; ;;; File: "pause" Module : " interface;workbench : " Version : 0.1 January 1995 initiated 6/10/94 v2.3 . Added button 7/27 . Tweeked synch . code to allow treetop trace without the Workbench up . 0.1 ( 1/9/95 ) adapted Synchronize / should - we - pause ? to also work with just a ;; start edge. (in-package :sparser) ;;;--------------- ;;; workbench hook ;;;--------------- (defun react-to-click-on-pause-button (button) ;; action on *wb/pause-button* (cond ((equal (ccl:dialog-item-text button) "resume") (ccl:set-dialog-item-text button "pause") (ccl:dialog-item-disable button) (throw :continue-from-pause :resume)) ((equal (ccl:dialog-item-text button) "pause") (ccl:set-dialog-item-text button "resume") (ccl:dialog-item-enable button)) (t (break "debug this: value of text doesn't match options")))) (defun set-pause-button-to-resume () ;; called from Put-parse-into-pause (ccl:set-dialog-item-text *wb/pause-button* "resume") (ccl:dialog-item-enable *wb/pause-button*)) ;;;------------------------------------- function called from Sparser events ;;;------------------------------------- (defun synchronize/should-we-pause? (sm &optional start-edge end-edge ) ;; called from End-SGML-section (if *text-out* (let* ((insertion-point-mark (ccl:fred-buffer *text-out*)) (insertion-position (ccl:buffer-position insertion-point-mark))) (cond (end-edge ;; the call is from markup with paired begin-end edges (synchronize-with-workbench-views start-edge end-edge)) ((edge-p start-edge) ;; the call is from a routine that knows it's ended a section ;; and should update the display, but that only has an edge ;; for the beginning of the section and not the end. (synchronize-with-workbench-views start-edge)) ((position-p start-edge) ;; call is from markup that isn't necessarily based on edges ;; but can track the position before the the word/edge that ;; indicated that a section has ended. (synchronize-with-workbench-views/pos start-edge))) (when *pause-after-each-paragraph* (put-parse-into-pause "--- after-section pause: ~A ---~%" (sm-full-name sm))) (unless (eql (ccl:buffer-position insertion-point-mark) insertion-position) ;; if it's moved (because we used the workbench), then ;; put it back at the end of the text where it was (set-mark insertion-point-mark insertion-position))) (if end-edge (synchronize-with-workbench-views start-edge end-edge) (if (position-p start-edge) (synchronize-with-workbench-views/pos start-edge))))) (defun put-parse-into-pause ( &rest args ) ;; also called directly from Should-we-pause-after-each-paragraph? (let* ((*backtrace-on-break* nil) (insertion-point-mark (ccl:fred-buffer *text-out*)) (insertion-position (ccl:buffer-position insertion-point-mark))) (set-pause-button-to-resume) ;;(ccl:set-window-layer *workshop-window* 0) ;; oops, this won't work because the 'break' below negates it. (catch :continue-from-pause (apply #'break args)) (unless (eql (ccl:buffer-position insertion-point-mark) insertion-position) ;; if it's moved (because we used the workbench), then ;; put it back at the end of the text where it was (set-mark insertion-point-mark insertion-position))))
null
https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/interface/workbench/pause.lisp
lisp
-*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- File: "pause" start edge. --------------- workbench hook --------------- action on *wb/pause-button* called from Put-parse-into-pause ------------------------------------- ------------------------------------- called from End-SGML-section the call is from markup with paired begin-end edges the call is from a routine that knows it's ended a section and should update the display, but that only has an edge for the beginning of the section and not the end. call is from markup that isn't necessarily based on edges but can track the position before the the word/edge that indicated that a section has ended. if it's moved (because we used the workbench), then put it back at the end of the text where it was also called directly from Should-we-pause-after-each-paragraph? (ccl:set-window-layer *workshop-window* 0) oops, this won't work because the 'break' below negates it. if it's moved (because we used the workbench), then put it back at the end of the text where it was
copyright ( c ) 1994 - 1996 -- all rights reserved Module : " interface;workbench : " Version : 0.1 January 1995 initiated 6/10/94 v2.3 . Added button 7/27 . Tweeked synch . code to allow treetop trace without the Workbench up . 0.1 ( 1/9/95 ) adapted Synchronize / should - we - pause ? to also work with just a (in-package :sparser) (defun react-to-click-on-pause-button (button) (cond ((equal (ccl:dialog-item-text button) "resume") (ccl:set-dialog-item-text button "pause") (ccl:dialog-item-disable button) (throw :continue-from-pause :resume)) ((equal (ccl:dialog-item-text button) "pause") (ccl:set-dialog-item-text button "resume") (ccl:dialog-item-enable button)) (t (break "debug this: value of text doesn't match options")))) (defun set-pause-button-to-resume () (ccl:set-dialog-item-text *wb/pause-button* "resume") (ccl:dialog-item-enable *wb/pause-button*)) function called from Sparser events (defun synchronize/should-we-pause? (sm &optional start-edge end-edge ) (if *text-out* (let* ((insertion-point-mark (ccl:fred-buffer *text-out*)) (insertion-position (ccl:buffer-position insertion-point-mark))) (cond (end-edge (synchronize-with-workbench-views start-edge end-edge)) ((edge-p start-edge) (synchronize-with-workbench-views start-edge)) ((position-p start-edge) (synchronize-with-workbench-views/pos start-edge))) (when *pause-after-each-paragraph* (put-parse-into-pause "--- after-section pause: ~A ---~%" (sm-full-name sm))) (unless (eql (ccl:buffer-position insertion-point-mark) insertion-position) (set-mark insertion-point-mark insertion-position))) (if end-edge (synchronize-with-workbench-views start-edge end-edge) (if (position-p start-edge) (synchronize-with-workbench-views/pos start-edge))))) (defun put-parse-into-pause ( &rest args ) (let* ((*backtrace-on-break* nil) (insertion-point-mark (ccl:fred-buffer *text-out*)) (insertion-position (ccl:buffer-position insertion-point-mark))) (set-pause-button-to-resume) (catch :continue-from-pause (apply #'break args)) (unless (eql (ccl:buffer-position insertion-point-mark) insertion-position) (set-mark insertion-point-mark insertion-position))))
600fab7af76cf4c8540ac28dbafe95f8f41bba0838d51ee5831979b9b377458e
McCLIM/McCLIM
with-output-to-drawing-stream.lisp
(in-package #:climi) (defmacro with-output-to-drawing-stream ((stream backend destination &rest args) &body body) (with-gensyms (cont) `(flet ((,cont (,stream) ,@body)) (declare (dynamic-extent (function ,cont))) (invoke-with-output-to-drawing-stream (function ,cont) ,backend ,destination ,@args)))) (defmethod invoke-with-output-to-drawing-stream (continuation backend destination &rest args) (with-port (port backend) (apply #'invoke-with-output-to-drawing-stream continuation port destination args)))
null
https://raw.githubusercontent.com/McCLIM/McCLIM/d49fef5c2bb1307a006cdadfc4061e0a6b0fff79/Core/windowing/with-output-to-drawing-stream.lisp
lisp
(in-package #:climi) (defmacro with-output-to-drawing-stream ((stream backend destination &rest args) &body body) (with-gensyms (cont) `(flet ((,cont (,stream) ,@body)) (declare (dynamic-extent (function ,cont))) (invoke-with-output-to-drawing-stream (function ,cont) ,backend ,destination ,@args)))) (defmethod invoke-with-output-to-drawing-stream (continuation backend destination &rest args) (with-port (port backend) (apply #'invoke-with-output-to-drawing-stream continuation port destination args)))
45b67d9db34239fd72025cba319d43cff824092ebc6fed553aa3e3881278dfd7
ardoq/analytics-clj
analytics_clj.clj
(ns ardoq.analytics-clj (:import [com.github.segmentio AnalyticsClient Config Defaults] [com.github.segmentio.models Traits Context Props Options])) (def context (doto (Context.) (.put "library" "analytics-clj"))) (defn- map-keys "Maps a function over the keys of an associative collection." [f coll] (persistent! (reduce-kv #(assoc! %1 (f %2) %3) (transient (empty coll)) coll))) (defn- identify* [client user-id traits options] (.identify client user-id traits options)) (defn- track* [client user-id event properties options] (.track client user-id event properties options)) (defn- make-alias* [client from to options] (.alias client from to options)) (defn- create-options [timestamp integration anonymous-id] (let [options (doto (Options.) (.setContext context))] (when timestamp (.setTimestamp options timestamp)) (when integration (.setIntegration options integration true)) (when anonymous-id (.setAnonymousId options anonymous-id)) options)) (defn initialize "Initializes and returns a client with given secret. Options: :host - the segment.io api endpoint (with scheme). Default value ''. :max-queue-size - maximum number of messages to allow into the queue before no new messages are accepted. Default value 10000. :timeout - number of milliseconds to wait before timing out the request. Default value 10000." ([secret] (initialize secret {})) ([secret {:keys [host max-queue-size timeout] :or {host Defaults/HOST max-queue-size Defaults/MAX_QUEUE_SIZE timeout Defaults/TIMEOUT}}] (AnalyticsClient. secret (doto (Config.) (.setHost host) (.setMaxQueueSize max-queue-size) (.setTimeout timeout))))) (defn identify "Identifying a user ties all of their actions to an id, and associates user traits to that id. Can also take an empty map of traits if you need to specify options, but no traits. Options: a map with keys: :timestamp - DateTime, useful for backdating events :integration - this call will be sent to the target integration :anonymous-id - the cookie / anonymous Id of this visitor " ([^AnalyticsClient client ^String user-id] (identify client user-id nil)) ([^AnalyticsClient client ^String user-id traits & [{:keys [timestamp integration anonymous-id]}]] (let [traits (reduce (fn [t [k v]] (.put ^Traits t (name k) v)) (Traits.) traits) options (create-options timestamp integration anonymous-id)] (identify* client user-id traits options)))) (defn full-name "Returns the full name of the map key. If it's a symbol, retrieves the full namespaced name and returns that instead." [k] (if (keyword? k) (str (.-sym k)) (name k))) (defn track "Whenever a user triggers an event, you’ll want to track it. Arguments: event - describes what this user just did. It's a human readable description like 'Played a Song', 'Printed a Report' or 'Updated Status'. properties - map with items that describe the event in more detail. This argument is optional, but highly recommended—you’ll find these properties extremely useful later. Options: a map with keys: :timestamp - DateTime, useful for backdating events :integration - this call will be sent to the target integration :anonymous-id - the cookie / anonymous Id of this visitor " ([^AnalyticsClient client ^String user-id ^String event] (track client user-id event {})) ([^AnalyticsClient client ^String user-id ^String event properties] (track client user-id event properties {} {})) ([^AnalyticsClient client ^String user-id ^String event properties & [{:keys [timestamp integration anonymous-id]}]] (let [properties (Props. (into-array Object (apply concat (vec (map-keys full-name properties))))) options (create-options timestamp integration anonymous-id)] (track* client user-id event properties options)))) (defn make-alias "Aliases an anonymous user into an identified user. from - the anonymous user's id before they are logged in. to - the identified user's id after they're logged in. Options: a map with keys: :timestamp - DateTime, useful for backdating events :integration - this call will be sent to the target integration :anonymous-id - the cookie / anonymous Id of this visitor " ([^AnalyticsClient client ^String from ^String to] (make-alias client from to {})) ([^AnalyticsClient client ^String from ^String to & [{:keys [timestamp integration anonymous-id]}]] (let [options (create-options timestamp integration anonymous-id)] (make-alias* client from to options)))) (defn flush-queue "Call flush to block until all the messages are flushed to the server. This is especially useful when turning off your web server to make sure we have all your messages." [^AnalyticsClient client] (.flush client))
null
https://raw.githubusercontent.com/ardoq/analytics-clj/4bf86696d81729d543cba8ad1b0208b367421988/src/ardoq/analytics_clj.clj
clojure
(ns ardoq.analytics-clj (:import [com.github.segmentio AnalyticsClient Config Defaults] [com.github.segmentio.models Traits Context Props Options])) (def context (doto (Context.) (.put "library" "analytics-clj"))) (defn- map-keys "Maps a function over the keys of an associative collection." [f coll] (persistent! (reduce-kv #(assoc! %1 (f %2) %3) (transient (empty coll)) coll))) (defn- identify* [client user-id traits options] (.identify client user-id traits options)) (defn- track* [client user-id event properties options] (.track client user-id event properties options)) (defn- make-alias* [client from to options] (.alias client from to options)) (defn- create-options [timestamp integration anonymous-id] (let [options (doto (Options.) (.setContext context))] (when timestamp (.setTimestamp options timestamp)) (when integration (.setIntegration options integration true)) (when anonymous-id (.setAnonymousId options anonymous-id)) options)) (defn initialize "Initializes and returns a client with given secret. Options: :host - the segment.io api endpoint (with scheme). Default value ''. :max-queue-size - maximum number of messages to allow into the queue before no new messages are accepted. Default value 10000. :timeout - number of milliseconds to wait before timing out the request. Default value 10000." ([secret] (initialize secret {})) ([secret {:keys [host max-queue-size timeout] :or {host Defaults/HOST max-queue-size Defaults/MAX_QUEUE_SIZE timeout Defaults/TIMEOUT}}] (AnalyticsClient. secret (doto (Config.) (.setHost host) (.setMaxQueueSize max-queue-size) (.setTimeout timeout))))) (defn identify "Identifying a user ties all of their actions to an id, and associates user traits to that id. Can also take an empty map of traits if you need to specify options, but no traits. Options: a map with keys: :timestamp - DateTime, useful for backdating events :integration - this call will be sent to the target integration :anonymous-id - the cookie / anonymous Id of this visitor " ([^AnalyticsClient client ^String user-id] (identify client user-id nil)) ([^AnalyticsClient client ^String user-id traits & [{:keys [timestamp integration anonymous-id]}]] (let [traits (reduce (fn [t [k v]] (.put ^Traits t (name k) v)) (Traits.) traits) options (create-options timestamp integration anonymous-id)] (identify* client user-id traits options)))) (defn full-name "Returns the full name of the map key. If it's a symbol, retrieves the full namespaced name and returns that instead." [k] (if (keyword? k) (str (.-sym k)) (name k))) (defn track "Whenever a user triggers an event, you’ll want to track it. Arguments: event - describes what this user just did. It's a human readable description like 'Played a Song', 'Printed a Report' or 'Updated Status'. properties - map with items that describe the event in more detail. This argument is optional, but highly recommended—you’ll find these properties extremely useful later. Options: a map with keys: :timestamp - DateTime, useful for backdating events :integration - this call will be sent to the target integration :anonymous-id - the cookie / anonymous Id of this visitor " ([^AnalyticsClient client ^String user-id ^String event] (track client user-id event {})) ([^AnalyticsClient client ^String user-id ^String event properties] (track client user-id event properties {} {})) ([^AnalyticsClient client ^String user-id ^String event properties & [{:keys [timestamp integration anonymous-id]}]] (let [properties (Props. (into-array Object (apply concat (vec (map-keys full-name properties))))) options (create-options timestamp integration anonymous-id)] (track* client user-id event properties options)))) (defn make-alias "Aliases an anonymous user into an identified user. from - the anonymous user's id before they are logged in. to - the identified user's id after they're logged in. Options: a map with keys: :timestamp - DateTime, useful for backdating events :integration - this call will be sent to the target integration :anonymous-id - the cookie / anonymous Id of this visitor " ([^AnalyticsClient client ^String from ^String to] (make-alias client from to {})) ([^AnalyticsClient client ^String from ^String to & [{:keys [timestamp integration anonymous-id]}]] (let [options (create-options timestamp integration anonymous-id)] (make-alias* client from to options)))) (defn flush-queue "Call flush to block until all the messages are flushed to the server. This is especially useful when turning off your web server to make sure we have all your messages." [^AnalyticsClient client] (.flush client))
1e680998812b94f2450b7ad007b8fac221ef4fdd4a3cdeba8992e8ecb4931e7d
Liutos/Project-Euler
pro6.lisp
(defun difference (n) (- (expt (/ (* n (1+ n)) 2) 2) (loop for i from 1 upto n summing (expt i 2))))
null
https://raw.githubusercontent.com/Liutos/Project-Euler/dd59940099ae37f971df1d74c4b7c78131fd5470/lisp/pro6.lisp
lisp
(defun difference (n) (- (expt (/ (* n (1+ n)) 2) 2) (loop for i from 1 upto n summing (expt i 2))))
16724d9a9a8a4d43a3e5753fd05494f3906a775e3beadc34a9291b18e9f39a05
brendanhay/gogol
CreateContact.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . People . CreateContact Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- Create a new contact and return the person resource for that contact . The request returns a 400 error if more than one field is specified on a field that is a singleton for contact sources : * biographies * birthdays * genders * names Mutate requests for the same user should be sent sequentially to avoid increased latency and failures . -- /See:/ < / People API Reference > for @people.people.createContact@. module Gogol.People.CreateContact ( -- * Resource PeoplePeopleCreateContactResource, -- ** Constructing a Request PeoplePeopleCreateContact (..), newPeoplePeopleCreateContact, ) where import Gogol.People.Types import qualified Gogol.Prelude as Core -- | A resource alias for @people.people.createContact@ method which the -- 'PeoplePeopleCreateContact' request conforms to. type PeoplePeopleCreateContactResource = "v1" Core.:> "people:createContact" Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "personFields" Core.FieldMask Core.:> Core.QueryParams "sources" PeopleCreateContactSources Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] Person Core.:> Core.Post '[Core.JSON] Person | Create a new contact and return the person resource for that contact . The request returns a 400 error if more than one field is specified on a field that is a singleton for contact sources : * biographies * birthdays * genders * names Mutate requests for the same user should be sent sequentially to avoid increased latency and failures . -- -- /See:/ 'newPeoplePeopleCreateContact' smart constructor. data PeoplePeopleCreateContact = PeoplePeopleCreateContact { -- | V1 error format. xgafv :: (Core.Maybe Xgafv), -- | OAuth access token. accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), -- | Multipart request metadata. payload :: Person, | Required . A field mask to restrict which fields on each person are returned . Multiple fields can be specified by separating them with commas . Defaults to all fields if not set . Valid values are : * addresses * ageRanges * biographies * birthdays * calendarUrls * clientData * coverPhotos * emailAddresses * events * externalIds * genders * imClients * interests * locales * locations * memberships * metadata * miscKeywords * names * nicknames * occupations * organizations * phoneNumbers * photos * relations * sipAddresses * skills * urls * userDefined personFields :: (Core.Maybe Core.FieldMask), -- | Optional. A mask of what source types to return. Defaults to READ/SOURCE/TYPE/CONTACT and READ/SOURCE/TYPE/PROFILE if not set. sources :: (Core.Maybe [PeopleCreateContactSources]), | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) -- | Creates a value of 'PeoplePeopleCreateContact' with the minimum fields required to make a request. newPeoplePeopleCreateContact :: -- | Multipart request metadata. See 'payload'. Person -> PeoplePeopleCreateContact newPeoplePeopleCreateContact payload = PeoplePeopleCreateContact { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, payload = payload, personFields = Core.Nothing, sources = Core.Nothing, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest PeoplePeopleCreateContact where type Rs PeoplePeopleCreateContact = Person type Scopes PeoplePeopleCreateContact = '[Contacts'FullControl] requestClient PeoplePeopleCreateContact {..} = go xgafv accessToken callback personFields (sources Core.^. Core._Default) uploadType uploadProtocol (Core.Just Core.AltJSON) payload peopleService where go = Core.buildClient ( Core.Proxy :: Core.Proxy PeoplePeopleCreateContactResource ) Core.mempty
null
https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-people/gen/Gogol/People/CreateContact.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated * Resource ** Constructing a Request | A resource alias for @people.people.createContact@ method which the 'PeoplePeopleCreateContact' request conforms to. /See:/ 'newPeoplePeopleCreateContact' smart constructor. | V1 error format. | OAuth access token. | Multipart request metadata. | Optional. A mask of what source types to return. Defaults to READ/SOURCE/TYPE/CONTACT and READ/SOURCE/TYPE/PROFILE if not set. | Upload protocol for media (e.g. \"raw\", \"multipart\"). | Creates a value of 'PeoplePeopleCreateContact' with the minimum fields required to make a request. | Multipart request metadata. See 'payload'.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . People . CreateContact Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) Create a new contact and return the person resource for that contact . The request returns a 400 error if more than one field is specified on a field that is a singleton for contact sources : * biographies * birthdays * genders * names Mutate requests for the same user should be sent sequentially to avoid increased latency and failures . /See:/ < / People API Reference > for @people.people.createContact@. module Gogol.People.CreateContact PeoplePeopleCreateContactResource, PeoplePeopleCreateContact (..), newPeoplePeopleCreateContact, ) where import Gogol.People.Types import qualified Gogol.Prelude as Core type PeoplePeopleCreateContactResource = "v1" Core.:> "people:createContact" Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "personFields" Core.FieldMask Core.:> Core.QueryParams "sources" PeopleCreateContactSources Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] Person Core.:> Core.Post '[Core.JSON] Person | Create a new contact and return the person resource for that contact . The request returns a 400 error if more than one field is specified on a field that is a singleton for contact sources : * biographies * birthdays * genders * names Mutate requests for the same user should be sent sequentially to avoid increased latency and failures . data PeoplePeopleCreateContact = PeoplePeopleCreateContact xgafv :: (Core.Maybe Xgafv), accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), payload :: Person, | Required . A field mask to restrict which fields on each person are returned . Multiple fields can be specified by separating them with commas . Defaults to all fields if not set . Valid values are : * addresses * ageRanges * biographies * birthdays * calendarUrls * clientData * coverPhotos * emailAddresses * events * externalIds * genders * imClients * interests * locales * locations * memberships * metadata * miscKeywords * names * nicknames * occupations * organizations * phoneNumbers * photos * relations * sipAddresses * skills * urls * userDefined personFields :: (Core.Maybe Core.FieldMask), sources :: (Core.Maybe [PeopleCreateContactSources]), | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) newPeoplePeopleCreateContact :: Person -> PeoplePeopleCreateContact newPeoplePeopleCreateContact payload = PeoplePeopleCreateContact { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, payload = payload, personFields = Core.Nothing, sources = Core.Nothing, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest PeoplePeopleCreateContact where type Rs PeoplePeopleCreateContact = Person type Scopes PeoplePeopleCreateContact = '[Contacts'FullControl] requestClient PeoplePeopleCreateContact {..} = go xgafv accessToken callback personFields (sources Core.^. Core._Default) uploadType uploadProtocol (Core.Just Core.AltJSON) payload peopleService where go = Core.buildClient ( Core.Proxy :: Core.Proxy PeoplePeopleCreateContactResource ) Core.mempty
7e98d082691c3f507544727fa74adc56aa9543ef44805cd894366007bc1b8983
xh4/web-toolkit
closer-mop-packages.lisp
(in-package :cl-user) (defpackage #:closer-mop (:use #:common-lisp #+lispworks #:lispworks) (:nicknames #:c2mop) #+(or allegro clozure lispworks mcl) (:shadow #:standard-class) #+(or allegro clisp clozure ecl clasp lispworks sbcl) (:shadow #:defgeneric #:defmethod #:standard-generic-function) #+clozure (:shadow standard-method) #+(or cmu mcl) (:shadow #:typep subtypep) #+lispworks5.1 (:import-from #:system #:with-hash-table-locked) #+(or lispworks6 lispworks7) (:import-from #:hcl #:with-hash-table-locked) #-(or clisp scl mezzano) (:import-from #+abcl #:ext #+allegro #:excl #+clozure #:ccl #+cmu #:pcl #+ecl #:clos #+clasp #:clos #+lispworks #:clos #+mcl #:ccl #+sbcl #:sb-pcl #:classp) (:import-from #+abcl #:mop #+allegro #:mop #+clisp #:clos #+clozure #:ccl #+cmu #:clos-mop #+ecl #:clos #+clasp #:clos #+lispworks #:clos #+mcl #:ccl #+sbcl #:sb-mop #+scl #:clos #+mezzano #:mezzano.clos #:direct-slot-definition #:effective-slot-definition #-lispworks #:eql-specializer #:forward-referenced-class #-lispworks #:funcallable-standard-class #-lispworks4 #:funcallable-standard-object #:metaobject #:slot-definition #-(or lispworks4 lispworks5 scl) #:specializer #:standard-accessor-method #:standard-direct-slot-definition #:standard-effective-slot-definition #:standard-reader-method #:standard-slot-definition #:standard-writer-method #-(or lispworks4.3 mezzano) #:accessor-method-slot-definition #-(or scl mezzano) #:add-dependent #-(or scl mezzano) #:add-direct-method #-mezzano #:add-direct-subclass #-(or scl mezzano) #:class-default-initargs #-scl #:class-direct-default-initargs #:class-direct-slots #:class-direct-subclasses #:class-direct-superclasses #:class-finalized-p #:class-precedence-list #:class-prototype #:class-slots #-(or clozure lispworks mcl) #:compute-applicable-methods-using-classes #:compute-class-precedence-list #-(or lispworks4 lispworks5 mezzano) #:compute-default-initargs #-clozure #:compute-discriminating-function #-(or clozure scl) #:compute-effective-method #:compute-effective-slot-definition #:compute-slots #:direct-slot-definition-class #:effective-slot-definition-class #:ensure-class #:ensure-class-using-class #-mezzano #:ensure-generic-function-using-class #-lispworks #:eql-specializer-object #:extract-lambda-list #:extract-specializer-names #:finalize-inheritance #-(or lispworks mezzano) #:find-method-combination #-(or lispworks scl mezzano) #:funcallable-standard-instance-access #-allegro #:generic-function-argument-precedence-order #:generic-function-declarations #:generic-function-lambda-list #:generic-function-method-class #:generic-function-method-combination #:generic-function-methods #:generic-function-name #-lispworks #:intern-eql-specializer #-(or allegro clisp clozure lispworks mcl scl mezzano) #:make-method-lambda #-(or scl mezzano) #:map-dependents #-clozure #:method-function #:method-generic-function #:method-lambda-list #:method-specializers #-lispworks4.3 #:reader-method-class #-(or scl mezzano) #:remove-dependent #-(or scl mezzano) #:remove-direct-method #-mezzano #:remove-direct-subclass #:set-funcallable-instance-function #:slot-boundp-using-class #:slot-definition-allocation #:slot-definition-initargs #:slot-definition-initform #:slot-definition-initfunction #:slot-definition-location #:slot-definition-name #:slot-definition-readers #:slot-definition-writers #:slot-definition-type #:slot-makunbound-using-class #-mezzano #:slot-value-using-class #-(or lispworks mezzano) #:specializer-direct-generic-functions #-mezzano #:specializer-direct-methods #-(or lispworks mezzano) #:standard-instance-access #-(or scl mezzano) #:update-dependent #:validate-superclass #-lispworks4.3 #:writer-method-class) (:export #:built-in-class #:class #:direct-slot-definition #:effective-slot-definition #:eql-specializer #+lispworks #:eql-specializer* #+mezzano #:eql-specializer #:forward-referenced-class #:funcallable-standard-class #:funcallable-standard-object #:generic-function #:metaobject #:method #:method-combination #:slot-definition #:specializer #:standard-accessor-method #:standard-class #:standard-generic-function #:standard-direct-slot-definition #:standard-effective-slot-definition #:standard-method #:standard-object #:standard-reader-method #:standard-slot-definition #:standard-writer-method #:defclass #:defgeneric #:define-method-combination #:defmethod #:classp #:ensure-finalized #:ensure-method #:fix-slot-initargs #:required-args #:subclassp #:accessor-method-slot-definition #:add-dependent #:add-direct-method #:add-direct-subclass #:class-default-initargs #:class-direct-default-initargs #:class-direct-slots #:class-direct-subclasses #:class-direct-superclasses #:class-finalized-p #:class-precedence-list #:class-prototype #:class-slots #:compute-applicable-methods-using-classes #:compute-class-precedence-list #:compute-default-initargs #:compute-discriminating-function #:compute-effective-method #:compute-effective-method-function #:compute-effective-slot-definition #:compute-slots #:direct-slot-definition-class #:effective-slot-definition-class #:ensure-class #:ensure-class-using-class #:ensure-generic-function #:ensure-generic-function-using-class #:eql-specializer-object #:extract-lambda-list #:extract-specializer-names #:finalize-inheritance #:find-method-combination #:funcallable-standard-instance-access #:generic-function-argument-precedence-order #:generic-function-declarations #:generic-function-lambda-list #:generic-function-method-class #:generic-function-method-combination #:generic-function-methods #:generic-function-name #:intern-eql-specializer #+lispworks #:intern-eql-specializer* #+mezzano #:intern-eql-specializer #:make-method-lambda #:map-dependents #:method-function #:method-generic-function #:method-lambda-list #:method-specializers #:reader-method-class #:remove-dependent #:remove-direct-method #:remove-direct-subclass #:set-funcallable-instance-function #:slot-boundp-using-class #:slot-definition-allocation #:slot-definition-initargs #:slot-definition-initform #:slot-definition-initfunction #:slot-definition-location #:slot-definition-name #:slot-definition-readers #:slot-definition-writers #:slot-definition-type #:slot-makunbound-using-class #:slot-value-using-class #:specializer-direct-generic-functions #:specializer-direct-methods #:standard-instance-access #:subtypep #:typep #:update-dependent #:validate-superclass #:writer-method-class #:warn-on-defmethod-without-generic-function)) (in-package :closer-mop) (macrolet ((define-closer-common-lisp-package () (loop with symbols = (nunion (loop for sym being the external-symbols of :common-lisp if (find-symbol (symbol-name sym) :c2mop) collect it else collect sym) (loop for sym being the external-symbols of :c2mop collect sym)) with map = '() for symbol in symbols do (push (symbol-name symbol) (getf map (symbol-package symbol))) finally (return `(defpackage #:closer-common-lisp (:nicknames #:c2cl) (:use) ,@(loop for (package symbols) on map by #'cddr collect `(:import-from ,(package-name package) ,@symbols)) (:export ,@(mapcar #'symbol-name symbols))))))) (define-closer-common-lisp-package)) (defpackage #:closer-common-lisp-user (:nicknames #:c2cl-user) (:use #:closer-common-lisp))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/closer-mop-20191227-git/closer-mop-packages.lisp
lisp
(in-package :cl-user) (defpackage #:closer-mop (:use #:common-lisp #+lispworks #:lispworks) (:nicknames #:c2mop) #+(or allegro clozure lispworks mcl) (:shadow #:standard-class) #+(or allegro clisp clozure ecl clasp lispworks sbcl) (:shadow #:defgeneric #:defmethod #:standard-generic-function) #+clozure (:shadow standard-method) #+(or cmu mcl) (:shadow #:typep subtypep) #+lispworks5.1 (:import-from #:system #:with-hash-table-locked) #+(or lispworks6 lispworks7) (:import-from #:hcl #:with-hash-table-locked) #-(or clisp scl mezzano) (:import-from #+abcl #:ext #+allegro #:excl #+clozure #:ccl #+cmu #:pcl #+ecl #:clos #+clasp #:clos #+lispworks #:clos #+mcl #:ccl #+sbcl #:sb-pcl #:classp) (:import-from #+abcl #:mop #+allegro #:mop #+clisp #:clos #+clozure #:ccl #+cmu #:clos-mop #+ecl #:clos #+clasp #:clos #+lispworks #:clos #+mcl #:ccl #+sbcl #:sb-mop #+scl #:clos #+mezzano #:mezzano.clos #:direct-slot-definition #:effective-slot-definition #-lispworks #:eql-specializer #:forward-referenced-class #-lispworks #:funcallable-standard-class #-lispworks4 #:funcallable-standard-object #:metaobject #:slot-definition #-(or lispworks4 lispworks5 scl) #:specializer #:standard-accessor-method #:standard-direct-slot-definition #:standard-effective-slot-definition #:standard-reader-method #:standard-slot-definition #:standard-writer-method #-(or lispworks4.3 mezzano) #:accessor-method-slot-definition #-(or scl mezzano) #:add-dependent #-(or scl mezzano) #:add-direct-method #-mezzano #:add-direct-subclass #-(or scl mezzano) #:class-default-initargs #-scl #:class-direct-default-initargs #:class-direct-slots #:class-direct-subclasses #:class-direct-superclasses #:class-finalized-p #:class-precedence-list #:class-prototype #:class-slots #-(or clozure lispworks mcl) #:compute-applicable-methods-using-classes #:compute-class-precedence-list #-(or lispworks4 lispworks5 mezzano) #:compute-default-initargs #-clozure #:compute-discriminating-function #-(or clozure scl) #:compute-effective-method #:compute-effective-slot-definition #:compute-slots #:direct-slot-definition-class #:effective-slot-definition-class #:ensure-class #:ensure-class-using-class #-mezzano #:ensure-generic-function-using-class #-lispworks #:eql-specializer-object #:extract-lambda-list #:extract-specializer-names #:finalize-inheritance #-(or lispworks mezzano) #:find-method-combination #-(or lispworks scl mezzano) #:funcallable-standard-instance-access #-allegro #:generic-function-argument-precedence-order #:generic-function-declarations #:generic-function-lambda-list #:generic-function-method-class #:generic-function-method-combination #:generic-function-methods #:generic-function-name #-lispworks #:intern-eql-specializer #-(or allegro clisp clozure lispworks mcl scl mezzano) #:make-method-lambda #-(or scl mezzano) #:map-dependents #-clozure #:method-function #:method-generic-function #:method-lambda-list #:method-specializers #-lispworks4.3 #:reader-method-class #-(or scl mezzano) #:remove-dependent #-(or scl mezzano) #:remove-direct-method #-mezzano #:remove-direct-subclass #:set-funcallable-instance-function #:slot-boundp-using-class #:slot-definition-allocation #:slot-definition-initargs #:slot-definition-initform #:slot-definition-initfunction #:slot-definition-location #:slot-definition-name #:slot-definition-readers #:slot-definition-writers #:slot-definition-type #:slot-makunbound-using-class #-mezzano #:slot-value-using-class #-(or lispworks mezzano) #:specializer-direct-generic-functions #-mezzano #:specializer-direct-methods #-(or lispworks mezzano) #:standard-instance-access #-(or scl mezzano) #:update-dependent #:validate-superclass #-lispworks4.3 #:writer-method-class) (:export #:built-in-class #:class #:direct-slot-definition #:effective-slot-definition #:eql-specializer #+lispworks #:eql-specializer* #+mezzano #:eql-specializer #:forward-referenced-class #:funcallable-standard-class #:funcallable-standard-object #:generic-function #:metaobject #:method #:method-combination #:slot-definition #:specializer #:standard-accessor-method #:standard-class #:standard-generic-function #:standard-direct-slot-definition #:standard-effective-slot-definition #:standard-method #:standard-object #:standard-reader-method #:standard-slot-definition #:standard-writer-method #:defclass #:defgeneric #:define-method-combination #:defmethod #:classp #:ensure-finalized #:ensure-method #:fix-slot-initargs #:required-args #:subclassp #:accessor-method-slot-definition #:add-dependent #:add-direct-method #:add-direct-subclass #:class-default-initargs #:class-direct-default-initargs #:class-direct-slots #:class-direct-subclasses #:class-direct-superclasses #:class-finalized-p #:class-precedence-list #:class-prototype #:class-slots #:compute-applicable-methods-using-classes #:compute-class-precedence-list #:compute-default-initargs #:compute-discriminating-function #:compute-effective-method #:compute-effective-method-function #:compute-effective-slot-definition #:compute-slots #:direct-slot-definition-class #:effective-slot-definition-class #:ensure-class #:ensure-class-using-class #:ensure-generic-function #:ensure-generic-function-using-class #:eql-specializer-object #:extract-lambda-list #:extract-specializer-names #:finalize-inheritance #:find-method-combination #:funcallable-standard-instance-access #:generic-function-argument-precedence-order #:generic-function-declarations #:generic-function-lambda-list #:generic-function-method-class #:generic-function-method-combination #:generic-function-methods #:generic-function-name #:intern-eql-specializer #+lispworks #:intern-eql-specializer* #+mezzano #:intern-eql-specializer #:make-method-lambda #:map-dependents #:method-function #:method-generic-function #:method-lambda-list #:method-specializers #:reader-method-class #:remove-dependent #:remove-direct-method #:remove-direct-subclass #:set-funcallable-instance-function #:slot-boundp-using-class #:slot-definition-allocation #:slot-definition-initargs #:slot-definition-initform #:slot-definition-initfunction #:slot-definition-location #:slot-definition-name #:slot-definition-readers #:slot-definition-writers #:slot-definition-type #:slot-makunbound-using-class #:slot-value-using-class #:specializer-direct-generic-functions #:specializer-direct-methods #:standard-instance-access #:subtypep #:typep #:update-dependent #:validate-superclass #:writer-method-class #:warn-on-defmethod-without-generic-function)) (in-package :closer-mop) (macrolet ((define-closer-common-lisp-package () (loop with symbols = (nunion (loop for sym being the external-symbols of :common-lisp if (find-symbol (symbol-name sym) :c2mop) collect it else collect sym) (loop for sym being the external-symbols of :c2mop collect sym)) with map = '() for symbol in symbols do (push (symbol-name symbol) (getf map (symbol-package symbol))) finally (return `(defpackage #:closer-common-lisp (:nicknames #:c2cl) (:use) ,@(loop for (package symbols) on map by #'cddr collect `(:import-from ,(package-name package) ,@symbols)) (:export ,@(mapcar #'symbol-name symbols))))))) (define-closer-common-lisp-package)) (defpackage #:closer-common-lisp-user (:nicknames #:c2cl-user) (:use #:closer-common-lisp))
06d87e4d8ed6b0c302ccda89ca53f3486b3b1ac37465a71623e499f660d4fe3b
clojerl/clojerl
clojerl.ExceptionInfo.erl
-module('clojerl.ExceptionInfo'). -include("clojerl.hrl"). -behavior('clojerl.IEquiv'). -behavior('clojerl.IError'). -behavior('clojerl.IExceptionInfo'). -behavior('clojerl.IHash'). -behavior('clojerl.IStringable'). -export([?CONSTRUCTOR/2, ?CONSTRUCTOR/3]). -export([equiv/2]). -export([ message/1 , message/2 ]). -export([ data/1 , cause/1 ]). -export([hash/1]). -export([str/1]). -export_type([type/0]). -type type() :: #{ ?TYPE => ?M , message => binary() , data => any() , cause => any() }. -spec ?CONSTRUCTOR(binary(), any()) -> type(). ?CONSTRUCTOR(Message, Data) when is_binary(Message) -> ?CONSTRUCTOR(Message, Data, ?NIL). -spec ?CONSTRUCTOR(binary(), any(), any()) -> type(). ?CONSTRUCTOR(_Message, ?NIL, _Cause) -> ErrorMessage = <<"Additional data must be non-nil.">>, erlang:error('clojerl.BadArgumentError':?CONSTRUCTOR(ErrorMessage)); ?CONSTRUCTOR(Message, Data, Cause) when is_binary(Message) -> #{ ?TYPE => ?M , message => Message , data => Data , cause => Cause }. %%------------------------------------------------------------------------------ Protocols %%------------------------------------------------------------------------------ %% clojerl.IEquiv equiv( #{?TYPE := ?M, message := Msg, data := Data, cause := Cause} , #{?TYPE := ?M, message := Msg, data := Data, cause := Cause} ) -> true; equiv(_, _) -> false. %% clojerl.IError message(#{?TYPE := ?M, message := Msg}) -> Msg. message(#{?TYPE := ?M} = ExInfo, Msg) -> ExInfo#{message := Msg}. %% clojerl.IExceptionInfo data(#{?TYPE := ?M, data := Data}) -> Data. cause(#{?TYPE := ?M, cause := Cause}) -> Cause. clojerl . IHash hash(#{?TYPE := ?M, data := Data}) -> erlang:phash2(Data). %% clojerl.IStringable str(#{?TYPE := ?M, message := Msg, data := Data}) -> DataBin = clj_rt:str(Data), clj_utils:error_str(?M, <<Msg/binary, " ", DataBin/binary>>).
null
https://raw.githubusercontent.com/clojerl/clojerl/506000465581d6349659898dd5025fa259d5cf28/src/erl/lang/errors/clojerl.ExceptionInfo.erl
erlang
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ clojerl.IEquiv clojerl.IError clojerl.IExceptionInfo clojerl.IStringable
-module('clojerl.ExceptionInfo'). -include("clojerl.hrl"). -behavior('clojerl.IEquiv'). -behavior('clojerl.IError'). -behavior('clojerl.IExceptionInfo'). -behavior('clojerl.IHash'). -behavior('clojerl.IStringable'). -export([?CONSTRUCTOR/2, ?CONSTRUCTOR/3]). -export([equiv/2]). -export([ message/1 , message/2 ]). -export([ data/1 , cause/1 ]). -export([hash/1]). -export([str/1]). -export_type([type/0]). -type type() :: #{ ?TYPE => ?M , message => binary() , data => any() , cause => any() }. -spec ?CONSTRUCTOR(binary(), any()) -> type(). ?CONSTRUCTOR(Message, Data) when is_binary(Message) -> ?CONSTRUCTOR(Message, Data, ?NIL). -spec ?CONSTRUCTOR(binary(), any(), any()) -> type(). ?CONSTRUCTOR(_Message, ?NIL, _Cause) -> ErrorMessage = <<"Additional data must be non-nil.">>, erlang:error('clojerl.BadArgumentError':?CONSTRUCTOR(ErrorMessage)); ?CONSTRUCTOR(Message, Data, Cause) when is_binary(Message) -> #{ ?TYPE => ?M , message => Message , data => Data , cause => Cause }. Protocols equiv( #{?TYPE := ?M, message := Msg, data := Data, cause := Cause} , #{?TYPE := ?M, message := Msg, data := Data, cause := Cause} ) -> true; equiv(_, _) -> false. message(#{?TYPE := ?M, message := Msg}) -> Msg. message(#{?TYPE := ?M} = ExInfo, Msg) -> ExInfo#{message := Msg}. data(#{?TYPE := ?M, data := Data}) -> Data. cause(#{?TYPE := ?M, cause := Cause}) -> Cause. clojerl . IHash hash(#{?TYPE := ?M, data := Data}) -> erlang:phash2(Data). str(#{?TYPE := ?M, message := Msg, data := Data}) -> DataBin = clj_rt:str(Data), clj_utils:error_str(?M, <<Msg/binary, " ", DataBin/binary>>).
39b8e63eb4cba470e2ef8a11aa4e0ccfc74e9bb8379ce23689da8d7cda1bafce
oakes/Nightcoders
template.prod.clj
(require '[clojure.java.io :as io] '[cljs.build.api :as api]) (defn delete-children-recursively! [f] (when (.isDirectory f) (doseq [f2 (.listFiles f)] (delete-children-recursively! f2))) (when (.exists f) (io/delete-file f))) (defn build-cljs [file-name opts] (let [out-file (str "resources/nightcoders/" file-name ".js") out-dir (str "resources/nightcoders/" file-name ".out")] (println "Building" out-file) (delete-children-recursively! (io/file out-dir)) (api/build "src" (merge {:output-to out-file :output-dir out-dir} opts)) (delete-children-recursively! (io/file out-dir)))) (build-cljs "main" {:main '%s :optimizations :advanced})
null
https://raw.githubusercontent.com/oakes/Nightcoders/c1b48129b08fdf1a0093878cc9b3249f44a5f732/resources/template.prod.clj
clojure
(require '[clojure.java.io :as io] '[cljs.build.api :as api]) (defn delete-children-recursively! [f] (when (.isDirectory f) (doseq [f2 (.listFiles f)] (delete-children-recursively! f2))) (when (.exists f) (io/delete-file f))) (defn build-cljs [file-name opts] (let [out-file (str "resources/nightcoders/" file-name ".js") out-dir (str "resources/nightcoders/" file-name ".out")] (println "Building" out-file) (delete-children-recursively! (io/file out-dir)) (api/build "src" (merge {:output-to out-file :output-dir out-dir} opts)) (delete-children-recursively! (io/file out-dir)))) (build-cljs "main" {:main '%s :optimizations :advanced})
d9e3711034a1c78841edb524798a987b81584d2c62ed3f782a18432769cf9aff
joinr/spork
primitive.clj
This is , more or less , a port of shape primitives from excellent book The Haskell School of Expression . I 'd like to port it ;eventually...for now it's not doing anything. (ns spork.geometry.primitive) ;ellipse :: Point -> Point -> Graphic : : Point - > Point - > Point - > Graphic ;line :: Point -> Point -> Graphic ;polygon :: [Point] -> Graphic ;polyline :: [Point] -> Graphic ; ;fillTri x y size w = ; drawInWindow w ( withColor Blue ; (polygon [(x,y), ; (x+size,y), ; (x,y-size)])) ; ; ;data Shape = Rectangle Side Side ; | Ellipse Radius Radius ; | RtTriangle Side Side ; | Polygon [ Vertex ] ; deriving Show ; type Vertex = ( Float , Float ) ;type Side = Float ;type Radius = Float ; ; ;inchToPixel :: Float -> Int inchToPixel x = round ( 100*x ) ; ;pixelToInch :: Int -> Float pixelToInch n = intToFloat n / 100 ; ;intToFloat :: Int -> Float intToFloat n = fromInteger ( toInteger n ) ; ; ;trans :: Vertex -> Point ;trans (x,y) = ( xWin2 + inchToPixel x, ; yWin2 - inchToPixel y ) ; ;transList :: [Vertex] -> [Point] ;transList [] = [] transList ( p : ps ) = trans p : transList ps ; ;;A ray is a vector, originating at a point, that extends infinitely in the ;;direction defined by another point. Direction should be a unit-vector. (defn ->ray [origin dir] {:origin origin :dir (vmath/v-unit dir)})
null
https://raw.githubusercontent.com/joinr/spork/bb80eddadf90bf92745bf5315217e25a99fbf9d6/obe/geometry/primitive.clj
clojure
eventually...for now it's not doing anything. ellipse :: Point -> Point -> Graphic line :: Point -> Point -> Graphic polygon :: [Point] -> Graphic polyline :: [Point] -> Graphic fillTri x y size w = drawInWindow w (polygon [(x,y), (x+size,y), (x,y-size)])) data Shape = Rectangle Side Side | Ellipse Radius Radius | RtTriangle Side Side | Polygon [ Vertex ] deriving Show type Side = Float type Radius = Float inchToPixel :: Float -> Int pixelToInch :: Int -> Float intToFloat :: Int -> Float trans :: Vertex -> Point trans (x,y) = ( xWin2 + inchToPixel x, yWin2 - inchToPixel y ) transList :: [Vertex] -> [Point] transList [] = [] A ray is a vector, originating at a point, that extends infinitely in the direction defined by another point. Direction should be a unit-vector.
This is , more or less , a port of shape primitives from excellent book The Haskell School of Expression . I 'd like to port it (ns spork.geometry.primitive) : : Point - > Point - > Point - > Graphic ( withColor Blue type Vertex = ( Float , Float ) inchToPixel x = round ( 100*x ) pixelToInch n = intToFloat n / 100 intToFloat n = fromInteger ( toInteger n ) transList ( p : ps ) = trans p : transList ps (defn ->ray [origin dir] {:origin origin :dir (vmath/v-unit dir)})
14d815b96cc338649434b3fa51878fc87cbd9d8c13c2148ea4600563cabfd50f
danilkolikov/dfl
Type.hs
| Module : Frontend . Inference . Type Description : Definition of a type Copyright : ( c ) , 2019 License : MIT Module with the definition of a type Module : Frontend.Inference.Type Description : Definition of a type Copyright : (c) Danil Kolikov, 2019 License : MIT Module with the definition of a type -} module Frontend.Inference.Type where import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import qualified Data.List.NonEmpty as NE import Core.Ident import Core.PredefinedIdents import Data.Maybe (fromMaybe) import qualified Frontend.Desugaring.Final.Ast as F import Frontend.Inference.AlgebraicExp import Frontend.Inference.Substitution import Frontend.Inference.WithVariables import Frontend.Syntax.Position -- | Type of an expression data Type = TypeVar Ident -- ^ Type variable | TypeConstr Ident -- ^ Type constructor | TypeFunction Type Type -- ^ Function type | TypeApplication Type (NE.NonEmpty Type) -- ^ Application of a type constructor deriving (Eq, Show) instance Substitutable Type where substitute sub type' = case type' of TypeVar ident -> fromMaybe type' (HM.lookup ident sub) TypeConstr ident -> TypeConstr ident TypeFunction from to -> TypeFunction (substitute sub from) (substitute sub to) TypeApplication func args -> TypeApplication (substitute sub func) (fmap (substitute sub) args) instance WithVariables Type where getVariableName type' = case type' of TypeVar name -> Just name _ -> Nothing getFreeVariables type' = case type' of TypeVar ident -> HS.singleton ident TypeConstr _ -> HS.empty TypeFunction from to -> getFreeVariables from `HS.union` getFreeVariables to TypeApplication func args -> HS.unions $ getFreeVariables func : map getFreeVariables (NE.toList args) instance IsAlgebraicExp Type where toAlgebraicExp kind = case kind of TypeVar name -> AlgebraicExpVar name TypeConstr name -> AlgebraicExpFunc name [] TypeFunction from to -> AlgebraicExpFunc (IdentUserDefined aPPLICATION) [ AlgebraicExpFunc (IdentUserDefined fUNCTION) [] , toAlgebraicExp from , toAlgebraicExp to ] TypeApplication func args -> AlgebraicExpFunc (IdentUserDefined aPPLICATION) (toAlgebraicExp func : map toAlgebraicExp (NE.toList args)) fromAlgebraicExp aExp = case aExp of AlgebraicExpVar name -> return $ TypeVar name AlgebraicExpFunc ident args | [] <- args -> return $ TypeConstr ident | func:rest <- args , IdentUserDefined name <- ident , name == aPPLICATION -> do funcType <- fromAlgebraicExp func restType <- mapM fromAlgebraicExp rest if funcType == TypeConstr (IdentUserDefined fUNCTION) && length restType == 2 then return $ TypeFunction (head restType) (last restType) else case restType of [] -> Nothing hd:tl -> return $ TypeApplication funcType (hd NE.:| tl) | otherwise -> Nothing -- | Drops information about positions removePositionsOfType :: WithLocation F.Type -> Type removePositionsOfType type' = case getValue type' of F.TypeVar name -> TypeVar (getValue name) F.TypeConstr name -> TypeConstr (getValue name) F.TypeFunction from to -> TypeFunction (removePositionsOfType from) (removePositionsOfType to) F.TypeApplication func args -> TypeApplication (removePositionsOfType func) (fmap removePositionsOfType args)
null
https://raw.githubusercontent.com/danilkolikov/dfl/698a8f32e23b381afe803fc0e353293a3bf644ba/src/Frontend/Inference/Type.hs
haskell
| Type of an expression ^ Type variable ^ Type constructor ^ Function type ^ Application of a type constructor | Drops information about positions
| Module : Frontend . Inference . Type Description : Definition of a type Copyright : ( c ) , 2019 License : MIT Module with the definition of a type Module : Frontend.Inference.Type Description : Definition of a type Copyright : (c) Danil Kolikov, 2019 License : MIT Module with the definition of a type -} module Frontend.Inference.Type where import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import qualified Data.List.NonEmpty as NE import Core.Ident import Core.PredefinedIdents import Data.Maybe (fromMaybe) import qualified Frontend.Desugaring.Final.Ast as F import Frontend.Inference.AlgebraicExp import Frontend.Inference.Substitution import Frontend.Inference.WithVariables import Frontend.Syntax.Position data Type | TypeFunction Type | TypeApplication Type deriving (Eq, Show) instance Substitutable Type where substitute sub type' = case type' of TypeVar ident -> fromMaybe type' (HM.lookup ident sub) TypeConstr ident -> TypeConstr ident TypeFunction from to -> TypeFunction (substitute sub from) (substitute sub to) TypeApplication func args -> TypeApplication (substitute sub func) (fmap (substitute sub) args) instance WithVariables Type where getVariableName type' = case type' of TypeVar name -> Just name _ -> Nothing getFreeVariables type' = case type' of TypeVar ident -> HS.singleton ident TypeConstr _ -> HS.empty TypeFunction from to -> getFreeVariables from `HS.union` getFreeVariables to TypeApplication func args -> HS.unions $ getFreeVariables func : map getFreeVariables (NE.toList args) instance IsAlgebraicExp Type where toAlgebraicExp kind = case kind of TypeVar name -> AlgebraicExpVar name TypeConstr name -> AlgebraicExpFunc name [] TypeFunction from to -> AlgebraicExpFunc (IdentUserDefined aPPLICATION) [ AlgebraicExpFunc (IdentUserDefined fUNCTION) [] , toAlgebraicExp from , toAlgebraicExp to ] TypeApplication func args -> AlgebraicExpFunc (IdentUserDefined aPPLICATION) (toAlgebraicExp func : map toAlgebraicExp (NE.toList args)) fromAlgebraicExp aExp = case aExp of AlgebraicExpVar name -> return $ TypeVar name AlgebraicExpFunc ident args | [] <- args -> return $ TypeConstr ident | func:rest <- args , IdentUserDefined name <- ident , name == aPPLICATION -> do funcType <- fromAlgebraicExp func restType <- mapM fromAlgebraicExp rest if funcType == TypeConstr (IdentUserDefined fUNCTION) && length restType == 2 then return $ TypeFunction (head restType) (last restType) else case restType of [] -> Nothing hd:tl -> return $ TypeApplication funcType (hd NE.:| tl) | otherwise -> Nothing removePositionsOfType :: WithLocation F.Type -> Type removePositionsOfType type' = case getValue type' of F.TypeVar name -> TypeVar (getValue name) F.TypeConstr name -> TypeConstr (getValue name) F.TypeFunction from to -> TypeFunction (removePositionsOfType from) (removePositionsOfType to) F.TypeApplication func args -> TypeApplication (removePositionsOfType func) (fmap removePositionsOfType args)
183188942702ce54ce6500630ae7bd5532252f4a3b5d4001b5416870fdb061df
wireless-net/erlang-nommu
tls_record.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2007 - 2014 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %% %%---------------------------------------------------------------------- Purpose : Handle TLS / SSL record protocol . ( Parts that are not shared with DTLS ) %%---------------------------------------------------------------------- -module(tls_record). -include("tls_record.hrl"). -include("ssl_internal.hrl"). -include("ssl_alert.hrl"). -include("tls_handshake.hrl"). -include("ssl_cipher.hrl"). %% Handling of incoming data -export([get_tls_records/2]). %% Decoding -export([decode_cipher_text/2]). %% Encoding -export([encode_plain_text/4]). Protocol version handling -export([protocol_version/1, lowest_protocol_version/2, highest_protocol_version/1, supported_protocol_versions/0, is_acceptable_version/1, is_acceptable_version/2]). -export_type([tls_version/0, tls_atom_version/0]). -type tls_version() :: ssl_record:ssl_version(). -type tls_atom_version() :: sslv3 | tlsv1 | 'tlsv1.1' | 'tlsv1.2'. -compile(inline). %%==================================================================== Internal application API %%==================================================================== %%-------------------------------------------------------------------- -spec get_tls_records(binary(), binary()) -> {[binary()], binary()} | #alert{}. %% %% Description: Given old buffer and new data from TCP, packs up a records %% and returns it as a list of tls_compressed binaries also returns leftover %% data %%-------------------------------------------------------------------- get_tls_records(Data, <<>>) -> get_tls_records_aux(Data, []); get_tls_records(Data, Buffer) -> get_tls_records_aux(list_to_binary([Buffer, Data]), []). get_tls_records_aux(<<?BYTE(?APPLICATION_DATA),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?APPLICATION_DATA, version = {MajVer, MinVer}, fragment = Data} | Acc]); get_tls_records_aux(<<?BYTE(?HANDSHAKE),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?HANDSHAKE, version = {MajVer, MinVer}, fragment = Data} | Acc]); get_tls_records_aux(<<?BYTE(?ALERT),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?ALERT, version = {MajVer, MinVer}, fragment = Data} | Acc]); get_tls_records_aux(<<?BYTE(?CHANGE_CIPHER_SPEC),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?CHANGE_CIPHER_SPEC, version = {MajVer, MinVer}, fragment = Data} | Acc]); %% Matches an ssl v2 client hello message. %% The server must be able to receive such messages, from clients that %% are willing to use ssl v3 or higher, but have ssl v2 compatibility. get_tls_records_aux(<<1:1, Length0:15, Data0:Length0/binary, Rest/binary>>, Acc) -> case Data0 of <<?BYTE(?CLIENT_HELLO), ?BYTE(MajVer), ?BYTE(MinVer), _/binary>> -> Length = Length0-1, <<?BYTE(_), Data1:Length/binary>> = Data0, Data = <<?BYTE(?CLIENT_HELLO), ?UINT24(Length), Data1/binary>>, get_tls_records_aux(Rest, [#ssl_tls{type = ?HANDSHAKE, version = {MajVer, MinVer}, fragment = Data} | Acc]); _ -> ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE) end; get_tls_records_aux(<<0:1, _CT:7, ?BYTE(_MajVer), ?BYTE(_MinVer), ?UINT16(Length), _/binary>>, _Acc) when Length > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_tls_records_aux(<<1:1, Length0:15, _/binary>>,_Acc) when Length0 > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_tls_records_aux(Data, Acc) -> case size(Data) =< ?MAX_CIPHER_TEXT_LENGTH + ?INITIAL_BYTES of true -> {lists:reverse(Acc), Data}; false -> ?ALERT_REC(?FATAL, ?UNEXPECTED_MESSAGE) end. encode_plain_text(Type, Version, Data, #connection_states{current_write = #connection_state{ sequence_number = Seq, compression_state=CompS0, security_parameters= #security_parameters{compression_algorithm=CompAlg} }= WriteState0} = ConnectionStates) -> {Comp, CompS1} = ssl_record:compress(CompAlg, Data, CompS0), WriteState1 = WriteState0#connection_state{compression_state = CompS1}, MacHash = calc_mac_hash(Type, Version, Comp, WriteState1), {CipherFragment, WriteState} = ssl_record:cipher(Version, Comp, WriteState1, MacHash), CipherText = encode_tls_cipher_text(Type, Version, CipherFragment), {CipherText, ConnectionStates#connection_states{current_write = WriteState#connection_state{sequence_number = Seq +1}}}. %%-------------------------------------------------------------------- -spec decode_cipher_text(#ssl_tls{}, #connection_states{}) -> {#ssl_tls{}, #connection_states{}}| #alert{}. %% %% Description: Decode cipher text %%-------------------------------------------------------------------- decode_cipher_text(#ssl_tls{type = Type, version = Version, fragment = CipherFragment} = CipherText, ConnnectionStates0) -> ReadState0 = ConnnectionStates0#connection_states.current_read, #connection_state{compression_state = CompressionS0, sequence_number = Seq, security_parameters = SecParams} = ReadState0, CompressAlg = SecParams#security_parameters.compression_algorithm, {PlainFragment, Mac, ReadState1} = ssl_record:decipher(Version, CipherFragment, ReadState0), MacHash = calc_mac_hash(Type, Version, PlainFragment, ReadState1), case ssl_record:is_correct_mac(Mac, MacHash) of true -> {Plain, CompressionS1} = ssl_record:uncompress(CompressAlg, PlainFragment, CompressionS0), ConnnectionStates = ConnnectionStates0#connection_states{ current_read = ReadState1#connection_state{ sequence_number = Seq + 1, compression_state = CompressionS1}}, {CipherText#ssl_tls{fragment = Plain}, ConnnectionStates}; false -> ?ALERT_REC(?FATAL, ?BAD_RECORD_MAC) end. %%-------------------------------------------------------------------- -spec protocol_version(tls_atom_version() | tls_version()) -> tls_version() | tls_atom_version(). %% %% Description: Creates a protocol version record from a version atom %% or vice versa. %%-------------------------------------------------------------------- protocol_version('tlsv1.2') -> {3, 3}; protocol_version('tlsv1.1') -> {3, 2}; protocol_version(tlsv1) -> {3, 1}; protocol_version(sslv3) -> {3, 0}; protocol_version(sslv2) -> %% Backwards compatibility {2, 0}; protocol_version({3, 3}) -> 'tlsv1.2'; protocol_version({3, 2}) -> 'tlsv1.1'; protocol_version({3, 1}) -> tlsv1; protocol_version({3, 0}) -> sslv3. %%-------------------------------------------------------------------- -spec lowest_protocol_version(tls_version(), tls_version()) -> tls_version(). %% Description : Lowes protocol version of two given versions %%-------------------------------------------------------------------- lowest_protocol_version(Version = {M, N}, {M, O}) when N < O -> Version; lowest_protocol_version({M, _}, Version = {M, _}) -> Version; lowest_protocol_version(Version = {M,_}, {N, _}) when M < N -> Version; lowest_protocol_version(_,Version) -> Version. %%-------------------------------------------------------------------- -spec highest_protocol_version([tls_version()]) -> tls_version(). %% %% Description: Highest protocol version present in a list %%-------------------------------------------------------------------- highest_protocol_version([]) -> highest_protocol_version(); highest_protocol_version(Versions) -> [Ver | Vers] = Versions, highest_protocol_version(Ver, Vers). highest_protocol_version(Version, []) -> Version; highest_protocol_version(Version = {N, M}, [{N, O} | Rest]) when M > O -> highest_protocol_version(Version, Rest); highest_protocol_version({M, _}, [Version = {M, _} | Rest]) -> highest_protocol_version(Version, Rest); highest_protocol_version(Version = {M,_}, [{N,_} | Rest]) when M > N -> highest_protocol_version(Version, Rest); highest_protocol_version(_, [Version | Rest]) -> highest_protocol_version(Version, Rest). %%-------------------------------------------------------------------- -spec supported_protocol_versions() -> [tls_version()]. %% %% Description: Protocol versions supported %%-------------------------------------------------------------------- supported_protocol_versions() -> Fun = fun(Version) -> protocol_version(Version) end, case application:get_env(ssl, protocol_version) of undefined -> lists:map(Fun, supported_protocol_versions([])); {ok, []} -> lists:map(Fun, supported_protocol_versions([])); {ok, Vsns} when is_list(Vsns) -> Versions = lists:filter(fun is_acceptable_version/1, lists:map(Fun, Vsns)), supported_protocol_versions(Versions); {ok, Vsn} -> Versions = lists:filter(fun is_acceptable_version/1, [Fun(Vsn)]), supported_protocol_versions(Versions) end. supported_protocol_versions([]) -> Vsns = case sufficient_tlsv1_2_crypto_support() of true -> ?ALL_SUPPORTED_VERSIONS; false -> ?MIN_SUPPORTED_VERSIONS end, application:set_env(ssl, protocol_version, Vsns), Vsns; supported_protocol_versions([_|_] = Vsns) -> Vsns. %%-------------------------------------------------------------------- %% Description : ssl version 2 is not acceptable security risks are too big . %% %%-------------------------------------------------------------------- -spec is_acceptable_version(tls_version()) -> boolean(). is_acceptable_version({N,_}) when N >= ?LOWEST_MAJOR_SUPPORTED_VERSION -> true; is_acceptable_version(_) -> false. -spec is_acceptable_version(tls_version(), Supported :: [tls_version()]) -> boolean(). is_acceptable_version({N,_} = Version, Versions) when N >= ?LOWEST_MAJOR_SUPPORTED_VERSION -> lists:member(Version, Versions); is_acceptable_version(_,_) -> false. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- encode_tls_cipher_text(Type, {MajVer, MinVer}, Fragment) -> Length = erlang:iolist_size(Fragment), [<<?BYTE(Type), ?BYTE(MajVer), ?BYTE(MinVer), ?UINT16(Length)>>, Fragment]. mac_hash({_,_}, ?NULL, _MacSecret, _SeqNo, _Type, _Length, _Fragment) -> <<>>; mac_hash({3, 0}, MacAlg, MacSecret, SeqNo, Type, Length, Fragment) -> ssl_v3:mac_hash(MacAlg, MacSecret, SeqNo, Type, Length, Fragment); mac_hash({3, N} = Version, MacAlg, MacSecret, SeqNo, Type, Length, Fragment) when N =:= 1; N =:= 2; N =:= 3 -> tls_v1:mac_hash(MacAlg, MacSecret, SeqNo, Type, Version, Length, Fragment). highest_protocol_version() -> highest_protocol_version(supported_protocol_versions()). sufficient_tlsv1_2_crypto_support() -> CryptoSupport = crypto:supports(), proplists:get_bool(sha256, proplists:get_value(hashs, CryptoSupport)). calc_mac_hash(Type, Version, PlainFragment, #connection_state{sequence_number = SeqNo, mac_secret = MacSecret, security_parameters = SecPars}) -> Length = erlang:iolist_size(PlainFragment), mac_hash(Version, SecPars#security_parameters.mac_algorithm, MacSecret, SeqNo, Type, Length, PlainFragment).
null
https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/ssl/src/tls_record.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ---------------------------------------------------------------------- ---------------------------------------------------------------------- Handling of incoming data Decoding Encoding ==================================================================== ==================================================================== -------------------------------------------------------------------- Description: Given old buffer and new data from TCP, packs up a records and returns it as a list of tls_compressed binaries also returns leftover data -------------------------------------------------------------------- Matches an ssl v2 client hello message. The server must be able to receive such messages, from clients that are willing to use ssl v3 or higher, but have ssl v2 compatibility. -------------------------------------------------------------------- Description: Decode cipher text -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Creates a protocol version record from a version atom or vice versa. -------------------------------------------------------------------- Backwards compatibility -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Highest protocol version present in a list -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Protocol versions supported -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright Ericsson AB 2007 - 2014 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " Purpose : Handle TLS / SSL record protocol . ( Parts that are not shared with DTLS ) -module(tls_record). -include("tls_record.hrl"). -include("ssl_internal.hrl"). -include("ssl_alert.hrl"). -include("tls_handshake.hrl"). -include("ssl_cipher.hrl"). -export([get_tls_records/2]). -export([decode_cipher_text/2]). -export([encode_plain_text/4]). Protocol version handling -export([protocol_version/1, lowest_protocol_version/2, highest_protocol_version/1, supported_protocol_versions/0, is_acceptable_version/1, is_acceptable_version/2]). -export_type([tls_version/0, tls_atom_version/0]). -type tls_version() :: ssl_record:ssl_version(). -type tls_atom_version() :: sslv3 | tlsv1 | 'tlsv1.1' | 'tlsv1.2'. -compile(inline). Internal application API -spec get_tls_records(binary(), binary()) -> {[binary()], binary()} | #alert{}. get_tls_records(Data, <<>>) -> get_tls_records_aux(Data, []); get_tls_records(Data, Buffer) -> get_tls_records_aux(list_to_binary([Buffer, Data]), []). get_tls_records_aux(<<?BYTE(?APPLICATION_DATA),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?APPLICATION_DATA, version = {MajVer, MinVer}, fragment = Data} | Acc]); get_tls_records_aux(<<?BYTE(?HANDSHAKE),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?HANDSHAKE, version = {MajVer, MinVer}, fragment = Data} | Acc]); get_tls_records_aux(<<?BYTE(?ALERT),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?ALERT, version = {MajVer, MinVer}, fragment = Data} | Acc]); get_tls_records_aux(<<?BYTE(?CHANGE_CIPHER_SPEC),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_tls_records_aux(Rest, [#ssl_tls{type = ?CHANGE_CIPHER_SPEC, version = {MajVer, MinVer}, fragment = Data} | Acc]); get_tls_records_aux(<<1:1, Length0:15, Data0:Length0/binary, Rest/binary>>, Acc) -> case Data0 of <<?BYTE(?CLIENT_HELLO), ?BYTE(MajVer), ?BYTE(MinVer), _/binary>> -> Length = Length0-1, <<?BYTE(_), Data1:Length/binary>> = Data0, Data = <<?BYTE(?CLIENT_HELLO), ?UINT24(Length), Data1/binary>>, get_tls_records_aux(Rest, [#ssl_tls{type = ?HANDSHAKE, version = {MajVer, MinVer}, fragment = Data} | Acc]); _ -> ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE) end; get_tls_records_aux(<<0:1, _CT:7, ?BYTE(_MajVer), ?BYTE(_MinVer), ?UINT16(Length), _/binary>>, _Acc) when Length > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_tls_records_aux(<<1:1, Length0:15, _/binary>>,_Acc) when Length0 > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_tls_records_aux(Data, Acc) -> case size(Data) =< ?MAX_CIPHER_TEXT_LENGTH + ?INITIAL_BYTES of true -> {lists:reverse(Acc), Data}; false -> ?ALERT_REC(?FATAL, ?UNEXPECTED_MESSAGE) end. encode_plain_text(Type, Version, Data, #connection_states{current_write = #connection_state{ sequence_number = Seq, compression_state=CompS0, security_parameters= #security_parameters{compression_algorithm=CompAlg} }= WriteState0} = ConnectionStates) -> {Comp, CompS1} = ssl_record:compress(CompAlg, Data, CompS0), WriteState1 = WriteState0#connection_state{compression_state = CompS1}, MacHash = calc_mac_hash(Type, Version, Comp, WriteState1), {CipherFragment, WriteState} = ssl_record:cipher(Version, Comp, WriteState1, MacHash), CipherText = encode_tls_cipher_text(Type, Version, CipherFragment), {CipherText, ConnectionStates#connection_states{current_write = WriteState#connection_state{sequence_number = Seq +1}}}. -spec decode_cipher_text(#ssl_tls{}, #connection_states{}) -> {#ssl_tls{}, #connection_states{}}| #alert{}. decode_cipher_text(#ssl_tls{type = Type, version = Version, fragment = CipherFragment} = CipherText, ConnnectionStates0) -> ReadState0 = ConnnectionStates0#connection_states.current_read, #connection_state{compression_state = CompressionS0, sequence_number = Seq, security_parameters = SecParams} = ReadState0, CompressAlg = SecParams#security_parameters.compression_algorithm, {PlainFragment, Mac, ReadState1} = ssl_record:decipher(Version, CipherFragment, ReadState0), MacHash = calc_mac_hash(Type, Version, PlainFragment, ReadState1), case ssl_record:is_correct_mac(Mac, MacHash) of true -> {Plain, CompressionS1} = ssl_record:uncompress(CompressAlg, PlainFragment, CompressionS0), ConnnectionStates = ConnnectionStates0#connection_states{ current_read = ReadState1#connection_state{ sequence_number = Seq + 1, compression_state = CompressionS1}}, {CipherText#ssl_tls{fragment = Plain}, ConnnectionStates}; false -> ?ALERT_REC(?FATAL, ?BAD_RECORD_MAC) end. -spec protocol_version(tls_atom_version() | tls_version()) -> tls_version() | tls_atom_version(). protocol_version('tlsv1.2') -> {3, 3}; protocol_version('tlsv1.1') -> {3, 2}; protocol_version(tlsv1) -> {3, 1}; protocol_version(sslv3) -> {3, 0}; {2, 0}; protocol_version({3, 3}) -> 'tlsv1.2'; protocol_version({3, 2}) -> 'tlsv1.1'; protocol_version({3, 1}) -> tlsv1; protocol_version({3, 0}) -> sslv3. -spec lowest_protocol_version(tls_version(), tls_version()) -> tls_version(). Description : Lowes protocol version of two given versions lowest_protocol_version(Version = {M, N}, {M, O}) when N < O -> Version; lowest_protocol_version({M, _}, Version = {M, _}) -> Version; lowest_protocol_version(Version = {M,_}, {N, _}) when M < N -> Version; lowest_protocol_version(_,Version) -> Version. -spec highest_protocol_version([tls_version()]) -> tls_version(). highest_protocol_version([]) -> highest_protocol_version(); highest_protocol_version(Versions) -> [Ver | Vers] = Versions, highest_protocol_version(Ver, Vers). highest_protocol_version(Version, []) -> Version; highest_protocol_version(Version = {N, M}, [{N, O} | Rest]) when M > O -> highest_protocol_version(Version, Rest); highest_protocol_version({M, _}, [Version = {M, _} | Rest]) -> highest_protocol_version(Version, Rest); highest_protocol_version(Version = {M,_}, [{N,_} | Rest]) when M > N -> highest_protocol_version(Version, Rest); highest_protocol_version(_, [Version | Rest]) -> highest_protocol_version(Version, Rest). -spec supported_protocol_versions() -> [tls_version()]. supported_protocol_versions() -> Fun = fun(Version) -> protocol_version(Version) end, case application:get_env(ssl, protocol_version) of undefined -> lists:map(Fun, supported_protocol_versions([])); {ok, []} -> lists:map(Fun, supported_protocol_versions([])); {ok, Vsns} when is_list(Vsns) -> Versions = lists:filter(fun is_acceptable_version/1, lists:map(Fun, Vsns)), supported_protocol_versions(Versions); {ok, Vsn} -> Versions = lists:filter(fun is_acceptable_version/1, [Fun(Vsn)]), supported_protocol_versions(Versions) end. supported_protocol_versions([]) -> Vsns = case sufficient_tlsv1_2_crypto_support() of true -> ?ALL_SUPPORTED_VERSIONS; false -> ?MIN_SUPPORTED_VERSIONS end, application:set_env(ssl, protocol_version, Vsns), Vsns; supported_protocol_versions([_|_] = Vsns) -> Vsns. Description : ssl version 2 is not acceptable security risks are too big . -spec is_acceptable_version(tls_version()) -> boolean(). is_acceptable_version({N,_}) when N >= ?LOWEST_MAJOR_SUPPORTED_VERSION -> true; is_acceptable_version(_) -> false. -spec is_acceptable_version(tls_version(), Supported :: [tls_version()]) -> boolean(). is_acceptable_version({N,_} = Version, Versions) when N >= ?LOWEST_MAJOR_SUPPORTED_VERSION -> lists:member(Version, Versions); is_acceptable_version(_,_) -> false. Internal functions encode_tls_cipher_text(Type, {MajVer, MinVer}, Fragment) -> Length = erlang:iolist_size(Fragment), [<<?BYTE(Type), ?BYTE(MajVer), ?BYTE(MinVer), ?UINT16(Length)>>, Fragment]. mac_hash({_,_}, ?NULL, _MacSecret, _SeqNo, _Type, _Length, _Fragment) -> <<>>; mac_hash({3, 0}, MacAlg, MacSecret, SeqNo, Type, Length, Fragment) -> ssl_v3:mac_hash(MacAlg, MacSecret, SeqNo, Type, Length, Fragment); mac_hash({3, N} = Version, MacAlg, MacSecret, SeqNo, Type, Length, Fragment) when N =:= 1; N =:= 2; N =:= 3 -> tls_v1:mac_hash(MacAlg, MacSecret, SeqNo, Type, Version, Length, Fragment). highest_protocol_version() -> highest_protocol_version(supported_protocol_versions()). sufficient_tlsv1_2_crypto_support() -> CryptoSupport = crypto:supports(), proplists:get_bool(sha256, proplists:get_value(hashs, CryptoSupport)). calc_mac_hash(Type, Version, PlainFragment, #connection_state{sequence_number = SeqNo, mac_secret = MacSecret, security_parameters = SecPars}) -> Length = erlang:iolist_size(PlainFragment), mac_hash(Version, SecPars#security_parameters.mac_algorithm, MacSecret, SeqNo, Type, Length, PlainFragment).
51fa1482531eef5b5af464b02a8fa0a1d80a228482df912be84649a1f66d4283
rorra/rorracasts_erlang
diccionario.erl
-module(diccionario). -compile(export_all). test() -> Constructor _D1 = dict:new(), %% Constructor desde una lista D2 = dict:from_list([{key3, [valor3]}, {key2, [valor2]}, {key1, valor}]), %% Diccionario a lista io:format("El diccionario a lista es ~w\n", [dict:to_list(D2)]), item D3 = dict:store(key4, 5, D2), valor a un item existente D4 = dict:append(key3, otro_valor, D3), Agregar una lista de valores a un item existente D5 = dict:append_list(key2, [un_valor, otro_valor], D4), %% Modificar un valor D6 = dict:update(key4, fun(X) -> X + 10 end, D5), existe una clave case dict:find(key2, D6) of {ok, Valor} -> io:format("La clave key2 existe y el valor es ~w\n", [Valor]); error -> io:format("La clave key2 no existe\n") end, case dict:find(foo, D6) of {ok, Valor1} -> io:fommat("La clave foo existe y el valor es ~w\n", [Valor1]); error -> io:format("La clave foo no existe\n") end, Acceso a un item sabiendo que existe la clave io:format("El valor que hay en la clave key1 es ~w\n", [dict:fetch(key1, D6)]), Iterando a traves del diccionario dict:map(fun(K, V) -> io:format("~w -> ~w\n", [K, V]) end, D6), %% Eliminar una llave D7 = dict:erase(key4, D6), D8 = dict:filter(fun(_Key, Value) -> is_atom(Value) end, D7), io:format("Diccionario filtrado: ~w\n", [dict:to_list(D8)]), D7.
null
https://raw.githubusercontent.com/rorra/rorracasts_erlang/c50d20abe3f1a65001576734caedae90f36e3ecd/006-dict-y-orddict/diccionario.erl
erlang
Constructor desde una lista Diccionario a lista Modificar un valor Eliminar una llave
-module(diccionario). -compile(export_all). test() -> Constructor _D1 = dict:new(), D2 = dict:from_list([{key3, [valor3]}, {key2, [valor2]}, {key1, valor}]), io:format("El diccionario a lista es ~w\n", [dict:to_list(D2)]), item D3 = dict:store(key4, 5, D2), valor a un item existente D4 = dict:append(key3, otro_valor, D3), Agregar una lista de valores a un item existente D5 = dict:append_list(key2, [un_valor, otro_valor], D4), D6 = dict:update(key4, fun(X) -> X + 10 end, D5), existe una clave case dict:find(key2, D6) of {ok, Valor} -> io:format("La clave key2 existe y el valor es ~w\n", [Valor]); error -> io:format("La clave key2 no existe\n") end, case dict:find(foo, D6) of {ok, Valor1} -> io:fommat("La clave foo existe y el valor es ~w\n", [Valor1]); error -> io:format("La clave foo no existe\n") end, Acceso a un item sabiendo que existe la clave io:format("El valor que hay en la clave key1 es ~w\n", [dict:fetch(key1, D6)]), Iterando a traves del diccionario dict:map(fun(K, V) -> io:format("~w -> ~w\n", [K, V]) end, D6), D7 = dict:erase(key4, D6), D8 = dict:filter(fun(_Key, Value) -> is_atom(Value) end, D7), io:format("Diccionario filtrado: ~w\n", [dict:to_list(D8)]), D7.
0318702937ffb41b0123f768ee743e8a947e66fa8b0534fbe92d6da84813805f
ivanjovanovic/sicp
e-5.4.scm
Exercise 5.4 . Specify register machines that implement each of the ; following procedures. For each machine, write a controller instruction ; sequence and draw a diagram showing the data paths. ; a. Recursive exponentiation: (define (expt b n) (if (= n 0) 1 (* b (expt b (- n 1))))) ; b. Iterative exponentiation: (define (expt b n) (define (expt-iter counter product) (if (= counter 0) product (expt-iter (- counter 1) (* b product)))) (expt-iter n 1)) ; ------------------------------------------------------------ ; I will just define the machines. a ) based n already given implementation in 5.1.scm we can similarly ; implement exponential. (controller (assign continue (label expt-done)) expt-loop (test (op =) (reg n) (const 0)) (branch (label base-case)) ; save current state and continue at after-expt (save continue) (save n) (assign n (op -) (reg n) (const 1)) (assign continue (label after-fact)) (goto (label expt-loop)) after-expt (restore n) (restore continue) (assign val (op *) (reg b) (reg val)) (goto (reg continue)) base-case (assign val (const 1)) (goto (reg continue)) expt-done) ; b) This is similar to the iterative machines we have already defined ; before. (controller init (assign counter (read)) ; assuming read is a primitive (assign base (read)) (assign product (const 1)) expt-iter (test (op =) (reg counter) (const 0)) (branch (label expt-done)) (assign counter (op -) (reg counter) (const 1)) (assign product (op *) (reg base) (reg product)) (goto expt-iter) expt-done)
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/5.1/e-5.4.scm
scheme
following procedures. For each machine, write a controller instruction sequence and draw a diagram showing the data paths. a. Recursive exponentiation: b. Iterative exponentiation: ------------------------------------------------------------ I will just define the machines. implement exponential. save current state and continue at after-expt b) This is similar to the iterative machines we have already defined before. assuming read is a primitive
Exercise 5.4 . Specify register machines that implement each of the (define (expt b n) (if (= n 0) 1 (* b (expt b (- n 1))))) (define (expt b n) (define (expt-iter counter product) (if (= counter 0) product (expt-iter (- counter 1) (* b product)))) (expt-iter n 1)) a ) based n already given implementation in 5.1.scm we can similarly (controller (assign continue (label expt-done)) expt-loop (test (op =) (reg n) (const 0)) (branch (label base-case)) (save continue) (save n) (assign n (op -) (reg n) (const 1)) (assign continue (label after-fact)) (goto (label expt-loop)) after-expt (restore n) (restore continue) (assign val (op *) (reg b) (reg val)) (goto (reg continue)) base-case (assign val (const 1)) (goto (reg continue)) expt-done) (controller init (assign base (read)) (assign product (const 1)) expt-iter (test (op =) (reg counter) (const 0)) (branch (label expt-done)) (assign counter (op -) (reg counter) (const 1)) (assign product (op *) (reg base) (reg product)) (goto expt-iter) expt-done)
74af562050a70e61b2760ccd878fc57ca0675589f9f1798bbb4b9daaface64a2
eareese/htdp-exercises
094-ufo-game-design.rkt
#lang htdp/bsl (require 2htdp/image) (require 2htdp/universe) ;; Exercise 94. Draw some sketches of what the [UFO and tank] game scenery looks ;; like at various stages. Use the sketches to determine the constant and the ;; variable pieces of the game. For the former, develop physical constants that ;; describe the dimensions of the world (canvas), its objects, and the graphical ;; constants used to render these objects. Then develop graphical constants for ;; the tank, the UFO, the missile, and some background scenery. Finally, create ;; your initial scene from the constants for the tank, the UFO, and the ;; background. ;; constants ;; canvas (define CANVAS (scene+curve (scene+curve (rectangle 200 200 "outline" "black") 0 195 10 1/2 100 195 10 1/3 "purple") 100 195 10 1/2 200 195 10 1/3 "purple")) (define TANK (rectangle 30 15 "solid" "blue")) (define TANK-Y (- (image-height CANVAS) (* 3/5 (image-height TANK)))) (define MISSILE (triangle 12 "solid" "tan")) (define UFO (overlay (circle 4 "solid" "green") (rectangle 20 2 "solid" "green"))) ;; INITIAL SCENE (place-images (list UFO TANK) (list (make-posn (* 1/2 (image-width CANVAS)) (image-height UFO)) (make-posn (* 1/2 (image-width CANVAS)) TANK-Y)) CANVAS)
null
https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part01-fixed-size-data/094-ufo-game-design.rkt
racket
Exercise 94. Draw some sketches of what the [UFO and tank] game scenery looks like at various stages. Use the sketches to determine the constant and the variable pieces of the game. For the former, develop physical constants that describe the dimensions of the world (canvas), its objects, and the graphical constants used to render these objects. Then develop graphical constants for the tank, the UFO, the missile, and some background scenery. Finally, create your initial scene from the constants for the tank, the UFO, and the background. constants canvas INITIAL SCENE
#lang htdp/bsl (require 2htdp/image) (require 2htdp/universe) (define CANVAS (scene+curve (scene+curve (rectangle 200 200 "outline" "black") 0 195 10 1/2 100 195 10 1/3 "purple") 100 195 10 1/2 200 195 10 1/3 "purple")) (define TANK (rectangle 30 15 "solid" "blue")) (define TANK-Y (- (image-height CANVAS) (* 3/5 (image-height TANK)))) (define MISSILE (triangle 12 "solid" "tan")) (define UFO (overlay (circle 4 "solid" "green") (rectangle 20 2 "solid" "green"))) (place-images (list UFO TANK) (list (make-posn (* 1/2 (image-width CANVAS)) (image-height UFO)) (make-posn (* 1/2 (image-width CANVAS)) TANK-Y)) CANVAS)
e57f0bb1e309130ad4628aada860ff7d09941d3f459fb76bc1df2a43838b235f
yrashk/erlang
erl_compile.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1997 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(erl_compile). -include("erl_compile.hrl"). -include("file.hrl"). -export([compile_cmdline/1]). %% Mapping from extension to {M,F} to run the correct compiler. compiler(".erl") -> {compile, compile}; compiler(".S") -> {compile, compile_asm}; compiler(".beam") -> {compile, compile_beam}; compiler(".core") -> {compile, compile_core}; compiler(".mib") -> {snmpc, compile}; compiler(".bin") -> {snmpc, mib_to_hrl}; compiler(".yrl") -> {yecc, compile}; compiler(".script") -> {systools, script2boot}; compiler(".rel") -> {systools, compile_rel}; compiler(".idl") -> {ic, compile}; compiler(".asn1") -> {asn1ct, compile_asn1}; compiler(".asn") -> {asn1ct, compile_asn}; compiler(".py") -> {asn1ct, compile_py}; compiler(".xml") -> {xmerl_scan, process}; compiler(_) -> no. %% Entry from command line. compile_cmdline(List) -> case compile(List) of ok -> my_halt(0); error -> my_halt(1); _ -> my_halt(2) end. my_halt(Reason) -> case process_info(group_leader(), status) of {_,waiting} -> %% Now all output data is down in the driver. %% Give the driver some extra time before halting. receive after 1 -> ok end, halt(Reason); _ -> %% Probably still processing I/O requests. erlang:yield(), my_halt(Reason) end. %% Run the the compiler in a separate process, trapping EXITs. compile(List) -> process_flag(trap_exit, true), Pid = spawn_link(fun() -> compiler_runner(List) end), receive {'EXIT', Pid, {compiler_result, Result}} -> Result; {'EXIT', Pid, Reason} -> io:format("Runtime error: ~p~n", [Reason]), error end. -spec compiler_runner([_]) -> no_return(). compiler_runner(List) -> %% We don't want the current directory in the code path. %% Remove it. Path = [D || D <- code:get_path(), D =/= "."], code:set_path(Path), exit({compiler_result, compile1(List)}). Parses the first part of the option list . compile1(['@cwd', Cwd|Rest]) -> CwdL = atom_to_list(Cwd), compile1(Rest, CwdL, #options{outdir=CwdL, cwd=CwdL}); compile1(Other) -> throw({error, {bad_input, Other}}). %% Parses all options. compile1(['@i', Dir|Rest], Cwd, Opts) -> AbsDir = filename:absname(Dir, Cwd), compile1(Rest, Cwd, Opts#options{includes=[AbsDir|Opts#options.includes]}); compile1(['@outdir', Dir|Rest], Cwd, Opts) -> AbsName = filename:absname(Dir, Cwd), case file_or_directory(AbsName) of file -> compile1(Rest, Cwd, Opts#options{outfile=AbsName}); directory -> compile1(Rest, Cwd, Opts#options{outdir=AbsName}) end; compile1(['@d', Name|Rest], Cwd, Opts) -> Defines = Opts#options.defines, compile1(Rest, Cwd, Opts#options{defines=[Name|Defines]}); compile1(['@dv', Name, Term|Rest], Cwd, Opts) -> Defines = Opts#options.defines, Value = make_term(atom_to_list(Term)), compile1(Rest, Cwd, Opts#options{defines=[{Name, Value}|Defines]}); compile1(['@warn', Level0|Rest], Cwd, Opts) -> case catch list_to_integer(atom_to_list(Level0)) of Level when is_integer(Level) -> compile1(Rest, Cwd, Opts#options{warning=Level}); _ -> compile1(Rest, Cwd, Opts) end; compile1(['@verbose', false|Rest], Cwd, Opts) -> compile1(Rest, Cwd, Opts#options{verbose=false}); compile1(['@verbose', true|Rest], Cwd, Opts) -> compile1(Rest, Cwd, Opts#options{verbose=true}); compile1(['@optimize', Atom|Rest], Cwd, Opts) -> Term = make_term(atom_to_list(Atom)), compile1(Rest, Cwd, Opts#options{optimize=Term}); compile1(['@option', Atom|Rest], Cwd, Opts) -> Term = make_term(atom_to_list(Atom)), Specific = Opts#options.specific, compile1(Rest, Cwd, Opts#options{specific=[Term|Specific]}); compile1(['@output_type', OutputType|Rest], Cwd, Opts) -> compile1(Rest, Cwd, Opts#options{output_type=OutputType}); compile1(['@files'|Rest], Cwd, Opts) -> Includes = lists:reverse(Opts#options.includes), compile2(Rest, Cwd, Opts#options{includes=Includes}). compile2(Files, Cwd, Opts) -> case {Opts#options.outfile, length(Files)} of {"", _} -> compile3(Files, Cwd, Opts); {[_|_], 1} -> compile3(Files, Cwd, Opts); {[_|_], _N} -> io:format("Output file name given, but more than one input file.~n"), error end. %% Compiles the list of files, until done or compilation fails. compile3([File|Rest], Cwd, Options) -> Ext = filename:extension(File), Root = filename:rootname(File), InFile = filename:absname(Root, Cwd), OutFile = case Options#options.outfile of "" -> filename:join(Options#options.outdir, filename:basename(Root)); Outfile -> filename:rootname(Outfile) end, case compile_file(Ext, InFile, OutFile, Options) of ok -> compile3(Rest, Cwd, Options); Other -> Other end; compile3([], _Cwd, _Options) -> ok. Invokes the appropriate compiler , depending on the file extension . compile_file("", Input, _Output, _Options) -> io:format("File has no extension: ~s~n", [Input]), error; compile_file(Ext, Input, Output, Options) -> case compiler(Ext) of no -> io:format("Unknown extension: '~s'\n", [Ext]), error; {M, F} -> case catch M:F(Input, Output, Options) of ok -> ok; error -> error; {'EXIT',Reason} -> io:format("Compiler function ~w:~w/3 failed:\n~p~n", [M,F,Reason]), error; Other -> io:format("Compiler function ~w:~w/3 returned:\n~p~n", [M,F,Other]), error end end. %% Guesses if a give name refers to a file or a directory. file_or_directory(Name) -> case file:read_file_info(Name) of {ok, #file_info{type=regular}} -> file; {ok, _} -> directory; {error, _} -> case filename:extension(Name) of [] -> directory; _Other -> file end end. Makes an Erlang term given a string . make_term(Str) -> case erl_scan:string(Str) of {ok, Tokens, _} -> case erl_parse:parse_term(Tokens ++ [{dot, 1}]) of {ok, Term} -> Term; {error, {_,_,Reason}} -> io:format("~s: ~s~n", [Reason, Str]), throw(error) end; {error, {_,_,Reason}, _} -> io:format("~s: ~s~n", [Reason, Str]), throw(error) end.
null
https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/stdlib/src/erl_compile.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% Mapping from extension to {M,F} to run the correct compiler. Entry from command line. Now all output data is down in the driver. Give the driver some extra time before halting. Probably still processing I/O requests. Run the the compiler in a separate process, trapping EXITs. We don't want the current directory in the code path. Remove it. Parses all options. Compiles the list of files, until done or compilation fails. Guesses if a give name refers to a file or a directory.
Copyright Ericsson AB 1997 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(erl_compile). -include("erl_compile.hrl"). -include("file.hrl"). -export([compile_cmdline/1]). compiler(".erl") -> {compile, compile}; compiler(".S") -> {compile, compile_asm}; compiler(".beam") -> {compile, compile_beam}; compiler(".core") -> {compile, compile_core}; compiler(".mib") -> {snmpc, compile}; compiler(".bin") -> {snmpc, mib_to_hrl}; compiler(".yrl") -> {yecc, compile}; compiler(".script") -> {systools, script2boot}; compiler(".rel") -> {systools, compile_rel}; compiler(".idl") -> {ic, compile}; compiler(".asn1") -> {asn1ct, compile_asn1}; compiler(".asn") -> {asn1ct, compile_asn}; compiler(".py") -> {asn1ct, compile_py}; compiler(".xml") -> {xmerl_scan, process}; compiler(_) -> no. compile_cmdline(List) -> case compile(List) of ok -> my_halt(0); error -> my_halt(1); _ -> my_halt(2) end. my_halt(Reason) -> case process_info(group_leader(), status) of {_,waiting} -> receive after 1 -> ok end, halt(Reason); _ -> erlang:yield(), my_halt(Reason) end. compile(List) -> process_flag(trap_exit, true), Pid = spawn_link(fun() -> compiler_runner(List) end), receive {'EXIT', Pid, {compiler_result, Result}} -> Result; {'EXIT', Pid, Reason} -> io:format("Runtime error: ~p~n", [Reason]), error end. -spec compiler_runner([_]) -> no_return(). compiler_runner(List) -> Path = [D || D <- code:get_path(), D =/= "."], code:set_path(Path), exit({compiler_result, compile1(List)}). Parses the first part of the option list . compile1(['@cwd', Cwd|Rest]) -> CwdL = atom_to_list(Cwd), compile1(Rest, CwdL, #options{outdir=CwdL, cwd=CwdL}); compile1(Other) -> throw({error, {bad_input, Other}}). compile1(['@i', Dir|Rest], Cwd, Opts) -> AbsDir = filename:absname(Dir, Cwd), compile1(Rest, Cwd, Opts#options{includes=[AbsDir|Opts#options.includes]}); compile1(['@outdir', Dir|Rest], Cwd, Opts) -> AbsName = filename:absname(Dir, Cwd), case file_or_directory(AbsName) of file -> compile1(Rest, Cwd, Opts#options{outfile=AbsName}); directory -> compile1(Rest, Cwd, Opts#options{outdir=AbsName}) end; compile1(['@d', Name|Rest], Cwd, Opts) -> Defines = Opts#options.defines, compile1(Rest, Cwd, Opts#options{defines=[Name|Defines]}); compile1(['@dv', Name, Term|Rest], Cwd, Opts) -> Defines = Opts#options.defines, Value = make_term(atom_to_list(Term)), compile1(Rest, Cwd, Opts#options{defines=[{Name, Value}|Defines]}); compile1(['@warn', Level0|Rest], Cwd, Opts) -> case catch list_to_integer(atom_to_list(Level0)) of Level when is_integer(Level) -> compile1(Rest, Cwd, Opts#options{warning=Level}); _ -> compile1(Rest, Cwd, Opts) end; compile1(['@verbose', false|Rest], Cwd, Opts) -> compile1(Rest, Cwd, Opts#options{verbose=false}); compile1(['@verbose', true|Rest], Cwd, Opts) -> compile1(Rest, Cwd, Opts#options{verbose=true}); compile1(['@optimize', Atom|Rest], Cwd, Opts) -> Term = make_term(atom_to_list(Atom)), compile1(Rest, Cwd, Opts#options{optimize=Term}); compile1(['@option', Atom|Rest], Cwd, Opts) -> Term = make_term(atom_to_list(Atom)), Specific = Opts#options.specific, compile1(Rest, Cwd, Opts#options{specific=[Term|Specific]}); compile1(['@output_type', OutputType|Rest], Cwd, Opts) -> compile1(Rest, Cwd, Opts#options{output_type=OutputType}); compile1(['@files'|Rest], Cwd, Opts) -> Includes = lists:reverse(Opts#options.includes), compile2(Rest, Cwd, Opts#options{includes=Includes}). compile2(Files, Cwd, Opts) -> case {Opts#options.outfile, length(Files)} of {"", _} -> compile3(Files, Cwd, Opts); {[_|_], 1} -> compile3(Files, Cwd, Opts); {[_|_], _N} -> io:format("Output file name given, but more than one input file.~n"), error end. compile3([File|Rest], Cwd, Options) -> Ext = filename:extension(File), Root = filename:rootname(File), InFile = filename:absname(Root, Cwd), OutFile = case Options#options.outfile of "" -> filename:join(Options#options.outdir, filename:basename(Root)); Outfile -> filename:rootname(Outfile) end, case compile_file(Ext, InFile, OutFile, Options) of ok -> compile3(Rest, Cwd, Options); Other -> Other end; compile3([], _Cwd, _Options) -> ok. Invokes the appropriate compiler , depending on the file extension . compile_file("", Input, _Output, _Options) -> io:format("File has no extension: ~s~n", [Input]), error; compile_file(Ext, Input, Output, Options) -> case compiler(Ext) of no -> io:format("Unknown extension: '~s'\n", [Ext]), error; {M, F} -> case catch M:F(Input, Output, Options) of ok -> ok; error -> error; {'EXIT',Reason} -> io:format("Compiler function ~w:~w/3 failed:\n~p~n", [M,F,Reason]), error; Other -> io:format("Compiler function ~w:~w/3 returned:\n~p~n", [M,F,Other]), error end end. file_or_directory(Name) -> case file:read_file_info(Name) of {ok, #file_info{type=regular}} -> file; {ok, _} -> directory; {error, _} -> case filename:extension(Name) of [] -> directory; _Other -> file end end. Makes an Erlang term given a string . make_term(Str) -> case erl_scan:string(Str) of {ok, Tokens, _} -> case erl_parse:parse_term(Tokens ++ [{dot, 1}]) of {ok, Term} -> Term; {error, {_,_,Reason}} -> io:format("~s: ~s~n", [Reason, Str]), throw(error) end; {error, {_,_,Reason}, _} -> io:format("~s: ~s~n", [Reason, Str]), throw(error) end.
86e49f32cd871383e609dac0af823aaada924e0d3d00413459d3bd3fa33e8aff
manuel-serrano/bigloo
emit_cop.scm
;*=====================================================================*/ * ... /prgm / project / bigloo / / comptime / Cgen / emit_cop.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Tue Jul 2 14:39:37 1996 * / * Last change : Tue May 10 08:03:27 2022 ( serrano ) * / * Copyright : 1996 - 2022 , see LICENSE file * / ;* ------------------------------------------------------------- */ ;* The emission of cop code. */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module cgen_emit-cop (include "Tools/location.sch" "Tools/fprint.sch" "Tools/trace.sch") (import type_type type_tools type_cache type_typeof tools_shape engine_param ast_var ast_node ast_env backend_c_emit cgen_cop (*module-location* module_module)) (export (generic emit-cop::bool ::cop) (reset-bdb-loc!) (emit-bdb-loc ::obj) (get-current-bdb-loc))) ;*---------------------------------------------------------------------*/ ;* emit-cop ... */ ;* ------------------------------------------------------------- */ * If emit - cop emit an expression with a ` ; ' it returns # f , * / * otherwise it returns * / ;* ------------------------------------------------------------- */ ;* The general idea of that printer is that no specific printer */ ;* ever emit \n because they are emitted by the location printer. */ ;*---------------------------------------------------------------------*/ (define-generic (emit-cop::bool cop::cop)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::clabel ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::clabel) (with-access::clabel cop (used? name body loc) (if used? (begin (emit-bdb-loc loc) (display name *c-port*) (write-char #\: *c-port*))) (emit-cop body))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cgoto ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cgoto) (with-access::cgoto cop (label loc) (emit-bdb-loc loc) (fprin *c-port* "goto " (clabel-name label) #\;) #f)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cblock ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cblock) (with-access::cblock cop (body loc) (emit-bdb-loc loc) (if (isa? body cblock) (emit-cop body) (begin (display #"{ " *c-port*) (trace cgen (display "/* cop-block */" *c-port*)) (emit-bdb-loc-comment loc) (if (emit-cop body) (begin (emit-bdb-loc (get-current-bdb-loc)) (display "; " *c-port*) (trace cgen (display "/* cop-block */" *c-port*)))) (display "} " *c-port*) (trace cgen (display "/* cop-block */" *c-port*)) #f)))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::creturn ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::creturn) (with-access::creturn cop (value loc tail) (emit-bdb-loc loc) (when tail (display "BGL_TAIL " *c-port*)) (display "return " *c-port*) (if (emit-cop value) (write-char #\; *c-port*)) #f)) ;*---------------------------------------------------------------------*/ * emit - cop : : ... * / ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::catom) (with-access::catom cop (value) (emit-atom-value value) #t)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cvoid ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cvoid) (with-access::cvoid cop (value) (emit-cop value))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::varc ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::varc) (with-access::varc cop (variable) (if (when (isa? variable global) (with-access::global variable (value) (when (isa? value scnst) (with-access::scnst value (class) (eq? class 'sreal))))) (begin (display "BGL_REAL_CNST( " *c-port*) (display (variable-name variable) *c-port*) (display ")" *c-port*)) (display (variable-name variable) *c-port*)) #t)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cpragma ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cpragma) (with-access::cpragma cop (args format loc) (emit-bdb-loc loc) (if (null? args) (display format *c-port*) (let* ((sport (open-input-string format)) (args (list->vector args)) (parser (regular-grammar () ((: #\$ (+ (in (#\0 #\9)))) (let* ((str (the-string)) (len (the-length)) (index (string->number (substring str 1 len)))) (emit-cop (vector-ref args (-fx index 1))) (ignore))) ("$$" (display "$" *c-port*) (ignore)) ((+ (out #\$)) (display (the-string) *c-port*) (ignore)) (else (the-failure))))) (read/rp parser sport) (close-input-port sport) #t)))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::ccast ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::ccast) (with-access::ccast cop (arg type loc) (emit-bdb-loc loc) (display "((" *c-port*) (display (type-name type) *c-port*) (write-char #\) *c-port*) (emit-cop arg) (write-char #\) *c-port*) #t)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::csequence ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::csequence) (with-access::csequence cop (c-exp? cops loc) (if c-exp? (begin (if (null? cops) (emit-atom-value #unspecified) (begin (display "( " *c-port*) (trace cgen (display "/* cop-csequence */" *c-port*)) (let liip ((exp cops)) (if (null? (cdr exp)) (begin (emit-cop (car exp)) (display ") " *c-port*) (trace cgen "/* cop-csequence */" *c-port*) #t) (begin (emit-cop (car exp)) (if (cfail? (car exp)) (begin (display ") " *c-port*) (trace cgen "/* cop-csequence */" *c-port*) #t) (begin (display ", " *c-port*) (trace cgen "/* cop-csequence */" *c-port*) (liip (cdr exp)))))))))) (let liip ((exp cops)) (if (null? exp) #f (let ((e (car exp))) (if (emit-cop e) (begin (display "; " *c-port*) (trace cgen (display "/* cop-csequence */" *c-port*)))) (if (cfail? e) (liip '()) (liip (cdr exp))))))))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::nop ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::nop) (with-access::nop cop (loc) (display "; " *c-port*) (trace cgen (display "/* cop-nop */" *c-port*)) #f)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::stop ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::stop) (with-access::stop cop (value loc) (if (emit-cop value) ;; we don't have to emit a location here because the ;; location is held by the printed value (begin (display "; " *c-port*) (trace cgen (display "/* cop-stop */" *c-port*)))) #f)) ;*---------------------------------------------------------------------*/ * emit - cop : : ... * / ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::csetq) (with-access::csetq cop (var value loc) we first emit a location for this node (emit-bdb-loc loc) (emit-cop var) ;; don't omit to put space sourrounding `=' otherwise ;; it could become an ambiguous assignement (e.g. x=-1). (display " = " *c-port*) (emit-cop value) #t)) ;*---------------------------------------------------------------------*/ * emit - cop : : ... * / ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cif) (with-access::cif cop (test true false loc) (emit-bdb-loc loc) (display "if(" *c-port*) (emit-cop test) (write-char #\) *c-port*) (emit-cop true) (display " else " *c-port*) (emit-cop false))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::local ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::local-var) (with-access::local-var cop (vars loc) (emit-bdb-loc loc) (for-each (lambda (local) (with-access::local local (volatile type name) ;; volatile is used only the *local-exit?* is true (fprin *c-port* (if volatile "volatile " " ") (make-typed-declaration type name) (if (and (>fx *bdb-debug* 0) (eq? (type-class type) 'bigloo)) (string-append " = ((" (make-typed-declaration type "") ")BUNSPEC)") "") #\;))) vars) #f)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::bdb-block ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::bdb-block) (with-access::bdb-block cop (loc body) (emit-bdb-loc loc) (fprin *c-port* "int bigloo_dummy_bdb; bigloo_dummy_bdb = 0; { ") (emit-cop body) (display "} " *c-port*) (trace cgen (display " /* cop-bdb-block */" *c-port*)))) ;*---------------------------------------------------------------------*/ ;* cfuncall-casts ... */ ;*---------------------------------------------------------------------*/ (define cfuncall-casts (make-vector 32 #f)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cfuncall ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cfuncall) (define (fun-cast actuals) (let ((largs (length actuals))) (cond ((>=fx largs (vector-length cfuncall-casts)) (format "(obj_t (*)(~(, )))" (make-list largs "obj_t"))) ((vector-ref cfuncall-casts largs) => (lambda (p) p)) (else (let ((p (format "(obj_t (*)(~(, )))" (make-list largs "obj_t")))) (vector-set! cfuncall-casts largs p) p))))) (define (fun-l-cast actuals) (format "(obj_t (*)(~(, )))" (map (lambda (a) (type-name (cop-type a))) (reverse! (cdr (reverse actuals)))))) (define (out-call op cast actuals) (if (eq? (cfuncall-type cop) *obj*) (begin (display "(" *c-port*) (display (cast actuals) *c-port*) (display op *c-port*) (display "(" *c-port*) (emit-cop (cfuncall-fun cop)) (display "))(" *c-port*)) (begin (display "((" *c-port*) (display (type-name (cfuncall-type cop)) *c-port*) (display "(*)())" *c-port*) (display op *c-port*) (display "(" *c-port*) (emit-cop (cfuncall-fun cop)) (display "))(" *c-port*)))) (labels ((emit-extra-light-cfuncall (cop) (let ((actuals (cfuncall-args cop))) (emit-cop (cfuncall-fun cop)) (write-char #\( *c-port*) (let loop ((actuals actuals)) ;; actuals are never empty because there is always the EOA . (if (null? (cddr actuals)) (begin (emit-cop (car actuals)) (write-char #\) *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-light-cfuncall (cop) (let ((actuals (cfuncall-args cop))) (out-call "PROCEDURE_L_ENTRY" fun-l-cast actuals) (let loop ((actuals actuals)) ;; actuals are never empty because there is always the function and EOA . (if (null? (cddr actuals)) (begin (emit-cop (car actuals)) (display ")" *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-regular-cfuncall/eoa (cop) (let ((actuals (cfuncall-args cop))) (out-call "PROCEDURE_ENTRY" fun-cast actuals) (let loop ((actuals actuals)) ;; actuals are never empty because there is always the function and EOA . (if (null? (cdr actuals)) (begin (emit-cop (car actuals)) (display ")" *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-regular-cfuncall/oeoa (cop) (let ((actuals (cfuncall-args cop))) (out-call "PROCEDURE_ENTRY" fun-cast actuals) (let loop ((actuals actuals)) ;; actuals are never empty because there is always the function and EOA . (if (null? (cddr actuals)) (begin (emit-cop (car actuals)) (display ")" *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-stdc-regular-cfuncall (cop) (begin (display "(VA_PROCEDUREP( " *c-port*) (emit-cop (cfuncall-fun cop)) (display " ) ? " *c-port*) (emit-regular-cfuncall/eoa cop) (display " : " *c-port*) (emit-regular-cfuncall/oeoa cop) (display " )" *c-port*) #t))) (emit-bdb-loc (cop-loc cop)) (case (cfuncall-strength cop) ((elight) (emit-extra-light-cfuncall cop)) ((light) (emit-light-cfuncall cop)) (else (if *stdc* (emit-stdc-regular-cfuncall cop) (emit-regular-cfuncall/eoa cop)))))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::capply ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::capply) (with-access::capply cop (fun arg loc) (emit-bdb-loc loc) (display "apply(" *c-port*) (emit-cop fun) (display ", " *c-port*) (emit-cop arg) (write-char #\) *c-port*) #t)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::capp ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::capp) (define (emit-infix-capp) (let ((actuals (capp-args cop))) (write-char #\( *c-port*) (cond ((null? actuals) (emit-cop (capp-fun cop))) ((null? (cdr actuals)) (emit-cop (car actuals)) (emit-cop (capp-fun cop))) ((null? (cddr actuals)) (emit-cop (car actuals)) (emit-cop (capp-fun cop)) (emit-cop (cadr actuals))) (else (error "emit-cop" "Illegal infix macro" (shape (varc-variable (capp-fun cop)))))) (write-char #\) *c-port*) #t)) (define (emit-prefix-capp) (let ((actuals (capp-args cop))) (emit-cop (capp-fun cop)) (write-char #\( *c-port*) (if (null? actuals) (begin (write-char #\) *c-port*) #t) (let loop ((actuals actuals)) (if (null? (cdr actuals)) (begin (emit-cop (car actuals)) (write-char #\) *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals)))))))) (define (emit-prefix-capp-sans-bdb-loc) (let ((o *bdb-debug-no-line-directives?*)) (set! *bdb-debug-no-line-directives?* #t) (emit-prefix-capp) (set! *bdb-debug-no-line-directives?* o))) (let ((fun (varc-variable (capp-fun cop))) (loc (capp-loc cop))) (emit-bdb-loc loc) (cond ((and (cfun? (global-value fun)) (cfun-infix? (global-value fun))) (emit-infix-capp)) ((and (cfun? (global-value fun)) (cfun-macro? (global-value fun))) (emit-prefix-capp-sans-bdb-loc)) (else (emit-prefix-capp))))) ;*---------------------------------------------------------------------*/ ;* *bfalse* */ ;* ------------------------------------------------------------- */ ;* A local cache for the C false macro. */ ;*---------------------------------------------------------------------*/ (define *bfalse* #f) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cfail ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cfail) (with-access::cfail cop (proc msg obj loc) (emit-bdb-loc loc) (if (not *bfalse*) (set! *bfalse* (get-global/module 'bfalse 'foreign))) (cond ((and (varc? proc) (eq? (varc-variable proc) *bfalse*) (varc? msg) (eq? (varc-variable msg) *bfalse*) (varc? obj) (eq? (varc-variable obj) *bfalse*)) (display "exit( -1 );" *c-port*)) ((<=fx *bdb-debug* 0) (display "FAILURE(" *c-port*) (emit-cop proc) (write-char #\, *c-port*) (emit-cop msg) (write-char #\, *c-port*) (emit-cop obj) (display ");" *c-port*)) (else (display "the_failure(" *c-port*) (emit-cop proc) (write-char #\, *c-port*) (emit-cop msg) (write-char #\, *c-port*) (emit-cop obj) (display "), exit( -1 );" *c-port*))) #f)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cswitch ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cswitch) (with-access::cswitch cop (test clauses loc) (emit-bdb-loc loc) (display "switch( " *c-port*) (emit-cop test) (display ") { " *c-port*) (trace cgen (display "/* cop-cswitch */" *c-port*)) (let loop ((clauses clauses) (seen '())) (let ((clause (car clauses))) (cond ((eq? (car clause) 'else) (let ((loc (cop-loc (cdr clause)))) (emit-bdb-loc loc) (display "default: " *c-port*) (if (emit-cop (cdr clause)) (begin (display "; " *c-port*) (trace cgen (display "/* cswitch default */" *c-port*)))) (display "} " *c-port*) (trace cgen (display "/* cswitch */" *c-port*)) #f)) ((every (lambda (n) (memq n seen)) (car clause)) (loop (cdr clauses) seen)) (else (for-each (lambda (t) (unless (memq t seen) (display "case " *c-port*) (emit-atom-value t) (display " : " *c-port*) (newline *c-port*))) (car clause)) (if (emit-cop (cdr clause)) (begin (display "; " *c-port*) (trace cgen (display "/* cswitch clause */" *c-port*)))) (display "break;" *c-port*) (loop (cdr clauses) (append (car clause) seen)))))))) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cmake-box ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cmake-box) (with-access::cmake-box cop (value loc stackable) (emit-bdb-loc loc) (if (local? stackable) (begin (display "MAKE_CELL_STACK(" *c-port*) (emit-cop value) (write-char #\, *c-port*) (display (variable-name stackable) *c-port*) (write-char #\) *c-port*)) (begin (display "MAKE_CELL(" *c-port*) (emit-cop value) (write-char #\) *c-port*))) #t)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cbox-ref ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cbox-ref) (with-access::cbox-ref cop (var loc) (emit-bdb-loc loc) (display "CELL_REF(" *c-port*) (emit-cop var) (write-char #\) *c-port*) #t)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cbox-set! ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cbox-set!) (with-access::cbox-set! cop (var value loc) (emit-bdb-loc loc) (display "CELL_SET(" *c-port*) (emit-cop var) (display ", " *c-port*) (emit-cop value) (write-char #\) *c-port*) #t)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cset-ex-it ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cset-ex-it) (with-access::cset-ex-it cop (exit jump-value body loc) (emit-bdb-loc loc) (display "if( SET_EXIT(" *c-port*) (emit-cop exit) (display " ) ) { " *c-port*) (trace cgen (display "/* cop-cset-ex-it */" *c-port*)) (when (emit-cop jump-value) (display ";" *c-port*)) (emit-bdb-loc loc) (display "} else {\n" *c-port*) (display "#if( SIGSETJMP_SAVESIGS == 0 )\n" *c-port*) (display " // MS: CARE 5 jan 2021: see runtime/Clib/csystem.c\n" *c-port*) (display " // bgl_restore_signal_handlers();\n" *c-port*) (display "#endif\n" *c-port*) (emit-cop body) (emit-bdb-loc loc) (display "}" *c-port*) (trace cgen (display "/* cop-cset-ex-it */" *c-port*)) #f)) ;*---------------------------------------------------------------------*/ ;* emit-cop ::cjump-ex-it ... */ ;*---------------------------------------------------------------------*/ (define-method (emit-cop cop::cjump-ex-it) (with-access::cjump-ex-it cop (exit value loc) (emit-bdb-loc loc) (display "JUMP_EXIT( " *c-port*) (emit-cop exit) (write-char #\, *c-port*) (emit-cop value) (write-char #\) *c-port*) #t)) ;*---------------------------------------------------------------------*/ ;* *bdb-loc* ... */ ;* ------------------------------------------------------------- */ ;* The current bdb source location information. */ ;*---------------------------------------------------------------------*/ (define *bdb-loc* #unspecified) ;*---------------------------------------------------------------------*/ ;* reset-bdb-loc! ... */ ;*---------------------------------------------------------------------*/ (define (reset-bdb-loc!) (set! *bdb-loc* #unspecified)) ;*---------------------------------------------------------------------*/ ;* get-current-bdb-loc ... */ ;*---------------------------------------------------------------------*/ (define (get-current-bdb-loc) *bdb-loc*) ;*---------------------------------------------------------------------*/ ;* emit-bdb-loc ... */ ;* ------------------------------------------------------------- */ ;* This function emits a bdb location information (that is a */ ;* C # line information.) This function emits this information */ ;* only if we are dumping the C code for a different Scheme source */ ;* code line that the previous line dump. */ ;*---------------------------------------------------------------------*/ (define (emit-bdb-loc cur-loc) (cond ((or (not *c-debug-lines-info*) *bdb-debug-no-line-directives?*) (newline *c-port*)) ((not (location? cur-loc)) (cond ((location? *bdb-loc*) (emit-bdb-loc *bdb-loc*)) ((location? *module-location*) ;; when no location is found, we use the location of ;; the module clause (emit-bdb-loc *module-location*)) ((pair? *src-files*) ;; when no location at all is found, emit a dummy " first file line " location (fprint *c-port* #"\n#line " 1 " \"" (car *src-files*) #\")))) (else (let ((cur-fname (location-fname cur-loc)) (cur-line (location-lnum cur-loc))) (when (and (integer? cur-line) (string? cur-fname)) (fprint *c-port* #"\n#line " cur-line " \"" cur-fname #\")) (set! *bdb-loc* cur-loc))))) ;*---------------------------------------------------------------------*/ ;* emit-bdb-loc-comment ... */ ;* ------------------------------------------------------------- */ ;* For debug purposes this function write a location is a C */ ;* comment (iff CUR-LOC is a location). */ ;*---------------------------------------------------------------------*/ (define (emit-bdb-loc-comment cur-loc) (if (location? cur-loc) (begin (display "/* " *c-port*) (display (location-fname cur-loc) *c-port*) (display " " *c-port*) (display (location-lnum cur-loc) *c-port*) (display " */" *c-port*))))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/16e397e187fa85d8949a0285bfb43d4ab4ed8839/comptime/Cgen/emit_cop.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * The emission of cop code. */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ... */ * ------------------------------------------------------------- */ ' it returns # f , * / * ------------------------------------------------------------- */ * The general idea of that printer is that no specific printer */ * ever emit \n because they are emitted by the location printer. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::clabel ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cgoto ... */ *---------------------------------------------------------------------*/ ) *---------------------------------------------------------------------*/ * emit-cop ::cblock ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::creturn ... */ *---------------------------------------------------------------------*/ *c-port*)) *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cvoid ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::varc ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cpragma ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::ccast ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::csequence ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::nop ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::stop ... */ *---------------------------------------------------------------------*/ we don't have to emit a location here because the location is held by the printed value *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ don't omit to put space sourrounding `=' otherwise it could become an ambiguous assignement (e.g. x=-1). *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::local ... */ *---------------------------------------------------------------------*/ volatile is used only the *local-exit?* is true ))) *---------------------------------------------------------------------*/ * emit-cop ::bdb-block ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cfuncall-casts ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cfuncall ... */ *---------------------------------------------------------------------*/ actuals are never empty because there is always actuals are never empty because there is always actuals are never empty because there is always actuals are never empty because there is always *---------------------------------------------------------------------*/ * emit-cop ::capply ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::capp ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *bfalse* */ * ------------------------------------------------------------- */ * A local cache for the C false macro. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cfail ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cswitch ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cmake-box ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cbox-ref ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cbox-set! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cset-ex-it ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-cop ::cjump-ex-it ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *bdb-loc* ... */ * ------------------------------------------------------------- */ * The current bdb source location information. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * reset-bdb-loc! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * get-current-bdb-loc ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-bdb-loc ... */ * ------------------------------------------------------------- */ * This function emits a bdb location information (that is a */ * C # line information.) This function emits this information */ * only if we are dumping the C code for a different Scheme source */ * code line that the previous line dump. */ *---------------------------------------------------------------------*/ when no location is found, we use the location of the module clause when no location at all is found, emit a dummy *---------------------------------------------------------------------*/ * emit-bdb-loc-comment ... */ * ------------------------------------------------------------- */ * For debug purposes this function write a location is a C */ * comment (iff CUR-LOC is a location). */ *---------------------------------------------------------------------*/
* ... /prgm / project / bigloo / / comptime / Cgen / emit_cop.scm * / * Author : * / * Creation : Tue Jul 2 14:39:37 1996 * / * Last change : Tue May 10 08:03:27 2022 ( serrano ) * / * Copyright : 1996 - 2022 , see LICENSE file * / (module cgen_emit-cop (include "Tools/location.sch" "Tools/fprint.sch" "Tools/trace.sch") (import type_type type_tools type_cache type_typeof tools_shape engine_param ast_var ast_node ast_env backend_c_emit cgen_cop (*module-location* module_module)) (export (generic emit-cop::bool ::cop) (reset-bdb-loc!) (emit-bdb-loc ::obj) (get-current-bdb-loc))) * otherwise it returns * / (define-generic (emit-cop::bool cop::cop)) (define-method (emit-cop cop::clabel) (with-access::clabel cop (used? name body loc) (if used? (begin (emit-bdb-loc loc) (display name *c-port*) (write-char #\: *c-port*))) (emit-cop body))) (define-method (emit-cop cop::cgoto) (with-access::cgoto cop (label loc) (emit-bdb-loc loc) #f)) (define-method (emit-cop cop::cblock) (with-access::cblock cop (body loc) (emit-bdb-loc loc) (if (isa? body cblock) (emit-cop body) (begin (display #"{ " *c-port*) (trace cgen (display "/* cop-block */" *c-port*)) (emit-bdb-loc-comment loc) (if (emit-cop body) (begin (emit-bdb-loc (get-current-bdb-loc)) (display "; " *c-port*) (trace cgen (display "/* cop-block */" *c-port*)))) (display "} " *c-port*) (trace cgen (display "/* cop-block */" *c-port*)) #f)))) (define-method (emit-cop cop::creturn) (with-access::creturn cop (value loc tail) (emit-bdb-loc loc) (when tail (display "BGL_TAIL " *c-port*)) (display "return " *c-port*) (if (emit-cop value) #f)) * emit - cop : : ... * / (define-method (emit-cop cop::catom) (with-access::catom cop (value) (emit-atom-value value) #t)) (define-method (emit-cop cop::cvoid) (with-access::cvoid cop (value) (emit-cop value))) (define-method (emit-cop cop::varc) (with-access::varc cop (variable) (if (when (isa? variable global) (with-access::global variable (value) (when (isa? value scnst) (with-access::scnst value (class) (eq? class 'sreal))))) (begin (display "BGL_REAL_CNST( " *c-port*) (display (variable-name variable) *c-port*) (display ")" *c-port*)) (display (variable-name variable) *c-port*)) #t)) (define-method (emit-cop cop::cpragma) (with-access::cpragma cop (args format loc) (emit-bdb-loc loc) (if (null? args) (display format *c-port*) (let* ((sport (open-input-string format)) (args (list->vector args)) (parser (regular-grammar () ((: #\$ (+ (in (#\0 #\9)))) (let* ((str (the-string)) (len (the-length)) (index (string->number (substring str 1 len)))) (emit-cop (vector-ref args (-fx index 1))) (ignore))) ("$$" (display "$" *c-port*) (ignore)) ((+ (out #\$)) (display (the-string) *c-port*) (ignore)) (else (the-failure))))) (read/rp parser sport) (close-input-port sport) #t)))) (define-method (emit-cop cop::ccast) (with-access::ccast cop (arg type loc) (emit-bdb-loc loc) (display "((" *c-port*) (display (type-name type) *c-port*) (write-char #\) *c-port*) (emit-cop arg) (write-char #\) *c-port*) #t)) (define-method (emit-cop cop::csequence) (with-access::csequence cop (c-exp? cops loc) (if c-exp? (begin (if (null? cops) (emit-atom-value #unspecified) (begin (display "( " *c-port*) (trace cgen (display "/* cop-csequence */" *c-port*)) (let liip ((exp cops)) (if (null? (cdr exp)) (begin (emit-cop (car exp)) (display ") " *c-port*) (trace cgen "/* cop-csequence */" *c-port*) #t) (begin (emit-cop (car exp)) (if (cfail? (car exp)) (begin (display ") " *c-port*) (trace cgen "/* cop-csequence */" *c-port*) #t) (begin (display ", " *c-port*) (trace cgen "/* cop-csequence */" *c-port*) (liip (cdr exp)))))))))) (let liip ((exp cops)) (if (null? exp) #f (let ((e (car exp))) (if (emit-cop e) (begin (display "; " *c-port*) (trace cgen (display "/* cop-csequence */" *c-port*)))) (if (cfail? e) (liip '()) (liip (cdr exp))))))))) (define-method (emit-cop cop::nop) (with-access::nop cop (loc) (display "; " *c-port*) (trace cgen (display "/* cop-nop */" *c-port*)) #f)) (define-method (emit-cop cop::stop) (with-access::stop cop (value loc) (if (emit-cop value) (begin (display "; " *c-port*) (trace cgen (display "/* cop-stop */" *c-port*)))) #f)) * emit - cop : : ... * / (define-method (emit-cop cop::csetq) (with-access::csetq cop (var value loc) we first emit a location for this node (emit-bdb-loc loc) (emit-cop var) (display " = " *c-port*) (emit-cop value) #t)) * emit - cop : : ... * / (define-method (emit-cop cop::cif) (with-access::cif cop (test true false loc) (emit-bdb-loc loc) (display "if(" *c-port*) (emit-cop test) (write-char #\) *c-port*) (emit-cop true) (display " else " *c-port*) (emit-cop false))) (define-method (emit-cop cop::local-var) (with-access::local-var cop (vars loc) (emit-bdb-loc loc) (for-each (lambda (local) (with-access::local local (volatile type name) (fprin *c-port* (if volatile "volatile " " ") (make-typed-declaration type name) (if (and (>fx *bdb-debug* 0) (eq? (type-class type) 'bigloo)) (string-append " = ((" (make-typed-declaration type "") ")BUNSPEC)") "") vars) #f)) (define-method (emit-cop cop::bdb-block) (with-access::bdb-block cop (loc body) (emit-bdb-loc loc) (fprin *c-port* "int bigloo_dummy_bdb; bigloo_dummy_bdb = 0; { ") (emit-cop body) (display "} " *c-port*) (trace cgen (display " /* cop-bdb-block */" *c-port*)))) (define cfuncall-casts (make-vector 32 #f)) (define-method (emit-cop cop::cfuncall) (define (fun-cast actuals) (let ((largs (length actuals))) (cond ((>=fx largs (vector-length cfuncall-casts)) (format "(obj_t (*)(~(, )))" (make-list largs "obj_t"))) ((vector-ref cfuncall-casts largs) => (lambda (p) p)) (else (let ((p (format "(obj_t (*)(~(, )))" (make-list largs "obj_t")))) (vector-set! cfuncall-casts largs p) p))))) (define (fun-l-cast actuals) (format "(obj_t (*)(~(, )))" (map (lambda (a) (type-name (cop-type a))) (reverse! (cdr (reverse actuals)))))) (define (out-call op cast actuals) (if (eq? (cfuncall-type cop) *obj*) (begin (display "(" *c-port*) (display (cast actuals) *c-port*) (display op *c-port*) (display "(" *c-port*) (emit-cop (cfuncall-fun cop)) (display "))(" *c-port*)) (begin (display "((" *c-port*) (display (type-name (cfuncall-type cop)) *c-port*) (display "(*)())" *c-port*) (display op *c-port*) (display "(" *c-port*) (emit-cop (cfuncall-fun cop)) (display "))(" *c-port*)))) (labels ((emit-extra-light-cfuncall (cop) (let ((actuals (cfuncall-args cop))) (emit-cop (cfuncall-fun cop)) (write-char #\( *c-port*) (let loop ((actuals actuals)) the EOA . (if (null? (cddr actuals)) (begin (emit-cop (car actuals)) (write-char #\) *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-light-cfuncall (cop) (let ((actuals (cfuncall-args cop))) (out-call "PROCEDURE_L_ENTRY" fun-l-cast actuals) (let loop ((actuals actuals)) the function and EOA . (if (null? (cddr actuals)) (begin (emit-cop (car actuals)) (display ")" *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-regular-cfuncall/eoa (cop) (let ((actuals (cfuncall-args cop))) (out-call "PROCEDURE_ENTRY" fun-cast actuals) (let loop ((actuals actuals)) the function and EOA . (if (null? (cdr actuals)) (begin (emit-cop (car actuals)) (display ")" *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-regular-cfuncall/oeoa (cop) (let ((actuals (cfuncall-args cop))) (out-call "PROCEDURE_ENTRY" fun-cast actuals) (let loop ((actuals actuals)) the function and EOA . (if (null? (cddr actuals)) (begin (emit-cop (car actuals)) (display ")" *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals))))))) (emit-stdc-regular-cfuncall (cop) (begin (display "(VA_PROCEDUREP( " *c-port*) (emit-cop (cfuncall-fun cop)) (display " ) ? " *c-port*) (emit-regular-cfuncall/eoa cop) (display " : " *c-port*) (emit-regular-cfuncall/oeoa cop) (display " )" *c-port*) #t))) (emit-bdb-loc (cop-loc cop)) (case (cfuncall-strength cop) ((elight) (emit-extra-light-cfuncall cop)) ((light) (emit-light-cfuncall cop)) (else (if *stdc* (emit-stdc-regular-cfuncall cop) (emit-regular-cfuncall/eoa cop)))))) (define-method (emit-cop cop::capply) (with-access::capply cop (fun arg loc) (emit-bdb-loc loc) (display "apply(" *c-port*) (emit-cop fun) (display ", " *c-port*) (emit-cop arg) (write-char #\) *c-port*) #t)) (define-method (emit-cop cop::capp) (define (emit-infix-capp) (let ((actuals (capp-args cop))) (write-char #\( *c-port*) (cond ((null? actuals) (emit-cop (capp-fun cop))) ((null? (cdr actuals)) (emit-cop (car actuals)) (emit-cop (capp-fun cop))) ((null? (cddr actuals)) (emit-cop (car actuals)) (emit-cop (capp-fun cop)) (emit-cop (cadr actuals))) (else (error "emit-cop" "Illegal infix macro" (shape (varc-variable (capp-fun cop)))))) (write-char #\) *c-port*) #t)) (define (emit-prefix-capp) (let ((actuals (capp-args cop))) (emit-cop (capp-fun cop)) (write-char #\( *c-port*) (if (null? actuals) (begin (write-char #\) *c-port*) #t) (let loop ((actuals actuals)) (if (null? (cdr actuals)) (begin (emit-cop (car actuals)) (write-char #\) *c-port*) #t) (begin (emit-cop (car actuals)) (display ", " *c-port*) (loop (cdr actuals)))))))) (define (emit-prefix-capp-sans-bdb-loc) (let ((o *bdb-debug-no-line-directives?*)) (set! *bdb-debug-no-line-directives?* #t) (emit-prefix-capp) (set! *bdb-debug-no-line-directives?* o))) (let ((fun (varc-variable (capp-fun cop))) (loc (capp-loc cop))) (emit-bdb-loc loc) (cond ((and (cfun? (global-value fun)) (cfun-infix? (global-value fun))) (emit-infix-capp)) ((and (cfun? (global-value fun)) (cfun-macro? (global-value fun))) (emit-prefix-capp-sans-bdb-loc)) (else (emit-prefix-capp))))) (define *bfalse* #f) (define-method (emit-cop cop::cfail) (with-access::cfail cop (proc msg obj loc) (emit-bdb-loc loc) (if (not *bfalse*) (set! *bfalse* (get-global/module 'bfalse 'foreign))) (cond ((and (varc? proc) (eq? (varc-variable proc) *bfalse*) (varc? msg) (eq? (varc-variable msg) *bfalse*) (varc? obj) (eq? (varc-variable obj) *bfalse*)) (display "exit( -1 );" *c-port*)) ((<=fx *bdb-debug* 0) (display "FAILURE(" *c-port*) (emit-cop proc) (write-char #\, *c-port*) (emit-cop msg) (write-char #\, *c-port*) (emit-cop obj) (display ");" *c-port*)) (else (display "the_failure(" *c-port*) (emit-cop proc) (write-char #\, *c-port*) (emit-cop msg) (write-char #\, *c-port*) (emit-cop obj) (display "), exit( -1 );" *c-port*))) #f)) (define-method (emit-cop cop::cswitch) (with-access::cswitch cop (test clauses loc) (emit-bdb-loc loc) (display "switch( " *c-port*) (emit-cop test) (display ") { " *c-port*) (trace cgen (display "/* cop-cswitch */" *c-port*)) (let loop ((clauses clauses) (seen '())) (let ((clause (car clauses))) (cond ((eq? (car clause) 'else) (let ((loc (cop-loc (cdr clause)))) (emit-bdb-loc loc) (display "default: " *c-port*) (if (emit-cop (cdr clause)) (begin (display "; " *c-port*) (trace cgen (display "/* cswitch default */" *c-port*)))) (display "} " *c-port*) (trace cgen (display "/* cswitch */" *c-port*)) #f)) ((every (lambda (n) (memq n seen)) (car clause)) (loop (cdr clauses) seen)) (else (for-each (lambda (t) (unless (memq t seen) (display "case " *c-port*) (emit-atom-value t) (display " : " *c-port*) (newline *c-port*))) (car clause)) (if (emit-cop (cdr clause)) (begin (display "; " *c-port*) (trace cgen (display "/* cswitch clause */" *c-port*)))) (display "break;" *c-port*) (loop (cdr clauses) (append (car clause) seen)))))))) (define-method (emit-cop cop::cmake-box) (with-access::cmake-box cop (value loc stackable) (emit-bdb-loc loc) (if (local? stackable) (begin (display "MAKE_CELL_STACK(" *c-port*) (emit-cop value) (write-char #\, *c-port*) (display (variable-name stackable) *c-port*) (write-char #\) *c-port*)) (begin (display "MAKE_CELL(" *c-port*) (emit-cop value) (write-char #\) *c-port*))) #t)) (define-method (emit-cop cop::cbox-ref) (with-access::cbox-ref cop (var loc) (emit-bdb-loc loc) (display "CELL_REF(" *c-port*) (emit-cop var) (write-char #\) *c-port*) #t)) (define-method (emit-cop cop::cbox-set!) (with-access::cbox-set! cop (var value loc) (emit-bdb-loc loc) (display "CELL_SET(" *c-port*) (emit-cop var) (display ", " *c-port*) (emit-cop value) (write-char #\) *c-port*) #t)) (define-method (emit-cop cop::cset-ex-it) (with-access::cset-ex-it cop (exit jump-value body loc) (emit-bdb-loc loc) (display "if( SET_EXIT(" *c-port*) (emit-cop exit) (display " ) ) { " *c-port*) (trace cgen (display "/* cop-cset-ex-it */" *c-port*)) (when (emit-cop jump-value) (display ";" *c-port*)) (emit-bdb-loc loc) (display "} else {\n" *c-port*) (display "#if( SIGSETJMP_SAVESIGS == 0 )\n" *c-port*) (display " // MS: CARE 5 jan 2021: see runtime/Clib/csystem.c\n" *c-port*) (display " // bgl_restore_signal_handlers();\n" *c-port*) (display "#endif\n" *c-port*) (emit-cop body) (emit-bdb-loc loc) (display "}" *c-port*) (trace cgen (display "/* cop-cset-ex-it */" *c-port*)) #f)) (define-method (emit-cop cop::cjump-ex-it) (with-access::cjump-ex-it cop (exit value loc) (emit-bdb-loc loc) (display "JUMP_EXIT( " *c-port*) (emit-cop exit) (write-char #\, *c-port*) (emit-cop value) (write-char #\) *c-port*) #t)) (define *bdb-loc* #unspecified) (define (reset-bdb-loc!) (set! *bdb-loc* #unspecified)) (define (get-current-bdb-loc) *bdb-loc*) (define (emit-bdb-loc cur-loc) (cond ((or (not *c-debug-lines-info*) *bdb-debug-no-line-directives?*) (newline *c-port*)) ((not (location? cur-loc)) (cond ((location? *bdb-loc*) (emit-bdb-loc *bdb-loc*)) ((location? *module-location*) (emit-bdb-loc *module-location*)) ((pair? *src-files*) " first file line " location (fprint *c-port* #"\n#line " 1 " \"" (car *src-files*) #\")))) (else (let ((cur-fname (location-fname cur-loc)) (cur-line (location-lnum cur-loc))) (when (and (integer? cur-line) (string? cur-fname)) (fprint *c-port* #"\n#line " cur-line " \"" cur-fname #\")) (set! *bdb-loc* cur-loc))))) (define (emit-bdb-loc-comment cur-loc) (if (location? cur-loc) (begin (display "/* " *c-port*) (display (location-fname cur-loc) *c-port*) (display " " *c-port*) (display (location-lnum cur-loc) *c-port*) (display " */" *c-port*))))
2e64938de00440d4e7fa26eae4b078acc697685ba79f4f732dd25028d8b894cb
shonfeder/alg_structs
semigroup.mli
* An interface for a type with a binary , associative operator over it . " A semigroup is an algebraic structure consisting of a set together with an associative binary operation " ( { { : } wikipedia ) } . " The term ' semigroup ' is standard , but semi - monoid would be more systematic . " { { : } ncatlab } Modules that implement the semigroup interface are a structural subtype of the better known { { ! module - type : Monoid . S } Monoids } interface . Semigroups are differentiated from Monoids by the absence of a unit ( or identity ) element . in their specification . "A semigroup is an algebraic structure consisting of a set together with an associative binary operation" ({{:} wikipedia)}. "The term 'semigroup' is standard, but semi-monoid would be more systematic." {{:} ncatlab} Modules that implement the semigroup interface are a structural subtype of the better known {{!module-type:Monoid.S} Monoids} interface. Semigroups are differentiated from Monoids by the absence of a unit (or identity) element. in their specification. *) (** {1 Seed} *) (** The [Seed] needed to generate an implementation of {{!module-type:S} Semigroup} for the type {{!type:Seed.t} t}. *) module type Seed = sig (** The principle (and sole) type. We can think of this set-theoretically as the carrier set of the algebraic structure or category-theoretically as the single object in the category, with each element being a morphism [t -> t]. *) type t (** [op x y] is an associative operation over all elements [x] and [y] of type {!type:t}. Category-theoretically, this is the composition of morphisms. *) val op : t -> t -> t end * As { ! module - type : Seed } but for parameteric types of one variable module type Seed1 = sig type 'a t (** [op x y] is an associative operation over all elements [x] and [y] of type {!type:t} *) val op : 'a t -> 'a t -> 'a t end * { 1 Interface } (** A semigroup is a set of objects with an associative binary operation over it *) module type S = sig include Seed * The infix version of { ! : op } . val ( * ) : t -> t -> t * [ concat xs ] is the concatenation of all elements of [ xs ] into a single value using [ op ] . This is equivalent to [ List.fold_right op ( NonEmptyList.tl xs ) ( NonEmptyList.hd xs ) ] . value using [op]. This is equivalent to [List.fold_right op (NonEmptyList.tl xs) (NonEmptyList.hd xs)]. *) val concat : t NonEmptyList.t -> t end module type S1 = sig include Seed1 * The infix for { ! : op } . val ( * ) : 'a t -> 'a t -> 'a t * [ concat xs ] is the concatenation of all elements of [ xs ] into a single value using [ op ] . This is equivalent to [ List.fold_right op ( NonEmptyList.tl xs ) ( NonEmptyList.hd xs ) ] . value using [op]. This is equivalent to [List.fold_right op (NonEmptyList.tl xs) (NonEmptyList.hd xs)]. *) val concat : 'a t NonEmptyList.t -> 'a t end * { 1 Laws } (** [Law] notes the laws that should be obeyed by any instantiation of {{!module-type:S} Semigroup} in the form of predicates that should be true for any arguments of the appropriate type. You can use the [alg_structs_qcheck] package to generate property based tests of these laws for new modules satisfying the interface. @param S An implementation of a {{!module-type: S} Semigroup} *) module Law (S : S) : sig (** [associativity x y z] is [true] when {[ S.(x * (y * z)) = S.((x * y) * z) ]} *) val associativity : S.t -> S.t -> S.t -> bool end (* TODO S2 for monoids over parametric types *) (** {1 Constructors} Functions and module functors for creating implementations of {{!module-type:S} Semigroups} *) (** [Make (S)] is an implementation of {{!module-type:S} Semigroup} generated from the {!module-type:Seed}. *) module Make (S:Seed) : S with type t = S.t (** [make op] is an implementation of {{!module-type:S} Semigroup} generated from the operation [op]. *) val make : ('a -> 'a -> 'a) -> (module S with type t = 'a) * { 1 Implementations } (** Semigroups over {!type:bool} *) module Bool : sig (** [op] is [(||)] *) module Or : S with type t = bool (** [op] is [(&&)] *) module And : S with type t = bool end (** Semigroups over {!type:int} *) module Int : sig (** [op] is [(+)] *) module Sum : S with type t = int (** [op] is [( * )]*) module Product : S with type t = int end (** Semigroups over option types *) module Option : sig * [ Make ( S ) ] is a semigroup where [ op a b ] is ... - [ None ] if both [ a ] and [ b ] are [ None ] - [ Some v ] if only one of [ a ] or [ b ] are [ Some v ] - [ Some ( S.op a ' b ' ) ] if [ b ] is [ Some b ' ] and [ a ] is [ Some a ' ] This enables chains of associations over optional values that preserves any values that may be present . E.g. , { [ # module O = Semigroup . Option . Make ( ( val Semigroup.make ( * ) ) ) ; ; module O : sig type t = int option op : t - > t - > t val ( * ) : t - > t - > t val concat : t NonEmptyList.t - > t end # O.(Some 2 * None * None * Some 2 ) ; ; - : O.t = Option . Some 4 ] } @param S An implementation of { { ! module - type : S } Semigroup } - [None] if both [a] and [b] are [None] - [Some v] if only one of [a] or [b] are [Some v] - [Some (S.op a' b')] if [b] is [Some b'] and [a] is [Some a'] This enables chains of associations over optional values that preserves any values that may be present. E.g., {[ # module O = Semigroup.Option.Make ((val Semigroup.make ( * )));; module O : sig type t = int option val op : t -> t -> t val ( * ) : t -> t -> t val concat : t NonEmptyList.t -> t end # O.(Some 2 * None * None * Some 2);; - : O.t = Option.Some 4 ]} @param S An implementation of {{!module-type:S} Semigroup} *) module Make (S : S) : S with type t = S.t Option.t end * [ Endo ] is a semigroup where the operator is the composition of functions with input and output of the same type . Or , to paraphrase the { { : -4.12.0.0/docs/Data-Semigroup.html#t:Endo } Haskell docs } , [ Endo ] implements " the semigroup of endomorphisms under composition " . " " just meaning a morphism with the same object for its source and target , i.e. , ( here ) a function with input and output of same type . E.g. using the first - order module generator { ! : Endo.make } , we can make the [ Endo ] semigroup over functions of type [ string - > string ] thus : { [ # module E = ( val Semigroup.Endo.make " " ) ; ; module E : sig type t = string - > string op : t - > t - > t val ( * ) : t - > t - > t val concat : t NonEmptyList.t - > t end ; ; # let comp = E. ( ( fun y - > " Hello , " ^ y ) * ( fun x - > x ^ " ! " ) ) ; ; val comp : E.t = < fun > ; ; # comp " OCaml " ; ; - : string = " Hello , ! " ] } with input and output of the same type. Or, to paraphrase the {{:-4.12.0.0/docs/Data-Semigroup.html#t:Endo} Haskell docs}, [Endo] implements "the semigroup of endomorphisms under composition". "Endomorphism" just meaning a morphism with the same object for its source and target, i.e., (here) a function with input and output of same type. E.g. using the first-order module generator {!val:Endo.make}, we can make the [Endo] semigroup over functions of type [string -> string] thus: {[ # module E = (val Semigroup.Endo.make "");; module E : sig type t = string -> string val op : t -> t -> t val ( * ) : t -> t -> t val concat : t NonEmptyList.t -> t end;; # let comp = E.( (fun y -> "Hello, " ^ y) * (fun x -> x ^ "!") );; val comp : E.t = <fun>;; # comp "OCaml";; - : string = "Hello, OCaml!" ]} *) module Endo : sig (** [Make (T)] is a module implementing the [Endo] semigroup for functions over type [T.t] *) module Make (T : Triv.S) : S with type t = (T.t -> T.t) * [ make ( Proxy : t Util.proxy ) ] is a first - class module implementing the [ Endo ] semigroup for functions [ ( t - > t ) ] . Note that [ Proxy ] is used only to convey the type . See { ! type : Util.proxy } . You can lift the result back into the module like so : { [ # module E = ( val Semigroup.Endo.make ( Util . Proxy : int proxy ) ) ; ; module E : sig type t = int - > int val op : t - > t - > t val ( * ) : t - > t - > t val concat : t NonEmptyList.t - > t end ] } [Endo] semigroup for functions [(t -> t)]. Note that [Proxy] is used only to convey the type. See {!type:Util.proxy}. You can lift the result back into the module like so: {[ # module E = (val Semigroup.Endo.make (Util.Proxy : int proxy));; module E : sig type t = int -> int val op : t -> t -> t val ( * ) : t -> t -> t val concat : t NonEmptyList.t -> t end ]} *) val make : 'a Util.proxy -> (module S with type t = 'a -> 'a) end (** [Dual] allows constructing the dual semigroup for a given semigroup. I.e., a semigroup with the arguments of it's operator reversed. *) module Dual : sig (** [Make (S)] is [S] except that [S.op] is defined as [Fun.flip S.op]. *) module Make (S : S) : S with type t = S.t (** [make op] is [Semigroup.make (Fun.flip op)]. *) val make : ('a -> 'a -> 'a) -> (module S with type t = 'a) end
null
https://raw.githubusercontent.com/shonfeder/alg_structs/09a57285ffae77dce2d2dd0581a0d453d31fb332/lib/semigroup.mli
ocaml
* {1 Seed} * The [Seed] needed to generate an implementation of {{!module-type:S} Semigroup} for the type {{!type:Seed.t} t}. * The principle (and sole) type. We can think of this set-theoretically as the carrier set of the algebraic structure or category-theoretically as the single object in the category, with each element being a morphism [t -> t]. * [op x y] is an associative operation over all elements [x] and [y] of type {!type:t}. Category-theoretically, this is the composition of morphisms. * [op x y] is an associative operation over all elements [x] and [y] of type {!type:t} * A semigroup is a set of objects with an associative binary operation over it * [Law] notes the laws that should be obeyed by any instantiation of {{!module-type:S} Semigroup} in the form of predicates that should be true for any arguments of the appropriate type. You can use the [alg_structs_qcheck] package to generate property based tests of these laws for new modules satisfying the interface. @param S An implementation of a {{!module-type: S} Semigroup} * [associativity x y z] is [true] when {[ S.(x * (y * z)) = S.((x * y) * z) ]} TODO S2 for monoids over parametric types * {1 Constructors} Functions and module functors for creating implementations of {{!module-type:S} Semigroups} * [Make (S)] is an implementation of {{!module-type:S} Semigroup} generated from the {!module-type:Seed}. * [make op] is an implementation of {{!module-type:S} Semigroup} generated from the operation [op]. * Semigroups over {!type:bool} * [op] is [(||)] * [op] is [(&&)] * Semigroups over {!type:int} * [op] is [(+)] * [op] is [( * )] * Semigroups over option types * [Make (T)] is a module implementing the [Endo] semigroup for functions over type [T.t] * [Dual] allows constructing the dual semigroup for a given semigroup. I.e., a semigroup with the arguments of it's operator reversed. * [Make (S)] is [S] except that [S.op] is defined as [Fun.flip S.op]. * [make op] is [Semigroup.make (Fun.flip op)].
* An interface for a type with a binary , associative operator over it . " A semigroup is an algebraic structure consisting of a set together with an associative binary operation " ( { { : } wikipedia ) } . " The term ' semigroup ' is standard , but semi - monoid would be more systematic . " { { : } ncatlab } Modules that implement the semigroup interface are a structural subtype of the better known { { ! module - type : Monoid . S } Monoids } interface . Semigroups are differentiated from Monoids by the absence of a unit ( or identity ) element . in their specification . "A semigroup is an algebraic structure consisting of a set together with an associative binary operation" ({{:} wikipedia)}. "The term 'semigroup' is standard, but semi-monoid would be more systematic." {{:} ncatlab} Modules that implement the semigroup interface are a structural subtype of the better known {{!module-type:Monoid.S} Monoids} interface. Semigroups are differentiated from Monoids by the absence of a unit (or identity) element. in their specification. *) module type Seed = sig type t val op : t -> t -> t end * As { ! module - type : Seed } but for parameteric types of one variable module type Seed1 = sig type 'a t val op : 'a t -> 'a t -> 'a t end * { 1 Interface } module type S = sig include Seed * The infix version of { ! : op } . val ( * ) : t -> t -> t * [ concat xs ] is the concatenation of all elements of [ xs ] into a single value using [ op ] . This is equivalent to [ List.fold_right op ( NonEmptyList.tl xs ) ( NonEmptyList.hd xs ) ] . value using [op]. This is equivalent to [List.fold_right op (NonEmptyList.tl xs) (NonEmptyList.hd xs)]. *) val concat : t NonEmptyList.t -> t end module type S1 = sig include Seed1 * The infix for { ! : op } . val ( * ) : 'a t -> 'a t -> 'a t * [ concat xs ] is the concatenation of all elements of [ xs ] into a single value using [ op ] . This is equivalent to [ List.fold_right op ( NonEmptyList.tl xs ) ( NonEmptyList.hd xs ) ] . value using [op]. This is equivalent to [List.fold_right op (NonEmptyList.tl xs) (NonEmptyList.hd xs)]. *) val concat : 'a t NonEmptyList.t -> 'a t end * { 1 Laws } module Law (S : S) : sig val associativity : S.t -> S.t -> S.t -> bool end module Make (S:Seed) : S with type t = S.t val make : ('a -> 'a -> 'a) -> (module S with type t = 'a) * { 1 Implementations } module Bool : sig module Or : S with type t = bool module And : S with type t = bool end module Int : sig module Sum : S with type t = int module Product : S with type t = int end module Option : sig * [ Make ( S ) ] is a semigroup where [ op a b ] is ... - [ None ] if both [ a ] and [ b ] are [ None ] - [ Some v ] if only one of [ a ] or [ b ] are [ Some v ] - [ Some ( S.op a ' b ' ) ] if [ b ] is [ Some b ' ] and [ a ] is [ Some a ' ] This enables chains of associations over optional values that preserves any values that may be present . E.g. , { [ # module O = Semigroup . Option . Make ( ( val Semigroup.make ( * ) ) ) ; ; module O : sig type t = int option op : t - > t - > t val ( * ) : t - > t - > t val concat : t NonEmptyList.t - > t end # O.(Some 2 * None * None * Some 2 ) ; ; - : O.t = Option . Some 4 ] } @param S An implementation of { { ! module - type : S } Semigroup } - [None] if both [a] and [b] are [None] - [Some v] if only one of [a] or [b] are [Some v] - [Some (S.op a' b')] if [b] is [Some b'] and [a] is [Some a'] This enables chains of associations over optional values that preserves any values that may be present. E.g., {[ # module O = Semigroup.Option.Make ((val Semigroup.make ( * )));; module O : sig type t = int option val op : t -> t -> t val ( * ) : t -> t -> t val concat : t NonEmptyList.t -> t end # O.(Some 2 * None * None * Some 2);; - : O.t = Option.Some 4 ]} @param S An implementation of {{!module-type:S} Semigroup} *) module Make (S : S) : S with type t = S.t Option.t end * [ Endo ] is a semigroup where the operator is the composition of functions with input and output of the same type . Or , to paraphrase the { { : -4.12.0.0/docs/Data-Semigroup.html#t:Endo } Haskell docs } , [ Endo ] implements " the semigroup of endomorphisms under composition " . " " just meaning a morphism with the same object for its source and target , i.e. , ( here ) a function with input and output of same type . E.g. using the first - order module generator { ! : Endo.make } , we can make the [ Endo ] semigroup over functions of type [ string - > string ] thus : { [ # module E = ( val Semigroup.Endo.make " " ) ; ; module E : sig type t = string - > string op : t - > t - > t val ( * ) : t - > t - > t val concat : t NonEmptyList.t - > t end ; ; # let comp = E. ( ( fun y - > " Hello , " ^ y ) * ( fun x - > x ^ " ! " ) ) ; ; val comp : E.t = < fun > ; ; # comp " OCaml " ; ; - : string = " Hello , ! " ] } with input and output of the same type. Or, to paraphrase the {{:-4.12.0.0/docs/Data-Semigroup.html#t:Endo} Haskell docs}, [Endo] implements "the semigroup of endomorphisms under composition". "Endomorphism" just meaning a morphism with the same object for its source and target, i.e., (here) a function with input and output of same type. E.g. using the first-order module generator {!val:Endo.make}, we can make the [Endo] semigroup over functions of type [string -> string] thus: {[ # module E = (val Semigroup.Endo.make "");; module E : sig type t = string -> string val op : t -> t -> t val ( * ) : t -> t -> t val concat : t NonEmptyList.t -> t end;; # let comp = E.( (fun y -> "Hello, " ^ y) * (fun x -> x ^ "!") );; val comp : E.t = <fun>;; # comp "OCaml";; - : string = "Hello, OCaml!" ]} *) module Endo : sig module Make (T : Triv.S) : S with type t = (T.t -> T.t) * [ make ( Proxy : t Util.proxy ) ] is a first - class module implementing the [ Endo ] semigroup for functions [ ( t - > t ) ] . Note that [ Proxy ] is used only to convey the type . See { ! type : Util.proxy } . You can lift the result back into the module like so : { [ # module E = ( val Semigroup.Endo.make ( Util . Proxy : int proxy ) ) ; ; module E : sig type t = int - > int val op : t - > t - > t val ( * ) : t - > t - > t val concat : t NonEmptyList.t - > t end ] } [Endo] semigroup for functions [(t -> t)]. Note that [Proxy] is used only to convey the type. See {!type:Util.proxy}. You can lift the result back into the module like so: {[ # module E = (val Semigroup.Endo.make (Util.Proxy : int proxy));; module E : sig type t = int -> int val op : t -> t -> t val ( * ) : t -> t -> t val concat : t NonEmptyList.t -> t end ]} *) val make : 'a Util.proxy -> (module S with type t = 'a -> 'a) end module Dual : sig module Make (S : S) : S with type t = S.t val make : ('a -> 'a -> 'a) -> (module S with type t = 'a) end
81d9ebab912009e9140c07314d423acee7c02f0c7d587bad2db7ae34ff1f35a7
imitator-model-checker/imitator
AlgoBCShuffle.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13 , LIPN , CNRS , France * Université de Lorraine , CNRS , , LORIA , Nancy , France * * Module description : Classical Behavioral Cartography with exhaustive coverage of integer points [ AF10 ] . Shuffled version , used for the distributed cartography . [ ACN15 ] * * File contributors : * Created : 2016/03/14 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13, LIPN, CNRS, France * Université de Lorraine, CNRS, Inria, LORIA, Nancy, France * * Module description: Classical Behavioral Cartography with exhaustive coverage of integer points [AF10]. Shuffled version, used for the distributed cartography. [ACN15] * * File contributors : Étienne André * Created : 2016/03/14 * ************************************************************) (************************************************************) (************************************************************) (* Modules *) (************************************************************) (************************************************************) open OCamlUtilities open ImitatorUtilities open Exceptions open AbstractModel open Result open AlgoCartoGeneric (************************************************************) (************************************************************) (* Internal exceptions *) (************************************************************) (************************************************************) (* To stop a loop when a point is found *) exception Found_point of PVal.pval (* To stop a loop when a point is found or there is no more point *) exception Stop_loop of more_points (************************************************************) (************************************************************) (* Class definition *) (************************************************************) (************************************************************) class algoBCShuffle (v0 : HyperRectangle.hyper_rectangle) (step : NumConst.t) (algo_instance_function : (PVal.pval -> AlgoStateBased.algoStateBased)) (tiles_manager_type : tiles_storage) = object (self) inherit algoCartoGeneric v0 step algo_instance_function tiles_manager_type as super (************************************************************) (* Class variables *) (************************************************************) (* The points array to be shuffled *) val mutable all_points_array : PVal.pval array option = None (* The index in the array *) val mutable next_point_index = 0 (************************************************************) (* Class methods *) (************************************************************) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) * Return the all_points_array ; raises InternalError if all_pi0_array was not initialized (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method private get_all_points_array_option = match all_points_array with | None -> raise (InternalError("all_points_array has not been initialized yet, altough it should have at this point.")) | Some all_points_array -> all_points_array (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (** Compute an array made of *all* points in V0 *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method private compute_all_points = (*** WARNING: step not implemented here! ***) if NumConst.neq step NumConst.one then( raise (InternalError("The step must be equal to 1 to compute all pi0 in V0 (for now).")); ); Check that nb_points has been computed ( it should have ) if NumConst.equal nb_points NumConst.zero then( raise (InternalError("The number of points in V0 has not been computed (but it should).")); ); (* Check that the number of points can be represented as an int *) if not (NumConst.is_int nb_points) then( raise (InternalError("The number of points in V0 is too big to be represented as an int.")); ); (* Convert to int *) let int_nb_points = NumConst.to_int nb_points in Create a array for all the pi0 , initially containing a useless object everywhere let useless_pi0 = new PVal.pval in self#print_algo_message Verbose_medium ("[compute_all_pi0] Creating an array of " ^ (string_of_int int_nb_points) ^ " points"); let all_points = Array.make int_nb_points useless_pi0 in self#print_algo_message Verbose_medium ("[compute_all_pi0] Computing the initial pi0"); Set the first point let first_point = self#compute_smallest_point in self#print_algo_message Verbose_medium ("[compute_all_pi0] Done computing the initial pi0"); self#print_algo_message Verbose_medium ("[compute_all_pi0] Setting pi0 to the first point"); Fill the first point with the initial pi0 all_points.(0) <- first_point; self#print_algo_message Verbose_medium ("[compute_all_pi0] Computing the other points"); (* Fill it for the other points *) let current_point = ref first_point in for pi0_index = 1 to int_nb_points - 1 do Compute the next pi0 let next_pi0_option = self#compute_next_sequential_pi0 !current_point in let next_pi0 = match next_pi0_option with If no more pi0 : problem ! | No_more -> raise (InternalError("No more pi0 before completing to fill the static array of all pi0.")) | Some_pval next_pi0 -> next_pi0 in (* Update the current point *) current_point := next_pi0; (* Fill the array *) all_points.(pi0_index) <- !current_point; done; self#print_algo_message Verbose_medium ("[compute_all_pi0] Done computing the other points"); (* Print some information *) if verbose_mode_greater Verbose_total then( (*** BEGIN DEBUG ***) (* Print all pi0 *) let model = Input.get_model() in for pi0_index = 0 to Array.length all_points - 1 do print_message Verbose_standard ((string_of_int pi0_index) ^ ":"); print_message Verbose_standard (ModelPrinter.string_of_pval model all_points.(pi0_index)); done; (*** END DEBUG ***) ); (* Return the array *) all_points (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (* Name of the algorithm *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method algorithm_name = "BC (full coverage, shuffle)" (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (* Variable initialization *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method initialize_variables = super#initialize_variables; Initialize the shuffled array 1 . Compute all points let all_points = self#compute_all_points in 2 . shuffle (*** TODO: add counter ***) * * NOTE : applied two times , because once is quite deterministic ( see warning in the array_shuffle code ) * * array_shuffle all_points; array_shuffle all_points; (*** TODO: add counter ***) 3 . Set it all_points_array <- Some all_points; 4 . Initialize the index next_point_index <- 0; (* Print some information *) if verbose_mode_greater Verbose_high then( (*** BEGIN DEBUG ***) (* Print all pi0 *) let model = Input.get_model() in for pi0_index = 0 to Array.length all_points - 1 do print_message Verbose_standard ((string_of_int pi0_index) ^ ":"); print_message Verbose_standard (ModelPrinter.string_of_pval model all_points.(pi0_index)); done; (*** END DEBUG ***) ); (* The end *) () (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (* Create the initial point for the analysis *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method get_initial_point = (* Print some information *) self#print_algo_message Verbose_medium ("Selecting the initial point (next point index = " ^ (string_of_int next_point_index) ^ ")"); (* Retrieve the array *) let all_points = self#get_all_points_array_option in (* Get the point *) let initial_point = all_points.(0) in Set the next to 1 (*** WARNING: incrementing is NOT good, as this function may in fact be called several times, in particular when called from distributed cartography ***) next_point_index <- 1; (* Return the point *) Some_pval initial_point (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (* Find the immediatly next point in the shuffled array *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method private next_point_in_array = (* Retrieve the array *) let all_points = self#get_all_points_array_option in (* Check that the array limit is not reached *) if next_point_index >= Array.length all_points then None else( (* Get the point *) let the_point = all_points.(next_point_index) in (* Increment the next point index *) next_point_index <- next_point_index + 1; (* Return the point *) Some the_point ) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (* Find the next point *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (*** BADPROG: code mostly copied from AlgoBCCover ***) method find_next_point = (* Print some information *) self#print_algo_message Verbose_medium ("Finding the next point (next point index = " ^ (string_of_int next_point_index) ^ ")"); Retrieve the current pi0 ( that must have been initialized before ) let current_pi0 = ref (self#get_current_point_option) in try( while true do 1 ) Compute the next pi0 ( if any left ) in a sequential manner let tentative_next_point = match self#next_point_in_array with | Some point -> point | None -> raise (Stop_loop No_more) in 2 ) Update our local current_pi0 current_pi0 := tentative_next_point; 3 ) Check that this pi0 is not covered by any tile self#print_algo_message Verbose_high ("Check whether pi0 is covered"); (* If uncovered: stop loop and return *) if self#test_pi0_uncovered !current_pi0 then raise (Stop_loop (Some_pval !current_pi0)) (* Else: keep running the loop *) while more pi0 and so on (* This point is unreachable *) raise (InternalError("This part of the code should be unreachable in find_next_point")) (* Return the point *) ) with Stop_loop sl -> sl (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (* Method packaging the result output by the algorithm *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method compute_bc_result = self#print_algo_message_newline Verbose_standard ( "Successfully terminated " ^ (after_seconds ()) ^ "." ); (* Get the termination status *) let termination_status = match termination_status with | None -> raise (InternalError "Termination status not set in BCShuffle.compute_bc_result") | Some status -> status in (* Retrieve the manager *) let tiles_manager = self#get_tiles_manager in (* Ask the tiles manager to process the result itself, by passing the appropriate arguments *) tiles_manager#process_result start_time v0 nb_points nb_unsuccessful_points termination_status None (************************************************************) (************************************************************) end;; (************************************************************) (************************************************************)
null
https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/AlgoBCShuffle.ml
ocaml
********************************************************** ********************************************************** Modules ********************************************************** ********************************************************** ********************************************************** ********************************************************** Internal exceptions ********************************************************** ********************************************************** To stop a loop when a point is found To stop a loop when a point is found or there is no more point ********************************************************** ********************************************************** Class definition ********************************************************** ********************************************************** ********************************************************** Class variables ********************************************************** The points array to be shuffled The index in the array ********************************************************** Class methods ********************************************************** -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- * Compute an array made of *all* points in V0 -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- ** WARNING: step not implemented here! ** Check that the number of points can be represented as an int Convert to int Fill it for the other points Update the current point Fill the array Print some information ** BEGIN DEBUG ** Print all pi0 ** END DEBUG ** Return the array -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Name of the algorithm -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Variable initialization -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- ** TODO: add counter ** ** TODO: add counter ** Print some information ** BEGIN DEBUG ** Print all pi0 ** END DEBUG ** The end -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Create the initial point for the analysis -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Print some information Retrieve the array Get the point ** WARNING: incrementing is NOT good, as this function may in fact be called several times, in particular when called from distributed cartography ** Return the point -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Find the immediatly next point in the shuffled array -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Retrieve the array Check that the array limit is not reached Get the point Increment the next point index Return the point -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Find the next point -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- ** BADPROG: code mostly copied from AlgoBCCover ** Print some information If uncovered: stop loop and return Else: keep running the loop This point is unreachable Return the point -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Method packaging the result output by the algorithm -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Get the termination status Retrieve the manager Ask the tiles manager to process the result itself, by passing the appropriate arguments ********************************************************** ********************************************************** ********************************************************** **********************************************************
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13 , LIPN , CNRS , France * Université de Lorraine , CNRS , , LORIA , Nancy , France * * Module description : Classical Behavioral Cartography with exhaustive coverage of integer points [ AF10 ] . Shuffled version , used for the distributed cartography . [ ACN15 ] * * File contributors : * Created : 2016/03/14 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13, LIPN, CNRS, France * Université de Lorraine, CNRS, Inria, LORIA, Nancy, France * * Module description: Classical Behavioral Cartography with exhaustive coverage of integer points [AF10]. Shuffled version, used for the distributed cartography. [ACN15] * * File contributors : Étienne André * Created : 2016/03/14 * ************************************************************) open OCamlUtilities open ImitatorUtilities open Exceptions open AbstractModel open Result open AlgoCartoGeneric exception Found_point of PVal.pval exception Stop_loop of more_points class algoBCShuffle (v0 : HyperRectangle.hyper_rectangle) (step : NumConst.t) (algo_instance_function : (PVal.pval -> AlgoStateBased.algoStateBased)) (tiles_manager_type : tiles_storage) = object (self) inherit algoCartoGeneric v0 step algo_instance_function tiles_manager_type as super val mutable all_points_array : PVal.pval array option = None val mutable next_point_index = 0 * Return the all_points_array ; raises InternalError if all_pi0_array was not initialized method private get_all_points_array_option = match all_points_array with | None -> raise (InternalError("all_points_array has not been initialized yet, altough it should have at this point.")) | Some all_points_array -> all_points_array method private compute_all_points = if NumConst.neq step NumConst.one then( raise (InternalError("The step must be equal to 1 to compute all pi0 in V0 (for now).")); ); Check that nb_points has been computed ( it should have ) if NumConst.equal nb_points NumConst.zero then( raise (InternalError("The number of points in V0 has not been computed (but it should).")); ); if not (NumConst.is_int nb_points) then( raise (InternalError("The number of points in V0 is too big to be represented as an int.")); ); let int_nb_points = NumConst.to_int nb_points in Create a array for all the pi0 , initially containing a useless object everywhere let useless_pi0 = new PVal.pval in self#print_algo_message Verbose_medium ("[compute_all_pi0] Creating an array of " ^ (string_of_int int_nb_points) ^ " points"); let all_points = Array.make int_nb_points useless_pi0 in self#print_algo_message Verbose_medium ("[compute_all_pi0] Computing the initial pi0"); Set the first point let first_point = self#compute_smallest_point in self#print_algo_message Verbose_medium ("[compute_all_pi0] Done computing the initial pi0"); self#print_algo_message Verbose_medium ("[compute_all_pi0] Setting pi0 to the first point"); Fill the first point with the initial pi0 all_points.(0) <- first_point; self#print_algo_message Verbose_medium ("[compute_all_pi0] Computing the other points"); let current_point = ref first_point in for pi0_index = 1 to int_nb_points - 1 do Compute the next pi0 let next_pi0_option = self#compute_next_sequential_pi0 !current_point in let next_pi0 = match next_pi0_option with If no more pi0 : problem ! | No_more -> raise (InternalError("No more pi0 before completing to fill the static array of all pi0.")) | Some_pval next_pi0 -> next_pi0 in current_point := next_pi0; all_points.(pi0_index) <- !current_point; done; self#print_algo_message Verbose_medium ("[compute_all_pi0] Done computing the other points"); if verbose_mode_greater Verbose_total then( let model = Input.get_model() in for pi0_index = 0 to Array.length all_points - 1 do print_message Verbose_standard ((string_of_int pi0_index) ^ ":"); print_message Verbose_standard (ModelPrinter.string_of_pval model all_points.(pi0_index)); done; ); all_points method algorithm_name = "BC (full coverage, shuffle)" method initialize_variables = super#initialize_variables; Initialize the shuffled array 1 . Compute all points let all_points = self#compute_all_points in 2 . shuffle * * NOTE : applied two times , because once is quite deterministic ( see warning in the array_shuffle code ) * * array_shuffle all_points; array_shuffle all_points; 3 . Set it all_points_array <- Some all_points; 4 . Initialize the index next_point_index <- 0; if verbose_mode_greater Verbose_high then( let model = Input.get_model() in for pi0_index = 0 to Array.length all_points - 1 do print_message Verbose_standard ((string_of_int pi0_index) ^ ":"); print_message Verbose_standard (ModelPrinter.string_of_pval model all_points.(pi0_index)); done; ); () method get_initial_point = self#print_algo_message Verbose_medium ("Selecting the initial point (next point index = " ^ (string_of_int next_point_index) ^ ")"); let all_points = self#get_all_points_array_option in let initial_point = all_points.(0) in Set the next to 1 next_point_index <- 1; Some_pval initial_point method private next_point_in_array = let all_points = self#get_all_points_array_option in if next_point_index >= Array.length all_points then None else( let the_point = all_points.(next_point_index) in next_point_index <- next_point_index + 1; Some the_point ) method find_next_point = self#print_algo_message Verbose_medium ("Finding the next point (next point index = " ^ (string_of_int next_point_index) ^ ")"); Retrieve the current pi0 ( that must have been initialized before ) let current_pi0 = ref (self#get_current_point_option) in try( while true do 1 ) Compute the next pi0 ( if any left ) in a sequential manner let tentative_next_point = match self#next_point_in_array with | Some point -> point | None -> raise (Stop_loop No_more) in 2 ) Update our local current_pi0 current_pi0 := tentative_next_point; 3 ) Check that this pi0 is not covered by any tile self#print_algo_message Verbose_high ("Check whether pi0 is covered"); if self#test_pi0_uncovered !current_pi0 then raise (Stop_loop (Some_pval !current_pi0)) while more pi0 and so on raise (InternalError("This part of the code should be unreachable in find_next_point")) ) with Stop_loop sl -> sl method compute_bc_result = self#print_algo_message_newline Verbose_standard ( "Successfully terminated " ^ (after_seconds ()) ^ "." ); let termination_status = match termination_status with | None -> raise (InternalError "Termination status not set in BCShuffle.compute_bc_result") | Some status -> status in let tiles_manager = self#get_tiles_manager in tiles_manager#process_result start_time v0 nb_points nb_unsuccessful_points termination_status None end;;
37c448bd57dfe443b3dff4dfc4b56b07304015085dbf456b206b066b615e6f3e
erlang/egd
egd_font.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 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% %% %% @doc egd_font %% -module(egd_font). -export([load/1, load_binary/1, size/1, glyph/2]). -include("egd.hrl"). %% Font represenatation in ets table %% egd_font_table %% %% Information: %% {Key, Description, Size} %% Key :: {Font :: atom(), information} %% Description :: any(), Description header from font file %% Size :: {W :: integer(), H :: integer()} %% : %% {Key, Translation LSs} where %% Key :: {Font :: atom(), Code :: integer()}, Code = glyph char code %% Translation :: { %% W :: integer(), % BBx width %% H :: integer(), % BBx height : : integer ( ) , % X start Y0 : : integer ( ) , % Y start %% Xm :: integer(), % Glyph X move when drawing %% } LSs : : [ [ { Xl : : integer ( ) , Xr : : integer ( ) } ] ] The first list is height ( top to bottom ) , the inner list is the list %% of line spans for the glyphs horizontal pixels. %% %%========================================================================== Interface functions %%========================================================================== size(Font) -> [{_Key, _Description, Size}] = ets:lookup(egd_font_table,{Font,information}), Size. glyph(Font, Code) -> [{_Key, Translation, LSs}] = ets:lookup(egd_font_table,{Font,Code}), {Translation, LSs}. load(Filename) -> {ok, Bin} = file:read_file(Filename), load_binary(Bin). load_binary(Bin) when is_binary(Bin) -> Font = erlang:binary_to_term(Bin), load_font_header(Font). %%========================================================================== Internal functions %%========================================================================== %% ETS handler functions initialize_table() -> egd_font_table = ets:new(egd_font_table, [named_table, ordered_set, public]), ok. glyph_insert(Font, Code, Translation, LSs) -> Element = {{Font, Code}, Translation, LSs}, ets:insert(egd_font_table, Element). font_insert(Font, Description, Dimensions) -> Element = {{Font, information}, Description, Dimensions}, ets:insert(egd_font_table, Element). %% Font loader functions is_font_loaded(Font) -> try case ets:lookup(egd_font_table, {Font, information}) of [] -> false; _ -> true end catch error:_ -> initialize_table(), false end. load_font_header({_Type, _Version, Font}) -> load_font_body(Font). load_font_body({Key,Desc,W,H,Glyphs,Bitmaps}) -> case is_font_loaded(Key) of true -> Key; false -> % insert dimensions font_insert(Key, Desc, {W,H}), parse_glyphs(Glyphs, Bitmaps, Key), Key end. parse_glyphs([], _ , _Key) -> ok; parse_glyphs([Glyph|Glyphs], Bs, Key) -> {Code, Translation, LSs} = parse_glyph(Glyph, Bs), glyph_insert(Key, Code, Translation, LSs), parse_glyphs(Glyphs, Bs, Key). parse_glyph({Code,W,H,X0,Y0,Xm,Offset}, Bitmasks) -> BytesPerLine = ((W+7) div 8), NumBytes = BytesPerLine*H, <<_:Offset/binary,Bitmask:NumBytes/binary,_/binary>> = Bitmasks, LSs = render_glyph(W,H,X0,Y0,Xm,Bitmask), {Code, {W,H,X0,Y0,Xm}, LSs}. render_glyph(W, H, X0, Y0, Xm, Bitmask) -> render_glyph(W,{0,H},X0,Y0,Xm,Bitmask, []). render_glyph(_W, {H,H}, _X0, _Y0, _Xm, _Bitmask, Out) -> Out; render_glyph(W, {Hi,H}, X0, Y0,Xm, Bitmask , LSs) -> N = ((W+7) div 8), O = N*Hi, <<_:O/binary, Submask/binary>> = Bitmask, LS = render_glyph_horizontal( Submask, % line glyph bitmask {down, W - 1}, % loop state W - 1, % Width Linespans render_glyph(W,{Hi+1,H},X0,Y0,Xm, Bitmask, [LS|LSs]). render_glyph_horizontal(Value, {Pr, Px}, 0, Spans) -> Cr = bit_spin(Value, 0), case {Pr,Cr} of {up , up } -> % closure of interval since its last [{0, Px}|Spans]; {up , down} -> % closure of interval [{1, Px}|Spans]; {down, up } -> % beginning of interval [{0, 0}|Spans]; {down, down} -> % no change in interval Spans end; render_glyph_horizontal(Value, {Pr, Px}, Cx, Spans) -> Cr = bit_spin(Value, Cx), case {Pr,Cr} of {up , up } -> % no change in interval render_glyph_horizontal(Value, {Cr, Px}, Cx - 1, Spans); {up , down} -> % closure of interval render_glyph_horizontal(Value, {Cr, Cx}, Cx - 1, [{Cx+1,Px}|Spans]); {down, up } -> % beginning of interval render_glyph_horizontal(Value, {Cr, Cx}, Cx - 1, Spans); {down, down} -> % no change in interval render_glyph_horizontal(Value, {Cr, Px}, Cx - 1, Spans) end. bit_spin(Value, Cx) -> <<_:Cx, Bit:1, _/bits>> = Value, case Bit of 1 -> up; 0 -> down end.
null
https://raw.githubusercontent.com/erlang/egd/1cea959544de7dd40a3284ba571a58939de57616/src/egd_font.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% @doc egd_font Font represenatation in ets table egd_font_table Information: {Key, Description, Size} Key :: {Font :: atom(), information} Description :: any(), Description header from font file Size :: {W :: integer(), H :: integer()} {Key, Translation LSs} where Key :: {Font :: atom(), Code :: integer()}, Code = glyph char code Translation :: { W :: integer(), % BBx width H :: integer(), % BBx height X start Y start Xm :: integer(), % Glyph X move when drawing } of line spans for the glyphs horizontal pixels. ========================================================================== ========================================================================== ========================================================================== ========================================================================== ETS handler functions Font loader functions insert dimensions line glyph bitmask loop state Width closure of interval since its last closure of interval beginning of interval no change in interval no change in interval closure of interval beginning of interval no change in interval
Copyright Ericsson AB 2008 - 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(egd_font). -export([load/1, load_binary/1, size/1, glyph/2]). -include("egd.hrl"). : LSs : : [ [ { Xl : : integer ( ) , Xr : : integer ( ) } ] ] The first list is height ( top to bottom ) , the inner list is the list Interface functions size(Font) -> [{_Key, _Description, Size}] = ets:lookup(egd_font_table,{Font,information}), Size. glyph(Font, Code) -> [{_Key, Translation, LSs}] = ets:lookup(egd_font_table,{Font,Code}), {Translation, LSs}. load(Filename) -> {ok, Bin} = file:read_file(Filename), load_binary(Bin). load_binary(Bin) when is_binary(Bin) -> Font = erlang:binary_to_term(Bin), load_font_header(Font). Internal functions initialize_table() -> egd_font_table = ets:new(egd_font_table, [named_table, ordered_set, public]), ok. glyph_insert(Font, Code, Translation, LSs) -> Element = {{Font, Code}, Translation, LSs}, ets:insert(egd_font_table, Element). font_insert(Font, Description, Dimensions) -> Element = {{Font, information}, Description, Dimensions}, ets:insert(egd_font_table, Element). is_font_loaded(Font) -> try case ets:lookup(egd_font_table, {Font, information}) of [] -> false; _ -> true end catch error:_ -> initialize_table(), false end. load_font_header({_Type, _Version, Font}) -> load_font_body(Font). load_font_body({Key,Desc,W,H,Glyphs,Bitmaps}) -> case is_font_loaded(Key) of true -> Key; false -> font_insert(Key, Desc, {W,H}), parse_glyphs(Glyphs, Bitmaps, Key), Key end. parse_glyphs([], _ , _Key) -> ok; parse_glyphs([Glyph|Glyphs], Bs, Key) -> {Code, Translation, LSs} = parse_glyph(Glyph, Bs), glyph_insert(Key, Code, Translation, LSs), parse_glyphs(Glyphs, Bs, Key). parse_glyph({Code,W,H,X0,Y0,Xm,Offset}, Bitmasks) -> BytesPerLine = ((W+7) div 8), NumBytes = BytesPerLine*H, <<_:Offset/binary,Bitmask:NumBytes/binary,_/binary>> = Bitmasks, LSs = render_glyph(W,H,X0,Y0,Xm,Bitmask), {Code, {W,H,X0,Y0,Xm}, LSs}. render_glyph(W, H, X0, Y0, Xm, Bitmask) -> render_glyph(W,{0,H},X0,Y0,Xm,Bitmask, []). render_glyph(_W, {H,H}, _X0, _Y0, _Xm, _Bitmask, Out) -> Out; render_glyph(W, {Hi,H}, X0, Y0,Xm, Bitmask , LSs) -> N = ((W+7) div 8), O = N*Hi, <<_:O/binary, Submask/binary>> = Bitmask, LS = render_glyph_horizontal( Linespans render_glyph(W,{Hi+1,H},X0,Y0,Xm, Bitmask, [LS|LSs]). render_glyph_horizontal(Value, {Pr, Px}, 0, Spans) -> Cr = bit_spin(Value, 0), case {Pr,Cr} of [{0, Px}|Spans]; [{1, Px}|Spans]; [{0, 0}|Spans]; Spans end; render_glyph_horizontal(Value, {Pr, Px}, Cx, Spans) -> Cr = bit_spin(Value, Cx), case {Pr,Cr} of render_glyph_horizontal(Value, {Cr, Px}, Cx - 1, Spans); render_glyph_horizontal(Value, {Cr, Cx}, Cx - 1, [{Cx+1,Px}|Spans]); render_glyph_horizontal(Value, {Cr, Cx}, Cx - 1, Spans); render_glyph_horizontal(Value, {Cr, Px}, Cx - 1, Spans) end. bit_spin(Value, Cx) -> <<_:Cx, Bit:1, _/bits>> = Value, case Bit of 1 -> up; 0 -> down end.
4b86d49d1a313bee19a625b901b1ebadad6803614399db1a1f2345456d36ff5c
gelisam/klister
IORef.hs
{-# LANGUAGE RankNTypes #-} -- | -- Variants of 'view', 'over', and 'set' for pieces of state which are represented using a Reader over an IORef instead of a State . module Control.Lens.IORef where import Control.Lens import Control.Monad.IO.Class import Control.Monad.Reader import Data.IORef viewIORef :: (MonadIO m, MonadReader r m) => Getting (IORef s) r (IORef s) -- ^ Getter r (IORef s) -> Getting a s a -- ^ Getter s a -> m a viewIORef refGetter leafGetter = do ref <- view refGetter s <- liftIO $ readIORef ref pure (view leafGetter s) overIORef :: (MonadIO m, MonadReader r m) => Getting (IORef s) r (IORef s) -- ^ Getter r (IORef s) -> ASetter' s a -- ^ Setter s a -> (a -> a) -> m () overIORef refGetter leafSetter f = do ref <- view refGetter liftIO $ modifyIORef ref (over leafSetter f) setIORef :: (MonadIO m, MonadReader r m) => Getting (IORef s) r (IORef s) -- ^ Getter r (IORef s) -> ASetter' s a -- ^ Setter s a -> a -> m () setIORef refGetter leafSetter a = do ref <- view refGetter liftIO $ modifyIORef ref (set leafSetter a)
null
https://raw.githubusercontent.com/gelisam/klister/71c71e6ab768e7e6b43e9402bc127423cd6e562b/src/Control/Lens/IORef.hs
haskell
# LANGUAGE RankNTypes # | Variants of 'view', 'over', and 'set' for pieces of state which are ^ Getter r (IORef s) ^ Getter s a ^ Getter r (IORef s) ^ Setter s a ^ Getter r (IORef s) ^ Setter s a
represented using a Reader over an IORef instead of a State . module Control.Lens.IORef where import Control.Lens import Control.Monad.IO.Class import Control.Monad.Reader import Data.IORef viewIORef :: (MonadIO m, MonadReader r m) -> m a viewIORef refGetter leafGetter = do ref <- view refGetter s <- liftIO $ readIORef ref pure (view leafGetter s) overIORef :: (MonadIO m, MonadReader r m) -> (a -> a) -> m () overIORef refGetter leafSetter f = do ref <- view refGetter liftIO $ modifyIORef ref (over leafSetter f) setIORef :: (MonadIO m, MonadReader r m) -> a -> m () setIORef refGetter leafSetter a = do ref <- view refGetter liftIO $ modifyIORef ref (set leafSetter a)
e703150997cb8bff38cb8bab4977b965ab9b63f6e94c9fd085b0d0cd1abfbfd3
theodormoroianu/SecondYearCourses
lab11_sol.hs
# LANGUAGE FlexibleInstances # import Data.Monoid import Data.Semigroup (Max (..), Min (..)) import Data.Foldable (foldMap, foldr) import Data.Char (isUpper) import Test.QuickCheck elem :: (Foldable t, Eq a) => a -> t a -> Bool elem x = getAny . foldMap (Any . (== x)) null :: (Foldable t) => t a -> Bool null = getAll . foldMap (All . (const False)) length :: (Foldable t) => t a -> Int length = getSum . foldMap (Sum . (const 1)) toList :: (Foldable t) => t a -> [a] toList = foldMap (:[]) fold :: (Foldable t, Monoid m) => t m -> m fold = foldMap id data Constant a b = Constant b instance Foldable (Constant a) where foldMap f (Constant b) = f b data Two a b = Two a b instance Foldable (Two a) where foldMap f (Two a b) = f b data Three a b c = Three a b c instance Foldable (Three a b) where foldMap f (Three a b c) = f c data Three' a b = Three' a b b instance Foldable (Three' a) where foldMap f (Three' a b1 b2) = f b1 <> f b2 data Four' a b = Four' a b b b instance Foldable (Four' a) where foldMap f (Four' a b1 b2 b3) = f b1 <> f b2 <> f b3 data GoatLord a = NoGoat | OneGoat a | MoreGoats (GoatLord a) (GoatLord a) (GoatLord a) instance Foldable GoatLord where foldMap f = go where go NoGoat = mempty go (OneGoat a) = f a go (MoreGoats gl1 gl2 gl3) = go gl1 <> go gl2 <> go gl3 filterF :: ( Applicative f , Foldable t , Monoid (f a) ) => (a -> Bool) -> t a -> f a filterF f = foldMap select where select a | f a = pure a | otherwise = mempty unit_testFilterF1 = filterF Data.Char.isUpper "aNA aRe mEre" == "NARE" unit_testFilterF2 = filterF Data.Char.isUpper "aNA aRe mEre" == First (Just 'N') unit_testFilterF3 = filterF Data.Char.isUpper "aNA aRe mEre" == Min 'A' unit_testFilterF4 = filterF Data.Char.isUpper "aNA aRe mEre" == Max 'R' unit_testFilterF5 = filterF Data.Char.isUpper "aNA aRe mEre" == Last (Just 'E') newtype Identity a = Identity a instance Functor Identity where fmap f (Identity a) = Identity (f a) data Pair a = Pair a a instance Functor Pair where fmap f (Pair a1 a2) = Pair (f a1) (f a2) scrieți pentru tipul Two de mai sus instance Functor (Two a) where fmap f (Two a b) = Two a (f b) scrieți pentru Three de mai sus instance Functor (Three a b) where fmap f (Three a b c) = Three a b (f c) scrieți pentru Three ' de mai sus instance Functor (Three' a) where fmap f (Three' a b1 b2) = Three' a (f b1) (f b2) data Four a b c d = Four a b c d instance Functor (Four a b c) where fmap f (Four a b c d) = Four a b c (f d) data Four'' a b = Four'' a a a b instance Functor (Four'' a) where fmap f (Four'' a1 a2 a3 b) = Four'' a1 a2 a3 (f b) scrieți o instanță de Functor penru instance Functor (Constant a) where fmap f (Constant b) = Constant (f b) data Quant a b = Finance | Desk a | Bloor b instance Functor (Quant a) where fmap _ Finance = Finance fmap _ (Desk a) = Desk a fmap f (Bloor b) = Bloor (f b) data K a b = K a instance Functor (K a) where fmap _ (K a) = K a newtype Flip f a b = Flip (f b a) deriving (Eq, Show) pentru Flip nu trebuie să faceți instanță instance Functor (Flip K a) where fmap f (Flip (K b)) = Flip (K (f b)) data LiftItOut f a = LiftItOut (f a) instance Functor f => Functor (LiftItOut f) where fmap f (LiftItOut fa) = LiftItOut (fmap f fa) data Parappa f g a = DaWrappa (f a) (g a) instance (Functor f, Functor g) => Functor (Parappa f g) where fmap f (DaWrappa fa ga) = DaWrappa (fmap f fa) (fmap f ga) data IgnoreOne f g a b = IgnoringSomething (f a) (g b) instance (Functor g) => Functor (IgnoreOne f g a) where fmap f (IgnoringSomething fa gb) = IgnoringSomething fa (fmap f gb) data Notorious g o a t = Notorious (g o) (g a) (g t) instance (Functor g) => Functor (Notorious g o a) where fmap f (Notorious ga gb gt) = Notorious ga gb (fmap f gt) scrieți o pentru instance Functor GoatLord where fmap f = go where go NoGoat = NoGoat go (OneGoat a) = OneGoat (f a) go (MoreGoats gl1 gl2 gl3) = MoreGoats (go gl1) (go gl2) (go gl3) data TalkToMe a = Halt | Print String a | Read (String -> a) instance Functor TalkToMe where fmap _ Halt = Halt fmap f (Print s a) = Print s (f a) fmap f (Read fa) = Read (f . fa)
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/99185b0e97119135e7301c2c7be0f07ae7258006/Haskell/l/lab11/lab11_sol.hs
haskell
# LANGUAGE FlexibleInstances # import Data.Monoid import Data.Semigroup (Max (..), Min (..)) import Data.Foldable (foldMap, foldr) import Data.Char (isUpper) import Test.QuickCheck elem :: (Foldable t, Eq a) => a -> t a -> Bool elem x = getAny . foldMap (Any . (== x)) null :: (Foldable t) => t a -> Bool null = getAll . foldMap (All . (const False)) length :: (Foldable t) => t a -> Int length = getSum . foldMap (Sum . (const 1)) toList :: (Foldable t) => t a -> [a] toList = foldMap (:[]) fold :: (Foldable t, Monoid m) => t m -> m fold = foldMap id data Constant a b = Constant b instance Foldable (Constant a) where foldMap f (Constant b) = f b data Two a b = Two a b instance Foldable (Two a) where foldMap f (Two a b) = f b data Three a b c = Three a b c instance Foldable (Three a b) where foldMap f (Three a b c) = f c data Three' a b = Three' a b b instance Foldable (Three' a) where foldMap f (Three' a b1 b2) = f b1 <> f b2 data Four' a b = Four' a b b b instance Foldable (Four' a) where foldMap f (Four' a b1 b2 b3) = f b1 <> f b2 <> f b3 data GoatLord a = NoGoat | OneGoat a | MoreGoats (GoatLord a) (GoatLord a) (GoatLord a) instance Foldable GoatLord where foldMap f = go where go NoGoat = mempty go (OneGoat a) = f a go (MoreGoats gl1 gl2 gl3) = go gl1 <> go gl2 <> go gl3 filterF :: ( Applicative f , Foldable t , Monoid (f a) ) => (a -> Bool) -> t a -> f a filterF f = foldMap select where select a | f a = pure a | otherwise = mempty unit_testFilterF1 = filterF Data.Char.isUpper "aNA aRe mEre" == "NARE" unit_testFilterF2 = filterF Data.Char.isUpper "aNA aRe mEre" == First (Just 'N') unit_testFilterF3 = filterF Data.Char.isUpper "aNA aRe mEre" == Min 'A' unit_testFilterF4 = filterF Data.Char.isUpper "aNA aRe mEre" == Max 'R' unit_testFilterF5 = filterF Data.Char.isUpper "aNA aRe mEre" == Last (Just 'E') newtype Identity a = Identity a instance Functor Identity where fmap f (Identity a) = Identity (f a) data Pair a = Pair a a instance Functor Pair where fmap f (Pair a1 a2) = Pair (f a1) (f a2) scrieți pentru tipul Two de mai sus instance Functor (Two a) where fmap f (Two a b) = Two a (f b) scrieți pentru Three de mai sus instance Functor (Three a b) where fmap f (Three a b c) = Three a b (f c) scrieți pentru Three ' de mai sus instance Functor (Three' a) where fmap f (Three' a b1 b2) = Three' a (f b1) (f b2) data Four a b c d = Four a b c d instance Functor (Four a b c) where fmap f (Four a b c d) = Four a b c (f d) data Four'' a b = Four'' a a a b instance Functor (Four'' a) where fmap f (Four'' a1 a2 a3 b) = Four'' a1 a2 a3 (f b) scrieți o instanță de Functor penru instance Functor (Constant a) where fmap f (Constant b) = Constant (f b) data Quant a b = Finance | Desk a | Bloor b instance Functor (Quant a) where fmap _ Finance = Finance fmap _ (Desk a) = Desk a fmap f (Bloor b) = Bloor (f b) data K a b = K a instance Functor (K a) where fmap _ (K a) = K a newtype Flip f a b = Flip (f b a) deriving (Eq, Show) pentru Flip nu trebuie să faceți instanță instance Functor (Flip K a) where fmap f (Flip (K b)) = Flip (K (f b)) data LiftItOut f a = LiftItOut (f a) instance Functor f => Functor (LiftItOut f) where fmap f (LiftItOut fa) = LiftItOut (fmap f fa) data Parappa f g a = DaWrappa (f a) (g a) instance (Functor f, Functor g) => Functor (Parappa f g) where fmap f (DaWrappa fa ga) = DaWrappa (fmap f fa) (fmap f ga) data IgnoreOne f g a b = IgnoringSomething (f a) (g b) instance (Functor g) => Functor (IgnoreOne f g a) where fmap f (IgnoringSomething fa gb) = IgnoringSomething fa (fmap f gb) data Notorious g o a t = Notorious (g o) (g a) (g t) instance (Functor g) => Functor (Notorious g o a) where fmap f (Notorious ga gb gt) = Notorious ga gb (fmap f gt) scrieți o pentru instance Functor GoatLord where fmap f = go where go NoGoat = NoGoat go (OneGoat a) = OneGoat (f a) go (MoreGoats gl1 gl2 gl3) = MoreGoats (go gl1) (go gl2) (go gl3) data TalkToMe a = Halt | Print String a | Read (String -> a) instance Functor TalkToMe where fmap _ Halt = Halt fmap f (Print s a) = Print s (f a) fmap f (Read fa) = Read (f . fa)
d4e86aff689605f00b69b750cdf1c983f24297a36f1aaa5aeaab61cd030b923d
michaelklishin/welle
counters_test.clj
(ns clojurewerkz.welle.test.counters-test (:require [clojurewerkz.welle.core :as wc] [clojurewerkz.welle.conversion :as conversion] [clojurewerkz.welle.buckets :as wb] [clojurewerkz.welle.counters :as cnt] [clojure.test :refer :all] [clojurewerkz.welle.testkit :refer [drain]])) (deftest test-counter (let [conn (wc/connect) bucket-name "clojurewerkz.welle.kv" counter "counter1" bucket (wb/update conn bucket-name {:allow-siblings true}) v1 (cnt/increment-counter conn bucket-name counter) v2 (cnt/fetch-counter conn bucket-name counter) v3 (cnt/increment-counter conn bucket-name counter {:value 2}) v4 (cnt/fetch-counter conn bucket-name counter) v5 (cnt/increment-counter conn bucket-name counter {:value -1}) v6 (cnt/fetch-counter conn bucket-name counter)] (is (= 1 v1)) (is (= 1 v2)) (is (= 3 v3)) (is (= 3 v4)) (is (= 2 v5)) (is (= 2 v6)) (drain conn bucket-name)))
null
https://raw.githubusercontent.com/michaelklishin/welle/3f3cd24af7c0d95489298e4096b362b6943f85ef/test/clojurewerkz/welle/test/counters_test.clj
clojure
(ns clojurewerkz.welle.test.counters-test (:require [clojurewerkz.welle.core :as wc] [clojurewerkz.welle.conversion :as conversion] [clojurewerkz.welle.buckets :as wb] [clojurewerkz.welle.counters :as cnt] [clojure.test :refer :all] [clojurewerkz.welle.testkit :refer [drain]])) (deftest test-counter (let [conn (wc/connect) bucket-name "clojurewerkz.welle.kv" counter "counter1" bucket (wb/update conn bucket-name {:allow-siblings true}) v1 (cnt/increment-counter conn bucket-name counter) v2 (cnt/fetch-counter conn bucket-name counter) v3 (cnt/increment-counter conn bucket-name counter {:value 2}) v4 (cnt/fetch-counter conn bucket-name counter) v5 (cnt/increment-counter conn bucket-name counter {:value -1}) v6 (cnt/fetch-counter conn bucket-name counter)] (is (= 1 v1)) (is (= 1 v2)) (is (= 3 v3)) (is (= 3 v4)) (is (= 2 v5)) (is (= 2 v6)) (drain conn bucket-name)))
5bcb8ec0ed7d5759d639b8b1e008f3461c43a7a557ac990c94f1ca9fcff0c38c
threatgrid/ctim
verdicts.cljc
(ns ctim.examples.verdicts (:require [ctim.schemas.common :as c])) (def verdict-maximal {:type "verdict" :observable {:type "ip", :value "10.0.0.1"} :disposition 1 :disposition_name "Clean" :judgement_id "-494d13ae-e914-43f0-883b-085062a8d9a1" :valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"}}) (def verdict-minimal {:type "verdict" :observable {:type "ip", :value "10.0.0.1"} :disposition 1 :valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"}})
null
https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/src/ctim/examples/verdicts.cljc
clojure
(ns ctim.examples.verdicts (:require [ctim.schemas.common :as c])) (def verdict-maximal {:type "verdict" :observable {:type "ip", :value "10.0.0.1"} :disposition 1 :disposition_name "Clean" :judgement_id "-494d13ae-e914-43f0-883b-085062a8d9a1" :valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"}}) (def verdict-minimal {:type "verdict" :observable {:type "ip", :value "10.0.0.1"} :disposition 1 :valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"}})
caa15bf64b3de72c2aafad4c43b303069471ce280aae1dd71696a2e3dad09c0f
karchie/stl2010-twitter
tweets.clj
(ns #^{:doc "Strange Loop 2010 twitter hackery" :author "Kevin A. Archie <>"} stl2010.tweets (:gen-class) (:use [clojure.contrib.string :only (join)]) (:require [clojure.contrib.http.agent :as http-agent] [clojure.contrib.json :as json])) (def +max-tweets+ 1200) (defn get-referenced-users [tweet] (set (map second (re-seq #"@(\w+)" (:text tweet))))) (defn build-nodes "Builds a set of unique nodes (Twitter users) from a collection of tweets." [tweets] (map #(hash-map :nodeName %) (set (mapcat #(conj (get-referenced-users %) (:from_user %)) tweets)))) (defn build-nodes-index "Builds a map from node name to 0-offset integer index" [nodes] (zipmap (map :nodeName nodes) (range))) (defn build-tweet-edge-identities "Builds the edge identities from a tweet" [tweet] (let [from-user (:from_user tweet) refs (get-referenced-users tweet)] (map #(hash-map :source from-user :target %) refs))) (defn build-edges-map "From a collection of tweets, builds a map from edge identity (as a map with :source and :target) to edge weight (number of occurrences)" [tweets] (reduce (fn [m tweet] (let [edges (build-tweet-edge-identities tweet)] (if (seq edges) (apply assoc m (mapcat #(vector % (inc (get m % 0))) edges)) m))) {} tweets)) (defn build-edges "Builds full edge records using zero-offset indices for the given tweets over the given nodes" [tweets nodes] (let [indices (build-nodes-index nodes)] (map (fn [[edge weight]] {:source (indices (:source edge)) :target (indices (:target edge)) :linkValue weight}) (build-edges-map tweets)))) (defn build-network "Builds a protovis-style network from the given collection of tweets" [tweets] (let [nodes (build-nodes tweets) edges (build-edges tweets nodes)] {:nodes nodes :links edges})) (defn get-some-tweets "Get some tweets matching the given search term(s), up to (not including) the optional tweet id :max-id. The search terms argument may be a string or a collection. Other optional keyword arguments: :results-per-page (default 100) - how many tweets per request" [terms & {:keys [max-id results-per-page] :or {results-per-page 100}}] (let [query (str "?" "q=" (if (coll? terms) (join "+" terms) terms) "&rpp=" results-per-page (if max-id (str "&max_id=" max-id) "")) entity (http-agent/string (http-agent/http-agent query))] (:results (json/read-json entity)))) (defn get-tweets "Get all the tweets available for the given search terms. Makes a request, and if the response is nonempty, uses the last id as max_id in another search request." ([terms acc] (let [oldest (if (empty? acc) nil (:id (last acc))) tweets (if oldest (do (print "have" (count acc) "tweets so far; ") (println "getting tweets before id" oldest) (get-some-tweets terms :max-id (dec oldest))) (get-some-tweets terms))] (if (or (empty? tweets) (>= (count acc) +max-tweets+)) acc (get-tweets terms (concat acc tweets))))) ([terms] (get-tweets terms []))) (defn extract-network "Retrieves tweets matching the given search term(s), extracts a protovis-style network from them, and writes as JavaScript into outfile; returns outfile" [outfile terms] (let [tweets (get-tweets terms) network (build-network tweets)] (with-open [fw (java.io.FileWriter. outfile) pw (java.io.PrintWriter. fw)] (.print pw "var strange_tweets = ") (json/write-json network pw) (.print pw ";")) {:node-count (count (:nodes network)) :link-count (count (:links network)) :tweet-count (count tweets) :output outfile})) (defn -main ([outfile & args] (println "done:" (extract-network outfile (if (seq args) args "strangeloop")) (System/exit 0))) ([] (println "Usage: tweets output-file [search-term ...]")))
null
https://raw.githubusercontent.com/karchie/stl2010-twitter/a5790cd1f9ca3d3962b21fe82b4b56a079a9042c/src/stl2010/tweets.clj
clojure
returns outfile"
(ns #^{:doc "Strange Loop 2010 twitter hackery" :author "Kevin A. Archie <>"} stl2010.tweets (:gen-class) (:use [clojure.contrib.string :only (join)]) (:require [clojure.contrib.http.agent :as http-agent] [clojure.contrib.json :as json])) (def +max-tweets+ 1200) (defn get-referenced-users [tweet] (set (map second (re-seq #"@(\w+)" (:text tweet))))) (defn build-nodes "Builds a set of unique nodes (Twitter users) from a collection of tweets." [tweets] (map #(hash-map :nodeName %) (set (mapcat #(conj (get-referenced-users %) (:from_user %)) tweets)))) (defn build-nodes-index "Builds a map from node name to 0-offset integer index" [nodes] (zipmap (map :nodeName nodes) (range))) (defn build-tweet-edge-identities "Builds the edge identities from a tweet" [tweet] (let [from-user (:from_user tweet) refs (get-referenced-users tweet)] (map #(hash-map :source from-user :target %) refs))) (defn build-edges-map "From a collection of tweets, builds a map from edge identity (as a map with :source and :target) to edge weight (number of occurrences)" [tweets] (reduce (fn [m tweet] (let [edges (build-tweet-edge-identities tweet)] (if (seq edges) (apply assoc m (mapcat #(vector % (inc (get m % 0))) edges)) m))) {} tweets)) (defn build-edges "Builds full edge records using zero-offset indices for the given tweets over the given nodes" [tweets nodes] (let [indices (build-nodes-index nodes)] (map (fn [[edge weight]] {:source (indices (:source edge)) :target (indices (:target edge)) :linkValue weight}) (build-edges-map tweets)))) (defn build-network "Builds a protovis-style network from the given collection of tweets" [tweets] (let [nodes (build-nodes tweets) edges (build-edges tweets nodes)] {:nodes nodes :links edges})) (defn get-some-tweets "Get some tweets matching the given search term(s), up to (not including) the optional tweet id :max-id. The search terms argument may be a string or a collection. Other optional keyword arguments: :results-per-page (default 100) - how many tweets per request" [terms & {:keys [max-id results-per-page] :or {results-per-page 100}}] (let [query (str "?" "q=" (if (coll? terms) (join "+" terms) terms) "&rpp=" results-per-page (if max-id (str "&max_id=" max-id) "")) entity (http-agent/string (http-agent/http-agent query))] (:results (json/read-json entity)))) (defn get-tweets "Get all the tweets available for the given search terms. Makes a request, and if the response is nonempty, uses the last id as max_id in another search request." ([terms acc] (let [oldest (if (empty? acc) nil (:id (last acc))) tweets (if oldest (do (print "have" (count acc) "tweets so far; ") (println "getting tweets before id" oldest) (get-some-tweets terms :max-id (dec oldest))) (get-some-tweets terms))] (if (or (empty? tweets) (>= (count acc) +max-tweets+)) acc (get-tweets terms (concat acc tweets))))) ([terms] (get-tweets terms []))) (defn extract-network "Retrieves tweets matching the given search term(s), extracts a protovis-style network from them, and writes as JavaScript into [outfile terms] (let [tweets (get-tweets terms) network (build-network tweets)] (with-open [fw (java.io.FileWriter. outfile) pw (java.io.PrintWriter. fw)] (.print pw "var strange_tweets = ") (json/write-json network pw) (.print pw ";")) {:node-count (count (:nodes network)) :link-count (count (:links network)) :tweet-count (count tweets) :output outfile})) (defn -main ([outfile & args] (println "done:" (extract-network outfile (if (seq args) args "strangeloop")) (System/exit 0))) ([] (println "Usage: tweets output-file [search-term ...]")))
bb850c28c3243f8bba2d1bd9bf1708cf1df5305854a8296d13e279eafef64921
jordanthayer/ocaml-search
main.ml
Online Planner . Will be first implemented by wrapping the progression planner with online capability : ( 1 ) receiving message ; ( 2 ) ask the simulator for the future committements ; ( 3 ) new branching rules that avoid mutex with future committements . try with a single search algorithm -- refer to main_pro / reg.ml for how to interface with multiple search algorithms . Note : regression would have to be armed with a STN . Online Planner. Will be first implemented by wrapping the progression planner with online capability: (1) receiving message; (2) ask the simulator for the future committements; (3) new branching rules that avoid mutex with future committements. try with a single search algorithm -- refer to main_pro/reg.ml for how to interface with multiple search algorithms. Note: regression would have to be armed with a STN. *) let parse_args () = let verb = ref 3 and p_alg = ref "unspeficied" and s_alg = ref "unspecified" and obj = ref "unspecified" and s_heu = ref "rp" and ept = ref 1.0 and pp = ref false and weight = ref 3.0 and runtime = ref 100.0 and basetime = ref infinity in Arg.parse [ "-debug", Arg.Int (fun i -> verb := i), "\tverbosity of debugging output (1-5)"; "-p", Arg.String (fun s -> p_alg := s), "\tSelect planner type"; "-s", Arg.String (fun s -> s_alg := s), "\tSelect the search algorithm"; "-o", Arg.String (fun s -> obj := s), "\tSelect the objective function"; "-ept", Arg.Float (fun f -> ept := f), "\tSet the estimated planning time value"; "-step_heu", Arg.String (fun s -> s_heu := s), "\tSelect the heuristic for optimizing steps"; "-pp", Arg.Set pp, "\tPost-process the fixed-time plan to reduce mpt effect"; "-w", Arg.Float (fun f -> weight := f), "\tSet weight for the weighted A* search algorithm"; "-t", Arg.Float (fun f -> runtime := f), "\tSet the runtime limit for search algorithm"; "-bt", Arg.Float (fun f -> basetime := f), "\tSet the basetime for synchronization"] (fun s -> raise (Arg.Bad s)) "Online Temporal Progression Planner, by Minh Do ()."; Args.set_args !p_alg !s_alg !obj !s_heu !pp !weight !runtime; Interactive.est_plan_time := !ept; if !basetime <> infinity then Time.set_basetime !basetime; !verb let main () = let v = parse_args () in Verb.with_level v (fun () -> Verb.pe 3 "Online forward planning! Send bug to Minh Do ()\n"; flush_all (); let buff = Lexing.from_channel stdin in let domain = Wrlexing.parse_verb 5 stderr "planning domain" (Parse_pddl_o.domain Lex_pddl_o.lexer) buff in let init_prob = Wrlexing.parse_verb 5 stderr "problem instance" (Parse_pddl_o.problem Lex_pddl_o.lexer) buff in Verb.pe 4 "%s\n%s\n" (Domain.domain_str domain) (Domain.problem_str init_prob); Apsp.build_scores init_prob; Interactive.sim_interact domain init_prob buff; Verb.pe 2 "Done planning!\n") let _ = main () EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/online/main.ml
ocaml
Online Planner . Will be first implemented by wrapping the progression planner with online capability : ( 1 ) receiving message ; ( 2 ) ask the simulator for the future committements ; ( 3 ) new branching rules that avoid mutex with future committements . try with a single search algorithm -- refer to main_pro / reg.ml for how to interface with multiple search algorithms . Note : regression would have to be armed with a STN . Online Planner. Will be first implemented by wrapping the progression planner with online capability: (1) receiving message; (2) ask the simulator for the future committements; (3) new branching rules that avoid mutex with future committements. try with a single search algorithm -- refer to main_pro/reg.ml for how to interface with multiple search algorithms. Note: regression would have to be armed with a STN. *) let parse_args () = let verb = ref 3 and p_alg = ref "unspeficied" and s_alg = ref "unspecified" and obj = ref "unspecified" and s_heu = ref "rp" and ept = ref 1.0 and pp = ref false and weight = ref 3.0 and runtime = ref 100.0 and basetime = ref infinity in Arg.parse [ "-debug", Arg.Int (fun i -> verb := i), "\tverbosity of debugging output (1-5)"; "-p", Arg.String (fun s -> p_alg := s), "\tSelect planner type"; "-s", Arg.String (fun s -> s_alg := s), "\tSelect the search algorithm"; "-o", Arg.String (fun s -> obj := s), "\tSelect the objective function"; "-ept", Arg.Float (fun f -> ept := f), "\tSet the estimated planning time value"; "-step_heu", Arg.String (fun s -> s_heu := s), "\tSelect the heuristic for optimizing steps"; "-pp", Arg.Set pp, "\tPost-process the fixed-time plan to reduce mpt effect"; "-w", Arg.Float (fun f -> weight := f), "\tSet weight for the weighted A* search algorithm"; "-t", Arg.Float (fun f -> runtime := f), "\tSet the runtime limit for search algorithm"; "-bt", Arg.Float (fun f -> basetime := f), "\tSet the basetime for synchronization"] (fun s -> raise (Arg.Bad s)) "Online Temporal Progression Planner, by Minh Do ()."; Args.set_args !p_alg !s_alg !obj !s_heu !pp !weight !runtime; Interactive.est_plan_time := !ept; if !basetime <> infinity then Time.set_basetime !basetime; !verb let main () = let v = parse_args () in Verb.with_level v (fun () -> Verb.pe 3 "Online forward planning! Send bug to Minh Do ()\n"; flush_all (); let buff = Lexing.from_channel stdin in let domain = Wrlexing.parse_verb 5 stderr "planning domain" (Parse_pddl_o.domain Lex_pddl_o.lexer) buff in let init_prob = Wrlexing.parse_verb 5 stderr "problem instance" (Parse_pddl_o.problem Lex_pddl_o.lexer) buff in Verb.pe 4 "%s\n%s\n" (Domain.domain_str domain) (Domain.problem_str init_prob); Apsp.build_scores init_prob; Interactive.sim_interact domain init_prob buff; Verb.pe 2 "Done planning!\n") let _ = main () EOF
a902db057a420d43f3be1f658ca823c7f4f2906f25cc5344889a2839806c3b98
marcelosousa/llvmvf
Module.hs
------------------------------------------------------------------------------- -- Module : Analysis.Type.Standard.Module Copyright : ( c ) 2013 -- A Type System for Memory Analysis of LLVM IR Modules -- Type Inference ------------------------------------------------------------------------------- module Analysis.Type.Standard.Module (typeCheckModule, STyRes) where import Analysis.Type.Standard.Function (typeCheckFunction,typeFunction) import Analysis.Type.Util import Analysis.Type.Standard.Global (typeCheckGlobal) import Language.LLVMIR import Language.LLVMIR.Printer import UU.PPrint import qualified Data.Map as M data STyRes = STyRes String TyEnv (M.Map Identifier TyEnv) initenv :: TyEnv initenv = M.insert (Global "llvm.lifetime.start") (TyPointer $ TyFunction [TyInt 64, TyPointer $ TyInt 8] TyVoid False) $ M.insert (Global "llvm.lifetime.end") (TyPointer $ TyFunction [TyInt 64, TyPointer $ TyInt 8] TyVoid False) $ M.insert (Global "llvm.frameaddress") (TyPointer $ TyFunction [TyInt 32] (TyPointer $ TyInt 8) False) $ M.insert (Global "llvm.dbg.declare") (TyPointer $ TyFunction [TyMetadata,TyMetadata] TyVoid False) $ M.singleton (Global "llvm.dbg.value") $ TyPointer $ TyFunction [TyMetadata, TyInt 64, TyMetadata] TyVoid False typeCheckModule :: Module -> STyRes typeCheckModule (Module i _ _ gvars funs nmdtys) = let tye = typeCheckGlo nmdtys initenv gvars in STyRes i tye $ typeCheckFuns nmdtys tye funs typeCheckGlo :: NamedTypes -> TyEnv -> Globals -> TyEnv typeCheckGlo nmdtye tye [] = tye typeCheckGlo nmdtye tye (x:xs) = let tye' = typeCheckGlobal nmdtye tye x in typeCheckGlo nmdtye tye' xs typeCheckFuns :: NamedTypes -> TyEnv -> Functions -> M.Map Identifier TyEnv typeCheckFuns nmdtye tye funs = let ntye = M.fold (\f r -> typeFunction r f) tye funs in M.map (typeCheckFunction nmdtye ntye) funs instance Show STyRes where show (STyRes s gs fns) = "Standard Type Analysis\n" ++ "Module " ++ s ++ "\n" ++ del ++ "Global Variables\n" ++ prettyTy gs ++ "\n" ++ del ++ foldr prettyFn del (M.toList fns) del :: String del = "========================\n" prettyFn :: (Identifier, TyEnv) -> String -> String prettyFn (n,ty) r = "Function " ++ show n ++ "\n" ++ prettyTy ty ++ r prettyTy :: TyEnv -> String prettyTy m = foldr prettyE "" $ M.toList m where prettyE (i,ty) s = (show $ pretty i) ++ "::" ++ (show $ pretty ty) ++ "\n" ++ s
null
https://raw.githubusercontent.com/marcelosousa/llvmvf/c314e43aa8bc8bb7fd9c83cebfbdcabee4ecfe1b/src/Analysis/Type/Standard/Module.hs
haskell
----------------------------------------------------------------------------- Module : Analysis.Type.Standard.Module A Type System for Memory Analysis of LLVM IR Modules Type Inference -----------------------------------------------------------------------------
Copyright : ( c ) 2013 module Analysis.Type.Standard.Module (typeCheckModule, STyRes) where import Analysis.Type.Standard.Function (typeCheckFunction,typeFunction) import Analysis.Type.Util import Analysis.Type.Standard.Global (typeCheckGlobal) import Language.LLVMIR import Language.LLVMIR.Printer import UU.PPrint import qualified Data.Map as M data STyRes = STyRes String TyEnv (M.Map Identifier TyEnv) initenv :: TyEnv initenv = M.insert (Global "llvm.lifetime.start") (TyPointer $ TyFunction [TyInt 64, TyPointer $ TyInt 8] TyVoid False) $ M.insert (Global "llvm.lifetime.end") (TyPointer $ TyFunction [TyInt 64, TyPointer $ TyInt 8] TyVoid False) $ M.insert (Global "llvm.frameaddress") (TyPointer $ TyFunction [TyInt 32] (TyPointer $ TyInt 8) False) $ M.insert (Global "llvm.dbg.declare") (TyPointer $ TyFunction [TyMetadata,TyMetadata] TyVoid False) $ M.singleton (Global "llvm.dbg.value") $ TyPointer $ TyFunction [TyMetadata, TyInt 64, TyMetadata] TyVoid False typeCheckModule :: Module -> STyRes typeCheckModule (Module i _ _ gvars funs nmdtys) = let tye = typeCheckGlo nmdtys initenv gvars in STyRes i tye $ typeCheckFuns nmdtys tye funs typeCheckGlo :: NamedTypes -> TyEnv -> Globals -> TyEnv typeCheckGlo nmdtye tye [] = tye typeCheckGlo nmdtye tye (x:xs) = let tye' = typeCheckGlobal nmdtye tye x in typeCheckGlo nmdtye tye' xs typeCheckFuns :: NamedTypes -> TyEnv -> Functions -> M.Map Identifier TyEnv typeCheckFuns nmdtye tye funs = let ntye = M.fold (\f r -> typeFunction r f) tye funs in M.map (typeCheckFunction nmdtye ntye) funs instance Show STyRes where show (STyRes s gs fns) = "Standard Type Analysis\n" ++ "Module " ++ s ++ "\n" ++ del ++ "Global Variables\n" ++ prettyTy gs ++ "\n" ++ del ++ foldr prettyFn del (M.toList fns) del :: String del = "========================\n" prettyFn :: (Identifier, TyEnv) -> String -> String prettyFn (n,ty) r = "Function " ++ show n ++ "\n" ++ prettyTy ty ++ r prettyTy :: TyEnv -> String prettyTy m = foldr prettyE "" $ M.toList m where prettyE (i,ty) s = (show $ pretty i) ++ "::" ++ (show $ pretty ty) ++ "\n" ++ s
fa3b8a95e055ea1009872daf6293f181b4b187fcd892c46915d995b6c3fee31f
alesaccoia/festival_flinger
cmu_us_rms_other.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Carnegie Mellon University ; ; ; and and ; ; ; Copyright ( c ) 1998 - 2000 ; ; ; All Rights Reserved . ; ; ; ;;; ;;; ;;; Permission is hereby granted, free of charge, to use and distribute ;;; ;;; this software and its documentation without restriction, including ;;; ;;; without limitation the rights to use, copy, modify, merge, publish, ;;; ;;; distribute, sublicense, and/or sell copies of this work, and to ;;; ;;; permit persons to whom this work is furnished to do so, subject to ;;; ;;; the following conditions: ;;; 1 . The code must retain the above copyright notice , this list of ; ; ; ;;; conditions and the following disclaimer. ;;; 2 . Any modifications must be clearly marked as such . ; ; ; 3 . Original authors ' names are not deleted . ; ; ; 4 . The authors ' names are not used to endorse or promote products ; ; ; ;;; derived from this software without specific prior written ;;; ;;; permission. ;;; ;;; ;;; CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ; ;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;; ;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;; SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ; ;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;; WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ; ;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;; ;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;; ;;; THIS SOFTWARE. ;;; ;;; ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Something else ;;; ;;; Load any necessary files here (define (cmu_us_rms::select_other) "(cmu_us_rms::select_other) Set up the anything esle for the voice." ;; something else ) (define (cmu_us_rms::reset_other) "(cmu_us_rms::reset_other) Reset other information." t ) (provide 'cmu_us_rms_other)
null
https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/lib/voices/us/cmu_us_rms_cg/festvox/cmu_us_rms_other.scm
scheme
;;; ; ; ; ; ; ; ; ; ;;; Permission is hereby granted, free of charge, to use and distribute ;;; this software and its documentation without restriction, including ;;; without limitation the rights to use, copy, modify, merge, publish, ;;; distribute, sublicense, and/or sell copies of this work, and to ;;; permit persons to whom this work is furnished to do so, subject to ;;; the following conditions: ;;; ; ; conditions and the following disclaimer. ;;; ; ; ; ; ; ; derived from this software without specific prior written ;;; permission. ;;; ;;; ; ; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;; ; ; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;; ; ; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;; THIS SOFTWARE. ;;; ;;; Something else Load any necessary files here something else
(define (cmu_us_rms::select_other) "(cmu_us_rms::select_other) Set up the anything esle for the voice." ) (define (cmu_us_rms::reset_other) "(cmu_us_rms::reset_other) Reset other information." t ) (provide 'cmu_us_rms_other)
fdd1886942299a9252f54e04cade98c92a531abe32079efba33cdf83f6259435
haskellfoundation/error-message-index
Foo.hs
module Foo where data Foo = Foo class IsAFoo x where convertToFoo :: x -> Foo instance IsAFoo Foo where convertToFoo = id
null
https://raw.githubusercontent.com/haskellfoundation/error-message-index/26c5c12c279eb4a997b1ff17eea46f1e86b046ab/message-index/messages/GHC-90177/example1/after/Foo.hs
haskell
module Foo where data Foo = Foo class IsAFoo x where convertToFoo :: x -> Foo instance IsAFoo Foo where convertToFoo = id
35856e663e0e11e4e228f43ec340991207db294eb0c88a828864a03353a74728
helium/blockchain-core
blockchain_cli_ledger.erl
%%%------------------------------------------------------------------- %% @doc %% == Blockchain CLI Ledger == %% @end %%%------------------------------------------------------------------- -module(blockchain_cli_ledger). -behavior(clique_handler). -export([register_cli/0]). -include("blockchain.hrl"). -include("blockchain_vars.hrl"). register_cli() -> register_all_usage(), register_all_cmds(). register_all_usage() -> lists:foreach(fun(Args) -> apply(clique, register_usage, Args) end, [ ledger_balance_usage(), ledger_export_usage(), ledger_gateways_usage(), ledger_cache_usage(), ledger_validators_usage(), ledger_variables_usage(), ledger_usage() ]). register_all_cmds() -> lists:foreach(fun(Cmds) -> [apply(clique, register_command, Cmd) || Cmd <- Cmds] end, [ ledger_balance_cmd(), ledger_export_cmd(), ledger_gateways_cmd(), ledger_cache_cmd(), ledger_validators_cmd(), ledger_variables_cmd(), ledger_cmd() ]). %%-------------------------------------------------------------------- %% ledger %%-------------------------------------------------------------------- ledger_usage() -> [["ledger"], ["blockchain ledger commands\n\n", " ledger balance - Get the balance for one or all addresses.\n" " ledger cache - Pre-load or clear h3 hex to region cache.\n" " ledger export - Export transactions from the ledger to <file>.\n" " ledger gateways - Display the list of active gateways.\n" " ledger validators - Retrieve all validators and a table of information about them.\n" " ledger variables - Interact with chain variables.\n" ] ]. ledger_cmd() -> [ [["ledger"], [], [], fun(_, _, _) -> usage end] ]. %%-------------------------------------------------------------------- %% ledger balance %%-------------------------------------------------------------------- ledger_balance_cmd() -> [ [["ledger", "balance", '*'], [], [], fun ledger_balance/3], [["ledger", "balance"], [], [ {htlc, [{shortname, "p"}, {longname, "htlc"}]} ], fun ledger_balance/3] ]. ledger_balance_usage() -> [["ledger", "balance"], ["ledger balance [<address> | -p]\n\n", " Retrieve the current balanace for a given <address>, all known addresses or just htlc balances.\n\n" "Options\n\n", " -p, --htlc\n", " Display balances for all known HTLCs.\n" ] ]. ledger_balance(["ledger", "balance", Str], [], []) -> Ledger = get_ledger(), case (catch libp2p_crypto:b58_to_bin(Str)) of {'EXIT', _} -> usage; Addr -> {ok, Entry} = blockchain_ledger_v1:find_entry(Addr, Ledger), {EntryMod, _EntryCF} = blockchain_ledger_v1:versioned_entry_mod_and_entries_cf(Ledger), R = [format_ledger_balance({Addr, EntryMod, Entry})], [clique_status:table(R)] end; ledger_balance(_CmdBase, [], []) -> Ledger = get_ledger(), {EntryMod, _EntryCF} = blockchain_ledger_v1:versioned_entry_mod_and_entries_cf(Ledger), Entries = maps:filter(fun(K, _V) -> is_binary(K) end, blockchain_ledger_v1:entries(Ledger)), R = [format_ledger_balance({A, EntryMod, E}) || {A, E} <- maps:to_list(Entries)], [clique_status:table(R)]; ledger_balance(_CmdBase, [], [{htlc, _}]) -> HTLCs = maps:filter(fun(K, _V) -> is_binary(K) end, blockchain_ledger_v1:htlcs(get_ledger())), R = [format_htlc_balance({A, H}) || {A, H} <- maps:to_list(HTLCs)], [clique_status:table(R)]. -spec format_ledger_balance({libp2p_crypto:pubkey_bin(), atom(), blockchain_ledger_entry_v1:entry() | blockchain_ledger_entry_v2:entry() | {error, any()}}) -> list(). format_ledger_balance({Addr, EntryMod, Entry}) -> [{p2p, libp2p_crypto:pubkey_bin_to_p2p(Addr)}, {nonce, integer_to_list(EntryMod:nonce(Entry))}, {balance, integer_to_list(EntryMod:balance(Entry))} ]. format_htlc_balance({Addr, HTLC}) -> [{address, libp2p_crypto:bin_to_b58(?B58_HTLC_VER, Addr)}, {payer, libp2p_crypto:pubkey_bin_to_p2p(blockchain_ledger_htlc_v1:payer(HTLC))}, {payee, libp2p_crypto:pubkey_bin_to_p2p(blockchain_ledger_htlc_v1:payee(HTLC))}, {hashlock, blockchain_utils:bin_to_hex(blockchain_ledger_htlc_v1:hashlock(HTLC))}, {timelock, integer_to_list(blockchain_ledger_htlc_v1:timelock(HTLC))}, {amount, integer_to_list(blockchain_ledger_htlc_v1:balance(HTLC))} ]. get_ledger() -> case blockchain_worker:blockchain() of undefined -> blockchain_ledger_v1:new("data"); Chain -> blockchain:ledger(Chain) end. %%-------------------------------------------------------------------- %% ledger cache %%-------------------------------------------------------------------- ledger_cache_cmd() -> [ [["ledger", "cache", '*'], [], [], fun ledger_cache/3] ]. ledger_cache_usage() -> [["ledger", "cache"], ["ledger cache [ prewarm | clear ]\n\n", " ledger cache prewarm - Pre-load h3 hex-to-region mapping for all gateways into cache.\n" " ledger cache clear - Clear h3 hex-to-region cache.\n" ] ]. ledger_cache(["ledger","cache","prewarm"], [], []) -> Ledger = blockchain:ledger(), Ret = blockchain_region_v1:prewarm_cache(Ledger), [clique_status:text(io_lib:format("~p", [Ret]))]; ledger_cache(["ledger","cache","clear"], [], []) -> Ret = blockchain_region_v1:clear_cache(), [clique_status:text(io_lib:format("~p", [Ret]))]; ledger_cache(["ledger","cache",_], [], []) -> ledger_cache_usage(). %%-------------------------------------------------------------------- %% ledger export %%-------------------------------------------------------------------- ledger_export_cmd() -> [ [["ledger", "export", '*'], [], [], fun ledger_export/3] ]. ledger_export_usage() -> [["ledger", "export"], ["ledger export <filename>\n\n", " Export transactions from the ledger to a given <filename>.\n" ] ]. ledger_export(["ledger", "export", Filename], [], []) -> case (catch file:write_file(Filename, io_lib:fwrite("~p.\n", [blockchain_ledger_exporter_v1:export(get_ledger())]))) of {'EXIT', _} -> usage; ok -> [clique_status:text(io_lib:format("ok, transactions written to ~p", [Filename]))]; {error, Reason} -> [clique_status:text(io_lib:format("~p", [Reason]))] end; ledger_export(_, _, _) -> usage. %%-------------------------------------------------------------------- %% ledger gateways %%-------------------------------------------------------------------- ledger_gateways_cmd() -> [ [["ledger", "gateways"], [], [], fun ledger_gateways/3], [["ledger", "gateways"], [], [{verbose, [{shortname, "v"}, {longname, "verbose"}]}], fun ledger_gateways/3] ]. ledger_gateways_usage() -> [["ledger", "gateways"], ["ledger gateways\n\n", " Retrieve all currently active gateways and their H3 index.\n" ] ]. ledger_gateways(_CmdBase, [], []) -> R = ledger_gw_fold(false), [clique_status:table(R)]; ledger_gateways(_CmdBase, [], [{verbose, _}]) -> R = ledger_gw_fold(true), [clique_status:table(R)]. ledger_gw_fold(Verbose) -> Ledger = get_ledger(), blockchain_ledger_v1:cf_fold( active_gateways, fun({Addr, BinGw}, Acc) -> Gw = blockchain_ledger_gateway_v2:deserialize(BinGw), [format_ledger_gateway_entry({Addr, Gw}, Ledger, Verbose) | Acc] end, [], Ledger). %%-------------------------------------------------------------------- %% ledger validators %%-------------------------------------------------------------------- ledger_validators_cmd() -> [ [["ledger", "validators"], [], [], fun ledger_validators/3], [["ledger", "validators"], [], [{verbose, [{shortname, "v"}, {longname, "verbose"}]}], fun ledger_validators/3] ]. ledger_validators_usage() -> [["ledger", "validators"], ["ledger validators\n\n", " Retrieve all validators and a table of information about them.\n" ] ]. ledger_validators(_CmdBase, [], []) -> R = ledger_val_fold(false), [clique_status:table(R)]; ledger_validators(_CmdBase, [], [{verbose, _}]) -> R = ledger_val_fold(true), [clique_status:table(R)]. ledger_val_fold(Verbose) -> Ledger = get_ledger(), blockchain_ledger_v1:cf_fold( validators, fun({Addr, BinVal}, Acc) -> Val = blockchain_ledger_validator_v1:deserialize(BinVal), [format_ledger_validator(Addr, Val, Ledger, Verbose) | Acc] end, [], Ledger). format_ledger_gateway_entry({GatewayAddr, Gateway}, Ledger, Verbose) -> {ok, Name} = erl_angry_purple_tiger:animal_name(libp2p_crypto:pubkey_to_b58(libp2p_crypto:bin_to_pubkey(GatewayAddr))), [{gateway_address, libp2p_crypto:pubkey_bin_to_p2p(GatewayAddr)}, {name, Name} | blockchain_ledger_gateway_v2:print(GatewayAddr, Gateway, Ledger, Verbose)]. format_ledger_validator(ValAddr, Validator, Ledger, Verbose) -> {ok, Height} = blockchain_ledger_v1:current_height(Ledger), [{name, blockchain_utils:addr2name(ValAddr)} | blockchain_ledger_validator_v1:print(Validator, Height, Verbose, Ledger)]. %%-------------------------------------------------------------------- %% ledger variables %%-------------------------------------------------------------------- ledger_variables_cmd() -> [ [["ledger", "variables", '*'], [], [], fun ledger_variables/3], [["ledger", "variables"], [], [ {all, [{shortname, "a"}, {longname, "all"}]} ], fun ledger_variables/3] ]. ledger_variables_usage() -> [["ledger", "variables"], ["ledger variables <variable name>\n\n", " Retrieve a chain-stored variable.\n", "Options\n\n", " -a, --all\n", " Display all variables.\n" ] ]. ledger_variables(Cmd, [], Flags) -> Ledger = get_ledger(), try case Cmd of [_, _, Name] -> NameAtom = list_to_atom(Name), case ?get_var(NameAtom, Ledger) of {ok, Var} -> [clique_status:text(io_lib:format("~p", [Var]))]; {error, not_found} -> [clique_status:text("variable not found")] end; [_, _] when Flags == [{all, undefined}] -> Vars = blockchain_ledger_v1:snapshot_vars(Ledger), [clique_status:text( [io_lib:format("~s: ~p~n", [N, V]) || {N, V} <- lists:sort(Vars)])]; _ -> usage end catch _:_ -> [clique_status:text("invalid variable name")] end.
null
https://raw.githubusercontent.com/helium/blockchain-core/0caf2295d0576c0ef803258e834bf6ec3b3e74bc/src/cli/blockchain_cli_ledger.erl
erlang
------------------------------------------------------------------- @doc == Blockchain CLI Ledger == @end ------------------------------------------------------------------- -------------------------------------------------------------------- ledger -------------------------------------------------------------------- -------------------------------------------------------------------- ledger balance -------------------------------------------------------------------- -------------------------------------------------------------------- ledger cache -------------------------------------------------------------------- -------------------------------------------------------------------- ledger export -------------------------------------------------------------------- -------------------------------------------------------------------- ledger gateways -------------------------------------------------------------------- -------------------------------------------------------------------- ledger validators -------------------------------------------------------------------- -------------------------------------------------------------------- ledger variables --------------------------------------------------------------------
-module(blockchain_cli_ledger). -behavior(clique_handler). -export([register_cli/0]). -include("blockchain.hrl"). -include("blockchain_vars.hrl"). register_cli() -> register_all_usage(), register_all_cmds(). register_all_usage() -> lists:foreach(fun(Args) -> apply(clique, register_usage, Args) end, [ ledger_balance_usage(), ledger_export_usage(), ledger_gateways_usage(), ledger_cache_usage(), ledger_validators_usage(), ledger_variables_usage(), ledger_usage() ]). register_all_cmds() -> lists:foreach(fun(Cmds) -> [apply(clique, register_command, Cmd) || Cmd <- Cmds] end, [ ledger_balance_cmd(), ledger_export_cmd(), ledger_gateways_cmd(), ledger_cache_cmd(), ledger_validators_cmd(), ledger_variables_cmd(), ledger_cmd() ]). ledger_usage() -> [["ledger"], ["blockchain ledger commands\n\n", " ledger balance - Get the balance for one or all addresses.\n" " ledger cache - Pre-load or clear h3 hex to region cache.\n" " ledger export - Export transactions from the ledger to <file>.\n" " ledger gateways - Display the list of active gateways.\n" " ledger validators - Retrieve all validators and a table of information about them.\n" " ledger variables - Interact with chain variables.\n" ] ]. ledger_cmd() -> [ [["ledger"], [], [], fun(_, _, _) -> usage end] ]. ledger_balance_cmd() -> [ [["ledger", "balance", '*'], [], [], fun ledger_balance/3], [["ledger", "balance"], [], [ {htlc, [{shortname, "p"}, {longname, "htlc"}]} ], fun ledger_balance/3] ]. ledger_balance_usage() -> [["ledger", "balance"], ["ledger balance [<address> | -p]\n\n", " Retrieve the current balanace for a given <address>, all known addresses or just htlc balances.\n\n" "Options\n\n", " -p, --htlc\n", " Display balances for all known HTLCs.\n" ] ]. ledger_balance(["ledger", "balance", Str], [], []) -> Ledger = get_ledger(), case (catch libp2p_crypto:b58_to_bin(Str)) of {'EXIT', _} -> usage; Addr -> {ok, Entry} = blockchain_ledger_v1:find_entry(Addr, Ledger), {EntryMod, _EntryCF} = blockchain_ledger_v1:versioned_entry_mod_and_entries_cf(Ledger), R = [format_ledger_balance({Addr, EntryMod, Entry})], [clique_status:table(R)] end; ledger_balance(_CmdBase, [], []) -> Ledger = get_ledger(), {EntryMod, _EntryCF} = blockchain_ledger_v1:versioned_entry_mod_and_entries_cf(Ledger), Entries = maps:filter(fun(K, _V) -> is_binary(K) end, blockchain_ledger_v1:entries(Ledger)), R = [format_ledger_balance({A, EntryMod, E}) || {A, E} <- maps:to_list(Entries)], [clique_status:table(R)]; ledger_balance(_CmdBase, [], [{htlc, _}]) -> HTLCs = maps:filter(fun(K, _V) -> is_binary(K) end, blockchain_ledger_v1:htlcs(get_ledger())), R = [format_htlc_balance({A, H}) || {A, H} <- maps:to_list(HTLCs)], [clique_status:table(R)]. -spec format_ledger_balance({libp2p_crypto:pubkey_bin(), atom(), blockchain_ledger_entry_v1:entry() | blockchain_ledger_entry_v2:entry() | {error, any()}}) -> list(). format_ledger_balance({Addr, EntryMod, Entry}) -> [{p2p, libp2p_crypto:pubkey_bin_to_p2p(Addr)}, {nonce, integer_to_list(EntryMod:nonce(Entry))}, {balance, integer_to_list(EntryMod:balance(Entry))} ]. format_htlc_balance({Addr, HTLC}) -> [{address, libp2p_crypto:bin_to_b58(?B58_HTLC_VER, Addr)}, {payer, libp2p_crypto:pubkey_bin_to_p2p(blockchain_ledger_htlc_v1:payer(HTLC))}, {payee, libp2p_crypto:pubkey_bin_to_p2p(blockchain_ledger_htlc_v1:payee(HTLC))}, {hashlock, blockchain_utils:bin_to_hex(blockchain_ledger_htlc_v1:hashlock(HTLC))}, {timelock, integer_to_list(blockchain_ledger_htlc_v1:timelock(HTLC))}, {amount, integer_to_list(blockchain_ledger_htlc_v1:balance(HTLC))} ]. get_ledger() -> case blockchain_worker:blockchain() of undefined -> blockchain_ledger_v1:new("data"); Chain -> blockchain:ledger(Chain) end. ledger_cache_cmd() -> [ [["ledger", "cache", '*'], [], [], fun ledger_cache/3] ]. ledger_cache_usage() -> [["ledger", "cache"], ["ledger cache [ prewarm | clear ]\n\n", " ledger cache prewarm - Pre-load h3 hex-to-region mapping for all gateways into cache.\n" " ledger cache clear - Clear h3 hex-to-region cache.\n" ] ]. ledger_cache(["ledger","cache","prewarm"], [], []) -> Ledger = blockchain:ledger(), Ret = blockchain_region_v1:prewarm_cache(Ledger), [clique_status:text(io_lib:format("~p", [Ret]))]; ledger_cache(["ledger","cache","clear"], [], []) -> Ret = blockchain_region_v1:clear_cache(), [clique_status:text(io_lib:format("~p", [Ret]))]; ledger_cache(["ledger","cache",_], [], []) -> ledger_cache_usage(). ledger_export_cmd() -> [ [["ledger", "export", '*'], [], [], fun ledger_export/3] ]. ledger_export_usage() -> [["ledger", "export"], ["ledger export <filename>\n\n", " Export transactions from the ledger to a given <filename>.\n" ] ]. ledger_export(["ledger", "export", Filename], [], []) -> case (catch file:write_file(Filename, io_lib:fwrite("~p.\n", [blockchain_ledger_exporter_v1:export(get_ledger())]))) of {'EXIT', _} -> usage; ok -> [clique_status:text(io_lib:format("ok, transactions written to ~p", [Filename]))]; {error, Reason} -> [clique_status:text(io_lib:format("~p", [Reason]))] end; ledger_export(_, _, _) -> usage. ledger_gateways_cmd() -> [ [["ledger", "gateways"], [], [], fun ledger_gateways/3], [["ledger", "gateways"], [], [{verbose, [{shortname, "v"}, {longname, "verbose"}]}], fun ledger_gateways/3] ]. ledger_gateways_usage() -> [["ledger", "gateways"], ["ledger gateways\n\n", " Retrieve all currently active gateways and their H3 index.\n" ] ]. ledger_gateways(_CmdBase, [], []) -> R = ledger_gw_fold(false), [clique_status:table(R)]; ledger_gateways(_CmdBase, [], [{verbose, _}]) -> R = ledger_gw_fold(true), [clique_status:table(R)]. ledger_gw_fold(Verbose) -> Ledger = get_ledger(), blockchain_ledger_v1:cf_fold( active_gateways, fun({Addr, BinGw}, Acc) -> Gw = blockchain_ledger_gateway_v2:deserialize(BinGw), [format_ledger_gateway_entry({Addr, Gw}, Ledger, Verbose) | Acc] end, [], Ledger). ledger_validators_cmd() -> [ [["ledger", "validators"], [], [], fun ledger_validators/3], [["ledger", "validators"], [], [{verbose, [{shortname, "v"}, {longname, "verbose"}]}], fun ledger_validators/3] ]. ledger_validators_usage() -> [["ledger", "validators"], ["ledger validators\n\n", " Retrieve all validators and a table of information about them.\n" ] ]. ledger_validators(_CmdBase, [], []) -> R = ledger_val_fold(false), [clique_status:table(R)]; ledger_validators(_CmdBase, [], [{verbose, _}]) -> R = ledger_val_fold(true), [clique_status:table(R)]. ledger_val_fold(Verbose) -> Ledger = get_ledger(), blockchain_ledger_v1:cf_fold( validators, fun({Addr, BinVal}, Acc) -> Val = blockchain_ledger_validator_v1:deserialize(BinVal), [format_ledger_validator(Addr, Val, Ledger, Verbose) | Acc] end, [], Ledger). format_ledger_gateway_entry({GatewayAddr, Gateway}, Ledger, Verbose) -> {ok, Name} = erl_angry_purple_tiger:animal_name(libp2p_crypto:pubkey_to_b58(libp2p_crypto:bin_to_pubkey(GatewayAddr))), [{gateway_address, libp2p_crypto:pubkey_bin_to_p2p(GatewayAddr)}, {name, Name} | blockchain_ledger_gateway_v2:print(GatewayAddr, Gateway, Ledger, Verbose)]. format_ledger_validator(ValAddr, Validator, Ledger, Verbose) -> {ok, Height} = blockchain_ledger_v1:current_height(Ledger), [{name, blockchain_utils:addr2name(ValAddr)} | blockchain_ledger_validator_v1:print(Validator, Height, Verbose, Ledger)]. ledger_variables_cmd() -> [ [["ledger", "variables", '*'], [], [], fun ledger_variables/3], [["ledger", "variables"], [], [ {all, [{shortname, "a"}, {longname, "all"}]} ], fun ledger_variables/3] ]. ledger_variables_usage() -> [["ledger", "variables"], ["ledger variables <variable name>\n\n", " Retrieve a chain-stored variable.\n", "Options\n\n", " -a, --all\n", " Display all variables.\n" ] ]. ledger_variables(Cmd, [], Flags) -> Ledger = get_ledger(), try case Cmd of [_, _, Name] -> NameAtom = list_to_atom(Name), case ?get_var(NameAtom, Ledger) of {ok, Var} -> [clique_status:text(io_lib:format("~p", [Var]))]; {error, not_found} -> [clique_status:text("variable not found")] end; [_, _] when Flags == [{all, undefined}] -> Vars = blockchain_ledger_v1:snapshot_vars(Ledger), [clique_status:text( [io_lib:format("~s: ~p~n", [N, V]) || {N, V} <- lists:sort(Vars)])]; _ -> usage end catch _:_ -> [clique_status:text("invalid variable name")] end.
3a9bdbd2323144682326a470e0a0e9cc5f452dc579b119ebeed3d3cae0bfec3f
cram2/cram
alpha-memory-node.lisp
;;; Copyright ( c ) 2009 , < > ;;; 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 Willow Garage , Inc. nor the names of its ;;; contributors may be used to endorse or promote products derived from ;;; this software without specific prior written permission. ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " ;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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. ;;; (in-package :prolog) (defclass alpha-memory-node (alpha-node) ((pattern :reader alpha-memory-node-pattern :initarg :pattern) (wme-memory :initform nil :reader wme-memory) (connections :reader connections :initform nil :documentation "List of connections input is called on when this node is reached. This is the point where beta nodes can connect to."))) (defmethod clear-facts ((node alpha-memory-node)) (loop for wme in (wme-memory node) do (input node wme :retract))) (defmethod gc-node ((node alpha-memory-node)) (when (and (null (wme-memory node)) (null (slot-value node 'connections))) (call-next-method))) (defmethod input ((node alpha-memory-node) wme operation &key unmatched) (cond (unmatched (call-next-method)) (t (let ((wme (typecase wme (alpha-node wme) (list node)))) (case operation (:assert (push wme (slot-value node 'wme-memory))) (:retract (assert (wme-memory node) nil "wme-memory already empty. Cannot retract.") (pop-if! (curry #'eq wme) (slot-value node 'wme-memory)) (gc-node node)) (t (error "Operation `~a' unknown." operation))) (loop for connection in (slot-value node 'connections) do (input connection wme operation)) wme))))
null
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_core/cram_prolog/src/rete/alpha-memory-node.lisp
lisp
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. contributors may be used to endorse or promote products derived from this software without specific prior written permission. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright ( c ) 2009 , < > * Neither the name of Willow Garage , Inc. nor the names of its THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN (in-package :prolog) (defclass alpha-memory-node (alpha-node) ((pattern :reader alpha-memory-node-pattern :initarg :pattern) (wme-memory :initform nil :reader wme-memory) (connections :reader connections :initform nil :documentation "List of connections input is called on when this node is reached. This is the point where beta nodes can connect to."))) (defmethod clear-facts ((node alpha-memory-node)) (loop for wme in (wme-memory node) do (input node wme :retract))) (defmethod gc-node ((node alpha-memory-node)) (when (and (null (wme-memory node)) (null (slot-value node 'connections))) (call-next-method))) (defmethod input ((node alpha-memory-node) wme operation &key unmatched) (cond (unmatched (call-next-method)) (t (let ((wme (typecase wme (alpha-node wme) (list node)))) (case operation (:assert (push wme (slot-value node 'wme-memory))) (:retract (assert (wme-memory node) nil "wme-memory already empty. Cannot retract.") (pop-if! (curry #'eq wme) (slot-value node 'wme-memory)) (gc-node node)) (t (error "Operation `~a' unknown." operation))) (loop for connection in (slot-value node 'connections) do (input connection wme operation)) wme))))
517f4d7f895b88fedd1cea4d0d157e8f52c0d94b77666a2ef3161063a778f2cf
haskell/ghcup-hs
IOStreams.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # module GHCup.Download.IOStreams where import GHCup.Download.Utils import GHCup.Errors import GHCup.Types.JSON ( ) import GHCup.Prelude import Control.Applicative import Control.Exception.Safe import Control.Monad import Control.Monad.Reader import Data.ByteString ( ByteString ) import Data.CaseInsensitive ( CI, original, mk ) import Data.IORef import Data.Maybe import Data.Text.Read import Haskus.Utils.Variant.Excepts import Network.Http.Client hiding ( URL ) import Prelude hiding ( abs , readFile , writeFile ) import System.ProgressBar import URI.ByteString import qualified Data.ByteString as BS import qualified Data.Map.Strict as M import qualified System.IO.Streams as Streams ---------------------------- --[ Low-level (non-curl) ]-- ---------------------------- downloadToFile :: (MonadMask m, MonadIO m) => Bool -- ^ https? -> ByteString -- ^ host (e.g. "www.example.com") -> ByteString -- ^ path (e.g. "/my/file") including query ^ optional port ( e.g. 3000 ) -> FilePath -- ^ destination file to create and write to -> M.Map (CI ByteString) ByteString -- ^ additional headers -> Maybe Integer -- ^ expected content length -> Excepts '[DownloadFailed, HTTPNotModified] m Response downloadToFile https host fullPath port destFile addHeaders eCSize = do let stepper = BS.appendFile destFile setup = BS.writeFile destFile mempty catchAllE (\case (V (HTTPStatusError i headers)) | i == 304 , Just e <- M.lookup (mk "etag") headers -> throwE $ HTTPNotModified (decUTF8Safe e) v -> throwE $ DownloadFailed v ) $ downloadInternal True https host fullPath port stepper setup addHeaders eCSize downloadInternal :: MonadIO m => Bool -- ^ whether to show a progress bar -> Bool -- ^ https? -> ByteString -- ^ host -> ByteString -- ^ path with query -> Maybe Int -- ^ optional port -> (ByteString -> IO a) -- ^ the consuming step function -> IO a -- ^ setup action -> M.Map (CI ByteString) ByteString -- ^ additional headers -> Maybe Integer -> Excepts '[ HTTPStatusError , URIParseError , UnsupportedScheme , NoLocationHeader , TooManyRedirs , ContentLengthError ] m Response downloadInternal = go (5 :: Int) where go redirs progressBar https host path port consumer setup addHeaders eCSize = do r <- liftIO $ withConnection' https host port action veitherToExcepts r >>= \case Right r' -> if redirs > 0 then followRedirectURL r' else throwE TooManyRedirs Left res -> pure res where action c = do let q = buildRequest1 $ do http GET path flip M.traverseWithKey addHeaders $ \key val -> setHeader (original key) val sendRequest c q emptyBody receiveResponse c (\r i' -> runE $ do let scode = getStatusCode r if | scode >= 200 && scode < 300 -> liftIO $ downloadStream r i' >> pure (Left r) | scode == 304 -> throwE $ HTTPStatusError scode (getHeaderMap r) | scode >= 300 && scode < 400 -> case getHeader r "Location" of Just r' -> pure $ Right r' Nothing -> throwE NoLocationHeader | otherwise -> throwE $ HTTPStatusError scode (getHeaderMap r) ) followRedirectURL bs = case parseURI strictURIParserOptions bs of Right uri' -> do (https', host', fullPath', port') <- liftE $ uriToQuadruple uri' go (redirs - 1) progressBar https' host' fullPath' port' consumer setup addHeaders eCSize Left e -> throwE e downloadStream r i' = do void setup let size = case getHeader r "Content-Length" of Just x' -> case decimal $ decUTF8Safe x' of Left _ -> Nothing Right (r', _) -> Just r' Nothing -> Nothing forM_ size $ \s -> forM_ eCSize $ \es -> when (es /= s) $ throwIO (ContentLengthError Nothing (Just s) es) let size' = eCSize <|> size (mpb :: Maybe (ProgressBar ())) <- case (progressBar, size') of (True, Just size'') -> Just <$> newProgressBar defStyle 10 (Progress 0 (fromInteger size'') ()) _ -> pure Nothing ior <- liftIO $ newIORef 0 outStream <- liftIO $ Streams.makeOutputStream (\case Just bs -> do let len = BS.length bs forM_ mpb $ \pb -> incProgress pb len -- check we don't exceed size forM_ size' $ \s -> do cs <- readIORef ior when ((cs + toInteger len) > s) $ throwIO (ContentLengthError Nothing (Just (cs + toInteger len)) s) modifyIORef ior (+ toInteger len) void $ consumer bs Nothing -> pure () ) liftIO $ Streams.connect i' outStream withConnection' :: Bool -> ByteString -> Maybe Int -> (Connection -> IO a) -> IO a withConnection' https host port = bracket acquire closeConnection where acquire = case https of True -> do ctx <- baselineContextSSL openConnectionSSL ctx host (fromIntegral $ fromMaybe 443 port) False -> openConnection host (fromIntegral $ fromMaybe 80 port)
null
https://raw.githubusercontent.com/haskell/ghcup-hs/109187eb6fcd8adc28cc892c5137fc9bae1d2639/lib/GHCup/Download/IOStreams.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # -------------------------- [ Low-level (non-curl) ]-- -------------------------- ^ https? ^ host (e.g. "www.example.com") ^ path (e.g. "/my/file") including query ^ destination file to create and write to ^ additional headers ^ expected content length ^ whether to show a progress bar ^ https? ^ host ^ path with query ^ optional port ^ the consuming step function ^ setup action ^ additional headers check we don't exceed size
# LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # module GHCup.Download.IOStreams where import GHCup.Download.Utils import GHCup.Errors import GHCup.Types.JSON ( ) import GHCup.Prelude import Control.Applicative import Control.Exception.Safe import Control.Monad import Control.Monad.Reader import Data.ByteString ( ByteString ) import Data.CaseInsensitive ( CI, original, mk ) import Data.IORef import Data.Maybe import Data.Text.Read import Haskus.Utils.Variant.Excepts import Network.Http.Client hiding ( URL ) import Prelude hiding ( abs , readFile , writeFile ) import System.ProgressBar import URI.ByteString import qualified Data.ByteString as BS import qualified Data.Map.Strict as M import qualified System.IO.Streams as Streams downloadToFile :: (MonadMask m, MonadIO m) ^ optional port ( e.g. 3000 ) -> Excepts '[DownloadFailed, HTTPNotModified] m Response downloadToFile https host fullPath port destFile addHeaders eCSize = do let stepper = BS.appendFile destFile setup = BS.writeFile destFile mempty catchAllE (\case (V (HTTPStatusError i headers)) | i == 304 , Just e <- M.lookup (mk "etag") headers -> throwE $ HTTPNotModified (decUTF8Safe e) v -> throwE $ DownloadFailed v ) $ downloadInternal True https host fullPath port stepper setup addHeaders eCSize downloadInternal :: MonadIO m -> Maybe Integer -> Excepts '[ HTTPStatusError , URIParseError , UnsupportedScheme , NoLocationHeader , TooManyRedirs , ContentLengthError ] m Response downloadInternal = go (5 :: Int) where go redirs progressBar https host path port consumer setup addHeaders eCSize = do r <- liftIO $ withConnection' https host port action veitherToExcepts r >>= \case Right r' -> if redirs > 0 then followRedirectURL r' else throwE TooManyRedirs Left res -> pure res where action c = do let q = buildRequest1 $ do http GET path flip M.traverseWithKey addHeaders $ \key val -> setHeader (original key) val sendRequest c q emptyBody receiveResponse c (\r i' -> runE $ do let scode = getStatusCode r if | scode >= 200 && scode < 300 -> liftIO $ downloadStream r i' >> pure (Left r) | scode == 304 -> throwE $ HTTPStatusError scode (getHeaderMap r) | scode >= 300 && scode < 400 -> case getHeader r "Location" of Just r' -> pure $ Right r' Nothing -> throwE NoLocationHeader | otherwise -> throwE $ HTTPStatusError scode (getHeaderMap r) ) followRedirectURL bs = case parseURI strictURIParserOptions bs of Right uri' -> do (https', host', fullPath', port') <- liftE $ uriToQuadruple uri' go (redirs - 1) progressBar https' host' fullPath' port' consumer setup addHeaders eCSize Left e -> throwE e downloadStream r i' = do void setup let size = case getHeader r "Content-Length" of Just x' -> case decimal $ decUTF8Safe x' of Left _ -> Nothing Right (r', _) -> Just r' Nothing -> Nothing forM_ size $ \s -> forM_ eCSize $ \es -> when (es /= s) $ throwIO (ContentLengthError Nothing (Just s) es) let size' = eCSize <|> size (mpb :: Maybe (ProgressBar ())) <- case (progressBar, size') of (True, Just size'') -> Just <$> newProgressBar defStyle 10 (Progress 0 (fromInteger size'') ()) _ -> pure Nothing ior <- liftIO $ newIORef 0 outStream <- liftIO $ Streams.makeOutputStream (\case Just bs -> do let len = BS.length bs forM_ mpb $ \pb -> incProgress pb len forM_ size' $ \s -> do cs <- readIORef ior when ((cs + toInteger len) > s) $ throwIO (ContentLengthError Nothing (Just (cs + toInteger len)) s) modifyIORef ior (+ toInteger len) void $ consumer bs Nothing -> pure () ) liftIO $ Streams.connect i' outStream withConnection' :: Bool -> ByteString -> Maybe Int -> (Connection -> IO a) -> IO a withConnection' https host port = bracket acquire closeConnection where acquire = case https of True -> do ctx <- baselineContextSSL openConnectionSSL ctx host (fromIntegral $ fromMaybe 443 port) False -> openConnection host (fromIntegral $ fromMaybe 80 port)
b0e89fe08f363cb6aaa948df260e827b56a7e3e2010597d4d3971b87ef4083a0
uwplse/synapse
log.rkt
#lang racket (provide logging? log-id log-start-time log-search log-cegis) (define logging? (make-parameter #f)) (define log-id (make-parameter #f)) (define log-start-time (make-parameter (current-inexact-milliseconds))) (define (format-time t) (~r (/ t 1000) #:precision 3)) (define (time-string search-start-time [my-start-time #f]) (define δt (format-time (- (current-inexact-milliseconds) search-start-time))) (cond [my-start-time (define my-time (format-time (- (current-inexact-milliseconds) my-start-time))) (format "t=~as; ~as" δt my-time)] [else (format "t=~as" δt)])) (define-syntax log-driver (syntax-rules () [(_ [src] [t] pred msg rest ...) (when (pred (logging?)) (parameterize ([error-print-width 100000]) (printf "[~a] [~a]~a ~a\n" src (time-string (log-start-time) t) (if (false? (log-id)) "" (format " [p~a]" (log-id))) (format msg rest ...))) (flush-output))] [(_ [src] pred msg rest ...) (log-driver [src] [#f] pred msg rest ...)])) (define-syntax log-search (syntax-rules () [(_ [t] msg rest ...) (log-driver ['search] [t] (compose not false?) msg rest ...)] [(_ msg rest ...) (log-search [#f] msg rest ...)])) (define-syntax log-cegis (syntax-rules () [(_ [trial] [t] msg rest ...) (log-driver ['icegis] [t] (lambda (b) (and (number? b) (> b 1))) (format "[r~a] ~a" trial (format msg rest ...)))] [(_ [trial] msg rest ...) (log-cegis [trial] [#f] msg rest ...)]))
null
https://raw.githubusercontent.com/uwplse/synapse/10f605f8f1fff6dade90607f516550b961a10169/opsyn/engine/log.rkt
racket
#lang racket (provide logging? log-id log-start-time log-search log-cegis) (define logging? (make-parameter #f)) (define log-id (make-parameter #f)) (define log-start-time (make-parameter (current-inexact-milliseconds))) (define (format-time t) (~r (/ t 1000) #:precision 3)) (define (time-string search-start-time [my-start-time #f]) (define δt (format-time (- (current-inexact-milliseconds) search-start-time))) (cond [my-start-time (define my-time (format-time (- (current-inexact-milliseconds) my-start-time))) (format "t=~as; ~as" δt my-time)] [else (format "t=~as" δt)])) (define-syntax log-driver (syntax-rules () [(_ [src] [t] pred msg rest ...) (when (pred (logging?)) (parameterize ([error-print-width 100000]) (printf "[~a] [~a]~a ~a\n" src (time-string (log-start-time) t) (if (false? (log-id)) "" (format " [p~a]" (log-id))) (format msg rest ...))) (flush-output))] [(_ [src] pred msg rest ...) (log-driver [src] [#f] pred msg rest ...)])) (define-syntax log-search (syntax-rules () [(_ [t] msg rest ...) (log-driver ['search] [t] (compose not false?) msg rest ...)] [(_ msg rest ...) (log-search [#f] msg rest ...)])) (define-syntax log-cegis (syntax-rules () [(_ [trial] [t] msg rest ...) (log-driver ['icegis] [t] (lambda (b) (and (number? b) (> b 1))) (format "[r~a] ~a" trial (format msg rest ...)))] [(_ [trial] msg rest ...) (log-cegis [trial] [#f] msg rest ...)]))
5fb1313432332f86ad600a182da6cacd350b80b31ab378f959aa59204181ffaa
raviksharma/bartosz-basics-of-haskell
Main.hs
module Main where import qualified Data.Map as M import Lexer (tokenize) import Parser (parse) import Evaluator main = do loop (M.fromList [("pi", pi), ("e", exp 1.0)]) loop symTab = do str <- getLine if null str then return () else let toks = tokenize str tree = parse toks Ev ev = evaluate tree symTab in case ev of Left msg -> do putStrLn $ "Error: " ++ msg loop symTab -- use old symTab Right (v, symTab') -> do print v loop symTab'
null
https://raw.githubusercontent.com/raviksharma/bartosz-basics-of-haskell/86d40d831f61415ef0022bff7fe7060ae6a23701/10-error-handling/evaluate4/Main.hs
haskell
use old symTab
module Main where import qualified Data.Map as M import Lexer (tokenize) import Parser (parse) import Evaluator main = do loop (M.fromList [("pi", pi), ("e", exp 1.0)]) loop symTab = do str <- getLine if null str then return () else let toks = tokenize str tree = parse toks Ev ev = evaluate tree symTab in case ev of Left msg -> do putStrLn $ "Error: " ++ msg Right (v, symTab') -> do print v loop symTab'
5d1e72fd6bdf9f8ef1604224b0155d753b3a89cdbfeb5f8feb8bdc541c1fe0af
ghc/nofib
ModArithm.hs
Time - stamp : < Sat Jun 05 2010 01:37:17 Stardate : Stardate : [ -28]3175.12 hwloidl > -- Modular Arithmetic over Z_p ----------------------------------------------------------------------------- @node Modular Arithmetic , ADT Matrix , Top , Top -- @chapter Modular Arithmetic module ModArithm (modHom, modSum, modDif, modProd, modQuot, modInv {-, Hom(hom) -} ) where # SPECIALISE modHom : : Int - > Int - > Int # modHom :: Int -> Int -> Int #-} modHom :: (Integral a) => a -> a -> a modHom m x = x `mod` m mapMod :: (Integral a) => (a -> a -> a) -> a -> a -> a -> a mapMod f m x y = modHom m (f x y) # SPECIALISE modSum : : Int - > Int - > Int - > Int # modSum :: Int -> Int -> Int -> Int #-} modSum :: (Integral a) => a -> a -> a -> a modSum = mapMod (+) # SPECIALISE modDif : : Int - > Int - > Int - > Int # modDif :: Int -> Int -> Int -> Int #-} modDif :: (Integral a) => a -> a -> a -> a modDif = mapMod (-) # SPECIALISE : : Int - > Int - > Int - > Int # modProd :: Int -> Int -> Int -> Int #-} modProd :: (Integral a) => a -> a -> a -> a modProd = mapMod (*) # SPECIALISE modQuot : : Int - > Int - > Int - > Int # modQuot :: Int -> Int -> Int -> Int #-} modQuot :: (Integral a) => a -> a -> a -> a modQuot m x y = modProd m x (modInv m y) {-# SPECIALISE modInv :: Int -> Int -> Int #-} modInv :: (Integral a) => a -> a -> a modInv m x = let (g,foo,inv) = gcdCF m x in if (g /= 1) then modHom m inv -- error $ "modInv: Input values " ++ (show (m,x)) ++ " are not relative prime!" ++ ("** Wrong GCD res: gcd= " ++ (show g) ++ "; but x*a+y*b= " ++ (show (m*foo+x*inv))) else modHom m inv gcdCF_with_check x y = let res@(g,a,b) = gcdCF x y in if check_gcdCF x y res then res else error ("** Wrong GCD res: gcd= " ++ (show g) ++ "; but x*a+y*b= " ++ (show (x*a+y*b))) # SPECIALISE gcdCF : : Int - > Int - > ( Int , Int , Int ) # gcdCF :: Int -> Int -> (Int,Int,Int) #-} gcdCF :: (Integral a) => a -> a -> (a,a,a) gcdCF x y = gcdCF' x y 1 0 0 1 where gcdCF' x 0 x1 x2 _ _ = (x,x1,x2) gcdCF' x y x1 x2 y1 y2 | x<y = gcdCF' y x y1 y2 x1 x2 | otherwise = let q = x `div` y z = x - q*y z1 = x1 - q*y1 z2 = x2 - q*y2 in gcdCF' y z y1 y2 z1 z2 check_gcdCF :: (Integral a) => a -> a -> (a,a,a) -> Bool check_gcdCF x y (g,a,b) = if (x*a+y*b)==g then True else False
null
https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/parallel/linsolv/ModArithm.hs
haskell
--------------------------------------------------------------------------- @chapter Modular Arithmetic , Hom(hom) # SPECIALISE modInv :: Int -> Int -> Int # error $ "modInv: Input values " ++ (show (m,x)) ++ " are not relative prime!" ++ ("** Wrong GCD res: gcd= " ++ (show g) ++ "; but x*a+y*b= " ++ (show (m*foo+x*inv)))
Time - stamp : < Sat Jun 05 2010 01:37:17 Stardate : Stardate : [ -28]3175.12 hwloidl > Modular Arithmetic over Z_p @node Modular Arithmetic , ADT Matrix , Top , Top module ModArithm (modHom, modSum, modDif, modProd, modQuot, modInv # SPECIALISE modHom : : Int - > Int - > Int # modHom :: Int -> Int -> Int #-} modHom :: (Integral a) => a -> a -> a modHom m x = x `mod` m mapMod :: (Integral a) => (a -> a -> a) -> a -> a -> a -> a mapMod f m x y = modHom m (f x y) # SPECIALISE modSum : : Int - > Int - > Int - > Int # modSum :: Int -> Int -> Int -> Int #-} modSum :: (Integral a) => a -> a -> a -> a modSum = mapMod (+) # SPECIALISE modDif : : Int - > Int - > Int - > Int # modDif :: Int -> Int -> Int -> Int #-} modDif :: (Integral a) => a -> a -> a -> a modDif = mapMod (-) # SPECIALISE : : Int - > Int - > Int - > Int # modProd :: Int -> Int -> Int -> Int #-} modProd :: (Integral a) => a -> a -> a -> a modProd = mapMod (*) # SPECIALISE modQuot : : Int - > Int - > Int - > Int # modQuot :: Int -> Int -> Int -> Int #-} modQuot :: (Integral a) => a -> a -> a -> a modQuot m x y = modProd m x (modInv m y) modInv :: (Integral a) => a -> a -> a modInv m x = let (g,foo,inv) = gcdCF m x in if (g /= 1) else modHom m inv gcdCF_with_check x y = let res@(g,a,b) = gcdCF x y in if check_gcdCF x y res then res else error ("** Wrong GCD res: gcd= " ++ (show g) ++ "; but x*a+y*b= " ++ (show (x*a+y*b))) # SPECIALISE gcdCF : : Int - > Int - > ( Int , Int , Int ) # gcdCF :: Int -> Int -> (Int,Int,Int) #-} gcdCF :: (Integral a) => a -> a -> (a,a,a) gcdCF x y = gcdCF' x y 1 0 0 1 where gcdCF' x 0 x1 x2 _ _ = (x,x1,x2) gcdCF' x y x1 x2 y1 y2 | x<y = gcdCF' y x y1 y2 x1 x2 | otherwise = let q = x `div` y z = x - q*y z1 = x1 - q*y1 z2 = x2 - q*y2 in gcdCF' y z y1 y2 z1 z2 check_gcdCF :: (Integral a) => a -> a -> (a,a,a) -> Bool check_gcdCF x y (g,a,b) = if (x*a+y*b)==g then True else False
ef76980f9c67c0652458cbdd76539085435457ae9c23bcdb7dba60389347d358
informatimago/lisp
scratch.lisp
(install-prompt-functions) (progn (let ((resource (gethash "lisp" *cached-resources*))) (let ((url (cached-resource-url resource)) (start (cached-resource-previous-length resource))) (multiple-value-bind (contents status headers uri stream do-close reason) (drakma:http-request url :external-format-in :latin-1 :keep-alive t :close nil :range '(0 0)) (declare (ignorable uri)) (let ((end (ignore-errors (let ((content-range (cdr (assoc :content-range headers)))) (parse-integer content-range :start (1+ (position #\/ content-range))))))) (if (and (= 206 status) end) (progn (multiple-value-setq (contents status headers uri stream do-close reason) (drakma:http-request url :external-format-in :latin-1 :range (list start end))) (unwind-protect (if (= status 200) (setf (cached-resource-previous-length resource) end (cached-resource-headers resource) headers (cached-resource-contents resource) contents) (error "Could not fetch the resource ~S for ~D ~A~%" (cached-resource-url resource) status reason)) (when do-close (close stream)))) (error "Could not fetch length of resource ~S for ~D ~A~%" (cached-resource-url resource) status reason)))))) (cached-resource-contents (gethash "lisp" *cached-resources*)) (initialize-cached-resources) (get-new-messages)) (initialize-cached-resources) (install-prompt-functions) (cached-resource-contents (gethash "lisp" *cached-resources*)) (get-new-messages)
null
https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/small-cl-pgms/irclog-prompter/scratch.lisp
lisp
(install-prompt-functions) (progn (let ((resource (gethash "lisp" *cached-resources*))) (let ((url (cached-resource-url resource)) (start (cached-resource-previous-length resource))) (multiple-value-bind (contents status headers uri stream do-close reason) (drakma:http-request url :external-format-in :latin-1 :keep-alive t :close nil :range '(0 0)) (declare (ignorable uri)) (let ((end (ignore-errors (let ((content-range (cdr (assoc :content-range headers)))) (parse-integer content-range :start (1+ (position #\/ content-range))))))) (if (and (= 206 status) end) (progn (multiple-value-setq (contents status headers uri stream do-close reason) (drakma:http-request url :external-format-in :latin-1 :range (list start end))) (unwind-protect (if (= status 200) (setf (cached-resource-previous-length resource) end (cached-resource-headers resource) headers (cached-resource-contents resource) contents) (error "Could not fetch the resource ~S for ~D ~A~%" (cached-resource-url resource) status reason)) (when do-close (close stream)))) (error "Could not fetch length of resource ~S for ~D ~A~%" (cached-resource-url resource) status reason)))))) (cached-resource-contents (gethash "lisp" *cached-resources*)) (initialize-cached-resources) (get-new-messages)) (initialize-cached-resources) (install-prompt-functions) (cached-resource-contents (gethash "lisp" *cached-resources*)) (get-new-messages)
a5e936c78729fca383bfeda31ca5c3a7ff1af73b15a0c14843c83e127812fcd9
beetleman/shadow-cljs-hooks
symbols.clj
(ns shadow-cljs-hooks.symbols) (defn eval-symbol [sym] (require (symbol (namespace sym)) :reload) (eval sym))
null
https://raw.githubusercontent.com/beetleman/shadow-cljs-hooks/1b0543124da8bc2dca04213bd3183ace14d2a1e1/src/shadow_cljs_hooks/symbols.clj
clojure
(ns shadow-cljs-hooks.symbols) (defn eval-symbol [sym] (require (symbol (namespace sym)) :reload) (eval sym))
dbada4230fe9beb3a05df860856a88e6fad62a82c665f0724a209c0fecfc0bae
input-output-hk/plutus
Spec.hs
-- editorconfig-checker-disable-file # LANGUAGE DataKinds # # LANGUAGE TypeApplications # # OPTIONS_GHC -fno - omit - interface - pragmas # # OPTIONS_GHC -fplugin PlutusTx . Plugin -fplugin - opt PlutusTx . Plugin : coverage - all # # OPTIONS_GHC -fplugin - opt PlutusTx . Plugin : max - simplifier - iterations - pir=0 # # OPTIONS_GHC -fplugin - opt PlutusTx . Plugin : max - simplifier - iterations - uplc=0 # module Plugin.Coverage.Spec (coverage) where import Control.Lens import Data.Map qualified as Map import Data.Proxy import Data.Set (Set) import Data.Set qualified as Set import PlutusTx.Code import PlutusTx.Coverage import PlutusTx.Plugin import PlutusTx.Prelude qualified as P import PlutusTx.Test import Prelude as Haskell import Test.Tasty import Test.Tasty.Extras import Test.Tasty.HUnit noBool :: CompiledCode (() -> ()) noBool = plc (Proxy @"noBool") (\() -> ()) boolTrueFalse :: CompiledCode (() -> Bool) boolTrueFalse = plc (Proxy @"boolTrueFalse") (\() -> True && False) boolOtherFunction :: CompiledCode (Maybe Integer -> Maybe Bool) boolOtherFunction = plc (Proxy @"boolOtherFunction") fun # INLINEABLE fun # fun :: Maybe Integer -> Maybe Bool fun x = case x of Just y | otherFun y -> Just False _ -> Nothing otherFun :: Integer -> Bool otherFun x = (x P.== 5) && True boolOtherFunctionSimplifiesAway :: CompiledCode (Integer -> Bool) boolOtherFunctionSimplifiesAway = plc (Proxy @"boolOtherFunctionSimplfiesAway") (\x -> otherFun x) boolQualifiedDisappears :: CompiledCode (() -> Bool) boolQualifiedDisappears = plc (Proxy @"boolQualifiedDisappears") (\ () -> Haskell.True) coverage :: TestNested coverage = testNested "Coverage" [ pure $ testGroup "Application heads and line coverage" [ mkTests "noBool" noBool Set.empty [30] , mkTests "boolTrueFalse" boolTrueFalse (Set.singleton "&&") [33] , mkTests "boolOtherFunction" boolOtherFunction (Set.fromList ["&&", "=="]) [36, 40, 41, 42] , mkTests "boolOtherFunctionSimplifiesAway" boolOtherFunctionSimplifiesAway (Set.fromList ["&&", "=="]) [48] , mkTests "boolQualifiedDisappears" boolQualifiedDisappears Set.empty [51] ] , goldenPir "coverageCode" boolOtherFunction ] mkTests :: String -> CompiledCode t -> Set String -> [Int] -> TestTree mkTests nm cc heads ls = testGroup nm [ applicationHeadsCorrect cc heads , linesInCoverageIndex cc ls ] applicationHeadsCorrect :: CompiledCode t -> Set String -> TestTree applicationHeadsCorrect cc heads = testCase "correct application heads" (assertEqual "" heads headSymbols) where headSymbols :: Set String headSymbols = -- TODO: This should really use a prism instead of going to and from lists I guess Set.fromList $ [ s | covMeta <- cc ^. to getCovIdx . coverageMetadata . to Map.elems , ApplicationHeadSymbol s <- Set.toList $ covMeta ^. metadataSet ] linesInCoverageIndex :: CompiledCode t -> [Int] -> TestTree linesInCoverageIndex cc ls = testCase "correct line coverage" (assertBool ("Lines " ++ show ls ++ " are not covered by " ++ show covLineSpans) covered) where covered = all (\l -> any (\(s, e) -> s <= l && l <= e) covLineSpans) ls covLineSpans = [ (covLoc ^. covLocStartLine, covLoc ^. covLocEndLine) | CoverLocation covLoc <- cc ^. to getCovIdx . coverageMetadata . to Map.keys ]
null
https://raw.githubusercontent.com/input-output-hk/plutus/863613c90abecb8271e9d80d868f2adb77b4d844/plutus-tx-plugin/test/Plugin/Coverage/Spec.hs
haskell
editorconfig-checker-disable-file TODO: This should really use a prism instead of going to and from lists I guess
# LANGUAGE DataKinds # # LANGUAGE TypeApplications # # OPTIONS_GHC -fno - omit - interface - pragmas # # OPTIONS_GHC -fplugin PlutusTx . Plugin -fplugin - opt PlutusTx . Plugin : coverage - all # # OPTIONS_GHC -fplugin - opt PlutusTx . Plugin : max - simplifier - iterations - pir=0 # # OPTIONS_GHC -fplugin - opt PlutusTx . Plugin : max - simplifier - iterations - uplc=0 # module Plugin.Coverage.Spec (coverage) where import Control.Lens import Data.Map qualified as Map import Data.Proxy import Data.Set (Set) import Data.Set qualified as Set import PlutusTx.Code import PlutusTx.Coverage import PlutusTx.Plugin import PlutusTx.Prelude qualified as P import PlutusTx.Test import Prelude as Haskell import Test.Tasty import Test.Tasty.Extras import Test.Tasty.HUnit noBool :: CompiledCode (() -> ()) noBool = plc (Proxy @"noBool") (\() -> ()) boolTrueFalse :: CompiledCode (() -> Bool) boolTrueFalse = plc (Proxy @"boolTrueFalse") (\() -> True && False) boolOtherFunction :: CompiledCode (Maybe Integer -> Maybe Bool) boolOtherFunction = plc (Proxy @"boolOtherFunction") fun # INLINEABLE fun # fun :: Maybe Integer -> Maybe Bool fun x = case x of Just y | otherFun y -> Just False _ -> Nothing otherFun :: Integer -> Bool otherFun x = (x P.== 5) && True boolOtherFunctionSimplifiesAway :: CompiledCode (Integer -> Bool) boolOtherFunctionSimplifiesAway = plc (Proxy @"boolOtherFunctionSimplfiesAway") (\x -> otherFun x) boolQualifiedDisappears :: CompiledCode (() -> Bool) boolQualifiedDisappears = plc (Proxy @"boolQualifiedDisappears") (\ () -> Haskell.True) coverage :: TestNested coverage = testNested "Coverage" [ pure $ testGroup "Application heads and line coverage" [ mkTests "noBool" noBool Set.empty [30] , mkTests "boolTrueFalse" boolTrueFalse (Set.singleton "&&") [33] , mkTests "boolOtherFunction" boolOtherFunction (Set.fromList ["&&", "=="]) [36, 40, 41, 42] , mkTests "boolOtherFunctionSimplifiesAway" boolOtherFunctionSimplifiesAway (Set.fromList ["&&", "=="]) [48] , mkTests "boolQualifiedDisappears" boolQualifiedDisappears Set.empty [51] ] , goldenPir "coverageCode" boolOtherFunction ] mkTests :: String -> CompiledCode t -> Set String -> [Int] -> TestTree mkTests nm cc heads ls = testGroup nm [ applicationHeadsCorrect cc heads , linesInCoverageIndex cc ls ] applicationHeadsCorrect :: CompiledCode t -> Set String -> TestTree applicationHeadsCorrect cc heads = testCase "correct application heads" (assertEqual "" heads headSymbols) where headSymbols :: Set String headSymbols = Set.fromList $ [ s | covMeta <- cc ^. to getCovIdx . coverageMetadata . to Map.elems , ApplicationHeadSymbol s <- Set.toList $ covMeta ^. metadataSet ] linesInCoverageIndex :: CompiledCode t -> [Int] -> TestTree linesInCoverageIndex cc ls = testCase "correct line coverage" (assertBool ("Lines " ++ show ls ++ " are not covered by " ++ show covLineSpans) covered) where covered = all (\l -> any (\(s, e) -> s <= l && l <= e) covLineSpans) ls covLineSpans = [ (covLoc ^. covLocStartLine, covLoc ^. covLocEndLine) | CoverLocation covLoc <- cc ^. to getCovIdx . coverageMetadata . to Map.keys ]
07fd2ad5f29abb39892cf88db8dfb6ab43cabc2e29c2ff9d87fbdfe9d2644d68
fragnix/fragnix
GHC.Integer.Logarithms.Compat.hs
{-# LANGUAGE Haskell2010 #-} # LINE 1 " src / GHC / Integer / Logarithms / Compat.hs " # -- | -- Module: GHC.Integer.Logarithms.Compat Copyright : ( c ) 2011 Licence : MIT Maintainer : < > -- Stability: Provisional Portability : Non - portable ( GHC extensions ) -- -- Low level stuff for integer logarithms. # LANGUAGE CPP , MagicHash , UnboxedTuples # module GHC.Integer.Logarithms.Compat ( -- * Functions integerLogBase# , integerLog2# , wordLog2# ) where -- Stuff is already there import GHC.Integer.Logarithms
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/application/GHC.Integer.Logarithms.Compat.hs
haskell
# LANGUAGE Haskell2010 # | Module: GHC.Integer.Logarithms.Compat Stability: Provisional Low level stuff for integer logarithms. * Functions Stuff is already there
# LINE 1 " src / GHC / Integer / Logarithms / Compat.hs " # Copyright : ( c ) 2011 Licence : MIT Maintainer : < > Portability : Non - portable ( GHC extensions ) # LANGUAGE CPP , MagicHash , UnboxedTuples # module GHC.Integer.Logarithms.Compat integerLogBase# , integerLog2# , wordLog2# ) where import GHC.Integer.Logarithms
db1b3869d26903d70ae1ada3cff64b3255a3fda85b504c7f7c2a54893b0b4858
kaznum/programming_in_ocaml_exercise
board.mli
(* マス目の状態 *) type state = Pressed | NotPressed (* 問題となる行・列のあるべき黒マス状態 *) type spec = int list (* 盤面 *) type board = { width : int; height : int; h_spec : spec list; v_spec : spec list; body : state ref list list; (* マス目の状態 *) } (* マス目が解となっているかどうかチェック *) val is_solved : h_spec:spec list -> v_spec:spec list -> state ref list list -> bool 問題から初期画面を作成する val board_of_spec : h_spec:spec list -> v_spec:spec list -> board
null
https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ch16/board.mli
ocaml
マス目の状態 問題となる行・列のあるべき黒マス状態 盤面 マス目の状態 マス目が解となっているかどうかチェック
type state = Pressed | NotPressed type spec = int list type board = { width : int; height : int; h_spec : spec list; v_spec : spec list; } val is_solved : h_spec:spec list -> v_spec:spec list -> state ref list list -> bool 問題から初期画面を作成する val board_of_spec : h_spec:spec list -> v_spec:spec list -> board
7ad88de2e1f9548bc524664827a65735127b2ac80bb338a919d9d895a399c22b
ijvcms/chuanqi_dev
map_20016.erl
-module(map_20016). -export([ range/0, data/0 ]). range() -> {48, 36}. data() -> { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,2,2,2,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,2,2,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,0,0,2,2,0,0,1,2,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,2,0,0,0,0,0,0,1,1,0,0,0,1,1,0,2,2,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1}, {1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,1}, {1,1,1,1,1,1,0,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1}, {1,1,1,1,1,1,1,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1}, {1,1,1,0,0,0,1,0,0,2,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1}, {1,1,0,0,0,2,1,0,2,2,2,2,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,2,1,2,2,0,0,0,0,2,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,2,1,1,1,2,0,2,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1}, {1,0,0,0,0,0,0,0,2,1,2,0,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1}, {1,0,0,0,0,0,0,0,2,2,2,0,0,1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1}, {1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1}, {1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1}, {1,1,1,0,0,0,0,0,2,1,1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,2,2,2,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,2,2,2,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,2,2,2,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} }.
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/map_data/map_20016.erl
erlang
-module(map_20016). -export([ range/0, data/0 ]). range() -> {48, 36}. data() -> { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,2,2,2,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,2,2,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,0,0,2,2,0,0,1,2,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,2,0,0,0,0,0,0,1,1,0,0,0,1,1,0,2,2,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1}, {1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,1}, {1,1,1,1,1,1,0,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1}, {1,1,1,1,1,1,1,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1}, {1,1,1,0,0,0,1,0,0,2,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1}, {1,1,0,0,0,2,1,0,2,2,2,2,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,2,1,2,2,0,0,0,0,2,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,2,1,1,1,2,0,2,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1}, {1,0,0,0,0,0,0,0,2,1,2,0,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1}, {1,0,0,0,0,0,0,0,2,2,2,0,0,1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1}, {1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1}, {1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1}, {1,1,1,0,0,0,0,0,2,1,1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,2,2,2,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,2,2,2,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,2,2,2,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} }.
1f4801637f95da0f3ddf2f9649a446a8a32925554936455dfa6331ce23eb02dc
cedlemo/OCaml-GI-ctypes-bindings-generator
Recent_manager_error.ml
open Ctypes open Foreign type t = Not_found | Invalid_uri | Invalid_encoding | Not_registered | Read | Write | Unknown let of_value v = if v = Unsigned.UInt32.of_int 0 then Not_found else if v = Unsigned.UInt32.of_int 1 then Invalid_uri else if v = Unsigned.UInt32.of_int 2 then Invalid_encoding else if v = Unsigned.UInt32.of_int 3 then Not_registered else if v = Unsigned.UInt32.of_int 4 then Read else if v = Unsigned.UInt32.of_int 5 then Write else if v = Unsigned.UInt32.of_int 6 then Unknown else raise (Invalid_argument "Unexpected Recent_manager_error value") let to_value = function | Not_found -> Unsigned.UInt32.of_int 0 | Invalid_uri -> Unsigned.UInt32.of_int 1 | Invalid_encoding -> Unsigned.UInt32.of_int 2 | Not_registered -> Unsigned.UInt32.of_int 3 | Read -> Unsigned.UInt32.of_int 4 | Write -> Unsigned.UInt32.of_int 5 | Unknown -> Unsigned.UInt32.of_int 6 let t_view = view ~read:of_value ~write:to_value uint32_t
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Recent_manager_error.ml
ocaml
open Ctypes open Foreign type t = Not_found | Invalid_uri | Invalid_encoding | Not_registered | Read | Write | Unknown let of_value v = if v = Unsigned.UInt32.of_int 0 then Not_found else if v = Unsigned.UInt32.of_int 1 then Invalid_uri else if v = Unsigned.UInt32.of_int 2 then Invalid_encoding else if v = Unsigned.UInt32.of_int 3 then Not_registered else if v = Unsigned.UInt32.of_int 4 then Read else if v = Unsigned.UInt32.of_int 5 then Write else if v = Unsigned.UInt32.of_int 6 then Unknown else raise (Invalid_argument "Unexpected Recent_manager_error value") let to_value = function | Not_found -> Unsigned.UInt32.of_int 0 | Invalid_uri -> Unsigned.UInt32.of_int 1 | Invalid_encoding -> Unsigned.UInt32.of_int 2 | Not_registered -> Unsigned.UInt32.of_int 3 | Read -> Unsigned.UInt32.of_int 4 | Write -> Unsigned.UInt32.of_int 5 | Unknown -> Unsigned.UInt32.of_int 6 let t_view = view ~read:of_value ~write:to_value uint32_t
b2e3a4ea15a3f6387924a5786bec98ad6133b66ada4667ca25aa9ddbb7cc6293
mro/geohash
assert2.ml
let equals_int = Assert.assert_equals_int let equals_float = Assert.assert_equals_float let equals_string = Assert.assert_equals_string
null
https://raw.githubusercontent.com/mro/geohash/6a8ab5102b6bc1b7fd8f090f54329273ed9a68c4/test/assert2.ml
ocaml
let equals_int = Assert.assert_equals_int let equals_float = Assert.assert_equals_float let equals_string = Assert.assert_equals_string
36ce8244c1bac6b9deb51b969e2ac1fac8eeb9dcd53e59ae3208fe5e0823423e
thattommyhall/offline-4clojure
p171.clj
;; Intervals - Medium Write a function that takes a sequence of integers and returns a sequence of " intervals " . Each interval is a a vector of two integers , start and end , such that all integers between start and end ( inclusive ) are contained in the input sequence . ;; tags - ;; restricted - (ns offline-4clojure.p171 (:use clojure.test)) (def __ ;; your solution here ) (defn -main [] (are [soln] soln (= (__ [1 2 3]) [[1 3]]) (= (__ [10 9 8 1 2 3]) [[1 3] [8 10]]) (= (__ [1 1 1 1 1 1 1]) [[1 1]]) (= (__ []) []) (= (__ [19 4 17 1 3 10 2 13 13 2 16 4 2 15 13 9 6 14 2 11]) [[1 4] [6 6] [9 11] [13 17] [19 19]]) ))
null
https://raw.githubusercontent.com/thattommyhall/offline-4clojure/73e32fc6687816aea3c514767cef3916176589ab/src/offline_4clojure/p171.clj
clojure
Intervals - Medium tags - restricted - your solution here
Write a function that takes a sequence of integers and returns a sequence of " intervals " . Each interval is a a vector of two integers , start and end , such that all integers between start and end ( inclusive ) are contained in the input sequence . (ns offline-4clojure.p171 (:use clojure.test)) (def __ ) (defn -main [] (are [soln] soln (= (__ [1 2 3]) [[1 3]]) (= (__ [10 9 8 1 2 3]) [[1 3] [8 10]]) (= (__ [1 1 1 1 1 1 1]) [[1 1]]) (= (__ []) []) (= (__ [19 4 17 1 3 10 2 13 13 2 16 4 2 15 13 9 6 14 2 11]) [[1 4] [6 6] [9 11] [13 17] [19 19]]) ))
7cba81c79d3d01b9a2c76e49c35630dc2e818db16dbf140654344e307ed270a8
portkey-cloud/aws-clj-sdk
_2017-07-01.clj
(ns portkey.aws.translate.-2017-07-01 (:require [portkey.aws])) (def endpoints '{"us-east-2" {:credential-scope {:service "translate", :region "us-east-2"}, :ssl-common-name "translate.us-east-2.amazonaws.com", :endpoint "-east-2.amazonaws.com", :signature-version :v4}, "us-west-2" {:credential-scope {:service "translate", :region "us-west-2"}, :ssl-common-name "translate.us-west-2.amazonaws.com", :endpoint "-west-2.amazonaws.com", :signature-version :v4}, "us-east-1" {:credential-scope {:service "translate", :region "us-east-1"}, :ssl-common-name "translate.us-east-1.amazonaws.com", :endpoint "-east-1.amazonaws.com", :signature-version :v4}}) (comment TODO support "json")
null
https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/translate/_2017-07-01.clj
clojure
(ns portkey.aws.translate.-2017-07-01 (:require [portkey.aws])) (def endpoints '{"us-east-2" {:credential-scope {:service "translate", :region "us-east-2"}, :ssl-common-name "translate.us-east-2.amazonaws.com", :endpoint "-east-2.amazonaws.com", :signature-version :v4}, "us-west-2" {:credential-scope {:service "translate", :region "us-west-2"}, :ssl-common-name "translate.us-west-2.amazonaws.com", :endpoint "-west-2.amazonaws.com", :signature-version :v4}, "us-east-1" {:credential-scope {:service "translate", :region "us-east-1"}, :ssl-common-name "translate.us-east-1.amazonaws.com", :endpoint "-east-1.amazonaws.com", :signature-version :v4}}) (comment TODO support "json")
c88c54ce49fcbd69acc8ab9332c10b80699ff050dc139c245e9054439230f301
jakemcc/sicp-study
1.19.clj
Exercise 1.19 (ns exercise1.19 (:use clojure.test)) Was attempting to use clojure.test , was having issues though , leaving in to hopefully ; have discussion on it Compute p ' and q ' Tpq = { a < - bq + aq + ap ; { b <- bp + aq If Tpq is applied twice that is the same as ' . Therefor to figure out p ' and q ' apply Tpq twice ; Tpq^2 = { a <- bpq + aqq + bqq + aqq + apq + bqp + aqp + app = ; b(pq + qq + qp) + a(pq + qq + qp) + a(pp + qq) ; { b <- bpp + aqp + bqq + aqq + apq = b(pp + qq) + a(qp + qq + pq) ; Looking at the equations you can see that p' = pp + qq, q' = 2*pq + qq ; Put those into fib-iter and it works (defn fib-iter [a b p q count] (cond (= count 0) b (even? count) (fib-iter a b (+ (* p p) (* q q)) ; compute p' (+ (* 2 p q) (* q q)) ; compute q' (/ count 2)) :else (fib-iter (+ (* b q) (* a q) (* a p)) (+ (* b p) (* a q)) p q (- count 1)))) (defn fib [n] (fib-iter 1 0 0 1 n)) 0 1 1 2 3 5 8 13
null
https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section1.2/1.19.clj
clojure
have discussion on it { b <- bp + aq Tpq^2 = { a <- bpq + aqq + bqq + aqq + apq + bqp + aqp + app = b(pq + qq + qp) + a(pq + qq + qp) + a(pp + qq) { b <- bpp + aqp + bqq + aqq + apq = b(pp + qq) + a(qp + qq + pq) Looking at the equations you can see that p' = pp + qq, q' = 2*pq + qq Put those into fib-iter and it works compute p' compute q'
Exercise 1.19 (ns exercise1.19 (:use clojure.test)) Was attempting to use clojure.test , was having issues though , leaving in to hopefully Compute p ' and q ' Tpq = { a < - bq + aq + ap If Tpq is applied twice that is the same as ' . Therefor to figure out p ' and q ' apply Tpq twice (defn fib-iter [a b p q count] (cond (= count 0) b (even? count) (fib-iter a b (/ count 2)) :else (fib-iter (+ (* b q) (* a q) (* a p)) (+ (* b p) (* a q)) p q (- count 1)))) (defn fib [n] (fib-iter 1 0 0 1 n)) 0 1 1 2 3 5 8 13
006968873791ae8e40c5c5e56ef06b500c8d65097f74d5d17a53bb61c8b557d0
lucywang000/shadow-test-utils
filters_test.cljc
(ns shadow-test-utils.filters-test (:require [shadow-test-utils.filters :refer [tweak-test-ns tweak-test-case]] [clojure.test :refer [deftest is are use-fixtures testing are]])) (defn v1 []) (defn v2 []) (defn ^:focus vf1 []) (defn ^:focus vf2 []) (defn ^:skip vs1 []) (defn ^:skip vs2 []) (deftest test-filter-test-case (are [args] (let [{:keys [before-vars after-vars]} args ns 'foo namespaces {ns {:vars before-vars}} after-tweak (tweak-test-case namespaces) vars (get-in after-tweak [ns :vars])] (is (= vars after-vars)) true) {:before-vars [#'v1 #'vf1 #'vf2 #'vs1 #'vs2] :after-vars [#'vf1 #'vf2]} {:before-vars [#'v1 #'vs1 #'vs2] :after-vars [#'v1]} {:before-vars [#'vs1] :after-vars nil} )) (deftest test-filter-test-ns (let [ns1 'ns1 ns2 'ns2 ns-f1 (vary-meta 'ns-f1 assoc :focus true) ns-f2 (vary-meta 'ns-f2 assoc :focus true) ns-s1 (vary-meta 'ns-s1 assoc :skip true) ns-s2 (vary-meta 'ns-s2 assoc :skip true)] (are [args] (let [{:keys [before-ns-keys after-ns-keys]} args namespaces (->> before-ns-keys (map (fn [x] [x {:vars [#'v1]}])) (into {})) after-tweak (tweak-test-ns namespaces)] (is (= (keys after-tweak) after-ns-keys)) true) {:before-ns-keys [ns1 ns-f1 ns-s1] :after-ns-keys [ns-f1]} {:before-ns-keys [ns1 ns-f1 ns-f2 ns-s1 ns-s2] :after-ns-keys [ns-f1 ns-f2]} {:before-ns-keys [ns1 ns-s1 ns-s2] :after-ns-keys [ns1]} {:before-ns-keys [ns1 ns2] :after-ns-keys [ns1 ns2]} {:before-ns-keys [ns-s1 ns-s2] :after-ns-keys nil} )))
null
https://raw.githubusercontent.com/lucywang000/shadow-test-utils/edd19c882b441e599c084feff1195bf8a40b7775/test/shadow_test_utils/filters_test.cljc
clojure
(ns shadow-test-utils.filters-test (:require [shadow-test-utils.filters :refer [tweak-test-ns tweak-test-case]] [clojure.test :refer [deftest is are use-fixtures testing are]])) (defn v1 []) (defn v2 []) (defn ^:focus vf1 []) (defn ^:focus vf2 []) (defn ^:skip vs1 []) (defn ^:skip vs2 []) (deftest test-filter-test-case (are [args] (let [{:keys [before-vars after-vars]} args ns 'foo namespaces {ns {:vars before-vars}} after-tweak (tweak-test-case namespaces) vars (get-in after-tweak [ns :vars])] (is (= vars after-vars)) true) {:before-vars [#'v1 #'vf1 #'vf2 #'vs1 #'vs2] :after-vars [#'vf1 #'vf2]} {:before-vars [#'v1 #'vs1 #'vs2] :after-vars [#'v1]} {:before-vars [#'vs1] :after-vars nil} )) (deftest test-filter-test-ns (let [ns1 'ns1 ns2 'ns2 ns-f1 (vary-meta 'ns-f1 assoc :focus true) ns-f2 (vary-meta 'ns-f2 assoc :focus true) ns-s1 (vary-meta 'ns-s1 assoc :skip true) ns-s2 (vary-meta 'ns-s2 assoc :skip true)] (are [args] (let [{:keys [before-ns-keys after-ns-keys]} args namespaces (->> before-ns-keys (map (fn [x] [x {:vars [#'v1]}])) (into {})) after-tweak (tweak-test-ns namespaces)] (is (= (keys after-tweak) after-ns-keys)) true) {:before-ns-keys [ns1 ns-f1 ns-s1] :after-ns-keys [ns-f1]} {:before-ns-keys [ns1 ns-f1 ns-f2 ns-s1 ns-s2] :after-ns-keys [ns-f1 ns-f2]} {:before-ns-keys [ns1 ns-s1 ns-s2] :after-ns-keys [ns1]} {:before-ns-keys [ns1 ns2] :after-ns-keys [ns1 ns2]} {:before-ns-keys [ns-s1 ns-s2] :after-ns-keys nil} )))
720f48f9c4cba4eb09f1bda32a75569e376abddf3e3452cf7d5d11349c3b8a42
qfpl/applied-fp-course
Topic.hs
module Level06.Types.Topic ( Topic , mkTopic , getTopic , encodeTopic ) where import Waargonaut.Encode (Encoder) import qualified Waargonaut.Encode as E import Level06.Types.Error (Error (EmptyTopic), nonEmptyText) import Data.Functor.Contravariant ((>$<)) import Data.Text (Text) newtype Topic = Topic Text deriving Show encodeTopic :: Applicative f => Encoder f Topic encodeTopic = getTopic >$< E.text mkTopic :: Text -> Either Error Topic mkTopic = nonEmptyText Topic EmptyTopic getTopic :: Topic -> Text getTopic (Topic t) = t
null
https://raw.githubusercontent.com/qfpl/applied-fp-course/d5a94a9dcee677bc95a5184c2ed13329c9f07559/src/Level06/Types/Topic.hs
haskell
module Level06.Types.Topic ( Topic , mkTopic , getTopic , encodeTopic ) where import Waargonaut.Encode (Encoder) import qualified Waargonaut.Encode as E import Level06.Types.Error (Error (EmptyTopic), nonEmptyText) import Data.Functor.Contravariant ((>$<)) import Data.Text (Text) newtype Topic = Topic Text deriving Show encodeTopic :: Applicative f => Encoder f Topic encodeTopic = getTopic >$< E.text mkTopic :: Text -> Either Error Topic mkTopic = nonEmptyText Topic EmptyTopic getTopic :: Topic -> Text getTopic (Topic t) = t
19064789b08021d68a53f019324e4217a27c9e40954b9569b4d909c3e5b00f73
lisp/de.setf.utility
date.lisp
;;; -*- Package: de.setf.utility.implementation; -*- This file is part of the ' de.setf.utility ' Common Lisp library . ;;; It implements universal time conversion functions. Copyright 2010 [ ) All Rights Reserved ;;; 'de.setf.utility' is free software: you can redistribute it and/or modify it under the terms of version 3 of the GNU Lesser General Public License as published by the Free Software Foundation . ;;; ;;; 'de.setf.utility' 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. ;;; A copy of the GNU Lesser General Public License should be included with ' de.setf.utility , as ` lgpl.txt ` . ;;; If not, see the GNU [site](/). ;;; contents : universal time conversion ;;; ;;; Implements universal-time data conversion according to java2se date and time patterns see ;;; ;;; date::define-date-conversion-function ;;; date:decode ;;; date:encode Copyright 2003 [ ) Copyright 2004 Ravenpack International ;;; 20040222.jaa decode-iso-time Copyright 2009 [ ) 20090304.jamderson repackaged 20091025.janderson added iso as shorthand op 20091220.janderson corrected treatment of single quote ; made ' Z ' decoding optional 20100210.janderson cleaned up ignored variables , types 20100919.janderson vary year as bce - year for xml - schema datatime additions to iso-8601 20110208.janderson invert offset sign to correctly reflect 20111005.janderson leave bce year offsets to eveutal duration calculations (in-package :de.setf.utility.implementation) #-( or sbcl allegro lispworks ccl abcl) (cerror "Continue anyway" "Conditionalization required for funcallable-standard-class") (defpackage :de.setf.date (:nicknames :date) (:use) (:documentation "This is the home package for data format patterns and for data conversion operators") (:export :day-and-month-to-day-in-year :day-in-month :day-in-month-name :day-in-quarter :day-in-week :day-in-week-name :day-in-year :day-in-year-to-day-and-month :day-name :decode :decode-am-pm :decode-day-name :decode-month-day-name :decode-month-name :decode-date-time :encode :encode-date-time :format-iso-time :format-excel-time :iso :leap-p :month-days :month-in-year :month-name :month-quarter :quarter-in-year :year :year-in-century :|yyyyMMdd| :|yyyyMMddTHH:mm:ss| :|ddMMyy| :|dddddddd MMM yyyy| :|yyyyMMddTHHmmss| :|yyMMdd.HHmm| :|EEE, dd.MM.yyyy| :|DDyy| :|ddMMyyyy| :|yyyyMMddTHHmmssZZ| :|yyyy-MM-ddTHH:mm:ss| :|ddMMyy.HHmm| :|yyyy-MM-ddTHH:mm:ssZZ| :|yyyy.MM.dd HH:mm:ss| )) (modPackage :de.setf.utility (:export :*current-year* :+ordinal-month-days+ :+ordinal-month-quarter+ :+seconds-in-week+ :+seconds-in-day+ :*day-names* :*month-names* :universal-time :decode-iso-time :iso-time :date-conversion-function) (:export-from :de.setf.date)) (eval-when (:compile-toplevel :load-toplevel :execute) (import 'de.setf.utility::format-iso-time :cl-user)) (deftype universal-time () 'integer) (defparameter *current-year* 0) (defvarconstant +ordinal-month-days+ #(0 31 28 31 30 31 30 31 31 30 31 30 31) "a constant array of the (1-based) days in each (1-based) month.") (defvarconstant +ordinal-month-quarter+ #(0 1 1 1 2 2 2 3 3 3 4 4 4) "a constant array of the respective quarter for each (1-based) month.") (defvar *day-names* #("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday") "a static array of the (0-based) day names. Monday is [0]") (defvar *day-names-from-one* #(nil "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday") "a static array of the (1-based) day names. Monday is [1]") (defvar *month-day-names* (let ((names (make-array 32 :initial-element nil))) (dotimes (i 31) (setf (aref names (1+ i)) (format nil "~:(~:R~)" (1+ i)))) names)) (defvar *month-names* #(nil "january" "february" "march" "april" "may" "june" "july" "august" "september" "october" "november" "december") "a static array of the (1-based) month names.") (defvarconstant +day-of-19000101+ 2 "1 january 1900 was a monday") (defvarconstant +seconds-in-day+ (* 60 60 24)) (defvarconstant +seconds-in-week+ (* 60 60 24 7)) (defparameter *date-package* (find-package :date)) (defun date:year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d m)) y)) (defun date:year-in-century (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d m)) (mod y 100))) (defun date:month-in-year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d y)) m)) (defun date:quarter-in-year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d y)) (svref +ordinal-month-quarter+ m))) (defun date:day-in-week-name (day &optional length &aux name) "returns the number name of a (0-based) day." (assert (<= 0 day 7)) (setf name (svref *day-names* day)) (if (and length (< length (length name))) (subseq name 0 length) name)) (defun date:day-in-month-name (day &optional length &aux name) "returns the number name of a (31-based) day." (assert (< 0 day 32)) (setf name (format nil "~:R" day)) (if (and length (< length (length name))) (subseq name 0 length) name)) (defun date:month-name (month &optional length &aux name) "returns the name of a (1-based) month." (assert (< 0 month 13)) (setf name (svref *month-names* month)) (if (and length (< length (length name))) (subseq name 0 length) name)) (defun date:leap-p (&optional (year (date:year))) (and (zerop (mod year 4)) (or (not (zerop (mod year 100))) (zerop (mod year 400))))) (defun date:month-days (month &optional (year nil)) "returns the number of days in a (1-based) month." (assert (< 0 month 13)) (+ (svref +ordinal-month-days+ month) (if (and year (date:leap-p year) (= month 2)) 1 0))) (defun date:month-quarter (month) "returns the respective (zero-based) quarter of a (1-based) month." (assert (< 0 month 13)) (svref +ordinal-month-quarter+ month)) (defun date:day-in-month (&optional (date (get-universal-time))) (multiple-value-bind (s min h d mon y) (decode-universal-time date) (declare (ignore s min h mon y)) d)) (defun date:day-in-year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h)) (+ d (reduce #'+ +ordinal-month-days+ :end m) (if (and (date:leap-p y) (> m 2)) 1 0)))) (defun date:day-in-quarter (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h)) (+ d (reduce #'+ +ordinal-month-days+ :start (svref #(0 1 1 1 4 4 4 7 7 7 10 10 10) m) :end m) (if (and (date:leap-p y) (= m 3)) 1 0)))) (defun date:day-in-week (&optional (date (get-universal-time))) (1+ (mod (1- (+ +day-of-19000101+ (floor date +seconds-in-day+))) 7))) (defun date:decode-month-name (month &key (start 0) (end (length month))) (flet ((test-name (name) (and (> (length month) 2) (string-equal name month :end1 (min (length name) end) :start2 start :end2 end)))) (declare (dynamic-extent #'test-name)) (position-if #'test-name *month-names* :start 1))) (defun date:decode-month-day-name (day &key (start 0) (end (length day))) (flet ((test-name (name) (string-equal name day :end1 (min (length name) end) :start2 start :end2 end))) (declare (dynamic-extent #'test-name)) (position-if #'test-name *month-day-names* :start 1))) (defun date:decode-day-name (day &key (start 0) (end (length day))) "returns the 0-based index of the given name in the week" (flet ((test-name (name) (and (> (length day) 2) (string-equal name day :end1 (min (length name) end) :start2 start :end2 end)))) (declare (dynamic-extent #'test-name)) (position-if #'test-name *day-names*))) (defun date:decode-am-pm (string &key (start 0)) (let ((end (+ start 2))) (and (<= end (length string)) (cond ((string-equal "am" string :start1 start :end1 end) :am) ((string-equal "pm" string :start1 start :end1 end) :pm))))) (defun date:day-in-year-to-day-and-month (day &optional (leap-p nil)) (let ((month 1) (month-days 0)) (when (numberp leap-p) (setf leap-p (date:leap-p leap-p))) (assert (<= 0 day (if leap-p 366 365))) (loop (setf month-days (aref +ordinal-month-days+ month)) (when (and leap-p (= month 2)) (incf month-days)) (when (or (>= month 12) (<= day month-days)) (return (values day month))) (decf day month-days) (incf month)))) (defun date:day-and-month-to-day-in-year (dim miy &optional (leap-p nil)) (assert (<= 1 miy 12)) (assert (<= 1 dim (aref +ordinal-month-days+ miy))) (when (numberp leap-p) (setf leap-p (date:leap-p leap-p))) (+ dim (reduce #'+ +ordinal-month-days+ :end miy) (if leap-p 1 0))) (eval-when (:execute :compile-toplevel :load-toplevel) (defun date-pattern-components (pattern-string) "Translate the pattern string into a list of component specifications. These serve in the respective encode/decode operator generation to indicate the proper element, variable, and parameters. Each component has one of the form: ((time-component variable) . encoded-length) string-literal character-literal " (let ((position 0) (length (length pattern-string)) (components nil) (letter #\null)) (flet ((not-supported-error (letter) (error "date aspect not supported: ~a: ~s" letter pattern-string))) (loop (when (>= position length) (return (reverse components))) (setf letter (char pattern-string position)) (case letter (#\' (let ((component-end (or (position letter pattern-string :start (1+ position)) (error "unbalanced quote: ~s" pattern-string)))) (if (= component-end (1+ position)) (push #\' components) (push (subseq pattern-string (1+ position) component-end) components)) (setf position (1+ component-end)))) ((#\+ #\-) (cond ((zerop position) (let ((component-end (or (position #\y pattern-string :start (1+ position) :test-not #'char=) (error "Invalid BCE indicator.")))) (assert (= (- component-end position) 5) () "Invalid BCE indicator.") (push '((.bce-year. year) . 4) components) (incf position 5))) (t (push letter components) (incf position 1)))) (t (let* ((component-end (or (position letter pattern-string :start position :test-not #'char=) length)) (component-length (- component-end position))) (push (case letter (#\g (not-supported-error letter)) (#\y (if (= component-length 2) `((.year-in-century. year) . ,component-length) `((.year. year) . ,component-length))) (#\M (if (> component-length 2) `((.month-name. month-in-year ,component-length) . ,component-length) `((.month-in-year. month-in-year) . ,component-length))) (#\w (not-supported-error letter)) (#\W (not-supported-error letter)) (#\D `((.day-in-year. day-in-month month-in-year) . ,component-length)) (#\d (if (> component-length 2) `((.day-in-month-name. day-in-month ,component-length) . ,component-length) `((.day-in-month. day-in-month) . ,component-length))) (#\E `((.day-in-week-name. day-in-week ,component-length) . ,component-length)) (#\F `((.day-in-week. day-in-week) . ,component-length)) (#\a `((.am-pm. hour-in-day) . ,component-length)) (#\H `((.hour-24-0-based. hour-in-day) . ,component-length)) (#\k `((.hour-24-1-based. hour-in-day) . ,component-length)) (#\K `((.hour-12-0-based. hour-in-day) . ,component-length)) (#\h `((.hour-12-1-based. hour-in-day) . ,component-length)) (#\m `((.minute-in-hour. minute-in-hour) . ,component-length)) (#\s `((.second-in-minute. second-in-minute) . ,component-length)) (#\S (not-supported-error letter)) ((#\z #\Z) `((.time-zone. time-zone) . ,(ecase component-length ((1 4 5) 4) ((2 3) 2)))) (t letter)) components) (incf position component-length)))))))) (defGeneric compute-date-encoder (pattern &key time-decoder) (:documentation "Generate a date encoding function given a PATTERN string or specification. PATTERN : (or STRING LIST) : the pattern Given a string, delegate the parsing to date-pattern-components and continue. Given a specification list, use the time components to construct a format string, and to generate conversions from the decoded time constituents.") (:method ((pattern string) &rest args) (apply #'compute-date-encoder (date-pattern-components pattern) args)) (:method ((components list) &key (time-decoder 'decode-universal-time) &aux (references nil) (format-string nil) (time-zone-p nil) (to-ignore '(second-in-minute minute-in-hour hour-in-day day-in-month month-in-year year day-in-week daylight-savings-time-p time-zone))) (setf format-string (with-output-to-string (stream) (dolist (component components) (etypecase component (cons (destructuring-bind (component-operation . length) component (destructuring-bind (time-component variable &optional arg) component-operation (case time-component (.bce-year. (push component-operation references) (format stream "~~{~~:[-~~;~~]~~~d,'0d~~}" length)) ((.year-in-century. .year. .week-in-year. .day-in-year. .day-in-week. .hour-24-0-based. .hour-24-1-based. .hour-12-0-based. .hour-12-1-based.) (push component-operation references) (format stream "~~~d,'0d" length)) ((.day-in-month-name. .day-in-week-name.) (push component-operation references) (format stream "~~~da" length)) (.month-name. (push component-operation references) (format stream "~~~da" length)) (.month-in-year. (push component-operation references) (if (> length 2) (format stream "~~~da" length) (format stream "~~~d,'0d" length))) (.am-pm. (push component-operation references) (format stream "~~~da" length)) (.time-zone. (push component-operation references) (write-string (ecase length (2 "~:[Z~;~:*~{~a~2,'0d~}~]") (4 "~:[Z~;~:*~{~a~2,'0d:00~}~]")) stream) (setf time-zone-p t)) (t (push variable references) (format stream "~~~d,'0d" length))) (setf to-ignore (remove variable to-ignore)) (when (symbolp arg) (setf to-ignore (remove arg to-ignore)))))) (string (write-string component stream)) (character (if (char= component #\~) (write-string "~~" stream) (write-char component stream))))))) `(lambda (time &optional stream) (macrolet ((.bce-year. (x) `(list (plusp ,x) (abs ,x))) (.year-in-century. (x) `(mod ,x 100)) (.year. (x) x) (.month-name. (x l) `(date:month-name ,x ,l)) (.month-in-year. (x) x) (.day-in-month-name. (x l) `(date:day-in-month-name ,x ,l)) (.day-in-month. (x) x) (.day-in-week-name. (x l) `(date:day-in-week-name ,x ,l)) (.day-in-week. (x) x) (.day-in-year. (dim miy) `(date:day-and-month-to-day-in-year ,dim ,miy year)) (.am-pm. (x) `(if (>= ,x 12) "pm" "am")) (.hour-24-0-based. (x) x) (.hour-24-1-based. (x) `(1+ ,x)) (.hour-12-0-based. (x) `(mod ,x 12)) (.hour-12-1-based. (x) `(1+ (mod ,x 12))) (.minute-in-hour. (x) x) (.second-in-minute. (x) x) (.time-zone. (x) `(unless (zerop ,x) (list (if (plusp ,x) "+" "-") (- ,x))))) (multiple-value-bind (second-in-minute minute-in-hour hour-in-day day-in-month month-in-year year day-in-week daylight-savings-time-p time-zone) (,time-decoder time ,@(when time-zone-p '(0))) ,@(when to-ignore `((declare (ignore ,@to-ignore)))) (format stream ,format-string ,@(reverse references))))))) (defgeneric compute-date-decoder (pattern &key time-encoder) (:documentation "Generate a date decoding function given a PATTERN string or specification. PATTERN : (or STRING LIST) : the pattern Given a string, delegate the parsing to date-pattern-components and continue. Given a specification list, use the time components to assemble the parsing steps, cache the intermediate values, and combine them as decoded time constituents.") (:method ((pattern string) &rest args) (apply #'compute-date-decoder (date-pattern-components pattern) args)) (:method ((components list) &key (time-encoder 'encode-universal-time) &aux (time-zone-p (find-if #'(lambda (component) (and (consp component) (consp (car component)) (or (eq (caar component) '.time-zone.)))) components)) (am-pm-p (find-if #'(lambda (c) (and (consp c) (consp (first c)) (eq (first (first c)) '.am-pm.))) components)) (day-in-year-p (find-if #'(lambda (c) (and (consp c) (consp (first c)) (eq (first (first c)) '.day-in-year.))) components))) `(lambda (string) must be runtime to allow for optional bce indicator (second-in-minute 0) (minute-in-hour 0) (hour-in-day 0) (day-in-month 1) ; initial values just in case the pattern (month-in-year 1) ; includes none. ? (sign 1) ,@(when day-in-year-p '((day-in-year 0))) (year 0) ,@(when am-pm-p '((am-pm :am))) ,@(when time-zone-p `((time-zone 0)))) ,@(mapcar #'(lambda (component) (etypecase component (cons (destructuring-bind ((time-component variable &optional arg) . length) component (declare (ignore arg)) (case time-component (.bce-year. `(let ((sign (if (member (char string position) '(#\+ #\-)) (char string (shiftf position (1+ position))) #\+)) (temp-year (parse-integer string :start position :end (incf position ,length)))) (setf year (ecase sign (#\+ temp-year) (#\- (- temp-year)))))) (.year-in-century. `(setf year (+ 1900 (parse-integer string :start position :end (incf position ,length))))) ((.day-in-week. .day-in-week-name.) ;; decode nothing, the text is for information only `(incf position ,length)) (.day-in-month-name. `(date:decode-month-day-name string :start position :end (incf position ,length))) (.week-in-year. `(setf month-in-year (week-in-year-to-month (parse-integer string :start position :end (incf position ,length))))) (.day-in-year. `(setf day-in-year (parse-integer string :start position :end (incf position ,length)))) ((.hour-24-0-based. .hour-12-0-based.) ; 12/24 distinction is handled below `(setf hour-in-day (parse-integer string :start position :end (incf position ,length)))) ((.hour-24-1-based. .hour-12-1-based.) `(setf hour-in-day (1- (parse-integer string :start position :end (incf position ,length))))) (.month-in-year. `(setf month-in-year (parse-integer string :start position :end (incf position ,length)))) (.month-name. `(date:decode-month-name string :start position :end (incf position ,length))) (.am-pm. `(setf am-pm (date:decode-am-pm string :start position :end (incf position ,length)))) (.time-zone. do n't always increment , alloe either ' Z ' or offset or both ( incf position ) `(let ((pm-position (or (position #\+ string :start position) (position #\- string :start position))) (z-position (when (find (char string position) "zZ") position)) (digit-position (position-if #'digit-char-p string :start position))) (setf time-zone (cond (pm-position (parse-integer string :start pm-position :end (+ pm-position 3))) ((and digit-position z-position) (parse-integer string :start digit-position :end (+ digit-position 2))) (z-position 0) (t (error "Invalid time zone specifier: ~s." string)))))) (t ; simple components `(setf ,variable (parse-integer string :start position :end (incf position ,length))))))) (string `(assert (eql (string-equal string ,component :start1 position :end1 (incf position ,(length component)))) () ,(format nil "Invalid time component. Expected ~s." component))) (character `(assert (eql (char string (shiftf position (1+ position))) ,component) () ,(format nil "Invalid time component. Expected '~c'." component))))) components) ,@(when am-pm-p `((case am-pm (:am) (:pm (incf hour-in-day 12))))) ,@(when day-in-year-p `((multiple-value-setq (day-in-month month-in-year) (date:day-in-year-to-day-and-month day-in-year year)))) (,time-encoder second-in-minute minute-in-hour hour-in-day day-in-month month-in-year (* sign year) ,@(when time-zone-p '((- time-zone)))))))) (defClass date-conversion-function (standard-generic-function) () (:metaclass #+:sbcl sb-mop:funcallable-standard-class #+:allegro mop:funcallable-standard-class #+lispworks hcl:funcallable-standard-class #+:ccl ccl:funcallable-standard-class #+abcl MOP:FUNCALLABLE-STANDARD-CLASS) (:documentation "A function class to distinguish conversion function for find-date-format.")) (defMacro date::define-date-conversion-function (pattern &key (type 'integer) (package :date) (time-encoder 'encode-universal-time) (time-decoder 'decode-universal-time)) (let ((name (intern pattern package))) `(progn ,@(when (eq package :date) `((eval-when (:execute :compile-toplevel :load-toplevel) (export ',name :date)))) (defGeneric ,name (datum &optional arg) (:generic-function-class date-conversion-function) (:method ((datum ,type) &optional arg) (,(compute-date-encoder pattern :time-decoder time-decoder) datum arg)) (:method ((datum string) &optional arg) (declare (ignore arg)) (,(compute-date-decoder pattern :time-encoder time-encoder) datum)))))) ) ; eval-when (date::define-date-conversion-function "DDyy") (date::define-date-conversion-function "ddMMyy") (date::define-date-conversion-function "ddMMyyyy") (date::define-date-conversion-function "yyyyMMdd") (date::define-date-conversion-function "yyMMdd.HHmm") (date::define-date-conversion-function "ddMMyy.HHmm") (date::define-date-conversion-function "yyyyMMddTHHmmss") (date::define-date-conversion-function "yyyyMMddTHHmmssZZ") (date::define-date-conversion-function "yyyyMMddTHH:mm:ss") (date::define-date-conversion-function "yyyy-MM-ddTHH:mm:ss") (date::define-date-conversion-function "yyyy-MM-ddTHH:mm:ssZZ") (date::define-date-conversion-function "EEE, dd.MM.yyyy") (date::define-date-conversion-function "dddddddd MMM yyyy") (date::define-date-conversion-function "yyyy.MM.dd HH:mm:ss") (defGeneric date::find-date-format (name &key if-does-not-exist) (:method ((name string) &key (if-does-not-exist :error)) (let ((symbol (find-symbol name *date-package*))) (if symbol (date::find-date-format symbol) (ecase if-does-not-exist (:error (error "date format not found: ~s." name)) (:create (eval `(date::define-date-conversion-function ,name))) ((nil) nil))))) (:method ((name symbol) &key (if-does-not-exist :error)) (let ((function nil)) (if (and (fboundp name) (typep (setf function (symbol-function name)) 'date-conversion-function)) function (ecase if-does-not-exist (:error (error "date format not found: ~s." name)) (:create (eval `(date::define-date-conversion-function ,name))) ((nil) nil)))))) (defGeneric date:encode (format &optional universal-time stream) (:method ((format (eql 'date:iso)) &optional (time (get-universal-time)) stream) (date:|yyyyMMddTHHmmss| time stream)) (:method ((format symbol) &optional (time (get-universal-time)) stream) (funcall (date::find-date-format format :if-does-not-exist :error) time stream)) (:method ((format string) &optional (time (get-universal-time)) stream) (funcall (date::find-date-format format :if-does-not-exist :error) time stream))) (defGeneric date:decode (format string) (:method ((format (eql 'date:iso)) (time string)) (date:|yyyyMMddTHHmmss| time)) (:method ((format symbol) (time string)) (funcall (date::find-date-format format :if-does-not-exist :error) time)) (:method ((format string) (time string)) (funcall (date::find-date-format format :if-does-not-exist :error) time))) one version only ;;(defun format-iso-time (&optional (time (get-universal-time)) stream) ;; (date:|yyyyMMddTHHmmssZZ| time stream)) (defgeneric date::format-iso-time (time stream &optional colon at var) (:method ((stream stream) (time integer) &optional colon at var) (declare (ignore colon at var)) (date:|yyyyMMddTHHmmssZZ| time stream))) (defgeneric date::format-excel-time (time stream &optional colon at var) (:method ((stream stream) (time integer) &optional colon at var) (declare (ignore colon at var)) (date::|yyyy.MM.dd HH:mm:ss| time stream))) ;;; (let ((time (get-universal-time))) (format nil ">>~/date:format-excel-time/<<" time)) ;;; (let ((time (get-universal-time))) (format nil ">>~/date:format-iso-time/<<" time)) (defun decode-iso-time (string) (if (> (length string ) 15) (date:|yyyyMMddTHHmmssZZ| string) (date:|yyyyMMddTHHmmss| string))) (defun iso-time (&optional (time (get-universal-time))) (etypecase time (integer (date:|yyyyMMddTHHmmss| time)) (string (ecase (length time) (15 (date:|yyyyMMddTHHmmss| time)) (19 (date:|yyyy-MM-ddTHH:mm:ss| time)) (21 (date:|yyyy-MM-ddTHH:mm:ssZZ| time)))))) ;(let ((time (get-universal-time))) (= (decode-iso-time (iso-time time)) time)) (setq *current-year* (date:year-in-century (get-universal-time))) (let ((*test-unit-situation* :define)) (test date-pattern-components/1 (date-pattern-components "yyyyMMddTHHmmssZZ") '(((.YEAR. YEAR) . 4) ((.MONTH-IN-YEAR. MONTH-IN-YEAR) . 2) ((.DAY-IN-MONTH. DAY-IN-MONTH) . 2) #\T ((.HOUR-24-0-BASED. HOUR-IN-DAY) . 2) ((.MINUTE-IN-HOUR. MINUTE-IN-HOUR) . 2) ((.SECOND-IN-MINUTE. SECOND-IN-MINUTE) . 2) ((.TIME-ZONE. TIME-ZONE) . 2))) (test date-pattern-components/2 (date-pattern-components "yyyyMMdd'T'HHmmssZZ") '(((.YEAR. YEAR) . 4) ((.MONTH-IN-YEAR. MONTH-IN-YEAR) . 2) ((.DAY-IN-MONTH. DAY-IN-MONTH) . 2) "T" ((.HOUR-24-0-BASED. HOUR-IN-DAY) . 2) ((.MINUTE-IN-HOUR. MINUTE-IN-HOUR) . 2) ((.SECOND-IN-MINUTE. SECOND-IN-MINUTE) . 2) ((.TIME-ZONE. TIME-ZONE) . 2))) (test date/1 (date:|ddMMyy| "010101") (encode-universal-time 0 0 0 01 01 1901)) (test date/2 (date:|ddMMyy| (encode-universal-time 0 0 0 01 01 1901)) "010101") (test date/3 (date:|yyyyMMdd| "19010101") (encode-universal-time 0 0 0 01 01 1901)) (test date/4 (date:|ddMMyy.HHmm| (encode-universal-time 01 02 03 04 05 1906)) "040506.0302") (test date/5 (date:|ddMMyy.HHmm| (encode-universal-time 01 02 03 04 05 1906) nil) "040506.0302") (test date/7en (date:|yyyyMMddTHHmmss| (encode-universal-time 01 02 03 04 05 1906)) "19060504T030201") (test date/7de (date:|yyyyMMddTHHmmss| "19060504T030201") (encode-universal-time 01 02 03 04 05 1906)) (test date/7err (type-of (nth-value 1 (ignore-errors (date:|yyyyMMddTHHmmss| "19060504X030201")))) 'simple-error) (test date/8 (date:|EEE, dd.MM.yyyy| (encode-universal-time 01 02 03 07 05 1955)) "Thu, 07.05.1955") (test date/9 (date:|dddddddd MMM yyyy| (encode-universal-time 01 02 03 08 08 1955)) "eighth aug 1955") ;; time zones (test date.zone (and (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z00")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z+00")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102+00")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z-05")) "20120101T050102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z+05")) "20111231T190102Z") (typep (nth-value 1 (ignore-errors (date:|yyyyMMddTHHmmssZZ| "20120101T00010200"))) 'error) (typep (nth-value 1 (ignore-errors (date:|yyyyMMddTHHmmssZZ| "20120101T001002/00"))) 'error) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20110101T010203-02") 0)) '(3 2 3 1 1 2011 5 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20110101T010203+00") 0)) '(3 2 1 1 1 2011 5 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20110101T010203+02") 0)) '(3 2 23 31 12 2010 4 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20111231T232425-02") 0)) '(25 24 1 1 1 2012 6 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20111231T232425+00") 0)) '(25 24 23 31 12 2011 5 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20111231T232425+02") 0)) '(25 24 21 31 12 2011 5 NIL 0)))) )
null
https://raw.githubusercontent.com/lisp/de.setf.utility/782cd79d99ebf40deeed60c492be9873bbe42a15/date.lisp
lisp
-*- Package: de.setf.utility.implementation; -*- It implements universal time conversion functions. 'de.setf.utility' is free software: you can redistribute it and/or modify 'de.setf.utility' 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. If not, see the GNU [site](/). contents : universal time conversion Implements universal-time data conversion according to java2se date and time patterns date::define-date-conversion-function date:decode date:encode 20040222.jaa decode-iso-time made ' Z ' decoding optional initial values just in case the pattern includes none. ? decode nothing, the text is for information only 12/24 distinction is handled below simple components eval-when (defun format-iso-time (&optional (time (get-universal-time)) stream) (date:|yyyyMMddTHHmmssZZ| time stream)) (let ((time (get-universal-time))) (format nil ">>~/date:format-excel-time/<<" time)) (let ((time (get-universal-time))) (format nil ">>~/date:format-iso-time/<<" time)) (let ((time (get-universal-time))) (= (decode-iso-time (iso-time time)) time)) time zones
This file is part of the ' de.setf.utility ' Common Lisp library . Copyright 2010 [ ) All Rights Reserved it under the terms of version 3 of the GNU Lesser General Public License as published by the Free Software Foundation . A copy of the GNU Lesser General Public License should be included with ' de.setf.utility , as ` lgpl.txt ` . see Copyright 2003 [ ) Copyright 2004 Ravenpack International Copyright 2009 [ ) 20090304.jamderson repackaged 20091025.janderson added iso as shorthand op 20100210.janderson cleaned up ignored variables , types 20100919.janderson vary year as bce - year for xml - schema datatime additions to iso-8601 20110208.janderson invert offset sign to correctly reflect 20111005.janderson leave bce year offsets to eveutal duration calculations (in-package :de.setf.utility.implementation) #-( or sbcl allegro lispworks ccl abcl) (cerror "Continue anyway" "Conditionalization required for funcallable-standard-class") (defpackage :de.setf.date (:nicknames :date) (:use) (:documentation "This is the home package for data format patterns and for data conversion operators") (:export :day-and-month-to-day-in-year :day-in-month :day-in-month-name :day-in-quarter :day-in-week :day-in-week-name :day-in-year :day-in-year-to-day-and-month :day-name :decode :decode-am-pm :decode-day-name :decode-month-day-name :decode-month-name :decode-date-time :encode :encode-date-time :format-iso-time :format-excel-time :iso :leap-p :month-days :month-in-year :month-name :month-quarter :quarter-in-year :year :year-in-century :|yyyyMMdd| :|yyyyMMddTHH:mm:ss| :|ddMMyy| :|dddddddd MMM yyyy| :|yyyyMMddTHHmmss| :|yyMMdd.HHmm| :|EEE, dd.MM.yyyy| :|DDyy| :|ddMMyyyy| :|yyyyMMddTHHmmssZZ| :|yyyy-MM-ddTHH:mm:ss| :|ddMMyy.HHmm| :|yyyy-MM-ddTHH:mm:ssZZ| :|yyyy.MM.dd HH:mm:ss| )) (modPackage :de.setf.utility (:export :*current-year* :+ordinal-month-days+ :+ordinal-month-quarter+ :+seconds-in-week+ :+seconds-in-day+ :*day-names* :*month-names* :universal-time :decode-iso-time :iso-time :date-conversion-function) (:export-from :de.setf.date)) (eval-when (:compile-toplevel :load-toplevel :execute) (import 'de.setf.utility::format-iso-time :cl-user)) (deftype universal-time () 'integer) (defparameter *current-year* 0) (defvarconstant +ordinal-month-days+ #(0 31 28 31 30 31 30 31 31 30 31 30 31) "a constant array of the (1-based) days in each (1-based) month.") (defvarconstant +ordinal-month-quarter+ #(0 1 1 1 2 2 2 3 3 3 4 4 4) "a constant array of the respective quarter for each (1-based) month.") (defvar *day-names* #("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday") "a static array of the (0-based) day names. Monday is [0]") (defvar *day-names-from-one* #(nil "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday") "a static array of the (1-based) day names. Monday is [1]") (defvar *month-day-names* (let ((names (make-array 32 :initial-element nil))) (dotimes (i 31) (setf (aref names (1+ i)) (format nil "~:(~:R~)" (1+ i)))) names)) (defvar *month-names* #(nil "january" "february" "march" "april" "may" "june" "july" "august" "september" "october" "november" "december") "a static array of the (1-based) month names.") (defvarconstant +day-of-19000101+ 2 "1 january 1900 was a monday") (defvarconstant +seconds-in-day+ (* 60 60 24)) (defvarconstant +seconds-in-week+ (* 60 60 24 7)) (defparameter *date-package* (find-package :date)) (defun date:year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d m)) y)) (defun date:year-in-century (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d m)) (mod y 100))) (defun date:month-in-year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d y)) m)) (defun date:quarter-in-year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h d y)) (svref +ordinal-month-quarter+ m))) (defun date:day-in-week-name (day &optional length &aux name) "returns the number name of a (0-based) day." (assert (<= 0 day 7)) (setf name (svref *day-names* day)) (if (and length (< length (length name))) (subseq name 0 length) name)) (defun date:day-in-month-name (day &optional length &aux name) "returns the number name of a (31-based) day." (assert (< 0 day 32)) (setf name (format nil "~:R" day)) (if (and length (< length (length name))) (subseq name 0 length) name)) (defun date:month-name (month &optional length &aux name) "returns the name of a (1-based) month." (assert (< 0 month 13)) (setf name (svref *month-names* month)) (if (and length (< length (length name))) (subseq name 0 length) name)) (defun date:leap-p (&optional (year (date:year))) (and (zerop (mod year 4)) (or (not (zerop (mod year 100))) (zerop (mod year 400))))) (defun date:month-days (month &optional (year nil)) "returns the number of days in a (1-based) month." (assert (< 0 month 13)) (+ (svref +ordinal-month-days+ month) (if (and year (date:leap-p year) (= month 2)) 1 0))) (defun date:month-quarter (month) "returns the respective (zero-based) quarter of a (1-based) month." (assert (< 0 month 13)) (svref +ordinal-month-quarter+ month)) (defun date:day-in-month (&optional (date (get-universal-time))) (multiple-value-bind (s min h d mon y) (decode-universal-time date) (declare (ignore s min h mon y)) d)) (defun date:day-in-year (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h)) (+ d (reduce #'+ +ordinal-month-days+ :end m) (if (and (date:leap-p y) (> m 2)) 1 0)))) (defun date:day-in-quarter (&optional (date (get-universal-time))) (multiple-value-bind (s min h d m y) (decode-universal-time date) (declare (ignore s min h)) (+ d (reduce #'+ +ordinal-month-days+ :start (svref #(0 1 1 1 4 4 4 7 7 7 10 10 10) m) :end m) (if (and (date:leap-p y) (= m 3)) 1 0)))) (defun date:day-in-week (&optional (date (get-universal-time))) (1+ (mod (1- (+ +day-of-19000101+ (floor date +seconds-in-day+))) 7))) (defun date:decode-month-name (month &key (start 0) (end (length month))) (flet ((test-name (name) (and (> (length month) 2) (string-equal name month :end1 (min (length name) end) :start2 start :end2 end)))) (declare (dynamic-extent #'test-name)) (position-if #'test-name *month-names* :start 1))) (defun date:decode-month-day-name (day &key (start 0) (end (length day))) (flet ((test-name (name) (string-equal name day :end1 (min (length name) end) :start2 start :end2 end))) (declare (dynamic-extent #'test-name)) (position-if #'test-name *month-day-names* :start 1))) (defun date:decode-day-name (day &key (start 0) (end (length day))) "returns the 0-based index of the given name in the week" (flet ((test-name (name) (and (> (length day) 2) (string-equal name day :end1 (min (length name) end) :start2 start :end2 end)))) (declare (dynamic-extent #'test-name)) (position-if #'test-name *day-names*))) (defun date:decode-am-pm (string &key (start 0)) (let ((end (+ start 2))) (and (<= end (length string)) (cond ((string-equal "am" string :start1 start :end1 end) :am) ((string-equal "pm" string :start1 start :end1 end) :pm))))) (defun date:day-in-year-to-day-and-month (day &optional (leap-p nil)) (let ((month 1) (month-days 0)) (when (numberp leap-p) (setf leap-p (date:leap-p leap-p))) (assert (<= 0 day (if leap-p 366 365))) (loop (setf month-days (aref +ordinal-month-days+ month)) (when (and leap-p (= month 2)) (incf month-days)) (when (or (>= month 12) (<= day month-days)) (return (values day month))) (decf day month-days) (incf month)))) (defun date:day-and-month-to-day-in-year (dim miy &optional (leap-p nil)) (assert (<= 1 miy 12)) (assert (<= 1 dim (aref +ordinal-month-days+ miy))) (when (numberp leap-p) (setf leap-p (date:leap-p leap-p))) (+ dim (reduce #'+ +ordinal-month-days+ :end miy) (if leap-p 1 0))) (eval-when (:execute :compile-toplevel :load-toplevel) (defun date-pattern-components (pattern-string) "Translate the pattern string into a list of component specifications. These serve in the respective encode/decode operator generation to indicate the proper element, variable, and parameters. Each component has one of the form: ((time-component variable) . encoded-length) string-literal character-literal " (let ((position 0) (length (length pattern-string)) (components nil) (letter #\null)) (flet ((not-supported-error (letter) (error "date aspect not supported: ~a: ~s" letter pattern-string))) (loop (when (>= position length) (return (reverse components))) (setf letter (char pattern-string position)) (case letter (#\' (let ((component-end (or (position letter pattern-string :start (1+ position)) (error "unbalanced quote: ~s" pattern-string)))) (if (= component-end (1+ position)) (push #\' components) (push (subseq pattern-string (1+ position) component-end) components)) (setf position (1+ component-end)))) ((#\+ #\-) (cond ((zerop position) (let ((component-end (or (position #\y pattern-string :start (1+ position) :test-not #'char=) (error "Invalid BCE indicator.")))) (assert (= (- component-end position) 5) () "Invalid BCE indicator.") (push '((.bce-year. year) . 4) components) (incf position 5))) (t (push letter components) (incf position 1)))) (t (let* ((component-end (or (position letter pattern-string :start position :test-not #'char=) length)) (component-length (- component-end position))) (push (case letter (#\g (not-supported-error letter)) (#\y (if (= component-length 2) `((.year-in-century. year) . ,component-length) `((.year. year) . ,component-length))) (#\M (if (> component-length 2) `((.month-name. month-in-year ,component-length) . ,component-length) `((.month-in-year. month-in-year) . ,component-length))) (#\w (not-supported-error letter)) (#\W (not-supported-error letter)) (#\D `((.day-in-year. day-in-month month-in-year) . ,component-length)) (#\d (if (> component-length 2) `((.day-in-month-name. day-in-month ,component-length) . ,component-length) `((.day-in-month. day-in-month) . ,component-length))) (#\E `((.day-in-week-name. day-in-week ,component-length) . ,component-length)) (#\F `((.day-in-week. day-in-week) . ,component-length)) (#\a `((.am-pm. hour-in-day) . ,component-length)) (#\H `((.hour-24-0-based. hour-in-day) . ,component-length)) (#\k `((.hour-24-1-based. hour-in-day) . ,component-length)) (#\K `((.hour-12-0-based. hour-in-day) . ,component-length)) (#\h `((.hour-12-1-based. hour-in-day) . ,component-length)) (#\m `((.minute-in-hour. minute-in-hour) . ,component-length)) (#\s `((.second-in-minute. second-in-minute) . ,component-length)) (#\S (not-supported-error letter)) ((#\z #\Z) `((.time-zone. time-zone) . ,(ecase component-length ((1 4 5) 4) ((2 3) 2)))) (t letter)) components) (incf position component-length)))))))) (defGeneric compute-date-encoder (pattern &key time-decoder) (:documentation "Generate a date encoding function given a PATTERN string or specification. PATTERN : (or STRING LIST) : the pattern Given a string, delegate the parsing to date-pattern-components and continue. Given a specification list, use the time components to construct a format string, and to generate conversions from the decoded time constituents.") (:method ((pattern string) &rest args) (apply #'compute-date-encoder (date-pattern-components pattern) args)) (:method ((components list) &key (time-decoder 'decode-universal-time) &aux (references nil) (format-string nil) (time-zone-p nil) (to-ignore '(second-in-minute minute-in-hour hour-in-day day-in-month month-in-year year day-in-week daylight-savings-time-p time-zone))) (setf format-string (with-output-to-string (stream) (dolist (component components) (etypecase component (cons (destructuring-bind (component-operation . length) component (destructuring-bind (time-component variable &optional arg) component-operation (case time-component (.bce-year. (push component-operation references) (format stream "~~{~~:[-~~;~~]~~~d,'0d~~}" length)) ((.year-in-century. .year. .week-in-year. .day-in-year. .day-in-week. .hour-24-0-based. .hour-24-1-based. .hour-12-0-based. .hour-12-1-based.) (push component-operation references) (format stream "~~~d,'0d" length)) ((.day-in-month-name. .day-in-week-name.) (push component-operation references) (format stream "~~~da" length)) (.month-name. (push component-operation references) (format stream "~~~da" length)) (.month-in-year. (push component-operation references) (if (> length 2) (format stream "~~~da" length) (format stream "~~~d,'0d" length))) (.am-pm. (push component-operation references) (format stream "~~~da" length)) (.time-zone. (push component-operation references) (write-string (ecase length (2 "~:[Z~;~:*~{~a~2,'0d~}~]") (4 "~:[Z~;~:*~{~a~2,'0d:00~}~]")) stream) (setf time-zone-p t)) (t (push variable references) (format stream "~~~d,'0d" length))) (setf to-ignore (remove variable to-ignore)) (when (symbolp arg) (setf to-ignore (remove arg to-ignore)))))) (string (write-string component stream)) (character (if (char= component #\~) (write-string "~~" stream) (write-char component stream))))))) `(lambda (time &optional stream) (macrolet ((.bce-year. (x) `(list (plusp ,x) (abs ,x))) (.year-in-century. (x) `(mod ,x 100)) (.year. (x) x) (.month-name. (x l) `(date:month-name ,x ,l)) (.month-in-year. (x) x) (.day-in-month-name. (x l) `(date:day-in-month-name ,x ,l)) (.day-in-month. (x) x) (.day-in-week-name. (x l) `(date:day-in-week-name ,x ,l)) (.day-in-week. (x) x) (.day-in-year. (dim miy) `(date:day-and-month-to-day-in-year ,dim ,miy year)) (.am-pm. (x) `(if (>= ,x 12) "pm" "am")) (.hour-24-0-based. (x) x) (.hour-24-1-based. (x) `(1+ ,x)) (.hour-12-0-based. (x) `(mod ,x 12)) (.hour-12-1-based. (x) `(1+ (mod ,x 12))) (.minute-in-hour. (x) x) (.second-in-minute. (x) x) (.time-zone. (x) `(unless (zerop ,x) (list (if (plusp ,x) "+" "-") (- ,x))))) (multiple-value-bind (second-in-minute minute-in-hour hour-in-day day-in-month month-in-year year day-in-week daylight-savings-time-p time-zone) (,time-decoder time ,@(when time-zone-p '(0))) ,@(when to-ignore `((declare (ignore ,@to-ignore)))) (format stream ,format-string ,@(reverse references))))))) (defgeneric compute-date-decoder (pattern &key time-encoder) (:documentation "Generate a date decoding function given a PATTERN string or specification. PATTERN : (or STRING LIST) : the pattern Given a string, delegate the parsing to date-pattern-components and continue. Given a specification list, use the time components to assemble the parsing steps, cache the intermediate values, and combine them as decoded time constituents.") (:method ((pattern string) &rest args) (apply #'compute-date-decoder (date-pattern-components pattern) args)) (:method ((components list) &key (time-encoder 'encode-universal-time) &aux (time-zone-p (find-if #'(lambda (component) (and (consp component) (consp (car component)) (or (eq (caar component) '.time-zone.)))) components)) (am-pm-p (find-if #'(lambda (c) (and (consp c) (consp (first c)) (eq (first (first c)) '.am-pm.))) components)) (day-in-year-p (find-if #'(lambda (c) (and (consp c) (consp (first c)) (eq (first (first c)) '.day-in-year.))) components))) `(lambda (string) must be runtime to allow for optional bce indicator (second-in-minute 0) (minute-in-hour 0) (hour-in-day 0) (sign 1) ,@(when day-in-year-p '((day-in-year 0))) (year 0) ,@(when am-pm-p '((am-pm :am))) ,@(when time-zone-p `((time-zone 0)))) ,@(mapcar #'(lambda (component) (etypecase component (cons (destructuring-bind ((time-component variable &optional arg) . length) component (declare (ignore arg)) (case time-component (.bce-year. `(let ((sign (if (member (char string position) '(#\+ #\-)) (char string (shiftf position (1+ position))) #\+)) (temp-year (parse-integer string :start position :end (incf position ,length)))) (setf year (ecase sign (#\+ temp-year) (#\- (- temp-year)))))) (.year-in-century. `(setf year (+ 1900 (parse-integer string :start position :end (incf position ,length))))) ((.day-in-week. .day-in-week-name.) `(incf position ,length)) (.day-in-month-name. `(date:decode-month-day-name string :start position :end (incf position ,length))) (.week-in-year. `(setf month-in-year (week-in-year-to-month (parse-integer string :start position :end (incf position ,length))))) (.day-in-year. `(setf day-in-year (parse-integer string :start position :end (incf position ,length)))) `(setf hour-in-day (parse-integer string :start position :end (incf position ,length)))) ((.hour-24-1-based. .hour-12-1-based.) `(setf hour-in-day (1- (parse-integer string :start position :end (incf position ,length))))) (.month-in-year. `(setf month-in-year (parse-integer string :start position :end (incf position ,length)))) (.month-name. `(date:decode-month-name string :start position :end (incf position ,length))) (.am-pm. `(setf am-pm (date:decode-am-pm string :start position :end (incf position ,length)))) (.time-zone. do n't always increment , alloe either ' Z ' or offset or both ( incf position ) `(let ((pm-position (or (position #\+ string :start position) (position #\- string :start position))) (z-position (when (find (char string position) "zZ") position)) (digit-position (position-if #'digit-char-p string :start position))) (setf time-zone (cond (pm-position (parse-integer string :start pm-position :end (+ pm-position 3))) ((and digit-position z-position) (parse-integer string :start digit-position :end (+ digit-position 2))) (z-position 0) (t (error "Invalid time zone specifier: ~s." string)))))) `(setf ,variable (parse-integer string :start position :end (incf position ,length))))))) (string `(assert (eql (string-equal string ,component :start1 position :end1 (incf position ,(length component)))) () ,(format nil "Invalid time component. Expected ~s." component))) (character `(assert (eql (char string (shiftf position (1+ position))) ,component) () ,(format nil "Invalid time component. Expected '~c'." component))))) components) ,@(when am-pm-p `((case am-pm (:am) (:pm (incf hour-in-day 12))))) ,@(when day-in-year-p `((multiple-value-setq (day-in-month month-in-year) (date:day-in-year-to-day-and-month day-in-year year)))) (,time-encoder second-in-minute minute-in-hour hour-in-day day-in-month month-in-year (* sign year) ,@(when time-zone-p '((- time-zone)))))))) (defClass date-conversion-function (standard-generic-function) () (:metaclass #+:sbcl sb-mop:funcallable-standard-class #+:allegro mop:funcallable-standard-class #+lispworks hcl:funcallable-standard-class #+:ccl ccl:funcallable-standard-class #+abcl MOP:FUNCALLABLE-STANDARD-CLASS) (:documentation "A function class to distinguish conversion function for find-date-format.")) (defMacro date::define-date-conversion-function (pattern &key (type 'integer) (package :date) (time-encoder 'encode-universal-time) (time-decoder 'decode-universal-time)) (let ((name (intern pattern package))) `(progn ,@(when (eq package :date) `((eval-when (:execute :compile-toplevel :load-toplevel) (export ',name :date)))) (defGeneric ,name (datum &optional arg) (:generic-function-class date-conversion-function) (:method ((datum ,type) &optional arg) (,(compute-date-encoder pattern :time-decoder time-decoder) datum arg)) (:method ((datum string) &optional arg) (declare (ignore arg)) (,(compute-date-decoder pattern :time-encoder time-encoder) datum)))))) (date::define-date-conversion-function "DDyy") (date::define-date-conversion-function "ddMMyy") (date::define-date-conversion-function "ddMMyyyy") (date::define-date-conversion-function "yyyyMMdd") (date::define-date-conversion-function "yyMMdd.HHmm") (date::define-date-conversion-function "ddMMyy.HHmm") (date::define-date-conversion-function "yyyyMMddTHHmmss") (date::define-date-conversion-function "yyyyMMddTHHmmssZZ") (date::define-date-conversion-function "yyyyMMddTHH:mm:ss") (date::define-date-conversion-function "yyyy-MM-ddTHH:mm:ss") (date::define-date-conversion-function "yyyy-MM-ddTHH:mm:ssZZ") (date::define-date-conversion-function "EEE, dd.MM.yyyy") (date::define-date-conversion-function "dddddddd MMM yyyy") (date::define-date-conversion-function "yyyy.MM.dd HH:mm:ss") (defGeneric date::find-date-format (name &key if-does-not-exist) (:method ((name string) &key (if-does-not-exist :error)) (let ((symbol (find-symbol name *date-package*))) (if symbol (date::find-date-format symbol) (ecase if-does-not-exist (:error (error "date format not found: ~s." name)) (:create (eval `(date::define-date-conversion-function ,name))) ((nil) nil))))) (:method ((name symbol) &key (if-does-not-exist :error)) (let ((function nil)) (if (and (fboundp name) (typep (setf function (symbol-function name)) 'date-conversion-function)) function (ecase if-does-not-exist (:error (error "date format not found: ~s." name)) (:create (eval `(date::define-date-conversion-function ,name))) ((nil) nil)))))) (defGeneric date:encode (format &optional universal-time stream) (:method ((format (eql 'date:iso)) &optional (time (get-universal-time)) stream) (date:|yyyyMMddTHHmmss| time stream)) (:method ((format symbol) &optional (time (get-universal-time)) stream) (funcall (date::find-date-format format :if-does-not-exist :error) time stream)) (:method ((format string) &optional (time (get-universal-time)) stream) (funcall (date::find-date-format format :if-does-not-exist :error) time stream))) (defGeneric date:decode (format string) (:method ((format (eql 'date:iso)) (time string)) (date:|yyyyMMddTHHmmss| time)) (:method ((format symbol) (time string)) (funcall (date::find-date-format format :if-does-not-exist :error) time)) (:method ((format string) (time string)) (funcall (date::find-date-format format :if-does-not-exist :error) time))) one version only (defgeneric date::format-iso-time (time stream &optional colon at var) (:method ((stream stream) (time integer) &optional colon at var) (declare (ignore colon at var)) (date:|yyyyMMddTHHmmssZZ| time stream))) (defgeneric date::format-excel-time (time stream &optional colon at var) (:method ((stream stream) (time integer) &optional colon at var) (declare (ignore colon at var)) (date::|yyyy.MM.dd HH:mm:ss| time stream))) (defun decode-iso-time (string) (if (> (length string ) 15) (date:|yyyyMMddTHHmmssZZ| string) (date:|yyyyMMddTHHmmss| string))) (defun iso-time (&optional (time (get-universal-time))) (etypecase time (integer (date:|yyyyMMddTHHmmss| time)) (string (ecase (length time) (15 (date:|yyyyMMddTHHmmss| time)) (19 (date:|yyyy-MM-ddTHH:mm:ss| time)) (21 (date:|yyyy-MM-ddTHH:mm:ssZZ| time)))))) (setq *current-year* (date:year-in-century (get-universal-time))) (let ((*test-unit-situation* :define)) (test date-pattern-components/1 (date-pattern-components "yyyyMMddTHHmmssZZ") '(((.YEAR. YEAR) . 4) ((.MONTH-IN-YEAR. MONTH-IN-YEAR) . 2) ((.DAY-IN-MONTH. DAY-IN-MONTH) . 2) #\T ((.HOUR-24-0-BASED. HOUR-IN-DAY) . 2) ((.MINUTE-IN-HOUR. MINUTE-IN-HOUR) . 2) ((.SECOND-IN-MINUTE. SECOND-IN-MINUTE) . 2) ((.TIME-ZONE. TIME-ZONE) . 2))) (test date-pattern-components/2 (date-pattern-components "yyyyMMdd'T'HHmmssZZ") '(((.YEAR. YEAR) . 4) ((.MONTH-IN-YEAR. MONTH-IN-YEAR) . 2) ((.DAY-IN-MONTH. DAY-IN-MONTH) . 2) "T" ((.HOUR-24-0-BASED. HOUR-IN-DAY) . 2) ((.MINUTE-IN-HOUR. MINUTE-IN-HOUR) . 2) ((.SECOND-IN-MINUTE. SECOND-IN-MINUTE) . 2) ((.TIME-ZONE. TIME-ZONE) . 2))) (test date/1 (date:|ddMMyy| "010101") (encode-universal-time 0 0 0 01 01 1901)) (test date/2 (date:|ddMMyy| (encode-universal-time 0 0 0 01 01 1901)) "010101") (test date/3 (date:|yyyyMMdd| "19010101") (encode-universal-time 0 0 0 01 01 1901)) (test date/4 (date:|ddMMyy.HHmm| (encode-universal-time 01 02 03 04 05 1906)) "040506.0302") (test date/5 (date:|ddMMyy.HHmm| (encode-universal-time 01 02 03 04 05 1906) nil) "040506.0302") (test date/7en (date:|yyyyMMddTHHmmss| (encode-universal-time 01 02 03 04 05 1906)) "19060504T030201") (test date/7de (date:|yyyyMMddTHHmmss| "19060504T030201") (encode-universal-time 01 02 03 04 05 1906)) (test date/7err (type-of (nth-value 1 (ignore-errors (date:|yyyyMMddTHHmmss| "19060504X030201")))) 'simple-error) (test date/8 (date:|EEE, dd.MM.yyyy| (encode-universal-time 01 02 03 07 05 1955)) "Thu, 07.05.1955") (test date/9 (date:|dddddddd MMM yyyy| (encode-universal-time 01 02 03 08 08 1955)) "eighth aug 1955") (test date.zone (and (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z00")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z+00")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102+00")) "20120101T000102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z-05")) "20120101T050102Z") (equal (date:|yyyyMMddTHHmmssZZ| (date:|yyyyMMddTHHmmssZZ| "20120101T000102Z+05")) "20111231T190102Z") (typep (nth-value 1 (ignore-errors (date:|yyyyMMddTHHmmssZZ| "20120101T00010200"))) 'error) (typep (nth-value 1 (ignore-errors (date:|yyyyMMddTHHmmssZZ| "20120101T001002/00"))) 'error) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20110101T010203-02") 0)) '(3 2 3 1 1 2011 5 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20110101T010203+00") 0)) '(3 2 1 1 1 2011 5 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20110101T010203+02") 0)) '(3 2 23 31 12 2010 4 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20111231T232425-02") 0)) '(25 24 1 1 1 2012 6 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20111231T232425+00") 0)) '(25 24 23 31 12 2011 5 NIL 0)) (equal (multiple-value-list (decode-universal-time (date:|yyyyMMddTHHmmssZZ| "20111231T232425+02") 0)) '(25 24 21 31 12 2011 5 NIL 0)))) )
fee4c758d9cfe11e3a75a2645b3a15ab08bd5d40e469eee825904e173ada562f
kelamg/HtDP2e-workthrough
ex499.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex499) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;; [List-of Numbers] -> Number ;; produces the product of all numbers in l (check-expect (product '()) 1) (check-expect (product '(1 5 2 10)) 100) (define (product l) (local (; [List-of Number] Number -> Number ; accumulator a is the product of all ; the numbers that l0 lacks from l (define (product/a l0 a) (cond [(empty? l0) a] [else (product/a (rest l0) (* (first l0) a))]))) (product/a l 1))) ;; Q - The performance of product is O(n) where n is the length of ;; the list. Does the accumulator version improve on this? ;; A - No. The accumulator traverses the entire list as well which means that ;; as n increases, so will the time to process the list with the accumulator ;; style product function.
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Accumulators/ex499.rkt
racket
about the language level of this file in a form that our tools can easily process. [List-of Numbers] -> Number produces the product of all numbers in l [List-of Number] Number -> Number accumulator a is the product of all the numbers that l0 lacks from l Q - The performance of product is O(n) where n is the length of the list. Does the accumulator version improve on this? A - No. The accumulator traverses the entire list as well which means that as n increases, so will the time to process the list with the accumulator style product function.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex499) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (check-expect (product '()) 1) (check-expect (product '(1 5 2 10)) 100) (define (product l) (define (product/a l0 a) (cond [(empty? l0) a] [else (product/a (rest l0) (* (first l0) a))]))) (product/a l 1)))
92b92d3236f232e3fdf519c15bca0d853d1ef3023637ff3a35bfb4414b8748d3
clash-lang/clash-compiler
Internal.hs
| Copyright : ( C ) 2019 , Google Inc. , 2021 - 2022 , QBayLogic B.V. , 2021 - 2022 , Myrtle.ai License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > Copyright : (C) 2019 , Google Inc., 2021-2022, QBayLogic B.V., 2021-2022, Myrtle.ai License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> -} # LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Clash.Class.AutoReg.Internal ( AutoReg (..) , deriveAutoReg , deriveAutoRegTuples ) where import Data.List (nub,zipWith4) import Data.Maybe (fromMaybe,isJust) import GHC.Stack (HasCallStack) import GHC.TypeNats (KnownNat,Nat,type (+)) import Clash.Explicit.Signal import Clash.Promoted.Nat import Clash.Magic import Clash.XException (NFDataX, deepErrorX) import Clash.Sized.BitVector import Clash.Sized.Fixed import Clash.Sized.Index import Clash.Sized.RTree import Clash.Sized.Signed import Clash.Sized.Unsigned import Clash.Sized.Vector (Vec, lazyV, smap) import Data.Int import Data.Word import Foreign.C.Types (CUShort) import Numeric.Half (Half) import Language.Haskell.TH.Datatype import Language.Haskell.TH.Syntax import Language.Haskell.TH.Lib import Language.Haskell.TH.Ppr import Control.Lens.Internal.TH (conAppsT) -- $setup -- >>> import Data.Maybe > > > import Clash . Prelude > > > : set -fplugin GHC.TypeLits . > > > : set -fplugin GHC.TypeLits . KnownNat . Solver | ' autoReg ' is a " smart " version of ' register ' . It does two things : -- 1 . It splits product types over their fields . For example , given a 3 - tuple , the corresponding HDL will end up with three instances of a register ( or more if the three fields can be split up similarly ) . -- -- 2. Given a data type where a constructor indicates (parts) of the data will ( not ) be updated a given cycle , it will split the data in two parts . The first part will contain the " always interesting " parts ( the constructor bits ) . The second holds the " potentially uninteresting " data ( the rest ) . -- Both parts will be stored in separate registers. The register holding the -- "potentially uninteresting" part will only be enabled if the constructor -- bits indicate they're interesting. -- The most important example of this is ' Maybe ' . Consider @Maybe ( Signed 16)@ ; -- when viewed as bits, a 'Nothing' would look like: -- > > > pack @(Maybe ( Signed 16 ) ) Nothing 0b0 _ .... _ .... _ .... _ .... -- -- and 'Just' -- > > > pack @(Maybe ( Signed 16 ) ) ( Just 3 ) -- 0b1_0000_0000_0000_0011 -- In the first case , Nothing , we do n't particularly care about updating the register holding the @Signed 16@ field , as they 'll be unknown anyway . We -- can therefore deassert its enable line. -- -- Making Clash lay it out like this increases the chances of synthesis tools -- clock gating the registers, saving energy. -- -- This version of 'autoReg' will split the given data type up recursively. For example , given @a : : Maybe ( Maybe Int , Maybe Int)@ , a total of five registers -- will be rendered. Both the "interesting" and "uninteresting" enable lines of -- the inner Maybe types will be controlled by the outer one, in addition to the inner parts controlling their " uninteresting " parts as described in ( 2 ) . -- -- The default implementation is just 'register'. If you don't need or want the special features of " AutoReg " , you can use that by writing an empty instance . -- -- > data MyDataType = ... > instance AutoReg MyDataType -- -- If you have a product type you can use 'deriveAutoReg' to derive an instance. -- class NFDataX a => AutoReg a where | For documentation see class ' AutoReg ' . -- -- This is the version with explicit clock\/reset\/enable inputs, " Clash . Prelude " exports an implicit version of this : ' Clash . Prelude.autoReg ' autoReg :: (HasCallStack, KnownDomain dom) => Clock dom -> Reset dom -> Enable dom -> a -- ^ Reset value -> Signal dom a -> Signal dom a autoReg = register # INLINE autoReg # instance AutoReg () instance AutoReg Bool instance AutoReg Double instance AutoReg Float instance AutoReg CUShort instance AutoReg Half instance AutoReg Char instance AutoReg Integer instance AutoReg Int instance AutoReg Int8 instance AutoReg Int16 instance AutoReg Int32 instance AutoReg Int64 instance AutoReg Word instance AutoReg Word8 instance AutoReg Word16 instance AutoReg Word32 instance AutoReg Word64 instance AutoReg Bit instance KnownNat n => AutoReg (BitVector n) instance AutoReg (Signed n) instance AutoReg (Unsigned n) instance AutoReg (Index n) instance NFDataX (rep (int + frac)) => AutoReg (Fixed rep int frac) instance AutoReg a => AutoReg (Maybe a) where autoReg clk rst en initVal input = createMaybe <$> tagR <*> valR where tag = isJust <$> input tagInit = isJust initVal tagR = register clk rst en tagInit tag val = fromMaybe (deepErrorX "autoReg'.val") <$> input valInit = fromMaybe (deepErrorX "autoReg'.valInit") initVal valR = autoReg clk rst (andEnable en tag) valInit val createMaybe t v = case t of True -> Just v False -> Nothing # INLINE autoReg # instance (KnownNat n, AutoReg a) => AutoReg (Vec n a) where autoReg :: forall dom. (HasCallStack, KnownDomain dom) => Clock dom -> Reset dom -> Enable dom -> Vec n a -- ^ Reset value -> Signal dom (Vec n a) -> Signal dom (Vec n a) autoReg clk rst en initVal xs = bundle $ smap go (lazyV initVal) <*> unbundle xs where go :: forall (i :: Nat). SNat i -> a -> Signal dom a -> Signal dom a go SNat = suffixNameFromNatP @i . autoReg clk rst en # INLINE autoReg # instance (KnownNat d, AutoReg a) => AutoReg (RTree d a) where autoReg clk rst en initVal xs = bundle $ (autoReg clk rst en) <$> lazyT initVal <*> unbundle xs # INLINE autoReg # | Decompose an applied type into its individual components . For example , this : -- -- @ Either -- @ -- -- would be unfolded to this: -- -- @ ( ' ConT ' ' ' Either , [ ' ConT ' ' ' Int , ' ConT ' ' ' ] ) -- @ -- -- This function ignores explicit parentheses and visible kind applications. -- -- NOTE: Copied from "Control.Lens.Internal.TH". TODO : Remove this function . Can be removed once we can upgrade to lens 4.18 . TODO : This is currently difficult due to issue with nix . unfoldType :: Type -> (Type, [Type]) unfoldType = go [] where go :: [Type] -> Type -> (Type, [Type]) go acc (ForallT _ _ ty) = go acc ty go acc (AppT ty1 ty2) = go (ty2:acc) ty1 go acc (SigT ty _) = go acc ty go acc (ParensT ty) = go acc ty #if MIN_VERSION_template_haskell(2,15,0) go acc (AppKindT ty _) = go acc ty #endif go acc ty = (ty, acc) | Automatically derives an ' AutoReg ' instance for a product type -- -- Usage: -- > data Pair a b = MkPair { getA : : a , : : b } deriving ( Generic , ) > data Tup3 a b c = : : Pair a b , : : c } deriving ( Generic , ) -- > deriveAutoReg ''Pair -- > deriveAutoReg ''Tup3 -- -- __NB__: Because of the way template haskell works the order here matters, if you try to @deriveAutoReg '' Tup3@ before it will complain -- about missing an @instance AutoReg (Pair a b)@. deriveAutoReg :: Name -> DecsQ deriveAutoReg tyNm = do tyInfo <- reifyDatatype tyNm case datatypeCons tyInfo of [] -> fail "Can't deriveAutoReg for empty types" [conInfo] -> deriveAutoRegProduct tyInfo conInfo _ -> fail "Can't deriveAutoReg for sum types" For a type like : data Product a b .. = { getA : : a , : : b , .. } This generates the following instance : instance ( AutoReg a , AutoReg b , .. ) = > AutoReg ( Product a b .. ) where autoReg clk rst en initVal input = MkProduct < $ > sig0 < * > sig1 ... where = ( \(MkProduct x _ ... ) - > x ) < $ > input ( \(MkProduct _ x ... ) - > x ) < $ > input ... initVal0 initVal1 ... = initVal sig0 = suffixNameP @"getA " autoReg clk rst en initVal0 field0 sig1 = suffixNameP @"getB " autoReg clk rst en initVal1 field1 ... For a type like: data Product a b .. = MkProduct { getA :: a, getB :: b, .. } This generates the following instance: instance (AutoReg a, AutoReg b, ..) => AutoReg (Product a b ..) where autoReg clk rst en initVal input = MkProduct <$> sig0 <*> sig1 ... where field0 = (\(MkProduct x _ ...) -> x) <$> input field1 = (\(MkProduct _ x ...) -> x) <$> input ... MkProduct initVal0 initVal1 ... = initVal sig0 = suffixNameP @"getA" autoReg clk rst en initVal0 field0 sig1 = suffixNameP @"getB" autoReg clk rst en initVal1 field1 ... -} deriveAutoRegProduct :: DatatypeInfo -> ConstructorInfo -> DecsQ deriveAutoRegProduct tyInfo conInfo = go (constructorName conInfo) fieldInfos where tyNm = datatypeName tyInfo #if MIN_VERSION_th_abstraction(0,3,0) tyArgs = datatypeInstTypes tyInfo #else tyArgs = datatypeVars tyInfo #endif ty = conAppsT tyNm tyArgs fieldInfos = zip fieldNames (constructorFields conInfo) where fieldNames = case constructorVariant conInfo of RecordConstructor nms -> map Just nms _ -> repeat Nothing go :: Name -> [(Maybe Name,Type)] -> Q [Dec] go dcNm fields = do clkN <- newName "clk" rstN <- newName "rst" enN <- newName "en" initValN <- newName "initVal" inputN <- newName "input" let initValE = varE initValN inputE = varE inputN argsP = map varP [clkN, rstN, enN, initValN, inputN] fieldNames = map fst fields field :: Name -> Int -> DecQ field nm nr = valD (varP nm) (normalB [| $fieldSel <$> $inputE |]) [] where fieldSel = do xNm <- newName "x" let fieldP = [ if nr == n then varP xNm else wildP | (n,_) <- zip [0..] fields] lamE [conP dcNm fieldP] (varE xNm) -- "\(Dc _ _ .. x _ ..) -> x" parts <- generateNames "field" fields fieldDecls <- sequence $ zipWith field parts [0..] sigs <- generateNames "sig" fields initVals <- generateNames "initVal" fields let initPat = conP dcNm (map varP initVals) initDecl <- valD initPat (normalB initValE) [] let clkE = varE clkN rstE = varE rstN enE = varE enN genAutoRegDecl :: PatQ -> ExpQ -> ExpQ -> Maybe Name -> DecsQ genAutoRegDecl s v i nameM = [d| $s = $nameMe autoReg $clkE $rstE $enE $i $v |] where nameMe = case nameM of Nothing -> [| id |] Just nm -> let nmSym = litT $ strTyLit (nameBase nm) in [| suffixNameP @($nmSym) |] partDecls <- concat <$> (sequence $ zipWith4 genAutoRegDecl (varP <$> sigs) (varE <$> parts) (varE <$> initVals) (fieldNames) ) let decls :: [DecQ] decls = map pure (initDecl : fieldDecls ++ partDecls) tyConE = conE dcNm body = case map varE sigs of (sig0:rest) -> foldl (\acc sigN -> [| $acc <*> $sigN |]) [| $tyConE <$> $sig0 |] rest [] -> [| $tyConE |] autoRegDec <- funD 'autoReg [clause argsP (normalB body) decls] ctx <- calculateRequiredContext conInfo return [InstanceD Nothing ctx (AppT (ConT ''AutoReg) ty) [ autoRegDec , PragmaD (InlineP 'autoReg Inline FunLike AllPhases) ]] -- Calculate the required constraint to call autoReg on all the fields of a -- given constructor calculateRequiredContext :: ConstructorInfo -> Q Cxt calculateRequiredContext conInfo = do let fieldTys = constructorFields conInfo wantedInstances <- mapM (\ty -> constraintsWantedFor ''AutoReg [ty]) (nub fieldTys) return $ nub (concat wantedInstances) constraintsWantedFor :: Name -> [Type] -> Q Cxt constraintsWantedFor clsNm tys | show clsNm == "GHC.TypeNats.KnownNat" = do KnownNat is special , you ca n't just lookup instances with reifyInstances . So we just pass KnownNat constraints . This will most likely require UndecidableInstances . return [conAppsT clsNm tys] constraintsWantedFor clsNm [ty] = case ty of VarT _ -> return [AppT (ConT clsNm) ty] ConT _ -> return [] _ -> do insts <- reifyInstances clsNm [ty] case insts of [InstanceD _ cxtInst (AppT autoRegCls instTy) _] | autoRegCls == ConT clsNm -> do let substs = findTyVarSubsts instTy ty cxt2 = map (applyTyVarSubsts substs) cxtInst okCxt = filter isOk cxt2 recurseCxt = filter needRecurse cxt2 recursed <- mapM recurse recurseCxt return (okCxt ++ concat recursed) [] -> fail $ "Missing instance " ++ show clsNm ++ " (" ++ pprint ty ++ ")" (_:_:_) -> fail $ "There are multiple " ++ show clsNm ++ " instances for " ++ pprint ty ++ ":\n" ++ pprint insts _ -> fail $ "Got unexpected instance: " ++ pprint insts where isOk :: Type -> Bool isOk (unfoldType -> (_cls,tys)) = case tys of [VarT _] -> True [_] -> False _ -> True -- see [NOTE: MultiParamTypeClasses] needRecurse :: Type -> Bool needRecurse (unfoldType -> (cls,tys)) = case tys of [AppT _ _] -> True [VarT _] -> False -- gets copied by "filter isOk" above [ConT _] -> False -- we can just drop constraints like: "AutoReg Bool => ..." or " KnownNat 4 = > " [TupleT 0] -> False -- handle Unit () [_] -> error ( "Error while deriveAutoReg: don't know how to handle: " ++ pprint cls ++ " (" ++ pprint tys ++ ")" ) _ -> False -- see [NOTE: MultiParamTypeClasses] recurse :: Type -> Q Cxt recurse (unfoldType -> (ConT cls,tys)) = constraintsWantedFor cls tys recurse t = fail ("Expected a class applied to some arguments but got " ++ pprint t) constraintsWantedFor clsNm tys = return [conAppsT clsNm tys] -- see [NOTE: MultiParamTypeClasses] -- [NOTE: MultiParamTypeClasses] -- The constraint calculation code doesn't handle MultiParamTypeClasses -- "properly", but it will try to pass them on, so the resulting instance should still compile with UndecidableInstances enabled . | Find tyVar substitutions between a general type and a second possibly less -- general type. For example: -- -- @ -- findTyVarSubsts "Either a b" "Either c [Bool]" -- == "[(a,c), (b,[Bool])]" -- @ findTyVarSubsts :: Type -> Type -> [(Name,Type)] findTyVarSubsts = go where go ty1 ty2 = case (ty1,ty2) of (VarT nm1 , VarT nm2) | nm1 == nm2 -> [] (VarT nm , t) -> [(nm,t)] (ConT _ , ConT _) -> [] (AppT x1 y1 , AppT x2 y2) -> go x1 x2 ++ go y1 y2 (SigT t1 k1 , SigT t2 k2) -> go t1 t2 ++ go k1 k2 (InfixT x1 _ y1 , InfixT x2 _ y2) -> go x1 x2 ++ go y1 y2 (UInfixT x1 _ y1, UInfixT x2 _ y2) -> go x1 x2 ++ go y1 y2 (ParensT x1 , ParensT x2) -> go x1 x2 #if __GLASGOW_HASKELL__ >= 808 (AppKindT t1 k1 , AppKindT t2 k2) -> go t1 t2 ++ go k1 k2 (ImplicitParamT _ x1, ImplicitParamT _ x2) -> go x1 x2 #endif (PromotedT _ , PromotedT _ ) -> [] (TupleT _ , TupleT _ ) -> [] (UnboxedTupleT _ , UnboxedTupleT _ ) -> [] (UnboxedSumT _ , UnboxedSumT _ ) -> [] (ArrowT , ArrowT ) -> [] (EqualityT , EqualityT ) -> [] (ListT , ListT ) -> [] (PromotedTupleT _ , PromotedTupleT _ ) -> [] (PromotedNilT , PromotedNilT ) -> [] (PromotedConsT , PromotedConsT ) -> [] (StarT , StarT ) -> [] (ConstraintT , ConstraintT ) -> [] (LitT _ , LitT _ ) -> [] (WildCardT , WildCardT ) -> [] _ -> error $ unlines [ "findTyVarSubsts: Unexpected types" , "ty1:", pprint ty1,"ty2:", pprint ty2] applyTyVarSubsts :: [(Name,Type)] -> Type -> Type applyTyVarSubsts substs ty = go ty where go ty' = case ty' of VarT n -> case lookup n substs of Nothing -> ty' Just m -> m ConT _ -> ty' AppT ty1 ty2 -> AppT (go ty1) (go ty2) LitT _ -> ty' _ -> error $ "TODO applyTyVarSubsts: " ++ show ty' -- | Generate a list of fresh Name's: prefix0 _ .. , _ .. , prefix2 _ .. , .. generateNames :: String -> [a] -> Q [Name] generateNames prefix xs = sequence (zipWith (\n _ -> newName $ prefix ++ show @Int n) [0..] xs) deriveAutoRegTuples :: [Int] -> DecsQ deriveAutoRegTuples xs = concat <$> mapM deriveAutoRegTuple xs deriveAutoRegTuple :: Int -> DecsQ deriveAutoRegTuple n | n < 2 = fail $ "deriveAutoRegTuple doesn't work for " ++ show n ++ "-tuples" | otherwise = deriveAutoReg tupN where tupN = mkName $ "(" ++ replicate (n-1) ',' ++ ")"
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/ba4765139ea0728546bf934005d2d9b77e48d8c7/clash-prelude/src/Clash/Class/AutoReg/Internal.hs
haskell
$setup >>> import Data.Maybe 2. Given a data type where a constructor indicates (parts) of the data will Both parts will be stored in separate registers. The register holding the "potentially uninteresting" part will only be enabled if the constructor bits indicate they're interesting. when viewed as bits, a 'Nothing' would look like: and 'Just' 0b1_0000_0000_0000_0011 can therefore deassert its enable line. Making Clash lay it out like this increases the chances of synthesis tools clock gating the registers, saving energy. This version of 'autoReg' will split the given data type up recursively. For will be rendered. Both the "interesting" and "uninteresting" enable lines of the inner Maybe types will be controlled by the outer one, in addition to The default implementation is just 'register'. If you don't need or want > data MyDataType = ... If you have a product type you can use 'deriveAutoReg' to derive an instance. This is the version with explicit clock\/reset\/enable inputs, ^ Reset value ^ Reset value @ @ would be unfolded to this: @ @ This function ignores explicit parentheses and visible kind applications. NOTE: Copied from "Control.Lens.Internal.TH". Usage: > deriveAutoReg ''Pair > deriveAutoReg ''Tup3 __NB__: Because of the way template haskell works the order here matters, about missing an @instance AutoReg (Pair a b)@. "\(Dc _ _ .. x _ ..) -> x" Calculate the required constraint to call autoReg on all the fields of a given constructor see [NOTE: MultiParamTypeClasses] gets copied by "filter isOk" above we can just drop constraints like: "AutoReg Bool => ..." handle Unit () see [NOTE: MultiParamTypeClasses] see [NOTE: MultiParamTypeClasses] [NOTE: MultiParamTypeClasses] The constraint calculation code doesn't handle MultiParamTypeClasses "properly", but it will try to pass them on, so the resulting instance should general type. For example: @ findTyVarSubsts "Either a b" "Either c [Bool]" == "[(a,c), (b,[Bool])]" @ | Generate a list of fresh Name's:
| Copyright : ( C ) 2019 , Google Inc. , 2021 - 2022 , QBayLogic B.V. , 2021 - 2022 , Myrtle.ai License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > Copyright : (C) 2019 , Google Inc., 2021-2022, QBayLogic B.V., 2021-2022, Myrtle.ai License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> -} # LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Clash.Class.AutoReg.Internal ( AutoReg (..) , deriveAutoReg , deriveAutoRegTuples ) where import Data.List (nub,zipWith4) import Data.Maybe (fromMaybe,isJust) import GHC.Stack (HasCallStack) import GHC.TypeNats (KnownNat,Nat,type (+)) import Clash.Explicit.Signal import Clash.Promoted.Nat import Clash.Magic import Clash.XException (NFDataX, deepErrorX) import Clash.Sized.BitVector import Clash.Sized.Fixed import Clash.Sized.Index import Clash.Sized.RTree import Clash.Sized.Signed import Clash.Sized.Unsigned import Clash.Sized.Vector (Vec, lazyV, smap) import Data.Int import Data.Word import Foreign.C.Types (CUShort) import Numeric.Half (Half) import Language.Haskell.TH.Datatype import Language.Haskell.TH.Syntax import Language.Haskell.TH.Lib import Language.Haskell.TH.Ppr import Control.Lens.Internal.TH (conAppsT) > > > import Clash . Prelude > > > : set -fplugin GHC.TypeLits . > > > : set -fplugin GHC.TypeLits . KnownNat . Solver | ' autoReg ' is a " smart " version of ' register ' . It does two things : 1 . It splits product types over their fields . For example , given a 3 - tuple , the corresponding HDL will end up with three instances of a register ( or more if the three fields can be split up similarly ) . ( not ) be updated a given cycle , it will split the data in two parts . The first part will contain the " always interesting " parts ( the constructor bits ) . The second holds the " potentially uninteresting " data ( the rest ) . The most important example of this is ' Maybe ' . Consider @Maybe ( Signed 16)@ ; > > > pack @(Maybe ( Signed 16 ) ) Nothing 0b0 _ .... _ .... _ .... _ .... > > > pack @(Maybe ( Signed 16 ) ) ( Just 3 ) In the first case , Nothing , we do n't particularly care about updating the register holding the @Signed 16@ field , as they 'll be unknown anyway . We example , given @a : : Maybe ( Maybe Int , Maybe Int)@ , a total of five registers the inner parts controlling their " uninteresting " parts as described in ( 2 ) . the special features of " AutoReg " , you can use that by writing an empty instance . > instance AutoReg MyDataType class NFDataX a => AutoReg a where | For documentation see class ' AutoReg ' . " Clash . Prelude " exports an implicit version of this : ' Clash . Prelude.autoReg ' autoReg :: (HasCallStack, KnownDomain dom) => Clock dom -> Reset dom -> Enable dom -> Signal dom a -> Signal dom a autoReg = register # INLINE autoReg # instance AutoReg () instance AutoReg Bool instance AutoReg Double instance AutoReg Float instance AutoReg CUShort instance AutoReg Half instance AutoReg Char instance AutoReg Integer instance AutoReg Int instance AutoReg Int8 instance AutoReg Int16 instance AutoReg Int32 instance AutoReg Int64 instance AutoReg Word instance AutoReg Word8 instance AutoReg Word16 instance AutoReg Word32 instance AutoReg Word64 instance AutoReg Bit instance KnownNat n => AutoReg (BitVector n) instance AutoReg (Signed n) instance AutoReg (Unsigned n) instance AutoReg (Index n) instance NFDataX (rep (int + frac)) => AutoReg (Fixed rep int frac) instance AutoReg a => AutoReg (Maybe a) where autoReg clk rst en initVal input = createMaybe <$> tagR <*> valR where tag = isJust <$> input tagInit = isJust initVal tagR = register clk rst en tagInit tag val = fromMaybe (deepErrorX "autoReg'.val") <$> input valInit = fromMaybe (deepErrorX "autoReg'.valInit") initVal valR = autoReg clk rst (andEnable en tag) valInit val createMaybe t v = case t of True -> Just v False -> Nothing # INLINE autoReg # instance (KnownNat n, AutoReg a) => AutoReg (Vec n a) where autoReg :: forall dom. (HasCallStack, KnownDomain dom) => Clock dom -> Reset dom -> Enable dom -> Signal dom (Vec n a) -> Signal dom (Vec n a) autoReg clk rst en initVal xs = bundle $ smap go (lazyV initVal) <*> unbundle xs where go :: forall (i :: Nat). SNat i -> a -> Signal dom a -> Signal dom a go SNat = suffixNameFromNatP @i . autoReg clk rst en # INLINE autoReg # instance (KnownNat d, AutoReg a) => AutoReg (RTree d a) where autoReg clk rst en initVal xs = bundle $ (autoReg clk rst en) <$> lazyT initVal <*> unbundle xs # INLINE autoReg # | Decompose an applied type into its individual components . For example , this : Either ( ' ConT ' ' ' Either , [ ' ConT ' ' ' Int , ' ConT ' ' ' ] ) TODO : Remove this function . Can be removed once we can upgrade to lens 4.18 . TODO : This is currently difficult due to issue with nix . unfoldType :: Type -> (Type, [Type]) unfoldType = go [] where go :: [Type] -> Type -> (Type, [Type]) go acc (ForallT _ _ ty) = go acc ty go acc (AppT ty1 ty2) = go (ty2:acc) ty1 go acc (SigT ty _) = go acc ty go acc (ParensT ty) = go acc ty #if MIN_VERSION_template_haskell(2,15,0) go acc (AppKindT ty _) = go acc ty #endif go acc ty = (ty, acc) | Automatically derives an ' AutoReg ' instance for a product type > data Pair a b = MkPair { getA : : a , : : b } deriving ( Generic , ) > data Tup3 a b c = : : Pair a b , : : c } deriving ( Generic , ) if you try to @deriveAutoReg '' Tup3@ before it will complain deriveAutoReg :: Name -> DecsQ deriveAutoReg tyNm = do tyInfo <- reifyDatatype tyNm case datatypeCons tyInfo of [] -> fail "Can't deriveAutoReg for empty types" [conInfo] -> deriveAutoRegProduct tyInfo conInfo _ -> fail "Can't deriveAutoReg for sum types" For a type like : data Product a b .. = { getA : : a , : : b , .. } This generates the following instance : instance ( AutoReg a , AutoReg b , .. ) = > AutoReg ( Product a b .. ) where autoReg clk rst en initVal input = MkProduct < $ > sig0 < * > sig1 ... where = ( \(MkProduct x _ ... ) - > x ) < $ > input ( \(MkProduct _ x ... ) - > x ) < $ > input ... initVal0 initVal1 ... = initVal sig0 = suffixNameP @"getA " autoReg clk rst en initVal0 field0 sig1 = suffixNameP @"getB " autoReg clk rst en initVal1 field1 ... For a type like: data Product a b .. = MkProduct { getA :: a, getB :: b, .. } This generates the following instance: instance (AutoReg a, AutoReg b, ..) => AutoReg (Product a b ..) where autoReg clk rst en initVal input = MkProduct <$> sig0 <*> sig1 ... where field0 = (\(MkProduct x _ ...) -> x) <$> input field1 = (\(MkProduct _ x ...) -> x) <$> input ... MkProduct initVal0 initVal1 ... = initVal sig0 = suffixNameP @"getA" autoReg clk rst en initVal0 field0 sig1 = suffixNameP @"getB" autoReg clk rst en initVal1 field1 ... -} deriveAutoRegProduct :: DatatypeInfo -> ConstructorInfo -> DecsQ deriveAutoRegProduct tyInfo conInfo = go (constructorName conInfo) fieldInfos where tyNm = datatypeName tyInfo #if MIN_VERSION_th_abstraction(0,3,0) tyArgs = datatypeInstTypes tyInfo #else tyArgs = datatypeVars tyInfo #endif ty = conAppsT tyNm tyArgs fieldInfos = zip fieldNames (constructorFields conInfo) where fieldNames = case constructorVariant conInfo of RecordConstructor nms -> map Just nms _ -> repeat Nothing go :: Name -> [(Maybe Name,Type)] -> Q [Dec] go dcNm fields = do clkN <- newName "clk" rstN <- newName "rst" enN <- newName "en" initValN <- newName "initVal" inputN <- newName "input" let initValE = varE initValN inputE = varE inputN argsP = map varP [clkN, rstN, enN, initValN, inputN] fieldNames = map fst fields field :: Name -> Int -> DecQ field nm nr = valD (varP nm) (normalB [| $fieldSel <$> $inputE |]) [] where fieldSel = do xNm <- newName "x" let fieldP = [ if nr == n then varP xNm else wildP | (n,_) <- zip [0..] fields] parts <- generateNames "field" fields fieldDecls <- sequence $ zipWith field parts [0..] sigs <- generateNames "sig" fields initVals <- generateNames "initVal" fields let initPat = conP dcNm (map varP initVals) initDecl <- valD initPat (normalB initValE) [] let clkE = varE clkN rstE = varE rstN enE = varE enN genAutoRegDecl :: PatQ -> ExpQ -> ExpQ -> Maybe Name -> DecsQ genAutoRegDecl s v i nameM = [d| $s = $nameMe autoReg $clkE $rstE $enE $i $v |] where nameMe = case nameM of Nothing -> [| id |] Just nm -> let nmSym = litT $ strTyLit (nameBase nm) in [| suffixNameP @($nmSym) |] partDecls <- concat <$> (sequence $ zipWith4 genAutoRegDecl (varP <$> sigs) (varE <$> parts) (varE <$> initVals) (fieldNames) ) let decls :: [DecQ] decls = map pure (initDecl : fieldDecls ++ partDecls) tyConE = conE dcNm body = case map varE sigs of (sig0:rest) -> foldl (\acc sigN -> [| $acc <*> $sigN |]) [| $tyConE <$> $sig0 |] rest [] -> [| $tyConE |] autoRegDec <- funD 'autoReg [clause argsP (normalB body) decls] ctx <- calculateRequiredContext conInfo return [InstanceD Nothing ctx (AppT (ConT ''AutoReg) ty) [ autoRegDec , PragmaD (InlineP 'autoReg Inline FunLike AllPhases) ]] calculateRequiredContext :: ConstructorInfo -> Q Cxt calculateRequiredContext conInfo = do let fieldTys = constructorFields conInfo wantedInstances <- mapM (\ty -> constraintsWantedFor ''AutoReg [ty]) (nub fieldTys) return $ nub (concat wantedInstances) constraintsWantedFor :: Name -> [Type] -> Q Cxt constraintsWantedFor clsNm tys | show clsNm == "GHC.TypeNats.KnownNat" = do KnownNat is special , you ca n't just lookup instances with reifyInstances . So we just pass KnownNat constraints . This will most likely require UndecidableInstances . return [conAppsT clsNm tys] constraintsWantedFor clsNm [ty] = case ty of VarT _ -> return [AppT (ConT clsNm) ty] ConT _ -> return [] _ -> do insts <- reifyInstances clsNm [ty] case insts of [InstanceD _ cxtInst (AppT autoRegCls instTy) _] | autoRegCls == ConT clsNm -> do let substs = findTyVarSubsts instTy ty cxt2 = map (applyTyVarSubsts substs) cxtInst okCxt = filter isOk cxt2 recurseCxt = filter needRecurse cxt2 recursed <- mapM recurse recurseCxt return (okCxt ++ concat recursed) [] -> fail $ "Missing instance " ++ show clsNm ++ " (" ++ pprint ty ++ ")" (_:_:_) -> fail $ "There are multiple " ++ show clsNm ++ " instances for " ++ pprint ty ++ ":\n" ++ pprint insts _ -> fail $ "Got unexpected instance: " ++ pprint insts where isOk :: Type -> Bool isOk (unfoldType -> (_cls,tys)) = case tys of [VarT _] -> True [_] -> False needRecurse :: Type -> Bool needRecurse (unfoldType -> (cls,tys)) = case tys of [AppT _ _] -> True or " KnownNat 4 = > " [_] -> error ( "Error while deriveAutoReg: don't know how to handle: " ++ pprint cls ++ " (" ++ pprint tys ++ ")" ) recurse :: Type -> Q Cxt recurse (unfoldType -> (ConT cls,tys)) = constraintsWantedFor cls tys recurse t = fail ("Expected a class applied to some arguments but got " ++ pprint t) constraintsWantedFor clsNm tys = still compile with UndecidableInstances enabled . | Find tyVar substitutions between a general type and a second possibly less findTyVarSubsts :: Type -> Type -> [(Name,Type)] findTyVarSubsts = go where go ty1 ty2 = case (ty1,ty2) of (VarT nm1 , VarT nm2) | nm1 == nm2 -> [] (VarT nm , t) -> [(nm,t)] (ConT _ , ConT _) -> [] (AppT x1 y1 , AppT x2 y2) -> go x1 x2 ++ go y1 y2 (SigT t1 k1 , SigT t2 k2) -> go t1 t2 ++ go k1 k2 (InfixT x1 _ y1 , InfixT x2 _ y2) -> go x1 x2 ++ go y1 y2 (UInfixT x1 _ y1, UInfixT x2 _ y2) -> go x1 x2 ++ go y1 y2 (ParensT x1 , ParensT x2) -> go x1 x2 #if __GLASGOW_HASKELL__ >= 808 (AppKindT t1 k1 , AppKindT t2 k2) -> go t1 t2 ++ go k1 k2 (ImplicitParamT _ x1, ImplicitParamT _ x2) -> go x1 x2 #endif (PromotedT _ , PromotedT _ ) -> [] (TupleT _ , TupleT _ ) -> [] (UnboxedTupleT _ , UnboxedTupleT _ ) -> [] (UnboxedSumT _ , UnboxedSumT _ ) -> [] (ArrowT , ArrowT ) -> [] (EqualityT , EqualityT ) -> [] (ListT , ListT ) -> [] (PromotedTupleT _ , PromotedTupleT _ ) -> [] (PromotedNilT , PromotedNilT ) -> [] (PromotedConsT , PromotedConsT ) -> [] (StarT , StarT ) -> [] (ConstraintT , ConstraintT ) -> [] (LitT _ , LitT _ ) -> [] (WildCardT , WildCardT ) -> [] _ -> error $ unlines [ "findTyVarSubsts: Unexpected types" , "ty1:", pprint ty1,"ty2:", pprint ty2] applyTyVarSubsts :: [(Name,Type)] -> Type -> Type applyTyVarSubsts substs ty = go ty where go ty' = case ty' of VarT n -> case lookup n substs of Nothing -> ty' Just m -> m ConT _ -> ty' AppT ty1 ty2 -> AppT (go ty1) (go ty2) LitT _ -> ty' _ -> error $ "TODO applyTyVarSubsts: " ++ show ty' prefix0 _ .. , _ .. , prefix2 _ .. , .. generateNames :: String -> [a] -> Q [Name] generateNames prefix xs = sequence (zipWith (\n _ -> newName $ prefix ++ show @Int n) [0..] xs) deriveAutoRegTuples :: [Int] -> DecsQ deriveAutoRegTuples xs = concat <$> mapM deriveAutoRegTuple xs deriveAutoRegTuple :: Int -> DecsQ deriveAutoRegTuple n | n < 2 = fail $ "deriveAutoRegTuple doesn't work for " ++ show n ++ "-tuples" | otherwise = deriveAutoReg tupN where tupN = mkName $ "(" ++ replicate (n-1) ',' ++ ")"
7424a19476490a0db4927c1559778812a60f94e3e62afc53a17c741cba543d6f
tonyrog/can
can_sup.erl
%%%---- BEGIN COPYRIGHT ------------------------------------------------------- %%% Copyright ( C ) 2007 - 2013 , Rogvall Invest AB , < > %%% %%% This software is licensed as described in the file COPYRIGHT, which %%% you should have received as part of this distribution. The terms %%% are also available at . %%% %%% You may opt to use, copy, modify, merge, publish, distribute and/or sell copies of the Software , and permit persons to whom the Software is %%% furnished to do so, under the terms of the COPYRIGHT file. %%% This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY %%% KIND, either express or implied. %%% %%%---- END COPYRIGHT --------------------------------------------------------- @author < > ( C ) 2013 , %%% @doc %%% Can supervisor %%% Created : 28 Aug 2006 by %%% @end -module(can_sup). -behaviour(supervisor). %% external exports -export([start_link/0, start_link/1, stop/0]). %% supervisor callbacks -export([init/1]). %%%---------------------------------------------------------------------- %%% API %%%---------------------------------------------------------------------- start_link(Args) -> case supervisor:start_link({local, ?MODULE}, ?MODULE, Args) of {ok, Pid} -> {ok, Pid, {normal, Args}}; Error -> Error end. start_link() -> supervisor:start_link({local,?MODULE}, ?MODULE, []). stop() -> exit(normal). %%%---------------------------------------------------------------------- %%% Callback functions from supervisor %%%---------------------------------------------------------------------- %%---------------------------------------------------------------------- %%---------------------------------------------------------------------- init(Args) -> CanRouter = {can_router, {can_router, start_link, [Args]}, permanent, 5000, worker, [can_router]}, CanIfSup = {can_if_sup, {can_if_sup, start_link, []}, permanent, 5000, worker, [can_if_sup]}, {ok,{{one_for_all,3,5}, [CanRouter, CanIfSup]}}.
null
https://raw.githubusercontent.com/tonyrog/can/9f76fd57198e5531978791e0528e1798a9c08693/src/can_sup.erl
erlang
---- BEGIN COPYRIGHT ------------------------------------------------------- This software is licensed as described in the file COPYRIGHT, which you should have received as part of this distribution. The terms are also available at . You may opt to use, copy, modify, merge, publish, distribute and/or sell furnished to do so, under the terms of the COPYRIGHT file. KIND, either express or implied. ---- END COPYRIGHT --------------------------------------------------------- @doc Can supervisor @end external exports supervisor callbacks ---------------------------------------------------------------------- API ---------------------------------------------------------------------- ---------------------------------------------------------------------- Callback functions from supervisor ---------------------------------------------------------------------- ---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright ( C ) 2007 - 2013 , Rogvall Invest AB , < > copies of the Software , and permit persons to whom the Software is This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY @author < > ( C ) 2013 , Created : 28 Aug 2006 by -module(can_sup). -behaviour(supervisor). -export([start_link/0, start_link/1, stop/0]). -export([init/1]). start_link(Args) -> case supervisor:start_link({local, ?MODULE}, ?MODULE, Args) of {ok, Pid} -> {ok, Pid, {normal, Args}}; Error -> Error end. start_link() -> supervisor:start_link({local,?MODULE}, ?MODULE, []). stop() -> exit(normal). init(Args) -> CanRouter = {can_router, {can_router, start_link, [Args]}, permanent, 5000, worker, [can_router]}, CanIfSup = {can_if_sup, {can_if_sup, start_link, []}, permanent, 5000, worker, [can_if_sup]}, {ok,{{one_for_all,3,5}, [CanRouter, CanIfSup]}}.
ae1a00a6da474d7f0ddb00680119de0a05f45dd286b3be9a7f245b9bb724e336
elastic/eui-cljs
header_breadcrumbs.cljs
(ns eui.header-breadcrumbs (:require ["@elastic/eui/lib/components/header/header_breadcrumbs/header_breadcrumbs.js" :as eui])) (def EuiHeaderBreadcrumbs eui/EuiHeaderBreadcrumbs)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/header_breadcrumbs.cljs
clojure
(ns eui.header-breadcrumbs (:require ["@elastic/eui/lib/components/header/header_breadcrumbs/header_breadcrumbs.js" :as eui])) (def EuiHeaderBreadcrumbs eui/EuiHeaderBreadcrumbs)
61ffde1c05a034db456a15bdadfba8f392da6ddc15eb9b8f113fc7c51bd265c3
xh4/web-toolkit
aes.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- aes.lisp -- implementation of the Rijndael block cipher ;;; Currently limited to 128 - bit block sizes , although the full range of ;;; key sizes is supported. (in-package :crypto) (in-ironclad-readtable) FIXME : is it work it to combine these into one large array and subscript into that rather than having separate arrays ? CMUCL and SBCL do n't seem to want to keep the constant in a register , ;;; preferring to reload it at every reference, so a single large ;;; array scheme might not be the best for them (yet) (declaim (type (simple-array (unsigned-byte 32) (256)) Te0 Te1 Te2 Te3 Te4 Td0 Td1 Td2 Td3 Td4)) (defconst Te0 #32@(#xc66363a5 #xf87c7c84 #xee777799 #xf67b7b8d #xfff2f20d #xd66b6bbd #xde6f6fb1 #x91c5c554 #x60303050 #x02010103 #xce6767a9 #x562b2b7d #xe7fefe19 #xb5d7d762 #x4dababe6 #xec76769a #x8fcaca45 #x1f82829d #x89c9c940 #xfa7d7d87 #xeffafa15 #xb25959eb #x8e4747c9 #xfbf0f00b #x41adadec #xb3d4d467 #x5fa2a2fd #x45afafea #x239c9cbf #x53a4a4f7 #xe4727296 #x9bc0c05b #x75b7b7c2 #xe1fdfd1c #x3d9393ae #x4c26266a #x6c36365a #x7e3f3f41 #xf5f7f702 #x83cccc4f #x6834345c #x51a5a5f4 #xd1e5e534 #xf9f1f108 #xe2717193 #xabd8d873 #x62313153 #x2a15153f #x0804040c #x95c7c752 #x46232365 #x9dc3c35e #x30181828 #x379696a1 #x0a05050f #x2f9a9ab5 #x0e070709 #x24121236 #x1b80809b #xdfe2e23d #xcdebeb26 #x4e272769 #x7fb2b2cd #xea75759f #x1209091b #x1d83839e #x582c2c74 #x341a1a2e #x361b1b2d #xdc6e6eb2 #xb45a5aee #x5ba0a0fb #xa45252f6 #x763b3b4d #xb7d6d661 #x7db3b3ce #x5229297b #xdde3e33e #x5e2f2f71 #x13848497 #xa65353f5 #xb9d1d168 #x00000000 #xc1eded2c #x40202060 #xe3fcfc1f #x79b1b1c8 #xb65b5bed #xd46a6abe #x8dcbcb46 #x67bebed9 #x7239394b #x944a4ade #x984c4cd4 #xb05858e8 #x85cfcf4a #xbbd0d06b #xc5efef2a #x4faaaae5 #xedfbfb16 #x864343c5 #x9a4d4dd7 #x66333355 #x11858594 #x8a4545cf #xe9f9f910 #x04020206 #xfe7f7f81 #xa05050f0 #x783c3c44 #x259f9fba #x4ba8a8e3 #xa25151f3 #x5da3a3fe #x804040c0 #x058f8f8a #x3f9292ad #x219d9dbc #x70383848 #xf1f5f504 #x63bcbcdf #x77b6b6c1 #xafdada75 #x42212163 #x20101030 #xe5ffff1a #xfdf3f30e #xbfd2d26d #x81cdcd4c #x180c0c14 #x26131335 #xc3ecec2f #xbe5f5fe1 #x359797a2 #x884444cc #x2e171739 #x93c4c457 #x55a7a7f2 #xfc7e7e82 #x7a3d3d47 #xc86464ac #xba5d5de7 #x3219192b #xe6737395 #xc06060a0 #x19818198 #x9e4f4fd1 #xa3dcdc7f #x44222266 #x542a2a7e #x3b9090ab #x0b888883 #x8c4646ca #xc7eeee29 #x6bb8b8d3 #x2814143c #xa7dede79 #xbc5e5ee2 #x160b0b1d #xaddbdb76 #xdbe0e03b #x64323256 #x743a3a4e #x140a0a1e #x924949db #x0c06060a #x4824246c #xb85c5ce4 #x9fc2c25d #xbdd3d36e #x43acacef #xc46262a6 #x399191a8 #x319595a4 #xd3e4e437 #xf279798b #xd5e7e732 #x8bc8c843 #x6e373759 #xda6d6db7 #x018d8d8c #xb1d5d564 #x9c4e4ed2 #x49a9a9e0 #xd86c6cb4 #xac5656fa #xf3f4f407 #xcfeaea25 #xca6565af #xf47a7a8e #x47aeaee9 #x10080818 #x6fbabad5 #xf0787888 #x4a25256f #x5c2e2e72 #x381c1c24 #x57a6a6f1 #x73b4b4c7 #x97c6c651 #xcbe8e823 #xa1dddd7c #xe874749c #x3e1f1f21 #x964b4bdd #x61bdbddc #x0d8b8b86 #x0f8a8a85 #xe0707090 #x7c3e3e42 #x71b5b5c4 #xcc6666aa #x904848d8 #x06030305 #xf7f6f601 #x1c0e0e12 #xc26161a3 #x6a35355f #xae5757f9 #x69b9b9d0 #x17868691 #x99c1c158 #x3a1d1d27 #x279e9eb9 #xd9e1e138 #xebf8f813 #x2b9898b3 #x22111133 #xd26969bb #xa9d9d970 #x078e8e89 #x339494a7 #x2d9b9bb6 #x3c1e1e22 #x15878792 #xc9e9e920 #x87cece49 #xaa5555ff #x50282878 #xa5dfdf7a #x038c8c8f #x59a1a1f8 #x09898980 #x1a0d0d17 #x65bfbfda #xd7e6e631 #x844242c6 #xd06868b8 #x824141c3 #x299999b0 #x5a2d2d77 #x1e0f0f11 #x7bb0b0cb #xa85454fc #x6dbbbbd6 #x2c16163a)) (defconst Te1 #32@(#xa5c66363 #x84f87c7c #x99ee7777 #x8df67b7b #x0dfff2f2 #xbdd66b6b #xb1de6f6f #x5491c5c5 #x50603030 #x03020101 #xa9ce6767 #x7d562b2b #x19e7fefe #x62b5d7d7 #xe64dabab #x9aec7676 #x458fcaca #x9d1f8282 #x4089c9c9 #x87fa7d7d #x15effafa #xebb25959 #xc98e4747 #x0bfbf0f0 #xec41adad #x67b3d4d4 #xfd5fa2a2 #xea45afaf #xbf239c9c #xf753a4a4 #x96e47272 #x5b9bc0c0 #xc275b7b7 #x1ce1fdfd #xae3d9393 #x6a4c2626 #x5a6c3636 #x417e3f3f #x02f5f7f7 #x4f83cccc #x5c683434 #xf451a5a5 #x34d1e5e5 #x08f9f1f1 #x93e27171 #x73abd8d8 #x53623131 #x3f2a1515 #x0c080404 #x5295c7c7 #x65462323 #x5e9dc3c3 #x28301818 #xa1379696 #x0f0a0505 #xb52f9a9a #x090e0707 #x36241212 #x9b1b8080 #x3ddfe2e2 #x26cdebeb #x694e2727 #xcd7fb2b2 #x9fea7575 #x1b120909 #x9e1d8383 #x74582c2c #x2e341a1a #x2d361b1b #xb2dc6e6e #xeeb45a5a #xfb5ba0a0 #xf6a45252 #x4d763b3b #x61b7d6d6 #xce7db3b3 #x7b522929 #x3edde3e3 #x715e2f2f #x97138484 #xf5a65353 #x68b9d1d1 #x00000000 #x2cc1eded #x60402020 #x1fe3fcfc #xc879b1b1 #xedb65b5b #xbed46a6a #x468dcbcb #xd967bebe #x4b723939 #xde944a4a #xd4984c4c #xe8b05858 #x4a85cfcf #x6bbbd0d0 #x2ac5efef #xe54faaaa #x16edfbfb #xc5864343 #xd79a4d4d #x55663333 #x94118585 #xcf8a4545 #x10e9f9f9 #x06040202 #x81fe7f7f #xf0a05050 #x44783c3c #xba259f9f #xe34ba8a8 #xf3a25151 #xfe5da3a3 #xc0804040 #x8a058f8f #xad3f9292 #xbc219d9d #x48703838 #x04f1f5f5 #xdf63bcbc #xc177b6b6 #x75afdada #x63422121 #x30201010 #x1ae5ffff #x0efdf3f3 #x6dbfd2d2 #x4c81cdcd #x14180c0c #x35261313 #x2fc3ecec #xe1be5f5f #xa2359797 #xcc884444 #x392e1717 #x5793c4c4 #xf255a7a7 #x82fc7e7e #x477a3d3d #xacc86464 #xe7ba5d5d #x2b321919 #x95e67373 #xa0c06060 #x98198181 #xd19e4f4f #x7fa3dcdc #x66442222 #x7e542a2a #xab3b9090 #x830b8888 #xca8c4646 #x29c7eeee #xd36bb8b8 #x3c281414 #x79a7dede #xe2bc5e5e #x1d160b0b #x76addbdb #x3bdbe0e0 #x56643232 #x4e743a3a #x1e140a0a #xdb924949 #x0a0c0606 #x6c482424 #xe4b85c5c #x5d9fc2c2 #x6ebdd3d3 #xef43acac #xa6c46262 #xa8399191 #xa4319595 #x37d3e4e4 #x8bf27979 #x32d5e7e7 #x438bc8c8 #x596e3737 #xb7da6d6d #x8c018d8d #x64b1d5d5 #xd29c4e4e #xe049a9a9 #xb4d86c6c #xfaac5656 #x07f3f4f4 #x25cfeaea #xafca6565 #x8ef47a7a #xe947aeae #x18100808 #xd56fbaba #x88f07878 #x6f4a2525 #x725c2e2e #x24381c1c #xf157a6a6 #xc773b4b4 #x5197c6c6 #x23cbe8e8 #x7ca1dddd #x9ce87474 #x213e1f1f #xdd964b4b #xdc61bdbd #x860d8b8b #x850f8a8a #x90e07070 #x427c3e3e #xc471b5b5 #xaacc6666 #xd8904848 #x05060303 #x01f7f6f6 #x121c0e0e #xa3c26161 #x5f6a3535 #xf9ae5757 #xd069b9b9 #x91178686 #x5899c1c1 #x273a1d1d #xb9279e9e #x38d9e1e1 #x13ebf8f8 #xb32b9898 #x33221111 #xbbd26969 #x70a9d9d9 #x89078e8e #xa7339494 #xb62d9b9b #x223c1e1e #x92158787 #x20c9e9e9 #x4987cece #xffaa5555 #x78502828 #x7aa5dfdf #x8f038c8c #xf859a1a1 #x80098989 #x171a0d0d #xda65bfbf #x31d7e6e6 #xc6844242 #xb8d06868 #xc3824141 #xb0299999 #x775a2d2d #x111e0f0f #xcb7bb0b0 #xfca85454 #xd66dbbbb #x3a2c1616)) (defconst Te2 #32@(#x63a5c663 #x7c84f87c #x7799ee77 #x7b8df67b #xf20dfff2 #x6bbdd66b #x6fb1de6f #xc55491c5 #x30506030 #x01030201 #x67a9ce67 #x2b7d562b #xfe19e7fe #xd762b5d7 #xabe64dab #x769aec76 #xca458fca #x829d1f82 #xc94089c9 #x7d87fa7d #xfa15effa #x59ebb259 #x47c98e47 #xf00bfbf0 #xadec41ad #xd467b3d4 #xa2fd5fa2 #xafea45af #x9cbf239c #xa4f753a4 #x7296e472 #xc05b9bc0 #xb7c275b7 #xfd1ce1fd #x93ae3d93 #x266a4c26 #x365a6c36 #x3f417e3f #xf702f5f7 #xcc4f83cc #x345c6834 #xa5f451a5 #xe534d1e5 #xf108f9f1 #x7193e271 #xd873abd8 #x31536231 #x153f2a15 #x040c0804 #xc75295c7 #x23654623 #xc35e9dc3 #x18283018 #x96a13796 #x050f0a05 #x9ab52f9a #x07090e07 #x12362412 #x809b1b80 #xe23ddfe2 #xeb26cdeb #x27694e27 #xb2cd7fb2 #x759fea75 #x091b1209 #x839e1d83 #x2c74582c #x1a2e341a #x1b2d361b #x6eb2dc6e #x5aeeb45a #xa0fb5ba0 #x52f6a452 #x3b4d763b #xd661b7d6 #xb3ce7db3 #x297b5229 #xe33edde3 #x2f715e2f #x84971384 #x53f5a653 #xd168b9d1 #x00000000 #xed2cc1ed #x20604020 #xfc1fe3fc #xb1c879b1 #x5bedb65b #x6abed46a #xcb468dcb #xbed967be #x394b7239 #x4ade944a #x4cd4984c #x58e8b058 #xcf4a85cf #xd06bbbd0 #xef2ac5ef #xaae54faa #xfb16edfb #x43c58643 #x4dd79a4d #x33556633 #x85941185 #x45cf8a45 #xf910e9f9 #x02060402 #x7f81fe7f #x50f0a050 #x3c44783c #x9fba259f #xa8e34ba8 #x51f3a251 #xa3fe5da3 #x40c08040 #x8f8a058f #x92ad3f92 #x9dbc219d #x38487038 #xf504f1f5 #xbcdf63bc #xb6c177b6 #xda75afda #x21634221 #x10302010 #xff1ae5ff #xf30efdf3 #xd26dbfd2 #xcd4c81cd #x0c14180c #x13352613 #xec2fc3ec #x5fe1be5f #x97a23597 #x44cc8844 #x17392e17 #xc45793c4 #xa7f255a7 #x7e82fc7e #x3d477a3d #x64acc864 #x5de7ba5d #x192b3219 #x7395e673 #x60a0c060 #x81981981 #x4fd19e4f #xdc7fa3dc #x22664422 #x2a7e542a #x90ab3b90 #x88830b88 #x46ca8c46 #xee29c7ee #xb8d36bb8 #x143c2814 #xde79a7de #x5ee2bc5e #x0b1d160b #xdb76addb #xe03bdbe0 #x32566432 #x3a4e743a #x0a1e140a #x49db9249 #x060a0c06 #x246c4824 #x5ce4b85c #xc25d9fc2 #xd36ebdd3 #xacef43ac #x62a6c462 #x91a83991 #x95a43195 #xe437d3e4 #x798bf279 #xe732d5e7 #xc8438bc8 #x37596e37 #x6db7da6d #x8d8c018d #xd564b1d5 #x4ed29c4e #xa9e049a9 #x6cb4d86c #x56faac56 #xf407f3f4 #xea25cfea #x65afca65 #x7a8ef47a #xaee947ae #x08181008 #xbad56fba #x7888f078 #x256f4a25 #x2e725c2e #x1c24381c #xa6f157a6 #xb4c773b4 #xc65197c6 #xe823cbe8 #xdd7ca1dd #x749ce874 #x1f213e1f #x4bdd964b #xbddc61bd #x8b860d8b #x8a850f8a #x7090e070 #x3e427c3e #xb5c471b5 #x66aacc66 #x48d89048 #x03050603 #xf601f7f6 #x0e121c0e #x61a3c261 #x355f6a35 #x57f9ae57 #xb9d069b9 #x86911786 #xc15899c1 #x1d273a1d #x9eb9279e #xe138d9e1 #xf813ebf8 #x98b32b98 #x11332211 #x69bbd269 #xd970a9d9 #x8e89078e #x94a73394 #x9bb62d9b #x1e223c1e #x87921587 #xe920c9e9 #xce4987ce #x55ffaa55 #x28785028 #xdf7aa5df #x8c8f038c #xa1f859a1 #x89800989 #x0d171a0d #xbfda65bf #xe631d7e6 #x42c68442 #x68b8d068 #x41c38241 #x99b02999 #x2d775a2d #x0f111e0f #xb0cb7bb0 #x54fca854 #xbbd66dbb #x163a2c16)) (defconst Te3 #32@(#x6363a5c6 #x7c7c84f8 #x777799ee #x7b7b8df6 #xf2f20dff #x6b6bbdd6 #x6f6fb1de #xc5c55491 #x30305060 #x01010302 #x6767a9ce #x2b2b7d56 #xfefe19e7 #xd7d762b5 #xababe64d #x76769aec #xcaca458f #x82829d1f #xc9c94089 #x7d7d87fa #xfafa15ef #x5959ebb2 #x4747c98e #xf0f00bfb #xadadec41 #xd4d467b3 #xa2a2fd5f #xafafea45 #x9c9cbf23 #xa4a4f753 #x727296e4 #xc0c05b9b #xb7b7c275 #xfdfd1ce1 #x9393ae3d #x26266a4c #x36365a6c #x3f3f417e #xf7f702f5 #xcccc4f83 #x34345c68 #xa5a5f451 #xe5e534d1 #xf1f108f9 #x717193e2 #xd8d873ab #x31315362 #x15153f2a #x04040c08 #xc7c75295 #x23236546 #xc3c35e9d #x18182830 #x9696a137 #x05050f0a #x9a9ab52f #x0707090e #x12123624 #x80809b1b #xe2e23ddf #xebeb26cd #x2727694e #xb2b2cd7f #x75759fea #x09091b12 #x83839e1d #x2c2c7458 #x1a1a2e34 #x1b1b2d36 #x6e6eb2dc #x5a5aeeb4 #xa0a0fb5b #x5252f6a4 #x3b3b4d76 #xd6d661b7 #xb3b3ce7d #x29297b52 #xe3e33edd #x2f2f715e #x84849713 #x5353f5a6 #xd1d168b9 #x00000000 #xeded2cc1 #x20206040 #xfcfc1fe3 #xb1b1c879 #x5b5bedb6 #x6a6abed4 #xcbcb468d #xbebed967 #x39394b72 #x4a4ade94 #x4c4cd498 #x5858e8b0 #xcfcf4a85 #xd0d06bbb #xefef2ac5 #xaaaae54f #xfbfb16ed #x4343c586 #x4d4dd79a #x33335566 #x85859411 #x4545cf8a #xf9f910e9 #x02020604 #x7f7f81fe #x5050f0a0 #x3c3c4478 #x9f9fba25 #xa8a8e34b #x5151f3a2 #xa3a3fe5d #x4040c080 #x8f8f8a05 #x9292ad3f #x9d9dbc21 #x38384870 #xf5f504f1 #xbcbcdf63 #xb6b6c177 #xdada75af #x21216342 #x10103020 #xffff1ae5 #xf3f30efd #xd2d26dbf #xcdcd4c81 #x0c0c1418 #x13133526 #xecec2fc3 #x5f5fe1be #x9797a235 #x4444cc88 #x1717392e #xc4c45793 #xa7a7f255 #x7e7e82fc #x3d3d477a #x6464acc8 #x5d5de7ba #x19192b32 #x737395e6 #x6060a0c0 #x81819819 #x4f4fd19e #xdcdc7fa3 #x22226644 #x2a2a7e54 #x9090ab3b #x8888830b #x4646ca8c #xeeee29c7 #xb8b8d36b #x14143c28 #xdede79a7 #x5e5ee2bc #x0b0b1d16 #xdbdb76ad #xe0e03bdb #x32325664 #x3a3a4e74 #x0a0a1e14 #x4949db92 #x06060a0c #x24246c48 #x5c5ce4b8 #xc2c25d9f #xd3d36ebd #xacacef43 #x6262a6c4 #x9191a839 #x9595a431 #xe4e437d3 #x79798bf2 #xe7e732d5 #xc8c8438b #x3737596e #x6d6db7da #x8d8d8c01 #xd5d564b1 #x4e4ed29c #xa9a9e049 #x6c6cb4d8 #x5656faac #xf4f407f3 #xeaea25cf #x6565afca #x7a7a8ef4 #xaeaee947 #x08081810 #xbabad56f #x787888f0 #x25256f4a #x2e2e725c #x1c1c2438 #xa6a6f157 #xb4b4c773 #xc6c65197 #xe8e823cb #xdddd7ca1 #x74749ce8 #x1f1f213e #x4b4bdd96 #xbdbddc61 #x8b8b860d #x8a8a850f #x707090e0 #x3e3e427c #xb5b5c471 #x6666aacc #x4848d890 #x03030506 #xf6f601f7 #x0e0e121c #x6161a3c2 #x35355f6a #x5757f9ae #xb9b9d069 #x86869117 #xc1c15899 #x1d1d273a #x9e9eb927 #xe1e138d9 #xf8f813eb #x9898b32b #x11113322 #x6969bbd2 #xd9d970a9 #x8e8e8907 #x9494a733 #x9b9bb62d #x1e1e223c #x87879215 #xe9e920c9 #xcece4987 #x5555ffaa #x28287850 #xdfdf7aa5 #x8c8c8f03 #xa1a1f859 #x89898009 #x0d0d171a #xbfbfda65 #xe6e631d7 #x4242c684 #x6868b8d0 #x4141c382 #x9999b029 #x2d2d775a #x0f0f111e #xb0b0cb7b #x5454fca8 #xbbbbd66d #x16163a2c)) (defconst Te4 #32@(#x63636363 #x7c7c7c7c #x77777777 #x7b7b7b7b #xf2f2f2f2 #x6b6b6b6b #x6f6f6f6f #xc5c5c5c5 #x30303030 #x01010101 #x67676767 #x2b2b2b2b #xfefefefe #xd7d7d7d7 #xabababab #x76767676 #xcacacaca #x82828282 #xc9c9c9c9 #x7d7d7d7d #xfafafafa #x59595959 #x47474747 #xf0f0f0f0 #xadadadad #xd4d4d4d4 #xa2a2a2a2 #xafafafaf #x9c9c9c9c #xa4a4a4a4 #x72727272 #xc0c0c0c0 #xb7b7b7b7 #xfdfdfdfd #x93939393 #x26262626 #x36363636 #x3f3f3f3f #xf7f7f7f7 #xcccccccc #x34343434 #xa5a5a5a5 #xe5e5e5e5 #xf1f1f1f1 #x71717171 #xd8d8d8d8 #x31313131 #x15151515 #x04040404 #xc7c7c7c7 #x23232323 #xc3c3c3c3 #x18181818 #x96969696 #x05050505 #x9a9a9a9a #x07070707 #x12121212 #x80808080 #xe2e2e2e2 #xebebebeb #x27272727 #xb2b2b2b2 #x75757575 #x09090909 #x83838383 #x2c2c2c2c #x1a1a1a1a #x1b1b1b1b #x6e6e6e6e #x5a5a5a5a #xa0a0a0a0 #x52525252 #x3b3b3b3b #xd6d6d6d6 #xb3b3b3b3 #x29292929 #xe3e3e3e3 #x2f2f2f2f #x84848484 #x53535353 #xd1d1d1d1 #x00000000 #xedededed #x20202020 #xfcfcfcfc #xb1b1b1b1 #x5b5b5b5b #x6a6a6a6a #xcbcbcbcb #xbebebebe #x39393939 #x4a4a4a4a #x4c4c4c4c #x58585858 #xcfcfcfcf #xd0d0d0d0 #xefefefef #xaaaaaaaa #xfbfbfbfb #x43434343 #x4d4d4d4d #x33333333 #x85858585 #x45454545 #xf9f9f9f9 #x02020202 #x7f7f7f7f #x50505050 #x3c3c3c3c #x9f9f9f9f #xa8a8a8a8 #x51515151 #xa3a3a3a3 #x40404040 #x8f8f8f8f #x92929292 #x9d9d9d9d #x38383838 #xf5f5f5f5 #xbcbcbcbc #xb6b6b6b6 #xdadadada #x21212121 #x10101010 #xffffffff #xf3f3f3f3 #xd2d2d2d2 #xcdcdcdcd #x0c0c0c0c #x13131313 #xecececec #x5f5f5f5f #x97979797 #x44444444 #x17171717 #xc4c4c4c4 #xa7a7a7a7 #x7e7e7e7e #x3d3d3d3d #x64646464 #x5d5d5d5d #x19191919 #x73737373 #x60606060 #x81818181 #x4f4f4f4f #xdcdcdcdc #x22222222 #x2a2a2a2a #x90909090 #x88888888 #x46464646 #xeeeeeeee #xb8b8b8b8 #x14141414 #xdededede #x5e5e5e5e #x0b0b0b0b #xdbdbdbdb #xe0e0e0e0 #x32323232 #x3a3a3a3a #x0a0a0a0a #x49494949 #x06060606 #x24242424 #x5c5c5c5c #xc2c2c2c2 #xd3d3d3d3 #xacacacac #x62626262 #x91919191 #x95959595 #xe4e4e4e4 #x79797979 #xe7e7e7e7 #xc8c8c8c8 #x37373737 #x6d6d6d6d #x8d8d8d8d #xd5d5d5d5 #x4e4e4e4e #xa9a9a9a9 #x6c6c6c6c #x56565656 #xf4f4f4f4 #xeaeaeaea #x65656565 #x7a7a7a7a #xaeaeaeae #x08080808 #xbabababa #x78787878 #x25252525 #x2e2e2e2e #x1c1c1c1c #xa6a6a6a6 #xb4b4b4b4 #xc6c6c6c6 #xe8e8e8e8 #xdddddddd #x74747474 #x1f1f1f1f #x4b4b4b4b #xbdbdbdbd #x8b8b8b8b #x8a8a8a8a #x70707070 #x3e3e3e3e #xb5b5b5b5 #x66666666 #x48484848 #x03030303 #xf6f6f6f6 #x0e0e0e0e #x61616161 #x35353535 #x57575757 #xb9b9b9b9 #x86868686 #xc1c1c1c1 #x1d1d1d1d #x9e9e9e9e #xe1e1e1e1 #xf8f8f8f8 #x98989898 #x11111111 #x69696969 #xd9d9d9d9 #x8e8e8e8e #x94949494 #x9b9b9b9b #x1e1e1e1e #x87878787 #xe9e9e9e9 #xcececece #x55555555 #x28282828 #xdfdfdfdf #x8c8c8c8c #xa1a1a1a1 #x89898989 #x0d0d0d0d #xbfbfbfbf #xe6e6e6e6 #x42424242 #x68686868 #x41414141 #x99999999 #x2d2d2d2d #x0f0f0f0f #xb0b0b0b0 #x54545454 #xbbbbbbbb #x16161616)) (defconst Td0 #32@(#x51f4a750 #x7e416553 #x1a17a4c3 #x3a275e96 #x3bab6bcb #x1f9d45f1 #xacfa58ab #x4be30393 #x2030fa55 #xad766df6 #x88cc7691 #xf5024c25 #x4fe5d7fc #xc52acbd7 #x26354480 #xb562a38f #xdeb15a49 #x25ba1b67 #x45ea0e98 #x5dfec0e1 #xc32f7502 #x814cf012 #x8d4697a3 #x6bd3f9c6 #x038f5fe7 #x15929c95 #xbf6d7aeb #x955259da #xd4be832d #x587421d3 #x49e06929 #x8ec9c844 #x75c2896a #xf48e7978 #x99583e6b #x27b971dd #xbee14fb6 #xf088ad17 #xc920ac66 #x7dce3ab4 #x63df4a18 #xe51a3182 #x97513360 #x62537f45 #xb16477e0 #xbb6bae84 #xfe81a01c #xf9082b94 #x70486858 #x8f45fd19 #x94de6c87 #x527bf8b7 #xab73d323 #x724b02e2 #xe31f8f57 #x6655ab2a #xb2eb2807 #x2fb5c203 #x86c57b9a #xd33708a5 #x302887f2 #x23bfa5b2 #x02036aba #xed16825c #x8acf1c2b #xa779b492 #xf307f2f0 #x4e69e2a1 #x65daf4cd #x0605bed5 #xd134621f #xc4a6fe8a #x342e539d #xa2f355a0 #x058ae132 #xa4f6eb75 #x0b83ec39 #x4060efaa #x5e719f06 #xbd6e1051 #x3e218af9 #x96dd063d #xdd3e05ae #x4de6bd46 #x91548db5 #x71c45d05 #x0406d46f #x605015ff #x1998fb24 #xd6bde997 #x894043cc #x67d99e77 #xb0e842bd #x07898b88 #xe7195b38 #x79c8eedb #xa17c0a47 #x7c420fe9 #xf8841ec9 #x00000000 #x09808683 #x322bed48 #x1e1170ac #x6c5a724e #xfd0efffb #x0f853856 #x3daed51e #x362d3927 #x0a0fd964 #x685ca621 #x9b5b54d1 #x24362e3a #x0c0a67b1 #x9357e70f #xb4ee96d2 #x1b9b919e #x80c0c54f #x61dc20a2 #x5a774b69 #x1c121a16 #xe293ba0a #xc0a02ae5 #x3c22e043 #x121b171d #x0e090d0b #xf28bc7ad #x2db6a8b9 #x141ea9c8 #x57f11985 #xaf75074c #xee99ddbb #xa37f60fd #xf701269f #x5c72f5bc #x44663bc5 #x5bfb7e34 #x8b432976 #xcb23c6dc #xb6edfc68 #xb8e4f163 #xd731dcca #x42638510 #x13972240 #x84c61120 #x854a247d #xd2bb3df8 #xaef93211 #xc729a16d #x1d9e2f4b #xdcb230f3 #x0d8652ec #x77c1e3d0 #x2bb3166c #xa970b999 #x119448fa #x47e96422 #xa8fc8cc4 #xa0f03f1a #x567d2cd8 #x223390ef #x87494ec7 #xd938d1c1 #x8ccaa2fe #x98d40b36 #xa6f581cf #xa57ade28 #xdab78e26 #x3fadbfa4 #x2c3a9de4 #x5078920d #x6a5fcc9b #x547e4662 #xf68d13c2 #x90d8b8e8 #x2e39f75e #x82c3aff5 #x9f5d80be #x69d0937c #x6fd52da9 #xcf2512b3 #xc8ac993b #x10187da7 #xe89c636e #xdb3bbb7b #xcd267809 #x6e5918f4 #xec9ab701 #x834f9aa8 #xe6956e65 #xaaffe67e #x21bccf08 #xef15e8e6 #xbae79bd9 #x4a6f36ce #xea9f09d4 #x29b07cd6 #x31a4b2af #x2a3f2331 #xc6a59430 #x35a266c0 #x744ebc37 #xfc82caa6 #xe090d0b0 #x33a7d815 #xf104984a #x41ecdaf7 #x7fcd500e #x1791f62f #x764dd68d #x43efb04d #xccaa4d54 #xe49604df #x9ed1b5e3 #x4c6a881b #xc12c1fb8 #x4665517f #x9d5eea04 #x018c355d #xfa877473 #xfb0b412e #xb3671d5a #x92dbd252 #xe9105633 #x6dd64713 #x9ad7618c #x37a10c7a #x59f8148e #xeb133c89 #xcea927ee #xb761c935 #xe11ce5ed #x7a47b13c #x9cd2df59 #x55f2733f #x1814ce79 #x73c737bf #x53f7cdea #x5ffdaa5b #xdf3d6f14 #x7844db86 #xcaaff381 #xb968c43e #x3824342c #xc2a3405f #x161dc372 #xbce2250c #x283c498b #xff0d9541 #x39a80171 #x080cb3de #xd8b4e49c #x6456c190 #x7bcb8461 #xd532b670 #x486c5c74 #xd0b85742)) (defconst Td1 #32@(#x5051f4a7 #x537e4165 #xc31a17a4 #x963a275e #xcb3bab6b #xf11f9d45 #xabacfa58 #x934be303 #x552030fa #xf6ad766d #x9188cc76 #x25f5024c #xfc4fe5d7 #xd7c52acb #x80263544 #x8fb562a3 #x49deb15a #x6725ba1b #x9845ea0e #xe15dfec0 #x02c32f75 #x12814cf0 #xa38d4697 #xc66bd3f9 #xe7038f5f #x9515929c #xebbf6d7a #xda955259 #x2dd4be83 #xd3587421 #x2949e069 #x448ec9c8 #x6a75c289 #x78f48e79 #x6b99583e #xdd27b971 #xb6bee14f #x17f088ad #x66c920ac #xb47dce3a #x1863df4a #x82e51a31 #x60975133 #x4562537f #xe0b16477 #x84bb6bae #x1cfe81a0 #x94f9082b #x58704868 #x198f45fd #x8794de6c #xb7527bf8 #x23ab73d3 #xe2724b02 #x57e31f8f #x2a6655ab #x07b2eb28 #x032fb5c2 #x9a86c57b #xa5d33708 #xf2302887 #xb223bfa5 #xba02036a #x5ced1682 #x2b8acf1c #x92a779b4 #xf0f307f2 #xa14e69e2 #xcd65daf4 #xd50605be #x1fd13462 #x8ac4a6fe #x9d342e53 #xa0a2f355 #x32058ae1 #x75a4f6eb #x390b83ec #xaa4060ef #x065e719f #x51bd6e10 #xf93e218a #x3d96dd06 #xaedd3e05 #x464de6bd #xb591548d #x0571c45d #x6f0406d4 #xff605015 #x241998fb #x97d6bde9 #xcc894043 #x7767d99e #xbdb0e842 #x8807898b #x38e7195b #xdb79c8ee #x47a17c0a #xe97c420f #xc9f8841e #x00000000 #x83098086 #x48322bed #xac1e1170 #x4e6c5a72 #xfbfd0eff #x560f8538 #x1e3daed5 #x27362d39 #x640a0fd9 #x21685ca6 #xd19b5b54 #x3a24362e #xb10c0a67 #x0f9357e7 #xd2b4ee96 #x9e1b9b91 #x4f80c0c5 #xa261dc20 #x695a774b #x161c121a #x0ae293ba #xe5c0a02a #x433c22e0 #x1d121b17 #x0b0e090d #xadf28bc7 #xb92db6a8 #xc8141ea9 #x8557f119 #x4caf7507 #xbbee99dd #xfda37f60 #x9ff70126 #xbc5c72f5 #xc544663b #x345bfb7e #x768b4329 #xdccb23c6 #x68b6edfc #x63b8e4f1 #xcad731dc #x10426385 #x40139722 #x2084c611 #x7d854a24 #xf8d2bb3d #x11aef932 #x6dc729a1 #x4b1d9e2f #xf3dcb230 #xec0d8652 #xd077c1e3 #x6c2bb316 #x99a970b9 #xfa119448 #x2247e964 #xc4a8fc8c #x1aa0f03f #xd8567d2c #xef223390 #xc787494e #xc1d938d1 #xfe8ccaa2 #x3698d40b #xcfa6f581 #x28a57ade #x26dab78e #xa43fadbf #xe42c3a9d #x0d507892 #x9b6a5fcc #x62547e46 #xc2f68d13 #xe890d8b8 #x5e2e39f7 #xf582c3af #xbe9f5d80 #x7c69d093 #xa96fd52d #xb3cf2512 #x3bc8ac99 #xa710187d #x6ee89c63 #x7bdb3bbb #x09cd2678 #xf46e5918 #x01ec9ab7 #xa8834f9a #x65e6956e #x7eaaffe6 #x0821bccf #xe6ef15e8 #xd9bae79b #xce4a6f36 #xd4ea9f09 #xd629b07c #xaf31a4b2 #x312a3f23 #x30c6a594 #xc035a266 #x37744ebc #xa6fc82ca #xb0e090d0 #x1533a7d8 #x4af10498 #xf741ecda #x0e7fcd50 #x2f1791f6 #x8d764dd6 #x4d43efb0 #x54ccaa4d #xdfe49604 #xe39ed1b5 #x1b4c6a88 #xb8c12c1f #x7f466551 #x049d5eea #x5d018c35 #x73fa8774 #x2efb0b41 #x5ab3671d #x5292dbd2 #x33e91056 #x136dd647 #x8c9ad761 #x7a37a10c #x8e59f814 #x89eb133c #xeecea927 #x35b761c9 #xede11ce5 #x3c7a47b1 #x599cd2df #x3f55f273 #x791814ce #xbf73c737 #xea53f7cd #x5b5ffdaa #x14df3d6f #x867844db #x81caaff3 #x3eb968c4 #x2c382434 #x5fc2a340 #x72161dc3 #x0cbce225 #x8b283c49 #x41ff0d95 #x7139a801 #xde080cb3 #x9cd8b4e4 #x906456c1 #x617bcb84 #x70d532b6 #x74486c5c #x42d0b857)) (defconst Td2 #32@(#xa75051f4 #x65537e41 #xa4c31a17 #x5e963a27 #x6bcb3bab #x45f11f9d #x58abacfa #x03934be3 #xfa552030 #x6df6ad76 #x769188cc #x4c25f502 #xd7fc4fe5 #xcbd7c52a #x44802635 #xa38fb562 #x5a49deb1 #x1b6725ba #x0e9845ea #xc0e15dfe #x7502c32f #xf012814c #x97a38d46 #xf9c66bd3 #x5fe7038f #x9c951592 #x7aebbf6d #x59da9552 #x832dd4be #x21d35874 #x692949e0 #xc8448ec9 #x896a75c2 #x7978f48e #x3e6b9958 #x71dd27b9 #x4fb6bee1 #xad17f088 #xac66c920 #x3ab47dce #x4a1863df #x3182e51a #x33609751 #x7f456253 #x77e0b164 #xae84bb6b #xa01cfe81 #x2b94f908 #x68587048 #xfd198f45 #x6c8794de #xf8b7527b #xd323ab73 #x02e2724b #x8f57e31f #xab2a6655 #x2807b2eb #xc2032fb5 #x7b9a86c5 #x08a5d337 #x87f23028 #xa5b223bf #x6aba0203 #x825ced16 #x1c2b8acf #xb492a779 #xf2f0f307 #xe2a14e69 #xf4cd65da #xbed50605 #x621fd134 #xfe8ac4a6 #x539d342e #x55a0a2f3 #xe132058a #xeb75a4f6 #xec390b83 #xefaa4060 #x9f065e71 #x1051bd6e #x8af93e21 #x063d96dd #x05aedd3e #xbd464de6 #x8db59154 #x5d0571c4 #xd46f0406 #x15ff6050 #xfb241998 #xe997d6bd #x43cc8940 #x9e7767d9 #x42bdb0e8 #x8b880789 #x5b38e719 #xeedb79c8 #x0a47a17c #x0fe97c42 #x1ec9f884 #x00000000 #x86830980 #xed48322b #x70ac1e11 #x724e6c5a #xfffbfd0e #x38560f85 #xd51e3dae #x3927362d #xd9640a0f #xa621685c #x54d19b5b #x2e3a2436 #x67b10c0a #xe70f9357 #x96d2b4ee #x919e1b9b #xc54f80c0 #x20a261dc #x4b695a77 #x1a161c12 #xba0ae293 #x2ae5c0a0 #xe0433c22 #x171d121b #x0d0b0e09 #xc7adf28b #xa8b92db6 #xa9c8141e #x198557f1 #x074caf75 #xddbbee99 #x60fda37f #x269ff701 #xf5bc5c72 #x3bc54466 #x7e345bfb #x29768b43 #xc6dccb23 #xfc68b6ed #xf163b8e4 #xdccad731 #x85104263 #x22401397 #x112084c6 #x247d854a #x3df8d2bb #x3211aef9 #xa16dc729 #x2f4b1d9e #x30f3dcb2 #x52ec0d86 #xe3d077c1 #x166c2bb3 #xb999a970 #x48fa1194 #x642247e9 #x8cc4a8fc #x3f1aa0f0 #x2cd8567d #x90ef2233 #x4ec78749 #xd1c1d938 #xa2fe8cca #x0b3698d4 #x81cfa6f5 #xde28a57a #x8e26dab7 #xbfa43fad #x9de42c3a #x920d5078 #xcc9b6a5f #x4662547e #x13c2f68d #xb8e890d8 #xf75e2e39 #xaff582c3 #x80be9f5d #x937c69d0 #x2da96fd5 #x12b3cf25 #x993bc8ac #x7da71018 #x636ee89c #xbb7bdb3b #x7809cd26 #x18f46e59 #xb701ec9a #x9aa8834f #x6e65e695 #xe67eaaff #xcf0821bc #xe8e6ef15 #x9bd9bae7 #x36ce4a6f #x09d4ea9f #x7cd629b0 #xb2af31a4 #x23312a3f #x9430c6a5 #x66c035a2 #xbc37744e #xcaa6fc82 #xd0b0e090 #xd81533a7 #x984af104 #xdaf741ec #x500e7fcd #xf62f1791 #xd68d764d #xb04d43ef #x4d54ccaa #x04dfe496 #xb5e39ed1 #x881b4c6a #x1fb8c12c #x517f4665 #xea049d5e #x355d018c #x7473fa87 #x412efb0b #x1d5ab367 #xd25292db #x5633e910 #x47136dd6 #x618c9ad7 #x0c7a37a1 #x148e59f8 #x3c89eb13 #x27eecea9 #xc935b761 #xe5ede11c #xb13c7a47 #xdf599cd2 #x733f55f2 #xce791814 #x37bf73c7 #xcdea53f7 #xaa5b5ffd #x6f14df3d #xdb867844 #xf381caaf #xc43eb968 #x342c3824 #x405fc2a3 #xc372161d #x250cbce2 #x498b283c #x9541ff0d #x017139a8 #xb3de080c #xe49cd8b4 #xc1906456 #x84617bcb #xb670d532 #x5c74486c #x5742d0b8)) (defconst Td3 #32@(#xf4a75051 #x4165537e #x17a4c31a #x275e963a #xab6bcb3b #x9d45f11f #xfa58abac #xe303934b #x30fa5520 #x766df6ad #xcc769188 #x024c25f5 #xe5d7fc4f #x2acbd7c5 #x35448026 #x62a38fb5 #xb15a49de #xba1b6725 #xea0e9845 #xfec0e15d #x2f7502c3 #x4cf01281 #x4697a38d #xd3f9c66b #x8f5fe703 #x929c9515 #x6d7aebbf #x5259da95 #xbe832dd4 #x7421d358 #xe0692949 #xc9c8448e #xc2896a75 #x8e7978f4 #x583e6b99 #xb971dd27 #xe14fb6be #x88ad17f0 #x20ac66c9 #xce3ab47d #xdf4a1863 #x1a3182e5 #x51336097 #x537f4562 #x6477e0b1 #x6bae84bb #x81a01cfe #x082b94f9 #x48685870 #x45fd198f #xde6c8794 #x7bf8b752 #x73d323ab #x4b02e272 #x1f8f57e3 #x55ab2a66 #xeb2807b2 #xb5c2032f #xc57b9a86 #x3708a5d3 #x2887f230 #xbfa5b223 #x036aba02 #x16825ced #xcf1c2b8a #x79b492a7 #x07f2f0f3 #x69e2a14e #xdaf4cd65 #x05bed506 #x34621fd1 #xa6fe8ac4 #x2e539d34 #xf355a0a2 #x8ae13205 #xf6eb75a4 #x83ec390b #x60efaa40 #x719f065e #x6e1051bd #x218af93e #xdd063d96 #x3e05aedd #xe6bd464d #x548db591 #xc45d0571 #x06d46f04 #x5015ff60 #x98fb2419 #xbde997d6 #x4043cc89 #xd99e7767 #xe842bdb0 #x898b8807 #x195b38e7 #xc8eedb79 #x7c0a47a1 #x420fe97c #x841ec9f8 #x00000000 #x80868309 #x2bed4832 #x1170ac1e #x5a724e6c #x0efffbfd #x8538560f #xaed51e3d #x2d392736 #x0fd9640a #x5ca62168 #x5b54d19b #x362e3a24 #x0a67b10c #x57e70f93 #xee96d2b4 #x9b919e1b #xc0c54f80 #xdc20a261 #x774b695a #x121a161c #x93ba0ae2 #xa02ae5c0 #x22e0433c #x1b171d12 #x090d0b0e #x8bc7adf2 #xb6a8b92d #x1ea9c814 #xf1198557 #x75074caf #x99ddbbee #x7f60fda3 #x01269ff7 #x72f5bc5c #x663bc544 #xfb7e345b #x4329768b #x23c6dccb #xedfc68b6 #xe4f163b8 #x31dccad7 #x63851042 #x97224013 #xc6112084 #x4a247d85 #xbb3df8d2 #xf93211ae #x29a16dc7 #x9e2f4b1d #xb230f3dc #x8652ec0d #xc1e3d077 #xb3166c2b #x70b999a9 #x9448fa11 #xe9642247 #xfc8cc4a8 #xf03f1aa0 #x7d2cd856 #x3390ef22 #x494ec787 #x38d1c1d9 #xcaa2fe8c #xd40b3698 #xf581cfa6 #x7ade28a5 #xb78e26da #xadbfa43f #x3a9de42c #x78920d50 #x5fcc9b6a #x7e466254 #x8d13c2f6 #xd8b8e890 #x39f75e2e #xc3aff582 #x5d80be9f #xd0937c69 #xd52da96f #x2512b3cf #xac993bc8 #x187da710 #x9c636ee8 #x3bbb7bdb #x267809cd #x5918f46e #x9ab701ec #x4f9aa883 #x956e65e6 #xffe67eaa #xbccf0821 #x15e8e6ef #xe79bd9ba #x6f36ce4a #x9f09d4ea #xb07cd629 #xa4b2af31 #x3f23312a #xa59430c6 #xa266c035 #x4ebc3774 #x82caa6fc #x90d0b0e0 #xa7d81533 #x04984af1 #xecdaf741 #xcd500e7f #x91f62f17 #x4dd68d76 #xefb04d43 #xaa4d54cc #x9604dfe4 #xd1b5e39e #x6a881b4c #x2c1fb8c1 #x65517f46 #x5eea049d #x8c355d01 #x877473fa #x0b412efb #x671d5ab3 #xdbd25292 #x105633e9 #xd647136d #xd7618c9a #xa10c7a37 #xf8148e59 #x133c89eb #xa927eece #x61c935b7 #x1ce5ede1 #x47b13c7a #xd2df599c #xf2733f55 #x14ce7918 #xc737bf73 #xf7cdea53 #xfdaa5b5f #x3d6f14df #x44db8678 #xaff381ca #x68c43eb9 #x24342c38 #xa3405fc2 #x1dc37216 #xe2250cbc #x3c498b28 #x0d9541ff #xa8017139 #x0cb3de08 #xb4e49cd8 #x56c19064 #xcb84617b #x32b670d5 #x6c5c7448 #xb85742d0)) (defconst Td4 #32@(#x52525252 #x09090909 #x6a6a6a6a #xd5d5d5d5 #x30303030 #x36363636 #xa5a5a5a5 #x38383838 #xbfbfbfbf #x40404040 #xa3a3a3a3 #x9e9e9e9e #x81818181 #xf3f3f3f3 #xd7d7d7d7 #xfbfbfbfb #x7c7c7c7c #xe3e3e3e3 #x39393939 #x82828282 #x9b9b9b9b #x2f2f2f2f #xffffffff #x87878787 #x34343434 #x8e8e8e8e #x43434343 #x44444444 #xc4c4c4c4 #xdededede #xe9e9e9e9 #xcbcbcbcb #x54545454 #x7b7b7b7b #x94949494 #x32323232 #xa6a6a6a6 #xc2c2c2c2 #x23232323 #x3d3d3d3d #xeeeeeeee #x4c4c4c4c #x95959595 #x0b0b0b0b #x42424242 #xfafafafa #xc3c3c3c3 #x4e4e4e4e #x08080808 #x2e2e2e2e #xa1a1a1a1 #x66666666 #x28282828 #xd9d9d9d9 #x24242424 #xb2b2b2b2 #x76767676 #x5b5b5b5b #xa2a2a2a2 #x49494949 #x6d6d6d6d #x8b8b8b8b #xd1d1d1d1 #x25252525 #x72727272 #xf8f8f8f8 #xf6f6f6f6 #x64646464 #x86868686 #x68686868 #x98989898 #x16161616 #xd4d4d4d4 #xa4a4a4a4 #x5c5c5c5c #xcccccccc #x5d5d5d5d #x65656565 #xb6b6b6b6 #x92929292 #x6c6c6c6c #x70707070 #x48484848 #x50505050 #xfdfdfdfd #xedededed #xb9b9b9b9 #xdadadada #x5e5e5e5e #x15151515 #x46464646 #x57575757 #xa7a7a7a7 #x8d8d8d8d #x9d9d9d9d #x84848484 #x90909090 #xd8d8d8d8 #xabababab #x00000000 #x8c8c8c8c #xbcbcbcbc #xd3d3d3d3 #x0a0a0a0a #xf7f7f7f7 #xe4e4e4e4 #x58585858 #x05050505 #xb8b8b8b8 #xb3b3b3b3 #x45454545 #x06060606 #xd0d0d0d0 #x2c2c2c2c #x1e1e1e1e #x8f8f8f8f #xcacacaca #x3f3f3f3f #x0f0f0f0f #x02020202 #xc1c1c1c1 #xafafafaf #xbdbdbdbd #x03030303 #x01010101 #x13131313 #x8a8a8a8a #x6b6b6b6b #x3a3a3a3a #x91919191 #x11111111 #x41414141 #x4f4f4f4f #x67676767 #xdcdcdcdc #xeaeaeaea #x97979797 #xf2f2f2f2 #xcfcfcfcf #xcececece #xf0f0f0f0 #xb4b4b4b4 #xe6e6e6e6 #x73737373 #x96969696 #xacacacac #x74747474 #x22222222 #xe7e7e7e7 #xadadadad #x35353535 #x85858585 #xe2e2e2e2 #xf9f9f9f9 #x37373737 #xe8e8e8e8 #x1c1c1c1c #x75757575 #xdfdfdfdf #x6e6e6e6e #x47474747 #xf1f1f1f1 #x1a1a1a1a #x71717171 #x1d1d1d1d #x29292929 #xc5c5c5c5 #x89898989 #x6f6f6f6f #xb7b7b7b7 #x62626262 #x0e0e0e0e #xaaaaaaaa #x18181818 #xbebebebe #x1b1b1b1b #xfcfcfcfc #x56565656 #x3e3e3e3e #x4b4b4b4b #xc6c6c6c6 #xd2d2d2d2 #x79797979 #x20202020 #x9a9a9a9a #xdbdbdbdb #xc0c0c0c0 #xfefefefe #x78787878 #xcdcdcdcd #x5a5a5a5a #xf4f4f4f4 #x1f1f1f1f #xdddddddd #xa8a8a8a8 #x33333333 #x88888888 #x07070707 #xc7c7c7c7 #x31313131 #xb1b1b1b1 #x12121212 #x10101010 #x59595959 #x27272727 #x80808080 #xecececec #x5f5f5f5f #x60606060 #x51515151 #x7f7f7f7f #xa9a9a9a9 #x19191919 #xb5b5b5b5 #x4a4a4a4a #x0d0d0d0d #x2d2d2d2d #xe5e5e5e5 #x7a7a7a7a #x9f9f9f9f #x93939393 #xc9c9c9c9 #x9c9c9c9c #xefefefef #xa0a0a0a0 #xe0e0e0e0 #x3b3b3b3b #x4d4d4d4d #xaeaeaeae #x2a2a2a2a #xf5f5f5f5 #xb0b0b0b0 #xc8c8c8c8 #xebebebeb #xbbbbbbbb #x3c3c3c3c #x83838383 #x53535353 #x99999999 #x61616161 #x17171717 #x2b2b2b2b #x04040404 #x7e7e7e7e #xbabababa #x77777777 #xd6d6d6d6 #x26262626 #xe1e1e1e1 #x69696969 #x14141414 #x63636363 #x55555555 #x21212121 #x0c0c0c0c #x7d7d7d7d)) (declaim (type (simple-array (unsigned-byte 32) (10)) round-constants)) (defconst round-constants #32@(#x01000000 #x02000000 #x04000000 #x08000000 #x10000000 #x20000000 #x40000000 #x80000000 #x1B000000 #x36000000)) the actual AES implementation waste a little space for " common " 128 - bit keys , but is anybody really ;;; going to notice? (deftype aes-round-keys () '(simple-array (unsigned-byte 32) (60))) (defclass aes (cipher 16-byte-block-mixin) ((encryption-round-keys :accessor encryption-round-keys :type aes-round-keys) (decryption-round-keys :accessor decryption-round-keys :type aes-round-keys) (n-rounds :accessor n-rounds))) (defun allocate-round-keys (key) (declare (type (simple-array (unsigned-byte 8) (*)) key)) (ecase (length key) ((16 24 32) (make-array 60 :element-type '(unsigned-byte 32) :initial-element 0)))) (defun generate-128-bit-round-keys (round-keys key) (declare (type aes-round-keys round-keys) (type (simple-array (unsigned-byte 8) (16)) key) (optimize (speed 3) (space 0) (debug 0))) (let ((round-key-offset 0)) (declare (type (integer 0 43) round-key-offset)) (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-key-offset)))) (dotimes (i 4) (setf (rk-ref i) (ub32ref/be key (* 4 i)))) (dotimes (i 10 (values round-keys 10)) (declare (type (integer 0 10) i)) (let ((tmp (rk-ref 3))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 4) (logxor (rk-ref 0) (logand (aref Te4 (third-byte tmp)) #xff000000) (logand (aref Te4 (second-byte tmp)) #x00ff0000) (logand (aref Te4 (first-byte tmp)) #x0000ff00) (logand (aref Te4 (fourth-byte tmp)) #x000000ff) (aref round-constants i)) (rk-ref 5) (logxor (rk-ref 1) (rk-ref 4)) (rk-ref 6) (logxor (rk-ref 2) (rk-ref 5)) (rk-ref 7) (logxor (rk-ref 3) (rk-ref 6))) (incf round-key-offset 4)))))) (defun generate-192-bit-round-keys (round-keys key) (declare (type aes-round-keys round-keys) (type (simple-array (unsigned-byte 8) (24)) key) (optimize (speed 3) (space 0) (debug 0))) (let ((round-key-offset 0)) (declare (type (integer 0 51) round-key-offset)) (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-key-offset)))) (dotimes (i 6) (setf (rk-ref i) (ub32ref/be key (* 4 i)))) (dotimes (i 8) (let ((tmp (rk-ref 5))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 6) (logxor (rk-ref 0) (logand (aref Te4 (third-byte tmp)) #xff000000) (logand (aref Te4 (second-byte tmp)) #x00ff0000) (logand (aref Te4 (first-byte tmp)) #x0000ff00) (logand (aref Te4 (fourth-byte tmp)) #x000000ff) (aref round-constants i)) (rk-ref 7) (logxor (rk-ref 1) (rk-ref 6)) (rk-ref 8) (logxor (rk-ref 2) (rk-ref 7)) (rk-ref 9) (logxor (rk-ref 3) (rk-ref 8))) (when (= 8 (1+ i)) (return-from generate-192-bit-round-keys (values round-keys 12))) (setf (rk-ref 10) (logxor (rk-ref 4) (rk-ref 9)) (rk-ref 11) (logxor (rk-ref 5) (rk-ref 10))) (incf round-key-offset 6)))))) (defun generate-256-bit-round-keys (round-keys key) (declare (type aes-round-keys round-keys) (type (simple-array (unsigned-byte 8) (32)) key) (optimize (speed 3) (space 0) (debug 0))) (let ((round-key-offset 0)) (declare (type (integer 0 59) round-key-offset)) (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-key-offset)))) (dotimes (i 8) (setf (rk-ref i) (ub32ref/be key (* 4 i)))) (dotimes (i 7) (let ((tmp (rk-ref 7))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 8) (logxor (rk-ref 0) (logand (aref Te4 (third-byte tmp)) #xff000000) (logand (aref Te4 (second-byte tmp)) #x00ff0000) (logand (aref Te4 (first-byte tmp)) #x0000ff00) (logand (aref Te4 (fourth-byte tmp)) #x000000ff) (aref round-constants i)) (rk-ref 9) (logxor (rk-ref 1) (rk-ref 8)) (rk-ref 10) (logxor (rk-ref 2) (rk-ref 9)) (rk-ref 11) (logxor (rk-ref 3) (rk-ref 10))) (when (= 7 (1+ i)) (return-from generate-256-bit-round-keys (values round-keys 14)))) (let ((tmp (rk-ref 11))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 12) (logxor (rk-ref 4) (logand (aref Te4 (fourth-byte tmp)) #xff000000) (logand (aref Te4 (third-byte tmp)) #x00ff0000) (logand (aref Te4 (second-byte tmp)) #x0000ff00) (logand (aref Te4 (first-byte tmp)) #x000000ff)) (rk-ref 13) (logxor (rk-ref 5) (rk-ref 12)) (rk-ref 14) (logxor (rk-ref 6) (rk-ref 13)) (rk-ref 15) (logxor (rk-ref 7) (rk-ref 14))) (incf round-key-offset 8)))))) (defun generate-round-keys-for-encryption (key round-keys) (declare (type (simple-array (unsigned-byte 8) (*)) key)) (ecase (length key) (16 (generate-128-bit-round-keys round-keys key)) (24 (generate-192-bit-round-keys round-keys key)) (32 (generate-256-bit-round-keys round-keys key)))) (defun generate-round-keys-for-decryption (round-keys n-rounds) (declare (type aes-round-keys round-keys) (type (unsigned-byte 16) n-rounds)) ;; invert the order of the round keys (do ((i 0 (+ 4 i)) (j (* 4 n-rounds) (- j 4))) ((>= i j)) (declare (type (unsigned-byte 16) i j)) (rotatef (aref round-keys i) (aref round-keys j)) (rotatef (aref round-keys (+ 1 i)) (aref round-keys (+ 1 j))) (rotatef (aref round-keys (+ 2 i)) (aref round-keys (+ 2 j))) (rotatef (aref round-keys (+ 3 i)) (aref round-keys (+ 3 j)))) apply inverse MixColumn transform to all round keys but the first (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-keys-offset)))) (do ((i 1 (+ 1 i)) (round-keys-offset 4 (+ 4 round-keys-offset))) ((>= i n-rounds) (values round-keys n-rounds)) (declare (type (unsigned-byte 16) round-keys-offset)) (macrolet ((mix-column (x) `(let ((column (rk-ref ,x))) (declare (type (unsigned-byte 32) column)) (setf (rk-ref ,x) (logxor (aref Td0 (first-byte (aref Te4 (fourth-byte column)))) (aref Td1 (first-byte (aref Te4 (third-byte column)))) (aref Td2 (first-byte (aref Te4 (second-byte column)))) (aref Td3 (first-byte (aref Te4 (first-byte column))))))))) (mix-column 0) (mix-column 1) (mix-column 2) (mix-column 3))))) (macrolet ((mix (rk a0 a1 a2 a3 sym0 sym1 sym2 sym3) `(logxor (aref ,a0 (fourth-byte ,sym0)) (aref ,a1 (third-byte ,sym1)) (aref ,a2 (second-byte ,sym2)) (aref ,a3 (first-byte ,sym3)) (rk-ref ,rk))) (mix-s-into-t-encrypting (offset) `(setf t0 (mix ,offset Te0 Te1 Te2 Te3 s0 s1 s2 s3) t1 (mix (1+ ,offset) Te0 Te1 Te2 Te3 s1 s2 s3 s0) t2 (mix (+ ,offset 2) Te0 Te1 Te2 Te3 s2 s3 s0 s1) t3 (mix (+ ,offset 3) Te0 Te1 Te2 Te3 s3 s0 s1 s2))) (mix-t-into-s-encrypting (offset) `(setf s0 (mix ,offset Te0 Te1 Te2 Te3 t0 t1 t2 t3) s1 (mix (1+ ,offset) Te0 Te1 Te2 Te3 t1 t2 t3 t0) s2 (mix (+ ,offset 2) Te0 Te1 Te2 Te3 t2 t3 t0 t1) s3 (mix (+ ,offset 3) Te0 Te1 Te2 Te3 t3 t0 t1 t2))) (mix-s-into-t-decrypting (offset) `(setf t0 (mix ,offset Td0 Td1 Td2 Td3 s0 s3 s2 s1) t1 (mix (1+ ,offset) Td0 Td1 Td2 Td3 s1 s0 s3 s2) t2 (mix (+ ,offset 2) Td0 Td1 Td2 Td3 s2 s1 s0 s3) t3 (mix (+ ,offset 3) Td0 Td1 Td2 Td3 s3 s2 s1 s0))) (mix-t-into-s-decrypting (offset) `(setf s0 (mix ,offset Td0 Td1 Td2 Td3 t0 t3 t2 t1) s1 (mix (1+ ,offset) Td0 Td1 Td2 Td3 t1 t0 t3 t2) s2 (mix (+ ,offset 2) Td0 Td1 Td2 Td3 t2 t1 t0 t3) s3 (mix (+ ,offset 3) Td0 Td1 Td2 Td3 t3 t2 t1 t0))) (rk-ref (x) `(aref round-keys (+ ,x round-key-offset))) #+nil (rk-ref (x) `(aref round-keys (+ ,x 0)))) (define-block-encryptor aes 16 (let ((round-keys (encryption-round-keys context)) (n-rounds (n-rounds context))) (declare (type aes-round-keys round-keys)) (declare (type (integer 0 14) n-rounds)) #+(and sbcl x86-64 aes-ni) (aes-ni-encrypt plaintext plaintext-start ciphertext ciphertext-start round-keys n-rounds) #-(and sbcl x86-64 aes-ni) (with-words ((s0 s1 s2 s3) plaintext plaintext-start) ;; the "optimized implementation" also had a fully unrolled version of ;; this loop hanging around. it might be worthwhile to translate it and ;; see if it actually gains us anything. a wizard would do this with a ;; macro which allows one to easily switch between unrolled and ;; non-unrolled versions. I am not a wizard. (let ((t0 0) (t1 0) (t2 0) (t3 0) (round-key-offset 0)) (declare (type (unsigned-byte 32) t0 t1 t2 t3)) (declare (type (unsigned-byte 16) round-key-offset)) ;; initial whitening (setf s0 (logxor s0 (aref round-keys 0)) s1 (logxor s1 (aref round-keys 1)) s2 (logxor s2 (aref round-keys 2)) s3 (logxor s3 (aref round-keys 3))) (do ((round (truncate n-rounds 2) (1- round))) ((zerop round)) (declare (type (unsigned-byte 16) round)) (mix-s-into-t-encrypting 4) (incf round-key-offset 8) (when (= round 1) (return-from nil (values))) (mix-t-into-s-encrypting 0)) ;; apply last round and dump cipher state into the ciphertext (flet ((apply-round (round-key u0 u1 u2 u3) (declare (type (unsigned-byte 32) round-key u0 u1 u2 u3)) (logxor (logand (aref Te4 (fourth-byte u0)) #xff000000) (logand (aref Te4 (third-byte u1)) #x00ff0000) (logand (aref Te4 (second-byte u2)) #x0000ff00) (logand (aref Te4 (first-byte u3)) #x000000ff) round-key))) (declare (inline apply-round)) (store-words ciphertext ciphertext-start (apply-round (rk-ref 0) t0 t1 t2 t3) (apply-round (rk-ref 1) t1 t2 t3 t0) (apply-round (rk-ref 2) t2 t3 t0 t1) (apply-round (rk-ref 3) t3 t0 t1 t2))))))) (define-block-decryptor aes 16 (let ((round-keys (decryption-round-keys context)) (n-rounds (n-rounds context))) (declare (type aes-round-keys round-keys)) (declare (type (unsigned-byte 16) n-rounds)) #+(and sbcl x86-64 aes-ni) (aes-ni-decrypt ciphertext ciphertext-start plaintext plaintext-start round-keys n-rounds) #-(and sbcl x86-64 aes-ni) (with-words ((s0 s1 s2 s3) ciphertext ciphertext-start) (let ((t0 0) (t1 0) (t2 0) (t3 0) (round-key-offset 0)) (declare (type (unsigned-byte 32) t0 t1 t2 t3)) (declare (type (unsigned-byte 16) round-key-offset)) ;; initial whitening (setf s0 (logxor s0 (aref round-keys 0)) s1 (logxor s1 (aref round-keys 1)) s2 (logxor s2 (aref round-keys 2)) s3 (logxor s3 (aref round-keys 3))) (do ((round (truncate n-rounds 2) (1- round))) ((zerop round)) (declare (type (unsigned-byte 16) round)) (mix-s-into-t-decrypting 4) (incf round-key-offset 8) (when (= round 1) (return-from nil (values))) (mix-t-into-s-decrypting 0)) ;; apply last round and dump cipher state into plaintext (flet ((apply-round (round-key u0 u1 u2 u3) (declare (type (unsigned-byte 32) round-key u0 u1 u2 u3)) (logxor (logand (aref Td4 (fourth-byte u0)) #xff000000) (logand (aref Td4 (third-byte u1)) #x00ff0000) (logand (aref Td4 (second-byte u2)) #x0000ff00) (logand (aref Td4 (first-byte u3)) #x000000ff) round-key))) (declare (inline apply-round)) (store-words plaintext plaintext-start (apply-round (rk-ref 0) t0 t3 t2 t1) (apply-round (rk-ref 1) t1 t0 t3 t2) (apply-round (rk-ref 2) t2 t1 t0 t3) (apply-round (rk-ref 3) t3 t2 t1 t0))))))) MACROLET (defmethod schedule-key ((cipher aes) key) #+(and sbcl x86-64 aes-ni) (let ((encryption-keys (allocate-round-keys key)) (decryption-keys (allocate-round-keys key)) (n-rounds (ecase (length key) (16 10) (24 12) (32 14)))) (declare (type aes-round-keys encryption-keys decryption-keys)) (aes-ni-generate-round-keys key (length key) encryption-keys decryption-keys) (setf (encryption-round-keys cipher) encryption-keys (decryption-round-keys cipher) decryption-keys (n-rounds cipher) n-rounds) cipher) #-(and sbcl x86-64 aes-ni) (multiple-value-bind (encryption-keys n-rounds) (generate-round-keys-for-encryption key (allocate-round-keys key)) (declare (type aes-round-keys encryption-keys)) (let ((decryption-keys (copy-seq encryption-keys))) (generate-round-keys-for-decryption decryption-keys n-rounds) (setf (encryption-round-keys cipher) encryption-keys (decryption-round-keys cipher) decryption-keys (n-rounds cipher) n-rounds) cipher))) (defcipher aes (:encrypt-function aes-encrypt-block) (:decrypt-function aes-decrypt-block) (:block-length 16) (:key-length (:fixed 16 24 32)))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/ironclad-v0.47/src/ciphers/aes.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*- key sizes is supported. preferring to reload it at every reference, so a single large array scheme might not be the best for them (yet) going to notice? invert the order of the round keys the "optimized implementation" also had a fully unrolled version of this loop hanging around. it might be worthwhile to translate it and see if it actually gains us anything. a wizard would do this with a macro which allows one to easily switch between unrolled and non-unrolled versions. I am not a wizard. initial whitening apply last round and dump cipher state into the ciphertext initial whitening apply last round and dump cipher state into plaintext
aes.lisp -- implementation of the Rijndael block cipher Currently limited to 128 - bit block sizes , although the full range of (in-package :crypto) (in-ironclad-readtable) FIXME : is it work it to combine these into one large array and subscript into that rather than having separate arrays ? CMUCL and SBCL do n't seem to want to keep the constant in a register , (declaim (type (simple-array (unsigned-byte 32) (256)) Te0 Te1 Te2 Te3 Te4 Td0 Td1 Td2 Td3 Td4)) (defconst Te0 #32@(#xc66363a5 #xf87c7c84 #xee777799 #xf67b7b8d #xfff2f20d #xd66b6bbd #xde6f6fb1 #x91c5c554 #x60303050 #x02010103 #xce6767a9 #x562b2b7d #xe7fefe19 #xb5d7d762 #x4dababe6 #xec76769a #x8fcaca45 #x1f82829d #x89c9c940 #xfa7d7d87 #xeffafa15 #xb25959eb #x8e4747c9 #xfbf0f00b #x41adadec #xb3d4d467 #x5fa2a2fd #x45afafea #x239c9cbf #x53a4a4f7 #xe4727296 #x9bc0c05b #x75b7b7c2 #xe1fdfd1c #x3d9393ae #x4c26266a #x6c36365a #x7e3f3f41 #xf5f7f702 #x83cccc4f #x6834345c #x51a5a5f4 #xd1e5e534 #xf9f1f108 #xe2717193 #xabd8d873 #x62313153 #x2a15153f #x0804040c #x95c7c752 #x46232365 #x9dc3c35e #x30181828 #x379696a1 #x0a05050f #x2f9a9ab5 #x0e070709 #x24121236 #x1b80809b #xdfe2e23d #xcdebeb26 #x4e272769 #x7fb2b2cd #xea75759f #x1209091b #x1d83839e #x582c2c74 #x341a1a2e #x361b1b2d #xdc6e6eb2 #xb45a5aee #x5ba0a0fb #xa45252f6 #x763b3b4d #xb7d6d661 #x7db3b3ce #x5229297b #xdde3e33e #x5e2f2f71 #x13848497 #xa65353f5 #xb9d1d168 #x00000000 #xc1eded2c #x40202060 #xe3fcfc1f #x79b1b1c8 #xb65b5bed #xd46a6abe #x8dcbcb46 #x67bebed9 #x7239394b #x944a4ade #x984c4cd4 #xb05858e8 #x85cfcf4a #xbbd0d06b #xc5efef2a #x4faaaae5 #xedfbfb16 #x864343c5 #x9a4d4dd7 #x66333355 #x11858594 #x8a4545cf #xe9f9f910 #x04020206 #xfe7f7f81 #xa05050f0 #x783c3c44 #x259f9fba #x4ba8a8e3 #xa25151f3 #x5da3a3fe #x804040c0 #x058f8f8a #x3f9292ad #x219d9dbc #x70383848 #xf1f5f504 #x63bcbcdf #x77b6b6c1 #xafdada75 #x42212163 #x20101030 #xe5ffff1a #xfdf3f30e #xbfd2d26d #x81cdcd4c #x180c0c14 #x26131335 #xc3ecec2f #xbe5f5fe1 #x359797a2 #x884444cc #x2e171739 #x93c4c457 #x55a7a7f2 #xfc7e7e82 #x7a3d3d47 #xc86464ac #xba5d5de7 #x3219192b #xe6737395 #xc06060a0 #x19818198 #x9e4f4fd1 #xa3dcdc7f #x44222266 #x542a2a7e #x3b9090ab #x0b888883 #x8c4646ca #xc7eeee29 #x6bb8b8d3 #x2814143c #xa7dede79 #xbc5e5ee2 #x160b0b1d #xaddbdb76 #xdbe0e03b #x64323256 #x743a3a4e #x140a0a1e #x924949db #x0c06060a #x4824246c #xb85c5ce4 #x9fc2c25d #xbdd3d36e #x43acacef #xc46262a6 #x399191a8 #x319595a4 #xd3e4e437 #xf279798b #xd5e7e732 #x8bc8c843 #x6e373759 #xda6d6db7 #x018d8d8c #xb1d5d564 #x9c4e4ed2 #x49a9a9e0 #xd86c6cb4 #xac5656fa #xf3f4f407 #xcfeaea25 #xca6565af #xf47a7a8e #x47aeaee9 #x10080818 #x6fbabad5 #xf0787888 #x4a25256f #x5c2e2e72 #x381c1c24 #x57a6a6f1 #x73b4b4c7 #x97c6c651 #xcbe8e823 #xa1dddd7c #xe874749c #x3e1f1f21 #x964b4bdd #x61bdbddc #x0d8b8b86 #x0f8a8a85 #xe0707090 #x7c3e3e42 #x71b5b5c4 #xcc6666aa #x904848d8 #x06030305 #xf7f6f601 #x1c0e0e12 #xc26161a3 #x6a35355f #xae5757f9 #x69b9b9d0 #x17868691 #x99c1c158 #x3a1d1d27 #x279e9eb9 #xd9e1e138 #xebf8f813 #x2b9898b3 #x22111133 #xd26969bb #xa9d9d970 #x078e8e89 #x339494a7 #x2d9b9bb6 #x3c1e1e22 #x15878792 #xc9e9e920 #x87cece49 #xaa5555ff #x50282878 #xa5dfdf7a #x038c8c8f #x59a1a1f8 #x09898980 #x1a0d0d17 #x65bfbfda #xd7e6e631 #x844242c6 #xd06868b8 #x824141c3 #x299999b0 #x5a2d2d77 #x1e0f0f11 #x7bb0b0cb #xa85454fc #x6dbbbbd6 #x2c16163a)) (defconst Te1 #32@(#xa5c66363 #x84f87c7c #x99ee7777 #x8df67b7b #x0dfff2f2 #xbdd66b6b #xb1de6f6f #x5491c5c5 #x50603030 #x03020101 #xa9ce6767 #x7d562b2b #x19e7fefe #x62b5d7d7 #xe64dabab #x9aec7676 #x458fcaca #x9d1f8282 #x4089c9c9 #x87fa7d7d #x15effafa #xebb25959 #xc98e4747 #x0bfbf0f0 #xec41adad #x67b3d4d4 #xfd5fa2a2 #xea45afaf #xbf239c9c #xf753a4a4 #x96e47272 #x5b9bc0c0 #xc275b7b7 #x1ce1fdfd #xae3d9393 #x6a4c2626 #x5a6c3636 #x417e3f3f #x02f5f7f7 #x4f83cccc #x5c683434 #xf451a5a5 #x34d1e5e5 #x08f9f1f1 #x93e27171 #x73abd8d8 #x53623131 #x3f2a1515 #x0c080404 #x5295c7c7 #x65462323 #x5e9dc3c3 #x28301818 #xa1379696 #x0f0a0505 #xb52f9a9a #x090e0707 #x36241212 #x9b1b8080 #x3ddfe2e2 #x26cdebeb #x694e2727 #xcd7fb2b2 #x9fea7575 #x1b120909 #x9e1d8383 #x74582c2c #x2e341a1a #x2d361b1b #xb2dc6e6e #xeeb45a5a #xfb5ba0a0 #xf6a45252 #x4d763b3b #x61b7d6d6 #xce7db3b3 #x7b522929 #x3edde3e3 #x715e2f2f #x97138484 #xf5a65353 #x68b9d1d1 #x00000000 #x2cc1eded #x60402020 #x1fe3fcfc #xc879b1b1 #xedb65b5b #xbed46a6a #x468dcbcb #xd967bebe #x4b723939 #xde944a4a #xd4984c4c #xe8b05858 #x4a85cfcf #x6bbbd0d0 #x2ac5efef #xe54faaaa #x16edfbfb #xc5864343 #xd79a4d4d #x55663333 #x94118585 #xcf8a4545 #x10e9f9f9 #x06040202 #x81fe7f7f #xf0a05050 #x44783c3c #xba259f9f #xe34ba8a8 #xf3a25151 #xfe5da3a3 #xc0804040 #x8a058f8f #xad3f9292 #xbc219d9d #x48703838 #x04f1f5f5 #xdf63bcbc #xc177b6b6 #x75afdada #x63422121 #x30201010 #x1ae5ffff #x0efdf3f3 #x6dbfd2d2 #x4c81cdcd #x14180c0c #x35261313 #x2fc3ecec #xe1be5f5f #xa2359797 #xcc884444 #x392e1717 #x5793c4c4 #xf255a7a7 #x82fc7e7e #x477a3d3d #xacc86464 #xe7ba5d5d #x2b321919 #x95e67373 #xa0c06060 #x98198181 #xd19e4f4f #x7fa3dcdc #x66442222 #x7e542a2a #xab3b9090 #x830b8888 #xca8c4646 #x29c7eeee #xd36bb8b8 #x3c281414 #x79a7dede #xe2bc5e5e #x1d160b0b #x76addbdb #x3bdbe0e0 #x56643232 #x4e743a3a #x1e140a0a #xdb924949 #x0a0c0606 #x6c482424 #xe4b85c5c #x5d9fc2c2 #x6ebdd3d3 #xef43acac #xa6c46262 #xa8399191 #xa4319595 #x37d3e4e4 #x8bf27979 #x32d5e7e7 #x438bc8c8 #x596e3737 #xb7da6d6d #x8c018d8d #x64b1d5d5 #xd29c4e4e #xe049a9a9 #xb4d86c6c #xfaac5656 #x07f3f4f4 #x25cfeaea #xafca6565 #x8ef47a7a #xe947aeae #x18100808 #xd56fbaba #x88f07878 #x6f4a2525 #x725c2e2e #x24381c1c #xf157a6a6 #xc773b4b4 #x5197c6c6 #x23cbe8e8 #x7ca1dddd #x9ce87474 #x213e1f1f #xdd964b4b #xdc61bdbd #x860d8b8b #x850f8a8a #x90e07070 #x427c3e3e #xc471b5b5 #xaacc6666 #xd8904848 #x05060303 #x01f7f6f6 #x121c0e0e #xa3c26161 #x5f6a3535 #xf9ae5757 #xd069b9b9 #x91178686 #x5899c1c1 #x273a1d1d #xb9279e9e #x38d9e1e1 #x13ebf8f8 #xb32b9898 #x33221111 #xbbd26969 #x70a9d9d9 #x89078e8e #xa7339494 #xb62d9b9b #x223c1e1e #x92158787 #x20c9e9e9 #x4987cece #xffaa5555 #x78502828 #x7aa5dfdf #x8f038c8c #xf859a1a1 #x80098989 #x171a0d0d #xda65bfbf #x31d7e6e6 #xc6844242 #xb8d06868 #xc3824141 #xb0299999 #x775a2d2d #x111e0f0f #xcb7bb0b0 #xfca85454 #xd66dbbbb #x3a2c1616)) (defconst Te2 #32@(#x63a5c663 #x7c84f87c #x7799ee77 #x7b8df67b #xf20dfff2 #x6bbdd66b #x6fb1de6f #xc55491c5 #x30506030 #x01030201 #x67a9ce67 #x2b7d562b #xfe19e7fe #xd762b5d7 #xabe64dab #x769aec76 #xca458fca #x829d1f82 #xc94089c9 #x7d87fa7d #xfa15effa #x59ebb259 #x47c98e47 #xf00bfbf0 #xadec41ad #xd467b3d4 #xa2fd5fa2 #xafea45af #x9cbf239c #xa4f753a4 #x7296e472 #xc05b9bc0 #xb7c275b7 #xfd1ce1fd #x93ae3d93 #x266a4c26 #x365a6c36 #x3f417e3f #xf702f5f7 #xcc4f83cc #x345c6834 #xa5f451a5 #xe534d1e5 #xf108f9f1 #x7193e271 #xd873abd8 #x31536231 #x153f2a15 #x040c0804 #xc75295c7 #x23654623 #xc35e9dc3 #x18283018 #x96a13796 #x050f0a05 #x9ab52f9a #x07090e07 #x12362412 #x809b1b80 #xe23ddfe2 #xeb26cdeb #x27694e27 #xb2cd7fb2 #x759fea75 #x091b1209 #x839e1d83 #x2c74582c #x1a2e341a #x1b2d361b #x6eb2dc6e #x5aeeb45a #xa0fb5ba0 #x52f6a452 #x3b4d763b #xd661b7d6 #xb3ce7db3 #x297b5229 #xe33edde3 #x2f715e2f #x84971384 #x53f5a653 #xd168b9d1 #x00000000 #xed2cc1ed #x20604020 #xfc1fe3fc #xb1c879b1 #x5bedb65b #x6abed46a #xcb468dcb #xbed967be #x394b7239 #x4ade944a #x4cd4984c #x58e8b058 #xcf4a85cf #xd06bbbd0 #xef2ac5ef #xaae54faa #xfb16edfb #x43c58643 #x4dd79a4d #x33556633 #x85941185 #x45cf8a45 #xf910e9f9 #x02060402 #x7f81fe7f #x50f0a050 #x3c44783c #x9fba259f #xa8e34ba8 #x51f3a251 #xa3fe5da3 #x40c08040 #x8f8a058f #x92ad3f92 #x9dbc219d #x38487038 #xf504f1f5 #xbcdf63bc #xb6c177b6 #xda75afda #x21634221 #x10302010 #xff1ae5ff #xf30efdf3 #xd26dbfd2 #xcd4c81cd #x0c14180c #x13352613 #xec2fc3ec #x5fe1be5f #x97a23597 #x44cc8844 #x17392e17 #xc45793c4 #xa7f255a7 #x7e82fc7e #x3d477a3d #x64acc864 #x5de7ba5d #x192b3219 #x7395e673 #x60a0c060 #x81981981 #x4fd19e4f #xdc7fa3dc #x22664422 #x2a7e542a #x90ab3b90 #x88830b88 #x46ca8c46 #xee29c7ee #xb8d36bb8 #x143c2814 #xde79a7de #x5ee2bc5e #x0b1d160b #xdb76addb #xe03bdbe0 #x32566432 #x3a4e743a #x0a1e140a #x49db9249 #x060a0c06 #x246c4824 #x5ce4b85c #xc25d9fc2 #xd36ebdd3 #xacef43ac #x62a6c462 #x91a83991 #x95a43195 #xe437d3e4 #x798bf279 #xe732d5e7 #xc8438bc8 #x37596e37 #x6db7da6d #x8d8c018d #xd564b1d5 #x4ed29c4e #xa9e049a9 #x6cb4d86c #x56faac56 #xf407f3f4 #xea25cfea #x65afca65 #x7a8ef47a #xaee947ae #x08181008 #xbad56fba #x7888f078 #x256f4a25 #x2e725c2e #x1c24381c #xa6f157a6 #xb4c773b4 #xc65197c6 #xe823cbe8 #xdd7ca1dd #x749ce874 #x1f213e1f #x4bdd964b #xbddc61bd #x8b860d8b #x8a850f8a #x7090e070 #x3e427c3e #xb5c471b5 #x66aacc66 #x48d89048 #x03050603 #xf601f7f6 #x0e121c0e #x61a3c261 #x355f6a35 #x57f9ae57 #xb9d069b9 #x86911786 #xc15899c1 #x1d273a1d #x9eb9279e #xe138d9e1 #xf813ebf8 #x98b32b98 #x11332211 #x69bbd269 #xd970a9d9 #x8e89078e #x94a73394 #x9bb62d9b #x1e223c1e #x87921587 #xe920c9e9 #xce4987ce #x55ffaa55 #x28785028 #xdf7aa5df #x8c8f038c #xa1f859a1 #x89800989 #x0d171a0d #xbfda65bf #xe631d7e6 #x42c68442 #x68b8d068 #x41c38241 #x99b02999 #x2d775a2d #x0f111e0f #xb0cb7bb0 #x54fca854 #xbbd66dbb #x163a2c16)) (defconst Te3 #32@(#x6363a5c6 #x7c7c84f8 #x777799ee #x7b7b8df6 #xf2f20dff #x6b6bbdd6 #x6f6fb1de #xc5c55491 #x30305060 #x01010302 #x6767a9ce #x2b2b7d56 #xfefe19e7 #xd7d762b5 #xababe64d #x76769aec #xcaca458f #x82829d1f #xc9c94089 #x7d7d87fa #xfafa15ef #x5959ebb2 #x4747c98e #xf0f00bfb #xadadec41 #xd4d467b3 #xa2a2fd5f #xafafea45 #x9c9cbf23 #xa4a4f753 #x727296e4 #xc0c05b9b #xb7b7c275 #xfdfd1ce1 #x9393ae3d #x26266a4c #x36365a6c #x3f3f417e #xf7f702f5 #xcccc4f83 #x34345c68 #xa5a5f451 #xe5e534d1 #xf1f108f9 #x717193e2 #xd8d873ab #x31315362 #x15153f2a #x04040c08 #xc7c75295 #x23236546 #xc3c35e9d #x18182830 #x9696a137 #x05050f0a #x9a9ab52f #x0707090e #x12123624 #x80809b1b #xe2e23ddf #xebeb26cd #x2727694e #xb2b2cd7f #x75759fea #x09091b12 #x83839e1d #x2c2c7458 #x1a1a2e34 #x1b1b2d36 #x6e6eb2dc #x5a5aeeb4 #xa0a0fb5b #x5252f6a4 #x3b3b4d76 #xd6d661b7 #xb3b3ce7d #x29297b52 #xe3e33edd #x2f2f715e #x84849713 #x5353f5a6 #xd1d168b9 #x00000000 #xeded2cc1 #x20206040 #xfcfc1fe3 #xb1b1c879 #x5b5bedb6 #x6a6abed4 #xcbcb468d #xbebed967 #x39394b72 #x4a4ade94 #x4c4cd498 #x5858e8b0 #xcfcf4a85 #xd0d06bbb #xefef2ac5 #xaaaae54f #xfbfb16ed #x4343c586 #x4d4dd79a #x33335566 #x85859411 #x4545cf8a #xf9f910e9 #x02020604 #x7f7f81fe #x5050f0a0 #x3c3c4478 #x9f9fba25 #xa8a8e34b #x5151f3a2 #xa3a3fe5d #x4040c080 #x8f8f8a05 #x9292ad3f #x9d9dbc21 #x38384870 #xf5f504f1 #xbcbcdf63 #xb6b6c177 #xdada75af #x21216342 #x10103020 #xffff1ae5 #xf3f30efd #xd2d26dbf #xcdcd4c81 #x0c0c1418 #x13133526 #xecec2fc3 #x5f5fe1be #x9797a235 #x4444cc88 #x1717392e #xc4c45793 #xa7a7f255 #x7e7e82fc #x3d3d477a #x6464acc8 #x5d5de7ba #x19192b32 #x737395e6 #x6060a0c0 #x81819819 #x4f4fd19e #xdcdc7fa3 #x22226644 #x2a2a7e54 #x9090ab3b #x8888830b #x4646ca8c #xeeee29c7 #xb8b8d36b #x14143c28 #xdede79a7 #x5e5ee2bc #x0b0b1d16 #xdbdb76ad #xe0e03bdb #x32325664 #x3a3a4e74 #x0a0a1e14 #x4949db92 #x06060a0c #x24246c48 #x5c5ce4b8 #xc2c25d9f #xd3d36ebd #xacacef43 #x6262a6c4 #x9191a839 #x9595a431 #xe4e437d3 #x79798bf2 #xe7e732d5 #xc8c8438b #x3737596e #x6d6db7da #x8d8d8c01 #xd5d564b1 #x4e4ed29c #xa9a9e049 #x6c6cb4d8 #x5656faac #xf4f407f3 #xeaea25cf #x6565afca #x7a7a8ef4 #xaeaee947 #x08081810 #xbabad56f #x787888f0 #x25256f4a #x2e2e725c #x1c1c2438 #xa6a6f157 #xb4b4c773 #xc6c65197 #xe8e823cb #xdddd7ca1 #x74749ce8 #x1f1f213e #x4b4bdd96 #xbdbddc61 #x8b8b860d #x8a8a850f #x707090e0 #x3e3e427c #xb5b5c471 #x6666aacc #x4848d890 #x03030506 #xf6f601f7 #x0e0e121c #x6161a3c2 #x35355f6a #x5757f9ae #xb9b9d069 #x86869117 #xc1c15899 #x1d1d273a #x9e9eb927 #xe1e138d9 #xf8f813eb #x9898b32b #x11113322 #x6969bbd2 #xd9d970a9 #x8e8e8907 #x9494a733 #x9b9bb62d #x1e1e223c #x87879215 #xe9e920c9 #xcece4987 #x5555ffaa #x28287850 #xdfdf7aa5 #x8c8c8f03 #xa1a1f859 #x89898009 #x0d0d171a #xbfbfda65 #xe6e631d7 #x4242c684 #x6868b8d0 #x4141c382 #x9999b029 #x2d2d775a #x0f0f111e #xb0b0cb7b #x5454fca8 #xbbbbd66d #x16163a2c)) (defconst Te4 #32@(#x63636363 #x7c7c7c7c #x77777777 #x7b7b7b7b #xf2f2f2f2 #x6b6b6b6b #x6f6f6f6f #xc5c5c5c5 #x30303030 #x01010101 #x67676767 #x2b2b2b2b #xfefefefe #xd7d7d7d7 #xabababab #x76767676 #xcacacaca #x82828282 #xc9c9c9c9 #x7d7d7d7d #xfafafafa #x59595959 #x47474747 #xf0f0f0f0 #xadadadad #xd4d4d4d4 #xa2a2a2a2 #xafafafaf #x9c9c9c9c #xa4a4a4a4 #x72727272 #xc0c0c0c0 #xb7b7b7b7 #xfdfdfdfd #x93939393 #x26262626 #x36363636 #x3f3f3f3f #xf7f7f7f7 #xcccccccc #x34343434 #xa5a5a5a5 #xe5e5e5e5 #xf1f1f1f1 #x71717171 #xd8d8d8d8 #x31313131 #x15151515 #x04040404 #xc7c7c7c7 #x23232323 #xc3c3c3c3 #x18181818 #x96969696 #x05050505 #x9a9a9a9a #x07070707 #x12121212 #x80808080 #xe2e2e2e2 #xebebebeb #x27272727 #xb2b2b2b2 #x75757575 #x09090909 #x83838383 #x2c2c2c2c #x1a1a1a1a #x1b1b1b1b #x6e6e6e6e #x5a5a5a5a #xa0a0a0a0 #x52525252 #x3b3b3b3b #xd6d6d6d6 #xb3b3b3b3 #x29292929 #xe3e3e3e3 #x2f2f2f2f #x84848484 #x53535353 #xd1d1d1d1 #x00000000 #xedededed #x20202020 #xfcfcfcfc #xb1b1b1b1 #x5b5b5b5b #x6a6a6a6a #xcbcbcbcb #xbebebebe #x39393939 #x4a4a4a4a #x4c4c4c4c #x58585858 #xcfcfcfcf #xd0d0d0d0 #xefefefef #xaaaaaaaa #xfbfbfbfb #x43434343 #x4d4d4d4d #x33333333 #x85858585 #x45454545 #xf9f9f9f9 #x02020202 #x7f7f7f7f #x50505050 #x3c3c3c3c #x9f9f9f9f #xa8a8a8a8 #x51515151 #xa3a3a3a3 #x40404040 #x8f8f8f8f #x92929292 #x9d9d9d9d #x38383838 #xf5f5f5f5 #xbcbcbcbc #xb6b6b6b6 #xdadadada #x21212121 #x10101010 #xffffffff #xf3f3f3f3 #xd2d2d2d2 #xcdcdcdcd #x0c0c0c0c #x13131313 #xecececec #x5f5f5f5f #x97979797 #x44444444 #x17171717 #xc4c4c4c4 #xa7a7a7a7 #x7e7e7e7e #x3d3d3d3d #x64646464 #x5d5d5d5d #x19191919 #x73737373 #x60606060 #x81818181 #x4f4f4f4f #xdcdcdcdc #x22222222 #x2a2a2a2a #x90909090 #x88888888 #x46464646 #xeeeeeeee #xb8b8b8b8 #x14141414 #xdededede #x5e5e5e5e #x0b0b0b0b #xdbdbdbdb #xe0e0e0e0 #x32323232 #x3a3a3a3a #x0a0a0a0a #x49494949 #x06060606 #x24242424 #x5c5c5c5c #xc2c2c2c2 #xd3d3d3d3 #xacacacac #x62626262 #x91919191 #x95959595 #xe4e4e4e4 #x79797979 #xe7e7e7e7 #xc8c8c8c8 #x37373737 #x6d6d6d6d #x8d8d8d8d #xd5d5d5d5 #x4e4e4e4e #xa9a9a9a9 #x6c6c6c6c #x56565656 #xf4f4f4f4 #xeaeaeaea #x65656565 #x7a7a7a7a #xaeaeaeae #x08080808 #xbabababa #x78787878 #x25252525 #x2e2e2e2e #x1c1c1c1c #xa6a6a6a6 #xb4b4b4b4 #xc6c6c6c6 #xe8e8e8e8 #xdddddddd #x74747474 #x1f1f1f1f #x4b4b4b4b #xbdbdbdbd #x8b8b8b8b #x8a8a8a8a #x70707070 #x3e3e3e3e #xb5b5b5b5 #x66666666 #x48484848 #x03030303 #xf6f6f6f6 #x0e0e0e0e #x61616161 #x35353535 #x57575757 #xb9b9b9b9 #x86868686 #xc1c1c1c1 #x1d1d1d1d #x9e9e9e9e #xe1e1e1e1 #xf8f8f8f8 #x98989898 #x11111111 #x69696969 #xd9d9d9d9 #x8e8e8e8e #x94949494 #x9b9b9b9b #x1e1e1e1e #x87878787 #xe9e9e9e9 #xcececece #x55555555 #x28282828 #xdfdfdfdf #x8c8c8c8c #xa1a1a1a1 #x89898989 #x0d0d0d0d #xbfbfbfbf #xe6e6e6e6 #x42424242 #x68686868 #x41414141 #x99999999 #x2d2d2d2d #x0f0f0f0f #xb0b0b0b0 #x54545454 #xbbbbbbbb #x16161616)) (defconst Td0 #32@(#x51f4a750 #x7e416553 #x1a17a4c3 #x3a275e96 #x3bab6bcb #x1f9d45f1 #xacfa58ab #x4be30393 #x2030fa55 #xad766df6 #x88cc7691 #xf5024c25 #x4fe5d7fc #xc52acbd7 #x26354480 #xb562a38f #xdeb15a49 #x25ba1b67 #x45ea0e98 #x5dfec0e1 #xc32f7502 #x814cf012 #x8d4697a3 #x6bd3f9c6 #x038f5fe7 #x15929c95 #xbf6d7aeb #x955259da #xd4be832d #x587421d3 #x49e06929 #x8ec9c844 #x75c2896a #xf48e7978 #x99583e6b #x27b971dd #xbee14fb6 #xf088ad17 #xc920ac66 #x7dce3ab4 #x63df4a18 #xe51a3182 #x97513360 #x62537f45 #xb16477e0 #xbb6bae84 #xfe81a01c #xf9082b94 #x70486858 #x8f45fd19 #x94de6c87 #x527bf8b7 #xab73d323 #x724b02e2 #xe31f8f57 #x6655ab2a #xb2eb2807 #x2fb5c203 #x86c57b9a #xd33708a5 #x302887f2 #x23bfa5b2 #x02036aba #xed16825c #x8acf1c2b #xa779b492 #xf307f2f0 #x4e69e2a1 #x65daf4cd #x0605bed5 #xd134621f #xc4a6fe8a #x342e539d #xa2f355a0 #x058ae132 #xa4f6eb75 #x0b83ec39 #x4060efaa #x5e719f06 #xbd6e1051 #x3e218af9 #x96dd063d #xdd3e05ae #x4de6bd46 #x91548db5 #x71c45d05 #x0406d46f #x605015ff #x1998fb24 #xd6bde997 #x894043cc #x67d99e77 #xb0e842bd #x07898b88 #xe7195b38 #x79c8eedb #xa17c0a47 #x7c420fe9 #xf8841ec9 #x00000000 #x09808683 #x322bed48 #x1e1170ac #x6c5a724e #xfd0efffb #x0f853856 #x3daed51e #x362d3927 #x0a0fd964 #x685ca621 #x9b5b54d1 #x24362e3a #x0c0a67b1 #x9357e70f #xb4ee96d2 #x1b9b919e #x80c0c54f #x61dc20a2 #x5a774b69 #x1c121a16 #xe293ba0a #xc0a02ae5 #x3c22e043 #x121b171d #x0e090d0b #xf28bc7ad #x2db6a8b9 #x141ea9c8 #x57f11985 #xaf75074c #xee99ddbb #xa37f60fd #xf701269f #x5c72f5bc #x44663bc5 #x5bfb7e34 #x8b432976 #xcb23c6dc #xb6edfc68 #xb8e4f163 #xd731dcca #x42638510 #x13972240 #x84c61120 #x854a247d #xd2bb3df8 #xaef93211 #xc729a16d #x1d9e2f4b #xdcb230f3 #x0d8652ec #x77c1e3d0 #x2bb3166c #xa970b999 #x119448fa #x47e96422 #xa8fc8cc4 #xa0f03f1a #x567d2cd8 #x223390ef #x87494ec7 #xd938d1c1 #x8ccaa2fe #x98d40b36 #xa6f581cf #xa57ade28 #xdab78e26 #x3fadbfa4 #x2c3a9de4 #x5078920d #x6a5fcc9b #x547e4662 #xf68d13c2 #x90d8b8e8 #x2e39f75e #x82c3aff5 #x9f5d80be #x69d0937c #x6fd52da9 #xcf2512b3 #xc8ac993b #x10187da7 #xe89c636e #xdb3bbb7b #xcd267809 #x6e5918f4 #xec9ab701 #x834f9aa8 #xe6956e65 #xaaffe67e #x21bccf08 #xef15e8e6 #xbae79bd9 #x4a6f36ce #xea9f09d4 #x29b07cd6 #x31a4b2af #x2a3f2331 #xc6a59430 #x35a266c0 #x744ebc37 #xfc82caa6 #xe090d0b0 #x33a7d815 #xf104984a #x41ecdaf7 #x7fcd500e #x1791f62f #x764dd68d #x43efb04d #xccaa4d54 #xe49604df #x9ed1b5e3 #x4c6a881b #xc12c1fb8 #x4665517f #x9d5eea04 #x018c355d #xfa877473 #xfb0b412e #xb3671d5a #x92dbd252 #xe9105633 #x6dd64713 #x9ad7618c #x37a10c7a #x59f8148e #xeb133c89 #xcea927ee #xb761c935 #xe11ce5ed #x7a47b13c #x9cd2df59 #x55f2733f #x1814ce79 #x73c737bf #x53f7cdea #x5ffdaa5b #xdf3d6f14 #x7844db86 #xcaaff381 #xb968c43e #x3824342c #xc2a3405f #x161dc372 #xbce2250c #x283c498b #xff0d9541 #x39a80171 #x080cb3de #xd8b4e49c #x6456c190 #x7bcb8461 #xd532b670 #x486c5c74 #xd0b85742)) (defconst Td1 #32@(#x5051f4a7 #x537e4165 #xc31a17a4 #x963a275e #xcb3bab6b #xf11f9d45 #xabacfa58 #x934be303 #x552030fa #xf6ad766d #x9188cc76 #x25f5024c #xfc4fe5d7 #xd7c52acb #x80263544 #x8fb562a3 #x49deb15a #x6725ba1b #x9845ea0e #xe15dfec0 #x02c32f75 #x12814cf0 #xa38d4697 #xc66bd3f9 #xe7038f5f #x9515929c #xebbf6d7a #xda955259 #x2dd4be83 #xd3587421 #x2949e069 #x448ec9c8 #x6a75c289 #x78f48e79 #x6b99583e #xdd27b971 #xb6bee14f #x17f088ad #x66c920ac #xb47dce3a #x1863df4a #x82e51a31 #x60975133 #x4562537f #xe0b16477 #x84bb6bae #x1cfe81a0 #x94f9082b #x58704868 #x198f45fd #x8794de6c #xb7527bf8 #x23ab73d3 #xe2724b02 #x57e31f8f #x2a6655ab #x07b2eb28 #x032fb5c2 #x9a86c57b #xa5d33708 #xf2302887 #xb223bfa5 #xba02036a #x5ced1682 #x2b8acf1c #x92a779b4 #xf0f307f2 #xa14e69e2 #xcd65daf4 #xd50605be #x1fd13462 #x8ac4a6fe #x9d342e53 #xa0a2f355 #x32058ae1 #x75a4f6eb #x390b83ec #xaa4060ef #x065e719f #x51bd6e10 #xf93e218a #x3d96dd06 #xaedd3e05 #x464de6bd #xb591548d #x0571c45d #x6f0406d4 #xff605015 #x241998fb #x97d6bde9 #xcc894043 #x7767d99e #xbdb0e842 #x8807898b #x38e7195b #xdb79c8ee #x47a17c0a #xe97c420f #xc9f8841e #x00000000 #x83098086 #x48322bed #xac1e1170 #x4e6c5a72 #xfbfd0eff #x560f8538 #x1e3daed5 #x27362d39 #x640a0fd9 #x21685ca6 #xd19b5b54 #x3a24362e #xb10c0a67 #x0f9357e7 #xd2b4ee96 #x9e1b9b91 #x4f80c0c5 #xa261dc20 #x695a774b #x161c121a #x0ae293ba #xe5c0a02a #x433c22e0 #x1d121b17 #x0b0e090d #xadf28bc7 #xb92db6a8 #xc8141ea9 #x8557f119 #x4caf7507 #xbbee99dd #xfda37f60 #x9ff70126 #xbc5c72f5 #xc544663b #x345bfb7e #x768b4329 #xdccb23c6 #x68b6edfc #x63b8e4f1 #xcad731dc #x10426385 #x40139722 #x2084c611 #x7d854a24 #xf8d2bb3d #x11aef932 #x6dc729a1 #x4b1d9e2f #xf3dcb230 #xec0d8652 #xd077c1e3 #x6c2bb316 #x99a970b9 #xfa119448 #x2247e964 #xc4a8fc8c #x1aa0f03f #xd8567d2c #xef223390 #xc787494e #xc1d938d1 #xfe8ccaa2 #x3698d40b #xcfa6f581 #x28a57ade #x26dab78e #xa43fadbf #xe42c3a9d #x0d507892 #x9b6a5fcc #x62547e46 #xc2f68d13 #xe890d8b8 #x5e2e39f7 #xf582c3af #xbe9f5d80 #x7c69d093 #xa96fd52d #xb3cf2512 #x3bc8ac99 #xa710187d #x6ee89c63 #x7bdb3bbb #x09cd2678 #xf46e5918 #x01ec9ab7 #xa8834f9a #x65e6956e #x7eaaffe6 #x0821bccf #xe6ef15e8 #xd9bae79b #xce4a6f36 #xd4ea9f09 #xd629b07c #xaf31a4b2 #x312a3f23 #x30c6a594 #xc035a266 #x37744ebc #xa6fc82ca #xb0e090d0 #x1533a7d8 #x4af10498 #xf741ecda #x0e7fcd50 #x2f1791f6 #x8d764dd6 #x4d43efb0 #x54ccaa4d #xdfe49604 #xe39ed1b5 #x1b4c6a88 #xb8c12c1f #x7f466551 #x049d5eea #x5d018c35 #x73fa8774 #x2efb0b41 #x5ab3671d #x5292dbd2 #x33e91056 #x136dd647 #x8c9ad761 #x7a37a10c #x8e59f814 #x89eb133c #xeecea927 #x35b761c9 #xede11ce5 #x3c7a47b1 #x599cd2df #x3f55f273 #x791814ce #xbf73c737 #xea53f7cd #x5b5ffdaa #x14df3d6f #x867844db #x81caaff3 #x3eb968c4 #x2c382434 #x5fc2a340 #x72161dc3 #x0cbce225 #x8b283c49 #x41ff0d95 #x7139a801 #xde080cb3 #x9cd8b4e4 #x906456c1 #x617bcb84 #x70d532b6 #x74486c5c #x42d0b857)) (defconst Td2 #32@(#xa75051f4 #x65537e41 #xa4c31a17 #x5e963a27 #x6bcb3bab #x45f11f9d #x58abacfa #x03934be3 #xfa552030 #x6df6ad76 #x769188cc #x4c25f502 #xd7fc4fe5 #xcbd7c52a #x44802635 #xa38fb562 #x5a49deb1 #x1b6725ba #x0e9845ea #xc0e15dfe #x7502c32f #xf012814c #x97a38d46 #xf9c66bd3 #x5fe7038f #x9c951592 #x7aebbf6d #x59da9552 #x832dd4be #x21d35874 #x692949e0 #xc8448ec9 #x896a75c2 #x7978f48e #x3e6b9958 #x71dd27b9 #x4fb6bee1 #xad17f088 #xac66c920 #x3ab47dce #x4a1863df #x3182e51a #x33609751 #x7f456253 #x77e0b164 #xae84bb6b #xa01cfe81 #x2b94f908 #x68587048 #xfd198f45 #x6c8794de #xf8b7527b #xd323ab73 #x02e2724b #x8f57e31f #xab2a6655 #x2807b2eb #xc2032fb5 #x7b9a86c5 #x08a5d337 #x87f23028 #xa5b223bf #x6aba0203 #x825ced16 #x1c2b8acf #xb492a779 #xf2f0f307 #xe2a14e69 #xf4cd65da #xbed50605 #x621fd134 #xfe8ac4a6 #x539d342e #x55a0a2f3 #xe132058a #xeb75a4f6 #xec390b83 #xefaa4060 #x9f065e71 #x1051bd6e #x8af93e21 #x063d96dd #x05aedd3e #xbd464de6 #x8db59154 #x5d0571c4 #xd46f0406 #x15ff6050 #xfb241998 #xe997d6bd #x43cc8940 #x9e7767d9 #x42bdb0e8 #x8b880789 #x5b38e719 #xeedb79c8 #x0a47a17c #x0fe97c42 #x1ec9f884 #x00000000 #x86830980 #xed48322b #x70ac1e11 #x724e6c5a #xfffbfd0e #x38560f85 #xd51e3dae #x3927362d #xd9640a0f #xa621685c #x54d19b5b #x2e3a2436 #x67b10c0a #xe70f9357 #x96d2b4ee #x919e1b9b #xc54f80c0 #x20a261dc #x4b695a77 #x1a161c12 #xba0ae293 #x2ae5c0a0 #xe0433c22 #x171d121b #x0d0b0e09 #xc7adf28b #xa8b92db6 #xa9c8141e #x198557f1 #x074caf75 #xddbbee99 #x60fda37f #x269ff701 #xf5bc5c72 #x3bc54466 #x7e345bfb #x29768b43 #xc6dccb23 #xfc68b6ed #xf163b8e4 #xdccad731 #x85104263 #x22401397 #x112084c6 #x247d854a #x3df8d2bb #x3211aef9 #xa16dc729 #x2f4b1d9e #x30f3dcb2 #x52ec0d86 #xe3d077c1 #x166c2bb3 #xb999a970 #x48fa1194 #x642247e9 #x8cc4a8fc #x3f1aa0f0 #x2cd8567d #x90ef2233 #x4ec78749 #xd1c1d938 #xa2fe8cca #x0b3698d4 #x81cfa6f5 #xde28a57a #x8e26dab7 #xbfa43fad #x9de42c3a #x920d5078 #xcc9b6a5f #x4662547e #x13c2f68d #xb8e890d8 #xf75e2e39 #xaff582c3 #x80be9f5d #x937c69d0 #x2da96fd5 #x12b3cf25 #x993bc8ac #x7da71018 #x636ee89c #xbb7bdb3b #x7809cd26 #x18f46e59 #xb701ec9a #x9aa8834f #x6e65e695 #xe67eaaff #xcf0821bc #xe8e6ef15 #x9bd9bae7 #x36ce4a6f #x09d4ea9f #x7cd629b0 #xb2af31a4 #x23312a3f #x9430c6a5 #x66c035a2 #xbc37744e #xcaa6fc82 #xd0b0e090 #xd81533a7 #x984af104 #xdaf741ec #x500e7fcd #xf62f1791 #xd68d764d #xb04d43ef #x4d54ccaa #x04dfe496 #xb5e39ed1 #x881b4c6a #x1fb8c12c #x517f4665 #xea049d5e #x355d018c #x7473fa87 #x412efb0b #x1d5ab367 #xd25292db #x5633e910 #x47136dd6 #x618c9ad7 #x0c7a37a1 #x148e59f8 #x3c89eb13 #x27eecea9 #xc935b761 #xe5ede11c #xb13c7a47 #xdf599cd2 #x733f55f2 #xce791814 #x37bf73c7 #xcdea53f7 #xaa5b5ffd #x6f14df3d #xdb867844 #xf381caaf #xc43eb968 #x342c3824 #x405fc2a3 #xc372161d #x250cbce2 #x498b283c #x9541ff0d #x017139a8 #xb3de080c #xe49cd8b4 #xc1906456 #x84617bcb #xb670d532 #x5c74486c #x5742d0b8)) (defconst Td3 #32@(#xf4a75051 #x4165537e #x17a4c31a #x275e963a #xab6bcb3b #x9d45f11f #xfa58abac #xe303934b #x30fa5520 #x766df6ad #xcc769188 #x024c25f5 #xe5d7fc4f #x2acbd7c5 #x35448026 #x62a38fb5 #xb15a49de #xba1b6725 #xea0e9845 #xfec0e15d #x2f7502c3 #x4cf01281 #x4697a38d #xd3f9c66b #x8f5fe703 #x929c9515 #x6d7aebbf #x5259da95 #xbe832dd4 #x7421d358 #xe0692949 #xc9c8448e #xc2896a75 #x8e7978f4 #x583e6b99 #xb971dd27 #xe14fb6be #x88ad17f0 #x20ac66c9 #xce3ab47d #xdf4a1863 #x1a3182e5 #x51336097 #x537f4562 #x6477e0b1 #x6bae84bb #x81a01cfe #x082b94f9 #x48685870 #x45fd198f #xde6c8794 #x7bf8b752 #x73d323ab #x4b02e272 #x1f8f57e3 #x55ab2a66 #xeb2807b2 #xb5c2032f #xc57b9a86 #x3708a5d3 #x2887f230 #xbfa5b223 #x036aba02 #x16825ced #xcf1c2b8a #x79b492a7 #x07f2f0f3 #x69e2a14e #xdaf4cd65 #x05bed506 #x34621fd1 #xa6fe8ac4 #x2e539d34 #xf355a0a2 #x8ae13205 #xf6eb75a4 #x83ec390b #x60efaa40 #x719f065e #x6e1051bd #x218af93e #xdd063d96 #x3e05aedd #xe6bd464d #x548db591 #xc45d0571 #x06d46f04 #x5015ff60 #x98fb2419 #xbde997d6 #x4043cc89 #xd99e7767 #xe842bdb0 #x898b8807 #x195b38e7 #xc8eedb79 #x7c0a47a1 #x420fe97c #x841ec9f8 #x00000000 #x80868309 #x2bed4832 #x1170ac1e #x5a724e6c #x0efffbfd #x8538560f #xaed51e3d #x2d392736 #x0fd9640a #x5ca62168 #x5b54d19b #x362e3a24 #x0a67b10c #x57e70f93 #xee96d2b4 #x9b919e1b #xc0c54f80 #xdc20a261 #x774b695a #x121a161c #x93ba0ae2 #xa02ae5c0 #x22e0433c #x1b171d12 #x090d0b0e #x8bc7adf2 #xb6a8b92d #x1ea9c814 #xf1198557 #x75074caf #x99ddbbee #x7f60fda3 #x01269ff7 #x72f5bc5c #x663bc544 #xfb7e345b #x4329768b #x23c6dccb #xedfc68b6 #xe4f163b8 #x31dccad7 #x63851042 #x97224013 #xc6112084 #x4a247d85 #xbb3df8d2 #xf93211ae #x29a16dc7 #x9e2f4b1d #xb230f3dc #x8652ec0d #xc1e3d077 #xb3166c2b #x70b999a9 #x9448fa11 #xe9642247 #xfc8cc4a8 #xf03f1aa0 #x7d2cd856 #x3390ef22 #x494ec787 #x38d1c1d9 #xcaa2fe8c #xd40b3698 #xf581cfa6 #x7ade28a5 #xb78e26da #xadbfa43f #x3a9de42c #x78920d50 #x5fcc9b6a #x7e466254 #x8d13c2f6 #xd8b8e890 #x39f75e2e #xc3aff582 #x5d80be9f #xd0937c69 #xd52da96f #x2512b3cf #xac993bc8 #x187da710 #x9c636ee8 #x3bbb7bdb #x267809cd #x5918f46e #x9ab701ec #x4f9aa883 #x956e65e6 #xffe67eaa #xbccf0821 #x15e8e6ef #xe79bd9ba #x6f36ce4a #x9f09d4ea #xb07cd629 #xa4b2af31 #x3f23312a #xa59430c6 #xa266c035 #x4ebc3774 #x82caa6fc #x90d0b0e0 #xa7d81533 #x04984af1 #xecdaf741 #xcd500e7f #x91f62f17 #x4dd68d76 #xefb04d43 #xaa4d54cc #x9604dfe4 #xd1b5e39e #x6a881b4c #x2c1fb8c1 #x65517f46 #x5eea049d #x8c355d01 #x877473fa #x0b412efb #x671d5ab3 #xdbd25292 #x105633e9 #xd647136d #xd7618c9a #xa10c7a37 #xf8148e59 #x133c89eb #xa927eece #x61c935b7 #x1ce5ede1 #x47b13c7a #xd2df599c #xf2733f55 #x14ce7918 #xc737bf73 #xf7cdea53 #xfdaa5b5f #x3d6f14df #x44db8678 #xaff381ca #x68c43eb9 #x24342c38 #xa3405fc2 #x1dc37216 #xe2250cbc #x3c498b28 #x0d9541ff #xa8017139 #x0cb3de08 #xb4e49cd8 #x56c19064 #xcb84617b #x32b670d5 #x6c5c7448 #xb85742d0)) (defconst Td4 #32@(#x52525252 #x09090909 #x6a6a6a6a #xd5d5d5d5 #x30303030 #x36363636 #xa5a5a5a5 #x38383838 #xbfbfbfbf #x40404040 #xa3a3a3a3 #x9e9e9e9e #x81818181 #xf3f3f3f3 #xd7d7d7d7 #xfbfbfbfb #x7c7c7c7c #xe3e3e3e3 #x39393939 #x82828282 #x9b9b9b9b #x2f2f2f2f #xffffffff #x87878787 #x34343434 #x8e8e8e8e #x43434343 #x44444444 #xc4c4c4c4 #xdededede #xe9e9e9e9 #xcbcbcbcb #x54545454 #x7b7b7b7b #x94949494 #x32323232 #xa6a6a6a6 #xc2c2c2c2 #x23232323 #x3d3d3d3d #xeeeeeeee #x4c4c4c4c #x95959595 #x0b0b0b0b #x42424242 #xfafafafa #xc3c3c3c3 #x4e4e4e4e #x08080808 #x2e2e2e2e #xa1a1a1a1 #x66666666 #x28282828 #xd9d9d9d9 #x24242424 #xb2b2b2b2 #x76767676 #x5b5b5b5b #xa2a2a2a2 #x49494949 #x6d6d6d6d #x8b8b8b8b #xd1d1d1d1 #x25252525 #x72727272 #xf8f8f8f8 #xf6f6f6f6 #x64646464 #x86868686 #x68686868 #x98989898 #x16161616 #xd4d4d4d4 #xa4a4a4a4 #x5c5c5c5c #xcccccccc #x5d5d5d5d #x65656565 #xb6b6b6b6 #x92929292 #x6c6c6c6c #x70707070 #x48484848 #x50505050 #xfdfdfdfd #xedededed #xb9b9b9b9 #xdadadada #x5e5e5e5e #x15151515 #x46464646 #x57575757 #xa7a7a7a7 #x8d8d8d8d #x9d9d9d9d #x84848484 #x90909090 #xd8d8d8d8 #xabababab #x00000000 #x8c8c8c8c #xbcbcbcbc #xd3d3d3d3 #x0a0a0a0a #xf7f7f7f7 #xe4e4e4e4 #x58585858 #x05050505 #xb8b8b8b8 #xb3b3b3b3 #x45454545 #x06060606 #xd0d0d0d0 #x2c2c2c2c #x1e1e1e1e #x8f8f8f8f #xcacacaca #x3f3f3f3f #x0f0f0f0f #x02020202 #xc1c1c1c1 #xafafafaf #xbdbdbdbd #x03030303 #x01010101 #x13131313 #x8a8a8a8a #x6b6b6b6b #x3a3a3a3a #x91919191 #x11111111 #x41414141 #x4f4f4f4f #x67676767 #xdcdcdcdc #xeaeaeaea #x97979797 #xf2f2f2f2 #xcfcfcfcf #xcececece #xf0f0f0f0 #xb4b4b4b4 #xe6e6e6e6 #x73737373 #x96969696 #xacacacac #x74747474 #x22222222 #xe7e7e7e7 #xadadadad #x35353535 #x85858585 #xe2e2e2e2 #xf9f9f9f9 #x37373737 #xe8e8e8e8 #x1c1c1c1c #x75757575 #xdfdfdfdf #x6e6e6e6e #x47474747 #xf1f1f1f1 #x1a1a1a1a #x71717171 #x1d1d1d1d #x29292929 #xc5c5c5c5 #x89898989 #x6f6f6f6f #xb7b7b7b7 #x62626262 #x0e0e0e0e #xaaaaaaaa #x18181818 #xbebebebe #x1b1b1b1b #xfcfcfcfc #x56565656 #x3e3e3e3e #x4b4b4b4b #xc6c6c6c6 #xd2d2d2d2 #x79797979 #x20202020 #x9a9a9a9a #xdbdbdbdb #xc0c0c0c0 #xfefefefe #x78787878 #xcdcdcdcd #x5a5a5a5a #xf4f4f4f4 #x1f1f1f1f #xdddddddd #xa8a8a8a8 #x33333333 #x88888888 #x07070707 #xc7c7c7c7 #x31313131 #xb1b1b1b1 #x12121212 #x10101010 #x59595959 #x27272727 #x80808080 #xecececec #x5f5f5f5f #x60606060 #x51515151 #x7f7f7f7f #xa9a9a9a9 #x19191919 #xb5b5b5b5 #x4a4a4a4a #x0d0d0d0d #x2d2d2d2d #xe5e5e5e5 #x7a7a7a7a #x9f9f9f9f #x93939393 #xc9c9c9c9 #x9c9c9c9c #xefefefef #xa0a0a0a0 #xe0e0e0e0 #x3b3b3b3b #x4d4d4d4d #xaeaeaeae #x2a2a2a2a #xf5f5f5f5 #xb0b0b0b0 #xc8c8c8c8 #xebebebeb #xbbbbbbbb #x3c3c3c3c #x83838383 #x53535353 #x99999999 #x61616161 #x17171717 #x2b2b2b2b #x04040404 #x7e7e7e7e #xbabababa #x77777777 #xd6d6d6d6 #x26262626 #xe1e1e1e1 #x69696969 #x14141414 #x63636363 #x55555555 #x21212121 #x0c0c0c0c #x7d7d7d7d)) (declaim (type (simple-array (unsigned-byte 32) (10)) round-constants)) (defconst round-constants #32@(#x01000000 #x02000000 #x04000000 #x08000000 #x10000000 #x20000000 #x40000000 #x80000000 #x1B000000 #x36000000)) the actual AES implementation waste a little space for " common " 128 - bit keys , but is anybody really (deftype aes-round-keys () '(simple-array (unsigned-byte 32) (60))) (defclass aes (cipher 16-byte-block-mixin) ((encryption-round-keys :accessor encryption-round-keys :type aes-round-keys) (decryption-round-keys :accessor decryption-round-keys :type aes-round-keys) (n-rounds :accessor n-rounds))) (defun allocate-round-keys (key) (declare (type (simple-array (unsigned-byte 8) (*)) key)) (ecase (length key) ((16 24 32) (make-array 60 :element-type '(unsigned-byte 32) :initial-element 0)))) (defun generate-128-bit-round-keys (round-keys key) (declare (type aes-round-keys round-keys) (type (simple-array (unsigned-byte 8) (16)) key) (optimize (speed 3) (space 0) (debug 0))) (let ((round-key-offset 0)) (declare (type (integer 0 43) round-key-offset)) (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-key-offset)))) (dotimes (i 4) (setf (rk-ref i) (ub32ref/be key (* 4 i)))) (dotimes (i 10 (values round-keys 10)) (declare (type (integer 0 10) i)) (let ((tmp (rk-ref 3))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 4) (logxor (rk-ref 0) (logand (aref Te4 (third-byte tmp)) #xff000000) (logand (aref Te4 (second-byte tmp)) #x00ff0000) (logand (aref Te4 (first-byte tmp)) #x0000ff00) (logand (aref Te4 (fourth-byte tmp)) #x000000ff) (aref round-constants i)) (rk-ref 5) (logxor (rk-ref 1) (rk-ref 4)) (rk-ref 6) (logxor (rk-ref 2) (rk-ref 5)) (rk-ref 7) (logxor (rk-ref 3) (rk-ref 6))) (incf round-key-offset 4)))))) (defun generate-192-bit-round-keys (round-keys key) (declare (type aes-round-keys round-keys) (type (simple-array (unsigned-byte 8) (24)) key) (optimize (speed 3) (space 0) (debug 0))) (let ((round-key-offset 0)) (declare (type (integer 0 51) round-key-offset)) (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-key-offset)))) (dotimes (i 6) (setf (rk-ref i) (ub32ref/be key (* 4 i)))) (dotimes (i 8) (let ((tmp (rk-ref 5))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 6) (logxor (rk-ref 0) (logand (aref Te4 (third-byte tmp)) #xff000000) (logand (aref Te4 (second-byte tmp)) #x00ff0000) (logand (aref Te4 (first-byte tmp)) #x0000ff00) (logand (aref Te4 (fourth-byte tmp)) #x000000ff) (aref round-constants i)) (rk-ref 7) (logxor (rk-ref 1) (rk-ref 6)) (rk-ref 8) (logxor (rk-ref 2) (rk-ref 7)) (rk-ref 9) (logxor (rk-ref 3) (rk-ref 8))) (when (= 8 (1+ i)) (return-from generate-192-bit-round-keys (values round-keys 12))) (setf (rk-ref 10) (logxor (rk-ref 4) (rk-ref 9)) (rk-ref 11) (logxor (rk-ref 5) (rk-ref 10))) (incf round-key-offset 6)))))) (defun generate-256-bit-round-keys (round-keys key) (declare (type aes-round-keys round-keys) (type (simple-array (unsigned-byte 8) (32)) key) (optimize (speed 3) (space 0) (debug 0))) (let ((round-key-offset 0)) (declare (type (integer 0 59) round-key-offset)) (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-key-offset)))) (dotimes (i 8) (setf (rk-ref i) (ub32ref/be key (* 4 i)))) (dotimes (i 7) (let ((tmp (rk-ref 7))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 8) (logxor (rk-ref 0) (logand (aref Te4 (third-byte tmp)) #xff000000) (logand (aref Te4 (second-byte tmp)) #x00ff0000) (logand (aref Te4 (first-byte tmp)) #x0000ff00) (logand (aref Te4 (fourth-byte tmp)) #x000000ff) (aref round-constants i)) (rk-ref 9) (logxor (rk-ref 1) (rk-ref 8)) (rk-ref 10) (logxor (rk-ref 2) (rk-ref 9)) (rk-ref 11) (logxor (rk-ref 3) (rk-ref 10))) (when (= 7 (1+ i)) (return-from generate-256-bit-round-keys (values round-keys 14)))) (let ((tmp (rk-ref 11))) (declare (type (unsigned-byte 32) tmp)) (setf (rk-ref 12) (logxor (rk-ref 4) (logand (aref Te4 (fourth-byte tmp)) #xff000000) (logand (aref Te4 (third-byte tmp)) #x00ff0000) (logand (aref Te4 (second-byte tmp)) #x0000ff00) (logand (aref Te4 (first-byte tmp)) #x000000ff)) (rk-ref 13) (logxor (rk-ref 5) (rk-ref 12)) (rk-ref 14) (logxor (rk-ref 6) (rk-ref 13)) (rk-ref 15) (logxor (rk-ref 7) (rk-ref 14))) (incf round-key-offset 8)))))) (defun generate-round-keys-for-encryption (key round-keys) (declare (type (simple-array (unsigned-byte 8) (*)) key)) (ecase (length key) (16 (generate-128-bit-round-keys round-keys key)) (24 (generate-192-bit-round-keys round-keys key)) (32 (generate-256-bit-round-keys round-keys key)))) (defun generate-round-keys-for-decryption (round-keys n-rounds) (declare (type aes-round-keys round-keys) (type (unsigned-byte 16) n-rounds)) (do ((i 0 (+ 4 i)) (j (* 4 n-rounds) (- j 4))) ((>= i j)) (declare (type (unsigned-byte 16) i j)) (rotatef (aref round-keys i) (aref round-keys j)) (rotatef (aref round-keys (+ 1 i)) (aref round-keys (+ 1 j))) (rotatef (aref round-keys (+ 2 i)) (aref round-keys (+ 2 j))) (rotatef (aref round-keys (+ 3 i)) (aref round-keys (+ 3 j)))) apply inverse MixColumn transform to all round keys but the first (macrolet ((rk-ref (x) `(aref round-keys (+ ,x round-keys-offset)))) (do ((i 1 (+ 1 i)) (round-keys-offset 4 (+ 4 round-keys-offset))) ((>= i n-rounds) (values round-keys n-rounds)) (declare (type (unsigned-byte 16) round-keys-offset)) (macrolet ((mix-column (x) `(let ((column (rk-ref ,x))) (declare (type (unsigned-byte 32) column)) (setf (rk-ref ,x) (logxor (aref Td0 (first-byte (aref Te4 (fourth-byte column)))) (aref Td1 (first-byte (aref Te4 (third-byte column)))) (aref Td2 (first-byte (aref Te4 (second-byte column)))) (aref Td3 (first-byte (aref Te4 (first-byte column))))))))) (mix-column 0) (mix-column 1) (mix-column 2) (mix-column 3))))) (macrolet ((mix (rk a0 a1 a2 a3 sym0 sym1 sym2 sym3) `(logxor (aref ,a0 (fourth-byte ,sym0)) (aref ,a1 (third-byte ,sym1)) (aref ,a2 (second-byte ,sym2)) (aref ,a3 (first-byte ,sym3)) (rk-ref ,rk))) (mix-s-into-t-encrypting (offset) `(setf t0 (mix ,offset Te0 Te1 Te2 Te3 s0 s1 s2 s3) t1 (mix (1+ ,offset) Te0 Te1 Te2 Te3 s1 s2 s3 s0) t2 (mix (+ ,offset 2) Te0 Te1 Te2 Te3 s2 s3 s0 s1) t3 (mix (+ ,offset 3) Te0 Te1 Te2 Te3 s3 s0 s1 s2))) (mix-t-into-s-encrypting (offset) `(setf s0 (mix ,offset Te0 Te1 Te2 Te3 t0 t1 t2 t3) s1 (mix (1+ ,offset) Te0 Te1 Te2 Te3 t1 t2 t3 t0) s2 (mix (+ ,offset 2) Te0 Te1 Te2 Te3 t2 t3 t0 t1) s3 (mix (+ ,offset 3) Te0 Te1 Te2 Te3 t3 t0 t1 t2))) (mix-s-into-t-decrypting (offset) `(setf t0 (mix ,offset Td0 Td1 Td2 Td3 s0 s3 s2 s1) t1 (mix (1+ ,offset) Td0 Td1 Td2 Td3 s1 s0 s3 s2) t2 (mix (+ ,offset 2) Td0 Td1 Td2 Td3 s2 s1 s0 s3) t3 (mix (+ ,offset 3) Td0 Td1 Td2 Td3 s3 s2 s1 s0))) (mix-t-into-s-decrypting (offset) `(setf s0 (mix ,offset Td0 Td1 Td2 Td3 t0 t3 t2 t1) s1 (mix (1+ ,offset) Td0 Td1 Td2 Td3 t1 t0 t3 t2) s2 (mix (+ ,offset 2) Td0 Td1 Td2 Td3 t2 t1 t0 t3) s3 (mix (+ ,offset 3) Td0 Td1 Td2 Td3 t3 t2 t1 t0))) (rk-ref (x) `(aref round-keys (+ ,x round-key-offset))) #+nil (rk-ref (x) `(aref round-keys (+ ,x 0)))) (define-block-encryptor aes 16 (let ((round-keys (encryption-round-keys context)) (n-rounds (n-rounds context))) (declare (type aes-round-keys round-keys)) (declare (type (integer 0 14) n-rounds)) #+(and sbcl x86-64 aes-ni) (aes-ni-encrypt plaintext plaintext-start ciphertext ciphertext-start round-keys n-rounds) #-(and sbcl x86-64 aes-ni) (with-words ((s0 s1 s2 s3) plaintext plaintext-start) (let ((t0 0) (t1 0) (t2 0) (t3 0) (round-key-offset 0)) (declare (type (unsigned-byte 32) t0 t1 t2 t3)) (declare (type (unsigned-byte 16) round-key-offset)) (setf s0 (logxor s0 (aref round-keys 0)) s1 (logxor s1 (aref round-keys 1)) s2 (logxor s2 (aref round-keys 2)) s3 (logxor s3 (aref round-keys 3))) (do ((round (truncate n-rounds 2) (1- round))) ((zerop round)) (declare (type (unsigned-byte 16) round)) (mix-s-into-t-encrypting 4) (incf round-key-offset 8) (when (= round 1) (return-from nil (values))) (mix-t-into-s-encrypting 0)) (flet ((apply-round (round-key u0 u1 u2 u3) (declare (type (unsigned-byte 32) round-key u0 u1 u2 u3)) (logxor (logand (aref Te4 (fourth-byte u0)) #xff000000) (logand (aref Te4 (third-byte u1)) #x00ff0000) (logand (aref Te4 (second-byte u2)) #x0000ff00) (logand (aref Te4 (first-byte u3)) #x000000ff) round-key))) (declare (inline apply-round)) (store-words ciphertext ciphertext-start (apply-round (rk-ref 0) t0 t1 t2 t3) (apply-round (rk-ref 1) t1 t2 t3 t0) (apply-round (rk-ref 2) t2 t3 t0 t1) (apply-round (rk-ref 3) t3 t0 t1 t2))))))) (define-block-decryptor aes 16 (let ((round-keys (decryption-round-keys context)) (n-rounds (n-rounds context))) (declare (type aes-round-keys round-keys)) (declare (type (unsigned-byte 16) n-rounds)) #+(and sbcl x86-64 aes-ni) (aes-ni-decrypt ciphertext ciphertext-start plaintext plaintext-start round-keys n-rounds) #-(and sbcl x86-64 aes-ni) (with-words ((s0 s1 s2 s3) ciphertext ciphertext-start) (let ((t0 0) (t1 0) (t2 0) (t3 0) (round-key-offset 0)) (declare (type (unsigned-byte 32) t0 t1 t2 t3)) (declare (type (unsigned-byte 16) round-key-offset)) (setf s0 (logxor s0 (aref round-keys 0)) s1 (logxor s1 (aref round-keys 1)) s2 (logxor s2 (aref round-keys 2)) s3 (logxor s3 (aref round-keys 3))) (do ((round (truncate n-rounds 2) (1- round))) ((zerop round)) (declare (type (unsigned-byte 16) round)) (mix-s-into-t-decrypting 4) (incf round-key-offset 8) (when (= round 1) (return-from nil (values))) (mix-t-into-s-decrypting 0)) (flet ((apply-round (round-key u0 u1 u2 u3) (declare (type (unsigned-byte 32) round-key u0 u1 u2 u3)) (logxor (logand (aref Td4 (fourth-byte u0)) #xff000000) (logand (aref Td4 (third-byte u1)) #x00ff0000) (logand (aref Td4 (second-byte u2)) #x0000ff00) (logand (aref Td4 (first-byte u3)) #x000000ff) round-key))) (declare (inline apply-round)) (store-words plaintext plaintext-start (apply-round (rk-ref 0) t0 t3 t2 t1) (apply-round (rk-ref 1) t1 t0 t3 t2) (apply-round (rk-ref 2) t2 t1 t0 t3) (apply-round (rk-ref 3) t3 t2 t1 t0))))))) MACROLET (defmethod schedule-key ((cipher aes) key) #+(and sbcl x86-64 aes-ni) (let ((encryption-keys (allocate-round-keys key)) (decryption-keys (allocate-round-keys key)) (n-rounds (ecase (length key) (16 10) (24 12) (32 14)))) (declare (type aes-round-keys encryption-keys decryption-keys)) (aes-ni-generate-round-keys key (length key) encryption-keys decryption-keys) (setf (encryption-round-keys cipher) encryption-keys (decryption-round-keys cipher) decryption-keys (n-rounds cipher) n-rounds) cipher) #-(and sbcl x86-64 aes-ni) (multiple-value-bind (encryption-keys n-rounds) (generate-round-keys-for-encryption key (allocate-round-keys key)) (declare (type aes-round-keys encryption-keys)) (let ((decryption-keys (copy-seq encryption-keys))) (generate-round-keys-for-decryption decryption-keys n-rounds) (setf (encryption-round-keys cipher) encryption-keys (decryption-round-keys cipher) decryption-keys (n-rounds cipher) n-rounds) cipher))) (defcipher aes (:encrypt-function aes-encrypt-block) (:decrypt-function aes-decrypt-block) (:block-length 16) (:key-length (:fixed 16 24 32)))
582d0f64003178df46c847f669b16ced2634d5f158e7209ec751a49061b4f088
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
Capability.hs
{-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} -- | Contains the types generated from the schema Capability module StripeAPI.Types.Capability where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import {-# SOURCE #-} StripeAPI.Types.Account import {-# SOURCE #-} StripeAPI.Types.AccountCapabilityFutureRequirements import {-# SOURCE #-} StripeAPI.Types.AccountCapabilityRequirements import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe | Defines the object schema located at @components.schemas.capability@ in the specification . -- -- This is an object representing a capability for a Stripe account. -- -- Related guide: [Account capabilities](https:\/\/stripe.com\/docs\/connect\/account-capabilities). data Capability = Capability { -- | account: The account for which the capability enables functionality. capabilityAccount :: CapabilityAccount'Variants, -- | future_requirements: capabilityFutureRequirements :: (GHC.Maybe.Maybe AccountCapabilityFutureRequirements), -- | id: The identifier for the capability. -- -- Constraints: -- * Maximum length of 5000 capabilityId :: Data.Text.Internal.Text, -- | requested: Whether the capability has been requested. capabilityRequested :: GHC.Types.Bool, | requested_at : Time at which the capability was requested . Measured in seconds since the Unix epoch . capabilityRequestedAt :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable GHC.Types.Int)), -- | requirements: capabilityRequirements :: (GHC.Maybe.Maybe AccountCapabilityRequirements), | status : The status of the capability . Can be \`active\ ` , \`inactive\ ` , \`pending\ ` , or ` . capabilityStatus :: CapabilityStatus' } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON Capability where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["account" Data.Aeson.Types.ToJSON..= capabilityAccount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("future_requirements" Data.Aeson.Types.ToJSON..=)) (capabilityFutureRequirements obj) : ["id" Data.Aeson.Types.ToJSON..= capabilityId obj] : ["requested" Data.Aeson.Types.ToJSON..= capabilityRequested obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requested_at" Data.Aeson.Types.ToJSON..=)) (capabilityRequestedAt obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requirements" Data.Aeson.Types.ToJSON..=)) (capabilityRequirements obj) : ["status" Data.Aeson.Types.ToJSON..= capabilityStatus obj] : ["object" Data.Aeson.Types.ToJSON..= Data.Aeson.Types.Internal.String "capability"] : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["account" Data.Aeson.Types.ToJSON..= capabilityAccount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("future_requirements" Data.Aeson.Types.ToJSON..=)) (capabilityFutureRequirements obj) : ["id" Data.Aeson.Types.ToJSON..= capabilityId obj] : ["requested" Data.Aeson.Types.ToJSON..= capabilityRequested obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requested_at" Data.Aeson.Types.ToJSON..=)) (capabilityRequestedAt obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requirements" Data.Aeson.Types.ToJSON..=)) (capabilityRequirements obj) : ["status" Data.Aeson.Types.ToJSON..= capabilityStatus obj] : ["object" Data.Aeson.Types.ToJSON..= Data.Aeson.Types.Internal.String "capability"] : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON Capability where parseJSON = Data.Aeson.Types.FromJSON.withObject "Capability" (\obj -> ((((((GHC.Base.pure Capability GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "account")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "future_requirements")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "id")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "requested")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "requested_at")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "requirements")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "status")) -- | Create a new 'Capability' with all required fields. mkCapability :: -- | 'capabilityAccount' CapabilityAccount'Variants -> -- | 'capabilityId' Data.Text.Internal.Text -> -- | 'capabilityRequested' GHC.Types.Bool -> -- | 'capabilityStatus' CapabilityStatus' -> Capability mkCapability capabilityAccount capabilityId capabilityRequested capabilityStatus = Capability { capabilityAccount = capabilityAccount, capabilityFutureRequirements = GHC.Maybe.Nothing, capabilityId = capabilityId, capabilityRequested = capabilityRequested, capabilityRequestedAt = GHC.Maybe.Nothing, capabilityRequirements = GHC.Maybe.Nothing, capabilityStatus = capabilityStatus } | Defines the oneOf schema located at @components.schemas.capability.properties.account.anyOf@ in the specification . -- -- The account for which the capability enables functionality. data CapabilityAccount'Variants = CapabilityAccount'Text Data.Text.Internal.Text | CapabilityAccount'Account Account deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON CapabilityAccount'Variants where toJSON (CapabilityAccount'Text a) = Data.Aeson.Types.ToJSON.toJSON a toJSON (CapabilityAccount'Account a) = Data.Aeson.Types.ToJSON.toJSON a instance Data.Aeson.Types.FromJSON.FromJSON CapabilityAccount'Variants where parseJSON val = case (CapabilityAccount'Text Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> ((CapabilityAccount'Account Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> Data.Aeson.Types.Internal.Error "No variant matched") of Data.Aeson.Types.Internal.Success a -> GHC.Base.pure a Data.Aeson.Types.Internal.Error a -> Control.Monad.Fail.fail a | Defines the enum schema located at @components.schemas.capability.properties.status@ in the specification . -- The status of the capability . Can be \`active\ ` , \`inactive\ ` , \`pending\ ` , or ` . data CapabilityStatus' = -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification. CapabilityStatus'Other Data.Aeson.Types.Internal.Value | -- | This constructor can be used to send values to the server which are not present in the specification yet. CapabilityStatus'Typed Data.Text.Internal.Text | Represents the JSON value CapabilityStatus'EnumActive | Represents the JSON value @"disabled"@ CapabilityStatus'EnumDisabled | -- | Represents the JSON value @"inactive"@ CapabilityStatus'EnumInactive | -- | Represents the JSON value @"pending"@ CapabilityStatus'EnumPending | -- | Represents the JSON value @"unrequested"@ CapabilityStatus'EnumUnrequested deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON CapabilityStatus' where toJSON (CapabilityStatus'Other val) = val toJSON (CapabilityStatus'Typed val) = Data.Aeson.Types.ToJSON.toJSON val toJSON (CapabilityStatus'EnumActive) = "active" toJSON (CapabilityStatus'EnumDisabled) = "disabled" toJSON (CapabilityStatus'EnumInactive) = "inactive" toJSON (CapabilityStatus'EnumPending) = "pending" toJSON (CapabilityStatus'EnumUnrequested) = "unrequested" instance Data.Aeson.Types.FromJSON.FromJSON CapabilityStatus' where parseJSON val = GHC.Base.pure ( if | val GHC.Classes.== "active" -> CapabilityStatus'EnumActive | val GHC.Classes.== "disabled" -> CapabilityStatus'EnumDisabled | val GHC.Classes.== "inactive" -> CapabilityStatus'EnumInactive | val GHC.Classes.== "pending" -> CapabilityStatus'EnumPending | val GHC.Classes.== "unrequested" -> CapabilityStatus'EnumUnrequested | GHC.Base.otherwise -> CapabilityStatus'Other val )
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/Capability.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | Contains the types generated from the schema Capability # SOURCE # # SOURCE # # SOURCE # This is an object representing a capability for a Stripe account. Related guide: [Account capabilities](https:\/\/stripe.com\/docs\/connect\/account-capabilities). | account: The account for which the capability enables functionality. | future_requirements: | id: The identifier for the capability. Constraints: | requested: Whether the capability has been requested. | requirements: | Create a new 'Capability' with all required fields. | 'capabilityAccount' | 'capabilityId' | 'capabilityRequested' | 'capabilityStatus' The account for which the capability enables functionality. | This case is used if the value encountered during decoding does not match any of the provided cases in the specification. | This constructor can be used to send values to the server which are not present in the specification yet. | Represents the JSON value @"inactive"@ | Represents the JSON value @"pending"@ | Represents the JSON value @"unrequested"@
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . module StripeAPI.Types.Capability where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe | Defines the object schema located at @components.schemas.capability@ in the specification . data Capability = Capability capabilityAccount :: CapabilityAccount'Variants, capabilityFutureRequirements :: (GHC.Maybe.Maybe AccountCapabilityFutureRequirements), * Maximum length of 5000 capabilityId :: Data.Text.Internal.Text, capabilityRequested :: GHC.Types.Bool, | requested_at : Time at which the capability was requested . Measured in seconds since the Unix epoch . capabilityRequestedAt :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable GHC.Types.Int)), capabilityRequirements :: (GHC.Maybe.Maybe AccountCapabilityRequirements), | status : The status of the capability . Can be \`active\ ` , \`inactive\ ` , \`pending\ ` , or ` . capabilityStatus :: CapabilityStatus' } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON Capability where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["account" Data.Aeson.Types.ToJSON..= capabilityAccount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("future_requirements" Data.Aeson.Types.ToJSON..=)) (capabilityFutureRequirements obj) : ["id" Data.Aeson.Types.ToJSON..= capabilityId obj] : ["requested" Data.Aeson.Types.ToJSON..= capabilityRequested obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requested_at" Data.Aeson.Types.ToJSON..=)) (capabilityRequestedAt obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requirements" Data.Aeson.Types.ToJSON..=)) (capabilityRequirements obj) : ["status" Data.Aeson.Types.ToJSON..= capabilityStatus obj] : ["object" Data.Aeson.Types.ToJSON..= Data.Aeson.Types.Internal.String "capability"] : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["account" Data.Aeson.Types.ToJSON..= capabilityAccount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("future_requirements" Data.Aeson.Types.ToJSON..=)) (capabilityFutureRequirements obj) : ["id" Data.Aeson.Types.ToJSON..= capabilityId obj] : ["requested" Data.Aeson.Types.ToJSON..= capabilityRequested obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requested_at" Data.Aeson.Types.ToJSON..=)) (capabilityRequestedAt obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("requirements" Data.Aeson.Types.ToJSON..=)) (capabilityRequirements obj) : ["status" Data.Aeson.Types.ToJSON..= capabilityStatus obj] : ["object" Data.Aeson.Types.ToJSON..= Data.Aeson.Types.Internal.String "capability"] : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON Capability where parseJSON = Data.Aeson.Types.FromJSON.withObject "Capability" (\obj -> ((((((GHC.Base.pure Capability GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "account")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "future_requirements")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "id")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "requested")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "requested_at")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "requirements")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "status")) mkCapability :: CapabilityAccount'Variants -> Data.Text.Internal.Text -> GHC.Types.Bool -> CapabilityStatus' -> Capability mkCapability capabilityAccount capabilityId capabilityRequested capabilityStatus = Capability { capabilityAccount = capabilityAccount, capabilityFutureRequirements = GHC.Maybe.Nothing, capabilityId = capabilityId, capabilityRequested = capabilityRequested, capabilityRequestedAt = GHC.Maybe.Nothing, capabilityRequirements = GHC.Maybe.Nothing, capabilityStatus = capabilityStatus } | Defines the oneOf schema located at @components.schemas.capability.properties.account.anyOf@ in the specification . data CapabilityAccount'Variants = CapabilityAccount'Text Data.Text.Internal.Text | CapabilityAccount'Account Account deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON CapabilityAccount'Variants where toJSON (CapabilityAccount'Text a) = Data.Aeson.Types.ToJSON.toJSON a toJSON (CapabilityAccount'Account a) = Data.Aeson.Types.ToJSON.toJSON a instance Data.Aeson.Types.FromJSON.FromJSON CapabilityAccount'Variants where parseJSON val = case (CapabilityAccount'Text Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> ((CapabilityAccount'Account Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> Data.Aeson.Types.Internal.Error "No variant matched") of Data.Aeson.Types.Internal.Success a -> GHC.Base.pure a Data.Aeson.Types.Internal.Error a -> Control.Monad.Fail.fail a | Defines the enum schema located at @components.schemas.capability.properties.status@ in the specification . The status of the capability . Can be \`active\ ` , \`inactive\ ` , \`pending\ ` , or ` . data CapabilityStatus' CapabilityStatus'Other Data.Aeson.Types.Internal.Value CapabilityStatus'Typed Data.Text.Internal.Text | Represents the JSON value CapabilityStatus'EnumActive | Represents the JSON value @"disabled"@ CapabilityStatus'EnumDisabled CapabilityStatus'EnumInactive CapabilityStatus'EnumPending CapabilityStatus'EnumUnrequested deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON CapabilityStatus' where toJSON (CapabilityStatus'Other val) = val toJSON (CapabilityStatus'Typed val) = Data.Aeson.Types.ToJSON.toJSON val toJSON (CapabilityStatus'EnumActive) = "active" toJSON (CapabilityStatus'EnumDisabled) = "disabled" toJSON (CapabilityStatus'EnumInactive) = "inactive" toJSON (CapabilityStatus'EnumPending) = "pending" toJSON (CapabilityStatus'EnumUnrequested) = "unrequested" instance Data.Aeson.Types.FromJSON.FromJSON CapabilityStatus' where parseJSON val = GHC.Base.pure ( if | val GHC.Classes.== "active" -> CapabilityStatus'EnumActive | val GHC.Classes.== "disabled" -> CapabilityStatus'EnumDisabled | val GHC.Classes.== "inactive" -> CapabilityStatus'EnumInactive | val GHC.Classes.== "pending" -> CapabilityStatus'EnumPending | val GHC.Classes.== "unrequested" -> CapabilityStatus'EnumUnrequested | GHC.Base.otherwise -> CapabilityStatus'Other val )
b9e99e9fdd67a147a941de3979f483e53c6d114c12e2b64987a278a0af8fca36
scrintal/heroicons-reagent
ellipsis_vertical.cljs
(ns com.scrintal.heroicons.solid.ellipsis-vertical) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M10.5 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0z" :clipRule "evenodd"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/ellipsis_vertical.cljs
clojure
(ns com.scrintal.heroicons.solid.ellipsis-vertical) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M10.5 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0z" :clipRule "evenodd"}]])
cc46a68680494848e4f77b18918cb318669701e09f504df1cb76941af486a35b
mogenslund/liquid
markdownfolds_test.clj
(ns liq.extras.markdownfolds-test (:require [clojure.test :refer :all] [liq.buffer :as buffer] [liq.extras.markdownfolds :refer :all])) (deftest get-headline-level-test "" (is (= (get-headline-level (buffer/buffer "# abc") 1) 1)) (is (= (get-headline-level (buffer/buffer "## abc") 1) 2)) (is (= (get-headline-level (buffer/buffer "abc\n## abc") 2) 2)) (is (= (get-headline-level (buffer/buffer "\n## abc") 2) 2)) (is (= (get-headline-level (buffer/buffer "\n") 2) 0)) (is (= (get-headline-level (buffer/buffer "abc") 1) 0)) (is (= (get-headline-level (buffer/buffer "") 1) 0)) (is (= (get-headline-level (buffer/buffer "abc") 2) 0)) (is (= (get-headline-level (buffer/buffer "abc") 0) 0))) (deftest get-level-end-test "" (is (= (get-level-end (buffer/buffer "# abc\nabc\n# def") 1) 2)) (is (= (get-level-end (buffer/buffer "# abc\nabc") 1) 2)) (is (= (get-level-end (buffer/buffer "# abc\n# abc") 1) 1)) (is (= (get-level-end (buffer/buffer "# abc\n# abc\nabc") 1) 1)) (is (= (get-level-end (buffer/buffer "# abc\n\n# abc") 1) 2)) (is (= (get-level-end (buffer/buffer "# abc") 1) 1)) (is (= (get-level-end (buffer/buffer "# aaa\n# aaa\n## bb\n123\n# ccc\n# ddd") 3) 4))) (deftest hide-level-test "" (let [buf (buffer/buffer "# abc\ndef")] (is (= (buf ::buffer/hidden-lines) {})) (is (= (-> buf buffer/left hide-level ::buffer/hidden-lines) {2 2}))))
null
https://raw.githubusercontent.com/mogenslund/liquid/eafc54df9c67f2e625220b78b65de1143099ef00/test/liq/extras/markdownfolds_test.clj
clojure
(ns liq.extras.markdownfolds-test (:require [clojure.test :refer :all] [liq.buffer :as buffer] [liq.extras.markdownfolds :refer :all])) (deftest get-headline-level-test "" (is (= (get-headline-level (buffer/buffer "# abc") 1) 1)) (is (= (get-headline-level (buffer/buffer "## abc") 1) 2)) (is (= (get-headline-level (buffer/buffer "abc\n## abc") 2) 2)) (is (= (get-headline-level (buffer/buffer "\n## abc") 2) 2)) (is (= (get-headline-level (buffer/buffer "\n") 2) 0)) (is (= (get-headline-level (buffer/buffer "abc") 1) 0)) (is (= (get-headline-level (buffer/buffer "") 1) 0)) (is (= (get-headline-level (buffer/buffer "abc") 2) 0)) (is (= (get-headline-level (buffer/buffer "abc") 0) 0))) (deftest get-level-end-test "" (is (= (get-level-end (buffer/buffer "# abc\nabc\n# def") 1) 2)) (is (= (get-level-end (buffer/buffer "# abc\nabc") 1) 2)) (is (= (get-level-end (buffer/buffer "# abc\n# abc") 1) 1)) (is (= (get-level-end (buffer/buffer "# abc\n# abc\nabc") 1) 1)) (is (= (get-level-end (buffer/buffer "# abc\n\n# abc") 1) 2)) (is (= (get-level-end (buffer/buffer "# abc") 1) 1)) (is (= (get-level-end (buffer/buffer "# aaa\n# aaa\n## bb\n123\n# ccc\n# ddd") 3) 4))) (deftest hide-level-test "" (let [buf (buffer/buffer "# abc\ndef")] (is (= (buf ::buffer/hidden-lines) {})) (is (= (-> buf buffer/left hide-level ::buffer/hidden-lines) {2 2}))))
05077cb599a00c0580e7576e024ea9121062a8b99903f4ac4219b0db30def60b
ocramz/sparse-linear-algebra
Accelerate.hs
# language GADTs , TypeFamilies # ----------------------------------------------------------------------------- -- | Module : Numeric . LinearAlgebra . Sparse . Accelerate Copyright : ( c ) 2017 -- License : BSD3 (see the file LICENSE) -- Maintainer : zocca marco gmail -- Stability : experimental -- Portability : portable -- -- `accelerate` instances for sparse linear algebra -- ----------------------------------------------------------------------------- module Numeric.LinearAlgebra.Sparse.Accelerate where import Foreign.Storable (Storable(..)) import Control.Monad.Primitive import Data.Ord (comparing) import qualified Data.Array.Accelerate as A import Data.Array.Accelerate (Acc, Array, Vector, Segments, DIM1, DIM2, Exp, Any(Any), All(All), Z(Z), (:.)((:.))) import Data.Array.Accelerate.IO -- (fromVectors, toVectors) import Data.Array.Accelerate.Array.Sugar import Data.Vector.Algorithms.Merge (sort, sortBy) import Data . Vector . Algorithms . Common import qualified Data.Vector as V import qualified Data.Vector.Mutable as VM import qualified Data . Vector . Generic as VG import qualified Data.Vector.Storable as VS import Data.Array.Accelerate.Interpreter (run) import Data . Array . Accelerate . Sparse . -- import Data.Array.Accelerate.Sparse.SVector import Data.Array.Accelerate.Sparse.COOElem -- takeWhile ins = A.fold ins (A.use []) where extractRow i = A.filter ( \coo - > let ixr = getRow coo in ixr = = i ) -- extractRow i = A.filter (\e -> A.lift (eqRowIx i e)) -- eqRowIx :: Eq i => i -> COOElem i a -> Bool -- eqRowIx i = (== i) . getRow . A.unlift -- withExp :: (a -> b) -> Exp a -> Exp b -- withExp f = A.lift . f . A.unlift -- empty = A.use $ V.fromList [] -- * SpGEMM : matrix-matrix product -- | Sort an accelerate array via vector-algorithms sortA :: (Vectors (EltRepr e) ~ VS.Vector e , Storable e , Ord e , Elt e , Shape t , PrimMonad m) => t -> Array t e -> m (Array t e) sortA dim v = do let vm = toVectors v vm' <- sortVS vm return $ fromVectors dim vm' -- | Sort a storable vector sortVS :: (Storable a, PrimMonad m, Ord a) => VS.Vector a -> m (VS.Vector a) sortVS v = do vm <- VS.thaw v sort vm VS.freeze vm sortWith :: (Ord b, PrimMonad m) => (a -> b) -> V.Vector a -> m (V.Vector a) sortWith by v = do vm <- V.thaw v sortBy (comparing by) vm V.freeze vm -- Sparse-matrix vector multiplication -- ----------------------------------- type SparseVector e = Vector ( A.Int32 , e ) type SparseMatrix e = ( Segments A.Int32 , SparseVector e ) smvm : : A.Num a = > Acc ( SparseMatrix a ) - > Acc ( Vector a ) - > Acc ( Vector a ) smvm -- = let (segd, svec) = A.unlift smat -- (inds, vals) = A.unzip svec -- vecVals = A.gather ( A.fromIntegral inds ) vec -- vecVals = A.backpermute -- (A.shape inds) -- (\i -> A.index1 $ A.fromIntegral $ inds A.! i) -- vec -- products = A.zipWith (*) vecVals vals -- in A.foldSeg ( + ) 0 products segd -- sv0 :: A.Array DIM1 (Int, Int) sv0 = A.fromList ( Z : . 5 ) $ zip [ 0,1,3,4,6 ] [ 4 .. ] sv1 :: A.Array DIM1 (COOElem Int Double) sv1 = A.fromList (Z :. 3) [a, b, c] where a = CooE (0, 1, pi) b = CooE (0, 0, 2.3) c = CooE (1, 1, 1.23)
null
https://raw.githubusercontent.com/ocramz/sparse-linear-algebra/77f14ebc5c545cb665cdd840149a021f3df07183/accelerate/src/Numeric/LinearAlgebra/Sparse/Accelerate.hs
haskell
--------------------------------------------------------------------------- | License : BSD3 (see the file LICENSE) Stability : experimental Portability : portable `accelerate` instances for sparse linear algebra --------------------------------------------------------------------------- (fromVectors, toVectors) import Data.Array.Accelerate.Sparse.SVector takeWhile ins = A.fold ins (A.use []) where extractRow i = A.filter (\e -> A.lift (eqRowIx i e)) eqRowIx :: Eq i => i -> COOElem i a -> Bool eqRowIx i = (== i) . getRow . A.unlift withExp :: (a -> b) -> Exp a -> Exp b withExp f = A.lift . f . A.unlift empty = A.use $ V.fromList [] * SpGEMM : matrix-matrix product | Sort an accelerate array via vector-algorithms | Sort a storable vector Sparse-matrix vector multiplication ----------------------------------- = let (segd, svec) = A.unlift smat (inds, vals) = A.unzip svec vecVals = A.gather ( A.fromIntegral inds ) vec vecVals = A.backpermute (A.shape inds) (\i -> A.index1 $ A.fromIntegral $ inds A.! i) vec products = A.zipWith (*) vecVals vals in sv0 :: A.Array DIM1 (Int, Int)
# language GADTs , TypeFamilies # Module : Numeric . LinearAlgebra . Sparse . Accelerate Copyright : ( c ) 2017 Maintainer : zocca marco gmail module Numeric.LinearAlgebra.Sparse.Accelerate where import Foreign.Storable (Storable(..)) import Control.Monad.Primitive import Data.Ord (comparing) import qualified Data.Array.Accelerate as A import Data.Array.Accelerate (Acc, Array, Vector, Segments, DIM1, DIM2, Exp, Any(Any), All(All), Z(Z), (:.)((:.))) import Data.Array.Accelerate.Array.Sugar import Data.Vector.Algorithms.Merge (sort, sortBy) import Data . Vector . Algorithms . Common import qualified Data.Vector as V import qualified Data.Vector.Mutable as VM import qualified Data . Vector . Generic as VG import qualified Data.Vector.Storable as VS import Data.Array.Accelerate.Interpreter (run) import Data . Array . Accelerate . Sparse . import Data.Array.Accelerate.Sparse.COOElem extractRow i = A.filter ( \coo - > let ixr = getRow coo in ixr = = i ) sortA :: (Vectors (EltRepr e) ~ VS.Vector e , Storable e , Ord e , Elt e , Shape t , PrimMonad m) => t -> Array t e -> m (Array t e) sortA dim v = do let vm = toVectors v vm' <- sortVS vm return $ fromVectors dim vm' sortVS :: (Storable a, PrimMonad m, Ord a) => VS.Vector a -> m (VS.Vector a) sortVS v = do vm <- VS.thaw v sort vm VS.freeze vm sortWith :: (Ord b, PrimMonad m) => (a -> b) -> V.Vector a -> m (V.Vector a) sortWith by v = do vm <- V.thaw v sortBy (comparing by) vm V.freeze vm type SparseVector e = Vector ( A.Int32 , e ) type SparseMatrix e = ( Segments A.Int32 , SparseVector e ) smvm : : A.Num a = > Acc ( SparseMatrix a ) - > Acc ( Vector a ) - > Acc ( Vector a ) smvm A.foldSeg ( + ) 0 products segd sv0 = A.fromList ( Z : . 5 ) $ zip [ 0,1,3,4,6 ] [ 4 .. ] sv1 :: A.Array DIM1 (COOElem Int Double) sv1 = A.fromList (Z :. 3) [a, b, c] where a = CooE (0, 1, pi) b = CooE (0, 0, 2.3) c = CooE (1, 1, 1.23)
8273aeeb94dbbd197f9c65dc2e7a1df900918c499a88925d9a13d702cfc2ab20
marianoguerra-atik/riak_core_ring_on_partisans_plumtree
pring_peer_service.erl
-module(pring_peer_service). -export([join/1, leave/1, on_down/2, members/0, manager/0, stop/0, stop/1]). -export([join_p/1, leave_p/1, members_p/1, connections_p/1]). join(Node) -> partisan_peer_service:join(Node). leave(Node) -> partisan_peer_service:leave(Node). on_down(Name, Fun) -> partisan_default_peer_service_manager:on_down(Name, Fun). members() -> partisan_peer_service:members(). manager() -> partisan_peer_service:manager(). stop() -> partisan_peer_service:stop("received stop request"). stop(Reason) -> partisan_peer_service:stop(Reason). join_p(Node) -> io:format("~p~n", [join(Node)]). leave_p(Node) -> io:format("~p~n", [leave(Node)]). members_p([]) -> partisan_peer_service_console:members([]). connections_p([]) -> io:format("~p~n", [partisan_peer_service:connections()]).
null
https://raw.githubusercontent.com/marianoguerra-atik/riak_core_ring_on_partisans_plumtree/19167b7f111221dc9c4ae127ac9fd3120b17dda1/apps/pring/src/pring_peer_service.erl
erlang
-module(pring_peer_service). -export([join/1, leave/1, on_down/2, members/0, manager/0, stop/0, stop/1]). -export([join_p/1, leave_p/1, members_p/1, connections_p/1]). join(Node) -> partisan_peer_service:join(Node). leave(Node) -> partisan_peer_service:leave(Node). on_down(Name, Fun) -> partisan_default_peer_service_manager:on_down(Name, Fun). members() -> partisan_peer_service:members(). manager() -> partisan_peer_service:manager(). stop() -> partisan_peer_service:stop("received stop request"). stop(Reason) -> partisan_peer_service:stop(Reason). join_p(Node) -> io:format("~p~n", [join(Node)]). leave_p(Node) -> io:format("~p~n", [leave(Node)]). members_p([]) -> partisan_peer_service_console:members([]). connections_p([]) -> io:format("~p~n", [partisan_peer_service:connections()]).
989c2d95f8941449622391e54b32934ac82e477cb250667cffe631853a4525c1
larcenists/larceny
128.body1.scm
Copyright ( C ) ( 2015 ) . All Rights Reserved . ;;; ;;; 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. Main part of the SRFI 114 reference implementation " There are two ways of constructing a software design : One way is to ;;; make it so simple that there are obviously no deficiencies, and the ;;; other way is to make it so complicated that there are no *obvious* ;;; deficiencies." --Tony Hoare Syntax ( because syntax must be defined before it is used , contra Dr. ) ;; Arithmetic if (define-syntax comparator-if<=> (syntax-rules () ((if<=> a b less equal greater) (comparator-if<=> (make-default-comparator) a b less equal greater)) ((comparator-if<=> comparator a b less equal greater) (cond ((=? comparator a b) equal) ((<? comparator a b) less) (else greater))))) Upper bound of hash functions is 2 ^ 25 - 1 (define-syntax hash-bound (syntax-rules () ((hash-bound) 33554432))) (define %salt% (make-parameter 16064047)) (define-syntax hash-salt (syntax-rules () ((hash-salt) (%salt%)))) (define-syntax with-hash-salt (syntax-rules () ((with-hash-salt new-salt hash-func obj) (parameterize ((%salt% new-salt)) (hash-func obj))))) ;;; Definition of comparator records with accessors and basic comparator ;;; These next two definitions are commented out because they 've been replaced by ( srfi 128 kernel ) , which allows the comparators of SRFI 114 and SRFI 128 to be interoperable and interchangeable . #; (define-record-type comparator (make-raw-comparator type-test equality ordering hash ordering? hash?) comparator? (type-test comparator-type-test-predicate) (equality comparator-equality-predicate) (ordering comparator-ordering-predicate) (hash comparator-hash-function) (ordering? comparator-ordered?) (hash? comparator-hashable?)) ;; Public constructor #; (define (make-comparator type-test equality ordering hash) (make-raw-comparator (if (eq? type-test #t) (lambda (x) #t) type-test) (if (eq? equality #t) (lambda (x y) (eqv? (ordering x y) 0)) equality) (if ordering ordering (lambda (x y) (error "ordering not supported"))) (if hash hash (lambda (x y) (error "hashing not supported"))) (if ordering #t #f) (if hash #t #f))) ;; Invoke the test type (define (comparator-test-type comparator obj) ((comparator-type-test-predicate comparator) obj)) ;; Invoke the test type and throw an error if it fails (define (comparator-check-type comparator obj) (if (comparator-test-type comparator obj) #t (error "comparator type check failed" comparator obj))) ;; Invoke the hash function (define (comparator-hash comparator obj) ((comparator-hash-function comparator) obj)) Comparison predicates ;; Binary versions for internal use (define (binary=? comparator a b) ((comparator-equality-predicate comparator) a b)) (define (binary<? comparator a b) ((comparator-ordering-predicate comparator) a b)) (define (binary>? comparator a b) (binary<? comparator b a)) (define (binary<=? comparator a b) (not (binary>? comparator a b))) (define (binary>=? comparator a b) (not (binary<? comparator a b))) ;; General versions for export (define (=? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary=? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (<? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary<? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (>? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary>? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (<=? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary<=? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (>=? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary>=? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) ;;; Simple ordering and hash functions (define (boolean<? a b) ;; #f < #t but not otherwise (and (not a) b)) (define (boolean-hash obj) (if obj (%salt%) 0)) (define (char-hash obj) (modulo (* (%salt%) (char->integer obj)) (hash-bound))) (define (char-ci-hash obj) (modulo (* (%salt%) (char->integer (char-foldcase obj))) (hash-bound))) This does a lousy job of hashing , and is n't even portable R7RS , ;; so it's commented out. #; (define (number-hash obj) (cond ((nan? obj) (%salt%)) ((and (infinite? obj) (positive? obj)) (* 2 (%salt%))) ((infinite? obj) (* (%salt%) 3)) ((real? obj) (abs (exact (round obj)))) (else (+ (number-hash (real-part obj)) (number-hash (imag-part obj)))))) (define (number-hash obj) (equal-hash obj)) ordering of complex numbers (define (complex<? a b) (if (= (real-part a) (real-part b)) (< (imag-part a) (imag-part b)) (< (real-part a) (real-part b)))) Use string - ci - hash from ( ) instead . #; (define (string-ci-hash obj) (string-hash (string-foldcase obj))) (define (symbol<? a b) (string<? (symbol->string a) (symbol->string b))) Use symbol - hash from ( ) instead . #; (define (symbol-hash obj) (string-hash (symbol->string obj))) ;;; Wrapped equality predicates ;;; These comparators don't have ordering functions. (define (make-eq-comparator) (make-comparator #t eq? #f default-hash)) (define (make-eqv-comparator) (make-comparator #t eqv? #f default-hash)) (define (make-equal-comparator) (make-comparator #t equal? #f default-hash)) ;;; Sequence ordering and hash functions The hash functions are based on djb2 , but modulo 2 ^ 25 instead of 2 ^ 32 in hopes of sticking to fixnums . (define (make-hasher) (let ((result (%salt%))) (case-lambda (() result) ((n) (set! result (+ (modulo (* result 33) (hash-bound)) n)) result)))) ;;; Pair comparator (define (make-pair-comparator car-comparator cdr-comparator) (make-comparator (make-pair-type-test car-comparator cdr-comparator) (make-pair=? car-comparator cdr-comparator) (make-pair<? car-comparator cdr-comparator) (make-pair-hash car-comparator cdr-comparator))) (define (make-pair-type-test car-comparator cdr-comparator) (lambda (obj) (and (pair? obj) (comparator-test-type car-comparator (car obj)) (comparator-test-type cdr-comparator (cdr obj))))) (define (make-pair=? car-comparator cdr-comparator) (lambda (a b) (and ((comparator-equality-predicate car-comparator) (car a) (car b)) ((comparator-equality-predicate cdr-comparator) (cdr a) (cdr b))))) (define (make-pair<? car-comparator cdr-comparator) (lambda (a b) (if (=? car-comparator (car a) (car b)) (<? cdr-comparator (cdr a) (cdr b)) (<? car-comparator (car a) (car b))))) (define (make-pair-hash car-comparator cdr-comparator) (lambda (obj) (let ((acc (make-hasher))) (acc (comparator-hash car-comparator (car obj))) (acc (comparator-hash cdr-comparator (cdr obj))) (acc)))) ;;; List comparator ;; Cheap test for listness (define (norp? obj) (or (null? obj) (pair? obj))) (define (make-list-comparator element-comparator type-test empty? head tail) (make-comparator (make-list-type-test element-comparator type-test empty? head tail) (make-list=? element-comparator type-test empty? head tail) (make-list<? element-comparator type-test empty? head tail) (make-list-hash element-comparator type-test empty? head tail))) (define (make-list-type-test element-comparator type-test empty? head tail) (lambda (obj) (and (type-test obj) (let ((elem-type-test (comparator-type-test-predicate element-comparator))) (let loop ((obj obj)) (cond ((empty? obj) #t) ((not (elem-type-test (head obj))) #f) (else (loop (tail obj))))))))) (define (make-list=? element-comparator type-test empty? head tail) (lambda (a b) (let ((elem=? (comparator-equality-predicate element-comparator))) (let loop ((a a) (b b)) (cond ((and (empty? a) (empty? b) #t)) ((empty? a) #f) ((empty? b) #f) ((elem=? (head a) (head b)) (loop (tail a) (tail b))) (else #f)))))) (define (make-list<? element-comparator type-test empty? head tail) (lambda (a b) (let ((elem=? (comparator-equality-predicate element-comparator)) (elem<? (comparator-ordering-predicate element-comparator))) (let loop ((a a) (b b)) (cond ((and (empty? a) (empty? b) #f)) ((empty? a) #t) ((empty? b) #f) ((elem=? (head a) (head b)) (loop (tail a) (tail b))) ((elem<? (head a) (head b)) #t) (else #f)))))) (define (make-list-hash element-comparator type-test empty? head tail) (lambda (obj) (let ((elem-hash (comparator-hash-function element-comparator)) (acc (make-hasher))) (let loop ((obj obj)) (cond ((empty? obj) (acc)) (else (acc (elem-hash (head obj))) (loop (tail obj)))))))) ;;; Vector comparator (define (make-vector-comparator element-comparator type-test length ref) (make-comparator (make-vector-type-test element-comparator type-test length ref) (make-vector=? element-comparator type-test length ref) (make-vector<? element-comparator type-test length ref) (make-vector-hash element-comparator type-test length ref))) (define (make-vector-type-test element-comparator type-test length ref) (lambda (obj) (and (type-test obj) (let ((elem-type-test (comparator-type-test-predicate element-comparator)) (len (length obj))) (let loop ((n 0)) (cond ((= n len) #t) ((not (elem-type-test (ref obj n))) #f) (else (loop (+ n 1))))))))) (define (make-vector=? element-comparator type-test length ref) (lambda (a b) (and (= (length a) (length b)) (let ((elem=? (comparator-equality-predicate element-comparator)) (len (length b))) (let loop ((n 0)) (cond ((= n len) #t) ((elem=? (ref a n) (ref b n)) (loop (+ n 1))) (else #f))))))) (define (make-vector<? element-comparator type-test length ref) (lambda (a b) (cond ((< (length a) (length b)) #t) ((> (length a) (length b)) #f) (else (let ((elem=? (comparator-equality-predicate element-comparator)) (elem<? (comparator-ordering-predicate element-comparator)) (len (length a))) (let loop ((n 0)) (cond ((= n len) #f) ((elem=? (ref a n) (ref b n)) (loop (+ n 1))) ((elem<? (ref a n) (ref b n)) #t) (else #f)))))))) (define (make-vector-hash element-comparator type-test length ref) (lambda (obj) (let ((elem-hash (comparator-hash-function element-comparator)) (acc (make-hasher)) (len (length obj))) (let loop ((n 0)) (cond ((= n len) (acc)) (else (acc (elem-hash (ref obj n))) (loop (+ n 1)))))))) Use string - hash from ( ) instead . #; (define (string-hash obj) (let ((acc (make-hasher)) (len (string-length obj))) (let loop ((n 0)) (cond ((= n len) (acc)) (else (acc (char->integer (string-ref obj n))) (loop (+ n 1)))))))
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/lib/SRFI/srfi/128.body1.scm
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no *obvious* deficiencies." --Tony Hoare Arithmetic if Definition of comparator records with accessors and basic comparator Public constructor Invoke the test type Invoke the test type and throw an error if it fails Invoke the hash function Binary versions for internal use General versions for export Simple ordering and hash functions #f < #t but not otherwise so it's commented out. Wrapped equality predicates These comparators don't have ordering functions. Sequence ordering and hash functions Pair comparator List comparator Cheap test for listness Vector comparator
Copyright ( C ) ( 2015 ) . All Rights Reserved . files ( the " Software " ) , to deal in the Software without sell copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , Main part of the SRFI 114 reference implementation " There are two ways of constructing a software design : One way is to Syntax ( because syntax must be defined before it is used , contra Dr. ) (define-syntax comparator-if<=> (syntax-rules () ((if<=> a b less equal greater) (comparator-if<=> (make-default-comparator) a b less equal greater)) ((comparator-if<=> comparator a b less equal greater) (cond ((=? comparator a b) equal) ((<? comparator a b) less) (else greater))))) Upper bound of hash functions is 2 ^ 25 - 1 (define-syntax hash-bound (syntax-rules () ((hash-bound) 33554432))) (define %salt% (make-parameter 16064047)) (define-syntax hash-salt (syntax-rules () ((hash-salt) (%salt%)))) (define-syntax with-hash-salt (syntax-rules () ((with-hash-salt new-salt hash-func obj) (parameterize ((%salt% new-salt)) (hash-func obj))))) These next two definitions are commented out because they 've been replaced by ( srfi 128 kernel ) , which allows the comparators of SRFI 114 and SRFI 128 to be interoperable and interchangeable . (define-record-type comparator (make-raw-comparator type-test equality ordering hash ordering? hash?) comparator? (type-test comparator-type-test-predicate) (equality comparator-equality-predicate) (ordering comparator-ordering-predicate) (hash comparator-hash-function) (ordering? comparator-ordered?) (hash? comparator-hashable?)) (define (make-comparator type-test equality ordering hash) (make-raw-comparator (if (eq? type-test #t) (lambda (x) #t) type-test) (if (eq? equality #t) (lambda (x y) (eqv? (ordering x y) 0)) equality) (if ordering ordering (lambda (x y) (error "ordering not supported"))) (if hash hash (lambda (x y) (error "hashing not supported"))) (if ordering #t #f) (if hash #t #f))) (define (comparator-test-type comparator obj) ((comparator-type-test-predicate comparator) obj)) (define (comparator-check-type comparator obj) (if (comparator-test-type comparator obj) #t (error "comparator type check failed" comparator obj))) (define (comparator-hash comparator obj) ((comparator-hash-function comparator) obj)) Comparison predicates (define (binary=? comparator a b) ((comparator-equality-predicate comparator) a b)) (define (binary<? comparator a b) ((comparator-ordering-predicate comparator) a b)) (define (binary>? comparator a b) (binary<? comparator b a)) (define (binary<=? comparator a b) (not (binary>? comparator a b))) (define (binary>=? comparator a b) (not (binary<? comparator a b))) (define (=? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary=? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (<? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary<? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (>? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary>? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (<=? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary<=? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (>=? comparator a b . objs) (let loop ((a a) (b b) (objs objs)) (and (binary>=? comparator a b) (if (null? objs) #t (loop b (car objs) (cdr objs)))))) (define (boolean<? a b) (and (not a) b)) (define (boolean-hash obj) (if obj (%salt%) 0)) (define (char-hash obj) (modulo (* (%salt%) (char->integer obj)) (hash-bound))) (define (char-ci-hash obj) (modulo (* (%salt%) (char->integer (char-foldcase obj))) (hash-bound))) This does a lousy job of hashing , and is n't even portable R7RS , (define (number-hash obj) (cond ((nan? obj) (%salt%)) ((and (infinite? obj) (positive? obj)) (* 2 (%salt%))) ((infinite? obj) (* (%salt%) 3)) ((real? obj) (abs (exact (round obj)))) (else (+ (number-hash (real-part obj)) (number-hash (imag-part obj)))))) (define (number-hash obj) (equal-hash obj)) ordering of complex numbers (define (complex<? a b) (if (= (real-part a) (real-part b)) (< (imag-part a) (imag-part b)) (< (real-part a) (real-part b)))) Use string - ci - hash from ( ) instead . (define (string-ci-hash obj) (string-hash (string-foldcase obj))) (define (symbol<? a b) (string<? (symbol->string a) (symbol->string b))) Use symbol - hash from ( ) instead . (define (symbol-hash obj) (string-hash (symbol->string obj))) (define (make-eq-comparator) (make-comparator #t eq? #f default-hash)) (define (make-eqv-comparator) (make-comparator #t eqv? #f default-hash)) (define (make-equal-comparator) (make-comparator #t equal? #f default-hash)) The hash functions are based on djb2 , but modulo 2 ^ 25 instead of 2 ^ 32 in hopes of sticking to fixnums . (define (make-hasher) (let ((result (%salt%))) (case-lambda (() result) ((n) (set! result (+ (modulo (* result 33) (hash-bound)) n)) result)))) (define (make-pair-comparator car-comparator cdr-comparator) (make-comparator (make-pair-type-test car-comparator cdr-comparator) (make-pair=? car-comparator cdr-comparator) (make-pair<? car-comparator cdr-comparator) (make-pair-hash car-comparator cdr-comparator))) (define (make-pair-type-test car-comparator cdr-comparator) (lambda (obj) (and (pair? obj) (comparator-test-type car-comparator (car obj)) (comparator-test-type cdr-comparator (cdr obj))))) (define (make-pair=? car-comparator cdr-comparator) (lambda (a b) (and ((comparator-equality-predicate car-comparator) (car a) (car b)) ((comparator-equality-predicate cdr-comparator) (cdr a) (cdr b))))) (define (make-pair<? car-comparator cdr-comparator) (lambda (a b) (if (=? car-comparator (car a) (car b)) (<? cdr-comparator (cdr a) (cdr b)) (<? car-comparator (car a) (car b))))) (define (make-pair-hash car-comparator cdr-comparator) (lambda (obj) (let ((acc (make-hasher))) (acc (comparator-hash car-comparator (car obj))) (acc (comparator-hash cdr-comparator (cdr obj))) (acc)))) (define (norp? obj) (or (null? obj) (pair? obj))) (define (make-list-comparator element-comparator type-test empty? head tail) (make-comparator (make-list-type-test element-comparator type-test empty? head tail) (make-list=? element-comparator type-test empty? head tail) (make-list<? element-comparator type-test empty? head tail) (make-list-hash element-comparator type-test empty? head tail))) (define (make-list-type-test element-comparator type-test empty? head tail) (lambda (obj) (and (type-test obj) (let ((elem-type-test (comparator-type-test-predicate element-comparator))) (let loop ((obj obj)) (cond ((empty? obj) #t) ((not (elem-type-test (head obj))) #f) (else (loop (tail obj))))))))) (define (make-list=? element-comparator type-test empty? head tail) (lambda (a b) (let ((elem=? (comparator-equality-predicate element-comparator))) (let loop ((a a) (b b)) (cond ((and (empty? a) (empty? b) #t)) ((empty? a) #f) ((empty? b) #f) ((elem=? (head a) (head b)) (loop (tail a) (tail b))) (else #f)))))) (define (make-list<? element-comparator type-test empty? head tail) (lambda (a b) (let ((elem=? (comparator-equality-predicate element-comparator)) (elem<? (comparator-ordering-predicate element-comparator))) (let loop ((a a) (b b)) (cond ((and (empty? a) (empty? b) #f)) ((empty? a) #t) ((empty? b) #f) ((elem=? (head a) (head b)) (loop (tail a) (tail b))) ((elem<? (head a) (head b)) #t) (else #f)))))) (define (make-list-hash element-comparator type-test empty? head tail) (lambda (obj) (let ((elem-hash (comparator-hash-function element-comparator)) (acc (make-hasher))) (let loop ((obj obj)) (cond ((empty? obj) (acc)) (else (acc (elem-hash (head obj))) (loop (tail obj)))))))) (define (make-vector-comparator element-comparator type-test length ref) (make-comparator (make-vector-type-test element-comparator type-test length ref) (make-vector=? element-comparator type-test length ref) (make-vector<? element-comparator type-test length ref) (make-vector-hash element-comparator type-test length ref))) (define (make-vector-type-test element-comparator type-test length ref) (lambda (obj) (and (type-test obj) (let ((elem-type-test (comparator-type-test-predicate element-comparator)) (len (length obj))) (let loop ((n 0)) (cond ((= n len) #t) ((not (elem-type-test (ref obj n))) #f) (else (loop (+ n 1))))))))) (define (make-vector=? element-comparator type-test length ref) (lambda (a b) (and (= (length a) (length b)) (let ((elem=? (comparator-equality-predicate element-comparator)) (len (length b))) (let loop ((n 0)) (cond ((= n len) #t) ((elem=? (ref a n) (ref b n)) (loop (+ n 1))) (else #f))))))) (define (make-vector<? element-comparator type-test length ref) (lambda (a b) (cond ((< (length a) (length b)) #t) ((> (length a) (length b)) #f) (else (let ((elem=? (comparator-equality-predicate element-comparator)) (elem<? (comparator-ordering-predicate element-comparator)) (len (length a))) (let loop ((n 0)) (cond ((= n len) #f) ((elem=? (ref a n) (ref b n)) (loop (+ n 1))) ((elem<? (ref a n) (ref b n)) #t) (else #f)))))))) (define (make-vector-hash element-comparator type-test length ref) (lambda (obj) (let ((elem-hash (comparator-hash-function element-comparator)) (acc (make-hasher)) (len (length obj))) (let loop ((n 0)) (cond ((= n len) (acc)) (else (acc (elem-hash (ref obj n))) (loop (+ n 1)))))))) Use string - hash from ( ) instead . (define (string-hash obj) (let ((acc (make-hasher)) (len (string-length obj))) (let loop ((n 0)) (cond ((= n len) (acc)) (else (acc (char->integer (string-ref obj n))) (loop (+ n 1)))))))
87ad62de888561f6870ee6a162ab82c1c98a0d4fbb7bc527fd293b6acb656954
cedlemo/OCaml-GI-ctypes-bindings-generator
Recent_chooser_error.ml
open Ctypes open Foreign type t = Not_found | Invalid_uri let of_value v = if v = Unsigned.UInt32.of_int 0 then Not_found else if v = Unsigned.UInt32.of_int 1 then Invalid_uri else raise (Invalid_argument "Unexpected Recent_chooser_error value") let to_value = function | Not_found -> Unsigned.UInt32.of_int 0 | Invalid_uri -> Unsigned.UInt32.of_int 1 let t_view = view ~read:of_value ~write:to_value uint32_t
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Recent_chooser_error.ml
ocaml
open Ctypes open Foreign type t = Not_found | Invalid_uri let of_value v = if v = Unsigned.UInt32.of_int 0 then Not_found else if v = Unsigned.UInt32.of_int 1 then Invalid_uri else raise (Invalid_argument "Unexpected Recent_chooser_error value") let to_value = function | Not_found -> Unsigned.UInt32.of_int 0 | Invalid_uri -> Unsigned.UInt32.of_int 1 let t_view = view ~read:of_value ~write:to_value uint32_t
0867aeb0f0db650da3d4893441c849c42b055bd877fcce2083fba79995725e17
scverif/scverif
asmlifter.mli
Copyright 2019 - Inria , NXP SPDX - License - Identifier : BSD-3 - Clause - Clear WITH modifications val lift_section : Asmast.section -> Ilast.macro_decl Location.located
null
https://raw.githubusercontent.com/scverif/scverif/307a17b61a2286fb7009d434825f9245caebfddc/src/asmlifter.mli
ocaml
Copyright 2019 - Inria , NXP SPDX - License - Identifier : BSD-3 - Clause - Clear WITH modifications val lift_section : Asmast.section -> Ilast.macro_decl Location.located
d259ba0e34e84b0a915d9b2ff68faa8b40dedaf8d97b7301f8aae2a24da8fc48
kblake/erlang-chat-demo
element_h3.erl
Nitrogen Web Framework for Erlang Copyright ( c ) 2008 - 2010 See MIT - LICENSE for licensing information . -module (element_h3). -include_lib ("wf.hrl"). -compile(export_all). reflect() -> record_info(fields, h3). render_element(Record) -> Text = wf:html_encode(Record#h3.text, Record#h3.html_encode), wf_tags:emit_tag(h3, Text, [ {class, [h3, Record#h3.class]}, {style, Record#h3.style} ]).
null
https://raw.githubusercontent.com/kblake/erlang-chat-demo/6fd2fce12f2e059e25a24c9a84169b088710edaf/apps/nitrogen/src/elements/heading/element_h3.erl
erlang
Nitrogen Web Framework for Erlang Copyright ( c ) 2008 - 2010 See MIT - LICENSE for licensing information . -module (element_h3). -include_lib ("wf.hrl"). -compile(export_all). reflect() -> record_info(fields, h3). render_element(Record) -> Text = wf:html_encode(Record#h3.text, Record#h3.html_encode), wf_tags:emit_tag(h3, Text, [ {class, [h3, Record#h3.class]}, {style, Record#h3.style} ]).
1a789a18194924647cb0349cd0ef279304dc0c4694205d39bd1b32dd5a4de933
spinda/liquidhaskell-cabal-demo
Setup.hs
import Distribution.Simple import LiquidHaskell.Cabal data Choice = Simple | Post choice :: Choice choice = Post -- Simple main :: IO () main = case choice of Simple -> liquidHaskellMain Post -> liquidHaskellMainHooks
null
https://raw.githubusercontent.com/spinda/liquidhaskell-cabal-demo/715b051f8352ddb3a81611b4b3db52ef5eb9ad50/Setup.hs
haskell
Simple
import Distribution.Simple import LiquidHaskell.Cabal data Choice = Simple | Post choice :: Choice main :: IO () main = case choice of Simple -> liquidHaskellMain Post -> liquidHaskellMainHooks
10dc35ff6c3c308b65622149458f5b85828231619e419c0127f42215a8137429
TrustInSoft/tis-kernel
intmap.mli
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) * Maps with integers keys using . From the paper of and : ' Fast Maps ' . From the paper of Chris Okasaki and Andrew Gill: 'Fast Mergeable Integer Maps'. *) type 'a t val empty : 'a t val singleton : int -> 'a -> 'a t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val is_empty : 'a t -> bool val size : 'a t -> int val mem : int -> 'a t -> bool val find : int -> 'a t -> 'a (** or raise Not_found *) val add : int -> 'a -> 'a t -> 'a t val remove : int -> 'a t -> 'a t (** [insert (fun key v old -> ...) key v map] *) val insert : (int -> 'a -> 'a -> 'a) -> int -> 'a -> 'a t -> 'a t val change : (int -> 'b -> 'a option -> 'a option) -> int -> 'b -> 'a t -> 'a t val iter : ('a -> unit) -> 'a t -> unit val iteri : (int -> 'a -> unit) -> 'a t -> unit val fold : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b val foldi : (int -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val mapl : (int -> 'a -> 'b) -> 'a t -> 'b list val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t val mapf : (int -> 'a -> 'b option) -> 'a t -> 'b t val mapq : (int -> 'a -> 'a option) -> 'a t -> 'a t val filter : (int -> 'a -> bool) -> 'a t -> 'a t val partition : (int -> 'a -> bool) -> 'a t -> 'a t * 'a t val partition_split : (int -> 'a -> 'a option * 'a option) -> 'a t -> 'a t * 'a t val for_all: (int -> 'a -> bool) -> 'a t -> bool val exists: (int -> 'a -> bool) -> 'a t -> bool val union : (int -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t val inter : (int -> 'a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t val interf : (int -> 'a -> 'b -> 'c option) -> 'a t -> 'b t -> 'c t val interq : (int -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val diffq : (int -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val subsetk : 'a t -> 'b t -> bool val subset : (int -> 'a -> 'b -> bool) -> 'a t -> 'b t -> bool val intersect : 'a t -> 'b t -> bool val intersectf : (int -> 'a -> 'b -> bool) -> 'a t -> 'b t -> bool val merge : (int -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t val iter2 : (int -> 'a option -> 'b option -> unit) -> 'a t -> 'b t -> unit val iterk : (int -> 'a -> 'b -> unit) -> 'a t -> 'b t -> unit val pp_bits : Format.formatter -> int -> unit val pp_tree : string -> Format.formatter -> 'a t -> unit
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/wp/qed/src/intmap.mli
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * or raise Not_found * [insert (fun key v old -> ...) key v map]
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * Maps with integers keys using . From the paper of and : ' Fast Maps ' . From the paper of Chris Okasaki and Andrew Gill: 'Fast Mergeable Integer Maps'. *) type 'a t val empty : 'a t val singleton : int -> 'a -> 'a t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val is_empty : 'a t -> bool val size : 'a t -> int val mem : int -> 'a t -> bool val add : int -> 'a -> 'a t -> 'a t val remove : int -> 'a t -> 'a t val insert : (int -> 'a -> 'a -> 'a) -> int -> 'a -> 'a t -> 'a t val change : (int -> 'b -> 'a option -> 'a option) -> int -> 'b -> 'a t -> 'a t val iter : ('a -> unit) -> 'a t -> unit val iteri : (int -> 'a -> unit) -> 'a t -> unit val fold : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b val foldi : (int -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val mapl : (int -> 'a -> 'b) -> 'a t -> 'b list val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t val mapf : (int -> 'a -> 'b option) -> 'a t -> 'b t val mapq : (int -> 'a -> 'a option) -> 'a t -> 'a t val filter : (int -> 'a -> bool) -> 'a t -> 'a t val partition : (int -> 'a -> bool) -> 'a t -> 'a t * 'a t val partition_split : (int -> 'a -> 'a option * 'a option) -> 'a t -> 'a t * 'a t val for_all: (int -> 'a -> bool) -> 'a t -> bool val exists: (int -> 'a -> bool) -> 'a t -> bool val union : (int -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t val inter : (int -> 'a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t val interf : (int -> 'a -> 'b -> 'c option) -> 'a t -> 'b t -> 'c t val interq : (int -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val diffq : (int -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val subsetk : 'a t -> 'b t -> bool val subset : (int -> 'a -> 'b -> bool) -> 'a t -> 'b t -> bool val intersect : 'a t -> 'b t -> bool val intersectf : (int -> 'a -> 'b -> bool) -> 'a t -> 'b t -> bool val merge : (int -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t val iter2 : (int -> 'a option -> 'b option -> unit) -> 'a t -> 'b t -> unit val iterk : (int -> 'a -> 'b -> unit) -> 'a t -> 'b t -> unit val pp_bits : Format.formatter -> int -> unit val pp_tree : string -> Format.formatter -> 'a t -> unit
a38af9f3ffa422e3e2fdad47bf0e6286560f964a47e4524fe58100ce3748a97f
kiselgra/c-mera
c.misc.04.hex.lisp
(include <stdio.h>) (function main () -> int (printf "%d\\n" 0x01) (printf "%d\\n" 012) (return 0)) # # 1 # # 12
null
https://raw.githubusercontent.com/kiselgra/c-mera/d06ed96d50a40a3fefe188202c8c535d6784f392/tests/c.misc.04.hex.lisp
lisp
(include <stdio.h>) (function main () -> int (printf "%d\\n" 0x01) (printf "%d\\n" 012) (return 0)) # # 1 # # 12
cf9ac2b5b496885d3b8c5d198ce6fccb48ac9c6d200e3b02b541a624ecbd1bc5
ghcjs/ghcjs-dom
MimeType.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.MimeType (js_getType, getType, js_getSuffixes, getSuffixes, js_getDescription, getDescription, js_getEnabledPlugin, getEnabledPlugin, MimeType(..), gTypeMimeType) 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 foreign import javascript unsafe "$1[\"type\"]" js_getType :: MimeType -> IO JSString | < -US/docs/Web/API/MimeType.type Mozilla MimeType.type documentation > getType :: (MonadIO m, FromJSString result) => MimeType -> m result getType self = liftIO (fromJSString <$> (js_getType self)) foreign import javascript unsafe "$1[\"suffixes\"]" js_getSuffixes :: MimeType -> IO JSString | < -US/docs/Web/API/MimeType.suffixes Mozilla MimeType.suffixes documentation > getSuffixes :: (MonadIO m, FromJSString result) => MimeType -> m result getSuffixes self = liftIO (fromJSString <$> (js_getSuffixes self)) foreign import javascript unsafe "$1[\"description\"]" js_getDescription :: MimeType -> IO JSString | < -US/docs/Web/API/MimeType.description Mozilla MimeType.description documentation > getDescription :: (MonadIO m, FromJSString result) => MimeType -> m result getDescription self = liftIO (fromJSString <$> (js_getDescription self)) foreign import javascript unsafe "$1[\"enabledPlugin\"]" js_getEnabledPlugin :: MimeType -> IO Plugin | < -US/docs/Web/API/MimeType.enabledPlugin Mozilla MimeType.enabledPlugin documentation > getEnabledPlugin :: (MonadIO m) => MimeType -> m Plugin getEnabledPlugin self = liftIO (js_getEnabledPlugin self)
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MimeType.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.MimeType (js_getType, getType, js_getSuffixes, getSuffixes, js_getDescription, getDescription, js_getEnabledPlugin, getEnabledPlugin, MimeType(..), gTypeMimeType) 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 foreign import javascript unsafe "$1[\"type\"]" js_getType :: MimeType -> IO JSString | < -US/docs/Web/API/MimeType.type Mozilla MimeType.type documentation > getType :: (MonadIO m, FromJSString result) => MimeType -> m result getType self = liftIO (fromJSString <$> (js_getType self)) foreign import javascript unsafe "$1[\"suffixes\"]" js_getSuffixes :: MimeType -> IO JSString | < -US/docs/Web/API/MimeType.suffixes Mozilla MimeType.suffixes documentation > getSuffixes :: (MonadIO m, FromJSString result) => MimeType -> m result getSuffixes self = liftIO (fromJSString <$> (js_getSuffixes self)) foreign import javascript unsafe "$1[\"description\"]" js_getDescription :: MimeType -> IO JSString | < -US/docs/Web/API/MimeType.description Mozilla MimeType.description documentation > getDescription :: (MonadIO m, FromJSString result) => MimeType -> m result getDescription self = liftIO (fromJSString <$> (js_getDescription self)) foreign import javascript unsafe "$1[\"enabledPlugin\"]" js_getEnabledPlugin :: MimeType -> IO Plugin | < -US/docs/Web/API/MimeType.enabledPlugin Mozilla MimeType.enabledPlugin documentation > getEnabledPlugin :: (MonadIO m) => MimeType -> m Plugin getEnabledPlugin self = liftIO (js_getEnabledPlugin self)
59c31204613e9ecf78fcf8af28d8d485b6bf1cd0ff4f77e23664abd35a8ca7cd
yapsterapp/er-cassandra
tables.clj
(ns er-cassandra.dump.tables (:require [cats.core :as monad :refer [return]] [clojure.java.io :as io] [er-cassandra.record :as cass.r] [er-cassandra.session :as cass.session] [er-cassandra.schema :as cass.schema] [prpr.promise :as pr :refer [ddo]] [prpr.stream :as stream] [qbits.hayt :as h] [taoensso.timbre :as timbre :refer [info]] [er-cassandra.dump.transit :as d.t]) (:import [com.cognitect.transit WriteHandler ReadHandler] [java.io EOFException])) (defn keyspace-table-name [keyspace table] (keyword (str (name keyspace) "." (name table)))) (defn counter-table? "returns true if the given table is a counter table" [cassandra keyspace table] (ddo [{tm-flags :flags :as tm} (cass.schema/table-metadata cassandra keyspace table)] (contains? tm-flags "counter"))) (defn key-counter-columns "returns [key-cols counter-col] for a counter table, nil otherwise" [cassandra keyspace table] (ddo [cols (cass.schema/table-columns-metadata cassandra keyspace table) :let [counter-col? #(= "counter" (:type %)) [counter-col] (filter counter-col? cols) key-cols (remove counter-col? cols)]] (return (if (some? counter-col) [(->> key-cols (map :column_name) (mapv keyword)) (-> counter-col :column_name keyword)])))) (defn keyspace-table-name-s "return a stream of all the table names in a keyspace which are not in the skip set" [cassandra keyspace skip] (ddo [table-s (cass.session/execute-buffered cassandra (str "select * from system_schema.tables where keyspace_name='" (name keyspace) "'") {}) :let [skip-set (->> skip (map keyword) set)]] (->> table-s (stream/map :table_name) (stream/map keyword) (stream/filter #(not (skip-set %))) return))) (defn remove-nil-values [r] (->> r (filter (fn [[k v]] (some? v))) (into {}))) (defn table->record-s "return a stream of records from a table" [cassandra keyspace table] (ddo [r-s (cass.r/select-buffered cassandra (keyspace-table-name keyspace table))] (return ;; remove nil values from the record streams ;; to avoid creating tombstones (stream/map remove-nil-values r-s)))) (defn dump-table [cassandra keyspace directory table] (ddo [:let [table (keyword table) directory (io/file directory) f (io/file directory (str (name table) ".transit"))] r-s (table->record-s cassandra keyspace table)] (d.t/record-s->transit-file f {:stream-name table :notify-s (d.t/log-notify-stream)} r-s))) (defn dump-tables [cassandra keyspace directory tables] (ddo [:let [table-s (stream/->source tables)] table-cnt (->> table-s (stream/map-concurrently 3 (fn [t] (ddo [r-s (table->record-s cassandra keyspace t)] (d.t/record-s->transit-file (io/file directory (str (name t) ".transit")) {:stream-name (name t) :notify-s (d.t/log-notify-stream)} r-s)))) (stream/count-all-throw ::dump-tables))] (info "dump-tables dumped" table-cnt "tables - FINISHED") (return table-cnt))) (defn dump-all-keyspace-tables "dump cassandra tables from a keyspace to EDN files in a directory" [cassandra keyspace directory skip] (ddo [table-s (keyspace-table-name-s cassandra keyspace skip)] (dump-tables cassandra keyspace directory table-s))) (defn insert-normal-record [cassandra keyspace table record] (cass.r/insert cassandra table (remove-nil-values record) {:prepare? true :consistency :any})) (defn update-counter-record "counter tables require an update statment... which requires an assumption that the counter table has been truncated" [cassandra keyspace table counter-key-cols counter-col record] ;; (warn "update-counter-record" { : keyspace keyspace ;; :table table ;; :counter-key-cols counter-key-cols ;; :counter-col counter-col ;; :record record}) (let [counter-val (get record counter-col)] (if (and (some? counter-val) (> counter-val 0)) (cass.r/update cassandra (keyspace-table-name keyspace table) counter-key-cols (assoc record counter-col [:+ counter-val]) {;; :prepare? has a bug for [:+] stmts ;; :prepare? true ;; :any not supported for prepared counter tables ;; :consistency :any }) (pr/success-pr nil)))) (defn load-record-s->table "load a stream of records to a table" [cassandra keyspace table {notify-s :notify-s notify-cnt :notify-cnt :as opts} r-s] (ddo [:let [notify-cnt (or notify-cnt 10000) counter-a (atom 0) update-counter-fn (fn [cnt] (let [nc (inc cnt)] (when (and notify-s (= 0 (mod nc notify-cnt))) (stream/try-put! notify-s [table nc] 0)) nc))] [counter-key-cols counter-col :as counter-table] (key-counter-columns cassandra keyspace table) ;; truncating means we can avoid inserting any null columns ;; and avoid creating lots of tombstones _ (cass.session/execute cassandra (h/truncate (keyspace-table-name keyspace table)) {}) total-cnt (->> r-s (stream/map-concurrently 50 (fn [r] (swap! counter-a update-counter-fn) (if (some? counter-col) (update-counter-record cassandra keyspace table counter-key-cols counter-col r) (insert-normal-record cassandra keyspace table r)))) (stream/count-all-throw ::load-record-s->table))] (when notify-s (stream/put! notify-s [table total-cnt :drained]) (stream/close! notify-s)) (return total-cnt))) (defn transit-file->entity-record-s [keyspace directory table] (ddo [:let [f (io/file directory (str (name table) ".transit"))] raw-s (d.t/transit-file->record-s f)] (return (stream/map remove-nil-values raw-s)))) (defn load-table "load a single table" [cassandra keyspace directory table] (ddo [:let [table (keyword table) directory (-> directory io/file) f (io/file directory (str (name table) ".transit"))] r-s (transit-file->entity-record-s keyspace directory table)] (load-record-s->table cassandra keyspace table {:counter-table table :notify-s (d.t/log-notify-stream)} r-s))) (defn load-tables [cassandra keyspace directory tables] (ddo [:let [table-s (stream/->source tables)] table-cnt (->> table-s (stream/map-concurrently 3 (fn [[t-n f]] (ddo [r-s (d.t/transit-file->record-s f)] (load-record-s->table cassandra keyspace t-n {:notify-s (d.t/log-notify-stream)} r-s)))) (stream/count-all-throw ::load-table))] (info "load-tables loaded " table-cnt "tables - FINISHED") (return table-cnt))) (defn load-all-tables-from-directory "load tables from EDN files in a directory to a cassandra keyspace" [cassandra keyspace directory skip] (ddo [:let [skip-set (->> skip (map keyword) set) file-s (-> directory io/file .listFiles seq stream/->source)] table-s (->> file-s (stream/map (fn [f] (let [[_ t-n] (re-matches #"^([^\.]+)(?:\..*)?$" (.getName f))] [(keyword t-n) f]))) (stream/filter (fn [[t-n f]] (not (skip-set t-n)))))] (load-tables cassandra keyspace directory table-s)))
null
https://raw.githubusercontent.com/yapsterapp/er-cassandra/1d059f47bdf8654c7a4dd6f0759f1a114fdeba81/src/er_cassandra/dump/tables.clj
clojure
remove nil values from the record streams to avoid creating tombstones (warn "update-counter-record" :table table :counter-key-cols counter-key-cols :counter-col counter-col :record record}) :prepare? has a bug for [:+] stmts :prepare? true :any not supported for prepared counter tables :consistency :any truncating means we can avoid inserting any null columns and avoid creating lots of tombstones
(ns er-cassandra.dump.tables (:require [cats.core :as monad :refer [return]] [clojure.java.io :as io] [er-cassandra.record :as cass.r] [er-cassandra.session :as cass.session] [er-cassandra.schema :as cass.schema] [prpr.promise :as pr :refer [ddo]] [prpr.stream :as stream] [qbits.hayt :as h] [taoensso.timbre :as timbre :refer [info]] [er-cassandra.dump.transit :as d.t]) (:import [com.cognitect.transit WriteHandler ReadHandler] [java.io EOFException])) (defn keyspace-table-name [keyspace table] (keyword (str (name keyspace) "." (name table)))) (defn counter-table? "returns true if the given table is a counter table" [cassandra keyspace table] (ddo [{tm-flags :flags :as tm} (cass.schema/table-metadata cassandra keyspace table)] (contains? tm-flags "counter"))) (defn key-counter-columns "returns [key-cols counter-col] for a counter table, nil otherwise" [cassandra keyspace table] (ddo [cols (cass.schema/table-columns-metadata cassandra keyspace table) :let [counter-col? #(= "counter" (:type %)) [counter-col] (filter counter-col? cols) key-cols (remove counter-col? cols)]] (return (if (some? counter-col) [(->> key-cols (map :column_name) (mapv keyword)) (-> counter-col :column_name keyword)])))) (defn keyspace-table-name-s "return a stream of all the table names in a keyspace which are not in the skip set" [cassandra keyspace skip] (ddo [table-s (cass.session/execute-buffered cassandra (str "select * from system_schema.tables where keyspace_name='" (name keyspace) "'") {}) :let [skip-set (->> skip (map keyword) set)]] (->> table-s (stream/map :table_name) (stream/map keyword) (stream/filter #(not (skip-set %))) return))) (defn remove-nil-values [r] (->> r (filter (fn [[k v]] (some? v))) (into {}))) (defn table->record-s "return a stream of records from a table" [cassandra keyspace table] (ddo [r-s (cass.r/select-buffered cassandra (keyspace-table-name keyspace table))] (return (stream/map remove-nil-values r-s)))) (defn dump-table [cassandra keyspace directory table] (ddo [:let [table (keyword table) directory (io/file directory) f (io/file directory (str (name table) ".transit"))] r-s (table->record-s cassandra keyspace table)] (d.t/record-s->transit-file f {:stream-name table :notify-s (d.t/log-notify-stream)} r-s))) (defn dump-tables [cassandra keyspace directory tables] (ddo [:let [table-s (stream/->source tables)] table-cnt (->> table-s (stream/map-concurrently 3 (fn [t] (ddo [r-s (table->record-s cassandra keyspace t)] (d.t/record-s->transit-file (io/file directory (str (name t) ".transit")) {:stream-name (name t) :notify-s (d.t/log-notify-stream)} r-s)))) (stream/count-all-throw ::dump-tables))] (info "dump-tables dumped" table-cnt "tables - FINISHED") (return table-cnt))) (defn dump-all-keyspace-tables "dump cassandra tables from a keyspace to EDN files in a directory" [cassandra keyspace directory skip] (ddo [table-s (keyspace-table-name-s cassandra keyspace skip)] (dump-tables cassandra keyspace directory table-s))) (defn insert-normal-record [cassandra keyspace table record] (cass.r/insert cassandra table (remove-nil-values record) {:prepare? true :consistency :any})) (defn update-counter-record "counter tables require an update statment... which requires an assumption that the counter table has been truncated" [cassandra keyspace table counter-key-cols counter-col record] { : keyspace keyspace (let [counter-val (get record counter-col)] (if (and (some? counter-val) (> counter-val 0)) (cass.r/update cassandra (keyspace-table-name keyspace table) counter-key-cols (assoc record counter-col [:+ counter-val]) }) (pr/success-pr nil)))) (defn load-record-s->table "load a stream of records to a table" [cassandra keyspace table {notify-s :notify-s notify-cnt :notify-cnt :as opts} r-s] (ddo [:let [notify-cnt (or notify-cnt 10000) counter-a (atom 0) update-counter-fn (fn [cnt] (let [nc (inc cnt)] (when (and notify-s (= 0 (mod nc notify-cnt))) (stream/try-put! notify-s [table nc] 0)) nc))] [counter-key-cols counter-col :as counter-table] (key-counter-columns cassandra keyspace table) _ (cass.session/execute cassandra (h/truncate (keyspace-table-name keyspace table)) {}) total-cnt (->> r-s (stream/map-concurrently 50 (fn [r] (swap! counter-a update-counter-fn) (if (some? counter-col) (update-counter-record cassandra keyspace table counter-key-cols counter-col r) (insert-normal-record cassandra keyspace table r)))) (stream/count-all-throw ::load-record-s->table))] (when notify-s (stream/put! notify-s [table total-cnt :drained]) (stream/close! notify-s)) (return total-cnt))) (defn transit-file->entity-record-s [keyspace directory table] (ddo [:let [f (io/file directory (str (name table) ".transit"))] raw-s (d.t/transit-file->record-s f)] (return (stream/map remove-nil-values raw-s)))) (defn load-table "load a single table" [cassandra keyspace directory table] (ddo [:let [table (keyword table) directory (-> directory io/file) f (io/file directory (str (name table) ".transit"))] r-s (transit-file->entity-record-s keyspace directory table)] (load-record-s->table cassandra keyspace table {:counter-table table :notify-s (d.t/log-notify-stream)} r-s))) (defn load-tables [cassandra keyspace directory tables] (ddo [:let [table-s (stream/->source tables)] table-cnt (->> table-s (stream/map-concurrently 3 (fn [[t-n f]] (ddo [r-s (d.t/transit-file->record-s f)] (load-record-s->table cassandra keyspace t-n {:notify-s (d.t/log-notify-stream)} r-s)))) (stream/count-all-throw ::load-table))] (info "load-tables loaded " table-cnt "tables - FINISHED") (return table-cnt))) (defn load-all-tables-from-directory "load tables from EDN files in a directory to a cassandra keyspace" [cassandra keyspace directory skip] (ddo [:let [skip-set (->> skip (map keyword) set) file-s (-> directory io/file .listFiles seq stream/->source)] table-s (->> file-s (stream/map (fn [f] (let [[_ t-n] (re-matches #"^([^\.]+)(?:\..*)?$" (.getName f))] [(keyword t-n) f]))) (stream/filter (fn [[t-n f]] (not (skip-set t-n)))))] (load-tables cassandra keyspace directory table-s)))
057cf1acbb0e09327c0ce5997d513339bd484394d7fced61ff398a3ac1ae6e63
kowey/GenI
FeatureStructure.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -fno - warn - orphans # module NLP.GenI.Test.FeatureStructure where import Control.Arrow ( (***) ) import Control.Monad ( liftM, liftM2 ) import GHC.Exts ( IsString(..) ) import Data.Maybe (isJust) import qualified Data.Map as Map import qualified Data.Text as T import Test.HUnit import Test.QuickCheck hiding (collect, Failure) import Test.QuickCheck.Arbitrary import Test.SmallCheck.Series import Test.Framework import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import NLP.GenI.GeniVal import NLP.GenI.Test.GeniVal ( gTestStrings, shrinkText ) import NLP.GenI.FeatureStructure import NLP.GenI.Parser ( geniLanguageDef ) import Text.ParserCombinators.Parsec.Token ( reservedNames ) suite :: Test.Framework.Test suite = testGroup "NLP.GenI.FeatureStructure" [ ] -- ---------------------------------------------------------------------- -- -- ---------------------------------------------------------------------- instance Arbitrary v => Arbitrary (AvPair v) where arbitrary = liftM2 AvPair arbitraryAtt arbitrary shrink x = do v <- shrink (avVal x) a <- shrinkText (avAtt x) return (AvPair a v) arbitraryAtt = elements (map T.pack (reservedNames geniLanguageDef) ++ gTestStrings) shrinkFeatStruct :: Arbitrary a => FeatStruct a -> [FeatStruct a] shrinkFeatStruct = fmap Map.fromList . shrinkList shrinkPair . Map.toList where shrinkPair (t, v) = do t2 <- shrinkText t v2 <- shrink v return (t2, v2) -- via derive instance ( Serial a ) = > Serial ( AvPair a ) where series = coseries rs d = [ \ t - > case t of AvPair x1 x2 - > t0 x1 x2 | t0 < - alts2 rs d ] -- via derive instance (Serial a) => Serial (AvPair a) where series = cons2 AvPair coseries rs d = [\ t -> case t of AvPair x1 x2 -> t0 x1 x2 | t0 <- alts2 rs d] -}
null
https://raw.githubusercontent.com/kowey/GenI/570a6ef70e61a7cb01fe0fc29732cd9c1c8f2d7a/geni-test/NLP/GenI/Test/FeatureStructure.hs
haskell
# LANGUAGE OverloadedStrings # ---------------------------------------------------------------------- ---------------------------------------------------------------------- via derive via derive
# LANGUAGE FlexibleInstances # # OPTIONS_GHC -fno - warn - orphans # module NLP.GenI.Test.FeatureStructure where import Control.Arrow ( (***) ) import Control.Monad ( liftM, liftM2 ) import GHC.Exts ( IsString(..) ) import Data.Maybe (isJust) import qualified Data.Map as Map import qualified Data.Text as T import Test.HUnit import Test.QuickCheck hiding (collect, Failure) import Test.QuickCheck.Arbitrary import Test.SmallCheck.Series import Test.Framework import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import NLP.GenI.GeniVal import NLP.GenI.Test.GeniVal ( gTestStrings, shrinkText ) import NLP.GenI.FeatureStructure import NLP.GenI.Parser ( geniLanguageDef ) import Text.ParserCombinators.Parsec.Token ( reservedNames ) suite :: Test.Framework.Test suite = testGroup "NLP.GenI.FeatureStructure" [ ] instance Arbitrary v => Arbitrary (AvPair v) where arbitrary = liftM2 AvPair arbitraryAtt arbitrary shrink x = do v <- shrink (avVal x) a <- shrinkText (avAtt x) return (AvPair a v) arbitraryAtt = elements (map T.pack (reservedNames geniLanguageDef) ++ gTestStrings) shrinkFeatStruct :: Arbitrary a => FeatStruct a -> [FeatStruct a] shrinkFeatStruct = fmap Map.fromList . shrinkList shrinkPair . Map.toList where shrinkPair (t, v) = do t2 <- shrinkText t v2 <- shrink v return (t2, v2) instance ( Serial a ) = > Serial ( AvPair a ) where series = coseries rs d = [ \ t - > case t of AvPair x1 x2 - > t0 x1 x2 | t0 < - alts2 rs d ] instance (Serial a) => Serial (AvPair a) where series = cons2 AvPair coseries rs d = [\ t -> case t of AvPair x1 x2 -> t0 x1 x2 | t0 <- alts2 rs d] -}
35bec3daf4c58a1e23e834da087bdb38143c111de1b1162fe9202f1a56a75bd5
polyfy/polylith
m107_missing_componens_in_project_test.clj
(ns polylith.clj.core.validator.m107-missing-componens-in-project-test (:require [clojure.test :refer :all] [polylith.clj.core.util.interface.color :as color] [polylith.clj.core.validator.m107-missing-componens-in-project :as m107]) (:refer-clojure :exclude [bases])) (def settings {:profile-to-settings {"default" {:paths [] :lib-deps {}} "admin" {:paths [] :lib-deps {"zprint" #:mvn{:version "0.4.15"}}}}}) (def projects [{:name "poly-migrator" :deps {"common" {:src {:direct ["file"] :missing-ifc {:direct ["user-config"] :indirect ["util"]} :indirect []}} "lib-dep" {:src {:direct ["common" "util"] :indirect ["file"]}}}}]) (def components [{:name "file" :interface {:name "file"}} {:name "util" :interface {:name "util"}} {:name "user-config" :interface {:name "user-config"}}]) (deftest errors--when-no-active-profiles--ignore-error (is (= nil (m107/errors "info" settings projects components color/none)))) (deftest errors--when-projects-with-missing-components--return-error (is (= [{:code 107 :colorized-message "Missing components in the poly-migrator project for these interfaces: user-config, util" :interfaces ["user-config" "util"] :message "Missing components in the poly-migrator project for these interfaces: user-config, util" :project "poly-migrator" :type "error"}] (m107/errors "info" (assoc settings :active-profiles #{"default"}) projects components color/none))))
null
https://raw.githubusercontent.com/polyfy/polylith/febea3d8a9b30a60397594dda3cb0f25154b8d8d/components/validator/test/polylith/clj/core/validator/m107_missing_componens_in_project_test.clj
clojure
(ns polylith.clj.core.validator.m107-missing-componens-in-project-test (:require [clojure.test :refer :all] [polylith.clj.core.util.interface.color :as color] [polylith.clj.core.validator.m107-missing-componens-in-project :as m107]) (:refer-clojure :exclude [bases])) (def settings {:profile-to-settings {"default" {:paths [] :lib-deps {}} "admin" {:paths [] :lib-deps {"zprint" #:mvn{:version "0.4.15"}}}}}) (def projects [{:name "poly-migrator" :deps {"common" {:src {:direct ["file"] :missing-ifc {:direct ["user-config"] :indirect ["util"]} :indirect []}} "lib-dep" {:src {:direct ["common" "util"] :indirect ["file"]}}}}]) (def components [{:name "file" :interface {:name "file"}} {:name "util" :interface {:name "util"}} {:name "user-config" :interface {:name "user-config"}}]) (deftest errors--when-no-active-profiles--ignore-error (is (= nil (m107/errors "info" settings projects components color/none)))) (deftest errors--when-projects-with-missing-components--return-error (is (= [{:code 107 :colorized-message "Missing components in the poly-migrator project for these interfaces: user-config, util" :interfaces ["user-config" "util"] :message "Missing components in the poly-migrator project for these interfaces: user-config, util" :project "poly-migrator" :type "error"}] (m107/errors "info" (assoc settings :active-profiles #{"default"}) projects components color/none))))
6316c7d890afe47aa331dbd846d7f08f7ab7e293160620b6b0e7b022be4ee781
karlll/bioerl
assembly.erl
% 2013 - 12 - 03 karlll < > % % Genome assembly % -module(assembly). -compile([export_all]). %% -------------------------------------------------------------------------- %% %% String composition %% %% -------------------------------------------------------------------------- %% print_str_compo(String,K) -> StrCompo = str_compo(String,K), lists:foreach(fun(El) -> io:format("~s~n",[El]) end, StrCompo). get_str_compo(String,K) -> StrCompo = str_compo(String,K), lists:map(fun(El) -> io_lib:format("~s~n",[El]) end, StrCompo). str_compo(String,K) -> Kmers = motif:get_kmers(String,K), lists:sort(Kmers). %% -------------------------------------------------------------------------- %% %% Overlapping graph %% %% -------------------------------------------------------------------------- %% write_olgraph_adj_list(Kmers,Filename) -> {ok, File} = file:open(Filename,[write]), AdjList1 = lists:keysort(1,overlapping_graph(Kmers)), AdjList2 = lists:filter(fun(E) -> {_K,L} = E, case L of [] -> false; _ -> true end end, AdjList1), AdjList2, lists:foreach(fun(F)-> {Kmer,L} = F, file:write(File,io_lib:format("~s -> ",[Kmer])), lists:foreach(fun(G) -> file:write(File,io_lib:format("~s",[G])) end, L), file:write(File,io_lib:format("~n",[])) end, AdjList2). print_olgraph_adj_list(Kmers) -> AdjList1 = lists:keysort(1,overlapping_graph(Kmers)), AdjList2 = lists:filter(fun(E) -> {_K,L} = E, case L of [] -> false; _ -> true end end, AdjList1), AdjList2, lists:foreach(fun(F)-> {Kmer,L} = F, io:format("~s -> ",[Kmer]), lists:foreach(fun(G) -> io:format("~s ",[G]) end, L), io:format("~n") end, AdjList2). overlapping_graph(Kmers) -> lists:map(fun(Kmer) -> {Kmer, get_adj_list(Kmer,Kmers)} end, Kmers). get_adj_list(Kmer,Kmers) -> Kmers2 = lists:delete(Kmer,Kmers), get_adj_list(Kmer,Kmers2,[]). get_adj_list(_Kmer,[],Acc) -> Acc; get_adj_list(Kmer1,[Kmer2|Tail],Acc) -> NewAcc = case is_overlapping(Kmer1,Kmer2) of true -> [Kmer2|Acc]; false -> Acc end, get_adj_list(Kmer1,Tail,NewAcc). is_overlapping(Kmer1,Kmer2) -> S = suffix(Kmer1), P = prefix(Kmer2), case S of P -> true; _ -> false end. prefix(Kmer) -> lists:sublist(Kmer,length(Kmer)-1). suffix([H|Tail]) -> Tail. %% -------------------------------------------------------------------------- %% DeBruijn graph % % %% -------------------------------------------------------------------------- %% test_debruijn_graph() -> L = get_dbgraph_adj_list(util:get_input("in.txt")), util:write_result_text(L,"res.txt"). get_dbgraph_adj_list(Kmers) -> AdjList = lists:keysort(1,debruijn_graph(Kmers)), lists:map(fun(F)-> {Kmer,L} = F, io_lib:format("~s -> ~s~n",[Kmer,string:join(L,",")]) end, AdjList). get_dbgraph_adj_list(String,K) -> AdjList1 = lists:keysort(1,debruijn_graph(String, K)), AdjList2 = lists:filter(fun(E) -> {_K,L} = E, case L of [] -> false; _ -> true end end, AdjList1), lists:map(fun(F)-> {Kmer,L} = F, io_lib:format("~s -> ~s~n",[Kmer,string:join(lists:sort(L),",")]) end, AdjList2). Construct a debruijn graph from a list of K - mers debruijn_graph(Kmers) -> debruijn_graph(Kmers,[]). debruijn_graph([],Acc) -> Acc; debruijn_graph([Kmer|T],Acc) -> P = prefix(Kmer), S = suffix(Kmer), NewAcc = case lists:keyfind(P,1,Acc) of {P,S2} -> lists:keyreplace(P,1,Acc,{P,[S|S2]}); false -> [{P,[S]}|Acc] end, debruijn_graph(T,NewAcc); % construct a debruijn graph by dividing the provided String in K-mers debruijn_graph(String,K) when is_integer(K) -> Nmers = motif:get_kmers(String,K-1), lists:map(fun(E)-> filter_nodes(E,String) end, overlapping_graph(Nmers)). % remove nodes that does not correspoing to a edge k-mer in the original strings filter_nodes(E,String) -> {N1,NL} = E, NewNL = lists:filter(fun(N) -> EdgeKmer = get_edge_kmer(N1,N), case string:str(String,EdgeKmer) of 0 -> false; _ -> true end end, NL), {N1,lists:sort(NewNL)}. ex . : AAGATTGAA - > AGATTGAAG = > edge k - mer AAGATTGAAG get_edge_kmer([H1|T1],N2) -> [H1|N2]. %% -------------------------------------------------------------------------- %% %% Eulerian path %% %% -------------------------------------------------------------------------- %% Read an adjecency list from in.txt , output an eulerian path to res.txt % Precond: Graph has an eulerian path. test_eulerian_path() -> G = build_graph(util:get_input("in.txt")), util:write_result_text(string:join(find_path(G,path),"->"),"res.txt"). Get the directed graph defined by AdjStrings , [ " Node1->Node2,Node3 " ] NB : digraph : delete(G ) should be called for the graph G returned by this function . build_graph(AdjStrings) -> AdjList = get_adj_list2(AdjStrings), % create empty graph G = digraph:new(), % create all vertices Ns = get_nodes(AdjList), VtxList = lists:map(fun(N) -> add_vertex(G,N) end, Ns), % add edges from adj list to G lists:foreach(fun(NodeEntry) -> {N,NL} = NodeEntry, lists:foreach(fun(E)-> io:format("Adding edge from node ~s to node ~s~n",[N,E]), add_edge(G,VtxList,N,E) end, NL) end, AdjList), G. Get a adjencency list from a set of strings in the form " Node - > NeighborA[,NeighborB ] " get_adj_list2(AdjStrings) -> get_adj_list2(AdjStrings,[]). get_adj_list2([],Acc) -> Acc; get_adj_list2([AdjStr|T],Acc) -> get_adj_list2(T,[get_nbs(AdjStr)|Acc]). get_nodes(AdjList) -> get_nodes(AdjList,[]). get_nodes([],Acc) -> sets:to_list(sets:from_list(Acc)); get_nodes([NodeEntry|T],Acc) -> {Node,NeighborList} = NodeEntry, get_nodes(T,[Node|NeighborList]++Acc). Get neighbors for a adjecency string in the format " Node - > Neighbors " % returns {Node,NeighborList} get_nbs(AdjStr) -> Sep = " -> ", NodeA = string:sub_string(AdjStr,1,string:str(AdjStr,Sep)-1), NodeBLst = string:sub_string(AdjStr,string:str(AdjStr,Sep)+length(Sep),length(AdjStr)), {NodeA, string:tokens(NodeBLst,",")}. % Add edge to directed graph G add_edge(G,VertexList,VertexName1,VertexName2) -> V1 = lists:keyfind(VertexName1,1,VertexList), V2 = lists:keyfind(VertexName2,1,VertexList), digraph:add_edge(G,VertexName1,VertexName2), ok. % Add verted to directed graph G add_vertex(G,VertexName) -> io:format("Adding vtx = ~s~n",[VertexName]), {VertexName,digraph:add_vertex(G,VertexName)}. Find an eulerian path or cycle in digraph = path|cycle find_path(G,Type) -> S = push(new_stack(),select_startnode(G,Type)), io:format("Initial stack = ~p~n",[S]), find_path(G,S,[]). find_path(Graph,[],Acc) -> digraph:delete(Graph), Acc; find_path(Graph,Stack,Acc) -> Node = peek(Stack), io:format("Current node = ~p~n",[Node]), {NewStack,NewAcc} = case digraph:out_edges(Graph,Node) of [E|T] -> {E,Node,NewDest,_} = digraph:edge(Graph,E), true = digraph:del_edge(Graph,E), io:format("Pushing node = ~p, Deleted edge = ~p~n",[NewDest,E]), {push(Stack,NewDest),Acc}; [] -> io:format("Adding/Popping ~p~n",[Node]), {Node,NS} = pop(Stack), {NS,[Node|Acc]} end, find_path(Graph,NewStack,NewAcc). new_stack() -> []. push(S,E) -> [E|S]. pop([H|S]) -> {H,S}. peek([H|S]) -> H. random_element(List) -> lists:nth(random:uniform(length(List)),List). G is a digraph which has an Eulerian path select_startnode(G,path) -> Nodes = digraph:vertices(G), StartNodes = lists:filter(fun(N) -> D = digraph:out_degree(G,N) - digraph:in_degree(G,N), case D of 1 -> true; _ -> false end end,Nodes), hd(StartNodes); G is a digraph which has an Eulerian cycle select_startnode(G,cycle) -> {X,Y,Z} = now(), random:seed(X,Y,Z), Nodes = digraph:vertices(G), lists:nth(random:uniform(length(Nodes)),Nodes).
null
https://raw.githubusercontent.com/karlll/bioerl/6ade2d63bb37f1312e33c3bbad9b7252323ad369/src/assembly.erl
erlang
-------------------------------------------------------------------------- %% String composition %% -------------------------------------------------------------------------- %% -------------------------------------------------------------------------- %% Overlapping graph %% -------------------------------------------------------------------------- %% -------------------------------------------------------------------------- %% % -------------------------------------------------------------------------- %% construct a debruijn graph by dividing the provided String in K-mers remove nodes that does not correspoing to a edge k-mer in the original strings -------------------------------------------------------------------------- %% Eulerian path %% -------------------------------------------------------------------------- %% Precond: Graph has an eulerian path. create empty graph create all vertices add edges from adj list to G returns {Node,NeighborList} Add edge to directed graph G Add verted to directed graph G
2013 - 12 - 03 karlll < > Genome assembly -module(assembly). -compile([export_all]). print_str_compo(String,K) -> StrCompo = str_compo(String,K), lists:foreach(fun(El) -> io:format("~s~n",[El]) end, StrCompo). get_str_compo(String,K) -> StrCompo = str_compo(String,K), lists:map(fun(El) -> io_lib:format("~s~n",[El]) end, StrCompo). str_compo(String,K) -> Kmers = motif:get_kmers(String,K), lists:sort(Kmers). write_olgraph_adj_list(Kmers,Filename) -> {ok, File} = file:open(Filename,[write]), AdjList1 = lists:keysort(1,overlapping_graph(Kmers)), AdjList2 = lists:filter(fun(E) -> {_K,L} = E, case L of [] -> false; _ -> true end end, AdjList1), AdjList2, lists:foreach(fun(F)-> {Kmer,L} = F, file:write(File,io_lib:format("~s -> ",[Kmer])), lists:foreach(fun(G) -> file:write(File,io_lib:format("~s",[G])) end, L), file:write(File,io_lib:format("~n",[])) end, AdjList2). print_olgraph_adj_list(Kmers) -> AdjList1 = lists:keysort(1,overlapping_graph(Kmers)), AdjList2 = lists:filter(fun(E) -> {_K,L} = E, case L of [] -> false; _ -> true end end, AdjList1), AdjList2, lists:foreach(fun(F)-> {Kmer,L} = F, io:format("~s -> ",[Kmer]), lists:foreach(fun(G) -> io:format("~s ",[G]) end, L), io:format("~n") end, AdjList2). overlapping_graph(Kmers) -> lists:map(fun(Kmer) -> {Kmer, get_adj_list(Kmer,Kmers)} end, Kmers). get_adj_list(Kmer,Kmers) -> Kmers2 = lists:delete(Kmer,Kmers), get_adj_list(Kmer,Kmers2,[]). get_adj_list(_Kmer,[],Acc) -> Acc; get_adj_list(Kmer1,[Kmer2|Tail],Acc) -> NewAcc = case is_overlapping(Kmer1,Kmer2) of true -> [Kmer2|Acc]; false -> Acc end, get_adj_list(Kmer1,Tail,NewAcc). is_overlapping(Kmer1,Kmer2) -> S = suffix(Kmer1), P = prefix(Kmer2), case S of P -> true; _ -> false end. prefix(Kmer) -> lists:sublist(Kmer,length(Kmer)-1). suffix([H|Tail]) -> Tail. test_debruijn_graph() -> L = get_dbgraph_adj_list(util:get_input("in.txt")), util:write_result_text(L,"res.txt"). get_dbgraph_adj_list(Kmers) -> AdjList = lists:keysort(1,debruijn_graph(Kmers)), lists:map(fun(F)-> {Kmer,L} = F, io_lib:format("~s -> ~s~n",[Kmer,string:join(L,",")]) end, AdjList). get_dbgraph_adj_list(String,K) -> AdjList1 = lists:keysort(1,debruijn_graph(String, K)), AdjList2 = lists:filter(fun(E) -> {_K,L} = E, case L of [] -> false; _ -> true end end, AdjList1), lists:map(fun(F)-> {Kmer,L} = F, io_lib:format("~s -> ~s~n",[Kmer,string:join(lists:sort(L),",")]) end, AdjList2). Construct a debruijn graph from a list of K - mers debruijn_graph(Kmers) -> debruijn_graph(Kmers,[]). debruijn_graph([],Acc) -> Acc; debruijn_graph([Kmer|T],Acc) -> P = prefix(Kmer), S = suffix(Kmer), NewAcc = case lists:keyfind(P,1,Acc) of {P,S2} -> lists:keyreplace(P,1,Acc,{P,[S|S2]}); false -> [{P,[S]}|Acc] end, debruijn_graph(T,NewAcc); debruijn_graph(String,K) when is_integer(K) -> Nmers = motif:get_kmers(String,K-1), lists:map(fun(E)-> filter_nodes(E,String) end, overlapping_graph(Nmers)). filter_nodes(E,String) -> {N1,NL} = E, NewNL = lists:filter(fun(N) -> EdgeKmer = get_edge_kmer(N1,N), case string:str(String,EdgeKmer) of 0 -> false; _ -> true end end, NL), {N1,lists:sort(NewNL)}. ex . : AAGATTGAA - > AGATTGAAG = > edge k - mer AAGATTGAAG get_edge_kmer([H1|T1],N2) -> [H1|N2]. Read an adjecency list from in.txt , output an eulerian path to res.txt test_eulerian_path() -> G = build_graph(util:get_input("in.txt")), util:write_result_text(string:join(find_path(G,path),"->"),"res.txt"). Get the directed graph defined by AdjStrings , [ " Node1->Node2,Node3 " ] NB : digraph : delete(G ) should be called for the graph G returned by this function . build_graph(AdjStrings) -> AdjList = get_adj_list2(AdjStrings), G = digraph:new(), Ns = get_nodes(AdjList), VtxList = lists:map(fun(N) -> add_vertex(G,N) end, Ns), lists:foreach(fun(NodeEntry) -> {N,NL} = NodeEntry, lists:foreach(fun(E)-> io:format("Adding edge from node ~s to node ~s~n",[N,E]), add_edge(G,VtxList,N,E) end, NL) end, AdjList), G. Get a adjencency list from a set of strings in the form " Node - > NeighborA[,NeighborB ] " get_adj_list2(AdjStrings) -> get_adj_list2(AdjStrings,[]). get_adj_list2([],Acc) -> Acc; get_adj_list2([AdjStr|T],Acc) -> get_adj_list2(T,[get_nbs(AdjStr)|Acc]). get_nodes(AdjList) -> get_nodes(AdjList,[]). get_nodes([],Acc) -> sets:to_list(sets:from_list(Acc)); get_nodes([NodeEntry|T],Acc) -> {Node,NeighborList} = NodeEntry, get_nodes(T,[Node|NeighborList]++Acc). Get neighbors for a adjecency string in the format " Node - > Neighbors " get_nbs(AdjStr) -> Sep = " -> ", NodeA = string:sub_string(AdjStr,1,string:str(AdjStr,Sep)-1), NodeBLst = string:sub_string(AdjStr,string:str(AdjStr,Sep)+length(Sep),length(AdjStr)), {NodeA, string:tokens(NodeBLst,",")}. add_edge(G,VertexList,VertexName1,VertexName2) -> V1 = lists:keyfind(VertexName1,1,VertexList), V2 = lists:keyfind(VertexName2,1,VertexList), digraph:add_edge(G,VertexName1,VertexName2), ok. add_vertex(G,VertexName) -> io:format("Adding vtx = ~s~n",[VertexName]), {VertexName,digraph:add_vertex(G,VertexName)}. Find an eulerian path or cycle in digraph = path|cycle find_path(G,Type) -> S = push(new_stack(),select_startnode(G,Type)), io:format("Initial stack = ~p~n",[S]), find_path(G,S,[]). find_path(Graph,[],Acc) -> digraph:delete(Graph), Acc; find_path(Graph,Stack,Acc) -> Node = peek(Stack), io:format("Current node = ~p~n",[Node]), {NewStack,NewAcc} = case digraph:out_edges(Graph,Node) of [E|T] -> {E,Node,NewDest,_} = digraph:edge(Graph,E), true = digraph:del_edge(Graph,E), io:format("Pushing node = ~p, Deleted edge = ~p~n",[NewDest,E]), {push(Stack,NewDest),Acc}; [] -> io:format("Adding/Popping ~p~n",[Node]), {Node,NS} = pop(Stack), {NS,[Node|Acc]} end, find_path(Graph,NewStack,NewAcc). new_stack() -> []. push(S,E) -> [E|S]. pop([H|S]) -> {H,S}. peek([H|S]) -> H. random_element(List) -> lists:nth(random:uniform(length(List)),List). G is a digraph which has an Eulerian path select_startnode(G,path) -> Nodes = digraph:vertices(G), StartNodes = lists:filter(fun(N) -> D = digraph:out_degree(G,N) - digraph:in_degree(G,N), case D of 1 -> true; _ -> false end end,Nodes), hd(StartNodes); G is a digraph which has an Eulerian cycle select_startnode(G,cycle) -> {X,Y,Z} = now(), random:seed(X,Y,Z), Nodes = digraph:vertices(G), lists:nth(random:uniform(length(Nodes)),Nodes).
4da25bd7ad80ac3df396fe56f1b6842321a11a7f75adc7424c9c0ad34a44abe2
facebook/pyre-check
lwtSubprocess.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) (* TODO(T132410158) Add a module-level doc comment. *) module Completed = struct type t = { stdout: string; stderr: string; status: Unix.process_status; } let create_from_process_and_consumers ~consume_stdout ~consume_stderr process = let open Lwt.Infix in Lwt.both process#status (Lwt.both (consume_stdout process#stdout) (consume_stderr process#stderr)) >>= fun (status, (stdout, stderr)) -> Lwt.return { stdout; stderr; status } end let run ?(consume_stdout = fun input_channel -> Lwt_io.read input_channel) ?(consume_stderr = fun input_channel -> Lwt_io.read input_channel) ~arguments executable = let lwt_command = executable, Array.of_list (executable :: arguments) in Lwt_process.with_process_full lwt_command (Completed.create_from_process_and_consumers ~consume_stdout ~consume_stderr)
null
https://raw.githubusercontent.com/facebook/pyre-check/98b8362ffa5c715c708676c1a37a52647ce79fe0/source/lwtSubprocess.ml
ocaml
TODO(T132410158) Add a module-level doc comment.
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) module Completed = struct type t = { stdout: string; stderr: string; status: Unix.process_status; } let create_from_process_and_consumers ~consume_stdout ~consume_stderr process = let open Lwt.Infix in Lwt.both process#status (Lwt.both (consume_stdout process#stdout) (consume_stderr process#stderr)) >>= fun (status, (stdout, stderr)) -> Lwt.return { stdout; stderr; status } end let run ?(consume_stdout = fun input_channel -> Lwt_io.read input_channel) ?(consume_stderr = fun input_channel -> Lwt_io.read input_channel) ~arguments executable = let lwt_command = executable, Array.of_list (executable :: arguments) in Lwt_process.with_process_full lwt_command (Completed.create_from_process_and_consumers ~consume_stdout ~consume_stderr)
cf6ebf5402f44dbf1bb9afbf2e4bcbba2ddf57c0c1aae4fa6619d0347ba6ab08
BranchTaken/Hemlock
zint.ml
module T = struct type t = int64 Stdlib.Array.t let min_word_length = 0L 2**64 bits . let init n ~f = Stdlib.Array.init (Stdlib.Int64.to_int n) (fun i -> f (Stdlib.Int64.of_int i)) let word_length t = Stdlib.Int64.of_int (Stdlib.Array.length t) let get i t = Stdlib.Array.get t (Stdlib.Int64.to_int i) end include T include Intw.MakeVI(T) let k_0 = of_uns 0x0L let k_1 = of_uns 0x1L let k_2 = of_uns 0x2L let k_3 = of_uns 0x3L let k_4 = of_uns 0x4L let k_5 = of_uns 0x5L let k_6 = of_uns 0x6L let k_7 = of_uns 0x7L let k_8 = of_uns 0x8L let k_9 = of_uns 0x9L let k_a = of_uns 0xaL let k_b = of_uns 0xbL let k_c = of_uns 0xcL let k_d = of_uns 0xdL let k_e = of_uns 0xeL let k_f = of_uns 0xfL let k_g = of_uns 0x10L
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/53da5c0d9cf0c94d58b4391735d917518eec67fa/bootstrap/src/basis/zint.ml
ocaml
module T = struct type t = int64 Stdlib.Array.t let min_word_length = 0L 2**64 bits . let init n ~f = Stdlib.Array.init (Stdlib.Int64.to_int n) (fun i -> f (Stdlib.Int64.of_int i)) let word_length t = Stdlib.Int64.of_int (Stdlib.Array.length t) let get i t = Stdlib.Array.get t (Stdlib.Int64.to_int i) end include T include Intw.MakeVI(T) let k_0 = of_uns 0x0L let k_1 = of_uns 0x1L let k_2 = of_uns 0x2L let k_3 = of_uns 0x3L let k_4 = of_uns 0x4L let k_5 = of_uns 0x5L let k_6 = of_uns 0x6L let k_7 = of_uns 0x7L let k_8 = of_uns 0x8L let k_9 = of_uns 0x9L let k_a = of_uns 0xaL let k_b = of_uns 0xbL let k_c = of_uns 0xcL let k_d = of_uns 0xdL let k_e = of_uns 0xeL let k_f = of_uns 0xfL let k_g = of_uns 0x10L
9d401a39b75371bcec4bbd552160ed8e4040135286189d7fed14804d29e47ed7
composewell/unicode-data
Numeric.hs
-- | Module : Unicode . . Numeric Copyright : ( c ) 2020 Composewell Technologies and Contributors -- License : Apache-2.0 -- Maintainer : -- Stability : experimental -- -- Numeric character property related functions. -- -- @since 0.3.0 module Unicode.Char.Numeric ( -- * Predicates isNumeric , isNumber -- * Numeric values , numericValue , integerValue -- * Re-export from @base@ , isDigit , isOctDigit , isHexDigit , digitToInt , intToDigit ) where import Data.Char (digitToInt, intToDigit, isDigit, isHexDigit, isOctDigit) import Data.Maybe (isJust) import Data.Ratio (numerator, denominator) import qualified Unicode.Char.Numeric.Compat as Compat import qualified Unicode.Internal.Char.DerivedNumericValues as V -- | Selects Unicode numeric characters, including digits from various scripts , Roman numerals , et cetera . -- This function returns ' True ' if its argument has one of the following ' Unicode . . General . 's , or ' False ' otherwise : -- * ' Unicode . . General . DecimalNumber ' * ' Unicode . . General . LetterNumber ' * ' Unicode . . General . OtherNumber ' -- -- __Note:__ a character may have a numeric value (see 'numericValue') but return ' False ' , because ' isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a -- numeric value. Use 'isNumeric' to cover those cases as well. -- -- prop> isNumber c == Data.Char.isNumber c -- -- @since 0.3.0 # DEPRECATED isNumber " Use Unicode . . Numeric . Compat.isNumber instead . This function will be a synonym for isNumeric in a future release . See . . Numeric . Compat for behavior compatible with base : Data . . " # # INLINE isNumber # isNumber :: Char -> Bool isNumber = Compat.isNumber -- | Selects Unicode character with a numeric value. -- -- __Note:__ a character may have a numeric value but return 'False' with the predicate ' Unicode . . Numeric . Compat.isNumber ' , because ' Unicode . . Numeric . Compat.isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a numeric value . -- -- prop> isNumeric c == isJust (numericValue c) -- @since 0.3.1 # INLINE isNumeric # isNumeric :: Char -> Bool isNumeric = isJust . V.numericValue -- | Numeric value of a character, if relevant. -- -- __Note:__ a character may have a numeric value but return 'False' with the predicate ' Unicode . . Numeric . Compat.isNumber ' , because ' Unicode . . Numeric . Compat.isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a numeric value . -- @since 0.3.1 # INLINE numericValue # numericValue :: Char -> Maybe Rational numericValue = V.numericValue -- | Integer value of a character, if relevant. -- -- This is a special case of 'numericValue'. -- -- __Note:__ a character may have a numeric value but return 'False' with the predicate ' Unicode . . Numeric . Compat.isNumber ' , because ' Unicode . . Numeric . Compat.isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a numeric value . -- @since 0.3.1 integerValue :: Char -> Maybe Int integerValue c = do r <- V.numericValue c if denominator r == 1 then Just (fromIntegral (numerator r)) else Nothing
null
https://raw.githubusercontent.com/composewell/unicode-data/bf8bb533650119b3ce196aa95b009c6f4ebc1f04/unicode-data/lib/Unicode/Char/Numeric.hs
haskell
| License : Apache-2.0 Maintainer : Stability : experimental Numeric character property related functions. @since 0.3.0 * Predicates * Numeric values * Re-export from @base@ | Selects Unicode numeric characters, including digits from various __Note:__ a character may have a numeric value (see 'numericValue') but return numeric value. Use 'isNumeric' to cover those cases as well. prop> isNumber c == Data.Char.isNumber c @since 0.3.0 | Selects Unicode character with a numeric value. __Note:__ a character may have a numeric value but return 'False' with prop> isNumeric c == isJust (numericValue c) | Numeric value of a character, if relevant. __Note:__ a character may have a numeric value but return 'False' with | Integer value of a character, if relevant. This is a special case of 'numericValue'. __Note:__ a character may have a numeric value but return 'False' with
Module : Unicode . . Numeric Copyright : ( c ) 2020 Composewell Technologies and Contributors module Unicode.Char.Numeric isNumeric , isNumber , numericValue , integerValue , isDigit , isOctDigit , isHexDigit , digitToInt , intToDigit ) where import Data.Char (digitToInt, intToDigit, isDigit, isHexDigit, isOctDigit) import Data.Maybe (isJust) import Data.Ratio (numerator, denominator) import qualified Unicode.Char.Numeric.Compat as Compat import qualified Unicode.Internal.Char.DerivedNumericValues as V scripts , Roman numerals , et cetera . This function returns ' True ' if its argument has one of the following ' Unicode . . General . 's , or ' False ' otherwise : * ' Unicode . . General . DecimalNumber ' * ' Unicode . . General . LetterNumber ' * ' Unicode . . General . OtherNumber ' ' False ' , because ' isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a # DEPRECATED isNumber " Use Unicode . . Numeric . Compat.isNumber instead . This function will be a synonym for isNumeric in a future release . See . . Numeric . Compat for behavior compatible with base : Data . . " # # INLINE isNumber # isNumber :: Char -> Bool isNumber = Compat.isNumber the predicate ' Unicode . . Numeric . Compat.isNumber ' , because ' Unicode . . Numeric . Compat.isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a numeric value . @since 0.3.1 # INLINE isNumeric # isNumeric :: Char -> Bool isNumeric = isJust . V.numericValue the predicate ' Unicode . . Numeric . Compat.isNumber ' , because ' Unicode . . Numeric . Compat.isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a numeric value . @since 0.3.1 # INLINE numericValue # numericValue :: Char -> Maybe Rational numericValue = V.numericValue the predicate ' Unicode . . Numeric . Compat.isNumber ' , because ' Unicode . . Numeric . Compat.isNumber ' only tests ' Unicode . . General . ' : some CJK characters are ' Unicode . . General . OtherLetter ' and do have a numeric value . @since 0.3.1 integerValue :: Char -> Maybe Int integerValue c = do r <- V.numericValue c if denominator r == 1 then Just (fromIntegral (numerator r)) else Nothing
0960eaeeeee9c59860f0df353dcb560e0f5e94093f7ee5a855a7473cfbce5b21
input-output-hk/marlowe-cardano
Store.hs
{-# LANGUAGE Arrows #-} # LANGUAGE DuplicateRecordFields # {-# LANGUAGE GADTs #-} # LANGUAGE KindSignatures # {-# LANGUAGE StrictData #-} module Language.Marlowe.Runtime.Indexer.Store where import Control.Concurrent.Component import Control.Concurrent.STM (STM, atomically, modifyTVar, newTVar, readTVar, writeTVar) import Control.Monad (forever, guard, unless) import Data.Aeson (ToJSON) import Data.Foldable (for_, traverse_) import Data.Function (on) import Data.List (partition) import Data.Map (Map) import qualified Data.Map as Map import Data.Semigroup (Last(..)) import GHC.Generics (Generic) import Language.Marlowe.Runtime.ChainSync.Api (ChainPoint, TxId, WithGenesis(..)) import Language.Marlowe.Runtime.Core.Api (ContractId) import Language.Marlowe.Runtime.History.Api (ExtractCreationError, ExtractMarloweTransactionError) import Language.Marlowe.Runtime.Indexer.ChainSeekClient (ChainEvent(..)) import Language.Marlowe.Runtime.Indexer.Database (DatabaseQueries(..)) import Language.Marlowe.Runtime.Indexer.Types (MarloweBlock(..), MarloweTransaction(..)) import Observe.Event (EventBackend, addField, withEvent) data StoreSelector f where Save :: StoreSelector SaveField data SaveField = RollbackPoint ChainPoint | Stats ChangesStatistics | LocalTip ChainPoint | RemoteTip ChainPoint | InvalidCreateTxs (Map ContractId ExtractCreationError) | InvalidApplyInputsTxs (Map TxId ExtractMarloweTransactionError) data StoreDependencies r = StoreDependencies { databaseQueries :: DatabaseQueries IO , eventBackend :: EventBackend IO r StoreSelector , pullEvent :: STM ChainEvent } | The store component aggregates changes into batches in one thread , and -- pulls batches to save in another. store :: Component IO (StoreDependencies r) () store = proc StoreDependencies{..} -> do -- Spawn the aggregator thread readChanges <- aggregator -< pullEvent -- Spawn the persister thread to read the changes accumulated by the aggregator. persister -< PersisterDependencies{..} -- | The aggregator component pulls chain events and accumulates a batch of -- changes to persist. aggregator :: Component IO (STM ChainEvent) (STM Changes) aggregator = component \pullEvent -> do -- A variable which will hold the accumulated changes. changesVar <- newTVar mempty let -- An action to read and empty the changes. readChanges = do -- Read the current changes changes <- readTVar changesVar Retry the STM transaction if the changes are empty guard case changes of Changes Nothing [] _ _ _ invalidCreateTxs invalidApplyInputsTxs -> not $ Map.null invalidCreateTxs && Map.null invalidApplyInputsTxs _ -> True -- Empty the changes variable writeTVar changesVar mempty -- Return the changes pure changes -- The IO action loop to run in this component's thread. runAggregator = forever do -- Pull an event from the queue. event <- atomically pullEvent let -- Compute the changes for the pulled event. changes = case event of RollForward block point tip -> mempty { blocks = [block] , statistics = computeStats block , localTip = Just point , remoteTip = Just tip , invalidCreateTxs = flip foldMap (transactions block) \case InvalidCreateTransaction contractId err -> Map.singleton contractId err _ -> mempty , invalidApplyInputsTxs = flip foldMap (transactions block) \case InvalidApplyInputsTransaction txId _ err -> Map.singleton txId err _ -> mempty } RollBackward point tip -> mempty { rollbackTo = Just point, localTip = Just point, remoteTip = Just tip } -- Append the new changes to the existing changes. atomically $ modifyTVar changesVar (<> changes) pure (runAggregator, readChanges) data PersisterDependencies r = PersisterDependencies { databaseQueries :: DatabaseQueries IO , eventBackend :: EventBackend IO r StoreSelector , readChanges :: STM Changes } -- | A component to save batches of changes to the database. persister :: Component IO (PersisterDependencies r) () persister = component_ \PersisterDependencies{..} -> forever do -- Read the next batch of changes. Changes{..} <- atomically readChanges -- Log a save event. withEvent eventBackend Save \ev -> do traverse_ (addField ev . LocalTip) localTip traverse_ (addField ev . RemoteTip) remoteTip addField ev $ Stats statistics If there is a rollback , save it first . for_ rollbackTo \point -> do addField ev $ RollbackPoint point commitRollback databaseQueries point unless (Map.null invalidCreateTxs) $ addField ev $ InvalidCreateTxs invalidCreateTxs unless (Map.null invalidApplyInputsTxs) $ addField ev $ InvalidApplyInputsTxs invalidApplyInputsTxs -- If there are blocks to save, save them. unless (null blocks) $ commitBlocks databaseQueries blocks data Changes = Changes { rollbackTo :: Maybe ChainPoint , blocks :: [MarloweBlock] , statistics :: ChangesStatistics , localTip :: Maybe ChainPoint , remoteTip :: Maybe ChainPoint , invalidCreateTxs :: Map ContractId ExtractCreationError , invalidApplyInputsTxs :: Map TxId ExtractMarloweTransactionError } deriving (Show, Eq, Generic) instance Semigroup Changes where a <> b = let a' = maybe id applyRollback (rollbackTo b) a in Changes { rollbackTo = rollbackTo a' , blocks = on (<>) blocks a' b , statistics = on (<>) statistics a' b , localTip = getLast $ on (<>) (Last . localTip) a b , remoteTip = getLast $ on (<>) (Last . remoteTip) a b , invalidCreateTxs = on (<>) invalidCreateTxs a b , invalidApplyInputsTxs = on (<>) invalidApplyInputsTxs a b } applyRollback :: ChainPoint -> Changes -> Changes applyRollback Genesis _ = mempty { rollbackTo = Just Genesis } applyRollback (At block) Changes{..} = if null blocksNotRolledBack then mempty { rollbackTo = Just (At block) } else mempty { blocks = blocksNotRolledBack , statistics = statistics `subStats` foldMap computeStats blocksRolledBack } where (blocksRolledBack, blocksNotRolledBack) = partition isRolledBack blocks isRolledBack MarloweBlock{..} = blockHeader > block subStats :: ChangesStatistics -> ChangesStatistics -> ChangesStatistics subStats a b = ChangesStatistics { blockCount = on (-) blockCount a b , createTxCount = on (-) createTxCount a b , applyInputsTxCount = on (-) applyInputsTxCount a b , withdrawTxCount = on (-) withdrawTxCount a b } computeStats :: MarloweBlock -> ChangesStatistics computeStats MarloweBlock{..} = (foldMap computeTxStats transactions) { blockCount = 1 } where computeTxStats CreateTransaction{} = mempty { createTxCount = 1 } computeTxStats ApplyInputsTransaction{} = mempty { applyInputsTxCount = 1 } computeTxStats WithdrawTransaction{} = mempty { withdrawTxCount = 1 } computeTxStats _ = mempty instance Monoid Changes where mempty = Changes Nothing mempty mempty Nothing Nothing mempty mempty data ChangesStatistics = ChangesStatistics { blockCount :: Int , createTxCount :: Int , applyInputsTxCount :: Int , withdrawTxCount :: Int } deriving (Show, Eq, Generic) instance ToJSON ChangesStatistics instance Semigroup ChangesStatistics where a <> b = ChangesStatistics { blockCount = on (+) blockCount a b , createTxCount = on (+) createTxCount a b , applyInputsTxCount = on (+) applyInputsTxCount a b , withdrawTxCount = on (+) withdrawTxCount a b } instance Monoid ChangesStatistics where mempty = ChangesStatistics 0 0 0 0
null
https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/e0b4fa12179e4d26f15f04e2a453de934b644ae2/marlowe-runtime/indexer/Language/Marlowe/Runtime/Indexer/Store.hs
haskell
# LANGUAGE Arrows # # LANGUAGE GADTs # # LANGUAGE StrictData # pulls batches to save in another. Spawn the aggregator thread Spawn the persister thread to read the changes accumulated by the aggregator. | The aggregator component pulls chain events and accumulates a batch of changes to persist. A variable which will hold the accumulated changes. An action to read and empty the changes. Read the current changes Empty the changes variable Return the changes The IO action loop to run in this component's thread. Pull an event from the queue. Compute the changes for the pulled event. Append the new changes to the existing changes. | A component to save batches of changes to the database. Read the next batch of changes. Log a save event. If there are blocks to save, save them.
# LANGUAGE DuplicateRecordFields # # LANGUAGE KindSignatures # module Language.Marlowe.Runtime.Indexer.Store where import Control.Concurrent.Component import Control.Concurrent.STM (STM, atomically, modifyTVar, newTVar, readTVar, writeTVar) import Control.Monad (forever, guard, unless) import Data.Aeson (ToJSON) import Data.Foldable (for_, traverse_) import Data.Function (on) import Data.List (partition) import Data.Map (Map) import qualified Data.Map as Map import Data.Semigroup (Last(..)) import GHC.Generics (Generic) import Language.Marlowe.Runtime.ChainSync.Api (ChainPoint, TxId, WithGenesis(..)) import Language.Marlowe.Runtime.Core.Api (ContractId) import Language.Marlowe.Runtime.History.Api (ExtractCreationError, ExtractMarloweTransactionError) import Language.Marlowe.Runtime.Indexer.ChainSeekClient (ChainEvent(..)) import Language.Marlowe.Runtime.Indexer.Database (DatabaseQueries(..)) import Language.Marlowe.Runtime.Indexer.Types (MarloweBlock(..), MarloweTransaction(..)) import Observe.Event (EventBackend, addField, withEvent) data StoreSelector f where Save :: StoreSelector SaveField data SaveField = RollbackPoint ChainPoint | Stats ChangesStatistics | LocalTip ChainPoint | RemoteTip ChainPoint | InvalidCreateTxs (Map ContractId ExtractCreationError) | InvalidApplyInputsTxs (Map TxId ExtractMarloweTransactionError) data StoreDependencies r = StoreDependencies { databaseQueries :: DatabaseQueries IO , eventBackend :: EventBackend IO r StoreSelector , pullEvent :: STM ChainEvent } | The store component aggregates changes into batches in one thread , and store :: Component IO (StoreDependencies r) () store = proc StoreDependencies{..} -> do readChanges <- aggregator -< pullEvent persister -< PersisterDependencies{..} aggregator :: Component IO (STM ChainEvent) (STM Changes) aggregator = component \pullEvent -> do changesVar <- newTVar mempty let readChanges = do changes <- readTVar changesVar Retry the STM transaction if the changes are empty guard case changes of Changes Nothing [] _ _ _ invalidCreateTxs invalidApplyInputsTxs -> not $ Map.null invalidCreateTxs && Map.null invalidApplyInputsTxs _ -> True writeTVar changesVar mempty pure changes runAggregator = forever do event <- atomically pullEvent let changes = case event of RollForward block point tip -> mempty { blocks = [block] , statistics = computeStats block , localTip = Just point , remoteTip = Just tip , invalidCreateTxs = flip foldMap (transactions block) \case InvalidCreateTransaction contractId err -> Map.singleton contractId err _ -> mempty , invalidApplyInputsTxs = flip foldMap (transactions block) \case InvalidApplyInputsTransaction txId _ err -> Map.singleton txId err _ -> mempty } RollBackward point tip -> mempty { rollbackTo = Just point, localTip = Just point, remoteTip = Just tip } atomically $ modifyTVar changesVar (<> changes) pure (runAggregator, readChanges) data PersisterDependencies r = PersisterDependencies { databaseQueries :: DatabaseQueries IO , eventBackend :: EventBackend IO r StoreSelector , readChanges :: STM Changes } persister :: Component IO (PersisterDependencies r) () persister = component_ \PersisterDependencies{..} -> forever do Changes{..} <- atomically readChanges withEvent eventBackend Save \ev -> do traverse_ (addField ev . LocalTip) localTip traverse_ (addField ev . RemoteTip) remoteTip addField ev $ Stats statistics If there is a rollback , save it first . for_ rollbackTo \point -> do addField ev $ RollbackPoint point commitRollback databaseQueries point unless (Map.null invalidCreateTxs) $ addField ev $ InvalidCreateTxs invalidCreateTxs unless (Map.null invalidApplyInputsTxs) $ addField ev $ InvalidApplyInputsTxs invalidApplyInputsTxs unless (null blocks) $ commitBlocks databaseQueries blocks data Changes = Changes { rollbackTo :: Maybe ChainPoint , blocks :: [MarloweBlock] , statistics :: ChangesStatistics , localTip :: Maybe ChainPoint , remoteTip :: Maybe ChainPoint , invalidCreateTxs :: Map ContractId ExtractCreationError , invalidApplyInputsTxs :: Map TxId ExtractMarloweTransactionError } deriving (Show, Eq, Generic) instance Semigroup Changes where a <> b = let a' = maybe id applyRollback (rollbackTo b) a in Changes { rollbackTo = rollbackTo a' , blocks = on (<>) blocks a' b , statistics = on (<>) statistics a' b , localTip = getLast $ on (<>) (Last . localTip) a b , remoteTip = getLast $ on (<>) (Last . remoteTip) a b , invalidCreateTxs = on (<>) invalidCreateTxs a b , invalidApplyInputsTxs = on (<>) invalidApplyInputsTxs a b } applyRollback :: ChainPoint -> Changes -> Changes applyRollback Genesis _ = mempty { rollbackTo = Just Genesis } applyRollback (At block) Changes{..} = if null blocksNotRolledBack then mempty { rollbackTo = Just (At block) } else mempty { blocks = blocksNotRolledBack , statistics = statistics `subStats` foldMap computeStats blocksRolledBack } where (blocksRolledBack, blocksNotRolledBack) = partition isRolledBack blocks isRolledBack MarloweBlock{..} = blockHeader > block subStats :: ChangesStatistics -> ChangesStatistics -> ChangesStatistics subStats a b = ChangesStatistics { blockCount = on (-) blockCount a b , createTxCount = on (-) createTxCount a b , applyInputsTxCount = on (-) applyInputsTxCount a b , withdrawTxCount = on (-) withdrawTxCount a b } computeStats :: MarloweBlock -> ChangesStatistics computeStats MarloweBlock{..} = (foldMap computeTxStats transactions) { blockCount = 1 } where computeTxStats CreateTransaction{} = mempty { createTxCount = 1 } computeTxStats ApplyInputsTransaction{} = mempty { applyInputsTxCount = 1 } computeTxStats WithdrawTransaction{} = mempty { withdrawTxCount = 1 } computeTxStats _ = mempty instance Monoid Changes where mempty = Changes Nothing mempty mempty Nothing Nothing mempty mempty data ChangesStatistics = ChangesStatistics { blockCount :: Int , createTxCount :: Int , applyInputsTxCount :: Int , withdrawTxCount :: Int } deriving (Show, Eq, Generic) instance ToJSON ChangesStatistics instance Semigroup ChangesStatistics where a <> b = ChangesStatistics { blockCount = on (+) blockCount a b , createTxCount = on (+) createTxCount a b , applyInputsTxCount = on (+) applyInputsTxCount a b , withdrawTxCount = on (+) withdrawTxCount a b } instance Monoid ChangesStatistics where mempty = ChangesStatistics 0 0 0 0
9ea022333c31f7cc5cf01e1fdf41386081d66359623cd267b8cd12af62f4a81a
ghcjs/ghcjs-dom
Request.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.Request (js_newRequest, newRequest, js_clone, clone, clone_, js_getMethod, getMethod, js_getUrl, getUrl, js_getHeaders, getHeaders, js_getType, getType, js_getDestination, getDestination, js_getReferrer, getReferrer, js_getReferrerPolicy, getReferrerPolicy, js_getMode, getMode, js_getCredentials, getCredentials, js_getCache, getCache, js_getRedirect, getRedirect, js_getIntegrity, getIntegrity, Request(..), gTypeRequest) 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 foreign import javascript unsafe "new window[\"Request\"]($1, $2)" js_newRequest :: JSVal -> Optional RequestInit -> IO Request | < -US/docs/Web/API/Request Mozilla Request documentation > newRequest :: (MonadIO m, ToJSVal input) => input -> Maybe RequestInit -> m Request newRequest input init = liftIO (toJSVal input >>= \ input' -> js_newRequest input' (maybeToOptional init)) foreign import javascript safe "$1[\"clone\"]()" js_clone :: Request -> IO Request | < -US/docs/Web/API/Request.clone Mozilla Request.clone documentation > clone :: (MonadIO m) => Request -> m Request clone self = liftIO (js_clone self) | < -US/docs/Web/API/Request.clone Mozilla Request.clone documentation > clone_ :: (MonadIO m) => Request -> m () clone_ self = liftIO (void (js_clone self)) foreign import javascript unsafe "$1[\"method\"]" js_getMethod :: Request -> IO JSString | < -US/docs/Web/API/Request.method Mozilla Request.method documentation > getMethod :: (MonadIO m, FromJSString result) => Request -> m result getMethod self = liftIO (fromJSString <$> (js_getMethod self)) foreign import javascript unsafe "$1[\"url\"]" js_getUrl :: Request -> IO JSString | < -US/docs/Web/API/Request.url Mozilla Request.url documentation > getUrl :: (MonadIO m, FromJSString result) => Request -> m result getUrl self = liftIO (fromJSString <$> (js_getUrl self)) foreign import javascript unsafe "$1[\"headers\"]" js_getHeaders :: Request -> IO Headers | < -US/docs/Web/API/Request.headers Mozilla Request.headers documentation > getHeaders :: (MonadIO m) => Request -> m Headers getHeaders self = liftIO (js_getHeaders self) foreign import javascript unsafe "$1[\"type\"]" js_getType :: Request -> IO JSVal -- | <-US/docs/Web/API/Request.type Mozilla Request.type documentation> getType :: (MonadIO m) => Request -> m RequestType getType self = liftIO ((js_getType self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"destination\"]" js_getDestination :: Request -> IO JSVal | < -US/docs/Web/API/Request.destination Mozilla Request.destination documentation > getDestination :: (MonadIO m) => Request -> m RequestDestination getDestination self = liftIO ((js_getDestination self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"referrer\"]" js_getReferrer :: Request -> IO JSString -- | <-US/docs/Web/API/Request.referrer Mozilla Request.referrer documentation> getReferrer :: (MonadIO m, FromJSString result) => Request -> m result getReferrer self = liftIO (fromJSString <$> (js_getReferrer self)) foreign import javascript unsafe "$1[\"referrerPolicy\"]" js_getReferrerPolicy :: Request -> IO JSVal | < -US/docs/Web/API/Request.referrerPolicy Mozilla documentation > getReferrerPolicy :: (MonadIO m) => Request -> m ReferrerPolicy getReferrerPolicy self = liftIO ((js_getReferrerPolicy self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"mode\"]" js_getMode :: Request -> IO JSVal -- | <-US/docs/Web/API/Request.mode Mozilla Request.mode documentation> getMode :: (MonadIO m) => Request -> m RequestMode getMode self = liftIO ((js_getMode self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"credentials\"]" js_getCredentials :: Request -> IO JSVal | < -US/docs/Web/API/Request.credentials Mozilla Request.credentials documentation > getCredentials :: (MonadIO m) => Request -> m RequestCredentials getCredentials self = liftIO ((js_getCredentials self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"cache\"]" js_getCache :: Request -> IO JSVal -- | <-US/docs/Web/API/Request.cache Mozilla Request.cache documentation> getCache :: (MonadIO m) => Request -> m RequestCache getCache self = liftIO ((js_getCache self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"redirect\"]" js_getRedirect :: Request -> IO JSVal | < -US/docs/Web/API/Request.redirect Mozilla Request.redirect documentation > getRedirect :: (MonadIO m) => Request -> m RequestRedirect getRedirect self = liftIO ((js_getRedirect self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"integrity\"]" js_getIntegrity :: Request -> IO JSString | < -US/docs/Web/API/Request.integrity Mozilla Request.integrity documentation > getIntegrity :: (MonadIO m, FromJSString result) => Request -> m result getIntegrity self = liftIO (fromJSString <$> (js_getIntegrity self))
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Request.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | <-US/docs/Web/API/Request.type Mozilla Request.type documentation> | <-US/docs/Web/API/Request.referrer Mozilla Request.referrer documentation> | <-US/docs/Web/API/Request.mode Mozilla Request.mode documentation> | <-US/docs/Web/API/Request.cache Mozilla Request.cache documentation>
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.Request (js_newRequest, newRequest, js_clone, clone, clone_, js_getMethod, getMethod, js_getUrl, getUrl, js_getHeaders, getHeaders, js_getType, getType, js_getDestination, getDestination, js_getReferrer, getReferrer, js_getReferrerPolicy, getReferrerPolicy, js_getMode, getMode, js_getCredentials, getCredentials, js_getCache, getCache, js_getRedirect, getRedirect, js_getIntegrity, getIntegrity, Request(..), gTypeRequest) 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 foreign import javascript unsafe "new window[\"Request\"]($1, $2)" js_newRequest :: JSVal -> Optional RequestInit -> IO Request | < -US/docs/Web/API/Request Mozilla Request documentation > newRequest :: (MonadIO m, ToJSVal input) => input -> Maybe RequestInit -> m Request newRequest input init = liftIO (toJSVal input >>= \ input' -> js_newRequest input' (maybeToOptional init)) foreign import javascript safe "$1[\"clone\"]()" js_clone :: Request -> IO Request | < -US/docs/Web/API/Request.clone Mozilla Request.clone documentation > clone :: (MonadIO m) => Request -> m Request clone self = liftIO (js_clone self) | < -US/docs/Web/API/Request.clone Mozilla Request.clone documentation > clone_ :: (MonadIO m) => Request -> m () clone_ self = liftIO (void (js_clone self)) foreign import javascript unsafe "$1[\"method\"]" js_getMethod :: Request -> IO JSString | < -US/docs/Web/API/Request.method Mozilla Request.method documentation > getMethod :: (MonadIO m, FromJSString result) => Request -> m result getMethod self = liftIO (fromJSString <$> (js_getMethod self)) foreign import javascript unsafe "$1[\"url\"]" js_getUrl :: Request -> IO JSString | < -US/docs/Web/API/Request.url Mozilla Request.url documentation > getUrl :: (MonadIO m, FromJSString result) => Request -> m result getUrl self = liftIO (fromJSString <$> (js_getUrl self)) foreign import javascript unsafe "$1[\"headers\"]" js_getHeaders :: Request -> IO Headers | < -US/docs/Web/API/Request.headers Mozilla Request.headers documentation > getHeaders :: (MonadIO m) => Request -> m Headers getHeaders self = liftIO (js_getHeaders self) foreign import javascript unsafe "$1[\"type\"]" js_getType :: Request -> IO JSVal getType :: (MonadIO m) => Request -> m RequestType getType self = liftIO ((js_getType self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"destination\"]" js_getDestination :: Request -> IO JSVal | < -US/docs/Web/API/Request.destination Mozilla Request.destination documentation > getDestination :: (MonadIO m) => Request -> m RequestDestination getDestination self = liftIO ((js_getDestination self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"referrer\"]" js_getReferrer :: Request -> IO JSString getReferrer :: (MonadIO m, FromJSString result) => Request -> m result getReferrer self = liftIO (fromJSString <$> (js_getReferrer self)) foreign import javascript unsafe "$1[\"referrerPolicy\"]" js_getReferrerPolicy :: Request -> IO JSVal | < -US/docs/Web/API/Request.referrerPolicy Mozilla documentation > getReferrerPolicy :: (MonadIO m) => Request -> m ReferrerPolicy getReferrerPolicy self = liftIO ((js_getReferrerPolicy self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"mode\"]" js_getMode :: Request -> IO JSVal getMode :: (MonadIO m) => Request -> m RequestMode getMode self = liftIO ((js_getMode self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"credentials\"]" js_getCredentials :: Request -> IO JSVal | < -US/docs/Web/API/Request.credentials Mozilla Request.credentials documentation > getCredentials :: (MonadIO m) => Request -> m RequestCredentials getCredentials self = liftIO ((js_getCredentials self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"cache\"]" js_getCache :: Request -> IO JSVal getCache :: (MonadIO m) => Request -> m RequestCache getCache self = liftIO ((js_getCache self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"redirect\"]" js_getRedirect :: Request -> IO JSVal | < -US/docs/Web/API/Request.redirect Mozilla Request.redirect documentation > getRedirect :: (MonadIO m) => Request -> m RequestRedirect getRedirect self = liftIO ((js_getRedirect self) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"integrity\"]" js_getIntegrity :: Request -> IO JSString | < -US/docs/Web/API/Request.integrity Mozilla Request.integrity documentation > getIntegrity :: (MonadIO m, FromJSString result) => Request -> m result getIntegrity self = liftIO (fromJSString <$> (js_getIntegrity self))
3012465948bac54825ceea52d4cf52befd66c5e364168a0c21d90b0b5e458cdb
DavidAlphaFox/RabbitMQ
mochiweb_acceptor.erl
@author < > @copyright 2010 Mochi Media , Inc. @doc MochiWeb acceptor . -module(mochiweb_acceptor). -author(''). -include("internal.hrl"). -export([start_link/3, init/3]). start_link(Server, Listen, Loop) -> proc_lib:spawn_link(?MODULE, init, [Server, Listen, Loop]). init(Server, Listen, Loop) -> T1 = os:timestamp(), case catch mochiweb_socket:accept(Listen) of {ok, Socket} -> gen_server:cast(Server, {accepted, self(), timer:now_diff(os:timestamp(), T1)}), call_loop(Loop, Socket); {error, closed} -> exit(normal); {error, timeout} -> init(Server, Listen, Loop); {error, esslaccept} -> exit(normal); Other -> error_logger:error_report( [{application, mochiweb}, "Accept failed error", lists:flatten(io_lib:format("~p", [Other]))]), exit({error, accept_failed}) end. call_loop({M, F}, Socket) -> M:F(Socket); call_loop({M, F, [A1]}, Socket) -> M:F(Socket, A1); call_loop({M, F, A}, Socket) -> erlang:apply(M, F, [Socket | A]); call_loop(Loop, Socket) -> Loop(Socket). %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif.
null
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/mochiweb-wrapper/mochiweb-git/src/mochiweb_acceptor.erl
erlang
Tests
@author < > @copyright 2010 Mochi Media , Inc. @doc MochiWeb acceptor . -module(mochiweb_acceptor). -author(''). -include("internal.hrl"). -export([start_link/3, init/3]). start_link(Server, Listen, Loop) -> proc_lib:spawn_link(?MODULE, init, [Server, Listen, Loop]). init(Server, Listen, Loop) -> T1 = os:timestamp(), case catch mochiweb_socket:accept(Listen) of {ok, Socket} -> gen_server:cast(Server, {accepted, self(), timer:now_diff(os:timestamp(), T1)}), call_loop(Loop, Socket); {error, closed} -> exit(normal); {error, timeout} -> init(Server, Listen, Loop); {error, esslaccept} -> exit(normal); Other -> error_logger:error_report( [{application, mochiweb}, "Accept failed error", lists:flatten(io_lib:format("~p", [Other]))]), exit({error, accept_failed}) end. call_loop({M, F}, Socket) -> M:F(Socket); call_loop({M, F, [A1]}, Socket) -> M:F(Socket, A1); call_loop({M, F, A}, Socket) -> erlang:apply(M, F, [Socket | A]); call_loop(Loop, Socket) -> Loop(Socket). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif.
44c4be859ba20aa518959fcc346ddfe633626132c635d3e0e3062b689aff634a
orbitz/phantom_types
will_compile.ml
let () = let s1 = Estring.make_utf8 "hello" in let s2 = Estring.make_utf8 "world" in let s3 = Estring.concat (Estring.make_utf8 " ") [s1; s2] in Printf.printf "%s\n" (Estring.str s3)
null
https://raw.githubusercontent.com/orbitz/phantom_types/12f199745f78024e67b01cc39c5aa1a23cfc18e5/estring/will_compile.ml
ocaml
let () = let s1 = Estring.make_utf8 "hello" in let s2 = Estring.make_utf8 "world" in let s3 = Estring.concat (Estring.make_utf8 " ") [s1; s2] in Printf.printf "%s\n" (Estring.str s3)
3f0bb3adc2236a9aaae39d4fe857179a0998eb3cb49e33dd9dbca05cb9de4321
gsdlab/clafer
TypeSystem.hs
# LANGUAGE TemplateHaskell # Copyright ( C ) 2015 < > 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 . Copyright (C) 2015 Michal Antkiewicz <> 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. -} module Suite.TypeSystem (tg_Test_Suite_TypeSystem) where import Language.Clafer import Language.ClaferT import Language.Clafer.Common import Language.Clafer.Intermediate.Intclafer import Language.Clafer.Intermediate.TypeSystem import Functions import qualified Data.Map as M import Data.Maybe (isJust) import Data.StringMap import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.TH tg_Test_Suite_TypeSystem :: TestTree tg_Test_Suite_TypeSystem = $(testGroupGenerator) model :: String model = unlines [ "abstract A" -- c0_A , " abstract as -> A *" -- c0_as , "abstract B : A" -- c0_B c1_as , "b : B" -- c0_b , " [ as = b ]" , " [ as.ref = b ]" ] case_TypeSystemTest :: Assertion case_TypeSystemTest = case compileOneFragment defaultClaferArgs{keep_unused=True} model of Left errors -> assertFailure $ show errors Right compilerResultMap -> case M.lookup Alloy compilerResultMap of Nothing -> assertFailure "No Alloy result in the result map" Just compilerResult -> let um' :: StringMap IClafer um' = uidIClaferMap $ claferEnv compilerResult root_TClafer = getTClaferByUID um' "root" clafer_TClafer = getTClaferByUID um' "clafer" c0_A_TClafer = getTClaferByUID um' "c0_A" c0_A_TClaferR = Just $ TClafer [ "c0_A" ] c0_A_TMap = getDrefTMapByUID um' "c0_A" c0_as_TMap = getDrefTMapByUID um' "c0_as" c0_as_TMapR = Just (TMap {_so = TClafer {_hi = ["c0_as"]}, _ta = TClafer {_hi = ["c0_A"]}}) c0_B_TClafer = getTClaferByUID um' "c0_B" c0_B_TClaferR = Just $ TClafer [ "c0_B", "c0_A" ] c1_as_TClafer = getTClaferByUID um' "c1_as" c1_as_TClaferR = Just $ TClafer [ "c1_as", "c0_as" ] c1_as_TMap = getDrefTMapByUID um' "c1_as" c1_as_TMapR = Just (TMap {_so = TClafer {_hi = ["c1_as","c0_as"]}, _ta = TClafer {_hi = [ "c0_B", "c0_A" ]}}) c0_b_TClafer = getTClaferByUID um' "c0_b" c0_b_TClaferR = Just $ TClafer [ "c0_b", "c0_B", "c0_A" ] in do (isJust $ findIClafer um' "c0_A") @? ("Clafer c0_A not found" ++ show um') root_TClafer == Just rootTClafer @? ("Incorrect class type for 'root':\ngot '" ++ show root_TClafer ++ "'\ninstead of '" ++ show rootTClafer ++ "'") clafer_TClafer == Just claferTClafer @? ("Incorrect class type for 'clafer':\ngot '" ++ show clafer_TClafer ++ "'\ninstead of '" ++ show claferTClafer ++ "'") c0_A_TClafer == c0_A_TClaferR @? ("Incorrect class type for 'c0_A':\ngot '" ++ show c0_A_TClafer ++ "'\ninstead of '" ++ show c0_A_TClaferR ++ "'") c0_A_TMap == Nothing @? ("Incorrect map type for 'c0_A':\ngot '" ++ show c0_A_TMap ++ "'\nbut it is \nt a reference.") c0_as_TMap == c0_as_TMapR @? ("Incorrect map type for 'c0_as':\ngot '" ++ show c0_as_TMap ++ "'\ninstead of '" ++ show c0_as_TMapR ++ "'") c0_B_TClafer == c0_B_TClaferR @? ("Incorrect class type for 'c0_B':\ngot '" ++ show c0_B_TClafer ++ "'\ninstead of '" ++ show c0_B_TClaferR ++ "'") c1_as_TClafer == c1_as_TClaferR @? ("Incorrect class type for 'c1_as':\ngot '" ++ show c1_as_TClafer ++ "'\ninstead of '" ++ show c1_as_TClaferR ++ "'") c1_as_TMap == c1_as_TMapR @? ("Incorrect map type for 'c1_as':\ngot '" ++ show c1_as_TMap ++ "'\ninstead of '" ++ show c1_as_TMapR ++ "'") c0_b_TClafer == c0_b_TClaferR @? ("Incorrect class type for 'c0_b':\ngot '" ++ show c0_b_TClafer ++ "'\ninstead of '" ++ show c0_b_TClaferR ++ "'")
null
https://raw.githubusercontent.com/gsdlab/clafer/a30a645ae1e4fc793851e53446d220924038873a/test/Suite/TypeSystem.hs
haskell
c0_A c0_as c0_B c0_b
# LANGUAGE TemplateHaskell # Copyright ( C ) 2015 < > 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 . Copyright (C) 2015 Michal Antkiewicz <> 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. -} module Suite.TypeSystem (tg_Test_Suite_TypeSystem) where import Language.Clafer import Language.ClaferT import Language.Clafer.Common import Language.Clafer.Intermediate.Intclafer import Language.Clafer.Intermediate.TypeSystem import Functions import qualified Data.Map as M import Data.Maybe (isJust) import Data.StringMap import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.TH tg_Test_Suite_TypeSystem :: TestTree tg_Test_Suite_TypeSystem = $(testGroupGenerator) model :: String model = unlines c1_as , " [ as = b ]" , " [ as.ref = b ]" ] case_TypeSystemTest :: Assertion case_TypeSystemTest = case compileOneFragment defaultClaferArgs{keep_unused=True} model of Left errors -> assertFailure $ show errors Right compilerResultMap -> case M.lookup Alloy compilerResultMap of Nothing -> assertFailure "No Alloy result in the result map" Just compilerResult -> let um' :: StringMap IClafer um' = uidIClaferMap $ claferEnv compilerResult root_TClafer = getTClaferByUID um' "root" clafer_TClafer = getTClaferByUID um' "clafer" c0_A_TClafer = getTClaferByUID um' "c0_A" c0_A_TClaferR = Just $ TClafer [ "c0_A" ] c0_A_TMap = getDrefTMapByUID um' "c0_A" c0_as_TMap = getDrefTMapByUID um' "c0_as" c0_as_TMapR = Just (TMap {_so = TClafer {_hi = ["c0_as"]}, _ta = TClafer {_hi = ["c0_A"]}}) c0_B_TClafer = getTClaferByUID um' "c0_B" c0_B_TClaferR = Just $ TClafer [ "c0_B", "c0_A" ] c1_as_TClafer = getTClaferByUID um' "c1_as" c1_as_TClaferR = Just $ TClafer [ "c1_as", "c0_as" ] c1_as_TMap = getDrefTMapByUID um' "c1_as" c1_as_TMapR = Just (TMap {_so = TClafer {_hi = ["c1_as","c0_as"]}, _ta = TClafer {_hi = [ "c0_B", "c0_A" ]}}) c0_b_TClafer = getTClaferByUID um' "c0_b" c0_b_TClaferR = Just $ TClafer [ "c0_b", "c0_B", "c0_A" ] in do (isJust $ findIClafer um' "c0_A") @? ("Clafer c0_A not found" ++ show um') root_TClafer == Just rootTClafer @? ("Incorrect class type for 'root':\ngot '" ++ show root_TClafer ++ "'\ninstead of '" ++ show rootTClafer ++ "'") clafer_TClafer == Just claferTClafer @? ("Incorrect class type for 'clafer':\ngot '" ++ show clafer_TClafer ++ "'\ninstead of '" ++ show claferTClafer ++ "'") c0_A_TClafer == c0_A_TClaferR @? ("Incorrect class type for 'c0_A':\ngot '" ++ show c0_A_TClafer ++ "'\ninstead of '" ++ show c0_A_TClaferR ++ "'") c0_A_TMap == Nothing @? ("Incorrect map type for 'c0_A':\ngot '" ++ show c0_A_TMap ++ "'\nbut it is \nt a reference.") c0_as_TMap == c0_as_TMapR @? ("Incorrect map type for 'c0_as':\ngot '" ++ show c0_as_TMap ++ "'\ninstead of '" ++ show c0_as_TMapR ++ "'") c0_B_TClafer == c0_B_TClaferR @? ("Incorrect class type for 'c0_B':\ngot '" ++ show c0_B_TClafer ++ "'\ninstead of '" ++ show c0_B_TClaferR ++ "'") c1_as_TClafer == c1_as_TClaferR @? ("Incorrect class type for 'c1_as':\ngot '" ++ show c1_as_TClafer ++ "'\ninstead of '" ++ show c1_as_TClaferR ++ "'") c1_as_TMap == c1_as_TMapR @? ("Incorrect map type for 'c1_as':\ngot '" ++ show c1_as_TMap ++ "'\ninstead of '" ++ show c1_as_TMapR ++ "'") c0_b_TClafer == c0_b_TClaferR @? ("Incorrect class type for 'c0_b':\ngot '" ++ show c0_b_TClafer ++ "'\ninstead of '" ++ show c0_b_TClaferR ++ "'")
87be0ff7d40a636d63db91f53675376eab3db0cafddd44828080572daf5161da
naproche/naproche
Time.hs
{- generated by Isabelle -} Title : Isabelle / Time.hs Author : Makarius LICENSE : BSD 3 - clause ( Isabelle ) Time based on milliseconds . See " $ ISABELLE_HOME / src / Pure / General / time.scala " Author: Makarius LICENSE: BSD 3-clause (Isabelle) Time based on milliseconds. See "$ISABELLE_HOME/src/Pure/General/time.scala" -} {-# LANGUAGE OverloadedStrings #-} module Isabelle.Time ( Time, seconds, minutes, ms, zero, is_zero, is_relevant, get_seconds, get_minutes, get_ms, message, now ) where import Text.Printf (printf) import Data.Time.Clock.POSIX (getPOSIXTime) import Isabelle.Bytes (Bytes) import Isabelle.Library newtype Time = Time Int instance Eq Time where Time a == Time b = a == b instance Ord Time where compare (Time a) (Time b) = compare a b instance Num Time where fromInteger = Time . fromInteger Time a + Time b = Time (a + b) Time a - Time b = Time (a - b) Time a * Time b = Time (a * b) abs (Time a) = Time (abs a) signum (Time a) = Time (signum a) seconds :: Double -> Time seconds s = Time (round (s * 1000.0)) minutes :: Double -> Time minutes m = Time (round (m * 60000.0)) ms :: Int -> Time ms = Time zero :: Time zero = ms 0 is_zero :: Time -> Bool is_zero (Time ms) = ms == 0 is_relevant :: Time -> Bool is_relevant (Time ms) = ms >= 1 get_seconds :: Time -> Double get_seconds (Time ms) = fromIntegral ms / 1000.0 get_minutes :: Time -> Double get_minutes (Time ms) = fromIntegral ms / 60000.0 get_ms :: Time -> Int get_ms (Time ms) = ms instance Show Time where show t = printf "%.3f" (get_seconds t) message :: Time -> Bytes message t = make_bytes (show t) <> "s" now :: IO Time now = do t <- getPOSIXTime return $ Time (round (realToFrac t * 1000.0 :: Double))
null
https://raw.githubusercontent.com/naproche/naproche/f88efe1cf38828069e0d6ba225318562702f3d41/Isabelle/src/Isabelle/Time.hs
haskell
generated by Isabelle # LANGUAGE OverloadedStrings #
Title : Isabelle / Time.hs Author : Makarius LICENSE : BSD 3 - clause ( Isabelle ) Time based on milliseconds . See " $ ISABELLE_HOME / src / Pure / General / time.scala " Author: Makarius LICENSE: BSD 3-clause (Isabelle) Time based on milliseconds. See "$ISABELLE_HOME/src/Pure/General/time.scala" -} module Isabelle.Time ( Time, seconds, minutes, ms, zero, is_zero, is_relevant, get_seconds, get_minutes, get_ms, message, now ) where import Text.Printf (printf) import Data.Time.Clock.POSIX (getPOSIXTime) import Isabelle.Bytes (Bytes) import Isabelle.Library newtype Time = Time Int instance Eq Time where Time a == Time b = a == b instance Ord Time where compare (Time a) (Time b) = compare a b instance Num Time where fromInteger = Time . fromInteger Time a + Time b = Time (a + b) Time a - Time b = Time (a - b) Time a * Time b = Time (a * b) abs (Time a) = Time (abs a) signum (Time a) = Time (signum a) seconds :: Double -> Time seconds s = Time (round (s * 1000.0)) minutes :: Double -> Time minutes m = Time (round (m * 60000.0)) ms :: Int -> Time ms = Time zero :: Time zero = ms 0 is_zero :: Time -> Bool is_zero (Time ms) = ms == 0 is_relevant :: Time -> Bool is_relevant (Time ms) = ms >= 1 get_seconds :: Time -> Double get_seconds (Time ms) = fromIntegral ms / 1000.0 get_minutes :: Time -> Double get_minutes (Time ms) = fromIntegral ms / 60000.0 get_ms :: Time -> Int get_ms (Time ms) = ms instance Show Time where show t = printf "%.3f" (get_seconds t) message :: Time -> Bytes message t = make_bytes (show t) <> "s" now :: IO Time now = do t <- getPOSIXTime return $ Time (round (realToFrac t * 1000.0 :: Double))
14c8b37e53e243dbe3fc1a70d988cc68a141b4d957be5318cf0be29e5b0a3554
caradoc-org/caradoc
textview.mli
(*****************************************************************************) (* Caradoc: a PDF parser and validator *) Copyright ( C ) 2017 (* *) (* This program is free software; you can redistribute it and/or modify *) it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . (*****************************************************************************) module TextView : sig type t val make : unit -> t val make_string : string -> t val help : t val move_up : t -> int -> unit val move_down : t -> int -> unit val move_to : t -> int -> unit val move_home : t -> unit val move_end : t -> unit val draw : t -> Curses.window -> unit end
null
https://raw.githubusercontent.com/caradoc-org/caradoc/100f53bc55ef682049e10fabf24869bc019dc6ce/src/ui/textview.mli
ocaml
*************************************************************************** Caradoc: a PDF parser and validator This program is free software; you can redistribute it and/or modify This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************
Copyright ( C ) 2017 it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . module TextView : sig type t val make : unit -> t val make_string : string -> t val help : t val move_up : t -> int -> unit val move_down : t -> int -> unit val move_to : t -> int -> unit val move_home : t -> unit val move_end : t -> unit val draw : t -> Curses.window -> unit end
0dd1816feab87ff1f079cd250c10ecf105d53cd9b738640846d2688213d3af8d
CloudI/CloudI
cloudi_request.erl
-*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*- ex : set utf-8 sts=4 ts=4 sw=4 et nomod : %%% %%%------------------------------------------------------------------------ %%% @doc %%% ==CloudI Request== %%% Request format transform. %%% @end %%% MIT License %%% Copyright ( c ) 2013 - 2023 Michael Truog < mjtruog at protonmail dot com > %%% %%% Permission is hereby granted, free of charge, to any person obtaining a %%% copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation %%% the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the %%% Software is furnished to do so, subject to the following conditions: %%% %%% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %%% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING %%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER %%% DEALINGS IN THE SOFTWARE. %%% @author < mjtruog at protonmail dot com > 2013 - 2023 Michael Truog %%% @version 2.0.6 {@date} {@time} %%%------------------------------------------------------------------------ -module(cloudi_request). -author('mjtruog at protonmail dot com'). %% external interface -export([external_format/2]). % erlang_binary: % % A raw format, making sure incoming binary data is preserved and % outgoing non-binary data is made binary as with erlang_string % (a human-readable format, same as file:consult/1). % The erlang_binary format allows data to pass-through unmodified % unless it requires modification for the external service to receive % the service request response. The erlang_binary format is only used by services that are able to handle raw Erlang % binary data. % % erlang_string: % Erlang terms as human - readable text for both incoming and outgoing % data (same as file:consult/1). % % erlang_term: % The Erlang External Term Format for both incoming and outgoing data % (). % % msgpack: % % The msgpack format with the following data modifications: outgoing Erlang atoms become msgpack binary strings ( using utf8 ) outgoing Erlang tuples become msgpack arrays Erlang maps are used if the Erlang version > = 18.x ( otherwise the jsx map format is used for outgoing Erlang data ) % Usage: Typically an Elixir / Erlang CloudI service will provide an ' output ' % configuration argument (i.e., an "output type") which determines the Erlang types used for the service 's outgoing service requests . % The 'output' configuration argument value can then influence how the % 'external_format' is used (where 'external_format' is also an service configuration argument ) . The ' output ' % configuration argument values are below: % external: % The cloudi_request:external_format/2 function should always be called due to assuming the Request is an Erlang binary . % The cloudi_response:external_format/2 function should always be called due to assuming the Response is an Erlang binary . % internal: % The cloudi_request:external_format/2 function should never be called % on the Request data. The cloudi_response:external_format/2 function % should never be called on the Response data. % both: If the Request is an Erlang binary , the Request and Response are handled as if the ' output ' is external . If the Request is not an Erlang binary , % the Request and Response are handled as if the 'output' is internal. % The internal and external configuration argument values refer to whether the output is for either an internal CloudI service ( Elixir / Erlang - only ) or an external CloudI service ( non - Elixir / Erlang ) . External CloudI services use Erlang binary data for RequestInfo / Request data and % ResponseInfo/Response data without any protocol enforced on the data % (making the data protocol-agnostic). The 'external_format' configuration % argument specifies a protocol to use with the Request data and the Response data ( RequestInfo and ResponseInfo are key / value metadata , which is a common % concept in any protocol), based on the 'output' configuration argument. % If the Erlang CloudI service needs an API with commands % (normally wrapped into tuples, used for the Request data), then % the 'output' configuration argument should support % external, internal, and both. The 'external_format' % configuration argument should also be supported. % % If the Erlang CloudI service's main purpose is to manage a source of Erlang binary data ( a protocol , e.g. , HTTP , TCP , UDP , etc . ) , % then the 'output' configuration argument and the 'external_format' % configuration argument should not be supported since the output should always be an Erlang binary ( to keep the burden of binary validation on the CloudI service that receives the service requests ) . -type external_format() :: erlang_string | erlang_term | msgpack. -export_type([external_format/0]). -include("cloudi_core_i_constants.hrl"). %%%------------------------------------------------------------------------ %%% External interface functions %%%------------------------------------------------------------------------ %%------------------------------------------------------------------------- %% @doc = = = Decode incoming external request data.=== %% @end %%------------------------------------------------------------------------- -spec external_format(Request :: binary(), Format :: external_format()) -> any(). external_format(Request, Format) when is_binary(Request) -> if Format =:= erlang_string -> cloudi_string:binary_to_term(Request); Format =:= erlang_term -> erlang:binary_to_term(Request); Format =:= msgpack -> {ok, Incoming} = cloudi_x_msgpack: unpack(Request, [{map_format, map}]), Incoming end. %%%------------------------------------------------------------------------ %%% Private functions %%%------------------------------------------------------------------------
null
https://raw.githubusercontent.com/CloudI/CloudI/e2e0b78f82ee6ba9f4f47713f19833bec8d071f6/src/lib/cloudi_core/src/cloudi_request.erl
erlang
------------------------------------------------------------------------ @doc ==CloudI Request== Request format transform. @end Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @version 2.0.6 {@date} {@time} ------------------------------------------------------------------------ external interface erlang_binary: A raw format, making sure incoming binary data is preserved and outgoing non-binary data is made binary as with erlang_string (a human-readable format, same as file:consult/1). The erlang_binary format allows data to pass-through unmodified unless it requires modification for the external service to receive the service request response. The erlang_binary format is only binary data. erlang_string: data (same as file:consult/1). erlang_term: (). msgpack: The msgpack format with the following data modifications: Usage: configuration argument (i.e., an "output type") which determines the The 'output' configuration argument value can then influence how the 'external_format' is used (where 'external_format' is also an configuration argument values are below: external: The cloudi_request:external_format/2 function should always be called The cloudi_response:external_format/2 function should always be called internal: The cloudi_request:external_format/2 function should never be called on the Request data. The cloudi_response:external_format/2 function should never be called on the Response data. both: the Request and Response are handled as if the 'output' is internal. The internal and external configuration argument values refer to whether ResponseInfo/Response data without any protocol enforced on the data (making the data protocol-agnostic). The 'external_format' configuration argument specifies a protocol to use with the Request data and the Response concept in any protocol), based on the 'output' configuration argument. If the Erlang CloudI service needs an API with commands (normally wrapped into tuples, used for the Request data), then the 'output' configuration argument should support external, internal, and both. The 'external_format' configuration argument should also be supported. If the Erlang CloudI service's main purpose is to manage a source then the 'output' configuration argument and the 'external_format' configuration argument should not be supported since the output should ------------------------------------------------------------------------ External interface functions ------------------------------------------------------------------------ ------------------------------------------------------------------------- @doc @end ------------------------------------------------------------------------- ------------------------------------------------------------------------ Private functions ------------------------------------------------------------------------
-*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*- ex : set utf-8 sts=4 ts=4 sw=4 et nomod : MIT License Copyright ( c ) 2013 - 2023 Michael Truog < mjtruog at protonmail dot com > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING @author < mjtruog at protonmail dot com > 2013 - 2023 Michael Truog -module(cloudi_request). -author('mjtruog at protonmail dot com'). -export([external_format/2]). used by services that are able to handle raw Erlang Erlang terms as human - readable text for both incoming and outgoing The Erlang External Term Format for both incoming and outgoing data outgoing Erlang atoms become msgpack binary strings ( using utf8 ) outgoing Erlang tuples become msgpack arrays Erlang maps are used if the Erlang version > = 18.x ( otherwise the jsx map format is used for outgoing Erlang data ) Typically an Elixir / Erlang CloudI service will provide an ' output ' Erlang types used for the service 's outgoing service requests . service configuration argument ) . The ' output ' due to assuming the Request is an Erlang binary . due to assuming the Response is an Erlang binary . If the Request is an Erlang binary , the Request and Response are handled as if the ' output ' is external . If the Request is not an Erlang binary , the output is for either an internal CloudI service ( Elixir / Erlang - only ) or an external CloudI service ( non - Elixir / Erlang ) . External CloudI services use Erlang binary data for RequestInfo / Request data and data ( RequestInfo and ResponseInfo are key / value metadata , which is a common of Erlang binary data ( a protocol , e.g. , HTTP , TCP , UDP , etc . ) , always be an Erlang binary ( to keep the burden of binary validation on the CloudI service that receives the service requests ) . -type external_format() :: erlang_string | erlang_term | msgpack. -export_type([external_format/0]). -include("cloudi_core_i_constants.hrl"). = = = Decode incoming external request data.=== -spec external_format(Request :: binary(), Format :: external_format()) -> any(). external_format(Request, Format) when is_binary(Request) -> if Format =:= erlang_string -> cloudi_string:binary_to_term(Request); Format =:= erlang_term -> erlang:binary_to_term(Request); Format =:= msgpack -> {ok, Incoming} = cloudi_x_msgpack: unpack(Request, [{map_format, map}]), Incoming end.
d9646cd67492bab9e452225127a17674855b87d1b5d482dc335af9493cc8dd53
jackfirth/rebellion
web-link.rkt
#lang racket/base (require racket/contract/base) (provide (contract-out [web-link (-> url-coercible? link-relation-coercible? url-coercible? web-link?)] [web-link? (-> any/c boolean?)] [web-link-source (-> web-link? url?)] [web-link-relation (-> web-link? (or/c url? symbol?))] [web-link-target (-> web-link? url?)])) (require net/url racket/struct rebellion/type/tuple) (module+ test (require (submod "..") racket/format rackunit)) ;@------------------------------------------------------------------------------ (define url-coercible? (or/c url? string?)) (define (url-coerce url-ish) (if (string? url-ish) (string->url url-ish) url-ish)) (define link-relation-coercible? (or/c url? string? symbol?)) (define (link-relation-coerce relation-ish) (if (string? relation-ish) (string->url relation-ish) relation-ish)) (define (link-relation->writable-value relation) (if (symbol? relation) relation (url->string relation))) (define (property-maker descriptor) (define name (tuple-type-name (tuple-descriptor-type descriptor))) (define accessor (tuple-descriptor-accessor descriptor)) (define equal+hash (default-tuple-equal+hash descriptor)) (define custom-write (make-constructor-style-printer (λ (_) name) (λ (this) (list (url->string (accessor this 0)) (link-relation->writable-value (accessor this 1)) (url->string (accessor this 2)))))) (list (cons prop:equal+hash equal+hash) (cons prop:custom-write custom-write))) (define-tuple-type web-link (source relation target) #:property-maker property-maker #:omit-root-binding) (define (web-link source relation target) (constructor:web-link (url-coerce source) (link-relation-coerce relation) (url-coerce target))) (module+ test (test-case "prop:custom-write" (define link (web-link "" 'stylesheet "/styles.css")) (check-equal? (~v link) #<<END (web-link "" 'stylesheet "/styles.css") END ) (check-equal? (~s link) #<<END #<web-link: "" stylesheet "/styles.css"> END ) (check-equal? (~a link) #<<END #<web-link: stylesheet /styles.css> END )))
null
https://raw.githubusercontent.com/jackfirth/rebellion/64f8f82ac3343fe632388bfcbb9e537759ac1ac2/web-link.rkt
racket
@------------------------------------------------------------------------------
#lang racket/base (require racket/contract/base) (provide (contract-out [web-link (-> url-coercible? link-relation-coercible? url-coercible? web-link?)] [web-link? (-> any/c boolean?)] [web-link-source (-> web-link? url?)] [web-link-relation (-> web-link? (or/c url? symbol?))] [web-link-target (-> web-link? url?)])) (require net/url racket/struct rebellion/type/tuple) (module+ test (require (submod "..") racket/format rackunit)) (define url-coercible? (or/c url? string?)) (define (url-coerce url-ish) (if (string? url-ish) (string->url url-ish) url-ish)) (define link-relation-coercible? (or/c url? string? symbol?)) (define (link-relation-coerce relation-ish) (if (string? relation-ish) (string->url relation-ish) relation-ish)) (define (link-relation->writable-value relation) (if (symbol? relation) relation (url->string relation))) (define (property-maker descriptor) (define name (tuple-type-name (tuple-descriptor-type descriptor))) (define accessor (tuple-descriptor-accessor descriptor)) (define equal+hash (default-tuple-equal+hash descriptor)) (define custom-write (make-constructor-style-printer (λ (_) name) (λ (this) (list (url->string (accessor this 0)) (link-relation->writable-value (accessor this 1)) (url->string (accessor this 2)))))) (list (cons prop:equal+hash equal+hash) (cons prop:custom-write custom-write))) (define-tuple-type web-link (source relation target) #:property-maker property-maker #:omit-root-binding) (define (web-link source relation target) (constructor:web-link (url-coerce source) (link-relation-coerce relation) (url-coerce target))) (module+ test (test-case "prop:custom-write" (define link (web-link "" 'stylesheet "/styles.css")) (check-equal? (~v link) #<<END (web-link "" 'stylesheet "/styles.css") END ) (check-equal? (~s link) #<<END #<web-link: "" stylesheet "/styles.css"> END ) (check-equal? (~a link) #<<END #<web-link: stylesheet /styles.css> END )))
125af31ff1394b3b8ef7d23bf9387bf55c8a79aa03821caa8d39b712bf9b758e
ocaml-flambda/ocaml-jst
translattribute.ml
(**************************************************************************) (* *) (* OCaml *) (* *) (* Pierre Chambart, OCamlPro *) (* *) Copyright 2015 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Typedtree open Lambda open Location let is_inline_attribute = [ ["inline"; "ocaml.inline"],true ] let is_inlined_attribute = [ ["inlined"; "ocaml.inlined"], true ; ["unrolled"; "ocaml.unrolled"], (Config.flambda || Config.flambda2) ] let is_specialise_attribute = [ ["specialise"; "ocaml.specialise"], Config.flambda ] let is_specialised_attribute = [ ["specialised"; "ocaml.specialised"], Config.flambda ] let is_local_attribute = [ ["local"; "ocaml.local"], true ] let is_tailcall_attribute = [ ["tailcall"; "ocaml.tailcall"], true ] let is_property_attribute = function | Noalloc -> [ ["noalloc"; "ocaml.noalloc"], true ] let is_tmc_attribute = [ ["tail_mod_cons"; "ocaml.tail_mod_cons"], true ] let is_poll_attribute = [ ["poll"; "ocaml.poll"], true ] let is_loop_attribute = [ ["loop"; "ocaml.loop"], true ] let find_attribute p attributes = let inline_attribute = Builtin_attributes.filter_attributes p attributes in let attr = match inline_attribute with | [] -> None | [attr] -> Some attr | attr :: {Parsetree.attr_name = {txt;loc}; _} :: _ -> Location.prerr_warning loc (Warnings.Duplicated_attribute txt); Some attr in attr let is_unrolled = function | {txt="unrolled"|"ocaml.unrolled"} -> true | {txt="inline"|"ocaml.inline"|"inlined"|"ocaml.inlined"} -> false | _ -> assert false let get_payload get_from_exp = let open Parsetree in function | PStr [{pstr_desc = Pstr_eval (exp, [])}] -> get_from_exp exp | _ -> Result.Error () let get_optional_payload get_from_exp = let open Parsetree in function | PStr [] -> Result.Ok None | other -> Result.map Option.some (get_payload get_from_exp other) let get_id_from_exp = let open Parsetree in function | { pexp_desc = Pexp_ident { txt = Longident.Lident id } } -> Result.Ok id | _ -> Result.Error () let get_int_from_exp = let open Parsetree in function | { pexp_desc = Pexp_constant (Pconst_integer(s, None)) } -> begin match Misc.Int_literal_converter.int s with | n -> Result.Ok n | exception (Failure _) -> Result.Error () end | _ -> Result.Error () let get_construct_from_exp = let open Parsetree in function | { pexp_desc = Pexp_construct ({ txt = Longident.Lident constr }, None) } -> Result.Ok constr | _ -> Result.Error () let get_bool_from_exp exp = Result.bind (get_construct_from_exp exp) (function | "true" -> Result.Ok true | "false" -> Result.Ok false | _ -> Result.Error ()) let parse_id_payload txt loc ~default ~empty cases payload = let[@local] warn () = let ( %> ) f g x = g (f x) in let msg = cases |> List.map (fst %> Printf.sprintf "'%s'") |> String.concat ", " |> Printf.sprintf "It must be either %s or empty" in Location.prerr_warning loc (Warnings.Attribute_payload (txt, msg)); default in match get_optional_payload get_id_from_exp payload with | Error () -> warn () | Ok None -> empty | Ok (Some id) -> match List.assoc_opt id cases with | Some r -> r | None -> warn () let parse_inline_attribute attr : inline_attribute = match attr with | None -> Default_inline | Some {Parsetree.attr_name = {txt;loc} as id; attr_payload = payload} -> if is_unrolled id then begin (* the 'unrolled' attributes must be used as [@unrolled n]. *) let warning txt = Warnings.Attribute_payload (txt, "It must be an integer literal") in match get_payload get_int_from_exp payload with | Ok n -> Unroll n | Error () -> Location.prerr_warning loc (warning txt); Default_inline end else parse_id_payload txt loc ~default:Default_inline ~empty:Always_inline [ "never", Never_inline; "always", Always_inline; "available", Available_inline; ] payload let parse_inlined_attribute attr : inlined_attribute = match attr with | None -> Default_inlined | Some {Parsetree.attr_name = {txt;loc} as id; attr_payload = payload} -> if is_unrolled id then begin (* the 'unrolled' attributes must be used as [@unrolled n]. *) let warning txt = Warnings.Attribute_payload (txt, "It must be an integer literal") in match get_payload get_int_from_exp payload with | Ok n -> Unroll n | Error () -> Location.prerr_warning loc (warning txt); Default_inlined end else parse_id_payload txt loc ~default:Default_inlined ~empty:Always_inlined [ "never", Never_inlined; "always", Always_inlined; "hint", Hint_inlined; ] payload let parse_specialise_attribute attr = match attr with | None -> Default_specialise | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_specialise ~empty:Always_specialise [ "never", Never_specialise; "always", Always_specialise; ] payload let parse_local_attribute attr = match attr with | None -> Default_local | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_local ~empty:Always_local [ "never", Never_local; "always", Always_local; "maybe", Default_local; ] payload let parse_property_attribute attr p = match attr with | None -> Default_check | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload}-> parse_id_payload txt loc ~default:Default_check ~empty:(Assert p) [ "assume", Assume p; ] payload let parse_poll_attribute attr = match attr with | None -> Default_poll | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_poll ~empty:Default_poll [ "error", Error_poll; ] payload let parse_loop_attribute attr = match attr with | None -> Default_loop | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_loop ~empty:Always_loop [ "never", Never_loop; "always", Always_loop; ] payload let get_inline_attribute l = let attr = find_attribute is_inline_attribute l in parse_inline_attribute attr let get_specialise_attribute l = let attr = find_attribute is_specialise_attribute l in parse_specialise_attribute attr let get_local_attribute l = let attr = find_attribute is_local_attribute l in parse_local_attribute attr let get_property_attribute l p = let attr = find_attribute (is_property_attribute p) l in parse_property_attribute attr p let get_check_attribute l = get_property_attribute l Noalloc let get_poll_attribute l = let attr = find_attribute is_poll_attribute l in parse_poll_attribute attr let get_loop_attribute l = let attr = find_attribute is_loop_attribute l in parse_loop_attribute attr let check_local_inline loc attr = match attr.local, attr.inline with | Always_local, (Always_inline | Available_inline | Unroll _) -> Location.prerr_warning loc (Warnings.Duplicated_attribute "local/inline") | _ -> () let check_poll_inline loc attr = match attr.poll, attr.inline with | Error_poll, (Always_inline | Available_inline | Unroll _) -> Location.prerr_warning loc (Warnings.Inlining_impossible "[@poll error] is incompatible with inlining") | _ -> () let check_poll_local loc attr = match attr.poll, attr.local with | Error_poll, Always_local -> Location.prerr_warning loc (Warnings.Inlining_impossible "[@poll error] is incompatible with local function optimization") | _ -> () let lfunction_with_attr ~attr { kind; params; return; body; attr=_; loc; mode; region } = lfunction ~kind ~params ~return ~body ~attr ~loc ~mode ~region let add_inline_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_inline_attribute attributes with | Default_inline -> expr | (Always_inline | Available_inline | Never_inline | Unroll _) as inline -> begin match attr.inline with | Default_inline -> () | Always_inline | Available_inline | Never_inline | Unroll _ -> Location.prerr_warning loc (Warnings.Duplicated_attribute "inline") end; let attr = { attr with inline } in check_local_inline loc attr; check_poll_inline loc attr; lfunction_with_attr ~attr funct end | _ -> expr let add_specialise_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_specialise_attribute attributes with | Default_specialise -> expr | (Always_specialise | Never_specialise) as specialise -> begin match attr.specialise with | Default_specialise -> () | Always_specialise | Never_specialise -> Location.prerr_warning loc (Warnings.Duplicated_attribute "specialise") end; let attr = { attr with specialise } in lfunction_with_attr ~attr funct end | _ -> expr let add_local_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_local_attribute attributes with | Default_local -> expr | (Always_local | Never_local) as local -> begin match attr.local with | Default_local -> () | Always_local | Never_local -> Location.prerr_warning loc (Warnings.Duplicated_attribute "local") end; let attr = { attr with local } in check_local_inline loc attr; check_poll_local loc attr; lfunction_with_attr ~attr funct end | _ -> expr let add_check_attribute expr loc attributes = let to_string = function | Noalloc -> "noalloc" in let to_string = function | Assert p -> to_string p | Assume p -> Printf.sprintf "%s assume" (to_string p) | Default_check -> assert false in match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_check_attribute attributes with | Default_check -> expr | (Assert _ | Assume _) as check -> begin match attr.check with | Default_check -> () | Assert Noalloc | Assume Noalloc -> Location.prerr_warning loc (Warnings.Duplicated_attribute (to_string check)) end; let attr = { attr with check } in lfunction_with_attr ~attr funct end | expr -> expr let add_loop_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_loop_attribute attributes with | Default_loop -> expr | (Always_loop | Never_loop) as loop -> begin match attr.loop with | Default_loop -> () | Always_loop | Never_loop -> Location.prerr_warning loc (Warnings.Duplicated_attribute "loop") end; let attr = { attr with loop } in lfunction_with_attr ~attr funct end | _ -> expr let add_tmc_attribute expr loc attributes = match expr with | Lfunction funct -> let attr = find_attribute is_tmc_attribute attributes in begin match attr with | None -> expr | Some _ -> if funct.attr.tmc_candidate then Location.prerr_warning loc (Warnings.Duplicated_attribute "tail_mod_cons"); let attr = { funct.attr with tmc_candidate = true } in lfunction_with_attr ~attr funct end | _ -> expr let add_poll_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_poll_attribute attributes with | Default_poll -> expr | Error_poll as poll -> begin match attr.poll with | Default_poll -> () | Error_poll -> Location.prerr_warning loc (Warnings.Duplicated_attribute "error_poll") end; let attr = { attr with poll } in check_poll_inline loc attr; check_poll_local loc attr; let attr = { attr with inline = Never_inline; local = Never_local } in lfunction_with_attr ~attr funct end | expr -> expr (* Get the [@inlined] attribute payload (or default if not present). *) let get_inlined_attribute e = let attr = find_attribute is_inlined_attribute e.exp_attributes in parse_inlined_attribute attr let get_inlined_attribute_on_module e = let rec get mod_expr = let attr = find_attribute is_inlined_attribute mod_expr.mod_attributes in let attr = parse_inlined_attribute attr in let attr = match mod_expr.Typedtree.mod_desc with | Tmod_constraint (me, _, _, _) -> let inner_attr = get me in begin match attr with | Always_inlined | Hint_inlined | Never_inlined | Unroll _ -> attr | Default_inlined -> inner_attr end | _ -> attr in attr in get e let get_specialised_attribute e = let attr = find_attribute is_specialised_attribute e.exp_attributes in parse_specialise_attribute attr let get_tailcall_attribute e = let attr = find_attribute is_tailcall_attribute e.exp_attributes in match attr with | None -> Default_tailcall | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> match get_optional_payload get_bool_from_exp payload with | Ok (None | Some true) -> Tailcall_expectation true | Ok (Some false) -> Tailcall_expectation false | Error () -> let msg = "Only an optional boolean literal is supported." in Location.prerr_warning loc (Warnings.Attribute_payload (txt, msg)); Default_tailcall let add_function_attributes lam loc attr = let lam = add_inline_attribute lam loc attr in let lam = add_specialise_attribute lam loc attr in let lam = add_local_attribute lam loc attr in let lam = add_check_attribute lam loc attr in let lam = add_loop_attribute lam loc attr in let lam = add_tmc_attribute lam loc attr in let lam = (* last because poll overrides inline and local *) add_poll_attribute lam loc attr in lam
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/a9268d29b47cd5c3c051e761f454330573f7ee0e/lambda/translattribute.ml
ocaml
************************************************************************ OCaml Pierre Chambart, OCamlPro en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ the 'unrolled' attributes must be used as [@unrolled n]. the 'unrolled' attributes must be used as [@unrolled n]. Get the [@inlined] attribute payload (or default if not present). last because poll overrides inline and local
Copyright 2015 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Typedtree open Lambda open Location let is_inline_attribute = [ ["inline"; "ocaml.inline"],true ] let is_inlined_attribute = [ ["inlined"; "ocaml.inlined"], true ; ["unrolled"; "ocaml.unrolled"], (Config.flambda || Config.flambda2) ] let is_specialise_attribute = [ ["specialise"; "ocaml.specialise"], Config.flambda ] let is_specialised_attribute = [ ["specialised"; "ocaml.specialised"], Config.flambda ] let is_local_attribute = [ ["local"; "ocaml.local"], true ] let is_tailcall_attribute = [ ["tailcall"; "ocaml.tailcall"], true ] let is_property_attribute = function | Noalloc -> [ ["noalloc"; "ocaml.noalloc"], true ] let is_tmc_attribute = [ ["tail_mod_cons"; "ocaml.tail_mod_cons"], true ] let is_poll_attribute = [ ["poll"; "ocaml.poll"], true ] let is_loop_attribute = [ ["loop"; "ocaml.loop"], true ] let find_attribute p attributes = let inline_attribute = Builtin_attributes.filter_attributes p attributes in let attr = match inline_attribute with | [] -> None | [attr] -> Some attr | attr :: {Parsetree.attr_name = {txt;loc}; _} :: _ -> Location.prerr_warning loc (Warnings.Duplicated_attribute txt); Some attr in attr let is_unrolled = function | {txt="unrolled"|"ocaml.unrolled"} -> true | {txt="inline"|"ocaml.inline"|"inlined"|"ocaml.inlined"} -> false | _ -> assert false let get_payload get_from_exp = let open Parsetree in function | PStr [{pstr_desc = Pstr_eval (exp, [])}] -> get_from_exp exp | _ -> Result.Error () let get_optional_payload get_from_exp = let open Parsetree in function | PStr [] -> Result.Ok None | other -> Result.map Option.some (get_payload get_from_exp other) let get_id_from_exp = let open Parsetree in function | { pexp_desc = Pexp_ident { txt = Longident.Lident id } } -> Result.Ok id | _ -> Result.Error () let get_int_from_exp = let open Parsetree in function | { pexp_desc = Pexp_constant (Pconst_integer(s, None)) } -> begin match Misc.Int_literal_converter.int s with | n -> Result.Ok n | exception (Failure _) -> Result.Error () end | _ -> Result.Error () let get_construct_from_exp = let open Parsetree in function | { pexp_desc = Pexp_construct ({ txt = Longident.Lident constr }, None) } -> Result.Ok constr | _ -> Result.Error () let get_bool_from_exp exp = Result.bind (get_construct_from_exp exp) (function | "true" -> Result.Ok true | "false" -> Result.Ok false | _ -> Result.Error ()) let parse_id_payload txt loc ~default ~empty cases payload = let[@local] warn () = let ( %> ) f g x = g (f x) in let msg = cases |> List.map (fst %> Printf.sprintf "'%s'") |> String.concat ", " |> Printf.sprintf "It must be either %s or empty" in Location.prerr_warning loc (Warnings.Attribute_payload (txt, msg)); default in match get_optional_payload get_id_from_exp payload with | Error () -> warn () | Ok None -> empty | Ok (Some id) -> match List.assoc_opt id cases with | Some r -> r | None -> warn () let parse_inline_attribute attr : inline_attribute = match attr with | None -> Default_inline | Some {Parsetree.attr_name = {txt;loc} as id; attr_payload = payload} -> if is_unrolled id then begin let warning txt = Warnings.Attribute_payload (txt, "It must be an integer literal") in match get_payload get_int_from_exp payload with | Ok n -> Unroll n | Error () -> Location.prerr_warning loc (warning txt); Default_inline end else parse_id_payload txt loc ~default:Default_inline ~empty:Always_inline [ "never", Never_inline; "always", Always_inline; "available", Available_inline; ] payload let parse_inlined_attribute attr : inlined_attribute = match attr with | None -> Default_inlined | Some {Parsetree.attr_name = {txt;loc} as id; attr_payload = payload} -> if is_unrolled id then begin let warning txt = Warnings.Attribute_payload (txt, "It must be an integer literal") in match get_payload get_int_from_exp payload with | Ok n -> Unroll n | Error () -> Location.prerr_warning loc (warning txt); Default_inlined end else parse_id_payload txt loc ~default:Default_inlined ~empty:Always_inlined [ "never", Never_inlined; "always", Always_inlined; "hint", Hint_inlined; ] payload let parse_specialise_attribute attr = match attr with | None -> Default_specialise | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_specialise ~empty:Always_specialise [ "never", Never_specialise; "always", Always_specialise; ] payload let parse_local_attribute attr = match attr with | None -> Default_local | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_local ~empty:Always_local [ "never", Never_local; "always", Always_local; "maybe", Default_local; ] payload let parse_property_attribute attr p = match attr with | None -> Default_check | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload}-> parse_id_payload txt loc ~default:Default_check ~empty:(Assert p) [ "assume", Assume p; ] payload let parse_poll_attribute attr = match attr with | None -> Default_poll | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_poll ~empty:Default_poll [ "error", Error_poll; ] payload let parse_loop_attribute attr = match attr with | None -> Default_loop | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> parse_id_payload txt loc ~default:Default_loop ~empty:Always_loop [ "never", Never_loop; "always", Always_loop; ] payload let get_inline_attribute l = let attr = find_attribute is_inline_attribute l in parse_inline_attribute attr let get_specialise_attribute l = let attr = find_attribute is_specialise_attribute l in parse_specialise_attribute attr let get_local_attribute l = let attr = find_attribute is_local_attribute l in parse_local_attribute attr let get_property_attribute l p = let attr = find_attribute (is_property_attribute p) l in parse_property_attribute attr p let get_check_attribute l = get_property_attribute l Noalloc let get_poll_attribute l = let attr = find_attribute is_poll_attribute l in parse_poll_attribute attr let get_loop_attribute l = let attr = find_attribute is_loop_attribute l in parse_loop_attribute attr let check_local_inline loc attr = match attr.local, attr.inline with | Always_local, (Always_inline | Available_inline | Unroll _) -> Location.prerr_warning loc (Warnings.Duplicated_attribute "local/inline") | _ -> () let check_poll_inline loc attr = match attr.poll, attr.inline with | Error_poll, (Always_inline | Available_inline | Unroll _) -> Location.prerr_warning loc (Warnings.Inlining_impossible "[@poll error] is incompatible with inlining") | _ -> () let check_poll_local loc attr = match attr.poll, attr.local with | Error_poll, Always_local -> Location.prerr_warning loc (Warnings.Inlining_impossible "[@poll error] is incompatible with local function optimization") | _ -> () let lfunction_with_attr ~attr { kind; params; return; body; attr=_; loc; mode; region } = lfunction ~kind ~params ~return ~body ~attr ~loc ~mode ~region let add_inline_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_inline_attribute attributes with | Default_inline -> expr | (Always_inline | Available_inline | Never_inline | Unroll _) as inline -> begin match attr.inline with | Default_inline -> () | Always_inline | Available_inline | Never_inline | Unroll _ -> Location.prerr_warning loc (Warnings.Duplicated_attribute "inline") end; let attr = { attr with inline } in check_local_inline loc attr; check_poll_inline loc attr; lfunction_with_attr ~attr funct end | _ -> expr let add_specialise_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_specialise_attribute attributes with | Default_specialise -> expr | (Always_specialise | Never_specialise) as specialise -> begin match attr.specialise with | Default_specialise -> () | Always_specialise | Never_specialise -> Location.prerr_warning loc (Warnings.Duplicated_attribute "specialise") end; let attr = { attr with specialise } in lfunction_with_attr ~attr funct end | _ -> expr let add_local_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_local_attribute attributes with | Default_local -> expr | (Always_local | Never_local) as local -> begin match attr.local with | Default_local -> () | Always_local | Never_local -> Location.prerr_warning loc (Warnings.Duplicated_attribute "local") end; let attr = { attr with local } in check_local_inline loc attr; check_poll_local loc attr; lfunction_with_attr ~attr funct end | _ -> expr let add_check_attribute expr loc attributes = let to_string = function | Noalloc -> "noalloc" in let to_string = function | Assert p -> to_string p | Assume p -> Printf.sprintf "%s assume" (to_string p) | Default_check -> assert false in match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_check_attribute attributes with | Default_check -> expr | (Assert _ | Assume _) as check -> begin match attr.check with | Default_check -> () | Assert Noalloc | Assume Noalloc -> Location.prerr_warning loc (Warnings.Duplicated_attribute (to_string check)) end; let attr = { attr with check } in lfunction_with_attr ~attr funct end | expr -> expr let add_loop_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_loop_attribute attributes with | Default_loop -> expr | (Always_loop | Never_loop) as loop -> begin match attr.loop with | Default_loop -> () | Always_loop | Never_loop -> Location.prerr_warning loc (Warnings.Duplicated_attribute "loop") end; let attr = { attr with loop } in lfunction_with_attr ~attr funct end | _ -> expr let add_tmc_attribute expr loc attributes = match expr with | Lfunction funct -> let attr = find_attribute is_tmc_attribute attributes in begin match attr with | None -> expr | Some _ -> if funct.attr.tmc_candidate then Location.prerr_warning loc (Warnings.Duplicated_attribute "tail_mod_cons"); let attr = { funct.attr with tmc_candidate = true } in lfunction_with_attr ~attr funct end | _ -> expr let add_poll_attribute expr loc attributes = match expr with | Lfunction({ attr = { stub = false } as attr } as funct) -> begin match get_poll_attribute attributes with | Default_poll -> expr | Error_poll as poll -> begin match attr.poll with | Default_poll -> () | Error_poll -> Location.prerr_warning loc (Warnings.Duplicated_attribute "error_poll") end; let attr = { attr with poll } in check_poll_inline loc attr; check_poll_local loc attr; let attr = { attr with inline = Never_inline; local = Never_local } in lfunction_with_attr ~attr funct end | expr -> expr let get_inlined_attribute e = let attr = find_attribute is_inlined_attribute e.exp_attributes in parse_inlined_attribute attr let get_inlined_attribute_on_module e = let rec get mod_expr = let attr = find_attribute is_inlined_attribute mod_expr.mod_attributes in let attr = parse_inlined_attribute attr in let attr = match mod_expr.Typedtree.mod_desc with | Tmod_constraint (me, _, _, _) -> let inner_attr = get me in begin match attr with | Always_inlined | Hint_inlined | Never_inlined | Unroll _ -> attr | Default_inlined -> inner_attr end | _ -> attr in attr in get e let get_specialised_attribute e = let attr = find_attribute is_specialised_attribute e.exp_attributes in parse_specialise_attribute attr let get_tailcall_attribute e = let attr = find_attribute is_tailcall_attribute e.exp_attributes in match attr with | None -> Default_tailcall | Some {Parsetree.attr_name = {txt; loc}; attr_payload = payload} -> match get_optional_payload get_bool_from_exp payload with | Ok (None | Some true) -> Tailcall_expectation true | Ok (Some false) -> Tailcall_expectation false | Error () -> let msg = "Only an optional boolean literal is supported." in Location.prerr_warning loc (Warnings.Attribute_payload (txt, msg)); Default_tailcall let add_function_attributes lam loc attr = let lam = add_inline_attribute lam loc attr in let lam = add_specialise_attribute lam loc attr in let lam = add_local_attribute lam loc attr in let lam = add_check_attribute lam loc attr in let lam = add_loop_attribute lam loc attr in let lam = add_tmc_attribute lam loc attr in let lam = add_poll_attribute lam loc attr in lam
8249c1043ef1af428a95b98fcbbd463f7ef1926f8570bec5b6690beeb5982726
nboldi/c-parser-in-haskell
RangeTree.hs
# LANGUAGE NamedFieldPuns # -- | A 2-Dimensional R-Tree for intervals module MiniC.RangeTree where import Text.Parsec.Pos import Text.Parsec.PosOps import MiniC.SourceNotation import MiniC.Representation import SourceCode.SourceTree import Control.Lens import Data.List import Data.Maybe import Debug.Trace -- | Trees of ranges in a hierarchical structure, with ranges and indices. data RangeTree = RangeTree { rtRange :: SourceRange , rtIndex :: RootIndex , rtChildren :: [RangeTree] } deriving (Eq) instance Show RangeTree where show = show' 0 where show' i (RangeTree rng ind children) = "\n" ++ replicate (4*i) '-' ++ shortShowRng rng ++ " <= " ++ show ind ++ concatMap (show' (i+1)) children -- | Generates a range tree from a source rose. Indexes the tree according to the -- hiearchy of nodes in the original tree. generateRangeTree :: RootIndex -> SourceRose BasicInfo -> [RangeTree] generateRangeTree ri (SourceRose inf original children) = (case (original, inf ^? biRange) of (True, Just rng) -> insertToRangeTree rng ri; _ -> id) $ foldl rangeTreeUnion [] (zipWith generateRangeTree (map (flip RootIndex ri) [0..]) children) | A tree of one element singletonRT :: SourceRange -> RootIndex -> RangeTree singletonRT sr ri = RangeTree sr ri [] -- Inserts a new node into a range tree insertToRangeTree :: SourceRange -> RootIndex -> [RangeTree] -> [RangeTree] insertToRangeTree sr ri ranges = let consumedIn = map (\rng -> if sr `rangeInside` rtRange rng && not (ri `rootPrefixOf` rtIndex rng) then Just (rng { rtChildren = insertToRangeTree sr ri (rtChildren rng) }) else Nothing ) ranges in case length $ filter isJust consumedIn of 1 -> zipWith fromMaybe ranges consumedIn 0 -> let (inside, outside) = partition (\rt -> rtRange rt `rangeInside` sr) ranges in (singletonRT sr ri) { rtChildren = inside } : outside _ -> error "insertToRangeTree: invalid RangeTree" | Creates the union of two range trees rangeTreeUnion :: [RangeTree] -> [RangeTree] -> [RangeTree] rangeTreeUnion (RangeTree rng ri children : rest) rt2 = rangeTreeUnion rest $ insertToRangeTree rng ri $ rangeTreeUnion children rt2 rangeTreeUnion [] rt2 = rt2 -- | Finds indices of nodes in the tree that are inside the given source range and -- satisfy the given predicate. findContainedWhere :: (SourceRange -> RootIndex -> Bool) -> SourceRange -> [RangeTree] -> [RootIndex] findContainedWhere pred sr (RangeTree rng ind _ : more) | rng `rangeInside` sr && pred rng ind = ind : findContainedWhere pred sr more findContainedWhere pred sr (tree : more) | rtRange tree `rangeOverlaps` sr = findContainedWhere pred sr (rtChildren tree) ++ findContainedWhere pred sr more findContainedWhere pred sr (_ : more) = findContainedWhere pred sr more findContainedWhere _ sr [] = []
null
https://raw.githubusercontent.com/nboldi/c-parser-in-haskell/1a92132e7d1b984cf93ec89d6836cc804257b57d/MiniC/RangeTree.hs
haskell
| A 2-Dimensional R-Tree for intervals | Trees of ranges in a hierarchical structure, with ranges and indices. | Generates a range tree from a source rose. Indexes the tree according to the hiearchy of nodes in the original tree. Inserts a new node into a range tree | Finds indices of nodes in the tree that are inside the given source range and satisfy the given predicate.
# LANGUAGE NamedFieldPuns # module MiniC.RangeTree where import Text.Parsec.Pos import Text.Parsec.PosOps import MiniC.SourceNotation import MiniC.Representation import SourceCode.SourceTree import Control.Lens import Data.List import Data.Maybe import Debug.Trace data RangeTree = RangeTree { rtRange :: SourceRange , rtIndex :: RootIndex , rtChildren :: [RangeTree] } deriving (Eq) instance Show RangeTree where show = show' 0 where show' i (RangeTree rng ind children) = "\n" ++ replicate (4*i) '-' ++ shortShowRng rng ++ " <= " ++ show ind ++ concatMap (show' (i+1)) children generateRangeTree :: RootIndex -> SourceRose BasicInfo -> [RangeTree] generateRangeTree ri (SourceRose inf original children) = (case (original, inf ^? biRange) of (True, Just rng) -> insertToRangeTree rng ri; _ -> id) $ foldl rangeTreeUnion [] (zipWith generateRangeTree (map (flip RootIndex ri) [0..]) children) | A tree of one element singletonRT :: SourceRange -> RootIndex -> RangeTree singletonRT sr ri = RangeTree sr ri [] insertToRangeTree :: SourceRange -> RootIndex -> [RangeTree] -> [RangeTree] insertToRangeTree sr ri ranges = let consumedIn = map (\rng -> if sr `rangeInside` rtRange rng && not (ri `rootPrefixOf` rtIndex rng) then Just (rng { rtChildren = insertToRangeTree sr ri (rtChildren rng) }) else Nothing ) ranges in case length $ filter isJust consumedIn of 1 -> zipWith fromMaybe ranges consumedIn 0 -> let (inside, outside) = partition (\rt -> rtRange rt `rangeInside` sr) ranges in (singletonRT sr ri) { rtChildren = inside } : outside _ -> error "insertToRangeTree: invalid RangeTree" | Creates the union of two range trees rangeTreeUnion :: [RangeTree] -> [RangeTree] -> [RangeTree] rangeTreeUnion (RangeTree rng ri children : rest) rt2 = rangeTreeUnion rest $ insertToRangeTree rng ri $ rangeTreeUnion children rt2 rangeTreeUnion [] rt2 = rt2 findContainedWhere :: (SourceRange -> RootIndex -> Bool) -> SourceRange -> [RangeTree] -> [RootIndex] findContainedWhere pred sr (RangeTree rng ind _ : more) | rng `rangeInside` sr && pred rng ind = ind : findContainedWhere pred sr more findContainedWhere pred sr (tree : more) | rtRange tree `rangeOverlaps` sr = findContainedWhere pred sr (rtChildren tree) ++ findContainedWhere pred sr more findContainedWhere pred sr (_ : more) = findContainedWhere pred sr more findContainedWhere _ sr [] = []
07aed5281da718e718b8315a6a340e514a273bec5621e3585ff0b9be0a496f39
synrc/nitro
element_password.erl
-module(element_password). -author('Vladimir Galunshchikov'). -include_lib("nitro/include/nitro.hrl"). -include_lib("nitro/include/event.hrl"). -compile(export_all). render_element(Record) when Record#password.show_if==false -> [<<>>]; render_element(Record) -> Id = case Record#password.postback of [] -> Record#password.id; Postback -> ID = case Record#password.id of [] -> nitro:temp_id(); I -> I end, nitro:wire(#event{type=click, postback=Postback, target=ID, source=Record#password.source, delegate=Record#password.delegate }), ID end, List = [ %global {<<"accesskey">>, Record#password.accesskey}, {<<"class">>, Record#password.class}, {<<"contenteditable">>, case Record#password.contenteditable of true -> "true"; false -> "false"; _ -> [] end}, {<<"contextmenu">>, Record#password.contextmenu}, {<<"dir">>, case Record#password.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end}, {<<"draggable">>, case Record#password.draggable of true -> "true"; false -> "false"; _ -> [] end}, {<<"dropzone">>, Record#password.dropzone}, {<<"hidden">>, case Record#password.hidden of "hidden" -> "hidden"; _ -> [] end}, {<<"id">>, Id}, {<<"lang">>, Record#password.lang}, {<<"spellcheck">>, case Record#password.spellcheck of true -> "true"; false -> "false"; _ -> [] end}, {<<"style">>, Record#password.style}, {<<"tabindex">>, Record#password.tabindex}, {<<"title">>, Record#password.title}, {<<"translate">>, case Record#password.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end}, % spec {<<"autocomplete">>, case Record#password.autocomplete of true -> "on"; false -> "off"; _ -> [] end}, {<<"autofocus">>,if Record#password.autofocus == true -> "autofocus"; true -> [] end}, {<<"disabled">>, if Record#password.disabled == true -> "disabled"; true -> [] end}, {<<"form">>,Record#password.form}, {<<"maxlength">>,Record#password.maxlength}, {<<"name">>,Record#password.name}, {<<"pattern">>,Record#password.pattern}, {<<"placeholder">>, Record#password.placeholder}, {<<"readonly">>,if Record#password.readonly == true -> "readonly"; true -> [] end}, {<<"required">>,if Record#password.required == true -> "required"; true -> [] end}, {<<"size">>,Record#password.size}, {<<"type">>, <<"password">>}, {<<"value">>, Record#password.value} | Record#password.data_fields ], wf_tags:emit_tag(<<"input">>, nitro:render(Record#password.body), List).
null
https://raw.githubusercontent.com/synrc/nitro/753b543626add2c014584546ec50870808a2eb90/src/elements/input/element_password.erl
erlang
global spec
-module(element_password). -author('Vladimir Galunshchikov'). -include_lib("nitro/include/nitro.hrl"). -include_lib("nitro/include/event.hrl"). -compile(export_all). render_element(Record) when Record#password.show_if==false -> [<<>>]; render_element(Record) -> Id = case Record#password.postback of [] -> Record#password.id; Postback -> ID = case Record#password.id of [] -> nitro:temp_id(); I -> I end, nitro:wire(#event{type=click, postback=Postback, target=ID, source=Record#password.source, delegate=Record#password.delegate }), ID end, List = [ {<<"accesskey">>, Record#password.accesskey}, {<<"class">>, Record#password.class}, {<<"contenteditable">>, case Record#password.contenteditable of true -> "true"; false -> "false"; _ -> [] end}, {<<"contextmenu">>, Record#password.contextmenu}, {<<"dir">>, case Record#password.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end}, {<<"draggable">>, case Record#password.draggable of true -> "true"; false -> "false"; _ -> [] end}, {<<"dropzone">>, Record#password.dropzone}, {<<"hidden">>, case Record#password.hidden of "hidden" -> "hidden"; _ -> [] end}, {<<"id">>, Id}, {<<"lang">>, Record#password.lang}, {<<"spellcheck">>, case Record#password.spellcheck of true -> "true"; false -> "false"; _ -> [] end}, {<<"style">>, Record#password.style}, {<<"tabindex">>, Record#password.tabindex}, {<<"title">>, Record#password.title}, {<<"translate">>, case Record#password.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end}, {<<"autocomplete">>, case Record#password.autocomplete of true -> "on"; false -> "off"; _ -> [] end}, {<<"autofocus">>,if Record#password.autofocus == true -> "autofocus"; true -> [] end}, {<<"disabled">>, if Record#password.disabled == true -> "disabled"; true -> [] end}, {<<"form">>,Record#password.form}, {<<"maxlength">>,Record#password.maxlength}, {<<"name">>,Record#password.name}, {<<"pattern">>,Record#password.pattern}, {<<"placeholder">>, Record#password.placeholder}, {<<"readonly">>,if Record#password.readonly == true -> "readonly"; true -> [] end}, {<<"required">>,if Record#password.required == true -> "required"; true -> [] end}, {<<"size">>,Record#password.size}, {<<"type">>, <<"password">>}, {<<"value">>, Record#password.value} | Record#password.data_fields ], wf_tags:emit_tag(<<"input">>, nitro:render(Record#password.body), List).
97a38d93520be10f6962299d06f23f69f219fbc3a606bb059d1c1484b707f827
vseloved/cl-agraph
triple.lisp
CL - AGRAPH triple definition and parsing / serialization ( c ) Vsevolod Dyomkin . see LICENSE file for permissions (in-package :agraph) (named-readtables:in-readtable rutils-readtable) ;;; URIs & blank nodes (defvar *prefixes* (let ((prefixes (make-hash-table :test 'equal))) (loop :for (prefix uri) :in '(("rdf" "-rdf-syntax-ns#") ("rdfs" "-schema#") ("owl" "#") ("xsd" "#") ("xs" "#") ("fn" "-functions#") ("err" "-errors#")) :do (set# prefix prefixes uri)) prefixes) "Default uri prefixes.") (defun register-prefix (prefix uri) "Register the mapping of PREFIX to URL for use in the function URI." (set# prefix *prefixes* uri)) (defun clear-prefix (prefix) "Unregister the mapping of PREFIX used in the function URI." (rem# prefix *prefixes*)) (defstruct (uri (:print-object (lambda (uri out) (format out "<~A>" (uri-name uri))))) name) (defvar *uris* (make-hash-table :test 'equal) "The cache of processed uris.") (defun uri (name) "Try to expand NAME using registered uri prefixes. Then create a URI object from it and return it. Also, cache the object in *URIS*." (dotable (prefix uri *prefixes*) (when (starts-with (strcat prefix ":") name) (:= name (strcat uri (slice name (1+ (length prefix))))) (return))) (getset# name *uris* (make-uri :name name))) (defstruct (blank-node (:print-object (lambda (bn out) (format out "_:~A" (blank-node-name bn))))) (name (symbol-name (gensym "bn")))) (progn (defvar *blank-nodes-repo* #h(equalp nil #h(equal)) "Blank-node caches by repo.") (defvar *blank-nodes* (? *blank-nodes-repo* nil) "The current blank-node cache.")) (defun blank-node (name) "Get the blank-node for NAME from the cache or add it there." (getset# name *blank-nodes* (make-blank-node :name name))) ;;; triples (defstruct (triple (:conc-name nil) (:print-object print-triple)) s p o g obj-lang obj-type) (defun print-triple (tr &optional out) (format out "~A ~A ~A~@[~A~]~@[ ~A~] ." (s tr) (p tr) (typecase (o tr) (string (fmt "~S" (o tr))) (otherwise (o tr))) (cond-it ((obj-type tr) (fmt "^^~A" it)) ((obj-lang tr) (fmt "@~A" it))) (g tr))) (defun ensure-subj (x) (etypecase x ((or uri blank-node) x) (string (uri x)))) (defun ensure-pred (x) (etypecase x (uri x) (blank-node (if *strict-mode* (error 'type-error :datum x :expected-type '(or uri string)) x)) (string (uri x)))) (defun ensure-obj (x &key lang type) (declare (ignore lang type)) (etypecase x ((or uri blank-node string number boolean) x))) (defun ensure-graph (x) (etypecase x ((or uri blank-node) x) (string (uri x)))) (defun <> (s p o &key g lang type) "" (make-triple :s (when s (ensure-subj s)) :p (when p (ensure-pred p)) :o (when o (ensure-obj o :lang lang :type type)) :g (when g (ensure-graph g)) :obj-lang lang :obj-type type)) ;;; utils (defun uri-or-blank-node (x) (if (stringp x) (uri x) (blank-node (second x)))) (defun triple-from-list (list) (with (((s p o &optional g) list) (lang nil) (type nil)) (make-triple :s (uri-or-blank-node s) :p (uri-or-blank-node p) :o (case (atomize o) (:uri (uri (second o))) (:bn (blank-node (second o))) (:literal-string (prog1 (second o) (when-it (getf o :lang) (:= lang it)) (when-it (getf o :uriref) (:= type (uri it))))) (t (uri o))) :g (when g (uri-or-blank-node g)) :obj-lang lang :obj-type type))) ;;; nquads (defparameter *strict-mode* nil "Parse according to the spec. Non-strict mode allows: - blank-nodes in predicates") (in-package :cl-ntriples) (defun parse-nq (stream) (list* ;; subject ::= uriref | nodeID (progn (consume-whitespace stream) (case (peek-char t stream) (#\< (parse-uriref stream)) (#\_ (list :bn (parse-node-id stream))) (otherwise (error "wrong char `~a' while parsing subject~%" (peek-char t stream))))) ;; predicate ::= uriref | nodeID (progn (consume-whitespace stream) (case (peek-char t stream) (#\< (parse-uriref stream)) (#\_ (if agraph::*strict-mode* (error "wrong char `_' while parsing subject~%") (list :bn (parse-node-id stream)))) (otherwise (error "wrong char `~a' while parsing subject~%" (peek-char t stream))))) object : : = uriref | nodeID | literal (progn (consume-whitespace stream) (case (peek-char t stream) (#\< (parse-uriref stream)) (#\_ (list :bn (parse-node-id stream))) (#\" (parse-literal stream)) (otherwise (error "wrong character `~a' in while parsing object~%" (peek-char t stream))))) ;; graph ::= uriref | nodeID (progn (consume-whitespace stream) (flet ((consume-dot-after (graph) (consume-whitespace stream) (case (peek-char t stream) (#\. (read-char stream) (consume-whitespace stream)) (otherwise (error "wrong char `~a' while parsing dot~%" (peek-char t stream)))) (list graph))) (case (peek-char t stream) (#\< (consume-dot-after (parse-uriref stream))) (#\_ (consume-dot-after (list :bn (parse-node-id stream)))) (#\. (read-char stream) nil) (otherwise (error "wrong char `~a' while parsing optional graph~%" (peek-char t stream)))))))) (defun agraph::parse-nq-line (stream) ;; consume white space if there is any at the start of a line (loop :for c = (peek-char t stream nil) :unless c :do (return-from agraph::parse-nq-line nil) :while (ntriple-ws-p c) :do (read-char stream)) ;; check if this line is a comment or a triple (if (char= #\# (peek-char t stream)) (progn ; consume comment line (loop :for c = (read-char stream nil) :unless c :do (return-from agraph::parse-nq-line 'comment) :until (ntriple-crlf-p c)) (when (and (peek-char t stream nil) (ntriple-crlf-p (peek-char t stream))) (read-char stream nil)) 'comment) (parse-nq stream))) (defun agraph::parse-nq-doc (stream) (loop :while (peek-char t stream nil) :for line := (agraph::parse-nq-line stream) :while line :unless (eql line 'comment) :collect line))
null
https://raw.githubusercontent.com/vseloved/cl-agraph/e605b34fa57a9ede6fb6cc13ef82fc3438898567/src/triple.lisp
lisp
URIs & blank nodes triples utils nquads subject ::= uriref | nodeID predicate ::= uriref | nodeID graph ::= uriref | nodeID consume white space if there is any at the start of a line check if this line is a comment or a triple consume comment line
CL - AGRAPH triple definition and parsing / serialization ( c ) Vsevolod Dyomkin . see LICENSE file for permissions (in-package :agraph) (named-readtables:in-readtable rutils-readtable) (defvar *prefixes* (let ((prefixes (make-hash-table :test 'equal))) (loop :for (prefix uri) :in '(("rdf" "-rdf-syntax-ns#") ("rdfs" "-schema#") ("owl" "#") ("xsd" "#") ("xs" "#") ("fn" "-functions#") ("err" "-errors#")) :do (set# prefix prefixes uri)) prefixes) "Default uri prefixes.") (defun register-prefix (prefix uri) "Register the mapping of PREFIX to URL for use in the function URI." (set# prefix *prefixes* uri)) (defun clear-prefix (prefix) "Unregister the mapping of PREFIX used in the function URI." (rem# prefix *prefixes*)) (defstruct (uri (:print-object (lambda (uri out) (format out "<~A>" (uri-name uri))))) name) (defvar *uris* (make-hash-table :test 'equal) "The cache of processed uris.") (defun uri (name) "Try to expand NAME using registered uri prefixes. Then create a URI object from it and return it. Also, cache the object in *URIS*." (dotable (prefix uri *prefixes*) (when (starts-with (strcat prefix ":") name) (:= name (strcat uri (slice name (1+ (length prefix))))) (return))) (getset# name *uris* (make-uri :name name))) (defstruct (blank-node (:print-object (lambda (bn out) (format out "_:~A" (blank-node-name bn))))) (name (symbol-name (gensym "bn")))) (progn (defvar *blank-nodes-repo* #h(equalp nil #h(equal)) "Blank-node caches by repo.") (defvar *blank-nodes* (? *blank-nodes-repo* nil) "The current blank-node cache.")) (defun blank-node (name) "Get the blank-node for NAME from the cache or add it there." (getset# name *blank-nodes* (make-blank-node :name name))) (defstruct (triple (:conc-name nil) (:print-object print-triple)) s p o g obj-lang obj-type) (defun print-triple (tr &optional out) (format out "~A ~A ~A~@[~A~]~@[ ~A~] ." (s tr) (p tr) (typecase (o tr) (string (fmt "~S" (o tr))) (otherwise (o tr))) (cond-it ((obj-type tr) (fmt "^^~A" it)) ((obj-lang tr) (fmt "@~A" it))) (g tr))) (defun ensure-subj (x) (etypecase x ((or uri blank-node) x) (string (uri x)))) (defun ensure-pred (x) (etypecase x (uri x) (blank-node (if *strict-mode* (error 'type-error :datum x :expected-type '(or uri string)) x)) (string (uri x)))) (defun ensure-obj (x &key lang type) (declare (ignore lang type)) (etypecase x ((or uri blank-node string number boolean) x))) (defun ensure-graph (x) (etypecase x ((or uri blank-node) x) (string (uri x)))) (defun <> (s p o &key g lang type) "" (make-triple :s (when s (ensure-subj s)) :p (when p (ensure-pred p)) :o (when o (ensure-obj o :lang lang :type type)) :g (when g (ensure-graph g)) :obj-lang lang :obj-type type)) (defun uri-or-blank-node (x) (if (stringp x) (uri x) (blank-node (second x)))) (defun triple-from-list (list) (with (((s p o &optional g) list) (lang nil) (type nil)) (make-triple :s (uri-or-blank-node s) :p (uri-or-blank-node p) :o (case (atomize o) (:uri (uri (second o))) (:bn (blank-node (second o))) (:literal-string (prog1 (second o) (when-it (getf o :lang) (:= lang it)) (when-it (getf o :uriref) (:= type (uri it))))) (t (uri o))) :g (when g (uri-or-blank-node g)) :obj-lang lang :obj-type type))) (defparameter *strict-mode* nil "Parse according to the spec. Non-strict mode allows: - blank-nodes in predicates") (in-package :cl-ntriples) (defun parse-nq (stream) (progn (consume-whitespace stream) (case (peek-char t stream) (#\< (parse-uriref stream)) (#\_ (list :bn (parse-node-id stream))) (otherwise (error "wrong char `~a' while parsing subject~%" (peek-char t stream))))) (progn (consume-whitespace stream) (case (peek-char t stream) (#\< (parse-uriref stream)) (#\_ (if agraph::*strict-mode* (error "wrong char `_' while parsing subject~%") (list :bn (parse-node-id stream)))) (otherwise (error "wrong char `~a' while parsing subject~%" (peek-char t stream))))) object : : = uriref | nodeID | literal (progn (consume-whitespace stream) (case (peek-char t stream) (#\< (parse-uriref stream)) (#\_ (list :bn (parse-node-id stream))) (#\" (parse-literal stream)) (otherwise (error "wrong character `~a' in while parsing object~%" (peek-char t stream))))) (progn (consume-whitespace stream) (flet ((consume-dot-after (graph) (consume-whitespace stream) (case (peek-char t stream) (#\. (read-char stream) (consume-whitespace stream)) (otherwise (error "wrong char `~a' while parsing dot~%" (peek-char t stream)))) (list graph))) (case (peek-char t stream) (#\< (consume-dot-after (parse-uriref stream))) (#\_ (consume-dot-after (list :bn (parse-node-id stream)))) (#\. (read-char stream) nil) (otherwise (error "wrong char `~a' while parsing optional graph~%" (peek-char t stream)))))))) (defun agraph::parse-nq-line (stream) (loop :for c = (peek-char t stream nil) :unless c :do (return-from agraph::parse-nq-line nil) :while (ntriple-ws-p c) :do (read-char stream)) (if (char= #\# (peek-char t stream)) (loop :for c = (read-char stream nil) :unless c :do (return-from agraph::parse-nq-line 'comment) :until (ntriple-crlf-p c)) (when (and (peek-char t stream nil) (ntriple-crlf-p (peek-char t stream))) (read-char stream nil)) 'comment) (parse-nq stream))) (defun agraph::parse-nq-doc (stream) (loop :while (peek-char t stream nil) :for line := (agraph::parse-nq-line stream) :while line :unless (eql line 'comment) :collect line))
7f104b20dfc7b0929bbcc1a3fc5e9bf43b7451f281aef4ed13fba53221bc09b7
williamleferrand/aws
sDB_factory.ml
SDB API (* *) module Make = functor (HC : Aws_sigs.HTTP_CLIENT) -> struct module C = CalendarLib.Calendar module P = CalendarLib.Printer.CalendarPrinter module X = My_xml open Lwt open Creds module Util = Aws_util exception Error of string let sprint = Printf.sprintf let print = Printf.printf let signed_request ?region ?(http_method=`POST) ?(http_uri="/") ?expires_minutes ?(safe=false) creds params = let http_host = match region with | Some r -> sprint "sdb.%s.amazonaws.com" r | None -> "sdb.amazonaws.com" in let params = ("Version", "2009-04-15" ) :: ("SignatureVersion", "2") :: ("SignatureMethod", "HmacSHA1") :: ("AWSAccessKeyId", creds.aws_access_key_id) :: params in let params = match expires_minutes with | Some i -> ("Expires", Util.minutes_from_now i) :: params | None -> ("Timestamp", Util.now_as_string ()) :: params in let signature = let sorted_params = Util.sort_assoc_list params in let key_equals_value = Util.encode_key_equals_value ~safe sorted_params in let uri_query_component = String.concat "&" key_equals_value in let string_to_sign = String.concat "\n" [ Util.string_of_t http_method ; String.lowercase http_host ; http_uri ; uri_query_component ] in let hmac_sha1_encoder = Cryptokit.MAC.hmac_sha1 creds.aws_secret_access_key in let signed_string = Cryptokit.hash_string hmac_sha1_encoder string_to_sign in Util.base64 signed_string in let params = ("Signature", signature) :: params in (http_host ^ http_uri), params (* XML readers *) let error_msg code' body = match X.xml_of_string body with | X.E ("Response",_, ( X.E ("Errors",_, [ X.E ("Error",_,[ X.E ("Code",_,[X.P code]); X.E ("Message",_,[X.P message]); _ ] ) ] ) ) :: _ ) -> `Error (code, message) | _ -> `Error ("unknown", body) let b64dec_if encoded s = if encoded then Util.base64_decoder s else s let b64enc_if encode s = if encode then Util.base64 s else s let domain_or_next_of_xml = function | X.E ("DomainName", _, [ X.P domain_name ]) -> `D domain_name | X.E ("NextToken", _, [ X.P next_token ]) -> `N next_token | _ -> raise (Error "ListDomainsResult.domain") let list_domains_response_of_xml = function | X.E ("ListDomainsResponse", _, [ X.E ("ListDomainsResult", _, domain_or_next_list ); _ ]) -> let domain_names, next_tokens = List.fold_left ( fun (domain_names, next_tokens) domain_or_next_xml -> match domain_or_next_of_xml domain_or_next_xml with | `D domain_name -> domain_name :: domain_names, next_tokens | `N next_token -> domain_names, next_token :: next_tokens ) ([],[]) domain_or_next_list in (* preseve the order of domains in response *) let domain_names = List.rev domain_names in domain_names, check that we have no more than one NextToken (match next_tokens with | [next_token] -> Some next_token | [] -> None | _ -> raise (Error "ListDomainsResponse: more than one NextToken") ) | _ -> raise (Error "ListDomainsResult") let attributes_of_xml encoded = function | X.E ("Attribute", _, [ X.E ("Name", _, [ X.P name ]); X.E ("Value", _, [ X.P value ]); ]) -> b64dec_if encoded name, Some (b64dec_if encoded value) | X.E ("Attribute", _, [ X.E ("Name", _, [ X.P name ]); X.E ("Value", _, [ ]); ]) -> b64dec_if encoded name, None | _ -> raise (Error "Attribute 1") let get_attributes_response_of_xml encoded = function | X.E ("GetAttributesResponse", _, [ X.E ("GetAttributesResult", _, attributes); _; ]) -> List.map (attributes_of_xml encoded) attributes | _ -> raise (Error "GetAttributesResponse") let attrs_of_xml encoded = function | X.E ("Attribute", _ , children) -> ( match children with | [ X.E ("Name", _, [ X.P name ]) ; X.E ("Value", _, [ X.P value ]) ; ] -> b64dec_if encoded name, Some (b64dec_if encoded value) | [ X.E ("Name", _, [ X.P name ]) ; X.E ("Value", _, [ ]) ; ] -> b64dec_if encoded name, None | l -> raise (Error (sprint "fat list %d" (List.length l))) ) | _ -> raise (Error "Attribute 3") let rec item_of_xml encoded acc token = function | [] -> (acc, token) | X.E ("Item", _, (X.E ("Name", _, [ X.P name ]) :: attrs)) :: nxt -> let a = List.map (attrs_of_xml encoded) attrs in item_of_xml encoded (((b64dec_if encoded name), a) :: acc) token nxt | X.E ("NextToken", _, [ X.P next_token ]) :: _ -> acc, (Some next_token) | _ -> raise (Error "Item") let select_of_xml encoded = function | X.E ("SelectResponse", _, [ X.E ("SelectResult", _, items); _ ; ]) -> item_of_xml encoded [] None items | _ -> raise (Error "SelectResponse") (* list all domains *) let list_domains creds ?token () = let url, params = signed_request creds (("Action", "ListDomains") :: match token with None -> [] | Some t -> [ "NextToken", t ]) in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in let xml = X.xml_of_string body in return (`Ok (list_domains_response_of_xml xml)) with HC.Http_error (code, _, body) -> return (error_msg code body) (* create domain *) let create_domain creds name = let url, params = signed_request creds [ "Action", "CreateDomain" ; "DomainName", name ] in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) (* delete domain *) let delete_domain creds name = let url, params = signed_request creds [ "Action", "DeleteDomain" ; "DomainName", name ] in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) (* put attributes *) let put_attributes ?(replace=false) ?(encode=true) creds ~domain ~item attrs = let _, attrs' = List.fold_left ( fun (i, acc) (name, value_opt) -> let value_s = match value_opt with | Some value -> b64enc_if encode value | None -> "" in let value_p = sprint "Attribute.%d.Value" i, value_s in let name_p = sprint "Attribute.%d.Name" i, b64enc_if encode name in let acc = name_p :: value_p :: ( if replace then (sprint "Attribute.%d.Replace" i, "true") :: acc else acc ) in i+1, acc ) (1, []) attrs in let url, params = signed_request creds (("Action", "PutAttributes") :: ("DomainName", domain) :: ("ItemName", b64enc_if encode item) :: attrs') in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) (* batch put attributes *) let batch_put_attributes ?(replace=false) ?(encode=true) creds domain items = let _, attrs' = List.fold_left (fun (i, acc) (item_name, attrs) -> let item_name_p = sprint "Item.%d.ItemName" i, b64enc_if encode item_name in let _, acc = List.fold_left ( fun (j, acc) (name, value_opt) -> let name_p = sprint "Item.%d.Attribute.%d.Name" i j, b64enc_if encode name in let value_s = match value_opt with | Some value -> b64enc_if encode value | None -> "" in let value_p = sprint "Item.%d.Attribute.%d.Value" i j, value_s in let acc' = name_p :: value_p :: if replace then (sprint "Item.%d.Attribute.%d.Replace" i j, "true") :: acc else acc in j+1, acc' ) (1, item_name_p :: acc) attrs in i+1, acc ) (1, []) items in let url, params = signed_request creds (("Action", "BatchPutAttributes") :: ("DomainName", domain) :: attrs') in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) (* get attributes *) let get_attributes ?(encoded=true) creds ~domain ?attribute ~item () = let attribute_name_p = match attribute with | None -> [] | Some attribute_name -> [ "AttributeName", (b64enc_if encoded attribute_name) ] in let url, params = signed_request creds ( ("Action", "GetAttributes") :: ("DomainName", domain) :: ("ItemName", b64enc_if encoded item) :: attribute_name_p ) in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in let xml = X.xml_of_string body in return (`Ok (get_attributes_response_of_xml encoded xml)) with HC.Http_error (code, _, body) -> return (error_msg code body) (* delete attributes *) let delete_attributes ?(encode=true) creds ~domain ~item attrs = let _, attrs' = List.fold_left ( fun (i, acc) (name, value) -> let name_p = sprint "Attribute.%d.Name" i, b64enc_if encode name in let value_p = sprint "Attribute.%d.Value" i, b64enc_if encode value in i+1, name_p :: value_p :: acc ) (0,[]) attrs in let url, params = signed_request creds (("Action", "DeleteAttributes") :: ("DomainName", domain) :: ("ItemName", b64enc_if encode item) :: attrs') in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) (* select: TODO if [encode=true], encode references to values in the select [expression]. This might not be easy, as the [expression] will have to be deconstructed (parsed). Alternatively, [expression] is replaced with an expression type, which would make value substitutions easier. Neither would work for numerical constraints. *) let select ?(consistent=false) ?(encoded=true) ?(token=None) creds expression = let url, params = signed_request ~safe:true creds (("Action", "Select") :: ("SelectExpression", expression) :: ("ConsistentRead", sprint "%B" consistent) :: (match token with | None -> [] | Some t -> [ "NextToken", t ])) in try_lwt let key_equals_value = Util.encode_key_equals_value ~safe:true params in let uri_query_component = String.concat "&" key_equals_value in lwt header, body = HC.post ~body:(`String uri_query_component) url in let xml = X.xml_of_string body in return (`Ok (select_of_xml encoded xml)) with HC.Http_error (code, _, body) -> return (error_msg code body) (* select all records where attribute [name] equals [value] *) let select_where_attribute_equals ?(consistent=false) ?(encoded=true) ?(token=None) creds ~domain ~name ~value = let expression = sprint "select * from `%s` where `%s` = %S" domain (b64enc_if encoded name) (b64enc_if encoded value) in select ~consistent ~encoded ~token creds expression end
null
https://raw.githubusercontent.com/williamleferrand/aws/d591ef0a2b89082caac6ddd6850b2d8b7824e577/src/sDB_factory.ml
ocaml
XML readers preseve the order of domains in response list all domains create domain delete domain put attributes batch put attributes get attributes delete attributes select: TODO if [encode=true], encode references to values in the select [expression]. This might not be easy, as the [expression] will have to be deconstructed (parsed). Alternatively, [expression] is replaced with an expression type, which would make value substitutions easier. Neither would work for numerical constraints. select all records where attribute [name] equals [value]
SDB API module Make = functor (HC : Aws_sigs.HTTP_CLIENT) -> struct module C = CalendarLib.Calendar module P = CalendarLib.Printer.CalendarPrinter module X = My_xml open Lwt open Creds module Util = Aws_util exception Error of string let sprint = Printf.sprintf let print = Printf.printf let signed_request ?region ?(http_method=`POST) ?(http_uri="/") ?expires_minutes ?(safe=false) creds params = let http_host = match region with | Some r -> sprint "sdb.%s.amazonaws.com" r | None -> "sdb.amazonaws.com" in let params = ("Version", "2009-04-15" ) :: ("SignatureVersion", "2") :: ("SignatureMethod", "HmacSHA1") :: ("AWSAccessKeyId", creds.aws_access_key_id) :: params in let params = match expires_minutes with | Some i -> ("Expires", Util.minutes_from_now i) :: params | None -> ("Timestamp", Util.now_as_string ()) :: params in let signature = let sorted_params = Util.sort_assoc_list params in let key_equals_value = Util.encode_key_equals_value ~safe sorted_params in let uri_query_component = String.concat "&" key_equals_value in let string_to_sign = String.concat "\n" [ Util.string_of_t http_method ; String.lowercase http_host ; http_uri ; uri_query_component ] in let hmac_sha1_encoder = Cryptokit.MAC.hmac_sha1 creds.aws_secret_access_key in let signed_string = Cryptokit.hash_string hmac_sha1_encoder string_to_sign in Util.base64 signed_string in let params = ("Signature", signature) :: params in (http_host ^ http_uri), params let error_msg code' body = match X.xml_of_string body with | X.E ("Response",_, ( X.E ("Errors",_, [ X.E ("Error",_,[ X.E ("Code",_,[X.P code]); X.E ("Message",_,[X.P message]); _ ] ) ] ) ) :: _ ) -> `Error (code, message) | _ -> `Error ("unknown", body) let b64dec_if encoded s = if encoded then Util.base64_decoder s else s let b64enc_if encode s = if encode then Util.base64 s else s let domain_or_next_of_xml = function | X.E ("DomainName", _, [ X.P domain_name ]) -> `D domain_name | X.E ("NextToken", _, [ X.P next_token ]) -> `N next_token | _ -> raise (Error "ListDomainsResult.domain") let list_domains_response_of_xml = function | X.E ("ListDomainsResponse", _, [ X.E ("ListDomainsResult", _, domain_or_next_list ); _ ]) -> let domain_names, next_tokens = List.fold_left ( fun (domain_names, next_tokens) domain_or_next_xml -> match domain_or_next_of_xml domain_or_next_xml with | `D domain_name -> domain_name :: domain_names, next_tokens | `N next_token -> domain_names, next_token :: next_tokens ) ([],[]) domain_or_next_list in let domain_names = List.rev domain_names in domain_names, check that we have no more than one NextToken (match next_tokens with | [next_token] -> Some next_token | [] -> None | _ -> raise (Error "ListDomainsResponse: more than one NextToken") ) | _ -> raise (Error "ListDomainsResult") let attributes_of_xml encoded = function | X.E ("Attribute", _, [ X.E ("Name", _, [ X.P name ]); X.E ("Value", _, [ X.P value ]); ]) -> b64dec_if encoded name, Some (b64dec_if encoded value) | X.E ("Attribute", _, [ X.E ("Name", _, [ X.P name ]); X.E ("Value", _, [ ]); ]) -> b64dec_if encoded name, None | _ -> raise (Error "Attribute 1") let get_attributes_response_of_xml encoded = function | X.E ("GetAttributesResponse", _, [ X.E ("GetAttributesResult", _, attributes); _; ]) -> List.map (attributes_of_xml encoded) attributes | _ -> raise (Error "GetAttributesResponse") let attrs_of_xml encoded = function | X.E ("Attribute", _ , children) -> ( match children with | [ X.E ("Name", _, [ X.P name ]) ; X.E ("Value", _, [ X.P value ]) ; ] -> b64dec_if encoded name, Some (b64dec_if encoded value) | [ X.E ("Name", _, [ X.P name ]) ; X.E ("Value", _, [ ]) ; ] -> b64dec_if encoded name, None | l -> raise (Error (sprint "fat list %d" (List.length l))) ) | _ -> raise (Error "Attribute 3") let rec item_of_xml encoded acc token = function | [] -> (acc, token) | X.E ("Item", _, (X.E ("Name", _, [ X.P name ]) :: attrs)) :: nxt -> let a = List.map (attrs_of_xml encoded) attrs in item_of_xml encoded (((b64dec_if encoded name), a) :: acc) token nxt | X.E ("NextToken", _, [ X.P next_token ]) :: _ -> acc, (Some next_token) | _ -> raise (Error "Item") let select_of_xml encoded = function | X.E ("SelectResponse", _, [ X.E ("SelectResult", _, items); _ ; ]) -> item_of_xml encoded [] None items | _ -> raise (Error "SelectResponse") let list_domains creds ?token () = let url, params = signed_request creds (("Action", "ListDomains") :: match token with None -> [] | Some t -> [ "NextToken", t ]) in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in let xml = X.xml_of_string body in return (`Ok (list_domains_response_of_xml xml)) with HC.Http_error (code, _, body) -> return (error_msg code body) let create_domain creds name = let url, params = signed_request creds [ "Action", "CreateDomain" ; "DomainName", name ] in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) let delete_domain creds name = let url, params = signed_request creds [ "Action", "DeleteDomain" ; "DomainName", name ] in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) let put_attributes ?(replace=false) ?(encode=true) creds ~domain ~item attrs = let _, attrs' = List.fold_left ( fun (i, acc) (name, value_opt) -> let value_s = match value_opt with | Some value -> b64enc_if encode value | None -> "" in let value_p = sprint "Attribute.%d.Value" i, value_s in let name_p = sprint "Attribute.%d.Name" i, b64enc_if encode name in let acc = name_p :: value_p :: ( if replace then (sprint "Attribute.%d.Replace" i, "true") :: acc else acc ) in i+1, acc ) (1, []) attrs in let url, params = signed_request creds (("Action", "PutAttributes") :: ("DomainName", domain) :: ("ItemName", b64enc_if encode item) :: attrs') in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) let batch_put_attributes ?(replace=false) ?(encode=true) creds domain items = let _, attrs' = List.fold_left (fun (i, acc) (item_name, attrs) -> let item_name_p = sprint "Item.%d.ItemName" i, b64enc_if encode item_name in let _, acc = List.fold_left ( fun (j, acc) (name, value_opt) -> let name_p = sprint "Item.%d.Attribute.%d.Name" i j, b64enc_if encode name in let value_s = match value_opt with | Some value -> b64enc_if encode value | None -> "" in let value_p = sprint "Item.%d.Attribute.%d.Value" i j, value_s in let acc' = name_p :: value_p :: if replace then (sprint "Item.%d.Attribute.%d.Replace" i j, "true") :: acc else acc in j+1, acc' ) (1, item_name_p :: acc) attrs in i+1, acc ) (1, []) items in let url, params = signed_request creds (("Action", "BatchPutAttributes") :: ("DomainName", domain) :: attrs') in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) let get_attributes ?(encoded=true) creds ~domain ?attribute ~item () = let attribute_name_p = match attribute with | None -> [] | Some attribute_name -> [ "AttributeName", (b64enc_if encoded attribute_name) ] in let url, params = signed_request creds ( ("Action", "GetAttributes") :: ("DomainName", domain) :: ("ItemName", b64enc_if encoded item) :: attribute_name_p ) in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in let xml = X.xml_of_string body in return (`Ok (get_attributes_response_of_xml encoded xml)) with HC.Http_error (code, _, body) -> return (error_msg code body) let delete_attributes ?(encode=true) creds ~domain ~item attrs = let _, attrs' = List.fold_left ( fun (i, acc) (name, value) -> let name_p = sprint "Attribute.%d.Name" i, b64enc_if encode name in let value_p = sprint "Attribute.%d.Value" i, b64enc_if encode value in i+1, name_p :: value_p :: acc ) (0,[]) attrs in let url, params = signed_request creds (("Action", "DeleteAttributes") :: ("DomainName", domain) :: ("ItemName", b64enc_if encode item) :: attrs') in try_lwt lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in return `Ok with HC.Http_error (code, _, body) -> return (error_msg code body) let select ?(consistent=false) ?(encoded=true) ?(token=None) creds expression = let url, params = signed_request ~safe:true creds (("Action", "Select") :: ("SelectExpression", expression) :: ("ConsistentRead", sprint "%B" consistent) :: (match token with | None -> [] | Some t -> [ "NextToken", t ])) in try_lwt let key_equals_value = Util.encode_key_equals_value ~safe:true params in let uri_query_component = String.concat "&" key_equals_value in lwt header, body = HC.post ~body:(`String uri_query_component) url in let xml = X.xml_of_string body in return (`Ok (select_of_xml encoded xml)) with HC.Http_error (code, _, body) -> return (error_msg code body) let select_where_attribute_equals ?(consistent=false) ?(encoded=true) ?(token=None) creds ~domain ~name ~value = let expression = sprint "select * from `%s` where `%s` = %S" domain (b64enc_if encoded name) (b64enc_if encoded value) in select ~consistent ~encoded ~token creds expression end