_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
524fe4f1c3737670c044ea4407d4635a1ecb801ac4de7fafb5a26870f1821e52
ocaml/ocaml
pr4466.ml
(* TEST * hassysthreads include systhreads ** native *) open Printf Regression test for PR#4466 : select timeout with simultaneous read and write on socket in Windows . and write on socket in Windows. *) (* Scenario: - thread [server] implements a simple 'echo' server on a socket - thread [reader] selects then reads from a socket connected to the echo server and copies to standard output - main program executes [writer], which writes to the same socket (the one connected to the echo server) *) let server sock = let (s, _) = Unix.accept sock in let buf = Bytes.make 1024 '>' in for i = 1 to 3 do let n = Unix.recv s buf 2 (Bytes.length buf - 2) [] in if n = 0 then begin Unix.close s; raise Thread.Exit end else begin ignore (Unix.send s buf 0 (n + 2) []) end done let reader s = let buf = Bytes.make 16 ' ' in match Unix.select [s] [] [] 10.0 with | (_::_, _, _) -> printf "Selected\n%!"; let n = Unix.recv s buf 0 (Bytes.length buf) [] in printf "Data read: %s\n%!" (Bytes.sub_string buf 0 n) | ([], _, _) -> printf "TIMEOUT\n%!" let writer s msg = ignore (Unix.send_substring s msg 0 (String.length msg) []) let _ = let addr = Unix.ADDR_INET(Unix.inet_addr_loopback, 0) in let serv = Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in Unix.setsockopt serv Unix.SO_REUSEADDR true; Unix.bind serv addr; let addr = Unix.getsockname serv in Unix.listen serv 5; let tserv = Thread.create server serv in Thread.delay 0.2; let client = Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in Unix.connect client addr; (* Send before select & read *) writer client "1111"; let a = Thread.create reader client in Thread.delay 0.1; Thread.join a; (* Select then send *) let a = Thread.create reader client in Thread.delay 0.1; writer client "2222"; Thread.join a; (* Select then send again *) let a = Thread.create reader client in Thread.delay 0.1; writer client "3333"; Thread.join a; (* Cleanup before exiting *) Thread.join tserv
null
https://raw.githubusercontent.com/ocaml/ocaml/55da58ca6c9144331c7fa56a5d0083cb97b50925/testsuite/tests/lib-threads/pr4466.ml
ocaml
TEST * hassysthreads include systhreads ** native Scenario: - thread [server] implements a simple 'echo' server on a socket - thread [reader] selects then reads from a socket connected to the echo server and copies to standard output - main program executes [writer], which writes to the same socket (the one connected to the echo server) Send before select & read Select then send Select then send again Cleanup before exiting
open Printf Regression test for PR#4466 : select timeout with simultaneous read and write on socket in Windows . and write on socket in Windows. *) let server sock = let (s, _) = Unix.accept sock in let buf = Bytes.make 1024 '>' in for i = 1 to 3 do let n = Unix.recv s buf 2 (Bytes.length buf - 2) [] in if n = 0 then begin Unix.close s; raise Thread.Exit end else begin ignore (Unix.send s buf 0 (n + 2) []) end done let reader s = let buf = Bytes.make 16 ' ' in match Unix.select [s] [] [] 10.0 with | (_::_, _, _) -> printf "Selected\n%!"; let n = Unix.recv s buf 0 (Bytes.length buf) [] in printf "Data read: %s\n%!" (Bytes.sub_string buf 0 n) | ([], _, _) -> printf "TIMEOUT\n%!" let writer s msg = ignore (Unix.send_substring s msg 0 (String.length msg) []) let _ = let addr = Unix.ADDR_INET(Unix.inet_addr_loopback, 0) in let serv = Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in Unix.setsockopt serv Unix.SO_REUSEADDR true; Unix.bind serv addr; let addr = Unix.getsockname serv in Unix.listen serv 5; let tserv = Thread.create server serv in Thread.delay 0.2; let client = Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in Unix.connect client addr; writer client "1111"; let a = Thread.create reader client in Thread.delay 0.1; Thread.join a; let a = Thread.create reader client in Thread.delay 0.1; writer client "2222"; Thread.join a; let a = Thread.create reader client in Thread.delay 0.1; writer client "3333"; Thread.join a; Thread.join tserv
007ba6a25419c92a95f331fbd04537ba36e1f7c648141aa91151ddf5a54d1e13
google/codeworld
Matcher.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE PackageImports #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ViewPatterns # Copyright 2020 The CodeWorld Authors . 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 . Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module CodeWorld.Compile.Requirements.Matcher where import Control.Monad import Data.Generics import Data.Generics.Twins import Data.List import Data.Maybe import "ghc" HsSyn import "ghc" OccName import "ghc" RdrName import "ghc" SrcLoc class (Data a, Typeable a) => Template a where toSplice :: a -> Maybe (HsSplice GhcPs) fromBracket :: (HsBracket GhcPs) -> Maybe a toParens :: a -> Maybe a toTuple :: a -> Maybe [a] toVar :: a -> Maybe a toCon :: a -> Maybe a toLit :: a -> Maybe a toNum :: a -> Maybe a toChar :: a -> Maybe a toStr :: a -> Maybe a instance Template (Pat GhcPs) where toSplice (SplicePat _ s) = Just s toSplice _ = Nothing fromBracket (PatBr _ (L _ p)) = Just p fromBracket _ = Nothing toParens (ParPat _ (L _ x)) = Just x toParens _ = Nothing toTuple (TuplePat _ ps _) = Just [p | L _ p <- ps] toTuple _ = Nothing toVar x@(VarPat _ _) = Just x toVar _ = Nothing toCon x@(ConPatIn _ _) = Just x toCon x@(ConPatOut {}) = Just x toCon _ = Nothing toLit x@(LitPat _ _) = Just x toLit _ = Nothing toNum x@(LitPat _ (HsInt _ _)) = Just x toNum x@(LitPat _ (HsInteger _ _ _)) = Just x toNum x@(LitPat _ (HsRat _ _ _)) = Just x toNum x@(LitPat _ (HsIntPrim _ _)) = Just x toNum x@(LitPat _ (HsWordPrim _ _)) = Just x toNum x@(LitPat _ (HsInt64Prim _ _)) = Just x toNum x@(LitPat _ (HsWord64Prim _ _)) = Just x toNum x@(LitPat _ (HsFloatPrim _ _)) = Just x toNum x@(LitPat _ (HsDoublePrim _ _)) = Just x toNum _ = Nothing toChar x@(LitPat _ (HsChar _ _)) = Just x toChar x@(LitPat _ (HsCharPrim _ _)) = Just x toChar _ = Nothing toStr x@(LitPat _ (HsString _ _)) = Just x toStr x@(LitPat _ (HsStringPrim _ _)) = Just x toStr _ = Nothing instance Template (HsExpr GhcPs) where toSplice (HsSpliceE _ s) = Just s toSplice _ = Nothing fromBracket (ExpBr _ (L _ e)) = Just e fromBracket _ = Nothing toParens (HsPar _ (L _ x)) = Just x toParens _ = Nothing toTuple (ExplicitTuple _ args _) = Just (concat $ tupArgExpr <$> args) toTuple _ = Nothing toVar x@(HsVar _ _) = Just x toVar _ = Nothing toCon x@(HsConLikeOut _ _) = Just x toCon _ = Nothing toLit x@(HsLit _ _) = Just x toLit x@(NegApp _ (L _ (HsLit _ _)) _) = Just x toLit _ = Nothing toNum x@(HsLit _ (HsInt _ _)) = Just x toNum x@(HsLit _ (HsInteger _ _ _)) = Just x toNum x@(HsLit _ (HsRat _ _ _)) = Just x toNum x@(HsLit _ (HsIntPrim _ _)) = Just x toNum x@(HsLit _ (HsWordPrim _ _)) = Just x toNum x@(HsLit _ (HsInt64Prim _ _)) = Just x toNum x@(HsLit _ (HsWord64Prim _ _)) = Just x toNum x@(HsLit _ (HsFloatPrim _ _)) = Just x toNum x@(HsLit _ (HsDoublePrim _ _)) = Just x toNum x@(NegApp _ (L _ (toNum -> Just _)) _) = Just x toNum _ = Nothing toChar x@(HsLit _ (HsChar _ _)) = Just x toChar x@(HsLit _ (HsCharPrim _ _)) = Just x toChar _ = Nothing toStr x@(HsLit _ (HsString _ _)) = Just x toStr x@(HsLit _ (HsStringPrim _ _)) = Just x toStr _ = Nothing tupArgExpr :: (LHsTupArg GhcPs) -> [HsExpr GhcPs] tupArgExpr (L _ (Present _ (L _ x))) = [x] tupArgExpr _ = [] match :: Data a => a -> a -> Bool match tmpl val = matchQ tmpl val matchQ :: GenericQ (GenericQ Bool) matchQ = matchesGhcPs ||| (matchesSpecials :: (Pat GhcPs) -> (Pat GhcPs) -> Maybe Bool) ||| (matchesSpecials :: (HsExpr GhcPs) -> (HsExpr GhcPs) -> Maybe Bool) ||| matchesWildcard ||| mismatchedNames ||| structuralEq matchesGhcPs :: GhcPs -> GhcPs -> Maybe Bool matchesGhcPs _ _ = Just True matchesSpecials :: Template a => a -> a -> Maybe Bool matchesSpecials (toParens -> Just x) y = Just (matchQ x y) matchesSpecials x (toParens -> Just y) = Just (matchQ x y) matchesSpecials ( toSplice -> Just (HsTypedSplice _ _ _ (L _ (HsApp _ op (L _ (HsBracket _ (fromBracket -> Just tmpl)))))) ) x = matchBrackets op tmpl x matchesSpecials ( toSplice -> Just (HsUntypedSplice _ _ _ (L _ (HsApp _ op (L _ (HsBracket _ (fromBracket -> Just tmpl)))))) ) x = matchBrackets op tmpl x matchesSpecials ( toSplice -> Just (HsTypedSplice _ _ _ (L _ (HsApp _ op (L _ (ExplicitList _ _ (sequence . map (\(L _ (HsBracket _ b)) -> fromBracket b) -> Just xs)))))) ) x = matchLogical op xs x matchesSpecials ( toSplice -> Just (HsUntypedSplice _ _ _ (L _ (HsApp _ op (L _ (ExplicitList _ _ (sequence . map (\(L _ (HsBracket _ b)) -> fromBracket b) -> Just xs)))))) ) x = matchLogical op xs x matchesSpecials ( toSplice -> Just (HsTypedSplice _ _ _ (L _ (HsVar _ (L _ id)))) ) x = matchSimple id x matchesSpecials ( toSplice -> Just (HsUntypedSplice _ _ _ (L _ (HsVar _ (L _ id)))) ) x = matchSimple id x matchesSpecials _ _ = Nothing matchBrackets :: Template a => LHsExpr GhcPs -> a -> a -> Maybe Bool matchBrackets op tmpl x = case op of (L _ (HsVar _ (L _ id))) -> case idName id of "tupleOf" -> case toTuple x of Just xs -> Just (all (match tmpl) xs); Nothing -> Just False "contains" -> Just (everything (||) (mkQ False (match tmpl)) x) _ -> Nothing _ -> Nothing matchLogical :: Template a => LHsExpr GhcPs -> [a] -> a -> Maybe Bool matchLogical op xs x = case op of (L _ (HsVar _ (L _ id))) -> case idName id of "allOf" -> Just (all (flip match x) xs) "anyOf" -> Just (any (flip match x) xs) "noneOf" -> Just (not (any (flip match x) xs)) _ -> Nothing _ -> Nothing matchSimple :: Template a => IdP GhcPs -> a -> Maybe Bool matchSimple id x = case idName id of "any" -> Just True "var" -> case toVar x of Just _ -> Just True; Nothing -> Just False "con" -> case toCon x of Just _ -> Just True; Nothing -> Just False "lit" -> case toLit x of Just _ -> Just True; Nothing -> Just False "num" -> case toNum x of Just _ -> Just True; Nothing -> Just False "char" -> case toChar x of Just _ -> Just True; Nothing -> Just False "str" -> case toStr x of Just _ -> Just True; Nothing -> Just False _ -> Nothing matchesWildcard :: IdP GhcPs -> IdP GhcPs -> Maybe Bool matchesWildcard id _ | "_" `isPrefixOf` (idName id) && "_" `isSuffixOf` (idName id) = Just True matchesWildcard _ _ = Nothing mismatchedNames :: IdP GhcPs -> IdP GhcPs -> Maybe Bool mismatchedNames x y = if idName x /= idName y then Just False else Nothing structuralEq :: (Data a, Data b) => a -> b -> Bool structuralEq x y = toConstr x == toConstr y && and (gzipWithQ matchQ x y) (|||) :: (Typeable a, Typeable b, Typeable x) => (x -> x -> Maybe Bool) -> (a -> b -> Bool) -> (a -> b -> Bool) f ||| g = \x y -> fromMaybe (g x y) (join (f <$> cast x <*> cast y)) infixr 0 ||| idName :: IdP GhcPs -> String idName = occNameString . rdrNameOcc
null
https://raw.githubusercontent.com/google/codeworld/77b0863075be12e3bc5f182a53fcc38b038c3e16/codeworld-compiler/src/CodeWorld/Compile/Requirements/Matcher.hs
haskell
# LANGUAGE PackageImports # # LANGUAGE RankNTypes #
# LANGUAGE FlexibleInstances # # LANGUAGE ViewPatterns # Copyright 2020 The CodeWorld Authors . 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 . Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module CodeWorld.Compile.Requirements.Matcher where import Control.Monad import Data.Generics import Data.Generics.Twins import Data.List import Data.Maybe import "ghc" HsSyn import "ghc" OccName import "ghc" RdrName import "ghc" SrcLoc class (Data a, Typeable a) => Template a where toSplice :: a -> Maybe (HsSplice GhcPs) fromBracket :: (HsBracket GhcPs) -> Maybe a toParens :: a -> Maybe a toTuple :: a -> Maybe [a] toVar :: a -> Maybe a toCon :: a -> Maybe a toLit :: a -> Maybe a toNum :: a -> Maybe a toChar :: a -> Maybe a toStr :: a -> Maybe a instance Template (Pat GhcPs) where toSplice (SplicePat _ s) = Just s toSplice _ = Nothing fromBracket (PatBr _ (L _ p)) = Just p fromBracket _ = Nothing toParens (ParPat _ (L _ x)) = Just x toParens _ = Nothing toTuple (TuplePat _ ps _) = Just [p | L _ p <- ps] toTuple _ = Nothing toVar x@(VarPat _ _) = Just x toVar _ = Nothing toCon x@(ConPatIn _ _) = Just x toCon x@(ConPatOut {}) = Just x toCon _ = Nothing toLit x@(LitPat _ _) = Just x toLit _ = Nothing toNum x@(LitPat _ (HsInt _ _)) = Just x toNum x@(LitPat _ (HsInteger _ _ _)) = Just x toNum x@(LitPat _ (HsRat _ _ _)) = Just x toNum x@(LitPat _ (HsIntPrim _ _)) = Just x toNum x@(LitPat _ (HsWordPrim _ _)) = Just x toNum x@(LitPat _ (HsInt64Prim _ _)) = Just x toNum x@(LitPat _ (HsWord64Prim _ _)) = Just x toNum x@(LitPat _ (HsFloatPrim _ _)) = Just x toNum x@(LitPat _ (HsDoublePrim _ _)) = Just x toNum _ = Nothing toChar x@(LitPat _ (HsChar _ _)) = Just x toChar x@(LitPat _ (HsCharPrim _ _)) = Just x toChar _ = Nothing toStr x@(LitPat _ (HsString _ _)) = Just x toStr x@(LitPat _ (HsStringPrim _ _)) = Just x toStr _ = Nothing instance Template (HsExpr GhcPs) where toSplice (HsSpliceE _ s) = Just s toSplice _ = Nothing fromBracket (ExpBr _ (L _ e)) = Just e fromBracket _ = Nothing toParens (HsPar _ (L _ x)) = Just x toParens _ = Nothing toTuple (ExplicitTuple _ args _) = Just (concat $ tupArgExpr <$> args) toTuple _ = Nothing toVar x@(HsVar _ _) = Just x toVar _ = Nothing toCon x@(HsConLikeOut _ _) = Just x toCon _ = Nothing toLit x@(HsLit _ _) = Just x toLit x@(NegApp _ (L _ (HsLit _ _)) _) = Just x toLit _ = Nothing toNum x@(HsLit _ (HsInt _ _)) = Just x toNum x@(HsLit _ (HsInteger _ _ _)) = Just x toNum x@(HsLit _ (HsRat _ _ _)) = Just x toNum x@(HsLit _ (HsIntPrim _ _)) = Just x toNum x@(HsLit _ (HsWordPrim _ _)) = Just x toNum x@(HsLit _ (HsInt64Prim _ _)) = Just x toNum x@(HsLit _ (HsWord64Prim _ _)) = Just x toNum x@(HsLit _ (HsFloatPrim _ _)) = Just x toNum x@(HsLit _ (HsDoublePrim _ _)) = Just x toNum x@(NegApp _ (L _ (toNum -> Just _)) _) = Just x toNum _ = Nothing toChar x@(HsLit _ (HsChar _ _)) = Just x toChar x@(HsLit _ (HsCharPrim _ _)) = Just x toChar _ = Nothing toStr x@(HsLit _ (HsString _ _)) = Just x toStr x@(HsLit _ (HsStringPrim _ _)) = Just x toStr _ = Nothing tupArgExpr :: (LHsTupArg GhcPs) -> [HsExpr GhcPs] tupArgExpr (L _ (Present _ (L _ x))) = [x] tupArgExpr _ = [] match :: Data a => a -> a -> Bool match tmpl val = matchQ tmpl val matchQ :: GenericQ (GenericQ Bool) matchQ = matchesGhcPs ||| (matchesSpecials :: (Pat GhcPs) -> (Pat GhcPs) -> Maybe Bool) ||| (matchesSpecials :: (HsExpr GhcPs) -> (HsExpr GhcPs) -> Maybe Bool) ||| matchesWildcard ||| mismatchedNames ||| structuralEq matchesGhcPs :: GhcPs -> GhcPs -> Maybe Bool matchesGhcPs _ _ = Just True matchesSpecials :: Template a => a -> a -> Maybe Bool matchesSpecials (toParens -> Just x) y = Just (matchQ x y) matchesSpecials x (toParens -> Just y) = Just (matchQ x y) matchesSpecials ( toSplice -> Just (HsTypedSplice _ _ _ (L _ (HsApp _ op (L _ (HsBracket _ (fromBracket -> Just tmpl)))))) ) x = matchBrackets op tmpl x matchesSpecials ( toSplice -> Just (HsUntypedSplice _ _ _ (L _ (HsApp _ op (L _ (HsBracket _ (fromBracket -> Just tmpl)))))) ) x = matchBrackets op tmpl x matchesSpecials ( toSplice -> Just (HsTypedSplice _ _ _ (L _ (HsApp _ op (L _ (ExplicitList _ _ (sequence . map (\(L _ (HsBracket _ b)) -> fromBracket b) -> Just xs)))))) ) x = matchLogical op xs x matchesSpecials ( toSplice -> Just (HsUntypedSplice _ _ _ (L _ (HsApp _ op (L _ (ExplicitList _ _ (sequence . map (\(L _ (HsBracket _ b)) -> fromBracket b) -> Just xs)))))) ) x = matchLogical op xs x matchesSpecials ( toSplice -> Just (HsTypedSplice _ _ _ (L _ (HsVar _ (L _ id)))) ) x = matchSimple id x matchesSpecials ( toSplice -> Just (HsUntypedSplice _ _ _ (L _ (HsVar _ (L _ id)))) ) x = matchSimple id x matchesSpecials _ _ = Nothing matchBrackets :: Template a => LHsExpr GhcPs -> a -> a -> Maybe Bool matchBrackets op tmpl x = case op of (L _ (HsVar _ (L _ id))) -> case idName id of "tupleOf" -> case toTuple x of Just xs -> Just (all (match tmpl) xs); Nothing -> Just False "contains" -> Just (everything (||) (mkQ False (match tmpl)) x) _ -> Nothing _ -> Nothing matchLogical :: Template a => LHsExpr GhcPs -> [a] -> a -> Maybe Bool matchLogical op xs x = case op of (L _ (HsVar _ (L _ id))) -> case idName id of "allOf" -> Just (all (flip match x) xs) "anyOf" -> Just (any (flip match x) xs) "noneOf" -> Just (not (any (flip match x) xs)) _ -> Nothing _ -> Nothing matchSimple :: Template a => IdP GhcPs -> a -> Maybe Bool matchSimple id x = case idName id of "any" -> Just True "var" -> case toVar x of Just _ -> Just True; Nothing -> Just False "con" -> case toCon x of Just _ -> Just True; Nothing -> Just False "lit" -> case toLit x of Just _ -> Just True; Nothing -> Just False "num" -> case toNum x of Just _ -> Just True; Nothing -> Just False "char" -> case toChar x of Just _ -> Just True; Nothing -> Just False "str" -> case toStr x of Just _ -> Just True; Nothing -> Just False _ -> Nothing matchesWildcard :: IdP GhcPs -> IdP GhcPs -> Maybe Bool matchesWildcard id _ | "_" `isPrefixOf` (idName id) && "_" `isSuffixOf` (idName id) = Just True matchesWildcard _ _ = Nothing mismatchedNames :: IdP GhcPs -> IdP GhcPs -> Maybe Bool mismatchedNames x y = if idName x /= idName y then Just False else Nothing structuralEq :: (Data a, Data b) => a -> b -> Bool structuralEq x y = toConstr x == toConstr y && and (gzipWithQ matchQ x y) (|||) :: (Typeable a, Typeable b, Typeable x) => (x -> x -> Maybe Bool) -> (a -> b -> Bool) -> (a -> b -> Bool) f ||| g = \x y -> fromMaybe (g x y) (join (f <$> cast x <*> cast y)) infixr 0 ||| idName :: IdP GhcPs -> String idName = occNameString . rdrNameOcc
6a7111f550c65ab40a8bf37c29653f4cca809c215dc4b9b76ccd45b9c7a05d6b
expipiplus1/vulkan
XR_MSFT_hand_tracking_mesh.hs
{-# language CPP #-} -- | = Name -- -- XR_MSFT_hand_tracking_mesh - instance extension -- -- = Specification -- -- See -- <#XR_MSFT_hand_tracking_mesh XR_MSFT_hand_tracking_mesh> -- in the main specification for complete information. -- -- = Registered Extension Number -- 53 -- -- = Revision -- 2 -- -- = Extension and Version Dependencies -- - Requires OpenXR 1.0 -- -- - Requires @XR_EXT_hand_tracking@ -- -- = See Also -- -- 'HandMeshIndexBufferMSFT', 'HandMeshMSFT', -- 'HandMeshSpaceCreateInfoMSFT', 'HandMeshUpdateInfoMSFT', ' HandMeshVertexBufferMSFT ' , ' HandMeshVertexMSFT ' , ' HandPoseTypeInfoMSFT ' , ' HandPoseTypeMSFT ' , ' SystemHandTrackingMeshPropertiesMSFT ' , ' createHandMeshSpaceMSFT ' , -- 'updateHandMeshMSFT' -- -- = Document Notes -- -- For more information, see the -- <#XR_MSFT_hand_tracking_mesh OpenXR Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module OpenXR.Extensions.XR_MSFT_hand_tracking_mesh ( createHandMeshSpaceMSFT , withHandMeshSpaceMSFT , updateHandMeshMSFT , HandMeshSpaceCreateInfoMSFT(..) , HandMeshUpdateInfoMSFT(..) , HandMeshMSFT(..) , HandMeshIndexBufferMSFT(..) , HandMeshVertexBufferMSFT(..) , HandMeshVertexMSFT(..) , SystemHandTrackingMeshPropertiesMSFT(..) , HandPoseTypeInfoMSFT(..) , HandPoseTypeMSFT( HAND_POSE_TYPE_TRACKED_MSFT , HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT , .. ) , MSFT_hand_tracking_mesh_SPEC_VERSION , pattern MSFT_hand_tracking_mesh_SPEC_VERSION , MSFT_HAND_TRACKING_MESH_EXTENSION_NAME , pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME , HandTrackerEXT(..) ) where import OpenXR.Internal.Utils (enumReadPrec) import OpenXR.Internal.Utils (enumShowsPrec) import OpenXR.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showsPrec) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import OpenXR.CStruct (FromCStruct) import OpenXR.CStruct (FromCStruct(..)) import OpenXR.CStruct (ToCStruct) import OpenXR.CStruct (ToCStruct(..)) import OpenXR.Zero (Zero) import OpenXR.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Data.Int (Int32) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import OpenXR.Core10.FundamentalTypes (bool32ToBool) import OpenXR.Core10.FundamentalTypes (boolToBool32) import OpenXR.Core10.Space (destroySpace) import OpenXR.Core10.FundamentalTypes (Bool32) import OpenXR.Extensions.Handles (HandTrackerEXT) import OpenXR.Extensions.Handles (HandTrackerEXT(..)) import OpenXR.Extensions.Handles (HandTrackerEXT(HandTrackerEXT)) import OpenXR.Extensions.Handles (HandTrackerEXT_T) import OpenXR.Dynamic (InstanceCmds(pXrCreateHandMeshSpaceMSFT)) import OpenXR.Dynamic (InstanceCmds(pXrUpdateHandMeshMSFT)) import OpenXR.Exception (OpenXrException(..)) import OpenXR.Core10.Space (Posef) import OpenXR.Core10.Enums.Result (Result) import OpenXR.Core10.Enums.Result (Result(..)) import OpenXR.Core10.Handles (Space) import OpenXR.Core10.Handles (Space(Space)) import OpenXR.Core10.Handles (Space_T) import OpenXR.Core10.Enums.StructureType (StructureType) import OpenXR.Core10.FundamentalTypes (Time) import OpenXR.Core10.Space (Vector3f) import OpenXR.Core10.Enums.Result (Result(SUCCESS)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_UPDATE_INFO_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_POSE_TYPE_INFO_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT)) import OpenXR.Extensions.Handles (HandTrackerEXT(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrCreateHandMeshSpaceMSFT :: FunPtr (Ptr HandTrackerEXT_T -> Ptr HandMeshSpaceCreateInfoMSFT -> Ptr (Ptr Space_T) -> IO Result) -> Ptr HandTrackerEXT_T -> Ptr HandMeshSpaceCreateInfoMSFT -> Ptr (Ptr Space_T) -> IO Result -- | xrCreateHandMeshSpaceMSFT - Create a space for hand mesh tracking -- -- == Parameter Descriptions -- -- = Description -- -- A hand mesh space location is specified by runtime preference to -- effectively represent hand mesh vertices without unnecessary -- transformations. For example, an optical hand tracking system /can/ -- define the hand mesh space origin at the depth camera’s optical center. -- -- An application should create separate hand mesh space handles for each -- hand to retrieve the corresponding hand mesh data. The runtime /may/ use -- the lifetime of this hand mesh space handle to manage the underlying -- device resources. Therefore, the application /should/ destroy the hand -- mesh handle after it is finished using the hand mesh. -- -- The hand mesh space can be related to other spaces in the session, such -- as view reference space, or grip action space from the -- \/interaction_profiles\/khr\/simple_controller interaction profile. The -- hand mesh space may be not locatable when the hand is outside of the -- tracking range, or if focus is removed from the application. In these -- cases, the runtime /must/ not set the -- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_POSITION_VALID_BIT' -- and -- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_ORIENTATION_VALID_BIT' -- bits on calls to 'OpenXR.Core10.Space.locateSpace' with the hand mesh -- space, and the application /should/ avoid using the returned poses or -- query for hand mesh data. -- If the underlying ' . Handles . ' is -- destroyed, the runtime /must/ continue to support -- 'OpenXR.Core10.Space.locateSpace' using the hand mesh space, and it -- /must/ return space location with -- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_POSITION_VALID_BIT' -- and -- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_ORIENTATION_VALID_BIT' -- unset. -- -- The application /may/ create a mesh space for the reference hand by -- setting @handPoseType@ to 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT'. -- Hand mesh spaces for the reference hand /must/ only be locatable in -- reference to mesh spaces or joint spaces of the reference hand. -- -- == Valid Usage (Implicit) -- -- - #VUID-xrCreateHandMeshSpaceMSFT-extension-notenabled# The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- calling 'createHandMeshSpaceMSFT' -- -- - #VUID-xrCreateHandMeshSpaceMSFT-handTracker-parameter# @handTracker@ /must/ be a valid ' . Handles . ' handle -- - # VUID - xrCreateHandMeshSpaceMSFT - createInfo - parameter # @createInfo@ -- /must/ be a pointer to a valid 'HandMeshSpaceCreateInfoMSFT' -- structure -- -- - #VUID-xrCreateHandMeshSpaceMSFT-space-parameter# @space@ /must/ be a -- pointer to an 'OpenXR.Core10.Handles.Space' handle -- -- == Return Codes -- -- [<#fundamentals-successcodes Success>] -- - ' OpenXR.Core10.Enums . Result . SUCCESS ' -- -- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' -- -- [<#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' -- - ' OpenXR.Core10.Enums . Result . ' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_POSE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' -- -- = See Also -- -- 'HandMeshSpaceCreateInfoMSFT', ' . Handles . ' , -- 'OpenXR.Core10.Handles.Space' createHandMeshSpaceMSFT :: forall io . (MonadIO io) | @handTracker@ is an ' OpenXR.Extensions . Handles . ' handle -- previously created with the ' . ' function . HandTrackerEXT -> -- | @createInfo@ is the 'HandMeshSpaceCreateInfoMSFT' used to specify the -- hand mesh space. HandMeshSpaceCreateInfoMSFT -> io (Result, Space) createHandMeshSpaceMSFT handTracker createInfo = liftIO . evalContT $ do let cmds = case handTracker of HandTrackerEXT{instanceCmds} -> instanceCmds let xrCreateHandMeshSpaceMSFTPtr = pXrCreateHandMeshSpaceMSFT cmds lift $ unless (xrCreateHandMeshSpaceMSFTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrCreateHandMeshSpaceMSFT is null" Nothing Nothing let xrCreateHandMeshSpaceMSFT' = mkXrCreateHandMeshSpaceMSFT xrCreateHandMeshSpaceMSFTPtr createInfo' <- ContT $ withCStruct (createInfo) pSpace <- ContT $ bracket (callocBytes @(Ptr Space_T) 8) free r <- lift $ traceAroundEvent "xrCreateHandMeshSpaceMSFT" (xrCreateHandMeshSpaceMSFT' (handTrackerEXTHandle (handTracker)) createInfo' (pSpace)) lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) space <- lift $ peek @(Ptr Space_T) pSpace pure $ (r, ((\h -> Space h cmds ) space)) -- | A convenience wrapper to make a compatible pair of calls to -- 'createHandMeshSpaceMSFT' and 'destroySpace' -- To ensure that ' ' is always called : pass -- 'Control.Exception.bracket' (or the allocate function from your -- favourite resource management library) as the last argument. -- To just extract the pair pass '(,)' as the last argument. -- withHandMeshSpaceMSFT :: forall io r . MonadIO io => HandTrackerEXT -> HandMeshSpaceCreateInfoMSFT -> (io (Result, Space) -> ((Result, Space) -> io ()) -> r) -> r withHandMeshSpaceMSFT handTracker createInfo b = b (createHandMeshSpaceMSFT handTracker createInfo) (\(_, o1) -> destroySpace o1) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrUpdateHandMeshMSFT :: FunPtr (Ptr HandTrackerEXT_T -> Ptr HandMeshUpdateInfoMSFT -> Ptr HandMeshMSFT -> IO Result) -> Ptr HandTrackerEXT_T -> Ptr HandMeshUpdateInfoMSFT -> Ptr HandMeshMSFT -> IO Result -- | xrUpdateHandMeshMSFT - Update hand mesh buffers -- -- == Parameter Descriptions -- -- = Description -- -- The application /should/ preallocate the index buffer and vertex buffer -- in 'HandMeshMSFT' using the @maxHandMeshIndexCount@ and @maxHandMeshVertexCount@ from the ' SystemHandTrackingMeshPropertiesMSFT ' returned from the ' OpenXR.Core10.Device.getSystemProperties ' function . -- -- The application /should/ preallocate the 'HandMeshMSFT' structure and -- reuse it for each frame so as to reduce the copies of data when -- underlying tracking data is not changed. The application should use @indexBufferChanged@ and @vertexBufferChanged@ in ' HandMeshMSFT ' to -- detect changes and avoid unnecessary data processing when there is no -- changes. -- -- == Valid Usage (Implicit) -- -- - #VUID-xrUpdateHandMeshMSFT-extension-notenabled# The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- calling 'updateHandMeshMSFT' -- -- - #VUID-xrUpdateHandMeshMSFT-handTracker-parameter# @handTracker@ /must/ be a valid ' . Handles . ' handle -- -- - #VUID-xrUpdateHandMeshMSFT-updateInfo-parameter# @updateInfo@ /must/ -- be a pointer to a valid 'HandMeshUpdateInfoMSFT' structure -- -- - #VUID-xrUpdateHandMeshMSFT-handMesh-parameter# @handMesh@ /must/ be -- a pointer to an 'HandMeshMSFT' structure -- -- == Return Codes -- -- [<#fundamentals-successcodes Success>] -- - ' OpenXR.Core10.Enums . Result . SUCCESS ' -- -- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' -- -- [<#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' -- - ' OpenXR.Core10.Enums . Result . ' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_TIME_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- - ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' -- -- = See Also -- -- 'HandMeshMSFT', 'HandMeshUpdateInfoMSFT', ' . Handles . ' updateHandMeshMSFT :: forall io . (MonadIO io) | @handTracker@ is an ' OpenXR.Extensions . Handles . ' handle -- previously created with ' . ' . HandTrackerEXT -> -- | @updateInfo@ is a 'HandMeshUpdateInfoMSFT' which contains information to -- query the hand mesh. HandMeshUpdateInfoMSFT -> io (Result, HandMeshMSFT) updateHandMeshMSFT handTracker updateInfo = liftIO . evalContT $ do let xrUpdateHandMeshMSFTPtr = pXrUpdateHandMeshMSFT (case handTracker of HandTrackerEXT{instanceCmds} -> instanceCmds) lift $ unless (xrUpdateHandMeshMSFTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrUpdateHandMeshMSFT is null" Nothing Nothing let xrUpdateHandMeshMSFT' = mkXrUpdateHandMeshMSFT xrUpdateHandMeshMSFTPtr updateInfo' <- ContT $ withCStruct (updateInfo) pHandMesh <- ContT (withZeroCStruct @HandMeshMSFT) r <- lift $ traceAroundEvent "xrUpdateHandMeshMSFT" (xrUpdateHandMeshMSFT' (handTrackerEXTHandle (handTracker)) updateInfo' (pHandMesh)) lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) handMesh <- lift $ peekCStruct @HandMeshMSFT pHandMesh pure $ (r, handMesh) -- | XrHandMeshSpaceCreateInfoMSFT - The information to create a hand mesh -- space -- -- == Valid Usage (Implicit) -- - # VUID - XrHandMeshSpaceCreateInfoMSFT - extension - notenabled # The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- using 'HandMeshSpaceCreateInfoMSFT' -- -- - #VUID-XrHandMeshSpaceCreateInfoMSFT-type-type# @type@ /must/ be ' OpenXR.Core10.Enums . StructureType . ' -- - # VUID - XrHandMeshSpaceCreateInfoMSFT - next - next # @next@ /must/ be -- @NULL@ or a valid pointer to the -- <#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- - # VUID - XrHandMeshSpaceCreateInfoMSFT - handPoseType - parameter # @handPoseType@ /must/ be a valid ' HandPoseTypeMSFT ' value -- -- = See Also -- ' HandPoseTypeMSFT ' , ' OpenXR.Core10.Space . ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' , -- 'createHandMeshSpaceMSFT' data HandMeshSpaceCreateInfoMSFT = HandMeshSpaceCreateInfoMSFT { -- | @handPoseType@ is an 'HandPoseTypeMSFT' used to specify the type of hand -- this mesh is tracking. Indices and vertices returned from -- 'updateHandMeshMSFT' for a hand type will be relative to the -- corresponding space create with the same hand type. handPoseType :: HandPoseTypeMSFT | @poseInHandMeshSpace@ is an ' OpenXR.Core10.Space . ' defining the -- position and orientation of the new space’s origin within the natural -- reference frame of the hand mesh space. poseInHandMeshSpace :: Posef } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshSpaceCreateInfoMSFT) #endif deriving instance Show HandMeshSpaceCreateInfoMSFT instance ToCStruct HandMeshSpaceCreateInfoMSFT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshSpaceCreateInfoMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (handPoseType) poke ((p `plusPtr` 20 :: Ptr Posef)) (poseInHandMeshSpace) f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (zero) poke ((p `plusPtr` 20 :: Ptr Posef)) (zero) f instance FromCStruct HandMeshSpaceCreateInfoMSFT where peekCStruct p = do handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) poseInHandMeshSpace <- peekCStruct @Posef ((p `plusPtr` 20 :: Ptr Posef)) pure $ HandMeshSpaceCreateInfoMSFT handPoseType poseInHandMeshSpace instance Storable HandMeshSpaceCreateInfoMSFT where sizeOf ~_ = 48 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshSpaceCreateInfoMSFT where zero = HandMeshSpaceCreateInfoMSFT zero zero -- | XrHandMeshUpdateInfoMSFT - The information to update a hand mesh -- -- == Member Descriptions -- -- = Description -- -- A runtime /may/ not maintain a full history of hand mesh data, therefore -- the returned 'HandMeshMSFT' might return data that’s not exactly -- corresponding to the @time@ input. If the runtime cannot return any -- tracking data for the given @time@ at all, it /must/ set @isActive@ to -- 'OpenXR.Core10.FundamentalTypes.FALSE' for the call to -- 'updateHandMeshMSFT'. Otherwise, if the runtime returns @isActive@ as ' OpenXR.Core10.FundamentalTypes . TRUE ' , the data in ' HandMeshMSFT ' must -- be valid to use. -- -- An application can choose different @handPoseType@ values to query the -- hand mesh data. The returned hand mesh /must/ be consistent to the hand -- joint space location on the same ' . Handles . ' when using the same -- 'HandPoseTypeMSFT'. -- -- == Valid Usage (Implicit) -- -- - #VUID-XrHandMeshUpdateInfoMSFT-extension-notenabled# The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- using 'HandMeshUpdateInfoMSFT' -- -- - #VUID-XrHandMeshUpdateInfoMSFT-type-type# @type@ /must/ be ' OpenXR.Core10.Enums . StructureType . TYPE_HAND_MESH_UPDATE_INFO_MSFT ' -- -- - #VUID-XrHandMeshUpdateInfoMSFT-next-next# @next@ /must/ be @NULL@ or -- a valid pointer to the -- <#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrHandMeshUpdateInfoMSFT-handPoseType-parameter# @handPoseType@ /must/ be a valid ' HandPoseTypeMSFT ' value -- -- = See Also -- ' HandPoseTypeMSFT ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' , -- <#XrTime >, -- 'updateHandMeshMSFT' data HandMeshUpdateInfoMSFT = HandMeshUpdateInfoMSFT { -- | @time@ is the -- <#XrTime > -- that describes the time for which the application wishes to query the -- hand mesh state. time :: Time , -- | @handPoseType@ is an 'HandPoseTypeMSFT' which describes the type of hand -- pose of the hand mesh to update. handPoseType :: HandPoseTypeMSFT } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshUpdateInfoMSFT) #endif deriving instance Show HandMeshUpdateInfoMSFT instance ToCStruct HandMeshUpdateInfoMSFT where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshUpdateInfoMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_UPDATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Time)) (time) poke ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) (handPoseType) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_UPDATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Time)) (zero) poke ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) (zero) f instance FromCStruct HandMeshUpdateInfoMSFT where peekCStruct p = do time <- peek @Time ((p `plusPtr` 16 :: Ptr Time)) handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) pure $ HandMeshUpdateInfoMSFT time handPoseType instance Storable HandMeshUpdateInfoMSFT where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshUpdateInfoMSFT where zero = HandMeshUpdateInfoMSFT zero zero -- | XrHandMeshMSFT - The data of a hand mesh -- -- == Member Descriptions -- -- = Description -- -- When the returned @isActive@ value is -- 'OpenXR.Core10.FundamentalTypes.FALSE', the runtime indicates the hand -- is not actively tracked, for example, the hand is outside of sensor’s -- range, or the input focus is taken away from the application. When the -- runtime returns 'OpenXR.Core10.FundamentalTypes.FALSE' to @isActive@, it /must/ set @indexBufferChanged@ and @vertexBufferChanged@ to -- 'OpenXR.Core10.FundamentalTypes.FALSE', and /must/ not change the -- content in @indexBuffer@ or @vertexBuffer@, -- -- When the returned @isActive@ value is ' OpenXR.Core10.FundamentalTypes . TRUE ' , the hand tracking mesh -- represented in @indexBuffer@ and @vertexBuffer@ are updated to the -- latest data of the @time@ given to the 'updateHandMeshMSFT' function. The runtime /must/ set @indexBufferChanged@ and @vertexBufferChanged@ to -- reflect whether the index or vertex buffer’s content are changed during -- the update. In this way, the application can easily avoid unnecessary -- processing of buffers when there’s no new data. -- -- The hand mesh is represented in triangle lists and each triangle’s -- vertices are in counter-clockwise order when looking from outside of the -- hand. When hand tracking is active, i.e. when @isActive@ is returned as ' OpenXR.Core10.FundamentalTypes . TRUE ' , the returned -- @indexBuffer.indexCountOutput@ value /must/ be positive and multiple of 3 , and @vertexBuffer.vertexCountOutput@ value /must/ be equal to or larger than 3 . -- -- == Valid Usage (Implicit) -- -- - #VUID-XrHandMeshMSFT-extension-notenabled# The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- using 'HandMeshMSFT' -- -- - #VUID-XrHandMeshMSFT-type-type# @type@ /must/ be ' OpenXR.Core10.Enums . StructureType . TYPE_HAND_MESH_MSFT ' -- -- - #VUID-XrHandMeshMSFT-next-next# @next@ /must/ be @NULL@ or a valid -- pointer to the -- <#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrHandMeshMSFT-indexBuffer-parameter# @indexBuffer@ /must/ be -- a valid 'HandMeshIndexBufferMSFT' structure -- -- - #VUID-XrHandMeshMSFT-vertexBuffer-parameter# @vertexBuffer@ /must/ -- be a valid 'HandMeshVertexBufferMSFT' structure -- -- = See Also -- -- <#XrBool32 >, -- 'HandMeshIndexBufferMSFT', 'HandMeshVertexBufferMSFT', ' OpenXR.Core10.Enums . StructureType . StructureType ' , ' updateHandMeshMSFT ' data HandMeshMSFT = HandMeshMSFT { -- | @isActive@ is an -- <#XrBool32 > -- indicating if the current hand tracker is active. isActive :: Bool | @indexBufferChanged@ is an -- <#XrBool32 > -- indicating if the @indexBuffer@ content was changed during the update. indexBufferChanged :: Bool , -- | @vertexBufferChanged@ is an -- <#XrBool32 > -- indicating if the @vertexBuffer@ content was changed during the update. vertexBufferChanged :: Bool , -- | @indexBuffer@ is an 'HandMeshIndexBufferMSFT' returns the index buffer -- of the tracked hand mesh. indexBuffer :: HandMeshIndexBufferMSFT , -- | @vertexBuffer@ is an 'HandMeshVertexBufferMSFT' returns the vertex -- buffer of the tracked hand mesh. vertexBuffer :: HandMeshVertexBufferMSFT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshMSFT) #endif deriving instance Show HandMeshMSFT instance ToCStruct HandMeshMSFT where withCStruct x f = allocaBytes 80 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (isActive)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (indexBufferChanged)) poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (vertexBufferChanged)) poke ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) (indexBuffer) poke ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) (vertexBuffer) f cStructSize = 80 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) (zero) poke ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) (zero) f instance FromCStruct HandMeshMSFT where peekCStruct p = do isActive <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) indexBufferChanged <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32)) vertexBufferChanged <- peek @Bool32 ((p `plusPtr` 24 :: Ptr Bool32)) indexBuffer <- peekCStruct @HandMeshIndexBufferMSFT ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) vertexBuffer <- peekCStruct @HandMeshVertexBufferMSFT ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) pure $ HandMeshMSFT (bool32ToBool isActive) (bool32ToBool indexBufferChanged) (bool32ToBool vertexBufferChanged) indexBuffer vertexBuffer instance Storable HandMeshMSFT where sizeOf ~_ = 80 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshMSFT where zero = HandMeshMSFT zero zero zero zero zero -- | XrHandMeshIndexBufferMSFT - The index buffer of a hand mesh -- -- == Member Descriptions -- -- = Description -- -- An application /should/ preallocate the indices array using the @maxHandMeshIndexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' . In this way , -- the application can avoid possible insufficient buffer sizees for each -- query, and therefore avoid reallocating memory each frame. -- The input @indexCapacityInput@ /must/ not be 0 , and @indices@ /must/ not -- be @NULL@, or else the runtime /must/ return -- 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' on calls to the -- 'updateHandMeshMSFT' function. -- -- If the input @indexCapacityInput@ is not sufficient to contain all -- output indices, the runtime /must/ return ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' on calls to ' updateHandMeshMSFT ' , not change the content in @indexBufferKey@ and @indices@ , and return 0 for @indexCountOutput@. -- -- If the input @indexCapacityInput@ is equal to or larger than the @maxHandMeshIndexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' , the runtime /must/ not return ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' -- error on 'updateHandMeshMSFT' because of insufficient index buffer size. -- If the input @indexBufferKey@ is 0 , the capacity of indices array is -- sufficient, and hand mesh tracking is active, the runtime /must/ return the latest non - zero @indexBufferKey@ , and fill in @indexCountOutput@ and -- @indices@. -- If the input @indexBufferKey@ is not 0 , the runtime /can/ either return without changing @indexCountOutput@ or content in @indices@ , and return ' OpenXR.Core10.FundamentalTypes . FALSE ' for @indexBufferChanged@ -- indicating the indices are not changed; or return a new non-zero @indexBufferKey@ and fill in latest data in @indexCountOutput@ and @indices@ , and return ' OpenXR.Core10.FundamentalTypes . TRUE ' for @indexBufferChanged@ indicating the indices are updated to a newer -- version. -- -- An application /can/ keep the 'HandMeshIndexBufferMSFT' structure for each frame in a frame loop and use the returned @indexBufferKey@ to -- identify different triangle list topology described in @indices@. The -- application can therefore avoid unnecessary processing of indices, such -- as coping them to GPU memory. -- The runtime /must/ return the same @indexBufferKey@ for the same ' . Handles . ' at a given time , regardless of the input ' HandPoseTypeMSFT ' in ' HandMeshUpdateInfoMSFT ' . This -- ensures the index buffer has the same mesh topology and allows the -- application to reason about vertices across different hand pose types. -- For example, the application /can/ build a procedure to perform UV -- mapping on vertices of a hand mesh using -- 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT', and apply the resultant UV -- data on vertices to the mesh returned from the same hand tracker using -- 'HAND_POSE_TYPE_TRACKED_MSFT'. -- -- == Valid Usage (Implicit) -- -- - #VUID-XrHandMeshIndexBufferMSFT-extension-notenabled# The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- using 'HandMeshIndexBufferMSFT' -- - # VUID - XrHandMeshIndexBufferMSFT - indices - parameter # @indices@ /must/ be a pointer to an array of @indexCapacityInput@ values -- -- - #VUID-XrHandMeshIndexBufferMSFT-indexCapacityInput-arraylength# The @indexCapacityInput@ parameter /must/ be greater than @0@ -- -- = See Also -- -- 'HandMeshMSFT' data HandMeshIndexBufferMSFT = HandMeshIndexBufferMSFT | @indexBufferKey@ is a @uint32_t@ serving as the key of the returned -- index buffer content or 0 to indicate a request to retrieve the latest -- indices regardless of existing content in @indices@. indexBufferKey :: Word32 | @indexCapacityInput@ is a positive @uint32_t@ describes the capacity of the @indices@ array . indexCapacityInput :: Word32 | @indexCountOutput@ is a returned by the runtime with the -- count of indices written in @indices@. indexCountOutput :: Word32 | @indices@ is an array of indices filled in by the runtime , specifying -- the indices of the triangles list in the vertex buffer. indices :: Ptr Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshIndexBufferMSFT) #endif deriving instance Show HandMeshIndexBufferMSFT instance ToCStruct HandMeshIndexBufferMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshIndexBufferMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr Word32)) (indexBufferKey) poke ((p `plusPtr` 4 :: Ptr Word32)) (indexCapacityInput) poke ((p `plusPtr` 8 :: Ptr Word32)) (indexCountOutput) poke ((p `plusPtr` 16 :: Ptr (Ptr Word32))) (indices) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 4 :: Ptr Word32)) (zero) poke ((p `plusPtr` 16 :: Ptr (Ptr Word32))) (zero) f instance FromCStruct HandMeshIndexBufferMSFT where peekCStruct p = do indexBufferKey <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32)) indexCapacityInput <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32)) indexCountOutput <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32)) indices <- peek @(Ptr Word32) ((p `plusPtr` 16 :: Ptr (Ptr Word32))) pure $ HandMeshIndexBufferMSFT indexBufferKey indexCapacityInput indexCountOutput indices instance Storable HandMeshIndexBufferMSFT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshIndexBufferMSFT where zero = HandMeshIndexBufferMSFT zero zero zero zero -- | XrHandMeshVertexBufferMSFT - The vertex buffer of a hand mesh -- -- == Member Descriptions -- -- = Description -- -- An application /should/ preallocate the vertices array using the @maxHandMeshVertexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' . In this way , -- the application can avoid possible insufficient buffer sizes for each -- query, and therefore avoid reallocating memory each frame. -- -- The input @vertexCapacityInput@ /must/ not be 0, and @vertices@ /must/ -- not be @NULL@, or else the runtime /must/ return -- 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' on calls to the -- 'updateHandMeshMSFT' function. -- -- If the input @vertexCapacityInput@ is not sufficient to contain all -- output vertices, the runtime /must/ return ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' on calls to the ' updateHandMeshMSFT ' , do not change content in @vertexUpdateTime@ and -- @vertices@, and return 0 for @vertexCountOutput@. -- -- If the input @vertexCapacityInput@ is equal to or larger than the @maxHandMeshVertexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' , the runtime /must/ not return ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' on calls to the ' updateHandMeshMSFT ' because of insufficient vertex -- buffer size. -- If the input @vertexUpdateTime@ is 0 , and the capacity of the vertices -- array is sufficient, and hand mesh tracking is active, the runtime -- /must/ return the latest non-zero @vertexUpdateTime@, and fill in the -- @vertexCountOutput@ and @vertices@ fields. -- If the input @vertexUpdateTime@ is not 0 , the runtime /can/ either return without changing or the content in -- @vertices@, and return 'OpenXR.Core10.FundamentalTypes.FALSE' for -- @vertexBufferChanged@ indicating the vertices are not changed; or return a new non - zero @vertexUpdateTime@ and fill in latest data in -- @vertexCountOutput@ and @vertices@ and return ' OpenXR.Core10.FundamentalTypes . TRUE ' for @vertexBufferChanged@ -- indicating the vertices are updated to a newer version. -- -- An application /can/ keep the 'HandMeshVertexBufferMSFT' structure for each frame in frame loop and use the returned @vertexUpdateTime@ to -- detect the changes of the content in @vertices@. The application can -- therefore avoid unnecessary processing of vertices, such as coping them -- to GPU memory. -- -- == Valid Usage (Implicit) -- -- - #VUID-XrHandMeshVertexBufferMSFT-extension-notenabled# The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- using 'HandMeshVertexBufferMSFT' -- -- - #VUID-XrHandMeshVertexBufferMSFT-vertices-parameter# @vertices@ -- /must/ be a pointer to an array of @vertexCapacityInput@ ' HandMeshVertexMSFT ' structures -- - # VUID - XrHandMeshVertexBufferMSFT - vertexCapacityInput - arraylength # The @vertexCapacityInput@ parameter /must/ be greater than @0@ -- -- = See Also -- ' HandMeshMSFT ' , ' HandMeshVertexMSFT ' , -- <#XrTime > data HandMeshVertexBufferMSFT = HandMeshVertexBufferMSFT { -- | @vertexUpdateTime@ is an -- <#XrTime > -- representing the time when the runtime receives the vertex buffer -- content or 0 to indicate a request to retrieve latest vertices -- regardless of existing content in @vertices@. vertexUpdateTime :: Time | @vertexCapacityInput@ is a positive @uint32_t@ describes the capacity of -- the @vertices@ array. vertexCapacityInput :: Word32 | @vertexCountOutput@ is a filled in by the runtime with the -- count of vertices written in @vertices@. vertexCountOutput :: Word32 | @vertices@ is an array of ' HandMeshVertexMSFT ' filled in by the runtime , -- specifying the vertices of the hand mesh including the position and -- normal vector in the hand mesh space. vertices :: Ptr HandMeshVertexMSFT } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshVertexBufferMSFT) #endif deriving instance Show HandMeshVertexBufferMSFT instance ToCStruct HandMeshVertexBufferMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshVertexBufferMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr Time)) (vertexUpdateTime) poke ((p `plusPtr` 8 :: Ptr Word32)) (vertexCapacityInput) poke ((p `plusPtr` 12 :: Ptr Word32)) (vertexCountOutput) poke ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) (vertices) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 8 :: Ptr Word32)) (zero) poke ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) (zero) f instance FromCStruct HandMeshVertexBufferMSFT where peekCStruct p = do vertexUpdateTime <- peek @Time ((p `plusPtr` 0 :: Ptr Time)) vertexCapacityInput <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32)) vertexCountOutput <- peek @Word32 ((p `plusPtr` 12 :: Ptr Word32)) vertices <- peek @(Ptr HandMeshVertexMSFT) ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) pure $ HandMeshVertexBufferMSFT vertexUpdateTime vertexCapacityInput vertexCountOutput vertices instance Storable HandMeshVertexBufferMSFT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshVertexBufferMSFT where zero = HandMeshVertexBufferMSFT zero zero zero zero -- | XrHandMeshVertexMSFT - The vertex of hand mesh -- -- == Valid Usage (Implicit) -- - # VUID - XrHandMeshVertexMSFT - extension - notenabled # The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using ' HandMeshVertexMSFT ' -- -- = See Also -- ' HandMeshVertexBufferMSFT ' , ' OpenXR.Core10.Space . ' data HandMeshVertexMSFT = HandMeshVertexMSFT | @position@ is an ' OpenXR.Core10.Space . ' structure representing -- the position of the vertex in the hand mesh space, measured in meters. position :: Vector3f | @normal@ is an ' OpenXR.Core10.Space . ' structure representing the -- unweighted normal of the triangle surface at the vertex as a unit vector -- in hand mesh space. normal :: Vector3f } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshVertexMSFT) #endif deriving instance Show HandMeshVertexMSFT instance ToCStruct HandMeshVertexMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshVertexMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr Vector3f)) (position) poke ((p `plusPtr` 12 :: Ptr Vector3f)) (normal) f cStructSize = 24 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr Vector3f)) (zero) poke ((p `plusPtr` 12 :: Ptr Vector3f)) (zero) f instance FromCStruct HandMeshVertexMSFT where peekCStruct p = do position <- peekCStruct @Vector3f ((p `plusPtr` 0 :: Ptr Vector3f)) normal <- peekCStruct @Vector3f ((p `plusPtr` 12 :: Ptr Vector3f)) pure $ HandMeshVertexMSFT position normal instance Storable HandMeshVertexMSFT where sizeOf ~_ = 24 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshVertexMSFT where zero = HandMeshVertexMSFT zero zero | XrSystemHandTrackingMeshPropertiesMSFT - System property for hand -- tracking mesh -- -- == Member Descriptions -- -- = Description -- -- If a runtime returns 'OpenXR.Core10.FundamentalTypes.FALSE' for -- @supportsHandTrackingMesh@, the system does not support hand tracking -- mesh input, and therefore /must/ return -- 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' from -- 'createHandMeshSpaceMSFT' and 'updateHandMeshMSFT'. The application -- /should/ avoid using hand mesh functionality when -- @supportsHandTrackingMesh@ is 'OpenXR.Core10.FundamentalTypes.FALSE'. -- -- If a runtime returns 'OpenXR.Core10.FundamentalTypes.TRUE' for -- @supportsHandTrackingMesh@, the system supports hand tracking mesh -- input. In this case, the runtime /must/ return a positive number for -- @maxHandMeshIndexCount@ and @maxHandMeshVertexCount@. An application /should/ use @maxHandMeshIndexCount@ and @maxHandMeshVertexCount@ to -- preallocate hand mesh buffers and reuse them in their render loop when -- calling 'updateHandMeshMSFT' every frame. -- -- == Valid Usage (Implicit) -- - # VUID - XrSystemHandTrackingMeshPropertiesMSFT - extension - notenabled # -- The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using ' SystemHandTrackingMeshPropertiesMSFT ' -- - # VUID - XrSystemHandTrackingMeshPropertiesMSFT - type - type # @type@ -- /must/ be ' OpenXR.Core10.Enums . StructureType . TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT ' -- - # VUID - XrSystemHandTrackingMeshPropertiesMSFT - next - next # @next@ -- /must/ be @NULL@ or a valid pointer to the -- <#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- = See Also -- -- <#XrBool32 >, ' OpenXR.Core10.Enums . StructureType . StructureType ' data SystemHandTrackingMeshPropertiesMSFT = SystemHandTrackingMeshPropertiesMSFT { -- | @supportsHandTrackingMesh@ is an -- <#XrBool32 >, -- indicating if current system is capable of hand tracking mesh input. supportsHandTrackingMesh :: Bool | @maxHandMeshIndexCount@ is a @uint32_t@ returns the maximum count of -- indices that will be returned from the hand tracker. maxHandMeshIndexCount :: Word32 | @maxHandMeshVertexCount@ is a @uint32_t@ returns the maximum count of -- vertices that will be returned from the hand tracker. maxHandMeshVertexCount :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SystemHandTrackingMeshPropertiesMSFT) #endif deriving instance Show SystemHandTrackingMeshPropertiesMSFT instance ToCStruct SystemHandTrackingMeshPropertiesMSFT where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p SystemHandTrackingMeshPropertiesMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (supportsHandTrackingMesh)) poke ((p `plusPtr` 20 :: Ptr Word32)) (maxHandMeshIndexCount) poke ((p `plusPtr` 24 :: Ptr Word32)) (maxHandMeshVertexCount) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Word32)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) f instance FromCStruct SystemHandTrackingMeshPropertiesMSFT where peekCStruct p = do supportsHandTrackingMesh <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) maxHandMeshIndexCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) maxHandMeshVertexCount <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) pure $ SystemHandTrackingMeshPropertiesMSFT (bool32ToBool supportsHandTrackingMesh) maxHandMeshIndexCount maxHandMeshVertexCount instance Storable SystemHandTrackingMeshPropertiesMSFT where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SystemHandTrackingMeshPropertiesMSFT where zero = SystemHandTrackingMeshPropertiesMSFT zero zero zero -- | XrHandPoseTypeInfoMSFT - Describes what hand pose type for the hand -- joint tracking. -- -- == Valid Usage (Implicit) -- -- - #VUID-XrHandPoseTypeInfoMSFT-extension-notenabled# The -- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to -- using 'HandPoseTypeInfoMSFT' -- -- - #VUID-XrHandPoseTypeInfoMSFT-type-type# @type@ /must/ be ' OpenXR.Core10.Enums . StructureType . TYPE_HAND_POSE_TYPE_INFO_MSFT ' -- -- - #VUID-XrHandPoseTypeInfoMSFT-next-next# @next@ /must/ be @NULL@ or a -- valid pointer to the -- <#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- - # VUID - XrHandPoseTypeInfoMSFT - handPoseType - parameter # @handPoseType@ /must/ be a valid ' HandPoseTypeMSFT ' value -- -- = See Also -- ' HandPoseTypeMSFT ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' data HandPoseTypeInfoMSFT = HandPoseTypeInfoMSFT { -- | @handPoseType@ is an 'HandPoseTypeMSFT' that describes the type of hand -- pose of the hand tracking. handPoseType :: HandPoseTypeMSFT } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandPoseTypeInfoMSFT) #endif deriving instance Show HandPoseTypeInfoMSFT instance ToCStruct HandPoseTypeInfoMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandPoseTypeInfoMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_POSE_TYPE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (handPoseType) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_POSE_TYPE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (zero) f instance FromCStruct HandPoseTypeInfoMSFT where peekCStruct p = do handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) pure $ HandPoseTypeInfoMSFT handPoseType instance Storable HandPoseTypeInfoMSFT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandPoseTypeInfoMSFT where zero = HandPoseTypeInfoMSFT zero -- | XrHandPoseTypeMSFT - Describe type of input hand pose -- = = -- The ' HAND_POSE_TYPE_TRACKED_MSFT ' input provides best fidelity to the -- user’s actual hand motion. When the hand tracking input requires the -- user to be holding a controller in their hand, the hand tracking input -- will appear as the user virtually holding the controller. This input can -- be used to render the hand shape together with the controller in hand. -- The ' HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT ' input does not move with -- the user’s actual hand. Through this reference hand pose, an application -- /can/ get a stable hand joint and mesh that has the same mesh topology -- as the tracked hand mesh using the same ' . Handles . ' , so that the application can -- apply the data computed from a reference hand pose to the corresponding -- tracked hand. -- -- Although a reference hand pose does not move with user’s hand motion, -- the bone length and hand thickness /may/ be updated, for example when -- tracking result refines, or a different user’s hand is detected. The -- application /should/ update reference hand joints and meshes when the tracked mesh ’s @indexBufferKey@ is changed or when the @isActive@ value -- returned from 'updateHandMeshMSFT' changes from -- 'OpenXR.Core10.FundamentalTypes.FALSE' to ' OpenXR.Core10.FundamentalTypes . TRUE ' . It can use the returned @indexBufferKey@ and @vertexUpdateTime@ from ' updateHandMeshMSFT ' to -- avoid unnecessary CPU or GPU work to process the neutral hand inputs. -- -- = See Also -- -- 'HandMeshSpaceCreateInfoMSFT', 'HandMeshUpdateInfoMSFT', -- 'HandPoseTypeInfoMSFT' newtype HandPoseTypeMSFT = HandPoseTypeMSFT Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'HAND_POSE_TYPE_TRACKED_MSFT' represents a hand pose provided by actual -- tracking of the user’s hand. pattern HAND_POSE_TYPE_TRACKED_MSFT = HandPoseTypeMSFT 0 -- | 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT' represents a stable reference -- hand pose in a relaxed open hand shape. pattern HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT = HandPoseTypeMSFT 1 {-# COMPLETE HAND_POSE_TYPE_TRACKED_MSFT , HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT :: HandPoseTypeMSFT #-} conNameHandPoseTypeMSFT :: String conNameHandPoseTypeMSFT = "HandPoseTypeMSFT" enumPrefixHandPoseTypeMSFT :: String enumPrefixHandPoseTypeMSFT = "HAND_POSE_TYPE_" showTableHandPoseTypeMSFT :: [(HandPoseTypeMSFT, String)] showTableHandPoseTypeMSFT = [ (HAND_POSE_TYPE_TRACKED_MSFT, "TRACKED_MSFT") , ( HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT , "REFERENCE_OPEN_PALM_MSFT" ) ] instance Show HandPoseTypeMSFT where showsPrec = enumShowsPrec enumPrefixHandPoseTypeMSFT showTableHandPoseTypeMSFT conNameHandPoseTypeMSFT (\(HandPoseTypeMSFT x) -> x) (showsPrec 11) instance Read HandPoseTypeMSFT where readPrec = enumReadPrec enumPrefixHandPoseTypeMSFT showTableHandPoseTypeMSFT conNameHandPoseTypeMSFT HandPoseTypeMSFT type MSFT_hand_tracking_mesh_SPEC_VERSION = 2 No documentation found for TopLevel " XR_MSFT_hand_tracking_mesh_SPEC_VERSION " pattern MSFT_hand_tracking_mesh_SPEC_VERSION :: forall a . Integral a => a pattern MSFT_hand_tracking_mesh_SPEC_VERSION = 2 type MSFT_HAND_TRACKING_MESH_EXTENSION_NAME = "XR_MSFT_hand_tracking_mesh" No documentation found for TopLevel " XR_MSFT_HAND_TRACKING_MESH_EXTENSION_NAME " pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME = "XR_MSFT_hand_tracking_mesh"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/openxr/src/OpenXR/Extensions/XR_MSFT_hand_tracking_mesh.hs
haskell
# language CPP # | = Name XR_MSFT_hand_tracking_mesh - instance extension = Specification See <#XR_MSFT_hand_tracking_mesh XR_MSFT_hand_tracking_mesh> in the main specification for complete information. = Registered Extension Number = Revision = Extension and Version Dependencies - Requires @XR_EXT_hand_tracking@ = See Also 'HandMeshIndexBufferMSFT', 'HandMeshMSFT', 'HandMeshSpaceCreateInfoMSFT', 'HandMeshUpdateInfoMSFT', 'updateHandMeshMSFT' = Document Notes For more information, see the <#XR_MSFT_hand_tracking_mesh OpenXR Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly. | xrCreateHandMeshSpaceMSFT - Create a space for hand mesh tracking == Parameter Descriptions = Description A hand mesh space location is specified by runtime preference to effectively represent hand mesh vertices without unnecessary transformations. For example, an optical hand tracking system /can/ define the hand mesh space origin at the depth camera’s optical center. An application should create separate hand mesh space handles for each hand to retrieve the corresponding hand mesh data. The runtime /may/ use the lifetime of this hand mesh space handle to manage the underlying device resources. Therefore, the application /should/ destroy the hand mesh handle after it is finished using the hand mesh. The hand mesh space can be related to other spaces in the session, such as view reference space, or grip action space from the \/interaction_profiles\/khr\/simple_controller interaction profile. The hand mesh space may be not locatable when the hand is outside of the tracking range, or if focus is removed from the application. In these cases, the runtime /must/ not set the 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_POSITION_VALID_BIT' and 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_ORIENTATION_VALID_BIT' bits on calls to 'OpenXR.Core10.Space.locateSpace' with the hand mesh space, and the application /should/ avoid using the returned poses or query for hand mesh data. destroyed, the runtime /must/ continue to support 'OpenXR.Core10.Space.locateSpace' using the hand mesh space, and it /must/ return space location with 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_POSITION_VALID_BIT' and 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_ORIENTATION_VALID_BIT' unset. The application /may/ create a mesh space for the reference hand by setting @handPoseType@ to 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT'. Hand mesh spaces for the reference hand /must/ only be locatable in reference to mesh spaces or joint spaces of the reference hand. == Valid Usage (Implicit) - #VUID-xrCreateHandMeshSpaceMSFT-extension-notenabled# The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to calling 'createHandMeshSpaceMSFT' - #VUID-xrCreateHandMeshSpaceMSFT-handTracker-parameter# @handTracker@ /must/ be a pointer to a valid 'HandMeshSpaceCreateInfoMSFT' structure - #VUID-xrCreateHandMeshSpaceMSFT-space-parameter# @space@ /must/ be a pointer to an 'OpenXR.Core10.Handles.Space' handle == Return Codes [<#fundamentals-successcodes Success>] - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' [<#fundamentals-errorcodes Failure>] - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' - 'OpenXR.Core10.Enums.Result.ERROR_POSE_INVALID' - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' = See Also 'HandMeshSpaceCreateInfoMSFT', 'OpenXR.Core10.Handles.Space' previously created with the | @createInfo@ is the 'HandMeshSpaceCreateInfoMSFT' used to specify the hand mesh space. | A convenience wrapper to make a compatible pair of calls to 'createHandMeshSpaceMSFT' and 'destroySpace' 'Control.Exception.bracket' (or the allocate function from your favourite resource management library) as the last argument. To just extract the pair pass '(,)' as the last argument. | xrUpdateHandMeshMSFT - Update hand mesh buffers == Parameter Descriptions = Description The application /should/ preallocate the index buffer and vertex buffer in 'HandMeshMSFT' using the @maxHandMeshIndexCount@ and The application /should/ preallocate the 'HandMeshMSFT' structure and reuse it for each frame so as to reduce the copies of data when underlying tracking data is not changed. The application should use detect changes and avoid unnecessary data processing when there is no changes. == Valid Usage (Implicit) - #VUID-xrUpdateHandMeshMSFT-extension-notenabled# The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to calling 'updateHandMeshMSFT' - #VUID-xrUpdateHandMeshMSFT-handTracker-parameter# @handTracker@ - #VUID-xrUpdateHandMeshMSFT-updateInfo-parameter# @updateInfo@ /must/ be a pointer to a valid 'HandMeshUpdateInfoMSFT' structure - #VUID-xrUpdateHandMeshMSFT-handMesh-parameter# @handMesh@ /must/ be a pointer to an 'HandMeshMSFT' structure == Return Codes [<#fundamentals-successcodes Success>] - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' [<#fundamentals-errorcodes Failure>] - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' - 'OpenXR.Core10.Enums.Result.ERROR_TIME_INVALID' - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' = See Also 'HandMeshMSFT', 'HandMeshUpdateInfoMSFT', previously created with | @updateInfo@ is a 'HandMeshUpdateInfoMSFT' which contains information to query the hand mesh. | XrHandMeshSpaceCreateInfoMSFT - The information to create a hand mesh space == Valid Usage (Implicit) @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using 'HandMeshSpaceCreateInfoMSFT' - #VUID-XrHandMeshSpaceCreateInfoMSFT-type-type# @type@ /must/ be @NULL@ or a valid pointer to the <#valid-usage-for-structure-pointer-chains next structure in a structure chain> = See Also 'createHandMeshSpaceMSFT' | @handPoseType@ is an 'HandPoseTypeMSFT' used to specify the type of hand this mesh is tracking. Indices and vertices returned from 'updateHandMeshMSFT' for a hand type will be relative to the corresponding space create with the same hand type. position and orientation of the new space’s origin within the natural reference frame of the hand mesh space. | XrHandMeshUpdateInfoMSFT - The information to update a hand mesh == Member Descriptions = Description A runtime /may/ not maintain a full history of hand mesh data, therefore the returned 'HandMeshMSFT' might return data that’s not exactly corresponding to the @time@ input. If the runtime cannot return any tracking data for the given @time@ at all, it /must/ set @isActive@ to 'OpenXR.Core10.FundamentalTypes.FALSE' for the call to 'updateHandMeshMSFT'. Otherwise, if the runtime returns @isActive@ as be valid to use. An application can choose different @handPoseType@ values to query the hand mesh data. The returned hand mesh /must/ be consistent to the hand joint space location on the same 'HandPoseTypeMSFT'. == Valid Usage (Implicit) - #VUID-XrHandMeshUpdateInfoMSFT-extension-notenabled# The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using 'HandMeshUpdateInfoMSFT' - #VUID-XrHandMeshUpdateInfoMSFT-type-type# @type@ /must/ be - #VUID-XrHandMeshUpdateInfoMSFT-next-next# @next@ /must/ be @NULL@ or a valid pointer to the <#valid-usage-for-structure-pointer-chains next structure in a structure chain> - #VUID-XrHandMeshUpdateInfoMSFT-handPoseType-parameter# = See Also <#XrTime >, 'updateHandMeshMSFT' | @time@ is the <#XrTime > that describes the time for which the application wishes to query the hand mesh state. | @handPoseType@ is an 'HandPoseTypeMSFT' which describes the type of hand pose of the hand mesh to update. | XrHandMeshMSFT - The data of a hand mesh == Member Descriptions = Description When the returned @isActive@ value is 'OpenXR.Core10.FundamentalTypes.FALSE', the runtime indicates the hand is not actively tracked, for example, the hand is outside of sensor’s range, or the input focus is taken away from the application. When the runtime returns 'OpenXR.Core10.FundamentalTypes.FALSE' to @isActive@, it 'OpenXR.Core10.FundamentalTypes.FALSE', and /must/ not change the content in @indexBuffer@ or @vertexBuffer@, When the returned @isActive@ value is represented in @indexBuffer@ and @vertexBuffer@ are updated to the latest data of the @time@ given to the 'updateHandMeshMSFT' function. reflect whether the index or vertex buffer’s content are changed during the update. In this way, the application can easily avoid unnecessary processing of buffers when there’s no new data. The hand mesh is represented in triangle lists and each triangle’s vertices are in counter-clockwise order when looking from outside of the hand. When hand tracking is active, i.e. when @isActive@ is returned as @indexBuffer.indexCountOutput@ value /must/ be positive and multiple of == Valid Usage (Implicit) - #VUID-XrHandMeshMSFT-extension-notenabled# The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using 'HandMeshMSFT' - #VUID-XrHandMeshMSFT-type-type# @type@ /must/ be - #VUID-XrHandMeshMSFT-next-next# @next@ /must/ be @NULL@ or a valid pointer to the <#valid-usage-for-structure-pointer-chains next structure in a structure chain> - #VUID-XrHandMeshMSFT-indexBuffer-parameter# @indexBuffer@ /must/ be a valid 'HandMeshIndexBufferMSFT' structure - #VUID-XrHandMeshMSFT-vertexBuffer-parameter# @vertexBuffer@ /must/ be a valid 'HandMeshVertexBufferMSFT' structure = See Also <#XrBool32 >, 'HandMeshIndexBufferMSFT', 'HandMeshVertexBufferMSFT', | @isActive@ is an <#XrBool32 > indicating if the current hand tracker is active. <#XrBool32 > indicating if the @indexBuffer@ content was changed during the update. | @vertexBufferChanged@ is an <#XrBool32 > indicating if the @vertexBuffer@ content was changed during the update. | @indexBuffer@ is an 'HandMeshIndexBufferMSFT' returns the index buffer of the tracked hand mesh. | @vertexBuffer@ is an 'HandMeshVertexBufferMSFT' returns the vertex buffer of the tracked hand mesh. | XrHandMeshIndexBufferMSFT - The index buffer of a hand mesh == Member Descriptions = Description An application /should/ preallocate the indices array using the the application can avoid possible insufficient buffer sizees for each query, and therefore avoid reallocating memory each frame. be @NULL@, or else the runtime /must/ return 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' on calls to the 'updateHandMeshMSFT' function. If the input @indexCapacityInput@ is not sufficient to contain all output indices, the runtime /must/ return If the input @indexCapacityInput@ is equal to or larger than the error on 'updateHandMeshMSFT' because of insufficient index buffer size. sufficient, and hand mesh tracking is active, the runtime /must/ return @indices@. indicating the indices are not changed; or return a new non-zero version. An application /can/ keep the 'HandMeshIndexBufferMSFT' structure for identify different triangle list topology described in @indices@. The application can therefore avoid unnecessary processing of indices, such as coping them to GPU memory. ensures the index buffer has the same mesh topology and allows the application to reason about vertices across different hand pose types. For example, the application /can/ build a procedure to perform UV mapping on vertices of a hand mesh using 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT', and apply the resultant UV data on vertices to the mesh returned from the same hand tracker using 'HAND_POSE_TYPE_TRACKED_MSFT'. == Valid Usage (Implicit) - #VUID-XrHandMeshIndexBufferMSFT-extension-notenabled# The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using 'HandMeshIndexBufferMSFT' - #VUID-XrHandMeshIndexBufferMSFT-indexCapacityInput-arraylength# The = See Also 'HandMeshMSFT' index buffer content or 0 to indicate a request to retrieve the latest indices regardless of existing content in @indices@. count of indices written in @indices@. the indices of the triangles list in the vertex buffer. | XrHandMeshVertexBufferMSFT - The vertex buffer of a hand mesh == Member Descriptions = Description An application /should/ preallocate the vertices array using the the application can avoid possible insufficient buffer sizes for each query, and therefore avoid reallocating memory each frame. The input @vertexCapacityInput@ /must/ not be 0, and @vertices@ /must/ not be @NULL@, or else the runtime /must/ return 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' on calls to the 'updateHandMeshMSFT' function. If the input @vertexCapacityInput@ is not sufficient to contain all output vertices, the runtime /must/ return @vertices@, and return 0 for @vertexCountOutput@. If the input @vertexCapacityInput@ is equal to or larger than the buffer size. array is sufficient, and hand mesh tracking is active, the runtime /must/ return the latest non-zero @vertexUpdateTime@, and fill in the @vertexCountOutput@ and @vertices@ fields. @vertices@, and return 'OpenXR.Core10.FundamentalTypes.FALSE' for @vertexBufferChanged@ indicating the vertices are not changed; or return @vertexCountOutput@ and @vertices@ and return indicating the vertices are updated to a newer version. An application /can/ keep the 'HandMeshVertexBufferMSFT' structure for detect the changes of the content in @vertices@. The application can therefore avoid unnecessary processing of vertices, such as coping them to GPU memory. == Valid Usage (Implicit) - #VUID-XrHandMeshVertexBufferMSFT-extension-notenabled# The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using 'HandMeshVertexBufferMSFT' - #VUID-XrHandMeshVertexBufferMSFT-vertices-parameter# @vertices@ /must/ be a pointer to an array of @vertexCapacityInput@ = See Also <#XrTime > | @vertexUpdateTime@ is an <#XrTime > representing the time when the runtime receives the vertex buffer content or 0 to indicate a request to retrieve latest vertices regardless of existing content in @vertices@. the @vertices@ array. count of vertices written in @vertices@. specifying the vertices of the hand mesh including the position and normal vector in the hand mesh space. | XrHandMeshVertexMSFT - The vertex of hand mesh == Valid Usage (Implicit) @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to = See Also the position of the vertex in the hand mesh space, measured in meters. unweighted normal of the triangle surface at the vertex as a unit vector in hand mesh space. tracking mesh == Member Descriptions = Description If a runtime returns 'OpenXR.Core10.FundamentalTypes.FALSE' for @supportsHandTrackingMesh@, the system does not support hand tracking mesh input, and therefore /must/ return 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' from 'createHandMeshSpaceMSFT' and 'updateHandMeshMSFT'. The application /should/ avoid using hand mesh functionality when @supportsHandTrackingMesh@ is 'OpenXR.Core10.FundamentalTypes.FALSE'. If a runtime returns 'OpenXR.Core10.FundamentalTypes.TRUE' for @supportsHandTrackingMesh@, the system supports hand tracking mesh input. In this case, the runtime /must/ return a positive number for @maxHandMeshIndexCount@ and @maxHandMeshVertexCount@. An application preallocate hand mesh buffers and reuse them in their render loop when calling 'updateHandMeshMSFT' every frame. == Valid Usage (Implicit) The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior /must/ be /must/ be @NULL@ or a valid pointer to the <#valid-usage-for-structure-pointer-chains next structure in a structure chain> = See Also <#XrBool32 >, | @supportsHandTrackingMesh@ is an <#XrBool32 >, indicating if current system is capable of hand tracking mesh input. indices that will be returned from the hand tracker. vertices that will be returned from the hand tracker. | XrHandPoseTypeInfoMSFT - Describes what hand pose type for the hand joint tracking. == Valid Usage (Implicit) - #VUID-XrHandPoseTypeInfoMSFT-extension-notenabled# The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to using 'HandPoseTypeInfoMSFT' - #VUID-XrHandPoseTypeInfoMSFT-type-type# @type@ /must/ be - #VUID-XrHandPoseTypeInfoMSFT-next-next# @next@ /must/ be @NULL@ or a valid pointer to the <#valid-usage-for-structure-pointer-chains next structure in a structure chain> = See Also | @handPoseType@ is an 'HandPoseTypeMSFT' that describes the type of hand pose of the hand tracking. | XrHandPoseTypeMSFT - Describe type of input hand pose user’s actual hand motion. When the hand tracking input requires the user to be holding a controller in their hand, the hand tracking input will appear as the user virtually holding the controller. This input can be used to render the hand shape together with the controller in hand. the user’s actual hand. Through this reference hand pose, an application /can/ get a stable hand joint and mesh that has the same mesh topology as the tracked hand mesh using the same apply the data computed from a reference hand pose to the corresponding tracked hand. Although a reference hand pose does not move with user’s hand motion, the bone length and hand thickness /may/ be updated, for example when tracking result refines, or a different user’s hand is detected. The application /should/ update reference hand joints and meshes when the returned from 'updateHandMeshMSFT' changes from 'OpenXR.Core10.FundamentalTypes.FALSE' to avoid unnecessary CPU or GPU work to process the neutral hand inputs. = See Also 'HandMeshSpaceCreateInfoMSFT', 'HandMeshUpdateInfoMSFT', 'HandPoseTypeInfoMSFT' | 'HAND_POSE_TYPE_TRACKED_MSFT' represents a hand pose provided by actual tracking of the user’s hand. | 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT' represents a stable reference hand pose in a relaxed open hand shape. # COMPLETE HAND_POSE_TYPE_TRACKED_MSFT , HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT :: HandPoseTypeMSFT #
53 2 - Requires OpenXR 1.0 ' HandMeshVertexBufferMSFT ' , ' HandMeshVertexMSFT ' , ' HandPoseTypeInfoMSFT ' , ' HandPoseTypeMSFT ' , ' SystemHandTrackingMeshPropertiesMSFT ' , ' createHandMeshSpaceMSFT ' , module OpenXR.Extensions.XR_MSFT_hand_tracking_mesh ( createHandMeshSpaceMSFT , withHandMeshSpaceMSFT , updateHandMeshMSFT , HandMeshSpaceCreateInfoMSFT(..) , HandMeshUpdateInfoMSFT(..) , HandMeshMSFT(..) , HandMeshIndexBufferMSFT(..) , HandMeshVertexBufferMSFT(..) , HandMeshVertexMSFT(..) , SystemHandTrackingMeshPropertiesMSFT(..) , HandPoseTypeInfoMSFT(..) , HandPoseTypeMSFT( HAND_POSE_TYPE_TRACKED_MSFT , HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT , .. ) , MSFT_hand_tracking_mesh_SPEC_VERSION , pattern MSFT_hand_tracking_mesh_SPEC_VERSION , MSFT_HAND_TRACKING_MESH_EXTENSION_NAME , pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME , HandTrackerEXT(..) ) where import OpenXR.Internal.Utils (enumReadPrec) import OpenXR.Internal.Utils (enumShowsPrec) import OpenXR.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showsPrec) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import OpenXR.CStruct (FromCStruct) import OpenXR.CStruct (FromCStruct(..)) import OpenXR.CStruct (ToCStruct) import OpenXR.CStruct (ToCStruct(..)) import OpenXR.Zero (Zero) import OpenXR.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Data.Int (Int32) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import OpenXR.Core10.FundamentalTypes (bool32ToBool) import OpenXR.Core10.FundamentalTypes (boolToBool32) import OpenXR.Core10.Space (destroySpace) import OpenXR.Core10.FundamentalTypes (Bool32) import OpenXR.Extensions.Handles (HandTrackerEXT) import OpenXR.Extensions.Handles (HandTrackerEXT(..)) import OpenXR.Extensions.Handles (HandTrackerEXT(HandTrackerEXT)) import OpenXR.Extensions.Handles (HandTrackerEXT_T) import OpenXR.Dynamic (InstanceCmds(pXrCreateHandMeshSpaceMSFT)) import OpenXR.Dynamic (InstanceCmds(pXrUpdateHandMeshMSFT)) import OpenXR.Exception (OpenXrException(..)) import OpenXR.Core10.Space (Posef) import OpenXR.Core10.Enums.Result (Result) import OpenXR.Core10.Enums.Result (Result(..)) import OpenXR.Core10.Handles (Space) import OpenXR.Core10.Handles (Space(Space)) import OpenXR.Core10.Handles (Space_T) import OpenXR.Core10.Enums.StructureType (StructureType) import OpenXR.Core10.FundamentalTypes (Time) import OpenXR.Core10.Space (Vector3f) import OpenXR.Core10.Enums.Result (Result(SUCCESS)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_UPDATE_INFO_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_POSE_TYPE_INFO_MSFT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT)) import OpenXR.Extensions.Handles (HandTrackerEXT(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrCreateHandMeshSpaceMSFT :: FunPtr (Ptr HandTrackerEXT_T -> Ptr HandMeshSpaceCreateInfoMSFT -> Ptr (Ptr Space_T) -> IO Result) -> Ptr HandTrackerEXT_T -> Ptr HandMeshSpaceCreateInfoMSFT -> Ptr (Ptr Space_T) -> IO Result If the underlying ' . Handles . ' is /must/ be a valid ' . Handles . ' handle - # VUID - xrCreateHandMeshSpaceMSFT - createInfo - parameter # @createInfo@ - ' OpenXR.Core10.Enums . Result . SUCCESS ' - ' OpenXR.Core10.Enums . Result . ' ' . Handles . ' , createHandMeshSpaceMSFT :: forall io . (MonadIO io) | @handTracker@ is an ' OpenXR.Extensions . Handles . ' handle ' . ' function . HandTrackerEXT HandMeshSpaceCreateInfoMSFT -> io (Result, Space) createHandMeshSpaceMSFT handTracker createInfo = liftIO . evalContT $ do let cmds = case handTracker of HandTrackerEXT{instanceCmds} -> instanceCmds let xrCreateHandMeshSpaceMSFTPtr = pXrCreateHandMeshSpaceMSFT cmds lift $ unless (xrCreateHandMeshSpaceMSFTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrCreateHandMeshSpaceMSFT is null" Nothing Nothing let xrCreateHandMeshSpaceMSFT' = mkXrCreateHandMeshSpaceMSFT xrCreateHandMeshSpaceMSFTPtr createInfo' <- ContT $ withCStruct (createInfo) pSpace <- ContT $ bracket (callocBytes @(Ptr Space_T) 8) free r <- lift $ traceAroundEvent "xrCreateHandMeshSpaceMSFT" (xrCreateHandMeshSpaceMSFT' (handTrackerEXTHandle (handTracker)) createInfo' (pSpace)) lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) space <- lift $ peek @(Ptr Space_T) pSpace pure $ (r, ((\h -> Space h cmds ) space)) To ensure that ' ' is always called : pass withHandMeshSpaceMSFT :: forall io r . MonadIO io => HandTrackerEXT -> HandMeshSpaceCreateInfoMSFT -> (io (Result, Space) -> ((Result, Space) -> io ()) -> r) -> r withHandMeshSpaceMSFT handTracker createInfo b = b (createHandMeshSpaceMSFT handTracker createInfo) (\(_, o1) -> destroySpace o1) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrUpdateHandMeshMSFT :: FunPtr (Ptr HandTrackerEXT_T -> Ptr HandMeshUpdateInfoMSFT -> Ptr HandMeshMSFT -> IO Result) -> Ptr HandTrackerEXT_T -> Ptr HandMeshUpdateInfoMSFT -> Ptr HandMeshMSFT -> IO Result @maxHandMeshVertexCount@ from the ' SystemHandTrackingMeshPropertiesMSFT ' returned from the ' OpenXR.Core10.Device.getSystemProperties ' function . @indexBufferChanged@ and @vertexBufferChanged@ in ' HandMeshMSFT ' to /must/ be a valid ' . Handles . ' handle - ' OpenXR.Core10.Enums . Result . SUCCESS ' - ' OpenXR.Core10.Enums . Result . ' - ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' ' . Handles . ' updateHandMeshMSFT :: forall io . (MonadIO io) | @handTracker@ is an ' OpenXR.Extensions . Handles . ' handle ' . ' . HandTrackerEXT HandMeshUpdateInfoMSFT -> io (Result, HandMeshMSFT) updateHandMeshMSFT handTracker updateInfo = liftIO . evalContT $ do let xrUpdateHandMeshMSFTPtr = pXrUpdateHandMeshMSFT (case handTracker of HandTrackerEXT{instanceCmds} -> instanceCmds) lift $ unless (xrUpdateHandMeshMSFTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrUpdateHandMeshMSFT is null" Nothing Nothing let xrUpdateHandMeshMSFT' = mkXrUpdateHandMeshMSFT xrUpdateHandMeshMSFTPtr updateInfo' <- ContT $ withCStruct (updateInfo) pHandMesh <- ContT (withZeroCStruct @HandMeshMSFT) r <- lift $ traceAroundEvent "xrUpdateHandMeshMSFT" (xrUpdateHandMeshMSFT' (handTrackerEXTHandle (handTracker)) updateInfo' (pHandMesh)) lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) handMesh <- lift $ peekCStruct @HandMeshMSFT pHandMesh pure $ (r, handMesh) - # VUID - XrHandMeshSpaceCreateInfoMSFT - extension - notenabled # The ' OpenXR.Core10.Enums . StructureType . ' - # VUID - XrHandMeshSpaceCreateInfoMSFT - next - next # @next@ /must/ be - # VUID - XrHandMeshSpaceCreateInfoMSFT - handPoseType - parameter # @handPoseType@ /must/ be a valid ' HandPoseTypeMSFT ' value ' HandPoseTypeMSFT ' , ' OpenXR.Core10.Space . ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' , data HandMeshSpaceCreateInfoMSFT = HandMeshSpaceCreateInfoMSFT handPoseType :: HandPoseTypeMSFT | @poseInHandMeshSpace@ is an ' OpenXR.Core10.Space . ' defining the poseInHandMeshSpace :: Posef } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshSpaceCreateInfoMSFT) #endif deriving instance Show HandMeshSpaceCreateInfoMSFT instance ToCStruct HandMeshSpaceCreateInfoMSFT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshSpaceCreateInfoMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (handPoseType) poke ((p `plusPtr` 20 :: Ptr Posef)) (poseInHandMeshSpace) f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (zero) poke ((p `plusPtr` 20 :: Ptr Posef)) (zero) f instance FromCStruct HandMeshSpaceCreateInfoMSFT where peekCStruct p = do handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) poseInHandMeshSpace <- peekCStruct @Posef ((p `plusPtr` 20 :: Ptr Posef)) pure $ HandMeshSpaceCreateInfoMSFT handPoseType poseInHandMeshSpace instance Storable HandMeshSpaceCreateInfoMSFT where sizeOf ~_ = 48 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshSpaceCreateInfoMSFT where zero = HandMeshSpaceCreateInfoMSFT zero zero ' OpenXR.Core10.FundamentalTypes . TRUE ' , the data in ' HandMeshMSFT ' must ' . Handles . ' when using the same ' OpenXR.Core10.Enums . StructureType . TYPE_HAND_MESH_UPDATE_INFO_MSFT ' @handPoseType@ /must/ be a valid ' HandPoseTypeMSFT ' value ' HandPoseTypeMSFT ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' , data HandMeshUpdateInfoMSFT = HandMeshUpdateInfoMSFT time :: Time handPoseType :: HandPoseTypeMSFT } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshUpdateInfoMSFT) #endif deriving instance Show HandMeshUpdateInfoMSFT instance ToCStruct HandMeshUpdateInfoMSFT where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshUpdateInfoMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_UPDATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Time)) (time) poke ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) (handPoseType) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_UPDATE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Time)) (zero) poke ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) (zero) f instance FromCStruct HandMeshUpdateInfoMSFT where peekCStruct p = do time <- peek @Time ((p `plusPtr` 16 :: Ptr Time)) handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) pure $ HandMeshUpdateInfoMSFT time handPoseType instance Storable HandMeshUpdateInfoMSFT where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshUpdateInfoMSFT where zero = HandMeshUpdateInfoMSFT zero zero /must/ set @indexBufferChanged@ and @vertexBufferChanged@ to ' OpenXR.Core10.FundamentalTypes . TRUE ' , the hand tracking mesh The runtime /must/ set @indexBufferChanged@ and @vertexBufferChanged@ to ' OpenXR.Core10.FundamentalTypes . TRUE ' , the returned 3 , and @vertexBuffer.vertexCountOutput@ value /must/ be equal to or larger than 3 . ' OpenXR.Core10.Enums . StructureType . TYPE_HAND_MESH_MSFT ' ' OpenXR.Core10.Enums . StructureType . StructureType ' , ' updateHandMeshMSFT ' data HandMeshMSFT = HandMeshMSFT isActive :: Bool | @indexBufferChanged@ is an indexBufferChanged :: Bool vertexBufferChanged :: Bool indexBuffer :: HandMeshIndexBufferMSFT vertexBuffer :: HandMeshVertexBufferMSFT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshMSFT) #endif deriving instance Show HandMeshMSFT instance ToCStruct HandMeshMSFT where withCStruct x f = allocaBytes 80 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (isActive)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (indexBufferChanged)) poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (vertexBufferChanged)) poke ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) (indexBuffer) poke ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) (vertexBuffer) f cStructSize = 80 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) (zero) poke ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) (zero) f instance FromCStruct HandMeshMSFT where peekCStruct p = do isActive <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) indexBufferChanged <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32)) vertexBufferChanged <- peek @Bool32 ((p `plusPtr` 24 :: Ptr Bool32)) indexBuffer <- peekCStruct @HandMeshIndexBufferMSFT ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) vertexBuffer <- peekCStruct @HandMeshVertexBufferMSFT ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) pure $ HandMeshMSFT (bool32ToBool isActive) (bool32ToBool indexBufferChanged) (bool32ToBool vertexBufferChanged) indexBuffer vertexBuffer instance Storable HandMeshMSFT where sizeOf ~_ = 80 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshMSFT where zero = HandMeshMSFT zero zero zero zero zero @maxHandMeshIndexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' . In this way , The input @indexCapacityInput@ /must/ not be 0 , and @indices@ /must/ not ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' on calls to ' updateHandMeshMSFT ' , not change the content in @indexBufferKey@ and @indices@ , and return 0 for @indexCountOutput@. @maxHandMeshIndexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' , the runtime /must/ not return ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' If the input @indexBufferKey@ is 0 , the capacity of indices array is the latest non - zero @indexBufferKey@ , and fill in @indexCountOutput@ and If the input @indexBufferKey@ is not 0 , the runtime /can/ either return without changing @indexCountOutput@ or content in @indices@ , and return ' OpenXR.Core10.FundamentalTypes . FALSE ' for @indexBufferChanged@ @indexBufferKey@ and fill in latest data in @indexCountOutput@ and @indices@ , and return ' OpenXR.Core10.FundamentalTypes . TRUE ' for @indexBufferChanged@ indicating the indices are updated to a newer each frame in a frame loop and use the returned @indexBufferKey@ to The runtime /must/ return the same @indexBufferKey@ for the same ' . Handles . ' at a given time , regardless of the input ' HandPoseTypeMSFT ' in ' HandMeshUpdateInfoMSFT ' . This - # VUID - XrHandMeshIndexBufferMSFT - indices - parameter # @indices@ /must/ be a pointer to an array of @indexCapacityInput@ values @indexCapacityInput@ parameter /must/ be greater than @0@ data HandMeshIndexBufferMSFT = HandMeshIndexBufferMSFT | @indexBufferKey@ is a @uint32_t@ serving as the key of the returned indexBufferKey :: Word32 | @indexCapacityInput@ is a positive @uint32_t@ describes the capacity of the @indices@ array . indexCapacityInput :: Word32 | @indexCountOutput@ is a returned by the runtime with the indexCountOutput :: Word32 | @indices@ is an array of indices filled in by the runtime , specifying indices :: Ptr Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshIndexBufferMSFT) #endif deriving instance Show HandMeshIndexBufferMSFT instance ToCStruct HandMeshIndexBufferMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshIndexBufferMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr Word32)) (indexBufferKey) poke ((p `plusPtr` 4 :: Ptr Word32)) (indexCapacityInput) poke ((p `plusPtr` 8 :: Ptr Word32)) (indexCountOutput) poke ((p `plusPtr` 16 :: Ptr (Ptr Word32))) (indices) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 4 :: Ptr Word32)) (zero) poke ((p `plusPtr` 16 :: Ptr (Ptr Word32))) (zero) f instance FromCStruct HandMeshIndexBufferMSFT where peekCStruct p = do indexBufferKey <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32)) indexCapacityInput <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32)) indexCountOutput <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32)) indices <- peek @(Ptr Word32) ((p `plusPtr` 16 :: Ptr (Ptr Word32))) pure $ HandMeshIndexBufferMSFT indexBufferKey indexCapacityInput indexCountOutput indices instance Storable HandMeshIndexBufferMSFT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshIndexBufferMSFT where zero = HandMeshIndexBufferMSFT zero zero zero zero @maxHandMeshVertexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' . In this way , ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' on calls to the ' updateHandMeshMSFT ' , do not change content in @vertexUpdateTime@ and @maxHandMeshVertexCount@ in ' SystemHandTrackingMeshPropertiesMSFT ' returned from ' OpenXR.Core10.Device.getSystemProperties ' , the runtime /must/ not return ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' on calls to the ' updateHandMeshMSFT ' because of insufficient vertex If the input @vertexUpdateTime@ is 0 , and the capacity of the vertices If the input @vertexUpdateTime@ is not 0 , the runtime /can/ either return without changing or the content in a new non - zero @vertexUpdateTime@ and fill in latest data in ' OpenXR.Core10.FundamentalTypes . TRUE ' for @vertexBufferChanged@ each frame in frame loop and use the returned @vertexUpdateTime@ to ' HandMeshVertexMSFT ' structures - # VUID - XrHandMeshVertexBufferMSFT - vertexCapacityInput - arraylength # The @vertexCapacityInput@ parameter /must/ be greater than @0@ ' HandMeshMSFT ' , ' HandMeshVertexMSFT ' , data HandMeshVertexBufferMSFT = HandMeshVertexBufferMSFT vertexUpdateTime :: Time | @vertexCapacityInput@ is a positive @uint32_t@ describes the capacity of vertexCapacityInput :: Word32 | @vertexCountOutput@ is a filled in by the runtime with the vertexCountOutput :: Word32 | @vertices@ is an array of ' HandMeshVertexMSFT ' filled in by the runtime , vertices :: Ptr HandMeshVertexMSFT } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshVertexBufferMSFT) #endif deriving instance Show HandMeshVertexBufferMSFT instance ToCStruct HandMeshVertexBufferMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshVertexBufferMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr Time)) (vertexUpdateTime) poke ((p `plusPtr` 8 :: Ptr Word32)) (vertexCapacityInput) poke ((p `plusPtr` 12 :: Ptr Word32)) (vertexCountOutput) poke ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) (vertices) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 8 :: Ptr Word32)) (zero) poke ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) (zero) f instance FromCStruct HandMeshVertexBufferMSFT where peekCStruct p = do vertexUpdateTime <- peek @Time ((p `plusPtr` 0 :: Ptr Time)) vertexCapacityInput <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32)) vertexCountOutput <- peek @Word32 ((p `plusPtr` 12 :: Ptr Word32)) vertices <- peek @(Ptr HandMeshVertexMSFT) ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) pure $ HandMeshVertexBufferMSFT vertexUpdateTime vertexCapacityInput vertexCountOutput vertices instance Storable HandMeshVertexBufferMSFT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshVertexBufferMSFT where zero = HandMeshVertexBufferMSFT zero zero zero zero - # VUID - XrHandMeshVertexMSFT - extension - notenabled # The using ' HandMeshVertexMSFT ' ' HandMeshVertexBufferMSFT ' , ' OpenXR.Core10.Space . ' data HandMeshVertexMSFT = HandMeshVertexMSFT | @position@ is an ' OpenXR.Core10.Space . ' structure representing position :: Vector3f | @normal@ is an ' OpenXR.Core10.Space . ' structure representing the normal :: Vector3f } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandMeshVertexMSFT) #endif deriving instance Show HandMeshVertexMSFT instance ToCStruct HandMeshVertexMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandMeshVertexMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr Vector3f)) (position) poke ((p `plusPtr` 12 :: Ptr Vector3f)) (normal) f cStructSize = 24 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr Vector3f)) (zero) poke ((p `plusPtr` 12 :: Ptr Vector3f)) (zero) f instance FromCStruct HandMeshVertexMSFT where peekCStruct p = do position <- peekCStruct @Vector3f ((p `plusPtr` 0 :: Ptr Vector3f)) normal <- peekCStruct @Vector3f ((p `plusPtr` 12 :: Ptr Vector3f)) pure $ HandMeshVertexMSFT position normal instance Storable HandMeshVertexMSFT where sizeOf ~_ = 24 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandMeshVertexMSFT where zero = HandMeshVertexMSFT zero zero | XrSystemHandTrackingMeshPropertiesMSFT - System property for hand /should/ use @maxHandMeshIndexCount@ and @maxHandMeshVertexCount@ to - # VUID - XrSystemHandTrackingMeshPropertiesMSFT - extension - notenabled # to using ' SystemHandTrackingMeshPropertiesMSFT ' - # VUID - XrSystemHandTrackingMeshPropertiesMSFT - type - type # @type@ ' OpenXR.Core10.Enums . StructureType . TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT ' - # VUID - XrSystemHandTrackingMeshPropertiesMSFT - next - next # @next@ ' OpenXR.Core10.Enums . StructureType . StructureType ' data SystemHandTrackingMeshPropertiesMSFT = SystemHandTrackingMeshPropertiesMSFT supportsHandTrackingMesh :: Bool | @maxHandMeshIndexCount@ is a @uint32_t@ returns the maximum count of maxHandMeshIndexCount :: Word32 | @maxHandMeshVertexCount@ is a @uint32_t@ returns the maximum count of maxHandMeshVertexCount :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SystemHandTrackingMeshPropertiesMSFT) #endif deriving instance Show SystemHandTrackingMeshPropertiesMSFT instance ToCStruct SystemHandTrackingMeshPropertiesMSFT where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p SystemHandTrackingMeshPropertiesMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (supportsHandTrackingMesh)) poke ((p `plusPtr` 20 :: Ptr Word32)) (maxHandMeshIndexCount) poke ((p `plusPtr` 24 :: Ptr Word32)) (maxHandMeshVertexCount) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Word32)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) f instance FromCStruct SystemHandTrackingMeshPropertiesMSFT where peekCStruct p = do supportsHandTrackingMesh <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) maxHandMeshIndexCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) maxHandMeshVertexCount <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) pure $ SystemHandTrackingMeshPropertiesMSFT (bool32ToBool supportsHandTrackingMesh) maxHandMeshIndexCount maxHandMeshVertexCount instance Storable SystemHandTrackingMeshPropertiesMSFT where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SystemHandTrackingMeshPropertiesMSFT where zero = SystemHandTrackingMeshPropertiesMSFT zero zero zero ' OpenXR.Core10.Enums . StructureType . TYPE_HAND_POSE_TYPE_INFO_MSFT ' - # VUID - XrHandPoseTypeInfoMSFT - handPoseType - parameter # @handPoseType@ /must/ be a valid ' HandPoseTypeMSFT ' value ' HandPoseTypeMSFT ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' data HandPoseTypeInfoMSFT = HandPoseTypeInfoMSFT handPoseType :: HandPoseTypeMSFT } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (HandPoseTypeInfoMSFT) #endif deriving instance Show HandPoseTypeInfoMSFT instance ToCStruct HandPoseTypeInfoMSFT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p HandPoseTypeInfoMSFT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_POSE_TYPE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (handPoseType) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_POSE_TYPE_INFO_MSFT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (zero) f instance FromCStruct HandPoseTypeInfoMSFT where peekCStruct p = do handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) pure $ HandPoseTypeInfoMSFT handPoseType instance Storable HandPoseTypeInfoMSFT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HandPoseTypeInfoMSFT where zero = HandPoseTypeInfoMSFT zero = = The ' HAND_POSE_TYPE_TRACKED_MSFT ' input provides best fidelity to the The ' HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT ' input does not move with ' . Handles . ' , so that the application can tracked mesh ’s @indexBufferKey@ is changed or when the @isActive@ value ' OpenXR.Core10.FundamentalTypes . TRUE ' . It can use the returned @indexBufferKey@ and @vertexUpdateTime@ from ' updateHandMeshMSFT ' to newtype HandPoseTypeMSFT = HandPoseTypeMSFT Int32 deriving newtype (Eq, Ord, Storable, Zero) pattern HAND_POSE_TYPE_TRACKED_MSFT = HandPoseTypeMSFT 0 pattern HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT = HandPoseTypeMSFT 1 conNameHandPoseTypeMSFT :: String conNameHandPoseTypeMSFT = "HandPoseTypeMSFT" enumPrefixHandPoseTypeMSFT :: String enumPrefixHandPoseTypeMSFT = "HAND_POSE_TYPE_" showTableHandPoseTypeMSFT :: [(HandPoseTypeMSFT, String)] showTableHandPoseTypeMSFT = [ (HAND_POSE_TYPE_TRACKED_MSFT, "TRACKED_MSFT") , ( HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT , "REFERENCE_OPEN_PALM_MSFT" ) ] instance Show HandPoseTypeMSFT where showsPrec = enumShowsPrec enumPrefixHandPoseTypeMSFT showTableHandPoseTypeMSFT conNameHandPoseTypeMSFT (\(HandPoseTypeMSFT x) -> x) (showsPrec 11) instance Read HandPoseTypeMSFT where readPrec = enumReadPrec enumPrefixHandPoseTypeMSFT showTableHandPoseTypeMSFT conNameHandPoseTypeMSFT HandPoseTypeMSFT type MSFT_hand_tracking_mesh_SPEC_VERSION = 2 No documentation found for TopLevel " XR_MSFT_hand_tracking_mesh_SPEC_VERSION " pattern MSFT_hand_tracking_mesh_SPEC_VERSION :: forall a . Integral a => a pattern MSFT_hand_tracking_mesh_SPEC_VERSION = 2 type MSFT_HAND_TRACKING_MESH_EXTENSION_NAME = "XR_MSFT_hand_tracking_mesh" No documentation found for TopLevel " XR_MSFT_HAND_TRACKING_MESH_EXTENSION_NAME " pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME = "XR_MSFT_hand_tracking_mesh"
8c2cbf511221c260417e6c0df70dce11c54186723cf59e3a0e1a0913ad5e0d99
openvstorage/alba
maintenance_config.ml
Copyright ( C ) iNuron - This file is part of Open vStorage . For license information , see < LICENSE.txt > Copyright (C) iNuron - This file is part of Open vStorage. For license information, see <LICENSE.txt> *) open! Prelude type redis_lru_cache_eviction = { host : string; port : int; key : string; } [@@deriving yojson, show] let redis_lru_cache_eviction_from_buffer buf = let host = Llio.string_from buf in let port = Llio.int_from buf in let key = Llio.string_from buf in { host; port; key; } let redis_lru_cache_eviction_to_buffer buf { host; port; key; } = Llio.string_to buf host; Llio.int_to buf port; Llio.string_to buf key type t = { enable_auto_repair : bool; auto_repair_timeout_seconds : float; auto_repair_disabled_nodes : string list; enable_rebalance : bool; cache_eviction_prefix_preset_pairs : (string, string) Hashtbl.t; redis_lru_cache_eviction : redis_lru_cache_eviction option; } [@@deriving yojson] let show t = to_yojson t |> Yojson.Safe.pretty_to_string let get_prefixes t = Hashtbl.fold (fun prefix _ acc -> prefix :: acc) t.cache_eviction_prefix_preset_pairs [] let from_buffer buf = let ser_version = Llio.int8_from buf in assert (ser_version = 1); let enable_auto_repair = Llio.bool_from buf in let auto_repair_timeout_seconds = Llio.float_from buf in let auto_repair_disabled_nodes = Llio.list_from Llio.string_from buf in let enable_rebalance = Llio.bool_from buf in let cache_eviction_prefix_preset_pairs = maybe_from_buffer (Llio.hashtbl_from (Llio.pair_from Llio.string_from Llio.string_from)) (Hashtbl.create 0) buf in let redis_lru_cache_eviction = maybe_from_buffer (Llio.option_from redis_lru_cache_eviction_from_buffer) None buf in { enable_auto_repair; auto_repair_timeout_seconds; auto_repair_disabled_nodes; enable_rebalance; cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction; } let to_buffer buf { enable_auto_repair; auto_repair_timeout_seconds; auto_repair_disabled_nodes; enable_rebalance; cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction; } = Llio.int8_to buf 1; Llio.bool_to buf enable_auto_repair; Llio.float_to buf auto_repair_timeout_seconds; Llio.list_to Llio.string_to buf auto_repair_disabled_nodes; Llio.bool_to buf enable_rebalance; Llio.hashtbl_to Llio.string_to Llio.string_to buf cache_eviction_prefix_preset_pairs; Llio.option_to redis_lru_cache_eviction_to_buffer buf redis_lru_cache_eviction module Update = struct type t = { enable_auto_repair' : bool option; auto_repair_timeout_seconds' : float option; auto_repair_add_disabled_nodes : string list; auto_repair_remove_disabled_nodes : string list; enable_rebalance' : bool option; add_cache_eviction_prefix_preset_pairs : (string * string) list; remove_cache_eviction_prefix_preset_pairs : string list; redis_lru_cache_eviction' : redis_lru_cache_eviction option; } let from_buffer buf = let ser_version = Llio.int8_from buf in assert (ser_version = 1); let enable_auto_repair' = Llio.option_from Llio.bool_from buf in let auto_repair_timeout_seconds' = Llio.option_from Llio.float_from buf in let auto_repair_remove_disabled_nodes = Llio.list_from Llio.string_from buf in let auto_repair_add_disabled_nodes = Llio.list_from Llio.string_from buf in let enable_rebalance' = Llio.option_from Llio.bool_from buf in let add_cache_eviction_prefix_preset_pairs, remove_cache_eviction_prefix_preset_pairs = maybe_from_buffer (Llio.pair_from (Llio.list_from (Llio.pair_from Llio.string_from Llio.string_from)) (Llio.list_from Llio.string_from)) ([], []) buf in let redis_lru_cache_eviction' = maybe_from_buffer (Llio.option_from redis_lru_cache_eviction_from_buffer) None buf in { enable_auto_repair'; auto_repair_timeout_seconds'; auto_repair_remove_disabled_nodes; auto_repair_add_disabled_nodes; enable_rebalance'; add_cache_eviction_prefix_preset_pairs; remove_cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction'; } let to_buffer buf { enable_auto_repair'; auto_repair_timeout_seconds'; auto_repair_remove_disabled_nodes; auto_repair_add_disabled_nodes; enable_rebalance'; add_cache_eviction_prefix_preset_pairs; remove_cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction'; } = Llio.int8_to buf 1; Llio.option_to Llio.bool_to buf enable_auto_repair'; Llio.option_to Llio.float_to buf auto_repair_timeout_seconds'; Llio.list_to Llio.string_to buf auto_repair_remove_disabled_nodes; Llio.list_to Llio.string_to buf auto_repair_add_disabled_nodes; Llio.option_to Llio.bool_to buf enable_rebalance'; Llio.list_to (Llio.pair_to Llio.string_to Llio.string_to) buf add_cache_eviction_prefix_preset_pairs; Llio.list_to Llio.string_to buf remove_cache_eviction_prefix_preset_pairs; Llio.option_to redis_lru_cache_eviction_to_buffer buf redis_lru_cache_eviction' let apply { enable_auto_repair; auto_repair_timeout_seconds; auto_repair_disabled_nodes; enable_rebalance; cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction; } { enable_auto_repair'; auto_repair_timeout_seconds'; auto_repair_remove_disabled_nodes; auto_repair_add_disabled_nodes; enable_rebalance'; add_cache_eviction_prefix_preset_pairs; remove_cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction'; } = { enable_auto_repair = Option.get_some_default enable_auto_repair enable_auto_repair'; auto_repair_timeout_seconds = Option.get_some_default auto_repair_timeout_seconds auto_repair_timeout_seconds'; auto_repair_disabled_nodes = List.filter (fun node -> not (List.mem node auto_repair_remove_disabled_nodes)) (List.rev_append auto_repair_add_disabled_nodes auto_repair_disabled_nodes); enable_rebalance = Option.get_some_default enable_rebalance enable_rebalance'; cache_eviction_prefix_preset_pairs = (let () = List.iter (fun prefix -> Hashtbl.remove cache_eviction_prefix_preset_pairs prefix) remove_cache_eviction_prefix_preset_pairs in let () = List.iter (fun (prefix, preset) -> Hashtbl.replace cache_eviction_prefix_preset_pairs prefix preset) add_cache_eviction_prefix_preset_pairs in cache_eviction_prefix_preset_pairs); redis_lru_cache_eviction = (match redis_lru_cache_eviction' with | Some x -> Some x | None -> redis_lru_cache_eviction); } end
null
https://raw.githubusercontent.com/openvstorage/alba/459bd459335138d6b282d332fcff53a1b4300c29/ocaml/src/maintenance_config.ml
ocaml
Copyright ( C ) iNuron - This file is part of Open vStorage . For license information , see < LICENSE.txt > Copyright (C) iNuron - This file is part of Open vStorage. For license information, see <LICENSE.txt> *) open! Prelude type redis_lru_cache_eviction = { host : string; port : int; key : string; } [@@deriving yojson, show] let redis_lru_cache_eviction_from_buffer buf = let host = Llio.string_from buf in let port = Llio.int_from buf in let key = Llio.string_from buf in { host; port; key; } let redis_lru_cache_eviction_to_buffer buf { host; port; key; } = Llio.string_to buf host; Llio.int_to buf port; Llio.string_to buf key type t = { enable_auto_repair : bool; auto_repair_timeout_seconds : float; auto_repair_disabled_nodes : string list; enable_rebalance : bool; cache_eviction_prefix_preset_pairs : (string, string) Hashtbl.t; redis_lru_cache_eviction : redis_lru_cache_eviction option; } [@@deriving yojson] let show t = to_yojson t |> Yojson.Safe.pretty_to_string let get_prefixes t = Hashtbl.fold (fun prefix _ acc -> prefix :: acc) t.cache_eviction_prefix_preset_pairs [] let from_buffer buf = let ser_version = Llio.int8_from buf in assert (ser_version = 1); let enable_auto_repair = Llio.bool_from buf in let auto_repair_timeout_seconds = Llio.float_from buf in let auto_repair_disabled_nodes = Llio.list_from Llio.string_from buf in let enable_rebalance = Llio.bool_from buf in let cache_eviction_prefix_preset_pairs = maybe_from_buffer (Llio.hashtbl_from (Llio.pair_from Llio.string_from Llio.string_from)) (Hashtbl.create 0) buf in let redis_lru_cache_eviction = maybe_from_buffer (Llio.option_from redis_lru_cache_eviction_from_buffer) None buf in { enable_auto_repair; auto_repair_timeout_seconds; auto_repair_disabled_nodes; enable_rebalance; cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction; } let to_buffer buf { enable_auto_repair; auto_repair_timeout_seconds; auto_repair_disabled_nodes; enable_rebalance; cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction; } = Llio.int8_to buf 1; Llio.bool_to buf enable_auto_repair; Llio.float_to buf auto_repair_timeout_seconds; Llio.list_to Llio.string_to buf auto_repair_disabled_nodes; Llio.bool_to buf enable_rebalance; Llio.hashtbl_to Llio.string_to Llio.string_to buf cache_eviction_prefix_preset_pairs; Llio.option_to redis_lru_cache_eviction_to_buffer buf redis_lru_cache_eviction module Update = struct type t = { enable_auto_repair' : bool option; auto_repair_timeout_seconds' : float option; auto_repair_add_disabled_nodes : string list; auto_repair_remove_disabled_nodes : string list; enable_rebalance' : bool option; add_cache_eviction_prefix_preset_pairs : (string * string) list; remove_cache_eviction_prefix_preset_pairs : string list; redis_lru_cache_eviction' : redis_lru_cache_eviction option; } let from_buffer buf = let ser_version = Llio.int8_from buf in assert (ser_version = 1); let enable_auto_repair' = Llio.option_from Llio.bool_from buf in let auto_repair_timeout_seconds' = Llio.option_from Llio.float_from buf in let auto_repair_remove_disabled_nodes = Llio.list_from Llio.string_from buf in let auto_repair_add_disabled_nodes = Llio.list_from Llio.string_from buf in let enable_rebalance' = Llio.option_from Llio.bool_from buf in let add_cache_eviction_prefix_preset_pairs, remove_cache_eviction_prefix_preset_pairs = maybe_from_buffer (Llio.pair_from (Llio.list_from (Llio.pair_from Llio.string_from Llio.string_from)) (Llio.list_from Llio.string_from)) ([], []) buf in let redis_lru_cache_eviction' = maybe_from_buffer (Llio.option_from redis_lru_cache_eviction_from_buffer) None buf in { enable_auto_repair'; auto_repair_timeout_seconds'; auto_repair_remove_disabled_nodes; auto_repair_add_disabled_nodes; enable_rebalance'; add_cache_eviction_prefix_preset_pairs; remove_cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction'; } let to_buffer buf { enable_auto_repair'; auto_repair_timeout_seconds'; auto_repair_remove_disabled_nodes; auto_repair_add_disabled_nodes; enable_rebalance'; add_cache_eviction_prefix_preset_pairs; remove_cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction'; } = Llio.int8_to buf 1; Llio.option_to Llio.bool_to buf enable_auto_repair'; Llio.option_to Llio.float_to buf auto_repair_timeout_seconds'; Llio.list_to Llio.string_to buf auto_repair_remove_disabled_nodes; Llio.list_to Llio.string_to buf auto_repair_add_disabled_nodes; Llio.option_to Llio.bool_to buf enable_rebalance'; Llio.list_to (Llio.pair_to Llio.string_to Llio.string_to) buf add_cache_eviction_prefix_preset_pairs; Llio.list_to Llio.string_to buf remove_cache_eviction_prefix_preset_pairs; Llio.option_to redis_lru_cache_eviction_to_buffer buf redis_lru_cache_eviction' let apply { enable_auto_repair; auto_repair_timeout_seconds; auto_repair_disabled_nodes; enable_rebalance; cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction; } { enable_auto_repair'; auto_repair_timeout_seconds'; auto_repair_remove_disabled_nodes; auto_repair_add_disabled_nodes; enable_rebalance'; add_cache_eviction_prefix_preset_pairs; remove_cache_eviction_prefix_preset_pairs; redis_lru_cache_eviction'; } = { enable_auto_repair = Option.get_some_default enable_auto_repair enable_auto_repair'; auto_repair_timeout_seconds = Option.get_some_default auto_repair_timeout_seconds auto_repair_timeout_seconds'; auto_repair_disabled_nodes = List.filter (fun node -> not (List.mem node auto_repair_remove_disabled_nodes)) (List.rev_append auto_repair_add_disabled_nodes auto_repair_disabled_nodes); enable_rebalance = Option.get_some_default enable_rebalance enable_rebalance'; cache_eviction_prefix_preset_pairs = (let () = List.iter (fun prefix -> Hashtbl.remove cache_eviction_prefix_preset_pairs prefix) remove_cache_eviction_prefix_preset_pairs in let () = List.iter (fun (prefix, preset) -> Hashtbl.replace cache_eviction_prefix_preset_pairs prefix preset) add_cache_eviction_prefix_preset_pairs in cache_eviction_prefix_preset_pairs); redis_lru_cache_eviction = (match redis_lru_cache_eviction' with | Some x -> Some x | None -> redis_lru_cache_eviction); } end
ee6727ac0d27d9e6d44199a7ed88ff86bf02700cdf7c18bfdb61f81b9e9d4689
chetmurthy/pa_ppx
pp_MLast.ml
module Ploc = struct include Ploc; value pp0_loc ppf loc = let fname = Ploc.file_name loc in let line = Ploc.line_nb loc in let bp = Ploc.first_pos loc in let ep = Ploc.last_pos loc in let bol = Ploc.bol_pos loc in let bp = bp - bol + 1 in let ep = ep - bol + 1 in Fmt.(pf ppf "<%a:%d:%d-%d>" (quote string) fname line bp ep) ; value pp1_loc ppf x = Fmt.(const string "<loc>" ppf ()); value pp_loc_verbose = ref False; value pp ppf x = if pp_loc_verbose.val then pp0_loc ppf x else pp1_loc ppf x ; type vala α = Ploc.vala α == [ VaAnt of string | VaVal of α ][@@"deriving_inline" show;] ; value rec pp_vala : ! α . Fmt.t α → Fmt.t (vala α) = fun (type a) (tp_0 : Fmt.t a) (ofmt : Format.formatter) arg → (fun ofmt → fun [ VaAnt v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>Pp_MLast.Ploc.VaAnt@ %a)@]" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v0 | VaVal v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>Pp_MLast.Ploc.VaVal@ %a)@]" tp_0 v0 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_vala : ! α . Fmt.t α → vala α → Stdlib.String.t = fun (type a) (tp_0 : Fmt.t a) arg → Format.asprintf "%a" (pp_vala tp_0) arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"]; end ; type loc = Ploc.t[@@"deriving_inline" show;]; value rec pp_loc : Fmt.t loc = fun (ofmt : Format.formatter) arg → Ploc.pp ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_loc : loc → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_loc arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"]; type type_var = (Ploc.vala (option string) * option bool)[@@"deriving_inline" show;] ; value rec pp_type_var : Fmt.t type_var = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) arg ])) v0 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" Fmt.bool arg ]) v1) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_type_var : type_var → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_type_var arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"]; type class_infos α = MLast.class_infos α == { ciLoc : loc; ciVir : Ploc.vala bool; ciPrm : (loc * Ploc.vala (list type_var)); ciNam : Ploc.vala string; ciExp : α; ciAttributes : attributes } and longid = MLast.longid == [ LiAcc of loc and longid and Ploc.vala string | LiApp of loc and longid and longid | LiUid of loc and Ploc.vala string | LiXtr of loc and string and option (Ploc.vala longid) ] and ctyp = MLast.ctyp == [ TyAcc of loc and longid and Ploc.vala string | TyAli of loc and ctyp and ctyp | TyAny of loc | TyApp of loc and ctyp and ctyp | TyArr of loc and ctyp and ctyp | TyCls of loc and Ploc.vala longid_lident | TyLab of loc and Ploc.vala string and ctyp | TyLid of loc and Ploc.vala string | TyMan of loc and ctyp and Ploc.vala bool and ctyp | TyObj of loc and Ploc.vala (list (option string * ctyp * attributes)) and Ploc.vala bool | TyOlb of loc and Ploc.vala string and ctyp | TyOpn of loc | TyPck of loc and module_type | TyPol of loc and Ploc.vala (list string) and ctyp | TyPot of loc and Ploc.vala (list string) and ctyp | TyQuo of loc and Ploc.vala string | TyRec of loc and Ploc.vala (list (loc * string * bool * ctyp * attributes)) | TySum of loc and Ploc.vala (list generic_constructor) | TyTup of loc and Ploc.vala (list ctyp) | TyVrn of loc and Ploc.vala (list poly_variant) and option (option (Ploc.vala (list string))) | TyXtr of loc and string and option (Ploc.vala ctyp) | TyAtt of loc and ctyp and attribute | TyExten of loc and attribute ] and poly_variant = MLast.poly_variant == [ PvTag of loc and Ploc.vala string and Ploc.vala bool and Ploc.vala (list ctyp) and attributes | PvInh of loc and ctyp ] and patt = MLast.patt == [ PaPfx of loc and longid and patt | PaLong of loc and longid | PaAli of loc and patt and patt | PaAnt of loc and patt | PaAny of loc | PaApp of loc and patt and patt | PaArr of loc and Ploc.vala (list patt) | PaChr of loc and Ploc.vala string | PaExc of loc and patt | PaFlo of loc and Ploc.vala string | PaInt of loc and Ploc.vala string and string | PaLab of loc and Ploc.vala (list (patt * Ploc.vala (option patt))) | PaLaz of loc and patt | PaLid of loc and Ploc.vala string | PaNty of loc and Ploc.vala string | PaOlb of loc and patt and Ploc.vala (option expr) | PaOrp of loc and patt and patt | PaRec of loc and Ploc.vala (list (patt * patt)) | PaRng of loc and patt and patt | PaStr of loc and Ploc.vala string | PaTup of loc and Ploc.vala (list patt) | PaTyc of loc and patt and ctyp | PaTyp of loc and Ploc.vala longid_lident | PaUnp of loc and Ploc.vala (option (Ploc.vala string)) and option module_type | PaVrn of loc and Ploc.vala string | PaXtr of loc and string and option (Ploc.vala patt) | PaAtt of loc and patt and attribute | PaExten of loc and attribute ] and expr = MLast.expr == [ ExAcc of loc and expr and expr | ExAnt of loc and expr | ExApp of loc and expr and expr | ExAre of loc and Ploc.vala string and expr and Ploc.vala (list expr) | ExArr of loc and Ploc.vala (list expr) | ExAsr of loc and expr | ExAss of loc and expr and expr | ExBae of loc and Ploc.vala string and expr and Ploc.vala (list expr) | ExChr of loc and Ploc.vala string | ExCoe of loc and expr and option ctyp and ctyp | ExFlo of loc and Ploc.vala string | ExFor of loc and patt and expr and expr and Ploc.vala bool and Ploc.vala (list expr) | ExFun of loc and Ploc.vala (list case_branch) | ExIfe of loc and expr and expr and expr | ExInt of loc and Ploc.vala string and string | ExLab of loc and Ploc.vala (list (patt * Ploc.vala (option expr))) | ExLaz of loc and expr | ExLet of loc and Ploc.vala bool and Ploc.vala (list (patt * expr * attributes)) and expr | ExLEx of loc and Ploc.vala string and Ploc.vala (list ctyp) and expr and attributes | ExLid of loc and Ploc.vala string | ExLmd of loc and Ploc.vala (option (Ploc.vala string)) and module_expr and expr | ExLop of loc and Ploc.vala bool and module_expr and expr | ExMat of loc and expr and Ploc.vala (list case_branch) | ExNew of loc and Ploc.vala longid_lident | ExObj of loc and Ploc.vala (option patt) and Ploc.vala (list class_str_item) | ExOlb of loc and patt and Ploc.vala (option expr) | ExOvr of loc and Ploc.vala (list (string * expr)) | ExPck of loc and module_expr and option module_type | ExRec of loc and Ploc.vala (list (patt * expr)) and option expr | ExSeq of loc and Ploc.vala (list expr) | ExSnd of loc and expr and Ploc.vala string | ExSte of loc and Ploc.vala string and expr and Ploc.vala (list expr) | ExStr of loc and Ploc.vala string | ExTry of loc and expr and Ploc.vala (list case_branch) | ExTup of loc and Ploc.vala (list expr) | ExTyc of loc and expr and ctyp | ExUid of loc and Ploc.vala string | ExVrn of loc and Ploc.vala string | ExWhi of loc and expr and Ploc.vala (list expr) | ExXtr of loc and string and option (Ploc.vala expr) | ExAtt of loc and expr and attribute | ExExten of loc and attribute | ExUnr of loc ] and case_branch = (patt * Ploc.vala (option expr) * expr) and module_type = MLast.module_type == [ MtLong of loc and longid | MtLongLid of loc and longid and Ploc.vala string | MtLid of loc and Ploc.vala string | MtFun of loc and Ploc.vala (option (Ploc.vala (option (Ploc.vala string)) * module_type)) and module_type | MtQuo of loc and Ploc.vala string | MtSig of loc and Ploc.vala (list sig_item) | MtTyo of loc and module_expr | MtWit of loc and module_type and Ploc.vala (list with_constr) | MtXtr of loc and string and option (Ploc.vala module_type) | MtAtt of loc and module_type and attribute | MtExten of loc and attribute ] and functor_parameter = option (Ploc.vala (option (Ploc.vala string)) * module_type) and sig_item = MLast.sig_item == [ SgCls of loc and Ploc.vala (list (class_infos class_type)) | SgClt of loc and Ploc.vala (list (class_infos class_type)) | SgDcl of loc and Ploc.vala (list sig_item) | SgDir of loc and Ploc.vala string and Ploc.vala (option expr) | SgExc of loc and generic_constructor and attributes | SgExt of loc and Ploc.vala string and ctyp and Ploc.vala (list string) and attributes | SgInc of loc and module_type and attributes | SgMod of loc and Ploc.vala bool and Ploc.vala (list (Ploc.vala (option (Ploc.vala string)) * module_type * attributes)) | SgMty of loc and Ploc.vala string and module_type and attributes | SgMtyAlias of loc and Ploc.vala string and Ploc.vala longid and attributes | SgModSubst of loc and Ploc.vala string and longid and attributes | SgOpn of loc and longid and attributes | SgTyp of loc and Ploc.vala bool and Ploc.vala (list type_decl) | SgTypExten of loc and type_extension | SgUse of loc and Ploc.vala string and Ploc.vala (list (sig_item * loc)) | SgVal of loc and Ploc.vala string and ctyp and attributes | SgXtr of loc and string and option (Ploc.vala sig_item) | SgFlAtt of loc and attribute | SgExten of loc and attribute and attributes ] and with_constr = MLast.with_constr == [ WcMod of loc and Ploc.vala longid and module_expr | WcMos of loc and Ploc.vala longid and module_expr | WcTyp of loc and Ploc.vala longid_lident and Ploc.vala (list type_var) and Ploc.vala bool and ctyp | WcTys of loc and Ploc.vala longid_lident and Ploc.vala (list type_var) and ctyp ] and module_expr = MLast.module_expr == [ MeAcc of loc and module_expr and module_expr | MeApp of loc and module_expr and module_expr | MeFun of loc and Ploc.vala (option (Ploc.vala (option (Ploc.vala string)) * module_type)) and module_expr | MeStr of loc and Ploc.vala (list str_item) | MeTyc of loc and module_expr and module_type | MeUid of loc and Ploc.vala string | MeUnp of loc and expr and option module_type and option module_type | MeXtr of loc and string and option (Ploc.vala module_expr) | MeAtt of loc and module_expr and attribute | MeExten of loc and attribute ] and str_item = MLast.str_item == [ StCls of loc and Ploc.vala (list (class_infos class_expr)) | StClt of loc and Ploc.vala (list (class_infos class_type)) | StDcl of loc and Ploc.vala (list str_item) | StDir of loc and Ploc.vala string and Ploc.vala (option expr) | StExc of loc and Ploc.vala extension_constructor and attributes | StExp of loc and expr and attributes | StExt of loc and Ploc.vala string and ctyp and Ploc.vala (list string) and attributes | StInc of loc and module_expr and attributes | StMod of loc and Ploc.vala bool and Ploc.vala (list (Ploc.vala (option (Ploc.vala string)) * module_expr * attributes)) | StMty of loc and Ploc.vala string and module_type and attributes | StOpn of loc and Ploc.vala bool and module_expr and attributes | StTyp of loc and Ploc.vala bool and Ploc.vala (list type_decl) | StTypExten of loc and type_extension | StUse of loc and Ploc.vala string and Ploc.vala (list (str_item * loc)) | StVal of loc and Ploc.vala bool and Ploc.vala (list (patt * expr * attributes)) | StXtr of loc and string and option (Ploc.vala str_item) | StFlAtt of loc and attribute | StExten of loc and attribute and attributes ] and type_decl = MLast.type_decl == { tdIsDecl : Ploc.vala bool; tdNam : Ploc.vala (loc * Ploc.vala string); tdPrm : Ploc.vala (list type_var); tdPrv : Ploc.vala bool; tdDef : ctyp; tdCon : Ploc.vala (list (ctyp * ctyp)); tdAttributes : attributes } and generic_constructor = (loc * Ploc.vala string * Ploc.vala (list ctyp) * Ploc.vala (option ctyp) * attributes) and extension_constructor = MLast.extension_constructor == [ EcTuple of loc and generic_constructor | EcRebind of loc and Ploc.vala string and Ploc.vala longid and attributes ] and type_extension = MLast.type_extension == { teNam : Ploc.vala longid_lident; tePrm : Ploc.vala (list type_var); tePrv : Ploc.vala bool; teECs : Ploc.vala (list extension_constructor); teAttributes : attributes } and class_type = MLast.class_type == [ CtLongLid of loc and longid and Ploc.vala string | CtLid of loc and Ploc.vala string | CtLop of loc and Ploc.vala bool and longid and class_type | CtCon of loc and class_type and Ploc.vala (list ctyp) | CtFun of loc and ctyp and class_type | CtSig of loc and Ploc.vala (option ctyp) and Ploc.vala (list class_sig_item) | CtXtr of loc and string and option (Ploc.vala class_type) | CtAtt of loc and class_type and attribute | CtExten of loc and attribute ] and class_sig_item = MLast.class_sig_item == [ CgCtr of loc and ctyp and ctyp and attributes | CgDcl of loc and Ploc.vala (list class_sig_item) | CgInh of loc and class_type and attributes | CgMth of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CgVal of loc and Ploc.vala bool and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CgVir of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CgFlAtt of loc and attribute | CgExten of loc and attribute ] and class_expr = MLast.class_expr == [ CeApp of loc and class_expr and expr | CeCon of loc and Ploc.vala longid_lident and Ploc.vala (list ctyp) | CeFun of loc and patt and class_expr | CeLet of loc and Ploc.vala bool and Ploc.vala (list (patt * expr * attributes)) and class_expr | CeLop of loc and Ploc.vala bool and longid and class_expr | CeStr of loc and Ploc.vala (option patt) and Ploc.vala (list class_str_item) | CeTyc of loc and class_expr and class_type | CeXtr of loc and string and option (Ploc.vala class_expr) | CeAtt of loc and class_expr and attribute | CeExten of loc and attribute ] and class_str_item = MLast.class_str_item == [ CrCtr of loc and ctyp and ctyp and attributes | CrDcl of loc and Ploc.vala (list class_str_item) | CrInh of loc and Ploc.vala bool and class_expr and Ploc.vala (option string) and attributes | CrIni of loc and expr and attributes | CrMth of loc and Ploc.vala bool and Ploc.vala bool and Ploc.vala string and Ploc.vala (option ctyp) and expr and attributes | CrVal of loc and Ploc.vala bool and Ploc.vala bool and Ploc.vala string and expr and attributes | CrVav of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CrVir of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CrFlAtt of loc and attribute | CrExten of loc and attribute ] and longid_lident = (option (Ploc.vala longid) * Ploc.vala string) and payload = MLast.payload == [ StAttr of loc and Ploc.vala (list str_item) | SiAttr of loc and Ploc.vala (list sig_item) | TyAttr of loc and Ploc.vala ctyp | PaAttr of loc and Ploc.vala patt and option (Ploc.vala expr) ] and attribute_body = (Ploc.vala (loc * string) * payload) and attribute = Ploc.vala attribute_body and attributes_no_anti = list attribute and attributes = Ploc.vala attributes_no_anti[@@"deriving_inline" show;]; value rec pp_class_infos : ! α . Fmt.t α → Fmt.t (class_infos α) = fun (type a) (tp_0 : Fmt.t a) (ofmt : Format.formatter) arg → (fun ofmt ({ciLoc = v_ciLoc; ciVir = v_ciVir; ciPrm = v_ciPrm; ciNam = v_ciNam; ciExp = v_ciExp; ciAttributes = v_ciAttributes} : class_infos a) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>{ @[Pp_MLast.ciLoc =@ %a@];@ @[ciVir =@ %a@];@ @[ciPrm =@ %a@];@ @[ciNam =@ %a@];@ @[ciExp =@ %a@];@ @[ciAttributes =@ %a@] }@]" pp_loc v_ciLoc (Ploc.pp_vala Fmt.bool) v_ciVir (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v1) v_ciPrm (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v_ciNam tp_0 v_ciExp pp_attributes v_ciAttributes) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_infos : ! α . Fmt.t α → class_infos α → Stdlib.String.t = fun (type a) (tp_0 : Fmt.t a) arg → Format.asprintf "%a" (pp_class_infos tp_0) arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_longid : Fmt.t longid = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ LiAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | LiApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 pp_longid v2 | LiUid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiUid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | LiXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_longid) arg ]) v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_longid : longid → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_longid arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_ctyp : Fmt.t ctyp = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ TyAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | TyAli v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAli@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 | TyAny v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAny@ %a)@]" pp_loc v0 | TyApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 | TyArr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyArr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 | TyCls v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyCls@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 | TyLab v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyLab@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 | TyLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | TyMan v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyMan@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 (Ploc.pp_vala Fmt.bool) v2 pp_ctyp v3 | TyObj v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyObj@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) arg ]) v0 pp_ctyp v1 pp_attributes v2)) arg)) v1 (Ploc.pp_vala Fmt.bool) v2 | TyOlb v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyOlb@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 | TyOpn v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyOpn@ %a)@]" pp_loc v0 | TyPck v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyPck@ (@,%a,@ %a@,))@]" pp_loc v0 pp_module_type v1 | TyPol v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyPol@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v1 pp_ctyp v2 | TyPot v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyPot@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v1 pp_ctyp v2 | TyQuo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyQuo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | TyRec v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyRec@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2, v3, v4) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a,@ %a,@ %a@])" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 Fmt.bool v2 pp_ctyp v3 pp_attributes v4)) arg)) v1 | TySum v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TySum@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_generic_constructor) arg)) v1 | TyTup v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyTup@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v1 | TyVrn v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyVrn@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_poly_variant) arg)) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) arg ]) arg ]) v2 | TyXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_ctyp) arg ]) v2 | TyAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_attribute v2 | TyExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_ctyp : ctyp → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_ctyp arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_poly_variant : Fmt.t poly_variant = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ PvTag v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PvTag@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v3 pp_attributes v4 | PvInh v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PvInh@ (@,%a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_poly_variant : poly_variant → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_poly_variant arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_patt : Fmt.t patt = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ PaPfx v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaPfx@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 pp_patt v2 | PaLong v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLong@ (@,%a,@ %a@,))@]" pp_loc v0 pp_longid v1 | PaAli v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAli@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaAnt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAnt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_patt v1 | PaAny v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAny@ %a)@]" pp_loc v0 | PaApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaArr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaArr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_patt) arg)) v1 | PaChr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaChr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaExc v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaExc@ (@,%a,@ %a@,))@]" pp_loc v0 pp_patt v1 | PaFlo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaFlo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaInt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaInt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v2 | PaLab v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLab@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_patt arg ])) v1)) arg)) v1 | PaLaz v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLaz@ (@,%a,@ %a@,))@]" pp_loc v0 pp_patt v1 | PaLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaNty v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaNty@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaOlb v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaOlb@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | PaOrp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaOrp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaRec v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaRec@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 pp_patt v1)) arg)) v1 | PaRng v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaRng@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaStr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaStr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaTup v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaTup@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_patt) arg)) v1 | PaTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_ctyp v2 | PaTyp v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaTyp@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 | PaUnp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaUnp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v2 | PaVrn v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaVrn@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_patt) arg ]) v2 | PaAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_attribute v2 | PaExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_patt : patt → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_patt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_expr : Fmt.t expr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ ExAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 | ExAnt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAnt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_expr v1 | ExApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 | ExAre v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAre@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_expr v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v3 | ExArr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExArr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v1 | ExAsr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAsr@ (@,%a,@ %a@,))@]" pp_loc v0 pp_expr v1 | ExAss v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAss@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 | ExBae v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExBae@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_expr v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v3 | ExChr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExChr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExCoe v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExCoe@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ]) v2 pp_ctyp v3 | ExFlo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExFlo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExFor v0 v1 v2 v3 v4 v5 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExFor@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_expr v2 pp_expr v3 (Ploc.pp_vala Fmt.bool) v4 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v5 | ExFun v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExFun@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_case_branch) arg)) v1 | ExIfe v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExIfe@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 pp_expr v3 | ExInt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExInt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v2 | ExLab v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLab@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v1)) arg)) v1 | ExLaz v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLaz@ (@,%a,@ %a@,))@]" pp_loc v0 pp_expr v1 | ExLet v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLet@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 pp_expr v1 pp_attributes v2)) arg)) v2 pp_expr v3 | ExLEx v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLEx@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 pp_expr v3 pp_attributes v4 | ExLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExLmd v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLmd@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v1 pp_module_expr v2 pp_expr v3 | ExLop v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLop@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_module_expr v2 pp_expr v3 | ExMat v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExMat@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_case_branch) arg)) v2 | ExNew v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExNew@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 | ExObj v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExObj@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_patt arg ])) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_str_item) arg)) v2 | ExOlb v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExOlb@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | ExOvr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExOvr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v0 pp_expr v1)) arg)) v1 | ExPck v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExPck@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v2 | ExRec v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExRec@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 pp_expr v1)) arg)) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ]) v2 | ExSeq v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExSeq@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v1 | ExSnd v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExSnd@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | ExSte v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExSte@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_expr v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v3 | ExStr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExStr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExTry v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExTry@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_case_branch) arg)) v2 | ExTup v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExTup@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v1 | ExTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_ctyp v2 | ExUid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExUid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExVrn v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExVrn@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExWhi v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExWhi@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v2 | ExXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_expr) arg ]) v2 | ExAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_attribute v2 | ExExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | ExUnr v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExUnr@ %a)@]" pp_loc v0 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_expr : expr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_expr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_case_branch : Fmt.t case_branch = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v1 pp_expr v2) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_case_branch : case_branch → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_case_branch arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_module_type : Fmt.t module_type = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ MtLong v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtLong@ (@,%a,@ %a@,))@]" pp_loc v0 pp_longid v1 | MtLongLid v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtLongLid@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | MtLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | MtFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1) arg ])) v1 pp_module_type v2 | MtQuo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtQuo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | MtSig v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtSig@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_sig_item) arg)) v1 | MtTyo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtTyo@ (@,%a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 | MtWit v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtWit@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_type v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_with_constr) arg)) v2 | MtXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_module_type) arg ]) v2 | MtAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_type v1 pp_attribute v2 | MtExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_module_type : module_type → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_module_type arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_functor_parameter : Fmt.t functor_parameter = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1) arg ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_functor_parameter : functor_parameter → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_functor_parameter arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_sig_item : Fmt.t sig_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ SgCls v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgCls@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_type)) arg)) v1 | SgClt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgClt@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_type)) arg)) v1 | SgDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_sig_item) arg)) v1 | SgDir v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgDir@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | SgExc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgExc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_generic_constructor v1 pp_attributes v2 | SgExt v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgExt@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v3 pp_attributes v4 | SgInc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgInc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_type v1 pp_attributes v2 | SgMod v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgMod@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1 pp_attributes v2)) arg)) v2 | SgMty v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgMty@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_module_type v2 pp_attributes v3 | SgMtyAlias v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgMtyAlias@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala pp_longid) v2 pp_attributes v3 | SgModSubst v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgModSubst@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_longid v2 pp_attributes v3 | SgOpn v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgOpn@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 pp_attributes v2 | SgTyp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgTyp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_decl) arg)) v2 | SgTypExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgTypExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_type_extension v1 | SgUse v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgUse@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_sig_item v0 pp_loc v1)) arg)) v2 | SgVal v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgVal@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 pp_attributes v3 | SgXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_sig_item) arg ]) v2 | SgFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | SgExten v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgExten@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_attribute v1 pp_attributes v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_sig_item : sig_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_sig_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_with_constr : Fmt.t with_constr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ WcMod v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcMod@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid) v1 pp_module_expr v2 | WcMos v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcMos@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid) v1 pp_module_expr v2 | WcTyp v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcTyp@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v2 (Ploc.pp_vala Fmt.bool) v3 pp_ctyp v4 | WcTys v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcTys@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v2 pp_ctyp v3 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_with_constr : with_constr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_with_constr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_module_expr : Fmt.t module_expr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ MeAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_module_expr v2 | MeApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_module_expr v2 | MeFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1) arg ])) v1 pp_module_expr v2 | MeStr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeStr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_str_item) arg)) v1 | MeTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_module_type v2 | MeUid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeUid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | MeUnp v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeUnp@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v2 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v3 | MeXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_module_expr) arg ]) v2 | MeAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_attribute v2 | MeExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_module_expr : module_expr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_module_expr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_str_item : Fmt.t str_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ StCls v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StCls@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_expr)) arg)) v1 | StClt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StClt@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_type)) arg)) v1 | StDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_str_item) arg)) v1 | StDir v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StDir@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | StExc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_extension_constructor) v1 pp_attributes v2 | StExp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_attributes v2 | StExt v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExt@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v3 pp_attributes v4 | StInc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StInc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_attributes v2 | StMod v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StMod@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_expr v1 pp_attributes v2)) arg)) v2 | StMty v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StMty@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_module_type v2 pp_attributes v3 | StOpn v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StOpn@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_module_expr v2 pp_attributes v3 | StTyp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StTyp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_decl) arg)) v2 | StTypExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StTypExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_type_extension v1 | StUse v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StUse@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_str_item v0 pp_loc v1)) arg)) v2 | StVal v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StVal@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 pp_expr v1 pp_attributes v2)) arg)) v2 | StXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_str_item) arg ]) v2 | StFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | StExten v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExten@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_attribute v1 pp_attributes v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_str_item : str_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_str_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_type_decl : Fmt.t type_decl = fun (ofmt : Format.formatter) arg → (fun ofmt ({tdIsDecl = v_tdIsDecl; tdNam = v_tdNam; tdPrm = v_tdPrm; tdPrv = v_tdPrv; tdDef = v_tdDef; tdCon = v_tdCon; tdAttributes = v_tdAttributes} : type_decl) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>{ @[MLast.tdIsDecl =@ %a@];@ @[tdNam =@ %a@];@ @[tdPrm =@ %a@];@ @[tdPrv =@ %a@];@ @[tdDef =@ %a@];@ @[tdCon =@ %a@];@ @[tdAttributes =@ %a@] }@]" (Ploc.pp_vala Fmt.bool) v_tdIsDecl (Ploc.pp_vala (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1)) v_tdNam (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v_tdPrm (Ploc.pp_vala Fmt.bool) v_tdPrv pp_ctyp v_tdDef (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_ctyp v0 pp_ctyp v1)) arg)) v_tdCon pp_attributes v_tdAttributes) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_type_decl : type_decl → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_type_decl arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_generic_constructor : Fmt.t generic_constructor = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1, v2, v3, v4) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a,@ %a,@ %a@])" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ])) v3 pp_attributes v4) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_generic_constructor : generic_constructor → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_generic_constructor arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_extension_constructor : Fmt.t extension_constructor = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ EcTuple v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.EcTuple@ (@,%a,@ %a@,))@]" pp_loc v0 pp_generic_constructor v1 | EcRebind v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.EcRebind@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala pp_longid) v2 pp_attributes v3 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_extension_constructor : extension_constructor → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_extension_constructor arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_type_extension : Fmt.t type_extension = fun (ofmt : Format.formatter) arg → (fun ofmt ({teNam = v_teNam; tePrm = v_tePrm; tePrv = v_tePrv; teECs = v_teECs; teAttributes = v_teAttributes} : type_extension) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>{ @[MLast.teNam =@ %a@];@ @[tePrm =@ %a@];@ @[tePrv =@ %a@];@ @[teECs =@ %a@];@ @[teAttributes =@ %a@] }@]" (Ploc.pp_vala pp_longid_lident) v_teNam (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v_tePrm (Ploc.pp_vala Fmt.bool) v_tePrv (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_extension_constructor) arg)) v_teECs pp_attributes v_teAttributes) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_type_extension : type_extension → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_type_extension arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_type : Fmt.t class_type = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CtLongLid v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtLongLid@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | CtLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | CtLop v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtLop@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_longid v2 pp_class_type v3 | CtCon v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtCon@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_type v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 | CtFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_class_type v2 | CtSig v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtSig@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ])) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_sig_item) arg)) v2 | CtXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_class_type) arg ]) v2 | CtAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_type v1 pp_attribute v2 | CtExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_type : class_type → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_type arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_sig_item : Fmt.t class_sig_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CgCtr v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgCtr@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 pp_attributes v3 | CgDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_sig_item) arg)) v1 | CgInh v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgInh@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_type v1 pp_attributes v2 | CgMth v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgMth@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CgVal v0 v1 v2 v3 v4 v5 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgVal@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v3 pp_ctyp v4 pp_attributes v5 | CgVir v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgVir@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CgFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | CgExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_sig_item : class_sig_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_sig_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_expr : Fmt.t class_expr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CeApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_expr v1 pp_expr v2 | CeCon v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeCon@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 | CeFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_class_expr v2 | CeLet v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeLet@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 pp_expr v1 pp_attributes v2)) arg)) v2 pp_class_expr v3 | CeLop v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeLop@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_longid v2 pp_class_expr v3 | CeStr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeStr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_patt arg ])) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_str_item) arg)) v2 | CeTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_expr v1 pp_class_type v2 | CeXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_class_expr) arg ]) v2 | CeAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_expr v1 pp_attribute v2 | CeExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_expr : class_expr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_expr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_str_item : Fmt.t class_str_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CrCtr v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrCtr@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 pp_attributes v3 | CrDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_str_item) arg)) v1 | CrInh v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrInh@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_class_expr v2 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) arg ])) v3 pp_attributes v4 | CrIni v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrIni@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_attributes v2 | CrMth v0 v1 v2 v3 v4 v5 v6 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrMth@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v3 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ])) v4 pp_expr v5 pp_attributes v6 | CrVal v0 v1 v2 v3 v4 v5 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrVal@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v3 pp_expr v4 pp_attributes v5 | CrVav v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrVav@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CrVir v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrVir@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CrFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | CrExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_str_item : class_str_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_str_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_longid_lident : Fmt.t longid_lident = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_longid) arg ]) v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_longid_lident : longid_lident → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_longid_lident arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_payload : Fmt.t payload = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ StAttr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StAttr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_str_item) arg)) v1 | SiAttr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SiAttr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_sig_item) arg)) v1 | TyAttr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAttr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_ctyp) v1 | PaAttr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAttr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_patt) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_expr) arg ]) v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_payload : payload → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_payload arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attribute_body : Fmt.t attribute_body = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1)) v0 pp_payload v1) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attribute_body : attribute_body → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attribute_body arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attribute : Fmt.t attribute = fun (ofmt : Format.formatter) arg → Ploc.pp_vala pp_attribute_body ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attribute : attribute → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attribute arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attributes_no_anti : Fmt.t attributes_no_anti = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_attribute) arg) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attributes_no_anti : attributes_no_anti → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attributes_no_anti arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attributes : Fmt.t attributes = fun (ofmt : Format.formatter) arg → Ploc.pp_vala pp_attributes_no_anti ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attributes : attributes → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attributes arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"];
null
https://raw.githubusercontent.com/chetmurthy/pa_ppx/7c662fcf4897c978ae8a5ea230af0e8b2fa5858b/base/pp_MLast.ml
ocaml
module Ploc = struct include Ploc; value pp0_loc ppf loc = let fname = Ploc.file_name loc in let line = Ploc.line_nb loc in let bp = Ploc.first_pos loc in let ep = Ploc.last_pos loc in let bol = Ploc.bol_pos loc in let bp = bp - bol + 1 in let ep = ep - bol + 1 in Fmt.(pf ppf "<%a:%d:%d-%d>" (quote string) fname line bp ep) ; value pp1_loc ppf x = Fmt.(const string "<loc>" ppf ()); value pp_loc_verbose = ref False; value pp ppf x = if pp_loc_verbose.val then pp0_loc ppf x else pp1_loc ppf x ; type vala α = Ploc.vala α == [ VaAnt of string | VaVal of α ][@@"deriving_inline" show;] ; value rec pp_vala : ! α . Fmt.t α → Fmt.t (vala α) = fun (type a) (tp_0 : Fmt.t a) (ofmt : Format.formatter) arg → (fun ofmt → fun [ VaAnt v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>Pp_MLast.Ploc.VaAnt@ %a)@]" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v0 | VaVal v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>Pp_MLast.Ploc.VaVal@ %a)@]" tp_0 v0 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_vala : ! α . Fmt.t α → vala α → Stdlib.String.t = fun (type a) (tp_0 : Fmt.t a) arg → Format.asprintf "%a" (pp_vala tp_0) arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"]; end ; type loc = Ploc.t[@@"deriving_inline" show;]; value rec pp_loc : Fmt.t loc = fun (ofmt : Format.formatter) arg → Ploc.pp ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_loc : loc → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_loc arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"]; type type_var = (Ploc.vala (option string) * option bool)[@@"deriving_inline" show;] ; value rec pp_type_var : Fmt.t type_var = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) arg ])) v0 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" Fmt.bool arg ]) v1) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_type_var : type_var → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_type_var arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"]; type class_infos α = MLast.class_infos α == { ciLoc : loc; ciVir : Ploc.vala bool; ciPrm : (loc * Ploc.vala (list type_var)); ciNam : Ploc.vala string; ciExp : α; ciAttributes : attributes } and longid = MLast.longid == [ LiAcc of loc and longid and Ploc.vala string | LiApp of loc and longid and longid | LiUid of loc and Ploc.vala string | LiXtr of loc and string and option (Ploc.vala longid) ] and ctyp = MLast.ctyp == [ TyAcc of loc and longid and Ploc.vala string | TyAli of loc and ctyp and ctyp | TyAny of loc | TyApp of loc and ctyp and ctyp | TyArr of loc and ctyp and ctyp | TyCls of loc and Ploc.vala longid_lident | TyLab of loc and Ploc.vala string and ctyp | TyLid of loc and Ploc.vala string | TyMan of loc and ctyp and Ploc.vala bool and ctyp | TyObj of loc and Ploc.vala (list (option string * ctyp * attributes)) and Ploc.vala bool | TyOlb of loc and Ploc.vala string and ctyp | TyOpn of loc | TyPck of loc and module_type | TyPol of loc and Ploc.vala (list string) and ctyp | TyPot of loc and Ploc.vala (list string) and ctyp | TyQuo of loc and Ploc.vala string | TyRec of loc and Ploc.vala (list (loc * string * bool * ctyp * attributes)) | TySum of loc and Ploc.vala (list generic_constructor) | TyTup of loc and Ploc.vala (list ctyp) | TyVrn of loc and Ploc.vala (list poly_variant) and option (option (Ploc.vala (list string))) | TyXtr of loc and string and option (Ploc.vala ctyp) | TyAtt of loc and ctyp and attribute | TyExten of loc and attribute ] and poly_variant = MLast.poly_variant == [ PvTag of loc and Ploc.vala string and Ploc.vala bool and Ploc.vala (list ctyp) and attributes | PvInh of loc and ctyp ] and patt = MLast.patt == [ PaPfx of loc and longid and patt | PaLong of loc and longid | PaAli of loc and patt and patt | PaAnt of loc and patt | PaAny of loc | PaApp of loc and patt and patt | PaArr of loc and Ploc.vala (list patt) | PaChr of loc and Ploc.vala string | PaExc of loc and patt | PaFlo of loc and Ploc.vala string | PaInt of loc and Ploc.vala string and string | PaLab of loc and Ploc.vala (list (patt * Ploc.vala (option patt))) | PaLaz of loc and patt | PaLid of loc and Ploc.vala string | PaNty of loc and Ploc.vala string | PaOlb of loc and patt and Ploc.vala (option expr) | PaOrp of loc and patt and patt | PaRec of loc and Ploc.vala (list (patt * patt)) | PaRng of loc and patt and patt | PaStr of loc and Ploc.vala string | PaTup of loc and Ploc.vala (list patt) | PaTyc of loc and patt and ctyp | PaTyp of loc and Ploc.vala longid_lident | PaUnp of loc and Ploc.vala (option (Ploc.vala string)) and option module_type | PaVrn of loc and Ploc.vala string | PaXtr of loc and string and option (Ploc.vala patt) | PaAtt of loc and patt and attribute | PaExten of loc and attribute ] and expr = MLast.expr == [ ExAcc of loc and expr and expr | ExAnt of loc and expr | ExApp of loc and expr and expr | ExAre of loc and Ploc.vala string and expr and Ploc.vala (list expr) | ExArr of loc and Ploc.vala (list expr) | ExAsr of loc and expr | ExAss of loc and expr and expr | ExBae of loc and Ploc.vala string and expr and Ploc.vala (list expr) | ExChr of loc and Ploc.vala string | ExCoe of loc and expr and option ctyp and ctyp | ExFlo of loc and Ploc.vala string | ExFor of loc and patt and expr and expr and Ploc.vala bool and Ploc.vala (list expr) | ExFun of loc and Ploc.vala (list case_branch) | ExIfe of loc and expr and expr and expr | ExInt of loc and Ploc.vala string and string | ExLab of loc and Ploc.vala (list (patt * Ploc.vala (option expr))) | ExLaz of loc and expr | ExLet of loc and Ploc.vala bool and Ploc.vala (list (patt * expr * attributes)) and expr | ExLEx of loc and Ploc.vala string and Ploc.vala (list ctyp) and expr and attributes | ExLid of loc and Ploc.vala string | ExLmd of loc and Ploc.vala (option (Ploc.vala string)) and module_expr and expr | ExLop of loc and Ploc.vala bool and module_expr and expr | ExMat of loc and expr and Ploc.vala (list case_branch) | ExNew of loc and Ploc.vala longid_lident | ExObj of loc and Ploc.vala (option patt) and Ploc.vala (list class_str_item) | ExOlb of loc and patt and Ploc.vala (option expr) | ExOvr of loc and Ploc.vala (list (string * expr)) | ExPck of loc and module_expr and option module_type | ExRec of loc and Ploc.vala (list (patt * expr)) and option expr | ExSeq of loc and Ploc.vala (list expr) | ExSnd of loc and expr and Ploc.vala string | ExSte of loc and Ploc.vala string and expr and Ploc.vala (list expr) | ExStr of loc and Ploc.vala string | ExTry of loc and expr and Ploc.vala (list case_branch) | ExTup of loc and Ploc.vala (list expr) | ExTyc of loc and expr and ctyp | ExUid of loc and Ploc.vala string | ExVrn of loc and Ploc.vala string | ExWhi of loc and expr and Ploc.vala (list expr) | ExXtr of loc and string and option (Ploc.vala expr) | ExAtt of loc and expr and attribute | ExExten of loc and attribute | ExUnr of loc ] and case_branch = (patt * Ploc.vala (option expr) * expr) and module_type = MLast.module_type == [ MtLong of loc and longid | MtLongLid of loc and longid and Ploc.vala string | MtLid of loc and Ploc.vala string | MtFun of loc and Ploc.vala (option (Ploc.vala (option (Ploc.vala string)) * module_type)) and module_type | MtQuo of loc and Ploc.vala string | MtSig of loc and Ploc.vala (list sig_item) | MtTyo of loc and module_expr | MtWit of loc and module_type and Ploc.vala (list with_constr) | MtXtr of loc and string and option (Ploc.vala module_type) | MtAtt of loc and module_type and attribute | MtExten of loc and attribute ] and functor_parameter = option (Ploc.vala (option (Ploc.vala string)) * module_type) and sig_item = MLast.sig_item == [ SgCls of loc and Ploc.vala (list (class_infos class_type)) | SgClt of loc and Ploc.vala (list (class_infos class_type)) | SgDcl of loc and Ploc.vala (list sig_item) | SgDir of loc and Ploc.vala string and Ploc.vala (option expr) | SgExc of loc and generic_constructor and attributes | SgExt of loc and Ploc.vala string and ctyp and Ploc.vala (list string) and attributes | SgInc of loc and module_type and attributes | SgMod of loc and Ploc.vala bool and Ploc.vala (list (Ploc.vala (option (Ploc.vala string)) * module_type * attributes)) | SgMty of loc and Ploc.vala string and module_type and attributes | SgMtyAlias of loc and Ploc.vala string and Ploc.vala longid and attributes | SgModSubst of loc and Ploc.vala string and longid and attributes | SgOpn of loc and longid and attributes | SgTyp of loc and Ploc.vala bool and Ploc.vala (list type_decl) | SgTypExten of loc and type_extension | SgUse of loc and Ploc.vala string and Ploc.vala (list (sig_item * loc)) | SgVal of loc and Ploc.vala string and ctyp and attributes | SgXtr of loc and string and option (Ploc.vala sig_item) | SgFlAtt of loc and attribute | SgExten of loc and attribute and attributes ] and with_constr = MLast.with_constr == [ WcMod of loc and Ploc.vala longid and module_expr | WcMos of loc and Ploc.vala longid and module_expr | WcTyp of loc and Ploc.vala longid_lident and Ploc.vala (list type_var) and Ploc.vala bool and ctyp | WcTys of loc and Ploc.vala longid_lident and Ploc.vala (list type_var) and ctyp ] and module_expr = MLast.module_expr == [ MeAcc of loc and module_expr and module_expr | MeApp of loc and module_expr and module_expr | MeFun of loc and Ploc.vala (option (Ploc.vala (option (Ploc.vala string)) * module_type)) and module_expr | MeStr of loc and Ploc.vala (list str_item) | MeTyc of loc and module_expr and module_type | MeUid of loc and Ploc.vala string | MeUnp of loc and expr and option module_type and option module_type | MeXtr of loc and string and option (Ploc.vala module_expr) | MeAtt of loc and module_expr and attribute | MeExten of loc and attribute ] and str_item = MLast.str_item == [ StCls of loc and Ploc.vala (list (class_infos class_expr)) | StClt of loc and Ploc.vala (list (class_infos class_type)) | StDcl of loc and Ploc.vala (list str_item) | StDir of loc and Ploc.vala string and Ploc.vala (option expr) | StExc of loc and Ploc.vala extension_constructor and attributes | StExp of loc and expr and attributes | StExt of loc and Ploc.vala string and ctyp and Ploc.vala (list string) and attributes | StInc of loc and module_expr and attributes | StMod of loc and Ploc.vala bool and Ploc.vala (list (Ploc.vala (option (Ploc.vala string)) * module_expr * attributes)) | StMty of loc and Ploc.vala string and module_type and attributes | StOpn of loc and Ploc.vala bool and module_expr and attributes | StTyp of loc and Ploc.vala bool and Ploc.vala (list type_decl) | StTypExten of loc and type_extension | StUse of loc and Ploc.vala string and Ploc.vala (list (str_item * loc)) | StVal of loc and Ploc.vala bool and Ploc.vala (list (patt * expr * attributes)) | StXtr of loc and string and option (Ploc.vala str_item) | StFlAtt of loc and attribute | StExten of loc and attribute and attributes ] and type_decl = MLast.type_decl == { tdIsDecl : Ploc.vala bool; tdNam : Ploc.vala (loc * Ploc.vala string); tdPrm : Ploc.vala (list type_var); tdPrv : Ploc.vala bool; tdDef : ctyp; tdCon : Ploc.vala (list (ctyp * ctyp)); tdAttributes : attributes } and generic_constructor = (loc * Ploc.vala string * Ploc.vala (list ctyp) * Ploc.vala (option ctyp) * attributes) and extension_constructor = MLast.extension_constructor == [ EcTuple of loc and generic_constructor | EcRebind of loc and Ploc.vala string and Ploc.vala longid and attributes ] and type_extension = MLast.type_extension == { teNam : Ploc.vala longid_lident; tePrm : Ploc.vala (list type_var); tePrv : Ploc.vala bool; teECs : Ploc.vala (list extension_constructor); teAttributes : attributes } and class_type = MLast.class_type == [ CtLongLid of loc and longid and Ploc.vala string | CtLid of loc and Ploc.vala string | CtLop of loc and Ploc.vala bool and longid and class_type | CtCon of loc and class_type and Ploc.vala (list ctyp) | CtFun of loc and ctyp and class_type | CtSig of loc and Ploc.vala (option ctyp) and Ploc.vala (list class_sig_item) | CtXtr of loc and string and option (Ploc.vala class_type) | CtAtt of loc and class_type and attribute | CtExten of loc and attribute ] and class_sig_item = MLast.class_sig_item == [ CgCtr of loc and ctyp and ctyp and attributes | CgDcl of loc and Ploc.vala (list class_sig_item) | CgInh of loc and class_type and attributes | CgMth of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CgVal of loc and Ploc.vala bool and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CgVir of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CgFlAtt of loc and attribute | CgExten of loc and attribute ] and class_expr = MLast.class_expr == [ CeApp of loc and class_expr and expr | CeCon of loc and Ploc.vala longid_lident and Ploc.vala (list ctyp) | CeFun of loc and patt and class_expr | CeLet of loc and Ploc.vala bool and Ploc.vala (list (patt * expr * attributes)) and class_expr | CeLop of loc and Ploc.vala bool and longid and class_expr | CeStr of loc and Ploc.vala (option patt) and Ploc.vala (list class_str_item) | CeTyc of loc and class_expr and class_type | CeXtr of loc and string and option (Ploc.vala class_expr) | CeAtt of loc and class_expr and attribute | CeExten of loc and attribute ] and class_str_item = MLast.class_str_item == [ CrCtr of loc and ctyp and ctyp and attributes | CrDcl of loc and Ploc.vala (list class_str_item) | CrInh of loc and Ploc.vala bool and class_expr and Ploc.vala (option string) and attributes | CrIni of loc and expr and attributes | CrMth of loc and Ploc.vala bool and Ploc.vala bool and Ploc.vala string and Ploc.vala (option ctyp) and expr and attributes | CrVal of loc and Ploc.vala bool and Ploc.vala bool and Ploc.vala string and expr and attributes | CrVav of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CrVir of loc and Ploc.vala bool and Ploc.vala string and ctyp and attributes | CrFlAtt of loc and attribute | CrExten of loc and attribute ] and longid_lident = (option (Ploc.vala longid) * Ploc.vala string) and payload = MLast.payload == [ StAttr of loc and Ploc.vala (list str_item) | SiAttr of loc and Ploc.vala (list sig_item) | TyAttr of loc and Ploc.vala ctyp | PaAttr of loc and Ploc.vala patt and option (Ploc.vala expr) ] and attribute_body = (Ploc.vala (loc * string) * payload) and attribute = Ploc.vala attribute_body and attributes_no_anti = list attribute and attributes = Ploc.vala attributes_no_anti[@@"deriving_inline" show;]; value rec pp_class_infos : ! α . Fmt.t α → Fmt.t (class_infos α) = fun (type a) (tp_0 : Fmt.t a) (ofmt : Format.formatter) arg → (fun ofmt ({ciLoc = v_ciLoc; ciVir = v_ciVir; ciPrm = v_ciPrm; ciNam = v_ciNam; ciExp = v_ciExp; ciAttributes = v_ciAttributes} : class_infos a) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>{ @[Pp_MLast.ciLoc =@ %a@];@ @[ciVir =@ %a@];@ @[ciPrm =@ %a@];@ @[ciNam =@ %a@];@ @[ciExp =@ %a@];@ @[ciAttributes =@ %a@] }@]" pp_loc v_ciLoc (Ploc.pp_vala Fmt.bool) v_ciVir (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v1) v_ciPrm (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v_ciNam tp_0 v_ciExp pp_attributes v_ciAttributes) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_infos : ! α . Fmt.t α → class_infos α → Stdlib.String.t = fun (type a) (tp_0 : Fmt.t a) arg → Format.asprintf "%a" (pp_class_infos tp_0) arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_longid : Fmt.t longid = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ LiAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | LiApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 pp_longid v2 | LiUid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiUid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | LiXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.LiXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_longid) arg ]) v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_longid : longid → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_longid arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_ctyp : Fmt.t ctyp = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ TyAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | TyAli v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAli@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 | TyAny v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAny@ %a)@]" pp_loc v0 | TyApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 | TyArr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyArr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 | TyCls v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyCls@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 | TyLab v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyLab@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 | TyLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | TyMan v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyMan@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 (Ploc.pp_vala Fmt.bool) v2 pp_ctyp v3 | TyObj v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyObj@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) arg ]) v0 pp_ctyp v1 pp_attributes v2)) arg)) v1 (Ploc.pp_vala Fmt.bool) v2 | TyOlb v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyOlb@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 | TyOpn v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyOpn@ %a)@]" pp_loc v0 | TyPck v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyPck@ (@,%a,@ %a@,))@]" pp_loc v0 pp_module_type v1 | TyPol v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyPol@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v1 pp_ctyp v2 | TyPot v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyPot@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v1 pp_ctyp v2 | TyQuo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyQuo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | TyRec v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyRec@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2, v3, v4) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a,@ %a,@ %a@])" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 Fmt.bool v2 pp_ctyp v3 pp_attributes v4)) arg)) v1 | TySum v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TySum@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_generic_constructor) arg)) v1 | TyTup v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyTup@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v1 | TyVrn v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyVrn@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_poly_variant) arg)) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) arg ]) arg ]) v2 | TyXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_ctyp) arg ]) v2 | TyAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_attribute v2 | TyExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_ctyp : ctyp → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_ctyp arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_poly_variant : Fmt.t poly_variant = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ PvTag v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PvTag@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v3 pp_attributes v4 | PvInh v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PvInh@ (@,%a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_poly_variant : poly_variant → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_poly_variant arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_patt : Fmt.t patt = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ PaPfx v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaPfx@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 pp_patt v2 | PaLong v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLong@ (@,%a,@ %a@,))@]" pp_loc v0 pp_longid v1 | PaAli v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAli@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaAnt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAnt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_patt v1 | PaAny v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAny@ %a)@]" pp_loc v0 | PaApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaArr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaArr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_patt) arg)) v1 | PaChr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaChr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaExc v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaExc@ (@,%a,@ %a@,))@]" pp_loc v0 pp_patt v1 | PaFlo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaFlo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaInt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaInt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v2 | PaLab v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLab@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_patt arg ])) v1)) arg)) v1 | PaLaz v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLaz@ (@,%a,@ %a@,))@]" pp_loc v0 pp_patt v1 | PaLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaNty v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaNty@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaOlb v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaOlb@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | PaOrp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaOrp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaRec v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaRec@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 pp_patt v1)) arg)) v1 | PaRng v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaRng@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_patt v2 | PaStr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaStr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaTup v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaTup@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_patt) arg)) v1 | PaTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_ctyp v2 | PaTyp v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaTyp@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 | PaUnp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaUnp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v2 | PaVrn v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaVrn@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | PaXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_patt) arg ]) v2 | PaAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_attribute v2 | PaExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_patt : patt → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_patt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_expr : Fmt.t expr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ ExAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 | ExAnt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAnt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_expr v1 | ExApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 | ExAre v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAre@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_expr v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v3 | ExArr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExArr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v1 | ExAsr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAsr@ (@,%a,@ %a@,))@]" pp_loc v0 pp_expr v1 | ExAss v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAss@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 | ExBae v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExBae@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_expr v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v3 | ExChr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExChr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExCoe v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExCoe@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ]) v2 pp_ctyp v3 | ExFlo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExFlo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExFor v0 v1 v2 v3 v4 v5 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExFor@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_expr v2 pp_expr v3 (Ploc.pp_vala Fmt.bool) v4 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v5 | ExFun v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExFun@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_case_branch) arg)) v1 | ExIfe v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExIfe@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_expr v2 pp_expr v3 | ExInt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExInt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v2 | ExLab v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLab@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v1)) arg)) v1 | ExLaz v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLaz@ (@,%a,@ %a@,))@]" pp_loc v0 pp_expr v1 | ExLet v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLet@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 pp_expr v1 pp_attributes v2)) arg)) v2 pp_expr v3 | ExLEx v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLEx@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 pp_expr v3 pp_attributes v4 | ExLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExLmd v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLmd@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v1 pp_module_expr v2 pp_expr v3 | ExLop v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExLop@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_module_expr v2 pp_expr v3 | ExMat v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExMat@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_case_branch) arg)) v2 | ExNew v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExNew@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 | ExObj v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExObj@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_patt arg ])) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_str_item) arg)) v2 | ExOlb v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExOlb@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | ExOvr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExOvr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v0 pp_expr v1)) arg)) v1 | ExPck v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExPck@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v2 | ExRec v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExRec@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_patt v0 pp_expr v1)) arg)) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ]) v2 | ExSeq v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExSeq@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v1 | ExSnd v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExSnd@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | ExSte v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExSte@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_expr v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v3 | ExStr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExStr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExTry v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExTry@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_case_branch) arg)) v2 | ExTup v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExTup@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v1 | ExTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_ctyp v2 | ExUid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExUid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExVrn v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExVrn@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | ExWhi v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExWhi@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_expr) arg)) v2 | ExXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_expr) arg ]) v2 | ExAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_attribute v2 | ExExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | ExUnr v0 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.ExUnr@ %a)@]" pp_loc v0 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_expr : expr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_expr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_case_branch : Fmt.t case_branch = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v1 pp_expr v2) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_case_branch : case_branch → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_case_branch arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_module_type : Fmt.t module_type = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ MtLong v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtLong@ (@,%a,@ %a@,))@]" pp_loc v0 pp_longid v1 | MtLongLid v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtLongLid@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | MtLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | MtFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1) arg ])) v1 pp_module_type v2 | MtQuo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtQuo@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | MtSig v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtSig@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_sig_item) arg)) v1 | MtTyo v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtTyo@ (@,%a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 | MtWit v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtWit@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_type v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_with_constr) arg)) v2 | MtXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_module_type) arg ]) v2 | MtAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_type v1 pp_attribute v2 | MtExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MtExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_module_type : module_type → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_module_type arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_functor_parameter : Fmt.t functor_parameter = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1) arg ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_functor_parameter : functor_parameter → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_functor_parameter arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_sig_item : Fmt.t sig_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ SgCls v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgCls@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_type)) arg)) v1 | SgClt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgClt@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_type)) arg)) v1 | SgDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_sig_item) arg)) v1 | SgDir v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgDir@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | SgExc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgExc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_generic_constructor v1 pp_attributes v2 | SgExt v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgExt@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v3 pp_attributes v4 | SgInc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgInc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_type v1 pp_attributes v2 | SgMod v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgMod@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1 pp_attributes v2)) arg)) v2 | SgMty v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgMty@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_module_type v2 pp_attributes v3 | SgMtyAlias v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgMtyAlias@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala pp_longid) v2 pp_attributes v3 | SgModSubst v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgModSubst@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_longid v2 pp_attributes v3 | SgOpn v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgOpn@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 pp_attributes v2 | SgTyp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgTyp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_decl) arg)) v2 | SgTypExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgTypExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_type_extension v1 | SgUse v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgUse@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_sig_item v0 pp_loc v1)) arg)) v2 | SgVal v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgVal@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 pp_attributes v3 | SgXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_sig_item) arg ]) v2 | SgFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | SgExten v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SgExten@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_attribute v1 pp_attributes v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_sig_item : sig_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_sig_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_with_constr : Fmt.t with_constr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ WcMod v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcMod@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid) v1 pp_module_expr v2 | WcMos v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcMos@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid) v1 pp_module_expr v2 | WcTyp v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcTyp@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v2 (Ploc.pp_vala Fmt.bool) v3 pp_ctyp v4 | WcTys v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.WcTys@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v2 pp_ctyp v3 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_with_constr : with_constr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_with_constr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_module_expr : Fmt.t module_expr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ MeAcc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeAcc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_module_expr v2 | MeApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_module_expr v2 | MeFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_type v1) arg ])) v1 pp_module_expr v2 | MeStr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeStr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_str_item) arg)) v1 | MeTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_module_type v2 | MeUid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeUid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | MeUnp v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeUnp@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v2 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_module_type arg ]) v3 | MeXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_module_expr) arg ]) v2 | MeAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_attribute v2 | MeExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.MeExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_module_expr : module_expr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_module_expr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_str_item : Fmt.t str_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ StCls v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StCls@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_expr)) arg)) v1 | StClt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StClt@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (pp_class_infos pp_class_type)) arg)) v1 | StDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_str_item) arg)) v1 | StDir v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StDir@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_expr arg ])) v2 | StExc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_extension_constructor) v1 pp_attributes v2 | StExp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_attributes v2 | StExt v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExt@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_ctyp v2 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg)) v3 pp_attributes v4 | StInc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StInc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_module_expr v1 pp_attributes v2 | StMod v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StMod@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) arg ])) v0 pp_module_expr v1 pp_attributes v2)) arg)) v2 | StMty v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StMty@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 pp_module_type v2 pp_attributes v3 | StOpn v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StOpn@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_module_expr v2 pp_attributes v3 | StTyp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StTyp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_decl) arg)) v2 | StTypExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StTypExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_type_extension v1 | StUse v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StUse@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_str_item v0 pp_loc v1)) arg)) v2 | StVal v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StVal@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 pp_expr v1 pp_attributes v2)) arg)) v2 | StXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_str_item) arg ]) v2 | StFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | StExten v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StExten@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_attribute v1 pp_attributes v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_str_item : str_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_str_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_type_decl : Fmt.t type_decl = fun (ofmt : Format.formatter) arg → (fun ofmt ({tdIsDecl = v_tdIsDecl; tdNam = v_tdNam; tdPrm = v_tdPrm; tdPrv = v_tdPrv; tdDef = v_tdDef; tdCon = v_tdCon; tdAttributes = v_tdAttributes} : type_decl) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>{ @[MLast.tdIsDecl =@ %a@];@ @[tdNam =@ %a@];@ @[tdPrm =@ %a@];@ @[tdPrv =@ %a@];@ @[tdDef =@ %a@];@ @[tdCon =@ %a@];@ @[tdAttributes =@ %a@] }@]" (Ploc.pp_vala Fmt.bool) v_tdIsDecl (Ploc.pp_vala (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1)) v_tdNam (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v_tdPrm (Ploc.pp_vala Fmt.bool) v_tdPrv pp_ctyp v_tdDef (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_ctyp v0 pp_ctyp v1)) arg)) v_tdCon pp_attributes v_tdAttributes) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_type_decl : type_decl → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_type_decl arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_generic_constructor : Fmt.t generic_constructor = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1, v2, v3, v4) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a,@ %a,@ %a@])" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ])) v3 pp_attributes v4) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_generic_constructor : generic_constructor → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_generic_constructor arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_extension_constructor : Fmt.t extension_constructor = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ EcTuple v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.EcTuple@ (@,%a,@ %a@,))@]" pp_loc v0 pp_generic_constructor v1 | EcRebind v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.EcRebind@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 (Ploc.pp_vala pp_longid) v2 pp_attributes v3 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_extension_constructor : extension_constructor → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_extension_constructor arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_type_extension : Fmt.t type_extension = fun (ofmt : Format.formatter) arg → (fun ofmt ({teNam = v_teNam; tePrm = v_tePrm; tePrv = v_tePrv; teECs = v_teECs; teAttributes = v_teAttributes} : type_extension) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>{ @[MLast.teNam =@ %a@];@ @[tePrm =@ %a@];@ @[tePrv =@ %a@];@ @[teECs =@ %a@];@ @[teAttributes =@ %a@] }@]" (Ploc.pp_vala pp_longid_lident) v_teNam (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_type_var) arg)) v_tePrm (Ploc.pp_vala Fmt.bool) v_tePrv (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_extension_constructor) arg)) v_teECs pp_attributes v_teAttributes) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_type_extension : type_extension → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_type_extension arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_type : Fmt.t class_type = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CtLongLid v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtLongLid@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_longid v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 | CtLid v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtLid@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1 | CtLop v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtLop@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_longid v2 pp_class_type v3 | CtCon v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtCon@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_type v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 | CtFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_class_type v2 | CtSig v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtSig@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ])) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_sig_item) arg)) v2 | CtXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_class_type) arg ]) v2 | CtAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_type v1 pp_attribute v2 | CtExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CtExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_type : class_type → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_type arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_sig_item : Fmt.t class_sig_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CgCtr v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgCtr@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 pp_attributes v3 | CgDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_sig_item) arg)) v1 | CgInh v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgInh@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_type v1 pp_attributes v2 | CgMth v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgMth@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CgVal v0 v1 v2 v3 v4 v5 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgVal@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v3 pp_ctyp v4 pp_attributes v5 | CgVir v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgVir@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CgFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | CgExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CgExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_sig_item : class_sig_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_sig_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_expr : Fmt.t class_expr = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CeApp v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeApp@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_expr v1 pp_expr v2 | CeCon v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeCon@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_longid_lident) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_ctyp) arg)) v2 | CeFun v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeFun@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_patt v1 pp_class_expr v2 | CeLet v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeLet@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} (fun (ofmt : Format.formatter) (v0, v1, v2) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a,@ %a@])" pp_patt v0 pp_expr v1 pp_attributes v2)) arg)) v2 pp_class_expr v3 | CeLop v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeLop@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_longid v2 pp_class_expr v3 | CeStr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeStr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_patt arg ])) v1 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_str_item) arg)) v2 | CeTyc v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeTyc@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_expr v1 pp_class_type v2 | CeXtr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeXtr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_class_expr) arg ]) v2 | CeAtt v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeAtt@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_class_expr v1 pp_attribute v2 | CeExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CeExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_expr : class_expr → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_expr arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_class_str_item : Fmt.t class_str_item = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ CrCtr v0 v1 v2 v3 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrCtr@ (@,%a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 pp_ctyp v1 pp_ctyp v2 pp_attributes v3 | CrDcl v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrDcl@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_class_str_item) arg)) v1 | CrInh v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrInh@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 pp_class_expr v2 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) arg ])) v3 pp_attributes v4 | CrIni v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrIni@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 pp_expr v1 pp_attributes v2 | CrMth v0 v1 v2 v3 v4 v5 v6 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrMth@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v3 (Ploc.pp_vala (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" pp_ctyp arg ])) v4 pp_expr v5 pp_attributes v6 | CrVal v0 v1 v2 v3 v4 v5 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrVal@ (@,%a,@ %a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala Fmt.bool) v2 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v3 pp_expr v4 pp_attributes v5 | CrVav v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrVav@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CrVir v0 v1 v2 v3 v4 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrVir@ (@,%a,@ %a,@ %a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala Fmt.bool) v1 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v2 pp_ctyp v3 pp_attributes v4 | CrFlAtt v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrFlAtt@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 | CrExten v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.CrExten@ (@,%a,@ %a@,))@]" pp_loc v0 pp_attribute v1 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_class_str_item : class_str_item → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_class_str_item arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_longid_lident : Fmt.t longid_lident = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_longid) arg ]) v0 (Ploc.pp_vala (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg)) v1) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_longid_lident : longid_lident → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_longid_lident arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_payload : Fmt.t payload = fun (ofmt : Format.formatter) arg → (fun ofmt → fun [ StAttr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.StAttr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_str_item) arg)) v1 | SiAttr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.SiAttr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_sig_item) arg)) v1 | TyAttr v0 v1 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.TyAttr@ (@,%a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_ctyp) v1 | PaAttr v0 v1 v2 → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[<2>MLast.PaAttr@ (@,%a,@ %a,@ %a@,))@]" pp_loc v0 (Ploc.pp_vala pp_patt) v1 (fun ofmt → fun [ None → let open Pa_ppx_runtime.Runtime.Fmt in const string "None" ofmt () | Some arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(Some %a)" (Ploc.pp_vala pp_expr) arg ]) v2 ]) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_payload : payload → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_payload arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attribute_body : Fmt.t attribute_body = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" (Ploc.pp_vala (fun (ofmt : Format.formatter) (v0, v1) → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "(@[%a,@ %a@])" pp_loc v0 (fun ofmt arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "%S" arg) v1)) v0 pp_payload v1) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attribute_body : attribute_body → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attribute_body arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attribute : Fmt.t attribute = fun (ofmt : Format.formatter) arg → Ploc.pp_vala pp_attribute_body ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attribute : attribute → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attribute arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attributes_no_anti : Fmt.t attributes_no_anti = fun (ofmt : Format.formatter) arg → (fun (ofmt : Format.formatter) arg → let open Pa_ppx_runtime.Runtime.Fmt in pf ofmt "@[<2>[%a@,]@]" (list ~{sep = semi} pp_attribute) arg) ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attributes_no_anti : attributes_no_anti → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attributes_no_anti arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and pp_attributes : Fmt.t attributes = fun (ofmt : Format.formatter) arg → Ploc.pp_vala pp_attributes_no_anti ofmt arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] and show_attributes : attributes → Stdlib.String.t = fun arg → Format.asprintf "%a" pp_attributes arg[@@"ocaml.warning" "-39";] [@@"ocaml.warning" "-33";] ; [@@@"end"];
50c128b3b549aa28a57a0c5ff89b8e491363b692c6580cc4ecd9e0c38651e5cb
raimohanska/rump
StringBuffer.hs
module Util.StringBuffer(StringBuffer, newSB, appendSB, readSB) where import Data.IORef import Control.Monad data StringBuffer = StringBuffer (IORef [String]) newSB = liftM StringBuffer $ newIORef [] appendSB sb s = modifyIORef sb (s :) readSB = readIORef >=> return . concat
null
https://raw.githubusercontent.com/raimohanska/rump/f64c95fe80bb37dedb3f55627c3450c878c66e80/src/Util/StringBuffer.hs
haskell
module Util.StringBuffer(StringBuffer, newSB, appendSB, readSB) where import Data.IORef import Control.Monad data StringBuffer = StringBuffer (IORef [String]) newSB = liftM StringBuffer $ newIORef [] appendSB sb s = modifyIORef sb (s :) readSB = readIORef >=> return . concat
ce80a4cf8c950216285d523b5474e410f1d40e8c517863edd7e157ba10c6887b
nixeagle/nisp
beta.lisp
(in-package :nisp.i) (define-simple-command beta (network-tree::next-node)) (defun shorturl-is.gd (string) (declare (type string string)) (drakma:http-request "" :parameters `(("longurl" . ,string)))) (define-simple-command beta-shorturl (reply (shorturl-is.gd (remaining-parameters)))) (define-simple-command beta-getip (reply (format nil "~{~{~A~^.~}~^ ~}" (mapcar (lambda (ip-vector) (coerce ip-vector 'list)) (usocket::get-hosts-by-name (remaining-parameters))))))
null
https://raw.githubusercontent.com/nixeagle/nisp/680b40b3b9ea4c33db0455ac73cbe3756afdbb1e/irc-bot/commands/beta.lisp
lisp
(in-package :nisp.i) (define-simple-command beta (network-tree::next-node)) (defun shorturl-is.gd (string) (declare (type string string)) (drakma:http-request "" :parameters `(("longurl" . ,string)))) (define-simple-command beta-shorturl (reply (shorturl-is.gd (remaining-parameters)))) (define-simple-command beta-getip (reply (format nil "~{~{~A~^.~}~^ ~}" (mapcar (lambda (ip-vector) (coerce ip-vector 'list)) (usocket::get-hosts-by-name (remaining-parameters))))))
3ce17410623b3234357c3fbb96b2952ec824950e1f2476af9308ac93c0cd64e0
elisehuard/game-in-haskell
Main.hs
import Testing.Sound import Testing.Backend import Testing.Graphics import Testing.Game import Testing.CommandLine import System.Exit ( exitSuccess ) import System.Random import Control.Concurrent (threadDelay) import Control.Monad (unless, join, when) import Control.Monad.Fix (fix) import FRP.Elerea.Simple as Elerea import Testing.GameTypes import Options import Control.Applicative ((<*>), pure) import Control.Concurrent (forkIO, newEmptyMVar) import Data.Aeson import Data.Maybe (fromMaybe, isJust, fromJust) import qualified Data.ByteString.Lazy as B (readFile) import qualified Data.ByteString.Lazy.Char8 as BC (lines) width :: Int width = 640 height :: Int height = 480 data MainOptions = MainOptions { optStartFile :: Maybe String , optInteractive :: Bool , optLog :: Maybe String } deriving Show instance Options.Options MainOptions where defineOptions = pure MainOptions <*> simpleOption "start-state" Nothing "file containing start state" <*> simpleOption "interactive" False "start an interactive session" <*> simpleOption "log" Nothing "file containing input logs" getStartState :: MainOptions -> IO StartState getStartState opts = if (isJust (optStartFile opts)) then fmap (\mb -> fromMaybe defaultStart mb) $ fmap decode $ B.readFile (fromJust (optStartFile opts)) else return defaultStart main :: IO () main = runCommand $ \opts _ -> do print opts startState <- getStartState opts commandVar <- newEmptyMVar when (optInteractive opts) $ do _ <- forkIO (interactiveCommandLine commandVar) return () (snapshotGen, snapshotSink) <- external (0,False) (recordGen, recordSink) <- external (0, False, False) (commandsGen, commandSink) <- external Nothing (directionKeyGen, directionKeySink) <- external (False, False, False, False) (shootKeyGen, shootKeySink) <- external (False, False, False, False) (windowSizeGen,windowSizeSink) <- external (fromIntegral width, fromIntegral height) randomGenerator <- newStdGen glossState <- initState textures <- loadTextures withWindow width height windowSizeSink "Game-Demo" $ \win -> do withSound $ \_ _ -> do sounds <- loadSounds backgroundMusic (backgroundTune sounds) network <- start $ do snapshot <- snapshotGen record <- recordGen commands <- commandsGen directionKey <- directionKeyGen shootKey <- shootKeyGen windowSize <- windowSizeGen hunted win windowSize directionKey shootKey randomGenerator textures glossState sounds startState snapshot record commands if (isJust (optLog opts)) then do inputs <- externalInputs (fromJust (optLog opts)) (flip mapM_) inputs $ \input -> do replayInput win input directionKeySink shootKeySink snapshotSink recordSink commandSink join network threadDelay 20000 else fix $ \loop -> do readInput win directionKeySink shootKeySink snapshotSink recordSink commandSink commandVar join network threadDelay 20000 esc <- exitKeyPressed win unless esc loop exitSuccess externalInputs :: String -> IO [ExternalInput] externalInputs file = fmap (map decodeOrThrow) $ fmap BC.lines $ B.readFile file where decodeOrThrow string = case (decode string :: Maybe ExternalInput) of Just x -> x Nothing -> error $ "Log file contains line that can't be decoded: " ++ show string
null
https://raw.githubusercontent.com/elisehuard/game-in-haskell/b755c42d63ff5dc9246b46590fb23ebcc1d455b1/src/Testing/Main.hs
haskell
import Testing.Sound import Testing.Backend import Testing.Graphics import Testing.Game import Testing.CommandLine import System.Exit ( exitSuccess ) import System.Random import Control.Concurrent (threadDelay) import Control.Monad (unless, join, when) import Control.Monad.Fix (fix) import FRP.Elerea.Simple as Elerea import Testing.GameTypes import Options import Control.Applicative ((<*>), pure) import Control.Concurrent (forkIO, newEmptyMVar) import Data.Aeson import Data.Maybe (fromMaybe, isJust, fromJust) import qualified Data.ByteString.Lazy as B (readFile) import qualified Data.ByteString.Lazy.Char8 as BC (lines) width :: Int width = 640 height :: Int height = 480 data MainOptions = MainOptions { optStartFile :: Maybe String , optInteractive :: Bool , optLog :: Maybe String } deriving Show instance Options.Options MainOptions where defineOptions = pure MainOptions <*> simpleOption "start-state" Nothing "file containing start state" <*> simpleOption "interactive" False "start an interactive session" <*> simpleOption "log" Nothing "file containing input logs" getStartState :: MainOptions -> IO StartState getStartState opts = if (isJust (optStartFile opts)) then fmap (\mb -> fromMaybe defaultStart mb) $ fmap decode $ B.readFile (fromJust (optStartFile opts)) else return defaultStart main :: IO () main = runCommand $ \opts _ -> do print opts startState <- getStartState opts commandVar <- newEmptyMVar when (optInteractive opts) $ do _ <- forkIO (interactiveCommandLine commandVar) return () (snapshotGen, snapshotSink) <- external (0,False) (recordGen, recordSink) <- external (0, False, False) (commandsGen, commandSink) <- external Nothing (directionKeyGen, directionKeySink) <- external (False, False, False, False) (shootKeyGen, shootKeySink) <- external (False, False, False, False) (windowSizeGen,windowSizeSink) <- external (fromIntegral width, fromIntegral height) randomGenerator <- newStdGen glossState <- initState textures <- loadTextures withWindow width height windowSizeSink "Game-Demo" $ \win -> do withSound $ \_ _ -> do sounds <- loadSounds backgroundMusic (backgroundTune sounds) network <- start $ do snapshot <- snapshotGen record <- recordGen commands <- commandsGen directionKey <- directionKeyGen shootKey <- shootKeyGen windowSize <- windowSizeGen hunted win windowSize directionKey shootKey randomGenerator textures glossState sounds startState snapshot record commands if (isJust (optLog opts)) then do inputs <- externalInputs (fromJust (optLog opts)) (flip mapM_) inputs $ \input -> do replayInput win input directionKeySink shootKeySink snapshotSink recordSink commandSink join network threadDelay 20000 else fix $ \loop -> do readInput win directionKeySink shootKeySink snapshotSink recordSink commandSink commandVar join network threadDelay 20000 esc <- exitKeyPressed win unless esc loop exitSuccess externalInputs :: String -> IO [ExternalInput] externalInputs file = fmap (map decodeOrThrow) $ fmap BC.lines $ B.readFile file where decodeOrThrow string = case (decode string :: Maybe ExternalInput) of Just x -> x Nothing -> error $ "Log file contains line that can't be decoded: " ++ show string
a80a24f50bf3c907e42d28c67460e7b3f0a6d9e9defeba76a71f92c058dbf020
okuoku/nausicaa
compile-all.ypsilon.sps
;;; Part of : / Contents : compile script for Ypsilon Scheme Date : Sat Dec 26 , 2009 ;;; ;;;Abstract ;;; ;;; ;;; Copyright ( c ) 2009 < > ;;; ;;;This program is free software: you can redistribute it and/or modify ;;;it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at ;;;your option) any later version. ;;; ;;;This program is distributed in the hope that it will be useful, but ;;;WITHOUT ANY WARRANTY; without even the implied warranty of ;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details . ;;; You should have received a copy of the GNU General Public License ;;;along with this program. If not, see </>. ;;; (import (only (foreign crypto gpg-error)) (only (foreign crypto gcrypt)) (only (foreign crypto gcrypt compensated)) (only (foreign crypto gcrypt enumerations)) ) ;;; end of file
null
https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/gcrypt/src/libraries/compile-all.ypsilon.sps
scheme
Abstract This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU along with this program. If not, see </>. end of file
Part of : / Contents : compile script for Ypsilon Scheme Date : Sat Dec 26 , 2009 Copyright ( c ) 2009 < > the Free Software Foundation , either version 3 of the License , or ( at General Public License for more details . You should have received a copy of the GNU General Public License (import (only (foreign crypto gpg-error)) (only (foreign crypto gcrypt)) (only (foreign crypto gcrypt compensated)) (only (foreign crypto gcrypt enumerations)) )
d23e753b13519b0eac69817effb2079df8bdfa0be8ba5fe3c1faaa88ba7062ba
cyga/real-world-haskell
add.hs
-- file: ch03/add.hs myNot True = False myNot False = True -- file: ch03/add.hs sumList (x:xs) = x + sumList xs sumList [] = 0
null
https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch03/add.hs
haskell
file: ch03/add.hs file: ch03/add.hs
myNot True = False myNot False = True sumList (x:xs) = x + sumList xs sumList [] = 0
0eb36fbdc822d3619a8535a6be76de75e281da6be569a047e9821eefeb0e30ee
UU-ComputerScience/uhc
Numeric.hs
# LANGUAGE CPP # # OPTIONS_GHC -XNoImplicitPrelude # ----------------------------------------------------------------------------- -- | -- Module : Numeric Copyright : ( c ) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Odds and ends, mostly functions for reading and showing -- 'RealFloat'-like kind of values. -- Adapted for EHC -- ----------------------------------------------------------------------------- module Numeric ( -- * Showing showSigned, -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS : : Integral a = > a - > ( a - > ) - > a - > ShowS showInt, -- :: Integral a => a -> ShowS showHex, -- :: Integral a => a -> ShowS showOct, -- :: Integral a => a -> ShowS showEFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS showFFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS showGFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS showFloat, -- :: (RealFloat a) => a -> ShowS floatToDigits, -- :: (RealFloat a) => Integer -> a -> ([Int], Int) -- * Reading -- | /NB:/ 'readInt' is the \'dual\' of 'showIntAtBase', -- and 'readDec' is the \`dual\' of 'showInt'. -- The inconsistent naming is a historical accident. readSigned, -- :: (Real a) => ReadS a -> ReadS a : : ( Integral a ) = > a - > ( Bool ) -- -> (Char -> Int) -> ReadS a readDec, -- :: (Integral a) => ReadS a readOct, -- :: (Integral a) => ReadS a readHex, -- :: (Integral a) => ReadS a readFloat, -- :: (RealFloat a) => ReadS a lexDigits, -- :: ReadS String -- * Miscellaneous #ifndef __UHC__ #endif fromRat, -- :: (RealFloat a) => Rational -> a ) where #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Read import GHC.Real import GHC.Float import GHC.Num import GHC.Show import Data.Maybe import Text.ParserCombinators.ReadP( ReadP, readP_to_S, pfail ) import qualified Text.Read.Lex as L #else import Data.Char #endif #ifdef __UHC__ import UHC.Float import UHC.Real import UHC.Show import Text . ParserCombinators . ReadP ( ReadP , readP_to_S , ) import qualified Text . Read . as L #endif #ifdef __HUGS__ import Hugs.Prelude import Hugs.Numeric #endif #ifdef __GLASGOW_HASKELL__ -- ----------------------------------------------------------------------------- -- Reading -- | Reads an /unsigned/ 'Integral' value in an arbitrary base. readInt :: Num a => a -- ^ the base -> (Char -> Bool) -- ^ a predicate distinguishing valid digits in this base -> (Char -> Int) -- ^ a function converting a valid digit character to an 'Int' -> ReadS a readInt base isDigit valDigit = readP_to_S (L.readIntP base isDigit valDigit) -- | Read an unsigned number in octal notation. readOct :: Num a => ReadS a readOct = readP_to_S L.readOctP -- | Read an unsigned number in decimal notation. readDec :: Num a => ReadS a readDec = readP_to_S L.readDecP -- | Read an unsigned number in hexadecimal notation. -- Both upper or lower case letters are allowed. readHex :: Num a => ReadS a readHex = readP_to_S L.readHexP -- | Reads an /unsigned/ 'RealFrac' value, -- expressed in decimal scientific notation. readFloat :: RealFrac a => ReadS a readFloat = readP_to_S readFloatP readFloatP :: RealFrac a => ReadP a readFloatP = do tok <- L.lex case tok of L.Rat y -> return (fromRational y) L.Int i -> return (fromInteger i) _ -> pfail -- It's turgid to have readSigned work using list comprehensions, -- but it's specified as a ReadS to ReadS transformer -- With a bit of luck no one will use it. -- | Reads a /signed/ 'Real' value, given a reader for an unsigned value. readSigned :: (Real a) => ReadS a -> ReadS a readSigned readPos = readParen False read' where read' r = read'' r ++ (do ("-",s) <- lex r (x,t) <- read'' s return (-x,t)) read'' r = do (str,s) <- lex r (n,"") <- readPos str return (n,s) -- ----------------------------------------------------------------------------- -- Showing | Show /non - negative/ ' Integral ' numbers in base 10 . showInt :: Integral a => a -> ShowS showInt n0 cs0 | n0 < 0 = error "Numeric.showInt: can't show negative numbers" | otherwise = go n0 cs0 where go n cs | n < 10 = case unsafeChr (ord '0' + fromIntegral n) of c@(C# _) -> c:cs | otherwise = case unsafeChr (ord '0' + fromIntegral r) of c@(C# _) -> go q (c:cs) where (q,r) = n `quotRem` 10 #endif /* __GLASGOW_HASKELL__ */ #if defined(__GLASGOW_HASKELL__) || defined(__UHC__) -- Controlling the format and precision of floats. The code that -- implements the formatting itself is in @PrelNum@ to avoid mutual module . {-# SPECIALIZE showEFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS #-} {-# SPECIALIZE showFFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS #-} {-# SPECIALIZE showGFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS #-} | Show a signed ' RealFloat ' value using scientific ( exponential ) notation ( e.g. @2.45e2@ , @1.5e-3@ ) . -- In the call @'showEFloat ' digs val@ , if @digs@ is ' Nothing ' , the value is shown to full precision ; if @digs@ is @'Just ' d@ , -- then at most @d@ digits after the decimal point are shown. showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS | Show a signed ' RealFloat ' value -- using standard decimal notation (e.g. @245000@, @0.0015@). -- In the call @'showFFloat ' digs val@ , if @digs@ is ' Nothing ' , the value is shown to full precision ; if @digs@ is @'Just ' d@ , -- then at most @d@ digits after the decimal point are shown. showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS | Show a signed ' RealFloat ' value -- using standard decimal notation for arguments whose absolute value lies between @0.1@ and @9,999,999@ , and scientific notation otherwise . -- In the call @'showGFloat ' digs val@ , if @digs@ is ' Nothing ' , the value is shown to full precision ; if @digs@ is @'Just ' d@ , -- then at most @d@ digits after the decimal point are shown. showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS showEFloat d x = showString (formatRealFloat FFExponent d x) showFFloat d x = showString (formatRealFloat FFFixed d x) showGFloat d x = showString (formatRealFloat FFGeneric d x) #endif /* __GLASGOW_HASKELL__ */ #ifndef __UHC__ -- --------------------------------------------------------------------------- Integer printing functions -- | Shows a /non-negative/ 'Integral' number using the base specified by the first argument , and the character representation specified by the second . showIntAtBase :: Integral a => a -> (Int -> Char) -> a -> ShowS showIntAtBase base toChr n0 r0 | base <= 1 = error ("Numeric.showIntAtBase: applied to unsupported base " ++ show base) | n0 < 0 = error ("Numeric.showIntAtBase: applied to negative number " ++ show n0) | otherwise = showIt (quotRem n0 base) r0 where showIt (n,d) r = seq c $ -- stricter than necessary case n of 0 -> r' _ -> showIt (quotRem n base) r' where c = toChr (fromIntegral d) r' = c : r | Show /non - negative/ ' Integral ' numbers in base 16 . showHex :: Integral a => a -> ShowS showHex = showIntAtBase 16 intToDigit | Show /non - negative/ ' Integral ' numbers in base 8 . showOct :: Integral a => a -> ShowS showOct = showIntAtBase 8 intToDigit #endif
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/ehclib/base/Numeric.hs
haskell
--------------------------------------------------------------------------- | Module : Numeric License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : provisional Portability : portable Odds and ends, mostly functions for reading and showing 'RealFloat'-like kind of values. --------------------------------------------------------------------------- * Showing :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS :: Integral a => a -> ShowS :: Integral a => a -> ShowS :: Integral a => a -> ShowS :: (RealFloat a) => Maybe Int -> a -> ShowS :: (RealFloat a) => Maybe Int -> a -> ShowS :: (RealFloat a) => Maybe Int -> a -> ShowS :: (RealFloat a) => a -> ShowS :: (RealFloat a) => Integer -> a -> ([Int], Int) * Reading | /NB:/ 'readInt' is the \'dual\' of 'showIntAtBase', and 'readDec' is the \`dual\' of 'showInt'. The inconsistent naming is a historical accident. :: (Real a) => ReadS a -> ReadS a -> (Char -> Int) -> ReadS a :: (Integral a) => ReadS a :: (Integral a) => ReadS a :: (Integral a) => ReadS a :: (RealFloat a) => ReadS a :: ReadS String * Miscellaneous :: (RealFloat a) => Rational -> a ----------------------------------------------------------------------------- Reading | Reads an /unsigned/ 'Integral' value in an arbitrary base. ^ the base ^ a predicate distinguishing valid digits in this base ^ a function converting a valid digit character to an 'Int' | Read an unsigned number in octal notation. | Read an unsigned number in decimal notation. | Read an unsigned number in hexadecimal notation. Both upper or lower case letters are allowed. | Reads an /unsigned/ 'RealFrac' value, expressed in decimal scientific notation. It's turgid to have readSigned work using list comprehensions, but it's specified as a ReadS to ReadS transformer With a bit of luck no one will use it. | Reads a /signed/ 'Real' value, given a reader for an unsigned value. ----------------------------------------------------------------------------- Showing Controlling the format and precision of floats. The code that implements the formatting itself is in @PrelNum@ to avoid # SPECIALIZE showEFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS # # SPECIALIZE showFFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS # # SPECIALIZE showGFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS # then at most @d@ digits after the decimal point are shown. using standard decimal notation (e.g. @245000@, @0.0015@). then at most @d@ digits after the decimal point are shown. using standard decimal notation for arguments whose absolute value lies then at most @d@ digits after the decimal point are shown. --------------------------------------------------------------------------- | Shows a /non-negative/ 'Integral' number using the base specified by the stricter than necessary
# LANGUAGE CPP # # OPTIONS_GHC -XNoImplicitPrelude # Copyright : ( c ) The University of Glasgow 2002 Adapted for EHC module Numeric ( : : Integral a = > a - > ( a - > ) - > a - > ShowS : : ( Integral a ) = > a - > ( Bool ) #ifndef __UHC__ #endif ) where #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Read import GHC.Real import GHC.Float import GHC.Num import GHC.Show import Data.Maybe import Text.ParserCombinators.ReadP( ReadP, readP_to_S, pfail ) import qualified Text.Read.Lex as L #else import Data.Char #endif #ifdef __UHC__ import UHC.Float import UHC.Real import UHC.Show import Text . ParserCombinators . ReadP ( ReadP , readP_to_S , ) import qualified Text . Read . as L #endif #ifdef __HUGS__ import Hugs.Prelude import Hugs.Numeric #endif #ifdef __GLASGOW_HASKELL__ readInt :: Num a -> ReadS a readInt base isDigit valDigit = readP_to_S (L.readIntP base isDigit valDigit) readOct :: Num a => ReadS a readOct = readP_to_S L.readOctP readDec :: Num a => ReadS a readDec = readP_to_S L.readDecP readHex :: Num a => ReadS a readHex = readP_to_S L.readHexP readFloat :: RealFrac a => ReadS a readFloat = readP_to_S readFloatP readFloatP :: RealFrac a => ReadP a readFloatP = do tok <- L.lex case tok of L.Rat y -> return (fromRational y) L.Int i -> return (fromInteger i) _ -> pfail readSigned :: (Real a) => ReadS a -> ReadS a readSigned readPos = readParen False read' where read' r = read'' r ++ (do ("-",s) <- lex r (x,t) <- read'' s return (-x,t)) read'' r = do (str,s) <- lex r (n,"") <- readPos str return (n,s) | Show /non - negative/ ' Integral ' numbers in base 10 . showInt :: Integral a => a -> ShowS showInt n0 cs0 | n0 < 0 = error "Numeric.showInt: can't show negative numbers" | otherwise = go n0 cs0 where go n cs | n < 10 = case unsafeChr (ord '0' + fromIntegral n) of c@(C# _) -> c:cs | otherwise = case unsafeChr (ord '0' + fromIntegral r) of c@(C# _) -> go q (c:cs) where (q,r) = n `quotRem` 10 #endif /* __GLASGOW_HASKELL__ */ #if defined(__GLASGOW_HASKELL__) || defined(__UHC__) mutual module . | Show a signed ' RealFloat ' value using scientific ( exponential ) notation ( e.g. @2.45e2@ , @1.5e-3@ ) . In the call @'showEFloat ' digs val@ , if @digs@ is ' Nothing ' , the value is shown to full precision ; if @digs@ is @'Just ' d@ , showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS | Show a signed ' RealFloat ' value In the call @'showFFloat ' digs val@ , if @digs@ is ' Nothing ' , the value is shown to full precision ; if @digs@ is @'Just ' d@ , showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS | Show a signed ' RealFloat ' value between @0.1@ and @9,999,999@ , and scientific notation otherwise . In the call @'showGFloat ' digs val@ , if @digs@ is ' Nothing ' , the value is shown to full precision ; if @digs@ is @'Just ' d@ , showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS showEFloat d x = showString (formatRealFloat FFExponent d x) showFFloat d x = showString (formatRealFloat FFFixed d x) showGFloat d x = showString (formatRealFloat FFGeneric d x) #endif /* __GLASGOW_HASKELL__ */ #ifndef __UHC__ Integer printing functions first argument , and the character representation specified by the second . showIntAtBase :: Integral a => a -> (Int -> Char) -> a -> ShowS showIntAtBase base toChr n0 r0 | base <= 1 = error ("Numeric.showIntAtBase: applied to unsupported base " ++ show base) | n0 < 0 = error ("Numeric.showIntAtBase: applied to negative number " ++ show n0) | otherwise = showIt (quotRem n0 base) r0 where case n of 0 -> r' _ -> showIt (quotRem n base) r' where c = toChr (fromIntegral d) r' = c : r | Show /non - negative/ ' Integral ' numbers in base 16 . showHex :: Integral a => a -> ShowS showHex = showIntAtBase 16 intToDigit | Show /non - negative/ ' Integral ' numbers in base 8 . showOct :: Integral a => a -> ShowS showOct = showIntAtBase 8 intToDigit #endif
59a47aafa886b0c27aa9d6ec999597f1403e90a49469708e45eb6b204d24b41e
8c6794b6/haskell-sc-scratch
WatchYourStep.hs
------------------------------------------------------------------------------ -- | -- Module : $Header$ -- License : BSD3 Maintainer : -- Stability : unstable -- Portability : non-portable -- module LearnYour.Zipper.WatchYourStep where import LearnYour.Zipper.Tree import LearnYour.Zipper.Scratch (Crumb(..), Zipper) goLeft :: Zipper a -> Maybe (Zipper a) goLeft (Node x l r, bs) = Just (l, LeftCrumb x r:bs) goLeft _ = Nothing goRight :: Zipper a -> Maybe (Zipper a) goRight (Node x l r, bs) = Just (r, RightCrumb x l:bs) goRight _ = Nothing goUp :: Zipper a -> Maybe (Zipper a) goUp (t, LeftCrumb x r: bs) = Just (Node x t r, bs) goUp (t, RightCrumb x l: bs) = Just (Node x l t, bs) goUp (_,_) = Nothing
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/LearnYour/Zipper/WatchYourStep.hs
haskell
---------------------------------------------------------------------------- | Module : $Header$ License : BSD3 Stability : unstable Portability : non-portable
Maintainer : module LearnYour.Zipper.WatchYourStep where import LearnYour.Zipper.Tree import LearnYour.Zipper.Scratch (Crumb(..), Zipper) goLeft :: Zipper a -> Maybe (Zipper a) goLeft (Node x l r, bs) = Just (l, LeftCrumb x r:bs) goLeft _ = Nothing goRight :: Zipper a -> Maybe (Zipper a) goRight (Node x l r, bs) = Just (r, RightCrumb x l:bs) goRight _ = Nothing goUp :: Zipper a -> Maybe (Zipper a) goUp (t, LeftCrumb x r: bs) = Just (Node x t r, bs) goUp (t, RightCrumb x l: bs) = Just (Node x l t, bs) goUp (_,_) = Nothing
4a5f2b6efb19874fe1fae534f548f3da4333d5cb9668fac3105277da14e1d657
mattmundell/nightshade
build-world.lisp
;;; Build all the Lisp code. ;;; ;;; Intended for a command like ;;; ;;; lisp -load src/tools/build-world.lisp ;;; ;;; or ;;; ;;; build-small/bin/lisp -core build-small/bin/lisp.core \ -eval " ( defvar user::src " ) " \ ;;; -load src/tools/build-world.lisp ;;; ;;; The source and target directories (variables src and target) are either ;;; supplied or set to "./src" and "./build/". Similarly the systems to ;;; compile can be set via the systems variable. (in-package "USER") (defvar src "./src/" "Location of the source.") (defvar target (if src (format () "~A/../build/" src) "./build/") "Destination directory for the build.") (defvar systems '(:lisp :compiler :ed :kernel) "A list of systems to build. Members of the list can be any of :code, :compiler, :ed and :kernel (the lisp kernel core), in any order") (defun preserve-logs (dir) "Backup previous log files." (format t "Preserving log files in ~A as .OLD...~%" dir) (dolist (file (lisp::enumerate-names (format () "~A/*.log" dir) () () () ())) FIX original appended the log to any existing old log (let ((old (format () "~A.OLD" file))) (if (probe-file old) (delete-file old)) (rename-file file old)))) (declaim (special *interactive*)) (defun build-world (src target systems) "Build Systems from Src into Target." (if src (or (eq (char src (1- (length src))) #\/) (setq src (format () "~A/" src))) FIX set to .. / .. /src relative to location of current script (setq src "./src/")) (or (probe-file src) (progn (format t "Source directory must exist.") (quit))) (format t "Source: ~A~%" src) (if target (or (eq (char target (1- (length target))) #\/) (setq target (format () "~A/" target))) (setq target "./build/")) (or (probe-file target) (progn (format t "Target directory must exist.") (quit))) (format t "Target: ~A~%" target) (preserve-logs target) (if (find-package "INTERFACE") (set (intern "*INTERFACE-STYLE*" "INTERFACE") :tty)) (setf (search-list "target:") `(,target ,src)) ;(format t "*features*: ~A~%" *features*) (format t "Loading features...~%") (load (open "target:features.lisp")) ;(format t "*features*: ~A~%" *features*) (format t "Loading setup...~%") (setq *compile-verbose* () *compile-print* ()) (load "target:tools/setup" :if-source-newer :load-source) (setf *interactive* () *gc-verbose* ()) ;; FIX quiet warning about def of comf (comf "target:tools/setup" :load t) (format t "Building these systems: ~A~%" systems) (when (probe-file "bootstrap.lisp") (format t "Loading bootstrap...") (comf "target:bootstrap" :load t)) (when (position :lisp systems) (format t "Compiling Lisp code...") (load "target:tools/worldcom")) (when (position :compiler systems) (format t "Compiling compiler...") (load "target:tools/comcom")) (when (position :ed systems) (format t "Compiling Editor...") (load "target:tools/edcom")) (when (position :kernel systems) (format t "Compiling kernel core...") (load "target:tools/worldbuild")) (when (position :boot systems) (format t "Compiling Boot code...") (load "target:tools/bootcom"))) (build-world src target systems)
null
https://raw.githubusercontent.com/mattmundell/nightshade/68e960eff95e007462f2613beabc6cac11e0dfa1/src/tools/build-world.lisp
lisp
Build all the Lisp code. Intended for a command like lisp -load src/tools/build-world.lisp or build-small/bin/lisp -core build-small/bin/lisp.core \ -load src/tools/build-world.lisp The source and target directories (variables src and target) are either supplied or set to "./src" and "./build/". Similarly the systems to compile can be set via the systems variable. (format t "*features*: ~A~%" *features*) (format t "*features*: ~A~%" *features*) FIX quiet warning about def of comf
-eval " ( defvar user::src " ) " \ (in-package "USER") (defvar src "./src/" "Location of the source.") (defvar target (if src (format () "~A/../build/" src) "./build/") "Destination directory for the build.") (defvar systems '(:lisp :compiler :ed :kernel) "A list of systems to build. Members of the list can be any of :code, :compiler, :ed and :kernel (the lisp kernel core), in any order") (defun preserve-logs (dir) "Backup previous log files." (format t "Preserving log files in ~A as .OLD...~%" dir) (dolist (file (lisp::enumerate-names (format () "~A/*.log" dir) () () () ())) FIX original appended the log to any existing old log (let ((old (format () "~A.OLD" file))) (if (probe-file old) (delete-file old)) (rename-file file old)))) (declaim (special *interactive*)) (defun build-world (src target systems) "Build Systems from Src into Target." (if src (or (eq (char src (1- (length src))) #\/) (setq src (format () "~A/" src))) FIX set to .. / .. /src relative to location of current script (setq src "./src/")) (or (probe-file src) (progn (format t "Source directory must exist.") (quit))) (format t "Source: ~A~%" src) (if target (or (eq (char target (1- (length target))) #\/) (setq target (format () "~A/" target))) (setq target "./build/")) (or (probe-file target) (progn (format t "Target directory must exist.") (quit))) (format t "Target: ~A~%" target) (preserve-logs target) (if (find-package "INTERFACE") (set (intern "*INTERFACE-STYLE*" "INTERFACE") :tty)) (setf (search-list "target:") `(,target ,src)) (format t "Loading features...~%") (load (open "target:features.lisp")) (format t "Loading setup...~%") (setq *compile-verbose* () *compile-print* ()) (load "target:tools/setup" :if-source-newer :load-source) (setf *interactive* () *gc-verbose* ()) (comf "target:tools/setup" :load t) (format t "Building these systems: ~A~%" systems) (when (probe-file "bootstrap.lisp") (format t "Loading bootstrap...") (comf "target:bootstrap" :load t)) (when (position :lisp systems) (format t "Compiling Lisp code...") (load "target:tools/worldcom")) (when (position :compiler systems) (format t "Compiling compiler...") (load "target:tools/comcom")) (when (position :ed systems) (format t "Compiling Editor...") (load "target:tools/edcom")) (when (position :kernel systems) (format t "Compiling kernel core...") (load "target:tools/worldbuild")) (when (position :boot systems) (format t "Compiling Boot code...") (load "target:tools/bootcom"))) (build-world src target systems)
8de3db5756dc0502ec2a3a611b72c3e3e05273dbd07b877d103eb11dfe43570b
tamarin-prover/tamarin-prover
Unicode.hs
-- | Copyright : ( c ) 2010 -- License : GPL v3 (see LICENSE) -- Maintainer : < > -- Portability : portable -- Support functions for exploiting Unicode characters . module Text.Unicode where -- | Convert a subscriptable character to its subsript. subscriptChar :: Char -> Char subscriptChar c = case c of '0' -> '₀' '1' -> '₁' '2' -> '₂' '3' -> '₃' '4' -> '₄' '5' -> '₅' '6' -> '₆' '7' -> '₇' '8' -> '₈' '9' -> '₉' '+' -> '₊' '-' -> '₋' '=' -> '₌' '(' -> '₍' ')' -> '₎' _ -> c -- FIXME: Add further characters from -- #super -- | Convert all subscriptable characters to subscripts. subscript :: String -> String subscript = map subscriptChar
null
https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/c78c7afd3b93b52dd4d2884952ec0fc273832a0d/lib/utils/src/Text/Unicode.hs
haskell
| License : GPL v3 (see LICENSE) Portability : portable | Convert a subscriptable character to its subsript. FIXME: Add further characters from #super | Convert all subscriptable characters to subscripts.
Copyright : ( c ) 2010 Maintainer : < > Support functions for exploiting Unicode characters . module Text.Unicode where subscriptChar :: Char -> Char subscriptChar c = case c of '0' -> '₀' '1' -> '₁' '2' -> '₂' '3' -> '₃' '4' -> '₄' '5' -> '₅' '6' -> '₆' '7' -> '₇' '8' -> '₈' '9' -> '₉' '+' -> '₊' '-' -> '₋' '=' -> '₌' '(' -> '₍' ')' -> '₎' subscript :: String -> String subscript = map subscriptChar
58adda590fe8825740f5006d1dd5d4c81857d01c3f056a1e2aaded93d7da9a9c
DougHamil/threeagent
core.cljs
(ns threeagent.core (:refer-clojure :exclude [atom]) (:require [threeagent.impl.scene :as scene] [threeagent.impl.types :refer [Context]] [reagent.ratom :as ratom])) (def atom ratom/atom) (def cursor ratom/cursor) (def track ratom/track) (defn render "Renders the threeagent scene at the specified `dom-root` using the `root-fn` as the root component function. Additional configuration can be provided through the `opts` parameter Example: ```clojure (threeagent/render my-root-fn (js/document.getElementById \"app\")) ``` " ([root-fn dom-root] (render root-fn dom-root {})) ([root-fn dom-root opts] (scene/render root-fn dom-root opts)))
null
https://raw.githubusercontent.com/DougHamil/threeagent/d1db04dc65845310f27dd3f7021be3a5b52140c2/src/main/threeagent/core.cljs
clojure
(ns threeagent.core (:refer-clojure :exclude [atom]) (:require [threeagent.impl.scene :as scene] [threeagent.impl.types :refer [Context]] [reagent.ratom :as ratom])) (def atom ratom/atom) (def cursor ratom/cursor) (def track ratom/track) (defn render "Renders the threeagent scene at the specified `dom-root` using the `root-fn` as the root component function. Additional configuration can be provided through the `opts` parameter Example: ```clojure (threeagent/render my-root-fn (js/document.getElementById \"app\")) ``` " ([root-fn dom-root] (render root-fn dom-root {})) ([root-fn dom-root opts] (scene/render root-fn dom-root opts)))
aae8681cb6cc840d267e2f35b5a3c0862a71327e69b41ec205dc5f33b77c9144
SumitPadhiyar/confuzz
lwt_afl_scheduler.mli
val fuzz : (unit -> unit) list -> unit (* Fuzzes an array of functions *) val get_fuzzed_calls : (unit -> 'a) list -> (unit -> 'a) list
null
https://raw.githubusercontent.com/SumitPadhiyar/confuzz/7d6b2af51d7135025f9ed1e013a9ae0940f3663e/src/core/lwt_afl_scheduler.mli
ocaml
Fuzzes an array of functions
val fuzz : (unit -> unit) list -> unit val get_fuzzed_calls : (unit -> 'a) list -> (unit -> 'a) list
385d28c61198d1723cbf1e5c41dc6112c014be341a6d317c2538ab9fa8ac9df5
dcos/dcos-net
dcos_rest_lashup_handler.erl
%%%------------------------------------------------------------------- @author sdhillon ( C ) 2016 , < COMPANY > %%% @doc %%% %%% @end Created : 24 . May 2016 9:34 PM %%%------------------------------------------------------------------- -module(dcos_rest_lashup_handler). -author("sdhillon"). %% API -export([ init/2, content_types_provided/2, allowed_methods/2, content_types_accepted/2, to_json/2, perform_op/2 ]). init(Req, Opts) -> {cowboy_rest, Req, Opts}. content_types_provided(Req, State) -> {[ {{<<"application">>, <<"json">>, []}, to_json} ], Req, State}. allowed_methods(Req, State) -> {[<<"GET">>, <<"POST">>], Req, State}. content_types_accepted(Req, State) -> {[ {{<<"text">>, <<"plain">>, []}, perform_op} ], Req, State}. perform_op(Req, State) -> Key = key(Req), case cowboy_req:header(<<"clock">>, Req, <<>>) of <<>> -> {{false, <<"Missing clock">>}, Req, State}; Clock -> Clock0 = binary_to_term(base64:decode(Clock)), {ok, Body, Req0} = cowboy_req:read_body(Req), Body0 = binary_to_list(Body), {ok, Scanned, _} = erl_scan:string(Body0), {ok, Parsed} = erl_parse:parse_exprs(Scanned), {value, Update, _Bindings} = erl_eval:exprs(Parsed, erl_eval:new_bindings()), perform_op(Key, Update, Clock0, Req0, State) end. perform_op(Key, Update, Clock, Req, State) -> case lashup_kv:request_op(Key, Clock, Update) of {ok, Value} -> Value0 = lists:map(fun encode_key/1, Value), {jsx:encode(Value0), Req, State}; {error, concurrency} -> {{false, <<"Concurrent update">>}, Req, State} end. to_json(Req, State) -> Key = key(Req), fetch_key(Key, Req, State). fetch_key(Key, Req, State) -> {Value, Clock} = lashup_kv:value2(Key), Value0 = lists:map(fun encode_key/1, Value), ClockBin = base64:encode(term_to_binary(Clock)), Req0 = cowboy_req:set_resp_header(<<"clock">>, ClockBin, Req), {jsx:encode(Value0), Req0, State}. key(Req) -> KeyHandler = cowboy_req:header(<<"key-handler">>, Req), KeyData = cowboy_req:path_info(Req), key(KeyData, KeyHandler). key([], _) -> erlang:throw(invalid_key); key(KeyData, _) -> lists:map(fun(X) -> binary_to_atom(X, utf8) end, KeyData). encode_key({{Name, Type = riak_dt_lwwreg}, Value}) -> #{value := Key} = encode_key(Name), {Key, [{type, Type}, {value, encode_key(Value)}]}; encode_key({{Name, Type = riak_dt_orswot}, Value}) -> #{value := Key} = encode_key(Name), {Key, [{type, Type}, {value, lists:map(fun encode_key/1, Value)}]}; encode_key(Value) when is_atom(Value) -> #{type => atom, value => Value}; encode_key(Value) when is_binary(Value) -> #{type => binary, value => Value}; encode_key(Value) when is_list(Value) -> #{type => string, value => list_to_binary(lists:flatten(Value))}; %% Probably an IP address? encode_key(IP = {A, B, C, D}) when is_integer(A) andalso is_integer(B) andalso is_integer(C) andalso is_integer(D) andalso A >= 0 andalso B >= 0 andalso C >= 0 andalso D >= 0 andalso A =< 255 andalso B =< 255 andalso C =< 255 andalso D =< 255 -> #{ type => ipaddress_tuple, value => list_to_binary(lists:flatten(inet:ntoa(IP))) }; encode_key(Value) when is_tuple(Value) -> #{ type => tuple, value => list_to_binary(lists:flatten(io_lib:format("~p", [Value]))) }; encode_key(Value) when is_tuple(Value) -> #{ type => unknown, value => list_to_binary(lists:flatten(io_lib:format("~p", [Value]))) }.
null
https://raw.githubusercontent.com/dcos/dcos-net/7bd01ac237ff4b9a12a020ed443e71c45f7063f4/apps/dcos_rest/src/dcos_rest_lashup_handler.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API Probably an IP address?
@author sdhillon ( C ) 2016 , < COMPANY > Created : 24 . May 2016 9:34 PM -module(dcos_rest_lashup_handler). -author("sdhillon"). -export([ init/2, content_types_provided/2, allowed_methods/2, content_types_accepted/2, to_json/2, perform_op/2 ]). init(Req, Opts) -> {cowboy_rest, Req, Opts}. content_types_provided(Req, State) -> {[ {{<<"application">>, <<"json">>, []}, to_json} ], Req, State}. allowed_methods(Req, State) -> {[<<"GET">>, <<"POST">>], Req, State}. content_types_accepted(Req, State) -> {[ {{<<"text">>, <<"plain">>, []}, perform_op} ], Req, State}. perform_op(Req, State) -> Key = key(Req), case cowboy_req:header(<<"clock">>, Req, <<>>) of <<>> -> {{false, <<"Missing clock">>}, Req, State}; Clock -> Clock0 = binary_to_term(base64:decode(Clock)), {ok, Body, Req0} = cowboy_req:read_body(Req), Body0 = binary_to_list(Body), {ok, Scanned, _} = erl_scan:string(Body0), {ok, Parsed} = erl_parse:parse_exprs(Scanned), {value, Update, _Bindings} = erl_eval:exprs(Parsed, erl_eval:new_bindings()), perform_op(Key, Update, Clock0, Req0, State) end. perform_op(Key, Update, Clock, Req, State) -> case lashup_kv:request_op(Key, Clock, Update) of {ok, Value} -> Value0 = lists:map(fun encode_key/1, Value), {jsx:encode(Value0), Req, State}; {error, concurrency} -> {{false, <<"Concurrent update">>}, Req, State} end. to_json(Req, State) -> Key = key(Req), fetch_key(Key, Req, State). fetch_key(Key, Req, State) -> {Value, Clock} = lashup_kv:value2(Key), Value0 = lists:map(fun encode_key/1, Value), ClockBin = base64:encode(term_to_binary(Clock)), Req0 = cowboy_req:set_resp_header(<<"clock">>, ClockBin, Req), {jsx:encode(Value0), Req0, State}. key(Req) -> KeyHandler = cowboy_req:header(<<"key-handler">>, Req), KeyData = cowboy_req:path_info(Req), key(KeyData, KeyHandler). key([], _) -> erlang:throw(invalid_key); key(KeyData, _) -> lists:map(fun(X) -> binary_to_atom(X, utf8) end, KeyData). encode_key({{Name, Type = riak_dt_lwwreg}, Value}) -> #{value := Key} = encode_key(Name), {Key, [{type, Type}, {value, encode_key(Value)}]}; encode_key({{Name, Type = riak_dt_orswot}, Value}) -> #{value := Key} = encode_key(Name), {Key, [{type, Type}, {value, lists:map(fun encode_key/1, Value)}]}; encode_key(Value) when is_atom(Value) -> #{type => atom, value => Value}; encode_key(Value) when is_binary(Value) -> #{type => binary, value => Value}; encode_key(Value) when is_list(Value) -> #{type => string, value => list_to_binary(lists:flatten(Value))}; encode_key(IP = {A, B, C, D}) when is_integer(A) andalso is_integer(B) andalso is_integer(C) andalso is_integer(D) andalso A >= 0 andalso B >= 0 andalso C >= 0 andalso D >= 0 andalso A =< 255 andalso B =< 255 andalso C =< 255 andalso D =< 255 -> #{ type => ipaddress_tuple, value => list_to_binary(lists:flatten(inet:ntoa(IP))) }; encode_key(Value) when is_tuple(Value) -> #{ type => tuple, value => list_to_binary(lists:flatten(io_lib:format("~p", [Value]))) }; encode_key(Value) when is_tuple(Value) -> #{ type => unknown, value => list_to_binary(lists:flatten(io_lib:format("~p", [Value]))) }.
7939ccce04e4a96ecdcf8ec58498076ac46551dbaadb08b4c6c5fe48fc37f44d
mauke/data-default
Base.hs
Copyright ( c ) 2013 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 the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY LUKAS MAI 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . Copyright (c) 2013 Lukas Mai 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 the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY LUKAS MAI 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Data.Default.Instances.Base ( -- | This module reexports the 'Data.Default.Class.Default' instances from the " Data . Default . Class " module . ) where import Data.Default.Class ()
null
https://raw.githubusercontent.com/mauke/data-default/b1a08788ca3d6a714319726e3768cf93df92458e/data-default-instances-base/Data/Default/Instances/Base.hs
haskell
| This module reexports the 'Data.Default.Class.Default' instances from the
Copyright ( c ) 2013 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 the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY LUKAS MAI 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . Copyright (c) 2013 Lukas Mai 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 the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY LUKAS MAI 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Data.Default.Instances.Base ( " Data . Default . Class " module . ) where import Data.Default.Class ()
ca7a1e26da31be75ead05843a09c6f37564bda4541943d6d1954bb23ddfd8852
dgtized/shimmers
spaces_divided.cljs
(ns shimmers.sketches.spaces-divided (:require [quil.core :as q :include-macros true] [quil.middleware :as m] [shimmers.algorithm.polygon-detection :as poly-detect] [shimmers.common.framerate :as framerate] [shimmers.common.quil :as cq] [shimmers.common.sequence :as cs] [shimmers.common.ui.debug :as debug] [shimmers.math.deterministic-random :as dr] [shimmers.sketch :as sketch :include-macros true] [thi.ng.geom.core :as g] [thi.ng.geom.line :as gl] [thi.ng.geom.polygon :as gp] [thi.ng.geom.vector :as gv] [thi.ng.math.core :as tm])) (defonce defo (debug/state)) (defn gen-line [bounds] (fn [] (let [[a b c d] (g/edges bounds) [[p1 q1] [p2 q2]] (dr/rand-nth [[a c] [b d]])] (gl/line2 (tm/mix p1 q1 (dr/random 0.1 0.9)) (tm/mix p2 q2 (dr/random 0.1 0.9)))))) (defn isec-point [l1 l2] (when-let [{:keys [type] :as hit} (g/intersect-line l1 l2)] (when (= type :intersect) {:isec (:p hit) :segments #{l1 l2}}))) (defn line-intersections [lines] (remove nil? (for [[a b] (cs/all-pairs lines)] (isec-point a b)))) (defn setup [] (q/color-mode :hsl 1.0) (let [bounds (cq/screen-rect 0.95)] {:bounds bounds :mouse (gv/vec2) :lines (repeatedly 6 (gen-line bounds))})) (defn update-state [{:keys [lines bounds] :as state}] (let [isecs (line-intersections (into lines (map gl/line2 (g/edges bounds))))] (-> state (assoc :intersections isecs :edges (poly-detect/intersections->edges isecs)) (update :mouse cq/mouse-last-position-clicked)))) ;; improved but still showing backwards triangles form inset sometimes? (defn draw-inset [shape] (let [inset (->> (poly-detect/inset-polygon shape 4) poly-detect/split-self-intersection (apply max-key g/area))] (when (> (g/area inset) 50) (cq/draw-polygon inset)))) (defn describe [{:keys [points] :as shape}] {:vertices points :self-intersecting (poly-detect/self-intersecting? shape) :clockwise (poly-detect/clockwise-polygon? points) :area (g/area shape)}) (defn calculate-polygons [edges] (->> edges poly-detect/edges->graph poly-detect/simple-polygons (mapv gp/polygon2))) (defn inset-shapes [polygons] (->> (for [poly polygons :let [inset (poly-detect/inset-polygon poly 2.0)]] (cond (poly-detect/self-intersecting? inset) (apply max-key g/area (poly-detect/split-self-intersection inset)) (> (g/area inset) 125) inset :else nil)) (remove nil?))) (defn draw [{:keys [mouse edges]}] (reset! defo {}) (q/ellipse-mode :radius) (q/background 1.0) ;; either inset or polygon detection is occasionally tossing in weird outputs ;; sometimes inset polygons self-intersect, so need to cut that part out (q/stroke-weight 1.0) (let [shapes (-> edges calculate-polygons inset-shapes)] (swap! defo assoc :n-polygons (count shapes)) (q/no-fill) (q/stroke 0.55 0.5 0.5 1.0) (doseq [s shapes] (cq/draw-polygon s)) (q/stroke 0.0 0.5 0.0 1.0) (doseq [s shapes] (draw-inset s)) ;; highlight points on hover + debug info (when-let [{:keys [points] :as shape} (some (fn [s] (when (g/contains-point? s mouse) s)) shapes)] (let [inner (poly-detect/inset-polygon shape 4)] (swap! defo assoc :polygon {:outer (describe shape) :inner (describe inner)}) (when-let [isec (poly-detect/self-intersecting? inner)] (q/with-stroke [0.0 0.5 0.5 1.0] (cq/circle isec 2.0) (cq/draw-polygon inner)))) (doseq [[idx p] (map-indexed vector points)] (q/fill (/ idx (count points)) 0.5 0.5 1.0) (cq/circle p 3.0))))) (comment ;; example of self intersect after inset operation (poly-detect/self-intersecting? (gp/polygon2 (poly-detect/inset-polygon (mapv gv/vec2 [[383.33 202.97] [435.44 199.85] [404.54 355.24] [411.73 357.02]]) -10)))) (sketch/defquil spaces-divided :created-at "2021-12-09" :size [800 600] :on-mount (debug/mount defo) :setup setup :update update-state :draw draw :middleware [m/fun-mode framerate/mode])
null
https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/sketches/spaces_divided.cljs
clojure
improved but still showing backwards triangles form inset sometimes? either inset or polygon detection is occasionally tossing in weird outputs sometimes inset polygons self-intersect, so need to cut that part out highlight points on hover + debug info example of self intersect after inset operation
(ns shimmers.sketches.spaces-divided (:require [quil.core :as q :include-macros true] [quil.middleware :as m] [shimmers.algorithm.polygon-detection :as poly-detect] [shimmers.common.framerate :as framerate] [shimmers.common.quil :as cq] [shimmers.common.sequence :as cs] [shimmers.common.ui.debug :as debug] [shimmers.math.deterministic-random :as dr] [shimmers.sketch :as sketch :include-macros true] [thi.ng.geom.core :as g] [thi.ng.geom.line :as gl] [thi.ng.geom.polygon :as gp] [thi.ng.geom.vector :as gv] [thi.ng.math.core :as tm])) (defonce defo (debug/state)) (defn gen-line [bounds] (fn [] (let [[a b c d] (g/edges bounds) [[p1 q1] [p2 q2]] (dr/rand-nth [[a c] [b d]])] (gl/line2 (tm/mix p1 q1 (dr/random 0.1 0.9)) (tm/mix p2 q2 (dr/random 0.1 0.9)))))) (defn isec-point [l1 l2] (when-let [{:keys [type] :as hit} (g/intersect-line l1 l2)] (when (= type :intersect) {:isec (:p hit) :segments #{l1 l2}}))) (defn line-intersections [lines] (remove nil? (for [[a b] (cs/all-pairs lines)] (isec-point a b)))) (defn setup [] (q/color-mode :hsl 1.0) (let [bounds (cq/screen-rect 0.95)] {:bounds bounds :mouse (gv/vec2) :lines (repeatedly 6 (gen-line bounds))})) (defn update-state [{:keys [lines bounds] :as state}] (let [isecs (line-intersections (into lines (map gl/line2 (g/edges bounds))))] (-> state (assoc :intersections isecs :edges (poly-detect/intersections->edges isecs)) (update :mouse cq/mouse-last-position-clicked)))) (defn draw-inset [shape] (let [inset (->> (poly-detect/inset-polygon shape 4) poly-detect/split-self-intersection (apply max-key g/area))] (when (> (g/area inset) 50) (cq/draw-polygon inset)))) (defn describe [{:keys [points] :as shape}] {:vertices points :self-intersecting (poly-detect/self-intersecting? shape) :clockwise (poly-detect/clockwise-polygon? points) :area (g/area shape)}) (defn calculate-polygons [edges] (->> edges poly-detect/edges->graph poly-detect/simple-polygons (mapv gp/polygon2))) (defn inset-shapes [polygons] (->> (for [poly polygons :let [inset (poly-detect/inset-polygon poly 2.0)]] (cond (poly-detect/self-intersecting? inset) (apply max-key g/area (poly-detect/split-self-intersection inset)) (> (g/area inset) 125) inset :else nil)) (remove nil?))) (defn draw [{:keys [mouse edges]}] (reset! defo {}) (q/ellipse-mode :radius) (q/background 1.0) (q/stroke-weight 1.0) (let [shapes (-> edges calculate-polygons inset-shapes)] (swap! defo assoc :n-polygons (count shapes)) (q/no-fill) (q/stroke 0.55 0.5 0.5 1.0) (doseq [s shapes] (cq/draw-polygon s)) (q/stroke 0.0 0.5 0.0 1.0) (doseq [s shapes] (draw-inset s)) (when-let [{:keys [points] :as shape} (some (fn [s] (when (g/contains-point? s mouse) s)) shapes)] (let [inner (poly-detect/inset-polygon shape 4)] (swap! defo assoc :polygon {:outer (describe shape) :inner (describe inner)}) (when-let [isec (poly-detect/self-intersecting? inner)] (q/with-stroke [0.0 0.5 0.5 1.0] (cq/circle isec 2.0) (cq/draw-polygon inner)))) (doseq [[idx p] (map-indexed vector points)] (q/fill (/ idx (count points)) 0.5 0.5 1.0) (cq/circle p 3.0))))) (comment (poly-detect/self-intersecting? (gp/polygon2 (poly-detect/inset-polygon (mapv gv/vec2 [[383.33 202.97] [435.44 199.85] [404.54 355.24] [411.73 357.02]]) -10)))) (sketch/defquil spaces-divided :created-at "2021-12-09" :size [800 600] :on-mount (debug/mount defo) :setup setup :update update-state :draw draw :middleware [m/fun-mode framerate/mode])
6dc06ad1cdd9dcb65e4cb6ddd0d0847581af36b4c63db8c641595d5977902c43
phadej/trustee
CabalBuild.hs
module Trustee.CabalBuild ( urakkaCabal, urakkaCabalRow, CabalResult (..), ) where import Control.Arrow (arr, (>>>), (|||)) import Control.Concurrent.STM (STM) import Trustee.GHC import Trustee.Monad import Trustee.Options import Peura import Urakka data CabalResult = CabalResultPending | CabalResultOk | CabalResultDryFail !ExitCode !ByteString !ByteString | CabalResultDepFail !ExitCode !ByteString !ByteString | CabalResultFail !ExitCode !ByteString !ByteString deriving stock (Show, Generic) deriving anyclass (NFData) urakkaCabal ^ GHC to build with -> Map PackageName VersionRange -- ^ constraints -> Path Absolute -- ^ working directory -> Verify -- ^ verify? -> M (STM CabalResult, Urakka () CabalResult) urakkaCabal ghcV constraints dir verify = do uDry <- urakka' $ \() -> do (ec, out, err) <- runCabal ModeDry dir ghcV constraints if isFailure ec then return $ Left $ CabalResultDryFail ec out err else return $ Right () (stm, post) <- urakkaSTM $ return . either id (const CabalResultOk) case verify of Verify -> do uDep <- urakka' $ \() -> do (ec, out, err) <- runCabal ModeDep dir ghcV constraints if isFailure ec then return $ Left $ CabalResultDepFail ec out err else return $ Right () uBld <- urakka' $ \() -> do (ec, out, err) <- runCabal ModeBuild dir ghcV constraints if isFailure ec then return $ Left $ CabalResultFail ec out err else return $ Right () let u :: Urakka () CabalResult u = uDry >>> arr Left ||| uDep >>> arr Left ||| uBld >>> post return (stm, u) SolveOnly -> do let u :: Urakka () CabalResult u = uDry >>> post return (stm, u) where isFailure (ExitFailure _) = True isFailure ExitSuccess = False urakkaCabalRow :: Traversable t => Verify -> t GHCVer -> Map PackageName VersionRange -> Path Absolute -> M (t (STM CabalResult), Urakka () (t CabalResult)) urakkaCabalRow verify ghcs constraints dir = fmap (\xs -> (fmap fst xs, traverse snd xs)) . for ghcs $ \ghcV -> urakkaCabal ghcV constraints dir verify
null
https://raw.githubusercontent.com/phadej/trustee/ab714484b39b43795ff586d5f232fad911a05dfd/src/Trustee/CabalBuild.hs
haskell
^ constraints ^ working directory ^ verify?
module Trustee.CabalBuild ( urakkaCabal, urakkaCabalRow, CabalResult (..), ) where import Control.Arrow (arr, (>>>), (|||)) import Control.Concurrent.STM (STM) import Trustee.GHC import Trustee.Monad import Trustee.Options import Peura import Urakka data CabalResult = CabalResultPending | CabalResultOk | CabalResultDryFail !ExitCode !ByteString !ByteString | CabalResultDepFail !ExitCode !ByteString !ByteString | CabalResultFail !ExitCode !ByteString !ByteString deriving stock (Show, Generic) deriving anyclass (NFData) urakkaCabal ^ GHC to build with -> M (STM CabalResult, Urakka () CabalResult) urakkaCabal ghcV constraints dir verify = do uDry <- urakka' $ \() -> do (ec, out, err) <- runCabal ModeDry dir ghcV constraints if isFailure ec then return $ Left $ CabalResultDryFail ec out err else return $ Right () (stm, post) <- urakkaSTM $ return . either id (const CabalResultOk) case verify of Verify -> do uDep <- urakka' $ \() -> do (ec, out, err) <- runCabal ModeDep dir ghcV constraints if isFailure ec then return $ Left $ CabalResultDepFail ec out err else return $ Right () uBld <- urakka' $ \() -> do (ec, out, err) <- runCabal ModeBuild dir ghcV constraints if isFailure ec then return $ Left $ CabalResultFail ec out err else return $ Right () let u :: Urakka () CabalResult u = uDry >>> arr Left ||| uDep >>> arr Left ||| uBld >>> post return (stm, u) SolveOnly -> do let u :: Urakka () CabalResult u = uDry >>> post return (stm, u) where isFailure (ExitFailure _) = True isFailure ExitSuccess = False urakkaCabalRow :: Traversable t => Verify -> t GHCVer -> Map PackageName VersionRange -> Path Absolute -> M (t (STM CabalResult), Urakka () (t CabalResult)) urakkaCabalRow verify ghcs constraints dir = fmap (\xs -> (fmap fst xs, traverse snd xs)) . for ghcs $ \ghcV -> urakkaCabal ghcV constraints dir verify
12c80b70e9175b9dd10c21d81441c1c9b6a837a6d449a8eaa80edc88801b6e77
chicken-mobile/chicken-sdl2-android-builder
gl.scm
;; chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2 ;; Copyright © 2013 , 2015 - 2016 . ;; 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. ;; ;; 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 HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , ;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED ;; OF THE POSSIBILITY OF SUCH DAMAGE. (export gl-create-context! gl-delete-context! gl-make-current! gl-get-current-window gl-get-current-context gl-attribute gl-attribute-set! SDL > = 2.0.2 SDL > = 2.0.1 gl-swap-window! gl-swap-interval gl-swap-interval-set! gl-bind-texture! gl-unbind-texture! gl-extension-supported? ;; TODO?: gl-get-proc-address ;; TODO?: gl-load-library ;; TODO?: gl-unload-library ) (: gl-create-context! (sdl2:window* -> sdl2:gl-context)) (define (gl-create-context! window) (let ((context (SDL_GL_CreateContext window))) (if (and (gl-context? context) (not (struct-null? context))) context (abort (sdl-failure "SDL_GL_CreateContext" #f))))) (: gl-delete-context! (sdl2:gl-context* -> void)) (define (gl-delete-context! context) (SDL_GL_DeleteContext context)) (: gl-make-current! (sdl2:window* sdl2:gl-context* -> void)) (define (gl-make-current! window gl-context) (let ((ret-code (SDL_GL_MakeCurrent window gl-context))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_MakeCurrent" ret-code))))) (: gl-get-current-window (-> sdl2:window)) (define (gl-get-current-window) (let ((window (SDL_GL_GetCurrentWindow))) (if (and (window? window) (not (struct-null? window))) window (abort (sdl-failure "SDL_GL_GetCurrentWindow" #f))))) (: gl-get-current-context (-> sdl2:gl-context)) (define (gl-get-current-context) (let ((context (SDL_GL_GetCurrentContext))) (if (and (gl-context? context) (not (struct-null? context))) context (abort (sdl-failure "SDL_GL_GetCurrentContext" #f))))) (define-inline (%gl-attr->int attr fn-name) (if (integer? attr) attr (symbol->gl-attr attr (lambda (x) (error fn-name "invalid GL attr symbol" x))))) ;;; - If attr is 'context-flags, the return value will be a list of ;;; symbols. ;;; - If attr is 'context-profile-mask, the return value will be a ;;; symbol ('core, 'compatibility, or 'es). ;;; - (2.0.4+) If attr is 'context-release-behavior, the return value ;;; will be a symbol ('none or 'flush). ;;; - For other attributes, the return value will be an integer. (define-inline (%int->gl-attr-value attr-int value-int) (cond ((= attr-int SDL_GL_CONTEXT_FLAGS) (unpack-gl-context-flags value-int)) ((= attr-int SDL_GL_CONTEXT_PROFILE_MASK) (gl-profile->symbol value-int)) ((and (feature? 'libSDL-2.0.4+) #+libSDL-2.0.4+ (= attr-int SDL_GL_CONTEXT_RELEASE_BEHAVIOR)) #+libSDL-2.0.4+ (gl-context-release-flag->symbol value-int)) (else value-int))) - If attr is ' context - flags , the value must be a list of GL ;;; context flag enum symbols, or an integer. - If attr is ' context - profile - mask , the value must be a GL profile ;;; enum symbol, or an integer. ;;; - For other attributes, the value must be an integer. (define-inline (%gl-attr-value->int attr-int value) (cond ((integer? value) value) ((= attr-int SDL_GL_CONTEXT_FLAGS) (pack-gl-context-flags value)) ((= attr-int SDL_GL_CONTEXT_PROFILE_MASK) (symbol->gl-profile value)) ((and (feature? 'libSDL-2.0.4+) #+libSDL-2.0.4+ (= attr-int SDL_GL_CONTEXT_RELEASE_BEHAVIOR)) #+libSDL-2.0.4+ (symbol->gl-context-release-flag value)) (else value))) Get the value of a GL attribute . Returns the value ( usually an ;;; integer) on success. Signals exception on failure. (: gl-attribute ((or symbol fixnum) -> (or fixnum symbol (list-of symbol)))) (define (gl-attribute attr) (let ((attr-int (%gl-attr->int attr 'gl-attribute))) (with-temp-mem ((value-out (%allocate-Sint32))) (let ((ret-code (SDL_GL_GetAttribute attr-int value-out))) (if (zero? ret-code) (%int->gl-attr-value attr-int (pointer-s32-ref value-out)) (begin (free value-out) (abort (sdl-failure "SDL_GL_GetAttribute" ret-code)))))))) Set the value of a GL attribute . Signals exception on failure . (: gl-attribute-set! ((or symbol fixnum) (or fixnum symbol (list-of symbol)) -> void)) (define (gl-attribute-set! attr value) (let* ((attr-int (%gl-attr->int attr 'gl-attribute-set!)) (value-int (%gl-attr-value->int attr-int value)) (ret-code (SDL_GL_SetAttribute attr-int value-int))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_SetAttribute" ret-code))))) (set! (setter gl-attribute) gl-attribute-set!) (: gl-reset-attributes! (-> void)) (define-versioned (gl-reset-attributes!) libSDL-2.0.2+ (SDL_GL_ResetAttributes)) (: gl-get-drawable-size (sdl2:window* -> fixnum fixnum)) (define-versioned (gl-get-drawable-size window) libSDL-2.0.1+ (with-temp-mem ((w-out (%allocate-Uint32)) (h-out (%allocate-Uint32))) (SDL_GL_GetDrawableSize window w-out h-out) (values (pointer-u32-ref w-out) (pointer-u32-ref h-out)))) (: gl-swap-window! (sdl2:window* -> void)) (define (gl-swap-window! window) (SDL_GL_SwapWindow window)) (: gl-swap-interval (-> fixnum)) (define (gl-swap-interval) (SDL_GL_GetSwapInterval)) (: gl-swap-interval-set! (fixnum -> void)) (define (gl-swap-interval-set! interval) (let ((ret-code (SDL_GL_SetSwapInterval interval))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_SetSwapInterval" ret-code))))) (set! (setter gl-swap-interval) gl-swap-interval-set!) (: gl-bind-texture! (sdl2:texture* -> float float)) (define (gl-bind-texture! texture) (with-temp-mem ((tex-w-out (%allocate-float)) (tex-h-out (%allocate-float))) (let ((ret-code (SDL_GL_BindTexture texture tex-w-out tex-h-out))) (if (zero? ret-code) (values (pointer-f32-ref tex-w-out) (pointer-f32-ref tex-h-out)) (begin (free tex-w-out) (free tex-h-out) (abort (sdl-failure "SDL_GL_BindTexture" ret-code))))))) (: gl-unbind-texture! (sdl2:texture* -> void)) (define (gl-unbind-texture! texture) (let ((ret-code (SDL_GL_UnbindTexture texture))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_UnbindTexture" ret-code))))) (define (gl-extension-supported? name-string) (SDL_GL_ExtensionSupported name-string)) TODO ? : gl - get - proc - address ( SDL_GL_GetProcAddress ) ;; TODO?: gl-load-library (SDL_GL_LoadLibrary) ;; TODO?: gl-unload-library (SDL_GL_UnloadLibrary)
null
https://raw.githubusercontent.com/chicken-mobile/chicken-sdl2-android-builder/90ef1f0ff667737736f1932e204d29ae615a00c4/eggs/sdl2/lib/sdl2/gl.scm
scheme
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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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. TODO?: gl-get-proc-address TODO?: gl-load-library TODO?: gl-unload-library - If attr is 'context-flags, the return value will be a list of symbols. - If attr is 'context-profile-mask, the return value will be a symbol ('core, 'compatibility, or 'es). - (2.0.4+) If attr is 'context-release-behavior, the return value will be a symbol ('none or 'flush). - For other attributes, the return value will be an integer. context flag enum symbols, or an integer. enum symbol, or an integer. - For other attributes, the value must be an integer. integer) on success. Signals exception on failure. TODO?: gl-load-library (SDL_GL_LoadLibrary) TODO?: gl-unload-library (SDL_GL_UnloadLibrary)
chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2 Copyright © 2013 , 2015 - 2016 . " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , (export gl-create-context! gl-delete-context! gl-make-current! gl-get-current-window gl-get-current-context gl-attribute gl-attribute-set! SDL > = 2.0.2 SDL > = 2.0.1 gl-swap-window! gl-swap-interval gl-swap-interval-set! gl-bind-texture! gl-unbind-texture! gl-extension-supported? ) (: gl-create-context! (sdl2:window* -> sdl2:gl-context)) (define (gl-create-context! window) (let ((context (SDL_GL_CreateContext window))) (if (and (gl-context? context) (not (struct-null? context))) context (abort (sdl-failure "SDL_GL_CreateContext" #f))))) (: gl-delete-context! (sdl2:gl-context* -> void)) (define (gl-delete-context! context) (SDL_GL_DeleteContext context)) (: gl-make-current! (sdl2:window* sdl2:gl-context* -> void)) (define (gl-make-current! window gl-context) (let ((ret-code (SDL_GL_MakeCurrent window gl-context))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_MakeCurrent" ret-code))))) (: gl-get-current-window (-> sdl2:window)) (define (gl-get-current-window) (let ((window (SDL_GL_GetCurrentWindow))) (if (and (window? window) (not (struct-null? window))) window (abort (sdl-failure "SDL_GL_GetCurrentWindow" #f))))) (: gl-get-current-context (-> sdl2:gl-context)) (define (gl-get-current-context) (let ((context (SDL_GL_GetCurrentContext))) (if (and (gl-context? context) (not (struct-null? context))) context (abort (sdl-failure "SDL_GL_GetCurrentContext" #f))))) (define-inline (%gl-attr->int attr fn-name) (if (integer? attr) attr (symbol->gl-attr attr (lambda (x) (error fn-name "invalid GL attr symbol" x))))) (define-inline (%int->gl-attr-value attr-int value-int) (cond ((= attr-int SDL_GL_CONTEXT_FLAGS) (unpack-gl-context-flags value-int)) ((= attr-int SDL_GL_CONTEXT_PROFILE_MASK) (gl-profile->symbol value-int)) ((and (feature? 'libSDL-2.0.4+) #+libSDL-2.0.4+ (= attr-int SDL_GL_CONTEXT_RELEASE_BEHAVIOR)) #+libSDL-2.0.4+ (gl-context-release-flag->symbol value-int)) (else value-int))) - If attr is ' context - flags , the value must be a list of GL - If attr is ' context - profile - mask , the value must be a GL profile (define-inline (%gl-attr-value->int attr-int value) (cond ((integer? value) value) ((= attr-int SDL_GL_CONTEXT_FLAGS) (pack-gl-context-flags value)) ((= attr-int SDL_GL_CONTEXT_PROFILE_MASK) (symbol->gl-profile value)) ((and (feature? 'libSDL-2.0.4+) #+libSDL-2.0.4+ (= attr-int SDL_GL_CONTEXT_RELEASE_BEHAVIOR)) #+libSDL-2.0.4+ (symbol->gl-context-release-flag value)) (else value))) Get the value of a GL attribute . Returns the value ( usually an (: gl-attribute ((or symbol fixnum) -> (or fixnum symbol (list-of symbol)))) (define (gl-attribute attr) (let ((attr-int (%gl-attr->int attr 'gl-attribute))) (with-temp-mem ((value-out (%allocate-Sint32))) (let ((ret-code (SDL_GL_GetAttribute attr-int value-out))) (if (zero? ret-code) (%int->gl-attr-value attr-int (pointer-s32-ref value-out)) (begin (free value-out) (abort (sdl-failure "SDL_GL_GetAttribute" ret-code)))))))) Set the value of a GL attribute . Signals exception on failure . (: gl-attribute-set! ((or symbol fixnum) (or fixnum symbol (list-of symbol)) -> void)) (define (gl-attribute-set! attr value) (let* ((attr-int (%gl-attr->int attr 'gl-attribute-set!)) (value-int (%gl-attr-value->int attr-int value)) (ret-code (SDL_GL_SetAttribute attr-int value-int))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_SetAttribute" ret-code))))) (set! (setter gl-attribute) gl-attribute-set!) (: gl-reset-attributes! (-> void)) (define-versioned (gl-reset-attributes!) libSDL-2.0.2+ (SDL_GL_ResetAttributes)) (: gl-get-drawable-size (sdl2:window* -> fixnum fixnum)) (define-versioned (gl-get-drawable-size window) libSDL-2.0.1+ (with-temp-mem ((w-out (%allocate-Uint32)) (h-out (%allocate-Uint32))) (SDL_GL_GetDrawableSize window w-out h-out) (values (pointer-u32-ref w-out) (pointer-u32-ref h-out)))) (: gl-swap-window! (sdl2:window* -> void)) (define (gl-swap-window! window) (SDL_GL_SwapWindow window)) (: gl-swap-interval (-> fixnum)) (define (gl-swap-interval) (SDL_GL_GetSwapInterval)) (: gl-swap-interval-set! (fixnum -> void)) (define (gl-swap-interval-set! interval) (let ((ret-code (SDL_GL_SetSwapInterval interval))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_SetSwapInterval" ret-code))))) (set! (setter gl-swap-interval) gl-swap-interval-set!) (: gl-bind-texture! (sdl2:texture* -> float float)) (define (gl-bind-texture! texture) (with-temp-mem ((tex-w-out (%allocate-float)) (tex-h-out (%allocate-float))) (let ((ret-code (SDL_GL_BindTexture texture tex-w-out tex-h-out))) (if (zero? ret-code) (values (pointer-f32-ref tex-w-out) (pointer-f32-ref tex-h-out)) (begin (free tex-w-out) (free tex-h-out) (abort (sdl-failure "SDL_GL_BindTexture" ret-code))))))) (: gl-unbind-texture! (sdl2:texture* -> void)) (define (gl-unbind-texture! texture) (let ((ret-code (SDL_GL_UnbindTexture texture))) (unless (zero? ret-code) (abort (sdl-failure "SDL_GL_UnbindTexture" ret-code))))) (define (gl-extension-supported? name-string) (SDL_GL_ExtensionSupported name-string)) TODO ? : gl - get - proc - address ( SDL_GL_GetProcAddress )
c928b90b4996d1c0e6065a565a0c8263d0dabce1525f575e8058990f70fe0ea3
domsj/orocksdb
rocks.ml
open Ctypes open Foreign open Rocks_common type bigarray = Rocks_intf.bigarray module Views = Views exception OperationOnInvalidObject = Rocks_common.OperationOnInvalidObject module WriteBatch = struct module C = CreateConstructors_(struct let name = "writebatch" end) include C let clear = foreign "rocksdb_writebatch_clear" (t @-> returning void) let count = foreign "rocksdb_writebatch_count" (t @-> returning int) let put_raw = foreign "rocksdb_writebatch_put" (t @-> ptr char @-> Views.int_to_size_t @-> ptr char @-> Views.int_to_size_t @-> returning void) let put_raw_string = foreign "rocksdb_writebatch_put" (t @-> ocaml_string @-> Views.int_to_size_t @-> ocaml_string @-> Views.int_to_size_t @-> returning void) let put ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len batch key value = let open Bigarray.Array1 in let key_len = match key_len with None -> dim key - key_pos | Some len -> len in let value_len = match value_len with None -> dim value - value_pos | Some len -> len in put_raw batch (bigarray_start array1 key +@ key_pos) key_len (bigarray_start array1 value +@ value_pos) value_len let put_string ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len batch key value = let key_len = match key_len with None -> String.length key - key_pos | Some len -> len in let value_len = match value_len with None -> String.length value - value_pos | Some len -> len in put_raw_string batch (ocaml_string_start key +@ key_pos) key_len (ocaml_string_start value +@ value_pos) value_len let delete_raw = foreign "rocksdb_writebatch_delete" (t @-> ptr char @-> Views.int_to_size_t @-> returning void) let delete_raw_string = foreign "rocksdb_writebatch_delete" (t @-> ocaml_string @-> Views.int_to_size_t @-> returning void) let delete ?(pos=0) ?len batch key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in delete_raw batch (bigarray_start array1 key +@ pos) len let delete_string ?(pos=0) ?len batch key = let len = match len with None -> String.length key - pos | Some len -> len in delete_raw_string batch (ocaml_string_start key +@ pos) len end module Version = Rocks_version let returning_error typ = ptr string_opt @-> returning typ let with_err_pointer f = let err_pointer = allocate string_opt None in let res = f err_pointer in match !@ err_pointer with | None -> res | Some err -> failwith err module rec Iterator : Rocks_intf.ITERATOR with type db := RocksDb.t = struct module ReadOptions = Rocks_options.ReadOptions type nonrec t = t let t = t type db let db = t let get_pointer = get_pointer exception InvalidIterator let create_no_gc = foreign "rocksdb_create_iterator" (db @-> ReadOptions.t @-> returning t) let destroy = let inner = foreign "rocksdb_iter_destroy" (t @-> returning void) in fun t -> inner t; t.valid <- false let create ?opts db = let inner opts = let t = create_no_gc db opts in Gc.finalise destroy t; t in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts let with_t ?opts db ~f = let inner opts = let t = create_no_gc db opts in finalize (fun () -> f t) (fun () -> destroy t) in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts let is_valid = foreign "rocksdb_iter_valid" (t @-> returning Views.bool_to_uchar) let seek_to_first = foreign "rocksdb_iter_seek_to_first" (t @-> returning void) let seek_to_last = foreign "rocksdb_iter_seek_to_last" (t @-> returning void) let seek_raw = foreign "rocksdb_iter_seek" (t @-> ptr char @-> Views.int_to_size_t @-> returning void) let seek_raw_string = foreign "rocksdb_iter_seek" (t @-> ocaml_string @-> Views.int_to_size_t @-> returning void) let seek ?(pos=0) ?len t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in seek_raw t (bigarray_start array1 key +@ pos) len let seek_string ?(pos=0) ?len t key = let len = match len with None -> String.length key - pos | Some len -> len in seek_raw_string t (ocaml_string_start key +@ pos) len let next = foreign "rocksdb_iter_next" (t @-> returning void) let prev = foreign "rocksdb_iter_prev" (t @-> returning void) let get_key_raw = let inner = foreign "rocksdb_iter_key" (t @-> ptr Views.int_to_size_t @-> returning (ptr char)) in fun t size -> if is_valid t then inner t size else raise InvalidIterator let get_key t = let res_size = allocate Views.int_to_size_t 0 in let res = get_key_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get key, is_valid=%b" (is_valid t)) else bigarray_of_ptr array1 (!@res_size) Bigarray.char res let get_key_string t = let res_size = allocate Views.int_to_size_t 0 in let res = get_key_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get key, is_valid=%b" (is_valid t)) else string_from_ptr res (!@ res_size) let get_value_raw = let inner = foreign "rocksdb_iter_value" (t @-> ptr Views.int_to_size_t @-> returning (ptr char)) in fun t size -> if is_valid t then inner t size else raise InvalidIterator let get_value t = let res_size = allocate Views.int_to_size_t 0 in let res = get_value_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get value, is_valid=%b" (is_valid t)) else bigarray_of_ptr array1 (!@res_size) Bigarray.char res let get_value_string t = let res_size = allocate Views.int_to_size_t 0 in let res = get_value_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get value, is_valid=%b" (is_valid t)) else string_from_ptr res (!@ res_size) let get_error_raw = foreign "rocksdb_iter_get_error" (t @-> ptr string_opt @-> returning void) let get_error t = let err_pointer = allocate string_opt None in get_error_raw t err_pointer; !@err_pointer end and Transaction : Rocks_intf.TRANSACTION with type db := RocksDb.t and type iter := Iterator.t = struct module ReadOptions = Rocks_options.ReadOptions module WriteOptions = Rocks_options.WriteOptions module TransactionOptions = Rocks_options.TransactionOptions module Snapshot = Rocks_options.Snapshot let name = "transaction" let destructor = "rocksdb_" ^ name ^ "_destroy" type db = t let db = t type nonrec t = t let t = t let txnbegin_raw = foreign "rocksdb_transaction_begin" (db @-> WriteOptions.t @-> TransactionOptions.t @-> ptr void @-> returning t) let destroy = make_destroy t destructor let txnbegin_no_gc ?wopts ?txnopts db = let inner wopts txnopts = txnbegin_raw db wopts txnopts null in match wopts, txnopts with None, None -> TransactionOptions.with_t (fun txnopts -> (WriteOptions.with_t (fun wopts -> inner wopts txnopts))) | Some wopts, None -> TransactionOptions.with_t (inner wopts) | None, Some txnopts -> (WriteOptions.with_t (fun wopts -> inner wopts txnopts)) | Some wopts, Some txnopts -> inner wopts txnopts let txnbegin ?wopts ?txnopts db = let t = txnbegin_no_gc ?wopts ?txnopts db in Gc.finalise destroy t; t let commit_raw = foreign "rocksdb_transaction_commit" (t @-> returning_error void) let commit t = with_err_pointer (commit_raw t) let rollback_raw = foreign "rocksdb_transaction_rollback" (t @-> returning_error void) let rollback t = with_err_pointer (rollback_raw t) let with_t db f = let t = txnbegin_no_gc db in finalize (fun () -> f t) (fun () -> destroy t) let put_raw = foreign "rocksdb_transaction_put" (t @-> ptr char @-> Views.int_to_size_t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let put_raw_string = foreign "rocksdb_transaction_put" (t @-> ocaml_string @-> Views.int_to_size_t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let put ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let open Bigarray.Array1 in let key_len = match key_len with None -> dim key - key_pos | Some len -> len in let value_len = match value_len with None -> dim value - value_pos | Some len -> len in with_err_pointer begin put_raw t (bigarray_start array1 key +@ key_pos) key_len (bigarray_start array1 value +@ value_pos) value_len end let put_string ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let key_len = match key_len with None -> String.length key - key_pos | Some len -> len in let value_len = match value_len with None -> String.length value - value_pos | Some len -> len in with_err_pointer begin put_raw_string t (ocaml_string_start key +@ key_pos) key_len (ocaml_string_start value +@ value_pos) value_len end let delete_raw = foreign "rocksdb_transaction_delete" (t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let delete_raw_string = foreign "rocksdb_transaction_delete" (t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let delete ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in with_err_pointer (delete_raw t (bigarray_start array1 key +@ pos) len) let delete_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in with_err_pointer (delete_raw_string t (ocaml_string_start key +@ pos) len) let get_raw = foreign "rocksdb_transaction_get" (t @-> ReadOptions.t @-> ptr char @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get_raw_string = foreign "rocksdb_transaction_get" (t @-> ReadOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw t opts (bigarray_start array1 key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = bigarray_of_ptr array1 (!@res_size) Bigarray.char res in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let get_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw_string t opts (ocaml_string_start key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = string_from_ptr res (!@ res_size) in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let get_snapshot = foreign "rocksdb_transaction_get_snapshot" (t @-> returning Snapshot.t) let free_snapshot = foreign "rocksdb_free" (Snapshot.t @-> returning void) let create_iterator_no_gc = foreign "rocksdb_transaction_create_iterator" (t @-> ReadOptions.t @-> returning t) let destroy_iterator = let inner = foreign "rocksdb_iter_destroy" (t @-> returning void) in fun t -> inner t; t.valid <- false let create_iterator ?opts txn = let inner opts = let t = create_iterator_no_gc txn opts in Gc.finalise destroy_iterator t; t in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts let with_iterator ?opts txn ~f = let inner opts = let t = create_iterator_no_gc txn opts in finalize (fun () -> f t) (fun () -> destroy_iterator t) in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts end and RocksDb : Rocks_intf.ROCKS with type batch := WriteBatch.t = struct module ReadOptions = Rocks_options.ReadOptions module WriteOptions = Rocks_options.WriteOptions module FlushOptions = Rocks_options.FlushOptions module Options = Rocks_options.Options module Cache = Rocks_options.Cache module Snapshot = Rocks_options.Snapshot module BlockBasedTableOptions = Rocks_options.BlockBasedTableOptions module TransactionDbOptions = Rocks_options.TransactionDbOptions type nonrec t = t type batch let t = t let get_pointer = get_pointer let open_db_raw = foreign "rocksdb_open" (Options.t @-> string @-> ptr string_opt @-> returning t) let open_db_for_read_only_raw = foreign "rocksdb_open_for_read_only" (Options.t @-> string @-> Views.bool_to_uchar @-> ptr string_opt @-> returning t) let open_transactiondb_raw = foreign "rocksdb_transactiondb_open" (Options.t @-> TransactionDbOptions.t @-> string @-> ptr string_opt @-> returning t) let open_transactiondb ?opts ?txnopts name = let inner opts txndbopts = with_err_pointer (open_transactiondb_raw opts txndbopts name) in match opts, txnopts with None, None -> TransactionDbOptions.with_t (fun txndbopts -> (Options.with_t (fun opts -> inner opts txndbopts))) | Some opts, None -> TransactionDbOptions.with_t (inner opts) | None, Some txndbopts -> Options.with_t (fun opts -> inner opts txndbopts) | Some opts, Some txndbopts -> inner opts txndbopts let open_db ?opts name = match opts with | None -> Options.with_t (fun options -> with_err_pointer (open_db_raw options name)) | Some opts -> with_err_pointer (open_db_raw opts name) let open_db_for_read_only ?opts name error_if_log_file_exists = match opts with | None -> Options.with_t (fun options -> with_err_pointer (open_db_for_read_only_raw options name error_if_log_file_exists)) | Some opts -> with_err_pointer (open_db_for_read_only_raw opts name error_if_log_file_exists) let close = let inner = foreign "rocksdb_close" (t @-> returning void) in fun t -> inner t; t.valid <- false let with_db ?opts name ~f = let db = open_db ?opts name in finalize (fun () -> f db) (fun () -> close db) let put_raw = foreign "rocksdb_put" (t @-> WriteOptions.t @-> ptr char @-> Views.int_to_size_t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let put_raw_string = foreign "rocksdb_put" (t @-> WriteOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let put ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let open Bigarray.Array1 in let key_len = match key_len with None -> dim key - key_pos | Some len -> len in let value_len = match value_len with None -> dim value - value_pos | Some len -> len in let inner opts = with_err_pointer begin put_raw t opts (bigarray_start array1 key +@ key_pos) key_len (bigarray_start array1 value +@ value_pos) value_len end in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let put_string ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let key_len = match key_len with None -> String.length key - key_pos | Some len -> len in let value_len = match value_len with None -> String.length value - value_pos | Some len -> len in let inner opts = with_err_pointer begin put_raw_string t opts (ocaml_string_start key +@ key_pos) key_len (ocaml_string_start value +@ value_pos) value_len end in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let delete_raw = foreign "rocksdb_delete" (t @-> WriteOptions.t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let delete_raw_string = foreign "rocksdb_delete" (t @-> WriteOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let delete ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in let inner opts = with_err_pointer (delete_raw t opts (bigarray_start array1 key +@ pos) len) in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let delete_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in let inner opts = with_err_pointer (delete_raw_string t opts (ocaml_string_start key +@ pos) len) in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let write_raw = foreign "rocksdb_write" (t @-> WriteOptions.t @-> WriteBatch.t @-> returning_error void) let write ?opts t wb = let inner opts = with_err_pointer (write_raw t opts wb) in match opts with | None -> WriteOptions.with_t inner | Some opts -> with_err_pointer (write_raw t opts wb) let get_raw = foreign "rocksdb_get" (t @-> ReadOptions.t @-> ptr char @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get_raw_string = foreign "rocksdb_get" (t @-> ReadOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw t opts (bigarray_start array1 key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = bigarray_of_ptr array1 (!@res_size) Bigarray.char res in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let get_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw_string t opts (ocaml_string_start key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = string_from_ptr res (!@ res_size) in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let flush_raw = foreign "rocksdb_flush" (t @-> FlushOptions.t @-> returning_error void) let flush ?opts t = let inner opts = with_err_pointer (flush_raw t opts) in match opts with | None -> FlushOptions.with_t inner | Some opts -> inner opts let create_snapshot = foreign "rocksdb_create_snapshot" (t @-> returning Snapshot.t) let release_snapshot = foreign "rocksdb_release_snapshot" (t @-> Snapshot.t @-> returning void) module CheckpointObject = struct let name = "checkpoint_object" let constructor = "rocksdb_" ^ name ^ "_create" let destructor = "rocksdb_" ^ name ^ "_destroy" type db = t let db = t type nonrec t = t let t = t let create_no_gc = foreign constructor (db @-> returning t) let destroy = make_destroy t destructor let create db = let t = create_no_gc db in Gc.finalise destroy t; t let with_t db f = let t = create_no_gc db in finalize (fun () -> f t) (fun () -> destroy t) end let checkpoint_create db dir log_size_for_flush = let checkpoint_create_raw = foreign "rocksdb_checkpoint_create" (CheckpointObject.t @-> string @-> Views.int_to_uint64_t @-> ptr string_opt @-> returning void) in CheckpointObject.with_t db (fun checkpoint_object -> with_err_pointer (checkpoint_create_raw checkpoint_object dir log_size_for_flush)) let property_value db name = (* Ugly hack. Is there a better way to retrieve string from C? *) let get = foreign "rocksdb_property_value" (t @-> string @-> returning (ptr_opt char)) in let free = foreign "free" ((ptr char) @-> returning void) in let strlen = foreign "strlen" ((ptr char) @-> returning int) in match get db name with Some p -> let value = string_from_ptr p ~length:(strlen p) in free p; Some value | None -> None end include RocksDb
null
https://raw.githubusercontent.com/domsj/orocksdb/36bd561f5cd75299b2bb5f8e707427626d4c9025/rocks.ml
ocaml
Ugly hack. Is there a better way to retrieve string from C?
open Ctypes open Foreign open Rocks_common type bigarray = Rocks_intf.bigarray module Views = Views exception OperationOnInvalidObject = Rocks_common.OperationOnInvalidObject module WriteBatch = struct module C = CreateConstructors_(struct let name = "writebatch" end) include C let clear = foreign "rocksdb_writebatch_clear" (t @-> returning void) let count = foreign "rocksdb_writebatch_count" (t @-> returning int) let put_raw = foreign "rocksdb_writebatch_put" (t @-> ptr char @-> Views.int_to_size_t @-> ptr char @-> Views.int_to_size_t @-> returning void) let put_raw_string = foreign "rocksdb_writebatch_put" (t @-> ocaml_string @-> Views.int_to_size_t @-> ocaml_string @-> Views.int_to_size_t @-> returning void) let put ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len batch key value = let open Bigarray.Array1 in let key_len = match key_len with None -> dim key - key_pos | Some len -> len in let value_len = match value_len with None -> dim value - value_pos | Some len -> len in put_raw batch (bigarray_start array1 key +@ key_pos) key_len (bigarray_start array1 value +@ value_pos) value_len let put_string ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len batch key value = let key_len = match key_len with None -> String.length key - key_pos | Some len -> len in let value_len = match value_len with None -> String.length value - value_pos | Some len -> len in put_raw_string batch (ocaml_string_start key +@ key_pos) key_len (ocaml_string_start value +@ value_pos) value_len let delete_raw = foreign "rocksdb_writebatch_delete" (t @-> ptr char @-> Views.int_to_size_t @-> returning void) let delete_raw_string = foreign "rocksdb_writebatch_delete" (t @-> ocaml_string @-> Views.int_to_size_t @-> returning void) let delete ?(pos=0) ?len batch key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in delete_raw batch (bigarray_start array1 key +@ pos) len let delete_string ?(pos=0) ?len batch key = let len = match len with None -> String.length key - pos | Some len -> len in delete_raw_string batch (ocaml_string_start key +@ pos) len end module Version = Rocks_version let returning_error typ = ptr string_opt @-> returning typ let with_err_pointer f = let err_pointer = allocate string_opt None in let res = f err_pointer in match !@ err_pointer with | None -> res | Some err -> failwith err module rec Iterator : Rocks_intf.ITERATOR with type db := RocksDb.t = struct module ReadOptions = Rocks_options.ReadOptions type nonrec t = t let t = t type db let db = t let get_pointer = get_pointer exception InvalidIterator let create_no_gc = foreign "rocksdb_create_iterator" (db @-> ReadOptions.t @-> returning t) let destroy = let inner = foreign "rocksdb_iter_destroy" (t @-> returning void) in fun t -> inner t; t.valid <- false let create ?opts db = let inner opts = let t = create_no_gc db opts in Gc.finalise destroy t; t in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts let with_t ?opts db ~f = let inner opts = let t = create_no_gc db opts in finalize (fun () -> f t) (fun () -> destroy t) in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts let is_valid = foreign "rocksdb_iter_valid" (t @-> returning Views.bool_to_uchar) let seek_to_first = foreign "rocksdb_iter_seek_to_first" (t @-> returning void) let seek_to_last = foreign "rocksdb_iter_seek_to_last" (t @-> returning void) let seek_raw = foreign "rocksdb_iter_seek" (t @-> ptr char @-> Views.int_to_size_t @-> returning void) let seek_raw_string = foreign "rocksdb_iter_seek" (t @-> ocaml_string @-> Views.int_to_size_t @-> returning void) let seek ?(pos=0) ?len t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in seek_raw t (bigarray_start array1 key +@ pos) len let seek_string ?(pos=0) ?len t key = let len = match len with None -> String.length key - pos | Some len -> len in seek_raw_string t (ocaml_string_start key +@ pos) len let next = foreign "rocksdb_iter_next" (t @-> returning void) let prev = foreign "rocksdb_iter_prev" (t @-> returning void) let get_key_raw = let inner = foreign "rocksdb_iter_key" (t @-> ptr Views.int_to_size_t @-> returning (ptr char)) in fun t size -> if is_valid t then inner t size else raise InvalidIterator let get_key t = let res_size = allocate Views.int_to_size_t 0 in let res = get_key_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get key, is_valid=%b" (is_valid t)) else bigarray_of_ptr array1 (!@res_size) Bigarray.char res let get_key_string t = let res_size = allocate Views.int_to_size_t 0 in let res = get_key_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get key, is_valid=%b" (is_valid t)) else string_from_ptr res (!@ res_size) let get_value_raw = let inner = foreign "rocksdb_iter_value" (t @-> ptr Views.int_to_size_t @-> returning (ptr char)) in fun t size -> if is_valid t then inner t size else raise InvalidIterator let get_value t = let res_size = allocate Views.int_to_size_t 0 in let res = get_value_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get value, is_valid=%b" (is_valid t)) else bigarray_of_ptr array1 (!@res_size) Bigarray.char res let get_value_string t = let res_size = allocate Views.int_to_size_t 0 in let res = get_value_raw t res_size in if (to_voidp res) = null then failwith (Printf.sprintf "could not get value, is_valid=%b" (is_valid t)) else string_from_ptr res (!@ res_size) let get_error_raw = foreign "rocksdb_iter_get_error" (t @-> ptr string_opt @-> returning void) let get_error t = let err_pointer = allocate string_opt None in get_error_raw t err_pointer; !@err_pointer end and Transaction : Rocks_intf.TRANSACTION with type db := RocksDb.t and type iter := Iterator.t = struct module ReadOptions = Rocks_options.ReadOptions module WriteOptions = Rocks_options.WriteOptions module TransactionOptions = Rocks_options.TransactionOptions module Snapshot = Rocks_options.Snapshot let name = "transaction" let destructor = "rocksdb_" ^ name ^ "_destroy" type db = t let db = t type nonrec t = t let t = t let txnbegin_raw = foreign "rocksdb_transaction_begin" (db @-> WriteOptions.t @-> TransactionOptions.t @-> ptr void @-> returning t) let destroy = make_destroy t destructor let txnbegin_no_gc ?wopts ?txnopts db = let inner wopts txnopts = txnbegin_raw db wopts txnopts null in match wopts, txnopts with None, None -> TransactionOptions.with_t (fun txnopts -> (WriteOptions.with_t (fun wopts -> inner wopts txnopts))) | Some wopts, None -> TransactionOptions.with_t (inner wopts) | None, Some txnopts -> (WriteOptions.with_t (fun wopts -> inner wopts txnopts)) | Some wopts, Some txnopts -> inner wopts txnopts let txnbegin ?wopts ?txnopts db = let t = txnbegin_no_gc ?wopts ?txnopts db in Gc.finalise destroy t; t let commit_raw = foreign "rocksdb_transaction_commit" (t @-> returning_error void) let commit t = with_err_pointer (commit_raw t) let rollback_raw = foreign "rocksdb_transaction_rollback" (t @-> returning_error void) let rollback t = with_err_pointer (rollback_raw t) let with_t db f = let t = txnbegin_no_gc db in finalize (fun () -> f t) (fun () -> destroy t) let put_raw = foreign "rocksdb_transaction_put" (t @-> ptr char @-> Views.int_to_size_t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let put_raw_string = foreign "rocksdb_transaction_put" (t @-> ocaml_string @-> Views.int_to_size_t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let put ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let open Bigarray.Array1 in let key_len = match key_len with None -> dim key - key_pos | Some len -> len in let value_len = match value_len with None -> dim value - value_pos | Some len -> len in with_err_pointer begin put_raw t (bigarray_start array1 key +@ key_pos) key_len (bigarray_start array1 value +@ value_pos) value_len end let put_string ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let key_len = match key_len with None -> String.length key - key_pos | Some len -> len in let value_len = match value_len with None -> String.length value - value_pos | Some len -> len in with_err_pointer begin put_raw_string t (ocaml_string_start key +@ key_pos) key_len (ocaml_string_start value +@ value_pos) value_len end let delete_raw = foreign "rocksdb_transaction_delete" (t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let delete_raw_string = foreign "rocksdb_transaction_delete" (t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let delete ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in with_err_pointer (delete_raw t (bigarray_start array1 key +@ pos) len) let delete_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in with_err_pointer (delete_raw_string t (ocaml_string_start key +@ pos) len) let get_raw = foreign "rocksdb_transaction_get" (t @-> ReadOptions.t @-> ptr char @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get_raw_string = foreign "rocksdb_transaction_get" (t @-> ReadOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw t opts (bigarray_start array1 key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = bigarray_of_ptr array1 (!@res_size) Bigarray.char res in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let get_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw_string t opts (ocaml_string_start key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = string_from_ptr res (!@ res_size) in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let get_snapshot = foreign "rocksdb_transaction_get_snapshot" (t @-> returning Snapshot.t) let free_snapshot = foreign "rocksdb_free" (Snapshot.t @-> returning void) let create_iterator_no_gc = foreign "rocksdb_transaction_create_iterator" (t @-> ReadOptions.t @-> returning t) let destroy_iterator = let inner = foreign "rocksdb_iter_destroy" (t @-> returning void) in fun t -> inner t; t.valid <- false let create_iterator ?opts txn = let inner opts = let t = create_iterator_no_gc txn opts in Gc.finalise destroy_iterator t; t in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts let with_iterator ?opts txn ~f = let inner opts = let t = create_iterator_no_gc txn opts in finalize (fun () -> f t) (fun () -> destroy_iterator t) in match opts with | None -> ReadOptions.with_t inner | Some opts -> inner opts end and RocksDb : Rocks_intf.ROCKS with type batch := WriteBatch.t = struct module ReadOptions = Rocks_options.ReadOptions module WriteOptions = Rocks_options.WriteOptions module FlushOptions = Rocks_options.FlushOptions module Options = Rocks_options.Options module Cache = Rocks_options.Cache module Snapshot = Rocks_options.Snapshot module BlockBasedTableOptions = Rocks_options.BlockBasedTableOptions module TransactionDbOptions = Rocks_options.TransactionDbOptions type nonrec t = t type batch let t = t let get_pointer = get_pointer let open_db_raw = foreign "rocksdb_open" (Options.t @-> string @-> ptr string_opt @-> returning t) let open_db_for_read_only_raw = foreign "rocksdb_open_for_read_only" (Options.t @-> string @-> Views.bool_to_uchar @-> ptr string_opt @-> returning t) let open_transactiondb_raw = foreign "rocksdb_transactiondb_open" (Options.t @-> TransactionDbOptions.t @-> string @-> ptr string_opt @-> returning t) let open_transactiondb ?opts ?txnopts name = let inner opts txndbopts = with_err_pointer (open_transactiondb_raw opts txndbopts name) in match opts, txnopts with None, None -> TransactionDbOptions.with_t (fun txndbopts -> (Options.with_t (fun opts -> inner opts txndbopts))) | Some opts, None -> TransactionDbOptions.with_t (inner opts) | None, Some txndbopts -> Options.with_t (fun opts -> inner opts txndbopts) | Some opts, Some txndbopts -> inner opts txndbopts let open_db ?opts name = match opts with | None -> Options.with_t (fun options -> with_err_pointer (open_db_raw options name)) | Some opts -> with_err_pointer (open_db_raw opts name) let open_db_for_read_only ?opts name error_if_log_file_exists = match opts with | None -> Options.with_t (fun options -> with_err_pointer (open_db_for_read_only_raw options name error_if_log_file_exists)) | Some opts -> with_err_pointer (open_db_for_read_only_raw opts name error_if_log_file_exists) let close = let inner = foreign "rocksdb_close" (t @-> returning void) in fun t -> inner t; t.valid <- false let with_db ?opts name ~f = let db = open_db ?opts name in finalize (fun () -> f db) (fun () -> close db) let put_raw = foreign "rocksdb_put" (t @-> WriteOptions.t @-> ptr char @-> Views.int_to_size_t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let put_raw_string = foreign "rocksdb_put" (t @-> WriteOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let put ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let open Bigarray.Array1 in let key_len = match key_len with None -> dim key - key_pos | Some len -> len in let value_len = match value_len with None -> dim value - value_pos | Some len -> len in let inner opts = with_err_pointer begin put_raw t opts (bigarray_start array1 key +@ key_pos) key_len (bigarray_start array1 value +@ value_pos) value_len end in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let put_string ?(key_pos=0) ?key_len ?(value_pos=0) ?value_len ?opts t key value = let key_len = match key_len with None -> String.length key - key_pos | Some len -> len in let value_len = match value_len with None -> String.length value - value_pos | Some len -> len in let inner opts = with_err_pointer begin put_raw_string t opts (ocaml_string_start key +@ key_pos) key_len (ocaml_string_start value +@ value_pos) value_len end in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let delete_raw = foreign "rocksdb_delete" (t @-> WriteOptions.t @-> ptr char @-> Views.int_to_size_t @-> returning_error void) let delete_raw_string = foreign "rocksdb_delete" (t @-> WriteOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> returning_error void) let delete ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in let inner opts = with_err_pointer (delete_raw t opts (bigarray_start array1 key +@ pos) len) in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let delete_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in let inner opts = with_err_pointer (delete_raw_string t opts (ocaml_string_start key +@ pos) len) in match opts with | None -> WriteOptions.with_t inner | Some opts -> inner opts let write_raw = foreign "rocksdb_write" (t @-> WriteOptions.t @-> WriteBatch.t @-> returning_error void) let write ?opts t wb = let inner opts = with_err_pointer (write_raw t opts wb) in match opts with | None -> WriteOptions.with_t inner | Some opts -> with_err_pointer (write_raw t opts wb) let get_raw = foreign "rocksdb_get" (t @-> ReadOptions.t @-> ptr char @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get_raw_string = foreign "rocksdb_get" (t @-> ReadOptions.t @-> ocaml_string @-> Views.int_to_size_t @-> ptr Views.int_to_size_t @-> returning_error (ptr char)) let get ?(pos=0) ?len ?opts t key = let open Bigarray.Array1 in let len = match len with None -> dim key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw t opts (bigarray_start array1 key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = bigarray_of_ptr array1 (!@res_size) Bigarray.char res in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let get_string ?(pos=0) ?len ?opts t key = let len = match len with None -> String.length key - pos | Some len -> len in let inner opts = let res_size = allocate Views.int_to_size_t 0 in let res = with_err_pointer (get_raw_string t opts (ocaml_string_start key +@ pos) len res_size) in if (to_voidp res) = null then None else begin let res' = string_from_ptr res (!@ res_size) in Gc.finalise_last (fun () -> free (to_voidp res)) res'; Some res' end in match opts with | Some opts -> inner opts | None -> ReadOptions.with_t inner let flush_raw = foreign "rocksdb_flush" (t @-> FlushOptions.t @-> returning_error void) let flush ?opts t = let inner opts = with_err_pointer (flush_raw t opts) in match opts with | None -> FlushOptions.with_t inner | Some opts -> inner opts let create_snapshot = foreign "rocksdb_create_snapshot" (t @-> returning Snapshot.t) let release_snapshot = foreign "rocksdb_release_snapshot" (t @-> Snapshot.t @-> returning void) module CheckpointObject = struct let name = "checkpoint_object" let constructor = "rocksdb_" ^ name ^ "_create" let destructor = "rocksdb_" ^ name ^ "_destroy" type db = t let db = t type nonrec t = t let t = t let create_no_gc = foreign constructor (db @-> returning t) let destroy = make_destroy t destructor let create db = let t = create_no_gc db in Gc.finalise destroy t; t let with_t db f = let t = create_no_gc db in finalize (fun () -> f t) (fun () -> destroy t) end let checkpoint_create db dir log_size_for_flush = let checkpoint_create_raw = foreign "rocksdb_checkpoint_create" (CheckpointObject.t @-> string @-> Views.int_to_uint64_t @-> ptr string_opt @-> returning void) in CheckpointObject.with_t db (fun checkpoint_object -> with_err_pointer (checkpoint_create_raw checkpoint_object dir log_size_for_flush)) let property_value db name = let get = foreign "rocksdb_property_value" (t @-> string @-> returning (ptr_opt char)) in let free = foreign "free" ((ptr char) @-> returning void) in let strlen = foreign "strlen" ((ptr char) @-> returning int) in match get db name with Some p -> let value = string_from_ptr p ~length:(strlen p) in free p; Some value | None -> None end include RocksDb
8702dfe76d0f954c18d6d8ebfe800b39252026db567601fb4c1db80895cb51d0
vagarenko/static-tensor
Vector.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE BangPatterns #-} module MatMul.Vector where import Data.Vector.Unboxed type Matrix4x4f = Vector Float mkMat :: [Float] -> Matrix4x4f mkMat xs@(_a:_b:_c:_d:_e:_f:_g:_h:_i:_j:_k:_l:_m:_n:_o:_p:_) = fromList xs mkMat _ = error "Not enough elements for matrix." mult :: Matrix4x4f -> Matrix4x4f -> Matrix4x4f mult a b = generate 16 go where go n = i0 * j0 + i1 * j1 + i2 * j2 + i3 * j3 where (!i, !j) = n `divMod` 4 i0 = unsafeIndex a (0 + i * 4) i1 = unsafeIndex a (1 + i * 4) i2 = unsafeIndex a (2 + i * 4) i3 = unsafeIndex a (3 + i * 4) j0 = unsafeIndex b (j + 0 * 4) j1 = unsafeIndex b (j + 1 * 4) j2 = unsafeIndex b (j + 2 * 4) j3 = unsafeIndex b (j + 3 * 4)
null
https://raw.githubusercontent.com/vagarenko/static-tensor/8409d281707c23f3fe2028e926f1d4e8f7a9bc2d/bench/MatMul/Vector.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE BangPatterns #
# LANGUAGE DeriveGeneric # module MatMul.Vector where import Data.Vector.Unboxed type Matrix4x4f = Vector Float mkMat :: [Float] -> Matrix4x4f mkMat xs@(_a:_b:_c:_d:_e:_f:_g:_h:_i:_j:_k:_l:_m:_n:_o:_p:_) = fromList xs mkMat _ = error "Not enough elements for matrix." mult :: Matrix4x4f -> Matrix4x4f -> Matrix4x4f mult a b = generate 16 go where go n = i0 * j0 + i1 * j1 + i2 * j2 + i3 * j3 where (!i, !j) = n `divMod` 4 i0 = unsafeIndex a (0 + i * 4) i1 = unsafeIndex a (1 + i * 4) i2 = unsafeIndex a (2 + i * 4) i3 = unsafeIndex a (3 + i * 4) j0 = unsafeIndex b (j + 0 * 4) j1 = unsafeIndex b (j + 1 * 4) j2 = unsafeIndex b (j + 2 * 4) j3 = unsafeIndex b (j + 3 * 4)
1ce28762a83c95aa9a89fa65d2fed08a480f7233ac5dd0954e7744bf0d79d4b0
clojure-dus/chess
piece_attacks.clj
(ns chess.movelogic.bitboard.piece-attacks (:use [chess.movelogic.bitboard file-rank bitoperations])) ; pre-calculated move and attack arrays (defn- create-vect-bitboards [moves-coords] "creates a vector of 64 squares which have bitboards in which moves-coords have been flaged " (let [all-moves (for [[square file rank] file-rank-squares [x y] moves-coords :let [f (+ file x) r (+ rank y)] :when (and (> f 0 ) (< f 9) (> r 0) (< r 9))] [square f r]) bitboard-updater (fn [result [square f r]] (let [bitboard (nth result square) bit (bit-set 0 (coord->square f r))] (assoc result square (bit-or bitboard bit)))) empty-board-vect (apply vector (repeat 64 0))] (reduce bitboard-updater empty-board-vect all-moves))) (defn indexed-bits [bit-vector] "gets the one bits from a vector of zero/ones into a vector of [pos 1] For example [1 0 1] -> [[0 1] [2 1]]" (keep-indexed #(when (== %2 1) [%1 %2]) bit-vector)) (defn slide-attack-byte [occupied-bits pos] "occupied-bits - flags the positions of all pieces of a rank,file or diagonal. pos - the current square position of the current piece returns a long where the first 8-bits flag the squares to which an piece on position pos can move (including any attacked pieces) Example : (slide-attack-bits 2r001001 3) -> 2r10110 occupied-bits can be between 0 and 64 which means that 6-bits are sufficient to represent all occupied states of any row,column or diagonal of a chessboard. The 2 outer bits a1 and h1 are not needed because they depend on b1 and g1. thats why six bits are sufficent." (let [occupied-bits (bit-shift-left occupied-bits 1) bit-vect (bit->vector occupied-bits 8) indexed-bits (indexed-bits bit-vect) nearest-left (nth (last (filter (fn [[idx bit]] (< idx pos)) indexed-bits)) 0 0) nearest-right (nth (first (filter (fn [[idx bit]] (> idx pos)) indexed-bits)) 0 9)] (vector->bit (for [idx (range 8)] (cond (= idx pos) 0 (< idx nearest-left) 0 (> idx nearest-right) 0 :else 1))))) (defn make-attack-diagonal [square occupied diagonal-row-getter] "returns a diagonal sliding attack mask. It does this by first the determining the member squares and square-pos of the wanted diagonal. Then a horizontal slide attack mask is generated using the given occupied bits and square pos. This horizotal is finally mapped back to the wanted diagonal and returnd" (let [diag-row (diagonal-row-getter square) position (.indexOf diag-row square) attack-bits (slide-attack-byte occupied position) attack-vect (bit->vector attack-bits 8) update-vect (partition 2 (interleave diag-row attack-vect))] (reduce (fn [bitmap [sq bit]] (if (= 1 bit) (bit-set bitmap sq) bitmap)) 0 update-vect))) ;;-------------------------------------------------------------------- ;; Pre-calculated attack and move arrays for each chess piece which are used by move.clj to calculate possible of an piece ;;-------------------------------------------------------------------- (def knight-attack-array "creates a lookup array of 64 squares which have bitboards in which knight-attacks have been flaged " (long-array (create-vect-bitboards [[1 2] [2 1] [2 -1] [1 -2] [-1 -2] [-2 -1] [-2 1] [-1 2]] ))) (def pawn-white-move-array "creates a lookup array of 64 squares which have bitboards in which white pawn moves have been flaged " (long-array (create-vect-bitboards [[0 1]]))) (def pawn-white-double-move-array "creates a lookup array of 64 squares which have bitboards in which the white double moves have been flaged " (let [row-4-squares [24 25 26 27 28 29 30 31]] (long-array (concat (repeat 8 0) (map #(bit-set 0 %) row-4-squares) (repeat 48 0))))) (def pawn-black-move-array "creates a lookup array of 64 squares which have bitboards in which black pawn moves have been flaged " (long-array (create-vect-bitboards [[0 -1]]))) (def pawn-black-double-move-array "creates a lookup array of 64 squares which have bitboards in which the black double moves have been flaged " (let [row-5-squares [32 33 34 35 36 37 38 39]] (long-array (concat (repeat 48 0) (map #(bit-set 0 %) row-5-squares) (repeat 8 0))))) (def pawn-white-attack-array "creates a lookup array of 64 squares which have bitboards in which white pawn attacks have been flaged " (long-array (create-vect-bitboards [[1 1] [-1 1]]))) (def pawn-black-attack-array "creates a lookup array of 64 squares which have bitboards in which black pawn attacks have been flaged " (long-array (create-vect-bitboards [[-1 -1] [1 -1]]))) (def king-attack-array "creates a lookup array of 64 squares which have bitboards in which king attacks have been flaged " (long-array (create-vect-bitboards [[1 1][-1 1][-1 -1][1 -1][0 1][0 -1][1 0][-1 0]]))) (def attack-array-ranks "2 dimensinal array [square][occupied] in which all horizontal slide positions have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a row." (to-long-array-2d (map (fn [square] (let [shift-left #(bit-shift-left %2 (aget ^ints rank-shift-array %1))] (for [occupied (range 64)] (shift-left square (slide-attack-byte occupied (square->column square)))))) (range 64)))) (defn ^long get-attack-rank [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-row (bit-and allpieces (aget ^longs masks-row from-sq)) ^long occupied-mask (unsigned-shift-right occupied-row (inc (aget ^ints rank-shift-array from-sq)))] (deep-aget ^longs attack-array-ranks from-sq occupied-mask))) (def attack-array-files "2 dimensinal array [square][occupied] in which all vertical slide positions have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a column." (to-long-array-2d (map (fn [square] (let [ shift-column-left #(bit-shift-left %2 (square->column %1))] (for [occupied (range 64)] (shift-column-left square (rotate90-bitboard-clockwise (slide-attack-byte occupied (- 7 (square->row square)))))))) (range 64)))) (defn ^long get-attack-file [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-column (bit-and allpieces (aget ^longs masks-column from-sq)) ^long occupied-mask (shift-rank-to-bottom occupied-column from-sq)] (deep-aget ^longs attack-array-files from-sq occupied-mask))) (def attack-array-diagonal-a1h8 "2 dimensinal array [square][occupied] in which all diagonal slide positions from a1 to h8 have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a diagonal." (to-long-array-2d (map (fn [square] (for [occupied (range 64)] (make-attack-diagonal square occupied get-diagonal-a1h8))) (range 64)))) (defn ^long get-attack-diagonal-a1h8 [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-diagonal (bit-and allpieces (aget ^longs masks-diagonal-a1h8 from-sq)) ^long occupied-mask (shift-diagonal-a1h8-to-bottom occupied-diagonal from-sq)] (deep-aget ^longs attack-array-diagonal-a1h8 from-sq occupied-mask))) (def attack-array-diagonal-a8h1 "2 dimensinal array [square][occupied] in which all diagonal slide positions from a8 to h1 have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a diagonal." (to-long-array-2d (map (fn [square] (for [occupied (range 64)] (make-attack-diagonal square occupied get-diagonal-a8h1))) (range 64)))) (defn ^long get-attack-diagonal-a8h1 [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-diagonal (bit-and allpieces (aget ^longs masks-diagonal-a8h1 from-sq)) ^long occupied-mask (shift-diagonal-a8h1-to-bottom occupied-diagonal from-sq)] (deep-aget ^longs attack-array-diagonal-a8h1 from-sq occupied-mask)))
null
https://raw.githubusercontent.com/clojure-dus/chess/7eb0e5bf15290f520f31e7eb3f2b7742c7f27729/src/chess/movelogic/bitboard/piece_attacks.clj
clojure
pre-calculated move and attack arrays -------------------------------------------------------------------- Pre-calculated attack and move arrays for each chess piece --------------------------------------------------------------------
(ns chess.movelogic.bitboard.piece-attacks (:use [chess.movelogic.bitboard file-rank bitoperations])) (defn- create-vect-bitboards [moves-coords] "creates a vector of 64 squares which have bitboards in which moves-coords have been flaged " (let [all-moves (for [[square file rank] file-rank-squares [x y] moves-coords :let [f (+ file x) r (+ rank y)] :when (and (> f 0 ) (< f 9) (> r 0) (< r 9))] [square f r]) bitboard-updater (fn [result [square f r]] (let [bitboard (nth result square) bit (bit-set 0 (coord->square f r))] (assoc result square (bit-or bitboard bit)))) empty-board-vect (apply vector (repeat 64 0))] (reduce bitboard-updater empty-board-vect all-moves))) (defn indexed-bits [bit-vector] "gets the one bits from a vector of zero/ones into a vector of [pos 1] For example [1 0 1] -> [[0 1] [2 1]]" (keep-indexed #(when (== %2 1) [%1 %2]) bit-vector)) (defn slide-attack-byte [occupied-bits pos] "occupied-bits - flags the positions of all pieces of a rank,file or diagonal. pos - the current square position of the current piece returns a long where the first 8-bits flag the squares to which an piece on position pos can move (including any attacked pieces) Example : (slide-attack-bits 2r001001 3) -> 2r10110 occupied-bits can be between 0 and 64 which means that 6-bits are sufficient to represent all occupied states of any row,column or diagonal of a chessboard. The 2 outer bits a1 and h1 are not needed because they depend on b1 and g1. thats why six bits are sufficent." (let [occupied-bits (bit-shift-left occupied-bits 1) bit-vect (bit->vector occupied-bits 8) indexed-bits (indexed-bits bit-vect) nearest-left (nth (last (filter (fn [[idx bit]] (< idx pos)) indexed-bits)) 0 0) nearest-right (nth (first (filter (fn [[idx bit]] (> idx pos)) indexed-bits)) 0 9)] (vector->bit (for [idx (range 8)] (cond (= idx pos) 0 (< idx nearest-left) 0 (> idx nearest-right) 0 :else 1))))) (defn make-attack-diagonal [square occupied diagonal-row-getter] "returns a diagonal sliding attack mask. It does this by first the determining the member squares and square-pos of the wanted diagonal. Then a horizontal slide attack mask is generated using the given occupied bits and square pos. This horizotal is finally mapped back to the wanted diagonal and returnd" (let [diag-row (diagonal-row-getter square) position (.indexOf diag-row square) attack-bits (slide-attack-byte occupied position) attack-vect (bit->vector attack-bits 8) update-vect (partition 2 (interleave diag-row attack-vect))] (reduce (fn [bitmap [sq bit]] (if (= 1 bit) (bit-set bitmap sq) bitmap)) 0 update-vect))) which are used by move.clj to calculate possible of an piece (def knight-attack-array "creates a lookup array of 64 squares which have bitboards in which knight-attacks have been flaged " (long-array (create-vect-bitboards [[1 2] [2 1] [2 -1] [1 -2] [-1 -2] [-2 -1] [-2 1] [-1 2]] ))) (def pawn-white-move-array "creates a lookup array of 64 squares which have bitboards in which white pawn moves have been flaged " (long-array (create-vect-bitboards [[0 1]]))) (def pawn-white-double-move-array "creates a lookup array of 64 squares which have bitboards in which the white double moves have been flaged " (let [row-4-squares [24 25 26 27 28 29 30 31]] (long-array (concat (repeat 8 0) (map #(bit-set 0 %) row-4-squares) (repeat 48 0))))) (def pawn-black-move-array "creates a lookup array of 64 squares which have bitboards in which black pawn moves have been flaged " (long-array (create-vect-bitboards [[0 -1]]))) (def pawn-black-double-move-array "creates a lookup array of 64 squares which have bitboards in which the black double moves have been flaged " (let [row-5-squares [32 33 34 35 36 37 38 39]] (long-array (concat (repeat 48 0) (map #(bit-set 0 %) row-5-squares) (repeat 8 0))))) (def pawn-white-attack-array "creates a lookup array of 64 squares which have bitboards in which white pawn attacks have been flaged " (long-array (create-vect-bitboards [[1 1] [-1 1]]))) (def pawn-black-attack-array "creates a lookup array of 64 squares which have bitboards in which black pawn attacks have been flaged " (long-array (create-vect-bitboards [[-1 -1] [1 -1]]))) (def king-attack-array "creates a lookup array of 64 squares which have bitboards in which king attacks have been flaged " (long-array (create-vect-bitboards [[1 1][-1 1][-1 -1][1 -1][0 1][0 -1][1 0][-1 0]]))) (def attack-array-ranks "2 dimensinal array [square][occupied] in which all horizontal slide positions have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a row." (to-long-array-2d (map (fn [square] (let [shift-left #(bit-shift-left %2 (aget ^ints rank-shift-array %1))] (for [occupied (range 64)] (shift-left square (slide-attack-byte occupied (square->column square)))))) (range 64)))) (defn ^long get-attack-rank [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-row (bit-and allpieces (aget ^longs masks-row from-sq)) ^long occupied-mask (unsigned-shift-right occupied-row (inc (aget ^ints rank-shift-array from-sq)))] (deep-aget ^longs attack-array-ranks from-sq occupied-mask))) (def attack-array-files "2 dimensinal array [square][occupied] in which all vertical slide positions have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a column." (to-long-array-2d (map (fn [square] (let [ shift-column-left #(bit-shift-left %2 (square->column %1))] (for [occupied (range 64)] (shift-column-left square (rotate90-bitboard-clockwise (slide-attack-byte occupied (- 7 (square->row square)))))))) (range 64)))) (defn ^long get-attack-file [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-column (bit-and allpieces (aget ^longs masks-column from-sq)) ^long occupied-mask (shift-rank-to-bottom occupied-column from-sq)] (deep-aget ^longs attack-array-files from-sq occupied-mask))) (def attack-array-diagonal-a1h8 "2 dimensinal array [square][occupied] in which all diagonal slide positions from a1 to h8 have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a diagonal." (to-long-array-2d (map (fn [square] (for [occupied (range 64)] (make-attack-diagonal square occupied get-diagonal-a1h8))) (range 64)))) (defn ^long get-attack-diagonal-a1h8 [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-diagonal (bit-and allpieces (aget ^longs masks-diagonal-a1h8 from-sq)) ^long occupied-mask (shift-diagonal-a1h8-to-bottom occupied-diagonal from-sq)] (deep-aget ^longs attack-array-diagonal-a1h8 from-sq occupied-mask))) (def attack-array-diagonal-a8h1 "2 dimensinal array [square][occupied] in which all diagonal slide positions from a8 to h1 have been flaged. occupied is a 6-bit (0..64) mask having 1 bit flags for all occupied squares of a diagonal." (to-long-array-2d (map (fn [square] (for [occupied (range 64)] (make-attack-diagonal square occupied get-diagonal-a8h1))) (range 64)))) (defn ^long get-attack-diagonal-a8h1 [game-state ^long from-sq] (let [^long allpieces (:allpieces game-state) occupied-diagonal (bit-and allpieces (aget ^longs masks-diagonal-a8h1 from-sq)) ^long occupied-mask (shift-diagonal-a8h1-to-bottom occupied-diagonal from-sq)] (deep-aget ^longs attack-array-diagonal-a8h1 from-sq occupied-mask)))
cfaa3a8cbc8aff8ee392830dc913dfa311df022d6de4c21c27b71f4246c09d74
Eonblast/Scalaxis
db_verify_use.erl
2010 - 2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > %% @doc Database based on db_ets that verifies the correct use of the DB %% interface. %% @end %% @version $Id$ -module(db_verify_use). -author(''). -vsn('$Id$'). -include("scalaris.hrl"). -behaviour(db_beh). -define(BASE_DB, db_ets). -type db_t()::{?BASE_DB:db(), Counter::non_neg_integer()}. Note : must include db_beh.hrl AFTER the type definitions for erlang < R13B04 % to work. -include("db_beh.hrl"). -define(TRACE0(Fun ) , io : : ~w()~n " , [ self ( ) , Fun ] ) ) . -define(TRACE1(Fun , Par1 ) , io : : " , [ self ( ) , Fun , Par1 ] ) ) . -define(TRACE2(Fun , Par1 , Par2 ) , io : : ~w(~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 ] ) ) . -define(TRACE3(Fun , Par1 , Par2 , Par3 ) , io : : ~w(~w , ~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 , Par3 ] ) ) . -define(TRACE4(Fun , Par1 , Par2 , Par3 , Par4 ) , io : : ~w(~w , ~w , ~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 , Par3 , Par4 ] ) ) . -define(TRACE5(Fun , Par1 , Par2 , Par3 , Par4 , Par5 ) , io : : ~w(~w , ~w , ~w , ~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 , Par3 , Par4 , Par5 ] ) ) . -define(TRACE0(Fun), ok). -define(TRACE1(Fun, Par1), ok). -define(TRACE2(Fun, Par1, Par2), ok). -define(TRACE3(Fun, Par1, Par2, Par3), ok). -define(TRACE4(Fun, Par1, Par2, Par3, Par4), ok). -define(TRACE5(Fun, Par1, Par2, Par3, Par4, Par5), ok). -spec verify_counter(Counter::non_neg_integer()) -> ok. verify_counter(Counter) -> case erlang:get(?MODULE) of Counter -> ok; undefined -> erlang:error({counter_undefined, Counter}); _ -> erlang:error({counter_mismatch, Counter, erlang:get(?MODULE)}) end. -spec update_counter(Counter::non_neg_integer()) -> NewCounter::non_neg_integer(). update_counter(Counter) -> NewCounter = Counter + 1, erlang:put(?MODULE, NewCounter), NewCounter. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% public functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% @doc initializes a new database. new_() -> ?TRACE0(new), case erlang:get(?MODULE) of undefined -> ok; _ -> erlang:error({counter_defined, erlang:get(?MODULE)}) end, erlang:put(?MODULE, 0), {?BASE_DB:new(), 0}. %% @doc Re-opens a previously existing database. open_(FileName) -> ?TRACE1(open, FileName), case erlang:get(?MODULE) of undefined -> ok; _ -> erlang:error({counter_defined, erlang:get(?MODULE)}) end, erlang:put(?MODULE, 0), {?BASE_DB:open(FileName), 0}. %% @doc Closes and deletes the DB. close_({DB, _Counter} = _DB_) -> ?TRACE1(close, _DB_), erlang:erase(?MODULE), ?BASE_DB:close(DB). %% @doc Closes and (optionally) deletes the DB. close_({DB, _Counter} = _DB_, Delete) -> ?TRACE2(close, _DB_, Delete), erlang:erase(?MODULE), ?BASE_DB:close(DB, Delete). @doc Returns the name of the DB which can be used with open/1 . get_name_({DB, Counter} = _DB_) -> ?TRACE1(get_name, _DB_), verify_counter(Counter), ?BASE_DB:get_name(DB). %% @doc Gets an entry from the DB. If there is no entry with the given key, %% an empty entry will be returned. get_entry_({DB, Counter} = _DB_, Key) -> ?TRACE2(get_entry, _DB_, Key), verify_counter(Counter), ?BASE_DB:get_entry(DB, Key). %% @doc Gets an entry from the DB. If there is no entry with the given key, an empty entry will be returned . The first component of the result %% tuple states whether the value really exists in the DB. get_entry2_({DB, Counter} = _DB_, Key) -> ?TRACE2(get_entry2, _DB_, Key), verify_counter(Counter), ?BASE_DB:get_entry2(DB, Key). %% @doc Inserts a complete entry into the DB. set_entry_({DB, Counter} = _DB_, Entry) -> ?TRACE2(set_entry, _DB_, Entry), verify_counter(Counter), {?BASE_DB:set_entry(DB, Entry), update_counter(Counter)}. %% @doc Updates an existing (!) entry in the DB. update_entry_({DB, Counter} = _DB_, Entry) -> ?TRACE2(update_entry, _DB_, Entry), verify_counter(Counter), {true, _} = ?BASE_DB:get_entry2(DB, db_entry:get_key(Entry)), {?BASE_DB:update_entry(DB, Entry), update_counter(Counter)}. %% @doc Removes all values with the given entry's key from the DB. delete_entry_({DB, Counter} = _DB_, Entry) -> ?TRACE2(delete_entry, _DB_, Entry), verify_counter(Counter), {?BASE_DB:delete_entry(DB, Entry), update_counter(Counter)}. %% @doc Returns the number of stored keys. get_load_({DB, Counter} = _DB_) -> ?TRACE1(get_load, _DB_), verify_counter(Counter), ?BASE_DB:get_load(DB). %% @doc Returns the number of stored keys in the given Interval. get_load_({DB, Counter} = _DB_, Interval) -> ?TRACE2(get_load, _DB_, Interval), verify_counter(Counter), ?BASE_DB:get_load(DB, Interval). @doc Adds all db_entry objects in the Data list . add_data_({DB, Counter} = _DB_, Data) -> ?TRACE2(add_data, _DB_, Data), verify_counter(Counter), {?BASE_DB:add_data(DB, Data), update_counter(Counter)}. @doc Splits the database into a database ( first element ) which contains all keys in MyNewInterval and a list of the other values ( second element ) . split_data_({DB, Counter} = _DB_, MyNewInterval) -> ?TRACE2(split_data, _DB_, MyNewInterval), verify_counter(Counter), {MyNewDB, HisList} = ?BASE_DB:split_data(DB, MyNewInterval), {{MyNewDB, update_counter(Counter)}, HisList}. @doc Returns the key that would remove not more than TargetLoad entries %% from the DB when starting at the key directly after Begin. get_split_key_({DB, Counter} = _DB_, Begin, TargetLoad, Direction) -> ?TRACE4(get_load, _DB_, Begin, TargetLoad, Direction), verify_counter(Counter), ?BASE_DB:get_split_key(DB, Begin, TargetLoad, Direction). %% @doc Gets (non-empty) db_entry objects in the given range. get_entries_({DB, Counter} = _DB_, Interval) -> ?TRACE2(get_entries, _DB_, Interval), verify_counter(Counter), ?BASE_DB:get_entries(DB, Interval). %% @doc Gets all custom objects (created by ValueFun(DBEntry)) from the DB for which FilterFun returns true . get_entries_({DB, Counter} = _DB_, FilterFun, ValueFun) -> ?TRACE3(get_entries, _DB_, FilterFun, ValueFun), verify_counter(Counter), ?BASE_DB:get_entries(DB, FilterFun, ValueFun). %% @doc Returns all key-value pairs of the given DB which are in the given interval but at most ChunkSize elements . get_chunk_({DB, Counter} = _DB_, Interval, ChunkSize) -> ?TRACE3(get_chunk, _DB_, Interval, ChunkSize), verify_counter(Counter), ?BASE_DB:get_chunk(DB, Interval, ChunkSize). %% @doc Returns all key-value pairs of the given DB which are in the given interval but at most ChunkSize elements . get_chunk_({DB, Counter} = _DB_, Interval, FilterFun, ValueFun, ChunkSize) -> ?TRACE5(get_chunk, _DB_, Interval, FilterFun, ValueFun, ChunkSize), verify_counter(Counter), ?BASE_DB:get_chunk(DB, Interval, FilterFun, ValueFun, ChunkSize). %% @doc Returns all DB entries. get_data_({DB, Counter} = _DB_) -> ?TRACE1(get_data, _DB_), verify_counter(Counter), ?BASE_DB:get_data(DB). %% doc Adds a subscription for the given interval under Tag (overwrites an %% existing subscription with that tag). set_subscription_({DB, Counter} = _DB_, SubscrTuple) -> ?TRACE2(set_subscription, _DB_, SubscrTuple), verify_counter(Counter), {?BASE_DB:set_subscription(DB, SubscrTuple), update_counter(Counter)}. %% doc Gets a subscription stored under Tag (empty list if there is none). get_subscription_({DB, Counter} = _DB_, Tag) -> ?TRACE2(get_data, _DB_, Tag), verify_counter(Counter), ?BASE_DB:get_subscription(DB, Tag). %% doc Removes a subscription stored under Tag (if there is one). remove_subscription_({DB, Counter} = _DB_, Tag) -> ?TRACE2(get_data, _DB_, Tag), verify_counter(Counter), {?BASE_DB:remove_subscription(DB, Tag), update_counter(Counter)}. %% @doc Adds the new interval to the interval to record changes for. %% Changed entries can then be gathered by get_changes/1. record_changes_({DB, Counter} = _DB_, NewInterval) -> ?TRACE2(record_changes, _DB_, NewInterval), verify_counter(Counter), {?BASE_DB:record_changes(DB, NewInterval), update_counter(Counter)}. %% @doc Stops recording changes and removes all entries from the table of %% changed keys. stop_record_changes_({DB, Counter} = _DB_) -> ?TRACE1(stop_record_changes, _DB_), verify_counter(Counter), {?BASE_DB:stop_record_changes(DB), update_counter(Counter)}. %% @doc Stops recording changes in the given interval and removes all such %% entries from the table of changed keys. stop_record_changes_({DB, Counter} = _DB_, Interval) -> ?TRACE2(stop_record_changes, _DB_, Interval), verify_counter(Counter), {?BASE_DB:stop_record_changes(DB, Interval), update_counter(Counter)}. %% @doc Gets all db_entry objects which have been changed or deleted. get_changes_({DB, Counter} = _DB_) -> ?TRACE1(get_changes, _DB_), verify_counter(Counter), ?BASE_DB:get_changes(DB). %% @doc Gets all db_entry objects in the given interval which have been %% changed or deleted. get_changes_({DB, Counter} = _DB_, Interval) -> ?TRACE2(get_changes, _DB_, Interval), verify_counter(Counter), ?BASE_DB:get_changes(DB, Interval). read({DB, Counter} = _DB_, Key) -> ?TRACE2(read, _DB_, Key), verify_counter(Counter), ?BASE_DB:read(DB, Key). write({DB, Counter} = _DB_, Key, Value, Version) -> ?TRACE4(write, _DB_, Key, Value, Version), verify_counter(Counter), {?BASE_DB:write(DB, Key, Value, Version), update_counter(Counter)}. delete({DB, Counter} = _DB_, Key) -> ?TRACE2(delete, _DB_, Key), verify_counter(Counter), {NewDB, Status} = ?BASE_DB:delete(DB, Key), {{NewDB, update_counter(Counter)}, Status}. update_entries_({DB, Counter} = _DB_, NewEntries, Pred, UpdateFun) -> ?TRACE4(update_entries, _DB_, NewEntries, Pred, UpdateFun), verify_counter(Counter), {?BASE_DB:update_entries(DB, NewEntries, Pred, UpdateFun), update_counter(Counter)}. %% @doc Deletes all objects in the given Range or (if a function is provided) for which the FilterFun returns true from the DB . delete_entries_({DB, Counter} = _DB_, RangeOrFilterFun) -> ?TRACE2(get_entries, _DB_, RangeOrFilterFun), verify_counter(Counter), {?BASE_DB:delete_entries(DB, RangeOrFilterFun), update_counter(Counter)}. delete_chunk_({DB, Counter} = _DB_, Interval, ChunkSize) -> ?TRACE3(delete_chunk, _DB_, Interval, ChunkSize), verify_counter(Counter), {RestInterval, NewDB} = ?BASE_DB:delete_chunk(DB, Interval, ChunkSize), {RestInterval, {NewDB, update_counter(Counter)}}. check_db({DB, Counter} = _DB_) -> ?TRACE1(check_db, _DB_), verify_counter(Counter), ?BASE_DB:check_db(DB).
null
https://raw.githubusercontent.com/Eonblast/Scalaxis/10287d11428e627dca8c41c818745763b9f7e8d4/src/db_verify_use.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc Database based on db_ets that verifies the correct use of the DB interface. @end @version $Id$ to work. public functions @doc initializes a new database. @doc Re-opens a previously existing database. @doc Closes and deletes the DB. @doc Closes and (optionally) deletes the DB. @doc Gets an entry from the DB. If there is no entry with the given key, an empty entry will be returned. @doc Gets an entry from the DB. If there is no entry with the given key, tuple states whether the value really exists in the DB. @doc Inserts a complete entry into the DB. @doc Updates an existing (!) entry in the DB. @doc Removes all values with the given entry's key from the DB. @doc Returns the number of stored keys. @doc Returns the number of stored keys in the given Interval. from the DB when starting at the key directly after Begin. @doc Gets (non-empty) db_entry objects in the given range. @doc Gets all custom objects (created by ValueFun(DBEntry)) from the DB for @doc Returns all key-value pairs of the given DB which are in the given @doc Returns all key-value pairs of the given DB which are in the given @doc Returns all DB entries. doc Adds a subscription for the given interval under Tag (overwrites an existing subscription with that tag). doc Gets a subscription stored under Tag (empty list if there is none). doc Removes a subscription stored under Tag (if there is one). @doc Adds the new interval to the interval to record changes for. Changed entries can then be gathered by get_changes/1. @doc Stops recording changes and removes all entries from the table of changed keys. @doc Stops recording changes in the given interval and removes all such entries from the table of changed keys. @doc Gets all db_entry objects which have been changed or deleted. @doc Gets all db_entry objects in the given interval which have been changed or deleted. @doc Deletes all objects in the given Range or (if a function is provided)
2010 - 2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > -module(db_verify_use). -author(''). -vsn('$Id$'). -include("scalaris.hrl"). -behaviour(db_beh). -define(BASE_DB, db_ets). -type db_t()::{?BASE_DB:db(), Counter::non_neg_integer()}. Note : must include db_beh.hrl AFTER the type definitions for erlang < R13B04 -include("db_beh.hrl"). -define(TRACE0(Fun ) , io : : ~w()~n " , [ self ( ) , Fun ] ) ) . -define(TRACE1(Fun , Par1 ) , io : : " , [ self ( ) , Fun , Par1 ] ) ) . -define(TRACE2(Fun , Par1 , Par2 ) , io : : ~w(~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 ] ) ) . -define(TRACE3(Fun , Par1 , Par2 , Par3 ) , io : : ~w(~w , ~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 , Par3 ] ) ) . -define(TRACE4(Fun , Par1 , Par2 , Par3 , Par4 ) , io : : ~w(~w , ~w , ~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 , Par3 , Par4 ] ) ) . -define(TRACE5(Fun , Par1 , Par2 , Par3 , Par4 , Par5 ) , io : : ~w(~w , ~w , ~w , ~w , ~w)~n " , [ self ( ) , Fun , Par1 , Par2 , Par3 , Par4 , Par5 ] ) ) . -define(TRACE0(Fun), ok). -define(TRACE1(Fun, Par1), ok). -define(TRACE2(Fun, Par1, Par2), ok). -define(TRACE3(Fun, Par1, Par2, Par3), ok). -define(TRACE4(Fun, Par1, Par2, Par3, Par4), ok). -define(TRACE5(Fun, Par1, Par2, Par3, Par4, Par5), ok). -spec verify_counter(Counter::non_neg_integer()) -> ok. verify_counter(Counter) -> case erlang:get(?MODULE) of Counter -> ok; undefined -> erlang:error({counter_undefined, Counter}); _ -> erlang:error({counter_mismatch, Counter, erlang:get(?MODULE)}) end. -spec update_counter(Counter::non_neg_integer()) -> NewCounter::non_neg_integer(). update_counter(Counter) -> NewCounter = Counter + 1, erlang:put(?MODULE, NewCounter), NewCounter. new_() -> ?TRACE0(new), case erlang:get(?MODULE) of undefined -> ok; _ -> erlang:error({counter_defined, erlang:get(?MODULE)}) end, erlang:put(?MODULE, 0), {?BASE_DB:new(), 0}. open_(FileName) -> ?TRACE1(open, FileName), case erlang:get(?MODULE) of undefined -> ok; _ -> erlang:error({counter_defined, erlang:get(?MODULE)}) end, erlang:put(?MODULE, 0), {?BASE_DB:open(FileName), 0}. close_({DB, _Counter} = _DB_) -> ?TRACE1(close, _DB_), erlang:erase(?MODULE), ?BASE_DB:close(DB). close_({DB, _Counter} = _DB_, Delete) -> ?TRACE2(close, _DB_, Delete), erlang:erase(?MODULE), ?BASE_DB:close(DB, Delete). @doc Returns the name of the DB which can be used with open/1 . get_name_({DB, Counter} = _DB_) -> ?TRACE1(get_name, _DB_), verify_counter(Counter), ?BASE_DB:get_name(DB). get_entry_({DB, Counter} = _DB_, Key) -> ?TRACE2(get_entry, _DB_, Key), verify_counter(Counter), ?BASE_DB:get_entry(DB, Key). an empty entry will be returned . The first component of the result get_entry2_({DB, Counter} = _DB_, Key) -> ?TRACE2(get_entry2, _DB_, Key), verify_counter(Counter), ?BASE_DB:get_entry2(DB, Key). set_entry_({DB, Counter} = _DB_, Entry) -> ?TRACE2(set_entry, _DB_, Entry), verify_counter(Counter), {?BASE_DB:set_entry(DB, Entry), update_counter(Counter)}. update_entry_({DB, Counter} = _DB_, Entry) -> ?TRACE2(update_entry, _DB_, Entry), verify_counter(Counter), {true, _} = ?BASE_DB:get_entry2(DB, db_entry:get_key(Entry)), {?BASE_DB:update_entry(DB, Entry), update_counter(Counter)}. delete_entry_({DB, Counter} = _DB_, Entry) -> ?TRACE2(delete_entry, _DB_, Entry), verify_counter(Counter), {?BASE_DB:delete_entry(DB, Entry), update_counter(Counter)}. get_load_({DB, Counter} = _DB_) -> ?TRACE1(get_load, _DB_), verify_counter(Counter), ?BASE_DB:get_load(DB). get_load_({DB, Counter} = _DB_, Interval) -> ?TRACE2(get_load, _DB_, Interval), verify_counter(Counter), ?BASE_DB:get_load(DB, Interval). @doc Adds all db_entry objects in the Data list . add_data_({DB, Counter} = _DB_, Data) -> ?TRACE2(add_data, _DB_, Data), verify_counter(Counter), {?BASE_DB:add_data(DB, Data), update_counter(Counter)}. @doc Splits the database into a database ( first element ) which contains all keys in MyNewInterval and a list of the other values ( second element ) . split_data_({DB, Counter} = _DB_, MyNewInterval) -> ?TRACE2(split_data, _DB_, MyNewInterval), verify_counter(Counter), {MyNewDB, HisList} = ?BASE_DB:split_data(DB, MyNewInterval), {{MyNewDB, update_counter(Counter)}, HisList}. @doc Returns the key that would remove not more than TargetLoad entries get_split_key_({DB, Counter} = _DB_, Begin, TargetLoad, Direction) -> ?TRACE4(get_load, _DB_, Begin, TargetLoad, Direction), verify_counter(Counter), ?BASE_DB:get_split_key(DB, Begin, TargetLoad, Direction). get_entries_({DB, Counter} = _DB_, Interval) -> ?TRACE2(get_entries, _DB_, Interval), verify_counter(Counter), ?BASE_DB:get_entries(DB, Interval). which FilterFun returns true . get_entries_({DB, Counter} = _DB_, FilterFun, ValueFun) -> ?TRACE3(get_entries, _DB_, FilterFun, ValueFun), verify_counter(Counter), ?BASE_DB:get_entries(DB, FilterFun, ValueFun). interval but at most ChunkSize elements . get_chunk_({DB, Counter} = _DB_, Interval, ChunkSize) -> ?TRACE3(get_chunk, _DB_, Interval, ChunkSize), verify_counter(Counter), ?BASE_DB:get_chunk(DB, Interval, ChunkSize). interval but at most ChunkSize elements . get_chunk_({DB, Counter} = _DB_, Interval, FilterFun, ValueFun, ChunkSize) -> ?TRACE5(get_chunk, _DB_, Interval, FilterFun, ValueFun, ChunkSize), verify_counter(Counter), ?BASE_DB:get_chunk(DB, Interval, FilterFun, ValueFun, ChunkSize). get_data_({DB, Counter} = _DB_) -> ?TRACE1(get_data, _DB_), verify_counter(Counter), ?BASE_DB:get_data(DB). set_subscription_({DB, Counter} = _DB_, SubscrTuple) -> ?TRACE2(set_subscription, _DB_, SubscrTuple), verify_counter(Counter), {?BASE_DB:set_subscription(DB, SubscrTuple), update_counter(Counter)}. get_subscription_({DB, Counter} = _DB_, Tag) -> ?TRACE2(get_data, _DB_, Tag), verify_counter(Counter), ?BASE_DB:get_subscription(DB, Tag). remove_subscription_({DB, Counter} = _DB_, Tag) -> ?TRACE2(get_data, _DB_, Tag), verify_counter(Counter), {?BASE_DB:remove_subscription(DB, Tag), update_counter(Counter)}. record_changes_({DB, Counter} = _DB_, NewInterval) -> ?TRACE2(record_changes, _DB_, NewInterval), verify_counter(Counter), {?BASE_DB:record_changes(DB, NewInterval), update_counter(Counter)}. stop_record_changes_({DB, Counter} = _DB_) -> ?TRACE1(stop_record_changes, _DB_), verify_counter(Counter), {?BASE_DB:stop_record_changes(DB), update_counter(Counter)}. stop_record_changes_({DB, Counter} = _DB_, Interval) -> ?TRACE2(stop_record_changes, _DB_, Interval), verify_counter(Counter), {?BASE_DB:stop_record_changes(DB, Interval), update_counter(Counter)}. get_changes_({DB, Counter} = _DB_) -> ?TRACE1(get_changes, _DB_), verify_counter(Counter), ?BASE_DB:get_changes(DB). get_changes_({DB, Counter} = _DB_, Interval) -> ?TRACE2(get_changes, _DB_, Interval), verify_counter(Counter), ?BASE_DB:get_changes(DB, Interval). read({DB, Counter} = _DB_, Key) -> ?TRACE2(read, _DB_, Key), verify_counter(Counter), ?BASE_DB:read(DB, Key). write({DB, Counter} = _DB_, Key, Value, Version) -> ?TRACE4(write, _DB_, Key, Value, Version), verify_counter(Counter), {?BASE_DB:write(DB, Key, Value, Version), update_counter(Counter)}. delete({DB, Counter} = _DB_, Key) -> ?TRACE2(delete, _DB_, Key), verify_counter(Counter), {NewDB, Status} = ?BASE_DB:delete(DB, Key), {{NewDB, update_counter(Counter)}, Status}. update_entries_({DB, Counter} = _DB_, NewEntries, Pred, UpdateFun) -> ?TRACE4(update_entries, _DB_, NewEntries, Pred, UpdateFun), verify_counter(Counter), {?BASE_DB:update_entries(DB, NewEntries, Pred, UpdateFun), update_counter(Counter)}. for which the FilterFun returns true from the DB . delete_entries_({DB, Counter} = _DB_, RangeOrFilterFun) -> ?TRACE2(get_entries, _DB_, RangeOrFilterFun), verify_counter(Counter), {?BASE_DB:delete_entries(DB, RangeOrFilterFun), update_counter(Counter)}. delete_chunk_({DB, Counter} = _DB_, Interval, ChunkSize) -> ?TRACE3(delete_chunk, _DB_, Interval, ChunkSize), verify_counter(Counter), {RestInterval, NewDB} = ?BASE_DB:delete_chunk(DB, Interval, ChunkSize), {RestInterval, {NewDB, update_counter(Counter)}}. check_db({DB, Counter} = _DB_) -> ?TRACE1(check_db, _DB_), verify_counter(Counter), ?BASE_DB:check_db(DB).
7f350bc363be31626bf5f29f4411c65c92913235754e114ab2acf766d6c0e77e
adacapo21/plutusPioneerProgram
FortyTwo.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} module Week02.FortyTwo where import Control.Monad hiding (fmap) import Data.Map as Map import Data.Text (Text) import Data.Void (Void) import Plutus.Contract import PlutusTx (Data (..)) import qualified PlutusTx import PlutusTx.Prelude hiding (Semigroup(..), unless) import Ledger hiding (singleton) import Ledger.Constraints as Constraints import qualified Ledger.Scripts as Scripts import Ledger.Ada as Ada import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage) import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions) import Playground.Types (KnownCurrency (..)) import Prelude (IO, Semigroup (..), String) import Text.Printf (printf) # OPTIONS_GHC -fno - warn - unused - imports # # INLINABLE mkValidator # mkValidator :: Data -> Data -> Data -> () mkValidator _ r _ | r == I 42 = () | otherwise = traceError "wrong redeemer" validator :: Validator validator = mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||]) valHash :: Ledger.ValidatorHash valHash = Scripts.validatorHash validator scrAddress :: Ledger.Address scrAddress = scriptAddress validator type GiftSchema = Endpoint "give" Integer .\/ Endpoint "grab" Integer give :: AsContractError e => Integer -> Contract w s e () give amount = do let tx = mustPayToOtherScript valHash (Datum $ Constr 0 []) $ Ada.lovelaceValueOf amount ledgerTx <- submitTx tx void $ awaitTxConfirmed $ txId ledgerTx logInfo @String $ printf "made a gift of %d lovelace" amount grab :: forall w s e. AsContractError e => Integer -> Contract w s e () grab n = do utxos <- utxoAt scrAddress let orefs = fst <$> Map.toList utxos lookups = Constraints.unspentOutputs utxos <> Constraints.otherScript validator tx :: TxConstraints Void Void tx = mconcat [mustSpendScriptOutput oref $ Redeemer $ I n | oref <- orefs] ledgerTx <- submitTxConstraintsWith @Void lookups tx void $ awaitTxConfirmed $ txId ledgerTx logInfo @String $ "collected gifts" endpoints :: Contract () GiftSchema Text () endpoints = (give' `select` grab') >> endpoints where give' = endpoint @"give" >>= give grab' = endpoint @"grab" >>= grab mkSchemaDefinitions ''GiftSchema mkKnownCurrencies []
null
https://raw.githubusercontent.com/adacapo21/plutusPioneerProgram/d76d46ea72267a19d7ea91ae9b39cafcf08ac962/week02/src/Week02/FortyTwo.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Week02.FortyTwo where import Control.Monad hiding (fmap) import Data.Map as Map import Data.Text (Text) import Data.Void (Void) import Plutus.Contract import PlutusTx (Data (..)) import qualified PlutusTx import PlutusTx.Prelude hiding (Semigroup(..), unless) import Ledger hiding (singleton) import Ledger.Constraints as Constraints import qualified Ledger.Scripts as Scripts import Ledger.Ada as Ada import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage) import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions) import Playground.Types (KnownCurrency (..)) import Prelude (IO, Semigroup (..), String) import Text.Printf (printf) # OPTIONS_GHC -fno - warn - unused - imports # # INLINABLE mkValidator # mkValidator :: Data -> Data -> Data -> () mkValidator _ r _ | r == I 42 = () | otherwise = traceError "wrong redeemer" validator :: Validator validator = mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||]) valHash :: Ledger.ValidatorHash valHash = Scripts.validatorHash validator scrAddress :: Ledger.Address scrAddress = scriptAddress validator type GiftSchema = Endpoint "give" Integer .\/ Endpoint "grab" Integer give :: AsContractError e => Integer -> Contract w s e () give amount = do let tx = mustPayToOtherScript valHash (Datum $ Constr 0 []) $ Ada.lovelaceValueOf amount ledgerTx <- submitTx tx void $ awaitTxConfirmed $ txId ledgerTx logInfo @String $ printf "made a gift of %d lovelace" amount grab :: forall w s e. AsContractError e => Integer -> Contract w s e () grab n = do utxos <- utxoAt scrAddress let orefs = fst <$> Map.toList utxos lookups = Constraints.unspentOutputs utxos <> Constraints.otherScript validator tx :: TxConstraints Void Void tx = mconcat [mustSpendScriptOutput oref $ Redeemer $ I n | oref <- orefs] ledgerTx <- submitTxConstraintsWith @Void lookups tx void $ awaitTxConfirmed $ txId ledgerTx logInfo @String $ "collected gifts" endpoints :: Contract () GiftSchema Text () endpoints = (give' `select` grab') >> endpoints where give' = endpoint @"give" >>= give grab' = endpoint @"grab" >>= grab mkSchemaDefinitions ''GiftSchema mkKnownCurrencies []
3cf9ba5927ca97cf4abf784f4a2a2a1a2845ee3c61709f1ce9d25774d167bedf
Zilliqa/scilla
DebugMessage.ml
This file is part of scilla . Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd. scilla is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . scilla 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 scilla . If not , see < / > . This file is part of scilla. Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd. scilla is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. scilla 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 scilla. If not, see </>. *) open Core open GlobalConfig (* Prints to log file *) let plog msg = match get_debug_level () with | Debug_Normal | Debug_Verbose -> let fname = get_log_file () in Out_channel.with_file fname ~append:true ~f:(fun h -> Out_channel.output_string h msg) | Debug_None -> () Verbose print to log file let pvlog msg = match get_debug_level () with | Debug_Verbose -> let fname = get_log_file () in Out_channel.with_file fname ~append:true ~f:(fun h -> Out_channel.output_string h (msg ())) | Debug_Normal | Debug_None -> () (* Prints to stdout and log file *) let pout msg = Out_channel.output_string Out_channel.stdout msg; plog ("stdout: " ^ msg ^ "\n") (* Prints to stderr and log file *) let perr msg = Out_channel.output_string Out_channel.stderr msg; plog ("stderr: " ^ msg ^ "\n") (* Prints to trace file, if set, else to stdout. *) let ptrace msg = let fname = GlobalConfig.get_trace_file () in if String.(fname <> "") then Out_channel.with_file fname ~append:true ~f:(fun h -> Out_channel.output_string h msg) else Out_channel.output_string Out_channel.stdout msg
null
https://raw.githubusercontent.com/Zilliqa/scilla/011323ac5da48ee16890b71424e057ffbc4216da/src/base/DebugMessage.ml
ocaml
Prints to log file Prints to stdout and log file Prints to stderr and log file Prints to trace file, if set, else to stdout.
This file is part of scilla . Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd. scilla is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . scilla 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 scilla . If not , see < / > . This file is part of scilla. Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd. scilla is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. scilla 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 scilla. If not, see </>. *) open Core open GlobalConfig let plog msg = match get_debug_level () with | Debug_Normal | Debug_Verbose -> let fname = get_log_file () in Out_channel.with_file fname ~append:true ~f:(fun h -> Out_channel.output_string h msg) | Debug_None -> () Verbose print to log file let pvlog msg = match get_debug_level () with | Debug_Verbose -> let fname = get_log_file () in Out_channel.with_file fname ~append:true ~f:(fun h -> Out_channel.output_string h (msg ())) | Debug_Normal | Debug_None -> () let pout msg = Out_channel.output_string Out_channel.stdout msg; plog ("stdout: " ^ msg ^ "\n") let perr msg = Out_channel.output_string Out_channel.stderr msg; plog ("stderr: " ^ msg ^ "\n") let ptrace msg = let fname = GlobalConfig.get_trace_file () in if String.(fname <> "") then Out_channel.with_file fname ~append:true ~f:(fun h -> Out_channel.output_string h msg) else Out_channel.output_string Out_channel.stdout msg
274e54e4af0e62570f273e9f3c97915e2f66c8ec4fcec1309182c6e3a29dff13
jordwalke/rehp
wiki_syntax.ml
Ocsimore * Copyright ( C ) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (C) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) * Pretty print wiki to DOM elements @author Pretty print wiki to DOM elements @author Vincent Balat *) open Js_of_ocaml module Html = Dom_html module W = Wikicreole let create n ? attrs children = let m = create n ? ( ) in List.iter ( Js.Node.append m ) children ; m let create n ?attrs children = let m = create n ?attrs () in List.iter (Js.Node.append m) children ; m *) let node x = (x : #Dom.node Js.t :> Dom.node Js.t) let ( <| ) e l = List.iter (fun c -> Dom.appendChild e c) l; node e let list_builder d tag c = d##createElement (Js.string tag) <| List.map (fun (c, l) -> d##createElement (Js.string "li") <| c @ match l with Some v -> [v] | None -> [] ) c let builder = let d = Html.document in { W.chars = (fun s -> node (d##createTextNode (Js.string s))) ; W.strong_elem = (fun s -> d##createElement (Js.string "strong") <| s) ; W.em_elem = (fun s -> d##createElement (Js.string "em") <| s) ; W.a_elem = (fun addr s -> let a = Html.createA d in a##.href := Js.string addr; a <| s ) ; W.youtube_elem = (fun addr _s -> let i = Html.createIframe d in i##.width := Js.string "480"; i##.height := Js.string "360"; let video_link = "/" ^ Js.to_string (Js.encodeURI (Js.string addr)) in i##.src := Js.string video_link; i##.frameBorder := Js.string "0"; node i ) ; W.br_elem = (fun () -> node (d##createElement (Js.string "br"))) ; W.img_elem = (fun addr alt -> let i = Html.createImg d in i##.src := Js.string addr; i##.alt := Js.string alt; node i ) ; W.tt_elem = (fun s -> d##createElement (Js.string "tt") <| s) ; W.p_elem = (fun s -> d##createElement (Js.string "p") <| s) ; W.pre_elem = (fun s -> let p = d##createElement (Js.string "pre") in Dom.appendChild p (d##createTextNode (Js.string (String.concat "" s))); node p ) ; W.h1_elem = (fun s -> d##createElement (Js.string "h1") <| s) ; W.h2_elem = (fun s -> d##createElement (Js.string "h2") <| s) ; W.h3_elem = (fun s -> d##createElement (Js.string "h3") <| s) ; W.h4_elem = (fun s -> d##createElement (Js.string "h4") <| s) ; W.h5_elem = (fun s -> d##createElement (Js.string "h5") <| s) ; W.h6_elem = (fun s -> d##createElement (Js.string "h6") <| s) ; W.ul_elem = (fun s -> list_builder d "ul" s) ; W.ol_elem = (fun s -> list_builder d "ol" s) ; W.hr_elem = (fun () -> node (d##createElement (Js.string "hr"))) ; W.table_elem = (fun rows -> let rows = List.map (fun entries -> d##createElement (Js.string "tr") <| List.map (fun (h, c) -> let kind = if h then "th" else "td" in d##createElement (Js.string kind) <| c ) entries ) rows in d##createElement (Js.string "table") <| [d##createElement (Js.string "tbody") <| rows] ) ; W.inline = (fun x -> x) } let xml_of_wiki s = Html.createDiv Html.document <| W.from_string builder s
null
https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/examples/wiki/wiki_syntax.ml
ocaml
Ocsimore * Copyright ( C ) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (C) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) * Pretty print wiki to DOM elements @author Pretty print wiki to DOM elements @author Vincent Balat *) open Js_of_ocaml module Html = Dom_html module W = Wikicreole let create n ? attrs children = let m = create n ? ( ) in List.iter ( Js.Node.append m ) children ; m let create n ?attrs children = let m = create n ?attrs () in List.iter (Js.Node.append m) children ; m *) let node x = (x : #Dom.node Js.t :> Dom.node Js.t) let ( <| ) e l = List.iter (fun c -> Dom.appendChild e c) l; node e let list_builder d tag c = d##createElement (Js.string tag) <| List.map (fun (c, l) -> d##createElement (Js.string "li") <| c @ match l with Some v -> [v] | None -> [] ) c let builder = let d = Html.document in { W.chars = (fun s -> node (d##createTextNode (Js.string s))) ; W.strong_elem = (fun s -> d##createElement (Js.string "strong") <| s) ; W.em_elem = (fun s -> d##createElement (Js.string "em") <| s) ; W.a_elem = (fun addr s -> let a = Html.createA d in a##.href := Js.string addr; a <| s ) ; W.youtube_elem = (fun addr _s -> let i = Html.createIframe d in i##.width := Js.string "480"; i##.height := Js.string "360"; let video_link = "/" ^ Js.to_string (Js.encodeURI (Js.string addr)) in i##.src := Js.string video_link; i##.frameBorder := Js.string "0"; node i ) ; W.br_elem = (fun () -> node (d##createElement (Js.string "br"))) ; W.img_elem = (fun addr alt -> let i = Html.createImg d in i##.src := Js.string addr; i##.alt := Js.string alt; node i ) ; W.tt_elem = (fun s -> d##createElement (Js.string "tt") <| s) ; W.p_elem = (fun s -> d##createElement (Js.string "p") <| s) ; W.pre_elem = (fun s -> let p = d##createElement (Js.string "pre") in Dom.appendChild p (d##createTextNode (Js.string (String.concat "" s))); node p ) ; W.h1_elem = (fun s -> d##createElement (Js.string "h1") <| s) ; W.h2_elem = (fun s -> d##createElement (Js.string "h2") <| s) ; W.h3_elem = (fun s -> d##createElement (Js.string "h3") <| s) ; W.h4_elem = (fun s -> d##createElement (Js.string "h4") <| s) ; W.h5_elem = (fun s -> d##createElement (Js.string "h5") <| s) ; W.h6_elem = (fun s -> d##createElement (Js.string "h6") <| s) ; W.ul_elem = (fun s -> list_builder d "ul" s) ; W.ol_elem = (fun s -> list_builder d "ol" s) ; W.hr_elem = (fun () -> node (d##createElement (Js.string "hr"))) ; W.table_elem = (fun rows -> let rows = List.map (fun entries -> d##createElement (Js.string "tr") <| List.map (fun (h, c) -> let kind = if h then "th" else "td" in d##createElement (Js.string kind) <| c ) entries ) rows in d##createElement (Js.string "table") <| [d##createElement (Js.string "tbody") <| rows] ) ; W.inline = (fun x -> x) } let xml_of_wiki s = Html.createDiv Html.document <| W.from_string builder s
51deb54fb84278acaee1ead5e65ee4fff24f7680194025211c86620b89885627
donaldsonjw/bigloo
iterate.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / comptime / Cfa / iterate.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : We d Feb 22 18:11:52 1995 * / * Last change : Fri Nov 18 07:40:33 2011 ( serrano ) * / * Copyright : 1995 - 2011 , see LICENSE file * / ;* ------------------------------------------------------------- */ ;* THE control flow analysis engine */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module cfa_iterate (include "Tools/trace.sch") (import tools_shape type_type type_cache ast_var ast_node ast_unit cfa_cfa cfa_info cfa_info2 cfa_loose cfa_approx) (export (cfa-iterate-to-fixpoint! globals) (cfa-intern-sfun!::approx ::intern-sfun/Cinfo ::obj) (generic cfa-export-var! ::value ::obj) (continue-cfa! reason) (cfa-iterate! globals) (cfa-current) *cfa-stamp*)) ;*---------------------------------------------------------------------*/ * cfa - iterate - to - fixpoint ! ... * / ;*---------------------------------------------------------------------*/ (define (cfa-iterate-to-fixpoint! globals) (trace cfa "================== iterate ===========================\n") ;; we reset the global stamp (set! *cfa-stamp* -1) ;; we collect all the exported variables (both functions and ;; variables). They are the root of the iteration process. (let ((glodefs '())) (for-each (lambda (g) (if (or (eq? (global-import g) 'export) (exported-closure? g)) (set! glodefs (cons g glodefs)))) globals) ;; we add the top level forms (set! glodefs (append (unit-initializers) glodefs)) ;; and we start iterations (continue-cfa! 'init) ;; and we do it (let loop () (if (continue-cfa?) (begin (cfa-iterate! glodefs) (loop)) glodefs)))) ;*---------------------------------------------------------------------*/ ;* exported-closure? ... */ ;*---------------------------------------------------------------------*/ (define (exported-closure? g) (and (eq? (global-removable g) 'never) (let ((val (global-value g))) (and (sfun? val) (global? (sfun-the-closure-global val)) (eq? (global-import (sfun-the-closure-global val)) 'export))))) ;*---------------------------------------------------------------------*/ * cfa - iterate ! ... * / ;*---------------------------------------------------------------------*/ (define (cfa-iterate! globals) (stop-cfa!) (set! *cfa-stamp* (+fx 1 *cfa-stamp*)) (trace cfa #\Newline "=======> Cfa iteration!: " *cfa-stamp* #\Newline) (for-each (lambda (g) (trace (cfa 2) "Exporting " (shape g) #\: #\Newline) (cfa-export-var! (global-value g) g) (trace (cfa 2) #\Newline)) globals) (trace cfa #\Newline)) ;*---------------------------------------------------------------------*/ * cfa - export - var ! ... * / ;*---------------------------------------------------------------------*/ (define-generic (cfa-export-var! value::value owner)) ;*---------------------------------------------------------------------*/ * cfa - export - var ! : : svar ... * / ;*---------------------------------------------------------------------*/ (define-method (cfa-export-var! value::svar/Cinfo owner) (with-access::svar/Cinfo value (stamp) (trace (cfa 3) "~~~ cfa-export/var!::svar/Cinfo[stamp: " stamp " *cfa-stamp*: " *cfa-stamp* "]" #\Newline) (if (=fx stamp *cfa-stamp*) (cfa-variable-value-approx value) (begin (set! stamp *cfa-stamp*) (loose! (cfa-variable-value-approx value) 'all))))) ;*---------------------------------------------------------------------*/ * cfa - export - var ! : : intern - sfun / Cinfo ... * / ;*---------------------------------------------------------------------*/ (define-method (cfa-export-var! value::intern-sfun/Cinfo owner) (with-access::intern-sfun/Cinfo value (stamp args approx) (trace (cfa 3) " ~~~ cfa-export-var!::intern-sfun/Cinfo[stamp: " stamp " *cfa-stamp*: " *cfa-stamp* "] " (shape owner) #\Newline) (if (=fx stamp *cfa-stamp*) (begin (set! stamp *cfa-stamp*) approx) (begin ;; for each iteration, we re-loose the approximation of the ;; formal parameters. Doing this, we don't have to take care ;; when we add an approximation of a previous set if this ;; set contains `top' or not. (for-each (lambda (local) (let ((val (local-value local))) (trace (cfa 3) " ~~~ formal " (shape local) " clo-env?: " (svar/Cinfo-clo-env? val) " val: " (shape (svar/Cinfo-approx val)) #\Newline) (unless (svar/Cinfo-clo-env? val) (approx-set-top! (svar/Cinfo-approx val))))) args) ;; after the formals, we loose the result. (loose! (cfa-intern-sfun! value owner) 'all))))) ;*---------------------------------------------------------------------*/ * cfa - intern - sfun ! : : intern - sfun / Cinfo ... * / ;*---------------------------------------------------------------------*/ (define (cfa-intern-sfun!::approx sfun::intern-sfun/Cinfo owner) (define (polymorphic approx) (with-access::intern-sfun/Cinfo sfun (polymorphic?) (when polymorphic? (with-access::approx approx (type) (set! type (get-bigloo-type type)))) approx)) (with-access::intern-sfun/Cinfo sfun (stamp body approx args) (if (=fx stamp *cfa-stamp*) (begin (trace (cfa 2) "<<< " (shape owner) " <- " (shape approx) #\Newline) (polymorphic approx)) (begin (trace (cfa 2) ">>> " (shape owner) #\Newline) (set! stamp *cfa-stamp*) (let ((cur *cfa-current*)) (set! *cfa-current* (format "~a[~a]" (variable-id owner) stamp)) (union-approx-filter! approx (cfa! body)) (trace (cfa 3) "<<< " (shape owner) " <= " (shape approx) #\Newline) (set! *cfa-current* cur)) (polymorphic approx))))) ;*---------------------------------------------------------------------*/ ;* The iteration process control */ ;*---------------------------------------------------------------------*/ (define *cfa-continue?* #unspecified) (define *cfa-stamp* -1) (define *cfa-current* #unspecified) ;*---------------------------------------------------------------------*/ * cfa - current ... * / ;*---------------------------------------------------------------------*/ (define (cfa-current) *cfa-current*) ;*---------------------------------------------------------------------*/ ;* continue-cfa! ... */ ;*---------------------------------------------------------------------*/ (define (continue-cfa! reason) (when (not *cfa-continue?*) (trace (cfa 2) (cfa-current) ": continue-cfa! (" reason ")\n")) (set! *cfa-continue?* #t)) ;*---------------------------------------------------------------------*/ ;* continue-cfa? ... */ ;*---------------------------------------------------------------------*/ (define (continue-cfa?) *cfa-continue?*) ;*---------------------------------------------------------------------*/ ;* stop-cfa! ... */ ;*---------------------------------------------------------------------*/ (define (stop-cfa!) (set! *cfa-continue?* #f))
null
https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/comptime/Cfa/iterate.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * THE control flow analysis engine */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ we reset the global stamp we collect all the exported variables (both functions and variables). They are the root of the iteration process. we add the top level forms and we start iterations and we do it *---------------------------------------------------------------------*/ * exported-closure? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ for each iteration, we re-loose the approximation of the formal parameters. Doing this, we don't have to take care when we add an approximation of a previous set if this set contains `top' or not. after the formals, we loose the result. *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * The iteration process control */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * continue-cfa! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * continue-cfa? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * stop-cfa! ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / comptime / Cfa / iterate.scm * / * Author : * / * Creation : We d Feb 22 18:11:52 1995 * / * Last change : Fri Nov 18 07:40:33 2011 ( serrano ) * / * Copyright : 1995 - 2011 , see LICENSE file * / (module cfa_iterate (include "Tools/trace.sch") (import tools_shape type_type type_cache ast_var ast_node ast_unit cfa_cfa cfa_info cfa_info2 cfa_loose cfa_approx) (export (cfa-iterate-to-fixpoint! globals) (cfa-intern-sfun!::approx ::intern-sfun/Cinfo ::obj) (generic cfa-export-var! ::value ::obj) (continue-cfa! reason) (cfa-iterate! globals) (cfa-current) *cfa-stamp*)) * cfa - iterate - to - fixpoint ! ... * / (define (cfa-iterate-to-fixpoint! globals) (trace cfa "================== iterate ===========================\n") (set! *cfa-stamp* -1) (let ((glodefs '())) (for-each (lambda (g) (if (or (eq? (global-import g) 'export) (exported-closure? g)) (set! glodefs (cons g glodefs)))) globals) (set! glodefs (append (unit-initializers) glodefs)) (continue-cfa! 'init) (let loop () (if (continue-cfa?) (begin (cfa-iterate! glodefs) (loop)) glodefs)))) (define (exported-closure? g) (and (eq? (global-removable g) 'never) (let ((val (global-value g))) (and (sfun? val) (global? (sfun-the-closure-global val)) (eq? (global-import (sfun-the-closure-global val)) 'export))))) * cfa - iterate ! ... * / (define (cfa-iterate! globals) (stop-cfa!) (set! *cfa-stamp* (+fx 1 *cfa-stamp*)) (trace cfa #\Newline "=======> Cfa iteration!: " *cfa-stamp* #\Newline) (for-each (lambda (g) (trace (cfa 2) "Exporting " (shape g) #\: #\Newline) (cfa-export-var! (global-value g) g) (trace (cfa 2) #\Newline)) globals) (trace cfa #\Newline)) * cfa - export - var ! ... * / (define-generic (cfa-export-var! value::value owner)) * cfa - export - var ! : : svar ... * / (define-method (cfa-export-var! value::svar/Cinfo owner) (with-access::svar/Cinfo value (stamp) (trace (cfa 3) "~~~ cfa-export/var!::svar/Cinfo[stamp: " stamp " *cfa-stamp*: " *cfa-stamp* "]" #\Newline) (if (=fx stamp *cfa-stamp*) (cfa-variable-value-approx value) (begin (set! stamp *cfa-stamp*) (loose! (cfa-variable-value-approx value) 'all))))) * cfa - export - var ! : : intern - sfun / Cinfo ... * / (define-method (cfa-export-var! value::intern-sfun/Cinfo owner) (with-access::intern-sfun/Cinfo value (stamp args approx) (trace (cfa 3) " ~~~ cfa-export-var!::intern-sfun/Cinfo[stamp: " stamp " *cfa-stamp*: " *cfa-stamp* "] " (shape owner) #\Newline) (if (=fx stamp *cfa-stamp*) (begin (set! stamp *cfa-stamp*) approx) (begin (for-each (lambda (local) (let ((val (local-value local))) (trace (cfa 3) " ~~~ formal " (shape local) " clo-env?: " (svar/Cinfo-clo-env? val) " val: " (shape (svar/Cinfo-approx val)) #\Newline) (unless (svar/Cinfo-clo-env? val) (approx-set-top! (svar/Cinfo-approx val))))) args) (loose! (cfa-intern-sfun! value owner) 'all))))) * cfa - intern - sfun ! : : intern - sfun / Cinfo ... * / (define (cfa-intern-sfun!::approx sfun::intern-sfun/Cinfo owner) (define (polymorphic approx) (with-access::intern-sfun/Cinfo sfun (polymorphic?) (when polymorphic? (with-access::approx approx (type) (set! type (get-bigloo-type type)))) approx)) (with-access::intern-sfun/Cinfo sfun (stamp body approx args) (if (=fx stamp *cfa-stamp*) (begin (trace (cfa 2) "<<< " (shape owner) " <- " (shape approx) #\Newline) (polymorphic approx)) (begin (trace (cfa 2) ">>> " (shape owner) #\Newline) (set! stamp *cfa-stamp*) (let ((cur *cfa-current*)) (set! *cfa-current* (format "~a[~a]" (variable-id owner) stamp)) (union-approx-filter! approx (cfa! body)) (trace (cfa 3) "<<< " (shape owner) " <= " (shape approx) #\Newline) (set! *cfa-current* cur)) (polymorphic approx))))) (define *cfa-continue?* #unspecified) (define *cfa-stamp* -1) (define *cfa-current* #unspecified) * cfa - current ... * / (define (cfa-current) *cfa-current*) (define (continue-cfa! reason) (when (not *cfa-continue?*) (trace (cfa 2) (cfa-current) ": continue-cfa! (" reason ")\n")) (set! *cfa-continue?* #t)) (define (continue-cfa?) *cfa-continue?*) (define (stop-cfa!) (set! *cfa-continue?* #f))
85a421a778c98545074a7c041e07d3bd4cbe0e64ac6eee7a38c726a093585ae2
leksah/leksah
WebKitGtk.hs
module Main (main) where import Data.Default (def) import Language.Javascript.JSaddle.WebKitGTK as JSaddleWK (run) import IDE.Web.Main (newIDE, startJSaddle) main :: IO () main = newIDE $ startJSaddle 3367 (\html url -> JSaddleWK.run)
null
https://raw.githubusercontent.com/leksah/leksah/f4bb70b1b51682053e5532ab98cacdf248a7e632/main/WebKitGtk.hs
haskell
module Main (main) where import Data.Default (def) import Language.Javascript.JSaddle.WebKitGTK as JSaddleWK (run) import IDE.Web.Main (newIDE, startJSaddle) main :: IO () main = newIDE $ startJSaddle 3367 (\html url -> JSaddleWK.run)
543f8081e496c69eadd6a4dd1207f2161ddf08df37037947f44655b151c4a3db
blindglobe/clocc
h2lisp.lisp
# ! /usr / bin / clisp -M ~sds / bin / clisp.mem -C ;;; Convert * .c to CLISP 's ffi ;;; Copyright ( C ) 1999 - 2001 , 2007 - 2008 by This is Free Software , covered by the GNU GPL ( v2 + ) ;;; See ;;; $ I d : h2lisp.lisp , v 2.10 2008/06/16 16:02:33 sds Exp $ ;;; $Source: /cvsroot/clocc/clocc/src/cllib/h2lisp.lisp,v $ (eval-when (:compile-toplevel :load-toplevel :execute) (require :cllib-base (translate-logical-pathname "clocc:src;cllib;base")) ;; `text-stream' ( require : cllib - html ( translate - logical - pathname " : html " ) ) ) (in-package :cllib) (export '(h2lisp)) ;;; ;;; C parsing ;;; (defstruct c-dim "C dimension." dim) (defstruct c-cmt "C comment." data) (defun read-standalone-char (stream char) (declare (ignore stream)) char) (defun read-c-object (stream char) (declare (stream stream) (character char)) (ecase char (#\{ (read-delimited-list #\} stream t)) (#\[ (make-c-dim :dim (car (read-delimited-list #\] stream t)))) (#\# (let ((com (read stream t nil t))) (ecase com (|include| (let ((ec (ecase (peek-char t stream t nil t) (#\" #\") (#\< #\>)))) (concatenate 'string "#include " (loop :for cc :of-type character = (read-char stream t nil t) :collect cc :until (char= cc ec)))))))) ;; (loop :for line :of-type simple-string = ;; (concatenate 'string "#" (read-line stream)) ;; :then (read-line stream) : until ( char= # \\ ( schar line ( 1- ( length line ) ) ) ) ;; :collect line) (#\/ (case (peek-char nil stream nil nil t) (#\* (read-char stream) (make-c-cmt :data (concatenate 'string "/*" (loop :for c1 = (read-char stream t nil t) :and c2 = #\Null :then c1 :until (and (char= c2 #\*) (char= c1 #\/)) :collect c1) "/"))) (#\/ (make-c-cmt :data (concatenate 'string "/" (read-line stream)))) (t #\/))))) (defun make-c-readtable (&optional (rt (copy-readtable))) "Make the readtable for parsing C." (set-macro-character #\/ #'read-c-object nil rt) (set-macro-character #\| #'read-standalone-char nil rt) (set-macro-character #\# #'read-c-object nil rt) # \a rt ) (set-macro-character #\; #'read-standalone-char nil rt) (set-syntax-from-char #\# #\a rt) (set-macro-character #\# #'read-c-object nil rt) (set-syntax-from-char #\: #\a rt) (set-macro-character #\: #'read-standalone-char nil rt) (set-syntax-from-char #\, #\a rt) (set-macro-character #\, #'read-standalone-char nil rt) (set-macro-character #\* #'read-standalone-char nil rt) (set-macro-character #\{ #'read-c-object nil rt) (set-macro-character #\} (get-macro-character #\)) nil rt) (set-macro-character #\[ #'read-c-object nil rt) (set-macro-character #\] (get-macro-character #\)) nil rt) (setf (readtable-case rt) :preserve) rt) (defparameter *c-readtable* (make-c-readtable) "The readtable for C parsing.") ;(defun uncomment-split (lst obj) ; "Read object from TS, remove comments, split on OBJ." ( declare ( list lst ) ) ( nsplit - list ( delete - if # ' c - cmt - p lst ) : obj obj ) ) (defun read-statement (ts) (declare (type text-stream ts)) (loop :for zz = (read-next ts :skip #'c-cmt-p) :until (eql zz #\;) :collect zz)) (defparameter *c-types* '(int uint char) "Known C types.") (defparameter *c-un-types* nil "UnKnown C types.") (defun c-see-type (sym) (assert (and sym (not (string-equal (string sym) "void"))) () "An attempt to define VOID or NIL: ~s" sym) (unless (member sym *c-types* :test #'eq) (pushnew sym *c-un-types* :test #'eq))) (defun c-def-type (sym) ( assert ( not ( member * c - types * : test # ' eq ) ) ( ) " redefining type ~s " ) (push sym *c-types*) (setq *c-un-types* (delete sym *c-un-types* :test #'eq))) (defun c-convert-decl (lst) "Convert declaration (type obj [dims]||(args)) to CLISP." (labels ((voidp (sy) (string-equal (string sy) "void")) (objp (ll) (or (symbolp ll) (and (consp ll) (or (eql (car ll) #\*) (null (cdr ll)))))) (cc (ll) (format t " --> ~s~%" ll) (etypecase (car ll) (c-dim `(c-array ,(cc (cdr ll)) ,(c-dim-dim (car ll)))) (cons (mapcar #'cc ll)) (null nil) (c-cmt (cc (cdr ll))) (symbol (cond ((voidp (car ll)) (if (eql #\* (cadr ll)) 'c-pointer nil)) (t (c-see-type (car ll)) (let* ((ptr (eql #\* (cadr ll)))) (list (c-convert-decl (if ptr (cddr ll) (cdr ll))) (if ptr `(c-ptr ,(car ll)) (car ll)))))))))) (let* ((fu (find-if #'objp lst :from-end t)) (ta (member fu lst)) (ld (ldiff lst ta)) (tail (map-in (lambda (el) (nsplit-list el :obj #\,)) (cdr ta)))) (typecase fu (symbol (unless (voidp fu) (list fu (cc (nconc tail ld))))) (cons `(,(car (last fu)) (c-function (:arguments ,(cc tail)) (:return-type ,(cc ld))))))))) (defun c-number (obj) (typecase obj (symbol (let* ((st (symbol-name obj)) (len (length st))) (cond ((string-beg-with "0x" st len) (unintern obj) (parse-integer st :radix 16 :start 2)) ((let ((ch (char st (1- len)))) (and (char-equal #\l ch) (prog2 (setf (char st (1- len)) #\0) (every #'digit-char-p st) (setf (char st (1- len)) ch)))) (unintern obj) (parse-integer st :end (1- len))) (obj)))) (t obj))) (defun c-eval (lst) (cond ((null (cdr lst)) (c-number (car lst))) ((eq (second lst) '<<) (ash (c-number (first lst)) (c-number (third lst)))))) ;;; ;;; H --> LISP ;;; (defgeneric h2lisp (in out) (:documentation "Convert C header to lisp. Return the number of forms processed.") (:method ((in string) (out t)) (h2lisp (pathname in) out)) (:method ((in cons) (out t)) (reduce #'+ in :key (lambda (in0) (h2lisp in0 out)))) (:method ((in t) (out string)) (h2lisp in (pathname out))) (:method ((in t) (out pathname)) (with-open-file (fout out :direction :output :if-exists :supersede :if-does-not-exist :create) (h2lisp in fout))) (:method ((in pathname) (out t)) (with-open-file (fin in :direction :input) (h2lisp fin out)))) (defmethod h2lisp ((in stream) (out stream)) (format out "~%;;; reading from ~a~2%" in) (unless (eq out *standard-output*) (format t "~%;;; reading from ~a~2%" in)) (loop :with *readtable* = *c-readtable* :and numf = 0 ;; :initially (setq *c-un-types* nil) :for line :of-type simple-string = (string-trim +whitespace+ (or (read-line in nil nil) (return (progn (format out "~%;;; ~:d form~:p in ~a~2%" numf in) (unless (eq out *standard-output*) (format t "~%;;; ~:d form~:p in ~a~2%" numf in)) (when *c-un-types* (format t "~% *** Undefined types:~ ~{~<~%~20t ~1,79:; ~a~>~^,~}~%" *c-un-types*)) numf)))) :for len = (length line) :with depth = 0 ; #if nesting :with ts :of-type text-stream = (make-text-stream :sock in) :do ; process statement (cond ((zerop len) (terpri out)) ((< len 3) (format out ";;; ~a~%" line)) ((string-beg-with "/*" line len) ;; comment, assume start/end on own line (format out ";;; ~a~%" line) (loop :until (search "*/" line :test #'char=) :do (setq line (read-line in)) (format out ";;; ~a~%" line))) ((string-beg-with-cs "#if" line len) (incf depth) (format out ";;; ~a~%" line)) ((string-beg-with-cs "#endif" line len) (decf depth) (format out ";;; ~a~%" line)) ((string-beg-with-cs "#define" line len) (incf numf) only 1 - line simple defines ! (format out ";;; ~a~%" line) (multiple-value-bind (var pos) (read-from-string line nil +eof+ :start 7) (let ((val (c-number (read-from-string line nil +eof+ :start pos)))) (typecase val (symbol (format out "(define-symbol-macro ~s ~s)~%" var val)) ((or number string) (format out "(defconstant ~s ~s)~%" var val)))))) ((string-beg-with-cs "#include" line len) (incf numf) (format out "(c-lines \"~a~~%\")~%" line)) ((string-beg-with-cs "typedef struct" line len) (incf numf) ( format out " ; ; ; ~a~% " line ) (multiple-value-bind (t0 t1) (values-list (string-tokens line :start 15 :max 2)) (c-def-type t1) (c-see-type t0) (format out "(def-c-type ~s ~s)~%" t0 t1))) ((string-beg-with-cs "typedef union" line len) (incf numf) ( format out " ; ; ; ~a~% " line ) (multiple-value-bind (t0 t1) (values-list (string-tokens line :start 14 :max 2)) (c-def-type t1) (c-see-type t0) (format out "(def-c-type ~s ~s)~%" t0 t1))) ((string-beg-with-cs "typedef enum" line len) (incf numf) (setf (ts-buff ts) line (ts-posn ts) 12) (let* ((rr (read-next ts :skip #'c-cmt-p)) (en (nsplit-list (delete-if #'c-cmt-p rr) :obj #\,)) (tt (read-next ts :skip #'c-cmt-p))) (c-def-type tt) (dolist (el en) (when (stringp (car el)) (format out "(c-lines \"~a~%\")~%" (car el)) (setf (car el) (cadr el) (cdr el) (cddr el))) (when (cdr el) (assert (eq '= (cadr el))) (setf (cadr el) (c-eval (cddr el)) (cddr el) nil))) (map-in (lambda (el) (if (cdr el) el (car el))) en) ;; (format out "~s~%" (cons 'def-c-enum (cons tt en))) (format out "(def-c-enum ~s~{~% ~s~})~%" tt en))) ((string-beg-with-cs "typedef" line len) (incf numf) ( format out " ; ; ; ~a~% " line ) (setf (ts-buff ts) line (ts-posn ts) 7) (let ((ll (read-statement ts))) (format out "(def-c-type ~s)~%" ll) (format out "~s~%" (cons 'def-c-type (c-convert-decl ll))))) ((string-beg-with-cs "struct" line len) (incf numf) (setf (ts-buff ts) line (ts-posn ts) 6) (let ((tt (read-next ts :skip #'c-cmt-p)) (ll (map-in #'c-convert-decl (nsplit-list (read-next ts :skip #'c-cmt-p) :obj #\;)))) (c-def-type tt) (format out "(def-c-struct ~s~{~% ~s~})~%" tt ll))) ((string-beg-with-cs "extern \"C\" {" line len) (format out ";;; ~a~%" line)) ((incf numf) ; function declaration (setf (ts-buff ts) line (ts-posn ts) 0) (let* ((ll (read-statement ts)) (args (mapcar #'c-convert-decl (nsplit-list (last ll) :obj #\,))) (fun (c-convert-decl (nbutlast ll)))) (format out "(def-c-call-out ~s ~s~>~})~% (: return - type~ { " (car fun) args (cdr fun))))))) ;(h2lisp *standard-input* *standard-output*) ;(LET ((*readtable* (copy-readtable))) ; (eval (read-from-string "(read-next ts :skip #'c-cmt-p)"))) (provide :cllib-h2lisp) file h2lisp.lisp ends here
null
https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/cllib/h2lisp.lisp
lisp
See $Source: /cvsroot/clocc/clocc/src/cllib/h2lisp.lisp,v $ `text-stream' C parsing (loop :for line :of-type simple-string = (concatenate 'string "#" (read-line stream)) :then (read-line stream) :collect line) #'read-standalone-char nil rt) (defun uncomment-split (lst obj) "Read object from TS, remove comments, split on OBJ." ) H --> LISP :initially (setq *c-un-types* nil) ~a~>~^,~}~%" *c-un-types*)) #if nesting process statement comment, assume start/end on own line (format out "~s~%" (cons 'def-c-enum (cons tt en))) )))) function declaration (h2lisp *standard-input* *standard-output*) (LET ((*readtable* (copy-readtable))) (eval (read-from-string "(read-next ts :skip #'c-cmt-p)")))
# ! /usr / bin / clisp -M ~sds / bin / clisp.mem -C Convert * .c to CLISP 's ffi Copyright ( C ) 1999 - 2001 , 2007 - 2008 by This is Free Software , covered by the GNU GPL ( v2 + ) $ I d : h2lisp.lisp , v 2.10 2008/06/16 16:02:33 sds Exp $ (eval-when (:compile-toplevel :load-toplevel :execute) (require :cllib-base (translate-logical-pathname "clocc:src;cllib;base")) ( require : cllib - html ( translate - logical - pathname " : html " ) ) ) (in-package :cllib) (export '(h2lisp)) (defstruct c-dim "C dimension." dim) (defstruct c-cmt "C comment." data) (defun read-standalone-char (stream char) (declare (ignore stream)) char) (defun read-c-object (stream char) (declare (stream stream) (character char)) (ecase char (#\{ (read-delimited-list #\} stream t)) (#\[ (make-c-dim :dim (car (read-delimited-list #\] stream t)))) (#\# (let ((com (read stream t nil t))) (ecase com (|include| (let ((ec (ecase (peek-char t stream t nil t) (#\" #\") (#\< #\>)))) (concatenate 'string "#include " (loop :for cc :of-type character = (read-char stream t nil t) :collect cc :until (char= cc ec)))))))) : until ( char= # \\ ( schar line ( 1- ( length line ) ) ) ) (#\/ (case (peek-char nil stream nil nil t) (#\* (read-char stream) (make-c-cmt :data (concatenate 'string "/*" (loop :for c1 = (read-char stream t nil t) :and c2 = #\Null :then c1 :until (and (char= c2 #\*) (char= c1 #\/)) :collect c1) "/"))) (#\/ (make-c-cmt :data (concatenate 'string "/" (read-line stream)))) (t #\/))))) (defun make-c-readtable (&optional (rt (copy-readtable))) "Make the readtable for parsing C." (set-macro-character #\/ #'read-c-object nil rt) (set-macro-character #\| #'read-standalone-char nil rt) (set-macro-character #\# #'read-c-object nil rt) # \a rt ) (set-syntax-from-char #\# #\a rt) (set-macro-character #\# #'read-c-object nil rt) (set-syntax-from-char #\: #\a rt) (set-macro-character #\: #'read-standalone-char nil rt) (set-syntax-from-char #\, #\a rt) (set-macro-character #\, #'read-standalone-char nil rt) (set-macro-character #\* #'read-standalone-char nil rt) (set-macro-character #\{ #'read-c-object nil rt) (set-macro-character #\} (get-macro-character #\)) nil rt) (set-macro-character #\[ #'read-c-object nil rt) (set-macro-character #\] (get-macro-character #\)) nil rt) (setf (readtable-case rt) :preserve) rt) (defparameter *c-readtable* (make-c-readtable) "The readtable for C parsing.") ( declare ( list lst ) ) ( nsplit - list ( delete - if # ' c - cmt - p lst ) : obj obj ) ) (defun read-statement (ts) (declare (type text-stream ts)) :collect zz)) (defparameter *c-types* '(int uint char) "Known C types.") (defparameter *c-un-types* nil "UnKnown C types.") (defun c-see-type (sym) (assert (and sym (not (string-equal (string sym) "void"))) () "An attempt to define VOID or NIL: ~s" sym) (unless (member sym *c-types* :test #'eq) (pushnew sym *c-un-types* :test #'eq))) (defun c-def-type (sym) ( assert ( not ( member * c - types * : test # ' eq ) ) ( ) " redefining type ~s " ) (push sym *c-types*) (setq *c-un-types* (delete sym *c-un-types* :test #'eq))) (defun c-convert-decl (lst) "Convert declaration (type obj [dims]||(args)) to CLISP." (labels ((voidp (sy) (string-equal (string sy) "void")) (objp (ll) (or (symbolp ll) (and (consp ll) (or (eql (car ll) #\*) (null (cdr ll)))))) (cc (ll) (format t " --> ~s~%" ll) (etypecase (car ll) (c-dim `(c-array ,(cc (cdr ll)) ,(c-dim-dim (car ll)))) (cons (mapcar #'cc ll)) (null nil) (c-cmt (cc (cdr ll))) (symbol (cond ((voidp (car ll)) (if (eql #\* (cadr ll)) 'c-pointer nil)) (t (c-see-type (car ll)) (let* ((ptr (eql #\* (cadr ll)))) (list (c-convert-decl (if ptr (cddr ll) (cdr ll))) (if ptr `(c-ptr ,(car ll)) (car ll)))))))))) (let* ((fu (find-if #'objp lst :from-end t)) (ta (member fu lst)) (ld (ldiff lst ta)) (tail (map-in (lambda (el) (nsplit-list el :obj #\,)) (cdr ta)))) (typecase fu (symbol (unless (voidp fu) (list fu (cc (nconc tail ld))))) (cons `(,(car (last fu)) (c-function (:arguments ,(cc tail)) (:return-type ,(cc ld))))))))) (defun c-number (obj) (typecase obj (symbol (let* ((st (symbol-name obj)) (len (length st))) (cond ((string-beg-with "0x" st len) (unintern obj) (parse-integer st :radix 16 :start 2)) ((let ((ch (char st (1- len)))) (and (char-equal #\l ch) (prog2 (setf (char st (1- len)) #\0) (every #'digit-char-p st) (setf (char st (1- len)) ch)))) (unintern obj) (parse-integer st :end (1- len))) (obj)))) (t obj))) (defun c-eval (lst) (cond ((null (cdr lst)) (c-number (car lst))) ((eq (second lst) '<<) (ash (c-number (first lst)) (c-number (third lst)))))) (defgeneric h2lisp (in out) (:documentation "Convert C header to lisp. Return the number of forms processed.") (:method ((in string) (out t)) (h2lisp (pathname in) out)) (:method ((in cons) (out t)) (reduce #'+ in :key (lambda (in0) (h2lisp in0 out)))) (:method ((in t) (out string)) (h2lisp in (pathname out))) (:method ((in t) (out pathname)) (with-open-file (fout out :direction :output :if-exists :supersede :if-does-not-exist :create) (h2lisp in fout))) (:method ((in pathname) (out t)) (with-open-file (fin in :direction :input) (h2lisp fin out)))) (defmethod h2lisp ((in stream) (out stream)) (format out "~%;;; reading from ~a~2%" in) (unless (eq out *standard-output*) (format t "~%;;; reading from ~a~2%" in)) (loop :with *readtable* = *c-readtable* :and numf = 0 :for line :of-type simple-string = (string-trim +whitespace+ (or (read-line in nil nil) (return (progn (format out "~%;;; ~:d form~:p in ~a~2%" numf in) (unless (eq out *standard-output*) (format t "~%;;; ~:d form~:p in ~a~2%" numf in)) (when *c-un-types* (format t "~% *** Undefined types:~ numf)))) :for len = (length line) :with ts :of-type text-stream = (make-text-stream :sock in) (cond ((zerop len) (terpri out)) ((< len 3) (format out ";;; ~a~%" line)) ((string-beg-with "/*" line len) (format out ";;; ~a~%" line) (loop :until (search "*/" line :test #'char=) :do (setq line (read-line in)) (format out ";;; ~a~%" line))) ((string-beg-with-cs "#if" line len) (incf depth) (format out ";;; ~a~%" line)) ((string-beg-with-cs "#endif" line len) (decf depth) (format out ";;; ~a~%" line)) ((string-beg-with-cs "#define" line len) (incf numf) only 1 - line simple defines ! (format out ";;; ~a~%" line) (multiple-value-bind (var pos) (read-from-string line nil +eof+ :start 7) (let ((val (c-number (read-from-string line nil +eof+ :start pos)))) (typecase val (symbol (format out "(define-symbol-macro ~s ~s)~%" var val)) ((or number string) (format out "(defconstant ~s ~s)~%" var val)))))) ((string-beg-with-cs "#include" line len) (incf numf) (format out "(c-lines \"~a~~%\")~%" line)) ((string-beg-with-cs "typedef struct" line len) (incf numf) ( format out " ; ; ; ~a~% " line ) (multiple-value-bind (t0 t1) (values-list (string-tokens line :start 15 :max 2)) (c-def-type t1) (c-see-type t0) (format out "(def-c-type ~s ~s)~%" t0 t1))) ((string-beg-with-cs "typedef union" line len) (incf numf) ( format out " ; ; ; ~a~% " line ) (multiple-value-bind (t0 t1) (values-list (string-tokens line :start 14 :max 2)) (c-def-type t1) (c-see-type t0) (format out "(def-c-type ~s ~s)~%" t0 t1))) ((string-beg-with-cs "typedef enum" line len) (incf numf) (setf (ts-buff ts) line (ts-posn ts) 12) (let* ((rr (read-next ts :skip #'c-cmt-p)) (en (nsplit-list (delete-if #'c-cmt-p rr) :obj #\,)) (tt (read-next ts :skip #'c-cmt-p))) (c-def-type tt) (dolist (el en) (when (stringp (car el)) (format out "(c-lines \"~a~%\")~%" (car el)) (setf (car el) (cadr el) (cdr el) (cddr el))) (when (cdr el) (assert (eq '= (cadr el))) (setf (cadr el) (c-eval (cddr el)) (cddr el) nil))) (map-in (lambda (el) (if (cdr el) el (car el))) en) (format out "(def-c-enum ~s~{~% ~s~})~%" tt en))) ((string-beg-with-cs "typedef" line len) (incf numf) ( format out " ; ; ; ~a~% " line ) (setf (ts-buff ts) line (ts-posn ts) 7) (let ((ll (read-statement ts))) (format out "(def-c-type ~s)~%" ll) (format out "~s~%" (cons 'def-c-type (c-convert-decl ll))))) ((string-beg-with-cs "struct" line len) (incf numf) (setf (ts-buff ts) line (ts-posn ts) 6) (let ((tt (read-next ts :skip #'c-cmt-p)) (ll (map-in #'c-convert-decl (nsplit-list (read-next ts :skip #'c-cmt-p) (c-def-type tt) (format out "(def-c-struct ~s~{~% ~s~})~%" tt ll))) ((string-beg-with-cs "extern \"C\" {" line len) (format out ";;; ~a~%" line)) (setf (ts-buff ts) line (ts-posn ts) 0) (let* ((ll (read-statement ts)) (args (mapcar #'c-convert-decl (nsplit-list (last ll) :obj #\,))) (fun (c-convert-decl (nbutlast ll)))) (format out "(def-c-call-out ~s ~s~>~})~% (: return - type~ { " (car fun) args (cdr fun))))))) (provide :cllib-h2lisp) file h2lisp.lisp ends here
7264f7872a5a19c421cd68d91cc42a9d8ecda632688f2427bfeeb779fa1fc647
NorfairKing/validity
EqSpec.hs
# LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # module Test.Validity.EqSpec where import Data.GenValidity import GHC.Generics (Generic) import Test.Hspec import Test.Validity.Eq import Test.Validity.Utils spec :: Spec spec = do eqSpec @Rational eqSpec @Int eqSpec DOES NOT HOLD because of NaN eqSpecOnArbitrary @Int eqSpecOnGen ((* 2) <$> genValid @Int) "even" (const []) failsBecause "(/=) and (==) don't have opposite semantics" $ eqSpec @EqFuncMismatch newtype EqFuncMismatch = EqFuncMismatch () deriving (Show, Generic) instance Validity EqFuncMismatch instance Eq EqFuncMismatch where (==) _ _ = True (/=) _ _ = True instance GenValid EqFuncMismatch where genValid = EqFuncMismatch <$> genValid shrinkValid _ = []
null
https://raw.githubusercontent.com/NorfairKing/validity/35bc8d45b27e6c21429e4b681b16e46ccd541b3b/genvalidity-hspec/test/Test/Validity/EqSpec.hs
haskell
# LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # module Test.Validity.EqSpec where import Data.GenValidity import GHC.Generics (Generic) import Test.Hspec import Test.Validity.Eq import Test.Validity.Utils spec :: Spec spec = do eqSpec @Rational eqSpec @Int eqSpec DOES NOT HOLD because of NaN eqSpecOnArbitrary @Int eqSpecOnGen ((* 2) <$> genValid @Int) "even" (const []) failsBecause "(/=) and (==) don't have opposite semantics" $ eqSpec @EqFuncMismatch newtype EqFuncMismatch = EqFuncMismatch () deriving (Show, Generic) instance Validity EqFuncMismatch instance Eq EqFuncMismatch where (==) _ _ = True (/=) _ _ = True instance GenValid EqFuncMismatch where genValid = EqFuncMismatch <$> genValid shrinkValid _ = []
10e04b7e5ec128b5b361555e02fdfd59af6a717557b2b52e3ebe18f7130f9064
coccinelle/coccinelle
unitary_ast0.ml
* This file is part of Coccinelle , licensed under the terms of the GPL v2 . * See copyright.txt in the Coccinelle source code for more information . * The Coccinelle source code can be obtained at * This file is part of Coccinelle, licensed under the terms of the GPL v2. * See copyright.txt in the Coccinelle source code for more information. * The Coccinelle source code can be obtained at *) (* find unitary metavariables *) module Ast0 = Ast0_cocci module Ast = Ast_cocci module V0 = Visitor_ast0 module VT0 = Visitor_ast0_types let set_minus s minus = List.filter (function n -> not (List.mem n minus)) s let rec nub = function [] -> [] | (x::xs) when (List.mem x xs) -> nub xs | (x::xs) -> x::(nub xs) (* ----------------------------------------------------------------------- *) (* Find the variables that occur free and occur free in a unitary way *) (* take everything *) let minus_checker name = let id = Ast0.unwrap_mcode name in [id] (* take only what is in the plus code *) let plus_checker (nm,_,_,mc,_,_) = match mc with Ast0.PLUS _ -> [nm] | _ -> [] let get_free checker t = let bind x y = x @ y in let option_default = [] in let donothing r k e = k e in (* considers a single list *) let collect_unitary_nonunitary free_usage = let free_usage = List.sort compare free_usage in let rec loop1 todrop = function [] -> [] | (x::xs) as all -> if x = todrop then loop1 todrop xs else all in let rec loop2 = function [] -> ([],[]) | [x] -> ([x],[]) | x::y::xs -> if x = y then let (unitary,non_unitary) = loop2(loop1 x xs) in (unitary,x::non_unitary) else let (unitary,non_unitary) = loop2 (y::xs) in (x::unitary,non_unitary) in loop2 free_usage in (* considers a list of lists *) let detect_unitary_frees l = let (unitary,nonunitary) = List.split (List.map collect_unitary_nonunitary l) in let unitary = nub (List.concat unitary) in let nonunitary = nub (List.concat nonunitary) in let unitary = List.filter (function x -> not (List.mem x nonunitary)) unitary in unitary@nonunitary@nonunitary in let whencode afn bfn expression = function Ast0.WhenNot(_,_,a) -> afn a | Ast0.WhenAlways(_,_,b) -> bfn b | Ast0.WhenModifier(_,_) -> option_default | Ast0.WhenNotTrue(_,_,a) -> expression a | Ast0.WhenNotFalse(_,_,a) -> expression a in let ident r k i = match Ast0.unwrap i with Ast0.MetaId(name,_,_,_) | Ast0.MetaFunc(name,_,_) | Ast0.MetaLocalFunc(name,_,_) -> bind (k i) (checker name) | Ast0.DisjId(starter,id_list,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_ident id_list) | _ -> k i in let type_collect res ty = bind res (Ast0.meta_names_of_typeC ty) in let mcode mc = List.fold_left (fun accu e -> match e with Ast0.MetaPosTag(Ast0.MetaPos(name,constraints,_)) -> Ast.cstr_fold { Ast.empty_cstr_transformer with Ast.cstr_script = Some (fun (_,(name,lang,params,_pos,body)) accu -> (* It seems that position variables are not relevant for unitaryness, so drop them *) bind (List.map fst (List.filter (function (_,Ast.MetaPosDecl _) -> false | _ -> true) params)) accu) } constraints accu | Ast0.MetaPosTag(Ast0.MetaCom(name,constraints)) -> bind (checker name) (Ast.cstr_fold { Ast.empty_cstr_transformer with Ast.cstr_script = Some (fun (_,(name,lang,params,_pos,body)) accu -> (* It seems that position variables are not relevant for unitaryness, so drop them *) bind (List.map fst (List.filter (function (_,Ast.MetaPosDecl _) -> false | _ -> true) params)) accu) } constraints accu) | _ -> accu) option_default (Ast0.get_pos mc) in let constraints_collect r res c = let cstr_expr = Some (fun e res -> bind res (r.VT0.combiner_rec_expression e)) in let cstr_meta_name = Some (fun mn res -> bind [mn] res) in let transformer = { Ast.empty_cstr_transformer with Ast.cstr_expr; Ast.cstr_meta_name } in Ast.cstr_fold transformer c res in let expression r k e = match Ast0.unwrap e with Ast0.MetaErr(name,constraints,_) -> let constraints = constraints_collect r option_default constraints in bind (k e) (bind (checker name) constraints) | Ast0.MetaExpr(name,constraints,type_list,_,_,_bitfield) -> let types = match type_list with Some type_list -> List.fold_left type_collect option_default type_list | None -> option_default in let constraints = constraints_collect r types constraints in bind (k e) (bind (checker name) constraints) | Ast0.MetaExprList(name,_,_,_) -> bind (k e) (checker name) | Ast0.DisjExpr(starter,expr_list,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_expression expr_list) | _ -> k e in let typeC r k t = match Ast0.unwrap t with Ast0.MetaType(name,_,_) -> bind (k t) (checker name) | Ast0.DisjType(starter,types,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_typeC types) | _ -> k t in let parameter r k p = match Ast0.unwrap p with Ast0.MetaParam(name,_,_) | Ast0.MetaParamList(name,_,_,_) -> bind (k p) (checker name) | _ -> option_default in let declaration r k d = match Ast0.unwrap d with Ast0.MetaDecl(name,_,_) -> bind (k d) (checker name) | Ast0.DisjDecl(starter,decls,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_declaration decls) | _ -> k d in let field r k d = match Ast0.unwrap d with Ast0.MetaField(name,_,_) | Ast0.MetaFieldList(name,_,_,_) -> bind (k d) (checker name) | Ast0.DisjField(starter,decls,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_field decls) | _ -> k d in let case_line r k c = match Ast0.unwrap c with Ast0.DisjCase(starter,case_lines,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_case_line case_lines) | _ -> k c in let attr_arg r k a = match Ast0.unwrap a with Ast0.MetaAttr(name,_,_) -> bind (k a) (checker name) | _ -> option_default in let statement r k s = match Ast0.unwrap s with Ast0.MetaStmt(name,_,_) | Ast0.MetaStmtList(name,_,_,_) -> bind (k s) (checker name) | Ast0.Disj(starter,stmt_list,mids,ender) -> detect_unitary_frees (List.map r.VT0.combiner_rec_statement_dots stmt_list) | Ast0.Nest(starter,stmt_dots,ender,whn,multi) -> bind (r.VT0.combiner_rec_statement_dots stmt_dots) (detect_unitary_frees (List.map (whencode r.VT0.combiner_rec_statement_dots r.VT0.combiner_rec_statement r.VT0.combiner_rec_expression) whn)) | Ast0.Dots(d,whn) -> detect_unitary_frees (List.map (whencode r.VT0.combiner_rec_statement_dots r.VT0.combiner_rec_statement r.VT0.combiner_rec_expression) whn) | _ -> k s in let res = V0.flat_combiner bind option_default mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode donothing donothing donothing donothing donothing donothing donothing donothing donothing ident expression donothing donothing typeC donothing parameter declaration field donothing statement donothing case_line donothing donothing attr_arg donothing in collect_unitary_nonunitary (List.concat (List.map res.VT0.combiner_rec_top_level t)) (* ----------------------------------------------------------------------- *) (* update the variables that are unitary *) let update_unitary unitary = let is_unitary name = match (List.mem (Ast0.unwrap_mcode name) unitary, !Flag.sgrep_mode2, Ast0.get_mcode_mcodekind name) with (true,true,_) | (true,_,Ast0.CONTEXT(_)) -> Ast0.PureContext | (true,_,_) -> Ast0.Pure | (false,true,_) | (false,_,Ast0.CONTEXT(_)) -> Ast0.Context | (false,_,_) -> Ast0.Impure in let mcode mc = List.iter (function Ast0.MetaPosTag(Ast0.MetaCom(name,constraints)) -> if not (List.mem (Ast0.unwrap_mcode name) unitary) then failwith (Printf.sprintf "line %d: comment variable %s must be used only once" (Ast0.get_mcode_line name) (snd (Ast0.unwrap_mcode name))) | _ -> ()) (Ast0.get_pos mc); mc in let ident r k i = let i = k i in match Ast0.unwrap i with Ast0.MetaId(name,constraints,seed,_) -> Ast0.rewrap i (Ast0.MetaId(name,constraints,seed,is_unitary name)) | Ast0.MetaFunc(name,constraints,_) -> Ast0.rewrap i (Ast0.MetaFunc(name,constraints,is_unitary name)) | Ast0.MetaLocalFunc(name,constraints,_) -> Ast0.rewrap i (Ast0.MetaLocalFunc(name,constraints,is_unitary name)) | _ -> i in let expression r k e = let e = k e in match Ast0.unwrap e with Ast0.MetaErr(name,constraints,_) -> Ast0.rewrap e (Ast0.MetaErr(name,constraints,is_unitary name)) | Ast0.MetaExpr(name,constraints,ty,form,_,bitfield) -> Ast0.rewrap e (Ast0.MetaExpr(name,constraints,ty,form,is_unitary name,bitfield)) | Ast0.MetaExprList(name,lenname,cstr,_) -> Ast0.rewrap e (Ast0.MetaExprList(name,lenname,cstr,is_unitary name)) | _ -> e in let typeC r k t = let t = k t in match Ast0.unwrap t with Ast0.MetaType(name,cstr,_) -> Ast0.rewrap t (Ast0.MetaType(name,cstr,is_unitary name)) | _ -> t in let parameter r k p = let p = k p in match Ast0.unwrap p with Ast0.MetaParam(name,cstr,_) -> Ast0.rewrap p (Ast0.MetaParam(name,cstr,is_unitary name)) | Ast0.MetaParamList(name,lenname,cstr,_) -> Ast0.rewrap p (Ast0.MetaParamList(name,lenname,cstr,is_unitary name)) | _ -> p in let declaration r k d = let d = k d in match Ast0.unwrap d with Ast0.MetaDecl(name,cstr,_) -> Ast0.rewrap d (Ast0.MetaDecl(name,cstr,is_unitary name)) | _ -> d in let statement r k s = let s = k s in match Ast0.unwrap s with Ast0.MetaStmt(name,cstr,_) -> Ast0.rewrap s (Ast0.MetaStmt(name,cstr,is_unitary name)) | Ast0.MetaStmtList(name,lenname,cstr,_) -> Ast0.rewrap s (Ast0.MetaStmtList(name,lenname,cstr,is_unitary name)) | _ -> s in let res = V0.rebuilder {V0.rebuilder_functions with VT0.rebuilder_meta_mcode = mcode; VT0.rebuilder_string_mcode = mcode; VT0.rebuilder_const_mcode = mcode; VT0.rebuilder_simpleAssign_mcode = mcode; VT0.rebuilder_opAssign_mcode = mcode; VT0.rebuilder_fix_mcode = mcode; VT0.rebuilder_unary_mcode = mcode; VT0.rebuilder_arithOp_mcode = mcode; VT0.rebuilder_logicalOp_mcode = mcode; VT0.rebuilder_cv_mcode = mcode; VT0.rebuilder_sign_mcode = mcode; VT0.rebuilder_struct_mcode = mcode; VT0.rebuilder_storage_mcode = mcode; VT0.rebuilder_inc_mcode = mcode; VT0.rebuilder_identfn = ident; VT0.rebuilder_exprfn = expression; VT0.rebuilder_tyfn = typeC; VT0.rebuilder_paramfn = parameter; VT0.rebuilder_stmtfn = statement; VT0.rebuilder_declfn = declaration} in List.map res.VT0.rebuilder_rec_top_level (* ----------------------------------------------------------------------- *) let rec split3 = function [] -> ([],[],[]) | (a,b,c)::xs -> let (l1,l2,l3) = split3 xs in (a::l1,b::l2,c::l3) let rec combine3 = function ([],[],[]) -> [] | (a::l1,b::l2,c::l3) -> (a,b,c) :: combine3 (l1,l2,l3) | _ -> failwith "not possible" (* ----------------------------------------------------------------------- *) (* process all rules *) let do_unitary rules = let rec loop = function [] -> ([],[]) | (r::rules) -> match r with Ast0.ScriptRule (_,_,_,_,_,_,_) | Ast0.InitialScriptRule (_,_,_,_,_,_) | Ast0.FinalScriptRule (_,_,_,_,_,_) -> let (x,rules) = loop rules in (x, r::rules) | Ast0.CocciRule((minus,metavars,chosen_isos),((plus,_) as plusz),inh,rt) -> let mm1 = List.map Ast.get_meta_name metavars in let (used_after, rest) = loop rules in let (m_unitary, m_nonunitary) = get_free minus_checker minus in let (p_unitary, p_nonunitary) = get_free plus_checker plus in let p_free = if !Flag.sgrep_mode2 then [] else p_unitary @ p_nonunitary in let (in_p, m_unitary) = List.partition (function x -> List.mem x p_free) m_unitary in let m_nonunitary = in_p @ m_nonunitary in let (m_unitary, not_local) = List.partition (function x -> List.mem x mm1) m_unitary in let m_unitary = List.filter (function x -> not (List.mem x used_after)) m_unitary in let rebuilt = update_unitary m_unitary minus in (set_minus (m_nonunitary @ used_after) mm1, (Ast0.CocciRule ((rebuilt, metavars, chosen_isos),plusz,inh,rt))::rest) in let (_,rules) = loop rules in rules let do_unitary minus plus = let ( minus , metavars , chosen_isos ) = split3 minus in let ( plus , _ ) = List.split plus in let rec loop = function ( [ ] , [ ] , [ ] ) - > ( [ ] , [ ] ) | ( mm1::metavars , m1::minus , p1::plus ) - > let = List.map Ast.get_meta_name in let ( used_after , rest ) = loop ( metavars , minus , plus ) in let ( m_unitary , m_nonunitary ) = get_free minus_checker m1 in let ( p_unitary , ) = get_free plus_checker p1 in let p_free = if ! Flag.sgrep_mode2 then [ ] else p_unitary @ in let ( in_p , m_unitary ) = List.partition ( function x - > List.mem x p_free ) m_unitary in let m_nonunitary = in_p@m_nonunitary in let ( m_unitary , not_local ) = List.partition ( function x - > List.mem x ) m_unitary in let m_unitary = ( function x - > not(List.mem x used_after ) ) m_unitary in let rebuilt = update_unitary m_unitary m1 in ( set_minus ( m_nonunitary @ used_after ) , rebuilt::rest ) | _ - > failwith " not possible " in let ( _ , rules ) = loop ( metavars , minus , plus ) in combine3 ( rules , metavars , chosen_isos ) let do_unitary minus plus = let (minus,metavars,chosen_isos) = split3 minus in let (plus,_) = List.split plus in let rec loop = function ([],[],[]) -> ([],[]) | (mm1::metavars,m1::minus,p1::plus) -> let mm1 = List.map Ast.get_meta_name mm1 in let (used_after,rest) = loop (metavars,minus,plus) in let (m_unitary,m_nonunitary) = get_free minus_checker m1 in let (p_unitary,p_nonunitary) = get_free plus_checker p1 in let p_free = if !Flag.sgrep_mode2 then [] else p_unitary @ p_nonunitary in let (in_p,m_unitary) = List.partition (function x -> List.mem x p_free) m_unitary in let m_nonunitary = in_p@m_nonunitary in let (m_unitary,not_local) = List.partition (function x -> List.mem x mm1) m_unitary in let m_unitary = List.filter (function x -> not(List.mem x used_after)) m_unitary in let rebuilt = update_unitary m_unitary m1 in (set_minus (m_nonunitary @ used_after) mm1, rebuilt::rest) | _ -> failwith "not possible" in let (_,rules) = loop (metavars,minus,plus) in combine3 (rules,metavars,chosen_isos) *)
null
https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/parsing_cocci/unitary_ast0.ml
ocaml
find unitary metavariables ----------------------------------------------------------------------- Find the variables that occur free and occur free in a unitary way take everything take only what is in the plus code considers a single list considers a list of lists It seems that position variables are not relevant for unitaryness, so drop them It seems that position variables are not relevant for unitaryness, so drop them ----------------------------------------------------------------------- update the variables that are unitary ----------------------------------------------------------------------- ----------------------------------------------------------------------- process all rules
* This file is part of Coccinelle , licensed under the terms of the GPL v2 . * See copyright.txt in the Coccinelle source code for more information . * The Coccinelle source code can be obtained at * This file is part of Coccinelle, licensed under the terms of the GPL v2. * See copyright.txt in the Coccinelle source code for more information. * The Coccinelle source code can be obtained at *) module Ast0 = Ast0_cocci module Ast = Ast_cocci module V0 = Visitor_ast0 module VT0 = Visitor_ast0_types let set_minus s minus = List.filter (function n -> not (List.mem n minus)) s let rec nub = function [] -> [] | (x::xs) when (List.mem x xs) -> nub xs | (x::xs) -> x::(nub xs) let minus_checker name = let id = Ast0.unwrap_mcode name in [id] let plus_checker (nm,_,_,mc,_,_) = match mc with Ast0.PLUS _ -> [nm] | _ -> [] let get_free checker t = let bind x y = x @ y in let option_default = [] in let donothing r k e = k e in let collect_unitary_nonunitary free_usage = let free_usage = List.sort compare free_usage in let rec loop1 todrop = function [] -> [] | (x::xs) as all -> if x = todrop then loop1 todrop xs else all in let rec loop2 = function [] -> ([],[]) | [x] -> ([x],[]) | x::y::xs -> if x = y then let (unitary,non_unitary) = loop2(loop1 x xs) in (unitary,x::non_unitary) else let (unitary,non_unitary) = loop2 (y::xs) in (x::unitary,non_unitary) in loop2 free_usage in let detect_unitary_frees l = let (unitary,nonunitary) = List.split (List.map collect_unitary_nonunitary l) in let unitary = nub (List.concat unitary) in let nonunitary = nub (List.concat nonunitary) in let unitary = List.filter (function x -> not (List.mem x nonunitary)) unitary in unitary@nonunitary@nonunitary in let whencode afn bfn expression = function Ast0.WhenNot(_,_,a) -> afn a | Ast0.WhenAlways(_,_,b) -> bfn b | Ast0.WhenModifier(_,_) -> option_default | Ast0.WhenNotTrue(_,_,a) -> expression a | Ast0.WhenNotFalse(_,_,a) -> expression a in let ident r k i = match Ast0.unwrap i with Ast0.MetaId(name,_,_,_) | Ast0.MetaFunc(name,_,_) | Ast0.MetaLocalFunc(name,_,_) -> bind (k i) (checker name) | Ast0.DisjId(starter,id_list,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_ident id_list) | _ -> k i in let type_collect res ty = bind res (Ast0.meta_names_of_typeC ty) in let mcode mc = List.fold_left (fun accu e -> match e with Ast0.MetaPosTag(Ast0.MetaPos(name,constraints,_)) -> Ast.cstr_fold { Ast.empty_cstr_transformer with Ast.cstr_script = Some (fun (_,(name,lang,params,_pos,body)) accu -> bind (List.map fst (List.filter (function (_,Ast.MetaPosDecl _) -> false | _ -> true) params)) accu) } constraints accu | Ast0.MetaPosTag(Ast0.MetaCom(name,constraints)) -> bind (checker name) (Ast.cstr_fold { Ast.empty_cstr_transformer with Ast.cstr_script = Some (fun (_,(name,lang,params,_pos,body)) accu -> bind (List.map fst (List.filter (function (_,Ast.MetaPosDecl _) -> false | _ -> true) params)) accu) } constraints accu) | _ -> accu) option_default (Ast0.get_pos mc) in let constraints_collect r res c = let cstr_expr = Some (fun e res -> bind res (r.VT0.combiner_rec_expression e)) in let cstr_meta_name = Some (fun mn res -> bind [mn] res) in let transformer = { Ast.empty_cstr_transformer with Ast.cstr_expr; Ast.cstr_meta_name } in Ast.cstr_fold transformer c res in let expression r k e = match Ast0.unwrap e with Ast0.MetaErr(name,constraints,_) -> let constraints = constraints_collect r option_default constraints in bind (k e) (bind (checker name) constraints) | Ast0.MetaExpr(name,constraints,type_list,_,_,_bitfield) -> let types = match type_list with Some type_list -> List.fold_left type_collect option_default type_list | None -> option_default in let constraints = constraints_collect r types constraints in bind (k e) (bind (checker name) constraints) | Ast0.MetaExprList(name,_,_,_) -> bind (k e) (checker name) | Ast0.DisjExpr(starter,expr_list,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_expression expr_list) | _ -> k e in let typeC r k t = match Ast0.unwrap t with Ast0.MetaType(name,_,_) -> bind (k t) (checker name) | Ast0.DisjType(starter,types,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_typeC types) | _ -> k t in let parameter r k p = match Ast0.unwrap p with Ast0.MetaParam(name,_,_) | Ast0.MetaParamList(name,_,_,_) -> bind (k p) (checker name) | _ -> option_default in let declaration r k d = match Ast0.unwrap d with Ast0.MetaDecl(name,_,_) -> bind (k d) (checker name) | Ast0.DisjDecl(starter,decls,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_declaration decls) | _ -> k d in let field r k d = match Ast0.unwrap d with Ast0.MetaField(name,_,_) | Ast0.MetaFieldList(name,_,_,_) -> bind (k d) (checker name) | Ast0.DisjField(starter,decls,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_field decls) | _ -> k d in let case_line r k c = match Ast0.unwrap c with Ast0.DisjCase(starter,case_lines,mids,ender) -> detect_unitary_frees(List.map r.VT0.combiner_rec_case_line case_lines) | _ -> k c in let attr_arg r k a = match Ast0.unwrap a with Ast0.MetaAttr(name,_,_) -> bind (k a) (checker name) | _ -> option_default in let statement r k s = match Ast0.unwrap s with Ast0.MetaStmt(name,_,_) | Ast0.MetaStmtList(name,_,_,_) -> bind (k s) (checker name) | Ast0.Disj(starter,stmt_list,mids,ender) -> detect_unitary_frees (List.map r.VT0.combiner_rec_statement_dots stmt_list) | Ast0.Nest(starter,stmt_dots,ender,whn,multi) -> bind (r.VT0.combiner_rec_statement_dots stmt_dots) (detect_unitary_frees (List.map (whencode r.VT0.combiner_rec_statement_dots r.VT0.combiner_rec_statement r.VT0.combiner_rec_expression) whn)) | Ast0.Dots(d,whn) -> detect_unitary_frees (List.map (whencode r.VT0.combiner_rec_statement_dots r.VT0.combiner_rec_statement r.VT0.combiner_rec_expression) whn) | _ -> k s in let res = V0.flat_combiner bind option_default mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode donothing donothing donothing donothing donothing donothing donothing donothing donothing ident expression donothing donothing typeC donothing parameter declaration field donothing statement donothing case_line donothing donothing attr_arg donothing in collect_unitary_nonunitary (List.concat (List.map res.VT0.combiner_rec_top_level t)) let update_unitary unitary = let is_unitary name = match (List.mem (Ast0.unwrap_mcode name) unitary, !Flag.sgrep_mode2, Ast0.get_mcode_mcodekind name) with (true,true,_) | (true,_,Ast0.CONTEXT(_)) -> Ast0.PureContext | (true,_,_) -> Ast0.Pure | (false,true,_) | (false,_,Ast0.CONTEXT(_)) -> Ast0.Context | (false,_,_) -> Ast0.Impure in let mcode mc = List.iter (function Ast0.MetaPosTag(Ast0.MetaCom(name,constraints)) -> if not (List.mem (Ast0.unwrap_mcode name) unitary) then failwith (Printf.sprintf "line %d: comment variable %s must be used only once" (Ast0.get_mcode_line name) (snd (Ast0.unwrap_mcode name))) | _ -> ()) (Ast0.get_pos mc); mc in let ident r k i = let i = k i in match Ast0.unwrap i with Ast0.MetaId(name,constraints,seed,_) -> Ast0.rewrap i (Ast0.MetaId(name,constraints,seed,is_unitary name)) | Ast0.MetaFunc(name,constraints,_) -> Ast0.rewrap i (Ast0.MetaFunc(name,constraints,is_unitary name)) | Ast0.MetaLocalFunc(name,constraints,_) -> Ast0.rewrap i (Ast0.MetaLocalFunc(name,constraints,is_unitary name)) | _ -> i in let expression r k e = let e = k e in match Ast0.unwrap e with Ast0.MetaErr(name,constraints,_) -> Ast0.rewrap e (Ast0.MetaErr(name,constraints,is_unitary name)) | Ast0.MetaExpr(name,constraints,ty,form,_,bitfield) -> Ast0.rewrap e (Ast0.MetaExpr(name,constraints,ty,form,is_unitary name,bitfield)) | Ast0.MetaExprList(name,lenname,cstr,_) -> Ast0.rewrap e (Ast0.MetaExprList(name,lenname,cstr,is_unitary name)) | _ -> e in let typeC r k t = let t = k t in match Ast0.unwrap t with Ast0.MetaType(name,cstr,_) -> Ast0.rewrap t (Ast0.MetaType(name,cstr,is_unitary name)) | _ -> t in let parameter r k p = let p = k p in match Ast0.unwrap p with Ast0.MetaParam(name,cstr,_) -> Ast0.rewrap p (Ast0.MetaParam(name,cstr,is_unitary name)) | Ast0.MetaParamList(name,lenname,cstr,_) -> Ast0.rewrap p (Ast0.MetaParamList(name,lenname,cstr,is_unitary name)) | _ -> p in let declaration r k d = let d = k d in match Ast0.unwrap d with Ast0.MetaDecl(name,cstr,_) -> Ast0.rewrap d (Ast0.MetaDecl(name,cstr,is_unitary name)) | _ -> d in let statement r k s = let s = k s in match Ast0.unwrap s with Ast0.MetaStmt(name,cstr,_) -> Ast0.rewrap s (Ast0.MetaStmt(name,cstr,is_unitary name)) | Ast0.MetaStmtList(name,lenname,cstr,_) -> Ast0.rewrap s (Ast0.MetaStmtList(name,lenname,cstr,is_unitary name)) | _ -> s in let res = V0.rebuilder {V0.rebuilder_functions with VT0.rebuilder_meta_mcode = mcode; VT0.rebuilder_string_mcode = mcode; VT0.rebuilder_const_mcode = mcode; VT0.rebuilder_simpleAssign_mcode = mcode; VT0.rebuilder_opAssign_mcode = mcode; VT0.rebuilder_fix_mcode = mcode; VT0.rebuilder_unary_mcode = mcode; VT0.rebuilder_arithOp_mcode = mcode; VT0.rebuilder_logicalOp_mcode = mcode; VT0.rebuilder_cv_mcode = mcode; VT0.rebuilder_sign_mcode = mcode; VT0.rebuilder_struct_mcode = mcode; VT0.rebuilder_storage_mcode = mcode; VT0.rebuilder_inc_mcode = mcode; VT0.rebuilder_identfn = ident; VT0.rebuilder_exprfn = expression; VT0.rebuilder_tyfn = typeC; VT0.rebuilder_paramfn = parameter; VT0.rebuilder_stmtfn = statement; VT0.rebuilder_declfn = declaration} in List.map res.VT0.rebuilder_rec_top_level let rec split3 = function [] -> ([],[],[]) | (a,b,c)::xs -> let (l1,l2,l3) = split3 xs in (a::l1,b::l2,c::l3) let rec combine3 = function ([],[],[]) -> [] | (a::l1,b::l2,c::l3) -> (a,b,c) :: combine3 (l1,l2,l3) | _ -> failwith "not possible" let do_unitary rules = let rec loop = function [] -> ([],[]) | (r::rules) -> match r with Ast0.ScriptRule (_,_,_,_,_,_,_) | Ast0.InitialScriptRule (_,_,_,_,_,_) | Ast0.FinalScriptRule (_,_,_,_,_,_) -> let (x,rules) = loop rules in (x, r::rules) | Ast0.CocciRule((minus,metavars,chosen_isos),((plus,_) as plusz),inh,rt) -> let mm1 = List.map Ast.get_meta_name metavars in let (used_after, rest) = loop rules in let (m_unitary, m_nonunitary) = get_free minus_checker minus in let (p_unitary, p_nonunitary) = get_free plus_checker plus in let p_free = if !Flag.sgrep_mode2 then [] else p_unitary @ p_nonunitary in let (in_p, m_unitary) = List.partition (function x -> List.mem x p_free) m_unitary in let m_nonunitary = in_p @ m_nonunitary in let (m_unitary, not_local) = List.partition (function x -> List.mem x mm1) m_unitary in let m_unitary = List.filter (function x -> not (List.mem x used_after)) m_unitary in let rebuilt = update_unitary m_unitary minus in (set_minus (m_nonunitary @ used_after) mm1, (Ast0.CocciRule ((rebuilt, metavars, chosen_isos),plusz,inh,rt))::rest) in let (_,rules) = loop rules in rules let do_unitary minus plus = let ( minus , metavars , chosen_isos ) = split3 minus in let ( plus , _ ) = List.split plus in let rec loop = function ( [ ] , [ ] , [ ] ) - > ( [ ] , [ ] ) | ( mm1::metavars , m1::minus , p1::plus ) - > let = List.map Ast.get_meta_name in let ( used_after , rest ) = loop ( metavars , minus , plus ) in let ( m_unitary , m_nonunitary ) = get_free minus_checker m1 in let ( p_unitary , ) = get_free plus_checker p1 in let p_free = if ! Flag.sgrep_mode2 then [ ] else p_unitary @ in let ( in_p , m_unitary ) = List.partition ( function x - > List.mem x p_free ) m_unitary in let m_nonunitary = in_p@m_nonunitary in let ( m_unitary , not_local ) = List.partition ( function x - > List.mem x ) m_unitary in let m_unitary = ( function x - > not(List.mem x used_after ) ) m_unitary in let rebuilt = update_unitary m_unitary m1 in ( set_minus ( m_nonunitary @ used_after ) , rebuilt::rest ) | _ - > failwith " not possible " in let ( _ , rules ) = loop ( metavars , minus , plus ) in combine3 ( rules , metavars , chosen_isos ) let do_unitary minus plus = let (minus,metavars,chosen_isos) = split3 minus in let (plus,_) = List.split plus in let rec loop = function ([],[],[]) -> ([],[]) | (mm1::metavars,m1::minus,p1::plus) -> let mm1 = List.map Ast.get_meta_name mm1 in let (used_after,rest) = loop (metavars,minus,plus) in let (m_unitary,m_nonunitary) = get_free minus_checker m1 in let (p_unitary,p_nonunitary) = get_free plus_checker p1 in let p_free = if !Flag.sgrep_mode2 then [] else p_unitary @ p_nonunitary in let (in_p,m_unitary) = List.partition (function x -> List.mem x p_free) m_unitary in let m_nonunitary = in_p@m_nonunitary in let (m_unitary,not_local) = List.partition (function x -> List.mem x mm1) m_unitary in let m_unitary = List.filter (function x -> not(List.mem x used_after)) m_unitary in let rebuilt = update_unitary m_unitary m1 in (set_minus (m_nonunitary @ used_after) mm1, rebuilt::rest) | _ -> failwith "not possible" in let (_,rules) = loop (metavars,minus,plus) in combine3 (rules,metavars,chosen_isos) *)
7ff00cd7094ece4989c73cbad2467c3de135fd7c94d1f9f993204516a9507f1e
ndmitchell/supero
queens.hs
-- !!! count the number of solutions to the "n queens" problem. ( grabbed from LML dist ) module Main(main) where #if MAIN main = print $ root 12 addInt'2 = (+) :: Int -> Int -> Int subInt'2 = (-) :: Int -> Int -> Int neqInt'2 = (/=) :: Int -> Int -> Bool eqInt'2 = (==) :: Int -> Int -> Bool gtInt'2 = (>) :: Int -> Int -> Bool safer'3 x d q = x /= q && x /= q+d && x /= q-d #endif root :: Int -> Int root nq = length (gen nq nq) safe :: Int -> Int -> [Int] -> Bool safe x d q = case q of [] -> True q:l -> safer'3 x q d {- x /= q && x /= q+d && x /= q-d -} && safe x (d+1) l gen :: Int -> Int -> [[Int]] gen nq n = case n == 0 of True -> [[]] False -> [ ( q : b ) | b < - gen nq ( n-1 ) , q < - [ 1 .. nq ] , safe q 1 b ] concatMap (\b -> concatMap (\q -> if safe q 1 b then [q:b] else []) (enumFromTo 1 nq)) (gen nq (n-1)) #if SUPERO (+) = addInt'2 (-) = subInt'2 (/=) = neqInt'2 (>) = gtInt'2 (==) = eqInt'2 a && b = case a of True -> b False -> False enumFromTo i j = if i > j then [] else i : enumFromTo (i+1) j length x = case x of [] -> 0 x:xs -> 1 + length xs concatMap f x = case x of [] -> [] x:xs -> f x ++ concatMap f xs (++) xs ys = case xs of [] -> ys x:xs -> x : (xs ++ ys) #endif
null
https://raw.githubusercontent.com/ndmitchell/supero/a8b16ea90862e2c021bb139d7a7e9a83700b43b2/supero3/samples/nofib/queens.hs
haskell
!!! count the number of solutions to the "n queens" problem. x /= q && x /= q+d && x /= q-d
( grabbed from LML dist ) module Main(main) where #if MAIN main = print $ root 12 addInt'2 = (+) :: Int -> Int -> Int subInt'2 = (-) :: Int -> Int -> Int neqInt'2 = (/=) :: Int -> Int -> Bool eqInt'2 = (==) :: Int -> Int -> Bool gtInt'2 = (>) :: Int -> Int -> Bool safer'3 x d q = x /= q && x /= q+d && x /= q-d #endif root :: Int -> Int root nq = length (gen nq nq) safe :: Int -> Int -> [Int] -> Bool safe x d q = case q of [] -> True gen :: Int -> Int -> [[Int]] gen nq n = case n == 0 of True -> [[]] False -> [ ( q : b ) | b < - gen nq ( n-1 ) , q < - [ 1 .. nq ] , safe q 1 b ] concatMap (\b -> concatMap (\q -> if safe q 1 b then [q:b] else []) (enumFromTo 1 nq)) (gen nq (n-1)) #if SUPERO (+) = addInt'2 (-) = subInt'2 (/=) = neqInt'2 (>) = gtInt'2 (==) = eqInt'2 a && b = case a of True -> b False -> False enumFromTo i j = if i > j then [] else i : enumFromTo (i+1) j length x = case x of [] -> 0 x:xs -> 1 + length xs concatMap f x = case x of [] -> [] x:xs -> f x ++ concatMap f xs (++) xs ys = case xs of [] -> ys x:xs -> x : (xs ++ ys) #endif
eacffe4cfe6a2ffd7b6cbe6b218ca50742b320882a36ca652b6289b27261b7ab
tailrecursion/cljson
cljson_test.clj
(ns tailrecursion.cljson-test (:require [clojure.tools.reader.edn :as e] [clojure.test :refer :all] [cheshire.core :refer [generate-string parse-string]] [tailrecursion.cljson :refer [encode decode clj->cljson cljson->clj]] [clojure.data.generators :as g]) (:refer-clojure :exclude [list])) (def scalars [(constantly nil) g/long g/boolean g/string g/symbol g/keyword g/uuid g/date]) (defn scalar [] (@#'g/call-through (g/rand-nth scalars))) (def collections [[g/vec [scalars]] [g/set [scalars]] [g/hash-map [scalars scalars]] [g/list [scalars]]]) (defn collection "Returns a collection of scalar elements based on *rnd*." [] (let [[coll args] (g/rand-nth collections)] (apply coll (map g/rand-nth args)))) (defn deep-collection ([breadth depth] (let [s (atom 0) c (atom 0) v (deep-collection breadth depth 0 s c)] (with-meta v {:collections @c :scalars @s}))) ([breadth depth nparents nscalars ncollections] (let [pcoll (/ (- depth nparents) depth) pscal (- 1 pcoll) ncoll (if (pos? pcoll) (g/geometric (/ 1 (* pcoll breadth))) 0) nscal (if (pos? pscal) (g/geometric (/ 1 (* pscal breadth))) 0) colls (for [_ (range ncoll)] (deep-collection breadth depth (inc nparents) nscalars ncollections)) scals (for [_ (range nscal)] (scalar)) items (g/shuffle (concat colls scals)) base (g/rand-nth [{} [] #{} ()])] (swap! nscalars + nscal) (swap! ncollections + ncoll) (into base (if (map? base) (map (partial apply vector) (partition 2 items)) items))))) (def ^:dynamic *magic* 1000) (deftest scalar-roundtrip (dotimes [_ *magic*] (let [x (scalar)] (is (= x (-> x clj->cljson cljson->clj)))))) (deftest collection-roundtrip (dotimes [_ *magic*] (let [x (collection)] (is (= x (-> x clj->cljson cljson->clj)))))) (defrecord Person [name]) (deftest tag-interpretation (let [bob (Person. "Bob")] (binding [*data-readers* {`Person map->Person}] (is (= bob (-> bob clj->cljson cljson->clj)))))) (deftest meta-roundtrip (let [m {:abc 123} s (with-meta {:x 1} m)] (binding [*print-meta* true] (is (= (meta (cljson->clj (clj->cljson s))) m))))) (deftest nested-perf (let [x (deep-collection 10 4)] (is (= x (-> x clj->cljson cljson->clj))))) ;;; benchmark (def breadth 10) (def depth 5) (def bench-colls (deep-collection breadth depth)) (let [{c :collections s :scalars} (meta bench-colls)] (printf "Deep collection %d x %d: %d collections and %d scalars.\n" breadth depth c s)) (deftest native-perf (let [x (atom nil)] (println "clojure.core/pr-str") (reset! x (time (doall (pr-str bench-colls)))) (println "clojure.tools.reader.edn/read-string") (time (doall (e/read-string @x))))) (deftest cljson-perf (let [x (atom nil)] (println "clj->cljson") (reset! x (time (doall (clj->cljson bench-colls)))) (println "cljson->clj") (time (cljson->clj @x)) (let [x (atom (doall (encode bench-colls)))] (println "generate-string") (reset! x (time (doall (generate-string @x)))) (println "parse-string") (time (doall (parse-string @x))))))
null
https://raw.githubusercontent.com/tailrecursion/cljson/180c0c3ea49e13da965fecb23c2f8e55e0f14b69/test/tailrecursion/cljson_test.clj
clojure
benchmark
(ns tailrecursion.cljson-test (:require [clojure.tools.reader.edn :as e] [clojure.test :refer :all] [cheshire.core :refer [generate-string parse-string]] [tailrecursion.cljson :refer [encode decode clj->cljson cljson->clj]] [clojure.data.generators :as g]) (:refer-clojure :exclude [list])) (def scalars [(constantly nil) g/long g/boolean g/string g/symbol g/keyword g/uuid g/date]) (defn scalar [] (@#'g/call-through (g/rand-nth scalars))) (def collections [[g/vec [scalars]] [g/set [scalars]] [g/hash-map [scalars scalars]] [g/list [scalars]]]) (defn collection "Returns a collection of scalar elements based on *rnd*." [] (let [[coll args] (g/rand-nth collections)] (apply coll (map g/rand-nth args)))) (defn deep-collection ([breadth depth] (let [s (atom 0) c (atom 0) v (deep-collection breadth depth 0 s c)] (with-meta v {:collections @c :scalars @s}))) ([breadth depth nparents nscalars ncollections] (let [pcoll (/ (- depth nparents) depth) pscal (- 1 pcoll) ncoll (if (pos? pcoll) (g/geometric (/ 1 (* pcoll breadth))) 0) nscal (if (pos? pscal) (g/geometric (/ 1 (* pscal breadth))) 0) colls (for [_ (range ncoll)] (deep-collection breadth depth (inc nparents) nscalars ncollections)) scals (for [_ (range nscal)] (scalar)) items (g/shuffle (concat colls scals)) base (g/rand-nth [{} [] #{} ()])] (swap! nscalars + nscal) (swap! ncollections + ncoll) (into base (if (map? base) (map (partial apply vector) (partition 2 items)) items))))) (def ^:dynamic *magic* 1000) (deftest scalar-roundtrip (dotimes [_ *magic*] (let [x (scalar)] (is (= x (-> x clj->cljson cljson->clj)))))) (deftest collection-roundtrip (dotimes [_ *magic*] (let [x (collection)] (is (= x (-> x clj->cljson cljson->clj)))))) (defrecord Person [name]) (deftest tag-interpretation (let [bob (Person. "Bob")] (binding [*data-readers* {`Person map->Person}] (is (= bob (-> bob clj->cljson cljson->clj)))))) (deftest meta-roundtrip (let [m {:abc 123} s (with-meta {:x 1} m)] (binding [*print-meta* true] (is (= (meta (cljson->clj (clj->cljson s))) m))))) (deftest nested-perf (let [x (deep-collection 10 4)] (is (= x (-> x clj->cljson cljson->clj))))) (def breadth 10) (def depth 5) (def bench-colls (deep-collection breadth depth)) (let [{c :collections s :scalars} (meta bench-colls)] (printf "Deep collection %d x %d: %d collections and %d scalars.\n" breadth depth c s)) (deftest native-perf (let [x (atom nil)] (println "clojure.core/pr-str") (reset! x (time (doall (pr-str bench-colls)))) (println "clojure.tools.reader.edn/read-string") (time (doall (e/read-string @x))))) (deftest cljson-perf (let [x (atom nil)] (println "clj->cljson") (reset! x (time (doall (clj->cljson bench-colls)))) (println "cljson->clj") (time (cljson->clj @x)) (let [x (atom (doall (encode bench-colls)))] (println "generate-string") (reset! x (time (doall (generate-string @x)))) (println "parse-string") (time (doall (parse-string @x))))))
2b571fc750b00fd08f11a0f320bb2f313eda8383a55fcf58bb732ca10ef3309e
clj-easy/graalvm-clojure
main.clj
(ns simple.main (:require [cljfmt.main :as fmt]) (:gen-class)) (defn -main [& args] (apply fmt/-main args))
null
https://raw.githubusercontent.com/clj-easy/graalvm-clojure/5de155ad4f95d5dac97aac1ab3d118400e7d186f/cljfmt/src/simple/main.clj
clojure
(ns simple.main (:require [cljfmt.main :as fmt]) (:gen-class)) (defn -main [& args] (apply fmt/-main args))
f97ea5f88692e64ec349242593c23174c50b72d320267139d6bd2b7bd79a7a84
EligiusSantori/L2Apf
return.scm
(module logic racket/base (require racket/contract "../packet/game/client/return.scm" (only-in "../system/connection.scm" send-packet) ) (provide return) (define (return connection [point 'return-point/town]) (send-packet connection (game-client-packet/return point)) ) )
null
https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/api/return.scm
scheme
(module logic racket/base (require racket/contract "../packet/game/client/return.scm" (only-in "../system/connection.scm" send-packet) ) (provide return) (define (return connection [point 'return-point/town]) (send-packet connection (game-client-packet/return point)) ) )
fdd00409672fb8d992bbf68f9ad9d2b35fe9ca73c692a779e76a6b4985a4e528
eareese/htdp-exercises
125-legal-sentences.rkt
Exercise 125 . Discriminate the legal from the illegal sentences : ;; (define-struct oops []) This is legal , apparently there can be zero or more names inside the brackets . ( define - struct child [ parents date ] ) ; This is legal. There is an opening paren, the keyword define-struct, a name `child`, then a list of names `parents`, `dob`, and `date` inside the square brackets, followed by the closing paren. ( define - struct ( child person ) [ dob date ] ) illegal ? ? The name should not look like ` ( child person ) ` , when it should look like a name or variable -- one name only , and no parentheses . ;; Explain why the sentences are legal or illegal.
null
https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part01-fixed-size-data/125-legal-sentences.rkt
racket
(define-struct oops []) This is legal. There is an opening paren, the keyword define-struct, a name `child`, then a list of names `parents`, `dob`, and `date` inside the square brackets, followed by the closing paren. Explain why the sentences are legal or illegal.
Exercise 125 . Discriminate the legal from the illegal sentences : This is legal , apparently there can be zero or more names inside the brackets . ( define - struct child [ parents date ] ) ( define - struct ( child person ) [ dob date ] ) illegal ? ? The name should not look like ` ( child person ) ` , when it should look like a name or variable -- one name only , and no parentheses .
6e249da251c1d616ed1d210c5573ea1c354cab94bbf915a4209b2d7dca6935a7
blynn/compiler
Webby.hs
-- In-browser compiler. module Main where import Base import Ast import Map import Typer import RTS import System import WartsBytes data StrLen = StrLen { _str :: String -> String, _len :: Int } instance Monoid StrLen where mempty = StrLen id 0 (StrLen s1 n1) <> (StrLen s2 n2) = StrLen (s1 . s2) (n1 + n2) hexValue d | d <= '9' = ord d - ord '0' | d <= 'F' = 10 + ord d - ord 'A' | d <= 'f' = 10 + ord d - ord 'a' unxxd s = StrLen (go s) (length s `div` 2) where go s = case s of [] -> id (d1:d0:rest) -> ((chr $ hexValue d1 * 16 + hexValue d0):) . go rest main = interact $ either id id . toWasm toWasm s = do tab <- insert "#" neatPrim <$> singleFile s ms <- topoModules tab objs <- foldM compileModule Tip ms let ffis = foldr (\(k, v) m -> insertWith (error $ "duplicate import: " ++ k) k v m) Tip $ concatMap (toAscList . ffiImports) $ elems tab ffiMap = fromList $ zip (keys ffis) [0..] lout = foldl (agglomerate ffiMap objs) layoutNew $ fst <$> ms mem = _memFun lout [] ffes = toAscList $ fst <$> _ffes lout go (n, x) -- Function section: for each export, declare a function of type () -> ().. | n == 3 = leb n <> extendSection x (replicate (length ffes) $ unxxd "01") -- Export section: add each export. | n == 7 = leb n <> extendSection x (zipWith encodeExport (fst <$> ffes) [allFunCount..]) -- Code section: for nth export, define a function calling rts_reduce([512 + 4*n]) | n == 10 = leb n <> extendSection x (callRoot <$> [0..length ffes - 1]) | True = leb n <> leb (_len s) <> s where s = unxxd x roots = encodeData rootBase $ littleEndian $ (snd <$> ffes) ++ [0] prog = encodeData heapBase $ littleEndian $ length mem : mem pure $ _str (unxxd "0061736d01000000" <> mconcat (map go wartsBytes) -- Data section: 512 : null - terminated roots array -- 1048576 - 4: hp 1048576 : initial heap contents <> leb 11 <> extendSection "00" [roots, prog]) "" extendSection x xs = encodeSection (k + length xs) $ unxxd s <> mconcat xs where (k, s) = splitLeb x splitLeb x = go x 1 0 where go (d1:d0:t) m acc | n < 128 = (acc + n*m, t) | True = go t (m*128) $ acc + (n - 128)*m where n = hexValue d1 * 16 + hexValue d0 encodeExport s n = encodeString s <> unxxd "00" <> leb n encodeString s = let n = length s in leb n <> StrLen (s++) n littleEndian ns = StrLen (foldr (.) id $ go 4 <$> ns) $ 4 * length ns where go k n | k == 0 = id | True = (chr (n `mod` 256):) . go (k - 1) (n `div` 256) sleb 512 = 8004 sleb ( 1048576 - 4 ) = fcff3f -- 0 locals. i32.const 0 ; i32.load 512 + 4*n ; call $ REDUCE ; end ; callRoot n = leb (_len s) <> s where s = unxxd "0041002802" <> slebPos (512 + 4*n) <> unxxd "10" <> leb reduceFunIdx <> unxxd "0b" encodeData addr s = addr <> leb (_len s) <> s encodeSection k s = let n = leb k in leb (_len n + _len s) <> n <> s leb n | n <= 127 = StrLen (chr n:) 1 | True = StrLen (chr (128 + n `mod` 128):) 1 <> leb (n `div` 128) slebPos n | n <= 63 = StrLen (chr n:) 1 | True = StrLen (chr (128 + n `mod` 128):) 1 <> slebPos (n `div` 128)
null
https://raw.githubusercontent.com/blynn/compiler/05f0c92d73b219fa245f164833c5d2345b897fbe/inn/Webby.hs
haskell
In-browser compiler. Function section: for each export, declare a function of type () -> ().. Export section: add each export. Code section: for nth export, define a function calling rts_reduce([512 + 4*n]) Data section: 1048576 - 4: hp 0 locals.
module Main where import Base import Ast import Map import Typer import RTS import System import WartsBytes data StrLen = StrLen { _str :: String -> String, _len :: Int } instance Monoid StrLen where mempty = StrLen id 0 (StrLen s1 n1) <> (StrLen s2 n2) = StrLen (s1 . s2) (n1 + n2) hexValue d | d <= '9' = ord d - ord '0' | d <= 'F' = 10 + ord d - ord 'A' | d <= 'f' = 10 + ord d - ord 'a' unxxd s = StrLen (go s) (length s `div` 2) where go s = case s of [] -> id (d1:d0:rest) -> ((chr $ hexValue d1 * 16 + hexValue d0):) . go rest main = interact $ either id id . toWasm toWasm s = do tab <- insert "#" neatPrim <$> singleFile s ms <- topoModules tab objs <- foldM compileModule Tip ms let ffis = foldr (\(k, v) m -> insertWith (error $ "duplicate import: " ++ k) k v m) Tip $ concatMap (toAscList . ffiImports) $ elems tab ffiMap = fromList $ zip (keys ffis) [0..] lout = foldl (agglomerate ffiMap objs) layoutNew $ fst <$> ms mem = _memFun lout [] ffes = toAscList $ fst <$> _ffes lout go (n, x) | n == 3 = leb n <> extendSection x (replicate (length ffes) $ unxxd "01") | n == 7 = leb n <> extendSection x (zipWith encodeExport (fst <$> ffes) [allFunCount..]) | n == 10 = leb n <> extendSection x (callRoot <$> [0..length ffes - 1]) | True = leb n <> leb (_len s) <> s where s = unxxd x roots = encodeData rootBase $ littleEndian $ (snd <$> ffes) ++ [0] prog = encodeData heapBase $ littleEndian $ length mem : mem pure $ _str (unxxd "0061736d01000000" <> mconcat (map go wartsBytes) 512 : null - terminated roots array 1048576 : initial heap contents <> leb 11 <> extendSection "00" [roots, prog]) "" extendSection x xs = encodeSection (k + length xs) $ unxxd s <> mconcat xs where (k, s) = splitLeb x splitLeb x = go x 1 0 where go (d1:d0:t) m acc | n < 128 = (acc + n*m, t) | True = go t (m*128) $ acc + (n - 128)*m where n = hexValue d1 * 16 + hexValue d0 encodeExport s n = encodeString s <> unxxd "00" <> leb n encodeString s = let n = length s in leb n <> StrLen (s++) n littleEndian ns = StrLen (foldr (.) id $ go 4 <$> ns) $ 4 * length ns where go k n | k == 0 = id | True = (chr (n `mod` 256):) . go (k - 1) (n `div` 256) sleb 512 = 8004 sleb ( 1048576 - 4 ) = fcff3f i32.const 0 ; i32.load 512 + 4*n ; call $ REDUCE ; end ; callRoot n = leb (_len s) <> s where s = unxxd "0041002802" <> slebPos (512 + 4*n) <> unxxd "10" <> leb reduceFunIdx <> unxxd "0b" encodeData addr s = addr <> leb (_len s) <> s encodeSection k s = let n = leb k in leb (_len n + _len s) <> n <> s leb n | n <= 127 = StrLen (chr n:) 1 | True = StrLen (chr (128 + n `mod` 128):) 1 <> leb (n `div` 128) slebPos n | n <= 63 = StrLen (chr n:) 1 | True = StrLen (chr (128 + n `mod` 128):) 1 <> slebPos (n `div` 128)
e8ed989f6329a637080e1e468a440f5f2f3ba980044ae12f244e7567f2fcad71
purcell/adventofcode2016
Day13.hs
module Main where import AdventOfCode import Data.Bits (popCount) import Data.List (nub) import Data.Tree (Tree) import qualified Data.Tree as T import Data.Set (Set) import qualified Data.Set as S type Coord = (Int, Int) puzzleInput = 1350 isOpen :: Coord -> Bool isOpen (x, y) = even $ bitsSet $ x * x + 3 * x + 2 * x * y + y + y * y + puzzleInput where bitsSet = popCount nextPaths :: [Coord] -> [[Coord]] nextPaths p@(cur:_) = (: p) <$> nextPositions cur nextPaths _ = undefined nextPositions :: Coord -> [Coord] nextPositions (x, y) = [ newpos | newpos@(x', y') <- [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] , x' >= 0 && y' >= 0 , isOpen newpos ] showMap :: Int -> Int -> String showMap w h = unlines $ showRow <$> [0 .. h] where showRow y = [ if isOpen (x, y) then '.' else '#' | x <- [0 .. w] ] paths = bfsOn head nextPaths [(1, 1)] partA = length (head $ dropWhile ((/= (31, 39)) . head) paths) - 1 partB = length $ nub $ concat $ takeWhile ((<= 51) . length) paths main = runDay $ Day 13 (many anyChar) (return . show . const partA) (return . show . const partB)
null
https://raw.githubusercontent.com/purcell/adventofcode2016/081f30de4ea6b939e6c3736d83836f4dd72ab9a2/src/Day13.hs
haskell
module Main where import AdventOfCode import Data.Bits (popCount) import Data.List (nub) import Data.Tree (Tree) import qualified Data.Tree as T import Data.Set (Set) import qualified Data.Set as S type Coord = (Int, Int) puzzleInput = 1350 isOpen :: Coord -> Bool isOpen (x, y) = even $ bitsSet $ x * x + 3 * x + 2 * x * y + y + y * y + puzzleInput where bitsSet = popCount nextPaths :: [Coord] -> [[Coord]] nextPaths p@(cur:_) = (: p) <$> nextPositions cur nextPaths _ = undefined nextPositions :: Coord -> [Coord] nextPositions (x, y) = [ newpos | newpos@(x', y') <- [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] , x' >= 0 && y' >= 0 , isOpen newpos ] showMap :: Int -> Int -> String showMap w h = unlines $ showRow <$> [0 .. h] where showRow y = [ if isOpen (x, y) then '.' else '#' | x <- [0 .. w] ] paths = bfsOn head nextPaths [(1, 1)] partA = length (head $ dropWhile ((/= (31, 39)) . head) paths) - 1 partB = length $ nub $ concat $ takeWhile ((<= 51) . length) paths main = runDay $ Day 13 (many anyChar) (return . show . const partA) (return . show . const partB)
d33c49d08e68b44666f4e263a06d9af9f96a01450131f6bcbf99042944319b8c
sharplispers/ironclad
dsa.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- ;;;; dsa.lisp -- implementation of the Digital Signature Algorithm (in-package :crypto) ;;; class definitions (defclass dsa-key () ((group :initarg :group :reader group))) (defclass dsa-public-key (dsa-key) ((y :initarg :y :reader dsa-key-y :type integer))) (defclass dsa-private-key (dsa-key) ((y :initarg :y :reader dsa-key-y :type integer) (x :initarg :x :reader dsa-key-x :type integer))) (defun dsa-key-p (dsa-key) (group-pval (group dsa-key))) (defun dsa-key-q (dsa-key) (group-qval (group dsa-key))) (defun dsa-key-g (dsa-key) (group-gval (group dsa-key))) ;;; function definitions (defmethod make-public-key ((kind (eql :dsa)) &key p q g y &allow-other-keys) (unless p (error 'missing-key-parameter :kind 'dsa :parameter 'p :description "modulus")) (unless q (error 'missing-key-parameter :kind 'dsa :parameter 'q :description "subgroup modulus")) (unless g (error 'missing-key-parameter :kind 'dsa :parameter 'g :description "generator")) (unless y (error 'missing-key-parameter :kind 'dsa :parameter 'y :description "public key")) (let ((group (make-instance 'discrete-logarithm-group :p p :q q :g g))) (make-instance 'dsa-public-key :group group :y y))) (defmethod destructure-public-key ((public-key dsa-public-key)) (list :p (dsa-key-p public-key) :q (dsa-key-q public-key) :g (dsa-key-g public-key) :y (dsa-key-y public-key))) (defmethod make-private-key ((kind (eql :dsa)) &key p q g y x &allow-other-keys) (unless p (error 'missing-key-parameter :kind 'dsa :parameter 'p :description "modulus")) (unless q (error 'missing-key-parameter :kind 'dsa :parameter 'q :description "subgroup modulus")) (unless g (error 'missing-key-parameter :kind 'dsa :parameter 'g :description "generator")) (unless x (error 'missing-key-parameter :kind 'dsa :parameter 'x :description "private key")) (let ((group (make-instance 'discrete-logarithm-group :p p :q q :g g))) (make-instance 'dsa-private-key :group group :x x :y (or y (expt-mod g x p))))) (defmethod destructure-private-key ((private-key dsa-private-key)) (list :p (dsa-key-p private-key) :q (dsa-key-q private-key) :g (dsa-key-g private-key) :x (dsa-key-x private-key) :y (dsa-key-y private-key))) (defmethod generate-key-pair ((kind (eql :dsa)) &key num-bits &allow-other-keys) (unless num-bits (error 'missing-key-parameter :kind 'dsa :parameter 'num-bits :description "modulus size")) (let* ((n (cond ((< num-bits 512) (error 'ironclad-error :format-control "NUM-BITS is too small for a DSA key.")) ((<= num-bits 1024) 160) ((<= num-bits 2048) 224) ((<= num-bits 3072) 256) ((<= num-bits 7680) 384) ((<= num-bits 15360) 512) (t (error 'ironclad-error :format-control "NUM-BITS is too big for a DSA key.")))) (q (generate-prime n)) (p (loop for z = (logior (ash 1 (- num-bits n 1)) (dpb 0 (byte 1 0) (random-bits (- num-bits n)))) for p = (1+ (* z q)) until (and (= num-bits (integer-length p)) (prime-p p)) finally (return p))) (g (find-subgroup-generator p q)) (x (+ 2 (strong-random (- q 2)))) (y (expt-mod g x p))) (values (make-private-key :dsa :p p :q q :g g :y y :x x) (make-public-key :dsa :p p :q q :g g :y y)))) (defmethod generate-signature-nonce ((key dsa-private-key) message &optional q) (declare (ignore key message)) (or *signature-nonce-for-test* (1+ (strong-random (1- q))))) (defmethod make-signature ((kind (eql :dsa)) &key r s n-bits &allow-other-keys) (unless r (error 'missing-signature-parameter :kind 'dsa :parameter 'r :description "first signature element")) (unless s (error 'missing-signature-parameter :kind 'dsa :parameter 's :description "second signature element")) (unless n-bits (error 'missing-signature-parameter :kind 'dsa :parameter 'n-bits :description "subgroup modulus size")) (concatenate '(simple-array (unsigned-byte 8) (*)) (integer-to-octets r :n-bits n-bits) (integer-to-octets s :n-bits n-bits))) (defmethod destructure-signature ((kind (eql :dsa)) signature) (let ((length (length signature))) (if (oddp length) (error 'invalid-signature-length :kind 'dsa) (let* ((middle (/ length 2)) (n-bits (* middle 8)) (r (octets-to-integer signature :start 0 :end middle)) (s (octets-to-integer signature :start middle))) (list :r r :s s :n-bits n-bits))))) ;;; Note that hashing is not performed here. (defmethod sign-message ((key dsa-private-key) message &key (start 0) end &allow-other-keys) (let* ((end (or end (length message))) (q (dsa-key-q key)) (qbits (integer-length q))) (when (> (* 8 (- end start)) qbits) ;; Only keep the required number of bits of message (setf end (+ start (/ qbits 8)))) (let* ((m (octets-to-integer message :start start :end end)) (p (dsa-key-p key)) (g (dsa-key-g key)) (x (dsa-key-x key)) (k (generate-signature-nonce key message q)) (r (mod (expt-mod g k p) q)) (k-inverse (modular-inverse-with-blinding k q)) (s (mod (* k-inverse (+ (* x r) m)) q))) (assert (= (mod (* k k-inverse) q) 1)) (if (not (or (zerop r) (zerop s))) (make-signature :dsa :r r :s s :n-bits qbits) (sign-message key message :start start :end end))))) (defmethod verify-signature ((key dsa-public-key) message signature &key (start 0) end &allow-other-keys) (let* ((end (or end (length message))) (q (dsa-key-q key)) (qbits (integer-length q))) (unless (= (* 4 (length signature)) qbits) (error 'invalid-signature-length :kind 'dsa)) (when (> (* 8 (- end start)) qbits) ;; Only keep the required number of bits of message (setf end (+ start (/ qbits 8)))) (let* ((m (octets-to-integer message :start start :end end)) (p (dsa-key-p key)) (g (dsa-key-g key)) (y (dsa-key-y key)) (signature-elements (destructure-signature :dsa signature)) (r (getf signature-elements :r)) (s (getf signature-elements :s))) (unless (and (< 0 r q) (< 0 s q)) (return-from verify-signature nil)) (let* ((w (modular-inverse s q)) (u1 (mod (* m w) q)) (u2 (mod (* r w) q)) (v (mod (mod (* (expt-mod g u1 p) (expt-mod y u2 p)) p) q))) (= v r)))))
null
https://raw.githubusercontent.com/sharplispers/ironclad/6cc4da8554558ee2e89ea38802bbf6d83100d4ea/src/public-key/dsa.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*- dsa.lisp -- implementation of the Digital Signature Algorithm class definitions function definitions Note that hashing is not performed here. Only keep the required number of bits of message Only keep the required number of bits of message
(in-package :crypto) (defclass dsa-key () ((group :initarg :group :reader group))) (defclass dsa-public-key (dsa-key) ((y :initarg :y :reader dsa-key-y :type integer))) (defclass dsa-private-key (dsa-key) ((y :initarg :y :reader dsa-key-y :type integer) (x :initarg :x :reader dsa-key-x :type integer))) (defun dsa-key-p (dsa-key) (group-pval (group dsa-key))) (defun dsa-key-q (dsa-key) (group-qval (group dsa-key))) (defun dsa-key-g (dsa-key) (group-gval (group dsa-key))) (defmethod make-public-key ((kind (eql :dsa)) &key p q g y &allow-other-keys) (unless p (error 'missing-key-parameter :kind 'dsa :parameter 'p :description "modulus")) (unless q (error 'missing-key-parameter :kind 'dsa :parameter 'q :description "subgroup modulus")) (unless g (error 'missing-key-parameter :kind 'dsa :parameter 'g :description "generator")) (unless y (error 'missing-key-parameter :kind 'dsa :parameter 'y :description "public key")) (let ((group (make-instance 'discrete-logarithm-group :p p :q q :g g))) (make-instance 'dsa-public-key :group group :y y))) (defmethod destructure-public-key ((public-key dsa-public-key)) (list :p (dsa-key-p public-key) :q (dsa-key-q public-key) :g (dsa-key-g public-key) :y (dsa-key-y public-key))) (defmethod make-private-key ((kind (eql :dsa)) &key p q g y x &allow-other-keys) (unless p (error 'missing-key-parameter :kind 'dsa :parameter 'p :description "modulus")) (unless q (error 'missing-key-parameter :kind 'dsa :parameter 'q :description "subgroup modulus")) (unless g (error 'missing-key-parameter :kind 'dsa :parameter 'g :description "generator")) (unless x (error 'missing-key-parameter :kind 'dsa :parameter 'x :description "private key")) (let ((group (make-instance 'discrete-logarithm-group :p p :q q :g g))) (make-instance 'dsa-private-key :group group :x x :y (or y (expt-mod g x p))))) (defmethod destructure-private-key ((private-key dsa-private-key)) (list :p (dsa-key-p private-key) :q (dsa-key-q private-key) :g (dsa-key-g private-key) :x (dsa-key-x private-key) :y (dsa-key-y private-key))) (defmethod generate-key-pair ((kind (eql :dsa)) &key num-bits &allow-other-keys) (unless num-bits (error 'missing-key-parameter :kind 'dsa :parameter 'num-bits :description "modulus size")) (let* ((n (cond ((< num-bits 512) (error 'ironclad-error :format-control "NUM-BITS is too small for a DSA key.")) ((<= num-bits 1024) 160) ((<= num-bits 2048) 224) ((<= num-bits 3072) 256) ((<= num-bits 7680) 384) ((<= num-bits 15360) 512) (t (error 'ironclad-error :format-control "NUM-BITS is too big for a DSA key.")))) (q (generate-prime n)) (p (loop for z = (logior (ash 1 (- num-bits n 1)) (dpb 0 (byte 1 0) (random-bits (- num-bits n)))) for p = (1+ (* z q)) until (and (= num-bits (integer-length p)) (prime-p p)) finally (return p))) (g (find-subgroup-generator p q)) (x (+ 2 (strong-random (- q 2)))) (y (expt-mod g x p))) (values (make-private-key :dsa :p p :q q :g g :y y :x x) (make-public-key :dsa :p p :q q :g g :y y)))) (defmethod generate-signature-nonce ((key dsa-private-key) message &optional q) (declare (ignore key message)) (or *signature-nonce-for-test* (1+ (strong-random (1- q))))) (defmethod make-signature ((kind (eql :dsa)) &key r s n-bits &allow-other-keys) (unless r (error 'missing-signature-parameter :kind 'dsa :parameter 'r :description "first signature element")) (unless s (error 'missing-signature-parameter :kind 'dsa :parameter 's :description "second signature element")) (unless n-bits (error 'missing-signature-parameter :kind 'dsa :parameter 'n-bits :description "subgroup modulus size")) (concatenate '(simple-array (unsigned-byte 8) (*)) (integer-to-octets r :n-bits n-bits) (integer-to-octets s :n-bits n-bits))) (defmethod destructure-signature ((kind (eql :dsa)) signature) (let ((length (length signature))) (if (oddp length) (error 'invalid-signature-length :kind 'dsa) (let* ((middle (/ length 2)) (n-bits (* middle 8)) (r (octets-to-integer signature :start 0 :end middle)) (s (octets-to-integer signature :start middle))) (list :r r :s s :n-bits n-bits))))) (defmethod sign-message ((key dsa-private-key) message &key (start 0) end &allow-other-keys) (let* ((end (or end (length message))) (q (dsa-key-q key)) (qbits (integer-length q))) (when (> (* 8 (- end start)) qbits) (setf end (+ start (/ qbits 8)))) (let* ((m (octets-to-integer message :start start :end end)) (p (dsa-key-p key)) (g (dsa-key-g key)) (x (dsa-key-x key)) (k (generate-signature-nonce key message q)) (r (mod (expt-mod g k p) q)) (k-inverse (modular-inverse-with-blinding k q)) (s (mod (* k-inverse (+ (* x r) m)) q))) (assert (= (mod (* k k-inverse) q) 1)) (if (not (or (zerop r) (zerop s))) (make-signature :dsa :r r :s s :n-bits qbits) (sign-message key message :start start :end end))))) (defmethod verify-signature ((key dsa-public-key) message signature &key (start 0) end &allow-other-keys) (let* ((end (or end (length message))) (q (dsa-key-q key)) (qbits (integer-length q))) (unless (= (* 4 (length signature)) qbits) (error 'invalid-signature-length :kind 'dsa)) (when (> (* 8 (- end start)) qbits) (setf end (+ start (/ qbits 8)))) (let* ((m (octets-to-integer message :start start :end end)) (p (dsa-key-p key)) (g (dsa-key-g key)) (y (dsa-key-y key)) (signature-elements (destructure-signature :dsa signature)) (r (getf signature-elements :r)) (s (getf signature-elements :s))) (unless (and (< 0 r q) (< 0 s q)) (return-from verify-signature nil)) (let* ((w (modular-inverse s q)) (u1 (mod (* m w) q)) (u2 (mod (* r w) q)) (v (mod (mod (* (expt-mod g u1 p) (expt-mod y u2 p)) p) q))) (= v r)))))
043c5cc3e5f5dfadcf18cf323915826ab30970d68798ee37f00e6f46d4aa1a2b
lem-project/lem
source-path-parser.lisp
;;;; Source-paths CMUCL / SBCL use a data structure called " source - path " to locate ;;; subforms. The compiler assigns a source-path to each form in a compilation unit . Compiler notes usually contain the source - path ;;; of the error location. ;;; ;;; Compiled code objects don't contain source paths, only the ;;; "toplevel-form-number" and the (sub-) "form-number". To get from ;;; the form-number to the source-path we need the entire toplevel-form ( i.e. we have to read the source code ) . CMUCL has already some ;;; utilities to do this translation, but we use some extended ;;; versions, because we need more exact position info. Apparently Hemlock is happy with the position of the toplevel - form ; we also ;;; need the position of subforms. ;;; ;;; We use a special readtable to get the positions of the subforms. ;;; The readtable stores the start and end position for each subform in ;;; hashtable for later retrieval. ;;; ;;; This code has been placed in the Public Domain. All warranties ;;; are disclaimed. Taken from swank-cmucl.lisp , by (defpackage micros/source-path-parser (:use cl) (:export read-source-form source-path-string-position source-path-file-position source-path-source-position sexp-in-bounds-p sexp-ref) (:shadow ignore-errors)) (in-package micros/source-path-parser) ;; Some test to ensure the required conformance (let ((rt (copy-readtable nil))) (assert (or (not (get-macro-character #\space rt)) (nth-value 1 (get-macro-character #\space rt)))) (assert (not (get-macro-character #\\ rt)))) (eval-when (:compile-toplevel) (defmacro ignore-errors (&rest forms) ;;`(progn . ,forms) ; for debugging `(cl:ignore-errors . ,forms))) (defun make-sharpdot-reader (orig-sharpdot-reader) (lambda (s c n) ;; We want things like M-. to work regardless of any #.-fu in ;; the source file that is to be visited. (For instance, when a ;; file contains #. forms referencing constants that do not ;; currently exist in the image.) (ignore-errors (funcall orig-sharpdot-reader s c n)))) (defun make-source-recorder (fn source-map) "Return a macro character function that does the same as FN, but additionally stores the result together with the stream positions before and after of calling FN in the hashtable SOURCE-MAP." (lambda (stream char) (let ((start (1- (file-position stream))) (values (multiple-value-list (funcall fn stream char))) (end (file-position stream))) #+(or) (format t "[~D \"~{~A~^, ~}\" ~D ~D ~S]~%" start values end (char-code char) char) (when values (destructuring-bind (&optional existing-start &rest existing-end) (car (gethash (car values) source-map)) ;; Some macros may return what a sub-call to another macro ;; produced, e.g. "#+(and) (a)" may end up saving (a) twice, once from # \ # and once from # \ ( . If the saved form ;; is a subform, don't save it again. (unless (and existing-start existing-end (<= start existing-start end) (<= start existing-end end)) (push (cons start end) (gethash (car values) source-map))))) (values-list values)))) (defun make-source-recording-readtable (readtable source-map) (declare (type readtable readtable) (type hash-table source-map)) "Return a source position recording copy of READTABLE. The source locations are stored in SOURCE-MAP." (flet ((install-special-sharpdot-reader (rt) (let ((fun (ignore-errors (get-dispatch-macro-character #\# #\. rt)))) (when fun (let ((wrapper (make-sharpdot-reader fun))) (set-dispatch-macro-character #\# #\. wrapper rt))))) (install-wrappers (rt) (dotimes (code 128) (let ((char (code-char code))) (multiple-value-bind (fun nt) (get-macro-character char rt) (when fun (let ((wrapper (make-source-recorder fun source-map))) (set-macro-character char wrapper nt rt)))))))) (let ((rt (copy-readtable readtable))) (install-special-sharpdot-reader rt) (install-wrappers rt) rt))) ;; FIXME: try to do this with *READ-SUPPRESS* = t to avoid interning. ;; Should be possible as we only need the right "list structure" and ;; not the right atoms. (defun read-and-record-source-map (stream) "Read the next object from STREAM. Return the object together with a hashtable that maps subexpressions of the object to stream positions." (let* ((source-map (make-hash-table :test #'eq)) (*readtable* (make-source-recording-readtable *readtable* source-map)) (*read-suppress* nil) (start (file-position stream)) (form (ignore-errors (read stream))) (end (file-position stream))) ;; ensure that at least FORM is in the source-map (unless (gethash form source-map) (push (cons start end) (gethash form source-map))) (values form source-map))) (defun starts-with-p (string prefix) (declare (type string string prefix)) (not (mismatch string prefix :end1 (min (length string) (length prefix)) :test #'char-equal))) (defun extract-package (line) (declare (type string line)) (let ((name (cadr (read-from-string line)))) (find-package name))) #+(or) (progn (assert (extract-package "(in-package cl)")) (assert (extract-package "(cl:in-package cl)")) (assert (extract-package "(in-package \"CL\")")) (assert (extract-package "(in-package #:cl)"))) ;; FIXME: do something cleaner than this. (defun readtable-for-package (package) : due to the load order we ca n't reference the swank ;; package. (funcall (read-from-string "micros::guess-buffer-readtable") (string-upcase (package-name package)))) ;; Search STREAM for a "(in-package ...)" form. Use that to derive ;; the values for *PACKAGE* and *READTABLE*. ;; IDEA : move GUESS - READER - STATE to swank.lisp so that all backends ;; use the same heuristic and to avoid the need to access ;; micros::guess-buffer-readtable from here. (defun guess-reader-state (stream) (let* ((point (file-position stream)) (pkg *package*)) (file-position stream 0) (loop for line = (read-line stream nil nil) do (when (not line) (return)) (when (or (starts-with-p line "(in-package ") (starts-with-p line "(cl:in-package ")) (let ((p (extract-package line))) (when p (setf pkg p))) (return))) (file-position stream point) (values (readtable-for-package pkg) pkg))) (defun skip-whitespace (stream) (peek-char t stream nil nil)) ;; Skip over N toplevel forms. (defun skip-toplevel-forms (n stream) (let ((*read-suppress* t)) (dotimes (i n) (read stream)) (skip-whitespace stream))) (defun read-source-form (n stream) "Read the Nth toplevel form number with source location recording. Return the form and the source-map." (multiple-value-bind (*readtable* *package*) (guess-reader-state stream) (let (#+sbcl (*features* (append *features* (symbol-value (find-symbol "+INTERNAL-FEATURES+" 'sb-impl))))) (skip-toplevel-forms n stream) (read-and-record-source-map stream)))) (defun source-path-stream-position (path stream) "Search the source-path PATH in STREAM and return its position." (check-source-path path) (destructuring-bind (tlf-number . path) path (multiple-value-bind (form source-map) (read-source-form tlf-number stream) (source-path-source-position (cons 0 path) form source-map)))) (defun check-source-path (path) (unless (and (consp path) (every #'integerp path)) (error "The source-path ~S is not valid." path))) (defun source-path-string-position (path string) (with-input-from-string (s string) (source-path-stream-position path s))) (defun source-path-file-position (path filename) ;; We go this long way round, and don't directly operate on the file stream because FILE - POSITION ( used above ) is not totally savy even on file character streams ; on SBCL , FILE - POSITION returns the binary offset , and not the character offset --- screwing up on Unicode . (let ((toplevel-number (first path)) (buffer)) (with-open-file (file filename) (skip-toplevel-forms (1+ toplevel-number) file) (let ((endpos (file-position file))) (setq buffer (make-array (list endpos) :element-type 'character :initial-element #\Space)) (assert (file-position file 0)) (read-sequence buffer file :end endpos))) (source-path-string-position path buffer))) (defgeneric sexp-in-bounds-p (sexp i) (:method ((list list) i) (< i (loop for e on list count t))) (:method ((sexp t) i) nil)) (defgeneric sexp-ref (sexp i) (:method ((s list) i) (elt s i))) (defun source-path-source-position (path form source-map) "Return the start position of PATH from FORM and SOURCE-MAP. All subforms along the path are considered and the start and end position of the deepest (i.e. smallest) possible form is returned." ;; compute all subforms along path (let ((forms (loop for i in path for f = form then (if (sexp-in-bounds-p f i) (sexp-ref f i)) collect f))) select the first subform present in source - map (loop for form in (nreverse forms) for ((start . end) . rest) = (gethash form source-map) when (and start end (not rest)) return (return (values start end)))))
null
https://raw.githubusercontent.com/lem-project/lem/c1c3d35905bfd0c6d1af1df4f7c6a7f415a1c7e9/lib/micros/swank/source-path-parser.lisp
lisp
Source-paths subforms. The compiler assigns a source-path to each form in a of the error location. Compiled code objects don't contain source paths, only the "toplevel-form-number" and the (sub-) "form-number". To get from the form-number to the source-path we need the entire toplevel-form utilities to do this translation, but we use some extended versions, because we need more exact position info. Apparently we also need the position of subforms. We use a special readtable to get the positions of the subforms. The readtable stores the start and end position for each subform in hashtable for later retrieval. This code has been placed in the Public Domain. All warranties are disclaimed. Some test to ensure the required conformance `(progn . ,forms) ; for debugging We want things like M-. to work regardless of any #.-fu in the source file that is to be visited. (For instance, when a file contains #. forms referencing constants that do not currently exist in the image.) Some macros may return what a sub-call to another macro produced, e.g. "#+(and) (a)" may end up saving (a) twice, is a subform, don't save it again. FIXME: try to do this with *READ-SUPPRESS* = t to avoid interning. Should be possible as we only need the right "list structure" and not the right atoms. ensure that at least FORM is in the source-map FIXME: do something cleaner than this. package. Search STREAM for a "(in-package ...)" form. Use that to derive the values for *PACKAGE* and *READTABLE*. use the same heuristic and to avoid the need to access micros::guess-buffer-readtable from here. Skip over N toplevel forms. We go this long way round, and don't directly operate on the file on SBCL , FILE - POSITION returns the binary compute all subforms along path
CMUCL / SBCL use a data structure called " source - path " to locate compilation unit . Compiler notes usually contain the source - path ( i.e. we have to read the source code ) . CMUCL has already some Taken from swank-cmucl.lisp , by (defpackage micros/source-path-parser (:use cl) (:export read-source-form source-path-string-position source-path-file-position source-path-source-position sexp-in-bounds-p sexp-ref) (:shadow ignore-errors)) (in-package micros/source-path-parser) (let ((rt (copy-readtable nil))) (assert (or (not (get-macro-character #\space rt)) (nth-value 1 (get-macro-character #\space rt)))) (assert (not (get-macro-character #\\ rt)))) (eval-when (:compile-toplevel) (defmacro ignore-errors (&rest forms) `(cl:ignore-errors . ,forms))) (defun make-sharpdot-reader (orig-sharpdot-reader) (lambda (s c n) (ignore-errors (funcall orig-sharpdot-reader s c n)))) (defun make-source-recorder (fn source-map) "Return a macro character function that does the same as FN, but additionally stores the result together with the stream positions before and after of calling FN in the hashtable SOURCE-MAP." (lambda (stream char) (let ((start (1- (file-position stream))) (values (multiple-value-list (funcall fn stream char))) (end (file-position stream))) #+(or) (format t "[~D \"~{~A~^, ~}\" ~D ~D ~S]~%" start values end (char-code char) char) (when values (destructuring-bind (&optional existing-start &rest existing-end) (car (gethash (car values) source-map)) once from # \ # and once from # \ ( . If the saved form (unless (and existing-start existing-end (<= start existing-start end) (<= start existing-end end)) (push (cons start end) (gethash (car values) source-map))))) (values-list values)))) (defun make-source-recording-readtable (readtable source-map) (declare (type readtable readtable) (type hash-table source-map)) "Return a source position recording copy of READTABLE. The source locations are stored in SOURCE-MAP." (flet ((install-special-sharpdot-reader (rt) (let ((fun (ignore-errors (get-dispatch-macro-character #\# #\. rt)))) (when fun (let ((wrapper (make-sharpdot-reader fun))) (set-dispatch-macro-character #\# #\. wrapper rt))))) (install-wrappers (rt) (dotimes (code 128) (let ((char (code-char code))) (multiple-value-bind (fun nt) (get-macro-character char rt) (when fun (let ((wrapper (make-source-recorder fun source-map))) (set-macro-character char wrapper nt rt)))))))) (let ((rt (copy-readtable readtable))) (install-special-sharpdot-reader rt) (install-wrappers rt) rt))) (defun read-and-record-source-map (stream) "Read the next object from STREAM. Return the object together with a hashtable that maps subexpressions of the object to stream positions." (let* ((source-map (make-hash-table :test #'eq)) (*readtable* (make-source-recording-readtable *readtable* source-map)) (*read-suppress* nil) (start (file-position stream)) (form (ignore-errors (read stream))) (end (file-position stream))) (unless (gethash form source-map) (push (cons start end) (gethash form source-map))) (values form source-map))) (defun starts-with-p (string prefix) (declare (type string string prefix)) (not (mismatch string prefix :end1 (min (length string) (length prefix)) :test #'char-equal))) (defun extract-package (line) (declare (type string line)) (let ((name (cadr (read-from-string line)))) (find-package name))) #+(or) (progn (assert (extract-package "(in-package cl)")) (assert (extract-package "(cl:in-package cl)")) (assert (extract-package "(in-package \"CL\")")) (assert (extract-package "(in-package #:cl)"))) (defun readtable-for-package (package) : due to the load order we ca n't reference the swank (funcall (read-from-string "micros::guess-buffer-readtable") (string-upcase (package-name package)))) IDEA : move GUESS - READER - STATE to swank.lisp so that all backends (defun guess-reader-state (stream) (let* ((point (file-position stream)) (pkg *package*)) (file-position stream 0) (loop for line = (read-line stream nil nil) do (when (not line) (return)) (when (or (starts-with-p line "(in-package ") (starts-with-p line "(cl:in-package ")) (let ((p (extract-package line))) (when p (setf pkg p))) (return))) (file-position stream point) (values (readtable-for-package pkg) pkg))) (defun skip-whitespace (stream) (peek-char t stream nil nil)) (defun skip-toplevel-forms (n stream) (let ((*read-suppress* t)) (dotimes (i n) (read stream)) (skip-whitespace stream))) (defun read-source-form (n stream) "Read the Nth toplevel form number with source location recording. Return the form and the source-map." (multiple-value-bind (*readtable* *package*) (guess-reader-state stream) (let (#+sbcl (*features* (append *features* (symbol-value (find-symbol "+INTERNAL-FEATURES+" 'sb-impl))))) (skip-toplevel-forms n stream) (read-and-record-source-map stream)))) (defun source-path-stream-position (path stream) "Search the source-path PATH in STREAM and return its position." (check-source-path path) (destructuring-bind (tlf-number . path) path (multiple-value-bind (form source-map) (read-source-form tlf-number stream) (source-path-source-position (cons 0 path) form source-map)))) (defun check-source-path (path) (unless (and (consp path) (every #'integerp path)) (error "The source-path ~S is not valid." path))) (defun source-path-string-position (path string) (with-input-from-string (s string) (source-path-stream-position path s))) (defun source-path-file-position (path filename) stream because FILE - POSITION ( used above ) is not totally savy even offset , and not the character offset --- screwing up on Unicode . (let ((toplevel-number (first path)) (buffer)) (with-open-file (file filename) (skip-toplevel-forms (1+ toplevel-number) file) (let ((endpos (file-position file))) (setq buffer (make-array (list endpos) :element-type 'character :initial-element #\Space)) (assert (file-position file 0)) (read-sequence buffer file :end endpos))) (source-path-string-position path buffer))) (defgeneric sexp-in-bounds-p (sexp i) (:method ((list list) i) (< i (loop for e on list count t))) (:method ((sexp t) i) nil)) (defgeneric sexp-ref (sexp i) (:method ((s list) i) (elt s i))) (defun source-path-source-position (path form source-map) "Return the start position of PATH from FORM and SOURCE-MAP. All subforms along the path are considered and the start and end position of the deepest (i.e. smallest) possible form is returned." (let ((forms (loop for i in path for f = form then (if (sexp-in-bounds-p f i) (sexp-ref f i)) collect f))) select the first subform present in source - map (loop for form in (nreverse forms) for ((start . end) . rest) = (gethash form source-map) when (and start end (not rest)) return (return (values start end)))))
e597d44e0a361a49495cca4edf509f427f4acad3534f70cc2664ec57e8f21d02
NoahTheDuke/netrunner-data
combine.clj
(ns nr-data.combine (:require [clojure.java.io :as io] [nr-data.data :as data] [nr-data.utils :refer [vals->vec]])) (defn combine-for-jnet [& _] (let [cycles (data/cycles) sets (data/sets) formats (data/formats) mwls (data/mwls) cards (data/combined-cards)] (print "Writing edn/raw_data.edn...") (spit (io/file "edn" "raw_data.edn") (sorted-map :cycles (vals->vec :position cycles) :sets (vals->vec :position sets) :cards (vals->vec :code cards) :formats (vals->vec :date-release formats) :mwls (vals->vec :date-start mwls))) (println "Done!"))) (comment (combine-for-jnet) )
null
https://raw.githubusercontent.com/NoahTheDuke/netrunner-data/aee6759dfa170c126eaab5a6bb00db855acae806/src/nr_data/combine.clj
clojure
(ns nr-data.combine (:require [clojure.java.io :as io] [nr-data.data :as data] [nr-data.utils :refer [vals->vec]])) (defn combine-for-jnet [& _] (let [cycles (data/cycles) sets (data/sets) formats (data/formats) mwls (data/mwls) cards (data/combined-cards)] (print "Writing edn/raw_data.edn...") (spit (io/file "edn" "raw_data.edn") (sorted-map :cycles (vals->vec :position cycles) :sets (vals->vec :position sets) :cards (vals->vec :code cards) :formats (vals->vec :date-release formats) :mwls (vals->vec :date-start mwls))) (println "Done!"))) (comment (combine-for-jnet) )
0d230b7575ea27bf6c74d26d20a7e76812deae10e52a1a928aaea835f00cce29
tomjaguarpaw/haskell-opaleye
PrimQuery.hs
# LANGUAGE LambdaCase # module Opaleye.Internal.PrimQuery where import Prelude hiding (product) import qualified Data.List.NonEmpty as NEL import Data.Semigroup (Semigroup, (<>)) import qualified Opaleye.Internal.HaskellDB.Sql as HSql import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import Opaleye.Internal.HaskellDB.PrimQuery (Symbol) data LimitOp = LimitOp Int | OffsetOp Int | LimitOffsetOp Int Int deriving Show data BinOp = Except | ExceptAll | Union | UnionAll | Intersect | IntersectAll deriving Show data JoinType = LeftJoin | RightJoin | FullJoin deriving Show data SemijoinType = Semi | Anti deriving Show data TableIdentifier = TableIdentifier { tiSchemaName :: Maybe String , tiTableName :: String } deriving Show tiToSqlTable :: TableIdentifier -> HSql.SqlTable tiToSqlTable ti = HSql.SqlTable { HSql.sqlTableSchemaName = tiSchemaName ti , HSql.sqlTableName = tiTableName ti } type Bindings a = [(Symbol, a)] data Lateral = NonLateral | Lateral deriving Show instance Semigroup Lateral where NonLateral <> NonLateral = NonLateral _ <> _ = Lateral instance Monoid Lateral where mappend = (<>) mempty = NonLateral data Recursive = NonRecursive | Recursive deriving Show aLeftJoin :: HPQ.PrimExpr -> PrimQuery -> PrimQueryArr aLeftJoin cond primQuery' = PrimQueryArr $ \lat primQueryL -> Join LeftJoin cond (NonLateral, primQueryL) (lat, primQuery') aProduct :: PrimQuery -> PrimQueryArr aProduct pq = PrimQueryArr (\lat primQuery -> times lat primQuery pq) aSemijoin :: SemijoinType -> PrimQuery -> PrimQueryArr aSemijoin joint existsQ = PrimQueryArr $ \_ primQ -> Semijoin joint primQ existsQ aRebind :: Bindings HPQ.PrimExpr -> PrimQueryArr aRebind bindings = PrimQueryArr $ \_ -> Rebind True bindings aRestrict :: HPQ.PrimExpr -> PrimQueryArr aRestrict predicate = PrimQueryArr $ \_ -> restrict predicate aLabel :: String -> PrimQueryArr aLabel l = PrimQueryArr $ \_ primQ -> Label l primQ -- The function 'Lateral -> PrimQuery -> PrimQuery' represents a -- select arrow in the following way: -- -- Lateral -- -- ^ Whether to join me laterally -- -> PrimQuery -- -- ^ The query that I will be joined after. If I refer to columns -- -- in here in a way that is only valid when I am joined laterally, -- -- then Lateral must be passed in as the argument above. -- -> PrimQuery -- -- ^ The result after joining me -- It is * always * valid to pass Lateral as the first argument . So why -- wouldn't we do that? Because we don't want to generate lateral -- subqueries if they are not needed; it might have performance -- implications. Even though there is good evidence that it *doesn't* -- have performance implications ( ) we still -- want to be cautious. -- -- Not every function of type `Lateral -> PrimQuery -> PrimQuery` is valid to be a PrimQuery . I think the condition that they must -- satisfy for validity is -- -- q == lateral (aProduct (toPrimQuery q) -- -- where == is observable equivalence, i.e. both queries must give the -- same results when combined with other queries and then run. newtype PrimQueryArr = PrimQueryArr { runPrimQueryArr :: Lateral -> PrimQuery -> PrimQuery } instance Semigroup PrimQueryArr where PrimQueryArr f1 <> PrimQueryArr f2 = PrimQueryArr (\lat -> f2 lat . f1 lat) instance Monoid PrimQueryArr where mappend = (<>) mempty = PrimQueryArr (\_ -> id) lateral :: PrimQueryArr -> PrimQueryArr lateral (PrimQueryArr pq) = PrimQueryArr (\_ -> pq Lateral) toPrimQuery :: PrimQueryArr -> PrimQuery toPrimQuery (PrimQueryArr f) = f NonLateral Unit -- We use a 'NEL.NonEmpty' for Product because otherwise we'd have to check -- for emptiness explicitly in the SQL generation phase. -- The type parameter 'a' is used to control whether the 'Empty' -- constructor can appear. If 'a' = '()' then it can appear. If 'a' -- = 'Void' then it cannot. When we create queries it is more -- convenient to allow 'Empty', but it is hard to represent 'Empty' in -- SQL so we remove it in 'Optimize' and set 'a = Void'. data PrimQuery' a = Unit Remove the Empty constructor in 0.10 | Empty a | BaseTable TableIdentifier (Bindings HPQ.PrimExpr) | Product (NEL.NonEmpty (Lateral, PrimQuery' a)) [HPQ.PrimExpr] -- | The subqueries to take the product of and the -- restrictions to apply | Aggregate (Bindings (Maybe (HPQ.AggrOp, [HPQ.OrderExpr], HPQ.AggrDistinct), HPQ.Symbol)) (PrimQuery' a) | Window (Bindings (HPQ.WndwOp, HPQ.Partition)) (PrimQuery' a) | Represents both @DISTINCT ON@ and @ORDER BY@ -- clauses. In order to represent valid SQL only, @DISTINCT ON@ expressions are always interpreted as the first @ORDER BY@s when -- present, preceding any in the provided list. -- See 'Opaleye.Internal.Sql.distinctOnOrderBy'. | DistinctOnOrderBy (Maybe (NEL.NonEmpty HPQ.PrimExpr)) [HPQ.OrderExpr] (PrimQuery' a) | Limit LimitOp (PrimQuery' a) | Join JoinType HPQ.PrimExpr (Lateral, PrimQuery' a) (Lateral, PrimQuery' a) | Semijoin SemijoinType (PrimQuery' a) (PrimQuery' a) | Exists Symbol (PrimQuery' a) | Values [Symbol] (NEL.NonEmpty [HPQ.PrimExpr]) | Binary BinOp (PrimQuery' a, PrimQuery' a) | Label String (PrimQuery' a) | RelExpr HPQ.PrimExpr (Bindings HPQ.PrimExpr) | Rebind Bool (Bindings HPQ.PrimExpr) (PrimQuery' a) | ForUpdate (PrimQuery' a) -- We may support more locking clauses than just ForUpdate in the future -- -- -select.html#SQL-FOR-UPDATE-SHARE | With Recursive Symbol [Symbol] (PrimQuery' a) (PrimQuery' a) deriving Show type PrimQuery = PrimQuery' () type PrimQueryFold p = PrimQueryFold' () p type PrimQueryFold' a p = PrimQueryFoldP a p p data PrimQueryFoldP a p p' = PrimQueryFold { unit :: p' , empty :: a -> p' , baseTable :: TableIdentifier -> Bindings HPQ.PrimExpr -> p' , product :: NEL.NonEmpty (Lateral, p) -> [HPQ.PrimExpr] -> p' , aggregate :: Bindings (Maybe (HPQ.AggrOp, [HPQ.OrderExpr], HPQ.AggrDistinct), HPQ.Symbol) -> p -> p' , window :: Bindings (HPQ.WndwOp, HPQ.Partition) -> p -> p' , distinctOnOrderBy :: Maybe (NEL.NonEmpty HPQ.PrimExpr) -> [HPQ.OrderExpr] -> p -> p' , limit :: LimitOp -> p -> p' , join :: JoinType -> HPQ.PrimExpr -> (Lateral, p) -> (Lateral, p) -> p' , semijoin :: SemijoinType -> p -> p -> p' , exists :: Symbol -> p -> p' , values :: [Symbol] -> NEL.NonEmpty [HPQ.PrimExpr] -> p' , binary :: BinOp -> (p, p) -> p' , label :: String -> p -> p' , relExpr :: HPQ.PrimExpr -> Bindings HPQ.PrimExpr -> p' -- ^ A relation-valued expression , rebind :: Bool -> Bindings HPQ.PrimExpr -> p -> p' , forUpdate :: p -> p' , with :: Recursive -> Symbol -> [Symbol] -> p -> p -> p' } primQueryFoldDefault :: PrimQueryFold' a (PrimQuery' a) primQueryFoldDefault = PrimQueryFold { unit = Unit , empty = Empty , baseTable = BaseTable , product = Product , aggregate = Aggregate , window = Window , distinctOnOrderBy = DistinctOnOrderBy , limit = Limit , join = Join , semijoin = Semijoin , values = Values , binary = Binary , label = Label , relExpr = RelExpr , exists = Exists , rebind = Rebind , forUpdate = ForUpdate , with = With } dimapPrimQueryFold :: (q -> p) -> (p' -> q') -> PrimQueryFoldP a p p' -> PrimQueryFoldP a q q' dimapPrimQueryFold self g f = PrimQueryFold { unit = g (unit f) , empty = g . empty f , baseTable = \ti bs -> g (baseTable f ti bs) , product = \ps conds -> g (product f ((fmap . fmap) self ps) conds) , aggregate = \b p -> g (aggregate f b (self p)) , window = \b p -> g (window f b (self p)) , distinctOnOrderBy = \m os p -> g (distinctOnOrderBy f m os (self p)) , limit = \l p -> g (limit f l (self p)) , join = \j pe lp lp' -> g (join f j pe (fmap self lp) (fmap self lp')) , semijoin = \j p1 p2 -> g (semijoin f j (self p1) (self p2)) , exists = \s p -> g (exists f s (self p)) , values = \ss nel -> g (values f ss nel) , binary = \bo (p1, p2) -> g (binary f bo (self p1, self p2)) , label = \l p -> g (label f l (self p)) , relExpr = \pe bs -> g (relExpr f pe bs) , rebind = \s bs p -> g (rebind f s bs (self p)) , forUpdate = \p -> g (forUpdate f (self p)) , with = \r s ss p1 p2 -> g (with f r s ss (self p1) (self p2)) } applyPrimQueryFoldF :: PrimQueryFoldP a (PrimQuery' a) p -> PrimQuery' a -> p applyPrimQueryFoldF f = \case Unit -> unit f Empty a -> empty f a BaseTable ti syms -> baseTable f ti syms Product qs pes -> product f qs pes Aggregate aggrs q -> aggregate f aggrs q Window wndws q -> window f wndws q DistinctOnOrderBy dxs oxs q -> distinctOnOrderBy f dxs oxs q Limit op q -> limit f op q Join j cond q1 q2 -> join f j cond q1 q2 Semijoin j q1 q2 -> semijoin f j q1 q2 Values ss pes -> values f ss pes Binary binop (q1, q2) -> binary f binop (q1, q2) Label l pq -> label f l pq RelExpr pe syms -> relExpr f pe syms Exists s q -> exists f s q Rebind star pes q -> rebind f star pes q ForUpdate q -> forUpdate f q With recursive name cols a b -> with f recursive name cols a b primQueryFoldF :: PrimQueryFoldP a p p' -> (PrimQuery' a -> p) -> PrimQuery' a -> p' primQueryFoldF g self = applyPrimQueryFoldF (dimapPrimQueryFold self id g) foldPrimQuery :: PrimQueryFold' a p -> PrimQuery' a -> p foldPrimQuery f = fix (primQueryFoldF f) where fix g = let x = g x in x -- Would be nice to show that this is associative composePrimQueryFold :: PrimQueryFoldP a (PrimQuery' a) q -> PrimQueryFoldP a p (PrimQuery' a) -> PrimQueryFoldP a p q composePrimQueryFold = fmapPrimQueryFold . applyPrimQueryFoldF where fmapPrimQueryFold = dimapPrimQueryFold id times :: Lateral -> PrimQuery -> PrimQuery -> PrimQuery times lat q q' = Product (pure q NEL.:| [(lat, q')]) [] restrict :: HPQ.PrimExpr -> PrimQuery -> PrimQuery restrict cond primQ = Product (return (pure primQ)) [cond] isUnit :: PrimQuery' a -> Bool isUnit Unit = True isUnit _ = False
null
https://raw.githubusercontent.com/tomjaguarpaw/haskell-opaleye/3046bc6cc544d5fb02c74f07dbb9796e777ac874/src/Opaleye/Internal/PrimQuery.hs
haskell
The function 'Lateral -> PrimQuery -> PrimQuery' represents a select arrow in the following way: Lateral -- ^ Whether to join me laterally -> PrimQuery -- ^ The query that I will be joined after. If I refer to columns -- in here in a way that is only valid when I am joined laterally, -- then Lateral must be passed in as the argument above. -> PrimQuery -- ^ The result after joining me wouldn't we do that? Because we don't want to generate lateral subqueries if they are not needed; it might have performance implications. Even though there is good evidence that it *doesn't* have performance implications want to be cautious. Not every function of type `Lateral -> PrimQuery -> PrimQuery` is satisfy for validity is q == lateral (aProduct (toPrimQuery q) where == is observable equivalence, i.e. both queries must give the same results when combined with other queries and then run. We use a 'NEL.NonEmpty' for Product because otherwise we'd have to check for emptiness explicitly in the SQL generation phase. The type parameter 'a' is used to control whether the 'Empty' constructor can appear. If 'a' = '()' then it can appear. If 'a' = 'Void' then it cannot. When we create queries it is more convenient to allow 'Empty', but it is hard to represent 'Empty' in SQL so we remove it in 'Optimize' and set 'a = Void'. | The subqueries to take the product of and the restrictions to apply clauses. In order to represent valid SQL only, present, preceding any in the provided list. See 'Opaleye.Internal.Sql.distinctOnOrderBy'. We may support more locking clauses than just -select.html#SQL-FOR-UPDATE-SHARE ^ A relation-valued expression Would be nice to show that this is associative
# LANGUAGE LambdaCase # module Opaleye.Internal.PrimQuery where import Prelude hiding (product) import qualified Data.List.NonEmpty as NEL import Data.Semigroup (Semigroup, (<>)) import qualified Opaleye.Internal.HaskellDB.Sql as HSql import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import Opaleye.Internal.HaskellDB.PrimQuery (Symbol) data LimitOp = LimitOp Int | OffsetOp Int | LimitOffsetOp Int Int deriving Show data BinOp = Except | ExceptAll | Union | UnionAll | Intersect | IntersectAll deriving Show data JoinType = LeftJoin | RightJoin | FullJoin deriving Show data SemijoinType = Semi | Anti deriving Show data TableIdentifier = TableIdentifier { tiSchemaName :: Maybe String , tiTableName :: String } deriving Show tiToSqlTable :: TableIdentifier -> HSql.SqlTable tiToSqlTable ti = HSql.SqlTable { HSql.sqlTableSchemaName = tiSchemaName ti , HSql.sqlTableName = tiTableName ti } type Bindings a = [(Symbol, a)] data Lateral = NonLateral | Lateral deriving Show instance Semigroup Lateral where NonLateral <> NonLateral = NonLateral _ <> _ = Lateral instance Monoid Lateral where mappend = (<>) mempty = NonLateral data Recursive = NonRecursive | Recursive deriving Show aLeftJoin :: HPQ.PrimExpr -> PrimQuery -> PrimQueryArr aLeftJoin cond primQuery' = PrimQueryArr $ \lat primQueryL -> Join LeftJoin cond (NonLateral, primQueryL) (lat, primQuery') aProduct :: PrimQuery -> PrimQueryArr aProduct pq = PrimQueryArr (\lat primQuery -> times lat primQuery pq) aSemijoin :: SemijoinType -> PrimQuery -> PrimQueryArr aSemijoin joint existsQ = PrimQueryArr $ \_ primQ -> Semijoin joint primQ existsQ aRebind :: Bindings HPQ.PrimExpr -> PrimQueryArr aRebind bindings = PrimQueryArr $ \_ -> Rebind True bindings aRestrict :: HPQ.PrimExpr -> PrimQueryArr aRestrict predicate = PrimQueryArr $ \_ -> restrict predicate aLabel :: String -> PrimQueryArr aLabel l = PrimQueryArr $ \_ primQ -> Label l primQ It is * always * valid to pass Lateral as the first argument . So why ( ) we still valid to be a PrimQuery . I think the condition that they must newtype PrimQueryArr = PrimQueryArr { runPrimQueryArr :: Lateral -> PrimQuery -> PrimQuery } instance Semigroup PrimQueryArr where PrimQueryArr f1 <> PrimQueryArr f2 = PrimQueryArr (\lat -> f2 lat . f1 lat) instance Monoid PrimQueryArr where mappend = (<>) mempty = PrimQueryArr (\_ -> id) lateral :: PrimQueryArr -> PrimQueryArr lateral (PrimQueryArr pq) = PrimQueryArr (\_ -> pq Lateral) toPrimQuery :: PrimQueryArr -> PrimQuery toPrimQuery (PrimQueryArr f) = f NonLateral Unit data PrimQuery' a = Unit Remove the Empty constructor in 0.10 | Empty a | BaseTable TableIdentifier (Bindings HPQ.PrimExpr) | Product (NEL.NonEmpty (Lateral, PrimQuery' a)) [HPQ.PrimExpr] | Aggregate (Bindings (Maybe (HPQ.AggrOp, [HPQ.OrderExpr], HPQ.AggrDistinct), HPQ.Symbol)) (PrimQuery' a) | Window (Bindings (HPQ.WndwOp, HPQ.Partition)) (PrimQuery' a) | Represents both @DISTINCT ON@ and @ORDER BY@ @DISTINCT ON@ expressions are always interpreted as the first @ORDER BY@s when | DistinctOnOrderBy (Maybe (NEL.NonEmpty HPQ.PrimExpr)) [HPQ.OrderExpr] (PrimQuery' a) | Limit LimitOp (PrimQuery' a) | Join JoinType HPQ.PrimExpr (Lateral, PrimQuery' a) (Lateral, PrimQuery' a) | Semijoin SemijoinType (PrimQuery' a) (PrimQuery' a) | Exists Symbol (PrimQuery' a) | Values [Symbol] (NEL.NonEmpty [HPQ.PrimExpr]) | Binary BinOp (PrimQuery' a, PrimQuery' a) | Label String (PrimQuery' a) | RelExpr HPQ.PrimExpr (Bindings HPQ.PrimExpr) | Rebind Bool (Bindings HPQ.PrimExpr) (PrimQuery' a) | ForUpdate (PrimQuery' a) ForUpdate in the future | With Recursive Symbol [Symbol] (PrimQuery' a) (PrimQuery' a) deriving Show type PrimQuery = PrimQuery' () type PrimQueryFold p = PrimQueryFold' () p type PrimQueryFold' a p = PrimQueryFoldP a p p data PrimQueryFoldP a p p' = PrimQueryFold { unit :: p' , empty :: a -> p' , baseTable :: TableIdentifier -> Bindings HPQ.PrimExpr -> p' , product :: NEL.NonEmpty (Lateral, p) -> [HPQ.PrimExpr] -> p' , aggregate :: Bindings (Maybe (HPQ.AggrOp, [HPQ.OrderExpr], HPQ.AggrDistinct), HPQ.Symbol) -> p -> p' , window :: Bindings (HPQ.WndwOp, HPQ.Partition) -> p -> p' , distinctOnOrderBy :: Maybe (NEL.NonEmpty HPQ.PrimExpr) -> [HPQ.OrderExpr] -> p -> p' , limit :: LimitOp -> p -> p' , join :: JoinType -> HPQ.PrimExpr -> (Lateral, p) -> (Lateral, p) -> p' , semijoin :: SemijoinType -> p -> p -> p' , exists :: Symbol -> p -> p' , values :: [Symbol] -> NEL.NonEmpty [HPQ.PrimExpr] -> p' , binary :: BinOp -> (p, p) -> p' , label :: String -> p -> p' , relExpr :: HPQ.PrimExpr -> Bindings HPQ.PrimExpr -> p' , rebind :: Bool -> Bindings HPQ.PrimExpr -> p -> p' , forUpdate :: p -> p' , with :: Recursive -> Symbol -> [Symbol] -> p -> p -> p' } primQueryFoldDefault :: PrimQueryFold' a (PrimQuery' a) primQueryFoldDefault = PrimQueryFold { unit = Unit , empty = Empty , baseTable = BaseTable , product = Product , aggregate = Aggregate , window = Window , distinctOnOrderBy = DistinctOnOrderBy , limit = Limit , join = Join , semijoin = Semijoin , values = Values , binary = Binary , label = Label , relExpr = RelExpr , exists = Exists , rebind = Rebind , forUpdate = ForUpdate , with = With } dimapPrimQueryFold :: (q -> p) -> (p' -> q') -> PrimQueryFoldP a p p' -> PrimQueryFoldP a q q' dimapPrimQueryFold self g f = PrimQueryFold { unit = g (unit f) , empty = g . empty f , baseTable = \ti bs -> g (baseTable f ti bs) , product = \ps conds -> g (product f ((fmap . fmap) self ps) conds) , aggregate = \b p -> g (aggregate f b (self p)) , window = \b p -> g (window f b (self p)) , distinctOnOrderBy = \m os p -> g (distinctOnOrderBy f m os (self p)) , limit = \l p -> g (limit f l (self p)) , join = \j pe lp lp' -> g (join f j pe (fmap self lp) (fmap self lp')) , semijoin = \j p1 p2 -> g (semijoin f j (self p1) (self p2)) , exists = \s p -> g (exists f s (self p)) , values = \ss nel -> g (values f ss nel) , binary = \bo (p1, p2) -> g (binary f bo (self p1, self p2)) , label = \l p -> g (label f l (self p)) , relExpr = \pe bs -> g (relExpr f pe bs) , rebind = \s bs p -> g (rebind f s bs (self p)) , forUpdate = \p -> g (forUpdate f (self p)) , with = \r s ss p1 p2 -> g (with f r s ss (self p1) (self p2)) } applyPrimQueryFoldF :: PrimQueryFoldP a (PrimQuery' a) p -> PrimQuery' a -> p applyPrimQueryFoldF f = \case Unit -> unit f Empty a -> empty f a BaseTable ti syms -> baseTable f ti syms Product qs pes -> product f qs pes Aggregate aggrs q -> aggregate f aggrs q Window wndws q -> window f wndws q DistinctOnOrderBy dxs oxs q -> distinctOnOrderBy f dxs oxs q Limit op q -> limit f op q Join j cond q1 q2 -> join f j cond q1 q2 Semijoin j q1 q2 -> semijoin f j q1 q2 Values ss pes -> values f ss pes Binary binop (q1, q2) -> binary f binop (q1, q2) Label l pq -> label f l pq RelExpr pe syms -> relExpr f pe syms Exists s q -> exists f s q Rebind star pes q -> rebind f star pes q ForUpdate q -> forUpdate f q With recursive name cols a b -> with f recursive name cols a b primQueryFoldF :: PrimQueryFoldP a p p' -> (PrimQuery' a -> p) -> PrimQuery' a -> p' primQueryFoldF g self = applyPrimQueryFoldF (dimapPrimQueryFold self id g) foldPrimQuery :: PrimQueryFold' a p -> PrimQuery' a -> p foldPrimQuery f = fix (primQueryFoldF f) where fix g = let x = g x in x composePrimQueryFold :: PrimQueryFoldP a (PrimQuery' a) q -> PrimQueryFoldP a p (PrimQuery' a) -> PrimQueryFoldP a p q composePrimQueryFold = fmapPrimQueryFold . applyPrimQueryFoldF where fmapPrimQueryFold = dimapPrimQueryFold id times :: Lateral -> PrimQuery -> PrimQuery -> PrimQuery times lat q q' = Product (pure q NEL.:| [(lat, q')]) [] restrict :: HPQ.PrimExpr -> PrimQuery -> PrimQuery restrict cond primQ = Product (return (pure primQ)) [cond] isUnit :: PrimQuery' a -> Bool isUnit Unit = True isUnit _ = False
319d22c341141e94c0cbdf4d83ac16c3044ae78ddd3e26f0ce383c8cd9799c0a
Verites/verigraph
Partition.hs
module Data.Partition ( EquivalenceClass , Partition , discretePartition , fromBlocks , partitionToSurjection , pickRepresentatives , allPartitionsOf , allRefinementsOf , addToPartition , mergePairs , mergeSets , getElem , getTail , tsort ) where import Data.Foldable (find, foldl') import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set -- | An equivalence class is just a set of elements. type EquivalenceClass a = Set a -- | A partition is a set of disjoint equivalence classes. type Partition a = Set (EquivalenceClass a) -- | Create the discrete partition of the given set, i.e. the most disjoint partition. In this -- partition, each element has its own equivalence class. discretePartition :: (Ord a) => [a] -> Partition a discretePartition = Set.fromList . map Set.singleton -- | Given a list of disjoint blocks, represented as lists of elements, create a partition. -- If the given blocks are not disjoint, creates a malformed partition. fromBlocks :: (Ord a) => [[a]] -> Partition a fromBlocks = Set.fromList . map Set.fromList -- | Obtain a surjective mapping that maps every element of the partitioned set to the -- representative of its equivalence class, given a function to select representatives. partitionToSurjection :: Ord a => Partition a -> (EquivalenceClass a -> b) -> Map a b partitionToSurjection partition pickRepresentative = Map.fromList [ (element, representative) | equivalenceClass <- Set.toList partition , let representative = pickRepresentative equivalenceClass , element <- Set.toList equivalenceClass ] -- | Given a partition, pick a representative for each equivalence class using the given function. pickRepresentatives :: Partition a -> (EquivalenceClass a -> b) -> [([a], b)] pickRepresentatives partition pickRepresentative = [ (Set.toList equivalenceClass, representative) | equivalenceClass <- Set.toList partition , let representative = pickRepresentative equivalenceClass ] -- | Create all partitions of the given set with a naive algorithm. allPartitionsOf :: Ord a => [a] -> [Partition a] allPartitionsOf [] = [Set.empty] allPartitionsOf [x] = [Set.singleton (Set.singleton x)] allPartitionsOf (x:xs) = concatMap (addToPartition x) (allPartitionsOf xs) -- | Insert an element that was not a member of the original set into the partition. It may be inserted -- into any existing block or as its own separate block. addToPartition :: Ord a => a -> Partition a -> [Partition a] addToPartition element partition = [ Set.fromList (insertAtBlock i element blocks) | i <- [0 .. length blocks] ] where blocks = Set.toList partition insertAtBlock _ x [] = [Set.singleton x] insertAtBlock 0 x (b:bs) = Set.insert x b : bs insertAtBlock i x (b:bs) = b : insertAtBlock (i-1) x bs -- | Create all refinements of the given partition, i.e. all partitions with more distinctions but -- no more identifications, or all ways to partition each block of the original partition. allRefinementsOf :: Ord a => Partition a -> [Partition a] allRefinementsOf partition = do let partitionsByBlock = [ allPartitionsOf (Set.toList block) | block <- Set.toList partition ] disjointPartitions <- naryProduct partitionsByBlock return (Set.unions disjointPartitions) | Calculates the cartesion product of @n@ lists , interpreting them as sets . naryProduct :: [[a]] -> [[a]] naryProduct [] = [[]] naryProduct (l:ls) = [ element : tuple | tuple <- naryProduct ls, element <- l] -- | Given a list of pairs of elements that should belong to the same equivalence class, "collapse" -- the necessary equivalence classes of the partition. mergePairs :: (Ord a, Show a) => [(a, a)] -> Partition a -> Partition a mergePairs toBeGlued partition = foldl' (flip merge) partition toBeGlued where merge (e1, e2) s = mergeEquivalences (e1, e2) s `Set.union` (s `diff` (e1,e2)) diff s (e1, e2) = if e1 == e2 then Set.delete (findEquivalenceClass e1 s) s else Set.delete (findEquivalenceClass e1 s) . Set.delete (findEquivalenceClass e2 s) $ s -- | Given a list of sets of elements that should belong to the same equivalence class, "collapse" -- the necessary equivalence classes of the partition. mergeSets :: (Ord a, Show a) => [Set a] -> Partition a -> Partition a mergeSets toBeGlued partition = foldl' (flip merge) partition toBeGlued where merge eq s = mergeNEquivalences eq s `Set.union` diffNEquivalences eq s diffNEquivalences :: (Ord a, Show a) => Set a -> Partition a -> Partition a diffNEquivalences eq set = actualDiff allSubSets where actualDiff = Set.foldl Set.difference set allSubSets = Set.map newFind eq newFind = Set.singleton . (`findEquivalenceClass` set) mergeNEquivalences :: (Ord a, Show a) => Set a -> Partition a -> Partition a mergeNEquivalences eq set = Set.singleton $ actualMerge allSubSets where actualMerge = Set.foldl Set.union Set.empty allSubSets = Set.map (`findEquivalenceClass` set) eq getElem :: Set a -> a getElem = Set.elemAt 0 getUnitSubset :: Set a -> Set a getUnitSubset set = Set.singleton (getElem set) getTail :: (Ord a) => Set a -> Set a getTail set = set `Set.difference` getUnitSubset set mergeEquivalences :: (Ord a, Show a) => (a, a) -> Partition a -> Partition a mergeEquivalences (e1,e2) set = Set.singleton (findEquivalenceClass e1 set `Set.union` findEquivalenceClass e2 set) -- works only with non-empty sets findEquivalenceClass :: (Eq a, Show a) => a -> Partition a -> EquivalenceClass a findEquivalenceClass element set | Set.null domain = error $ "could not find equivalence class for " ++ show element ++ " in " ++ show set | otherwise = getElem domain where domain = Set.filter (element `elem`) set type PairsRelation a = Set (a,a) elementInImage :: Ord a => PairsRelation a -> a -> PairsRelation a elementInImage rel item = Set.filter ((== item) . snd) rel elementNotInDomain :: Ord a => PairsRelation a -> a -> PairsRelation a elementNotInDomain rel item = Set.filter ((/= item) . fst) rel noIncoming :: Ord a => PairsRelation a -> Set a -> Maybe a noIncoming rel = find (null . elementInImage rel) isCyclic :: Ord a => PairsRelation a -> Bool isCyclic = not . null . until (\rel -> removeOneItem rel == rel) removeOneItem where removeOneItem rel = maybe rel (elementNotInDomain rel) . noIncoming rel $ relationDomain rel relationDomain = Set.map fst tsort :: Ord a => PairsRelation a -> Set a -> Maybe [a] tsort rel disconnected = let items = relationElements rel `Set.union` disconnected in if isCyclic rel then Nothing else Just $ buildOrdering rel items relationElements :: Ord a => PairsRelation a -> Set a relationElements = foldr (\(x,y) -> Set.insert x . Set.insert y) Set.empty buildOrdering :: Ord a => PairsRelation a -> Set a -> [a] buildOrdering relation items = maybe [] addToOrderRemoveFromRelation $ noIncoming relation items where addToOrderRemoveFromRelation i = i : buildOrdering (elementNotInDomain relation i) (Set.delete i items)
null
https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/src/library/Data/Partition.hs
haskell
| An equivalence class is just a set of elements. | A partition is a set of disjoint equivalence classes. | Create the discrete partition of the given set, i.e. the most disjoint partition. In this partition, each element has its own equivalence class. | Given a list of disjoint blocks, represented as lists of elements, create a partition. If the given blocks are not disjoint, creates a malformed partition. | Obtain a surjective mapping that maps every element of the partitioned set to the representative of its equivalence class, given a function to select representatives. | Given a partition, pick a representative for each equivalence class using the given function. | Create all partitions of the given set with a naive algorithm. | Insert an element that was not a member of the original set into the partition. It may be inserted into any existing block or as its own separate block. | Create all refinements of the given partition, i.e. all partitions with more distinctions but no more identifications, or all ways to partition each block of the original partition. | Given a list of pairs of elements that should belong to the same equivalence class, "collapse" the necessary equivalence classes of the partition. | Given a list of sets of elements that should belong to the same equivalence class, "collapse" the necessary equivalence classes of the partition. works only with non-empty sets
module Data.Partition ( EquivalenceClass , Partition , discretePartition , fromBlocks , partitionToSurjection , pickRepresentatives , allPartitionsOf , allRefinementsOf , addToPartition , mergePairs , mergeSets , getElem , getTail , tsort ) where import Data.Foldable (find, foldl') import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set type EquivalenceClass a = Set a type Partition a = Set (EquivalenceClass a) discretePartition :: (Ord a) => [a] -> Partition a discretePartition = Set.fromList . map Set.singleton fromBlocks :: (Ord a) => [[a]] -> Partition a fromBlocks = Set.fromList . map Set.fromList partitionToSurjection :: Ord a => Partition a -> (EquivalenceClass a -> b) -> Map a b partitionToSurjection partition pickRepresentative = Map.fromList [ (element, representative) | equivalenceClass <- Set.toList partition , let representative = pickRepresentative equivalenceClass , element <- Set.toList equivalenceClass ] pickRepresentatives :: Partition a -> (EquivalenceClass a -> b) -> [([a], b)] pickRepresentatives partition pickRepresentative = [ (Set.toList equivalenceClass, representative) | equivalenceClass <- Set.toList partition , let representative = pickRepresentative equivalenceClass ] allPartitionsOf :: Ord a => [a] -> [Partition a] allPartitionsOf [] = [Set.empty] allPartitionsOf [x] = [Set.singleton (Set.singleton x)] allPartitionsOf (x:xs) = concatMap (addToPartition x) (allPartitionsOf xs) addToPartition :: Ord a => a -> Partition a -> [Partition a] addToPartition element partition = [ Set.fromList (insertAtBlock i element blocks) | i <- [0 .. length blocks] ] where blocks = Set.toList partition insertAtBlock _ x [] = [Set.singleton x] insertAtBlock 0 x (b:bs) = Set.insert x b : bs insertAtBlock i x (b:bs) = b : insertAtBlock (i-1) x bs allRefinementsOf :: Ord a => Partition a -> [Partition a] allRefinementsOf partition = do let partitionsByBlock = [ allPartitionsOf (Set.toList block) | block <- Set.toList partition ] disjointPartitions <- naryProduct partitionsByBlock return (Set.unions disjointPartitions) | Calculates the cartesion product of @n@ lists , interpreting them as sets . naryProduct :: [[a]] -> [[a]] naryProduct [] = [[]] naryProduct (l:ls) = [ element : tuple | tuple <- naryProduct ls, element <- l] mergePairs :: (Ord a, Show a) => [(a, a)] -> Partition a -> Partition a mergePairs toBeGlued partition = foldl' (flip merge) partition toBeGlued where merge (e1, e2) s = mergeEquivalences (e1, e2) s `Set.union` (s `diff` (e1,e2)) diff s (e1, e2) = if e1 == e2 then Set.delete (findEquivalenceClass e1 s) s else Set.delete (findEquivalenceClass e1 s) . Set.delete (findEquivalenceClass e2 s) $ s mergeSets :: (Ord a, Show a) => [Set a] -> Partition a -> Partition a mergeSets toBeGlued partition = foldl' (flip merge) partition toBeGlued where merge eq s = mergeNEquivalences eq s `Set.union` diffNEquivalences eq s diffNEquivalences :: (Ord a, Show a) => Set a -> Partition a -> Partition a diffNEquivalences eq set = actualDiff allSubSets where actualDiff = Set.foldl Set.difference set allSubSets = Set.map newFind eq newFind = Set.singleton . (`findEquivalenceClass` set) mergeNEquivalences :: (Ord a, Show a) => Set a -> Partition a -> Partition a mergeNEquivalences eq set = Set.singleton $ actualMerge allSubSets where actualMerge = Set.foldl Set.union Set.empty allSubSets = Set.map (`findEquivalenceClass` set) eq getElem :: Set a -> a getElem = Set.elemAt 0 getUnitSubset :: Set a -> Set a getUnitSubset set = Set.singleton (getElem set) getTail :: (Ord a) => Set a -> Set a getTail set = set `Set.difference` getUnitSubset set mergeEquivalences :: (Ord a, Show a) => (a, a) -> Partition a -> Partition a mergeEquivalences (e1,e2) set = Set.singleton (findEquivalenceClass e1 set `Set.union` findEquivalenceClass e2 set) findEquivalenceClass :: (Eq a, Show a) => a -> Partition a -> EquivalenceClass a findEquivalenceClass element set | Set.null domain = error $ "could not find equivalence class for " ++ show element ++ " in " ++ show set | otherwise = getElem domain where domain = Set.filter (element `elem`) set type PairsRelation a = Set (a,a) elementInImage :: Ord a => PairsRelation a -> a -> PairsRelation a elementInImage rel item = Set.filter ((== item) . snd) rel elementNotInDomain :: Ord a => PairsRelation a -> a -> PairsRelation a elementNotInDomain rel item = Set.filter ((/= item) . fst) rel noIncoming :: Ord a => PairsRelation a -> Set a -> Maybe a noIncoming rel = find (null . elementInImage rel) isCyclic :: Ord a => PairsRelation a -> Bool isCyclic = not . null . until (\rel -> removeOneItem rel == rel) removeOneItem where removeOneItem rel = maybe rel (elementNotInDomain rel) . noIncoming rel $ relationDomain rel relationDomain = Set.map fst tsort :: Ord a => PairsRelation a -> Set a -> Maybe [a] tsort rel disconnected = let items = relationElements rel `Set.union` disconnected in if isCyclic rel then Nothing else Just $ buildOrdering rel items relationElements :: Ord a => PairsRelation a -> Set a relationElements = foldr (\(x,y) -> Set.insert x . Set.insert y) Set.empty buildOrdering :: Ord a => PairsRelation a -> Set a -> [a] buildOrdering relation items = maybe [] addToOrderRemoveFromRelation $ noIncoming relation items where addToOrderRemoveFromRelation i = i : buildOrdering (elementNotInDomain relation i) (Set.delete i items)
5d94ebf0e8a85fd6aa5a5a2aa71610511f9f4e47d177979feb3224d95f4cc57f
ryanpbrewster/haskell
LetWhereScope.hs
foo x = let y = 2*x in bar y -- where bar z = y*x (does not compile, y is not in scope) where bar z = x*z
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/hello-world/LetWhereScope.hs
haskell
where bar z = y*x (does not compile, y is not in scope)
foo x = let y = 2*x in bar y where bar z = x*z
7ddaa3669581ec968ab943c84198281318930e096029ab9c9ca5044495f68649
rudymatela/speculate
Timeout.hs
-- | -- Module : Test.Speculate.Utils.Timeout Copyright : ( c ) 2016 - 2019 License : 3 - Clause BSD ( see the file LICENSE ) Maintainer : < > -- -- This module is part of Speculate. -- Evaluate values to WHNF until a timeout . module Test.Speculate.Utils.Timeout ( timeoutToNothing , fromTimeout , timeoutToFalse , timeoutToTrue , timeoutToError ) where import System.IO.Unsafe (unsafePerformIO) import Control.Exception (evaluate) import System.Timeout import Data.Maybe (fromMaybe) TODO : Move this into LeanCheck ? -- | In microseconds usTimeoutToNothing :: Int -> a -> Maybe a usTimeoutToNothing n = unsafePerformIO . timeout n . evaluate | Returns Nothing if value can not be evaluated to WHNF in a given number of seconds timeoutToNothing :: RealFrac s => s -> a -> Maybe a timeoutToNothing n = usTimeoutToNothing $ round (n * 1000000) fromTimeout :: RealFrac s => s -> a -> a -> a fromTimeout n x = fromMaybe x . timeoutToNothing n timeoutToFalse :: RealFrac s => s -> Bool -> Bool timeoutToFalse n = fromTimeout n False timeoutToTrue :: RealFrac s => s -> Bool -> Bool timeoutToTrue n = fromTimeout n True timeoutToError :: RealFrac s => s -> a -> a timeoutToError n = fromTimeout n (error "timeoutToError: timed out")
null
https://raw.githubusercontent.com/rudymatela/speculate/8ec39747d03033db4349d554467d4b78bb72935d/src/Test/Speculate/Utils/Timeout.hs
haskell
| Module : Test.Speculate.Utils.Timeout This module is part of Speculate. | In microseconds
Copyright : ( c ) 2016 - 2019 License : 3 - Clause BSD ( see the file LICENSE ) Maintainer : < > Evaluate values to WHNF until a timeout . module Test.Speculate.Utils.Timeout ( timeoutToNothing , fromTimeout , timeoutToFalse , timeoutToTrue , timeoutToError ) where import System.IO.Unsafe (unsafePerformIO) import Control.Exception (evaluate) import System.Timeout import Data.Maybe (fromMaybe) TODO : Move this into LeanCheck ? usTimeoutToNothing :: Int -> a -> Maybe a usTimeoutToNothing n = unsafePerformIO . timeout n . evaluate | Returns Nothing if value can not be evaluated to WHNF in a given number of seconds timeoutToNothing :: RealFrac s => s -> a -> Maybe a timeoutToNothing n = usTimeoutToNothing $ round (n * 1000000) fromTimeout :: RealFrac s => s -> a -> a -> a fromTimeout n x = fromMaybe x . timeoutToNothing n timeoutToFalse :: RealFrac s => s -> Bool -> Bool timeoutToFalse n = fromTimeout n False timeoutToTrue :: RealFrac s => s -> Bool -> Bool timeoutToTrue n = fromTimeout n True timeoutToError :: RealFrac s => s -> a -> a timeoutToError n = fromTimeout n (error "timeoutToError: timed out")
8f49b7ab49d8a5937f07bddafa0886353bc6e4ffc5bfb8385349cff579afc389
amalloy/aoc-2021
Main.hs
module Main where import Control.Arrow ((&&&)) import Data.Array import Data.Char (digitToInt) data Octopus = Exhausted | Energized | Latent Int deriving (Eq, Show) type Cave = Array (Int, Int) Octopus type Input = Cave addEnergy :: Int -> Octopus -> Octopus addEnergy a o = case o of Latent b | a + b >= 10 -> Energized | otherwise -> Latent (a + b) _ -> o step :: Cave -> (Cave, Int) step c = let c' = fmap (addEnergy 1) c completed = complete c' numFlashes = length . filter (== Exhausted) . elems $ completed c'' = fmap revitalize completed in (c'', numFlashes) where revitalize Exhausted = Latent 0 revitalize x = x complete :: Cave -> Cave complete c = case [i | (i, Energized) <- assocs c] of [] -> c energized -> let bs = bounds c recipients = filter (inRange bs) $ neighbors =<< energized collateral = [(i, addEnergy 1) | i <- recipients] changes = [(i, const Exhausted) | i <- energized] ++ collateral c' = accum (\o f -> f o) c changes in complete c' neighbors :: (Int, Int) -> [(Int, Int)] neighbors (x, y) = do dx <- [0, 1, -1] dy <- [0, 1, -1] pure (x + dx, y + dy) part1 :: Input -> Int part1 = runCave 100 0 where runCave 0 flashes _ = flashes runCave steps flashes c = runCave (steps - 1) (fs + flashes) c' where (c', fs) = step c part2 :: Input -> Int part2 cave = go cave where n = rangeSize $ bounds cave go c = case step c of (c', f) | f == n -> 1 | otherwise -> succ $ go c' prepare :: String -> Input prepare s = let rows = lines s bounds = ((0, 0), (length rows - 1, length (head rows) - 1)) octopi = (Latent . digitToInt) <$> concat rows in listArray bounds octopi main :: IO () main = readFile "input.txt" >>= print . (part1 &&& part2) . prepare
null
https://raw.githubusercontent.com/amalloy/aoc-2021/b46506baa52e3a4c8a122fda8019c1103957371a/day11/src/Main.hs
haskell
module Main where import Control.Arrow ((&&&)) import Data.Array import Data.Char (digitToInt) data Octopus = Exhausted | Energized | Latent Int deriving (Eq, Show) type Cave = Array (Int, Int) Octopus type Input = Cave addEnergy :: Int -> Octopus -> Octopus addEnergy a o = case o of Latent b | a + b >= 10 -> Energized | otherwise -> Latent (a + b) _ -> o step :: Cave -> (Cave, Int) step c = let c' = fmap (addEnergy 1) c completed = complete c' numFlashes = length . filter (== Exhausted) . elems $ completed c'' = fmap revitalize completed in (c'', numFlashes) where revitalize Exhausted = Latent 0 revitalize x = x complete :: Cave -> Cave complete c = case [i | (i, Energized) <- assocs c] of [] -> c energized -> let bs = bounds c recipients = filter (inRange bs) $ neighbors =<< energized collateral = [(i, addEnergy 1) | i <- recipients] changes = [(i, const Exhausted) | i <- energized] ++ collateral c' = accum (\o f -> f o) c changes in complete c' neighbors :: (Int, Int) -> [(Int, Int)] neighbors (x, y) = do dx <- [0, 1, -1] dy <- [0, 1, -1] pure (x + dx, y + dy) part1 :: Input -> Int part1 = runCave 100 0 where runCave 0 flashes _ = flashes runCave steps flashes c = runCave (steps - 1) (fs + flashes) c' where (c', fs) = step c part2 :: Input -> Int part2 cave = go cave where n = rangeSize $ bounds cave go c = case step c of (c', f) | f == n -> 1 | otherwise -> succ $ go c' prepare :: String -> Input prepare s = let rows = lines s bounds = ((0, 0), (length rows - 1, length (head rows) - 1)) octopi = (Latent . digitToInt) <$> concat rows in listArray bounds octopi main :: IO () main = readFile "input.txt" >>= print . (part1 &&& part2) . prepare
f856b2bcaa440fdc62a60d7e1d27875fc1eaf4407f290b68e3b2aa5f87d12617
janestreet/base
word_size.ml
open! Import module Sys = Sys0 type t = | W32 | W64 [@@deriving_inline sexp_of] let sexp_of_t = (function | W32 -> Sexplib0.Sexp.Atom "W32" | W64 -> Sexplib0.Sexp.Atom "W64" : t -> Sexplib0.Sexp.t) ;; [@@@end] let num_bits = function | W32 -> 32 | W64 -> 64 ;; let word_size = match Sys.word_size_in_bits with | 32 -> W32 | 64 -> W64 | _ -> failwith "unknown word size" ;;
null
https://raw.githubusercontent.com/janestreet/base/c95422a6b5d5dba29c51df3e37b8f50eaff6ad68/src/word_size.ml
ocaml
open! Import module Sys = Sys0 type t = | W32 | W64 [@@deriving_inline sexp_of] let sexp_of_t = (function | W32 -> Sexplib0.Sexp.Atom "W32" | W64 -> Sexplib0.Sexp.Atom "W64" : t -> Sexplib0.Sexp.t) ;; [@@@end] let num_bits = function | W32 -> 32 | W64 -> 64 ;; let word_size = match Sys.word_size_in_bits with | 32 -> W32 | 64 -> W64 | _ -> failwith "unknown word size" ;;
c72a433ee5bb7e9626e6a1d4b6e0fdf30f27277d46faa8f2d6e5783c013685f9
RBornat/jape
runproof.mli
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Jape 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 jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) open Cxttype open Sequent open Forcedef open Japeenv open Name open Paraparam open Proofstage open Proofstate open Proviso open Tactictype val proofsdone : bool ref val mkstate : visproviso list -> seq list -> prooftree -> proofstate val startstate : japeenv -> visproviso list -> seq list -> seq -> proofstate val addproof : (string list -> unit) -> (string list * string * string * int -> bool) -> name -> bool -> proofstate -> bool -> (seq * model) option -> bool val doProof : (string list -> unit) -> (string list * string * string * int -> bool) -> japeenv -> name -> proofstage -> seq -> paraparam list * seq list * proviso list * tactic -> (seq * model) option -> (name * proofstate * (seq * model) option) option val runprooftracing : bool ref
null
https://raw.githubusercontent.com/RBornat/jape/1f757680878527eebd04919f00bfb18a9b41bdf2/distrib/camlengine/runproof.mli
ocaml
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Jape 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 jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) open Cxttype open Sequent open Forcedef open Japeenv open Name open Paraparam open Proofstage open Proofstate open Proviso open Tactictype val proofsdone : bool ref val mkstate : visproviso list -> seq list -> prooftree -> proofstate val startstate : japeenv -> visproviso list -> seq list -> seq -> proofstate val addproof : (string list -> unit) -> (string list * string * string * int -> bool) -> name -> bool -> proofstate -> bool -> (seq * model) option -> bool val doProof : (string list -> unit) -> (string list * string * string * int -> bool) -> japeenv -> name -> proofstage -> seq -> paraparam list * seq list * proviso list * tactic -> (seq * model) option -> (name * proofstate * (seq * model) option) option val runprooftracing : bool ref
c37a0cda24ccbb4861510809437406b8c74f94a786437d26a4ba27b56ed4499c
biocad/openapi3
Validation.hs
{-# OPTIONS_GHC -Wall #-} # LANGUAGE CPP # {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # {-# LANGUAGE GADTs #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE PackageImports #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} # LANGUAGE ViewPatterns # -- | Module : Data . OpenApi . Internal . Schema . Validation Copyright : ( c ) 2015 GetShopTV License : BSD3 Maintainer : < > -- Stability: experimental -- Validate JSON values with Swagger Schema . module Data.OpenApi.Internal.Schema.Validation where import Prelude () import Prelude.Compat import Control.Applicative import Control.Lens hiding (allOf) import Control.Monad (forM, forM_, when) import Data.Aeson hiding (Result) #if MIN_VERSION_aeson(2,0,0) import qualified Data.Aeson.KeyMap as KeyMap #endif import Data.Foldable (for_, sequenceA_, traverse_) #if !MIN_VERSION_aeson(2,0,0) import Data.HashMap.Strict (HashMap) #endif import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap import qualified "unordered-containers" Data.HashSet as HashSet import Data.Maybe (fromMaybe) import Data.Proxy import Data.Scientific (Scientific, isInteger) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import Data.Vector (Vector) import qualified Data.Vector as Vector import Data.OpenApi.Aeson.Compat (hasKey, keyToText, lookupKey, objectToList) import Data.OpenApi.Declare import Data.OpenApi.Internal import Data.OpenApi.Internal.Schema import Data.OpenApi.Internal.Utils import Data.OpenApi.Lens -- $setup > > > import Data . OpenApi . Internal . Schema . Validation -- | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value. This can be used with QuickCheck to ensure those instances are coherent : -- -- prop> validateToJSON (x :: Int) == [] -- -- /NOTE:/ @'validateToJSON'@ does not perform string pattern validation. -- See @'validateToJSONWithPatternChecker'@. -- -- See 'renderValidationErrors' on how the output is structured. validatePrettyToJSON :: forall a. (ToJSON a, ToSchema a) => a -> Maybe String validatePrettyToJSON = renderValidationErrors validateToJSON -- | Variant of 'validatePrettyToJSON' with typed output. validateToJSON :: forall a. (ToJSON a, ToSchema a) => a -> [ValidationError] validateToJSON = validateToJSONWithPatternChecker (\_pattern _str -> True) -- | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value and pattern checker. This can be used with QuickCheck to ensure those instances are coherent . -- For validation without patterns see See also : -- 'renderValidationErrors'. validateToJSONWithPatternChecker :: forall a. (ToJSON a, ToSchema a) => (Pattern -> Text -> Bool) -> a -> [ValidationError] validateToJSONWithPatternChecker checker = validateJSONWithPatternChecker checker defs sch . toJSON where (defs, sch) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty -- | Pretty print validation errors -- together with actual JSON and Swagger Schema -- (using 'encodePretty'). -- > > > import Data . Aeson as Aeson -- >>> import Data.Foldable (traverse_) > > > import -- >>> data Phone = Phone { value :: String } deriving (Generic) -- >>> data Person = Person { name :: String, phone :: Phone } deriving (Generic) > > > instance ToJSON Person where toJSON p = object [ " name " .. = name p ] > > > instance Phone > > > instance Person > > > let person = Person { name = " " , phone = Phone " 123456 " } -- >>> traverse_ putStrLn $ renderValidationErrors validateToJSON person -- Validation against the schema fails: * property " phone " is required , but not found in " { \"name\":\"John\ " } " -- <BLANKLINE> -- JSON value: -- { " name " : " " -- } -- <BLANKLINE> -- Swagger Schema: -- { -- "properties": { -- "name": { -- "type": "string" -- }, -- "phone": { -- "$ref": "#/components/schemas/Phone" -- } -- }, -- "required": [ -- "name", -- "phone" -- ], -- "type": "object" -- } -- <BLANKLINE> -- Swagger Description Context: -- { -- "Phone": { -- "properties": { -- "value": { -- "type": "string" -- } -- }, -- "required": [ -- "value" -- ], -- "type": "object" -- } -- } -- <BLANKLINE> renderValidationErrors :: forall a. (ToJSON a, ToSchema a) => (a -> [ValidationError]) -> a -> Maybe String renderValidationErrors f x = case f x of [] -> Nothing errors -> Just $ unlines [ "Validation against the schema fails:" , unlines (map (" * " ++) errors) , "JSON value:" , ppJSONString (toJSON x) , "" , "Swagger Schema:" , ppJSONString (toJSON schema_) , "" , "Swagger Description Context:" , ppJSONString (toJSON refs_) ] where ppJSONString = TL.unpack . TL.decodeUtf8 . encodePretty (refs_, schema_) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty -- | Validate JSON @'Value'@ against Swagger @'Schema'@. -- prop > validateJSON mempty ( toSchema ( Proxy : : Proxy Int ) ) ( toJSON ( x : : Int ) ) = = [ ] -- -- /NOTE:/ @'validateJSON'@ does not perform string pattern validation. See @'validateJSONWithPatternChecker'@. validateJSON :: Definitions Schema -> Schema -> Value -> [ValidationError] validateJSON = validateJSONWithPatternChecker (\_pattern _str -> True) -- | Validate JSON @'Value'@ agains Swagger @'ToSchema'@ for a given value and pattern checker. -- For validation without patterns see @'validateJSON'@. validateJSONWithPatternChecker :: (Pattern -> Text -> Bool) -> Definitions Schema -> Schema -> Value -> [ValidationError] validateJSONWithPatternChecker checker defs sch js = case runValidation (validateWithSchema js) cfg sch of Failed xs -> xs Passed _ -> mempty where cfg = defaultConfig { configPatternChecker = checker , configDefinitions = defs } -- | Validation error message. type ValidationError = String -- | Validation result type. data Result a = Failed [ValidationError] -- ^ Validation failed with a list of error messages. | Passed a -- ^ Validation passed. deriving (Eq, Show, Functor) instance Applicative Result where pure = Passed Passed f <*> Passed x = Passed (f x) Failed xs <*> Failed ys = Failed (xs <> ys) Failed xs <*> _ = Failed xs _ <*> Failed ys = Failed ys instance Alternative Result where empty = Failed mempty Passed x <|> _ = Passed x _ <|> y = y instance Monad Result where return = pure Passed x >>= f = f x Failed xs >>= _ = Failed xs -- | Validation configuration. data Config = Config { -- | Pattern checker for @'_schemaPattern'@ validation. configPatternChecker :: Pattern -> Text -> Bool -- | Schema definitions in scope to resolve references. , configDefinitions :: Definitions Schema } -- | Default @'Config'@: -- -- @ -- defaultConfig = 'Config' -- { 'configPatternChecker' = \\_pattern _str -> True , ' configDefinitions ' = -- } -- @ defaultConfig :: Config defaultConfig = Config { configPatternChecker = \_pattern _str -> True , configDefinitions = mempty } -- | Value validation. newtype Validation s a = Validation { runValidation :: Config -> s -> Result a } deriving (Functor) instance Applicative (Validation schema) where pure x = Validation (\_ _ -> pure x) Validation f <*> Validation x = Validation (\c s -> f c s <*> x c s) instance Alternative (Validation schema) where empty = Validation (\_ _ -> empty) Validation x <|> Validation y = Validation (\c s -> x c s <|> y c s) instance Profunctor Validation where dimap f g (Validation k) = Validation (\c s -> fmap g (k c (f s))) instance Choice Validation where left' (Validation g) = Validation (\c -> either (fmap Left . g c) (pure . Right)) right' (Validation g) = Validation (\c -> either (pure . Left) (fmap Right . g c)) instance Monad (Validation s) where return = pure Validation x >>= f = Validation (\c s -> x c s >>= \y -> runValidation (f y) c s) (>>) = (*>) withConfig :: (Config -> Validation s a) -> Validation s a withConfig f = Validation (\c -> runValidation (f c) c) withSchema :: (s -> Validation s a) -> Validation s a withSchema f = Validation (\c s -> runValidation (f s) c s) -- | Issue an error message. invalid :: String -> Validation schema a invalid msg = Validation (\_ _ -> Failed [msg]) -- | Validation passed. valid :: Validation schema () valid = pure () -- | Validate schema's property given a lens into that property -- and property checker. checkMissing :: Validation s () -> Lens' s (Maybe a) -> (a -> Validation s ()) -> Validation s () checkMissing missing l g = withSchema $ \sch -> case sch ^. l of Nothing -> missing Just x -> g x -- | Validate schema's property given a lens into that property -- and property checker. -- If property is missing in schema, consider it valid. check :: Lens' s (Maybe a) -> (a -> Validation s ()) -> Validation s () check = checkMissing valid -- | Validate same value with different schema. sub :: t -> Validation t a -> Validation s a sub = lmap . const -- | Validate same value with a part of the original schema. sub_ :: Getting a s a -> Validation a r -> Validation s r sub_ = lmap . view -- | Validate value against a schema given schema reference and validation function. withRef :: Reference -> (Schema -> Validation s a) -> Validation s a withRef (Reference ref) f = withConfig $ \cfg -> case InsOrdHashMap.lookup ref (configDefinitions cfg) of Nothing -> invalid $ "unknown schema " ++ show ref Just s -> f s validateWithSchemaRef :: Referenced Schema -> Value -> Validation s () validateWithSchemaRef (Ref ref) js = withRef ref $ \sch -> sub sch (validateWithSchema js) validateWithSchemaRef (Inline s) js = sub s (validateWithSchema js) -- | Validate JSON @'Value'@ with Swagger @'Schema'@. validateWithSchema :: Value -> Validation Schema () validateWithSchema val = do validateSchemaType val validateEnum val validateInteger :: Scientific -> Validation Schema () validateInteger n = do when (not (isInteger n)) $ invalid ("not an integer") validateNumber n validateNumber :: Scientific -> Validation Schema () validateNumber n = withConfig $ \_cfg -> withSchema $ \sch -> do let exMax = Just True == sch ^. exclusiveMaximum exMin = Just True == sch ^. exclusiveMinimum check maximum_ $ \m -> when (if exMax then (n >= m) else (n > m)) $ invalid ("value " ++ show n ++ " exceeds maximum (should be " ++ (if exMax then "<" else "<=") ++ show m ++ ")") check minimum_ $ \m -> when (if exMin then (n <= m) else (n < m)) $ invalid ("value " ++ show n ++ " falls below minimum (should be " ++ (if exMin then ">" else ">=") ++ show m ++ ")") check multipleOf $ \k -> when (not (isInteger (n / k))) $ invalid ("expected a multiple of " ++ show k ++ " but got " ++ show n) validateString :: Text -> Validation Schema () validateString s = do check maxLength $ \n -> when (len > fromInteger n) $ invalid ("string is too long (length should be <=" ++ show n ++ ")") check minLength $ \n -> when (len < fromInteger n) $ invalid ("string is too short (length should be >=" ++ show n ++ ")") check pattern $ \regex -> do withConfig $ \cfg -> do when (not (configPatternChecker cfg regex s)) $ invalid ("string does not match pattern " ++ show regex) where len = Text.length s validateArray :: Vector Value -> Validation Schema () validateArray xs = do check maxItems $ \n -> when (len > fromInteger n) $ invalid ("array exceeds maximum size (should be <=" ++ show n ++ ")") check minItems $ \n -> when (len < fromInteger n) $ invalid ("array is too short (size should be >=" ++ show n ++ ")") check items $ \case OpenApiItemsObject itemSchema -> traverse_ (validateWithSchemaRef itemSchema) xs OpenApiItemsArray itemSchemas -> do when (len /= length itemSchemas) $ invalid ("array size is invalid (should be exactly " ++ show (length itemSchemas) ++ ")") sequenceA_ (zipWith validateWithSchemaRef itemSchemas (Vector.toList xs)) check uniqueItems $ \unique -> when (unique && not allUnique) $ invalid ("array is expected to contain unique items, but it does not") where len = Vector.length xs allUnique = len == HashSet.size (HashSet.fromList (Vector.toList xs)) validateObject :: #if MIN_VERSION_aeson(2,0,0) KeyMap.KeyMap Value #else HashMap Text Value #endif -> Validation Schema () validateObject o = withSchema $ \sch -> case sch ^. discriminator of Just (Discriminator pname types) -> case fromJSON <$> lookupKey pname o of Just (Success pvalue) -> let ref = fromMaybe pvalue $ InsOrdHashMap.lookup pvalue types -- TODO ref may be name or reference in validateWithSchemaRef (Ref (Reference ref)) (Object o) Just (Error msg) -> invalid ("failed to parse discriminator property " ++ show pname ++ ": " ++ show msg) Nothing -> invalid ("discriminator property " ++ show pname ++ "is missing") Nothing -> do check maxProperties $ \n -> when (size > n) $ invalid ("object size exceeds maximum (total number of properties should be <=" ++ show n ++ ")") check minProperties $ \n -> when (size < n) $ invalid ("object size is too small (total number of properties should be >=" ++ show n ++ ")") validateRequired validateProps where size = fromIntegral (length o) validateRequired = withSchema $ \sch -> traverse_ validateReq (sch ^. required) validateReq n = when (not (hasKey n o)) $ invalid ("property " ++ show n ++ " is required, but not found in " ++ show (encode o)) validateProps = withSchema $ \sch -> do for_ (objectToList o) $ \(keyToText -> k, v) -> case v of Null | not (k `elem` (sch ^. required)) -> valid -- null is fine for non-required property _ -> case InsOrdHashMap.lookup k (sch ^. properties) of Nothing -> checkMissing (unknownProperty k) additionalProperties $ validateAdditional k v Just s -> validateWithSchemaRef s v validateAdditional _ _ (AdditionalPropertiesAllowed True) = valid validateAdditional k _ (AdditionalPropertiesAllowed False) = invalid $ "additionalProperties=false but extra property " <> show k <> " found" validateAdditional _ v (AdditionalPropertiesSchema s) = validateWithSchemaRef s v unknownProperty :: Text -> Validation s a unknownProperty pname = invalid $ "property " <> show pname <> " is found in JSON value, but it is not mentioned in Swagger schema" validateEnum :: Value -> Validation Schema () validateEnum val = do check enum_ $ \xs -> when (val `notElem` xs) $ invalid ("expected one of " ++ show (encode xs) ++ " but got " ++ show val) -- | Infer schema type based on used properties. -- -- This is like 'inferParamSchemaTypes', but also works for objects: -- > > > inferSchemaTypes < $ > decode " { " : 1 } " -- Just [OpenApiObject] inferSchemaTypes :: Schema -> [OpenApiType] inferSchemaTypes sch = inferParamSchemaTypes sch ++ [ OpenApiObject | any ($ sch) [ has (additionalProperties._Just) , has (maxProperties._Just) , has (minProperties._Just) , has (properties.folded) , has (required.folded) ] ] -- | Infer schema type based on used properties. -- > > > inferSchemaTypes < $ > decode " { \"minLength\ " : 2 } " -- Just [OpenApiString] -- -- >>> inferSchemaTypes <$> decode "{\"maxItems\": 0}" -- Just [OpenApiArray] -- -- From numeric properties 'OpenApiInteger' type is inferred. -- If you want 'OpenApiNumber' instead, you must specify it explicitly. -- > > > inferSchemaTypes < $ > decode " { \"minimum\ " : 1 } " -- Just [OpenApiInteger] inferParamSchemaTypes :: Schema -> [OpenApiType] inferParamSchemaTypes sch = concat [ [ OpenApiArray | any ($ sch) [ has (items._Just) , has (maxItems._Just) , has (minItems._Just) , has (uniqueItems._Just) ] ] , [ OpenApiInteger | any ($ sch) [ has (exclusiveMaximum._Just) , has (exclusiveMinimum._Just) , has (maximum_._Just) , has (minimum_._Just) , has (multipleOf._Just) ] ] , [ OpenApiString | any ($ sch) [ has (maxLength._Just) , has (minLength._Just) , has (pattern._Just) ] ] ] validateSchemaType :: Value -> Validation Schema () validateSchemaType val = withSchema $ \sch -> case sch of (view oneOf -> Just variants) -> do res <- forM variants $ \var -> (True <$ validateWithSchemaRef var val) <|> (return False) case length $ filter id res of 0 -> invalid $ "Value not valid under any of 'oneOf' schemas: " ++ show val 1 -> valid _ -> invalid $ "Value matches more than one of 'oneOf' schemas: " ++ show val (view allOf -> Just variants) -> do Default semantics for Validation Monad will abort when at least one -- variant does not match. forM_ variants $ \var -> validateWithSchemaRef var val _ -> case (sch ^. type_, val) of (Just OpenApiNull, Null) -> valid (Just OpenApiBoolean, Bool _) -> valid (Just OpenApiInteger, Number n) -> validateInteger n (Just OpenApiNumber, Number n) -> validateNumber n (Just OpenApiString, String s) -> validateString s (Just OpenApiArray, Array xs) -> validateArray xs (Just OpenApiObject, Object o) -> validateObject o (Nothing, Null) -> valid (Nothing, Bool _) -> valid -- Number by default (Nothing, Number n) -> validateNumber n (Nothing, String s) -> validateString s (Nothing, Array xs) -> validateArray xs (Nothing, Object o) -> validateObject o bad -> invalid $ "expected JSON value of type " ++ showType bad validateParamSchemaType :: Value -> Validation Schema () validateParamSchemaType val = withSchema $ \sch -> case (sch ^. type_, val) of (Just OpenApiBoolean, Bool _) -> valid (Just OpenApiInteger, Number n) -> validateInteger n (Just OpenApiNumber, Number n) -> validateNumber n (Just OpenApiString, String s) -> validateString s (Just OpenApiArray, Array xs) -> validateArray xs (Nothing, Bool _) -> valid -- Number by default (Nothing, Number n) -> validateNumber n (Nothing, String s) -> validateString s (Nothing, Array xs) -> validateArray xs bad -> invalid $ "expected JSON value of type " ++ showType bad showType :: (Maybe OpenApiType, Value) -> String showType (Just ty, _) = show ty showType (Nothing, Null) = "OpenApiNull" showType (Nothing, Bool _) = "OpenApiBoolean" showType (Nothing, Number _) = "OpenApiNumber" showType (Nothing, String _) = "OpenApiString" showType (Nothing, Array _) = "OpenApiArray" showType (Nothing, Object _) = "OpenApiObject"
null
https://raw.githubusercontent.com/biocad/openapi3/cffc5ebf91212e9658b432cfdb5c3974bb9cf18c/src/Data/OpenApi/Internal/Schema/Validation.hs
haskell
# OPTIONS_GHC -Wall # # LANGUAGE DataKinds # # LANGUAGE DeriveFunctor # # LANGUAGE GADTs # # LANGUAGE PackageImports # # LANGUAGE RankNTypes # # LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # | Stability: experimental $setup | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value. prop> validateToJSON (x :: Int) == [] /NOTE:/ @'validateToJSON'@ does not perform string pattern validation. See @'validateToJSONWithPatternChecker'@. See 'renderValidationErrors' on how the output is structured. | Variant of 'validatePrettyToJSON' with typed output. | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value and pattern checker. 'renderValidationErrors'. | Pretty print validation errors together with actual JSON and Swagger Schema (using 'encodePretty'). >>> import Data.Foldable (traverse_) >>> data Phone = Phone { value :: String } deriving (Generic) >>> data Person = Person { name :: String, phone :: Phone } deriving (Generic) >>> traverse_ putStrLn $ renderValidationErrors validateToJSON person Validation against the schema fails: <BLANKLINE> JSON value: { } <BLANKLINE> Swagger Schema: { "properties": { "name": { "type": "string" }, "phone": { "$ref": "#/components/schemas/Phone" } }, "required": [ "name", "phone" ], "type": "object" } <BLANKLINE> Swagger Description Context: { "Phone": { "properties": { "value": { "type": "string" } }, "required": [ "value" ], "type": "object" } } <BLANKLINE> | Validate JSON @'Value'@ against Swagger @'Schema'@. /NOTE:/ @'validateJSON'@ does not perform string pattern validation. | Validate JSON @'Value'@ agains Swagger @'ToSchema'@ for a given value and pattern checker. | Validation error message. | Validation result type. ^ Validation failed with a list of error messages. ^ Validation passed. | Validation configuration. | Pattern checker for @'_schemaPattern'@ validation. | Schema definitions in scope to resolve references. | Default @'Config'@: @ defaultConfig = 'Config' { 'configPatternChecker' = \\_pattern _str -> True } @ | Value validation. | Issue an error message. | Validation passed. | Validate schema's property given a lens into that property and property checker. | Validate schema's property given a lens into that property and property checker. If property is missing in schema, consider it valid. | Validate same value with different schema. | Validate same value with a part of the original schema. | Validate value against a schema given schema reference and validation function. | Validate JSON @'Value'@ with Swagger @'Schema'@. TODO ref may be name or reference null is fine for non-required property | Infer schema type based on used properties. This is like 'inferParamSchemaTypes', but also works for objects: Just [OpenApiObject] | Infer schema type based on used properties. Just [OpenApiString] >>> inferSchemaTypes <$> decode "{\"maxItems\": 0}" Just [OpenApiArray] From numeric properties 'OpenApiInteger' type is inferred. If you want 'OpenApiNumber' instead, you must specify it explicitly. Just [OpenApiInteger] variant does not match. Number by default Number by default
# LANGUAGE CPP # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE ViewPatterns # Module : Data . OpenApi . Internal . Schema . Validation Copyright : ( c ) 2015 GetShopTV License : BSD3 Maintainer : < > Validate JSON values with Swagger Schema . module Data.OpenApi.Internal.Schema.Validation where import Prelude () import Prelude.Compat import Control.Applicative import Control.Lens hiding (allOf) import Control.Monad (forM, forM_, when) import Data.Aeson hiding (Result) #if MIN_VERSION_aeson(2,0,0) import qualified Data.Aeson.KeyMap as KeyMap #endif import Data.Foldable (for_, sequenceA_, traverse_) #if !MIN_VERSION_aeson(2,0,0) import Data.HashMap.Strict (HashMap) #endif import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap import qualified "unordered-containers" Data.HashSet as HashSet import Data.Maybe (fromMaybe) import Data.Proxy import Data.Scientific (Scientific, isInteger) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import Data.Vector (Vector) import qualified Data.Vector as Vector import Data.OpenApi.Aeson.Compat (hasKey, keyToText, lookupKey, objectToList) import Data.OpenApi.Declare import Data.OpenApi.Internal import Data.OpenApi.Internal.Schema import Data.OpenApi.Internal.Utils import Data.OpenApi.Lens > > > import Data . OpenApi . Internal . Schema . Validation This can be used with QuickCheck to ensure those instances are coherent : validatePrettyToJSON :: forall a. (ToJSON a, ToSchema a) => a -> Maybe String validatePrettyToJSON = renderValidationErrors validateToJSON validateToJSON :: forall a. (ToJSON a, ToSchema a) => a -> [ValidationError] validateToJSON = validateToJSONWithPatternChecker (\_pattern _str -> True) This can be used with QuickCheck to ensure those instances are coherent . For validation without patterns see See also : validateToJSONWithPatternChecker :: forall a. (ToJSON a, ToSchema a) => (Pattern -> Text -> Bool) -> a -> [ValidationError] validateToJSONWithPatternChecker checker = validateJSONWithPatternChecker checker defs sch . toJSON where (defs, sch) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty > > > import Data . Aeson as Aeson > > > import > > > instance ToJSON Person where toJSON p = object [ " name " .. = name p ] > > > instance Phone > > > instance Person > > > let person = Person { name = " " , phone = Phone " 123456 " } * property " phone " is required , but not found in " { \"name\":\"John\ " } " " name " : " " renderValidationErrors :: forall a. (ToJSON a, ToSchema a) => (a -> [ValidationError]) -> a -> Maybe String renderValidationErrors f x = case f x of [] -> Nothing errors -> Just $ unlines [ "Validation against the schema fails:" , unlines (map (" * " ++) errors) , "JSON value:" , ppJSONString (toJSON x) , "" , "Swagger Schema:" , ppJSONString (toJSON schema_) , "" , "Swagger Description Context:" , ppJSONString (toJSON refs_) ] where ppJSONString = TL.unpack . TL.decodeUtf8 . encodePretty (refs_, schema_) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty prop > validateJSON mempty ( toSchema ( Proxy : : Proxy Int ) ) ( toJSON ( x : : Int ) ) = = [ ] See @'validateJSONWithPatternChecker'@. validateJSON :: Definitions Schema -> Schema -> Value -> [ValidationError] validateJSON = validateJSONWithPatternChecker (\_pattern _str -> True) For validation without patterns see @'validateJSON'@. validateJSONWithPatternChecker :: (Pattern -> Text -> Bool) -> Definitions Schema -> Schema -> Value -> [ValidationError] validateJSONWithPatternChecker checker defs sch js = case runValidation (validateWithSchema js) cfg sch of Failed xs -> xs Passed _ -> mempty where cfg = defaultConfig { configPatternChecker = checker , configDefinitions = defs } type ValidationError = String data Result a deriving (Eq, Show, Functor) instance Applicative Result where pure = Passed Passed f <*> Passed x = Passed (f x) Failed xs <*> Failed ys = Failed (xs <> ys) Failed xs <*> _ = Failed xs _ <*> Failed ys = Failed ys instance Alternative Result where empty = Failed mempty Passed x <|> _ = Passed x _ <|> y = y instance Monad Result where return = pure Passed x >>= f = f x Failed xs >>= _ = Failed xs data Config = Config configPatternChecker :: Pattern -> Text -> Bool , configDefinitions :: Definitions Schema } , ' configDefinitions ' = defaultConfig :: Config defaultConfig = Config { configPatternChecker = \_pattern _str -> True , configDefinitions = mempty } newtype Validation s a = Validation { runValidation :: Config -> s -> Result a } deriving (Functor) instance Applicative (Validation schema) where pure x = Validation (\_ _ -> pure x) Validation f <*> Validation x = Validation (\c s -> f c s <*> x c s) instance Alternative (Validation schema) where empty = Validation (\_ _ -> empty) Validation x <|> Validation y = Validation (\c s -> x c s <|> y c s) instance Profunctor Validation where dimap f g (Validation k) = Validation (\c s -> fmap g (k c (f s))) instance Choice Validation where left' (Validation g) = Validation (\c -> either (fmap Left . g c) (pure . Right)) right' (Validation g) = Validation (\c -> either (pure . Left) (fmap Right . g c)) instance Monad (Validation s) where return = pure Validation x >>= f = Validation (\c s -> x c s >>= \y -> runValidation (f y) c s) (>>) = (*>) withConfig :: (Config -> Validation s a) -> Validation s a withConfig f = Validation (\c -> runValidation (f c) c) withSchema :: (s -> Validation s a) -> Validation s a withSchema f = Validation (\c s -> runValidation (f s) c s) invalid :: String -> Validation schema a invalid msg = Validation (\_ _ -> Failed [msg]) valid :: Validation schema () valid = pure () checkMissing :: Validation s () -> Lens' s (Maybe a) -> (a -> Validation s ()) -> Validation s () checkMissing missing l g = withSchema $ \sch -> case sch ^. l of Nothing -> missing Just x -> g x check :: Lens' s (Maybe a) -> (a -> Validation s ()) -> Validation s () check = checkMissing valid sub :: t -> Validation t a -> Validation s a sub = lmap . const sub_ :: Getting a s a -> Validation a r -> Validation s r sub_ = lmap . view withRef :: Reference -> (Schema -> Validation s a) -> Validation s a withRef (Reference ref) f = withConfig $ \cfg -> case InsOrdHashMap.lookup ref (configDefinitions cfg) of Nothing -> invalid $ "unknown schema " ++ show ref Just s -> f s validateWithSchemaRef :: Referenced Schema -> Value -> Validation s () validateWithSchemaRef (Ref ref) js = withRef ref $ \sch -> sub sch (validateWithSchema js) validateWithSchemaRef (Inline s) js = sub s (validateWithSchema js) validateWithSchema :: Value -> Validation Schema () validateWithSchema val = do validateSchemaType val validateEnum val validateInteger :: Scientific -> Validation Schema () validateInteger n = do when (not (isInteger n)) $ invalid ("not an integer") validateNumber n validateNumber :: Scientific -> Validation Schema () validateNumber n = withConfig $ \_cfg -> withSchema $ \sch -> do let exMax = Just True == sch ^. exclusiveMaximum exMin = Just True == sch ^. exclusiveMinimum check maximum_ $ \m -> when (if exMax then (n >= m) else (n > m)) $ invalid ("value " ++ show n ++ " exceeds maximum (should be " ++ (if exMax then "<" else "<=") ++ show m ++ ")") check minimum_ $ \m -> when (if exMin then (n <= m) else (n < m)) $ invalid ("value " ++ show n ++ " falls below minimum (should be " ++ (if exMin then ">" else ">=") ++ show m ++ ")") check multipleOf $ \k -> when (not (isInteger (n / k))) $ invalid ("expected a multiple of " ++ show k ++ " but got " ++ show n) validateString :: Text -> Validation Schema () validateString s = do check maxLength $ \n -> when (len > fromInteger n) $ invalid ("string is too long (length should be <=" ++ show n ++ ")") check minLength $ \n -> when (len < fromInteger n) $ invalid ("string is too short (length should be >=" ++ show n ++ ")") check pattern $ \regex -> do withConfig $ \cfg -> do when (not (configPatternChecker cfg regex s)) $ invalid ("string does not match pattern " ++ show regex) where len = Text.length s validateArray :: Vector Value -> Validation Schema () validateArray xs = do check maxItems $ \n -> when (len > fromInteger n) $ invalid ("array exceeds maximum size (should be <=" ++ show n ++ ")") check minItems $ \n -> when (len < fromInteger n) $ invalid ("array is too short (size should be >=" ++ show n ++ ")") check items $ \case OpenApiItemsObject itemSchema -> traverse_ (validateWithSchemaRef itemSchema) xs OpenApiItemsArray itemSchemas -> do when (len /= length itemSchemas) $ invalid ("array size is invalid (should be exactly " ++ show (length itemSchemas) ++ ")") sequenceA_ (zipWith validateWithSchemaRef itemSchemas (Vector.toList xs)) check uniqueItems $ \unique -> when (unique && not allUnique) $ invalid ("array is expected to contain unique items, but it does not") where len = Vector.length xs allUnique = len == HashSet.size (HashSet.fromList (Vector.toList xs)) validateObject :: #if MIN_VERSION_aeson(2,0,0) KeyMap.KeyMap Value #else HashMap Text Value #endif -> Validation Schema () validateObject o = withSchema $ \sch -> case sch ^. discriminator of Just (Discriminator pname types) -> case fromJSON <$> lookupKey pname o of Just (Success pvalue) -> let ref = fromMaybe pvalue $ InsOrdHashMap.lookup pvalue types in validateWithSchemaRef (Ref (Reference ref)) (Object o) Just (Error msg) -> invalid ("failed to parse discriminator property " ++ show pname ++ ": " ++ show msg) Nothing -> invalid ("discriminator property " ++ show pname ++ "is missing") Nothing -> do check maxProperties $ \n -> when (size > n) $ invalid ("object size exceeds maximum (total number of properties should be <=" ++ show n ++ ")") check minProperties $ \n -> when (size < n) $ invalid ("object size is too small (total number of properties should be >=" ++ show n ++ ")") validateRequired validateProps where size = fromIntegral (length o) validateRequired = withSchema $ \sch -> traverse_ validateReq (sch ^. required) validateReq n = when (not (hasKey n o)) $ invalid ("property " ++ show n ++ " is required, but not found in " ++ show (encode o)) validateProps = withSchema $ \sch -> do for_ (objectToList o) $ \(keyToText -> k, v) -> case v of _ -> case InsOrdHashMap.lookup k (sch ^. properties) of Nothing -> checkMissing (unknownProperty k) additionalProperties $ validateAdditional k v Just s -> validateWithSchemaRef s v validateAdditional _ _ (AdditionalPropertiesAllowed True) = valid validateAdditional k _ (AdditionalPropertiesAllowed False) = invalid $ "additionalProperties=false but extra property " <> show k <> " found" validateAdditional _ v (AdditionalPropertiesSchema s) = validateWithSchemaRef s v unknownProperty :: Text -> Validation s a unknownProperty pname = invalid $ "property " <> show pname <> " is found in JSON value, but it is not mentioned in Swagger schema" validateEnum :: Value -> Validation Schema () validateEnum val = do check enum_ $ \xs -> when (val `notElem` xs) $ invalid ("expected one of " ++ show (encode xs) ++ " but got " ++ show val) > > > inferSchemaTypes < $ > decode " { " : 1 } " inferSchemaTypes :: Schema -> [OpenApiType] inferSchemaTypes sch = inferParamSchemaTypes sch ++ [ OpenApiObject | any ($ sch) [ has (additionalProperties._Just) , has (maxProperties._Just) , has (minProperties._Just) , has (properties.folded) , has (required.folded) ] ] > > > inferSchemaTypes < $ > decode " { \"minLength\ " : 2 } " > > > inferSchemaTypes < $ > decode " { \"minimum\ " : 1 } " inferParamSchemaTypes :: Schema -> [OpenApiType] inferParamSchemaTypes sch = concat [ [ OpenApiArray | any ($ sch) [ has (items._Just) , has (maxItems._Just) , has (minItems._Just) , has (uniqueItems._Just) ] ] , [ OpenApiInteger | any ($ sch) [ has (exclusiveMaximum._Just) , has (exclusiveMinimum._Just) , has (maximum_._Just) , has (minimum_._Just) , has (multipleOf._Just) ] ] , [ OpenApiString | any ($ sch) [ has (maxLength._Just) , has (minLength._Just) , has (pattern._Just) ] ] ] validateSchemaType :: Value -> Validation Schema () validateSchemaType val = withSchema $ \sch -> case sch of (view oneOf -> Just variants) -> do res <- forM variants $ \var -> (True <$ validateWithSchemaRef var val) <|> (return False) case length $ filter id res of 0 -> invalid $ "Value not valid under any of 'oneOf' schemas: " ++ show val 1 -> valid _ -> invalid $ "Value matches more than one of 'oneOf' schemas: " ++ show val (view allOf -> Just variants) -> do Default semantics for Validation Monad will abort when at least one forM_ variants $ \var -> validateWithSchemaRef var val _ -> case (sch ^. type_, val) of (Just OpenApiNull, Null) -> valid (Just OpenApiBoolean, Bool _) -> valid (Just OpenApiInteger, Number n) -> validateInteger n (Just OpenApiNumber, Number n) -> validateNumber n (Just OpenApiString, String s) -> validateString s (Just OpenApiArray, Array xs) -> validateArray xs (Just OpenApiObject, Object o) -> validateObject o (Nothing, Null) -> valid (Nothing, Bool _) -> valid (Nothing, Number n) -> validateNumber n (Nothing, String s) -> validateString s (Nothing, Array xs) -> validateArray xs (Nothing, Object o) -> validateObject o bad -> invalid $ "expected JSON value of type " ++ showType bad validateParamSchemaType :: Value -> Validation Schema () validateParamSchemaType val = withSchema $ \sch -> case (sch ^. type_, val) of (Just OpenApiBoolean, Bool _) -> valid (Just OpenApiInteger, Number n) -> validateInteger n (Just OpenApiNumber, Number n) -> validateNumber n (Just OpenApiString, String s) -> validateString s (Just OpenApiArray, Array xs) -> validateArray xs (Nothing, Bool _) -> valid (Nothing, Number n) -> validateNumber n (Nothing, String s) -> validateString s (Nothing, Array xs) -> validateArray xs bad -> invalid $ "expected JSON value of type " ++ showType bad showType :: (Maybe OpenApiType, Value) -> String showType (Just ty, _) = show ty showType (Nothing, Null) = "OpenApiNull" showType (Nothing, Bool _) = "OpenApiBoolean" showType (Nothing, Number _) = "OpenApiNumber" showType (Nothing, String _) = "OpenApiString" showType (Nothing, Array _) = "OpenApiArray" showType (Nothing, Object _) = "OpenApiObject"
3fa3b2e29a1835d4260f71364d43cca368c99473c8fb2e7f51826ec2fddf7657
jacekschae/learn-reitit-course-files
test_system.clj
(ns cheffy.test-system (:require [clojure.test :refer :all] [integrant.repl.state :as state] [ring.mock.request :as mock] [muuntaja.core :as m] [cheffy.auth0 :as auth0])) (def token (atom nil)) (defn account-fixture [f] (auth0/create-auth0-user {:connection "Username-Password-Authentication" :email "" :password "s#m3R4nd0m-pass"}) (reset! token (auth0/get-test-token "")) (f)) (defn token-fixture [f] (reset! token (auth0/get-test-token "")) (f) (reset! token nil)) (defn test-endpoint ([method uri] (test-endpoint method uri nil)) ([method uri opts] (let [app (-> state/system :cheffy/app) request (app (-> (mock/request method uri) (cond-> (:auth opts) (mock/header :authorization (str "Bearer " (or @token (auth0/get-test-token "")))) (:body opts) (mock/json-body (:body opts)))))] (update request :body (partial m/decode "application/json"))))) (comment (let [request (test-endpoint :get "/v1/recipes") decoded-request (m/decode-response-body request)] (assoc request :body decoded-request)) (test-endpoint :post "/v1/recipes" {:img "string" :name "my name" :prep-time 30}))
null
https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/47-tests-refactor/test/cheffy/test_system.clj
clojure
(ns cheffy.test-system (:require [clojure.test :refer :all] [integrant.repl.state :as state] [ring.mock.request :as mock] [muuntaja.core :as m] [cheffy.auth0 :as auth0])) (def token (atom nil)) (defn account-fixture [f] (auth0/create-auth0-user {:connection "Username-Password-Authentication" :email "" :password "s#m3R4nd0m-pass"}) (reset! token (auth0/get-test-token "")) (f)) (defn token-fixture [f] (reset! token (auth0/get-test-token "")) (f) (reset! token nil)) (defn test-endpoint ([method uri] (test-endpoint method uri nil)) ([method uri opts] (let [app (-> state/system :cheffy/app) request (app (-> (mock/request method uri) (cond-> (:auth opts) (mock/header :authorization (str "Bearer " (or @token (auth0/get-test-token "")))) (:body opts) (mock/json-body (:body opts)))))] (update request :body (partial m/decode "application/json"))))) (comment (let [request (test-endpoint :get "/v1/recipes") decoded-request (m/decode-response-body request)] (assoc request :body decoded-request)) (test-endpoint :post "/v1/recipes" {:img "string" :name "my name" :prep-time 30}))
929c1b38df6607bc1c3016d4fa7ce97eb1f066203722e00e30a19db5a9f2884f
GlideAngle/flare-timing
Alt.hs
module Serve.Alt ( getAltTaskScore , getAltTaskValidityWorking , getAltTaskRouteSphere , getAltTaskRouteEllipse , getAltTaskLanding , getAltTaskArrival ) where import Data.List (zip4) import Servant (throwError) import Control.Monad (join) import Control.Monad.Reader (asks) import Flight.Units () import Flight.Track.Land (TaskLanding(..), taskLanding) import Flight.Track.Arrival (TrackArrival(..)) import Flight.Track.Place (rankByAirScoreTotal) import qualified Flight.Track.Mask as Mask (CompMaskingArrival(..)) import qualified Flight.Track.Point as Alt (AlternativePointing(..), AltBreakdown(..)) import qualified "flight-gap-valid" Flight.Score as Vw (ValidityWorking(..)) import Flight.Comp (AltDot(AltFs, AltAs), IxTask(..), Pilot(..)) import Flight.Route (TrackLine(..), GeoLines(..)) import Serve.Validity (nullValidityWorking) import Serve.Config (AppT(..), Config(..)) import Serve.Error (errTaskStep, errTaskBounds) getAltTaskValidityWorking :: Int -> AppT k IO (Maybe Vw.ValidityWorking) getAltTaskValidityWorking ii = do ls' <- fmap Alt.validityWorkingLaunch <$> asks altFsScore ts' <- fmap Alt.validityWorkingTime <$> asks altFsScore ds' <- fmap Alt.validityWorkingDistance <$> asks altFsScore ss' <- fmap Alt.validityWorkingStop <$> asks altFsScore case (ls', ts', ds', ss') of (Just ls, Just ts, Just ds, Just ss) -> case drop (ii - 1) $ zip4 ls ts ds ss of (lv, tv, dv, sv) : _ -> return $ do lv' <- lv tv' <- tv dv' <- dv return $ nullValidityWorking { Vw.launch = lv' , Vw.time = tv' , Vw.distance = dv' , Vw.stop = sv } _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "gap-point" ii getAltTaskScore :: AltDot -> Int -> AppT k IO [(Pilot, Alt.AltBreakdown)] getAltTaskScore AltFs ii = do xs' <- fmap Alt.score <$> asks altFsScore case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "fs-score" ii getAltTaskScore AltAs ii = do xs' <- fmap Alt.score <$> asks altAsScore let asSorted = (fmap . fmap) rankByAirScoreTotal xs' case asSorted of Just xs -> case drop (ii - 1) xs of x : _ -> return x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "as-score" ii getAltTaskRouteSphere :: Int -> AppT k IO (Maybe TrackLine) getAltTaskRouteSphere ii = do xs' <- asks altFsRoute case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return $ sphere x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "fs-route" ii getAltTaskRouteEllipse :: Int -> AppT k IO (Maybe TrackLine) getAltTaskRouteEllipse ii = do xs' <- asks altFsRoute case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return $ ellipse x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "fs-route" ii getAltTaskLanding :: Int -> AppT k IO (Maybe TaskLanding) getAltTaskLanding ii = do x <- asks altFsLandout return . join $ taskLanding (IxTask ii) <$> x getAltTaskArrival :: Int -> AppT k IO [(Pilot, TrackArrival)] getAltTaskArrival ii = do xs' <- fmap Mask.arrivalRank <$> asks maskingArrival case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "mask-track" ii
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/app-serve/src/Serve/Alt.hs
haskell
module Serve.Alt ( getAltTaskScore , getAltTaskValidityWorking , getAltTaskRouteSphere , getAltTaskRouteEllipse , getAltTaskLanding , getAltTaskArrival ) where import Data.List (zip4) import Servant (throwError) import Control.Monad (join) import Control.Monad.Reader (asks) import Flight.Units () import Flight.Track.Land (TaskLanding(..), taskLanding) import Flight.Track.Arrival (TrackArrival(..)) import Flight.Track.Place (rankByAirScoreTotal) import qualified Flight.Track.Mask as Mask (CompMaskingArrival(..)) import qualified Flight.Track.Point as Alt (AlternativePointing(..), AltBreakdown(..)) import qualified "flight-gap-valid" Flight.Score as Vw (ValidityWorking(..)) import Flight.Comp (AltDot(AltFs, AltAs), IxTask(..), Pilot(..)) import Flight.Route (TrackLine(..), GeoLines(..)) import Serve.Validity (nullValidityWorking) import Serve.Config (AppT(..), Config(..)) import Serve.Error (errTaskStep, errTaskBounds) getAltTaskValidityWorking :: Int -> AppT k IO (Maybe Vw.ValidityWorking) getAltTaskValidityWorking ii = do ls' <- fmap Alt.validityWorkingLaunch <$> asks altFsScore ts' <- fmap Alt.validityWorkingTime <$> asks altFsScore ds' <- fmap Alt.validityWorkingDistance <$> asks altFsScore ss' <- fmap Alt.validityWorkingStop <$> asks altFsScore case (ls', ts', ds', ss') of (Just ls, Just ts, Just ds, Just ss) -> case drop (ii - 1) $ zip4 ls ts ds ss of (lv, tv, dv, sv) : _ -> return $ do lv' <- lv tv' <- tv dv' <- dv return $ nullValidityWorking { Vw.launch = lv' , Vw.time = tv' , Vw.distance = dv' , Vw.stop = sv } _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "gap-point" ii getAltTaskScore :: AltDot -> Int -> AppT k IO [(Pilot, Alt.AltBreakdown)] getAltTaskScore AltFs ii = do xs' <- fmap Alt.score <$> asks altFsScore case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "fs-score" ii getAltTaskScore AltAs ii = do xs' <- fmap Alt.score <$> asks altAsScore let asSorted = (fmap . fmap) rankByAirScoreTotal xs' case asSorted of Just xs -> case drop (ii - 1) xs of x : _ -> return x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "as-score" ii getAltTaskRouteSphere :: Int -> AppT k IO (Maybe TrackLine) getAltTaskRouteSphere ii = do xs' <- asks altFsRoute case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return $ sphere x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "fs-route" ii getAltTaskRouteEllipse :: Int -> AppT k IO (Maybe TrackLine) getAltTaskRouteEllipse ii = do xs' <- asks altFsRoute case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return $ ellipse x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "fs-route" ii getAltTaskLanding :: Int -> AppT k IO (Maybe TaskLanding) getAltTaskLanding ii = do x <- asks altFsLandout return . join $ taskLanding (IxTask ii) <$> x getAltTaskArrival :: Int -> AppT k IO [(Pilot, TrackArrival)] getAltTaskArrival ii = do xs' <- fmap Mask.arrivalRank <$> asks maskingArrival case xs' of Just xs -> case drop (ii - 1) xs of x : _ -> return x _ -> throwError $ errTaskBounds ii _ -> throwError $ errTaskStep "mask-track" ii
98d24e6183cb508f014bbede8d86d34a1ed31832c07e24f75cb4a2c1cc7ff621
aeternity/aeternity
aesc_htlc_SUITE.erl
%%%============================================================================= ( C ) 2018 , Aeternity Anstalt %%% @doc Test utils for State Channel markets , using HTLC contracts %%% @end %%%============================================================================= -module(aesc_htlc_SUITE). -export([ all/0 , groups/0 , suite/0 , init_per_suite/1 , end_per_suite/1 , init_per_group/2 , end_per_group/2 , init_per_testcase/2 , end_per_testcase/2 ]). %% test case exports -export([ create_3_party/1 , simple_msg_relay/1 , alice_pays_bob/1 , alice_tries_early_refund/1 , alice_gets_refund_after_timeout/1 , bob_tries_receiving_too_late/1 , shutdown/1 ]). %%% ======================================================================== %%% Strategy %%% We reuse as much as we can from the aesc_fsm_SUITE. One quirk of the fsm_SUITE is that it spawns proxy processes which are %%% linked to the testcase process, and here we want to use test sequences %%% which begin with a market setup that remains throughout the sequence. To achieve this , we create yet another proxy process in ` init_per_group/2 ` . %%% This proxy evaluates funs provided by the testcase process, and forwards %%% all received messages to it (the testcase process 'registers' with the %%% proxy in `init_per_testcase/2`, etc.) %%% ======================================================================== -import(aec_test_utils, [ get_debug/1 ]). -import(aesc_fsm_SUITE, [ create_channel_/3 , channel_shutdown/3 , prepare_contract_create_args/3 , load_contract/4 , call_contract/9 , receive_log/2 , set_configs/2 , peek_message_queue/2 , prepare_patron/1 , prep_initiator/2 , prep_responder/2 , rpc/4 , receive_from_fsm/4 , get_both_balances/3 ]). -include_lib("common_test/include/ct.hrl"). -include("../../aecontract/test/include/aect_sophia_vsn.hrl"). -include_lib("aecontract/include/aecontract.hrl"). -include_lib("aecontract/include/hard_forks.hrl"). -include("../../aecore/test/aec_test_utils.hrl"). -define(MINIMUM_FEE, 100). -define(DEFAULT_TIMEOUT, 3). -define(TIMEOUT, 3000). -define(SLIGHTLY_LONGER_TIMEOUT, 2000). -define(LONG_TIMEOUT, 60000). -define(PORT, 9325). -define(PEEK_MSGQ(_D), peek_message_queue(?LINE, _D)). -define(LOG(_Fmt , _ ) , log(_Fmt , _ , ? LINE , true ) ) . -define(LOG(_D , _ Fmt , _ ) , log(_Fmt , _ , ? LINE , _ D ) ) . -define(MINIMUM_DEPTH, 5). -define(MINIMUM_DEPTH_FACTOR, 10). -define(MINIMUM_DEPTH_STRATEGY, txfee). -define(INITIATOR_AMOUNT, (10000000 * aec_test_utils:min_gas_price())). -define(RESPONDER_AMOUNT, (10000000 * aec_test_utils:min_gas_price())). -define(ACCOUNT_BALANCE, max(?INITIATOR_AMOUNT, ?RESPONDER_AMOUNT) * 1000). -define(SLOGAN, {slogan, {?FUNCTION_NAME, ?LINE}}). -define(SLOGAN(I), {slogan, {?FUNCTION_NAME, ?LINE, I}}). all() -> [{group, all_tests}]. groups() -> [ {all_tests, [sequence], [ {group, happy_path} ]} , {happy_path, [sequence], [ create_3_party , simple_msg_relay , alice_pays_bob , alice_tries_early_refund , alice_gets_refund_after_timeout , bob_tries_receiving_too_late , shutdown ]} ]. suite() -> []. init_per_suite(Config) -> case aec_governance:get_network_id() of Id when Id == <<"local_iris_testnet">>; Id == <<"local_ceres_testnet">> -> aesc_fsm_SUITE:init_per_suite([{symlink, "latest.aesc_htlc"} | Config]); Other -> {skip, {only_on_iris, Other}} end. end_per_suite(Config) -> aesc_fsm_SUITE:end_per_suite(Config). init_per_group(_, Config) -> init_per_group_(Config). init_per_group_(Config) -> Node = dev1, aecore_suite_utils:reinit_with_ct_consensus(Node), prepare_patron(Node), Alice = prep_client(?ACCOUNT_BALANCE, Node), Bob = prep_client(?ACCOUNT_BALANCE, Node), #{alice := Ah, bob := Bh} = prep_hub(?ACCOUNT_BALANCE, ?ACCOUNT_BALANCE, Node), set_configs([ {alice, Alice} , {bob, Bob} , {hub_alice, Ah} , {hub_bob, Bh} , {roles, [alice, bob, hub_alice, hub_bob]} , {port, ?PORT} , {proxy, spawn_proxy()} ], Config). end_per_group(_Grp, Config) -> proxy_stop(Config), ok. init_per_testcase(TC, Config0) -> Debug = get_debug(Config0) orelse (os:getenv("CT_DEBUG") == "1"), Config = [{debug, Debug} | init_encrypt_nonce(Config0)], Config1 = case ?config(saved_config, Config) of undefined -> Config; {_Saver, SavedConf} -> SavedConf ++ Config end, proxy_register(Config1), aesc_fsm_SUITE:init_per_testcase(TC, Config1). end_per_testcase(_Case, Config) -> proxy_unregister(Config), ok. init_encrypt_nonce(Cfg) -> Nonce = crypto:strong_rand_bytes(enacl:box_NONCEBYTES()), lists:keystore(encrypt_nonce, 1, Cfg, {encrypt_nonce, Nonce}). %%%=================================================================== %%% Test state %%% %%% Note that all testcases need to return {save_config, Config}, in %%% order for the market data structure to carry forward through the %%% sequence. %%%=================================================================== create_3_party(Cfg) -> Debug = get_debug(Cfg), [Alice, Bob, Ah, Bh] = [?config(R, Cfg) || R <- [alice, bob, hub_alice, hub_bob]], %% side of the market ( Variables : Cx = Client , ) CfgA = set_configs([{responder, Ah}, {initiator, Alice}], Cfg), #{i := Ca, r := Ha} = _ChannelA = proxy_do(fun() -> create_channel_(CfgA, #{msg_forwarding => true}, Debug) end, CfgA), %% side of the market CfgB = set_configs([{responder, Bh}, {initiator, Bob}], Cfg), #{i := Cb, r := Hb} = _ChannelB = proxy_do(fun() -> create_channel_(CfgB, #{msg_forwarding => true}, Debug) end, CfgB), ?LOG("3-way Channel Market set up (no contract yet).", []), %% {Time, CompileRes} = timer:tc(fun compile_contract/0), ct:log("Time to compile contract: ~p", [Time]), ct:log("CompileRes = ~p", [CompileRes]), %% Contract for Fee = ?MINIMUM_FEE, Timeout = ?DEFAULT_TIMEOUT, CreateArgsA = contract_create_args( CompileRes, [encpub(Alice), Fee, Timeout], 10), {Ha1, Ca1, ContractPubKeyA} = proxy_do(fun() -> load_contract(CreateArgsA, Ha, Ca, CfgA) end, CfgA), ?LOG("HTLC contract loaded on Alice's channel", []), %% Contract for CreateArgsB = contract_create_args( CompileRes, [encpub(Bob), Fee, Timeout], 10), {Hb1, Cb1, ContractPubKeyB} = proxy_do(fun() -> load_contract(CreateArgsB, Hb, Cb, CfgB) end, CfgB), ?LOG("HTLC contract loaded on Bob's channel", []), {save_config, [ {market, #{ contract_meta => CompileRes , encpub(Alice) => #{ client => Ca1 , hub => Ha1 , contract => ContractPubKeyA } , encpub(Bob) => #{ client => Cb1 , hub => Hb1 , contract => ContractPubKeyB } }} ]}. simple_msg_relay(Cfg) -> #{pub := A, priv := Apriv, encoded_pub := Ae} = ?config(alice, Cfg), #{pub := B, priv := Bpriv, encoded_pub := Be} = ?config(bob, Cfg), Msg = <<"hello there!!!">>, #{Ae := #{client := Ac, hub := Ah} = _ChA, Be := #{client := Bc, hub := Bh} = _ChB} = _Market = ?config(market, Cfg), EncryptedMsg = encrypt_msg(Msg, B, Apriv, Cfg), send_inband(Ac, A, B, EncryptedMsg, Cfg), relay_msg(Ah, Bh, Cfg), receive_inband(Bc, EncryptedMsg, Cfg), {ok, Msg} = decrypt_msg(EncryptedMsg, A, Bpriv, Cfg), save_config(Cfg). encrypt_msg(Msg, TheirPub, MyPriv, Cfg) -> Nonce = ?config(encrypt_nonce, Cfg), EncPub = enacl:crypto_sign_ed25519_public_to_curve25519(TheirPub), EncPriv = enacl:crypto_sign_ed25519_secret_to_curve25519(MyPriv), enacl:box(Msg, Nonce, EncPub, EncPriv). decrypt_msg(Msg, TheirPub, MyPriv, Cfg) -> Nonce = ?config(encrypt_nonce, Cfg), EncPub = enacl:crypto_sign_ed25519_public_to_curve25519(TheirPub), EncPriv = enacl:crypto_sign_ed25519_secret_to_curve25519(MyPriv), enacl:box_open(Msg, Nonce, EncPub, EncPriv). alice_pays_bob(Cfg) -> #{encoded_pub := AlicePub} = ?config(alice, Cfg), #{encoded_pub := BobPub} = ?config(bob, Cfg), [{AlicePub, _}, {BobPub, _}] = BalancesBefore = check_all_balances([AlicePub, BobPub], Cfg), Amount = 1000, Fee = 100, Timeout = 3, T0 = timestamp(), HashLock = request_hashlock(AlicePub, BobPub, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), %% %% Transaction %% {AbsTimeout, Cfg1} = new_send(AlicePub, BobPub, Amount, Fee, Timeout, HashLock, Cfg), {{ok, _}, Cfg2} = new_receive(AlicePub, BobPub, Amount, AbsTimeout, HashLock, Cfg1), {{ok, _}, Cfg3} = recv(AlicePub, BobPub, Amount, HashLock, Cfg2), {_, Cfg4} = collect(AlicePub, BobPub, Amount, HashLock, Cfg3), %% %% T1 = timestamp(), ?LOG("Time for Alice Pays Bob: ~p ms", [T1-T0]), {ok, _BalancesAfter} = expect_balances(BalancesBefore, [{AlicePub, [{client_balance, -(Amount + Fee)}, {hub_balance, (Amount + Fee)}]}, {BobPub, [{client_balance, Amount}, {hub_balance, -Amount}]}], Cfg4), save_config(Cfg4). alice_tries_early_refund(Cfg) -> #{encoded_pub := A} = ?config(alice, Cfg), #{encoded_pub := B} = ?config(bob, Cfg), Amount = 1000, Fee = 100, Timeout = 3, %% Before = check_all_balances([A, B], Cfg), HashLock = request_hashlock(A, B, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), %% %% Transaction %% {AbsTimeout, Cfg1} = new_send(A, B, Amount, Fee, Timeout, HashLock, Cfg), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg2} = refund(A, B, Amount, HashLock, Cfg1), {ok, AfterSend} = expect_balances(Before, [{A, [{client_balance, -(Amount + Fee)}]}], Cfg2), {{ok, _}, Cfg3} = new_receive(A, B, Amount, AbsTimeout, HashLock, Cfg2), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg4} = refund(A, B, Amount, HashLock, Cfg3), {ok, AfterNewRecv} = expect_balances(AfterSend, [{B, [{hub_balance, -Amount}]}], Cfg4), {{ok,_}, Cfg5} = recv(A, B, Amount, HashLock, Cfg4), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg6} = refund(A, B, Amount, HashLock, Cfg5), {ok, AfterRecv} = expect_balances(AfterNewRecv, [{B, [{client_balance, Amount}]}], Cfg6), {_, Cfg7} = collect(A, B, Amount, HashLock, Cfg6), {ok, AfterCollect} = expect_balances(AfterRecv, [{A, [{hub_balance, (Amount + Fee)}]}], Cfg7), {{error, <<"NOT_ACTIVE">>}, Cfg8} = refund(A, B, Amount, HashLock, Cfg7), {ok, _} = expect_balances(AfterCollect, [], Cfg8), %% %% save_config(Cfg8). alice_gets_refund_after_timeout(Cfg) -> #{encoded_pub := A} = ?config(alice, Cfg), #{encoded_pub := B} = ?config(bob, Cfg), Amount = 1000, Fee = 100, Timeout = 3, %% Before = check_all_balances([A, B], Cfg), HashLock = request_hashlock(A, B, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), %% %% Transaction %% {_AbsTimeout, Cfg1} = new_send(A, B, Amount, Fee, Timeout, HashLock, Cfg), {ok, AfterSend} = expect_balances(Before, [{A, [{client_balance, -(Amount + Fee)}]}], Cfg1), %% Refund timeout is `Timeout + 3` mine_key_blocks(Timeout), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg2} = refund(A, B, Amount, HashLock, Cfg1), mine_key_blocks(3), {{ok, _}, Cfg3} = refund(A, B, Amount, HashLock, Cfg2), {ok, _AfterRefund} = expect_balances(AfterSend, [{A, [{client_balance, Amount}, {hub_balance, Fee}]}], Cfg3), save_config(Cfg3). bob_tries_receiving_too_late(Cfg) -> #{encoded_pub := A} = ?config(alice, Cfg), #{encoded_pub := B} = ?config(bob, Cfg), Amount = 1000, Fee = 100, Timeout = 3, %% Before = check_all_balances([A, B], Cfg), HashLock = request_hashlock(A, B, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), %% %% Transaction %% {AbsTimeout, Cfg1} = new_send(A, B, Amount, Fee, Timeout, HashLock, Cfg), {{ok, {{bytes,32}, {bytes, Id}}}, Cfg2} = new_receive(A, B, Amount, AbsTimeout, HashLock, Cfg1), {ok, AfterNewRecv} = expect_balances(Before, [{A, [{client_balance, -(Amount + Fee)}]}, {B, [{hub_balance, -Amount}]}], Cfg2), mine_key_blocks(Timeout), {{error, <<"RECEIVE_TIMEOUT">>}, Cfg3} = recv(A, B, Amount, HashLock, Cfg2), %% Hub must wait Timeout + 3 before claiming a collateral refund %% {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg4} = refund_receive(B, Id, Cfg3), mine_key_blocks(3), {{ok,_}, Cfg5} = refund_receive(B, Id, Cfg4), {ok, AfterRefundRecv} = expect_balances(AfterNewRecv, [{B, [{hub_balance, Amount}]}], Cfg4), {{ok,_}, Cfg6} = refund(A, B, Amount, HashLock, Cfg5), {ok, _} = expect_balances(AfterRefundRecv, [{A, [{client_balance, Amount}, {hub_balance, Fee}]}], Cfg6), save_config(Cfg6). shutdown(Config) -> Debug = get_debug(Config), Market = ?config(market, Config), ?LOG("Market = ~p", [Market]), maps:fold( fun(_ClientPub, #{client := C, hub := H}, ok) -> ConfigX = set_configs([{responder, H}, {initiator, C}], Config), proxy_do(fun() -> shutdown(C, H, ConfigX, Debug) end, ConfigX), ok end, ok, maps:remove(contract_meta, Market)), ok. save_config(Cfg) -> {save_config, [{market, ?config(market, Cfg)}]}. encpub(#{encoded_pub := P}) -> P. timestamp() -> erlang:system_time(millisecond). %%%=================================================================== %%% Market operations %%%=================================================================== request_hashlock(A, B, Amount, Cfg) -> #{A := ChA, B := ChB} = _Market = ?config(market, Cfg), Seq = erlang:unique_integer([positive, monotonic]), Req = #{ <<"req">> => <<"SEND">> , <<"id">> => Seq , <<"amount">> => Amount }, ok = inband_msg_via_hub(Req, ChA, ChB, Cfg), ?LOG("Inband msg send request:~n~p", [Req]), %% Secret = crypto:strong_rand_bytes(32), HashLock = crypto:hash(sha256, Secret), Rep = #{ <<"reply">> => <<"OK">> , <<"id">> => Seq , <<"hash_lock">> => aeser_api_encoder:encode(bytearray, HashLock) }, ok = inband_msg_via_hub(Rep, ChB, ChA, Cfg), ?LOG("Inband msg OK:~n~p", [Rep]), #{hashlock => HashLock, secret => Secret}. new_send(A, B, Amount, Fee, Timeout, #{hashlock := HashLock}, Cfg) -> {{ok, {integer, AbsTimeout}}, Cfg1} = client_calls_contract(A, <<"new_send">>, [Amount, B, Fee, Timeout, HashLock], Amount + Fee, Cfg), ?LOG("AbsTimeout from new_send(): ~p", [AbsTimeout]), {AbsTimeout, Cfg1}. new_receive(A, B, Amount, AbsTimeout, #{hashlock := HashLock}, Cfg) -> {Res, Cfg1} = hub_calls_contract(B, <<"new_receive">>, [Amount, A, AbsTimeout, HashLock], Amount, Cfg), ?LOG("new_receive: ~p", [Res]), {Res, Cfg1}. recv(A, B, Amount, #{hashlock := HashLock, secret := Secret}, Cfg) -> {Res, Cfg1} = client_calls_contract(B, <<"receive">>, [A, Amount, HashLock, Secret], 0, Cfg), ?LOG("receive Res: ~p", [Res]), {Res, Cfg1}. collect(A, B, Amount, #{hashlock := HashLock, secret := Secret}, Cfg) -> {Res, Cfg1} = hub_calls_contract(A, <<"collect">>, [B, Amount, HashLock, Secret], 0, Cfg), ?LOG("collect Res: ~p", [Res]), {Res, Cfg1}. refund(A, B, Amount, #{hashlock := HashLock}, Cfg) -> {Res, Cfg1} = client_calls_contract(A, <<"refund">>, [B, Amount, HashLock], 0, Cfg), ?LOG("refund Res: ~p", [Res]), {Res, Cfg1}. refund_receive(B, Id, Cfg) -> {Res, Cfg1} = hub_calls_contract(B, <<"refund_receive">>, [Id], 0, Cfg), ?LOG("refund_receive Res: ~p", [Res]), {Res, Cfg1}. inband_msg_via_hub(Msg0, ChA, ChB, Cfg) -> Msg = jsx:encode(Msg0), #{ client := #{fsm := _FsmC} = Ac, hub := #{pub := HubPub} = Ah } = ChA, #{ hub := #{fsm := _FsmH} = Bh, client := #{pub := BPub} = Bc } = ChB, ok = send_inband(Ac, HubPub, Msg, Cfg), ok = receive_inband(Ah, Msg, Cfg), ok = send_inband(Bh, BPub, Msg, Cfg), ok = receive_inband(Bc, Msg, Cfg). send_inband(#{fsm := Fsm}, Pub, Msg, Cfg) -> ok = proxy_do(fun() -> rpc(dev1, aesc_fsm, inband_msg, [Fsm, Pub, Msg]) end, Cfg), ok. send_inband(#{fsm := Fsm}, From, To, Msg, Cfg) -> ok = proxy_do(fun() -> rpc(dev1, aesc_fsm, inband_msg, [Fsm, From, To, Msg]) end, Cfg). receive_inband(R, Msg, Cfg) -> {ok, Res} = receive_from_fsm( message, R, fun(#{info := #{info := M}}) when M == Msg -> ok end, 1000), ?LOG(get_debug(Cfg), "received inband: ~p", [Res]), ok. relay_msg(Ah, Bh, Cfg) -> {ok, Res} = receive_from_fsm( message, Ah, fun(#{notice := please_forward}) -> ok end, 1000), ?LOG(get_debug(Cfg), "relay got ~p", [Res]), #{info := #{from := From, to := To, info := Msg}} = Res, send_inband(Bh, From, To, Msg, Cfg), ok. client_calls_contract(ChId, F, Args, Deposit, Cfg) -> call_contract_({client, hub}, ChId, F, Args, Deposit, Cfg). hub_calls_contract(ChId, F, Args, Deposit, Cfg) -> call_contract_({hub, client}, ChId, F, Args, Deposit, Cfg). call_contract_({A, B}, ChId, F, Args, Deposit, Cfg) -> Debug = get_debug(Cfg), #{contract_meta := CMeta, ChId := Ch} = ?config(market, Cfg), #{contract := Contract, A := Caller, B := Responder} = Ch, {Caller1, Responder1, CallRes} = contract_call(Contract, F, Args, Deposit, Caller, Responder, CMeta, Cfg), Cfg1 = update_market(ChId, Ch#{A := Caller1, B := Responder1}, Cfg), ?LOG(Debug, "Client contract call (~p) -> ~p", [F, CallRes]), {CallRes, Cfg1}. update_market(ChId, Ch, Cfg) -> M = ?config(market, Cfg), set_configs([{market, M#{ChId := Ch}}], Cfg). check_all_balances(Keys, Cfg) -> Market = ?config(market, Cfg), lists:map(fun(K) -> {K, check_channel_balances(K, Market)} end, Keys). check_channel_balances(Id, Market) -> #{Id := #{client := #{fsm := Fsm, pub := CPub}, hub := #{pub := HPub}}} = Market, {CBal, HBal} = get_both_balances(Fsm, CPub, HPub), #{client_balance => CBal, hub_balance => HBal}. expect_balances(Before, Changes, Cfg) -> Keys = [K || {K, _} <- Before], After = check_all_balances(Keys, Cfg), Expected = lists:foldl(fun({K, Changes1}, Acc) -> apply_balance_changes(K, Changes1, Acc) end, Before, Changes), ?LOG("Balances~n" " before: ~p~n" " after : ~p~n" " expect: ~p", [Before, After, Expected]), {balances_after, After} = {balances_after, Expected}, {ok, After}. apply_balance_changes(K, Changes, Bs) -> lists:map(fun({K1, Map}) when K1 == K -> {K1, lists:foldl(fun({Side, Amt}, Acc) -> add_amt(Side, Amt, Acc) end, Map, Changes)}; (Other) -> Other end, Bs). add_amt(K, Amt, Map) -> maps:update_with(K, fun(V) -> V + Amt end, Map). %%%=================================================================== %%% Account preparation %%%=================================================================== prep_client(Amount, Node) -> I = prep_initiator(Amount, Node), I#{encoded_pub => encode_pub(I)}. encode_pub(#{pub := Pub}) -> aeser_api_encoder:encode(account_pubkey, Pub). prep_hub(AmountI, AmountR, Node) -> Alice = prep_responder(AmountI, Node), Bob = prep_responder(AmountR, Node), #{alice => Alice, bob => Bob}. shutdown(I, R, Cfg, Debug) -> channel_shutdown(I, R, Cfg), {ok, _} = receive_log(I, Debug), {ok, _} = receive_log(R, Debug), ok. %%%=================================================================== %%% Proxy process %%%=================================================================== spawn_proxy() -> Parent = self(), spawn(fun() -> proxy_loop(#{parent => Parent}) end). proxy_register(Config) -> Proxy = ?config(proxy, Config), link(Proxy), call_proxy({register, self()}, Config). proxy_unregister(Config) -> Proxy = ?config(proxy, Config), call_proxy({register, undefined}, Config), unlink(Proxy), ok. proxy_stop(Config) -> Proxy = ?config(proxy, Config), proxy_do(fun() -> ok end, Config), % just checking exit(Proxy, kill). proxy_do(F, Config) -> call_proxy({do, F}, Config). call_proxy(Req, Config) -> Proxy = ?config(proxy, Config), MRef = erlang:monitor(process, Proxy), Proxy ! {'$proxy_call', {self(), MRef}, Req}, receive {MRef, Result} -> erlang:demonitor(MRef), Result; {'DOWN', MRef, _, _, Reason} -> error(Reason) after 10000 -> error(timeout) end. proxy_loop(#{parent := Parent} = St) -> receive {'$proxy_call', {From, Ref}, Req} -> {Reply, St1} = proxy_handle_call(Req, From, St), From ! {Ref, Reply}, proxy_loop(St1); Msg -> case Parent of undefined -> ct:pal("PROXY (no parent): ~p", [Msg]); _ when is_pid(Parent) -> Parent ! Msg end, proxy_loop(St) end. proxy_handle_call(Req, _From, St) -> case Req of {register, Pid} -> {ok, St#{parent := Pid}}; {do, F} -> {F(), St} end. compile_contract() -> Fname = filename:join(code:lib_dir(aecontract), "../../extras/test/contracts/channel_htlc.aes"), {ok, Res} = aeso_compiler:file(Fname, [{backend, fate}]), Res. contract_create_args(CompileRes, Args, Deposit) -> {ok, CallData} = aefa_fate_code:encode_calldata( maps:get(fate_code, CompileRes), <<"init">>, Args), Code = aect_sophia:serialize(CompileRes, _SophiaVsn = 3), #{ vm_version => aect_test_utils:vm_version() , abi_version => aect_test_utils:abi_version() , deposit => Deposit , code => Code , call_data => CallData }. contract_call(ContractId, F, Args, Amount, A, B, Meta, Cfg) -> {ok, CallData} = aefa_fate_code:encode_calldata( maps:get(fate_code, Meta), F, Args), CallArgs = #{ contract => ContractId , abi_version => aect_test_utils:abi_version() , amount => Amount , call_data => CallData , return_result => true }, {A1, B1, CallRes} = aesc_fsm_SUITE:upd_call_contract(A, B, CallArgs, Cfg), {A1, B1, decode_callres(CallRes, F, Meta)}. %% NOTE: the `unit' data type comes back as `{{tuple, []}, {tuple, {}}}' %% decode_callres({ok, Value}, F, Meta) -> {ok, aefa_fate_code:decode_result(maps:get(fate_code, Meta), F, Value)}; decode_callres({error, Reason}, _, _) -> {error, Reason}; decode_callres({revert, Reason}, _F, _Meta) -> {error, aeb_fate_encoding:deserialize(Reason)}. mine_key_blocks(N) -> aecore_suite_utils:mine_key_blocks(aecore_suite_utils:node_name(dev1), N).
null
https://raw.githubusercontent.com/aeternity/aeternity/e1c5c0c9d8d599129cc8bc67b50d2caf14bd583b/apps/aechannel/test/aesc_htlc_SUITE.erl
erlang
============================================================================= @doc @end ============================================================================= test case exports ======================================================================== Strategy We reuse as much as we can from the aesc_fsm_SUITE. linked to the testcase process, and here we want to use test sequences which begin with a market setup that remains throughout the sequence. This proxy evaluates funs provided by the testcase process, and forwards all received messages to it (the testcase process 'registers' with the proxy in `init_per_testcase/2`, etc.) ======================================================================== =================================================================== Test state Note that all testcases need to return {save_config, Config}, in order for the market data structure to carry forward through the sequence. =================================================================== Transaction Transaction Transaction Refund timeout is `Timeout + 3` Transaction =================================================================== Market operations =================================================================== =================================================================== Account preparation =================================================================== =================================================================== Proxy process =================================================================== just checking NOTE: the `unit' data type comes back as `{{tuple, []}, {tuple, {}}}'
( C ) 2018 , Aeternity Anstalt Test utils for State Channel markets , using HTLC contracts -module(aesc_htlc_SUITE). -export([ all/0 , groups/0 , suite/0 , init_per_suite/1 , end_per_suite/1 , init_per_group/2 , end_per_group/2 , init_per_testcase/2 , end_per_testcase/2 ]). -export([ create_3_party/1 , simple_msg_relay/1 , alice_pays_bob/1 , alice_tries_early_refund/1 , alice_gets_refund_after_timeout/1 , bob_tries_receiving_too_late/1 , shutdown/1 ]). One quirk of the fsm_SUITE is that it spawns proxy processes which are To achieve this , we create yet another proxy process in ` init_per_group/2 ` . -import(aec_test_utils, [ get_debug/1 ]). -import(aesc_fsm_SUITE, [ create_channel_/3 , channel_shutdown/3 , prepare_contract_create_args/3 , load_contract/4 , call_contract/9 , receive_log/2 , set_configs/2 , peek_message_queue/2 , prepare_patron/1 , prep_initiator/2 , prep_responder/2 , rpc/4 , receive_from_fsm/4 , get_both_balances/3 ]). -include_lib("common_test/include/ct.hrl"). -include("../../aecontract/test/include/aect_sophia_vsn.hrl"). -include_lib("aecontract/include/aecontract.hrl"). -include_lib("aecontract/include/hard_forks.hrl"). -include("../../aecore/test/aec_test_utils.hrl"). -define(MINIMUM_FEE, 100). -define(DEFAULT_TIMEOUT, 3). -define(TIMEOUT, 3000). -define(SLIGHTLY_LONGER_TIMEOUT, 2000). -define(LONG_TIMEOUT, 60000). -define(PORT, 9325). -define(PEEK_MSGQ(_D), peek_message_queue(?LINE, _D)). -define(LOG(_Fmt , _ ) , log(_Fmt , _ , ? LINE , true ) ) . -define(LOG(_D , _ Fmt , _ ) , log(_Fmt , _ , ? LINE , _ D ) ) . -define(MINIMUM_DEPTH, 5). -define(MINIMUM_DEPTH_FACTOR, 10). -define(MINIMUM_DEPTH_STRATEGY, txfee). -define(INITIATOR_AMOUNT, (10000000 * aec_test_utils:min_gas_price())). -define(RESPONDER_AMOUNT, (10000000 * aec_test_utils:min_gas_price())). -define(ACCOUNT_BALANCE, max(?INITIATOR_AMOUNT, ?RESPONDER_AMOUNT) * 1000). -define(SLOGAN, {slogan, {?FUNCTION_NAME, ?LINE}}). -define(SLOGAN(I), {slogan, {?FUNCTION_NAME, ?LINE, I}}). all() -> [{group, all_tests}]. groups() -> [ {all_tests, [sequence], [ {group, happy_path} ]} , {happy_path, [sequence], [ create_3_party , simple_msg_relay , alice_pays_bob , alice_tries_early_refund , alice_gets_refund_after_timeout , bob_tries_receiving_too_late , shutdown ]} ]. suite() -> []. init_per_suite(Config) -> case aec_governance:get_network_id() of Id when Id == <<"local_iris_testnet">>; Id == <<"local_ceres_testnet">> -> aesc_fsm_SUITE:init_per_suite([{symlink, "latest.aesc_htlc"} | Config]); Other -> {skip, {only_on_iris, Other}} end. end_per_suite(Config) -> aesc_fsm_SUITE:end_per_suite(Config). init_per_group(_, Config) -> init_per_group_(Config). init_per_group_(Config) -> Node = dev1, aecore_suite_utils:reinit_with_ct_consensus(Node), prepare_patron(Node), Alice = prep_client(?ACCOUNT_BALANCE, Node), Bob = prep_client(?ACCOUNT_BALANCE, Node), #{alice := Ah, bob := Bh} = prep_hub(?ACCOUNT_BALANCE, ?ACCOUNT_BALANCE, Node), set_configs([ {alice, Alice} , {bob, Bob} , {hub_alice, Ah} , {hub_bob, Bh} , {roles, [alice, bob, hub_alice, hub_bob]} , {port, ?PORT} , {proxy, spawn_proxy()} ], Config). end_per_group(_Grp, Config) -> proxy_stop(Config), ok. init_per_testcase(TC, Config0) -> Debug = get_debug(Config0) orelse (os:getenv("CT_DEBUG") == "1"), Config = [{debug, Debug} | init_encrypt_nonce(Config0)], Config1 = case ?config(saved_config, Config) of undefined -> Config; {_Saver, SavedConf} -> SavedConf ++ Config end, proxy_register(Config1), aesc_fsm_SUITE:init_per_testcase(TC, Config1). end_per_testcase(_Case, Config) -> proxy_unregister(Config), ok. init_encrypt_nonce(Cfg) -> Nonce = crypto:strong_rand_bytes(enacl:box_NONCEBYTES()), lists:keystore(encrypt_nonce, 1, Cfg, {encrypt_nonce, Nonce}). create_3_party(Cfg) -> Debug = get_debug(Cfg), [Alice, Bob, Ah, Bh] = [?config(R, Cfg) || R <- [alice, bob, hub_alice, hub_bob]], side of the market ( Variables : Cx = Client , ) CfgA = set_configs([{responder, Ah}, {initiator, Alice}], Cfg), #{i := Ca, r := Ha} = _ChannelA = proxy_do(fun() -> create_channel_(CfgA, #{msg_forwarding => true}, Debug) end, CfgA), side of the market CfgB = set_configs([{responder, Bh}, {initiator, Bob}], Cfg), #{i := Cb, r := Hb} = _ChannelB = proxy_do(fun() -> create_channel_(CfgB, #{msg_forwarding => true}, Debug) end, CfgB), ?LOG("3-way Channel Market set up (no contract yet).", []), {Time, CompileRes} = timer:tc(fun compile_contract/0), ct:log("Time to compile contract: ~p", [Time]), ct:log("CompileRes = ~p", [CompileRes]), Contract for Fee = ?MINIMUM_FEE, Timeout = ?DEFAULT_TIMEOUT, CreateArgsA = contract_create_args( CompileRes, [encpub(Alice), Fee, Timeout], 10), {Ha1, Ca1, ContractPubKeyA} = proxy_do(fun() -> load_contract(CreateArgsA, Ha, Ca, CfgA) end, CfgA), ?LOG("HTLC contract loaded on Alice's channel", []), Contract for CreateArgsB = contract_create_args( CompileRes, [encpub(Bob), Fee, Timeout], 10), {Hb1, Cb1, ContractPubKeyB} = proxy_do(fun() -> load_contract(CreateArgsB, Hb, Cb, CfgB) end, CfgB), ?LOG("HTLC contract loaded on Bob's channel", []), {save_config, [ {market, #{ contract_meta => CompileRes , encpub(Alice) => #{ client => Ca1 , hub => Ha1 , contract => ContractPubKeyA } , encpub(Bob) => #{ client => Cb1 , hub => Hb1 , contract => ContractPubKeyB } }} ]}. simple_msg_relay(Cfg) -> #{pub := A, priv := Apriv, encoded_pub := Ae} = ?config(alice, Cfg), #{pub := B, priv := Bpriv, encoded_pub := Be} = ?config(bob, Cfg), Msg = <<"hello there!!!">>, #{Ae := #{client := Ac, hub := Ah} = _ChA, Be := #{client := Bc, hub := Bh} = _ChB} = _Market = ?config(market, Cfg), EncryptedMsg = encrypt_msg(Msg, B, Apriv, Cfg), send_inband(Ac, A, B, EncryptedMsg, Cfg), relay_msg(Ah, Bh, Cfg), receive_inband(Bc, EncryptedMsg, Cfg), {ok, Msg} = decrypt_msg(EncryptedMsg, A, Bpriv, Cfg), save_config(Cfg). encrypt_msg(Msg, TheirPub, MyPriv, Cfg) -> Nonce = ?config(encrypt_nonce, Cfg), EncPub = enacl:crypto_sign_ed25519_public_to_curve25519(TheirPub), EncPriv = enacl:crypto_sign_ed25519_secret_to_curve25519(MyPriv), enacl:box(Msg, Nonce, EncPub, EncPriv). decrypt_msg(Msg, TheirPub, MyPriv, Cfg) -> Nonce = ?config(encrypt_nonce, Cfg), EncPub = enacl:crypto_sign_ed25519_public_to_curve25519(TheirPub), EncPriv = enacl:crypto_sign_ed25519_secret_to_curve25519(MyPriv), enacl:box_open(Msg, Nonce, EncPub, EncPriv). alice_pays_bob(Cfg) -> #{encoded_pub := AlicePub} = ?config(alice, Cfg), #{encoded_pub := BobPub} = ?config(bob, Cfg), [{AlicePub, _}, {BobPub, _}] = BalancesBefore = check_all_balances([AlicePub, BobPub], Cfg), Amount = 1000, Fee = 100, Timeout = 3, T0 = timestamp(), HashLock = request_hashlock(AlicePub, BobPub, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), {AbsTimeout, Cfg1} = new_send(AlicePub, BobPub, Amount, Fee, Timeout, HashLock, Cfg), {{ok, _}, Cfg2} = new_receive(AlicePub, BobPub, Amount, AbsTimeout, HashLock, Cfg1), {{ok, _}, Cfg3} = recv(AlicePub, BobPub, Amount, HashLock, Cfg2), {_, Cfg4} = collect(AlicePub, BobPub, Amount, HashLock, Cfg3), T1 = timestamp(), ?LOG("Time for Alice Pays Bob: ~p ms", [T1-T0]), {ok, _BalancesAfter} = expect_balances(BalancesBefore, [{AlicePub, [{client_balance, -(Amount + Fee)}, {hub_balance, (Amount + Fee)}]}, {BobPub, [{client_balance, Amount}, {hub_balance, -Amount}]}], Cfg4), save_config(Cfg4). alice_tries_early_refund(Cfg) -> #{encoded_pub := A} = ?config(alice, Cfg), #{encoded_pub := B} = ?config(bob, Cfg), Amount = 1000, Fee = 100, Timeout = 3, Before = check_all_balances([A, B], Cfg), HashLock = request_hashlock(A, B, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), {AbsTimeout, Cfg1} = new_send(A, B, Amount, Fee, Timeout, HashLock, Cfg), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg2} = refund(A, B, Amount, HashLock, Cfg1), {ok, AfterSend} = expect_balances(Before, [{A, [{client_balance, -(Amount + Fee)}]}], Cfg2), {{ok, _}, Cfg3} = new_receive(A, B, Amount, AbsTimeout, HashLock, Cfg2), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg4} = refund(A, B, Amount, HashLock, Cfg3), {ok, AfterNewRecv} = expect_balances(AfterSend, [{B, [{hub_balance, -Amount}]}], Cfg4), {{ok,_}, Cfg5} = recv(A, B, Amount, HashLock, Cfg4), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg6} = refund(A, B, Amount, HashLock, Cfg5), {ok, AfterRecv} = expect_balances(AfterNewRecv, [{B, [{client_balance, Amount}]}], Cfg6), {_, Cfg7} = collect(A, B, Amount, HashLock, Cfg6), {ok, AfterCollect} = expect_balances(AfterRecv, [{A, [{hub_balance, (Amount + Fee)}]}], Cfg7), {{error, <<"NOT_ACTIVE">>}, Cfg8} = refund(A, B, Amount, HashLock, Cfg7), {ok, _} = expect_balances(AfterCollect, [], Cfg8), save_config(Cfg8). alice_gets_refund_after_timeout(Cfg) -> #{encoded_pub := A} = ?config(alice, Cfg), #{encoded_pub := B} = ?config(bob, Cfg), Amount = 1000, Fee = 100, Timeout = 3, Before = check_all_balances([A, B], Cfg), HashLock = request_hashlock(A, B, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), {_AbsTimeout, Cfg1} = new_send(A, B, Amount, Fee, Timeout, HashLock, Cfg), {ok, AfterSend} = expect_balances(Before, [{A, [{client_balance, -(Amount + Fee)}]}], Cfg1), mine_key_blocks(Timeout), {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg2} = refund(A, B, Amount, HashLock, Cfg1), mine_key_blocks(3), {{ok, _}, Cfg3} = refund(A, B, Amount, HashLock, Cfg2), {ok, _AfterRefund} = expect_balances(AfterSend, [{A, [{client_balance, Amount}, {hub_balance, Fee}]}], Cfg3), save_config(Cfg3). bob_tries_receiving_too_late(Cfg) -> #{encoded_pub := A} = ?config(alice, Cfg), #{encoded_pub := B} = ?config(bob, Cfg), Amount = 1000, Fee = 100, Timeout = 3, Before = check_all_balances([A, B], Cfg), HashLock = request_hashlock(A, B, Amount, Cfg), ?LOG("Hashlock Res = ~p", [HashLock]), {AbsTimeout, Cfg1} = new_send(A, B, Amount, Fee, Timeout, HashLock, Cfg), {{ok, {{bytes,32}, {bytes, Id}}}, Cfg2} = new_receive(A, B, Amount, AbsTimeout, HashLock, Cfg1), {ok, AfterNewRecv} = expect_balances(Before, [{A, [{client_balance, -(Amount + Fee)}]}, {B, [{hub_balance, -Amount}]}], Cfg2), mine_key_blocks(Timeout), {{error, <<"RECEIVE_TIMEOUT">>}, Cfg3} = recv(A, B, Amount, HashLock, Cfg2), Hub must wait Timeout + 3 before claiming a collateral refund {{error, <<"NOT_YET_REFUNDABLE">>}, Cfg4} = refund_receive(B, Id, Cfg3), mine_key_blocks(3), {{ok,_}, Cfg5} = refund_receive(B, Id, Cfg4), {ok, AfterRefundRecv} = expect_balances(AfterNewRecv, [{B, [{hub_balance, Amount}]}], Cfg4), {{ok,_}, Cfg6} = refund(A, B, Amount, HashLock, Cfg5), {ok, _} = expect_balances(AfterRefundRecv, [{A, [{client_balance, Amount}, {hub_balance, Fee}]}], Cfg6), save_config(Cfg6). shutdown(Config) -> Debug = get_debug(Config), Market = ?config(market, Config), ?LOG("Market = ~p", [Market]), maps:fold( fun(_ClientPub, #{client := C, hub := H}, ok) -> ConfigX = set_configs([{responder, H}, {initiator, C}], Config), proxy_do(fun() -> shutdown(C, H, ConfigX, Debug) end, ConfigX), ok end, ok, maps:remove(contract_meta, Market)), ok. save_config(Cfg) -> {save_config, [{market, ?config(market, Cfg)}]}. encpub(#{encoded_pub := P}) -> P. timestamp() -> erlang:system_time(millisecond). request_hashlock(A, B, Amount, Cfg) -> #{A := ChA, B := ChB} = _Market = ?config(market, Cfg), Seq = erlang:unique_integer([positive, monotonic]), Req = #{ <<"req">> => <<"SEND">> , <<"id">> => Seq , <<"amount">> => Amount }, ok = inband_msg_via_hub(Req, ChA, ChB, Cfg), ?LOG("Inband msg send request:~n~p", [Req]), Secret = crypto:strong_rand_bytes(32), HashLock = crypto:hash(sha256, Secret), Rep = #{ <<"reply">> => <<"OK">> , <<"id">> => Seq , <<"hash_lock">> => aeser_api_encoder:encode(bytearray, HashLock) }, ok = inband_msg_via_hub(Rep, ChB, ChA, Cfg), ?LOG("Inband msg OK:~n~p", [Rep]), #{hashlock => HashLock, secret => Secret}. new_send(A, B, Amount, Fee, Timeout, #{hashlock := HashLock}, Cfg) -> {{ok, {integer, AbsTimeout}}, Cfg1} = client_calls_contract(A, <<"new_send">>, [Amount, B, Fee, Timeout, HashLock], Amount + Fee, Cfg), ?LOG("AbsTimeout from new_send(): ~p", [AbsTimeout]), {AbsTimeout, Cfg1}. new_receive(A, B, Amount, AbsTimeout, #{hashlock := HashLock}, Cfg) -> {Res, Cfg1} = hub_calls_contract(B, <<"new_receive">>, [Amount, A, AbsTimeout, HashLock], Amount, Cfg), ?LOG("new_receive: ~p", [Res]), {Res, Cfg1}. recv(A, B, Amount, #{hashlock := HashLock, secret := Secret}, Cfg) -> {Res, Cfg1} = client_calls_contract(B, <<"receive">>, [A, Amount, HashLock, Secret], 0, Cfg), ?LOG("receive Res: ~p", [Res]), {Res, Cfg1}. collect(A, B, Amount, #{hashlock := HashLock, secret := Secret}, Cfg) -> {Res, Cfg1} = hub_calls_contract(A, <<"collect">>, [B, Amount, HashLock, Secret], 0, Cfg), ?LOG("collect Res: ~p", [Res]), {Res, Cfg1}. refund(A, B, Amount, #{hashlock := HashLock}, Cfg) -> {Res, Cfg1} = client_calls_contract(A, <<"refund">>, [B, Amount, HashLock], 0, Cfg), ?LOG("refund Res: ~p", [Res]), {Res, Cfg1}. refund_receive(B, Id, Cfg) -> {Res, Cfg1} = hub_calls_contract(B, <<"refund_receive">>, [Id], 0, Cfg), ?LOG("refund_receive Res: ~p", [Res]), {Res, Cfg1}. inband_msg_via_hub(Msg0, ChA, ChB, Cfg) -> Msg = jsx:encode(Msg0), #{ client := #{fsm := _FsmC} = Ac, hub := #{pub := HubPub} = Ah } = ChA, #{ hub := #{fsm := _FsmH} = Bh, client := #{pub := BPub} = Bc } = ChB, ok = send_inband(Ac, HubPub, Msg, Cfg), ok = receive_inband(Ah, Msg, Cfg), ok = send_inband(Bh, BPub, Msg, Cfg), ok = receive_inband(Bc, Msg, Cfg). send_inband(#{fsm := Fsm}, Pub, Msg, Cfg) -> ok = proxy_do(fun() -> rpc(dev1, aesc_fsm, inband_msg, [Fsm, Pub, Msg]) end, Cfg), ok. send_inband(#{fsm := Fsm}, From, To, Msg, Cfg) -> ok = proxy_do(fun() -> rpc(dev1, aesc_fsm, inband_msg, [Fsm, From, To, Msg]) end, Cfg). receive_inband(R, Msg, Cfg) -> {ok, Res} = receive_from_fsm( message, R, fun(#{info := #{info := M}}) when M == Msg -> ok end, 1000), ?LOG(get_debug(Cfg), "received inband: ~p", [Res]), ok. relay_msg(Ah, Bh, Cfg) -> {ok, Res} = receive_from_fsm( message, Ah, fun(#{notice := please_forward}) -> ok end, 1000), ?LOG(get_debug(Cfg), "relay got ~p", [Res]), #{info := #{from := From, to := To, info := Msg}} = Res, send_inband(Bh, From, To, Msg, Cfg), ok. client_calls_contract(ChId, F, Args, Deposit, Cfg) -> call_contract_({client, hub}, ChId, F, Args, Deposit, Cfg). hub_calls_contract(ChId, F, Args, Deposit, Cfg) -> call_contract_({hub, client}, ChId, F, Args, Deposit, Cfg). call_contract_({A, B}, ChId, F, Args, Deposit, Cfg) -> Debug = get_debug(Cfg), #{contract_meta := CMeta, ChId := Ch} = ?config(market, Cfg), #{contract := Contract, A := Caller, B := Responder} = Ch, {Caller1, Responder1, CallRes} = contract_call(Contract, F, Args, Deposit, Caller, Responder, CMeta, Cfg), Cfg1 = update_market(ChId, Ch#{A := Caller1, B := Responder1}, Cfg), ?LOG(Debug, "Client contract call (~p) -> ~p", [F, CallRes]), {CallRes, Cfg1}. update_market(ChId, Ch, Cfg) -> M = ?config(market, Cfg), set_configs([{market, M#{ChId := Ch}}], Cfg). check_all_balances(Keys, Cfg) -> Market = ?config(market, Cfg), lists:map(fun(K) -> {K, check_channel_balances(K, Market)} end, Keys). check_channel_balances(Id, Market) -> #{Id := #{client := #{fsm := Fsm, pub := CPub}, hub := #{pub := HPub}}} = Market, {CBal, HBal} = get_both_balances(Fsm, CPub, HPub), #{client_balance => CBal, hub_balance => HBal}. expect_balances(Before, Changes, Cfg) -> Keys = [K || {K, _} <- Before], After = check_all_balances(Keys, Cfg), Expected = lists:foldl(fun({K, Changes1}, Acc) -> apply_balance_changes(K, Changes1, Acc) end, Before, Changes), ?LOG("Balances~n" " before: ~p~n" " after : ~p~n" " expect: ~p", [Before, After, Expected]), {balances_after, After} = {balances_after, Expected}, {ok, After}. apply_balance_changes(K, Changes, Bs) -> lists:map(fun({K1, Map}) when K1 == K -> {K1, lists:foldl(fun({Side, Amt}, Acc) -> add_amt(Side, Amt, Acc) end, Map, Changes)}; (Other) -> Other end, Bs). add_amt(K, Amt, Map) -> maps:update_with(K, fun(V) -> V + Amt end, Map). prep_client(Amount, Node) -> I = prep_initiator(Amount, Node), I#{encoded_pub => encode_pub(I)}. encode_pub(#{pub := Pub}) -> aeser_api_encoder:encode(account_pubkey, Pub). prep_hub(AmountI, AmountR, Node) -> Alice = prep_responder(AmountI, Node), Bob = prep_responder(AmountR, Node), #{alice => Alice, bob => Bob}. shutdown(I, R, Cfg, Debug) -> channel_shutdown(I, R, Cfg), {ok, _} = receive_log(I, Debug), {ok, _} = receive_log(R, Debug), ok. spawn_proxy() -> Parent = self(), spawn(fun() -> proxy_loop(#{parent => Parent}) end). proxy_register(Config) -> Proxy = ?config(proxy, Config), link(Proxy), call_proxy({register, self()}, Config). proxy_unregister(Config) -> Proxy = ?config(proxy, Config), call_proxy({register, undefined}, Config), unlink(Proxy), ok. proxy_stop(Config) -> Proxy = ?config(proxy, Config), exit(Proxy, kill). proxy_do(F, Config) -> call_proxy({do, F}, Config). call_proxy(Req, Config) -> Proxy = ?config(proxy, Config), MRef = erlang:monitor(process, Proxy), Proxy ! {'$proxy_call', {self(), MRef}, Req}, receive {MRef, Result} -> erlang:demonitor(MRef), Result; {'DOWN', MRef, _, _, Reason} -> error(Reason) after 10000 -> error(timeout) end. proxy_loop(#{parent := Parent} = St) -> receive {'$proxy_call', {From, Ref}, Req} -> {Reply, St1} = proxy_handle_call(Req, From, St), From ! {Ref, Reply}, proxy_loop(St1); Msg -> case Parent of undefined -> ct:pal("PROXY (no parent): ~p", [Msg]); _ when is_pid(Parent) -> Parent ! Msg end, proxy_loop(St) end. proxy_handle_call(Req, _From, St) -> case Req of {register, Pid} -> {ok, St#{parent := Pid}}; {do, F} -> {F(), St} end. compile_contract() -> Fname = filename:join(code:lib_dir(aecontract), "../../extras/test/contracts/channel_htlc.aes"), {ok, Res} = aeso_compiler:file(Fname, [{backend, fate}]), Res. contract_create_args(CompileRes, Args, Deposit) -> {ok, CallData} = aefa_fate_code:encode_calldata( maps:get(fate_code, CompileRes), <<"init">>, Args), Code = aect_sophia:serialize(CompileRes, _SophiaVsn = 3), #{ vm_version => aect_test_utils:vm_version() , abi_version => aect_test_utils:abi_version() , deposit => Deposit , code => Code , call_data => CallData }. contract_call(ContractId, F, Args, Amount, A, B, Meta, Cfg) -> {ok, CallData} = aefa_fate_code:encode_calldata( maps:get(fate_code, Meta), F, Args), CallArgs = #{ contract => ContractId , abi_version => aect_test_utils:abi_version() , amount => Amount , call_data => CallData , return_result => true }, {A1, B1, CallRes} = aesc_fsm_SUITE:upd_call_contract(A, B, CallArgs, Cfg), {A1, B1, decode_callres(CallRes, F, Meta)}. decode_callres({ok, Value}, F, Meta) -> {ok, aefa_fate_code:decode_result(maps:get(fate_code, Meta), F, Value)}; decode_callres({error, Reason}, _, _) -> {error, Reason}; decode_callres({revert, Reason}, _F, _Meta) -> {error, aeb_fate_encoding:deserialize(Reason)}. mine_key_blocks(N) -> aecore_suite_utils:mine_key_blocks(aecore_suite_utils:node_name(dev1), N).
1f42606424e5f5de5c9e764602f9875b7b40017ea1b10453fd4ce2a8430afbf2
plumatic/grab-bag
bucket.clj
(ns store.bucket (:refer-clojure :exclude [get get-in put keys seq count sync update merge vals empty? update-in]) (:use [plumbing.core :exclude [update]]) (:require [clojure.core :as clojure] [clojure.java.io :as java-io] [ring.util.codec :as codec] [plumbing.chm :as chm] [plumbing.error :as err] [plumbing.graph :as graph] [plumbing.parallel :as parallel] [plumbing.resource :as resource] [plumbing.serialize :as serialize]) (:import [java.io ByteArrayOutputStream File] [java.util.concurrent ConcurrentHashMap ConcurrentMap] [org.apache.commons.io IOUtils])) (set! *warn-on-reflection* true) (defprotocol IReadBucket (get [this k] "fetch value for key") (batch-get [this ks] "return seq of [k v] pairs") (exists? [this k] "does key exist in bucket") (keys [this] "seq of existing keys") (vals [this] "seq of existing vals") (seq [this] "seq of [k v] elems") (count [this] "the number of kv pairs in this bucket (boxed Long)")) (defn empty? [b] (-> b count zero?)) (defn pseq "Parallel bucket/seq in n-threads. Not lazy." [b n-threads] (parallel/map-work n-threads (fn [k] [k (get b k)]) (keys b))) (defprotocol IWriteBucket (put [this k v] "write value for key. return value can be anything") (batch-put [this kvs] "put a seq of [k v] pairs") (delete [this k] "remove key-value pair") (update [this k f]) (sync [this]) (close [this])) (defmacro get! "Get the value in the bucket under key k. If the key is not present, set the value to the result of default-expr and return it." [m k default-expr] `(let [m# ~m k# ~k] (or (get m# k#) (let [nv# ~default-expr] (put m# k# nv#) nv#)))) (defn update-in [b [k & ks] f] (if-not (clojure.core/seq ks) (update b k f) (update b k #(clojure.core/update-in % (vec ks) f)))) (defn get-in [b [k & ks]] (clojure.core/get-in (get b k) ks)) (extend-type store.bucket.IWriteBucket resource/PCloseable (close [this] (close this))) (defprotocol IMergeBucket (merge [this k v] "merge v into current value") (batch-merge [this kvs] "merge key valye pairs kvs into current values")) (defprotocol IConditionalWriteBucket (put-cond [this k v old-v] "Put v under k and return true iff old value is old-v, else return false.")) (defprotocol IOptimizeBucket (optimize [this] "optimize for in order reads from disk on :keys and :seq requests")) Default Bucket Operations (defn default-batch-put [b kvs] (doseq [[k v] kvs] (put b k v))) (defn default-batch-get [b ks] (for [k ks] [k (get b k)])) ;;TODO: put on the protocol, implementations can be much more efficient deleting with cursor. (defn clear [b] (doseq [k (keys b)] (delete b k))) (defn default-update [b k f] (->> k (get b) f (put b k))) (defn default-seq [b] (for [k (keys b)] [k (get b k)])) (defn default-merge [b merge-fn k v] (assert merge-fn) (update b k (fn [v-to] (merge-fn k v-to v)))) (defn default-batch-merge [b merge-fn kvs] (assert merge-fn) (doseq [[k v] kvs] (update b k (fn [v-to] (merge-fn k v-to v))))) ;; make this a deftype for purposes of extend-type (deftype HashmapBucket [^ConcurrentMap h merge-fn] IReadBucket (keys [this] (clojure.core/seq (.keySet h))) (vals [this] (clojure.core/seq (.values h))) (get [this k] (.get h k)) (batch-get [this ks] (default-batch-get this ks)) (seq [this] (clojure.core/seq (for [^java.util.Map$Entry e (.entrySet h)] [(.getKey e) (.getValue e)]))) (exists? [this k] (.containsKey h k)) (count [this] (long (.size h))) IMergeBucket (merge [this k v] (default-merge this merge-fn k v)) (batch-merge [this kvs] (default-batch-merge this merge-fn kvs)) IWriteBucket (put [this k v] (.put h k v)) (batch-put [this kvs] (default-batch-put this kvs)) (delete [this k] (.remove h k)) (update [this k f] (chm/update! h k f)) (sync [this] nil) (close [this] nil) IConditionalWriteBucket (put-cond [this k v old-v] (chm/try-replace! h k v old-v))) (defn hashmap-bucket [^ConcurrentMap h & [merge-fn]] (->HashmapBucket h merge-fn)) (defn lru-hashmap-bucket [cache-size & [entry-weight-fn]] (hashmap-bucket (chm/lru-chm cache-size entry-weight-fn))) (defmulti bucket #(or (:type %) :mem)) (defn write-blocks! [b writes block-size] (doseq [blocks (partition-all block-size writes) :when blocks [op vs] (group-by first blocks)] (when op (case op :put (batch-put b (map second vs)) :update (batch-merge b (map second vs)))))) (defn drain-seq [b] (->> (keys b) (map (fn [k] (let [[v op] (delete b k)] [op [k v]]))))) (defn with-flush "Takes a bucket with a merge fn and wraps with an in-memory cache that can be flushed with sync. Read operations read from the underlying store, and will not reflect unflushed writes." ([b merge-fn & {:keys [block-size] :or {block-size 100}}] (let [mem-bucket (bucket {:type :mem})] (reify IReadBucket (get [this k] (get b k)) (exists? [this k] (exists? b k)) (keys [this] (keys b)) (count [this] (long (count b))) (batch-get [this ks] (batch-get b ks)) (seq [this] (seq b)) IMergeBucket (merge [this k v] (update this k #(merge-fn k % v))) (batch-merge [this kvs] (default-batch-merge this merge-fn kvs)) IWriteBucket (update [this k f] (update mem-bucket k (fn [old-tuple] (let [[val op] (or old-tuple [nil :update])] [(f val) op])))) (delete [this k] (delete mem-bucket k) (delete b k)) (put [this k v] (put mem-bucket k [v :put])) (batch-put [this kvs] (default-batch-put this kvs)) (sync [this] (write-blocks! b (drain-seq mem-bucket) block-size) (sync b)) (close [this] (sync this) (close b)))))) ;; TODO: observe for hitrate, etc? TODO : fails if vals not present ? (defn mem-cache "full read memory cache in front of bucket b. If no-write-through? is true, then only store writes in the mem bucket but not backing. Otherwise, write-through to underlying bucket." [b & [mem no-write-through?]] (let [mem (or mem (bucket {:type :mem}))] (reify IReadBucket (get [this k] (or (get mem k) (do (let [v (get b k)] (when-not (nil? v) (put mem k v)) v)))) (exists? [this k] (get this k)) (batch-get [this ks] (default-batch-get this ks)) IWriteBucket (put [this k v] (assert (not (nil? v)) "Cannot send put nil in this bucket") (put mem k v) (when-not no-write-through? (put b k v))) (batch-put [this kvs] (default-batch-put this kvs)) (close [this] (close b)) (sync [this] (sync b)) (delete [this k] (doseq [bb [b mem]] (delete bb k)))))) (defn bounded-write-through-cache [b cache-size & [entry-weight-fn]] (mem-cache b (lru-hashmap-bucket cache-size entry-weight-fn))) (defn full-mem-cache "memory cache of the entire bucket, with write-through. Reads full contents into memory on creation, and never reads again (unless you call sync)." [backing] (let [mem (bucket {:type :mem})] (doto (reify IReadBucket (get [this k] (get mem k)) (exists? [this k] (exists? mem k)) (keys [this] (keys mem)) (vals [this] (vals mem)) (count [this] (long (count mem))) (batch-get [this ks] (batch-get mem ks)) (seq [this] (seq mem)) IWriteBucket (put [this k v] (doseq [b [backing mem]] (put b k v))) (batch-put [this kvs] (doseq [b [backing mem]] (batch-put b kvs))) (update [this k f] (default-update this k f)) (close [this] (close backing)) (sync [this] (clear mem) (batch-put mem (seq backing))) (delete [this k] (doseq [b [backing mem]] (delete b k)))) (sync)))) (defn wrapper-policy [b {:keys [merge bounded-cache-size entry-weight-fn full-cache] :as args}] (cond bounded-cache-size (bounded-write-through-cache b bounded-cache-size entry-weight-fn) full-cache (full-mem-cache b) merge (with-flush b merge) :else b)) (defn serialization-fns [serialize-method] (case serialize-method nil [(fn [x] (let [baos (ByteArrayOutputStream.)] (serialize/serialize-impl serialize/+clojure+ baos x) (.toByteArray baos))) (partial serialize/deserialize-impl serialize/+clojure+)] :raw [(let [byte-class (class (byte-array 0))] #(do (when-not (instance? byte-class %) (throw (RuntimeException. "Non-byte-array!"))) %)) #(IOUtils/toByteArray ^java.io.InputStream %)] [(partial serialize/serialize serialize-method) serialize/deserialize-stream])) (set! *warn-on-reflection* false) (defmethod bucket :fs [{:keys [name path serialize-method merge] :as args}] (err/assert-keys [:name :path] args) (let [[serialize deserialize] (serialization-fns serialize-method) dir-path (str (java-io/file path name)) f (if (string? dir-path) (java-io/file dir-path) dir-path)] (.mkdirs f) (-> (reify IReadBucket (get [this k] (let [f (File. f ^String (codec/url-encode k))] (when (.exists f) (-> f java-io/input-stream deserialize)))) (batch-get [this ks] (default-batch-get this ks)) (seq [this] (default-seq this)) (vals [this] (map second (seq this))) (exists? [this k] (let [f (File. f ^String (codec/url-encode k))] (.exists f))) (keys [this] (unchunk (for [^File c (.listFiles f) :when (and (.isFile c) (not (.isHidden c)))] (codec/url-decode (.getName c))))) (count [this] (long (clojure.core/count (keys this)))) IMergeBucket (merge [this k v] (default-merge this merge k v)) (batch-merge [this kvs] (default-batch-merge this merge kvs)) IWriteBucket (put [this k v] (let [f (File. f ^String (codec/url-encode k))] (-> v serialize (java-io/copy f)))) (batch-put [this kvs] (default-batch-put this kvs)) (delete [this k] (let [f (File. f ^String (codec/url-encode k))] (.delete f))) (update [this k f] (default-update this k f)) (sync [this] nil) (close [this] nil)) (wrapper-policy args)))) (set! *warn-on-reflection* true) (defmethod bucket :mem [{:keys [merge]}] (hashmap-bucket (ConcurrentHashMap.) merge)) (defmethod bucket :mem-lru [{:keys [cache-size entry-weight-fn] :as m}] (assert (integer? cache-size)) (lru-hashmap-bucket cache-size entry-weight-fn)) ;;; Extend Read buckets to clojure maps (def ^:private read-bucket-map-impls {:get (fn [this k] (this k)) :seq (fn [this] (clojure/seq this)) :batch-get (fn [this ks] (default-batch-get this ks)) :keys (fn [this] (clojure/keys this)) :exists? (fn [this k] (find this k)) :count (fn [this] (clojure/count this)) :vals (fn [this] (clojure/vals this))}) (doseq [c [clojure.lang.PersistentHashMap clojure.lang.PersistentArrayMap clojure.lang.PersistentStructMap]] (extend c IReadBucket read-bucket-map-impls)) (defnk bucket-resource [{env :stage} ec2-keys & bucket-args] (if (= env :test) (bucket (assoc bucket-args :type (if (= (:type bucket-args) :sql) :sql :mem))) (bucket (clojure.core/merge ec2-keys bucket-args)))) (def env-bucket (graph/instance bucket-resource [name env] {:name (str name "-" (clojure.core/name env))})) (defnk bucket-key [ec2-keys key {env :stage} & bucket-args] (if (= env :test) nil (let [b (bucket (clojure.core/merge ec2-keys bucket-args)) v (get b key)] (close b) v))) (def env-bucket-key (graph/instance bucket-key [name env] {:name (str name "-" (clojure.core/name env))})) (defn ->mem-bucket [data] (doto (bucket {}) (batch-put data))) (defn ->map "Convert a bucket into a map" [b] (into {} (seq b))) (set! *warn-on-reflection* false)
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/store/src/store/bucket.clj
clojure
TODO: put on the protocol, implementations can be much more efficient deleting with cursor. make this a deftype for purposes of extend-type TODO: observe for hitrate, etc? Extend Read buckets to clojure maps
(ns store.bucket (:refer-clojure :exclude [get get-in put keys seq count sync update merge vals empty? update-in]) (:use [plumbing.core :exclude [update]]) (:require [clojure.core :as clojure] [clojure.java.io :as java-io] [ring.util.codec :as codec] [plumbing.chm :as chm] [plumbing.error :as err] [plumbing.graph :as graph] [plumbing.parallel :as parallel] [plumbing.resource :as resource] [plumbing.serialize :as serialize]) (:import [java.io ByteArrayOutputStream File] [java.util.concurrent ConcurrentHashMap ConcurrentMap] [org.apache.commons.io IOUtils])) (set! *warn-on-reflection* true) (defprotocol IReadBucket (get [this k] "fetch value for key") (batch-get [this ks] "return seq of [k v] pairs") (exists? [this k] "does key exist in bucket") (keys [this] "seq of existing keys") (vals [this] "seq of existing vals") (seq [this] "seq of [k v] elems") (count [this] "the number of kv pairs in this bucket (boxed Long)")) (defn empty? [b] (-> b count zero?)) (defn pseq "Parallel bucket/seq in n-threads. Not lazy." [b n-threads] (parallel/map-work n-threads (fn [k] [k (get b k)]) (keys b))) (defprotocol IWriteBucket (put [this k v] "write value for key. return value can be anything") (batch-put [this kvs] "put a seq of [k v] pairs") (delete [this k] "remove key-value pair") (update [this k f]) (sync [this]) (close [this])) (defmacro get! "Get the value in the bucket under key k. If the key is not present, set the value to the result of default-expr and return it." [m k default-expr] `(let [m# ~m k# ~k] (or (get m# k#) (let [nv# ~default-expr] (put m# k# nv#) nv#)))) (defn update-in [b [k & ks] f] (if-not (clojure.core/seq ks) (update b k f) (update b k #(clojure.core/update-in % (vec ks) f)))) (defn get-in [b [k & ks]] (clojure.core/get-in (get b k) ks)) (extend-type store.bucket.IWriteBucket resource/PCloseable (close [this] (close this))) (defprotocol IMergeBucket (merge [this k v] "merge v into current value") (batch-merge [this kvs] "merge key valye pairs kvs into current values")) (defprotocol IConditionalWriteBucket (put-cond [this k v old-v] "Put v under k and return true iff old value is old-v, else return false.")) (defprotocol IOptimizeBucket (optimize [this] "optimize for in order reads from disk on :keys and :seq requests")) Default Bucket Operations (defn default-batch-put [b kvs] (doseq [[k v] kvs] (put b k v))) (defn default-batch-get [b ks] (for [k ks] [k (get b k)])) (defn clear [b] (doseq [k (keys b)] (delete b k))) (defn default-update [b k f] (->> k (get b) f (put b k))) (defn default-seq [b] (for [k (keys b)] [k (get b k)])) (defn default-merge [b merge-fn k v] (assert merge-fn) (update b k (fn [v-to] (merge-fn k v-to v)))) (defn default-batch-merge [b merge-fn kvs] (assert merge-fn) (doseq [[k v] kvs] (update b k (fn [v-to] (merge-fn k v-to v))))) (deftype HashmapBucket [^ConcurrentMap h merge-fn] IReadBucket (keys [this] (clojure.core/seq (.keySet h))) (vals [this] (clojure.core/seq (.values h))) (get [this k] (.get h k)) (batch-get [this ks] (default-batch-get this ks)) (seq [this] (clojure.core/seq (for [^java.util.Map$Entry e (.entrySet h)] [(.getKey e) (.getValue e)]))) (exists? [this k] (.containsKey h k)) (count [this] (long (.size h))) IMergeBucket (merge [this k v] (default-merge this merge-fn k v)) (batch-merge [this kvs] (default-batch-merge this merge-fn kvs)) IWriteBucket (put [this k v] (.put h k v)) (batch-put [this kvs] (default-batch-put this kvs)) (delete [this k] (.remove h k)) (update [this k f] (chm/update! h k f)) (sync [this] nil) (close [this] nil) IConditionalWriteBucket (put-cond [this k v old-v] (chm/try-replace! h k v old-v))) (defn hashmap-bucket [^ConcurrentMap h & [merge-fn]] (->HashmapBucket h merge-fn)) (defn lru-hashmap-bucket [cache-size & [entry-weight-fn]] (hashmap-bucket (chm/lru-chm cache-size entry-weight-fn))) (defmulti bucket #(or (:type %) :mem)) (defn write-blocks! [b writes block-size] (doseq [blocks (partition-all block-size writes) :when blocks [op vs] (group-by first blocks)] (when op (case op :put (batch-put b (map second vs)) :update (batch-merge b (map second vs)))))) (defn drain-seq [b] (->> (keys b) (map (fn [k] (let [[v op] (delete b k)] [op [k v]]))))) (defn with-flush "Takes a bucket with a merge fn and wraps with an in-memory cache that can be flushed with sync. Read operations read from the underlying store, and will not reflect unflushed writes." ([b merge-fn & {:keys [block-size] :or {block-size 100}}] (let [mem-bucket (bucket {:type :mem})] (reify IReadBucket (get [this k] (get b k)) (exists? [this k] (exists? b k)) (keys [this] (keys b)) (count [this] (long (count b))) (batch-get [this ks] (batch-get b ks)) (seq [this] (seq b)) IMergeBucket (merge [this k v] (update this k #(merge-fn k % v))) (batch-merge [this kvs] (default-batch-merge this merge-fn kvs)) IWriteBucket (update [this k f] (update mem-bucket k (fn [old-tuple] (let [[val op] (or old-tuple [nil :update])] [(f val) op])))) (delete [this k] (delete mem-bucket k) (delete b k)) (put [this k v] (put mem-bucket k [v :put])) (batch-put [this kvs] (default-batch-put this kvs)) (sync [this] (write-blocks! b (drain-seq mem-bucket) block-size) (sync b)) (close [this] (sync this) (close b)))))) TODO : fails if vals not present ? (defn mem-cache "full read memory cache in front of bucket b. If no-write-through? is true, then only store writes in the mem bucket but not backing. Otherwise, write-through to underlying bucket." [b & [mem no-write-through?]] (let [mem (or mem (bucket {:type :mem}))] (reify IReadBucket (get [this k] (or (get mem k) (do (let [v (get b k)] (when-not (nil? v) (put mem k v)) v)))) (exists? [this k] (get this k)) (batch-get [this ks] (default-batch-get this ks)) IWriteBucket (put [this k v] (assert (not (nil? v)) "Cannot send put nil in this bucket") (put mem k v) (when-not no-write-through? (put b k v))) (batch-put [this kvs] (default-batch-put this kvs)) (close [this] (close b)) (sync [this] (sync b)) (delete [this k] (doseq [bb [b mem]] (delete bb k)))))) (defn bounded-write-through-cache [b cache-size & [entry-weight-fn]] (mem-cache b (lru-hashmap-bucket cache-size entry-weight-fn))) (defn full-mem-cache "memory cache of the entire bucket, with write-through. Reads full contents into memory on creation, and never reads again (unless you call sync)." [backing] (let [mem (bucket {:type :mem})] (doto (reify IReadBucket (get [this k] (get mem k)) (exists? [this k] (exists? mem k)) (keys [this] (keys mem)) (vals [this] (vals mem)) (count [this] (long (count mem))) (batch-get [this ks] (batch-get mem ks)) (seq [this] (seq mem)) IWriteBucket (put [this k v] (doseq [b [backing mem]] (put b k v))) (batch-put [this kvs] (doseq [b [backing mem]] (batch-put b kvs))) (update [this k f] (default-update this k f)) (close [this] (close backing)) (sync [this] (clear mem) (batch-put mem (seq backing))) (delete [this k] (doseq [b [backing mem]] (delete b k)))) (sync)))) (defn wrapper-policy [b {:keys [merge bounded-cache-size entry-weight-fn full-cache] :as args}] (cond bounded-cache-size (bounded-write-through-cache b bounded-cache-size entry-weight-fn) full-cache (full-mem-cache b) merge (with-flush b merge) :else b)) (defn serialization-fns [serialize-method] (case serialize-method nil [(fn [x] (let [baos (ByteArrayOutputStream.)] (serialize/serialize-impl serialize/+clojure+ baos x) (.toByteArray baos))) (partial serialize/deserialize-impl serialize/+clojure+)] :raw [(let [byte-class (class (byte-array 0))] #(do (when-not (instance? byte-class %) (throw (RuntimeException. "Non-byte-array!"))) %)) #(IOUtils/toByteArray ^java.io.InputStream %)] [(partial serialize/serialize serialize-method) serialize/deserialize-stream])) (set! *warn-on-reflection* false) (defmethod bucket :fs [{:keys [name path serialize-method merge] :as args}] (err/assert-keys [:name :path] args) (let [[serialize deserialize] (serialization-fns serialize-method) dir-path (str (java-io/file path name)) f (if (string? dir-path) (java-io/file dir-path) dir-path)] (.mkdirs f) (-> (reify IReadBucket (get [this k] (let [f (File. f ^String (codec/url-encode k))] (when (.exists f) (-> f java-io/input-stream deserialize)))) (batch-get [this ks] (default-batch-get this ks)) (seq [this] (default-seq this)) (vals [this] (map second (seq this))) (exists? [this k] (let [f (File. f ^String (codec/url-encode k))] (.exists f))) (keys [this] (unchunk (for [^File c (.listFiles f) :when (and (.isFile c) (not (.isHidden c)))] (codec/url-decode (.getName c))))) (count [this] (long (clojure.core/count (keys this)))) IMergeBucket (merge [this k v] (default-merge this merge k v)) (batch-merge [this kvs] (default-batch-merge this merge kvs)) IWriteBucket (put [this k v] (let [f (File. f ^String (codec/url-encode k))] (-> v serialize (java-io/copy f)))) (batch-put [this kvs] (default-batch-put this kvs)) (delete [this k] (let [f (File. f ^String (codec/url-encode k))] (.delete f))) (update [this k f] (default-update this k f)) (sync [this] nil) (close [this] nil)) (wrapper-policy args)))) (set! *warn-on-reflection* true) (defmethod bucket :mem [{:keys [merge]}] (hashmap-bucket (ConcurrentHashMap.) merge)) (defmethod bucket :mem-lru [{:keys [cache-size entry-weight-fn] :as m}] (assert (integer? cache-size)) (lru-hashmap-bucket cache-size entry-weight-fn)) (def ^:private read-bucket-map-impls {:get (fn [this k] (this k)) :seq (fn [this] (clojure/seq this)) :batch-get (fn [this ks] (default-batch-get this ks)) :keys (fn [this] (clojure/keys this)) :exists? (fn [this k] (find this k)) :count (fn [this] (clojure/count this)) :vals (fn [this] (clojure/vals this))}) (doseq [c [clojure.lang.PersistentHashMap clojure.lang.PersistentArrayMap clojure.lang.PersistentStructMap]] (extend c IReadBucket read-bucket-map-impls)) (defnk bucket-resource [{env :stage} ec2-keys & bucket-args] (if (= env :test) (bucket (assoc bucket-args :type (if (= (:type bucket-args) :sql) :sql :mem))) (bucket (clojure.core/merge ec2-keys bucket-args)))) (def env-bucket (graph/instance bucket-resource [name env] {:name (str name "-" (clojure.core/name env))})) (defnk bucket-key [ec2-keys key {env :stage} & bucket-args] (if (= env :test) nil (let [b (bucket (clojure.core/merge ec2-keys bucket-args)) v (get b key)] (close b) v))) (def env-bucket-key (graph/instance bucket-key [name env] {:name (str name "-" (clojure.core/name env))})) (defn ->mem-bucket [data] (doto (bucket {}) (batch-put data))) (defn ->map "Convert a bucket into a map" [b] (into {} (seq b))) (set! *warn-on-reflection* false)
89ffe3b168388cbea29809ef1e240c0e75cc5a12340075455b8a1c2fe94bc9c1
erdos/stencil
util.clj
(ns stencil.util (:require [clojure.zip]) (:import [io.github.erdos.stencil.exceptions ParsingException EvalException])) (set! *warn-on-reflection* true) (defn stacks-difference-key "Removes suffixes of two lists where key-fn gives the same result." [key-fn stack1 stack2] (assert (ifn? key-fn)) (let [cnt (count (take-while true? (map (fn [a b] (= (key-fn a) (key-fn b))) (reverse stack1) (reverse stack2))))] [(take (- (count stack1) cnt) stack1) (take (- (count stack2) cnt) stack2)])) (defn update-peek "Updates top element of a stack." [xs f & args] (assert (ifn? f)) (conj (pop xs) (apply f (peek xs) args))) (defn mod-stack-top-last "Updatest last element of top elem of stack." [stack f & args] (assert (list? stack) (str "Stack is not a list: " (pr-str stack))) (apply update-peek stack update-peek f args)) (defn mod-stack-top-conj "Conjoins an element to the top item of a stack." [stack & items] (update-peek stack into items)) (defn update-some [m path f] (or (some->> (get-in m path) f (assoc-in m path)) m)) (defn fixpt [f x] (let [fx (f x)] (if (= fx x) x (recur f fx)))) (defn zipper? [loc] (-> loc meta (contains? :zip/branch?))) (defn iterations [f elem] (eduction (take-while some?) (iterate f elem))) same as ( first ( filter pred xs ) ) (defn find-first [pred xs] (reduce (fn [_ x] (if (pred x) (reduced x))) nil xs)) (defn find-last [pred xs] (reduce (fn [a x] (if (pred x) x a)) nil xs)) (def xml-zip "Like clojure.zip/xml-zip but more flexible. Only maps are considered branches." (partial clojure.zip/zipper map? (comp seq :content) (fn [node children] (assoc node :content (some-> children vec))))) (defn assoc-if-val [m k v] (if (some? v) (assoc m k v) m)) (defn suffixes [xs] (take-while seq (iterate next xs))) (defn prefixes [xs] (take-while seq (iterate butlast xs))) (defmacro fail [msg obj] (assert (string? msg)) (assert (map? obj)) `(throw (ex-info ~msg ~obj))) (defn ->int [x] (cond (nil? x) nil (string? x) (Integer/parseInt (str x)) (number? x) (int x) :else (fail "Unexpected type of input" {:type (:type x) :input x}))) (defn subs-last [^String s ^long n] (.substring s (- (.length s) n))) (defn parsing-exception [expression message] (ParsingException/fromMessage (str expression) (str message))) (defn eval-exception [message expression] (assert (string? message)) (EvalException. message expression)) ;; return xml zipper of location that matches predicate or nil (defn find-first-in-tree [predicate tree-loc] (assert (ifn? predicate)) (assert (zipper? tree-loc)) (letfn [(coords-of-first [node] (loop [children (:content node) index 0] (when-let [[c & cs] (not-empty children)] (if (predicate c) [index] (if-let [cf (coords-of-first c)] (cons index cf) (recur cs (inc index))))))) (nth-child [loc i] (loop [loc (clojure.zip/down loc), i i] (if (zero? i) loc (recur (clojure.zip/right loc) (dec i)))))] (if (predicate (clojure.zip/node tree-loc)) tree-loc (when-let [coords (coords-of-first (clojure.zip/node tree-loc))] (reduce nth-child tree-loc coords))))) (defn- dfs-walk-xml-node-1 [loc predicate edit-fn] (assert (zipper? loc)) (loop [loc loc] (if (clojure.zip/end? loc) (clojure.zip/root loc) (if (predicate (clojure.zip/node loc)) (recur (clojure.zip/next (edit-fn loc))) (recur (clojure.zip/next loc)))))) (defn dfs-walk-xml-node [xml-tree predicate edit-fn] (assert (fn? predicate)) (assert (fn? edit-fn)) (assert (map? xml-tree)) (if-let [loc (find-first-in-tree predicate (xml-zip xml-tree))] (dfs-walk-xml-node-1 loc predicate edit-fn) xml-tree)) (defn dfs-walk-xml [xml-tree predicate edit-fn] (assert (fn? edit-fn)) (dfs-walk-xml-node xml-tree predicate #(clojure.zip/edit % edit-fn))) (defn unlazy-tree [xml-tree] (assert (map? xml-tree)) (doto xml-tree (-> :content dorun))) (defmacro when-pred [pred body] `(let [b# ~body] (when (~pred b#) b#))) (defn ^String string ([values] (apply str values)) ([xform coll] (transduce xform (fn ([^Object s] (.toString s)) ([^StringBuilder b v] (.append b v))) (StringBuilder.) coll))) (defn ^{:inline (fn [c] `(case ~c (\tab \space \newline \u00A0 \u2007 \u202F ;; non-breaking spaces \u000B \u000C \u000D \u001C \u001D \u001E \u001F) true false))} whitespace? [c] (whitespace? c)) ;; like clojure.string/trim but supports a wider range of whitespace characters (defn ^String trim [^CharSequence s] (loop [right-idx (.length s)] (if (zero? right-idx) "" (if (whitespace? (.charAt s (dec right-idx))) (recur (dec right-idx)) (loop [left-idx 0] (if (whitespace? (.charAt s left-idx)) (recur (inc left-idx)) (.toString (.subSequence s left-idx right-idx)))))))) :OK
null
https://raw.githubusercontent.com/erdos/stencil/92a7dab98affd26ac7c32ab7c4ba5477f5ad1633/src/stencil/util.clj
clojure
return xml zipper of location that matches predicate or nil non-breaking spaces like clojure.string/trim but supports a wider range of whitespace characters
(ns stencil.util (:require [clojure.zip]) (:import [io.github.erdos.stencil.exceptions ParsingException EvalException])) (set! *warn-on-reflection* true) (defn stacks-difference-key "Removes suffixes of two lists where key-fn gives the same result." [key-fn stack1 stack2] (assert (ifn? key-fn)) (let [cnt (count (take-while true? (map (fn [a b] (= (key-fn a) (key-fn b))) (reverse stack1) (reverse stack2))))] [(take (- (count stack1) cnt) stack1) (take (- (count stack2) cnt) stack2)])) (defn update-peek "Updates top element of a stack." [xs f & args] (assert (ifn? f)) (conj (pop xs) (apply f (peek xs) args))) (defn mod-stack-top-last "Updatest last element of top elem of stack." [stack f & args] (assert (list? stack) (str "Stack is not a list: " (pr-str stack))) (apply update-peek stack update-peek f args)) (defn mod-stack-top-conj "Conjoins an element to the top item of a stack." [stack & items] (update-peek stack into items)) (defn update-some [m path f] (or (some->> (get-in m path) f (assoc-in m path)) m)) (defn fixpt [f x] (let [fx (f x)] (if (= fx x) x (recur f fx)))) (defn zipper? [loc] (-> loc meta (contains? :zip/branch?))) (defn iterations [f elem] (eduction (take-while some?) (iterate f elem))) same as ( first ( filter pred xs ) ) (defn find-first [pred xs] (reduce (fn [_ x] (if (pred x) (reduced x))) nil xs)) (defn find-last [pred xs] (reduce (fn [a x] (if (pred x) x a)) nil xs)) (def xml-zip "Like clojure.zip/xml-zip but more flexible. Only maps are considered branches." (partial clojure.zip/zipper map? (comp seq :content) (fn [node children] (assoc node :content (some-> children vec))))) (defn assoc-if-val [m k v] (if (some? v) (assoc m k v) m)) (defn suffixes [xs] (take-while seq (iterate next xs))) (defn prefixes [xs] (take-while seq (iterate butlast xs))) (defmacro fail [msg obj] (assert (string? msg)) (assert (map? obj)) `(throw (ex-info ~msg ~obj))) (defn ->int [x] (cond (nil? x) nil (string? x) (Integer/parseInt (str x)) (number? x) (int x) :else (fail "Unexpected type of input" {:type (:type x) :input x}))) (defn subs-last [^String s ^long n] (.substring s (- (.length s) n))) (defn parsing-exception [expression message] (ParsingException/fromMessage (str expression) (str message))) (defn eval-exception [message expression] (assert (string? message)) (EvalException. message expression)) (defn find-first-in-tree [predicate tree-loc] (assert (ifn? predicate)) (assert (zipper? tree-loc)) (letfn [(coords-of-first [node] (loop [children (:content node) index 0] (when-let [[c & cs] (not-empty children)] (if (predicate c) [index] (if-let [cf (coords-of-first c)] (cons index cf) (recur cs (inc index))))))) (nth-child [loc i] (loop [loc (clojure.zip/down loc), i i] (if (zero? i) loc (recur (clojure.zip/right loc) (dec i)))))] (if (predicate (clojure.zip/node tree-loc)) tree-loc (when-let [coords (coords-of-first (clojure.zip/node tree-loc))] (reduce nth-child tree-loc coords))))) (defn- dfs-walk-xml-node-1 [loc predicate edit-fn] (assert (zipper? loc)) (loop [loc loc] (if (clojure.zip/end? loc) (clojure.zip/root loc) (if (predicate (clojure.zip/node loc)) (recur (clojure.zip/next (edit-fn loc))) (recur (clojure.zip/next loc)))))) (defn dfs-walk-xml-node [xml-tree predicate edit-fn] (assert (fn? predicate)) (assert (fn? edit-fn)) (assert (map? xml-tree)) (if-let [loc (find-first-in-tree predicate (xml-zip xml-tree))] (dfs-walk-xml-node-1 loc predicate edit-fn) xml-tree)) (defn dfs-walk-xml [xml-tree predicate edit-fn] (assert (fn? edit-fn)) (dfs-walk-xml-node xml-tree predicate #(clojure.zip/edit % edit-fn))) (defn unlazy-tree [xml-tree] (assert (map? xml-tree)) (doto xml-tree (-> :content dorun))) (defmacro when-pred [pred body] `(let [b# ~body] (when (~pred b#) b#))) (defn ^String string ([values] (apply str values)) ([xform coll] (transduce xform (fn ([^Object s] (.toString s)) ([^StringBuilder b v] (.append b v))) (StringBuilder.) coll))) (defn ^{:inline (fn [c] `(case ~c (\tab \space \newline \u000B \u000C \u000D \u001C \u001D \u001E \u001F) true false))} whitespace? [c] (whitespace? c)) (defn ^String trim [^CharSequence s] (loop [right-idx (.length s)] (if (zero? right-idx) "" (if (whitespace? (.charAt s (dec right-idx))) (recur (dec right-idx)) (loop [left-idx 0] (if (whitespace? (.charAt s left-idx)) (recur (inc left-idx)) (.toString (.subSequence s left-idx right-idx)))))))) :OK
cc63ec26396ee41296eedf9927d5bcf98e91cc7750a3af55df673131b6cf0809
oriansj/mes-m2
getopt-long.scm
Copyright ( C ) 1998 , 2001 , 2006 Free Software Foundation , Inc. Copyright ( C ) 2017,2018 Jan ( janneke ) Nieuwenhuizen < > ;;; ;; This library is free software; you can redistribute it and/or ;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . ;; ;; This library is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Lesser General Public License for more details. ;; You should have received a copy of the GNU Lesser General Public ;; License along with this library; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA Author : ( rewritten by ) ( regexps removed by Jan ( janneke ) Nieuwenhuizen ) ( srfi-9 backport by Jan ( janneke ) Nieuwenhuizen ) ;;; Commentary: ;;; This module implements some complex command line option parsing, in ;;; the spirit of the GNU C library function `getopt_long'. Both long ;;; and short options are supported. ;;; ;;; The theory is that people should be able to constrain the set of ;;; options they want to process using a grammar, rather than some arbitrary ;;; structure. The grammar makes the option descriptions easy to read. ;;; ;;; `getopt-long' is a procedure for parsing command-line arguments in a ;;; manner consistent with other GNU programs. `option-ref' is a procedure ;;; that facilitates processing of the `getopt-long' return value. ( ARGS GRAMMAR ) Parse the arguments ARGS according to the argument list grammar GRAMMAR . ;;; ARGS should be a list of strings . Its first element should be the ;;; name of the program; subsequent elements should be the arguments ;;; that were passed to the program on the command line. The ;;; `program-arguments' procedure returns a list of this form. ;;; GRAMMAR is a list of the form : ;;; ((OPTION (PROPERTY VALUE) ...) ...) ;;; ;;; Each OPTION should be a symbol. `getopt-long' will accept a command - line option named ` --OPTION ' . ;;; Each option can have the following (PROPERTY VALUE) pairs: ;;; ;;; (single-char CHAR) --- Accept `-CHAR' as a single-character ;;; equivalent to `--OPTION'. This is how to specify traditional ;;; Unix-style flags. ( required ? ) --- If is true , the option is required . ;;; getopt-long will raise an error if it is not found in ARGS. ( value BOOL ) --- If is # t , the option accepts a value ; if ;;; it is #f, it does not; and if it is the symbol ;;; `optional', the option may appear in ARGS with or ;;; without a value. ( predicate ) --- If the option accepts a value ( i.e. you specified ` ( value # t ) ' for this option ) , then will apply to the value , and throw an exception if it returns # f. FUNC should be a procedure which ;;; accepts a string and returns a boolean value; you may need to use quasiquotes to get it into GRAMMAR . ;;; ;;; The (PROPERTY VALUE) pairs may occur in any order, but each ;;; property may occur only once. By default, options do not have ;;; single-character equivalents, are not required, and do not take ;;; values. ;;; ;;; In ARGS, single-character options may be combined, in the usual ;;; Unix fashion: ("-x" "-y") is equivalent to ("-xy"). If an option ;;; accepts values, then it must be the last option in the ;;; combination; the value is the next argument. So, for example, using ;;; the following grammar: ( ( apples ( single - char # \a ) ) ( blimps ( single - char # \b ) ( value # t ) ) ( catalexis ( single - char # \c ) ( value # t ) ) ) ;;; the following argument lists would be acceptable: ;;; ("-a" "-b" "bang" "-c" "couth") ("bang" and "couth" are the values ;;; for "blimps" and "catalexis") ;;; ("-ab" "bang" "-c" "couth") (same) ;;; ("-ac" "couth" "-b" "bang") (same) ;;; ("-abc" "couth" "bang") (an error, since `-b' is not the ;;; last option in its combination) ;;; If an option 's value is optional , then decides ;;; whether it has a value by looking at what follows it in ARGS. If ;;; the next element is does not appear to be an option itself, then ;;; that element is the option's value. ;;; ;;; The value of a long option can appear as the next element in ARGS, ;;; or it can follow the option name, separated by an `=' character. ;;; Thus, using the same grammar as above, the following argument lists ;;; are equivalent: ( " --apples " " Braeburn " " --blimps " " Goodyear " ) ( " --apples = Braeburn " " --blimps " " Goodyear " ) ( " --blimps " " Goodyear " " --apples = Braeburn " ) ;;; ;;; If the option "--" appears in ARGS, argument parsing stops there; ;;; subsequent arguments are returned as ordinary arguments, even if ;;; they resemble options. So, in the argument list: ( " --apples " " " " -- " " --blimp " " Goodyear " ) ;;; `getopt-long' will recognize the `apples' option as having the value " " , but it will not recognize the ` blimp ' option ; it will return the strings " --blimp " and " Goodyear " as ;;; ordinary argument strings. ;;; ;;; The `getopt-long' function returns the parsed argument list as an assocation list , mapping option names --- the symbols from GRAMMAR ;;; --- onto their values, or #t if the option does not accept a value. ;;; Unused options do not appear in the alist. ;;; ;;; All arguments that are not the value of any option are returned ;;; as a list, associated with the empty list. ;;; ;;; `getopt-long' throws an exception if: - it finds an unrecognized property in GRAMMAR ;;; - the value of the `single-char' property is not a character ;;; - it finds an unrecognized option in ARGS ;;; - a required option is omitted - an option that requires an argument does n't get one ;;; - an option that doesn't accept an argument does get one (this can ;;; only happen using the long option `--opt=value' syntax) ;;; - an option predicate fails ;;; ;;; So, for example: ;;; ;;; (define grammar ` ( ( lockfile - dir ( required ? # t ) ;;; (value #t) ;;; (single-char #\k) ;;; (predicate ,file-is-directory?)) ;;; (verbose (required? #f) ;;; (single-char #\v) ;;; (value #f)) ( x - includes ( single - char # \x ) ) ( rnet - server ( single - char # \y ) ;;; (predicate ,string?)))) ;;; ( ( " my - prog " " -vk " " /tmp " " foo1 " " --x - includes=/usr / include " ;;; "--rnet-server=lamprod" "--" "-fred" "foo2" "foo3") ;;; grammar) ;;; => ((() "foo1" "-fred" "foo2" "foo3") ( rnet - server . " " ) ;;; (x-includes . "/usr/include") ( lockfile - dir . " /tmp " ) ;;; (verbose . #t)) ;;; (option-ref OPTIONS KEY DEFAULT) Return value in alist OPTIONS using KEY , a symbol ; or DEFAULT if not ;;; found. The value is either a string or `#t'. ;;; ;;; For example, using the `getopt-long' return value from above: ;;; ( option - ref ( ... ) ' x - includes 42 ) = > " /usr / include " ( option - ref ( ... ) ' not - a - key ! 31 ) = > 31 ;;; Code: (define-module (mes getopt-long) #:use-module (ice-9 optargs) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9) #:export (getopt-long option-ref)) (define-record-type option-spec (%make-option-spec name value required? option-spec->single-char predicate value-policy) option-spec? (name option-spec->name set-option-spec-name!) (value option-spec->value set-option-spec-value!) (required? option-spec->required? set-option-spec-required?!) (option-spec->single-char option-spec->single-char set-option-spec-single-char!) (predicate option-spec->predicate set-option-spec-predicate!) (value-policy option-spec->value-policy set-option-spec-value-policy!)) (define (make-option-spec name) (%make-option-spec name #f #f #f #f #f)) (define (parse-option-spec desc) (let ((spec (make-option-spec (symbol->string (car desc))))) (for-each (lambda (desc-elem) (let ((given (lambda () (cadr desc-elem)))) (case (car desc-elem) ((required?) (set-option-spec-required?! spec (given))) ((value) (set-option-spec-value-policy! spec (given))) ((single-char) (or (char? (given)) (error "`single-char' value must be a char!")) (set-option-spec-single-char! spec (given))) ((predicate) (set-option-spec-predicate! spec ((lambda (pred) (lambda (name val) (or (not val) (pred val) (error "option predicate failed:" name)))) (given)))) (else (error "invalid getopt-long option property:" (car desc-elem)))))) (cdr desc)) spec)) (define (split-arg-list argument-list) ;; Scan ARGUMENT-LIST for "--" and return (BEFORE-LS . AFTER-LS). Discard the " -- " . If no " -- " is found , AFTER - LS is empty . (let loop ((yes '()) (no argument-list)) (cond ((null? no) (cons (reverse yes) no)) ((string=? "--" (car no)) (cons (reverse yes) (cdr no))) (else (loop (cons (car no) yes) (cdr no)))))) (define (expand-clumped-singles opt-ls) example : ( " --xyz " " -abc5d " ) = > ( " --xyz " " -a " " -b " " -c " " 5d " ) (let loop ((opt-ls opt-ls) (ret-ls '())) (cond ((null? opt-ls) (reverse ret-ls)) ;;; retval ((let ((opt (car opt-ls))) (and (eq? (string-ref opt 0) #\-) (> (string-length opt) 1) (char-alphabetic? (string-ref opt 1)))) (let* ((opt (car opt-ls)) (n (char->integer (string-ref opt 1))) (sub (substring opt 1 (string-length opt))) (end (string-index (substring opt 1 (string-length opt)) (negate char-alphabetic?))) (end (if end (1+ end) (string-length opt))) (singles-string (substring opt 1 end)) (singles (reverse (map (lambda (c) (string-append "-" (make-string 1 c))) (string->list singles-string)))) (extra (substring opt end))) (loop (cdr opt-ls) (append (if (string=? "" extra) singles (cons extra singles)) ret-ls)))) (else (loop (cdr opt-ls) (cons (car opt-ls) ret-ls)))))) (define (looks-like-an-option string) (eq? (string-ref string 0) #\-)) (define (process-options specs argument-ls stop-at-first-non-option) Use SPECS to scan ARGUMENT - LS ; return ( FOUND . ETC ) . FOUND is an unordered list of option specs for found options , while ETC ;; is an order-maintained list of elements in ARGUMENT-LS that are neither ;; options nor their values. (let ((idx (map (lambda (spec) (cons (option-spec->name spec) spec)) specs)) (sc-idx (map (lambda (spec) (cons (make-string 1 (option-spec->single-char spec)) spec)) (filter option-spec->single-char specs)))) (let loop ((argument-ls argument-ls) (found '()) (etc '())) (let ((eat! (lambda (spec ls) (let ((val!loop (lambda (val n-ls n-found n-etc) (set-option-spec-value! spec ;; handle multiple occurrances (cond ((option-spec->value spec) => (lambda (cur) ((if (list? cur) cons list) val cur))) (else val))) (loop n-ls n-found n-etc))) (ERR:no-arg (lambda () (error (string-append "option must be specified" " with argument:") (option-spec->name spec))))) (cond ((eq? 'optional (option-spec->value-policy spec)) (if (or (null? (cdr ls)) (looks-like-an-option (cadr ls))) (val!loop #t (cdr ls) (cons spec found) etc) (val!loop (cadr ls) (cddr ls) (cons spec found) etc))) ((eq? #t (option-spec->value-policy spec)) (if (or (null? (cdr ls)) (looks-like-an-option (cadr ls))) (ERR:no-arg) (val!loop (cadr ls) (cddr ls) (cons spec found) etc))) (else (val!loop #t (cdr ls) (cons spec found) etc))))))) (if (null? argument-ls) (cons found (reverse etc)) ;;; retval (cond ((let ((opt (car argument-ls))) (and (eq? (string-ref opt 0) #\-) (> (string-length opt) 1) (let ((n (char->integer (string-ref opt 1)))) (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z))) (and (>= n (char->integer #\a)) (<= n (char->integer #\z))))))) (let* ((c (substring (car argument-ls) 1 2)) (spec (or (assoc-ref sc-idx c) (error "no such option:" (car argument-ls))))) (eat! spec argument-ls))) ((let ((opt (car argument-ls))) (and (string-prefix? "--" opt) (let ((n (char->integer (string-ref opt 2)))) (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z))) (and (>= n (char->integer #\a)) (<= n (char->integer #\z))))) (not (string-index opt #\space)) (not (string-index opt #\=)))) (let* ((opt (substring (car argument-ls) 2)) (spec (or (assoc-ref idx opt) (error "no such option:" (car argument-ls))))) (eat! spec argument-ls))) ((let ((opt (car argument-ls))) (and (string-prefix? "--" opt) (let ((n (char->integer (string-ref opt 2)))) (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z))) (and (>= n (char->integer #\a)) (<= n (char->integer #\z))))) (or (string-index opt #\=) (string-index opt #\space)))) (let* ((is (or (string-index (car argument-ls) #\=) (string-index (car argument-ls) #\space))) (opt (substring (car argument-ls) 2 is)) (spec (or (assoc-ref idx opt) (error "no such option:" (substring opt is))))) (if (option-spec->value-policy spec) (eat! spec (append (list 'ignored (substring (car argument-ls) (1+ is))) (cdr argument-ls))) (error "option does not support argument:" opt)))) (stop-at-first-non-option (cons found (append (reverse etc) argument-ls))) (else (loop (cdr argument-ls) found (cons (car argument-ls) etc))))))))) (define* (getopt-long program-arguments option-desc-list #:key stop-at-first-non-option) "Process options, handling both long and short options, similar to the glibc function 'getopt_long'. PROGRAM-ARGUMENTS should be a value similar to what (program-arguments) returns. OPTION-DESC-LIST is a list of option descriptions. Each option description must satisfy the following grammar: <option-spec> :: (<name> . <attribute-ls>) <attribute-ls> :: (<attribute> . <attribute-ls>) | () <attribute> :: <required-attribute> | <arg-required-attribute> | <single-char-attribute> | <predicate-attribute> | <value-attribute> <required-attribute> :: (required? <boolean>) <single-char-attribute> :: (single-char <char>) <value-attribute> :: (value #t) (value #f) (value optional) <predicate-attribute> :: (predicate <1-ary-function>) The procedure returns an alist of option names and values. Each option name is a symbol. The option value will be '#t' if no value was specified. There is a special item in the returned alist with a key of the empty list, (): the list of arguments that are not options or option values. By default, options are not required, and option values are not required. By default, single character equivalents are not supported; if you want to allow the user to use single character options, you need to add a `single-char' clause to the option description." (let* ((specifications (map parse-option-spec option-desc-list)) (pair (split-arg-list (cdr program-arguments) )) (split-ls (expand-clumped-singles (car pair))) (non-split-ls (cdr pair)) (found/etc (process-options specifications split-ls stop-at-first-non-option)) (found (car found/etc)) (rest-ls (append (cdr found/etc) non-split-ls))) (for-each (lambda (spec) (let ((name (option-spec->name spec)) (val (option-spec->value spec))) (and (option-spec->required? spec) (or (memq spec found) (error "option must be specified:" name))) (and (memq spec found) (eq? #t (option-spec->value-policy spec)) (or val (error "option must be specified with argument:" name))) (let ((pred (option-spec->predicate spec))) (and pred (pred name val))))) specifications) (cons (cons '() rest-ls) (let ((multi-count (map (lambda (desc) (cons (car desc) 0)) option-desc-list))) (map (lambda (spec) (let ((name (string->symbol (option-spec->name spec)))) (cons name ;; handle multiple occurrances (let ((maybe-ls (option-spec->value spec))) (if (list? maybe-ls) (let* ((look (assq name multi-count)) (idx (cdr look)) (val (list-ref maybe-ls idx))) (set-cdr! look (1+ idx)) ; ugh! val) maybe-ls))))) found))))) (define (option-ref options key default) or DEFAULT if not found . The value is either a string or `#t'." (or (assq-ref options key) default)) ;;; getopt-long.scm ends here
null
https://raw.githubusercontent.com/oriansj/mes-m2/b44fbc976ae334252de4eb82a57c361a195f2194/module/mes/getopt-long.scm
scheme
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software Commentary: This module implements some complex command line option parsing, in the spirit of the GNU C library function `getopt_long'. Both long and short options are supported. The theory is that people should be able to constrain the set of options they want to process using a grammar, rather than some arbitrary structure. The grammar makes the option descriptions easy to read. `getopt-long' is a procedure for parsing command-line arguments in a manner consistent with other GNU programs. `option-ref' is a procedure that facilitates processing of the `getopt-long' return value. name of the program; subsequent elements should be the arguments that were passed to the program on the command line. The `program-arguments' procedure returns a list of this form. ((OPTION (PROPERTY VALUE) ...) ...) Each OPTION should be a symbol. `getopt-long' will accept a Each option can have the following (PROPERTY VALUE) pairs: (single-char CHAR) --- Accept `-CHAR' as a single-character equivalent to `--OPTION'. This is how to specify traditional Unix-style flags. getopt-long will raise an error if it is not found in ARGS. if it is #f, it does not; and if it is the symbol `optional', the option may appear in ARGS with or without a value. accepts a string and returns a boolean value; you may The (PROPERTY VALUE) pairs may occur in any order, but each property may occur only once. By default, options do not have single-character equivalents, are not required, and do not take values. In ARGS, single-character options may be combined, in the usual Unix fashion: ("-x" "-y") is equivalent to ("-xy"). If an option accepts values, then it must be the last option in the combination; the value is the next argument. So, for example, using the following grammar: the following argument lists would be acceptable: ("-a" "-b" "bang" "-c" "couth") ("bang" and "couth" are the values for "blimps" and "catalexis") ("-ab" "bang" "-c" "couth") (same) ("-ac" "couth" "-b" "bang") (same) ("-abc" "couth" "bang") (an error, since `-b' is not the last option in its combination) whether it has a value by looking at what follows it in ARGS. If the next element is does not appear to be an option itself, then that element is the option's value. The value of a long option can appear as the next element in ARGS, or it can follow the option name, separated by an `=' character. Thus, using the same grammar as above, the following argument lists are equivalent: If the option "--" appears in ARGS, argument parsing stops there; subsequent arguments are returned as ordinary arguments, even if they resemble options. So, in the argument list: `getopt-long' will recognize the `apples' option as having the it will return the strings " --blimp " and " Goodyear " as ordinary argument strings. The `getopt-long' function returns the parsed argument list as an --- onto their values, or #t if the option does not accept a value. Unused options do not appear in the alist. All arguments that are not the value of any option are returned as a list, associated with the empty list. `getopt-long' throws an exception if: - the value of the `single-char' property is not a character - it finds an unrecognized option in ARGS - a required option is omitted - an option that doesn't accept an argument does get one (this can only happen using the long option `--opt=value' syntax) - an option predicate fails So, for example: (define grammar (value #t) (single-char #\k) (predicate ,file-is-directory?)) (verbose (required? #f) (single-char #\v) (value #f)) (predicate ,string?)))) "--rnet-server=lamprod" "--" "-fred" "foo2" "foo3") grammar) => ((() "foo1" "-fred" "foo2" "foo3") (x-includes . "/usr/include") (verbose . #t)) (option-ref OPTIONS KEY DEFAULT) or DEFAULT if not found. The value is either a string or `#t'. For example, using the `getopt-long' return value from above: Code: Scan ARGUMENT-LIST for "--" and return (BEFORE-LS . AFTER-LS). retval return ( FOUND . ETC ) . is an order-maintained list of elements in ARGUMENT-LS that are neither options nor their values. handle multiple occurrances retval handle multiple occurrances ugh! getopt-long.scm ends here
Copyright ( C ) 1998 , 2001 , 2006 Free Software Foundation , Inc. Copyright ( C ) 2017,2018 Jan ( janneke ) Nieuwenhuizen < > version 2.1 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA Author : ( rewritten by ) ( regexps removed by Jan ( janneke ) Nieuwenhuizen ) ( srfi-9 backport by Jan ( janneke ) Nieuwenhuizen ) ( ARGS GRAMMAR ) Parse the arguments ARGS according to the argument list grammar GRAMMAR . ARGS should be a list of strings . Its first element should be the GRAMMAR is a list of the form : command - line option named ` --OPTION ' . ( required ? ) --- If is true , the option is required . ( predicate ) --- If the option accepts a value ( i.e. you specified ` ( value # t ) ' for this option ) , then will apply to the value , and throw an exception if it returns # f. FUNC should be a procedure which need to use quasiquotes to get it into GRAMMAR . ( ( apples ( single - char # \a ) ) ( blimps ( single - char # \b ) ( value # t ) ) ( catalexis ( single - char # \c ) ( value # t ) ) ) If an option 's value is optional , then decides ( " --apples " " Braeburn " " --blimps " " Goodyear " ) ( " --apples = Braeburn " " --blimps " " Goodyear " ) ( " --blimps " " Goodyear " " --apples = Braeburn " ) ( " --apples " " " " -- " " --blimp " " Goodyear " ) value " " , but it will not recognize the ` blimp ' assocation list , mapping option names --- the symbols from GRAMMAR - it finds an unrecognized property in GRAMMAR - an option that requires an argument does n't get one ` ( ( lockfile - dir ( required ? # t ) ( x - includes ( single - char # \x ) ) ( rnet - server ( single - char # \y ) ( ( " my - prog " " -vk " " /tmp " " foo1 " " --x - includes=/usr / include " ( rnet - server . " " ) ( lockfile - dir . " /tmp " ) ( option - ref ( ... ) ' x - includes 42 ) = > " /usr / include " ( option - ref ( ... ) ' not - a - key ! 31 ) = > 31 (define-module (mes getopt-long) #:use-module (ice-9 optargs) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9) #:export (getopt-long option-ref)) (define-record-type option-spec (%make-option-spec name value required? option-spec->single-char predicate value-policy) option-spec? (name option-spec->name set-option-spec-name!) (value option-spec->value set-option-spec-value!) (required? option-spec->required? set-option-spec-required?!) (option-spec->single-char option-spec->single-char set-option-spec-single-char!) (predicate option-spec->predicate set-option-spec-predicate!) (value-policy option-spec->value-policy set-option-spec-value-policy!)) (define (make-option-spec name) (%make-option-spec name #f #f #f #f #f)) (define (parse-option-spec desc) (let ((spec (make-option-spec (symbol->string (car desc))))) (for-each (lambda (desc-elem) (let ((given (lambda () (cadr desc-elem)))) (case (car desc-elem) ((required?) (set-option-spec-required?! spec (given))) ((value) (set-option-spec-value-policy! spec (given))) ((single-char) (or (char? (given)) (error "`single-char' value must be a char!")) (set-option-spec-single-char! spec (given))) ((predicate) (set-option-spec-predicate! spec ((lambda (pred) (lambda (name val) (or (not val) (pred val) (error "option predicate failed:" name)))) (given)))) (else (error "invalid getopt-long option property:" (car desc-elem)))))) (cdr desc)) spec)) (define (split-arg-list argument-list) Discard the " -- " . If no " -- " is found , AFTER - LS is empty . (let loop ((yes '()) (no argument-list)) (cond ((null? no) (cons (reverse yes) no)) ((string=? "--" (car no)) (cons (reverse yes) (cdr no))) (else (loop (cons (car no) yes) (cdr no)))))) (define (expand-clumped-singles opt-ls) example : ( " --xyz " " -abc5d " ) = > ( " --xyz " " -a " " -b " " -c " " 5d " ) (let loop ((opt-ls opt-ls) (ret-ls '())) (cond ((null? opt-ls) ((let ((opt (car opt-ls))) (and (eq? (string-ref opt 0) #\-) (> (string-length opt) 1) (char-alphabetic? (string-ref opt 1)))) (let* ((opt (car opt-ls)) (n (char->integer (string-ref opt 1))) (sub (substring opt 1 (string-length opt))) (end (string-index (substring opt 1 (string-length opt)) (negate char-alphabetic?))) (end (if end (1+ end) (string-length opt))) (singles-string (substring opt 1 end)) (singles (reverse (map (lambda (c) (string-append "-" (make-string 1 c))) (string->list singles-string)))) (extra (substring opt end))) (loop (cdr opt-ls) (append (if (string=? "" extra) singles (cons extra singles)) ret-ls)))) (else (loop (cdr opt-ls) (cons (car opt-ls) ret-ls)))))) (define (looks-like-an-option string) (eq? (string-ref string 0) #\-)) (define (process-options specs argument-ls stop-at-first-non-option) FOUND is an unordered list of option specs for found options , while ETC (let ((idx (map (lambda (spec) (cons (option-spec->name spec) spec)) specs)) (sc-idx (map (lambda (spec) (cons (make-string 1 (option-spec->single-char spec)) spec)) (filter option-spec->single-char specs)))) (let loop ((argument-ls argument-ls) (found '()) (etc '())) (let ((eat! (lambda (spec ls) (let ((val!loop (lambda (val n-ls n-found n-etc) (set-option-spec-value! spec (cond ((option-spec->value spec) => (lambda (cur) ((if (list? cur) cons list) val cur))) (else val))) (loop n-ls n-found n-etc))) (ERR:no-arg (lambda () (error (string-append "option must be specified" " with argument:") (option-spec->name spec))))) (cond ((eq? 'optional (option-spec->value-policy spec)) (if (or (null? (cdr ls)) (looks-like-an-option (cadr ls))) (val!loop #t (cdr ls) (cons spec found) etc) (val!loop (cadr ls) (cddr ls) (cons spec found) etc))) ((eq? #t (option-spec->value-policy spec)) (if (or (null? (cdr ls)) (looks-like-an-option (cadr ls))) (ERR:no-arg) (val!loop (cadr ls) (cddr ls) (cons spec found) etc))) (else (val!loop #t (cdr ls) (cons spec found) etc))))))) (if (null? argument-ls) (cond ((let ((opt (car argument-ls))) (and (eq? (string-ref opt 0) #\-) (> (string-length opt) 1) (let ((n (char->integer (string-ref opt 1)))) (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z))) (and (>= n (char->integer #\a)) (<= n (char->integer #\z))))))) (let* ((c (substring (car argument-ls) 1 2)) (spec (or (assoc-ref sc-idx c) (error "no such option:" (car argument-ls))))) (eat! spec argument-ls))) ((let ((opt (car argument-ls))) (and (string-prefix? "--" opt) (let ((n (char->integer (string-ref opt 2)))) (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z))) (and (>= n (char->integer #\a)) (<= n (char->integer #\z))))) (not (string-index opt #\space)) (not (string-index opt #\=)))) (let* ((opt (substring (car argument-ls) 2)) (spec (or (assoc-ref idx opt) (error "no such option:" (car argument-ls))))) (eat! spec argument-ls))) ((let ((opt (car argument-ls))) (and (string-prefix? "--" opt) (let ((n (char->integer (string-ref opt 2)))) (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z))) (and (>= n (char->integer #\a)) (<= n (char->integer #\z))))) (or (string-index opt #\=) (string-index opt #\space)))) (let* ((is (or (string-index (car argument-ls) #\=) (string-index (car argument-ls) #\space))) (opt (substring (car argument-ls) 2 is)) (spec (or (assoc-ref idx opt) (error "no such option:" (substring opt is))))) (if (option-spec->value-policy spec) (eat! spec (append (list 'ignored (substring (car argument-ls) (1+ is))) (cdr argument-ls))) (error "option does not support argument:" opt)))) (stop-at-first-non-option (cons found (append (reverse etc) argument-ls))) (else (loop (cdr argument-ls) found (cons (car argument-ls) etc))))))))) (define* (getopt-long program-arguments option-desc-list #:key stop-at-first-non-option) "Process options, handling both long and short options, similar to the glibc function 'getopt_long'. PROGRAM-ARGUMENTS should be a value similar to what (program-arguments) returns. OPTION-DESC-LIST is a list of option descriptions. Each option description must satisfy the following grammar: <option-spec> :: (<name> . <attribute-ls>) <attribute-ls> :: (<attribute> . <attribute-ls>) | () <attribute> :: <required-attribute> | <arg-required-attribute> | <single-char-attribute> | <predicate-attribute> | <value-attribute> <required-attribute> :: (required? <boolean>) <single-char-attribute> :: (single-char <char>) <value-attribute> :: (value #t) (value #f) (value optional) <predicate-attribute> :: (predicate <1-ary-function>) The procedure returns an alist of option names and values. Each option name is a symbol. The option value will be '#t' if no value was specified. There is a special item in the returned alist with a key of the empty list, (): the list of arguments that are not options or option values. By default, options are not required, and option values are not if you want to allow the user to use single character options, you need to add a `single-char' clause to the option description." (let* ((specifications (map parse-option-spec option-desc-list)) (pair (split-arg-list (cdr program-arguments) )) (split-ls (expand-clumped-singles (car pair))) (non-split-ls (cdr pair)) (found/etc (process-options specifications split-ls stop-at-first-non-option)) (found (car found/etc)) (rest-ls (append (cdr found/etc) non-split-ls))) (for-each (lambda (spec) (let ((name (option-spec->name spec)) (val (option-spec->value spec))) (and (option-spec->required? spec) (or (memq spec found) (error "option must be specified:" name))) (and (memq spec found) (eq? #t (option-spec->value-policy spec)) (or val (error "option must be specified with argument:" name))) (let ((pred (option-spec->predicate spec))) (and pred (pred name val))))) specifications) (cons (cons '() rest-ls) (let ((multi-count (map (lambda (desc) (cons (car desc) 0)) option-desc-list))) (map (lambda (spec) (let ((name (string->symbol (option-spec->name spec)))) (cons name (let ((maybe-ls (option-spec->value spec))) (if (list? maybe-ls) (let* ((look (assq name multi-count)) (idx (cdr look)) (val (list-ref maybe-ls idx))) val) maybe-ls))))) found))))) (define (option-ref options key default) or DEFAULT if not found . The value is either a string or `#t'." (or (assq-ref options key) default))
eee39d2daa33d1168e727bca420c2befd1757dc6a18c716a726147e036aee6b1
facebook/duckling
Tests.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Time.ZH.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Locale import Duckling.Testing.Asserts import Duckling.Testing.Types import Duckling.Time.ZH.Corpus import qualified Duckling.Time.ZH.CN.Corpus as CN import qualified Duckling.Time.ZH.HK.Corpus as HK import qualified Duckling.Time.ZH.MO.Corpus as MO import qualified Duckling.Time.ZH.TW.Corpus as TW tests :: TestTree tests = testGroup "ZH Tests" [ makeCorpusTest [Seal Time] defaultCorpus , localeTests ] localeTests :: TestTree localeTests = testGroup "Locale Tests" [ testGroup "ZH_CN Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeCN CN.allExamples ] , testGroup "ZH_HK Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeHK HK.allExamples ] , testGroup "ZH_MO Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeMO MO.allExamples ] , testGroup "ZH_TW Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeTW TW.allExamples ] ] where localeCN = makeLocale ZH $ Just CN localeHK = makeLocale ZH $ Just HK localeMO = makeLocale ZH $ Just MO localeTW = makeLocale ZH $ Just TW
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Time/ZH/Tests.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.Time.ZH.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Locale import Duckling.Testing.Asserts import Duckling.Testing.Types import Duckling.Time.ZH.Corpus import qualified Duckling.Time.ZH.CN.Corpus as CN import qualified Duckling.Time.ZH.HK.Corpus as HK import qualified Duckling.Time.ZH.MO.Corpus as MO import qualified Duckling.Time.ZH.TW.Corpus as TW tests :: TestTree tests = testGroup "ZH Tests" [ makeCorpusTest [Seal Time] defaultCorpus , localeTests ] localeTests :: TestTree localeTests = testGroup "Locale Tests" [ testGroup "ZH_CN Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeCN CN.allExamples ] , testGroup "ZH_HK Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeHK HK.allExamples ] , testGroup "ZH_MO Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeMO MO.allExamples ] , testGroup "ZH_TW Tests" [ makeCorpusTest [Seal Time] $ withLocale corpus localeTW TW.allExamples ] ] where localeCN = makeLocale ZH $ Just CN localeHK = makeLocale ZH $ Just HK localeMO = makeLocale ZH $ Just MO localeTW = makeLocale ZH $ Just TW
1dfad2d43ecdd4ea1cdf6f536f2104577d4ca827dd0554a911d753bcc5c7aa3d
open-company/open-company-web
macros.clj
(ns oc.web.macros (:require [cljs.compiler :as compiler] [cljs.core :as cljs])) (defn- to-property [sym] (symbol (str "-" sym))) (defmacro goog-extend [type base-type ctor & methods] `(do (defn ~type ~@ctor) (goog/inherits ~type ~base-type) ~@(map (fn [method] `(set! (.. ~type -prototype ~(to-property (first method))) (fn ~@(rest method)))) methods)))
null
https://raw.githubusercontent.com/open-company/open-company-web/dfce3dd9bc115df91003179bceb87cca1f84b6cf/src/main/oc/web/macros.clj
clojure
(ns oc.web.macros (:require [cljs.compiler :as compiler] [cljs.core :as cljs])) (defn- to-property [sym] (symbol (str "-" sym))) (defmacro goog-extend [type base-type ctor & methods] `(do (defn ~type ~@ctor) (goog/inherits ~type ~base-type) ~@(map (fn [method] `(set! (.. ~type -prototype ~(to-property (first method))) (fn ~@(rest method)))) methods)))
7f96a0a432d32cd45da15c24adc8ee790e35c192ef50f41e984994d0bde0fde1
bhk/scam
math0.scm
;;---------------------------------------------------------------- : operations on U and UF values ;;---------------------------------------------------------------- (require "core.scm") ;; Convert decimal digits to unary digits. ;; (define `(d2u-macro d) (subst 1 "01" 2 "011" 4 "31" 5 "311" 7 "61" 9 "81" 8 "611" 6 "3111" 3 "0111" (or d "?"))) ;; Convert unary digits to decimal digits. ;; (define `(u2d-macro u) (subst "0111" 3 "3111" 6 "611" 8 "81" 9 "61" 7 "311" 5 "31" 4 "011" 2 "01" 1 u)) (define (d2u d) (d2u-macro d)) (define (u2d u) (u2d-macro u)) (define `(spread u) (subst 0 " 0" u)) (define `(smash uv) (subst " " nil uv)) (define `(u2uv u) (native-strip (spread u))) (define `U1 "01") (define `U2 "011") (define `U3 "0111") (define `U4 "01111") (define `U5 "011111") (define `U6 "0111111") (define `U7 "01111111") (define `U8 "011111111") (define `U9 "0111111111") (define `U10 "01111111111") (define `T9 "111111111") (define `T10 "1111111111") ;; Non-nil if X > 0. X may be in decimal *or* (perhaps signed) U format. ;; (define `(n>0? x) (subst 0 nil (filter-out "-%" x))) (define `(u<0? u) (findstring 1 (filter "-%" u))) This is exported later in math.scm (define `(0- x) (subst "--" "" (.. "-" x))) Get leading zeros in UF value U. ;; (define (uf-get-lz u) (subst ":" " " (filter-out "01%" (subst " " ":" ":01" " 01" u)))) Trim leading zeros from UF value U. ;; (define (uf-trim-lz u) (subst ":" " " (filter "01%" (subst " " ":" ":01" " 01" u)))) Get trailing zeros in UF value U. ;; (define `(uf-get-tz u) (subst "." " " (filter "%0" (subst "0 " "0." u)))) Trim trailing zeros from UF value U. ;; (define `(uf-trim-tz u) (subst "." " " (filter-out "%0" (subst "0 " "0." u)))) (define `(uf-ends-in-0? u) (filter "09" (.. u "9"))) (define (u-carry-fn u nines zeros) (subst (.. nines 1) (.. 1 zeros) (if (findstring (.. nines nines 1) u) (u-carry-fn u (.. nines nines) (.. zeros zeros)) u))) Return a well - formed U value ( with digit values 0 ... 9 ) that has the same numeric value as U. U may have digits with values from 0 to 27 , but MUST ;; already have enough digits to hold the resulting value. If carry is propagated from the top digit , a mal - formed result beginning with " 1 " ;; (not "01") will result. ;; (define `(u-carry u) (foreach (w (subst "01111111111" "10" u)) Now digits in W are < = 18 . (if (findstring "01111111111" w) (u-carry-fn w U9 0) w))) Return a well - formed UF value ( with digit values 0 ... 9 ) that has the same numeric value of N , which may have digits with values from 0 to 27 . ;; (define `(uf-carry uf) (filter "0%" (spread (u-carry (smash uf))))) Add A to B. A , B , and result are UF - encoded . Result is modulo 1 . ;; (define `(uf-add a b) (uf-carry (subst "10" "1" "00" 0 (join a b)))) Remove extraneous leading zeros from a U - encoded non - negative integer . ;; (define `(u-norm-uns u) (.. 0 (smash (rest (subst "01" "0 1" u))))) (define `(neg-digits u) (subst "1" "~" u)) (define `(neg-swap u) (subst "~" "*" 1 "~" "*" 1 u)) Combine 1 's with adjacent ~ 's ( anti-1 's ) . ;; (define `(neg-rreduce u) (subst "111111~~~~~~" nil "111~~~" nil "11~~" nil "1~" nil u)) ;; Return the 9's-complement of UV value. ;; (define `(uv-complement-digits uv) (subst "1110111" 0 "11011" 0 "101" 0 (patsubst "0%" "%0111111111" (patsubst "0111111%" "%101111" uv)))) Return 10 's complement of UF . The result is possibly not well - formed ( it may contain a digit with value 10 ) . The result is equivalent to ( 1 - UF ) mod 1 . ;; (define `(uf-complement uf) (.. (uv-complement-digits uf) 1)) Assert : at most one " ~ " in each digit (define (borrow-n u zeros) (if (findstring (.. zeros "~") u) (subst (.. zeros "~") (.. "~" (subst 0 U9 zeros)) "1~" nil (borrow-n u (.. zeros zeros))) u)) Zero - extend X on the left to have numdigits(X ) ) digits ;; (define `(lzpad x y) (spread (.. (subst 1 "" y) x))) ;; Eliminate "~" digits by borrowing from 1's in more significant places. On entry , digits in U may contain all 1 's or all ~ 's ( up to 9 of them ) . If there are no 1 's to borrow from , one or more " ~ " digits may remain in ;; the result. ;; (define `(borrow-macro u) (borrow-n (neg-rreduce (subst "0~" "~0111111111" u)) "0")) (define (u-sub-unsigned a b) ;; add "unary negative" B to A (define `x (subst "10" "1" "00" 0 (join (lzpad a b) (lzpad (neg-digits b) a)))) ;; Normalize but retain "-" if present as initial word. (define `(u-norm-x u) (patsubst "-0" 0 (smash (patsubst "0%" 0 (subst "01" "0 1" u))))) (foreach (u (smash (neg-rreduce x))) (if (findstring "~" u) (u-norm-x (borrow-macro (if (filter "~%" (subst 0 nil u)) ;; negative (.. "- " (neg-swap u)) ;; positive u))) (u-norm-uns u)))) ;; A and B must be non-negative, unsigned integers. ;; ;; A, B, and result are U strings containing only digits. ;; (define `(u-add-unsigned a b) (u-norm-uns (u-carry (smash (subst "10" "1" "00" "0" (join (lzpad b a) (lzpad a b))))))) (define (u-add-unsigned-fn a b) (u-add-unsigned a b)) Add two U - values , returning a normalized U - value ( no extraneous leading zeros , and no " -0 " value ) . ;; (define (u-add a b) (define `ua (subst "-" nil a)) (define `ub (subst "-" nil b)) (if (findstring "-" (.. a b)) (if (findstring 1 (.. a b)) (if (findstring "-" a) ;; a is negative (if (findstring "-" b) ;; both negative (.. "-" (u-add-unsigned-fn ua ub)) ;; b non-negative (u-sub-unsigned b ua)) ;; a non-negative (u-sub-unsigned a ub)) 0) (u-add-unsigned a b))) (define `(u-sub a b) (u-add a (0- b))) Subtract B from A. Result is modulo 1 . E.g. : 0.1 - 0.2 -- > 0.9 ;; (define `(uf-sub a b) Assert : A and B are normalized numbers (uf-add a (uf-complement b))) Combine 1 's with ~ 's after a join . For performance , we minimize the ;; number of subst calls *and* the number of times that substitutions are ;; made within a string during the subst calls. ;; (define `(cmp-reduce u) (subst "111110~~~~~" 0 ;; max remaining reduction is "11110~~~~" "10~" nil ;; max remaining reduction is "111~~~" "11~~" nil "1~" nil 0 nil u)) (define `(u-cmp-unsigned a b) (word 1 (cmp-reduce (join (lzpad a b) (lzpad (neg-digits b) a))))) Compare A to B. A and B can be U - numbers * or * UV - numbers . ;; ;; If A>B, return "1..." (word consisting of 1's) ;; If A=B, return nil ;; If A<B, return "~..." (word consisting of ~'s) ;; (define (u-cmp a b) (if (findstring "-" (.. a b)) (if (findstring 1 (.. a b)) (if (findstring "-" a) (if (findstring "-" b) (u-cmp (subst "-" nil b) (subst "-" nil a)) "~") 1)) (u-cmp-unsigned a b))) (define `(u-lt? a b) (findstring 1 (u-cmp b a))) ;; Compare A to B. The return value is as for `u-cmp`. ;; A and B may contain extraneous spaces. ;; (define (uf-cmp a b) (word 1 (cmp-reduce (join a (neg-digits b))))) (define `(uf-lt? a b) (findstring 1 (uf-cmp b a))) ;; Subtract B from A, returning [SIGN ...RESULT]. ;; SIGN = "+" or "-" RESULT = UF - encoded number [ 0 ... 1 ) ;; (define (uf-sign-sub a b negate?) ;; expect normalized numbers (define `prefix+ (.. (if negate? "-" "+") " ")) (define `prefix- (.. (if negate? "+" "-") " ")) (define `(sub-reduce u) (subst "111110~~~~~" 0 ;; max remaining reduction is "11110~~~~" "10~" nil ;; max remaining reduction is "111~~~" "11~~" nil "1~" nil "10" 1 "00" 0 u)) (foreach (u (smash (sub-reduce (join a (neg-digits b))))) (if (findstring "~" u) (u2uv (borrow-macro (if (filter "~%" (subst 0 nil u)) ;; negative (.. prefix- (neg-swap u)) ;; positive (.. prefix+ u)))) (.. prefix+ (u2uv u))))) Propagate carry until all digits are proper ( 9 or less ) . ;; (define (u-carry-all u) (if (findstring "01111111111" u) (u-carry-all (patsubst "-1%" "-01%" (patsubst "1%" "01%" (subst T10 "X0" "0X" 1 u)))) u)) Increment U by one for each " 1 " in ONES . ONES is a string containing an arbitrary number of " 1 " characters . ;; (define (u-add-ones e ones) (or (filter-out "-% %1111111111" (.. e ones)) (u-add e (u-carry-all (.. "0" ones))))) Subtract 1 from a U - value ( possibly include a " - " sign ) . ;; (define (u-1 e) (or (patsubst "%1" "%" (filter-out "-% %0" e)) (filter-out "0% %1111111111" (.. e 1)) (u-add e "-01"))) (define `(u+1 u) (or (filter-out "-% %1111111111" (.. u 1)) (u-add u "01"))) ;;-------------------------------- ;; Multiplication ;;-------------------------------- ;; Propagate carry from each digit to the next higher digit (without ;; cascading). ;; (define `(uf-xcarry u) (subst T10 "X 0" " 0X" "1" u)) Reduce maximum digit value from 19 ( or less ) to 10 . Reduce maximum digit by 9 when maximum digit is 19 or greater . ;; (define `(uf-carry_19_10 u) (subst " 01111111111" "1 0" u)) Reduce maximum digit value from 27 to 10 . ;; (define `(uf-carry_27_10 u) (uf-carry_19_10 (uf-carry_19_10 u))) Reduce maximum digit value from 45 to 27 . ;; (define `(uf-carry_45_27 u) (subst " 011111111111111111111" "11 0" u)) Reduce maximum digit value from 81 to 10 . ;; (define `(uf-carry_81_10 u) (uf-carry_19_10 (uf-xcarry u))) (define `(>>1 uf) (.. "0 " uf)) (define `(j>>1 a b) (join a (.. "0 " b))) (define `(j>>2 a b) (join a (.. "0 0 " b))) (define `(j>>4 a b) (join a (.. "0 0 0 0 " b))) Add two values without performing a carry operation ( leaving large digit ;; values). ;; (define `(uf-add-x a b) (subst "10" "1" "00" 0 (join a b))) After one or more ` join ` operations , remove extraneous ' 0 ' characters and ;; propagate overflow from each digit to next higher digit (non-cascading). ;; (define `(merge-and-carry u) (define `(space-carry u) (subst T10 "X " " X" "1" u)) (.. 0 (subst " " " 0" (space-carry (subst 0 nil u))))) ;; True when A's length > B's length. ;; (define `(longer? a b) (word (words (.. "1 " b)) a)) Multiply by single digit ( UF values in & out ) , and do not carry . Leaves digits with values up to 81 . ;; (define `(uf*digit_81 a digit) (>>1 (subst "1" (subst "0" nil digit) a))) Multiply by single digit ( UF values in & out ) . ;; (define `(uf*digit a digit) (uf-carry (uf-xcarry (uf*digit_81 a digit)))) ;; (uf*CONSTANT u) (define `(uf*2 u) (uf-carry_19_10 (subst 1 11 u))) (define `(uf*4 u) ;; Versus "(subst 1 1111 u) + carry20 + carry10", this is slightly smaller ;; and faster for large numbers. (subst " 011111" "x 0" "1" "xx" " 0xxxxx" "1 0" "x" "11" u)) (define `(uf*0.1 u) (.. "0 " u)) (define `(uf*0.2 u) (uf*2 (.. "0 " u))) (define `(uf*0.4 u) (uf*4 (.. "0 " u))) (define `(uf*0.5 a) (subst "11" "2" "1 0" " 011111" "2" 1 (.. a " 0"))) (define `(uf*0.3_10 u) (uf-carry_27_10 (>>1 (subst 1 111 u)))) (define `(uf*0.7_10 u) (uf-carry_81_10 (>>1 (subst 1 1111111 u)))) (define `(uf*0.9_10 u) (uf-carry_81_10 (>>1 (subst 1 111111111 u)))) ;;---------------------------------------------------------------- ` vmul ` precomputes products for digits of the multiplier , and handles 9 ;; digits per iteration. ;; ;; The pre-computed products are in improper form, with digit values up to 11 ( in the case of A*6 ) . ;; Times are surprisingly linear with the size of B : ( len(B)+9 ) * ( len(A)+80 ) * 0.135 ;;---------------------------------------------------------------- ;; Multiply by a digit, given precomputed results: (define (A*0 b u1 u2 u3 u4 u5 u7 u9) nil) (define (A*01 b u1 u2 u3 u4 u5 u7 u9) u1) (define (A*011 b u1 u2 u3 u4 u5 u7 u9) u2) (define (A*0111 b u1 u2 u3 u4 u5 u7 u9) u3) (define (A*01111 b u1 u2 u3 u4 u5 u7 u9) u4) (define (A*011111 b u1 u2 u3 u4 u5 u7 u9) u5) (define (A*0111111 b u1 u2 u3 u4 u5 u7 u9) (uf*2 u3)) (define (A*01111111 b u1 u2 u3 u4 u5 u7 u9) u7) (define (A*011111111 b u1 u2 u3 u4 u5 u7 u9) (uf*2 u4)) (define (A*0111111111 b u1 u2 u3 u4 u5 u7 u9) u9) (define (vmul-9 b u1 u2 u3 u4 u5 u7 u9) (declare (A*)) (define `(d n) (native-var (.. (native-name A*) (word n b)))) max digit = 9 * 11=99 -- > 9 + 9=18 (merge-and-carry (j>>4 (j>>2 (j>>1 (d 1) (d 2)) (j>>1 (d 3) (d 4))) (j>>2 (j>>1 (d 5) (d 6)) (j>>1 (d 7) (j>>1 (d 8) (d 9))))))) Multiply A by B. U1 , U3 , etc . , hold the values of A*1 , A*3 , etc . ;; (define (vmul-loop b u1 u2 u3 u4 u5 u7 u9) (define `(>>9 u) (.. "0 0 0 0 0 0 0 0 0 " u)) (if (word 10 b) (uf-carry_45_27 (uf-add (>>9 (vmul-loop (nth-rest 10 b) u1 u2 u3 u4 u5 u7 u9)) (native-var (native-name vmul-9)))) (native-var (native-name vmul-9)))) (declare (vmul a b)) ( uf - mul A B ) must produce len(A)+len(B ) digits . vmul does that only when B ends in a non - zero digit , so we strip trailing zeros before calling it . ;; (define (vmul-0 a b) (if (findstring 1 b) (._. (vmul a (uf-trim-tz b)) (uf-get-tz b)) (._. (patsubst "%" 0 a) b))) (define (vmul a b) (if (uf-ends-in-0? b) (vmul-0 a b) (vmul-loop b (uf*0.1 a) (uf*0.2 a) (uf*0.3_10 a) (uf*0.4 a) (uf*0.5 a) (uf*0.7_10 a) (uf*0.9_10 a)))) ;;---------------------------------------------------------------- ;; uf-mul-fixed ;; ;; These functions are tailored to the size of the multiplier. Each returns numbers with maximum digit values of 27 . ;;---------------------------------------------------------------- Multiply A by B if B has 1 .. 8 digits . Return nil otherwise . ;; (define `(uf-mul-fixed a b) (declare (uf*b a b)) (native-var (.. (native-name uf*b) (words b)))) (define (uf*b1 a b) (uf-xcarry (uf*digit_81 a b))) (define (uf*b2 a b) (define `(d n) (uf*digit_81 a (word n b))) max digit size : 81 + 81 = 172 -- > 16 + 9 = 25 (merge-and-carry (j>>1 (d 1) (d 2)))) B may hold more than three digits . ETC , if given , will also be added to the result ( max . digit = 27 ) . ;; (define (uf*b3 a b ?etc) (define `(d n) (uf*digit_81 a (word n b))) max digit size : 81 + 81 + 81 + 27 = 270 -- > 9 + 27 = 36 -- > 27 (uf-carry_19_10 (merge-and-carry (j>>2 (j>>1 (d 1) (d 2)) (j>>1 (d 3) etc))))) (define (uf*b4 a b) (uf*b3 a b (uf*b1 a (word 4 b)))) (define (uf*b5 a b) (uf*b3 a b (uf*b2 a (nth-rest 4 b)))) (define (uf*b6 a b) (uf*b3 a b (uf*b3 a (nth-rest 4 b)))) (define (uf*b7 a b) (uf*b3 a b (uf*b4 a (nth-rest 4 b)))) (define (uf*b8 a b) (uf*b3 a b (uf*b5 a (nth-rest 4 b)))) Multiply two UF values . The result will have exactly ( words A ) + ( words ;; B) digits. ;; (define (uf-mul a b) (if (longer? b a) (uf-mul b a) (uf-carry (or (uf-mul-fixed a b) (vmul a b))))) ;;-------------------------------- Division ;;-------------------------------- (define `(merge2 w1 w2) (.. (subst 1 T10 w1) w2)) Compute second argument for ` guess - digit ` . ;; (define `(tally2 u) (subst 0 "" (merge2 (word 1 u) (word 2 u)))) Guess the first digit of A / B using the first 3 digits of A and the first 2 digits of B. We assume A < B. A & B are UF numbers . ;; ;; E.g. A = 0.123xxx "01 011 0111 ..." ;; B = 0.23xxx "011 0111 ..." result = 0.4 " 01111 " ;; ;; In: A = dividend BHI = ( tally2 B ) ;; (define `(guess-digit a bhi) (define `ahi (subst 0 nil (merge2 (merge2 (word 1 a) (word 2 a)) (word 3 a)))) ;; min(floor(ahi/bhi),9) (define `q (subst bhi "x" 1 nil "x" 1 ahi)) (.. 0 (subst T10 T9 q))) (define `DIV-TRUNCATE 1) (define `DIV-NEAREST 2) (define `DIV-CEILING 3) (define `DIV-REMAINDER 4) (define `DIV-FLOOR 9) ;; only for signed values ;; (div-post POST Q REM B) : Called with results of (uf-div a b num-digits). ;; Q/10 = the first N digits of A / B , prefixed with " 0 " ;; REM = remainder (always less than B) ;; A = B*IQ + REM*10^(-N) ;; (define (div-post mode q/10 rem b) ;; Round last digit up when REM>B/2 or REM==B/2 and last digit is odd (define `round-up (if (filter [DIV-NEAREST DIV-CEILING] mode) (findstring 1 (if (filter DIV-CEILING mode) rem (or (uf-cmp rem (uf*0.5 b)) (subst "11" nil (lastword q/10))))))) (if round-up (uf-carry (.. q/10 1)) (if (filter DIV-REMAINDER mode) rem ;; TRUNCATE or round down q/10))) In : ZA = [ Z ... A ] ( Z is first digit , A is in remaining digits ) A , B are UF - encoded B > = 0.1 ;; A < B ;; Z is 0 unless previous subtraction overflowed ;; ;; We choose a guess for the next digit, D, using the initial ;; digits of A and B: ( 1 ) Atop = A mod 0.001 [ 0.000 .. 0.999 ] Af = A - Atop ( 2 ) Btop = B mod 0.01 [ 0.10 .. 0.99 ] ; Bf = B - Btop ( 3 ) D = floor(10*Atop / Btop ) ( 4 ) 10*Atop - D*Btop < = Btop - 0.01 [ 3,2 ] ( 5 ) 10*Atop - ( D*B - D*Bf ) < = Btop - 0.01 [ 4,2 ] ( 6 ) 10*Atop - D*B < Btop - 0.01 - D*Bf [ 5 ] ( 7 ) 10*A - D*B < BTop - 0.01 - D*Bf + 10*Af [ 6,1 ] ;; (8) 10*A - D*B < B [7,1,2] ;; When D is 10 we substitute 9 , since we know : ( 9 ) 10*A - 9*B < B [ A < B ] ;; (define (div-loop za b bhi num-digits mode digits) (define `a (rest za)) (define `z (word 1 za)) (cond Z is non - zero only when the previous quotient digit was too large by one ; we adjust for this and continue ... [ 4 % of the time ] ((findstring "1" z) ;; Assert: Z == U9 (div-loop (>>1 (uf-add a b)) b bhi num-digits mode (subst "1x" "" (.. digits "x")))) ;; done? ((word num-digits digits) (div-post mode (>>1 digits) a b)) ;; calculate next digit (else ' foreach ' is a fast ' let ' when the value is exactly one word (foreach (d (guess-digit a bhi)) initial digit of 10*A - D*B is 0 if no overflow , 9 otherwise (define `next-za (uf-sub a (uf*digit b d))) (div-loop next-za b bhi num-digits mode (.. digits (if digits " ") d)))))) ;; uf-div-long: handle arbitrarily long divisors ;; (define `(uf-div-long a b n mode) (div-loop (>>1 a) b (tally2 b) n mode nil)) ;;-------------------------------- ;; uf-div1 ;;-------------------------------- For uf - div1 and uf - div2 we compute X / Y via X*(1 / Y ) . When Y has have prime factors other than 2 and 5 , 1 / Y is a repeating decimal . For those , ;; we compute the repeating portion, multiply it by X, and then use ;; power-seq-1 to generate enough digits of precision. ;; ;; In order to have certainty about the initial digits, we need to assurance that the exact value does not contain indefinitely long strings of 0s . ;; (Otherwise, an arbitrarily small error in our approximation from the ;; exact value could affect the digits of interest.) ;; ;; We know that in the repeating portion of the quotient (the portion after ;; which the dividend digits have been "consumed" in long division) there are never more than len(Y)-1 consecutive 0s ( unless all remaining zeros are zero ) . [ Consider what partial remainder in long division could generate as many zeros as the size of the divisor ... ] ;; ;; Therefore, we compute N + 1 + len(Y) digits of the power sequence, unless X is longer than (define `(is-odd? digit) (findstring 1 (subst "11" nil digit))) Divide X by two , when last digit in X is even . ;; (define `(uf/2 x) (subst "11" "2" "1 0" " 011111" "2" 1 x)) (define (uf*3 u) (uf-carry (subst 1 111 u))) Add two UF numbers , returning a non - well - formed UF number ( with digit values up to 10 ) . ;; (define `(uf-add_10 x y) (uf-carry_19_10 (uf-add-x x y))) (define `(uf*0.25 x) (subst "11" "2" "1 0" " 0112" "22" 1 "2 0" " 011111" (._. x "0 0"))) (define `(uf*1.5 x) (uf-carry (subst "11" "x" "1 0" " 0xxxxx" "x" "111" (._. x 0)))) Add X to Y , returning a non - canonical value ( digits up to 10 ) . ;; (define `(uf-add_10 x y) (uf-carry_19_10 (uf-add-x x y))) ;; Compute A * (1 + X + X^2 + X^3 + ...) in special cases wherein X can be described as 1>>N. = string of N " 0 " words . ;; (define (power-seq-1 a zeros n0 n1) (if (word n1 (nth-rest n0 zeros)) All remaining terms approach Residue : 0 < Residue < = 1>>N ;; Exact = A + Residue Result = A + 1>>N ;; = Exact + 1>>N - Residue (wordlist 1 (words zeros) (uf-add a (.. zeros 1))) (power-seq-1 (uf-add_10 a (._. zeros a)) (._. zeros zeros) n0 n1))) ;; Round U to the nearest N digits, returning U/10. ;; N is in decimal. N > 0. ;; (define (uf-round n mode u) (define `q/10 (>>1 (wordlist 1 n u))) (define `last-digit (word n u)) (define `next-digit (word 2 (nth-rest n u))) (define `remaining-digits (nth-rest 3 (nth-rest n u))) (define `nearest-up? (findstring U6 (or (filter-out U5 (or next-digit 0)) (if (or (findstring 1 remaining-digits) (is-odd? last-digit)) U6)))) (define `round-up? (if (filter DIV-NEAREST mode) nearest-up? (if (filter DIV-CEILING mode) Find any non - zero digit following the last digit . (findstring " 01" (nth-rest n u))))) (if round-up? (uf-carry (.. q/10 1)) q/10)) (define `(rdiv a b n zs m) = x0+x1 - 1 = x0 + len(B ) + 2 This conservative definition for is faster to compute than ;; the exact value, which would be given by: ( if ( word 4 ( nth - rest n a ) ) ( words ( nth - rest 3 a ) ) ;; n)) (define `x0 (if (word n a) (words a) n)) (define `x1 (words (.. b " 1 1 1"))) (power-seq-1 m zs x0 x1)) ;; uf-div1: single-digit divisors ;; (define (uf-div1 a b n mode) (define `(uf*1.42857 x) (rest (uf-mul x [U1 U4 U2 U8 U5 U7]))) (define `product (cond ((filter [U3 U6 U7 U9] b) ;; repeating decimals (rdiv a b n (if (filter U7 b) "0 0 0 0 0 0" "0") (if (filter [U3 U6] b) (if (filter U3 b) 3 6 (if (filter U7 b) 7 9 ((filter [U1 U2 U4 U8] b) (rest (if (findstring U4 b) (uf*0.25 (if (filter U4 b) a (uf*0.5 a))) ;; 4 & 8 (if (filter U2 b) (uf*0.5 a) a)))) ;; 2 & 1 (else 5 (uf-round n mode product)) ;;-------------------------------- ;; uf-div2 ;;-------------------------------- (define (recip-loop divisor r) (define `next-r (subst divisor "x" (subst "x" nil 1 T10 r))) (.. (subst 1 nil r) (if (filter "1 %x1" r) nil (.. " " (recip-loop divisor next-r))))) Calculate a repeating decimal reciprocal for a 2 - digit number that is relatively prime to 10 . Result is a UF - number holding 0.1 / X. E.g. : When X = 0.13 , the result is 0.76923 . ;; ;; note: this gets memoized ;; (define (recip2 x) (native-strip (subst "x" 1 " " " 0" (recip-loop (tally2 x) T10)))) (memoize (native-name recip2)) (define (recip-div2 x y n r) (rest (rdiv x y n (.. "0 " (patsubst "%" 0 r)) (uf-mul x r)))) (define (uf-div2 x y n mode) ( expect 2 ( words y ) ) (cond Note : while uf - div requires Y>=0.1 , uf - div2 does not . This may happen after divisors that are multiples of 2 or 5 are reduced , below . ((filter 0 (word 1 y)) (uf-div1 (rest x) (rest y) n mode)) ((filter [0 U2 U4 U5 U6 U8] (word 2 y)) multiple of 2 or 5 (if (filter [0 U5] (word 2 y)) (if (filter U5 (word 2 y)) (uf-div2 (uf*0.2 x) (wordlist 1 2 (uf*0.2 y)) n mode) (uf-div1 x (word 1 y) n mode)) (uf-div2 (uf*0.5 x) (uf/2 y) n mode))) (else (uf-round n mode (recip-div2 x y n (recip2 y)))))) ;;-------------------------------- ;; uf-div3 ;;-------------------------------- We convert the divisor Y to a string of tally marks -- a string of 1 's whose length is the numeric value of Y<<len(Y ) -- and we convert the first len(Y ) dividend digits to tally marks . Each ` ( subst YT ... ) ` ;; precisely yields the next quotient digit and a remainder for computing ;; subsequent digits. ;; YT = divisor as a string of tally marks ( Y<<len(Y ) ) XT = initial digits of dividend as tally marks ( 0 's indicating the ;; previous quotient digit; 1's for partial remainder) X = remaining UF digits in dividend ( 0 < = X < 1 ) ;; Q = quotient digits computed so far ;; N = number of digits required on return ;; MODE = DIV-NEAREST/CEILING/TRUNCATE ;; sdiv - loop uses an unusual representation for its results . Digits have no " 0 " prefix ; exactly one space delimits each digit ; both 0 's and 1 's designate 1 's . It is more efficient to correct this after the loop . (define (sdiv-done yt xt x n) Include next digit and then one more non - zero digit if any value remains in X or XT (.. (subst "01" " " (.. 0 xt 1)) (findstring 1 x))) (define (sdiv-loop yt xt x n ?zeros) (define `xstep ( subst 0 nil ... ) removes 0 's from X and 0 's denoting Y in XT (subst 0 nil (.. (subst 1 T10 xt) (word 1 x)))) (._. (subst 1 nil xt) (native-call (if (word n zeros) (native-name sdiv-done) (native-name sdiv-loop)) yt (subst yt 0 xstep) (rest x) n (.. zeros " 0")))) (define `(tally3 x) (subst 0 nil (merge2 (merge2 (word 1 x) (word 2 x)) (word 3 x)))) (define (uf-div3 x y n mode) (define `raw (sdiv-loop (tally3 y) (tally3 x) (nth-rest 4 x) n)) (uf-round n mode (native-strip (subst 0 1 " " " 0" raw)))) (declare (uf-div a b n mode)) Compute remainder using DIV - TRUNCATE and subtraction . ;; (define (uf-remainder a b n) (define `(<<n u) (or (rest (nth-rest n u)) 0)) (<<n (uf-sub a (uf-mul b (rest (uf-div a b n DIV-TRUNCATE)))))) ;; Divide A by B ;; In : A & B are UF - encoded numbers ( 0 - 0.999 ... ) ;; A < B B > = 0.1 ;; N = number of digits of quotient to compute (in *DECIMAL*) ;; MODE = [see out, below] ;; Out : The returned value ( always UF - encoded ) depends on MODE : ;; ;; DIV-TRUNCATE => Qt/10 DIV - NEAREST = > Qn/10 [ round to nearest , ties to odd ] ;; DIV-CEILING => Qc/10 ;; DIV-REMAINDER => REM ;; where Qt , Qn , Qc , and REM are defined as : ;; ;; Qt = floor(A/B << N) >> N Qc = Qt + ( REM>0 ? 1>>N : 0 ) Qn = Qt + ( REM>0.5 or ( REM=0.5 and is - odd(floor(Q<<N ) ) ) ? 1>>N : 0 ) ;; REM = (A - Qt*B)<<N ;; [ " X>>N " means ^ -N and " X<<N " means X*10^N. ] ;; Note that Qn or Qc may be equal to 1 , which can not be represented in a UF - number . This is the reason why Q{x}/10 is returned instead of Q{x } . ;; (define (uf-div a b n mode) ( assert ( findstring 1 ( word 1 b ) ) ) (cond ((uf-ends-in-0? b) (uf-div a (uf-trim-tz b) n mode)) ((filter "0 -%" n) (div-post mode 0 a b)) ((not (findstring 1 a)) 0) ((word 4 b) (uf-div-long a b n mode)) ((filter DIV-REMAINDER mode) (uf-remainder a b n)) (else ;; call uf-div1, uf-div2, or uf-div3 (native-call (.. (native-name uf-div) (words b)) a b n mode)))) Divide UA by UB , rounding down to the nearest integer . If UB==0 , nil is ;; returned. ;; UA , UB , and the result are ( non - negative ) U - strings . ;; ;; MODE = DIV-TRUNCATE => quotient (truncated) ;; DIV-REMAINDER => remainder ;; (define (u-fdiv ua ub mode) (cond extraneous leading zeros ((filter "00%" (._. ua ub)) (u-fdiv (patsubst "00%" "0%" ua) (patsubst "00%" "0%" ub) mode)) ((and ua (findstring 1 ub)) (define `_a (spread ua)) ;; has initial extraneous space (define `_b (spread ub)) ;; has initial extraneous space (define `uresult num - digits = max(0 , ( len A ) - ( len B ) + 1 ) (foreach (num-digits (words (nth-rest (words _b) _a))) (if (filter 0 num-digits) ;; B is longer than A (if (filter DIV-REMAINDER mode) ua 0) (uf-div (.. "0" _a) (native-strip _b) num-digits mode)))) (u-norm-uns (smash uresult)))))
null
https://raw.githubusercontent.com/bhk/scam/59d7c02e673f1faebd0b7625d8c595daaa5efc51/math0.scm
scheme
---------------------------------------------------------------- ---------------------------------------------------------------- Convert decimal digits to unary digits. Convert unary digits to decimal digits. Non-nil if X > 0. X may be in decimal *or* (perhaps signed) U format. already have enough digits to hold the resulting value. If carry is (not "01") will result. Return the 9's-complement of UV value. Eliminate "~" digits by borrowing from 1's in more significant places. the result. add "unary negative" B to A Normalize but retain "-" if present as initial word. negative positive A and B must be non-negative, unsigned integers. A, B, and result are U strings containing only digits. a is negative both negative b non-negative a non-negative number of subst calls *and* the number of times that substitutions are made within a string during the subst calls. max remaining reduction is "11110~~~~" max remaining reduction is "111~~~" If A>B, return "1..." (word consisting of 1's) If A=B, return nil If A<B, return "~..." (word consisting of ~'s) Compare A to B. The return value is as for `u-cmp`. A and B may contain extraneous spaces. Subtract B from A, returning [SIGN ...RESULT]. SIGN = "+" or "-" expect normalized numbers max remaining reduction is "11110~~~~" max remaining reduction is "111~~~" negative positive -------------------------------- Multiplication -------------------------------- Propagate carry from each digit to the next higher digit (without cascading). values). propagate overflow from each digit to next higher digit (non-cascading). True when A's length > B's length. (uf*CONSTANT u) Versus "(subst 1 1111 u) + carry20 + carry10", this is slightly smaller and faster for large numbers. ---------------------------------------------------------------- digits per iteration. The pre-computed products are in improper form, with digit values up to ---------------------------------------------------------------- Multiply by a digit, given precomputed results: ---------------------------------------------------------------- uf-mul-fixed These functions are tailored to the size of the multiplier. Each returns ---------------------------------------------------------------- B) digits. -------------------------------- -------------------------------- E.g. A = 0.123xxx "01 011 0111 ..." B = 0.23xxx "011 0111 ..." In: A = dividend min(floor(ahi/bhi),9) only for signed values (div-post POST Q REM B) : Called with results of (uf-div a b num-digits). REM = remainder (always less than B) A = B*IQ + REM*10^(-N) Round last digit up when REM>B/2 or REM==B/2 and last digit is odd TRUNCATE or round down A < B Z is 0 unless previous subtraction overflowed We choose a guess for the next digit, D, using the initial digits of A and B: Bf = B - Btop (8) 10*A - D*B < B [7,1,2] we adjust for this and continue ... [ 4 % of the time ] Assert: Z == U9 done? calculate next digit uf-div-long: handle arbitrarily long divisors -------------------------------- uf-div1 -------------------------------- we compute the repeating portion, multiply it by X, and then use power-seq-1 to generate enough digits of precision. In order to have certainty about the initial digits, we need to assurance (Otherwise, an arbitrarily small error in our approximation from the exact value could affect the digits of interest.) We know that in the repeating portion of the quotient (the portion after which the dividend digits have been "consumed" in long division) there Therefore, we compute N + 1 + len(Y) digits of the power sequence, unless Compute A * (1 + X + X^2 + X^3 + ...) in special cases wherein X can be Exact = A + Residue = Exact + 1>>N - Residue Round U to the nearest N digits, returning U/10. N is in decimal. N > 0. the exact value, which would be given by: n)) uf-div1: single-digit divisors repeating decimals 4 & 8 2 & 1 -------------------------------- uf-div2 -------------------------------- note: this gets memoized -------------------------------- uf-div3 -------------------------------- precisely yields the next quotient digit and a remainder for computing subsequent digits. previous quotient digit; 1's for partial remainder) Q = quotient digits computed so far N = number of digits required on return MODE = DIV-NEAREST/CEILING/TRUNCATE exactly one space delimits each digit ; both 0 's and 1 's Divide A by B A < B N = number of digits of quotient to compute (in *DECIMAL*) MODE = [see out, below] DIV-TRUNCATE => Qt/10 DIV-CEILING => Qc/10 DIV-REMAINDER => REM Qt = floor(A/B << N) >> N REM = (A - Qt*B)<<N call uf-div1, uf-div2, or uf-div3 returned. MODE = DIV-TRUNCATE => quotient (truncated) DIV-REMAINDER => remainder has initial extraneous space has initial extraneous space B is longer than A
: operations on U and UF values (require "core.scm") (define `(d2u-macro d) (subst 1 "01" 2 "011" 4 "31" 5 "311" 7 "61" 9 "81" 8 "611" 6 "3111" 3 "0111" (or d "?"))) (define `(u2d-macro u) (subst "0111" 3 "3111" 6 "611" 8 "81" 9 "61" 7 "311" 5 "31" 4 "011" 2 "01" 1 u)) (define (d2u d) (d2u-macro d)) (define (u2d u) (u2d-macro u)) (define `(spread u) (subst 0 " 0" u)) (define `(smash uv) (subst " " nil uv)) (define `(u2uv u) (native-strip (spread u))) (define `U1 "01") (define `U2 "011") (define `U3 "0111") (define `U4 "01111") (define `U5 "011111") (define `U6 "0111111") (define `U7 "01111111") (define `U8 "011111111") (define `U9 "0111111111") (define `U10 "01111111111") (define `T9 "111111111") (define `T10 "1111111111") (define `(n>0? x) (subst 0 nil (filter-out "-%" x))) (define `(u<0? u) (findstring 1 (filter "-%" u))) This is exported later in math.scm (define `(0- x) (subst "--" "" (.. "-" x))) Get leading zeros in UF value U. (define (uf-get-lz u) (subst ":" " " (filter-out "01%" (subst " " ":" ":01" " 01" u)))) Trim leading zeros from UF value U. (define (uf-trim-lz u) (subst ":" " " (filter "01%" (subst " " ":" ":01" " 01" u)))) Get trailing zeros in UF value U. (define `(uf-get-tz u) (subst "." " " (filter "%0" (subst "0 " "0." u)))) Trim trailing zeros from UF value U. (define `(uf-trim-tz u) (subst "." " " (filter-out "%0" (subst "0 " "0." u)))) (define `(uf-ends-in-0? u) (filter "09" (.. u "9"))) (define (u-carry-fn u nines zeros) (subst (.. nines 1) (.. 1 zeros) (if (findstring (.. nines nines 1) u) (u-carry-fn u (.. nines nines) (.. zeros zeros)) u))) Return a well - formed U value ( with digit values 0 ... 9 ) that has the same numeric value as U. U may have digits with values from 0 to 27 , but MUST propagated from the top digit , a mal - formed result beginning with " 1 " (define `(u-carry u) (foreach (w (subst "01111111111" "10" u)) Now digits in W are < = 18 . (if (findstring "01111111111" w) (u-carry-fn w U9 0) w))) Return a well - formed UF value ( with digit values 0 ... 9 ) that has the same numeric value of N , which may have digits with values from 0 to 27 . (define `(uf-carry uf) (filter "0%" (spread (u-carry (smash uf))))) Add A to B. A , B , and result are UF - encoded . Result is modulo 1 . (define `(uf-add a b) (uf-carry (subst "10" "1" "00" 0 (join a b)))) Remove extraneous leading zeros from a U - encoded non - negative integer . (define `(u-norm-uns u) (.. 0 (smash (rest (subst "01" "0 1" u))))) (define `(neg-digits u) (subst "1" "~" u)) (define `(neg-swap u) (subst "~" "*" 1 "~" "*" 1 u)) Combine 1 's with adjacent ~ 's ( anti-1 's ) . (define `(neg-rreduce u) (subst "111111~~~~~~" nil "111~~~" nil "11~~" nil "1~" nil u)) (define `(uv-complement-digits uv) (subst "1110111" 0 "11011" 0 "101" 0 (patsubst "0%" "%0111111111" (patsubst "0111111%" "%101111" uv)))) Return 10 's complement of UF . The result is possibly not well - formed ( it may contain a digit with value 10 ) . The result is equivalent to ( 1 - UF ) mod 1 . (define `(uf-complement uf) (.. (uv-complement-digits uf) 1)) Assert : at most one " ~ " in each digit (define (borrow-n u zeros) (if (findstring (.. zeros "~") u) (subst (.. zeros "~") (.. "~" (subst 0 U9 zeros)) "1~" nil (borrow-n u (.. zeros zeros))) u)) Zero - extend X on the left to have numdigits(X ) ) digits (define `(lzpad x y) (spread (.. (subst 1 "" y) x))) On entry , digits in U may contain all 1 's or all ~ 's ( up to 9 of them ) . If there are no 1 's to borrow from , one or more " ~ " digits may remain in (define `(borrow-macro u) (borrow-n (neg-rreduce (subst "0~" "~0111111111" u)) "0")) (define (u-sub-unsigned a b) (define `x (subst "10" "1" "00" 0 (join (lzpad a b) (lzpad (neg-digits b) a)))) (define `(u-norm-x u) (patsubst "-0" 0 (smash (patsubst "0%" 0 (subst "01" "0 1" u))))) (foreach (u (smash (neg-rreduce x))) (if (findstring "~" u) (u-norm-x (borrow-macro (if (filter "~%" (subst 0 nil u)) (.. "- " (neg-swap u)) u))) (u-norm-uns u)))) (define `(u-add-unsigned a b) (u-norm-uns (u-carry (smash (subst "10" "1" "00" "0" (join (lzpad b a) (lzpad a b))))))) (define (u-add-unsigned-fn a b) (u-add-unsigned a b)) Add two U - values , returning a normalized U - value ( no extraneous leading zeros , and no " -0 " value ) . (define (u-add a b) (define `ua (subst "-" nil a)) (define `ub (subst "-" nil b)) (if (findstring "-" (.. a b)) (if (findstring 1 (.. a b)) (if (findstring "-" a) (if (findstring "-" b) (.. "-" (u-add-unsigned-fn ua ub)) (u-sub-unsigned b ua)) (u-sub-unsigned a ub)) 0) (u-add-unsigned a b))) (define `(u-sub a b) (u-add a (0- b))) Subtract B from A. Result is modulo 1 . E.g. : 0.1 - 0.2 -- > 0.9 (define `(uf-sub a b) Assert : A and B are normalized numbers (uf-add a (uf-complement b))) Combine 1 's with ~ 's after a join . For performance , we minimize the (define `(cmp-reduce u) "11~~" nil "1~" nil 0 nil u)) (define `(u-cmp-unsigned a b) (word 1 (cmp-reduce (join (lzpad a b) (lzpad (neg-digits b) a))))) Compare A to B. A and B can be U - numbers * or * UV - numbers . (define (u-cmp a b) (if (findstring "-" (.. a b)) (if (findstring 1 (.. a b)) (if (findstring "-" a) (if (findstring "-" b) (u-cmp (subst "-" nil b) (subst "-" nil a)) "~") 1)) (u-cmp-unsigned a b))) (define `(u-lt? a b) (findstring 1 (u-cmp b a))) (define (uf-cmp a b) (word 1 (cmp-reduce (join a (neg-digits b))))) (define `(uf-lt? a b) (findstring 1 (uf-cmp b a))) RESULT = UF - encoded number [ 0 ... 1 ) (define (uf-sign-sub a b negate?) (define `prefix+ (.. (if negate? "-" "+") " ")) (define `prefix- (.. (if negate? "+" "-") " ")) (define `(sub-reduce u) "11~~" nil "1~" nil "10" 1 "00" 0 u)) (foreach (u (smash (sub-reduce (join a (neg-digits b))))) (if (findstring "~" u) (u2uv (borrow-macro (if (filter "~%" (subst 0 nil u)) (.. prefix- (neg-swap u)) (.. prefix+ u)))) (.. prefix+ (u2uv u))))) Propagate carry until all digits are proper ( 9 or less ) . (define (u-carry-all u) (if (findstring "01111111111" u) (u-carry-all (patsubst "-1%" "-01%" (patsubst "1%" "01%" (subst T10 "X0" "0X" 1 u)))) u)) Increment U by one for each " 1 " in ONES . ONES is a string containing an arbitrary number of " 1 " characters . (define (u-add-ones e ones) (or (filter-out "-% %1111111111" (.. e ones)) (u-add e (u-carry-all (.. "0" ones))))) Subtract 1 from a U - value ( possibly include a " - " sign ) . (define (u-1 e) (or (patsubst "%1" "%" (filter-out "-% %0" e)) (filter-out "0% %1111111111" (.. e 1)) (u-add e "-01"))) (define `(u+1 u) (or (filter-out "-% %1111111111" (.. u 1)) (u-add u "01"))) (define `(uf-xcarry u) (subst T10 "X 0" " 0X" "1" u)) Reduce maximum digit value from 19 ( or less ) to 10 . Reduce maximum digit by 9 when maximum digit is 19 or greater . (define `(uf-carry_19_10 u) (subst " 01111111111" "1 0" u)) Reduce maximum digit value from 27 to 10 . (define `(uf-carry_27_10 u) (uf-carry_19_10 (uf-carry_19_10 u))) Reduce maximum digit value from 45 to 27 . (define `(uf-carry_45_27 u) (subst " 011111111111111111111" "11 0" u)) Reduce maximum digit value from 81 to 10 . (define `(uf-carry_81_10 u) (uf-carry_19_10 (uf-xcarry u))) (define `(>>1 uf) (.. "0 " uf)) (define `(j>>1 a b) (join a (.. "0 " b))) (define `(j>>2 a b) (join a (.. "0 0 " b))) (define `(j>>4 a b) (join a (.. "0 0 0 0 " b))) Add two values without performing a carry operation ( leaving large digit (define `(uf-add-x a b) (subst "10" "1" "00" 0 (join a b))) After one or more ` join ` operations , remove extraneous ' 0 ' characters and (define `(merge-and-carry u) (define `(space-carry u) (subst T10 "X " " X" "1" u)) (.. 0 (subst " " " 0" (space-carry (subst 0 nil u))))) (define `(longer? a b) (word (words (.. "1 " b)) a)) Multiply by single digit ( UF values in & out ) , and do not carry . Leaves digits with values up to 81 . (define `(uf*digit_81 a digit) (>>1 (subst "1" (subst "0" nil digit) a))) Multiply by single digit ( UF values in & out ) . (define `(uf*digit a digit) (uf-carry (uf-xcarry (uf*digit_81 a digit)))) (define `(uf*2 u) (uf-carry_19_10 (subst 1 11 u))) (define `(uf*4 u) (subst " 011111" "x 0" "1" "xx" " 0xxxxx" "1 0" "x" "11" u)) (define `(uf*0.1 u) (.. "0 " u)) (define `(uf*0.2 u) (uf*2 (.. "0 " u))) (define `(uf*0.4 u) (uf*4 (.. "0 " u))) (define `(uf*0.5 a) (subst "11" "2" "1 0" " 011111" "2" 1 (.. a " 0"))) (define `(uf*0.3_10 u) (uf-carry_27_10 (>>1 (subst 1 111 u)))) (define `(uf*0.7_10 u) (uf-carry_81_10 (>>1 (subst 1 1111111 u)))) (define `(uf*0.9_10 u) (uf-carry_81_10 (>>1 (subst 1 111111111 u)))) ` vmul ` precomputes products for digits of the multiplier , and handles 9 11 ( in the case of A*6 ) . Times are surprisingly linear with the size of B : ( len(B)+9 ) * ( len(A)+80 ) * 0.135 (define (A*0 b u1 u2 u3 u4 u5 u7 u9) nil) (define (A*01 b u1 u2 u3 u4 u5 u7 u9) u1) (define (A*011 b u1 u2 u3 u4 u5 u7 u9) u2) (define (A*0111 b u1 u2 u3 u4 u5 u7 u9) u3) (define (A*01111 b u1 u2 u3 u4 u5 u7 u9) u4) (define (A*011111 b u1 u2 u3 u4 u5 u7 u9) u5) (define (A*0111111 b u1 u2 u3 u4 u5 u7 u9) (uf*2 u3)) (define (A*01111111 b u1 u2 u3 u4 u5 u7 u9) u7) (define (A*011111111 b u1 u2 u3 u4 u5 u7 u9) (uf*2 u4)) (define (A*0111111111 b u1 u2 u3 u4 u5 u7 u9) u9) (define (vmul-9 b u1 u2 u3 u4 u5 u7 u9) (declare (A*)) (define `(d n) (native-var (.. (native-name A*) (word n b)))) max digit = 9 * 11=99 -- > 9 + 9=18 (merge-and-carry (j>>4 (j>>2 (j>>1 (d 1) (d 2)) (j>>1 (d 3) (d 4))) (j>>2 (j>>1 (d 5) (d 6)) (j>>1 (d 7) (j>>1 (d 8) (d 9))))))) Multiply A by B. U1 , U3 , etc . , hold the values of A*1 , A*3 , etc . (define (vmul-loop b u1 u2 u3 u4 u5 u7 u9) (define `(>>9 u) (.. "0 0 0 0 0 0 0 0 0 " u)) (if (word 10 b) (uf-carry_45_27 (uf-add (>>9 (vmul-loop (nth-rest 10 b) u1 u2 u3 u4 u5 u7 u9)) (native-var (native-name vmul-9)))) (native-var (native-name vmul-9)))) (declare (vmul a b)) ( uf - mul A B ) must produce len(A)+len(B ) digits . vmul does that only when B ends in a non - zero digit , so we strip trailing zeros before calling it . (define (vmul-0 a b) (if (findstring 1 b) (._. (vmul a (uf-trim-tz b)) (uf-get-tz b)) (._. (patsubst "%" 0 a) b))) (define (vmul a b) (if (uf-ends-in-0? b) (vmul-0 a b) (vmul-loop b (uf*0.1 a) (uf*0.2 a) (uf*0.3_10 a) (uf*0.4 a) (uf*0.5 a) (uf*0.7_10 a) (uf*0.9_10 a)))) numbers with maximum digit values of 27 . Multiply A by B if B has 1 .. 8 digits . Return nil otherwise . (define `(uf-mul-fixed a b) (declare (uf*b a b)) (native-var (.. (native-name uf*b) (words b)))) (define (uf*b1 a b) (uf-xcarry (uf*digit_81 a b))) (define (uf*b2 a b) (define `(d n) (uf*digit_81 a (word n b))) max digit size : 81 + 81 = 172 -- > 16 + 9 = 25 (merge-and-carry (j>>1 (d 1) (d 2)))) B may hold more than three digits . ETC , if given , will also be added to the result ( max . digit = 27 ) . (define (uf*b3 a b ?etc) (define `(d n) (uf*digit_81 a (word n b))) max digit size : 81 + 81 + 81 + 27 = 270 -- > 9 + 27 = 36 -- > 27 (uf-carry_19_10 (merge-and-carry (j>>2 (j>>1 (d 1) (d 2)) (j>>1 (d 3) etc))))) (define (uf*b4 a b) (uf*b3 a b (uf*b1 a (word 4 b)))) (define (uf*b5 a b) (uf*b3 a b (uf*b2 a (nth-rest 4 b)))) (define (uf*b6 a b) (uf*b3 a b (uf*b3 a (nth-rest 4 b)))) (define (uf*b7 a b) (uf*b3 a b (uf*b4 a (nth-rest 4 b)))) (define (uf*b8 a b) (uf*b3 a b (uf*b5 a (nth-rest 4 b)))) Multiply two UF values . The result will have exactly ( words A ) + ( words (define (uf-mul a b) (if (longer? b a) (uf-mul b a) (uf-carry (or (uf-mul-fixed a b) (vmul a b))))) Division (define `(merge2 w1 w2) (.. (subst 1 T10 w1) w2)) Compute second argument for ` guess - digit ` . (define `(tally2 u) (subst 0 "" (merge2 (word 1 u) (word 2 u)))) Guess the first digit of A / B using the first 3 digits of A and the first 2 digits of B. We assume A < B. A & B are UF numbers . result = 0.4 " 01111 " BHI = ( tally2 B ) (define `(guess-digit a bhi) (define `ahi (subst 0 nil (merge2 (merge2 (word 1 a) (word 2 a)) (word 3 a)))) (define `q (subst bhi "x" 1 nil "x" 1 ahi)) (.. 0 (subst T10 T9 q))) (define `DIV-TRUNCATE 1) (define `DIV-NEAREST 2) (define `DIV-CEILING 3) (define `DIV-REMAINDER 4) Q/10 = the first N digits of A / B , prefixed with " 0 " (define (div-post mode q/10 rem b) (define `round-up (if (filter [DIV-NEAREST DIV-CEILING] mode) (findstring 1 (if (filter DIV-CEILING mode) rem (or (uf-cmp rem (uf*0.5 b)) (subst "11" nil (lastword q/10))))))) (if round-up (uf-carry (.. q/10 1)) (if (filter DIV-REMAINDER mode) rem q/10))) In : ZA = [ Z ... A ] ( Z is first digit , A is in remaining digits ) A , B are UF - encoded B > = 0.1 ( 1 ) Atop = A mod 0.001 [ 0.000 .. 0.999 ] Af = A - Atop ( 3 ) D = floor(10*Atop / Btop ) ( 4 ) 10*Atop - D*Btop < = Btop - 0.01 [ 3,2 ] ( 5 ) 10*Atop - ( D*B - D*Bf ) < = Btop - 0.01 [ 4,2 ] ( 6 ) 10*Atop - D*B < Btop - 0.01 - D*Bf [ 5 ] ( 7 ) 10*A - D*B < BTop - 0.01 - D*Bf + 10*Af [ 6,1 ] When D is 10 we substitute 9 , since we know : ( 9 ) 10*A - 9*B < B [ A < B ] (define (div-loop za b bhi num-digits mode digits) (define `a (rest za)) (define `z (word 1 za)) (cond Z is non - zero only when the previous quotient digit was too large by ((findstring "1" z) (div-loop (>>1 (uf-add a b)) b bhi num-digits mode (subst "1x" "" (.. digits "x")))) ((word num-digits digits) (div-post mode (>>1 digits) a b)) (else ' foreach ' is a fast ' let ' when the value is exactly one word (foreach (d (guess-digit a bhi)) initial digit of 10*A - D*B is 0 if no overflow , 9 otherwise (define `next-za (uf-sub a (uf*digit b d))) (div-loop next-za b bhi num-digits mode (.. digits (if digits " ") d)))))) (define `(uf-div-long a b n mode) (div-loop (>>1 a) b (tally2 b) n mode nil)) For uf - div1 and uf - div2 we compute X / Y via X*(1 / Y ) . When Y has have prime factors other than 2 and 5 , 1 / Y is a repeating decimal . For those , that the exact value does not contain indefinitely long strings of 0s . are never more than len(Y)-1 consecutive 0s ( unless all remaining zeros are zero ) . [ Consider what partial remainder in long division could generate as many zeros as the size of the divisor ... ] X is longer than (define `(is-odd? digit) (findstring 1 (subst "11" nil digit))) Divide X by two , when last digit in X is even . (define `(uf/2 x) (subst "11" "2" "1 0" " 011111" "2" 1 x)) (define (uf*3 u) (uf-carry (subst 1 111 u))) Add two UF numbers , returning a non - well - formed UF number ( with digit values up to 10 ) . (define `(uf-add_10 x y) (uf-carry_19_10 (uf-add-x x y))) (define `(uf*0.25 x) (subst "11" "2" "1 0" " 0112" "22" 1 "2 0" " 011111" (._. x "0 0"))) (define `(uf*1.5 x) (uf-carry (subst "11" "x" "1 0" " 0xxxxx" "x" "111" (._. x 0)))) Add X to Y , returning a non - canonical value ( digits up to 10 ) . (define `(uf-add_10 x y) (uf-carry_19_10 (uf-add-x x y))) described as 1>>N. = string of N " 0 " words . (define (power-seq-1 a zeros n0 n1) (if (word n1 (nth-rest n0 zeros)) All remaining terms approach Residue : 0 < Residue < = 1>>N Result = A + 1>>N (wordlist 1 (words zeros) (uf-add a (.. zeros 1))) (power-seq-1 (uf-add_10 a (._. zeros a)) (._. zeros zeros) n0 n1))) (define (uf-round n mode u) (define `q/10 (>>1 (wordlist 1 n u))) (define `last-digit (word n u)) (define `next-digit (word 2 (nth-rest n u))) (define `remaining-digits (nth-rest 3 (nth-rest n u))) (define `nearest-up? (findstring U6 (or (filter-out U5 (or next-digit 0)) (if (or (findstring 1 remaining-digits) (is-odd? last-digit)) U6)))) (define `round-up? (if (filter DIV-NEAREST mode) nearest-up? (if (filter DIV-CEILING mode) Find any non - zero digit following the last digit . (findstring " 01" (nth-rest n u))))) (if round-up? (uf-carry (.. q/10 1)) q/10)) (define `(rdiv a b n zs m) = x0+x1 - 1 = x0 + len(B ) + 2 This conservative definition for is faster to compute than ( if ( word 4 ( nth - rest n a ) ) ( words ( nth - rest 3 a ) ) (define `x0 (if (word n a) (words a) n)) (define `x1 (words (.. b " 1 1 1"))) (power-seq-1 m zs x0 x1)) (define (uf-div1 a b n mode) (define `(uf*1.42857 x) (rest (uf-mul x [U1 U4 U2 U8 U5 U7]))) (define `product (cond ((filter [U3 U6 U7 U9] b) (rdiv a b n (if (filter U7 b) "0 0 0 0 0 0" "0") (if (filter [U3 U6] b) (if (filter U3 b) 3 6 (if (filter U7 b) 7 9 ((filter [U1 U2 U4 U8] b) (rest (if (findstring U4 b) (else 5 (uf-round n mode product)) (define (recip-loop divisor r) (define `next-r (subst divisor "x" (subst "x" nil 1 T10 r))) (.. (subst 1 nil r) (if (filter "1 %x1" r) nil (.. " " (recip-loop divisor next-r))))) Calculate a repeating decimal reciprocal for a 2 - digit number that is relatively prime to 10 . Result is a UF - number holding 0.1 / X. E.g. : When X = 0.13 , the result is 0.76923 . (define (recip2 x) (native-strip (subst "x" 1 " " " 0" (recip-loop (tally2 x) T10)))) (memoize (native-name recip2)) (define (recip-div2 x y n r) (rest (rdiv x y n (.. "0 " (patsubst "%" 0 r)) (uf-mul x r)))) (define (uf-div2 x y n mode) ( expect 2 ( words y ) ) (cond Note : while uf - div requires Y>=0.1 , uf - div2 does not . This may happen after divisors that are multiples of 2 or 5 are reduced , below . ((filter 0 (word 1 y)) (uf-div1 (rest x) (rest y) n mode)) ((filter [0 U2 U4 U5 U6 U8] (word 2 y)) multiple of 2 or 5 (if (filter [0 U5] (word 2 y)) (if (filter U5 (word 2 y)) (uf-div2 (uf*0.2 x) (wordlist 1 2 (uf*0.2 y)) n mode) (uf-div1 x (word 1 y) n mode)) (uf-div2 (uf*0.5 x) (uf/2 y) n mode))) (else (uf-round n mode (recip-div2 x y n (recip2 y)))))) We convert the divisor Y to a string of tally marks -- a string of 1 's whose length is the numeric value of Y<<len(Y ) -- and we convert the first len(Y ) dividend digits to tally marks . Each ` ( subst YT ... ) ` YT = divisor as a string of tally marks ( Y<<len(Y ) ) XT = initial digits of dividend as tally marks ( 0 's indicating the X = remaining UF digits in dividend ( 0 < = X < 1 ) sdiv - loop uses an unusual representation for its results . Digits have no designate 1 's . It is more efficient to correct this after the loop . (define (sdiv-done yt xt x n) Include next digit and then one more non - zero digit if any value remains in X or XT (.. (subst "01" " " (.. 0 xt 1)) (findstring 1 x))) (define (sdiv-loop yt xt x n ?zeros) (define `xstep ( subst 0 nil ... ) removes 0 's from X and 0 's denoting Y in XT (subst 0 nil (.. (subst 1 T10 xt) (word 1 x)))) (._. (subst 1 nil xt) (native-call (if (word n zeros) (native-name sdiv-done) (native-name sdiv-loop)) yt (subst yt 0 xstep) (rest x) n (.. zeros " 0")))) (define `(tally3 x) (subst 0 nil (merge2 (merge2 (word 1 x) (word 2 x)) (word 3 x)))) (define (uf-div3 x y n mode) (define `raw (sdiv-loop (tally3 y) (tally3 x) (nth-rest 4 x) n)) (uf-round n mode (native-strip (subst 0 1 " " " 0" raw)))) (declare (uf-div a b n mode)) Compute remainder using DIV - TRUNCATE and subtraction . (define (uf-remainder a b n) (define `(<<n u) (or (rest (nth-rest n u)) 0)) (<<n (uf-sub a (uf-mul b (rest (uf-div a b n DIV-TRUNCATE)))))) In : A & B are UF - encoded numbers ( 0 - 0.999 ... ) B > = 0.1 Out : The returned value ( always UF - encoded ) depends on MODE : DIV - NEAREST = > Qn/10 [ round to nearest , ties to odd ] where Qt , Qn , Qc , and REM are defined as : Qc = Qt + ( REM>0 ? 1>>N : 0 ) Qn = Qt + ( REM>0.5 or ( REM=0.5 and is - odd(floor(Q<<N ) ) ) ? 1>>N : 0 ) [ " X>>N " means ^ -N and " X<<N " means X*10^N. ] Note that Qn or Qc may be equal to 1 , which can not be represented in a UF - number . This is the reason why Q{x}/10 is returned instead of Q{x } . (define (uf-div a b n mode) ( assert ( findstring 1 ( word 1 b ) ) ) (cond ((uf-ends-in-0? b) (uf-div a (uf-trim-tz b) n mode)) ((filter "0 -%" n) (div-post mode 0 a b)) ((not (findstring 1 a)) 0) ((word 4 b) (uf-div-long a b n mode)) ((filter DIV-REMAINDER mode) (uf-remainder a b n)) (else (native-call (.. (native-name uf-div) (words b)) a b n mode)))) Divide UA by UB , rounding down to the nearest integer . If UB==0 , nil is UA , UB , and the result are ( non - negative ) U - strings . (define (u-fdiv ua ub mode) (cond extraneous leading zeros ((filter "00%" (._. ua ub)) (u-fdiv (patsubst "00%" "0%" ua) (patsubst "00%" "0%" ub) mode)) ((and ua (findstring 1 ub)) (define `uresult num - digits = max(0 , ( len A ) - ( len B ) + 1 ) (foreach (num-digits (words (nth-rest (words _b) _a))) (if (filter 0 num-digits) (if (filter DIV-REMAINDER mode) ua 0) (uf-div (.. "0" _a) (native-strip _b) num-digits mode)))) (u-norm-uns (smash uresult)))))
dc010e09ed3de38bd43313dc7f4874bce6f7a24cee7dae679aaaef9122f04b15
expipiplus1/vulkan
VK_NV_shader_subgroup_partitioned.hs
{-# language CPP #-} -- | = Name -- -- VK_NV_shader_subgroup_partitioned - device extension -- -- == VK_NV_shader_subgroup_partitioned -- -- [__Name String__] -- @VK_NV_shader_subgroup_partitioned@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] 199 -- -- [__Revision__] 1 -- -- [__Extension and Version Dependencies__] -- - Requires support for Vulkan 1.1 -- -- [__Contact__] -- - -- <-Docs/issues/new?body=[VK_NV_shader_subgroup_partitioned] @jeffbolznv%0A*Here describe the issue or question you have about the VK_NV_shader_subgroup_partitioned extension* > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] 2018 - 03 - 17 -- -- [__Interactions and External Dependencies__] -- -- - This extension requires -- <-Registry/blob/master/extensions/NV/SPV_NV_shader_subgroup_partitioned.html SPV_NV_shader_subgroup_partitioned> -- -- - This extension provides API support for -- < GL_NV_shader_subgroup_partitioned> -- -- [__Contributors__] -- - , NVIDIA -- -- == Description -- -- This extension enables support for a new class of -- <-extensions/html/vkspec.html#shaders-group-operations group operations> -- on -- <-extensions/html/vkspec.html#shaders-scope-subgroup subgroups> -- via the -- < GL_NV_shader_subgroup_partitioned> GLSL extension and -- <-Registry/blob/master/extensions/NV/SPV_NV_shader_subgroup_partitioned.html SPV_NV_shader_subgroup_partitioned> -- SPIR-V extension. Support for these new operations is advertised via the ' Vulkan . Core11.Enums . SubgroupFeatureFlagBits . SUBGROUP_FEATURE_PARTITIONED_BIT_NV ' -- bit. -- This extension requires Vulkan 1.1 , for general subgroup support . -- -- == New Enum Constants -- - ' NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME ' -- - ' NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION ' -- -- - Extending ' Vulkan . Core11.Enums . SubgroupFeatureFlagBits . SubgroupFeatureFlagBits ' : -- - ' Vulkan . Core11.Enums . SubgroupFeatureFlagBits . SUBGROUP_FEATURE_PARTITIONED_BIT_NV ' -- -- == Version History -- - Revision 1 , 2018 - 03 - 17 ( ) -- -- - Internal revisions -- -- == See Also -- -- No cross-references are available -- -- == Document Notes -- -- For more information, see the < -extensions/html/vkspec.html#VK_NV_shader_subgroup_partitioned Vulkan Specification > -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_NV_shader_subgroup_partitioned ( NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION , pattern NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION , NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME , pattern NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME ) where import Data.String (IsString) type NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION = 1 No documentation found for TopLevel " VK_NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION " pattern NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION :: forall a . Integral a => a pattern NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION = 1 type NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME = "VK_NV_shader_subgroup_partitioned" No documentation found for TopLevel " VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME " pattern NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME = "VK_NV_shader_subgroup_partitioned"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src/Vulkan/Extensions/VK_NV_shader_subgroup_partitioned.hs
haskell
# language CPP # | = Name VK_NV_shader_subgroup_partitioned - device extension == VK_NV_shader_subgroup_partitioned [__Name String__] @VK_NV_shader_subgroup_partitioned@ [__Extension Type__] Device extension [__Registered Extension Number__] [__Revision__] [__Extension and Version Dependencies__] [__Contact__] <-Docs/issues/new?body=[VK_NV_shader_subgroup_partitioned] @jeffbolznv%0A*Here describe the issue or question you have about the VK_NV_shader_subgroup_partitioned extension* > == Other Extension Metadata [__Last Modified Date__] [__Interactions and External Dependencies__] - This extension requires <-Registry/blob/master/extensions/NV/SPV_NV_shader_subgroup_partitioned.html SPV_NV_shader_subgroup_partitioned> - This extension provides API support for < GL_NV_shader_subgroup_partitioned> [__Contributors__] == Description This extension enables support for a new class of <-extensions/html/vkspec.html#shaders-group-operations group operations> on <-extensions/html/vkspec.html#shaders-scope-subgroup subgroups> via the < GL_NV_shader_subgroup_partitioned> <-Registry/blob/master/extensions/NV/SPV_NV_shader_subgroup_partitioned.html SPV_NV_shader_subgroup_partitioned> SPIR-V extension. Support for these new operations is advertised via the bit. == New Enum Constants - Extending == Version History - Internal revisions == See Also No cross-references are available == Document Notes For more information, see the This page is a generated document. Fixes and changes should be made to the generator scripts, not directly.
199 1 - Requires support for Vulkan 1.1 - 2018 - 03 - 17 - , NVIDIA GLSL extension and ' Vulkan . Core11.Enums . SubgroupFeatureFlagBits . SUBGROUP_FEATURE_PARTITIONED_BIT_NV ' This extension requires Vulkan 1.1 , for general subgroup support . - ' NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME ' - ' NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION ' ' Vulkan . Core11.Enums . SubgroupFeatureFlagBits . SubgroupFeatureFlagBits ' : - ' Vulkan . Core11.Enums . SubgroupFeatureFlagBits . SUBGROUP_FEATURE_PARTITIONED_BIT_NV ' - Revision 1 , 2018 - 03 - 17 ( ) < -extensions/html/vkspec.html#VK_NV_shader_subgroup_partitioned Vulkan Specification > module Vulkan.Extensions.VK_NV_shader_subgroup_partitioned ( NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION , pattern NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION , NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME , pattern NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME ) where import Data.String (IsString) type NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION = 1 No documentation found for TopLevel " VK_NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION " pattern NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION :: forall a . Integral a => a pattern NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION = 1 type NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME = "VK_NV_shader_subgroup_partitioned" No documentation found for TopLevel " VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME " pattern NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME = "VK_NV_shader_subgroup_partitioned"
22e0bf9acce7bc29ec7f80a88e38fd45a89f067d1bef6941cd003d6c8fd0d4b8
tfausak/salve
Main.hs
import qualified Control.Monad as Monad import qualified Salve import qualified System.Exit as Exit import qualified Test.HUnit as Test main :: IO () main = do counts <- Test.runTestTT $ Test.TestList [ (compare <$> Salve.parseVersion "1.2.3" <*> Salve.parseVersion "2.0.0") Test.~?= Just LT, (compare <$> Salve.parseVersion "1.2.3" <*> Salve.parseVersion "1.3.0") Test.~?= Just LT, (compare <$> Salve.parseVersion "1.2.3" <*> Salve.parseVersion "1.2.4") Test.~?= Just LT, (compare <$> Salve.parseVersion "0.0.9" <*> Salve.parseVersion "0.0.10") Test.~?= Just LT, ( compare <$> Salve.parseVersion "1.2.3-a" <*> Salve.parseVersion "1.2.3-b" ) Test.~?= Just LT, ( compare <$> Salve.parseVersion "1.2.3-pre" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just LT, ( compare <$> Salve.parseVersion "1.2.4-pre" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just GT, ( compare <$> Salve.parseVersion "1.2.3+a" <*> Salve.parseVersion "1.2.3+b" ) Test.~?= Just EQ, ((==) <$> Salve.parseVersion "1.2.3+a" <*> Salve.parseVersion "1.2.3+b") Test.~?= Just False, (compare <$> Salve.parsePreRelease "1" <*> Salve.parsePreRelease "a") Test.~?= Just LT, (compare <$> Salve.parsePreRelease "9" <*> Salve.parsePreRelease "10") Test.~?= Just LT, (compare <$> Salve.parsePreRelease "p10" <*> Salve.parsePreRelease "p9") Test.~?= Just LT, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.3-pre" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<=1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<=1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<=1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.3-pre" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.3+build" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">=1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">=1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">=1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.4-pre" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3-pre" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3 <1.2.5" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3 <1.2.5" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3 <1.2.5" <*> Salve.parseVersion "1.2.5" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.5" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.5" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "2.0.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.0.3" <*> Salve.parseVersion "0.0.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.0.3" <*> Salve.parseVersion "0.0.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.0.3" <*> Salve.parseVersion "0.0.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.x" <*> Salve.parseVersion "1.1.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.x" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.x" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "0.1.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "1.0.0" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "2.0.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "x.x.x" <*> Salve.parseVersion "0.0.0" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "x.x.x" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "x.x.x" <*> Salve.parseVersion "2.0.0" ) Test.~?= Just True ] let hasErrors = Test.errors counts /= 0 hasFailures = Test.failures counts /= 0 Monad.when (hasErrors || hasFailures) Exit.exitFailure
null
https://raw.githubusercontent.com/tfausak/salve/806d35f181802bcf8a07f2b390710a9eefd57fca/source/test-suite/Main.hs
haskell
import qualified Control.Monad as Monad import qualified Salve import qualified System.Exit as Exit import qualified Test.HUnit as Test main :: IO () main = do counts <- Test.runTestTT $ Test.TestList [ (compare <$> Salve.parseVersion "1.2.3" <*> Salve.parseVersion "2.0.0") Test.~?= Just LT, (compare <$> Salve.parseVersion "1.2.3" <*> Salve.parseVersion "1.3.0") Test.~?= Just LT, (compare <$> Salve.parseVersion "1.2.3" <*> Salve.parseVersion "1.2.4") Test.~?= Just LT, (compare <$> Salve.parseVersion "0.0.9" <*> Salve.parseVersion "0.0.10") Test.~?= Just LT, ( compare <$> Salve.parseVersion "1.2.3-a" <*> Salve.parseVersion "1.2.3-b" ) Test.~?= Just LT, ( compare <$> Salve.parseVersion "1.2.3-pre" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just LT, ( compare <$> Salve.parseVersion "1.2.4-pre" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just GT, ( compare <$> Salve.parseVersion "1.2.3+a" <*> Salve.parseVersion "1.2.3+b" ) Test.~?= Just EQ, ((==) <$> Salve.parseVersion "1.2.3+a" <*> Salve.parseVersion "1.2.3+b") Test.~?= Just False, (compare <$> Salve.parsePreRelease "1" <*> Salve.parsePreRelease "a") Test.~?= Just LT, (compare <$> Salve.parsePreRelease "9" <*> Salve.parsePreRelease "10") Test.~?= Just LT, (compare <$> Salve.parsePreRelease "p10" <*> Salve.parsePreRelease "p9") Test.~?= Just LT, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<1.2.3" <*> Salve.parseVersion "1.2.3-pre" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<=1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<=1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "<=1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.3-pre" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "=1.2.3" <*> Salve.parseVersion "1.2.3+build" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">=1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">=1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">=1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3" <*> Salve.parseVersion "1.2.4-pre" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3-pre" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3 <1.2.5" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3 <1.2.5" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint ">1.2.3 <1.2.5" <*> Salve.parseVersion "1.2.5" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 || 1.2.4" <*> Salve.parseVersion "1.2.5" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.2 || >1.2.3 <1.3.0" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.3 - 1.2.4" <*> Salve.parseVersion "1.2.5" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "~1.2.3" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^1.2.3" <*> Salve.parseVersion "2.0.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.2.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.2.4" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.2.3" <*> Salve.parseVersion "0.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.0.3" <*> Salve.parseVersion "0.0.2" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.0.3" <*> Salve.parseVersion "0.0.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "^0.0.3" <*> Salve.parseVersion "0.0.4" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.x" <*> Salve.parseVersion "1.1.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.x" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.2.x" <*> Salve.parseVersion "1.3.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "0.1.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "1.0.0" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "1.x.x" <*> Salve.parseVersion "2.0.0" ) Test.~?= Just False, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "x.x.x" <*> Salve.parseVersion "0.0.0" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "x.x.x" <*> Salve.parseVersion "1.2.3" ) Test.~?= Just True, ( Salve.satisfiesConstraint <$> Salve.parseConstraint "x.x.x" <*> Salve.parseVersion "2.0.0" ) Test.~?= Just True ] let hasErrors = Test.errors counts /= 0 hasFailures = Test.failures counts /= 0 Monad.when (hasErrors || hasFailures) Exit.exitFailure
0d6cb0be9c74c99531667c4ce338e691a58f12daaabdf782e185034c2d12bd99
plaidfinch/ComonadSheet
Indexed.hs
| Module : Control . Comonad . Sheet . Indexed Description : Adds absolute position to n - dimensional comonadic spreadsheets . Copyright : Copyright ( c ) 2014 Maintainer : Stability : experimental Portability : non - portable This module defines the @Indexed@ type , which bolts an absolute coordinate onto a normal nested structure , allowing you to talk about absolute position as well as relative position . Module : Control.Comonad.Sheet.Indexed Description : Adds absolute position to n-dimensional comonadic spreadsheets. Copyright : Copyright (c) 2014 Kenneth Foner Maintainer : Stability : experimental Portability : non-portable This module defines the @Indexed@ type, which bolts an absolute coordinate onto a normal nested structure, allowing you to talk about absolute position as well as relative position. -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE TypeFamilies # # LANGUAGE PolyKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # module Control.Comonad.Sheet.Indexed where import Control.Comonad import Control.Applicative import Data.Functor.Identity import Data.Functor.Compose import Data.Numeric.Witness.Peano import Data.Stream.Tape import Control.Comonad.Sheet.Reference import Data.Functor.Nested import Data.List.Indexed -- | An n-dimensional coordinate is a list of length n of absolute references. type Coordinate n = CountedList n (Ref Absolute) -- | An indexed sheet is an n-dimensionally nested 'Tape' paired with an n-dimensional coordinate which -- represents the absolute position of the current focus in the sheet. data Indexed ts a = Indexed { index :: Coordinate (NestedCount ts) , unindexed :: Nested ts a } instance (Functor (Nested ts)) => Functor (Indexed ts) where fmap f (Indexed i t) = Indexed i (fmap f t) | For a sheet to be , it needs to consist of n - dimensionally nested ' Tape 's , such that we can take the -- cross product of all n tapes to generate a tape of indices. type Indexable ts = ( Cross (NestedCount ts) Tape , ts ~ NestedNTimes (NestedCount ts) Tape ) instance (ComonadApply (Nested ts), Indexable ts) => Comonad (Indexed ts) where extract = extract . unindexed duplicate it = Indexed (index it) $ Indexed <$> indices (index it) <@> duplicate (unindexed it) instance (ComonadApply (Nested ts), Indexable ts) => ComonadApply (Indexed ts) where (Indexed i fs) <@> (Indexed _ xs) = Indexed i (fs <@> xs) -- | Takes an n-coordinate and generates an n-dimensional enumerated space of coordinates. indices :: (Cross n Tape) => Coordinate n -> Nested (NestedNTimes n Tape) (Coordinate n) indices = cross . fmap enumerate | The cross product of an n - length counted list of @(t a)@ is an n - nested @t@ of counted lists of class Cross n t where cross :: CountedList n (t a) -> Nested (NestedNTimes n t) (CountedList n a) instance (Functor t) => Cross (Succ Zero) t where cross (t ::: _) = Flat $ (::: CountedNil) <$> t instance ( Cross (Succ n) t , Functor t , Functor (Nested (NestedNTimes (Succ n) t)) ) => Cross (Succ (Succ n)) t where cross (t ::: ts) = Nest $ (\xs -> (::: xs) <$> t) <$> cross ts
null
https://raw.githubusercontent.com/plaidfinch/ComonadSheet/1cc9a91dc311bc1c692df4faaea091238b7871c2/src/Control/Comonad/Sheet/Indexed.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # | An n-dimensional coordinate is a list of length n of absolute references. | An indexed sheet is an n-dimensionally nested 'Tape' paired with an n-dimensional coordinate which represents the absolute position of the current focus in the sheet. cross product of all n tapes to generate a tape of indices. | Takes an n-coordinate and generates an n-dimensional enumerated space of coordinates.
| Module : Control . Comonad . Sheet . Indexed Description : Adds absolute position to n - dimensional comonadic spreadsheets . Copyright : Copyright ( c ) 2014 Maintainer : Stability : experimental Portability : non - portable This module defines the @Indexed@ type , which bolts an absolute coordinate onto a normal nested structure , allowing you to talk about absolute position as well as relative position . Module : Control.Comonad.Sheet.Indexed Description : Adds absolute position to n-dimensional comonadic spreadsheets. Copyright : Copyright (c) 2014 Kenneth Foner Maintainer : Stability : experimental Portability : non-portable This module defines the @Indexed@ type, which bolts an absolute coordinate onto a normal nested structure, allowing you to talk about absolute position as well as relative position. -} # LANGUAGE TypeFamilies # # LANGUAGE PolyKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # module Control.Comonad.Sheet.Indexed where import Control.Comonad import Control.Applicative import Data.Functor.Identity import Data.Functor.Compose import Data.Numeric.Witness.Peano import Data.Stream.Tape import Control.Comonad.Sheet.Reference import Data.Functor.Nested import Data.List.Indexed type Coordinate n = CountedList n (Ref Absolute) data Indexed ts a = Indexed { index :: Coordinate (NestedCount ts) , unindexed :: Nested ts a } instance (Functor (Nested ts)) => Functor (Indexed ts) where fmap f (Indexed i t) = Indexed i (fmap f t) | For a sheet to be , it needs to consist of n - dimensionally nested ' Tape 's , such that we can take the type Indexable ts = ( Cross (NestedCount ts) Tape , ts ~ NestedNTimes (NestedCount ts) Tape ) instance (ComonadApply (Nested ts), Indexable ts) => Comonad (Indexed ts) where extract = extract . unindexed duplicate it = Indexed (index it) $ Indexed <$> indices (index it) <@> duplicate (unindexed it) instance (ComonadApply (Nested ts), Indexable ts) => ComonadApply (Indexed ts) where (Indexed i fs) <@> (Indexed _ xs) = Indexed i (fs <@> xs) indices :: (Cross n Tape) => Coordinate n -> Nested (NestedNTimes n Tape) (Coordinate n) indices = cross . fmap enumerate | The cross product of an n - length counted list of @(t a)@ is an n - nested @t@ of counted lists of class Cross n t where cross :: CountedList n (t a) -> Nested (NestedNTimes n t) (CountedList n a) instance (Functor t) => Cross (Succ Zero) t where cross (t ::: _) = Flat $ (::: CountedNil) <$> t instance ( Cross (Succ n) t , Functor t , Functor (Nested (NestedNTimes (Succ n) t)) ) => Cross (Succ (Succ n)) t where cross (t ::: ts) = Nest $ (\xs -> (::: xs) <$> t) <$> cross ts
34c1d53f242f24a203fb5f36111c70d51222feec5d95d021f64bb0bd0446cbe3
benzap/eden
reserved.cljc
(ns eden.std.reserved) (def ^:dynamic *reserved-words* '[ = ..= .= and or == != > >= < <= + - * / not - end if then else elseif for in while do until repeat function -> ]) (defn reserved? [sym] (contains? (set *reserved-words*) sym))
null
https://raw.githubusercontent.com/benzap/eden/dbfa63dc18dbc5ef18a9b2b16dbb7af0e633f6d0/src/eden/std/reserved.cljc
clojure
(ns eden.std.reserved) (def ^:dynamic *reserved-words* '[ = ..= .= and or == != > >= < <= + - * / not - end if then else elseif for in while do until repeat function -> ]) (defn reserved? [sym] (contains? (set *reserved-words*) sym))
d72aa5f4e682bd07bfa3d2583596985ffd5902fdab1f2d5353724677a8e11462
Eventuria/demonstration-gsd
RenameWorkspace.hs
# LANGUAGE NamedFieldPuns # # LANGUAGE DuplicateRecordFields # # LANGUAGE DataKinds # module Eventuria.GSD.Write.CommandConsumer.Handling.Commands.RenameWorkspace where import qualified Data.UUID.V4 as Uuid import qualified Data.Time as Time import Eventuria.Libraries.CQRS.Write.CommandConsumption.CommandHandlingResult import Eventuria.GSD.Write.Model.Events.Event import Eventuria.GSD.Write.Model.WriteModel import Eventuria.GSD.Write.Model.Commands.Command handle :: GsdWriteModel -> RenameWorkspace -> IO (CommandHandlingResult) handle writeModel RenameWorkspace { commandId, workspaceId, workspaceNewName} = do createdOn <- Time.getCurrentTime eventId <- Uuid.nextRandom return $ CommandValidated [toEvent $ WorkspaceRenamed { eventId , createdOn, workspaceId , workspaceNewName}]
null
https://raw.githubusercontent.com/Eventuria/demonstration-gsd/5c7692b310086bc172d3fd4e1eaf09ae51ea468f/src/Eventuria/GSD/Write/CommandConsumer/Handling/Commands/RenameWorkspace.hs
haskell
# LANGUAGE NamedFieldPuns # # LANGUAGE DuplicateRecordFields # # LANGUAGE DataKinds # module Eventuria.GSD.Write.CommandConsumer.Handling.Commands.RenameWorkspace where import qualified Data.UUID.V4 as Uuid import qualified Data.Time as Time import Eventuria.Libraries.CQRS.Write.CommandConsumption.CommandHandlingResult import Eventuria.GSD.Write.Model.Events.Event import Eventuria.GSD.Write.Model.WriteModel import Eventuria.GSD.Write.Model.Commands.Command handle :: GsdWriteModel -> RenameWorkspace -> IO (CommandHandlingResult) handle writeModel RenameWorkspace { commandId, workspaceId, workspaceNewName} = do createdOn <- Time.getCurrentTime eventId <- Uuid.nextRandom return $ CommandValidated [toEvent $ WorkspaceRenamed { eventId , createdOn, workspaceId , workspaceNewName}]
fc146b122af95c3b4729a3c0bbc1c692c5998fe61b8c7ea26145dff58ae34799
hbr/fmlib
indent.mli
(** The allowed indentations: Helper module for indentation sensitive parsing. *) type expectation = | Indent of int (** [Indent n] An indentation of at least [n] columns is expected. *) | Align of int (** [Align n] Start at colmun [n] is expected. *) | Align_between of int * int (** [Align_between a b] Start between the columns [a] and [b] is expected. *) (** The expected indentiation. *) type violation = expectation (** @deprecated Use [expectation]! *) val group: ('a * expectation option) list -> (expectation option * 'a list) list * [ group lst ] Group the list of expectations . Failed expectations with the same indentation expectation ( or not indentation expectation ) are grouped into one list . The sequence is not changed . Failed expectations with the same indentation expectation (or not indentation expectation) are grouped into one list. The sequence is not changed. *) type t (** Allowed indentations *) val expectation: t -> expectation option * [ expectation ] The expected indentation or alignment . Returns [ None ] if all positions are allowed . all positions are allowed. *) val initial: t * Initially all indentations 0,1 , ... are allowed and no alignment is required . *) val check_position: int -> t -> expectation option (** [check_position col ind] Return a violated expectation, if [pos] is not an allowed indentation position. Otherwise return [None]. *) val token: int -> t -> t (** [token pos ind] Accept a token at column [pos]. Preconditions: [is_position_allowed pos ind]. *) val align: t -> t (** [align ind] Set the alignment flag. The next token sets the indentation set to [{pos}] where [pos] is the column of the token and clears the aligment flag. *) val left_align: t -> t (** [left_align ind] Set the alignment flag and the indentation set to [{pos}] where [pos] is the lower bound of the current set of indentation positions. *) val end_align: t -> t -> t * [ end_align ind0 ] End the aligned sequence i.e. handle the corner case that the aligned sequence is empty . that the aligned sequence is empty. *) val start_indent: int -> t -> t (** [start_indent i ind] Start an indented grammar construct indented by at least [i] relative to its parent. If the aligmnent flag is set, indentation is ignored. Precondition: [0 <= incr] *) val end_indent: int -> t -> t -> t * [ end_indent i ind0 ] End the current indentation which has been started with and indentation of [ i ] columns relative to [ ind0 ] . with and indentation of [i] columns relative to [ind0]. *)
null
https://raw.githubusercontent.com/hbr/fmlib/45ee4d2c76a19ef44557c554de30ec57d94bb9e5/src/parse/indent.mli
ocaml
* The allowed indentations: Helper module for indentation sensitive parsing. * [Indent n] An indentation of at least [n] columns is expected. * [Align n] Start at colmun [n] is expected. * [Align_between a b] Start between the columns [a] and [b] is expected. * The expected indentiation. * @deprecated Use [expectation]! * Allowed indentations * [check_position col ind] Return a violated expectation, if [pos] is not an allowed indentation position. Otherwise return [None]. * [token pos ind] Accept a token at column [pos]. Preconditions: [is_position_allowed pos ind]. * [align ind] Set the alignment flag. The next token sets the indentation set to [{pos}] where [pos] is the column of the token and clears the aligment flag. * [left_align ind] Set the alignment flag and the indentation set to [{pos}] where [pos] is the lower bound of the current set of indentation positions. * [start_indent i ind] Start an indented grammar construct indented by at least [i] relative to its parent. If the aligmnent flag is set, indentation is ignored. Precondition: [0 <= incr]
type expectation = | Indent of int type violation = expectation val group: ('a * expectation option) list -> (expectation option * 'a list) list * [ group lst ] Group the list of expectations . Failed expectations with the same indentation expectation ( or not indentation expectation ) are grouped into one list . The sequence is not changed . Failed expectations with the same indentation expectation (or not indentation expectation) are grouped into one list. The sequence is not changed. *) type t val expectation: t -> expectation option * [ expectation ] The expected indentation or alignment . Returns [ None ] if all positions are allowed . all positions are allowed. *) val initial: t * Initially all indentations 0,1 , ... are allowed and no alignment is required . *) val check_position: int -> t -> expectation option val token: int -> t -> t val align: t -> t val left_align: t -> t val end_align: t -> t -> t * [ end_align ind0 ] End the aligned sequence i.e. handle the corner case that the aligned sequence is empty . that the aligned sequence is empty. *) val start_indent: int -> t -> t val end_indent: int -> t -> t -> t * [ end_indent i ind0 ] End the current indentation which has been started with and indentation of [ i ] columns relative to [ ind0 ] . with and indentation of [i] columns relative to [ind0]. *)
7ebdb0cb59df223345bbd08541a7f6f226ad05f1e25110ace6702b5aa24521f6
d-cent/objective8
create_profile.clj
(ns objective8.front-end.templates.create-profile (:require [net.cgrand.enlive-html :as html] [net.cgrand.jsoup :as jsoup] [objective8.front-end.templates.page-furniture :as pf] [objective8.front-end.templates.template-functions :as tf])) (def create-profile-template (html/html-resource "templates/jade/create-profile.html" {:parser jsoup/parser})) (defn apply-validations [{:keys [doc] :as context} nodes] (let [validation-data (get-in doc [:flash :validation]) validation-report (:report validation-data) previous-inputs (:data validation-data)] (html/at nodes [:.clj-name-length-error] (when (contains? (:name validation-report) :length) identity) [:.clj-name-empty-error] (when (contains? (:name validation-report) :empty) identity) [:.clj-create-profile-name] (if-let [input-name (:name previous-inputs)] (html/set-attr :value input-name) identity) [:.clj-biog-length-error] (when (contains? (:biog validation-report) :length) identity) [:.clj-biog-empty-error] (when (contains? (:biog validation-report) :empty) identity) [:.clj-create-profile-biog] (if-let [input-biog (:biog previous-inputs)] (html/content input-biog) identity)))) (defn create-profile-page [{:keys [anti-forgery-snippet doc] :as context}] (->> (html/at create-profile-template [(and (html/has :meta) (html/attr= :name "description"))] (html/set-attr "content" (:description doc)) [:.clj-masthead-signed-out] (html/substitute (pf/masthead context)) [:.clj-status-bar] (html/substitute (pf/status-flash-bar context)) [:.clj-create-profile-form] (html/prepend anti-forgery-snippet)) (apply-validations context)))
null
https://raw.githubusercontent.com/d-cent/objective8/db8344ba4425ca0b38a31c99a3b282d7c8ddaef0/src/objective8/front_end/templates/create_profile.clj
clojure
(ns objective8.front-end.templates.create-profile (:require [net.cgrand.enlive-html :as html] [net.cgrand.jsoup :as jsoup] [objective8.front-end.templates.page-furniture :as pf] [objective8.front-end.templates.template-functions :as tf])) (def create-profile-template (html/html-resource "templates/jade/create-profile.html" {:parser jsoup/parser})) (defn apply-validations [{:keys [doc] :as context} nodes] (let [validation-data (get-in doc [:flash :validation]) validation-report (:report validation-data) previous-inputs (:data validation-data)] (html/at nodes [:.clj-name-length-error] (when (contains? (:name validation-report) :length) identity) [:.clj-name-empty-error] (when (contains? (:name validation-report) :empty) identity) [:.clj-create-profile-name] (if-let [input-name (:name previous-inputs)] (html/set-attr :value input-name) identity) [:.clj-biog-length-error] (when (contains? (:biog validation-report) :length) identity) [:.clj-biog-empty-error] (when (contains? (:biog validation-report) :empty) identity) [:.clj-create-profile-biog] (if-let [input-biog (:biog previous-inputs)] (html/content input-biog) identity)))) (defn create-profile-page [{:keys [anti-forgery-snippet doc] :as context}] (->> (html/at create-profile-template [(and (html/has :meta) (html/attr= :name "description"))] (html/set-attr "content" (:description doc)) [:.clj-masthead-signed-out] (html/substitute (pf/masthead context)) [:.clj-status-bar] (html/substitute (pf/status-flash-bar context)) [:.clj-create-profile-form] (html/prepend anti-forgery-snippet)) (apply-validations context)))
97090687bb02e31cfa87782a3ba4c32bebd9225e2701db99eaf17f40ca8e2695
hoelzl/Clicc
tidef.lisp
;;;----------------------------------------------------------------------------- Copyright ( C ) 1993 Christian - Albrechts - Universitaet zu Kiel , Germany ;;;----------------------------------------------------------------------------- Projekt : APPLY - A Practicable And Portable Lisp Implementation ;;; ------------------------------------------------------ Funktion : . Variablen und Konstanten der Typinferenz ;;; $ Revision : 1.40 $ $ Log : , v $ ;;; Revision 1.40 1993/12/09 10:31:24 hk ;;; provide wieder an das Dateiende ;;; Revision 1.39 1993/11/21 22:07:54 kl Die Typinferenzfeatures werden nun nicht mehr über den Typinferenzlevel , sondern über neu angelegte Prädikate abgefragt . ;;; ;;; Revision 1.38 1993/09/13 12:31:52 hk * ti - level * auf 2 gesetzt , und gut . ;;; Revision 1.37 1993/09/12 16:06:32 kl an die nochmals umgestellten Typinferenz - Level angepasst . ;;; Revision 1.36 1993/09/12 11:47:44 kl Typinferenz - Level 2 gestrichen . Es gibt nun die Level 0 -- 3 . ;;; Revision 1.35 1993/09/04 14:02:03 kl Hilfsvariable * successor - workset * zur Beschleunigung der Fixpunktiteration eingefuehrt . Leveln 1 und 2 erweitert . ;;; Revision 1.34 1993/06/17 08:00:09 hk eingefuegt ;;; ;;; Revision 1.33 1993/06/08 11:53:57 kl ;;; *ti-level* und *ti-verbosity* erhoeht. ;;; Revision 1.32 1993/05/17 06:39:02 kl Vorbereitung auf einen . ;;; Revision 1.31 1993/05/06 06:49:21 kl Variablen * ti - errors * und * ti - warnings * gestrichen . ;;; noch auf *NWarnings* zugegriffen. ;;; Revision 1.30 1993/04/20 15:04:00 kl * ti - level * auf 3 erhoeht und unnoetige . ;;; Revision 1.29 1993/04/18 16:00:21 kl . ;;; Revision 1.28 1993/03/18 13:27:53 kl Konstanten fuer die des analysed - Slots entfernt . ;;; Revision 1.27 1993/03/10 08:48:49 kl * ti - verbosity * gesenkt . ;;; ;;; Revision 1.26 1993/03/05 15:35:31 kl Neue Konstanten eingefuehrt . ;;; Revision 1.25 1993/03/04 10:43:33 kl * ti - level * eingefuehrt und unnoetige . ;;; ;;; Revision 1.24 1993/02/16 16:11:15 hk Revision Keyword eingefuegt . ;;; ;;; Revision 1.23 1993/02/02 09:02:51 kl Makrodefinitionen zs - typecase und update - type - f nach titypes verlegt . ;;; Revision 1.22 1993/01/27 13:02:47 kl Makrodefinition von update - type - f aus timisc.lisp . ;;; Revision 1.21 1993/01/26 18:39:35 kl Globale Variablen aus den Typinferenzdurchlaeufen hierhin verlegt . ;;; ;;; Revision 1.20 1993/01/25 13:16:29 kl * ti - current - function * eingefuehrt . entfernt , weil die entsprechenden in Annotationen . ;;; ;;; Revision 1.19 1993/01/21 12:28:45 kl Makro zs - typecase , ueber zs - typen entspricht eingebaut . ;;; Revision 1.18 1993/01/20 17:49:17 kl nun defclass1 anstatt . ;;; Revision 1.17 1993/01/19 10:32:27 kl Neue globale Variable * ti - type - declarations - are - initialized * eingefuehrt . ;;; ;;; Revision 1.16 1993/01/10 18:08:24 kl ;;; *ti-get-type-assertions-from-predicate-positions* eingefuehrt. ;;; Revision 1.15 1992/12/10 10:14:19 kl und . ;;; Revision 1.14 1992/12/08 14:14:43 kl geaendert . ;;; ;;; Revision 1.13 1992/12/02 09:36:44 kl Unnoetige globale Variablen entfernt . get - fun - descr nach . ;;; Revision 1.12 1992/12/01 15:39:30 kl und neue globale Variablen eingefuehrt . ;;; Revision 1.11 1992/11/26 11:14:42 kl um Typschemata erweitert . fuer die getypten importierten Funktionen und fuer zwei ;;; Anzeigeschalter eingefuehrt. ;;; Revision 1.10 1992/11/04 13:26:35 kl Typdeklarationen nach tidecl.lisp verlegt . . ;;; ;;; Revision 1.9 1992/11/02 12:12:30 kl Typdeklarationen erweitert . ;;; Revision 1.8 1992/10/27 12:08:38 kl An neuen Typverband angepasst . ;;; ;;; Revision 1.7 1992/10/02 14:24:21 kl Typschemata werden waehrend der Uebersetzungzeit in Funktionen umgewandelt . ;;; Revision 1.6 1992/10/01 17:02:41 kl Makro declare - type auf neue Art der Typabstraktionsfunktionen umgestellt . ;;; ;;; Revision 1.5 1992/09/25 16:40:37 kl Alle Definitionen des Typverbandes nach titypes.lisp verlegt . ;;; ;;; Revision 1.4 1992/09/15 14:33:23 kl Repraesentation der Funktionsbeschreibungen verbessert . ;;; Revision 1.3 1992/09/14 14:07:05 kl Liste der Systemfunktionsbeschreibungen erweitert . ;;; ;;; Revision 1.2 1992/09/12 19:50:56 kl Zu einigen Systemfunktionen sind jetzt Typen deklariert . ;;; Revision 1.1 1992/09/12 18:06:25 kl ;;; Initial revision ;;; ;;;----------------------------------------------------------------------------- (in-package "CLICC") ;;------------------------------------------------------------------------------ Natuerliche Zahl , die angibt , die . Je hoeher der angegebenen Wert ist , desto ` globaler ' arbeitet die Typinferenz . Mit niedrigerem Grad sinkt die fuer die , allerdings in der Regel die inferierten Ergebnisse schwacher . ;; Die genaue Einteilung ist wie folgt : ;; 0 : Es werden keine Typen inferiert . werden auf die entsprechenden Typen , alle ;; werden auf das Top-Element des Typverbandes gesetzt. ;; 1 : Es werden keine Aufrufkontexte beachtet . Das entspricht in diesem Fall einer intraprozeduralen Typinferenz . Diese Stufe wird realisiert , indem die Eintrittsumgebungen aller Funktionen mit Top - Elementen vorbesetzt werden und der Ergebnistyp Top gesetzt wird . ;; 2 : In dieser Stufe werden alle Aufrufkontexte beachtet . ;; 3 : In dieser Stufe werden die Typen globaler in den . Die Ausfuehrung dieser Analysestufe benoetigt in der Regel deutlich die . Sie ermittelt dafuer die i m Vergleich zu den . ;;------------------------------------------------------------------------------ (defvar *ti-level* 2) ;;------------------------------------------------------------------------------ ;; Prädikate für einzelne Typinferenzfeatures: ;;------------------------------------------------------------------------------ Soll eine den Nichtliteralen durchgeführt werden ? ;;------------------------------------------------------------------------------ (defun do-type-inference-on-non-literals () (> *ti-level* 0)) ;; Soll eine interprozedurale Analyse durchgeführt werden? ;;------------------------------------------------------------------------------ (defun do-interprocedural-type-inference () (> *ti-level* 1)) Sollen für dynamisch präzise Typen ermittelt werden ? ;;------------------------------------------------------------------------------ (defun use-bindings-of-dynamic-variables () (> *ti-level* 2)) die ( aufwendigere ) Typsemantik für Funktionen verwendet werden ? ;;------------------------------------------------------------------------------ (defun use-precise-function-type-semantics () (> *ti-level* 2)) ;;------------------------------------------------------------------------------ Natuerliche den . angegebenen Wert ist , desto und Meldungen werden waehrend des Durchlaufs erzeugt . Ist * ti - verbosity*=0 , werden . ;;------------------------------------------------------------------------------ (defvar *ti-verbosity* 3) ;;------------------------------------------------------------------------------ Diese Variable wird zum Propagieren von Typbindungen verwendet . Sie enthaelt die locations in Form einer Assoziationsliste . Die Liste besteht ( < location > . < zugeordneter Typ > ) . ;;------------------------------------------------------------------------------ (defvar *type-environment*) ;;------------------------------------------------------------------------------ Menge der noch zu analysierenden Funktionen und Klassen . Diese Variable wird i m zweiten Pass der Typinferenz ( tipass2 ) verwendet . ;;------------------------------------------------------------------------------ (defvar *ti-workset*) ;;------------------------------------------------------------------------------ * successor - workset * enthaelt die analysierenden ;; aktuell analysierten Funktion. Sie enthaelt somit einen kleinen Ausschnitt aller zu bearbeitenden Funktionen . Die Einfuehrung dieser Menge beschleunigt die Fixpunktiteration , weil nicht alle Mengenoperation auf der evtl . * geschehen . ;;------------------------------------------------------------------------------ (defvar *successor-workset*) ;;------------------------------------------------------------------------------ Sind die Typdeklarationen initialisiert worden ? die importierten Funktionen und Funktionen zur Typzusicherungen fuer Ausdruecke an Praedikatsposition eines Konditionals . ;;------------------------------------------------------------------------------ (defvar *ti-type-declarations-are-initialized*) ;;------------------------------------------------------------------------------ Umgebung , in der Funktionen fuer Typzusicherungen in if - Konstrukten in Form einer . Sie enthaelt Paare der Gestalt : ;; (<Praedikat> . <Typzusicherungsfunktion>) ;;------------------------------------------------------------------------------ (defvar *ti-predicate-assertion-environment* ()) ;;------------------------------------------------------------------------------ Angabe , wie haeufig die Groesse der * ti - workset * ausgeben werden soll . ;;------------------------------------------------------------------------------ (defconstant *ti-write-size-of-workset-interval* 300) ;;------------------------------------------------------------------------------ (provide "tidef")
null
https://raw.githubusercontent.com/hoelzl/Clicc/cea01db35301144967dc74fd2f96dd58aa52d6ea/src/compiler/tidef.lisp
lisp
----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ------------------------------------------------------ Revision 1.40 1993/12/09 10:31:24 hk provide wieder an das Dateiende Revision 1.38 1993/09/13 12:31:52 hk Revision 1.33 1993/06/08 11:53:57 kl *ti-level* und *ti-verbosity* erhoeht. noch auf *NWarnings* zugegriffen. Revision 1.26 1993/03/05 15:35:31 kl Revision 1.24 1993/02/16 16:11:15 hk Revision 1.23 1993/02/02 09:02:51 kl Revision 1.20 1993/01/25 13:16:29 kl Revision 1.19 1993/01/21 12:28:45 kl Revision 1.16 1993/01/10 18:08:24 kl *ti-get-type-assertions-from-predicate-positions* eingefuehrt. Revision 1.13 1992/12/02 09:36:44 kl Anzeigeschalter eingefuehrt. Revision 1.9 1992/11/02 12:12:30 kl Revision 1.7 1992/10/02 14:24:21 kl Revision 1.5 1992/09/25 16:40:37 kl Revision 1.4 1992/09/15 14:33:23 kl Revision 1.2 1992/09/12 19:50:56 kl Initial revision ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ werden auf das Top-Element des Typverbandes gesetzt. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Prädikate für einzelne Typinferenzfeatures: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Soll eine interprozedurale Analyse durchgeführt werden? ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ aktuell analysierten Funktion. Sie enthaelt somit einen kleinen Ausschnitt ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ (<Praedikat> . <Typzusicherungsfunktion>) ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
Copyright ( C ) 1993 Christian - Albrechts - Universitaet zu Kiel , Germany Projekt : APPLY - A Practicable And Portable Lisp Implementation Funktion : . Variablen und Konstanten der Typinferenz $ Revision : 1.40 $ $ Log : , v $ Revision 1.39 1993/11/21 22:07:54 kl Die Typinferenzfeatures werden nun nicht mehr über den Typinferenzlevel , sondern über neu angelegte Prädikate abgefragt . * ti - level * auf 2 gesetzt , und gut . Revision 1.37 1993/09/12 16:06:32 kl an die nochmals umgestellten Typinferenz - Level angepasst . Revision 1.36 1993/09/12 11:47:44 kl Typinferenz - Level 2 gestrichen . Es gibt nun die Level 0 -- 3 . Revision 1.35 1993/09/04 14:02:03 kl Hilfsvariable * successor - workset * zur Beschleunigung der Fixpunktiteration eingefuehrt . Leveln 1 und 2 erweitert . Revision 1.34 1993/06/17 08:00:09 hk eingefuegt Revision 1.32 1993/05/17 06:39:02 kl Vorbereitung auf einen . Revision 1.31 1993/05/06 06:49:21 kl Variablen * ti - errors * und * ti - warnings * gestrichen . Revision 1.30 1993/04/20 15:04:00 kl * ti - level * auf 3 erhoeht und unnoetige . Revision 1.29 1993/04/18 16:00:21 kl . Revision 1.28 1993/03/18 13:27:53 kl Konstanten fuer die des analysed - Slots entfernt . Revision 1.27 1993/03/10 08:48:49 kl * ti - verbosity * gesenkt . Neue Konstanten eingefuehrt . Revision 1.25 1993/03/04 10:43:33 kl * ti - level * eingefuehrt und unnoetige . Revision Keyword eingefuegt . Makrodefinitionen zs - typecase und update - type - f nach titypes verlegt . Revision 1.22 1993/01/27 13:02:47 kl Makrodefinition von update - type - f aus timisc.lisp . Revision 1.21 1993/01/26 18:39:35 kl Globale Variablen aus den Typinferenzdurchlaeufen hierhin verlegt . * ti - current - function * eingefuehrt . entfernt , weil die entsprechenden in Annotationen . Makro zs - typecase , ueber zs - typen entspricht eingebaut . Revision 1.18 1993/01/20 17:49:17 kl nun defclass1 anstatt . Revision 1.17 1993/01/19 10:32:27 kl Neue globale Variable * ti - type - declarations - are - initialized * eingefuehrt . Revision 1.15 1992/12/10 10:14:19 kl und . Revision 1.14 1992/12/08 14:14:43 kl geaendert . Unnoetige globale Variablen entfernt . get - fun - descr nach . Revision 1.12 1992/12/01 15:39:30 kl und neue globale Variablen eingefuehrt . Revision 1.11 1992/11/26 11:14:42 kl um Typschemata erweitert . fuer die getypten importierten Funktionen und fuer zwei Revision 1.10 1992/11/04 13:26:35 kl Typdeklarationen nach tidecl.lisp verlegt . . Typdeklarationen erweitert . Revision 1.8 1992/10/27 12:08:38 kl An neuen Typverband angepasst . Typschemata werden waehrend der Uebersetzungzeit in Funktionen umgewandelt . Revision 1.6 1992/10/01 17:02:41 kl Makro declare - type auf neue Art der Typabstraktionsfunktionen umgestellt . Alle Definitionen des Typverbandes nach titypes.lisp verlegt . Repraesentation der Funktionsbeschreibungen verbessert . Revision 1.3 1992/09/14 14:07:05 kl Liste der Systemfunktionsbeschreibungen erweitert . Zu einigen Systemfunktionen sind jetzt Typen deklariert . Revision 1.1 1992/09/12 18:06:25 kl (in-package "CLICC") Natuerliche Zahl , die angibt , die . Je hoeher der angegebenen Wert ist , desto ` globaler ' arbeitet die Typinferenz . Mit niedrigerem Grad sinkt die fuer die , allerdings in der Regel die inferierten Ergebnisse schwacher . Die genaue Einteilung ist wie folgt : 0 : Es werden keine Typen inferiert . werden auf die entsprechenden Typen , alle 1 : Es werden keine Aufrufkontexte beachtet . Das entspricht in diesem Fall einer intraprozeduralen Typinferenz . Diese Stufe wird realisiert , indem die Eintrittsumgebungen aller Funktionen mit Top - Elementen vorbesetzt werden und der Ergebnistyp Top gesetzt wird . 2 : In dieser Stufe werden alle Aufrufkontexte beachtet . 3 : In dieser Stufe werden die Typen globaler in den . Die Ausfuehrung dieser Analysestufe benoetigt in der Regel deutlich die . Sie ermittelt dafuer die i m Vergleich zu den . (defvar *ti-level* 2) Soll eine den Nichtliteralen durchgeführt werden ? (defun do-type-inference-on-non-literals () (> *ti-level* 0)) (defun do-interprocedural-type-inference () (> *ti-level* 1)) Sollen für dynamisch präzise Typen ermittelt werden ? (defun use-bindings-of-dynamic-variables () (> *ti-level* 2)) die ( aufwendigere ) Typsemantik für Funktionen verwendet werden ? (defun use-precise-function-type-semantics () (> *ti-level* 2)) Natuerliche den . angegebenen Wert ist , desto und Meldungen werden waehrend des Durchlaufs erzeugt . Ist * ti - verbosity*=0 , werden . (defvar *ti-verbosity* 3) Diese Variable wird zum Propagieren von Typbindungen verwendet . Sie enthaelt die locations in Form einer Assoziationsliste . Die Liste besteht ( < location > . < zugeordneter Typ > ) . (defvar *type-environment*) Menge der noch zu analysierenden Funktionen und Klassen . Diese Variable wird i m zweiten Pass der Typinferenz ( tipass2 ) verwendet . (defvar *ti-workset*) * successor - workset * enthaelt die analysierenden aller zu bearbeitenden Funktionen . Die Einfuehrung dieser Menge beschleunigt die Fixpunktiteration , weil nicht alle Mengenoperation auf der evtl . * geschehen . (defvar *successor-workset*) Sind die Typdeklarationen initialisiert worden ? die importierten Funktionen und Funktionen zur Typzusicherungen fuer Ausdruecke an Praedikatsposition eines Konditionals . (defvar *ti-type-declarations-are-initialized*) Umgebung , in der Funktionen fuer Typzusicherungen in if - Konstrukten in Form einer . Sie enthaelt Paare der Gestalt : (defvar *ti-predicate-assertion-environment* ()) Angabe , wie haeufig die Groesse der * ti - workset * ausgeben werden soll . (defconstant *ti-write-size-of-workset-interval* 300) (provide "tidef")
d648ff264caebdf5c1689defb7393879baf157c69586eb14ff193673a0d40db7
cgrand/boring
boring.clj
(ns net.cgrand.boring (:require [clojure.java.io :as io])) ;; syntax: "(" tunnel ")" rest ;; examples: (ssh:user@server)localhost:5555 ;; examples: (ssh:user@server)(oc:pod-name)5555 (defprotocol Connector (connect-through [connector host port] "Returns a pair of streams as {:in output-stream :out input-stream} -- yes they are inverted.")) (def socket-connector (reify java.io.Closeable (close [_] nil) Connector (connect-through [_ host port] (let [socket (java.net.Socket. ^String host (int port))] {:in (.getOutputStream socket) :out (.getInputStream socket)})))) (defn- resolve-identity [options host user] (some #(let [creds (get-in options % {})] (when (some creds [:ssh/key :ssh/password]) creds)) [[[host user]] [[host]] []])) (defn ssh [connector tunnel-segment-spec options] (let [[_ user ssh-host ssh-port] (re-matches #"(.*?)@(.*?)(?::(\d+))?" tunnel-segment-spec) ssh-port (Integer/parseInt (or ssh-port "22")) {:keys [:ssh/key :ssh/password]} (resolve-identity options ssh-host user)] TODO use connector for nested tunnels (let [client (doto (org.apache.sshd.client.SshClient/setUpDefaultClient) .start) session (-> client (.connect user ssh-host ssh-port) (doto .await) .getSession)] (if key (.addPublicKeyIdentity session (org.apache.sshd.common.util.security.SecurityUtils/loadKeyPairIdentity "shhhh" (io/input-stream key) (reify org.apache.sshd.common.config.keys.FilePasswordProvider (getPassword [_ _] password)))) (.addPasswordIdentity session password)) (-> session .auth .verify) (reify java.io.Closeable (close [_] (.close session) (.close connector)) Connector (connect-through [_ host port] (let [channel (.createDirectTcpipChannel session (org.apache.sshd.common.util.net.SshdSocketAddress. "ssh-repl-client" 0) (org.apache.sshd.common.util.net.SshdSocketAddress. host port))] (-> channel .open .verify) {:in (-> channel .getInvertedIn #_(io/writer :encoding "UTF-8")) :out (-> channel .getInvertedOut #_(io/reader :encoding "UTF-8"))})))))) (defn- require-resolve-sym [sym] (let [ns-sym (symbol (namespace sym))] (when-not (find-ns ns-sym) (require ns-sym)) (resolve sym))) (defn- parse-connection-string [connection-string] (if-some [[_ tunnel-segments exit] (re-matches #"(\((?:[^()]|\)\()*\))?([^()]*)" connection-string)] (let [tunnel-segments (into [] (map #(if-some [[_ ns tag segment-spec] (re-matches #"\((?:(.*?)/)?(.*?):(.*)\)" %)] [(require-resolve-sym (symbol (or ns "net.cgrand.boring") tag)) segment-spec] (throw (ex-info (str "Can't parse tunnel segment. " (pr-str %)) {::segment %})))) (re-seq #"\(.*?\)" (or tunnel-segments "")))] [tunnel-segments exit]) (throw (ex-info (str "Can't parse connection string. " (pr-str connection-string)) {::connection-string connection-string})))) (defn connect "Returns a pair of streams as {:in output-stream :out input-stream} -- yes they are inverted." [connection-string options] (let [[tunnels exit] (parse-connection-string connection-string) [_ host port] (re-matches #"(?:(.*):)?(\d+)" exit) port (Integer/parseInt port) connector (reduce (fn [connector [f spec]] (f connector spec options)) socket-connector #_TODO tunnels)] (connect-through connector host port))) ; TODO api for repeatedly establishing connections while sharing tunnels
null
https://raw.githubusercontent.com/cgrand/boring/bca8885f01f8c7c0ad67c8d23cdd4ccc199dec1c/src/net/cgrand/boring.clj
clojure
syntax: "(" tunnel ")" rest examples: (ssh:user@server)localhost:5555 examples: (ssh:user@server)(oc:pod-name)5555 TODO api for repeatedly establishing connections while sharing tunnels
(ns net.cgrand.boring (:require [clojure.java.io :as io])) (defprotocol Connector (connect-through [connector host port] "Returns a pair of streams as {:in output-stream :out input-stream} -- yes they are inverted.")) (def socket-connector (reify java.io.Closeable (close [_] nil) Connector (connect-through [_ host port] (let [socket (java.net.Socket. ^String host (int port))] {:in (.getOutputStream socket) :out (.getInputStream socket)})))) (defn- resolve-identity [options host user] (some #(let [creds (get-in options % {})] (when (some creds [:ssh/key :ssh/password]) creds)) [[[host user]] [[host]] []])) (defn ssh [connector tunnel-segment-spec options] (let [[_ user ssh-host ssh-port] (re-matches #"(.*?)@(.*?)(?::(\d+))?" tunnel-segment-spec) ssh-port (Integer/parseInt (or ssh-port "22")) {:keys [:ssh/key :ssh/password]} (resolve-identity options ssh-host user)] TODO use connector for nested tunnels (let [client (doto (org.apache.sshd.client.SshClient/setUpDefaultClient) .start) session (-> client (.connect user ssh-host ssh-port) (doto .await) .getSession)] (if key (.addPublicKeyIdentity session (org.apache.sshd.common.util.security.SecurityUtils/loadKeyPairIdentity "shhhh" (io/input-stream key) (reify org.apache.sshd.common.config.keys.FilePasswordProvider (getPassword [_ _] password)))) (.addPasswordIdentity session password)) (-> session .auth .verify) (reify java.io.Closeable (close [_] (.close session) (.close connector)) Connector (connect-through [_ host port] (let [channel (.createDirectTcpipChannel session (org.apache.sshd.common.util.net.SshdSocketAddress. "ssh-repl-client" 0) (org.apache.sshd.common.util.net.SshdSocketAddress. host port))] (-> channel .open .verify) {:in (-> channel .getInvertedIn #_(io/writer :encoding "UTF-8")) :out (-> channel .getInvertedOut #_(io/reader :encoding "UTF-8"))})))))) (defn- require-resolve-sym [sym] (let [ns-sym (symbol (namespace sym))] (when-not (find-ns ns-sym) (require ns-sym)) (resolve sym))) (defn- parse-connection-string [connection-string] (if-some [[_ tunnel-segments exit] (re-matches #"(\((?:[^()]|\)\()*\))?([^()]*)" connection-string)] (let [tunnel-segments (into [] (map #(if-some [[_ ns tag segment-spec] (re-matches #"\((?:(.*?)/)?(.*?):(.*)\)" %)] [(require-resolve-sym (symbol (or ns "net.cgrand.boring") tag)) segment-spec] (throw (ex-info (str "Can't parse tunnel segment. " (pr-str %)) {::segment %})))) (re-seq #"\(.*?\)" (or tunnel-segments "")))] [tunnel-segments exit]) (throw (ex-info (str "Can't parse connection string. " (pr-str connection-string)) {::connection-string connection-string})))) (defn connect "Returns a pair of streams as {:in output-stream :out input-stream} -- yes they are inverted." [connection-string options] (let [[tunnels exit] (parse-connection-string connection-string) [_ host port] (re-matches #"(?:(.*):)?(\d+)" exit) port (Integer/parseInt port) connector (reduce (fn [connector [f spec]] (f connector spec options)) socket-connector #_TODO tunnels)] (connect-through connector host port)))
81bb3ddd8ec72ab09ab6c318f43c4e54299d671670437d55e29621a41d4b1d16
emqx/quic
quicer_nif.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(quicer_nif). -export([ open_lib/0 , close_lib/0 , reg_open/0 , reg_open/1 , reg_close/0 , listen/2 , close_listener/1 , async_connect/3 , async_accept/2 , async_handshake/1 , async_shutdown_connection/3 , async_accept_stream/2 , start_stream/2 , csend/4 , send/3 , recv/2 , send_dgram/3 , async_shutdown_stream/3 , sockname/1 , getopt/3 , setopt/4 , controlling_process/2 ]). -export([ get_conn_rid/1 , get_stream_rid/1 ]). %% For tests only -export([open_connection/0]). -on_load(init/0). -include_lib("kernel/include/file.hrl"). -include("quicer.hrl"). -include("quicer_types.hrl"). -spec init() -> ok. init() -> NifName = "libquicer_nif", {ok, Niflib} = locate_lib(priv_dir(), NifName), ok = erlang:load_nif(Niflib, 0), It could cause if MsQuic library is not opened nor registered . %% here we have added dummy calls, and it should cover most of cases unless caller wants to call : load_nif/1 and then call quicer_nif %% without opened library to suicide. %% Note , we could do same dummy calls in instead but it might mess up the reference counts . {ok, _} = open_lib(), %% dummy reg open case reg_open() of ok -> ok; {error, badarg} -> %% already opened ok end. -spec open_lib() -> {ok, true} | %% opened {ok, false} | %% already opened {ok, debug} | %% opened with lttng debug library loaded (if present) {error, open_failed, atom_reason()}. open_lib() -> LibFile = case locate_lib(priv_dir(), "libmsquic.lttng.so") of {ok, File} -> File; {error, _} -> priv_dir() end, open_lib(LibFile). open_lib(_LttngLib) -> erlang:nif_error(nif_library_not_loaded). -spec close_lib() -> ok. close_lib() -> erlang:nif_error(nif_library_not_loaded). -spec reg_open() -> ok | {error, badarg}. reg_open() -> erlang:nif_error(nif_library_not_loaded). -spec reg_open(execution_profile()) -> ok | {error, badarg}. reg_open(_) -> erlang:nif_error(nif_library_not_loaded). -spec reg_close() -> ok. reg_close() -> erlang:nif_error(nif_library_not_loaded). -spec listen(listen_on(), listen_opts()) -> {ok, listener_handle()} | {error, listener_open_error, atom_reason()} | {error, listener_start_error, atom_reason()}. listen(_ListenOn, _Options) -> erlang:nif_error(nif_library_not_loaded). -spec close_listener(listener_handle()) -> ok. close_listener(_Listener) -> erlang:nif_error(nif_library_not_loaded). -spec open_connection() -> {ok, connection_handle()} | {error, atom_reason()}. open_connection() -> erlang:nif_error(nif_library_not_loaded). -spec async_connect(hostname(), inet:port_number(), conn_opts()) -> {ok, connection_handle()} | {error, conn_open_error | config_error | conn_start_error}. async_connect(_Host, _Port, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec async_accept(listener_handle(), acceptor_opts()) -> {ok, listener_handle()} | {error, badarg | param_error | not_enough_mem | badpid}. async_accept(_Listener, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec async_handshake(connection_handle()) -> ok | {error, badarg | atom_reason()}. async_handshake(_Connection) -> erlang:nif_error(nif_library_not_loaded). -spec async_shutdown_connection(connection_handle(), conn_shutdown_flag(), app_errno()) -> ok | {error, badarg}. async_shutdown_connection(_Conn, _Flags, _ErrorCode) -> erlang:nif_error(nif_library_not_loaded). -spec async_accept_stream(connection_handle(), stream_opts()) -> {ok, connection_handle()} | {error, badarg | internal_error | bad_pid | owner_dead}. async_accept_stream(_Conn, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec start_stream(connection_handle(), stream_opts()) -> {ok, stream_handle()} | {error, badarg | internal_error | bad_pid | owner_dead | not_enough_mem} | {error, stream_open_error, atom_reason()} | {error, stream_start_error, atom_reason()}. start_stream(_Conn, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec csend(connection_handle(), iodata(), stream_opts(), send_flags()) -> {ok, BytesSent :: pos_integer()} | {error, badarg | not_enough_mem | closed} | {error, stream_send_error, atom_reason()}. csend(_Conn, _Data, _Opts, _Flags) -> erlang:nif_error(nif_library_not_loaded). -spec send(stream_handle(), iodata(), send_flags()) -> {ok, BytesSent :: pos_integer()} | {error, badarg | not_enough_mem | closed} | {error, stream_send_error, atom_reason()}. send(_Stream, _Data, _Flags) -> erlang:nif_error(nif_library_not_loaded). -spec recv(stream_handle(), non_neg_integer()) -> {ok, binary()} | {ok, not_ready} | {error, badarg | einval | closed}. recv(_Stream, _Len) -> erlang:nif_error(nif_library_not_loaded). -spec send_dgram(connection_handle(), iodata(), send_flags()) -> {ok, BytesSent :: pos_integer()} | {error, badarg | not_enough_memory | closed} | {error, dgram_send_error, atom_reason()}. send_dgram(_Conn, _Data, _Flags) -> erlang:nif_error(nif_library_not_loaded). -spec async_shutdown_stream(stream_handle(), stream_shutdown_flags(), app_errno()) -> ok | {error, badarg | atom_reason()}. async_shutdown_stream(_Stream, _Flags, _ErrorCode) -> erlang:nif_error(nif_library_not_loaded). -spec sockname(connection_handle() | stream_handle()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, badarg | sockname_error}. sockname(_Conn) -> erlang:nif_error(nif_library_not_loaded). -spec getopt(handle(), optname(), optlevel()) -> not_found | %% `optname' not found, or wrong `optlevel' must be a bug. {ok, any()} | %% when optname = param_conn_settings {error, badarg | param_error | internal_error | not_enough_mem} | {error, atom_reason()}. getopt(_Handle, _Optname, _IsRaw) -> erlang:nif_error(nif_library_not_loaded). -spec setopt(handle(), optname(), any(), optlevel()) -> ok | {error, badarg | param_error | internal_error | not_enough_mem} | {error, atom_reason()}. setopt(_Handle, _Opt, _Value, _Level) -> erlang:nif_error(nif_library_not_loaded). -spec get_conn_rid(connection_handle()) -> {ok, non_neg_integer()} | {error, badarg | internal_error}. get_conn_rid(_Handle) -> erlang:nif_error(nif_library_not_loaded). -spec get_stream_rid(stream_handle()) -> {ok, non_neg_integer()} | {error, badarg | internal_error}. get_stream_rid(_Handle) -> erlang:nif_error(nif_library_not_loaded). -spec controlling_process(connection_handle() | stream_handle(), pid()) -> ok | {error, closed | badarg | owner_dead | not_owner}. controlling_process(_H, _P) -> erlang:nif_error(nif_library_not_loaded). %% Internals -spec locate_lib(file:name(), file:name()) -> {ok, file:filename()} | {error, not_found}. locate_lib(PrivDir, LibName) -> case prim_file:read_file_info(PrivDir) of {ok, #file_info{type = directory}} -> {ok, filename:join(PrivDir, LibName)}; maybe escript , Escript = filename:dirname(filename:dirname(PrivDir)), case file:read_file_info(Escript) of {ok, #file_info{type = regular}} -> try locate the file in same dir of escript {ok, filename:join(filename:dirname(Escript), LibName)}; _ -> {error, not_found} end end. priv_dir() -> case code:priv_dir(quicer) of {error, bad_name} -> "priv"; Dir -> Dir end.
null
https://raw.githubusercontent.com/emqx/quic/d2d8db11e6e5a54ff325c6db9a9816eee8ffb020/src/quicer_nif.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------- For tests only here we have added dummy calls, and it should cover most of cases without opened library to suicide. dummy reg open already opened opened already opened opened with lttng debug library loaded (if present) `optname' not found, or wrong `optlevel' must be a bug. when optname = param_conn_settings Internals
Copyright ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. 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(quicer_nif). -export([ open_lib/0 , close_lib/0 , reg_open/0 , reg_open/1 , reg_close/0 , listen/2 , close_listener/1 , async_connect/3 , async_accept/2 , async_handshake/1 , async_shutdown_connection/3 , async_accept_stream/2 , start_stream/2 , csend/4 , send/3 , recv/2 , send_dgram/3 , async_shutdown_stream/3 , sockname/1 , getopt/3 , setopt/4 , controlling_process/2 ]). -export([ get_conn_rid/1 , get_stream_rid/1 ]). -export([open_connection/0]). -on_load(init/0). -include_lib("kernel/include/file.hrl"). -include("quicer.hrl"). -include("quicer_types.hrl"). -spec init() -> ok. init() -> NifName = "libquicer_nif", {ok, Niflib} = locate_lib(priv_dir(), NifName), ok = erlang:load_nif(Niflib, 0), It could cause if MsQuic library is not opened nor registered . unless caller wants to call : load_nif/1 and then call quicer_nif Note , we could do same dummy calls in instead but it might mess up the reference counts . {ok, _} = open_lib(), case reg_open() of ok -> ok; {error, badarg} -> ok end. -spec open_lib() -> {error, open_failed, atom_reason()}. open_lib() -> LibFile = case locate_lib(priv_dir(), "libmsquic.lttng.so") of {ok, File} -> File; {error, _} -> priv_dir() end, open_lib(LibFile). open_lib(_LttngLib) -> erlang:nif_error(nif_library_not_loaded). -spec close_lib() -> ok. close_lib() -> erlang:nif_error(nif_library_not_loaded). -spec reg_open() -> ok | {error, badarg}. reg_open() -> erlang:nif_error(nif_library_not_loaded). -spec reg_open(execution_profile()) -> ok | {error, badarg}. reg_open(_) -> erlang:nif_error(nif_library_not_loaded). -spec reg_close() -> ok. reg_close() -> erlang:nif_error(nif_library_not_loaded). -spec listen(listen_on(), listen_opts()) -> {ok, listener_handle()} | {error, listener_open_error, atom_reason()} | {error, listener_start_error, atom_reason()}. listen(_ListenOn, _Options) -> erlang:nif_error(nif_library_not_loaded). -spec close_listener(listener_handle()) -> ok. close_listener(_Listener) -> erlang:nif_error(nif_library_not_loaded). -spec open_connection() -> {ok, connection_handle()} | {error, atom_reason()}. open_connection() -> erlang:nif_error(nif_library_not_loaded). -spec async_connect(hostname(), inet:port_number(), conn_opts()) -> {ok, connection_handle()} | {error, conn_open_error | config_error | conn_start_error}. async_connect(_Host, _Port, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec async_accept(listener_handle(), acceptor_opts()) -> {ok, listener_handle()} | {error, badarg | param_error | not_enough_mem | badpid}. async_accept(_Listener, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec async_handshake(connection_handle()) -> ok | {error, badarg | atom_reason()}. async_handshake(_Connection) -> erlang:nif_error(nif_library_not_loaded). -spec async_shutdown_connection(connection_handle(), conn_shutdown_flag(), app_errno()) -> ok | {error, badarg}. async_shutdown_connection(_Conn, _Flags, _ErrorCode) -> erlang:nif_error(nif_library_not_loaded). -spec async_accept_stream(connection_handle(), stream_opts()) -> {ok, connection_handle()} | {error, badarg | internal_error | bad_pid | owner_dead}. async_accept_stream(_Conn, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec start_stream(connection_handle(), stream_opts()) -> {ok, stream_handle()} | {error, badarg | internal_error | bad_pid | owner_dead | not_enough_mem} | {error, stream_open_error, atom_reason()} | {error, stream_start_error, atom_reason()}. start_stream(_Conn, _Opts) -> erlang:nif_error(nif_library_not_loaded). -spec csend(connection_handle(), iodata(), stream_opts(), send_flags()) -> {ok, BytesSent :: pos_integer()} | {error, badarg | not_enough_mem | closed} | {error, stream_send_error, atom_reason()}. csend(_Conn, _Data, _Opts, _Flags) -> erlang:nif_error(nif_library_not_loaded). -spec send(stream_handle(), iodata(), send_flags()) -> {ok, BytesSent :: pos_integer()} | {error, badarg | not_enough_mem | closed} | {error, stream_send_error, atom_reason()}. send(_Stream, _Data, _Flags) -> erlang:nif_error(nif_library_not_loaded). -spec recv(stream_handle(), non_neg_integer()) -> {ok, binary()} | {ok, not_ready} | {error, badarg | einval | closed}. recv(_Stream, _Len) -> erlang:nif_error(nif_library_not_loaded). -spec send_dgram(connection_handle(), iodata(), send_flags()) -> {ok, BytesSent :: pos_integer()} | {error, badarg | not_enough_memory | closed} | {error, dgram_send_error, atom_reason()}. send_dgram(_Conn, _Data, _Flags) -> erlang:nif_error(nif_library_not_loaded). -spec async_shutdown_stream(stream_handle(), stream_shutdown_flags(), app_errno()) -> ok | {error, badarg | atom_reason()}. async_shutdown_stream(_Stream, _Flags, _ErrorCode) -> erlang:nif_error(nif_library_not_loaded). -spec sockname(connection_handle() | stream_handle()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, badarg | sockname_error}. sockname(_Conn) -> erlang:nif_error(nif_library_not_loaded). -spec getopt(handle(), optname(), optlevel()) -> {error, badarg | param_error | internal_error | not_enough_mem} | {error, atom_reason()}. getopt(_Handle, _Optname, _IsRaw) -> erlang:nif_error(nif_library_not_loaded). -spec setopt(handle(), optname(), any(), optlevel()) -> ok | {error, badarg | param_error | internal_error | not_enough_mem} | {error, atom_reason()}. setopt(_Handle, _Opt, _Value, _Level) -> erlang:nif_error(nif_library_not_loaded). -spec get_conn_rid(connection_handle()) -> {ok, non_neg_integer()} | {error, badarg | internal_error}. get_conn_rid(_Handle) -> erlang:nif_error(nif_library_not_loaded). -spec get_stream_rid(stream_handle()) -> {ok, non_neg_integer()} | {error, badarg | internal_error}. get_stream_rid(_Handle) -> erlang:nif_error(nif_library_not_loaded). -spec controlling_process(connection_handle() | stream_handle(), pid()) -> ok | {error, closed | badarg | owner_dead | not_owner}. controlling_process(_H, _P) -> erlang:nif_error(nif_library_not_loaded). -spec locate_lib(file:name(), file:name()) -> {ok, file:filename()} | {error, not_found}. locate_lib(PrivDir, LibName) -> case prim_file:read_file_info(PrivDir) of {ok, #file_info{type = directory}} -> {ok, filename:join(PrivDir, LibName)}; maybe escript , Escript = filename:dirname(filename:dirname(PrivDir)), case file:read_file_info(Escript) of {ok, #file_info{type = regular}} -> try locate the file in same dir of escript {ok, filename:join(filename:dirname(Escript), LibName)}; _ -> {error, not_found} end end. priv_dir() -> case code:priv_dir(quicer) of {error, bad_name} -> "priv"; Dir -> Dir end.
6559fc6a50c52ad22f2b3f16a2578882b23439c8c78517869dab987ef8a4bbcb
gvolpe/effects-playground
Main.hs
module Main where import Prelude hiding ( read ) import Cap ( echoCap ) import Cloud ( cloudEcho ) import Fusion ( fusedEchoIO ) import Poly ( echoPoly ) import ReaderIO ( echoRIO ) import Tagless cloudMain :: IO () cloudMain = cloudEcho fusedMain :: IO () fusedMain = fusedEchoIO polyMain :: IO () polyMain = echoPoly rioMain :: IO () rioMain = echoRIO taglessMain :: IO () taglessMain = echoTagless main :: IO () main = echoCap
null
https://raw.githubusercontent.com/gvolpe/effects-playground/2b5600fe0378b6716282b59785c98a8a75445aa1/app/Main.hs
haskell
module Main where import Prelude hiding ( read ) import Cap ( echoCap ) import Cloud ( cloudEcho ) import Fusion ( fusedEchoIO ) import Poly ( echoPoly ) import ReaderIO ( echoRIO ) import Tagless cloudMain :: IO () cloudMain = cloudEcho fusedMain :: IO () fusedMain = fusedEchoIO polyMain :: IO () polyMain = echoPoly rioMain :: IO () rioMain = echoRIO taglessMain :: IO () taglessMain = echoTagless main :: IO () main = echoCap
80c04b8cce4bbcdde881d15894dbf44e1330064b731d83941ed68fa6974896b9
justinethier/cyclone
sets-test.scm
(import (scheme base) (scheme char) (scheme complex) (cyclone test) (srfi 113) (srfi 128) ) (include "comparators-shim.scm") ;(use test) ( use srfi-113 ) ( use srfi-128 ) ;(load "../sets/comparators-shim.scm") (test-group "sets" (define (big x) (> x 5)) (test-group "sets" (test-group "sets/simple" (define nums (set number-comparator)) ;; nums is now {} (define syms (set eq-comparator 'a 'b 'c 'd)) ;; syms is now {a, b, c, d} (define nums2 (set-copy nums)) ;; nums2 is now {} (define syms2 (set-copy syms)) syms2 is now { a , b , c , d } (define esyms (set eq-comparator)) ;; esyms is now {} (test-assert (set-empty? esyms)) (define total 0) (test-assert (set? nums)) (test-assert (set? syms)) (test-assert (set? nums2)) (test-assert (set? syms2)) (test-assert (not (set? 'a))) (set-adjoin! nums 2) (set-adjoin! nums 3) (set-adjoin! nums 4) (set-adjoin! nums 4) nums is now { 2 , 3 , 4 } (test 4 (set-size (set-adjoin nums 5))) (test 3 (set-size nums)) (test 3 (set-size (set-delete syms 'd))) (test 2 (set-size (set-delete-all syms '(c d)))) (test 4 (set-size syms)) (set-adjoin! syms 'e 'f) ;; syms is now {a, b, c, d, e, f} (test 4 (set-size (set-delete-all! syms '(e f)))) ;; syms is now {a, b, c, d} (test 0 (set-size nums2)) (test 4 (set-size syms2)) (set-delete! nums 2) nums is now { 3 , 4 } (test 2 (set-size nums)) (set-delete! nums 1) (test 2 (set-size nums)) Broken ! - ( set ! nums2 ( set - map ( lambda ( x ) ( * 10 x ) ) number - comparator nums ) ) (set! nums2 (set-map number-comparator (lambda (x) (* 10 x)) nums)) nums2 is now { 30 , 40 } (test-assert (set-contains? nums2 30)) (test-assert (not (set-contains? nums2 3))) (set-for-each (lambda (x) (set! total (+ total x))) nums2) (test 70 total) (test 10 (set-fold + 3 nums)) (set! nums (set eqv-comparator 10 20 30 40 50)) nums is now { 10 , 20 , 30 , 40 , 50 } (test-assert (set=? nums (set-unfold (lambda (i) (= i 0)) (lambda (i) (* i 10)) (lambda (i) (- i 1)) 5 eqv-comparator))) (test '(a) (set->list (set eq-comparator 'a))) (set! syms2 (list->set eq-comparator '(e f))) syms2 is now { e , f } (test 2 (set-size syms2)) (test-assert (set-contains? syms2 'e)) (test-assert (set-contains? syms2 'f)) (list->set! syms2 '(a b)) (test 4 (set-size syms2)) ) ; end sets/simple (test-group "sets/search" (define yam (set char-comparator #\y #\a #\m)) (define (failure/insert insert ignore) (insert 1)) (define (failure/ignore insert ignore) (ignore 2)) (define (success/update element update remove) (update #\b 3)) (define (success/remove element update remove) (remove 4)) (define yam! (set char-comparator #\y #\a #\m #\!)) (define bam (set char-comparator #\b #\a #\m)) (define ym (set char-comparator #\y #\m)) ; (define-values (set1 obj1) ; (set-search! (set-copy yam) #\! failure/insert error)) ; (test-assert (set=? yam! set1)) ( test 1 obj1 ) ( define - values ( set2 obj2 ) ; (set-search! (set-copy yam) #\! failure/ignore error)) ; (test-assert (set=? yam set2)) ( test 2 obj2 ) ( define - values ( set3 obj3 ) ( set - search ! ( set - copy yam ) # \y error success / update ) ) ; (test-assert (set=? bam set3)) ( test 3 obj3 ) ; (define-values (set4 obj4) ( set - search ! ( set - copy yam ) # \a error success / remove ) ) ; (test-assert (set=? ym set4)) ( test 4 obj4 ) ) ; end sets/search (test-group "sets/subsets" (define set2 (set number-comparator 1 2)) (define other-set2 (set number-comparator 1 2)) (define set3 (set number-comparator 1 2 3)) (define set4 (set number-comparator 1 2 3 4)) (define setx (set number-comparator 10 20 30 40)) (test-assert (set=? set2 other-set2)) (test-assert (not (set=? set2 set3))) (test-assert (not (set=? set2 set3 other-set2))) (test-assert (set<? set2 set3 set4)) (test-assert (not (set<? set2 other-set2))) (test-assert (set<=? set2 other-set2 set3)) (test-assert (not (set<=? set2 set3 other-set2))) (test-assert (set>? set4 set3 set2)) (test-assert (not (set>? set2 other-set2))) (test-assert (set>=? set3 other-set2 set2)) (test-assert (not (set>=? other-set2 set3 set2))) ) ; end sets/subsets (test-group "sets/ops" ;; Potentially mutable (define abcd (set eq-comparator 'a 'b 'c 'd)) (define efgh (set eq-comparator 'e 'f 'g 'h)) (define abgh (set eq-comparator 'a 'b 'g 'h)) ;; Never get a chance to be mutated (define other-abcd (set eq-comparator 'a 'b 'c 'd)) (define other-efgh (set eq-comparator 'e 'f 'g 'h)) (define other-abgh (set eq-comparator 'a 'b 'g 'h)) (define all (set eq-comparator 'a 'b 'c 'd 'e 'f 'g 'h)) (define none (set eq-comparator)) (define ab (set eq-comparator 'a 'b)) (define cd (set eq-comparator 'c 'd)) (define ef (set eq-comparator 'e 'f)) (define gh (set eq-comparator 'g 'h)) (define cdgh (set eq-comparator 'c 'd 'g 'h)) (define abcdgh (set eq-comparator 'a 'b 'c 'd 'g 'h)) (define abefgh (set eq-comparator 'a 'b 'e 'f 'g 'h)) (test-assert (set-disjoint? abcd efgh)) (test-assert (not (set-disjoint? abcd ab))) (parameterize ((current-test-comparator set=?)) (test abcd (set-union abcd)) (test all (set-union abcd efgh)) (test abcdgh (set-union abcd abgh)) (test abefgh (set-union efgh abgh)) (define efgh2 (set-copy efgh)) (set-union! efgh2) (test efgh efgh2) (set-union! efgh2 abgh) (test abefgh efgh2) (test abcd (set-intersection abcd)) (test none (set-intersection abcd efgh)) (define abcd2 (set-copy abcd)) (set-intersection! abcd2) (test abcd abcd2) (set-intersection! abcd2 efgh) (test none abcd2) (test ab (set-intersection abcd abgh)) (test ab (set-intersection abgh abcd)) (test abcd (set-difference abcd)) (test cd (set-difference abcd ab)) (test abcd (set-difference abcd gh)) (test none (set-difference abcd abcd)) (define abcd3 (set-copy abcd)) (set-difference! abcd3) (test abcd abcd3) (set-difference! abcd3 abcd) (test none abcd3) (test cdgh (set-xor abcd abgh)) (test all (set-xor abcd efgh)) (test none (set-xor abcd other-abcd)) (define abcd4 (set-copy abcd)) ;; don't test xor! effect (test none (set-xor! abcd4 other-abcd)) (test "abcd smashed?" other-abcd abcd) (test "efgh smashed?" other-efgh efgh) (test "abgh smashed?" other-abgh abgh)) ) ; end sets/subsets (test-group "sets/mismatch" (define nums (set number-comparator 1 2 3)) (define syms (set eq-comparator 'a 'b 'c)) (test-error (set=? nums syms)) (test-error (set<? nums syms)) (test-error (set<=? nums syms)) (test-error (set>? nums syms)) (test-error (set>=? nums syms)) (test-error (set-union nums syms)) (test-error (set-intersection nums syms)) (test-error (set-difference nums syms)) (test-error (set-xor nums syms)) (test-error (set-union! nums syms)) (test-error (set-intersection! nums syms)) (test-error (set-difference! nums syms)) (test-error (set-xor! nums syms)) ) ; end sets/mismatch (test-group "sets/whole" (define whole (set eqv-comparator 1 2 3 4 5 6 7 8 9 10)) (define whole2 (set-copy whole)) (define whole3 (set-copy whole)) (define whole4 (set-copy whole)) (define bottom (set eqv-comparator 1 2 3 4 5)) (define top (set eqv-comparator 6 7 8 9 10)) ( define - values ( ) ; (set-partition big whole)) ; (set-partition! big whole4) ; (parameterize ((current-test-comparator set=?)) ; (test top (set-filter big whole)) ; (test bottom (set-remove big whole)) ( set - filter ! big ) ( test - assert ( not ( set - contains ? 1 ) ) ) ( set - remove ! big whole3 ) ( test - assert ( not ( set - contains ? whole3 10 ) ) ) ; (test top topx) ( test bottom ) ( test top ) ) (test 5 (set-count big whole)) (define hetero (set eqv-comparator 1 2 'a 3 4)) (define homo (set eqv-comparator 1 2 3 4 5)) (test 'a (set-find symbol? hetero (lambda () (error "wrong")))) (test-error (set-find symbol? homo (lambda () (error "wrong")))) (test-assert (set-any? symbol? hetero)) (test-assert (set-any? number? hetero)) (test-assert (not (set-every? symbol? hetero))) (test-assert (not (set-every? number? hetero))) (test-assert (not (set-any? symbol? homo))) (test-assert (set-every? number? homo)) ) ; end sets/whole (test-group "sets/lowlevel" (define bucket (set string-ci-comparator "abc" "def")) (test string-ci-comparator (set-element-comparator bucket)) (test-assert (set-contains? bucket "abc")) (test-assert (set-contains? bucket "ABC")) (test "def" (set-member bucket "DEF" "fqz")) (test "fqz" (set-member bucket "lmn" "fqz")) (define nums (set number-comparator 1 2 3)) nums is now { 1 , 2 , 3 } (define nums2 (set-replace nums 2.0)) nums2 is now { 1 , 2.0 , 3 } (test-assert (set-any? inexact? nums2)) (set-replace! nums 2.0) nums is now { 1 , 2.0 , 3 } (test-assert (set-any? inexact? nums)) (define sos (set set-comparator (set equal-comparator '(2 . 1) '(1 . 1) '(0 . 2) '(0 . 0)) (set equal-comparator '(2 . 1) '(1 . 1) '(0 . 0) '(0 . 2)))) (test 1 (set-size sos)) ) ; end sets/lowlevel ) ; end sets (test-group "bags" (test-group "bags/simple" (define nums (bag number-comparator)) ;; nums is now {} (define syms (bag eq-comparator 'a 'b 'c 'd)) ;; syms is now {a, b, c, d} (define nums2 (bag-copy nums)) ;; nums2 is now {} (define syms2 (bag-copy syms)) syms2 is now { a , b , c , d } (define esyms (bag eq-comparator)) ;; esyms is now {} (test-assert (bag-empty? esyms)) (define total 0) (test-assert (bag? nums)) (test-assert (bag? syms)) (test-assert (bag? nums2)) (test-assert (bag? syms2)) (test-assert (not (bag? 'a))) (bag-adjoin! nums 2) (bag-adjoin! nums 3) (bag-adjoin! nums 4) nums is now { 2 , 3 , 4 } (test 4 (bag-size (bag-adjoin nums 5))) (test 3 (bag-size nums)) (test 3 (bag-size (bag-delete syms 'd))) (test 2 (bag-size (bag-delete-all syms '(c d)))) (test 4 (bag-size syms)) (bag-adjoin! syms 'e 'f) ;; syms is now {a, b, c, d, e, f} (test 4 (bag-size (bag-delete-all! syms '(e f)))) ;; syms is now {a, b, c, d} (test 3 (bag-size nums)) (bag-delete! nums 1) (test 3 (bag-size nums)) Broken - ( set ! nums2 ( bag - map ( lambda ( x ) ( * 10 x ) ) number - comparator nums ) ) (set! nums2 (bag-map number-comparator (lambda (x) (* 10 x)) nums)) nums2 is now { 20 , 30 , 40 } (test-assert (bag-contains? nums2 30)) (test-assert (not (bag-contains? nums2 3))) (bag-for-each (lambda (x) (set! total (+ total x))) nums2) (test 90 total) (test 12 (bag-fold + 3 nums)) (set! nums (bag eqv-comparator 10 20 30 40 50)) nums is now { 10 , 20 , 30 , 40 , 50 } (test-assert (bag=? nums (bag-unfold (lambda (i) (= i 0)) (lambda (i) (* i 10)) (lambda (i) (- i 1)) 5 eqv-comparator))) (test '(a) (bag->list (bag eq-comparator 'a))) (set! syms2 (list->bag eq-comparator '(e f))) syms2 is now { e , f } (test 2 (bag-size syms2)) (test-assert (bag-contains? syms2 'e)) (test-assert (bag-contains? syms2 'f)) (list->bag! syms2 '(e f)) syms2 is now { e , e , f , f } (test 4 (bag-size syms2)) ) ; end bags/simple (test-group "bags/search" (define yam (bag char-comparator #\y #\a #\m)) (define (failure/insert insert ignore) (insert 1)) (define (failure/ignore insert ignore) (ignore 2)) (define (success/update element update remove) (update #\b 3)) (define (success/remove element update remove) (remove 4)) (define yam! (bag char-comparator #\y #\a #\m #\!)) (define bam (bag char-comparator #\b #\a #\m)) (define ym (bag char-comparator #\y #\m)) ; (define-values (bag1 obj1) ; (bag-search! (bag-copy yam) #\! failure/insert error)) ; (test-assert (bag=? yam! bag1)) ( test 1 obj1 ) ; (define-values (bag2 obj2) ; (bag-search! (bag-copy yam) #\! failure/ignore error)) ; (test-assert (bag=? yam bag2)) ( test 2 obj2 ) ; (define-values (bag3 obj3) ( bag - search ! ( bag - copy yam ) # \y error success / update ) ) ; (test-assert (bag=? bam bag3)) ( test 3 obj3 ) ( define - values ( bag4 obj4 ) ( bag - search ! ( bag - copy yam ) # \a error success / remove ) ) ; (test-assert (bag=? ym bag4)) ( test 4 obj4 ) ) ; end bags/search (test-group "bags/elemcount" (define mybag (bag eqv-comparator 1 1 1 1 1 2 2)) (test 5 (bag-element-count mybag 1)) (test 0 (bag-element-count mybag 3)) ) ; end bags/elemcount (test-group "bags/subbags" (define bag2 (bag number-comparator 1 2)) (define other-bag2 (bag number-comparator 1 2)) (define bag3 (bag number-comparator 1 2 3)) (define bag4 (bag number-comparator 1 2 3 4)) (define bagx (bag number-comparator 10 20 30 40)) (test-assert (bag=? bag2 other-bag2)) (test-assert (not (bag=? bag2 bag3))) (test-assert (not (bag=? bag2 bag3 other-bag2))) (test-assert (bag<? bag2 bag3 bag4)) (test-assert (not (bag<? bag2 other-bag2))) (test-assert (bag<=? bag2 other-bag2 bag3)) (test-assert (not (bag<=? bag2 bag3 other-bag2))) (test-assert (bag>? bag4 bag3 bag2)) (test-assert (not (bag>? bag2 other-bag2))) (test-assert (bag>=? bag3 other-bag2 bag2)) (test-assert (not (bag>=? other-bag2 bag3 bag2))) end bags / subbags (test-group "bags/multi" (define one (bag eqv-comparator 10)) (define two (bag eqv-comparator 10 10)) (test-assert (not (bag=? one two))) (test-assert (bag<? one two)) (test-assert (not (bag>? one two))) (test-assert (bag<=? one two)) (test-assert (not (bag>? one two))) (test-assert (bag=? two two)) (test-assert (not (bag<? two two))) (test-assert (not (bag>? two two))) (test-assert (bag<=? two two)) (test-assert (bag>=? two two)) (test '((10 . 2)) (let ((result '())) (bag-for-each-unique (lambda (x y) (set! result (cons (cons x y) result))) two) result)) (test 25 (bag-fold + 5 two)) (test 12 (bag-fold-unique (lambda (k n r) (+ k n r)) 0 two)) ) ; end bags/multi (test-group "bags/ops" ;; Potentially mutable (define abcd (bag eq-comparator 'a 'b 'c 'd)) (define efgh (bag eq-comparator 'e 'f 'g 'h)) (define abgh (bag eq-comparator 'a 'b 'g 'h)) ;; Never get a chance to be mutated (define other-abcd (bag eq-comparator 'a 'b 'c 'd)) (define other-efgh (bag eq-comparator 'e 'f 'g 'h)) (define other-abgh (bag eq-comparator 'a 'b 'g 'h)) (define all (bag eq-comparator 'a 'b 'c 'd 'e 'f 'g 'h)) (define none (bag eq-comparator)) (define ab (bag eq-comparator 'a 'b)) (define cd (bag eq-comparator 'c 'd)) (define ef (bag eq-comparator 'e 'f)) (define gh (bag eq-comparator 'g 'h)) (define cdgh (bag eq-comparator 'c 'd 'g 'h)) (define abcdgh (bag eq-comparator 'a 'b 'c 'd 'g 'h)) (define abefgh (bag eq-comparator 'a 'b 'e 'f 'g 'h)) (test-assert (bag-disjoint? abcd efgh)) (test-assert (not (bag-disjoint? abcd ab))) (parameterize ((current-test-comparator bag=?)) (test abcd (bag-union abcd)) (test all (bag-union abcd efgh)) (test abcdgh (bag-union abcd abgh)) (test abefgh (bag-union efgh abgh)) (define efgh2 (bag-copy efgh)) (bag-union! efgh2) (test efgh efgh2) (bag-union! efgh2 abgh) (test abefgh efgh2) (test abcd (bag-intersection abcd)) (test none (bag-intersection abcd efgh)) (define abcd2 (bag-copy abcd)) (bag-intersection! abcd2) (test abcd abcd2) (bag-intersection! abcd2 efgh) (test none abcd2) (test ab (bag-intersection abcd abgh)) (test ab (bag-intersection abgh abcd)) (test abcd (bag-difference abcd)) (test cd (bag-difference abcd ab)) (test abcd (bag-difference abcd gh)) (test none (bag-difference abcd abcd)) (define abcd3 (bag-copy abcd)) (bag-difference! abcd3) (test abcd abcd3) (bag-difference! abcd3 abcd) (test none abcd3) (test cdgh (bag-xor abcd abgh)) (test all (bag-xor abcd efgh)) (test none (bag-xor abcd other-abcd)) (define abcd4 (bag-copy abcd)) (test none (bag-xor! abcd4 other-abcd)) (define abab (bag eq-comparator 'a 'b 'a 'b)) (test ab (bag-sum ab)) (define ab2 (bag-copy ab)) (test ab (bag-sum! ab2)) (test abab (bag-sum! ab2 ab)) (test abab ab2) (test abab (bag-product 2 ab)) (define ab3 (bag-copy ab)) (bag-product! 2 ab3) (test abab ab3) (test "abcd smashed?" other-abcd abcd) (test "abcd smashed?" other-abcd abcd) (test "efgh smashed?" other-efgh efgh) (test "abgh smashed?" other-abgh abgh)) ) ; end bags/ops (test-group "bags/mismatch" (define nums (bag number-comparator 1 2 3)) (define syms (bag eq-comparator 'a 'b 'c)) (test-error (bag=? nums syms)) (test-error (bag<? nums syms)) (test-error (bag<=? nums syms)) (test-error (bag>? nums syms)) (test-error (bag>=? nums syms)) (test-error (bag-union nums syms)) (test-error (bag-intersection nums syms)) (test-error (bag-difference nums syms)) (test-error (bag-xor nums syms)) (test-error (bag-union! nums syms)) (test-error (bag-intersection! nums syms)) (test-error (bag-difference! nums syms)) ) ; end bags/mismatch (test-group "bags/whole" (define whole (bag eqv-comparator 1 2 3 4 5 6 7 8 9 10)) (define whole2 (bag-copy whole)) (define whole3 (bag-copy whole)) (define whole4 (bag-copy whole)) (define bottom (bag eqv-comparator 1 2 3 4 5)) (define top (bag eqv-comparator 6 7 8 9 10)) ( define - values ( ) ; (bag-partition big whole)) ; (bag-partition! big whole4) ; (parameterize ((current-test-comparator bag=?)) ; (test top (bag-filter big whole)) ; (test bottom (bag-remove big whole)) ( bag - filter ! big ) ( test - assert ( not ( bag - contains ? 1 ) ) ) ( bag - remove ! big whole3 ) ( test - assert ( not ( bag - contains ? whole3 10 ) ) ) ; (test top topx) ( test bottom ) ( test top ) ) (test 5 (bag-count big whole)) (define hetero (bag eqv-comparator 1 2 'a 3 4)) (define homo (bag eqv-comparator 1 2 3 4 5)) (test 'a (bag-find symbol? hetero (lambda () (error "wrong")))) (test-error (bag-find symbol? homo (lambda () (error "wrong")))) (test-assert (bag-any? symbol? hetero)) (test-assert (bag-any? number? hetero)) (test-assert (not (bag-every? symbol? hetero))) (test-assert (not (bag-every? number? hetero))) (test-assert (not (bag-any? symbol? homo))) (test-assert (bag-every? number? homo)) ) ; end bags/whole (test-group "bags/lowlevel" (define bucket (bag string-ci-comparator "abc" "def")) (test string-ci-comparator (bag-element-comparator bucket)) (test-assert (bag-contains? bucket "abc")) (test-assert (bag-contains? bucket "ABC")) (test "def" (bag-member bucket "DEF" "fqz")) (test "fqz" (bag-member bucket "lmn" "fqz")) (define nums (bag number-comparator 1 2 3)) nums is now { 1 , 2 , 3 } (define nums2 (bag-replace nums 2.0)) nums2 is now { 1 , 2.0 , 3 } (test-assert (bag-any? inexact? nums2)) (bag-replace! nums 2.0) nums is now { 1 , 2.0 , 3 } (test-assert (bag-any? inexact? nums)) (define bob (bag bag-comparator (bag eqv-comparator 1 2) (bag eqv-comparator 1 2))) (test 2 (bag-size bob)) ) ; end bags/lowlevel (test-group "bags/semantics" (define mybag (bag number-comparator 1 2)) mybag is { 1 , 2 } (test 2 (bag-size mybag)) (bag-adjoin! mybag 1) mybag is { 1 , 1 , 2 } (test 3 (bag-size mybag)) (test 2 (bag-unique-size mybag)) (bag-delete! mybag 2) mybag is { 1 , 1 } (bag-delete! mybag 2) (test 2 (bag-size mybag)) (bag-increment! mybag 1 3) mybag is { 1 , 1 , 1 , 1 , 1 } (test 5 (bag-size mybag)) (test-assert (bag-decrement! mybag 1 2)) mybag is { 1 , 1 , 1 } (test 3 (bag-size mybag)) (bag-decrement! mybag 1 5) ;; mybag is {} (test 0 (bag-size mybag)) ) ; end bags/semantics (test-group "bags/convert" (define multi (bag eqv-comparator 1 2 2 3 3 3)) (define single (bag eqv-comparator 1 2 3)) (define singleset (set eqv-comparator 1 2 3)) (define minibag (bag eqv-comparator 'a 'a)) (define alist '((a . 2))) (test alist (bag->alist minibag)) (test-assert (bag=? minibag (alist->bag eqv-comparator alist))) (test-assert (set=? singleset (bag->set single))) (test-assert (set=? singleset (bag->set multi))) (test-assert (bag=? single (set->bag singleset))) (test-assert (not (bag=? multi (set->bag singleset)))) (set->bag! minibag singleset) minibag is now { a , a , a , a , 1 , 2 , 3 } (test-assert (bag-contains? minibag 1)) ) ; end bags/convert (test-group "bags/sumprod" (define abb (bag eq-comparator 'a 'b 'b)) (define aab (bag eq-comparator 'a 'a 'b)) (define total (bag-sum abb aab)) (test 3 (bag-count (lambda (x) (eqv? x 'a)) total)) (test 3 (bag-count (lambda (x) (eqv? x 'b)) total)) (test 12 (bag-size (bag-product 2 total))) (define bag1 (bag eqv-comparator 1)) (bag-sum! bag1 bag1) (test 2 (bag-size bag1)) (bag-product! 2 bag1) (test 4 (bag-size bag1)) ) ; end bag/sumprod ) ; end bags (test-group "comparators" (define a (set number-comparator 1 2 3)) (define b (set number-comparator 1 2 4)) (define aa (bag number-comparator 1 2 3)) (define bb (bag number-comparator 1 2 4)) (test-assert (not (=? set-comparator a b))) (test-assert (=? set-comparator a (set-copy a))) (test-error (<? set-comparator a b)) (test-assert (not (=? bag-comparator aa bb))) (test-assert (=? bag-comparator aa (bag-copy aa))) (test-error (<? bag-comparator aa bb)) (test-assert (not (=? (make-default-comparator) a aa))) ) ; end comparators ) ; end r7rs-sets (test-exit)
null
https://raw.githubusercontent.com/justinethier/cyclone/a1c2a8f282f37ce180a5921ae26a5deb04768269/srfi/sets/sets-test.scm
scheme
(use test) (load "../sets/comparators-shim.scm") nums is now {} syms is now {a, b, c, d} nums2 is now {} esyms is now {} syms is now {a, b, c, d, e, f} syms is now {a, b, c, d} end sets/simple (define-values (set1 obj1) (set-search! (set-copy yam) #\! failure/insert error)) (test-assert (set=? yam! set1)) (set-search! (set-copy yam) #\! failure/ignore error)) (test-assert (set=? yam set2)) (test-assert (set=? bam set3)) (define-values (set4 obj4) (test-assert (set=? ym set4)) end sets/search end sets/subsets Potentially mutable Never get a chance to be mutated don't test xor! effect end sets/subsets end sets/mismatch (set-partition big whole)) (set-partition! big whole4) (parameterize ((current-test-comparator set=?)) (test top (set-filter big whole)) (test bottom (set-remove big whole)) (test top topx) end sets/whole end sets/lowlevel end sets nums is now {} syms is now {a, b, c, d} nums2 is now {} esyms is now {} syms is now {a, b, c, d, e, f} syms is now {a, b, c, d} end bags/simple (define-values (bag1 obj1) (bag-search! (bag-copy yam) #\! failure/insert error)) (test-assert (bag=? yam! bag1)) (define-values (bag2 obj2) (bag-search! (bag-copy yam) #\! failure/ignore error)) (test-assert (bag=? yam bag2)) (define-values (bag3 obj3) (test-assert (bag=? bam bag3)) (test-assert (bag=? ym bag4)) end bags/search end bags/elemcount end bags/multi Potentially mutable Never get a chance to be mutated end bags/ops end bags/mismatch (bag-partition big whole)) (bag-partition! big whole4) (parameterize ((current-test-comparator bag=?)) (test top (bag-filter big whole)) (test bottom (bag-remove big whole)) (test top topx) end bags/whole end bags/lowlevel mybag is {} end bags/semantics end bags/convert end bag/sumprod end bags end comparators end r7rs-sets
(import (scheme base) (scheme char) (scheme complex) (cyclone test) (srfi 113) (srfi 128) ) (include "comparators-shim.scm") ( use srfi-113 ) ( use srfi-128 ) (test-group "sets" (define (big x) (> x 5)) (test-group "sets" (test-group "sets/simple" (define nums (set number-comparator)) (define syms (set eq-comparator 'a 'b 'c 'd)) (define nums2 (set-copy nums)) (define syms2 (set-copy syms)) syms2 is now { a , b , c , d } (define esyms (set eq-comparator)) (test-assert (set-empty? esyms)) (define total 0) (test-assert (set? nums)) (test-assert (set? syms)) (test-assert (set? nums2)) (test-assert (set? syms2)) (test-assert (not (set? 'a))) (set-adjoin! nums 2) (set-adjoin! nums 3) (set-adjoin! nums 4) (set-adjoin! nums 4) nums is now { 2 , 3 , 4 } (test 4 (set-size (set-adjoin nums 5))) (test 3 (set-size nums)) (test 3 (set-size (set-delete syms 'd))) (test 2 (set-size (set-delete-all syms '(c d)))) (test 4 (set-size syms)) (set-adjoin! syms 'e 'f) (test 4 (set-size (set-delete-all! syms '(e f)))) (test 0 (set-size nums2)) (test 4 (set-size syms2)) (set-delete! nums 2) nums is now { 3 , 4 } (test 2 (set-size nums)) (set-delete! nums 1) (test 2 (set-size nums)) Broken ! - ( set ! nums2 ( set - map ( lambda ( x ) ( * 10 x ) ) number - comparator nums ) ) (set! nums2 (set-map number-comparator (lambda (x) (* 10 x)) nums)) nums2 is now { 30 , 40 } (test-assert (set-contains? nums2 30)) (test-assert (not (set-contains? nums2 3))) (set-for-each (lambda (x) (set! total (+ total x))) nums2) (test 70 total) (test 10 (set-fold + 3 nums)) (set! nums (set eqv-comparator 10 20 30 40 50)) nums is now { 10 , 20 , 30 , 40 , 50 } (test-assert (set=? nums (set-unfold (lambda (i) (= i 0)) (lambda (i) (* i 10)) (lambda (i) (- i 1)) 5 eqv-comparator))) (test '(a) (set->list (set eq-comparator 'a))) (set! syms2 (list->set eq-comparator '(e f))) syms2 is now { e , f } (test 2 (set-size syms2)) (test-assert (set-contains? syms2 'e)) (test-assert (set-contains? syms2 'f)) (list->set! syms2 '(a b)) (test 4 (set-size syms2)) (test-group "sets/search" (define yam (set char-comparator #\y #\a #\m)) (define (failure/insert insert ignore) (insert 1)) (define (failure/ignore insert ignore) (ignore 2)) (define (success/update element update remove) (update #\b 3)) (define (success/remove element update remove) (remove 4)) (define yam! (set char-comparator #\y #\a #\m #\!)) (define bam (set char-comparator #\b #\a #\m)) (define ym (set char-comparator #\y #\m)) ( test 1 obj1 ) ( define - values ( set2 obj2 ) ( test 2 obj2 ) ( define - values ( set3 obj3 ) ( set - search ! ( set - copy yam ) # \y error success / update ) ) ( test 3 obj3 ) ( set - search ! ( set - copy yam ) # \a error success / remove ) ) ( test 4 obj4 ) (test-group "sets/subsets" (define set2 (set number-comparator 1 2)) (define other-set2 (set number-comparator 1 2)) (define set3 (set number-comparator 1 2 3)) (define set4 (set number-comparator 1 2 3 4)) (define setx (set number-comparator 10 20 30 40)) (test-assert (set=? set2 other-set2)) (test-assert (not (set=? set2 set3))) (test-assert (not (set=? set2 set3 other-set2))) (test-assert (set<? set2 set3 set4)) (test-assert (not (set<? set2 other-set2))) (test-assert (set<=? set2 other-set2 set3)) (test-assert (not (set<=? set2 set3 other-set2))) (test-assert (set>? set4 set3 set2)) (test-assert (not (set>? set2 other-set2))) (test-assert (set>=? set3 other-set2 set2)) (test-assert (not (set>=? other-set2 set3 set2))) (test-group "sets/ops" (define abcd (set eq-comparator 'a 'b 'c 'd)) (define efgh (set eq-comparator 'e 'f 'g 'h)) (define abgh (set eq-comparator 'a 'b 'g 'h)) (define other-abcd (set eq-comparator 'a 'b 'c 'd)) (define other-efgh (set eq-comparator 'e 'f 'g 'h)) (define other-abgh (set eq-comparator 'a 'b 'g 'h)) (define all (set eq-comparator 'a 'b 'c 'd 'e 'f 'g 'h)) (define none (set eq-comparator)) (define ab (set eq-comparator 'a 'b)) (define cd (set eq-comparator 'c 'd)) (define ef (set eq-comparator 'e 'f)) (define gh (set eq-comparator 'g 'h)) (define cdgh (set eq-comparator 'c 'd 'g 'h)) (define abcdgh (set eq-comparator 'a 'b 'c 'd 'g 'h)) (define abefgh (set eq-comparator 'a 'b 'e 'f 'g 'h)) (test-assert (set-disjoint? abcd efgh)) (test-assert (not (set-disjoint? abcd ab))) (parameterize ((current-test-comparator set=?)) (test abcd (set-union abcd)) (test all (set-union abcd efgh)) (test abcdgh (set-union abcd abgh)) (test abefgh (set-union efgh abgh)) (define efgh2 (set-copy efgh)) (set-union! efgh2) (test efgh efgh2) (set-union! efgh2 abgh) (test abefgh efgh2) (test abcd (set-intersection abcd)) (test none (set-intersection abcd efgh)) (define abcd2 (set-copy abcd)) (set-intersection! abcd2) (test abcd abcd2) (set-intersection! abcd2 efgh) (test none abcd2) (test ab (set-intersection abcd abgh)) (test ab (set-intersection abgh abcd)) (test abcd (set-difference abcd)) (test cd (set-difference abcd ab)) (test abcd (set-difference abcd gh)) (test none (set-difference abcd abcd)) (define abcd3 (set-copy abcd)) (set-difference! abcd3) (test abcd abcd3) (set-difference! abcd3 abcd) (test none abcd3) (test cdgh (set-xor abcd abgh)) (test all (set-xor abcd efgh)) (test none (set-xor abcd other-abcd)) (define abcd4 (set-copy abcd)) (test none (set-xor! abcd4 other-abcd)) (test "abcd smashed?" other-abcd abcd) (test "efgh smashed?" other-efgh efgh) (test "abgh smashed?" other-abgh abgh)) (test-group "sets/mismatch" (define nums (set number-comparator 1 2 3)) (define syms (set eq-comparator 'a 'b 'c)) (test-error (set=? nums syms)) (test-error (set<? nums syms)) (test-error (set<=? nums syms)) (test-error (set>? nums syms)) (test-error (set>=? nums syms)) (test-error (set-union nums syms)) (test-error (set-intersection nums syms)) (test-error (set-difference nums syms)) (test-error (set-xor nums syms)) (test-error (set-union! nums syms)) (test-error (set-intersection! nums syms)) (test-error (set-difference! nums syms)) (test-error (set-xor! nums syms)) (test-group "sets/whole" (define whole (set eqv-comparator 1 2 3 4 5 6 7 8 9 10)) (define whole2 (set-copy whole)) (define whole3 (set-copy whole)) (define whole4 (set-copy whole)) (define bottom (set eqv-comparator 1 2 3 4 5)) (define top (set eqv-comparator 6 7 8 9 10)) ( define - values ( ) ( set - filter ! big ) ( test - assert ( not ( set - contains ? 1 ) ) ) ( set - remove ! big whole3 ) ( test - assert ( not ( set - contains ? whole3 10 ) ) ) ( test bottom ) ( test top ) ) (test 5 (set-count big whole)) (define hetero (set eqv-comparator 1 2 'a 3 4)) (define homo (set eqv-comparator 1 2 3 4 5)) (test 'a (set-find symbol? hetero (lambda () (error "wrong")))) (test-error (set-find symbol? homo (lambda () (error "wrong")))) (test-assert (set-any? symbol? hetero)) (test-assert (set-any? number? hetero)) (test-assert (not (set-every? symbol? hetero))) (test-assert (not (set-every? number? hetero))) (test-assert (not (set-any? symbol? homo))) (test-assert (set-every? number? homo)) (test-group "sets/lowlevel" (define bucket (set string-ci-comparator "abc" "def")) (test string-ci-comparator (set-element-comparator bucket)) (test-assert (set-contains? bucket "abc")) (test-assert (set-contains? bucket "ABC")) (test "def" (set-member bucket "DEF" "fqz")) (test "fqz" (set-member bucket "lmn" "fqz")) (define nums (set number-comparator 1 2 3)) nums is now { 1 , 2 , 3 } (define nums2 (set-replace nums 2.0)) nums2 is now { 1 , 2.0 , 3 } (test-assert (set-any? inexact? nums2)) (set-replace! nums 2.0) nums is now { 1 , 2.0 , 3 } (test-assert (set-any? inexact? nums)) (define sos (set set-comparator (set equal-comparator '(2 . 1) '(1 . 1) '(0 . 2) '(0 . 0)) (set equal-comparator '(2 . 1) '(1 . 1) '(0 . 0) '(0 . 2)))) (test 1 (set-size sos)) (test-group "bags" (test-group "bags/simple" (define nums (bag number-comparator)) (define syms (bag eq-comparator 'a 'b 'c 'd)) (define nums2 (bag-copy nums)) (define syms2 (bag-copy syms)) syms2 is now { a , b , c , d } (define esyms (bag eq-comparator)) (test-assert (bag-empty? esyms)) (define total 0) (test-assert (bag? nums)) (test-assert (bag? syms)) (test-assert (bag? nums2)) (test-assert (bag? syms2)) (test-assert (not (bag? 'a))) (bag-adjoin! nums 2) (bag-adjoin! nums 3) (bag-adjoin! nums 4) nums is now { 2 , 3 , 4 } (test 4 (bag-size (bag-adjoin nums 5))) (test 3 (bag-size nums)) (test 3 (bag-size (bag-delete syms 'd))) (test 2 (bag-size (bag-delete-all syms '(c d)))) (test 4 (bag-size syms)) (bag-adjoin! syms 'e 'f) (test 4 (bag-size (bag-delete-all! syms '(e f)))) (test 3 (bag-size nums)) (bag-delete! nums 1) (test 3 (bag-size nums)) Broken - ( set ! nums2 ( bag - map ( lambda ( x ) ( * 10 x ) ) number - comparator nums ) ) (set! nums2 (bag-map number-comparator (lambda (x) (* 10 x)) nums)) nums2 is now { 20 , 30 , 40 } (test-assert (bag-contains? nums2 30)) (test-assert (not (bag-contains? nums2 3))) (bag-for-each (lambda (x) (set! total (+ total x))) nums2) (test 90 total) (test 12 (bag-fold + 3 nums)) (set! nums (bag eqv-comparator 10 20 30 40 50)) nums is now { 10 , 20 , 30 , 40 , 50 } (test-assert (bag=? nums (bag-unfold (lambda (i) (= i 0)) (lambda (i) (* i 10)) (lambda (i) (- i 1)) 5 eqv-comparator))) (test '(a) (bag->list (bag eq-comparator 'a))) (set! syms2 (list->bag eq-comparator '(e f))) syms2 is now { e , f } (test 2 (bag-size syms2)) (test-assert (bag-contains? syms2 'e)) (test-assert (bag-contains? syms2 'f)) (list->bag! syms2 '(e f)) syms2 is now { e , e , f , f } (test 4 (bag-size syms2)) (test-group "bags/search" (define yam (bag char-comparator #\y #\a #\m)) (define (failure/insert insert ignore) (insert 1)) (define (failure/ignore insert ignore) (ignore 2)) (define (success/update element update remove) (update #\b 3)) (define (success/remove element update remove) (remove 4)) (define yam! (bag char-comparator #\y #\a #\m #\!)) (define bam (bag char-comparator #\b #\a #\m)) (define ym (bag char-comparator #\y #\m)) ( test 1 obj1 ) ( test 2 obj2 ) ( bag - search ! ( bag - copy yam ) # \y error success / update ) ) ( test 3 obj3 ) ( define - values ( bag4 obj4 ) ( bag - search ! ( bag - copy yam ) # \a error success / remove ) ) ( test 4 obj4 ) (test-group "bags/elemcount" (define mybag (bag eqv-comparator 1 1 1 1 1 2 2)) (test 5 (bag-element-count mybag 1)) (test 0 (bag-element-count mybag 3)) (test-group "bags/subbags" (define bag2 (bag number-comparator 1 2)) (define other-bag2 (bag number-comparator 1 2)) (define bag3 (bag number-comparator 1 2 3)) (define bag4 (bag number-comparator 1 2 3 4)) (define bagx (bag number-comparator 10 20 30 40)) (test-assert (bag=? bag2 other-bag2)) (test-assert (not (bag=? bag2 bag3))) (test-assert (not (bag=? bag2 bag3 other-bag2))) (test-assert (bag<? bag2 bag3 bag4)) (test-assert (not (bag<? bag2 other-bag2))) (test-assert (bag<=? bag2 other-bag2 bag3)) (test-assert (not (bag<=? bag2 bag3 other-bag2))) (test-assert (bag>? bag4 bag3 bag2)) (test-assert (not (bag>? bag2 other-bag2))) (test-assert (bag>=? bag3 other-bag2 bag2)) (test-assert (not (bag>=? other-bag2 bag3 bag2))) end bags / subbags (test-group "bags/multi" (define one (bag eqv-comparator 10)) (define two (bag eqv-comparator 10 10)) (test-assert (not (bag=? one two))) (test-assert (bag<? one two)) (test-assert (not (bag>? one two))) (test-assert (bag<=? one two)) (test-assert (not (bag>? one two))) (test-assert (bag=? two two)) (test-assert (not (bag<? two two))) (test-assert (not (bag>? two two))) (test-assert (bag<=? two two)) (test-assert (bag>=? two two)) (test '((10 . 2)) (let ((result '())) (bag-for-each-unique (lambda (x y) (set! result (cons (cons x y) result))) two) result)) (test 25 (bag-fold + 5 two)) (test 12 (bag-fold-unique (lambda (k n r) (+ k n r)) 0 two)) (test-group "bags/ops" (define abcd (bag eq-comparator 'a 'b 'c 'd)) (define efgh (bag eq-comparator 'e 'f 'g 'h)) (define abgh (bag eq-comparator 'a 'b 'g 'h)) (define other-abcd (bag eq-comparator 'a 'b 'c 'd)) (define other-efgh (bag eq-comparator 'e 'f 'g 'h)) (define other-abgh (bag eq-comparator 'a 'b 'g 'h)) (define all (bag eq-comparator 'a 'b 'c 'd 'e 'f 'g 'h)) (define none (bag eq-comparator)) (define ab (bag eq-comparator 'a 'b)) (define cd (bag eq-comparator 'c 'd)) (define ef (bag eq-comparator 'e 'f)) (define gh (bag eq-comparator 'g 'h)) (define cdgh (bag eq-comparator 'c 'd 'g 'h)) (define abcdgh (bag eq-comparator 'a 'b 'c 'd 'g 'h)) (define abefgh (bag eq-comparator 'a 'b 'e 'f 'g 'h)) (test-assert (bag-disjoint? abcd efgh)) (test-assert (not (bag-disjoint? abcd ab))) (parameterize ((current-test-comparator bag=?)) (test abcd (bag-union abcd)) (test all (bag-union abcd efgh)) (test abcdgh (bag-union abcd abgh)) (test abefgh (bag-union efgh abgh)) (define efgh2 (bag-copy efgh)) (bag-union! efgh2) (test efgh efgh2) (bag-union! efgh2 abgh) (test abefgh efgh2) (test abcd (bag-intersection abcd)) (test none (bag-intersection abcd efgh)) (define abcd2 (bag-copy abcd)) (bag-intersection! abcd2) (test abcd abcd2) (bag-intersection! abcd2 efgh) (test none abcd2) (test ab (bag-intersection abcd abgh)) (test ab (bag-intersection abgh abcd)) (test abcd (bag-difference abcd)) (test cd (bag-difference abcd ab)) (test abcd (bag-difference abcd gh)) (test none (bag-difference abcd abcd)) (define abcd3 (bag-copy abcd)) (bag-difference! abcd3) (test abcd abcd3) (bag-difference! abcd3 abcd) (test none abcd3) (test cdgh (bag-xor abcd abgh)) (test all (bag-xor abcd efgh)) (test none (bag-xor abcd other-abcd)) (define abcd4 (bag-copy abcd)) (test none (bag-xor! abcd4 other-abcd)) (define abab (bag eq-comparator 'a 'b 'a 'b)) (test ab (bag-sum ab)) (define ab2 (bag-copy ab)) (test ab (bag-sum! ab2)) (test abab (bag-sum! ab2 ab)) (test abab ab2) (test abab (bag-product 2 ab)) (define ab3 (bag-copy ab)) (bag-product! 2 ab3) (test abab ab3) (test "abcd smashed?" other-abcd abcd) (test "abcd smashed?" other-abcd abcd) (test "efgh smashed?" other-efgh efgh) (test "abgh smashed?" other-abgh abgh)) (test-group "bags/mismatch" (define nums (bag number-comparator 1 2 3)) (define syms (bag eq-comparator 'a 'b 'c)) (test-error (bag=? nums syms)) (test-error (bag<? nums syms)) (test-error (bag<=? nums syms)) (test-error (bag>? nums syms)) (test-error (bag>=? nums syms)) (test-error (bag-union nums syms)) (test-error (bag-intersection nums syms)) (test-error (bag-difference nums syms)) (test-error (bag-xor nums syms)) (test-error (bag-union! nums syms)) (test-error (bag-intersection! nums syms)) (test-error (bag-difference! nums syms)) (test-group "bags/whole" (define whole (bag eqv-comparator 1 2 3 4 5 6 7 8 9 10)) (define whole2 (bag-copy whole)) (define whole3 (bag-copy whole)) (define whole4 (bag-copy whole)) (define bottom (bag eqv-comparator 1 2 3 4 5)) (define top (bag eqv-comparator 6 7 8 9 10)) ( define - values ( ) ( bag - filter ! big ) ( test - assert ( not ( bag - contains ? 1 ) ) ) ( bag - remove ! big whole3 ) ( test - assert ( not ( bag - contains ? whole3 10 ) ) ) ( test bottom ) ( test top ) ) (test 5 (bag-count big whole)) (define hetero (bag eqv-comparator 1 2 'a 3 4)) (define homo (bag eqv-comparator 1 2 3 4 5)) (test 'a (bag-find symbol? hetero (lambda () (error "wrong")))) (test-error (bag-find symbol? homo (lambda () (error "wrong")))) (test-assert (bag-any? symbol? hetero)) (test-assert (bag-any? number? hetero)) (test-assert (not (bag-every? symbol? hetero))) (test-assert (not (bag-every? number? hetero))) (test-assert (not (bag-any? symbol? homo))) (test-assert (bag-every? number? homo)) (test-group "bags/lowlevel" (define bucket (bag string-ci-comparator "abc" "def")) (test string-ci-comparator (bag-element-comparator bucket)) (test-assert (bag-contains? bucket "abc")) (test-assert (bag-contains? bucket "ABC")) (test "def" (bag-member bucket "DEF" "fqz")) (test "fqz" (bag-member bucket "lmn" "fqz")) (define nums (bag number-comparator 1 2 3)) nums is now { 1 , 2 , 3 } (define nums2 (bag-replace nums 2.0)) nums2 is now { 1 , 2.0 , 3 } (test-assert (bag-any? inexact? nums2)) (bag-replace! nums 2.0) nums is now { 1 , 2.0 , 3 } (test-assert (bag-any? inexact? nums)) (define bob (bag bag-comparator (bag eqv-comparator 1 2) (bag eqv-comparator 1 2))) (test 2 (bag-size bob)) (test-group "bags/semantics" (define mybag (bag number-comparator 1 2)) mybag is { 1 , 2 } (test 2 (bag-size mybag)) (bag-adjoin! mybag 1) mybag is { 1 , 1 , 2 } (test 3 (bag-size mybag)) (test 2 (bag-unique-size mybag)) (bag-delete! mybag 2) mybag is { 1 , 1 } (bag-delete! mybag 2) (test 2 (bag-size mybag)) (bag-increment! mybag 1 3) mybag is { 1 , 1 , 1 , 1 , 1 } (test 5 (bag-size mybag)) (test-assert (bag-decrement! mybag 1 2)) mybag is { 1 , 1 , 1 } (test 3 (bag-size mybag)) (bag-decrement! mybag 1 5) (test 0 (bag-size mybag)) (test-group "bags/convert" (define multi (bag eqv-comparator 1 2 2 3 3 3)) (define single (bag eqv-comparator 1 2 3)) (define singleset (set eqv-comparator 1 2 3)) (define minibag (bag eqv-comparator 'a 'a)) (define alist '((a . 2))) (test alist (bag->alist minibag)) (test-assert (bag=? minibag (alist->bag eqv-comparator alist))) (test-assert (set=? singleset (bag->set single))) (test-assert (set=? singleset (bag->set multi))) (test-assert (bag=? single (set->bag singleset))) (test-assert (not (bag=? multi (set->bag singleset)))) (set->bag! minibag singleset) minibag is now { a , a , a , a , 1 , 2 , 3 } (test-assert (bag-contains? minibag 1)) (test-group "bags/sumprod" (define abb (bag eq-comparator 'a 'b 'b)) (define aab (bag eq-comparator 'a 'a 'b)) (define total (bag-sum abb aab)) (test 3 (bag-count (lambda (x) (eqv? x 'a)) total)) (test 3 (bag-count (lambda (x) (eqv? x 'b)) total)) (test 12 (bag-size (bag-product 2 total))) (define bag1 (bag eqv-comparator 1)) (bag-sum! bag1 bag1) (test 2 (bag-size bag1)) (bag-product! 2 bag1) (test 4 (bag-size bag1)) (test-group "comparators" (define a (set number-comparator 1 2 3)) (define b (set number-comparator 1 2 4)) (define aa (bag number-comparator 1 2 3)) (define bb (bag number-comparator 1 2 4)) (test-assert (not (=? set-comparator a b))) (test-assert (=? set-comparator a (set-copy a))) (test-error (<? set-comparator a b)) (test-assert (not (=? bag-comparator aa bb))) (test-assert (=? bag-comparator aa (bag-copy aa))) (test-error (<? bag-comparator aa bb)) (test-assert (not (=? (make-default-comparator) a aa))) (test-exit)
2cfba4c4ad35125128973768badfc209aa5577d94b71b8c25ea7be958c216a8e
souenzzo/souenzzo.github.io
fnvr.clj
(ns br.com.souenzzo.fnvr (:require [clojure.data.json :as json] [clojure.string :as string] [clojure.java.io :as io]) (:import (java.util Date) (java.time Instant) (java.net URLEncoder URI) (java.nio.charset StandardCharsets) (java.net.http HttpClient HttpRequest HttpResponse$BodyHandlers))) (set! *warn-on-reflection* true) (defn query [sym] (-> (str "=" sym) slurp (json/read-str :key-fn keyword) :response :docs (->> (filter (fn [{:keys [id]}] (= id (str (namespace sym) ":" (name sym)))))) first)) (def *client (delay (HttpClient/newHttpClient))) (defn select [^HttpClient client params] (let [{:keys [responseHeader response]} (-> (str "?" (string/join "&" (for [[k v] params] (str (URLEncoder/encode (name k) StandardCharsets/UTF_8) "=" (URLEncoder/encode (str v) StandardCharsets/UTF_8))))) ;; (doto prn) URI/create HttpRequest/newBuilder .build (as-> % (.send client % (HttpResponse$BodyHandlers/ofInputStream))) .body io/reader (json/read :key-fn keyword)) {:keys [docs start]} response] (when (seq docs) (lazy-cat docs (select client (assoc params :start (+ start (count docs)))))))) (defn version-history [sym] (-> (select @*client {:q (str "g:" (namespace sym) " AND a:" (name sym) "") :core "gav"}) (->> (map (fn [{:keys [timestamp v]}] {:mvn/version v :sym sym :timestamp (Date/from (Instant/ofEpochMilli timestamp))})))))
null
https://raw.githubusercontent.com/souenzzo/souenzzo.github.io/30a811c4e5633ad07bba1d58d19eb091dac222e9/projects/fnvr/src/br/com/souenzzo/fnvr.clj
clojure
(doto prn)
(ns br.com.souenzzo.fnvr (:require [clojure.data.json :as json] [clojure.string :as string] [clojure.java.io :as io]) (:import (java.util Date) (java.time Instant) (java.net URLEncoder URI) (java.nio.charset StandardCharsets) (java.net.http HttpClient HttpRequest HttpResponse$BodyHandlers))) (set! *warn-on-reflection* true) (defn query [sym] (-> (str "=" sym) slurp (json/read-str :key-fn keyword) :response :docs (->> (filter (fn [{:keys [id]}] (= id (str (namespace sym) ":" (name sym)))))) first)) (def *client (delay (HttpClient/newHttpClient))) (defn select [^HttpClient client params] (let [{:keys [responseHeader response]} (-> (str "?" (string/join "&" (for [[k v] params] (str (URLEncoder/encode (name k) StandardCharsets/UTF_8) "=" (URLEncoder/encode (str v) StandardCharsets/UTF_8))))) URI/create HttpRequest/newBuilder .build (as-> % (.send client % (HttpResponse$BodyHandlers/ofInputStream))) .body io/reader (json/read :key-fn keyword)) {:keys [docs start]} response] (when (seq docs) (lazy-cat docs (select client (assoc params :start (+ start (count docs)))))))) (defn version-history [sym] (-> (select @*client {:q (str "g:" (namespace sym) " AND a:" (name sym) "") :core "gav"}) (->> (map (fn [{:keys [timestamp v]}] {:mvn/version v :sym sym :timestamp (Date/from (Instant/ofEpochMilli timestamp))})))))
b490f68b147364141ed6f15516d6b244e5486772fc59832dbad7fae2b9a72303
xapi-project/xen-api
test_pvs_site.ml
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) module T = Test_common let name_label = "my_pvs_site" let name_description = "about my_pvs_site" let pVS_uuid = "my_pvs_uuid" let cleanup_storage _ _ = () let test_unlicensed () = let __context = T.make_test_database ~features:[] () in Alcotest.check_raises "test_unlicensed: should raise license_restriction" Api_errors.(Server_error (license_restriction, ["PVS_proxy"])) (fun () -> ignore (Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid ) ) let test_introduce () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in Alcotest.(check string) "test_introduce: checking name_label" name_label (Db.PVS_site.get_name_label ~__context ~self:pvs_site) ; Alcotest.(check (list (Alcotest_comparators.ref ()))) "test_introduce: cache storage should be empty" [] (Db.PVS_site.get_cache_storage ~__context ~self:pvs_site) let test_forget_ok () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ; Alcotest.(check bool) "test_forget_ok: PVS site ref should no longer be recognised" false (Db.is_valid_ref __context pvs_site) let test_forget_stopped_proxy () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let (_ : API.ref_PVS_proxy) = T.make_pvs_proxy ~__context ~site:pvs_site ~currently_attached:false () in Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ; Alcotest.(check bool) "test_forget_stopped_proxy: PVS site ref should no longer be recognised" false (Db.is_valid_ref __context pvs_site) let test_forget_running_proxy () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let pvs_proxy = T.make_pvs_proxy ~__context ~site:pvs_site ~currently_attached:true () in Alcotest.check_raises "test_forget_running_proxy should raise \ Api_errors.pvs_site_contains_running_proxies" Api_errors.( Server_error (pvs_site_contains_running_proxies, [Ref.string_of pvs_proxy]) ) (fun () -> Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ) let test_forget_server () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let pvs_server = T.make_pvs_server ~__context ~site:pvs_site () in Alcotest.check_raises "test_forget_server should raise Api_errors.pvs_site_contains_servers" Api_errors.( Server_error (pvs_site_contains_servers, [Ref.string_of pvs_server]) ) (fun () -> Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ) let test_forget_running_proxy_and_server () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let pvs_proxy = T.make_pvs_proxy ~__context ~site:pvs_site ~currently_attached:true () in let (_ : API.ref_PVS_server) = T.make_pvs_server ~__context ~site:pvs_site () in Alcotest.check_raises "test_forget_running_proxy_and_server: should raise \ pvs_site_contains_running_proxies" Api_errors.( Server_error (pvs_site_contains_running_proxies, [Ref.string_of pvs_proxy]) ) (fun () -> Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ) let test = [ ("test_unlicensed", `Quick, test_unlicensed) ; ("test_introduce", `Quick, test_introduce) ; ("test_forget_ok", `Quick, test_forget_ok) ; ("test_forget_stopped_proxy", `Quick, test_forget_stopped_proxy) ; ("test_forget_running_proxy", `Quick, test_forget_running_proxy) ; ("test_forget_server", `Quick, test_forget_server) ; ( "test_forget_running_proxy_and_server" , `Quick , test_forget_running_proxy_and_server ) ]
null
https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/tests/test_pvs_site.ml
ocaml
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) module T = Test_common let name_label = "my_pvs_site" let name_description = "about my_pvs_site" let pVS_uuid = "my_pvs_uuid" let cleanup_storage _ _ = () let test_unlicensed () = let __context = T.make_test_database ~features:[] () in Alcotest.check_raises "test_unlicensed: should raise license_restriction" Api_errors.(Server_error (license_restriction, ["PVS_proxy"])) (fun () -> ignore (Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid ) ) let test_introduce () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in Alcotest.(check string) "test_introduce: checking name_label" name_label (Db.PVS_site.get_name_label ~__context ~self:pvs_site) ; Alcotest.(check (list (Alcotest_comparators.ref ()))) "test_introduce: cache storage should be empty" [] (Db.PVS_site.get_cache_storage ~__context ~self:pvs_site) let test_forget_ok () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ; Alcotest.(check bool) "test_forget_ok: PVS site ref should no longer be recognised" false (Db.is_valid_ref __context pvs_site) let test_forget_stopped_proxy () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let (_ : API.ref_PVS_proxy) = T.make_pvs_proxy ~__context ~site:pvs_site ~currently_attached:false () in Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ; Alcotest.(check bool) "test_forget_stopped_proxy: PVS site ref should no longer be recognised" false (Db.is_valid_ref __context pvs_site) let test_forget_running_proxy () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let pvs_proxy = T.make_pvs_proxy ~__context ~site:pvs_site ~currently_attached:true () in Alcotest.check_raises "test_forget_running_proxy should raise \ Api_errors.pvs_site_contains_running_proxies" Api_errors.( Server_error (pvs_site_contains_running_proxies, [Ref.string_of pvs_proxy]) ) (fun () -> Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ) let test_forget_server () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let pvs_server = T.make_pvs_server ~__context ~site:pvs_site () in Alcotest.check_raises "test_forget_server should raise Api_errors.pvs_site_contains_servers" Api_errors.( Server_error (pvs_site_contains_servers, [Ref.string_of pvs_server]) ) (fun () -> Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ) let test_forget_running_proxy_and_server () = let __context = T.make_test_database () in let pvs_site = Xapi_pvs_site.introduce ~__context ~name_label ~name_description ~pVS_uuid in let pvs_proxy = T.make_pvs_proxy ~__context ~site:pvs_site ~currently_attached:true () in let (_ : API.ref_PVS_server) = T.make_pvs_server ~__context ~site:pvs_site () in Alcotest.check_raises "test_forget_running_proxy_and_server: should raise \ pvs_site_contains_running_proxies" Api_errors.( Server_error (pvs_site_contains_running_proxies, [Ref.string_of pvs_proxy]) ) (fun () -> Xapi_pvs_site.forget_internal ~__context ~self:pvs_site ~cleanup_storage ) let test = [ ("test_unlicensed", `Quick, test_unlicensed) ; ("test_introduce", `Quick, test_introduce) ; ("test_forget_ok", `Quick, test_forget_ok) ; ("test_forget_stopped_proxy", `Quick, test_forget_stopped_proxy) ; ("test_forget_running_proxy", `Quick, test_forget_running_proxy) ; ("test_forget_server", `Quick, test_forget_server) ; ( "test_forget_running_proxy_and_server" , `Quick , test_forget_running_proxy_and_server ) ]
2f34a417b7df08b6be2dd38af4bbda1ab3fa97c17f60410288961d2501cb213a
alt-romes/ghengin
Utils.hs
module Ghengin.Vulkan.Utils where import qualified FIR import qualified Vulkan as Vk stageFlag :: FIR.Shader -> Vk.ShaderStageFlagBits stageFlag FIR.VertexShader = Vk.SHADER_STAGE_VERTEX_BIT stageFlag FIR.TessellationControlShader = Vk.SHADER_STAGE_TESSELLATION_CONTROL_BIT stageFlag FIR.TessellationEvaluationShader = Vk.SHADER_STAGE_TESSELLATION_EVALUATION_BIT stageFlag FIR.GeometryShader = Vk.SHADER_STAGE_GEOMETRY_BIT stageFlag FIR.FragmentShader = Vk.SHADER_STAGE_FRAGMENT_BIT stageFlag FIR.ComputeShader = Vk.SHADER_STAGE_COMPUTE_BIT
null
https://raw.githubusercontent.com/alt-romes/ghengin/7d58fe3af2859f0a888158dba98e277b64c3d349/src/Ghengin/Vulkan/Utils.hs
haskell
module Ghengin.Vulkan.Utils where import qualified FIR import qualified Vulkan as Vk stageFlag :: FIR.Shader -> Vk.ShaderStageFlagBits stageFlag FIR.VertexShader = Vk.SHADER_STAGE_VERTEX_BIT stageFlag FIR.TessellationControlShader = Vk.SHADER_STAGE_TESSELLATION_CONTROL_BIT stageFlag FIR.TessellationEvaluationShader = Vk.SHADER_STAGE_TESSELLATION_EVALUATION_BIT stageFlag FIR.GeometryShader = Vk.SHADER_STAGE_GEOMETRY_BIT stageFlag FIR.FragmentShader = Vk.SHADER_STAGE_FRAGMENT_BIT stageFlag FIR.ComputeShader = Vk.SHADER_STAGE_COMPUTE_BIT
4c08cd7c893fa3c9fbe30b14b341286b100a0e15d256c51a363594d3c2a67561
CSVdB/pinky
LinearAlgebra.hs
module Pinky.Core.LinearAlgebra ( V , konstV , M , diag , (<#>) , (<#.>) , (<+>) , (<->) , Prod , Min , Plus , ElemProd , outerProd , transpose , vToM , mToV , mapV , mapMatrix , maxIndex , intToV , listToV , listToM , unsafeListToM , toDoubleList , unsafeFromDoubleList , unsafeFromTrippleList , resizeV , resizeM ) where import Pinky.Core.LinearAlgebra.Internal
null
https://raw.githubusercontent.com/CSVdB/pinky/e77a4c0812ceb4b8548c41a7652fb247c2ab39e0/pinky/src/Pinky/Core/LinearAlgebra.hs
haskell
module Pinky.Core.LinearAlgebra ( V , konstV , M , diag , (<#>) , (<#.>) , (<+>) , (<->) , Prod , Min , Plus , ElemProd , outerProd , transpose , vToM , mToV , mapV , mapMatrix , maxIndex , intToV , listToV , listToM , unsafeListToM , toDoubleList , unsafeFromDoubleList , unsafeFromTrippleList , resizeV , resizeM ) where import Pinky.Core.LinearAlgebra.Internal
34c9f5fee818e55520eea0d9ea844d78516fb80c4a7051ebed17da383c6abb66
mfoemmel/erlang-otp
user.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(user). -compile( [ inline, { inline_size, 100 } ] ). %% Basic standard i/o server for user interface port. -export([start/0, start/1, start_out/0]). -export([interfaces/1]). -define(NAME, user). %% Internal exports -export([server/1, server/2]). %% Defines for control ops -define(CTRL_OP_GET_WINSIZE,100). %% %% The basic server and start-up. %% start() -> start_port([eof,binary]). start([Mod,Fun|Args]) -> Mod , Fun , should return a pid . That process is supposed to act %% as the io port. Pid = apply(Mod, Fun, Args), % This better work! Id = spawn(?MODULE, server, [Pid]), register(?NAME, Id), Id. start_out() -> %% Output-only version of start/0 start_port([out,binary]). start_port(PortSettings) -> Id = spawn(?MODULE,server,[{fd,0,1},PortSettings]), register(?NAME,Id), Id. %% Return the pid of the shell process. %% Note: We can't ask the user process for this info since it %% may be busy waiting for data from the port. interfaces(User) -> case process_info(User, dictionary) of {dictionary,Dict} -> case lists:keysearch(shell, 1, Dict) of {value,Sh={shell,Shell}} when is_pid(Shell) -> [Sh]; _ -> [] end; _ -> [] end. server(Pid) when is_pid(Pid) -> process_flag(trap_exit, true), link(Pid), run(Pid). server(PortName,PortSettings) -> process_flag(trap_exit, true), Port = open_port(PortName,PortSettings), run(Port). run(P) -> put(read_mode,list), put(unicode,false), case init:get_argument(noshell) of non - empty list - > noshell {ok, [_|_]} -> put(shell, noshell), server_loop(P, queue:new()); _ -> group_leader(self(), self()), catch_loop(P, start_init_shell()) end. catch_loop(Port, Shell) -> catch_loop(Port, Shell, queue:new()). catch_loop(Port, Shell, Q) -> case catch server_loop(Port, Q) of new_shell -> exit(Shell, kill), catch_loop(Port, start_new_shell()); {unknown_exit,{Shell,Reason},_} -> % shell has exited case Reason of normal -> put_chars("*** ", Port, []); _ -> put_chars("*** ERROR: ", Port, []) end, put_chars("Shell process terminated! ***\n", Port, []), catch_loop(Port, start_new_shell()); {unknown_exit,_,Q1} -> catch_loop(Port, Shell, Q1); {'EXIT',R} -> exit(R) end. link_and_save_shell(Shell) -> link(Shell), put(shell, Shell), Shell. start_init_shell() -> link_and_save_shell(shell:start(init)). start_new_shell() -> link_and_save_shell(shell:start()). server_loop(Port, Q) -> receive {io_request,From,ReplyAs,Request} when is_pid(From) -> server_loop(Port, do_io_request(Request, From, ReplyAs, Port, Q)); {Port,{data,Bytes}} -> case get(shell) of noshell -> server_loop(Port, queue:snoc(Q, Bytes)); _ -> case contains_ctrl_g_or_ctrl_c(Bytes) of false -> server_loop(Port, queue:snoc(Q, Bytes)); _ -> throw(new_shell) end end; {Port, eof} -> put(eof, true), server_loop(Port, Q); %% Ignore messages from port here. {'EXIT',Port,badsig} -> % Ignore badsig errors server_loop(Port, Q); {'EXIT',Port,What} -> % Port has exited exit(What); %% Check if shell has exited {'EXIT',SomePid,What} -> case get(shell) of noshell -> server_loop(Port, Q); % Ignore _ -> throw({unknown_exit,{SomePid,What},Q}) end; _Other -> % Ignore other messages server_loop(Port, Q) end. get_fd_geometry(Port) -> case (catch port_control(Port,?CTRL_OP_GET_WINSIZE,[])) of List when is_list(List), length(List) =:= 8 -> <<W:32/native,H:32/native>> = list_to_binary(List), {W,H}; _ -> error end. NewSaveBuffer , FromPid , ReplyAs , Port , SaveBuffer ) do_io_request(Req, From, ReplyAs, Port, Q0) -> case io_request(Req, Port, Q0) of {_Status,Reply,Q1} -> io_reply(From, ReplyAs, Reply), Q1; {exit,What} -> send_port(Port, close), exit(What) end. New in R13B %% Encoding option (unicode/latin1) io_request({put_chars,unicode,Chars}, Port, Q) -> % Binary new in R9C put_chars(wrap_characters_to_binary(Chars,unicode, case get(unicode) of true -> unicode; _ -> latin1 end), Port, Q); io_request({put_chars,unicode,Mod,Func,Args}, Port, Q) -> Result = case catch apply(Mod,Func,Args) of Data when is_list(Data); is_binary(Data) -> wrap_characters_to_binary(Data,unicode, case get(unicode) of true -> unicode; _ -> latin1 end); Undef -> Undef end, put_chars(Result, Port, Q); io_request({put_chars,latin1,Chars}, Port, Q) -> % Binary new in R9C Data = case get(unicode) of true -> unicode:characters_to_binary(Chars,latin1,unicode); false -> erlang:iolist_to_binary(Chars) end, put_chars(Data, Port, Q); io_request({put_chars,latin1,Mod,Func,Args}, Port, Q) -> Result = case catch apply(Mod,Func,Args) of Data when is_list(Data); is_binary(Data) -> unicode:characters_to_binary(Data,latin1, case get(unicode) of true -> unicode; _ -> latin1 end); Undef -> Undef end, put_chars(Result, Port, Q); io_request({get_chars,Enc,Prompt,N}, Port, Q) -> % New in R9C get_chars(Prompt, io_lib, collect_chars, N, Port, Q, Enc); io_request({get_line,Enc,Prompt}, Port, Q) -> case get(read_mode) of binary -> get_line_bin(Prompt,Port,Q,Enc); _ -> get_chars(Prompt, io_lib, collect_line, [], Port, Q, Enc) end; io_request({get_until,Enc,Prompt,M,F,As}, Port, Q) -> get_chars(Prompt, io_lib, get_until, {M,F,As}, Port, Q, Enc); End New in R13B io_request(getopts, Port, Q) -> getopts(Port, Q); io_request({setopts,Opts}, Port, Q) when is_list(Opts) -> setopts(Opts, Port, Q); io_request({requests,Reqs}, Port, Q) -> io_requests(Reqs, {ok,ok,Q}, Port); %% New in R12 io_request({get_geometry,columns},Port,Q) -> case get_fd_geometry(Port) of {W,_H} -> {ok,W,Q}; _ -> {error,{error,enotsup},Q} end; io_request({get_geometry,rows},Port,Q) -> case get_fd_geometry(Port) of {_W,H} -> {ok,H,Q}; _ -> {error,{error,enotsup},Q} end; %% BC with pre-R13 nodes io_request({put_chars,Chars}, Port, Q) -> io_request({put_chars,latin1,Chars}, Port, Q); io_request({put_chars,Mod,Func,Args}, Port, Q) -> io_request({put_chars,latin1,Mod,Func,Args}, Port, Q); io_request({get_chars,Prompt,N}, Port, Q) -> io_request({get_chars,latin1,Prompt,N}, Port, Q); io_request({get_line,Prompt}, Port, Q) -> io_request({get_line,latin1,Prompt}, Port, Q); io_request({get_until,Prompt,M,F,As}, Port, Q) -> io_request({get_until,latin1,Prompt,M,F,As}, Port, Q); io_request(R, _Port, Q) -> %Unknown request {error,{error,{request,R}},Q}. %Ignore but give error (?) Status = io_requests(RequestList , PrevStat , Port ) %% Process a list of output requests as long as the previous status is 'ok'. io_requests([R|Rs], {ok,_Res,Q}, Port) -> io_requests(Rs, io_request(R, Port, Q), Port); io_requests([_|_], Error, _) -> Error; io_requests([], Stat, _) -> Stat. put_port(DeepList , Port ) %% Take a deep list of characters, flatten and output them to the %% port. put_port(List, Port) -> send_port(Port, {command, List}). %% send_port(Port, Command) send_port(Port, Command) -> Port ! {self(),Command}. io_reply(From , , Reply ) %% The function for sending i/o command acknowledgement. %% The ACK contains the return value. io_reply(From, ReplyAs, Reply) -> From ! {io_reply,ReplyAs,Reply}. %% put_chars put_chars(Chars, Port, Q) when is_binary(Chars) -> put_port(Chars, Port), {ok,ok,Q}; put_chars(Chars, Port, Q) -> case catch list_to_binary(Chars) of Binary when is_binary(Binary) -> put_chars(Binary, Port, Q); _ -> {error,{error,put_chars},Q} end. expand_encoding([]) -> []; expand_encoding([latin1 | T]) -> [{encoding,latin1} | expand_encoding(T)]; expand_encoding([unicode | T]) -> [{encoding,unicode} | expand_encoding(T)]; expand_encoding([H|T]) -> [H|expand_encoding(T)]. %% setopts setopts(Opts0,Port,Q) -> Opts = proplists:unfold( proplists:substitute_negations( [{list,binary}], expand_encoding(Opts0))), case check_valid_opts(Opts) of true -> do_setopts(Opts,Port,Q); false -> {error,{error,enotsup},Q} end. check_valid_opts([]) -> true; check_valid_opts([{binary,_}|T]) -> check_valid_opts(T); check_valid_opts([{encoding,Valid}|T]) when Valid =:= latin1; Valid =:= utf8; Valid =:= unicode -> check_valid_opts(T); check_valid_opts(_) -> false. do_setopts(Opts, _Port, Q) -> case proplists:get_value(encoding,Opts) of Valid when Valid =:= unicode; Valid =:= utf8 -> put(unicode,true); latin1 -> put(unicode,false); undefined -> ok end, case proplists:get_value(binary, Opts) of true -> put(read_mode,binary), {ok,ok,Q}; false -> put(read_mode,list), {ok,ok,Q}; _ -> {ok,ok,Q} end. getopts(_Port,Q) -> Bin = {binary, case get(read_mode) of binary -> true; _ -> false end}, Uni = {encoding, case get(unicode) of true -> unicode; _ -> latin1 end}, {ok,[Bin,Uni],Q}. get_line_bin(Prompt,Port,Q, Enc) -> prompt(Port, Prompt), case {get(eof),queue:is_empty(Q)} of {true,true} -> {ok,eof,Q}; _ -> get_line(Prompt,Port, Q, [], Enc) end. get_line(Prompt, Port, Q, Acc, Enc) -> case queue:is_empty(Q) of true -> receive {Port,{data,Bytes}} -> get_line_bytes(Prompt, Port, Q, Acc, Bytes, Enc); {Port, eof} -> put(eof, true), {ok, eof, []}; {io_request,From,ReplyAs,{get_geometry,_}=Req} when is_pid(From) -> do_io_request(Req, From, ReplyAs, Port, queue:new()), %% No prompt. get_line(Prompt, Port, Q, Acc, Enc); {io_request,From,ReplyAs,Request} when is_pid(From) -> do_io_request(Request, From, ReplyAs, Port, queue:new()), prompt(Port, Prompt), get_line(Prompt, Port, Q, Acc, Enc); {'EXIT',From,What} when node(From) =:= node() -> {exit,What} end; false -> get_line_doit(Prompt, Port, Q, Acc, Enc) end. get_line_bytes(Prompt, Port, Q, Acc, Bytes, Enc) -> case get(shell) of noshell -> get_line_doit(Prompt, Port, queue:snoc(Q, Bytes),Acc,Enc); _ -> case contains_ctrl_g_or_ctrl_c(Bytes) of false -> get_line_doit(Prompt, Port, queue:snoc(Q, Bytes), Acc, Enc); _ -> throw(new_shell) end end. is_cr_at(Pos,Bin) -> case Bin of <<_:Pos/binary,$\r,_/binary>> -> true; _ -> false end. srch(<<>>,_,_) -> nomatch; srch(<<X:8,_/binary>>,X,N) -> {match,[{N,1}]}; srch(<<_:8,T/binary>>,X,N) -> srch(T,X,N+1). get_line_doit(Prompt, Port, Q, Accu, Enc) -> case queue:is_empty(Q) of true -> case get(eof) of true -> case Accu of [] -> {ok,eof,Q}; _ -> {ok,binrev(Accu,[]),Q} end; _ -> get_line(Prompt, Port, Q, Accu, Enc) end; false -> Bin = queue:head(Q), case srch(Bin,$\n,0) of nomatch -> X = byte_size(Bin)-1, case is_cr_at(X,Bin) of true -> <<D:X/binary,_/binary>> = Bin, get_line_doit(Prompt, Port, queue:tail(Q), [<<$\r>>,D|Accu], Enc); false -> get_line_doit(Prompt, Port, queue:tail(Q), [Bin|Accu], Enc) end; {match,[{Pos,1}]} -> %% We are done PosPlus = Pos + 1, case Accu of [] -> {Head,Tail} = case is_cr_at(Pos - 1,Bin) of false -> <<H:PosPlus/binary, T/binary>> = Bin, {H,T}; true -> PosMinus = Pos - 1, <<H:PosMinus/binary, _,_,T/binary>> = Bin, {binrev([],[H,$\n]),T} end, case Tail of <<>> -> {ok, cast(Head,Enc), queue:tail(Q)}; _ -> {ok, cast(Head,Enc), queue:cons(Tail, queue:tail(Q))} end; [<<$\r>>|Stack1] when Pos =:= 0 -> <<_:PosPlus/binary,Tail/binary>> = Bin, case Tail of <<>> -> {ok, cast(binrev(Stack1, [$\n]),Enc), queue:tail(Q)}; _ -> {ok, cast(binrev(Stack1, [$\n]),Enc), queue:cons(Tail, queue:tail(Q))} end; _ -> {Head,Tail} = case is_cr_at(Pos - 1,Bin) of false -> <<H:PosPlus/binary, T/binary>> = Bin, {H,T}; true -> PosMinus = Pos - 1, <<H:PosMinus/binary, _,_,T/binary>> = Bin, {[H,$\n],T} end, case Tail of <<>> -> {ok, cast(binrev(Accu,[Head]),Enc), queue:tail(Q)}; _ -> {ok, cast(binrev(Accu,[Head]),Enc), queue:cons(Tail, queue:tail(Q))} end end end end. binrev(L, T) -> list_to_binary(lists:reverse(L, T)). is_cr_at(Pos , ) - > case of %% <<_:Pos/binary,$\r,_/binary>> -> %% true; %% _ -> %% false %% end. collect_line_bin_re(Bin,_Data , Stack , _ ) - > %% case re:run(Bin,<<"\n">>) of %% nomatch -> %% X = byte_size(Bin)-1, case is_cr_at(X , ) of %% true -> < < D :X / binary,_/binary > > = , %% [<<$\r>>,D|Stack]; %% false -> %% [Bin|Stack] %% end; %% {match,[{Pos,1}]} -> %% PosPlus = Pos + 1, case of %% [] -> case ) of %% false -> < < Head : PosPlus / binary , Tail / binary > > = , %% {stop, Head, Tail}; %% true -> %% PosMinus = Pos - 1, < < Head : PosMinus / binary,_,_,Tail / binary > > = , %% {stop, binrev([],[Head,$\n]),Tail} %% end; %% [<<$\r>>|Stack1] when Pos =:= 0 -> < < _ : PosPlus / binary , Tail / binary > > = , { stop , binrev(Stack1 , [ $ \n]),Tail } ; %% _ -> case ) of %% false -> < < Head : PosPlus / binary , Tail / binary > > = , %% {stop,binrev(Stack, [Head]),Tail}; %% true -> %% PosMinus = Pos - 1, < < Head : PosMinus / binary,_,_,Tail / binary > > = , %% {stop, binrev(Stack,[Head,$\n]),Tail} %% end %% end %% end. get_chars(Prompt , Module , Function , XtraArg , Port , Queue ) %% Gets characters from the input port until the applied function returns { stop , Result , RestBuf } . Does not block output until input %% has been received. %% Returns: { Status , Result , NewQueue } %% {exit,Reason} %% Entry function. get_chars(Prompt, M, F, Xa, Port, Q, Fmt) -> prompt(Port, Prompt), case {get(eof),queue:is_empty(Q)} of {true,true} -> {ok,eof,Q}; _ -> get_chars(Prompt, M, F, Xa, Port, Q, start, Fmt) end. First loop . Wait for port data . Respond to output requests . get_chars(Prompt, M, F, Xa, Port, Q, State, Fmt) -> case queue:is_empty(Q) of true -> receive {Port,{data,Bytes}} -> get_chars_bytes(State, M, F, Xa, Port, Q, Bytes, Fmt); {Port, eof} -> put(eof, true), {ok, eof, []}; { io_request , From , ReplyAs , Request } when is_pid(From ) - > get_chars_req(Prompt , M , F , Xa , Port , queue : new ( ) , State , Request , From , ) ; {io_request,From,ReplyAs,{get_geometry,_}=Req} when is_pid(From) -> do_io_request(Req, From, ReplyAs, Port, queue:new()), %Keep Q over this call %% No prompt. get_chars(Prompt, M, F, Xa, Port, Q, State, Fmt); {io_request,From,ReplyAs,Request} when is_pid(From) -> get_chars_req(Prompt, M, F, Xa, Port, Q, State, Request, From, ReplyAs, Fmt); {'EXIT',From,What} when node(From) =:= node() -> {exit,What} end; false -> get_chars_apply(State, M, F, Xa, Port, Q, Fmt) end. get_chars_req(Prompt, M, F, XtraArg, Port, Q, State, Req, From, ReplyAs, Fmt) -> do_io_request(Req, From, ReplyAs, Port, queue:new()), %Keep Q over this call prompt(Port, Prompt), get_chars(Prompt, M, F, XtraArg, Port, Q, State, Fmt). Second loop . Pass data to client as long as it wants more . %% A ^G in data interrupts loop if 'noshell' is not undefined. get_chars_bytes(State, M, F, Xa, Port, Q, Bytes, Fmt) -> case get(shell) of noshell -> get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, Bytes),Fmt); _ -> case contains_ctrl_g_or_ctrl_c(Bytes) of false -> get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, Bytes),Fmt); _ -> throw(new_shell) end end. get_chars_apply(State0, M, F, Xa, Port, Q, Fmt) -> case catch M:F(State0, cast(queue:head(Q),Fmt), Fmt, Xa) of {stop,Result,<<>>} -> {ok,Result,queue:tail(Q)}; {stop,Result,[]} -> {ok,Result,queue:tail(Q)}; {stop,Result,eof} -> {ok,Result,queue:tail(Q)}; {stop,Result,Buf} -> {ok,Result,queue:cons(Buf, queue:tail(Q))}; {'EXIT',_} -> {error,{error,err_func(M, F, Xa)},queue:new()}; State1 -> get_chars_more(State1, M, F, Xa, Port, queue:tail(Q), Fmt) end. get_chars_more(State, M, F, Xa, Port, Q, Fmt) -> case queue:is_empty(Q) of true -> case get(eof) of undefined -> receive {Port,{data,Bytes}} -> get_chars_bytes(State, M, F, Xa, Port, Q, Bytes, Fmt); {Port,eof} -> put(eof, true), get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, eof), Fmt); {'EXIT',From,What} when node(From) =:= node() -> {exit,What} end; _ -> get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, eof), Fmt) end; false -> get_chars_apply(State, M, F, Xa, Port, Q, Fmt) end. %% prompt(Port, Prompt) %% Print Prompt onto Port common case , reduces execution time by 20 % prompt(_Port, '') -> ok; prompt(Port, Prompt) -> put_port(io_lib:format_prompt(Prompt), Port). Convert error code to make it look as before err_func(io_lib, get_until, {_,F,_}) -> F; err_func(_, F, _) -> F. using regexp reduces execution time by > 50 % compared to old code running two regexps in sequence is much faster than \\x03|\\x07 contains_ctrl_g_or_ctrl_c(BinOrList)-> case {re:run(BinOrList, <<3>>),re:run(BinOrList, <<7>>)} of {nomatch, nomatch} -> false; _ -> true end. %% Convert a buffer between list and binary cast(Data, _Format) when is_atom(Data) -> Data; cast(Data, Format) -> cast(Data, get(read_mode), Format, get(unicode)). cast(B, binary, latin1, false) when is_binary(B) -> B; cast(B, binary, latin1, true) when is_binary(B) -> unicode:characters_to_binary(B, unicode, latin1); cast(L, binary, latin1, false) -> erlang:iolist_to_binary(L); cast(L, binary, latin1, true) -> case unicode:characters_to_binary( erlang:iolist_to_binary(L),unicode,latin1) of % may fail {error,_,_} -> exit({no_translation, unicode, latin1}); Else -> Else end; cast(B, binary, unicode, true) when is_binary(B) -> B; cast(B, binary, unicode, false) when is_binary(B) -> unicode:characters_to_binary(B,latin1,unicode); cast(L, binary, unicode, true) -> possibly a list containing UTF-8 encoded characters unicode:characters_to_binary(erlang:iolist_to_binary(L)); cast(L, binary, unicode, false) -> unicode:characters_to_binary(L, latin1, unicode); cast(L, list, latin1, UniTerm) -> case UniTerm of true -> % Convert input characters to protocol format (i.e latin1) case unicode:characters_to_list( erlang:iolist_to_binary(L),unicode) of % may fail {error,_,_} -> exit({no_translation, unicode, latin1}); Else -> [ case X of High when High > 255 -> exit({no_translation, unicode, latin1}); Low -> Low end || X <- Else ] end; _ -> binary_to_list(erlang:iolist_to_binary(L)) end; cast(L, list, unicode, UniTerm) -> unicode:characters_to_list(erlang:iolist_to_binary(L), case UniTerm of true -> unicode; _ -> latin1 end); cast(Other, _, _,_) -> Other. wrap_characters_to_binary(Chars,unicode,latin1) -> case unicode:characters_to_binary(Chars,unicode,latin1) of {error,_,_} -> list_to_binary( [ case X of High when High > 255 -> ["\\x{",erlang:integer_to_list(X, 16),$}]; Low -> Low end || X <- unicode:characters_to_list(Chars,unicode) ]); Bin -> Bin end; wrap_characters_to_binary(Bin,From,From) when is_binary(Bin) -> Bin; wrap_characters_to_binary(Chars,From,To) -> unicode:characters_to_binary(Chars,From,To).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/kernel/src/user.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% Basic standard i/o server for user interface port. Internal exports Defines for control ops The basic server and start-up. as the io port. This better work! Output-only version of start/0 Return the pid of the shell process. Note: We can't ask the user process for this info since it may be busy waiting for data from the port. shell has exited Ignore messages from port here. Ignore badsig errors Port has exited Check if shell has exited Ignore Ignore other messages Encoding option (unicode/latin1) Binary new in R9C Binary new in R9C New in R9C New in R12 BC with pre-R13 nodes Unknown request Ignore but give error (?) Process a list of output requests as long as the previous status is 'ok'. Take a deep list of characters, flatten and output them to the port. send_port(Port, Command) The function for sending i/o command acknowledgement. The ACK contains the return value. put_chars setopts No prompt. We are done <<_:Pos/binary,$\r,_/binary>> -> true; _ -> false end. case re:run(Bin,<<"\n">>) of nomatch -> X = byte_size(Bin)-1, true -> [<<$\r>>,D|Stack]; false -> [Bin|Stack] end; {match,[{Pos,1}]} -> PosPlus = Pos + 1, [] -> false -> {stop, Head, Tail}; true -> PosMinus = Pos - 1, {stop, binrev([],[Head,$\n]),Tail} end; [<<$\r>>|Stack1] when Pos =:= 0 -> _ -> false -> {stop,binrev(Stack, [Head]),Tail}; true -> PosMinus = Pos - 1, {stop, binrev(Stack,[Head,$\n]),Tail} end end end. Gets characters from the input port until the applied function has been received. Returns: {exit,Reason} Entry function. Keep Q over this call No prompt. Keep Q over this call A ^G in data interrupts loop if 'noshell' is not undefined. prompt(Port, Prompt) Print Prompt onto Port compared to old code Convert a buffer between list and binary may fail Convert input characters to protocol format (i.e latin1) may fail
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(user). -compile( [ inline, { inline_size, 100 } ] ). -export([start/0, start/1, start_out/0]). -export([interfaces/1]). -define(NAME, user). -export([server/1, server/2]). -define(CTRL_OP_GET_WINSIZE,100). start() -> start_port([eof,binary]). start([Mod,Fun|Args]) -> Mod , Fun , should return a pid . That process is supposed to act Id = spawn(?MODULE, server, [Pid]), register(?NAME, Id), Id. start_out() -> start_port([out,binary]). start_port(PortSettings) -> Id = spawn(?MODULE,server,[{fd,0,1},PortSettings]), register(?NAME,Id), Id. interfaces(User) -> case process_info(User, dictionary) of {dictionary,Dict} -> case lists:keysearch(shell, 1, Dict) of {value,Sh={shell,Shell}} when is_pid(Shell) -> [Sh]; _ -> [] end; _ -> [] end. server(Pid) when is_pid(Pid) -> process_flag(trap_exit, true), link(Pid), run(Pid). server(PortName,PortSettings) -> process_flag(trap_exit, true), Port = open_port(PortName,PortSettings), run(Port). run(P) -> put(read_mode,list), put(unicode,false), case init:get_argument(noshell) of non - empty list - > noshell {ok, [_|_]} -> put(shell, noshell), server_loop(P, queue:new()); _ -> group_leader(self(), self()), catch_loop(P, start_init_shell()) end. catch_loop(Port, Shell) -> catch_loop(Port, Shell, queue:new()). catch_loop(Port, Shell, Q) -> case catch server_loop(Port, Q) of new_shell -> exit(Shell, kill), catch_loop(Port, start_new_shell()); case Reason of normal -> put_chars("*** ", Port, []); _ -> put_chars("*** ERROR: ", Port, []) end, put_chars("Shell process terminated! ***\n", Port, []), catch_loop(Port, start_new_shell()); {unknown_exit,_,Q1} -> catch_loop(Port, Shell, Q1); {'EXIT',R} -> exit(R) end. link_and_save_shell(Shell) -> link(Shell), put(shell, Shell), Shell. start_init_shell() -> link_and_save_shell(shell:start(init)). start_new_shell() -> link_and_save_shell(shell:start()). server_loop(Port, Q) -> receive {io_request,From,ReplyAs,Request} when is_pid(From) -> server_loop(Port, do_io_request(Request, From, ReplyAs, Port, Q)); {Port,{data,Bytes}} -> case get(shell) of noshell -> server_loop(Port, queue:snoc(Q, Bytes)); _ -> case contains_ctrl_g_or_ctrl_c(Bytes) of false -> server_loop(Port, queue:snoc(Q, Bytes)); _ -> throw(new_shell) end end; {Port, eof} -> put(eof, true), server_loop(Port, Q); server_loop(Port, Q); exit(What); {'EXIT',SomePid,What} -> case get(shell) of noshell -> _ -> throw({unknown_exit,{SomePid,What},Q}) end; server_loop(Port, Q) end. get_fd_geometry(Port) -> case (catch port_control(Port,?CTRL_OP_GET_WINSIZE,[])) of List when is_list(List), length(List) =:= 8 -> <<W:32/native,H:32/native>> = list_to_binary(List), {W,H}; _ -> error end. NewSaveBuffer , FromPid , ReplyAs , Port , SaveBuffer ) do_io_request(Req, From, ReplyAs, Port, Q0) -> case io_request(Req, Port, Q0) of {_Status,Reply,Q1} -> io_reply(From, ReplyAs, Reply), Q1; {exit,What} -> send_port(Port, close), exit(What) end. New in R13B put_chars(wrap_characters_to_binary(Chars,unicode, case get(unicode) of true -> unicode; _ -> latin1 end), Port, Q); io_request({put_chars,unicode,Mod,Func,Args}, Port, Q) -> Result = case catch apply(Mod,Func,Args) of Data when is_list(Data); is_binary(Data) -> wrap_characters_to_binary(Data,unicode, case get(unicode) of true -> unicode; _ -> latin1 end); Undef -> Undef end, put_chars(Result, Port, Q); Data = case get(unicode) of true -> unicode:characters_to_binary(Chars,latin1,unicode); false -> erlang:iolist_to_binary(Chars) end, put_chars(Data, Port, Q); io_request({put_chars,latin1,Mod,Func,Args}, Port, Q) -> Result = case catch apply(Mod,Func,Args) of Data when is_list(Data); is_binary(Data) -> unicode:characters_to_binary(Data,latin1, case get(unicode) of true -> unicode; _ -> latin1 end); Undef -> Undef end, put_chars(Result, Port, Q); get_chars(Prompt, io_lib, collect_chars, N, Port, Q, Enc); io_request({get_line,Enc,Prompt}, Port, Q) -> case get(read_mode) of binary -> get_line_bin(Prompt,Port,Q,Enc); _ -> get_chars(Prompt, io_lib, collect_line, [], Port, Q, Enc) end; io_request({get_until,Enc,Prompt,M,F,As}, Port, Q) -> get_chars(Prompt, io_lib, get_until, {M,F,As}, Port, Q, Enc); End New in R13B io_request(getopts, Port, Q) -> getopts(Port, Q); io_request({setopts,Opts}, Port, Q) when is_list(Opts) -> setopts(Opts, Port, Q); io_request({requests,Reqs}, Port, Q) -> io_requests(Reqs, {ok,ok,Q}, Port); io_request({get_geometry,columns},Port,Q) -> case get_fd_geometry(Port) of {W,_H} -> {ok,W,Q}; _ -> {error,{error,enotsup},Q} end; io_request({get_geometry,rows},Port,Q) -> case get_fd_geometry(Port) of {_W,H} -> {ok,H,Q}; _ -> {error,{error,enotsup},Q} end; io_request({put_chars,Chars}, Port, Q) -> io_request({put_chars,latin1,Chars}, Port, Q); io_request({put_chars,Mod,Func,Args}, Port, Q) -> io_request({put_chars,latin1,Mod,Func,Args}, Port, Q); io_request({get_chars,Prompt,N}, Port, Q) -> io_request({get_chars,latin1,Prompt,N}, Port, Q); io_request({get_line,Prompt}, Port, Q) -> io_request({get_line,latin1,Prompt}, Port, Q); io_request({get_until,Prompt,M,F,As}, Port, Q) -> io_request({get_until,latin1,Prompt,M,F,As}, Port, Q); Status = io_requests(RequestList , PrevStat , Port ) io_requests([R|Rs], {ok,_Res,Q}, Port) -> io_requests(Rs, io_request(R, Port, Q), Port); io_requests([_|_], Error, _) -> Error; io_requests([], Stat, _) -> Stat. put_port(DeepList , Port ) put_port(List, Port) -> send_port(Port, {command, List}). send_port(Port, Command) -> Port ! {self(),Command}. io_reply(From , , Reply ) io_reply(From, ReplyAs, Reply) -> From ! {io_reply,ReplyAs,Reply}. put_chars(Chars, Port, Q) when is_binary(Chars) -> put_port(Chars, Port), {ok,ok,Q}; put_chars(Chars, Port, Q) -> case catch list_to_binary(Chars) of Binary when is_binary(Binary) -> put_chars(Binary, Port, Q); _ -> {error,{error,put_chars},Q} end. expand_encoding([]) -> []; expand_encoding([latin1 | T]) -> [{encoding,latin1} | expand_encoding(T)]; expand_encoding([unicode | T]) -> [{encoding,unicode} | expand_encoding(T)]; expand_encoding([H|T]) -> [H|expand_encoding(T)]. setopts(Opts0,Port,Q) -> Opts = proplists:unfold( proplists:substitute_negations( [{list,binary}], expand_encoding(Opts0))), case check_valid_opts(Opts) of true -> do_setopts(Opts,Port,Q); false -> {error,{error,enotsup},Q} end. check_valid_opts([]) -> true; check_valid_opts([{binary,_}|T]) -> check_valid_opts(T); check_valid_opts([{encoding,Valid}|T]) when Valid =:= latin1; Valid =:= utf8; Valid =:= unicode -> check_valid_opts(T); check_valid_opts(_) -> false. do_setopts(Opts, _Port, Q) -> case proplists:get_value(encoding,Opts) of Valid when Valid =:= unicode; Valid =:= utf8 -> put(unicode,true); latin1 -> put(unicode,false); undefined -> ok end, case proplists:get_value(binary, Opts) of true -> put(read_mode,binary), {ok,ok,Q}; false -> put(read_mode,list), {ok,ok,Q}; _ -> {ok,ok,Q} end. getopts(_Port,Q) -> Bin = {binary, case get(read_mode) of binary -> true; _ -> false end}, Uni = {encoding, case get(unicode) of true -> unicode; _ -> latin1 end}, {ok,[Bin,Uni],Q}. get_line_bin(Prompt,Port,Q, Enc) -> prompt(Port, Prompt), case {get(eof),queue:is_empty(Q)} of {true,true} -> {ok,eof,Q}; _ -> get_line(Prompt,Port, Q, [], Enc) end. get_line(Prompt, Port, Q, Acc, Enc) -> case queue:is_empty(Q) of true -> receive {Port,{data,Bytes}} -> get_line_bytes(Prompt, Port, Q, Acc, Bytes, Enc); {Port, eof} -> put(eof, true), {ok, eof, []}; {io_request,From,ReplyAs,{get_geometry,_}=Req} when is_pid(From) -> do_io_request(Req, From, ReplyAs, Port, queue:new()), get_line(Prompt, Port, Q, Acc, Enc); {io_request,From,ReplyAs,Request} when is_pid(From) -> do_io_request(Request, From, ReplyAs, Port, queue:new()), prompt(Port, Prompt), get_line(Prompt, Port, Q, Acc, Enc); {'EXIT',From,What} when node(From) =:= node() -> {exit,What} end; false -> get_line_doit(Prompt, Port, Q, Acc, Enc) end. get_line_bytes(Prompt, Port, Q, Acc, Bytes, Enc) -> case get(shell) of noshell -> get_line_doit(Prompt, Port, queue:snoc(Q, Bytes),Acc,Enc); _ -> case contains_ctrl_g_or_ctrl_c(Bytes) of false -> get_line_doit(Prompt, Port, queue:snoc(Q, Bytes), Acc, Enc); _ -> throw(new_shell) end end. is_cr_at(Pos,Bin) -> case Bin of <<_:Pos/binary,$\r,_/binary>> -> true; _ -> false end. srch(<<>>,_,_) -> nomatch; srch(<<X:8,_/binary>>,X,N) -> {match,[{N,1}]}; srch(<<_:8,T/binary>>,X,N) -> srch(T,X,N+1). get_line_doit(Prompt, Port, Q, Accu, Enc) -> case queue:is_empty(Q) of true -> case get(eof) of true -> case Accu of [] -> {ok,eof,Q}; _ -> {ok,binrev(Accu,[]),Q} end; _ -> get_line(Prompt, Port, Q, Accu, Enc) end; false -> Bin = queue:head(Q), case srch(Bin,$\n,0) of nomatch -> X = byte_size(Bin)-1, case is_cr_at(X,Bin) of true -> <<D:X/binary,_/binary>> = Bin, get_line_doit(Prompt, Port, queue:tail(Q), [<<$\r>>,D|Accu], Enc); false -> get_line_doit(Prompt, Port, queue:tail(Q), [Bin|Accu], Enc) end; {match,[{Pos,1}]} -> PosPlus = Pos + 1, case Accu of [] -> {Head,Tail} = case is_cr_at(Pos - 1,Bin) of false -> <<H:PosPlus/binary, T/binary>> = Bin, {H,T}; true -> PosMinus = Pos - 1, <<H:PosMinus/binary, _,_,T/binary>> = Bin, {binrev([],[H,$\n]),T} end, case Tail of <<>> -> {ok, cast(Head,Enc), queue:tail(Q)}; _ -> {ok, cast(Head,Enc), queue:cons(Tail, queue:tail(Q))} end; [<<$\r>>|Stack1] when Pos =:= 0 -> <<_:PosPlus/binary,Tail/binary>> = Bin, case Tail of <<>> -> {ok, cast(binrev(Stack1, [$\n]),Enc), queue:tail(Q)}; _ -> {ok, cast(binrev(Stack1, [$\n]),Enc), queue:cons(Tail, queue:tail(Q))} end; _ -> {Head,Tail} = case is_cr_at(Pos - 1,Bin) of false -> <<H:PosPlus/binary, T/binary>> = Bin, {H,T}; true -> PosMinus = Pos - 1, <<H:PosMinus/binary, _,_,T/binary>> = Bin, {[H,$\n],T} end, case Tail of <<>> -> {ok, cast(binrev(Accu,[Head]),Enc), queue:tail(Q)}; _ -> {ok, cast(binrev(Accu,[Head]),Enc), queue:cons(Tail, queue:tail(Q))} end end end end. binrev(L, T) -> list_to_binary(lists:reverse(L, T)). is_cr_at(Pos , ) - > case of collect_line_bin_re(Bin,_Data , Stack , _ ) - > case is_cr_at(X , ) of < < D :X / binary,_/binary > > = , case of case ) of < < Head : PosPlus / binary , Tail / binary > > = , < < Head : PosMinus / binary,_,_,Tail / binary > > = , < < _ : PosPlus / binary , Tail / binary > > = , { stop , binrev(Stack1 , [ $ \n]),Tail } ; case ) of < < Head : PosPlus / binary , Tail / binary > > = , < < Head : PosMinus / binary,_,_,Tail / binary > > = , get_chars(Prompt , Module , Function , XtraArg , Port , Queue ) returns { stop , Result , RestBuf } . Does not block output until input { Status , Result , NewQueue } get_chars(Prompt, M, F, Xa, Port, Q, Fmt) -> prompt(Port, Prompt), case {get(eof),queue:is_empty(Q)} of {true,true} -> {ok,eof,Q}; _ -> get_chars(Prompt, M, F, Xa, Port, Q, start, Fmt) end. First loop . Wait for port data . Respond to output requests . get_chars(Prompt, M, F, Xa, Port, Q, State, Fmt) -> case queue:is_empty(Q) of true -> receive {Port,{data,Bytes}} -> get_chars_bytes(State, M, F, Xa, Port, Q, Bytes, Fmt); {Port, eof} -> put(eof, true), {ok, eof, []}; { io_request , From , ReplyAs , Request } when is_pid(From ) - > get_chars_req(Prompt , M , F , Xa , Port , queue : new ( ) , State , Request , From , ) ; {io_request,From,ReplyAs,{get_geometry,_}=Req} when is_pid(From) -> do_io_request(Req, From, ReplyAs, Port, get_chars(Prompt, M, F, Xa, Port, Q, State, Fmt); {io_request,From,ReplyAs,Request} when is_pid(From) -> get_chars_req(Prompt, M, F, Xa, Port, Q, State, Request, From, ReplyAs, Fmt); {'EXIT',From,What} when node(From) =:= node() -> {exit,What} end; false -> get_chars_apply(State, M, F, Xa, Port, Q, Fmt) end. get_chars_req(Prompt, M, F, XtraArg, Port, Q, State, Req, From, ReplyAs, Fmt) -> prompt(Port, Prompt), get_chars(Prompt, M, F, XtraArg, Port, Q, State, Fmt). Second loop . Pass data to client as long as it wants more . get_chars_bytes(State, M, F, Xa, Port, Q, Bytes, Fmt) -> case get(shell) of noshell -> get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, Bytes),Fmt); _ -> case contains_ctrl_g_or_ctrl_c(Bytes) of false -> get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, Bytes),Fmt); _ -> throw(new_shell) end end. get_chars_apply(State0, M, F, Xa, Port, Q, Fmt) -> case catch M:F(State0, cast(queue:head(Q),Fmt), Fmt, Xa) of {stop,Result,<<>>} -> {ok,Result,queue:tail(Q)}; {stop,Result,[]} -> {ok,Result,queue:tail(Q)}; {stop,Result,eof} -> {ok,Result,queue:tail(Q)}; {stop,Result,Buf} -> {ok,Result,queue:cons(Buf, queue:tail(Q))}; {'EXIT',_} -> {error,{error,err_func(M, F, Xa)},queue:new()}; State1 -> get_chars_more(State1, M, F, Xa, Port, queue:tail(Q), Fmt) end. get_chars_more(State, M, F, Xa, Port, Q, Fmt) -> case queue:is_empty(Q) of true -> case get(eof) of undefined -> receive {Port,{data,Bytes}} -> get_chars_bytes(State, M, F, Xa, Port, Q, Bytes, Fmt); {Port,eof} -> put(eof, true), get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, eof), Fmt); {'EXIT',From,What} when node(From) =:= node() -> {exit,What} end; _ -> get_chars_apply(State, M, F, Xa, Port, queue:snoc(Q, eof), Fmt) end; false -> get_chars_apply(State, M, F, Xa, Port, Q, Fmt) end. prompt(_Port, '') -> ok; prompt(Port, Prompt) -> put_port(io_lib:format_prompt(Prompt), Port). Convert error code to make it look as before err_func(io_lib, get_until, {_,F,_}) -> F; err_func(_, F, _) -> F. running two regexps in sequence is much faster than \\x03|\\x07 contains_ctrl_g_or_ctrl_c(BinOrList)-> case {re:run(BinOrList, <<3>>),re:run(BinOrList, <<7>>)} of {nomatch, nomatch} -> false; _ -> true end. cast(Data, _Format) when is_atom(Data) -> Data; cast(Data, Format) -> cast(Data, get(read_mode), Format, get(unicode)). cast(B, binary, latin1, false) when is_binary(B) -> B; cast(B, binary, latin1, true) when is_binary(B) -> unicode:characters_to_binary(B, unicode, latin1); cast(L, binary, latin1, false) -> erlang:iolist_to_binary(L); cast(L, binary, latin1, true) -> case unicode:characters_to_binary( {error,_,_} -> exit({no_translation, unicode, latin1}); Else -> Else end; cast(B, binary, unicode, true) when is_binary(B) -> B; cast(B, binary, unicode, false) when is_binary(B) -> unicode:characters_to_binary(B,latin1,unicode); cast(L, binary, unicode, true) -> possibly a list containing UTF-8 encoded characters unicode:characters_to_binary(erlang:iolist_to_binary(L)); cast(L, binary, unicode, false) -> unicode:characters_to_binary(L, latin1, unicode); cast(L, list, latin1, UniTerm) -> case UniTerm of case unicode:characters_to_list( {error,_,_} -> exit({no_translation, unicode, latin1}); Else -> [ case X of High when High > 255 -> exit({no_translation, unicode, latin1}); Low -> Low end || X <- Else ] end; _ -> binary_to_list(erlang:iolist_to_binary(L)) end; cast(L, list, unicode, UniTerm) -> unicode:characters_to_list(erlang:iolist_to_binary(L), case UniTerm of true -> unicode; _ -> latin1 end); cast(Other, _, _,_) -> Other. wrap_characters_to_binary(Chars,unicode,latin1) -> case unicode:characters_to_binary(Chars,unicode,latin1) of {error,_,_} -> list_to_binary( [ case X of High when High > 255 -> ["\\x{",erlang:integer_to_list(X, 16),$}]; Low -> Low end || X <- unicode:characters_to_list(Chars,unicode) ]); Bin -> Bin end; wrap_characters_to_binary(Bin,From,From) when is_binary(Bin) -> Bin; wrap_characters_to_binary(Chars,From,To) -> unicode:characters_to_binary(Chars,From,To).
bc4579659f8f3a270bdfee9f6ad2bcf19f74efa69c399e0c4d6a4a853698ebc0
plumatic/grab-bag
fetched_page.clj
(ns domain.docs.fetched-page (:use plumbing.core) (:require [schema.core :as s])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Schemas and Constructors (s/defschema FetchedPage {:url (s/named String "canonical first casing of url that is observed") :resolved (s/named String "resolved version of url that comes from response") :fetch-date Long :html String s/Keyword s/Any}) (s/defn ^:always-validate fetched-page :- FetchedPage [url resolved fetch-date html] {:url url :resolved resolved :fetch-date fetch-date :html html})
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/domain/src/domain/docs/fetched_page.clj
clojure
(ns domain.docs.fetched-page (:use plumbing.core) (:require [schema.core :as s])) Schemas and Constructors (s/defschema FetchedPage {:url (s/named String "canonical first casing of url that is observed") :resolved (s/named String "resolved version of url that comes from response") :fetch-date Long :html String s/Keyword s/Any}) (s/defn ^:always-validate fetched-page :- FetchedPage [url resolved fetch-date html] {:url url :resolved resolved :fetch-date fetch-date :html html})
a8df41ccc0291e270b329d18e6251f434177ee0325f2d3f2bd5649170ddf681c
finnishtransportagency/harja
talvihoidon_hoitoluokat.clj
(ns harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.talvihoidon-hoitoluokat (:require [taoensso.timbre :as log] [clojure.java.jdbc :as jdbc] [harja.kyselyt.hoitoluokat :as hoitoluokat] [harja.domain.hoitoluokat :as domain] [harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.shapefile :as shapefile])) (defn vie-hoitoluokka-entry [db talvihoito] (if (:the_geom talvihoito) (hoitoluokat/vie-hoitoluokkatauluun! db (:alkusijain talvihoito) ;; tienumero (:alkusijai0 talvihoito) ;; aosa (:alkusijai1 talvihoito) ;; aet (:loppusija0 talvihoito) ;; losa (:loppusija1 talvihoito) ;; let hoitoluokka (.toString (:the_geom talvihoito)) "talvihoito") (log/warn "Talvihoitoluokkaa ei voida tuoda ilman geometriaa."))) (defn vie-hoitoluokat-kantaan [db shapefile] (if shapefile (do (log/debug (str "Tuodaan talvihoitoluokkatietoja kantaan tiedostosta " shapefile)) (jdbc/with-db-transaction [db db] (hoitoluokat/tuhoa-hoitoluokkadata! db "talvihoito") (doseq [soratie (shapefile/tuo shapefile)] (vie-hoitoluokka-entry db soratie)) (when (= 0 (:lkm (first (hoitoluokat/tarkista-hoitoluokkadata db "talvihoito")))) (throw (Exception. "Yhtään talvihoitoluokkageometriaa ei viety kantaan. Tarkista aineiston yhteensopivuus sisäänlukevan kooditoteutuksen kanssa."))))) (throw (Exception. (format "Talvihoitoluokkatietojen geometrioiden tiedostopolkua % ei löydy konfiguraatiosta. Tuontia ei suoriteta." shapefile)))))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/2f6ad1bbabd403bd8c7e553e2b0950e52c3968a6/src/clj/harja/palvelin/integraatiot/paikkatietojarjestelma/tuonnit/talvihoidon_hoitoluokat.clj
clojure
tienumero aosa aet losa let
(ns harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.talvihoidon-hoitoluokat (:require [taoensso.timbre :as log] [clojure.java.jdbc :as jdbc] [harja.kyselyt.hoitoluokat :as hoitoluokat] [harja.domain.hoitoluokat :as domain] [harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.shapefile :as shapefile])) (defn vie-hoitoluokka-entry [db talvihoito] (if (:the_geom talvihoito) (hoitoluokat/vie-hoitoluokkatauluun! db hoitoluokka (.toString (:the_geom talvihoito)) "talvihoito") (log/warn "Talvihoitoluokkaa ei voida tuoda ilman geometriaa."))) (defn vie-hoitoluokat-kantaan [db shapefile] (if shapefile (do (log/debug (str "Tuodaan talvihoitoluokkatietoja kantaan tiedostosta " shapefile)) (jdbc/with-db-transaction [db db] (hoitoluokat/tuhoa-hoitoluokkadata! db "talvihoito") (doseq [soratie (shapefile/tuo shapefile)] (vie-hoitoluokka-entry db soratie)) (when (= 0 (:lkm (first (hoitoluokat/tarkista-hoitoluokkadata db "talvihoito")))) (throw (Exception. "Yhtään talvihoitoluokkageometriaa ei viety kantaan. Tarkista aineiston yhteensopivuus sisäänlukevan kooditoteutuksen kanssa."))))) (throw (Exception. (format "Talvihoitoluokkatietojen geometrioiden tiedostopolkua % ei löydy konfiguraatiosta. Tuontia ei suoriteta." shapefile)))))
46ae060597f03eb925c893ad9af23ebfbecc7e550e1057895c5bc8a0dc101845
NetComposer/nksip
fork_test_server2.erl
%% ------------------------------------------------------------------- %% fork_test : %% Copyright ( c ) 2013 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(fork_test_server2). -include_lib("nkserver/include/nkserver_module.hrl"). -export([srv_init/2, sip_route/5]). srv_init(_Package, State) -> ok = nkserver:put(?MODULE, domains, [<<"nksip">>, <<"127.0.0.1">>, <<"[::1]">>]), {ok, State}. sip_route(_Scheme, _User, Domain, _Req, _Call) -> % Route for the rest of servers in fork test % Adds x-nk-id header. serverA is stateless, rest are stateful % Always Record-Route % If domain is "nksip" routes to fork_test_serverR Opts = [record_route, {insert, "x-nk-id", ?MODULE}], Domains = nkserver:get(?MODULE, domains), case lists:member(Domain, Domains) of true when Domain==<<"nksip">> -> {proxy, ruri, [{route, "<sip:127.0.0.1;lr>"}|Opts]}; true -> {proxy, ruri, Opts}; false -> {reply, forbidden} end.
null
https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/test/callbacks/fork_test_server2.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- Route for the rest of servers in fork test Adds x-nk-id header. serverA is stateless, rest are stateful Always Record-Route If domain is "nksip" routes to fork_test_serverR
fork_test : Copyright ( c ) 2013 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(fork_test_server2). -include_lib("nkserver/include/nkserver_module.hrl"). -export([srv_init/2, sip_route/5]). srv_init(_Package, State) -> ok = nkserver:put(?MODULE, domains, [<<"nksip">>, <<"127.0.0.1">>, <<"[::1]">>]), {ok, State}. sip_route(_Scheme, _User, Domain, _Req, _Call) -> Opts = [record_route, {insert, "x-nk-id", ?MODULE}], Domains = nkserver:get(?MODULE, domains), case lists:member(Domain, Domains) of true when Domain==<<"nksip">> -> {proxy, ruri, [{route, "<sip:127.0.0.1;lr>"}|Opts]}; true -> {proxy, ruri, Opts}; false -> {reply, forbidden} end.
fa676ca5f1c8037f0a3690c51de30806ca96d82c9763c9a46c3db6883671c2ef
tommaisey/aeon
mk.scm
(mk-r6rs '(rsc3) (cons "../src/sys.guile.scm" rsc3-src) (string-append (list-ref (command-line) 1) "/rsc3.guile.sls") rsc3-dep '() '()) (mk-r6rs '(rsc3) (cons "../src/sys.plt.scm" rsc3-src) (string-append (list-ref (command-line) 1) "/rsc3.mzscheme.sls") (cons '(prefix (scheme) plt:) rsc3-dep) '() '())
null
https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/src/ext/mk.scm
scheme
(mk-r6rs '(rsc3) (cons "../src/sys.guile.scm" rsc3-src) (string-append (list-ref (command-line) 1) "/rsc3.guile.sls") rsc3-dep '() '()) (mk-r6rs '(rsc3) (cons "../src/sys.plt.scm" rsc3-src) (string-append (list-ref (command-line) 1) "/rsc3.mzscheme.sls") (cons '(prefix (scheme) plt:) rsc3-dep) '() '())
0db89f9675a7968d998c593ae2e84225850562fb181e0abea94d032fb1738412
heyarne/airsonic-ui
events.cljs
(ns bulma.modal.events (:require [re-frame.core :as rf])) (defn show-modal [db [_ modal-id]] (assoc-in db [:bulma :visible-modal] modal-id)) (rf/reg-event-db ::show show-modal) (defn hide-modal [db _] (update db :bulma dissoc :visible-modal)) (rf/reg-event-db ::hide hide-modal) (defn toggle-modal [db [_ modal-id]] (let [visible-modal (get-in db [:bulma :visible-modal])] (if (= visible-modal modal-id) (hide-modal db [::hide]) (show-modal db [::show modal-id])))) (rf/reg-event-db ::toggle toggle-modal)
null
https://raw.githubusercontent.com/heyarne/airsonic-ui/7adb03d6e2ba0ff764796a57b7e87f62b242c9b7/src/cljs/bulma/modal/events.cljs
clojure
(ns bulma.modal.events (:require [re-frame.core :as rf])) (defn show-modal [db [_ modal-id]] (assoc-in db [:bulma :visible-modal] modal-id)) (rf/reg-event-db ::show show-modal) (defn hide-modal [db _] (update db :bulma dissoc :visible-modal)) (rf/reg-event-db ::hide hide-modal) (defn toggle-modal [db [_ modal-id]] (let [visible-modal (get-in db [:bulma :visible-modal])] (if (= visible-modal modal-id) (hide-modal db [::hide]) (show-modal db [::show modal-id])))) (rf/reg-event-db ::toggle toggle-modal)
028927cd81d352d8d0e7f50c062fa439f4d83a4d8300a68fe73137381bf41787
bgamari/the-thoralf-plugin
Nat.hs
{-# LANGUAGE TypeInType #-} {-# LANGUAGE GADTs #-} # LANGUAGE TypeOperators # # LANGUAGE StandaloneDeriving # # LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fplugin ThoralfPlugin.Plugin #-} module Nat where import ThoralfPlugin.Theory.Bool import Data.Type.Equality import Data.Kind import GHC.TypeLits test1 :: 1 :~: 1 test1 = Refl test2 :: (a + 1) :~: (1 + a) test2 = Refl test3 :: (a + b) :~: (b + a) test3 = Refl : : ( a + b ) : ~ : b test3Bad = Refl NOTE : Expected failure for . • Could n't match type ‘ b ’ with ‘ a + b ’ ‘ b ’ is a rigid type variable bound by the type signature for : : : forall ( a : : ) ( b : : ) . ( a + b ) : ~ : b Expected type : ( a + b ) : ~ : b Actual type : b : ~ : b • In the expression : In an equation for ‘ ’ : test3Bad = Refl • Relevant bindings include : : ( a + b ) : ~ : b test3Bad :: (a + b) :~: b test3Bad = Refl NOTE: Expected failure for test3Bad. • Couldn't match type ‘b’ with ‘a + b’ ‘b’ is a rigid type variable bound by the type signature for: test3Bad :: forall (a :: Nat) (b :: Nat). (a + b) :~: b Expected type: (a + b) :~: b Actual type: b :~: b • In the expression: Refl In an equation for ‘test3Bad’: test3Bad = Refl • Relevant bindings include test3Bad :: (a + b) :~: b -} test4 :: (a + b) :~: (a + a) -> a :~: b test4 Refl = Refl ltTrans :: forall (a :: Nat) (b :: Nat) (c :: Nat) . (a <? b) :~: 'True -> (b <? c) :~: 'True -> (a <? c) :~: 'True ltTrans Refl Refl = Refl data Vec :: Nat -> Type -> Type where VNil :: Vec 0 a (:>) :: a -> Vec n a -> Vec (1+n) a deriving instance Show a => Show (Vec n a) infixr 5 :> concatVec :: Vec n a -> Vec m a -> Vec (n+m) a concatVec VNil ys = ys concatVec (x:> xs) ys = x :> (concatVec xs ys) snocVec :: a -> Vec n a -> Vec (1+n) a snocVec x VNil = x :> VNil snocVec x (y :> ys) = y :> (snocVec x ys) reverseVec :: Vec n a -> Vec n a reverseVec VNil = VNil reverseVec (x :> xs) = snocVec x (reverseVec xs) stripPrefix :: Eq a => Vec n a -> Vec m a -> Maybe (Vec (m - n) a) stripPrefix VNil ys = Just ys stripPrefix _ VNil = Nothing stripPrefix (x :> xs) (y :> ys) = if x == y then stripPrefix xs ys else Nothing vecTests :: IO () vecTests = do let v = 1 :> 2 :> (VNil :: Vec 0 Int) let w = 3 :> 4 :> (VNil :: Vec 0 Int) let vw = concatVec v w putStrLn ("[1,2] = " ++ (show v)) putStrLn ("reverse [1,2] = " ++ (show $ reverseVec v)) putStrLn ("concat [1,2] [3,4] = " ++ (show vw)) putStrLn ("snoc 3 [1,2] = " ++ (show $ snocVec 3 v)) putStrLn ("stripPrefix [1,2] [1,2,3,4] = " ++ (show $ stripPrefix v vw)) putStrLn ("stripPrefix [3,4] [1,2,3,4] = " ++ (show $ stripPrefix w vw)) putStrLn ("stripPrefix [] [1,2,3,4] = " ++ (show $ stripPrefix VNil vw)) putStrLn ("stripPrefix [1,2] [] = " ++ (show $ stripPrefix v VNil))
null
https://raw.githubusercontent.com/bgamari/the-thoralf-plugin/fa4e403b25bfcaf9e8d5142ab40d3c54b33a3630/test-suite-rows/Nat.hs
haskell
# LANGUAGE TypeInType # # LANGUAGE GADTs # # LANGUAGE RankNTypes # # OPTIONS_GHC -fplugin ThoralfPlugin.Plugin #
# LANGUAGE TypeOperators # # LANGUAGE StandaloneDeriving # # LANGUAGE AllowAmbiguousTypes # module Nat where import ThoralfPlugin.Theory.Bool import Data.Type.Equality import Data.Kind import GHC.TypeLits test1 :: 1 :~: 1 test1 = Refl test2 :: (a + 1) :~: (1 + a) test2 = Refl test3 :: (a + b) :~: (b + a) test3 = Refl : : ( a + b ) : ~ : b test3Bad = Refl NOTE : Expected failure for . • Could n't match type ‘ b ’ with ‘ a + b ’ ‘ b ’ is a rigid type variable bound by the type signature for : : : forall ( a : : ) ( b : : ) . ( a + b ) : ~ : b Expected type : ( a + b ) : ~ : b Actual type : b : ~ : b • In the expression : In an equation for ‘ ’ : test3Bad = Refl • Relevant bindings include : : ( a + b ) : ~ : b test3Bad :: (a + b) :~: b test3Bad = Refl NOTE: Expected failure for test3Bad. • Couldn't match type ‘b’ with ‘a + b’ ‘b’ is a rigid type variable bound by the type signature for: test3Bad :: forall (a :: Nat) (b :: Nat). (a + b) :~: b Expected type: (a + b) :~: b Actual type: b :~: b • In the expression: Refl In an equation for ‘test3Bad’: test3Bad = Refl • Relevant bindings include test3Bad :: (a + b) :~: b -} test4 :: (a + b) :~: (a + a) -> a :~: b test4 Refl = Refl ltTrans :: forall (a :: Nat) (b :: Nat) (c :: Nat) . (a <? b) :~: 'True -> (b <? c) :~: 'True -> (a <? c) :~: 'True ltTrans Refl Refl = Refl data Vec :: Nat -> Type -> Type where VNil :: Vec 0 a (:>) :: a -> Vec n a -> Vec (1+n) a deriving instance Show a => Show (Vec n a) infixr 5 :> concatVec :: Vec n a -> Vec m a -> Vec (n+m) a concatVec VNil ys = ys concatVec (x:> xs) ys = x :> (concatVec xs ys) snocVec :: a -> Vec n a -> Vec (1+n) a snocVec x VNil = x :> VNil snocVec x (y :> ys) = y :> (snocVec x ys) reverseVec :: Vec n a -> Vec n a reverseVec VNil = VNil reverseVec (x :> xs) = snocVec x (reverseVec xs) stripPrefix :: Eq a => Vec n a -> Vec m a -> Maybe (Vec (m - n) a) stripPrefix VNil ys = Just ys stripPrefix _ VNil = Nothing stripPrefix (x :> xs) (y :> ys) = if x == y then stripPrefix xs ys else Nothing vecTests :: IO () vecTests = do let v = 1 :> 2 :> (VNil :: Vec 0 Int) let w = 3 :> 4 :> (VNil :: Vec 0 Int) let vw = concatVec v w putStrLn ("[1,2] = " ++ (show v)) putStrLn ("reverse [1,2] = " ++ (show $ reverseVec v)) putStrLn ("concat [1,2] [3,4] = " ++ (show vw)) putStrLn ("snoc 3 [1,2] = " ++ (show $ snocVec 3 v)) putStrLn ("stripPrefix [1,2] [1,2,3,4] = " ++ (show $ stripPrefix v vw)) putStrLn ("stripPrefix [3,4] [1,2,3,4] = " ++ (show $ stripPrefix w vw)) putStrLn ("stripPrefix [] [1,2,3,4] = " ++ (show $ stripPrefix VNil vw)) putStrLn ("stripPrefix [1,2] [] = " ++ (show $ stripPrefix v VNil))
07c554c946ba0053462f1fa36a30388c9dd8bdf75840d15e7987187229fdcb81
ewestern/geos
Profile.hs
import Data.Geometry.Geos.Geometry import Data.Geometry.Geos.Types import qualified Data.Vector as V import qualified Data.Set as S import qualified Data.ByteString.Char8 as BS8 import Data.Geometry.Geos.Serialize loadThingsFromFile :: FilePath -> IO [Some Geometry] loadThingsFromFile fp = do rows <- BS8.readFile fp return $ readHex <$> (BS8.lines rows) main = do points <- (fmap ensurePoint) <$> loadThingsFromFile "tests/sampledata/points.csv" mapM_ print points
null
https://raw.githubusercontent.com/ewestern/geos/3568c3449efe180bd89959c9247d4667137662b6/profile/Profile.hs
haskell
import Data.Geometry.Geos.Geometry import Data.Geometry.Geos.Types import qualified Data.Vector as V import qualified Data.Set as S import qualified Data.ByteString.Char8 as BS8 import Data.Geometry.Geos.Serialize loadThingsFromFile :: FilePath -> IO [Some Geometry] loadThingsFromFile fp = do rows <- BS8.readFile fp return $ readHex <$> (BS8.lines rows) main = do points <- (fmap ensurePoint) <$> loadThingsFromFile "tests/sampledata/points.csv" mapM_ print points
b50342180363105eddadc0010809783d6badf903391af2e593260c22f6a88813
bristolpl/intensional-datatys
FromCore.hs
# LANGUAGE LambdaCase # module Intensional.FromCore ( freshCoreType, freshCoreScheme, fromCoreCons, consInstArgs, getVar, ) where import Control.Monad.RWS import qualified Data.IntSet as I import qualified Data.Map as M import GhcPlugins hiding ((<>), Expr (..), Type) import Intensional.InferM import Intensional.Scheme as Scheme import ToIface import qualified TyCoRep as Tcr import Intensional.Types -- A fresh monomorphic type freshCoreType :: Tcr.Type -> InferM Type freshCoreType = fromCore Nothing -- A fresh polymorphic type freshCoreScheme :: Tcr.Type -> InferM Scheme freshCoreScheme = fromCoreScheme Nothing -- The type of a constructor injected into a fresh refinement environment fromCoreCons :: DataCon -> InferM Scheme fromCoreCons k = do x <- fresh let d = dataConTyCon k b <- isIneligible d unless b $ do l <- asks inferLoc emitKD k l (Inj x d) fromCoreScheme (Just x) (dataConUserType k) -- The argument types of an instantiated constructor consInstArgs :: RVar -> [Type] -> DataCon -> InferM [Type] consInstArgs x as k = mapM fromCoreInst (dataConRepArgTys k) where fromCoreInst :: Tcr.Type -> InferM Type fromCoreInst (Tcr.TyVarTy a) = case lookup a (zip (dataConUnivTyVars k) as) of Nothing -> return (Var (getName a)) Just t -> return t fromCoreInst (Tcr.AppTy a b) = App <$> (fromCoreInst a) <*> (fromCoreInst b) fromCoreInst (Tcr.TyConApp d as') | isTypeSynonymTyCon d, Just (as'', s) <- synTyConDefn_maybe d = fromCoreInst (substTy (extendTvSubstList emptySubst (zip as'' as')) s) -- Instantiate type synonym arguments | isClassTyCon d = return Ambiguous -- Disregard type class evidence | otherwise = do b <- isIneligible d if b then Data (Base d) <$> (mapM fromCoreInst as') else Data (Inj x d) <$> (mapM fromCoreInst as') fromCoreInst (Tcr.FunTy a b) = (:=>) <$> fromCoreInst a <*> fromCoreInst b fromCoreInst (Tcr.LitTy l) = return (Lit $ toIfaceTyLit l) fromCoreInst _ = return Ambiguous -- Convert a monomorphic core type fromCore :: Maybe RVar -> Tcr.Type -> InferM Type fromCore _ (Tcr.TyVarTy a) = Var <$> getExternalName a fromCore f (Tcr.AppTy a b) = liftM2 App (fromCore f a) (fromCore f b) fromCore f (Tcr.TyConApp d as) | isTypeSynonymTyCon d, Just (as', s) <- synTyConDefn_maybe d = fromCore f (substTy (extendTvSubstList emptySubst (zip as' as)) s) -- Instantiate type synonyms | isClassTyCon d = return Ambiguous -- Disregard type class evidence fromCore Nothing (Tcr.TyConApp d as) = do x <- fresh b <- isIneligible d if b then Data (Base d) <$> mapM (fromCore Nothing) as else Data (Inj x d) <$> mapM (fromCore Nothing) as fromCore (Just x) (Tcr.TyConApp d as) = do b <- isIneligible d if b then Data (Base d) <$> mapM (fromCore (Just x)) as else Data (Inj x d) <$> mapM (fromCore (Just x)) as fromCore f (Tcr.FunTy a b) = liftM2 (:=>) (fromCore f a) (fromCore f b) fromCore _ (Tcr.LitTy l) = return $ Lit $ toIfaceTyLit l fromCore _ _ = return Ambiguous -- Higher-ranked or impredicative types, casts and coercions -- Convert a polymorphic core type fromCoreScheme :: Maybe RVar -> Tcr.Type -> InferM Scheme fromCoreScheme f (Tcr.ForAllTy b t) = do a <- getExternalName (Tcr.binderVar b) scheme <- fromCoreScheme f t return scheme {tyvars = a : tyvars scheme} fromCoreScheme f (Tcr.FunTy a b) = do a' <- fromCore f a scheme <- fromCoreScheme f b -- Optimistically push arrows inside univiersal quantifier return scheme {body = a' :=> body scheme} fromCoreScheme f t = Forall [] <$> fromCore f t -- Lookup constrained variable and emit its constraints getVar :: Var -> InferM Scheme getVar v = asks (M.lookup (getName v) . varEnv) >>= \case Just scheme -> do Localise constraints fre_scheme <- foldM ( \s x -> do y <- fresh return (rename x y s) ) (scheme {boundvs = mempty}) (I.toList (boundvs scheme)) -- Emit constriants associated with a variable tell (constraints fre_scheme) return fre_scheme {Scheme.constraints = mempty} Nothing -> do var_scheme <- freshCoreScheme $ varType v maximise True (body var_scheme) return var_scheme -- Maximise/minimise a library type, i.e. assert every constructor occurs in covariant positions maximise :: Bool -> Type -> InferM () maximise True (Data (Inj x d) _) = do l <- asks inferLoc mapM_ (\k -> emitKD k l (Inj x d)) $ tyConDataCons d maximise b (x :=> y) = maximise (not b) x >> maximise b y maximise _ _ = return ()
null
https://raw.githubusercontent.com/bristolpl/intensional-datatys/ce6e7f5069530ea21a3e19c8e9e17fc23dc8e66c/src/Intensional/FromCore.hs
haskell
A fresh monomorphic type A fresh polymorphic type The type of a constructor injected into a fresh refinement environment The argument types of an instantiated constructor Instantiate type synonym arguments Disregard type class evidence Convert a monomorphic core type Instantiate type synonyms Disregard type class evidence Higher-ranked or impredicative types, casts and coercions Convert a polymorphic core type Optimistically push arrows inside univiersal quantifier Lookup constrained variable and emit its constraints Emit constriants associated with a variable Maximise/minimise a library type, i.e. assert every constructor occurs in covariant positions
# LANGUAGE LambdaCase # module Intensional.FromCore ( freshCoreType, freshCoreScheme, fromCoreCons, consInstArgs, getVar, ) where import Control.Monad.RWS import qualified Data.IntSet as I import qualified Data.Map as M import GhcPlugins hiding ((<>), Expr (..), Type) import Intensional.InferM import Intensional.Scheme as Scheme import ToIface import qualified TyCoRep as Tcr import Intensional.Types freshCoreType :: Tcr.Type -> InferM Type freshCoreType = fromCore Nothing freshCoreScheme :: Tcr.Type -> InferM Scheme freshCoreScheme = fromCoreScheme Nothing fromCoreCons :: DataCon -> InferM Scheme fromCoreCons k = do x <- fresh let d = dataConTyCon k b <- isIneligible d unless b $ do l <- asks inferLoc emitKD k l (Inj x d) fromCoreScheme (Just x) (dataConUserType k) consInstArgs :: RVar -> [Type] -> DataCon -> InferM [Type] consInstArgs x as k = mapM fromCoreInst (dataConRepArgTys k) where fromCoreInst :: Tcr.Type -> InferM Type fromCoreInst (Tcr.TyVarTy a) = case lookup a (zip (dataConUnivTyVars k) as) of Nothing -> return (Var (getName a)) Just t -> return t fromCoreInst (Tcr.AppTy a b) = App <$> (fromCoreInst a) <*> (fromCoreInst b) fromCoreInst (Tcr.TyConApp d as') | isTypeSynonymTyCon d, Just (as'', s) <- synTyConDefn_maybe d = | otherwise = do b <- isIneligible d if b then Data (Base d) <$> (mapM fromCoreInst as') else Data (Inj x d) <$> (mapM fromCoreInst as') fromCoreInst (Tcr.FunTy a b) = (:=>) <$> fromCoreInst a <*> fromCoreInst b fromCoreInst (Tcr.LitTy l) = return (Lit $ toIfaceTyLit l) fromCoreInst _ = return Ambiguous fromCore :: Maybe RVar -> Tcr.Type -> InferM Type fromCore _ (Tcr.TyVarTy a) = Var <$> getExternalName a fromCore f (Tcr.AppTy a b) = liftM2 App (fromCore f a) (fromCore f b) fromCore f (Tcr.TyConApp d as) | isTypeSynonymTyCon d, Just (as', s) <- synTyConDefn_maybe d = fromCore Nothing (Tcr.TyConApp d as) = do x <- fresh b <- isIneligible d if b then Data (Base d) <$> mapM (fromCore Nothing) as else Data (Inj x d) <$> mapM (fromCore Nothing) as fromCore (Just x) (Tcr.TyConApp d as) = do b <- isIneligible d if b then Data (Base d) <$> mapM (fromCore (Just x)) as else Data (Inj x d) <$> mapM (fromCore (Just x)) as fromCore f (Tcr.FunTy a b) = liftM2 (:=>) (fromCore f a) (fromCore f b) fromCore _ (Tcr.LitTy l) = return $ Lit $ toIfaceTyLit l fromCoreScheme :: Maybe RVar -> Tcr.Type -> InferM Scheme fromCoreScheme f (Tcr.ForAllTy b t) = do a <- getExternalName (Tcr.binderVar b) scheme <- fromCoreScheme f t return scheme {tyvars = a : tyvars scheme} fromCoreScheme f (Tcr.FunTy a b) = do a' <- fromCore f a return scheme {body = a' :=> body scheme} fromCoreScheme f t = Forall [] <$> fromCore f t getVar :: Var -> InferM Scheme getVar v = asks (M.lookup (getName v) . varEnv) >>= \case Just scheme -> do Localise constraints fre_scheme <- foldM ( \s x -> do y <- fresh return (rename x y s) ) (scheme {boundvs = mempty}) (I.toList (boundvs scheme)) tell (constraints fre_scheme) return fre_scheme {Scheme.constraints = mempty} Nothing -> do var_scheme <- freshCoreScheme $ varType v maximise True (body var_scheme) return var_scheme maximise :: Bool -> Type -> InferM () maximise True (Data (Inj x d) _) = do l <- asks inferLoc mapM_ (\k -> emitKD k l (Inj x d)) $ tyConDataCons d maximise b (x :=> y) = maximise (not b) x >> maximise b y maximise _ _ = return ()
46c7265feb3e07f6a08aa9eca7c7e803342c4a1c66886a5b00ffa1c1bb98c682
TrustInSoft/tis-interpreter
sparecode_params.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) include Plugin.Register (struct let name = "sparecode" let shortname = "sparecode" let help = "code cleaner" end) module Analysis = False(struct let option_name = "-sparecode" let help = "perform a spare code analysis" end) let () = Analysis.add_aliases ["-sparecode-analysis"] module Annot = True(struct let option_name = "-sparecode-annot" let help = "select more things to keep every reachable annotation" end) module GlobDecl = False(struct let option_name = "-rm-unused-globals" let help = ("only remove unused global types and variables "^ "(automatically done by -sparecode-analysis)") end) (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/sparecode/sparecode_params.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ Local Variables: compile-command: "make -C ../../.." End:
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . include Plugin.Register (struct let name = "sparecode" let shortname = "sparecode" let help = "code cleaner" end) module Analysis = False(struct let option_name = "-sparecode" let help = "perform a spare code analysis" end) let () = Analysis.add_aliases ["-sparecode-analysis"] module Annot = True(struct let option_name = "-sparecode-annot" let help = "select more things to keep every reachable annotation" end) module GlobDecl = False(struct let option_name = "-rm-unused-globals" let help = ("only remove unused global types and variables "^ "(automatically done by -sparecode-analysis)") end)
1740e44b4e2cfadc4990fe3609b16dc2fba7be7413aa662f4e94218573eb12ce
kritzcreek/fby19
AST.hs
{-# language OverloadedStrings #-} module AST where import Prelude hiding (unwords) import Data.Text (Text, unwords) import qualified Data.Text as Text data Exp = EVar Text | ELit Lit | EApp Exp Exp | ELam Text Exp | ELet Text Exp Exp deriving (Eq, Ord, Show) data Lit = LInt Integer | LBool Bool deriving (Eq, Ord, Show) data Type = TInt | TBool | TVar Text | TFun Type Type deriving (Eq, Ord, Show) data Scheme = Scheme [Text] Type -- Ignore from here onwards isFun :: Type -> Bool isFun ty = case ty of TFun _ _ -> True _ -> False prettyType :: Type -> Text prettyType ty = case ty of TVar var -> var TInt -> "Int" TBool -> "Bool" TFun ty1 ty2 -> (if isFun ty1 then "(" <> prettyType ty1 <> ")" else prettyType ty1) <> " -> " <> prettyType ty2 prettyScheme :: Scheme -> Text prettyScheme (Scheme [] ty) = prettyType ty prettyScheme (Scheme vars ty) = let This means we can only print types with a maximum of 26 type -- variables (Should be enough for the talk :D) vars' = zip vars (map Text.singleton ['a'..'z']) renamedTy = foldl renameVar ty vars' in "forall " <> unwords (map snd vars') <> ". " <> prettyType renamedTy renameVar :: Type -> (Text, Text) -> Type renameVar ty (old, new) = case ty of TInt -> TInt TBool -> TBool TVar var -> TVar (if var == old then new else var) TFun t1 t2 -> TFun (renameVar t1 (old, new)) (renameVar t2 (old, new))
null
https://raw.githubusercontent.com/kritzcreek/fby19/c6b6f541686055923fb694692c0568345416b9d1/src/AST.hs
haskell
# language OverloadedStrings # Ignore from here onwards variables (Should be enough for the talk :D)
module AST where import Prelude hiding (unwords) import Data.Text (Text, unwords) import qualified Data.Text as Text data Exp = EVar Text | ELit Lit | EApp Exp Exp | ELam Text Exp | ELet Text Exp Exp deriving (Eq, Ord, Show) data Lit = LInt Integer | LBool Bool deriving (Eq, Ord, Show) data Type = TInt | TBool | TVar Text | TFun Type Type deriving (Eq, Ord, Show) data Scheme = Scheme [Text] Type isFun :: Type -> Bool isFun ty = case ty of TFun _ _ -> True _ -> False prettyType :: Type -> Text prettyType ty = case ty of TVar var -> var TInt -> "Int" TBool -> "Bool" TFun ty1 ty2 -> (if isFun ty1 then "(" <> prettyType ty1 <> ")" else prettyType ty1) <> " -> " <> prettyType ty2 prettyScheme :: Scheme -> Text prettyScheme (Scheme [] ty) = prettyType ty prettyScheme (Scheme vars ty) = let This means we can only print types with a maximum of 26 type vars' = zip vars (map Text.singleton ['a'..'z']) renamedTy = foldl renameVar ty vars' in "forall " <> unwords (map snd vars') <> ". " <> prettyType renamedTy renameVar :: Type -> (Text, Text) -> Type renameVar ty (old, new) = case ty of TInt -> TInt TBool -> TBool TVar var -> TVar (if var == old then new else var) TFun t1 t2 -> TFun (renameVar t1 (old, new)) (renameVar t2 (old, new))
7b2e4c7dc385f5be55ac86c2e1e6ade85fc7b8ea086f64667ab336e5bbb9b0b6
Smoltbob/Caml-Est-Belle
basmlparser.ml
let print_ast l = let s = (Bparser.toplevel Blexer.token l) in print_string (Bsyntax.to_string_top s); print_newline () let file f = let inchan = open_in f in try print_ast (Lexing.from_channel inchan); close_in inchan with e -> (close_in inchan; raise e) let () = let files = ref [] in Arg.parse [ ] (fun s -> files := !files @ [s]) (Printf.sprintf "usage: %s filenames" Sys.argv.(0)); List.iter (fun f -> ignore (file f)) !files
null
https://raw.githubusercontent.com/Smoltbob/Caml-Est-Belle/3d6f53d4e8e01bbae57a0a402b7c0f02f4ed767c/compiler/basmlparser.ml
ocaml
let print_ast l = let s = (Bparser.toplevel Blexer.token l) in print_string (Bsyntax.to_string_top s); print_newline () let file f = let inchan = open_in f in try print_ast (Lexing.from_channel inchan); close_in inchan with e -> (close_in inchan; raise e) let () = let files = ref [] in Arg.parse [ ] (fun s -> files := !files @ [s]) (Printf.sprintf "usage: %s filenames" Sys.argv.(0)); List.iter (fun f -> ignore (file f)) !files
59b1102b52d57de0cfc1d129a2a4dfa691202977b3b67a5a21173fd4d484c599
tomjridge/tjr_simple_earley
test2.ml
test2 , represent nt_item as int (* compared to test, we use lazy enumeration *) open Tjr_simple_earley open Util.Map_ops open Fast_ds (* simple test ------------------------------------------------------ *) Encode nonterminals and terminals as ints ; nts are even ; tms are odd odd *) type sym = E | One | Eps let is_nt = function | E -> true | _ -> false module X1 = struct type nonrec sym = sym let is_nt = is_nt end module Tmp1 = Make_sym(X1) let sym2int : sym -> int = Tmp1.make () @@ fun ~sym2int -> sym2int module Tmp2 = Make_rhs(X1) Encode the grammar E - > E E E | " 1 " | eps let rhss = [ [E;E;E]; [One]; [Eps] ] let (rhs2i,hd_bs) = Tmp2.make ~sym2int @@ fun ~rhs2i ~hd_bs -> (rhs2i,hd_bs) (* Provide a function that produces new items, given a nonterminal and an input position k *) let rhss' = List.map rhs2i rhss let new_items ~nt ~input ~k = match nt with | _ when nt = sym2int E -> rhss' |> List.map (fun bs -> let i = k in S.to_int (nt,i,k,bs)) | _ -> failwith __LOC__ (* Example input; use command line argument *) let input = String.make (Sys.argv.(1) |> int_of_string) '1' (* Provide a function that details how to parse terminals at a given position k in the input *) let parse_tm ~tm ~input ~k ~input_length = match () with | _ when tm = sym2int Eps -> [k] | _ when tm = sym2int One -> (* print_endline (string_of_int k); *) if String.get input k = '1' then [k+1] else [] | _ -> failwith __LOC__ let input_length = String.length input (* Initial nonterminal *) let init_nt = sym2int E let dot_bs_hd nitm = nitm |> S.dot_bs_as_int |> hd_bs open S Construct ( nonterminal ) item operations let nt_item_ops = { dot_nt; dot_i; dot_k; dot_bs_hd } let bitms_lt_k_ops = { map_add=(fun k v t -> t.(k) <- v; t); map_find=(fun k t -> t.(k)); map_empty=(Array.make (input_length + 1) map_nt_ops.map_empty); (* FIXME +1? *) map_remove=(fun k t -> failwith __LOC__); (* not used *) } let cut = S.cut Finally , run ! open Earley let main () = run_earley ~nt_item_ops ~bitms_lt_k_ops ~cut ~new_items ~input ~parse_tm ~input_length ~init_nt |> fun s -> s.k |> string_of_int |> print_endline let _ = main () $ bin $ time ./test2.native 400 400 real 0m2.508s user 0m2.484s sys 0m0.016s # ( h : pc1177 ) ( p:~/l / github / p_tjr_simple_earley / src / ) ( d:/dev / loop7[/git ] ) [ dev ! ? ] $ bin $ time ./test2.native 400 400 real 0m2.508s user 0m2.484s sys 0m0.016s # (h:pc1177) (p:~/l/github/p_tjr_simple_earley/src/bin) (d:/dev/loop7[/git]) [dev !?] *) let _ = Printf.printf "Number of items processed: %d\n%!" (!Earley.counter)
null
https://raw.githubusercontent.com/tomjridge/tjr_simple_earley/ca558e0e7f4ddba4cd6573bf180710cd02f25ba4/_archive/2019-04-16/bin/test2.ml
ocaml
compared to test, we use lazy enumeration simple test ------------------------------------------------------ Provide a function that produces new items, given a nonterminal and an input position k Example input; use command line argument Provide a function that details how to parse terminals at a given position k in the input print_endline (string_of_int k); Initial nonterminal FIXME +1? not used
test2 , represent nt_item as int open Tjr_simple_earley open Util.Map_ops open Fast_ds Encode nonterminals and terminals as ints ; nts are even ; tms are odd odd *) type sym = E | One | Eps let is_nt = function | E -> true | _ -> false module X1 = struct type nonrec sym = sym let is_nt = is_nt end module Tmp1 = Make_sym(X1) let sym2int : sym -> int = Tmp1.make () @@ fun ~sym2int -> sym2int module Tmp2 = Make_rhs(X1) Encode the grammar E - > E E E | " 1 " | eps let rhss = [ [E;E;E]; [One]; [Eps] ] let (rhs2i,hd_bs) = Tmp2.make ~sym2int @@ fun ~rhs2i ~hd_bs -> (rhs2i,hd_bs) let rhss' = List.map rhs2i rhss let new_items ~nt ~input ~k = match nt with | _ when nt = sym2int E -> rhss' |> List.map (fun bs -> let i = k in S.to_int (nt,i,k,bs)) | _ -> failwith __LOC__ let input = String.make (Sys.argv.(1) |> int_of_string) '1' let parse_tm ~tm ~input ~k ~input_length = match () with | _ when tm = sym2int Eps -> [k] | _ when tm = sym2int One -> if String.get input k = '1' then [k+1] else [] | _ -> failwith __LOC__ let input_length = String.length input let init_nt = sym2int E let dot_bs_hd nitm = nitm |> S.dot_bs_as_int |> hd_bs open S Construct ( nonterminal ) item operations let nt_item_ops = { dot_nt; dot_i; dot_k; dot_bs_hd } let bitms_lt_k_ops = { map_add=(fun k v t -> t.(k) <- v; t); map_find=(fun k t -> t.(k)); } let cut = S.cut Finally , run ! open Earley let main () = run_earley ~nt_item_ops ~bitms_lt_k_ops ~cut ~new_items ~input ~parse_tm ~input_length ~init_nt |> fun s -> s.k |> string_of_int |> print_endline let _ = main () $ bin $ time ./test2.native 400 400 real 0m2.508s user 0m2.484s sys 0m0.016s # ( h : pc1177 ) ( p:~/l / github / p_tjr_simple_earley / src / ) ( d:/dev / loop7[/git ] ) [ dev ! ? ] $ bin $ time ./test2.native 400 400 real 0m2.508s user 0m2.484s sys 0m0.016s # (h:pc1177) (p:~/l/github/p_tjr_simple_earley/src/bin) (d:/dev/loop7[/git]) [dev !?] *) let _ = Printf.printf "Number of items processed: %d\n%!" (!Earley.counter)
592a2dbc656f5eddfac4bf83cbdbf15baf7d4be65e32e978a4bf609e0e1a3ad2
ertugrulcetin/ClojureNews
user.cljs
(ns route.user (:require-macros [secretary.core :refer [defroute]]) (:require [reagent.core :as r] [secretary.core] [view.user] [view.changepassword] [util.view] [controller.user :as controller])) (defroute user "/user/:username" [username] (controller/user username)) (defroute user "/user/:username/changepassword" [username] (controller/change-password-page username))
null
https://raw.githubusercontent.com/ertugrulcetin/ClojureNews/28002f6b620fa4977d561b0cfca0c7f6a635057b/src/cljs/route/user.cljs
clojure
(ns route.user (:require-macros [secretary.core :refer [defroute]]) (:require [reagent.core :as r] [secretary.core] [view.user] [view.changepassword] [util.view] [controller.user :as controller])) (defroute user "/user/:username" [username] (controller/user username)) (defroute user "/user/:username/changepassword" [username] (controller/change-password-page username))
e9a3cdb7b693f3b84b64951edcf7f2cb0265c8cfb2414885feeb1cc50e6537b3
davejacobs/ml
logistic.clj
(ns ml.logistic (:require [ml.optimization :as optimization]) (:use clojure.options [incanter core io stats])) (defn g [z] (/ 1 (+ 1 (exp (- z))))) (defn h [xs thetas] (matrix-map g (mmult xs thetas))) (defn logarithmic-cost [hypothesis actual] (let [m (count hypothesis) multiplier (/ 1 m) if-0-fn (mmult (trans (minus actual)) (log hypothesis)) if-1-fn (mmult (trans (minus 1 actual)) (log (minus 1 hypothesis))) sum-differences (minus if-0-fn if-1-fn)] (mult multiplier sum-differences))) (defn regularize [thetas lambda] (let [m (count thetas) squared-sum (sum (sq (rest thetas)))] (* (/ lambda (* 2 m)) squared-sum))) (defn+opts cost [xs ys thetas | {cost-fn logarithmic-cost}] (let [hypothesis (h xs thetas)] (cost-fn hypothesis ys))) (defn gradient [xs ys thetas & args] (apply optimization/gradient xs ys thetas :hypothesis-fn h args)) (defn descend [xs ys & args] (apply optimization/descend xs ys :cost-fn cost args)) (defn probabilities [points thetas category] (let [probabilities-of-one (h points thetas)] (if (zero? category) (minus 1 probabilities-of-one) probabilities-of-one))) (defn predict-category [points thetas threshold] (let [prediction-fn #(if (> % threshold) 1 0)] (matrix-map prediction-fn (probabilities points thetas 1))))
null
https://raw.githubusercontent.com/davejacobs/ml/4ceda8cee8a79ff52e57484c2988a2ddf10def7f/src/ml/logistic.clj
clojure
(ns ml.logistic (:require [ml.optimization :as optimization]) (:use clojure.options [incanter core io stats])) (defn g [z] (/ 1 (+ 1 (exp (- z))))) (defn h [xs thetas] (matrix-map g (mmult xs thetas))) (defn logarithmic-cost [hypothesis actual] (let [m (count hypothesis) multiplier (/ 1 m) if-0-fn (mmult (trans (minus actual)) (log hypothesis)) if-1-fn (mmult (trans (minus 1 actual)) (log (minus 1 hypothesis))) sum-differences (minus if-0-fn if-1-fn)] (mult multiplier sum-differences))) (defn regularize [thetas lambda] (let [m (count thetas) squared-sum (sum (sq (rest thetas)))] (* (/ lambda (* 2 m)) squared-sum))) (defn+opts cost [xs ys thetas | {cost-fn logarithmic-cost}] (let [hypothesis (h xs thetas)] (cost-fn hypothesis ys))) (defn gradient [xs ys thetas & args] (apply optimization/gradient xs ys thetas :hypothesis-fn h args)) (defn descend [xs ys & args] (apply optimization/descend xs ys :cost-fn cost args)) (defn probabilities [points thetas category] (let [probabilities-of-one (h points thetas)] (if (zero? category) (minus 1 probabilities-of-one) probabilities-of-one))) (defn predict-category [points thetas threshold] (let [prediction-fn #(if (> % threshold) 1 0)] (matrix-map prediction-fn (probabilities points thetas 1))))
78c70502b8f83b4d03166eb92a7ac8b049123ef36ef4ea930a4cb9ea0633c3dc
wdebeaum/step
wood.lisp
;;;; ;;;; W::WOOD ;;;; (define-words :pos W::n :templ count-pred-templ :tags (:base500) :words ( (W::WOOD (SENSES ((meta-data :origin BOLT :entry-date 20031230 :change-date nil :comments most-frequent-words) (LF-PARENT ONT::material) (TEMPL MASS-PRED-TEMPL) ) ) ) ))
null
https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/wood.lisp
lisp
W::WOOD
(define-words :pos W::n :templ count-pred-templ :tags (:base500) :words ( (W::WOOD (SENSES ((meta-data :origin BOLT :entry-date 20031230 :change-date nil :comments most-frequent-words) (LF-PARENT ONT::material) (TEMPL MASS-PRED-TEMPL) ) ) ) ))
4b372c6b5814f69f9094a7a592500e797af1f19a3b81d7d0f8dcf3c96ec113d2
elaforge/karya
LIntegrate.hs
Copyright 2013 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt -- | Functions to deal with derive and score integration. module Cmd.Repl.LIntegrate where import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Text as Text import qualified Cmd.Cmd as Cmd import qualified Cmd.Create as Create import qualified Cmd.Edit as Edit import qualified Cmd.Integrate.Merge as Merge import qualified Cmd.Perf as Perf import qualified Cmd.Selection as Selection import qualified Derive.Derive as Derive import qualified Derive.Stack as Stack import qualified Derive.Stream as Stream import qualified Ui.Block as Block import qualified Ui.Event as Event import qualified Ui.Events as Events import qualified Ui.Ui as Ui import Global import Types -- * create -- | Create an integrated block from the focused block. The block integrate call will automatically create one block , but you have to use this if you want more than one . Actually , you can use it on a block without a ` < < ` -- integrate call, but there isn't much point since it won't reintegrate until -- you add one. block :: Cmd.M m => m ViewId block = do source_block <- Cmd.get_focused_block ruler_id <- Ui.block_ruler source_block dest_block <- Create.block ruler_id Ui.set_integrated_block dest_block $ Just (source_block, Block.DeriveDestinations []) Cmd.derive_immediately [source_block] Cmd.inflict_block_damage source_block Create.view dest_block -- | Create a block integrate copy of the selected block. Details at ' Block . ScoreDestinations ' . score_block :: Cmd.M m => m ViewId score_block = do source_block <- Cmd.get_focused_block ruler_id <- Ui.block_ruler source_block dest_block <- Create.block ruler_id Ui.set_integrated_block dest_block $ Just (source_block, Block.ScoreDestinations []) Cmd.inflict_block_damage source_block Create.view dest_block -- | Similar to 'block', explicitly create another track integrated from the -- selected one, which should already have a `<` integrate call on it. track :: Cmd.M m => m () track = do (block_id, _, track_id, _) <- Selection.get_insert Ui.modify_integrated_tracks block_id ((track_id, Block.DeriveDestinations []) :) Cmd.derive_immediately [block_id] Cmd.inflict_track_damage block_id track_id -- | Create a track integrate copy of the selected track. Details at ' Block . ScoreDestinations ' . score_track :: Cmd.M m => m () score_track = do (block_id, _, track_id, _) <- Selection.get_insert Ui.modify_integrated_tracks block_id ((track_id, Block.ScoreDestinations []) :) Cmd.inflict_track_damage block_id track_id clear_score_track :: Cmd.M m => m () clear_score_track = do (block_id, _, track_ids, _) <- Selection.tracks Ui.modify_integrated_tracks block_id $ filter ((`notElem` track_ids) . fst) clear_score_tracks_of :: Ui.M m => BlockId -> m () clear_score_tracks_of block_id = Ui.modify_integrated_tracks block_id (const []) -- * revert -- | Revert the selected range back to the integrated state. sel_revert :: Cmd.M m => m () sel_revert = do (block_id, _, track_ids, range) <- Selection.tracks Edit.clear_range track_ids range by_dest <- Block.destination_to_source <$> Ui.get_block block_id sequence_ [ Ui.insert_block_events block_id track_id (map Event.unmodified (Map.elems index)) | (track_id, (_, index)) <- by_dest , track_id `elem` track_ids ] delete_manual :: Cmd.M m => Block.SourceKey -> m () delete_manual key = do block_id <- Cmd.get_focused_block Ui.set_integrated_manual block_id key Nothing -- * inspect track_sources :: Cmd.M m => m Text track_sources = do block <- Ui.get_block =<< Cmd.get_focused_block return $ Text.unlines $ List.intercalate [""] $ map show_source $ Block.block_integrated_tracks block where show_source (source, dests) = "=== source: " <> pretty source : show_track_dests dests show_track_dests :: Block.TrackDestinations -> [Text] show_track_dests = \case Block.DeriveDestinations dests -> concatMap show_dest dests Block.ScoreDestinations dests -> concatMap show_score_dest dests show_score_dest :: (TrackId, (TrackId, Block.EventIndex)) -> [Text] show_score_dest (source, (dest, events)) = "== " <> pretty source <> " -> " <> pretty dest <> ":" : show_index events show_dest :: Block.NoteDestination -> [Text] show_dest (Block.NoteDestination key note controls) = "== key: " <> pretty key : "== note: " <> pretty (fst note) : show_index (snd note) ++ concatMap show_control (Map.toList controls) where show_control (name, (track_id, index)) = "== control " <> name <> ": " <> pretty track_id : show_index index show_index :: Block.EventIndex -> [Text] show_index = map show_event . Map.elems show_event :: Event.Event -> Text show_event e = mconcat [ pretty (Event.start e), "+", pretty (Event.duration e) , " ", pretty (Event.text e) , " ", fromMaybe "?" $ Stack.pretty_ui_inner . Event.stack_stack =<< Event.stack e ] -- | Show the integration state in an abbreviated way. -- This is an inverse mapping from dest to source. dest_to_sources :: Cmd.M m => m [(TrackId, (Block.Source, Text))] dest_to_sources = do block <- Ui.get_block =<< Cmd.get_focused_block return $ map (fmap (fmap Block.short_event_index)) $ Block.destination_to_source block sel_edits :: Cmd.M m => m ([Event.IndexKey], [Merge.Edit]) sel_edits = do (block_id, _, track_id, _) <- Selection.get_insert edits block_id track_id edits :: Cmd.M m => BlockId -> TrackId -> m ([Event.IndexKey], [Merge.Edit]) edits block_id track_id = do block <- Ui.get_block block_id index <- Cmd.require "track is not integrated from anywhere" $ lookup track_id $ indices_of (Block.block_integrated block) (Block.block_integrated_tracks block) events <- Ui.get_events track_id let (deleted, edits) = Merge.diff_events index (Events.ascending events) return (Set.toList deleted, filter Merge.is_modified edits) -- | Show source UI events. indices :: Cmd.M m => m [(TrackId, (Block.Source, Block.EventIndex))] indices = fmap Block.destination_to_source . Ui.get_block =<< Cmd.get_focused_block indices_of :: Maybe (BlockId, Block.TrackDestinations) -> [(TrackId, Block.TrackDestinations)] -> [(TrackId, Block.EventIndex)] indices_of integrated integrated_tracks = block_indices ++ concatMap dest_indices integrated_tracks where block_indices = maybe [] dest_indices integrated dest_indices (_, Block.DeriveDestinations dests) = concatMap derive_indices dests dest_indices (_, Block.ScoreDestinations dests) = map snd dests derive_indices (Block.NoteDestination _ note controls) = note : Map.elems controls -- | This is always going to be empty because cache strips collect_integrated. -- That's too bad because sometimes I want to see the original events, for -- debugging. integrated :: Cmd.M m => m Text integrated = do integrated <- Cmd.perf_integrated <$> (Perf.get =<< Cmd.get_focused_block) return $ Text.unlines $ concatMap fmt integrated where fmt (Derive.Integrated source events) = pretty source : Stream.short_events events
null
https://raw.githubusercontent.com/elaforge/karya/b4a5700868f4409c8d4f246bf93a31fc81662341/Cmd/Repl/LIntegrate.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt | Functions to deal with derive and score integration. * create | Create an integrated block from the focused block. The block integrate integrate call, but there isn't much point since it won't reintegrate until you add one. | Create a block integrate copy of the selected block. Details at | Similar to 'block', explicitly create another track integrated from the selected one, which should already have a `<` integrate call on it. | Create a track integrate copy of the selected track. Details at * revert | Revert the selected range back to the integrated state. * inspect | Show the integration state in an abbreviated way. This is an inverse mapping from dest to source. | Show source UI events. | This is always going to be empty because cache strips collect_integrated. That's too bad because sometimes I want to see the original events, for debugging.
Copyright 2013 module Cmd.Repl.LIntegrate where import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Text as Text import qualified Cmd.Cmd as Cmd import qualified Cmd.Create as Create import qualified Cmd.Edit as Edit import qualified Cmd.Integrate.Merge as Merge import qualified Cmd.Perf as Perf import qualified Cmd.Selection as Selection import qualified Derive.Derive as Derive import qualified Derive.Stack as Stack import qualified Derive.Stream as Stream import qualified Ui.Block as Block import qualified Ui.Event as Event import qualified Ui.Events as Events import qualified Ui.Ui as Ui import Global import Types call will automatically create one block , but you have to use this if you want more than one . Actually , you can use it on a block without a ` < < ` block :: Cmd.M m => m ViewId block = do source_block <- Cmd.get_focused_block ruler_id <- Ui.block_ruler source_block dest_block <- Create.block ruler_id Ui.set_integrated_block dest_block $ Just (source_block, Block.DeriveDestinations []) Cmd.derive_immediately [source_block] Cmd.inflict_block_damage source_block Create.view dest_block ' Block . ScoreDestinations ' . score_block :: Cmd.M m => m ViewId score_block = do source_block <- Cmd.get_focused_block ruler_id <- Ui.block_ruler source_block dest_block <- Create.block ruler_id Ui.set_integrated_block dest_block $ Just (source_block, Block.ScoreDestinations []) Cmd.inflict_block_damage source_block Create.view dest_block track :: Cmd.M m => m () track = do (block_id, _, track_id, _) <- Selection.get_insert Ui.modify_integrated_tracks block_id ((track_id, Block.DeriveDestinations []) :) Cmd.derive_immediately [block_id] Cmd.inflict_track_damage block_id track_id ' Block . ScoreDestinations ' . score_track :: Cmd.M m => m () score_track = do (block_id, _, track_id, _) <- Selection.get_insert Ui.modify_integrated_tracks block_id ((track_id, Block.ScoreDestinations []) :) Cmd.inflict_track_damage block_id track_id clear_score_track :: Cmd.M m => m () clear_score_track = do (block_id, _, track_ids, _) <- Selection.tracks Ui.modify_integrated_tracks block_id $ filter ((`notElem` track_ids) . fst) clear_score_tracks_of :: Ui.M m => BlockId -> m () clear_score_tracks_of block_id = Ui.modify_integrated_tracks block_id (const []) sel_revert :: Cmd.M m => m () sel_revert = do (block_id, _, track_ids, range) <- Selection.tracks Edit.clear_range track_ids range by_dest <- Block.destination_to_source <$> Ui.get_block block_id sequence_ [ Ui.insert_block_events block_id track_id (map Event.unmodified (Map.elems index)) | (track_id, (_, index)) <- by_dest , track_id `elem` track_ids ] delete_manual :: Cmd.M m => Block.SourceKey -> m () delete_manual key = do block_id <- Cmd.get_focused_block Ui.set_integrated_manual block_id key Nothing track_sources :: Cmd.M m => m Text track_sources = do block <- Ui.get_block =<< Cmd.get_focused_block return $ Text.unlines $ List.intercalate [""] $ map show_source $ Block.block_integrated_tracks block where show_source (source, dests) = "=== source: " <> pretty source : show_track_dests dests show_track_dests :: Block.TrackDestinations -> [Text] show_track_dests = \case Block.DeriveDestinations dests -> concatMap show_dest dests Block.ScoreDestinations dests -> concatMap show_score_dest dests show_score_dest :: (TrackId, (TrackId, Block.EventIndex)) -> [Text] show_score_dest (source, (dest, events)) = "== " <> pretty source <> " -> " <> pretty dest <> ":" : show_index events show_dest :: Block.NoteDestination -> [Text] show_dest (Block.NoteDestination key note controls) = "== key: " <> pretty key : "== note: " <> pretty (fst note) : show_index (snd note) ++ concatMap show_control (Map.toList controls) where show_control (name, (track_id, index)) = "== control " <> name <> ": " <> pretty track_id : show_index index show_index :: Block.EventIndex -> [Text] show_index = map show_event . Map.elems show_event :: Event.Event -> Text show_event e = mconcat [ pretty (Event.start e), "+", pretty (Event.duration e) , " ", pretty (Event.text e) , " ", fromMaybe "?" $ Stack.pretty_ui_inner . Event.stack_stack =<< Event.stack e ] dest_to_sources :: Cmd.M m => m [(TrackId, (Block.Source, Text))] dest_to_sources = do block <- Ui.get_block =<< Cmd.get_focused_block return $ map (fmap (fmap Block.short_event_index)) $ Block.destination_to_source block sel_edits :: Cmd.M m => m ([Event.IndexKey], [Merge.Edit]) sel_edits = do (block_id, _, track_id, _) <- Selection.get_insert edits block_id track_id edits :: Cmd.M m => BlockId -> TrackId -> m ([Event.IndexKey], [Merge.Edit]) edits block_id track_id = do block <- Ui.get_block block_id index <- Cmd.require "track is not integrated from anywhere" $ lookup track_id $ indices_of (Block.block_integrated block) (Block.block_integrated_tracks block) events <- Ui.get_events track_id let (deleted, edits) = Merge.diff_events index (Events.ascending events) return (Set.toList deleted, filter Merge.is_modified edits) indices :: Cmd.M m => m [(TrackId, (Block.Source, Block.EventIndex))] indices = fmap Block.destination_to_source . Ui.get_block =<< Cmd.get_focused_block indices_of :: Maybe (BlockId, Block.TrackDestinations) -> [(TrackId, Block.TrackDestinations)] -> [(TrackId, Block.EventIndex)] indices_of integrated integrated_tracks = block_indices ++ concatMap dest_indices integrated_tracks where block_indices = maybe [] dest_indices integrated dest_indices (_, Block.DeriveDestinations dests) = concatMap derive_indices dests dest_indices (_, Block.ScoreDestinations dests) = map snd dests derive_indices (Block.NoteDestination _ note controls) = note : Map.elems controls integrated :: Cmd.M m => m Text integrated = do integrated <- Cmd.perf_integrated <$> (Perf.get =<< Cmd.get_focused_block) return $ Text.unlines $ concatMap fmt integrated where fmt (Derive.Integrated source events) = pretty source : Stream.short_events events
92362eee44bb14323cd737abbe1c019fb07a52fa5a93f6a2e01121e908f28a2c
Zulu-Inuoe/clution
enum.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; enum.lisp --- Defining foreign constants as Lisp keywords. ;;; Copyright ( C ) 2005 - 2006 , < > ;;; ;;; 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. ;;; (in-package #:cffi) ;; TODO the accessors names are rather inconsistent: FOREIGN - ENUM - VALUE FOREIGN - BITFIELD - VALUE ;; FOREIGN-ENUM-KEYWORD FOREIGN-BITFIELD-SYMBOLS ;; FOREIGN-ENUM-KEYWORD-LIST FOREIGN-BITFIELD-SYMBOL-LIST I 'd rename them to : FOREIGN-*-KEY(S ) and FOREIGN-*-ALL - KEYS -- ;; TODO bitfield is a confusing name, because the C standard calls the " int foo : 3 " type as a bitfield . Maybe rename to defbitmask ? -- ;;;# Foreign Constants as Lisp Keywords ;;; ;;; This module defines the DEFCENUM macro, which provides an ;;; interface for defining a type and associating a set of integer ;;; constants with keyword symbols for that type. ;;; ;;; The keywords are automatically translated to the appropriate ;;; constant for the type by a type translator when passed as ;;; arguments or a return value to a foreign function. (defclass foreign-enum (named-foreign-type enhanced-foreign-type) ((keyword-values :initform (error "Must specify KEYWORD-VALUES.") :initarg :keyword-values :reader keyword-values) (value-keywords :initform (error "Must specify VALUE-KEYWORDS.") :initarg :value-keywords :reader value-keywords)) (:documentation "Describes a foreign enumerated type.")) (deftype enum-key () '(and symbol (not null))) (defparameter +valid-enum-base-types+ *built-in-integer-types*) (defun parse-foreign-enum-like (type-name base-type values &optional field-mode-p) (let ((keyword-values (make-hash-table :test 'eq)) (value-keywords (make-hash-table)) (field-keywords (list)) (bit-index->keyword (make-array 0 :adjustable t :element-type t)) (default-value (if field-mode-p 1 0)) (most-extreme-value 0) (has-negative-value? nil)) (dolist (pair values) (destructuring-bind (keyword &optional (value default-value valuep)) (ensure-list pair) (check-type keyword enum-key) ;;(check-type value integer) (when (> (abs value) (abs most-extreme-value)) (setf most-extreme-value value)) (when (minusp value) (setf has-negative-value? t)) (if field-mode-p (if valuep (when (and (>= value default-value) (single-bit-p value)) (setf default-value (ash value 1))) (setf default-value (ash default-value 1))) (setf default-value (1+ value))) (if (gethash keyword keyword-values) (error "A foreign enum cannot contain duplicate keywords: ~S." keyword) (setf (gethash keyword keyword-values) value)) ;; This is completely arbitrary behaviour: we keep the last ;; value->keyword mapping. I suppose the opposite would be just as good ( keeping the first ) . Returning a list with all ;; the keywords might be a solution too? Suggestions ;; welcome. --luis (setf (gethash value value-keywords) keyword) (when (and field-mode-p (single-bit-p value)) (let ((bit-index (1- (integer-length value)))) (push keyword field-keywords) (when (<= (array-dimension bit-index->keyword 0) bit-index) (setf bit-index->keyword (adjust-array bit-index->keyword (1+ bit-index) :initial-element nil))) (setf (aref bit-index->keyword bit-index) keyword))))) (if base-type (progn (setf base-type (canonicalize-foreign-type base-type)) ;; I guess we don't lose much by not strictly adhering to the C standard here , and some libs out in the wild are ;; already using e.g. :double. #+nil (assert (member base-type +valid-enum-base-types+ :test 'eq) () "Invalid base type ~S for enum type ~S. Must be one of ~S." base-type type-name +valid-enum-base-types+)) ;; details: -is-the-underlying-type-of-a-c-enum (let ((bits (integer-length most-extreme-value))) (setf base-type (let ((most-uint-bits (load-time-value (* (foreign-type-size :unsigned-int) 8))) (most-ulong-bits (load-time-value (* (foreign-type-size :unsigned-long) 8))) (most-ulonglong-bits (load-time-value (* (foreign-type-size :unsigned-long-long) 8)))) (or (if has-negative-value? (cond ((<= (1+ bits) most-uint-bits) :int) ((<= (1+ bits) most-ulong-bits) :long) ((<= (1+ bits) most-ulonglong-bits) :long-long)) (cond ((<= bits most-uint-bits) :unsigned-int) ((<= bits most-ulong-bits) :unsigned-long) ((<= bits most-ulonglong-bits) :unsigned-long-long))) (error "Enum value ~S of enum ~S is too large to store." most-extreme-value type-name)))))) (values base-type keyword-values value-keywords field-keywords (when field-mode-p (alexandria:copy-array bit-index->keyword :adjustable nil :fill-pointer nil))))) (defun make-foreign-enum (type-name base-type values) "Makes a new instance of the foreign-enum class." (multiple-value-bind (base-type keyword-values value-keywords) (parse-foreign-enum-like type-name base-type values) (make-instance 'foreign-enum :name type-name :actual-type (parse-type base-type) :keyword-values keyword-values :value-keywords value-keywords))) (defun %defcenum-like (name-and-options enum-list type-factory) (discard-docstring enum-list) (destructuring-bind (name &optional base-type) (ensure-list name-and-options) (let ((type (funcall type-factory name base-type enum-list))) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-type ',name ;; ,type is not enough here, someone needs to ;; define it when we're being loaded from a fasl. (,type-factory ',name ',base-type ',enum-list)) ,@(remove nil (mapcar (lambda (key) (unless (keywordp key) `(defconstant ,key ,(foreign-enum-value type key)))) (foreign-enum-keyword-list type))))))) (defmacro defcenum (name-and-options &body enum-list) "Define an foreign enumerated type." (%defcenum-like name-and-options enum-list 'make-foreign-enum)) (defun hash-keys-to-list (ht) (loop for k being the hash-keys in ht collect k)) (defun foreign-enum-keyword-list (enum-type) "Return a list of KEYWORDS defined in ENUM-TYPE." (hash-keys-to-list (keyword-values (ensure-parsed-base-type enum-type)))) These [ four ] functions could be good canditates for compiler macros ;;; when the value or keyword is constant. I am not going to bother ;;; until someone has a serious performance need to do so though. --jamesjb (defun %foreign-enum-value (type keyword &key errorp) (check-type keyword enum-key) (or (gethash keyword (keyword-values type)) (when errorp (error "~S is not defined as a keyword for enum type ~S." keyword type)))) (defun foreign-enum-value (type keyword &key (errorp t)) "Convert a KEYWORD into an integer according to the enum TYPE." (let ((type-obj (ensure-parsed-base-type type))) (if (not (typep type-obj 'foreign-enum)) (error "~S is not a foreign enum type." type) (%foreign-enum-value type-obj keyword :errorp errorp)))) (defun %foreign-enum-keyword (type value &key errorp) (check-type value integer) (or (gethash value (value-keywords type)) (when errorp (error "~S is not defined as a value for enum type ~S." value type)))) (defun foreign-enum-keyword (type value &key (errorp t)) "Convert an integer VALUE into a keyword according to the enum TYPE." (let ((type-obj (ensure-parsed-base-type type))) (if (not (typep type-obj 'foreign-enum)) (error "~S is not a foreign enum type." type) (%foreign-enum-keyword type-obj value :errorp errorp)))) (defmethod translate-to-foreign (value (type foreign-enum)) (if (keywordp value) (%foreign-enum-value type value :errorp t) value)) (defmethod translate-into-foreign-memory (value (type foreign-enum) pointer) (setf (mem-aref pointer (unparse-type (actual-type type))) (translate-to-foreign value type))) (defmethod translate-from-foreign (value (type foreign-enum)) (%foreign-enum-keyword type value :errorp t)) (defmethod expand-to-foreign (value (type foreign-enum)) (once-only (value) `(if (keywordp ,value) (%foreign-enum-value ,type ,value :errorp t) ,value))) There are two expansions necessary for an enum : first , the enum ;;; keyword needs to be translated to an int, and then the int needs ;;; to be made indirect. (defmethod expand-to-foreign-dyn-indirect (value var body (type foreign-enum)) (expand-to-foreign-dyn-indirect ; Make the integer indirect (with-unique-names (feint) (call-next-method value feint (list feint) type)) ; TRANSLATABLE-FOREIGN-TYPE method var body (actual-type type))) ;;;# Foreign Bitfields as Lisp keywords ;;; DEFBITFIELD is an abstraction similar to the one provided by DEFCENUM . ;;; With some changes to DEFCENUM, this could certainly be implemented on ;;; top of it. (defclass foreign-bitfield (foreign-enum) ((field-keywords :initform (error "Must specify FIELD-KEYWORDS.") :initarg :field-keywords :reader field-keywords) (bit-index->keyword :initform (error "Must specify BIT-INDEX->KEYWORD") :initarg :bit-index->keyword :reader bit-index->keyword)) (:documentation "Describes a foreign bitfield type.")) (defun make-foreign-bitfield (type-name base-type values) "Makes a new instance of the foreign-bitfield class." (multiple-value-bind (base-type keyword-values value-keywords field-keywords bit-index->keyword) (parse-foreign-enum-like type-name base-type values t) (make-instance 'foreign-bitfield :name type-name :actual-type (parse-type base-type) :keyword-values keyword-values :value-keywords value-keywords :field-keywords field-keywords :bit-index->keyword bit-index->keyword))) (defmacro defbitfield (name-and-options &body masks) "Define an foreign enumerated type." (%defcenum-like name-and-options masks 'make-foreign-bitfield)) (defun foreign-bitfield-symbol-list (bitfield-type) "Return a list of SYMBOLS defined in BITFIELD-TYPE." (field-keywords (ensure-parsed-base-type bitfield-type))) (defun %foreign-bitfield-value (type symbols) (declare (optimize speed)) (labels ((process-one (symbol) (check-type symbol symbol) (or (gethash symbol (keyword-values type)) (error "~S is not a valid symbol for bitfield type ~S." symbol type)))) (declare (dynamic-extent #'process-one)) (cond ((consp symbols) (reduce #'logior symbols :key #'process-one)) ((null symbols) 0) (t (process-one symbols))))) (defun foreign-bitfield-value (type symbols) "Convert a list of symbols into an integer according to the TYPE bitfield." (let ((type-obj (ensure-parsed-base-type type))) (assert (typep type-obj 'foreign-bitfield) () "~S is not a foreign bitfield type." type) (%foreign-bitfield-value type-obj symbols))) (define-compiler-macro foreign-bitfield-value (&whole form type symbols) "Optimize for when TYPE and SYMBOLS are constant." (declare (notinline foreign-bitfield-value)) (if (and (constantp type) (constantp symbols)) (foreign-bitfield-value (eval type) (eval symbols)) form)) (defun %foreign-bitfield-symbols (type value) (check-type value integer) (check-type type foreign-bitfield) (loop :with bit-index->keyword = (bit-index->keyword type) :for bit-index :from 0 :below (array-dimension bit-index->keyword 0) :for mask = 1 :then (ash mask 1) :for key = (aref bit-index->keyword bit-index) :when (and key (= (logand value mask) mask)) :collect key)) (defun foreign-bitfield-symbols (type value) "Convert an integer VALUE into a list of matching symbols according to the bitfield TYPE." (let ((type-obj (ensure-parsed-base-type type))) (if (not (typep type-obj 'foreign-bitfield)) (error "~S is not a foreign bitfield type." type) (%foreign-bitfield-symbols type-obj value)))) (define-compiler-macro foreign-bitfield-symbols (&whole form type value) "Optimize for when TYPE and SYMBOLS are constant." (declare (notinline foreign-bitfield-symbols)) (if (and (constantp type) (constantp value)) `(quote ,(foreign-bitfield-symbols (eval type) (eval value))) form)) (defmethod translate-to-foreign (value (type foreign-bitfield)) (if (integerp value) value (%foreign-bitfield-value type (ensure-list value)))) (defmethod translate-from-foreign (value (type foreign-bitfield)) (%foreign-bitfield-symbols type value)) (defmethod expand-to-foreign (value (type foreign-bitfield)) (flet ((expander (value type) `(if (integerp ,value) ,value (%foreign-bitfield-value ,type (ensure-list ,value))))) (if (constantp value) (eval (expander value type)) (expander value type)))) (defmethod expand-from-foreign (value (type foreign-bitfield)) (flet ((expander (value type) `(%foreign-bitfield-symbols ,type ,value))) (if (constantp value) (eval (expander value type)) (expander value type))))
null
https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/cffi_0.19.0/src/enum.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- enum.lisp --- Defining foreign constants as Lisp keywords. 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 sell copies 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. TODO the accessors names are rather inconsistent: FOREIGN-ENUM-KEYWORD FOREIGN-BITFIELD-SYMBOLS FOREIGN-ENUM-KEYWORD-LIST FOREIGN-BITFIELD-SYMBOL-LIST TODO bitfield is a confusing name, because the C standard calls # Foreign Constants as Lisp Keywords This module defines the DEFCENUM macro, which provides an interface for defining a type and associating a set of integer constants with keyword symbols for that type. The keywords are automatically translated to the appropriate constant for the type by a type translator when passed as arguments or a return value to a foreign function. (check-type value integer) This is completely arbitrary behaviour: we keep the last value->keyword mapping. I suppose the opposite would be the keywords might be a solution too? Suggestions welcome. --luis I guess we don't lose much by not strictly adhering to already using e.g. :double. details: -is-the-underlying-type-of-a-c-enum ,type is not enough here, someone needs to define it when we're being loaded from a fasl. when the value or keyword is constant. I am not going to bother until someone has a serious performance need to do so though. --jamesjb keyword needs to be translated to an int, and then the int needs to be made indirect. Make the integer indirect TRANSLATABLE-FOREIGN-TYPE method # Foreign Bitfields as Lisp keywords With some changes to DEFCENUM, this could certainly be implemented on top of it.
Copyright ( C ) 2005 - 2006 , < > files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package #:cffi) FOREIGN - ENUM - VALUE FOREIGN - BITFIELD - VALUE I 'd rename them to : FOREIGN-*-KEY(S ) and FOREIGN-*-ALL - KEYS -- the " int foo : 3 " type as a bitfield . Maybe rename to defbitmask ? -- (defclass foreign-enum (named-foreign-type enhanced-foreign-type) ((keyword-values :initform (error "Must specify KEYWORD-VALUES.") :initarg :keyword-values :reader keyword-values) (value-keywords :initform (error "Must specify VALUE-KEYWORDS.") :initarg :value-keywords :reader value-keywords)) (:documentation "Describes a foreign enumerated type.")) (deftype enum-key () '(and symbol (not null))) (defparameter +valid-enum-base-types+ *built-in-integer-types*) (defun parse-foreign-enum-like (type-name base-type values &optional field-mode-p) (let ((keyword-values (make-hash-table :test 'eq)) (value-keywords (make-hash-table)) (field-keywords (list)) (bit-index->keyword (make-array 0 :adjustable t :element-type t)) (default-value (if field-mode-p 1 0)) (most-extreme-value 0) (has-negative-value? nil)) (dolist (pair values) (destructuring-bind (keyword &optional (value default-value valuep)) (ensure-list pair) (check-type keyword enum-key) (when (> (abs value) (abs most-extreme-value)) (setf most-extreme-value value)) (when (minusp value) (setf has-negative-value? t)) (if field-mode-p (if valuep (when (and (>= value default-value) (single-bit-p value)) (setf default-value (ash value 1))) (setf default-value (ash default-value 1))) (setf default-value (1+ value))) (if (gethash keyword keyword-values) (error "A foreign enum cannot contain duplicate keywords: ~S." keyword) (setf (gethash keyword keyword-values) value)) just as good ( keeping the first ) . Returning a list with all (setf (gethash value value-keywords) keyword) (when (and field-mode-p (single-bit-p value)) (let ((bit-index (1- (integer-length value)))) (push keyword field-keywords) (when (<= (array-dimension bit-index->keyword 0) bit-index) (setf bit-index->keyword (adjust-array bit-index->keyword (1+ bit-index) :initial-element nil))) (setf (aref bit-index->keyword bit-index) keyword))))) (if base-type (progn (setf base-type (canonicalize-foreign-type base-type)) the C standard here , and some libs out in the wild are #+nil (assert (member base-type +valid-enum-base-types+ :test 'eq) () "Invalid base type ~S for enum type ~S. Must be one of ~S." base-type type-name +valid-enum-base-types+)) (let ((bits (integer-length most-extreme-value))) (setf base-type (let ((most-uint-bits (load-time-value (* (foreign-type-size :unsigned-int) 8))) (most-ulong-bits (load-time-value (* (foreign-type-size :unsigned-long) 8))) (most-ulonglong-bits (load-time-value (* (foreign-type-size :unsigned-long-long) 8)))) (or (if has-negative-value? (cond ((<= (1+ bits) most-uint-bits) :int) ((<= (1+ bits) most-ulong-bits) :long) ((<= (1+ bits) most-ulonglong-bits) :long-long)) (cond ((<= bits most-uint-bits) :unsigned-int) ((<= bits most-ulong-bits) :unsigned-long) ((<= bits most-ulonglong-bits) :unsigned-long-long))) (error "Enum value ~S of enum ~S is too large to store." most-extreme-value type-name)))))) (values base-type keyword-values value-keywords field-keywords (when field-mode-p (alexandria:copy-array bit-index->keyword :adjustable nil :fill-pointer nil))))) (defun make-foreign-enum (type-name base-type values) "Makes a new instance of the foreign-enum class." (multiple-value-bind (base-type keyword-values value-keywords) (parse-foreign-enum-like type-name base-type values) (make-instance 'foreign-enum :name type-name :actual-type (parse-type base-type) :keyword-values keyword-values :value-keywords value-keywords))) (defun %defcenum-like (name-and-options enum-list type-factory) (discard-docstring enum-list) (destructuring-bind (name &optional base-type) (ensure-list name-and-options) (let ((type (funcall type-factory name base-type enum-list))) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-type ',name (,type-factory ',name ',base-type ',enum-list)) ,@(remove nil (mapcar (lambda (key) (unless (keywordp key) `(defconstant ,key ,(foreign-enum-value type key)))) (foreign-enum-keyword-list type))))))) (defmacro defcenum (name-and-options &body enum-list) "Define an foreign enumerated type." (%defcenum-like name-and-options enum-list 'make-foreign-enum)) (defun hash-keys-to-list (ht) (loop for k being the hash-keys in ht collect k)) (defun foreign-enum-keyword-list (enum-type) "Return a list of KEYWORDS defined in ENUM-TYPE." (hash-keys-to-list (keyword-values (ensure-parsed-base-type enum-type)))) These [ four ] functions could be good canditates for compiler macros (defun %foreign-enum-value (type keyword &key errorp) (check-type keyword enum-key) (or (gethash keyword (keyword-values type)) (when errorp (error "~S is not defined as a keyword for enum type ~S." keyword type)))) (defun foreign-enum-value (type keyword &key (errorp t)) "Convert a KEYWORD into an integer according to the enum TYPE." (let ((type-obj (ensure-parsed-base-type type))) (if (not (typep type-obj 'foreign-enum)) (error "~S is not a foreign enum type." type) (%foreign-enum-value type-obj keyword :errorp errorp)))) (defun %foreign-enum-keyword (type value &key errorp) (check-type value integer) (or (gethash value (value-keywords type)) (when errorp (error "~S is not defined as a value for enum type ~S." value type)))) (defun foreign-enum-keyword (type value &key (errorp t)) "Convert an integer VALUE into a keyword according to the enum TYPE." (let ((type-obj (ensure-parsed-base-type type))) (if (not (typep type-obj 'foreign-enum)) (error "~S is not a foreign enum type." type) (%foreign-enum-keyword type-obj value :errorp errorp)))) (defmethod translate-to-foreign (value (type foreign-enum)) (if (keywordp value) (%foreign-enum-value type value :errorp t) value)) (defmethod translate-into-foreign-memory (value (type foreign-enum) pointer) (setf (mem-aref pointer (unparse-type (actual-type type))) (translate-to-foreign value type))) (defmethod translate-from-foreign (value (type foreign-enum)) (%foreign-enum-keyword type value :errorp t)) (defmethod expand-to-foreign (value (type foreign-enum)) (once-only (value) `(if (keywordp ,value) (%foreign-enum-value ,type ,value :errorp t) ,value))) There are two expansions necessary for an enum : first , the enum (defmethod expand-to-foreign-dyn-indirect (value var body (type foreign-enum)) (with-unique-names (feint) var body (actual-type type))) DEFBITFIELD is an abstraction similar to the one provided by DEFCENUM . (defclass foreign-bitfield (foreign-enum) ((field-keywords :initform (error "Must specify FIELD-KEYWORDS.") :initarg :field-keywords :reader field-keywords) (bit-index->keyword :initform (error "Must specify BIT-INDEX->KEYWORD") :initarg :bit-index->keyword :reader bit-index->keyword)) (:documentation "Describes a foreign bitfield type.")) (defun make-foreign-bitfield (type-name base-type values) "Makes a new instance of the foreign-bitfield class." (multiple-value-bind (base-type keyword-values value-keywords field-keywords bit-index->keyword) (parse-foreign-enum-like type-name base-type values t) (make-instance 'foreign-bitfield :name type-name :actual-type (parse-type base-type) :keyword-values keyword-values :value-keywords value-keywords :field-keywords field-keywords :bit-index->keyword bit-index->keyword))) (defmacro defbitfield (name-and-options &body masks) "Define an foreign enumerated type." (%defcenum-like name-and-options masks 'make-foreign-bitfield)) (defun foreign-bitfield-symbol-list (bitfield-type) "Return a list of SYMBOLS defined in BITFIELD-TYPE." (field-keywords (ensure-parsed-base-type bitfield-type))) (defun %foreign-bitfield-value (type symbols) (declare (optimize speed)) (labels ((process-one (symbol) (check-type symbol symbol) (or (gethash symbol (keyword-values type)) (error "~S is not a valid symbol for bitfield type ~S." symbol type)))) (declare (dynamic-extent #'process-one)) (cond ((consp symbols) (reduce #'logior symbols :key #'process-one)) ((null symbols) 0) (t (process-one symbols))))) (defun foreign-bitfield-value (type symbols) "Convert a list of symbols into an integer according to the TYPE bitfield." (let ((type-obj (ensure-parsed-base-type type))) (assert (typep type-obj 'foreign-bitfield) () "~S is not a foreign bitfield type." type) (%foreign-bitfield-value type-obj symbols))) (define-compiler-macro foreign-bitfield-value (&whole form type symbols) "Optimize for when TYPE and SYMBOLS are constant." (declare (notinline foreign-bitfield-value)) (if (and (constantp type) (constantp symbols)) (foreign-bitfield-value (eval type) (eval symbols)) form)) (defun %foreign-bitfield-symbols (type value) (check-type value integer) (check-type type foreign-bitfield) (loop :with bit-index->keyword = (bit-index->keyword type) :for bit-index :from 0 :below (array-dimension bit-index->keyword 0) :for mask = 1 :then (ash mask 1) :for key = (aref bit-index->keyword bit-index) :when (and key (= (logand value mask) mask)) :collect key)) (defun foreign-bitfield-symbols (type value) "Convert an integer VALUE into a list of matching symbols according to the bitfield TYPE." (let ((type-obj (ensure-parsed-base-type type))) (if (not (typep type-obj 'foreign-bitfield)) (error "~S is not a foreign bitfield type." type) (%foreign-bitfield-symbols type-obj value)))) (define-compiler-macro foreign-bitfield-symbols (&whole form type value) "Optimize for when TYPE and SYMBOLS are constant." (declare (notinline foreign-bitfield-symbols)) (if (and (constantp type) (constantp value)) `(quote ,(foreign-bitfield-symbols (eval type) (eval value))) form)) (defmethod translate-to-foreign (value (type foreign-bitfield)) (if (integerp value) value (%foreign-bitfield-value type (ensure-list value)))) (defmethod translate-from-foreign (value (type foreign-bitfield)) (%foreign-bitfield-symbols type value)) (defmethod expand-to-foreign (value (type foreign-bitfield)) (flet ((expander (value type) `(if (integerp ,value) ,value (%foreign-bitfield-value ,type (ensure-list ,value))))) (if (constantp value) (eval (expander value type)) (expander value type)))) (defmethod expand-from-foreign (value (type foreign-bitfield)) (flet ((expander (value type) `(%foreign-bitfield-symbols ,type ,value))) (if (constantp value) (eval (expander value type)) (expander value type))))
d893150de55b9dadadd6c93e60ef37375fb21d5b7405a6e299f263f752c2aa93
fishcakez/sbroker
sbroker_fq2_queue.erl
%%------------------------------------------------------------------- %% Copyright ( c ) 2016 , < > %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file %% except in compliance with the License. You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %%------------------------------------------------------------------- -module(sbroker_fq2_queue). -behaviour(sbroker_queue). -behaviour(sbroker_fair_queue). -export([init/3]). -export([handle_in/5]). -export([handle_out/2]). -export([handle_fq_out/2]). -export([handle_timeout/2]). -export([handle_cancel/3]). -export([handle_info/3]). -export([code_change/4]). -export([config_change/3]). -export([len/1]). -export([send_time/1]). -export([terminate/2]). This sbroker_queue module is used to an alternate to sbroker_fq_queue %% to test config changes. init(Q, Time, Args) -> sbroker_fq_queue:init(Q, Time, Args). handle_in(SendTime, From, Value, Time, State) -> sbroker_fq_queue:handle_in(SendTime, From, Value, Time, State). handle_out(Time, State) -> sbroker_fq_queue:handle_out(Time, State). handle_fq_out(Time, State) -> sbroker_fq_queue:handle_fq_out(Time, State). handle_timeout(Time, State) -> sbroker_fq_queue:handle_timeout(Time, State). handle_cancel(Tag, Time, State) -> sbroker_fq_queue:handle_cancel(Tag, Time, State). handle_info(Msg, Time, State) -> sbroker_fq_queue:handle_info(Msg, Time, State). code_change(OldVsn, Time, State, Extra) -> sbroker_fq_queue:codeg_change(OldVsn, Time, State, Extra). config_change(Args, Time, State) -> sbroker_fq_queue:config_change(Args, Time, State). len(State) -> sbroker_fq_queue:len(State). send_time(State) -> sbroker_fq_queue:send_time(State). terminate(Reason, State) -> sbroker_fq_queue:terminate(Reason, State).
null
https://raw.githubusercontent.com/fishcakez/sbroker/10f7e3970d0a296fbf08b1d1a94c88979a7deb5e/test/sbroker_fq2_queue.erl
erlang
------------------------------------------------------------------- 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, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- to test config changes.
Copyright ( c ) 2016 , < > This file is provided to you under the Apache License , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(sbroker_fq2_queue). -behaviour(sbroker_queue). -behaviour(sbroker_fair_queue). -export([init/3]). -export([handle_in/5]). -export([handle_out/2]). -export([handle_fq_out/2]). -export([handle_timeout/2]). -export([handle_cancel/3]). -export([handle_info/3]). -export([code_change/4]). -export([config_change/3]). -export([len/1]). -export([send_time/1]). -export([terminate/2]). This sbroker_queue module is used to an alternate to sbroker_fq_queue init(Q, Time, Args) -> sbroker_fq_queue:init(Q, Time, Args). handle_in(SendTime, From, Value, Time, State) -> sbroker_fq_queue:handle_in(SendTime, From, Value, Time, State). handle_out(Time, State) -> sbroker_fq_queue:handle_out(Time, State). handle_fq_out(Time, State) -> sbroker_fq_queue:handle_fq_out(Time, State). handle_timeout(Time, State) -> sbroker_fq_queue:handle_timeout(Time, State). handle_cancel(Tag, Time, State) -> sbroker_fq_queue:handle_cancel(Tag, Time, State). handle_info(Msg, Time, State) -> sbroker_fq_queue:handle_info(Msg, Time, State). code_change(OldVsn, Time, State, Extra) -> sbroker_fq_queue:codeg_change(OldVsn, Time, State, Extra). config_change(Args, Time, State) -> sbroker_fq_queue:config_change(Args, Time, State). len(State) -> sbroker_fq_queue:len(State). send_time(State) -> sbroker_fq_queue:send_time(State). terminate(Reason, State) -> sbroker_fq_queue:terminate(Reason, State).
b7c6b002ae526e9ebf361bba79c3f7cb652d3125755ec2662eb822ceaa135e55
well-typed/optics
Operators.hs
-- | -- Module: Optics.Operators -- Description: Definitions of infix operators for optics. -- -- Defines some infix operators for optics operations. This is a deliberately -- small collection. -- If you like operators , you may also wish to import @Optics . State . Operators@ from the @optics - extra@ package . -- module Optics.Operators ( (^.) , (^..) , (^?) , (#) , (%~) , (%!~) , (.~) , (!~) , (?~) , (?!~) ) where import Optics.AffineFold import Optics.Fold import Optics.Getter import Optics.Optic import Optics.Review import Optics.Setter -- | Flipped infix version of 'view'. (^.) :: Is k A_Getter => s -> Optic' k is s a -> a (^.) = flip view {-# INLINE (^.) #-} infixl 8 ^. -- | Flipped infix version of 'preview'. (^?) :: Is k An_AffineFold => s -> Optic' k is s a -> Maybe a (^?) = flip preview {-# INLINE (^?) #-} infixl 8 ^? -- | Flipped infix version of 'toListOf'. (^..) :: Is k A_Fold => s -> Optic' k is s a -> [a] (^..) = flip toListOf {-# INLINE (^..) #-} infixl 8 ^.. -- | Infix version of 'review'. (#) :: Is k A_Review => Optic' k is t b -> b -> t (#) = review # INLINE ( # ) # infixr 8 # -- | Infix version of 'over'. (%~) :: Is k A_Setter => Optic k is s t a b -> (a -> b) -> s -> t (%~) = over {-# INLINE (%~) #-} infixr 4 %~ -- | Infix version of 'over''. (%!~) :: Is k A_Setter => Optic k is s t a b -> (a -> b) -> s -> t (%!~) = over' {-# INLINE (%!~) #-} infixr 4 %!~ -- | Infix version of 'set'. (.~) :: Is k A_Setter => Optic k is s t a b -> b -> s -> t (.~) = set # INLINE ( .~ ) # infixr 4 .~ -- | Infix version of 'set''. (!~) :: Is k A_Setter => Optic k is s t a b -> b -> s -> t (!~) = set' {-# INLINE (!~) #-} infixr 4 !~ -- | Set the target of a 'Setter' to 'Just' a value. -- -- @ -- o '?~' b ≡ 'set' o ('Just' b) -- @ -- -- >>> Nothing & equality ?~ 'x' -- Just 'x' -- > > > Map.empty & at 3 ? ~ ' x ' -- fromList [(3,'x')] (?~) :: Is k A_Setter => Optic k is s t a (Maybe b) -> b -> s -> t (?~) = \o -> set o . Just {-# INLINE (?~) #-} infixr 4 ?~ -- | Strict version of ('?~'). (?!~) :: Is k A_Setter => Optic k is s t a (Maybe b) -> b -> s -> t (?!~) = \o !b -> set' o (Just b) {-# INLINE (?!~) #-} infixr 4 ?!~ -- $setup -- >>> import qualified Data.Map as Map > > > import Optics . Core
null
https://raw.githubusercontent.com/well-typed/optics/7cc3f9c334cdf69feaf10f58b11d3dbe2f98812c/optics-core/src/Optics/Operators.hs
haskell
| Module: Optics.Operators Description: Definitions of infix operators for optics. Defines some infix operators for optics operations. This is a deliberately small collection. | Flipped infix version of 'view'. # INLINE (^.) # | Flipped infix version of 'preview'. # INLINE (^?) # | Flipped infix version of 'toListOf'. # INLINE (^..) # | Infix version of 'review'. | Infix version of 'over'. # INLINE (%~) # | Infix version of 'over''. # INLINE (%!~) # | Infix version of 'set'. | Infix version of 'set''. # INLINE (!~) # | Set the target of a 'Setter' to 'Just' a value. @ o '?~' b ≡ 'set' o ('Just' b) @ >>> Nothing & equality ?~ 'x' Just 'x' fromList [(3,'x')] # INLINE (?~) # | Strict version of ('?~'). # INLINE (?!~) # $setup >>> import qualified Data.Map as Map
If you like operators , you may also wish to import @Optics . State . Operators@ from the @optics - extra@ package . module Optics.Operators ( (^.) , (^..) , (^?) , (#) , (%~) , (%!~) , (.~) , (!~) , (?~) , (?!~) ) where import Optics.AffineFold import Optics.Fold import Optics.Getter import Optics.Optic import Optics.Review import Optics.Setter (^.) :: Is k A_Getter => s -> Optic' k is s a -> a (^.) = flip view infixl 8 ^. (^?) :: Is k An_AffineFold => s -> Optic' k is s a -> Maybe a (^?) = flip preview infixl 8 ^? (^..) :: Is k A_Fold => s -> Optic' k is s a -> [a] (^..) = flip toListOf infixl 8 ^.. (#) :: Is k A_Review => Optic' k is t b -> b -> t (#) = review # INLINE ( # ) # infixr 8 # (%~) :: Is k A_Setter => Optic k is s t a b -> (a -> b) -> s -> t (%~) = over infixr 4 %~ (%!~) :: Is k A_Setter => Optic k is s t a b -> (a -> b) -> s -> t (%!~) = over' infixr 4 %!~ (.~) :: Is k A_Setter => Optic k is s t a b -> b -> s -> t (.~) = set # INLINE ( .~ ) # infixr 4 .~ (!~) :: Is k A_Setter => Optic k is s t a b -> b -> s -> t (!~) = set' infixr 4 !~ > > > Map.empty & at 3 ? ~ ' x ' (?~) :: Is k A_Setter => Optic k is s t a (Maybe b) -> b -> s -> t (?~) = \o -> set o . Just infixr 4 ?~ (?!~) :: Is k A_Setter => Optic k is s t a (Maybe b) -> b -> s -> t (?!~) = \o !b -> set' o (Just b) infixr 4 ?!~ > > > import Optics . Core
aa21d491b5da951366fb0e1bc6dcdb4a44d50305c26f48e39dd66b388ec25014
ghollisjr/cl-ana
h5e.lisp
TBP H5E_ERR_CLS_g
null
https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/hdf-cffi/src/h5e.lisp
lisp
TBP H5E_ERR_CLS_g
b816d7a19f9e853a645604e2acf6477fa84ebb95177a68f4ddededa45db1f8fe
y-taka-23/miso-tutorial-app
Api.hs
# LANGUAGE DataKinds # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Api where import Miso import Servant import Action import Html import Model import Routing type Api = JsonApi :<|> IsomorphicApi :<|> StaticApi :<|> NotFoundApi type JsonApi = "api" :> "players" :> Get '[JSON] [Player] :<|> "api" :> "players" :> Capture "id" PlayerId :> ReqBody '[JSON] Player :> Put '[JSON] NoContent type IsomorphicApi = ToServerRoutes Route HtmlPage Action type StaticApi = "static" :> Raw type NotFoundApi = Raw api :: Proxy Api api = Proxy
null
https://raw.githubusercontent.com/y-taka-23/miso-tutorial-app/6c2152a546f3cb82b498be4995ba29e669509eed/server/Api.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators #
# LANGUAGE DataKinds # module Api where import Miso import Servant import Action import Html import Model import Routing type Api = JsonApi :<|> IsomorphicApi :<|> StaticApi :<|> NotFoundApi type JsonApi = "api" :> "players" :> Get '[JSON] [Player] :<|> "api" :> "players" :> Capture "id" PlayerId :> ReqBody '[JSON] Player :> Put '[JSON] NoContent type IsomorphicApi = ToServerRoutes Route HtmlPage Action type StaticApi = "static" :> Raw type NotFoundApi = Raw api :: Proxy Api api = Proxy
b4b58b0c01f581245d9be8fe84d86e176659a7d243ec8019d51c78df6152c3c9
outergod/cl-heredoc
ring-buffer.lisp
;;;; cl-heredoc - ring-buffer.lisp Copyright ( C ) 2010 < > ;;;; This file is part of cl-heredoc. ;;;; cl-heredoc is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ;;;; (at your option) any later version. ;;;; ;;;; cl-heredoc is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program. If not, see </>. (in-package :cl-heredoc) Operations on ring buffers , as described by in ANSI Common Lisp . (defstruct ring-buffer "Structure defining ring buffers utilizing a simple VECTOR of fixed size and four indices: START: Index of first live value END: Index of last live value USED: Beginning of current match NEW: End of current match" vector (start -1) (used -1) (new -1) (end -1)) (defun new-ring-buffer (length) "new-ring-buffer length => ring-buffer Create a new RING-BUFFER containing a simple character vector of fixed size LENGTH." (make-ring-buffer :vector (make-array length :element-type 'character))) (defun rbref (buffer index) "rbref buffer index => character or #\Nul Return character stored at INDEX in ring BUFFER." (char (ring-buffer-vector buffer) (mod index (length (ring-buffer-vector buffer))))) (defun (setf rbref) (value buffer index) "setf (rbref buffer index) value => value SETF for RBREF. If INDEX > LENGTH of BUFFER, start over at the beginning." (setf (char (ring-buffer-vector buffer) (mod index (length (ring-buffer-vector buffer)))) value)) (defun ring-buffer-insert (buffer value) "ring-buffer-insert buffer value => value Increment END of BUFFER inserting VALUE at the new index." (setf (rbref buffer (incf (ring-buffer-end buffer))) value)) (defun ring-buffer-reset (buffer) "ring-buffer-reset buffer => end-index Reset match beginning/end indices USED and NEW in BUFFER to START and END." (setf (ring-buffer-used buffer) (ring-buffer-start buffer) (ring-buffer-new buffer) (ring-buffer-end buffer))) (defun ring-buffer-pop (buffer) "ring-buffer-pop buffer => character Increment START of BUFFER returning VALUE at the new index. Additionally, reset the BUFFER match indices." (prog1 (rbref buffer (incf (ring-buffer-start buffer))) (ring-buffer-reset buffer))) (defun ring-buffer-next (buffer) "ring-buffer-next buffer => character or nil Return next match character incrementing USED in BUFFER or simply NIL if none are left." (when (< (ring-buffer-used buffer) (ring-buffer-new buffer)) (rbref buffer (incf (ring-buffer-used buffer))))) (defun ring-buffer-clear (buffer) "ring-buffer-clear buffer => -1 Reset all indices of BUFFER to their initial state." (setf (ring-buffer-start buffer) -1 (ring-buffer-used buffer) -1 (ring-buffer-new buffer) -1 (ring-buffer-end buffer) -1)) (defun ring-buffer-flush (buffer) "ring-buffer-flush buffer => string Flush all unused characters in BUFFER." (with-output-to-string (out) (do ((index (1+ (ring-buffer-used buffer)) (1+ index))) ((> index (ring-buffer-end buffer))) (write-char (rbref buffer index) out))))
null
https://raw.githubusercontent.com/outergod/cl-heredoc/a8c8a3557bb6b4854adff86f10182c22e6676ac8/src/ring-buffer.lisp
lisp
cl-heredoc - ring-buffer.lisp This file is part of cl-heredoc. cl-heredoc is free software; you can redistribute it and/or modify either version 3 of the License , or (at your option) any later version. cl-heredoc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>.
Copyright ( C ) 2010 < > it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License (in-package :cl-heredoc) Operations on ring buffers , as described by in ANSI Common Lisp . (defstruct ring-buffer "Structure defining ring buffers utilizing a simple VECTOR of fixed size and four indices: START: Index of first live value END: Index of last live value USED: Beginning of current match NEW: End of current match" vector (start -1) (used -1) (new -1) (end -1)) (defun new-ring-buffer (length) "new-ring-buffer length => ring-buffer Create a new RING-BUFFER containing a simple character vector of fixed size LENGTH." (make-ring-buffer :vector (make-array length :element-type 'character))) (defun rbref (buffer index) "rbref buffer index => character or #\Nul Return character stored at INDEX in ring BUFFER." (char (ring-buffer-vector buffer) (mod index (length (ring-buffer-vector buffer))))) (defun (setf rbref) (value buffer index) "setf (rbref buffer index) value => value SETF for RBREF. If INDEX > LENGTH of BUFFER, start over at the beginning." (setf (char (ring-buffer-vector buffer) (mod index (length (ring-buffer-vector buffer)))) value)) (defun ring-buffer-insert (buffer value) "ring-buffer-insert buffer value => value Increment END of BUFFER inserting VALUE at the new index." (setf (rbref buffer (incf (ring-buffer-end buffer))) value)) (defun ring-buffer-reset (buffer) "ring-buffer-reset buffer => end-index Reset match beginning/end indices USED and NEW in BUFFER to START and END." (setf (ring-buffer-used buffer) (ring-buffer-start buffer) (ring-buffer-new buffer) (ring-buffer-end buffer))) (defun ring-buffer-pop (buffer) "ring-buffer-pop buffer => character Increment START of BUFFER returning VALUE at the new index. Additionally, reset the BUFFER match indices." (prog1 (rbref buffer (incf (ring-buffer-start buffer))) (ring-buffer-reset buffer))) (defun ring-buffer-next (buffer) "ring-buffer-next buffer => character or nil Return next match character incrementing USED in BUFFER or simply NIL if none are left." (when (< (ring-buffer-used buffer) (ring-buffer-new buffer)) (rbref buffer (incf (ring-buffer-used buffer))))) (defun ring-buffer-clear (buffer) "ring-buffer-clear buffer => -1 Reset all indices of BUFFER to their initial state." (setf (ring-buffer-start buffer) -1 (ring-buffer-used buffer) -1 (ring-buffer-new buffer) -1 (ring-buffer-end buffer) -1)) (defun ring-buffer-flush (buffer) "ring-buffer-flush buffer => string Flush all unused characters in BUFFER." (with-output-to-string (out) (do ((index (1+ (ring-buffer-used buffer)) (1+ index))) ((> index (ring-buffer-end buffer))) (write-char (rbref buffer index) out))))
58c9d76005a59ebca36ff440c7c80d3a4f59ef28749e71fe5895809bd54d4598
oakes/Nightweb
service.clj
(ns net.clandroid.service (:require [neko.-utils :as utils]) (:import [android.app Activity])) (defn start-service! [^Activity context class-name connected] (let [intent (android.content.Intent.) connection (proxy [android.content.ServiceConnection] [] (onServiceConnected [component-name binder] (connected binder)) (onServiceDisconnected [component-name] ()))] (.setClassName intent context class-name) (.startService context intent) (.bindService context intent connection 0) connection)) (defn stop-service! [^Activity context connection] (.unbindService context connection)) (defn start-receiver! [^Activity context receiver-name func] (let [receiver (proxy [android.content.BroadcastReceiver] [] (onReceive [context intent] (func context intent)))] (.registerReceiver context receiver (android.content.IntentFilter. receiver-name)) receiver)) (defn start-local-receiver! [^Activity context receiver-name func] (-> (android.support.v4.content.LocalBroadcastManager/getInstance context) (start-receiver! receiver-name func))) (defn stop-receiver! [^Activity context receiver] (.unregisterReceiver context receiver)) (defn stop-local-receiver! [^Activity context receiver-name] (-> (android.support.v4.content.LocalBroadcastManager/getInstance context) (stop-receiver! receiver-name))) (defn send-broadcast! [^Activity context params action-name] (let [intent (android.content.Intent.)] (.putExtra intent "params" params) (.setAction intent action-name) (.sendBroadcast context intent))) (defn send-local-broadcast! [^Activity context params action-name] (-> (android.support.v4.content.LocalBroadcastManager/getInstance context) (send-broadcast! params action-name))) (defn start-foreground! [service id notification] (.startForeground service id notification)) (do (gen-class :name "CustomBinder" :extends android.os.Binder :state "state" :init "init" :constructors {[android.app.Service] []} :prefix "binder-") (defn binder-init [service] [[] service]) (defn create-binder [service] (CustomBinder. service))) (defmacro defservice [name & {:keys [extends prefix on-start-command def state] :as options}] (let [options (or options {}) sname (utils/simple-name name) prefix (or prefix (str sname "-")) def (or def (symbol (utils/unicaseize sname)))] `(do (gen-class :name ~name :main false :prefix ~prefix ~@(when state '(:init "init" :state "state")) :extends ~(or extends android.app.Service) :exposes-methods {~'onCreate ~'superOnCreate ~'onDestroy ~'superOnDestroy}) ~(when state `(defn ~(symbol (str prefix "init")) [] [[] ~state])) (defn ~(symbol (str prefix "onBind")) [~(vary-meta 'this assoc :tag name), ^android.content.Intent ~'intent] (def ~(vary-meta def assoc :tag name) ~'this) (~create-binder ~'this)) ~(when on-start-command `(defn ~(symbol (str prefix "onStartCommand")) [~(vary-meta 'this assoc :tag name), ^android.content.Intent ~'intent, ^int ~'flags, ^int ~'startId] (def ~(vary-meta def assoc :tag name) ~'this) (~on-start-command ~'this ~'intent ~'flags ~'startId) android.app.Service/START_STICKY)) ~@(map #(let [func (options %) event-name (utils/keyword->camelcase %)] (when func `(defn ~(symbol (str prefix event-name)) [~(vary-meta 'this assoc :tag name)] (~(symbol (str ".super" (utils/capitalize event-name))) ~'this) (~func ~'this)))) [:on-create :on-destroy]))))
null
https://raw.githubusercontent.com/oakes/Nightweb/089c7a99a9a875fde33cc29d56e1faf54dc9de84/android/src/clojure/net/clandroid/service.clj
clojure
(ns net.clandroid.service (:require [neko.-utils :as utils]) (:import [android.app Activity])) (defn start-service! [^Activity context class-name connected] (let [intent (android.content.Intent.) connection (proxy [android.content.ServiceConnection] [] (onServiceConnected [component-name binder] (connected binder)) (onServiceDisconnected [component-name] ()))] (.setClassName intent context class-name) (.startService context intent) (.bindService context intent connection 0) connection)) (defn stop-service! [^Activity context connection] (.unbindService context connection)) (defn start-receiver! [^Activity context receiver-name func] (let [receiver (proxy [android.content.BroadcastReceiver] [] (onReceive [context intent] (func context intent)))] (.registerReceiver context receiver (android.content.IntentFilter. receiver-name)) receiver)) (defn start-local-receiver! [^Activity context receiver-name func] (-> (android.support.v4.content.LocalBroadcastManager/getInstance context) (start-receiver! receiver-name func))) (defn stop-receiver! [^Activity context receiver] (.unregisterReceiver context receiver)) (defn stop-local-receiver! [^Activity context receiver-name] (-> (android.support.v4.content.LocalBroadcastManager/getInstance context) (stop-receiver! receiver-name))) (defn send-broadcast! [^Activity context params action-name] (let [intent (android.content.Intent.)] (.putExtra intent "params" params) (.setAction intent action-name) (.sendBroadcast context intent))) (defn send-local-broadcast! [^Activity context params action-name] (-> (android.support.v4.content.LocalBroadcastManager/getInstance context) (send-broadcast! params action-name))) (defn start-foreground! [service id notification] (.startForeground service id notification)) (do (gen-class :name "CustomBinder" :extends android.os.Binder :state "state" :init "init" :constructors {[android.app.Service] []} :prefix "binder-") (defn binder-init [service] [[] service]) (defn create-binder [service] (CustomBinder. service))) (defmacro defservice [name & {:keys [extends prefix on-start-command def state] :as options}] (let [options (or options {}) sname (utils/simple-name name) prefix (or prefix (str sname "-")) def (or def (symbol (utils/unicaseize sname)))] `(do (gen-class :name ~name :main false :prefix ~prefix ~@(when state '(:init "init" :state "state")) :extends ~(or extends android.app.Service) :exposes-methods {~'onCreate ~'superOnCreate ~'onDestroy ~'superOnDestroy}) ~(when state `(defn ~(symbol (str prefix "init")) [] [[] ~state])) (defn ~(symbol (str prefix "onBind")) [~(vary-meta 'this assoc :tag name), ^android.content.Intent ~'intent] (def ~(vary-meta def assoc :tag name) ~'this) (~create-binder ~'this)) ~(when on-start-command `(defn ~(symbol (str prefix "onStartCommand")) [~(vary-meta 'this assoc :tag name), ^android.content.Intent ~'intent, ^int ~'flags, ^int ~'startId] (def ~(vary-meta def assoc :tag name) ~'this) (~on-start-command ~'this ~'intent ~'flags ~'startId) android.app.Service/START_STICKY)) ~@(map #(let [func (options %) event-name (utils/keyword->camelcase %)] (when func `(defn ~(symbol (str prefix event-name)) [~(vary-meta 'this assoc :tag name)] (~(symbol (str ".super" (utils/capitalize event-name))) ~'this) (~func ~'this)))) [:on-create :on-destroy]))))